Skip to main content

rust_diskann/
lib.rs

1//! # DiskAnn (generic over `anndists::Distance<T>`)
2//!
3//! An on-disk DiskANN library that:
4//! - Builds a Vamana-style graph (greedy + α-pruning) in memory
5//! - Writes vectors + fixed-degree adjacency to a single file
6//! - Memory-maps the file for low-overhead reads
7//! - Is **generic over any Distance<T>** from `anndists` (e.g. L2 on `f32`, Cosine on `f32`,
8//!   Hamming on `u64`, …)
9//!
10//! ## Example (f32 + L2)
11//! ```no_run
12//! use anndists::dist::DistL2;
13//! use rust_diskann::{DiskANN, DiskAnnParams};
14//!
15//! let vectors: Vec<Vec<f32>> = vec![vec![0.0; 128]; 1000];
16//! let index = DiskANN::<f32, DistL2>::build_index_default(&vectors, DistL2, "index.db").unwrap();
17//!
18//! let q = vec![0.0; 128];
19//! let nns = index.search(&q, 10, 64);
20//! ```
21//!
22//! ## Example (u64 + Hamming)
23//! ```no_run
24//! use anndists::dist::DistHamming;
25//! use rust_diskann::{DiskANN, DiskAnnParams};
26//! let index: Vec<Vec<u64>> = vec![vec![0u64; 128]; 1000];
27//! let idx = DiskANN::<u64, DistHamming>::build_index_default(&index, DistHamming, "mh.db").unwrap();
28//! let q = vec![0u64; 128];
29//! let _ = idx.search(&q, 10, 64);
30//! ```
31//!
32//! ## File Layout
33//! [ metadata_len:u64 ][ metadata (bincode) ][ padding up to vectors_offset ]
34//! [ vectors (num * dim * T) ][ adjacency (num * max_degree * u32) ]
35//!
36//! `vectors_offset` is a fixed 1 MiB gap by default.
37
38use anndists::prelude::Distance;
39use memmap2::Mmap;
40use rand::{prelude::*, thread_rng};
41use rayon::prelude::*;
42use serde::{Deserialize, Serialize};
43use std::cmp::{Ordering, Reverse};
44use std::collections::{BinaryHeap, HashSet};
45use std::fs::OpenOptions;
46use std::io::{Read, Seek, SeekFrom, Write};
47use std::marker::PhantomData;
48use thiserror::Error;
49
50pub mod mmap_dynamic;
51
52/// Padding sentinel for adjacency slots (avoid colliding with node 0).
53const PAD_U32: u32 = u32::MAX;
54
55/// Defaults for in-memory DiskANN builds
56pub const DISKANN_DEFAULT_MAX_DEGREE: usize = 64;
57pub const DISKANN_DEFAULT_BUILD_BEAM: usize = 128;
58pub const DISKANN_DEFAULT_ALPHA: f32 = 1.2;
59/// Default number of extra random seeds per node during graph build
60pub const DISKANN_DEFAULT_EXTRA_SEEDS: usize = 1;
61
62/// Practical DiskANN-style slack before reverse-neighbor re-pruning.
63/// Legacy C++ DiskANN allows reverse lists to grow to about GRAPH_SLACK_FACTOR * R
64/// before triggering prune, instead of pruning immediately at R.
65const GRAPH_SLACK_FACTOR: f32 = 1.3;
66
67/// Maximum candidate pool considered by RobustPrune, matching DiskANN's default.
68const MAX_OCCLUSION_SIZE: usize = 750;
69
70/// Number of nodes processed together in one micro-batch during graph build.
71///
72/// Smaller values:
73/// - are closer to true incremental insertion
74/// - usually improve faithfulness to practical Vamana behavior
75/// - but are slower
76///
77/// Larger values:
78/// - are faster
79/// - but behave more like a batched graph rebuild
80///
81/// Recommended starting values:
82/// - 128 for better quality
83/// - 256 for a balanced tradeoff
84/// - 512 for faster builds
85const MICRO_BATCH_CHUNK_SIZE: usize = 256;
86
87/// Optional bag of knobs if you want to override just a few.
88#[derive(Clone, Copy, Debug)]
89pub struct DiskAnnParams {
90    pub max_degree: usize,
91    pub build_beam_width: usize,
92    pub alpha: f32,
93    /// Extra random seeds per node during graph construction (>=0).
94    pub extra_seeds: usize,
95}
96
97impl Default for DiskAnnParams {
98    fn default() -> Self {
99        Self {
100            max_degree: DISKANN_DEFAULT_MAX_DEGREE,
101            build_beam_width: DISKANN_DEFAULT_BUILD_BEAM,
102            alpha: DISKANN_DEFAULT_ALPHA,
103            extra_seeds: DISKANN_DEFAULT_EXTRA_SEEDS,
104        }
105    }
106}
107
108/// Custom error type for DiskAnn operations
109#[derive(Debug, Error)]
110pub enum DiskAnnError {
111    /// Represents I/O errors during file operations
112    #[error("I/O error: {0}")]
113    Io(#[from] std::io::Error),
114
115    /// Represents serialization/deserialization errors
116    #[error("Serialization error: {0}")]
117    Bincode(#[from] bincode::Error),
118
119    /// Represents index-specific errors
120    #[error("Index error: {0}")]
121    IndexError(String),
122}
123
124/// Internal metadata structure stored in the index file
125#[derive(Serialize, Deserialize, Debug)]
126struct Metadata {
127    dim: usize,
128    num_vectors: usize,
129    max_degree: usize,
130    medoid_id: u32,
131    vectors_offset: u64,
132    adjacency_offset: u64,
133    elem_size: u8,
134    distance_name: String,
135}
136
137/// Candidate for search/frontier queues
138#[derive(Clone, Copy, Debug)]
139struct Candidate {
140    dist: f32,
141    id: u32,
142}
143impl PartialEq for Candidate {
144    fn eq(&self, other: &Self) -> bool {
145        self.id == other.id && self.dist.to_bits() == other.dist.to_bits()
146    }
147}
148impl Eq for Candidate {}
149impl PartialOrd for Candidate {
150    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
151        Some(
152            self.dist
153                .total_cmp(&other.dist)
154                .then_with(|| self.id.cmp(&other.id)),
155        )
156    }
157}
158impl Ord for Candidate {
159    fn cmp(&self, other: &Self) -> Ordering {
160        self.partial_cmp(other).unwrap_or(Ordering::Equal)
161    }
162}
163
164/// Flat contiguous matrix used during build to improve cache locality.
165///
166/// Rows are stored consecutively in `data`, row-major.
167#[derive(Clone, Debug)]
168struct FlatVectors<T> {
169    data: Vec<T>,
170    dim: usize,
171    n: usize,
172}
173
174impl<T: Copy> FlatVectors<T> {
175    fn from_vecs(vectors: &[Vec<T>]) -> Result<Self, DiskAnnError> {
176        if vectors.is_empty() {
177            return Err(DiskAnnError::IndexError("No vectors provided".to_string()));
178        }
179        let dim = vectors[0].len();
180        for (i, v) in vectors.iter().enumerate() {
181            if v.len() != dim {
182                return Err(DiskAnnError::IndexError(format!(
183                    "Vector {} has dimension {} but expected {}",
184                    i,
185                    v.len(),
186                    dim
187                )));
188            }
189        }
190
191        let n = vectors.len();
192        let mut data = Vec::with_capacity(n * dim);
193        for v in vectors {
194            data.extend_from_slice(v);
195        }
196
197        Ok(Self { data, dim, n })
198    }
199
200    #[inline]
201    fn row(&self, idx: usize) -> &[T] {
202        let start = idx * self.dim;
203        let end = start + self.dim;
204        &self.data[start..end]
205    }
206}
207
208/// Small ordered beam structure used only during build-time greedy search.
209///
210/// It keeps elements in **descending** distance order:
211/// - index 0 is the worst element
212/// - last element is the best element
213///
214/// This makes:
215/// - `best()` cheap via `last()`
216/// - `worst()` cheap via `first()`
217/// - capped beam maintenance simple
218#[derive(Default, Debug)]
219struct OrderedBeam {
220    items: Vec<Candidate>,
221}
222
223impl OrderedBeam {
224    #[inline]
225    fn clear(&mut self) {
226        self.items.clear();
227    }
228
229    #[inline]
230    fn len(&self) -> usize {
231        self.items.len()
232    }
233
234    #[inline]
235    fn is_empty(&self) -> bool {
236        self.items.is_empty()
237    }
238
239    #[inline]
240    fn best(&self) -> Option<Candidate> {
241        self.items.last().copied()
242    }
243
244    #[inline]
245    fn worst(&self) -> Option<Candidate> {
246        self.items.first().copied()
247    }
248
249    #[inline]
250    fn pop_best(&mut self) -> Option<Candidate> {
251        self.items.pop()
252    }
253
254    #[inline]
255    fn reserve(&mut self, cap: usize) {
256        if self.items.capacity() < cap {
257            self.items.reserve(cap - self.items.capacity());
258        }
259    }
260
261    #[inline]
262    fn insert_unbounded(&mut self, cand: Candidate) {
263        let pos = self.items.partition_point(|x| {
264            x.dist > cand.dist || (x.dist.to_bits() == cand.dist.to_bits() && x.id > cand.id)
265        });
266        self.items.insert(pos, cand);
267    }
268
269    #[inline]
270    fn insert_capped(&mut self, cand: Candidate, cap: usize) {
271        if cap == 0 {
272            return;
273        }
274
275        if self.items.len() < cap {
276            self.insert_unbounded(cand);
277            return;
278        }
279
280        // Since items[0] is the worst, only insert if the new candidate is better.
281        let worst = self.items[0];
282        if cand.dist >= worst.dist {
283            return;
284        }
285
286        self.insert_unbounded(cand);
287
288        if self.items.len() > cap {
289            self.items.remove(0);
290        }
291    }
292}
293
294/// Reusable scratch buffers for build-time greedy search.
295/// One instance is created per Rayon worker via `map_init`, so allocations are reused
296/// across many nodes in the build.
297#[derive(Debug)]
298struct BuildScratch {
299    marks: Vec<u32>,
300    epoch: u32,
301
302    visited_ids: Vec<u32>,
303    visited_dists: Vec<f32>,
304
305    frontier: OrderedBeam,
306    work: OrderedBeam,
307
308    seeds: Vec<usize>,
309    candidates: Vec<(u32, f32)>,
310}
311
312impl BuildScratch {
313    fn new(n: usize, beam_width: usize, max_degree: usize, extra_seeds: usize) -> Self {
314        Self {
315            marks: vec![0u32; n],
316            epoch: 1,
317            visited_ids: Vec::with_capacity(beam_width * 4),
318            visited_dists: Vec::with_capacity(beam_width * 4),
319            frontier: {
320                let mut b = OrderedBeam::default();
321                b.reserve(beam_width * 2);
322                b
323            },
324            work: {
325                let mut b = OrderedBeam::default();
326                b.reserve(beam_width * 2);
327                b
328            },
329            seeds: Vec::with_capacity(1 + extra_seeds),
330            candidates: Vec::with_capacity(beam_width * (4 + extra_seeds) + max_degree * 2),
331        }
332    }
333
334    #[inline]
335    fn reset_search(&mut self) {
336        self.epoch = self.epoch.wrapping_add(1);
337        if self.epoch == 0 {
338            self.marks.fill(0);
339            self.epoch = 1;
340        }
341        self.visited_ids.clear();
342        self.visited_dists.clear();
343        self.frontier.clear();
344        self.work.clear();
345    }
346
347    #[inline]
348    fn is_marked(&self, idx: usize) -> bool {
349        self.marks[idx] == self.epoch
350    }
351
352    #[inline]
353    fn mark_with_dist(&mut self, idx: usize, dist: f32) {
354        self.marks[idx] = self.epoch;
355        self.visited_ids.push(idx as u32);
356        self.visited_dists.push(dist);
357    }
358}
359
360#[derive(Debug)]
361struct IncrementalInsertScratch {
362    build: BuildScratch,
363}
364
365impl IncrementalInsertScratch {
366    fn new(n: usize, beam_width: usize, max_degree: usize, extra_seeds: usize) -> Self {
367        Self {
368            build: BuildScratch::new(n, beam_width, max_degree, extra_seeds),
369        }
370    }
371}
372
373/// Main struct representing a DiskANN index (generic over vector element `T` and distance `D`)
374pub struct DiskANN<T, D>
375where
376    T: bytemuck::Pod + Copy + Send + Sync + 'static,
377    D: Distance<T> + Send + Sync + Copy + Clone + 'static,
378{
379    /// Dimensionality of vectors in the index
380    pub dim: usize,
381    /// Number of vectors in the index
382    pub num_vectors: usize,
383    /// Maximum number of edges per node
384    pub max_degree: usize,
385    /// Informational: type name of the distance (from metadata)
386    pub distance_name: String,
387
388    /// ID of the medoid (used as entry point)
389    medoid_id: u32,
390    // Offsets
391    vectors_offset: u64,
392    adjacency_offset: u64,
393
394    /// Memory-mapped file
395    mmap: Mmap,
396
397    /// The distance strategy
398    dist: D,
399
400    /// keep `T` in the type so the compiler knows about it
401    _phantom: PhantomData<T>,
402}
403
404// constructors
405
406impl<T, D> DiskANN<T, D>
407where
408    T: bytemuck::Pod + Copy + Send + Sync + 'static,
409    D: Distance<T> + Send + Sync + Copy + Clone + 'static,
410{
411    /// Build with default parameters: (M=64, L=128, alpha=1.2, extra_seeds=1).
412    pub fn build_index_default(
413        vectors: &[Vec<T>],
414        dist: D,
415        file_path: &str,
416    ) -> Result<Self, DiskAnnError> {
417        Self::build_index(
418            vectors,
419            DISKANN_DEFAULT_MAX_DEGREE,
420            DISKANN_DEFAULT_BUILD_BEAM,
421            DISKANN_DEFAULT_ALPHA,
422            DISKANN_DEFAULT_EXTRA_SEEDS,
423            dist,
424            file_path,
425        )
426    }
427
428    /// Build with a `DiskAnnParams` bundle.
429    pub fn build_index_with_params(
430        vectors: &[Vec<T>],
431        dist: D,
432        file_path: &str,
433        p: DiskAnnParams,
434    ) -> Result<Self, DiskAnnError> {
435        Self::build_index(
436            vectors,
437            p.max_degree,
438            p.build_beam_width,
439            p.alpha,
440            p.extra_seeds,
441            dist,
442            file_path,
443        )
444    }
445
446    /// Opens an existing index file, supplying the distance strategy explicitly.
447    pub fn open_index_with(path: &str, dist: D) -> Result<Self, DiskAnnError> {
448        let mut file = OpenOptions::new().read(true).write(false).open(path)?;
449
450        // Read metadata length
451        let mut buf8 = [0u8; 8];
452        file.seek(SeekFrom::Start(0))?;
453        file.read_exact(&mut buf8)?;
454        let md_len = u64::from_le_bytes(buf8);
455
456        // Read metadata
457        let mut md_bytes = vec![0u8; md_len as usize];
458        file.read_exact(&mut md_bytes)?;
459        let metadata: Metadata = bincode::deserialize(&md_bytes)?;
460
461        let mmap = unsafe { memmap2::Mmap::map(&file)? };
462
463        // Validate element size vs T
464        let want = std::mem::size_of::<T>() as u8;
465        if metadata.elem_size != want {
466            return Err(DiskAnnError::IndexError(format!(
467                "element size mismatch: file has {}B, T is {}B",
468                metadata.elem_size, want
469            )));
470        }
471
472        // Optional sanity/logging: warn if type differs from recorded name
473        let expected = std::any::type_name::<D>();
474        if metadata.distance_name != expected {
475            eprintln!(
476                "Warning: index recorded distance `{}` but you opened with `{}`",
477                metadata.distance_name, expected
478            );
479        }
480
481        Ok(Self {
482            dim: metadata.dim,
483            num_vectors: metadata.num_vectors,
484            max_degree: metadata.max_degree,
485            distance_name: metadata.distance_name,
486            medoid_id: metadata.medoid_id,
487            vectors_offset: metadata.vectors_offset,
488            adjacency_offset: metadata.adjacency_offset,
489            mmap,
490            dist,
491            _phantom: PhantomData,
492        })
493    }
494}
495
496/// Extra sugar when your distance type implements `Default`.
497impl<T, D> DiskANN<T, D>
498where
499    T: bytemuck::Pod + Copy + Send + Sync + 'static,
500    D: Distance<T> + Default + Send + Sync + Copy + Clone + 'static,
501{
502    /// Build with default params **and** `D::default()` metric.
503    pub fn build_index_default_metric(
504        vectors: &[Vec<T>],
505        file_path: &str,
506    ) -> Result<Self, DiskAnnError> {
507        Self::build_index_default(vectors, D::default(), file_path)
508    }
509
510    /// Open an index using `D::default()` as the distance (matches what you built with).
511    pub fn open_index_default_metric(path: &str) -> Result<Self, DiskAnnError> {
512        Self::open_index_with(path, D::default())
513    }
514}
515
516impl<T, D> DiskANN<T, D>
517where
518    T: bytemuck::Pod + Copy + Send + Sync + 'static,
519    D: Distance<T> + Send + Sync + Copy + Clone + 'static,
520{
521    /// Builds a new index from provided vectors
522    ///
523    /// # Arguments
524    /// * `vectors` - The vectors to index (slice of Vec<T>)
525    /// * `max_degree` - Maximum edges per node (M ~ 24-64+)
526    /// * `build_beam_width` - Construction L (e.g., 128-400)
527    /// * `alpha` - Pruning parameter (1.2–2.0)
528    /// * `extra_seeds` - Extra random seeds per node (>=0)
529    /// * `dist` - Any `anndists::Distance<T>`
530    /// * `file_path` - Path of index file
531    pub fn build_index(
532        vectors: &[Vec<T>],
533        max_degree: usize,
534        build_beam_width: usize,
535        alpha: f32,
536        extra_seeds: usize,
537        dist: D,
538        file_path: &str,
539    ) -> Result<Self, DiskAnnError> {
540        let flat = FlatVectors::from_vecs(vectors)?;
541
542        let num_vectors = flat.n;
543        let dim = flat.dim;
544
545        let mut file = OpenOptions::new()
546            .create(true)
547            .write(true)
548            .read(true)
549            .truncate(true)
550            .open(file_path)?;
551
552        // Reserve space for metadata (we'll write it after data)
553        let vectors_offset = 1024 * 1024;
554        assert_eq!(
555            (vectors_offset as usize) % std::mem::align_of::<T>(),
556            0,
557            "vectors_offset must be aligned for T"
558        );
559
560        let elem_sz = std::mem::size_of::<T>() as u64;
561        let total_vector_bytes = (num_vectors as u64) * (dim as u64) * elem_sz;
562
563        // Write vectors contiguous
564        file.seek(SeekFrom::Start(vectors_offset as u64))?;
565        file.write_all(bytemuck::cast_slice::<T, u8>(&flat.data))?;
566
567        // Compute medoid using flat storage
568        let medoid_id = calculate_medoid(&flat, dist);
569
570        // Build graph
571        let adjacency_offset = vectors_offset as u64 + total_vector_bytes;
572        let graph = build_vamana_graph(
573            &flat,
574            max_degree,
575            build_beam_width,
576            alpha,
577            extra_seeds,
578            dist,
579            medoid_id as u32,
580        );
581
582        // Write adjacency lists
583        file.seek(SeekFrom::Start(adjacency_offset))?;
584        for neighbors in &graph {
585            let mut padded = neighbors.clone();
586            padded.resize(max_degree, PAD_U32);
587            let bytes = bytemuck::cast_slice::<u32, u8>(&padded);
588            file.write_all(bytes)?;
589        }
590
591        // Write metadata
592        let metadata = Metadata {
593            dim,
594            num_vectors,
595            max_degree,
596            medoid_id: medoid_id as u32,
597            vectors_offset: vectors_offset as u64,
598            adjacency_offset,
599            elem_size: std::mem::size_of::<T>() as u8,
600            distance_name: std::any::type_name::<D>().to_string(),
601        };
602
603        let md_bytes = bincode::serialize(&metadata)?;
604        file.seek(SeekFrom::Start(0))?;
605        let md_len = md_bytes.len() as u64;
606        file.write_all(&md_len.to_le_bytes())?;
607        file.write_all(&md_bytes)?;
608        file.sync_all()?;
609
610        // Memory map the file
611        let mmap = unsafe { memmap2::Mmap::map(&file)? };
612
613        Ok(Self {
614            dim,
615            num_vectors,
616            max_degree,
617            distance_name: metadata.distance_name,
618            medoid_id: metadata.medoid_id,
619            vectors_offset: metadata.vectors_offset,
620            adjacency_offset: metadata.adjacency_offset,
621            mmap,
622            dist,
623            _phantom: PhantomData,
624        })
625    }
626
627    /// Searches the index for nearest neighbors using a best-first beam search.
628    /// Termination rule: continue while the best frontier can still improve the worst in working set.
629    pub fn search_with_dists(&self, query: &[T], k: usize, beam_width: usize) -> Vec<(u32, f32)> {
630        assert_eq!(
631            query.len(),
632            self.dim,
633            "Query dim {} != index dim {}",
634            query.len(),
635            self.dim
636        );
637
638        let mut visited = HashSet::new();
639        let mut frontier: BinaryHeap<Reverse<Candidate>> = BinaryHeap::new();
640        let mut w: BinaryHeap<Candidate> = BinaryHeap::new();
641
642        let start_dist = self.distance_to(query, self.medoid_id as usize);
643        let start = Candidate {
644            dist: start_dist,
645            id: self.medoid_id,
646        };
647        frontier.push(Reverse(start));
648        w.push(start);
649        visited.insert(self.medoid_id);
650
651        while let Some(Reverse(best)) = frontier.peek().copied() {
652            if w.len() >= beam_width {
653                if let Some(worst) = w.peek() {
654                    if best.dist >= worst.dist {
655                        break;
656                    }
657                }
658            }
659            let Reverse(current) = frontier.pop().unwrap();
660
661            for &nb in self.get_neighbors(current.id) {
662                if nb == PAD_U32 {
663                    continue;
664                }
665                if !visited.insert(nb) {
666                    continue;
667                }
668
669                let d = self.distance_to(query, nb as usize);
670                let cand = Candidate { dist: d, id: nb };
671
672                if w.len() < beam_width {
673                    w.push(cand);
674                    frontier.push(Reverse(cand));
675                } else if d < w.peek().unwrap().dist {
676                    w.pop();
677                    w.push(cand);
678                    frontier.push(Reverse(cand));
679                }
680            }
681        }
682
683        let mut results: Vec<_> = w.into_vec();
684        results.sort_by(|a, b| a.dist.total_cmp(&b.dist));
685        results.truncate(k);
686        results.into_iter().map(|c| (c.id, c.dist)).collect()
687    }
688
689    /// search but only return neighbor ids
690    pub fn search(&self, query: &[T], k: usize, beam_width: usize) -> Vec<u32> {
691        self.search_with_dists(query, k, beam_width)
692            .into_iter()
693            .map(|(id, _dist)| id)
694            .collect()
695    }
696
697    /// Gets the neighbors of a node from the (fixed-degree) adjacency region
698    fn get_neighbors(&self, node_id: u32) -> &[u32] {
699        let offset = self.adjacency_offset + (node_id as u64 * self.max_degree as u64 * 4);
700        let start = offset as usize;
701        let end = start + (self.max_degree * 4);
702        let bytes = &self.mmap[start..end];
703        bytemuck::cast_slice(bytes)
704    }
705
706    /// Computes distance between `query` and vector `idx`
707    fn distance_to(&self, query: &[T], idx: usize) -> f32 {
708        let elem_sz = std::mem::size_of::<T>();
709        let offset = self.vectors_offset + (idx as u64 * self.dim as u64 * elem_sz as u64);
710        let start = offset as usize;
711        let end = start + (self.dim * elem_sz);
712        let bytes = &self.mmap[start..end];
713        let vector: &[T] = bytemuck::cast_slice(bytes);
714        self.dist.eval(query, vector)
715    }
716
717    /// Gets a vector from the index
718    pub fn get_vector(&self, idx: usize) -> Vec<T> {
719        let elem_sz = std::mem::size_of::<T>();
720        let offset = self.vectors_offset + (idx as u64 * self.dim as u64 * elem_sz as u64);
721        let start = offset as usize;
722        let end = start + (self.dim * elem_sz);
723        let bytes = &self.mmap[start..end];
724        let vector: &[T] = bytemuck::cast_slice(bytes);
725        vector.to_vec()
726    }
727}
728
729/// Calculates the medoid using flat contiguous storage.
730fn calculate_medoid<T, D>(vectors: &FlatVectors<T>, dist: D) -> usize
731where
732    T: bytemuck::Pod + Copy + Send + Sync,
733    D: Distance<T> + Copy + Sync,
734{
735    let n = vectors.n;
736    let k = 8.min(n);
737    let mut rng = thread_rng();
738    let pivots: Vec<usize> = (0..k).map(|_| rng.gen_range(0..n)).collect();
739
740    let (best_idx, _best_score) = (0..n)
741        .into_par_iter()
742        .map(|i| {
743            let vi = vectors.row(i);
744            let score: f32 = pivots.iter().map(|&p| dist.eval(vi, vectors.row(p))).sum();
745            (i, score)
746        })
747        .reduce(|| (0usize, f32::MAX), |a, b| if a.1 <= b.1 { a } else { b });
748
749    best_idx
750}
751
752fn dedup_keep_best_by_id_in_place(cands: &mut Vec<(u32, f32)>) {
753    if cands.is_empty() {
754        return;
755    }
756
757    cands.sort_by(|a, b| a.0.cmp(&b.0).then_with(|| a.1.total_cmp(&b.1)));
758
759    let mut write = 0usize;
760    for read in 0..cands.len() {
761        if write == 0 || cands[read].0 != cands[write - 1].0 {
762            cands[write] = cands[read];
763            write += 1;
764        }
765    }
766    cands.truncate(write);
767}
768
769/// Merge one micro-batch of newly computed outgoing neighbor lists back into the graph.
770/// Mark all nodes in the chunk as affected.
771/// Count reverse-edge insertions implied by the chunk.
772/// Build a CSR-style flat incoming buffer.
773/// Commit chunk outgoing lists.
774/// Re-prune only the affected nodes.
775fn merge_chunk_updates_into_graph_reuse<T, D>(
776    graph: &mut [Vec<u32>],
777    chunk_nodes: &[usize],
778    chunk_pruned: &[Vec<u32>],
779    vectors: &FlatVectors<T>,
780    max_degree: usize,
781    slack_limit: usize,
782    alpha: f32,
783    dist: D,
784    merge: &mut MergeScratch,
785) where
786    T: bytemuck::Pod + Copy + Send + Sync,
787    D: Distance<T> + Copy + Sync,
788{
789    merge.reset();
790
791    // Mark chunk nodes as affected.
792    for &u in chunk_nodes {
793        merge.mark_affected(u);
794    }
795
796    // Count reverse-edge insertions and mark touched destinations.
797    let mut total_incoming = 0usize;
798
799    for (local_idx, &u) in chunk_nodes.iter().enumerate() {
800        for &dst in &chunk_pruned[local_idx] {
801            let dst_usize = dst as usize;
802            if dst_usize == u {
803                continue;
804            }
805
806            merge.mark_affected(dst_usize);
807            merge.incoming_counts[dst_usize] += 1;
808            total_incoming += 1;
809        }
810    }
811
812    // Build CSR offsets only for affected nodes.
813    merge.affected_nodes.sort_unstable();
814
815    let mut running = 0usize;
816    for &u in &merge.affected_nodes {
817        merge.incoming_offsets[u] = running;
818        running += merge.incoming_counts[u];
819        merge.incoming_offsets[u + 1] = running;
820    }
821
822    merge.incoming_flat.resize(total_incoming, PAD_U32);
823
824    // Initialize write cursors.
825    for &u in &merge.affected_nodes {
826        merge.incoming_write[u] = merge.incoming_offsets[u];
827    }
828
829    // Fill CSR incoming buffer.
830    for (local_idx, &u) in chunk_nodes.iter().enumerate() {
831        for &dst in &chunk_pruned[local_idx] {
832            let dst_usize = dst as usize;
833            if dst_usize == u {
834                continue;
835            }
836
837            let pos = merge.incoming_write[dst_usize];
838            merge.incoming_flat[pos] = u as u32;
839            merge.incoming_write[dst_usize] += 1;
840        }
841    }
842
843    // Commit chunk outgoing lists first.
844    for (local_idx, &u) in chunk_nodes.iter().enumerate() {
845        graph[u] = chunk_pruned[local_idx].clone();
846    }
847
848    // Hybrid slack-aware microbatch merge:
849    // keep merged lists under slack, reprune only overflowed ones.
850    let affected = merge.affected_nodes.clone();
851
852    let updated_pairs: Vec<(usize, Vec<u32>)> = affected
853        .into_par_iter()
854        .map(|u| {
855            let start = merge.incoming_offsets[u];
856            let end = merge.incoming_offsets[u + 1];
857
858            let mut ids: Vec<u32> = Vec::with_capacity(graph[u].len() + (end - start));
859
860            // Current adjacency after chunk commit.
861            ids.extend_from_slice(&graph[u]);
862
863            // Reverse insertions from this chunk.
864            if start < end {
865                ids.extend_from_slice(&merge.incoming_flat[start..end]);
866            }
867
868            // Remove self-loops / padding.
869            ids.retain(|&id| id != PAD_U32 && id as usize != u);
870
871            // Deduplicate.
872            ids.sort_unstable();
873            ids.dedup();
874
875            if ids.is_empty() {
876                return (u, Vec::new());
877            }
878
879            // Under slack: keep as-is.
880            if ids.len() <= slack_limit {
881                return (u, ids);
882            }
883
884            // Overflow: score and prune back to max_degree.
885            let mut pool = Vec::<(u32, f32)>::with_capacity(ids.len());
886            for id in ids {
887                let d = dist.eval(vectors.row(u), vectors.row(id as usize));
888                pool.push((id, d));
889            }
890
891            let pruned = prune_neighbors(u, &pool, vectors, max_degree, alpha, dist);
892            (u, pruned)
893        })
894        .collect();
895
896    for (u, neigh) in updated_pairs {
897        graph[u] = neigh;
898    }
899
900    // Cleanup touched metadata.
901    for &u in &merge.affected_nodes {
902        merge.incoming_counts[u] = 0;
903        merge.incoming_offsets[u + 1] = 0;
904    }
905}
906
907/// Reusable scratch buffers for micro-batch merge.
908/// This avoids rebuilding `Vec<Vec<u32>>` for incoming reverse edges on every chunk.
909/// Instead, incoming reverse edges are accumulated into a CSR-like flat buffer.
910///
911/// Layout:
912/// - incoming_counts[u] = number of reverse edges targeting node u in this chunk
913/// - incoming_offsets[u]..incoming_offsets[u+1] is u's segment in incoming_flat
914/// - affected_nodes stores exactly the nodes touched in this chunk, so we do not
915///   scan all `n` nodes during merge.
916#[derive(Debug)]
917struct MergeScratch {
918    incoming_counts: Vec<usize>,
919    incoming_offsets: Vec<usize>,
920    incoming_write: Vec<usize>,
921    incoming_flat: Vec<u32>,
922
923    affected_marks: Vec<u32>,
924    affected_epoch: u32,
925    affected_nodes: Vec<usize>,
926}
927
928impl MergeScratch {
929    fn new(n: usize) -> Self {
930        Self {
931            incoming_counts: vec![0usize; n],
932            incoming_offsets: vec![0usize; n + 1],
933            incoming_write: vec![0usize; n],
934            incoming_flat: Vec::new(),
935            affected_marks: vec![0u32; n],
936            affected_epoch: 1,
937            affected_nodes: Vec::new(),
938        }
939    }
940
941    #[inline]
942    fn reset(&mut self) {
943        self.affected_epoch = self.affected_epoch.wrapping_add(1);
944        if self.affected_epoch == 0 {
945            self.affected_marks.fill(0);
946            self.affected_epoch = 1;
947        }
948        self.affected_nodes.clear();
949        self.incoming_flat.clear();
950    }
951
952    #[inline]
953    fn mark_affected(&mut self, u: usize) {
954        if self.affected_marks[u] != self.affected_epoch {
955            self.affected_marks[u] = self.affected_epoch;
956            self.affected_nodes.push(u);
957            self.incoming_counts[u] = 0;
958        }
959    }
960}
961
962/// Build a Vamana-like graph using a micro-batched practical DiskANN strategy,
963/// with reusable scratch both for per-thread search state and for chunk merge state.
964fn build_vamana_graph<T, D>(
965    vectors: &FlatVectors<T>,
966    max_degree: usize,
967    build_beam_width: usize,
968    alpha: f32,
969    extra_seeds: usize,
970    dist: D,
971    medoid_id: u32,
972) -> Vec<Vec<u32>>
973where
974    T: bytemuck::Pod + Copy + Send + Sync,
975    D: Distance<T> + Copy + Sync,
976{
977    let n = vectors.n;
978    let mut graph = vec![Vec::<u32>::new(); n];
979    // Bootstrap with a random R-out directed graph.
980    {
981        let mut rng = thread_rng();
982        let target = max_degree.min(n.saturating_sub(1));
983
984        for i in 0..n {
985            let mut s = HashSet::with_capacity(target);
986            while s.len() < target {
987                let nb = rng.gen_range(0..n);
988                if nb != i {
989                    s.insert(nb as u32);
990                }
991            }
992            graph[i] = s.into_iter().collect();
993        }
994    }
995
996    let mut rng = thread_rng();
997    let slack_limit = ((GRAPH_SLACK_FACTOR * max_degree as f32).ceil() as usize).max(max_degree);
998
999    // Reused across all chunks in the single Vamana construction pass.
1000    let mut merge_scratch = MergeScratch::new(n);
1001
1002    let mut order: Vec<usize> = (0..n).collect();
1003    order.shuffle(&mut rng);
1004
1005    for chunk in order.chunks(MICRO_BATCH_CHUNK_SIZE) {
1006        let snapshot = &graph;
1007        // Compute new outgoing lists for this chunk in parallel.
1008        let chunk_results: Vec<(usize, Vec<u32>)> = chunk
1009            .par_iter()
1010            .map_init(
1011                || IncrementalInsertScratch::new(n, build_beam_width, max_degree, extra_seeds),
1012                |scratch, &u| {
1013                    let bs = &mut scratch.build;
1014                    bs.candidates.clear();
1015
1016                    // Start from current adjacency.
1017                    for &nb in &snapshot[u] {
1018                        let d = dist.eval(vectors.row(u), vectors.row(nb as usize));
1019                        bs.candidates.push((nb, d));
1020                    }
1021
1022                    // Seed list: medoid + distinct random starts.
1023                    bs.seeds.clear();
1024                    bs.seeds.push(medoid_id as usize);
1025
1026                    let mut local_rng = thread_rng();
1027                    while bs.seeds.len() < 1 + extra_seeds {
1028                        let s = local_rng.gen_range(0..n);
1029                        if !bs.seeds.contains(&s) {
1030                            bs.seeds.push(s);
1031                        }
1032                    }
1033
1034                    let seeds_len = bs.seeds.len();
1035                    for si in 0..seeds_len {
1036                        let start = bs.seeds[si];
1037
1038                        greedy_search_visited_collect(
1039                            vectors.row(u),
1040                            vectors,
1041                            snapshot,
1042                            start,
1043                            build_beam_width,
1044                            dist,
1045                            bs,
1046                        );
1047
1048                        for i in 0..bs.visited_ids.len() {
1049                            bs.candidates.push((bs.visited_ids[i], bs.visited_dists[i]));
1050                        }
1051                    }
1052
1053                    dedup_keep_best_by_id_in_place(&mut bs.candidates);
1054
1055                    let pruned =
1056                        prune_neighbors(u, &bs.candidates, vectors, max_degree, alpha, dist);
1057
1058                    (u, pruned)
1059                },
1060            )
1061            .collect();
1062
1063        let mut chunk_nodes = Vec::<usize>::with_capacity(chunk_results.len());
1064        let mut chunk_pruned = Vec::<Vec<u32>>::with_capacity(chunk_results.len());
1065
1066        for (u, pruned) in chunk_results {
1067            chunk_nodes.push(u);
1068            chunk_pruned.push(pruned);
1069        }
1070        // Merge chunk back into graph using reusable CSR-style scratch.
1071        merge_chunk_updates_into_graph_reuse(
1072            &mut graph,
1073            &chunk_nodes,
1074            &chunk_pruned,
1075            vectors,
1076            max_degree,
1077            slack_limit,
1078            alpha,
1079            dist,
1080            &mut merge_scratch,
1081        );
1082    }
1083
1084    // Final cleanup: enforce bounded degree and deduplication.
1085    graph
1086        .into_par_iter()
1087        .enumerate()
1088        .map(|(u, neigh)| {
1089            if neigh.len() <= max_degree {
1090                return neigh;
1091            }
1092
1093            let mut ids = neigh;
1094            ids.sort_unstable();
1095            ids.dedup();
1096
1097            let pool: Vec<(u32, f32)> = ids
1098                .into_iter()
1099                .filter(|&id| id as usize != u)
1100                .map(|id| (id, dist.eval(vectors.row(u), vectors.row(id as usize))))
1101                .collect();
1102
1103            prune_neighbors(u, &pool, vectors, max_degree, alpha, dist)
1104        })
1105        .collect()
1106}
1107
1108/// Build-time greedy search:
1109/// - dense visited marks instead of HashMap/HashSet
1110/// - visited_ids + visited_dists instead of recomputing distances later
1111/// - ordered beams instead of BinaryHeap
1112/// Output is written into `scratch.visited_ids` and `scratch.visited_dists`.
1113fn greedy_search_visited_collect<T, D>(
1114    query: &[T],
1115    vectors: &FlatVectors<T>,
1116    graph: &[Vec<u32>],
1117    start_id: usize,
1118    beam_width: usize,
1119    dist: D,
1120    scratch: &mut BuildScratch,
1121) where
1122    T: bytemuck::Pod + Copy + Send + Sync,
1123    D: Distance<T> + Copy,
1124{
1125    scratch.reset_search();
1126
1127    let start_dist = dist.eval(query, vectors.row(start_id));
1128    let start = Candidate {
1129        dist: start_dist,
1130        id: start_id as u32,
1131    };
1132
1133    scratch.frontier.insert_unbounded(start);
1134    scratch.work.insert_capped(start, beam_width);
1135    scratch.mark_with_dist(start_id, start_dist);
1136
1137    while !scratch.frontier.is_empty() {
1138        let best = scratch.frontier.best().unwrap();
1139        if scratch.work.len() >= beam_width {
1140            if let Some(worst) = scratch.work.worst() {
1141                if best.dist >= worst.dist {
1142                    break;
1143                }
1144            }
1145        }
1146
1147        let cur = scratch.frontier.pop_best().unwrap();
1148
1149        for &nb in &graph[cur.id as usize] {
1150            let nb_usize = nb as usize;
1151            if scratch.is_marked(nb_usize) {
1152                continue;
1153            }
1154
1155            let d = dist.eval(query, vectors.row(nb_usize));
1156            scratch.mark_with_dist(nb_usize, d);
1157
1158            let cand = Candidate { dist: d, id: nb };
1159
1160            if scratch.work.len() < beam_width {
1161                scratch.work.insert_unbounded(cand);
1162                scratch.frontier.insert_unbounded(cand);
1163            } else if let Some(worst) = scratch.work.worst() {
1164                if d < worst.dist {
1165                    scratch.work.insert_capped(cand, beam_width);
1166                    scratch.frontier.insert_unbounded(cand);
1167                }
1168            }
1169        }
1170    }
1171}
1172
1173/// Vamana RobustPrune with progressive alpha relaxation.
1174fn prune_neighbors<T, D>(
1175    node_id: usize,
1176    candidates: &[(u32, f32)],
1177    vectors: &FlatVectors<T>,
1178    max_degree: usize,
1179    alpha: f32,
1180    dist: D,
1181) -> Vec<u32>
1182where
1183    T: bytemuck::Pod + Copy + Send + Sync,
1184    D: Distance<T> + Copy,
1185{
1186    if candidates.is_empty() || max_degree == 0 {
1187        return Vec::new();
1188    }
1189
1190    // Sort by distance from node_id, nearest first.
1191    let mut sorted = candidates.to_vec();
1192    sorted.sort_by(|a, b| a.1.total_cmp(&b.1));
1193    sorted.truncate(MAX_OCCLUSION_SIZE);
1194
1195    // Remove self and duplicate ids while keeping the nearest occurrence.
1196    let mut uniq = Vec::<(u32, f32)>::with_capacity(sorted.len());
1197    let mut seen = HashSet::with_capacity(sorted.len());
1198    for &(cand_id, cand_dist) in &sorted {
1199        if cand_id as usize == node_id || !seen.insert(cand_id) {
1200            continue;
1201        }
1202        uniq.push((cand_id, cand_dist));
1203    }
1204
1205    if uniq.is_empty() {
1206        return Vec::new();
1207    }
1208
1209    let mut pruned = Vec::<u32>::with_capacity(max_degree);
1210    let mut occlude_factors = vec![0.0f32; uniq.len()];
1211    let target_alpha = alpha.max(1.0);
1212    let increment = target_alpha.min(1.2);
1213    let mut current_alpha = 1.0f32;
1214
1215    loop {
1216        for i in 0..uniq.len() {
1217            if pruned.len() >= max_degree {
1218                return pruned;
1219            }
1220            if occlude_factors[i] > current_alpha {
1221                continue;
1222            }
1223
1224            let (selected_id, _) = uniq[i];
1225            occlude_factors[i] = f32::MAX;
1226            pruned.push(selected_id);
1227
1228            for j in (i + 1)..uniq.len() {
1229                if occlude_factors[j] > target_alpha {
1230                    continue;
1231                }
1232
1233                let (candidate_id, candidate_dist) = uniq[j];
1234                let pair_dist = dist.eval(
1235                    vectors.row(candidate_id as usize),
1236                    vectors.row(selected_id as usize),
1237                );
1238                let factor = if pair_dist == 0.0 {
1239                    f32::MAX
1240                } else {
1241                    candidate_dist / pair_dist
1242                };
1243                occlude_factors[j] = occlude_factors[j].max(factor);
1244            }
1245        }
1246
1247        if current_alpha >= target_alpha {
1248            break;
1249        }
1250        current_alpha = (current_alpha * increment).min(target_alpha);
1251    }
1252
1253    pruned
1254}
1255
1256#[cfg(test)]
1257mod tests {
1258    use super::*;
1259    use anndists::dist::{DistCosine, DistJaccard, DistL2};
1260    use rand::{Rng, SeedableRng, rngs::StdRng};
1261    use std::fs;
1262
1263    fn euclid(a: &[f32], b: &[f32]) -> f32 {
1264        a.iter()
1265            .zip(b)
1266            .map(|(x, y)| (x - y) * (x - y))
1267            .sum::<f32>()
1268            .sqrt()
1269    }
1270
1271    fn exact_recall<T, D>(
1272        index: &DiskANN<T, D>,
1273        vectors: &[Vec<T>],
1274        queries: &[Vec<T>],
1275        dist: D,
1276        k: usize,
1277        beam: usize,
1278    ) -> f32
1279    where
1280        T: bytemuck::Pod + Copy + Send + Sync + 'static,
1281        D: Distance<T> + Send + Sync + Copy + Clone + 'static,
1282    {
1283        let mut hits = 0usize;
1284        for query in queries {
1285            let mut truth: Vec<(usize, f32)> = vectors
1286                .iter()
1287                .enumerate()
1288                .map(|(id, vector)| (id, dist.eval(query, vector)))
1289                .collect();
1290            truth.sort_by(|a, b| a.1.total_cmp(&b.1));
1291            let truth: HashSet<u32> = truth.into_iter().take(k).map(|(id, _)| id as u32).collect();
1292
1293            hits += index
1294                .search(query, k, beam)
1295                .into_iter()
1296                .filter(|id| truth.contains(id))
1297                .count();
1298        }
1299        hits as f32 / (queries.len() * k) as f32
1300    }
1301
1302    fn quality_params() -> DiskAnnParams {
1303        DiskAnnParams {
1304            max_degree: 32,
1305            build_beam_width: 128,
1306            alpha: 1.2,
1307            extra_seeds: 1,
1308        }
1309    }
1310
1311    #[test]
1312    fn test_small_index_l2() {
1313        let path = "test_small_l2.db";
1314        let _ = fs::remove_file(path);
1315
1316        let vectors = vec![
1317            vec![0.0, 0.0],
1318            vec![1.0, 0.0],
1319            vec![0.0, 1.0],
1320            vec![1.0, 1.0],
1321            vec![0.5, 0.5],
1322        ];
1323
1324        let index = DiskANN::<f32, DistL2>::build_index_default(&vectors, DistL2, path).unwrap();
1325
1326        let q = vec![0.1, 0.1];
1327        let nns = index.search(&q, 3, 8);
1328        assert_eq!(nns.len(), 3);
1329
1330        let v = index.get_vector(nns[0] as usize);
1331        assert!(euclid(&q, &v) < 1.0);
1332
1333        let _ = fs::remove_file(path);
1334    }
1335
1336    #[test]
1337    fn test_cosine() {
1338        let path = "test_cosine.db";
1339        let _ = fs::remove_file(path);
1340
1341        let vectors = vec![
1342            vec![1.0, 0.0, 0.0],
1343            vec![0.0, 1.0, 0.0],
1344            vec![0.0, 0.0, 1.0],
1345            vec![1.0, 1.0, 0.0],
1346            vec![1.0, 0.0, 1.0],
1347        ];
1348
1349        let index =
1350            DiskANN::<f32, DistCosine>::build_index_default(&vectors, DistCosine, path).unwrap();
1351
1352        let q = vec![2.0, 0.0, 0.0];
1353        let nns = index.search(&q, 2, 8);
1354        assert_eq!(nns.len(), 2);
1355
1356        let v = index.get_vector(nns[0] as usize);
1357        let dot = v.iter().zip(&q).map(|(a, b)| a * b).sum::<f32>();
1358        let n1 = v.iter().map(|x| x * x).sum::<f32>().sqrt();
1359        let n2 = q.iter().map(|x| x * x).sum::<f32>().sqrt();
1360        let cos = dot / (n1 * n2);
1361        assert!(cos > 0.7);
1362
1363        let _ = fs::remove_file(path);
1364    }
1365
1366    #[test]
1367    fn test_persistence_and_open() {
1368        let path = "test_persist.db";
1369        let _ = fs::remove_file(path);
1370
1371        let vectors = vec![
1372            vec![0.0, 0.0],
1373            vec![1.0, 0.0],
1374            vec![0.0, 1.0],
1375            vec![1.0, 1.0],
1376        ];
1377
1378        {
1379            let _idx = DiskANN::<f32, DistL2>::build_index_default(&vectors, DistL2, path).unwrap();
1380        }
1381
1382        let idx2 = DiskANN::<f32, DistL2>::open_index_default_metric(path).unwrap();
1383        assert_eq!(idx2.num_vectors, 4);
1384        assert_eq!(idx2.dim, 2);
1385
1386        let q = vec![0.9, 0.9];
1387        let res = idx2.search(&q, 2, 8);
1388        assert_eq!(res[0], 3);
1389
1390        let _ = fs::remove_file(path);
1391    }
1392
1393    #[test]
1394    fn test_grid_connectivity() {
1395        let path = "test_grid.db";
1396        let _ = fs::remove_file(path);
1397
1398        let mut vectors = Vec::new();
1399        for i in 0..5 {
1400            for j in 0..5 {
1401                vectors.push(vec![i as f32, j as f32]);
1402            }
1403        }
1404
1405        let index = DiskANN::<f32, DistL2>::build_index_with_params(
1406            &vectors,
1407            DistL2,
1408            path,
1409            DiskAnnParams {
1410                max_degree: 4,
1411                build_beam_width: 64,
1412                alpha: 1.5,
1413                extra_seeds: DISKANN_DEFAULT_EXTRA_SEEDS,
1414            },
1415        )
1416        .unwrap();
1417
1418        for target in 0..vectors.len() {
1419            let q = &vectors[target];
1420            let nns = index.search(q, 10, 32);
1421            if !nns.contains(&(target as u32)) {
1422                let v = index.get_vector(nns[0] as usize);
1423                assert!(euclid(q, &v) < 2.0);
1424            }
1425            for &nb in nns.iter().take(5) {
1426                let v = index.get_vector(nb as usize);
1427                assert!(euclid(q, &v) < 5.0);
1428            }
1429        }
1430
1431        let _ = fs::remove_file(path);
1432    }
1433
1434    #[test]
1435    fn test_medium_random() {
1436        let path = "test_medium.db";
1437        let _ = fs::remove_file(path);
1438
1439        let n = 200usize;
1440        let d = 32usize;
1441        let mut rng = rand::thread_rng();
1442        let vectors: Vec<Vec<f32>> = (0..n)
1443            .map(|_| (0..d).map(|_| rng.r#gen::<f32>()).collect())
1444            .collect();
1445
1446        let index = DiskANN::<f32, DistL2>::build_index_with_params(
1447            &vectors,
1448            DistL2,
1449            path,
1450            DiskAnnParams {
1451                max_degree: 32,
1452                build_beam_width: 128,
1453                alpha: 1.2,
1454                extra_seeds: DISKANN_DEFAULT_EXTRA_SEEDS,
1455            },
1456        )
1457        .unwrap();
1458
1459        let q: Vec<f32> = (0..d).map(|_| rng.r#gen::<f32>()).collect();
1460        let res = index.search(&q, 10, 64);
1461        assert_eq!(res.len(), 10);
1462
1463        let dists: Vec<f32> = res
1464            .iter()
1465            .map(|&id| {
1466                let v = index.get_vector(id as usize);
1467                euclid(&q, &v)
1468            })
1469            .collect();
1470        let mut sorted = dists.clone();
1471        sorted.sort_by(|a, b| a.total_cmp(b));
1472        assert_eq!(dists, sorted);
1473
1474        let _ = fs::remove_file(path);
1475    }
1476
1477    #[test]
1478    fn test_regular_l2_recall() {
1479        let path = "test_regular_l2_recall.db";
1480        let _ = fs::remove_file(path);
1481        let mut rng = StdRng::seed_from_u64(11);
1482        let vectors: Vec<Vec<f32>> = (0..500)
1483            .map(|_| (0..24).map(|_| rng.r#gen::<f32>()).collect())
1484            .collect();
1485        let queries: Vec<Vec<f32>> = (0..40)
1486            .map(|_| (0..24).map(|_| rng.r#gen::<f32>()).collect())
1487            .collect();
1488
1489        let index =
1490            DiskANN::build_index_with_params(&vectors, DistL2, path, quality_params()).unwrap();
1491        let recall = exact_recall(&index, &vectors, &queries, DistL2, 10, 256);
1492        assert!(recall >= 0.95, "regular L2 recall was {recall}");
1493        let _ = fs::remove_file(path);
1494    }
1495
1496    #[test]
1497    fn test_clustered_l2_recall() {
1498        let path = "test_clustered_l2_recall.db";
1499        let _ = fs::remove_file(path);
1500        let mut rng = StdRng::seed_from_u64(23);
1501        let dim = 24usize;
1502        let clusters = 12usize;
1503        let mut vectors = Vec::with_capacity(clusters * 50);
1504        let mut queries = Vec::with_capacity(clusters * 3);
1505
1506        for cluster in 0..clusters {
1507            let mut center = vec![0.0f32; dim];
1508            center[cluster] = 40.0;
1509            center[(cluster + 7) % dim] = -25.0;
1510            for _ in 0..50 {
1511                vectors.push(
1512                    center
1513                        .iter()
1514                        .map(|value| value + rng.gen_range(-0.4f32..0.4f32))
1515                        .collect(),
1516                );
1517            }
1518            for _ in 0..3 {
1519                queries.push(
1520                    center
1521                        .iter()
1522                        .map(|value| value + rng.gen_range(-0.4f32..0.4f32))
1523                        .collect(),
1524                );
1525            }
1526        }
1527
1528        let index =
1529            DiskANN::build_index_with_params(&vectors, DistL2, path, quality_params()).unwrap();
1530        let recall = exact_recall(&index, &vectors, &queries, DistL2, 10, 256);
1531        assert!(recall >= 0.95, "clustered L2 recall was {recall}");
1532        let _ = fs::remove_file(path);
1533    }
1534
1535    #[test]
1536    fn test_cosine_recall() {
1537        let path = "test_cosine_recall.db";
1538        let _ = fs::remove_file(path);
1539        let mut rng = StdRng::seed_from_u64(37);
1540        let vectors: Vec<Vec<f32>> = (0..500)
1541            .map(|_| (0..32).map(|_| rng.gen_range(-1.0f32..1.0f32)).collect())
1542            .collect();
1543        let queries: Vec<Vec<f32>> = (0..40)
1544            .map(|_| (0..32).map(|_| rng.gen_range(-1.0f32..1.0f32)).collect())
1545            .collect();
1546
1547        let index =
1548            DiskANN::build_index_with_params(&vectors, DistCosine, path, quality_params()).unwrap();
1549        let recall = exact_recall(&index, &vectors, &queries, DistCosine, 10, 256);
1550        assert!(recall >= 0.95, "cosine recall was {recall}");
1551        let _ = fs::remove_file(path);
1552    }
1553
1554    #[test]
1555    fn test_jaccard_recall() {
1556        let path = "test_jaccard_recall.db";
1557        let _ = fs::remove_file(path);
1558        let mut rng = StdRng::seed_from_u64(41);
1559        let vectors: Vec<Vec<u32>> = (0..400)
1560            .map(|_| (0..32).map(|_| rng.gen_range(0u32..8u32)).collect())
1561            .collect();
1562        let queries: Vec<Vec<u32>> = (0..40)
1563            .map(|_| (0..32).map(|_| rng.gen_range(0u32..8u32)).collect())
1564            .collect();
1565
1566        let index = DiskANN::build_index_with_params(&vectors, DistJaccard, path, quality_params())
1567            .unwrap();
1568        let recall = exact_recall(&index, &vectors, &queries, DistJaccard, 10, 256);
1569        assert!(recall >= 0.95, "Jaccard recall was {recall}");
1570        let _ = fs::remove_file(path);
1571    }
1572}