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
50mod mmap_dynamic;
51pub use mmap_dynamic::DeleteStats;
52
53/// Padding sentinel for adjacency slots (avoid colliding with node 0).
54const PAD_U32: u32 = u32::MAX;
55
56/// Defaults for in-memory DiskANN builds
57pub const DISKANN_DEFAULT_MAX_DEGREE: usize = 64;
58pub const DISKANN_DEFAULT_BUILD_BEAM: usize = 128;
59pub const DISKANN_DEFAULT_ALPHA: f32 = 1.2;
60/// Default number of extra random seeds per node during graph build
61pub const DISKANN_DEFAULT_EXTRA_SEEDS: usize = 1;
62
63/// Practical DiskANN-style slack before reverse-neighbor re-pruning.
64/// Legacy C++ DiskANN allows reverse lists to grow to about GRAPH_SLACK_FACTOR * R
65/// before triggering prune, instead of pruning immediately at R.
66const GRAPH_SLACK_FACTOR: f32 = 1.3;
67
68/// Maximum candidate pool considered by RobustPrune, matching DiskANN's default.
69const MAX_OCCLUSION_SIZE: usize = 750;
70
71/// Number of nodes processed together in one micro-batch during graph build.
72///
73/// Smaller values:
74/// - are closer to true incremental insertion
75/// - usually improve faithfulness to practical Vamana behavior
76/// - but are slower
77///
78/// Larger values:
79/// - are faster
80/// - but behave more like a batched graph rebuild
81///
82/// Recommended starting values:
83/// - 128 for better quality
84/// - 256 for a balanced tradeoff
85/// - 512 for faster builds
86const MICRO_BATCH_CHUNK_SIZE: usize = 256;
87
88/// Optional bag of knobs if you want to override just a few.
89#[derive(Clone, Copy, Debug)]
90pub struct DiskAnnParams {
91    pub max_degree: usize,
92    pub build_beam_width: usize,
93    pub alpha: f32,
94    /// Extra random seeds per node during graph construction (>=0).
95    pub extra_seeds: usize,
96}
97
98impl Default for DiskAnnParams {
99    fn default() -> Self {
100        Self {
101            max_degree: DISKANN_DEFAULT_MAX_DEGREE,
102            build_beam_width: DISKANN_DEFAULT_BUILD_BEAM,
103            alpha: DISKANN_DEFAULT_ALPHA,
104            extra_seeds: DISKANN_DEFAULT_EXTRA_SEEDS,
105        }
106    }
107}
108
109/// Custom error type for DiskAnn operations
110#[derive(Debug, Error)]
111pub enum DiskAnnError {
112    /// Represents I/O errors during file operations
113    #[error("I/O error: {0}")]
114    Io(#[from] std::io::Error),
115
116    /// Represents serialization/deserialization errors
117    #[error("Serialization error: {0}")]
118    Bincode(#[from] bincode::Error),
119
120    /// Represents index-specific errors
121    #[error("Index error: {0}")]
122    IndexError(String),
123}
124
125/// Internal metadata structure stored in the index file
126#[derive(Serialize, Deserialize, Debug)]
127struct Metadata {
128    dim: usize,
129    num_vectors: usize,
130    max_degree: usize,
131    medoid_id: u32,
132    vectors_offset: u64,
133    adjacency_offset: u64,
134    elem_size: u8,
135    distance_name: String,
136}
137
138/// Candidate for search/frontier queues
139#[derive(Clone, Copy, Debug)]
140pub(crate) struct Candidate {
141    dist: f32,
142    id: u32,
143}
144
145/// One beam-search implementation shared by legacy static and dynamic storage.
146/// Storage adapters provide distances and the currently visible neighbor view.
147pub(crate) fn graph_search(
148    start_id: u32,
149    beam_width: usize,
150    mut distance: impl FnMut(u32) -> f32,
151    mut neighbors: impl FnMut(u32) -> Vec<u32>,
152) -> Vec<Candidate> {
153    let beam_width = beam_width.max(1);
154    let start = Candidate {
155        dist: distance(start_id),
156        id: start_id,
157    };
158    let mut visited = HashSet::from([start_id]);
159    let mut frontier = BinaryHeap::from([Reverse(start)]);
160    let mut work = BinaryHeap::from([start]);
161
162    while let Some(Reverse(best)) = frontier.peek().copied() {
163        if work.len() >= beam_width && best.dist >= work.peek().unwrap().dist {
164            break;
165        }
166        let Reverse(current) = frontier.pop().unwrap();
167        for neighbor in neighbors(current.id) {
168            if !visited.insert(neighbor) {
169                continue;
170            }
171            let candidate = Candidate {
172                dist: distance(neighbor),
173                id: neighbor,
174            };
175            if work.len() < beam_width {
176                work.push(candidate);
177                frontier.push(Reverse(candidate));
178            } else if candidate.dist < work.peek().unwrap().dist {
179                work.pop();
180                work.push(candidate);
181                frontier.push(Reverse(candidate));
182            }
183        }
184    }
185
186    let mut results = work.into_vec();
187    results.sort_by(|a, b| a.dist.total_cmp(&b.dist));
188    results
189}
190impl PartialEq for Candidate {
191    fn eq(&self, other: &Self) -> bool {
192        self.id == other.id && self.dist.to_bits() == other.dist.to_bits()
193    }
194}
195impl Eq for Candidate {}
196impl PartialOrd for Candidate {
197    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
198        Some(
199            self.dist
200                .total_cmp(&other.dist)
201                .then_with(|| self.id.cmp(&other.id)),
202        )
203    }
204}
205impl Ord for Candidate {
206    fn cmp(&self, other: &Self) -> Ordering {
207        self.partial_cmp(other).unwrap_or(Ordering::Equal)
208    }
209}
210
211/// Flat contiguous matrix used during build to improve cache locality.
212///
213/// Rows are stored consecutively in `data`, row-major.
214#[derive(Clone, Debug)]
215struct FlatVectors<T> {
216    data: Vec<T>,
217    dim: usize,
218    n: usize,
219}
220
221impl<T: Copy> FlatVectors<T> {
222    fn from_vecs(vectors: &[Vec<T>]) -> Result<Self, DiskAnnError> {
223        if vectors.is_empty() {
224            return Err(DiskAnnError::IndexError("No vectors provided".to_string()));
225        }
226        let dim = vectors[0].len();
227        for (i, v) in vectors.iter().enumerate() {
228            if v.len() != dim {
229                return Err(DiskAnnError::IndexError(format!(
230                    "Vector {} has dimension {} but expected {}",
231                    i,
232                    v.len(),
233                    dim
234                )));
235            }
236        }
237
238        let n = vectors.len();
239        let mut data = Vec::with_capacity(n * dim);
240        for v in vectors {
241            data.extend_from_slice(v);
242        }
243
244        Ok(Self { data, dim, n })
245    }
246
247    #[inline]
248    fn row(&self, idx: usize) -> &[T] {
249        let start = idx * self.dim;
250        let end = start + self.dim;
251        &self.data[start..end]
252    }
253}
254
255/// Small ordered beam structure used only during build-time greedy search.
256///
257/// It keeps elements in **descending** distance order:
258/// - index 0 is the worst element
259/// - last element is the best element
260///
261/// This makes:
262/// - `best()` cheap via `last()`
263/// - `worst()` cheap via `first()`
264/// - capped beam maintenance simple
265#[derive(Default, Debug)]
266struct OrderedBeam {
267    items: Vec<Candidate>,
268}
269
270impl OrderedBeam {
271    #[inline]
272    fn clear(&mut self) {
273        self.items.clear();
274    }
275
276    #[inline]
277    fn len(&self) -> usize {
278        self.items.len()
279    }
280
281    #[inline]
282    fn is_empty(&self) -> bool {
283        self.items.is_empty()
284    }
285
286    #[inline]
287    fn best(&self) -> Option<Candidate> {
288        self.items.last().copied()
289    }
290
291    #[inline]
292    fn worst(&self) -> Option<Candidate> {
293        self.items.first().copied()
294    }
295
296    #[inline]
297    fn pop_best(&mut self) -> Option<Candidate> {
298        self.items.pop()
299    }
300
301    #[inline]
302    fn reserve(&mut self, cap: usize) {
303        if self.items.capacity() < cap {
304            self.items.reserve(cap - self.items.capacity());
305        }
306    }
307
308    #[inline]
309    fn insert_unbounded(&mut self, cand: Candidate) {
310        let pos = self.items.partition_point(|x| {
311            x.dist > cand.dist || (x.dist.to_bits() == cand.dist.to_bits() && x.id > cand.id)
312        });
313        self.items.insert(pos, cand);
314    }
315
316    #[inline]
317    fn insert_capped(&mut self, cand: Candidate, cap: usize) {
318        if cap == 0 {
319            return;
320        }
321
322        if self.items.len() < cap {
323            self.insert_unbounded(cand);
324            return;
325        }
326
327        // Since items[0] is the worst, only insert if the new candidate is better.
328        let worst = self.items[0];
329        if cand.dist >= worst.dist {
330            return;
331        }
332
333        self.insert_unbounded(cand);
334
335        if self.items.len() > cap {
336            self.items.remove(0);
337        }
338    }
339}
340
341/// Reusable scratch buffers for build-time greedy search.
342/// One instance is created per Rayon worker via `map_init`, so allocations are reused
343/// across many nodes in the build.
344#[derive(Debug)]
345struct BuildScratch {
346    marks: Vec<u32>,
347    epoch: u32,
348
349    visited_ids: Vec<u32>,
350    visited_dists: Vec<f32>,
351
352    frontier: OrderedBeam,
353    work: OrderedBeam,
354
355    seeds: Vec<usize>,
356    candidates: Vec<(u32, f32)>,
357}
358
359impl BuildScratch {
360    fn new(n: usize, beam_width: usize, max_degree: usize, extra_seeds: usize) -> Self {
361        Self {
362            marks: vec![0u32; n],
363            epoch: 1,
364            visited_ids: Vec::with_capacity(beam_width * 4),
365            visited_dists: Vec::with_capacity(beam_width * 4),
366            frontier: {
367                let mut b = OrderedBeam::default();
368                b.reserve(beam_width * 2);
369                b
370            },
371            work: {
372                let mut b = OrderedBeam::default();
373                b.reserve(beam_width * 2);
374                b
375            },
376            seeds: Vec::with_capacity(1 + extra_seeds),
377            candidates: Vec::with_capacity(beam_width * (4 + extra_seeds) + max_degree * 2),
378        }
379    }
380
381    #[inline]
382    fn reset_search(&mut self) {
383        self.epoch = self.epoch.wrapping_add(1);
384        if self.epoch == 0 {
385            self.marks.fill(0);
386            self.epoch = 1;
387        }
388        self.visited_ids.clear();
389        self.visited_dists.clear();
390        self.frontier.clear();
391        self.work.clear();
392    }
393
394    #[inline]
395    fn is_marked(&self, idx: usize) -> bool {
396        self.marks[idx] == self.epoch
397    }
398
399    #[inline]
400    fn mark_with_dist(&mut self, idx: usize, dist: f32) {
401        self.marks[idx] = self.epoch;
402        self.visited_ids.push(idx as u32);
403        self.visited_dists.push(dist);
404    }
405}
406
407#[derive(Debug)]
408struct IncrementalInsertScratch {
409    build: BuildScratch,
410}
411
412impl IncrementalInsertScratch {
413    fn new(n: usize, beam_width: usize, max_degree: usize, extra_seeds: usize) -> Self {
414        Self {
415            build: BuildScratch::new(n, beam_width, max_degree, extra_seeds),
416        }
417    }
418}
419
420/// Main struct representing a DiskANN index (generic over vector element `T` and distance `D`)
421pub struct DiskANN<T, D>
422where
423    T: bytemuck::Pod + Copy + Send + Sync + 'static,
424    D: Distance<T> + Send + Sync + Copy + Clone + 'static,
425{
426    /// Dimensionality of vectors in the index
427    pub dim: usize,
428    /// Number of vectors in the index
429    pub num_vectors: usize,
430    /// Maximum number of edges per node
431    pub max_degree: usize,
432    /// Informational: type name of the distance (from metadata)
433    pub distance_name: String,
434
435    /// ID of the medoid (used as entry point)
436    medoid_id: u32,
437    // Offsets
438    vectors_offset: u64,
439    adjacency_offset: u64,
440
441    /// Memory-mapped file
442    mmap: Option<Mmap>,
443
444    /// Dynamic-v2 storage when this index was opened or built for updates.
445    dynamic: Option<mmap_dynamic::MmapDynamicDiskANN<T, D>>,
446
447    /// The distance strategy
448    dist: D,
449
450    /// keep `T` in the type so the compiler knows about it
451    _phantom: PhantomData<T>,
452}
453
454// constructors
455
456impl<T, D> DiskANN<T, D>
457where
458    T: bytemuck::Pod + Copy + Send + Sync + 'static,
459    D: Distance<T> + Send + Sync + Copy + Clone + 'static,
460{
461    fn from_dynamic(dynamic: mmap_dynamic::MmapDynamicDiskANN<T, D>, dist: D) -> Self {
462        Self {
463            dim: dynamic.dim(),
464            num_vectors: dynamic.len(),
465            max_degree: dynamic.max_degree(),
466            distance_name: dynamic.distance_name().to_string(),
467            medoid_id: dynamic.medoid_id(),
468            vectors_offset: 0,
469            adjacency_offset: 0,
470            mmap: None,
471            dynamic: Some(dynamic),
472            dist,
473            _phantom: PhantomData,
474        }
475    }
476
477    /// Build with default parameters: (M=64, L=128, alpha=1.2, extra_seeds=1).
478    pub fn build_index_default(
479        vectors: &[Vec<T>],
480        dist: D,
481        file_path: &str,
482    ) -> Result<Self, DiskAnnError> {
483        Self::build_index(
484            vectors,
485            DISKANN_DEFAULT_MAX_DEGREE,
486            DISKANN_DEFAULT_BUILD_BEAM,
487            DISKANN_DEFAULT_ALPHA,
488            DISKANN_DEFAULT_EXTRA_SEEDS,
489            dist,
490            file_path,
491        )
492    }
493
494    /// Build with a `DiskAnnParams` bundle.
495    pub fn build_index_with_params(
496        vectors: &[Vec<T>],
497        dist: D,
498        file_path: &str,
499        p: DiskAnnParams,
500    ) -> Result<Self, DiskAnnError> {
501        Self::build_index(
502            vectors,
503            p.max_degree,
504            p.build_beam_width,
505            p.alpha,
506            p.extra_seeds,
507            dist,
508            file_path,
509        )
510    }
511
512    /// Opens an existing index file, supplying the distance strategy explicitly.
513    pub fn open_index_with(path: &str, dist: D) -> Result<Self, DiskAnnError> {
514        let mut file = OpenOptions::new().read(true).write(false).open(path)?;
515
516        // Read metadata length
517        let mut buf8 = [0u8; 8];
518        file.seek(SeekFrom::Start(0))?;
519        file.read_exact(&mut buf8)?;
520        let md_len = u64::from_le_bytes(buf8);
521
522        // Read metadata
523        let mut md_bytes = vec![0u8; md_len as usize];
524        file.read_exact(&mut md_bytes)?;
525        let metadata: Metadata = bincode::deserialize(&md_bytes)?;
526
527        let mmap = unsafe { memmap2::Mmap::map(&file)? };
528
529        // Validate element size vs T
530        let want = std::mem::size_of::<T>() as u8;
531        if metadata.elem_size != want {
532            return Err(DiskAnnError::IndexError(format!(
533                "element size mismatch: file has {}B, T is {}B",
534                metadata.elem_size, want
535            )));
536        }
537
538        // Optional sanity/logging: warn if type differs from recorded name
539        let expected = std::any::type_name::<D>();
540        if metadata.distance_name != expected {
541            eprintln!(
542                "Warning: index recorded distance `{}` but you opened with `{}`",
543                metadata.distance_name, expected
544            );
545        }
546
547        Ok(Self {
548            dim: metadata.dim,
549            num_vectors: metadata.num_vectors,
550            max_degree: metadata.max_degree,
551            distance_name: metadata.distance_name,
552            medoid_id: metadata.medoid_id,
553            vectors_offset: metadata.vectors_offset,
554            adjacency_offset: metadata.adjacency_offset,
555            mmap: Some(mmap),
556            dynamic: None,
557            dist,
558            _phantom: PhantomData,
559        })
560    }
561
562    /// Starts a transient update session from a static index.
563    /// Commit it with `commit_updates_to_static`; the work file is not a
564    /// persistent index format and is never accepted by `open_index_with`.
565    pub fn begin_updates(
566        self,
567        capacity: usize,
568        alpha: f32,
569        path: &str,
570    ) -> Result<Self, DiskAnnError> {
571        if self.dynamic.is_some() {
572            return Err(DiskAnnError::IndexError(
573                "source index is already dynamic".into(),
574            ));
575        }
576        let dist = self.dist;
577        let dynamic =
578            mmap_dynamic::MmapDynamicDiskANN::create_from_static(&self, capacity, alpha, path)?;
579        Ok(Self::from_dynamic(dynamic, dist))
580    }
581
582    /// True while this handle is a transient update session.
583    pub fn is_updating(&self) -> bool {
584        self.dynamic.is_some()
585    }
586
587    /// Number of addressable slots. Static-v1 capacity equals its vector count.
588    pub fn capacity(&self) -> usize {
589        self.dynamic
590            .as_ref()
591            .map_or(self.num_vectors, |dynamic| dynamic.capacity())
592    }
593
594    /// Inserts one vector during a transient update session.
595    pub fn insert(&mut self, vector: Vec<T>, beam: usize) -> Result<u32, DiskAnnError> {
596        let dynamic = self
597            .dynamic
598            .as_mut()
599            .ok_or_else(|| DiskAnnError::IndexError("begin_updates must be called first".into()))?;
600        let id = dynamic.insert(vector, beam)?;
601        self.num_vectors = dynamic.len();
602        Ok(id)
603    }
604
605    /// Inserts a batch during a transient update session.
606    pub fn insert_batch(
607        &mut self,
608        vectors: Vec<Vec<T>>,
609        beam: usize,
610    ) -> Result<Vec<u32>, DiskAnnError> {
611        let dynamic = self
612            .dynamic
613            .as_mut()
614            .ok_or_else(|| DiskAnnError::IndexError("begin_updates must be called first".into()))?;
615        let ids = dynamic.insert_batch(vectors, beam)?;
616        self.num_vectors = dynamic.len();
617        Ok(ids)
618    }
619
620    /// Deletes one node and repairs its neighborhood with MERIT.
621    pub fn delete(&mut self, id: u32) -> Result<Option<DeleteStats>, DiskAnnError> {
622        let mut stats = self.delete_batch(&[id])?;
623        Ok(stats.pop())
624    }
625
626    /// Deletes one node with explicitly configured MERIT repair parameters.
627    pub fn delete_with_params(
628        &mut self,
629        id: u32,
630        repair_beam: usize,
631        repair_degree: usize,
632    ) -> Result<Option<DeleteStats>, DiskAnnError> {
633        let mut stats = self.delete_batch_with_params(&[id], repair_beam, repair_degree)?;
634        Ok(stats.pop())
635    }
636
637    /// Deletes a batch with MERIT defaults: repair beam `2R` and `k_r = 2`.
638    pub fn delete_batch(&mut self, ids: &[u32]) -> Result<Vec<DeleteStats>, DiskAnnError> {
639        self.delete_batch_with_params(ids, 2 * self.max_degree, 2)
640    }
641
642    /// Deletes a batch with explicitly configured MERIT repair parameters.
643    pub fn delete_batch_with_params(
644        &mut self,
645        ids: &[u32],
646        repair_beam: usize,
647        repair_degree: usize,
648    ) -> Result<Vec<DeleteStats>, DiskAnnError> {
649        let dynamic = self
650            .dynamic
651            .as_mut()
652            .ok_or_else(|| DiskAnnError::IndexError("begin_updates must be called first".into()))?;
653        let stats = dynamic.delete_batch(ids, repair_beam, repair_degree);
654        self.num_vectors = dynamic.len();
655        Ok(stats)
656    }
657
658    /// Flushes pending update-workspace writes. Static handles are read-only.
659    pub fn flush(&self) -> Result<(), DiskAnnError> {
660        if let Some(dynamic) = &self.dynamic {
661            dynamic.flush()?;
662        }
663        Ok(())
664    }
665
666    /// Finishes an update session and commits it as an ordinary static index.
667    ///
668    /// Only live vectors and live, version-matching edges are written. IDs are
669    /// compacted to `0..num_vectors`; the returned tuple contains the ordinary
670    /// static search index and the required old-to-new ID mapping.
671    pub fn commit_updates_to_static(
672        self,
673        path: &str,
674    ) -> Result<(Self, Vec<Option<u32>>), DiskAnnError> {
675        let dynamic = self.dynamic.as_ref().ok_or_else(|| {
676            DiskAnnError::IndexError("commit requires a dynamic update session".into())
677        })?;
678        let (live, remap, medoid_id, id_map) = dynamic.static_layout();
679        let work_path = dynamic.work_path().to_path_buf();
680        if live.is_empty() {
681            return Err(DiskAnnError::IndexError(
682                "cannot commit an empty static index".into(),
683            ));
684        }
685        let temporary = format!("{path}.static-commit-{}", std::process::id());
686        let dist = self.dist;
687        let result = write_static_graph_streaming(
688            dynamic,
689            &live,
690            &remap,
691            self.max_degree,
692            medoid_id,
693            &self.distance_name,
694            &temporary,
695        );
696        drop(self);
697        result?;
698        std::fs::rename(&temporary, path)?;
699        if work_path != std::path::Path::new(path) {
700            let _ = std::fs::remove_file(work_path);
701        }
702        Ok((Self::open_index_with(path, dist)?, id_map))
703    }
704}
705
706fn write_static_graph_streaming<T, D>(
707    dynamic: &mmap_dynamic::MmapDynamicDiskANN<T, D>,
708    live: &[u32],
709    remap: &[u32],
710    max_degree: usize,
711    medoid_id: u32,
712    distance_name: &str,
713    path: &str,
714) -> Result<(), DiskAnnError>
715where
716    T: bytemuck::Pod + Copy + Send + Sync + 'static,
717    D: Distance<T> + Send + Sync + Copy + Clone + 'static,
718{
719    let dim = dynamic.dim();
720    let vectors_offset = 1024 * 1024u64;
721    let adjacency_offset = vectors_offset + (live.len() * dim * std::mem::size_of::<T>()) as u64;
722    let mut file = OpenOptions::new()
723        .create(true)
724        .truncate(true)
725        .read(true)
726        .write(true)
727        .open(path)?;
728    file.seek(SeekFrom::Start(vectors_offset))?;
729    for old_id in live {
730        file.write_all(bytemuck::cast_slice(dynamic.vector_slice(*old_id)))?;
731    }
732    file.seek(SeekFrom::Start(adjacency_offset))?;
733    let mut row = Vec::with_capacity(max_degree);
734    for old_id in live {
735        row.clear();
736        row.extend(
737            dynamic
738                .live_neighbors(*old_id)
739                .into_iter()
740                .map(|old| remap[old as usize])
741                .filter(|new| *new != PAD_U32),
742        );
743        row.resize(max_degree, PAD_U32);
744        file.write_all(bytemuck::cast_slice(&row))?;
745    }
746    let metadata = Metadata {
747        dim,
748        num_vectors: live.len(),
749        max_degree,
750        medoid_id,
751        vectors_offset,
752        adjacency_offset,
753        elem_size: std::mem::size_of::<T>() as u8,
754        distance_name: distance_name.to_owned(),
755    };
756    let bytes = bincode::serialize(&metadata)?;
757    file.seek(SeekFrom::Start(0))?;
758    file.write_all(&(bytes.len() as u64).to_le_bytes())?;
759    file.write_all(&bytes)?;
760    file.sync_all()?;
761    Ok(())
762}
763
764/// Extra sugar when your distance type implements `Default`.
765impl<T, D> DiskANN<T, D>
766where
767    T: bytemuck::Pod + Copy + Send + Sync + 'static,
768    D: Distance<T> + Default + Send + Sync + Copy + Clone + 'static,
769{
770    /// Build with default params **and** `D::default()` metric.
771    pub fn build_index_default_metric(
772        vectors: &[Vec<T>],
773        file_path: &str,
774    ) -> Result<Self, DiskAnnError> {
775        Self::build_index_default(vectors, D::default(), file_path)
776    }
777
778    /// Open an index using `D::default()` as the distance (matches what you built with).
779    pub fn open_index_default_metric(path: &str) -> Result<Self, DiskAnnError> {
780        Self::open_index_with(path, D::default())
781    }
782}
783
784impl<T, D> DiskANN<T, D>
785where
786    T: bytemuck::Pod + Copy + Send + Sync + 'static,
787    D: Distance<T> + Send + Sync + Copy + Clone + 'static,
788{
789    /// Builds a new index from provided vectors
790    ///
791    /// # Arguments
792    /// * `vectors` - The vectors to index (slice of Vec<T>)
793    /// * `max_degree` - Maximum edges per node (M ~ 24-64+)
794    /// * `build_beam_width` - Construction L (e.g., 128-400)
795    /// * `alpha` - Pruning parameter (1.2–2.0)
796    /// * `extra_seeds` - Extra random seeds per node (>=0)
797    /// * `dist` - Any `anndists::Distance<T>`
798    /// * `file_path` - Path of index file
799    pub fn build_index(
800        vectors: &[Vec<T>],
801        max_degree: usize,
802        build_beam_width: usize,
803        alpha: f32,
804        extra_seeds: usize,
805        dist: D,
806        file_path: &str,
807    ) -> Result<Self, DiskAnnError> {
808        let flat = FlatVectors::from_vecs(vectors)?;
809
810        let num_vectors = flat.n;
811        let dim = flat.dim;
812
813        let mut file = OpenOptions::new()
814            .create(true)
815            .write(true)
816            .read(true)
817            .truncate(true)
818            .open(file_path)?;
819
820        // Reserve space for metadata (we'll write it after data)
821        let vectors_offset = 1024 * 1024;
822        assert_eq!(
823            (vectors_offset as usize) % std::mem::align_of::<T>(),
824            0,
825            "vectors_offset must be aligned for T"
826        );
827
828        let elem_sz = std::mem::size_of::<T>() as u64;
829        let total_vector_bytes = (num_vectors as u64) * (dim as u64) * elem_sz;
830
831        // Write vectors contiguous
832        file.seek(SeekFrom::Start(vectors_offset as u64))?;
833        file.write_all(bytemuck::cast_slice::<T, u8>(&flat.data))?;
834
835        // Compute medoid using flat storage
836        let medoid_id = calculate_medoid(&flat, dist);
837
838        // Build graph
839        let adjacency_offset = vectors_offset as u64 + total_vector_bytes;
840        let graph = build_vamana_graph(
841            &flat,
842            max_degree,
843            build_beam_width,
844            alpha,
845            extra_seeds,
846            dist,
847            medoid_id as u32,
848        );
849
850        // Write adjacency lists
851        file.seek(SeekFrom::Start(adjacency_offset))?;
852        for neighbors in &graph {
853            let mut padded = neighbors.clone();
854            padded.resize(max_degree, PAD_U32);
855            let bytes = bytemuck::cast_slice::<u32, u8>(&padded);
856            file.write_all(bytes)?;
857        }
858
859        // Write metadata
860        let metadata = Metadata {
861            dim,
862            num_vectors,
863            max_degree,
864            medoid_id: medoid_id as u32,
865            vectors_offset: vectors_offset as u64,
866            adjacency_offset,
867            elem_size: std::mem::size_of::<T>() as u8,
868            distance_name: std::any::type_name::<D>().to_string(),
869        };
870
871        let md_bytes = bincode::serialize(&metadata)?;
872        file.seek(SeekFrom::Start(0))?;
873        let md_len = md_bytes.len() as u64;
874        file.write_all(&md_len.to_le_bytes())?;
875        file.write_all(&md_bytes)?;
876        file.sync_all()?;
877
878        // Memory map the file
879        let mmap = unsafe { memmap2::Mmap::map(&file)? };
880
881        Ok(Self {
882            dim,
883            num_vectors,
884            max_degree,
885            distance_name: metadata.distance_name,
886            medoid_id: metadata.medoid_id,
887            vectors_offset: metadata.vectors_offset,
888            adjacency_offset: metadata.adjacency_offset,
889            mmap: Some(mmap),
890            dynamic: None,
891            dist,
892            _phantom: PhantomData,
893        })
894    }
895
896    /// Searches the index for nearest neighbors using a best-first beam search.
897    /// Termination rule: continue while the best frontier can still improve the worst in working set.
898    pub fn search_with_dists(&self, query: &[T], k: usize, beam_width: usize) -> Vec<(u32, f32)> {
899        if let Some(dynamic) = &self.dynamic {
900            return dynamic.search_with_dists(query, k, beam_width);
901        }
902        assert_eq!(
903            query.len(),
904            self.dim,
905            "Query dim {} != index dim {}",
906            query.len(),
907            self.dim
908        );
909
910        let mut results = graph_search(
911            self.medoid_id,
912            beam_width,
913            |id| self.distance_to(query, id as usize),
914            |id| {
915                self.get_neighbors(id)
916                    .iter()
917                    .copied()
918                    .filter(|neighbor| *neighbor != PAD_U32)
919                    .collect()
920            },
921        );
922        results.truncate(k);
923        results.into_iter().map(|c| (c.id, c.dist)).collect()
924    }
925
926    /// search but only return neighbor ids
927    pub fn search(&self, query: &[T], k: usize, beam_width: usize) -> Vec<u32> {
928        self.search_with_dists(query, k, beam_width)
929            .into_iter()
930            .map(|(id, _dist)| id)
931            .collect()
932    }
933
934    /// Gets the neighbors of a node from the (fixed-degree) adjacency region
935    fn get_neighbors(&self, node_id: u32) -> &[u32] {
936        let offset = self.adjacency_offset + (node_id as u64 * self.max_degree as u64 * 4);
937        let start = offset as usize;
938        let end = start + (self.max_degree * 4);
939        let bytes = &self.mmap.as_ref().expect("static mmap missing")[start..end];
940        bytemuck::cast_slice(bytes)
941    }
942
943    /// Computes distance between `query` and vector `idx`
944    fn distance_to(&self, query: &[T], idx: usize) -> f32 {
945        let elem_sz = std::mem::size_of::<T>();
946        let offset = self.vectors_offset + (idx as u64 * self.dim as u64 * elem_sz as u64);
947        let start = offset as usize;
948        let end = start + (self.dim * elem_sz);
949        let bytes = &self.mmap.as_ref().expect("static mmap missing")[start..end];
950        let vector: &[T] = bytemuck::cast_slice(bytes);
951        self.dist.eval(query, vector)
952    }
953
954    /// Gets a vector from the index
955    pub fn get_vector(&self, idx: usize) -> Vec<T> {
956        if let Some(dynamic) = &self.dynamic {
957            return dynamic.get_vector(idx);
958        }
959        let elem_sz = std::mem::size_of::<T>();
960        let offset = self.vectors_offset + (idx as u64 * self.dim as u64 * elem_sz as u64);
961        let start = offset as usize;
962        let end = start + (self.dim * elem_sz);
963        let bytes = &self.mmap.as_ref().expect("static mmap missing")[start..end];
964        let vector: &[T] = bytemuck::cast_slice(bytes);
965        vector.to_vec()
966    }
967}
968
969/// Calculates the medoid using flat contiguous storage.
970fn calculate_medoid<T, D>(vectors: &FlatVectors<T>, dist: D) -> usize
971where
972    T: bytemuck::Pod + Copy + Send + Sync,
973    D: Distance<T> + Copy + Sync,
974{
975    let n = vectors.n;
976    let k = 8.min(n);
977    let mut rng = thread_rng();
978    let pivots: Vec<usize> = (0..k).map(|_| rng.gen_range(0..n)).collect();
979
980    let (best_idx, _best_score) = (0..n)
981        .into_par_iter()
982        .map(|i| {
983            let vi = vectors.row(i);
984            let score: f32 = pivots.iter().map(|&p| dist.eval(vi, vectors.row(p))).sum();
985            (i, score)
986        })
987        .reduce(|| (0usize, f32::MAX), |a, b| if a.1 <= b.1 { a } else { b });
988
989    best_idx
990}
991
992fn dedup_keep_best_by_id_in_place(cands: &mut Vec<(u32, f32)>) {
993    if cands.is_empty() {
994        return;
995    }
996
997    cands.sort_by(|a, b| a.0.cmp(&b.0).then_with(|| a.1.total_cmp(&b.1)));
998
999    let mut write = 0usize;
1000    for read in 0..cands.len() {
1001        if write == 0 || cands[read].0 != cands[write - 1].0 {
1002            cands[write] = cands[read];
1003            write += 1;
1004        }
1005    }
1006    cands.truncate(write);
1007}
1008
1009/// Merge one micro-batch of newly computed outgoing neighbor lists back into the graph.
1010/// Mark all nodes in the chunk as affected.
1011/// Count reverse-edge insertions implied by the chunk.
1012/// Build a CSR-style flat incoming buffer.
1013/// Commit chunk outgoing lists.
1014/// Re-prune only the affected nodes.
1015fn merge_chunk_updates_into_graph_reuse<T, D>(
1016    graph: &mut [Vec<u32>],
1017    chunk_nodes: &[usize],
1018    chunk_pruned: &[Vec<u32>],
1019    vectors: &FlatVectors<T>,
1020    max_degree: usize,
1021    slack_limit: usize,
1022    alpha: f32,
1023    dist: D,
1024    merge: &mut MergeScratch,
1025) where
1026    T: bytemuck::Pod + Copy + Send + Sync,
1027    D: Distance<T> + Copy + Sync,
1028{
1029    merge.reset();
1030
1031    // Mark chunk nodes as affected.
1032    for &u in chunk_nodes {
1033        merge.mark_affected(u);
1034    }
1035
1036    // Count reverse-edge insertions and mark touched destinations.
1037    let mut total_incoming = 0usize;
1038
1039    for (local_idx, &u) in chunk_nodes.iter().enumerate() {
1040        for &dst in &chunk_pruned[local_idx] {
1041            let dst_usize = dst as usize;
1042            if dst_usize == u {
1043                continue;
1044            }
1045
1046            merge.mark_affected(dst_usize);
1047            merge.incoming_counts[dst_usize] += 1;
1048            total_incoming += 1;
1049        }
1050    }
1051
1052    // Build CSR offsets only for affected nodes.
1053    merge.affected_nodes.sort_unstable();
1054
1055    let mut running = 0usize;
1056    for &u in &merge.affected_nodes {
1057        merge.incoming_offsets[u] = running;
1058        running += merge.incoming_counts[u];
1059        merge.incoming_offsets[u + 1] = running;
1060    }
1061
1062    merge.incoming_flat.resize(total_incoming, PAD_U32);
1063
1064    // Initialize write cursors.
1065    for &u in &merge.affected_nodes {
1066        merge.incoming_write[u] = merge.incoming_offsets[u];
1067    }
1068
1069    // Fill CSR incoming buffer.
1070    for (local_idx, &u) in chunk_nodes.iter().enumerate() {
1071        for &dst in &chunk_pruned[local_idx] {
1072            let dst_usize = dst as usize;
1073            if dst_usize == u {
1074                continue;
1075            }
1076
1077            let pos = merge.incoming_write[dst_usize];
1078            merge.incoming_flat[pos] = u as u32;
1079            merge.incoming_write[dst_usize] += 1;
1080        }
1081    }
1082
1083    // Commit chunk outgoing lists first.
1084    for (local_idx, &u) in chunk_nodes.iter().enumerate() {
1085        graph[u] = chunk_pruned[local_idx].clone();
1086    }
1087
1088    // Hybrid slack-aware microbatch merge:
1089    // keep merged lists under slack, reprune only overflowed ones.
1090    let affected = merge.affected_nodes.clone();
1091
1092    let updated_pairs: Vec<(usize, Vec<u32>)> = affected
1093        .into_par_iter()
1094        .map(|u| {
1095            let start = merge.incoming_offsets[u];
1096            let end = merge.incoming_offsets[u + 1];
1097
1098            let mut ids: Vec<u32> = Vec::with_capacity(graph[u].len() + (end - start));
1099
1100            // Current adjacency after chunk commit.
1101            ids.extend_from_slice(&graph[u]);
1102
1103            // Reverse insertions from this chunk.
1104            if start < end {
1105                ids.extend_from_slice(&merge.incoming_flat[start..end]);
1106            }
1107
1108            // Remove self-loops / padding.
1109            ids.retain(|&id| id != PAD_U32 && id as usize != u);
1110
1111            // Deduplicate.
1112            ids.sort_unstable();
1113            ids.dedup();
1114
1115            if ids.is_empty() {
1116                return (u, Vec::new());
1117            }
1118
1119            // Under slack: keep as-is.
1120            if ids.len() <= slack_limit {
1121                return (u, ids);
1122            }
1123
1124            // Overflow: score and prune back to max_degree.
1125            let mut pool = Vec::<(u32, f32)>::with_capacity(ids.len());
1126            for id in ids {
1127                let d = dist.eval(vectors.row(u), vectors.row(id as usize));
1128                pool.push((id, d));
1129            }
1130
1131            let pruned = prune_neighbors(u, &pool, vectors, max_degree, alpha, dist);
1132            (u, pruned)
1133        })
1134        .collect();
1135
1136    for (u, neigh) in updated_pairs {
1137        graph[u] = neigh;
1138    }
1139
1140    // Cleanup touched metadata.
1141    for &u in &merge.affected_nodes {
1142        merge.incoming_counts[u] = 0;
1143        merge.incoming_offsets[u + 1] = 0;
1144    }
1145}
1146
1147/// Reusable scratch buffers for micro-batch merge.
1148/// This avoids rebuilding `Vec<Vec<u32>>` for incoming reverse edges on every chunk.
1149/// Instead, incoming reverse edges are accumulated into a CSR-like flat buffer.
1150///
1151/// Layout:
1152/// - incoming_counts[u] = number of reverse edges targeting node u in this chunk
1153/// - incoming_offsets[u]..incoming_offsets[u+1] is u's segment in incoming_flat
1154/// - affected_nodes stores exactly the nodes touched in this chunk, so we do not
1155///   scan all `n` nodes during merge.
1156#[derive(Debug)]
1157struct MergeScratch {
1158    incoming_counts: Vec<usize>,
1159    incoming_offsets: Vec<usize>,
1160    incoming_write: Vec<usize>,
1161    incoming_flat: Vec<u32>,
1162
1163    affected_marks: Vec<u32>,
1164    affected_epoch: u32,
1165    affected_nodes: Vec<usize>,
1166}
1167
1168impl MergeScratch {
1169    fn new(n: usize) -> Self {
1170        Self {
1171            incoming_counts: vec![0usize; n],
1172            incoming_offsets: vec![0usize; n + 1],
1173            incoming_write: vec![0usize; n],
1174            incoming_flat: Vec::new(),
1175            affected_marks: vec![0u32; n],
1176            affected_epoch: 1,
1177            affected_nodes: Vec::new(),
1178        }
1179    }
1180
1181    #[inline]
1182    fn reset(&mut self) {
1183        self.affected_epoch = self.affected_epoch.wrapping_add(1);
1184        if self.affected_epoch == 0 {
1185            self.affected_marks.fill(0);
1186            self.affected_epoch = 1;
1187        }
1188        self.affected_nodes.clear();
1189        self.incoming_flat.clear();
1190    }
1191
1192    #[inline]
1193    fn mark_affected(&mut self, u: usize) {
1194        if self.affected_marks[u] != self.affected_epoch {
1195            self.affected_marks[u] = self.affected_epoch;
1196            self.affected_nodes.push(u);
1197            self.incoming_counts[u] = 0;
1198        }
1199    }
1200}
1201
1202/// Build a Vamana-like graph using a micro-batched practical DiskANN strategy,
1203/// with reusable scratch both for per-thread search state and for chunk merge state.
1204fn build_vamana_graph<T, D>(
1205    vectors: &FlatVectors<T>,
1206    max_degree: usize,
1207    build_beam_width: usize,
1208    alpha: f32,
1209    extra_seeds: usize,
1210    dist: D,
1211    medoid_id: u32,
1212) -> Vec<Vec<u32>>
1213where
1214    T: bytemuck::Pod + Copy + Send + Sync,
1215    D: Distance<T> + Copy + Sync,
1216{
1217    let n = vectors.n;
1218    let mut graph = vec![Vec::<u32>::new(); n];
1219    // Bootstrap with a random R-out directed graph.
1220    {
1221        let mut rng = thread_rng();
1222        let target = max_degree.min(n.saturating_sub(1));
1223
1224        for i in 0..n {
1225            let mut s = HashSet::with_capacity(target);
1226            while s.len() < target {
1227                let nb = rng.gen_range(0..n);
1228                if nb != i {
1229                    s.insert(nb as u32);
1230                }
1231            }
1232            graph[i] = s.into_iter().collect();
1233        }
1234    }
1235
1236    let mut rng = thread_rng();
1237    let slack_limit = ((GRAPH_SLACK_FACTOR * max_degree as f32).ceil() as usize).max(max_degree);
1238
1239    // Reused across all chunks in the single Vamana construction pass.
1240    let mut merge_scratch = MergeScratch::new(n);
1241
1242    let mut order: Vec<usize> = (0..n).collect();
1243    order.shuffle(&mut rng);
1244
1245    for chunk in order.chunks(MICRO_BATCH_CHUNK_SIZE) {
1246        let snapshot = &graph;
1247        // Compute new outgoing lists for this chunk in parallel.
1248        let chunk_results: Vec<(usize, Vec<u32>)> = chunk
1249            .par_iter()
1250            .map_init(
1251                || IncrementalInsertScratch::new(n, build_beam_width, max_degree, extra_seeds),
1252                |scratch, &u| {
1253                    let bs = &mut scratch.build;
1254                    bs.candidates.clear();
1255
1256                    // Start from current adjacency.
1257                    for &nb in &snapshot[u] {
1258                        let d = dist.eval(vectors.row(u), vectors.row(nb as usize));
1259                        bs.candidates.push((nb, d));
1260                    }
1261
1262                    // Seed list: medoid + distinct random starts.
1263                    bs.seeds.clear();
1264                    bs.seeds.push(medoid_id as usize);
1265
1266                    let mut local_rng = thread_rng();
1267                    while bs.seeds.len() < 1 + extra_seeds {
1268                        let s = local_rng.gen_range(0..n);
1269                        if !bs.seeds.contains(&s) {
1270                            bs.seeds.push(s);
1271                        }
1272                    }
1273
1274                    let seeds_len = bs.seeds.len();
1275                    for si in 0..seeds_len {
1276                        let start = bs.seeds[si];
1277
1278                        greedy_search_visited_collect(
1279                            vectors.row(u),
1280                            vectors,
1281                            snapshot,
1282                            start,
1283                            build_beam_width,
1284                            dist,
1285                            bs,
1286                        );
1287
1288                        for i in 0..bs.visited_ids.len() {
1289                            bs.candidates.push((bs.visited_ids[i], bs.visited_dists[i]));
1290                        }
1291                    }
1292
1293                    dedup_keep_best_by_id_in_place(&mut bs.candidates);
1294
1295                    let pruned =
1296                        prune_neighbors(u, &bs.candidates, vectors, max_degree, alpha, dist);
1297
1298                    (u, pruned)
1299                },
1300            )
1301            .collect();
1302
1303        let mut chunk_nodes = Vec::<usize>::with_capacity(chunk_results.len());
1304        let mut chunk_pruned = Vec::<Vec<u32>>::with_capacity(chunk_results.len());
1305
1306        for (u, pruned) in chunk_results {
1307            chunk_nodes.push(u);
1308            chunk_pruned.push(pruned);
1309        }
1310        // Merge chunk back into graph using reusable CSR-style scratch.
1311        merge_chunk_updates_into_graph_reuse(
1312            &mut graph,
1313            &chunk_nodes,
1314            &chunk_pruned,
1315            vectors,
1316            max_degree,
1317            slack_limit,
1318            alpha,
1319            dist,
1320            &mut merge_scratch,
1321        );
1322    }
1323
1324    // Final cleanup: enforce bounded degree and deduplication.
1325    graph
1326        .into_par_iter()
1327        .enumerate()
1328        .map(|(u, neigh)| {
1329            if neigh.len() <= max_degree {
1330                return neigh;
1331            }
1332
1333            let mut ids = neigh;
1334            ids.sort_unstable();
1335            ids.dedup();
1336
1337            let pool: Vec<(u32, f32)> = ids
1338                .into_iter()
1339                .filter(|&id| id as usize != u)
1340                .map(|id| (id, dist.eval(vectors.row(u), vectors.row(id as usize))))
1341                .collect();
1342
1343            prune_neighbors(u, &pool, vectors, max_degree, alpha, dist)
1344        })
1345        .collect()
1346}
1347
1348/// Build-time greedy search:
1349/// - dense visited marks instead of HashMap/HashSet
1350/// - visited_ids + visited_dists instead of recomputing distances later
1351/// - ordered beams instead of BinaryHeap
1352/// Output is written into `scratch.visited_ids` and `scratch.visited_dists`.
1353fn greedy_search_visited_collect<T, D>(
1354    query: &[T],
1355    vectors: &FlatVectors<T>,
1356    graph: &[Vec<u32>],
1357    start_id: usize,
1358    beam_width: usize,
1359    dist: D,
1360    scratch: &mut BuildScratch,
1361) where
1362    T: bytemuck::Pod + Copy + Send + Sync,
1363    D: Distance<T> + Copy,
1364{
1365    scratch.reset_search();
1366
1367    let start_dist = dist.eval(query, vectors.row(start_id));
1368    let start = Candidate {
1369        dist: start_dist,
1370        id: start_id as u32,
1371    };
1372
1373    scratch.frontier.insert_unbounded(start);
1374    scratch.work.insert_capped(start, beam_width);
1375    scratch.mark_with_dist(start_id, start_dist);
1376
1377    while !scratch.frontier.is_empty() {
1378        let best = scratch.frontier.best().unwrap();
1379        if scratch.work.len() >= beam_width {
1380            if let Some(worst) = scratch.work.worst() {
1381                if best.dist >= worst.dist {
1382                    break;
1383                }
1384            }
1385        }
1386
1387        let cur = scratch.frontier.pop_best().unwrap();
1388
1389        for &nb in &graph[cur.id as usize] {
1390            let nb_usize = nb as usize;
1391            if scratch.is_marked(nb_usize) {
1392                continue;
1393            }
1394
1395            let d = dist.eval(query, vectors.row(nb_usize));
1396            scratch.mark_with_dist(nb_usize, d);
1397
1398            let cand = Candidate { dist: d, id: nb };
1399
1400            if scratch.work.len() < beam_width {
1401                scratch.work.insert_unbounded(cand);
1402                scratch.frontier.insert_unbounded(cand);
1403            } else if let Some(worst) = scratch.work.worst() {
1404                if d < worst.dist {
1405                    scratch.work.insert_capped(cand, beam_width);
1406                    scratch.frontier.insert_unbounded(cand);
1407                }
1408            }
1409        }
1410    }
1411}
1412
1413/// Vamana RobustPrune with progressive alpha relaxation.
1414fn prune_neighbors<T, D>(
1415    node_id: usize,
1416    candidates: &[(u32, f32)],
1417    vectors: &FlatVectors<T>,
1418    max_degree: usize,
1419    alpha: f32,
1420    dist: D,
1421) -> Vec<u32>
1422where
1423    T: bytemuck::Pod + Copy + Send + Sync,
1424    D: Distance<T> + Copy,
1425{
1426    if candidates.is_empty() || max_degree == 0 {
1427        return Vec::new();
1428    }
1429
1430    // Sort by distance from node_id, nearest first.
1431    let mut sorted = candidates.to_vec();
1432    sorted.sort_by(|a, b| a.1.total_cmp(&b.1));
1433    sorted.truncate(MAX_OCCLUSION_SIZE);
1434
1435    // Remove self and duplicate ids while keeping the nearest occurrence.
1436    let mut uniq = Vec::<(u32, f32)>::with_capacity(sorted.len());
1437    let mut seen = HashSet::with_capacity(sorted.len());
1438    for &(cand_id, cand_dist) in &sorted {
1439        if cand_id as usize == node_id || !seen.insert(cand_id) {
1440            continue;
1441        }
1442        uniq.push((cand_id, cand_dist));
1443    }
1444
1445    if uniq.is_empty() {
1446        return Vec::new();
1447    }
1448
1449    let mut pruned = Vec::<u32>::with_capacity(max_degree);
1450    let mut occlude_factors = vec![0.0f32; uniq.len()];
1451    let target_alpha = alpha.max(1.0);
1452    let increment = target_alpha.min(1.2);
1453    let mut current_alpha = 1.0f32;
1454
1455    loop {
1456        for i in 0..uniq.len() {
1457            if pruned.len() >= max_degree {
1458                return pruned;
1459            }
1460            if occlude_factors[i] > current_alpha {
1461                continue;
1462            }
1463
1464            let (selected_id, _) = uniq[i];
1465            occlude_factors[i] = f32::MAX;
1466            pruned.push(selected_id);
1467
1468            for j in (i + 1)..uniq.len() {
1469                if occlude_factors[j] > target_alpha {
1470                    continue;
1471                }
1472
1473                let (candidate_id, candidate_dist) = uniq[j];
1474                let pair_dist = dist.eval(
1475                    vectors.row(candidate_id as usize),
1476                    vectors.row(selected_id as usize),
1477                );
1478                let factor = if pair_dist == 0.0 {
1479                    f32::MAX
1480                } else {
1481                    candidate_dist / pair_dist
1482                };
1483                occlude_factors[j] = occlude_factors[j].max(factor);
1484            }
1485        }
1486
1487        if current_alpha >= target_alpha {
1488            break;
1489        }
1490        current_alpha = (current_alpha * increment).min(target_alpha);
1491    }
1492
1493    pruned
1494}
1495
1496#[cfg(test)]
1497mod tests {
1498    use super::*;
1499    use anndists::dist::{DistCosine, DistJaccard, DistL1, DistL2};
1500    use rand::{Rng, SeedableRng, rngs::StdRng};
1501    use std::{fs, time::Instant};
1502
1503    fn euclid(a: &[f32], b: &[f32]) -> f32 {
1504        a.iter()
1505            .zip(b)
1506            .map(|(x, y)| (x - y) * (x - y))
1507            .sum::<f32>()
1508            .sqrt()
1509    }
1510
1511    fn exact_recall<T, D>(
1512        index: &DiskANN<T, D>,
1513        vectors: &[Vec<T>],
1514        queries: &[Vec<T>],
1515        dist: D,
1516        k: usize,
1517        beam: usize,
1518    ) -> f32
1519    where
1520        T: bytemuck::Pod + Copy + Send + Sync + 'static,
1521        D: Distance<T> + Send + Sync + Copy + Clone + 'static,
1522    {
1523        let mut hits = 0usize;
1524        for query in queries {
1525            let mut truth: Vec<(usize, f32)> = vectors
1526                .iter()
1527                .enumerate()
1528                .map(|(id, vector)| (id, dist.eval(query, vector)))
1529                .collect();
1530            truth.sort_by(|a, b| a.1.total_cmp(&b.1));
1531            let truth: HashSet<u32> = truth.into_iter().take(k).map(|(id, _)| id as u32).collect();
1532
1533            hits += index
1534                .search(query, k, beam)
1535                .into_iter()
1536                .filter(|id| truth.contains(id))
1537                .count();
1538        }
1539        hits as f32 / (queries.len() * k) as f32
1540    }
1541
1542    fn exact_recall_mapped<T, D>(
1543        index: &DiskANN<T, D>,
1544        internal_to_original: &[u32],
1545        vectors: &[Vec<T>],
1546        active: &[bool],
1547        queries: &[Vec<T>],
1548        dist: D,
1549    ) -> f32
1550    where
1551        T: bytemuck::Pod + Copy + Send + Sync + 'static,
1552        D: Distance<T> + Send + Sync + Copy + Clone + 'static,
1553    {
1554        let mut hits = 0usize;
1555        for query in queries {
1556            let mut truth = vectors
1557                .iter()
1558                .enumerate()
1559                .filter(|(id, _)| active[*id])
1560                .map(|(id, vector)| (id as u32, dist.eval(query, vector)))
1561                .collect::<Vec<_>>();
1562            truth.sort_by(|a, b| a.1.total_cmp(&b.1));
1563            let truth = truth
1564                .into_iter()
1565                .take(10)
1566                .map(|item| item.0)
1567                .collect::<HashSet<_>>();
1568            hits += index
1569                .search(query, 10, 256)
1570                .into_iter()
1571                .filter(|id| truth.contains(&internal_to_original[*id as usize]))
1572                .count();
1573        }
1574        hits as f32 / (queries.len() * 10) as f32
1575    }
1576
1577    fn merit_clustered_delete<T, D>(
1578        vectors: &[Vec<T>],
1579        queries: &[Vec<T>],
1580        dist: D,
1581        tag: &str,
1582    ) -> (f32, f32, f64, f64)
1583    where
1584        T: bytemuck::Pod + Copy + Send + Sync + 'static,
1585        D: Distance<T> + Send + Sync + Copy + Clone + 'static,
1586    {
1587        let static_path = format!("test_{tag}_static.db");
1588        let work_path = format!("test_{tag}.work");
1589        let rebuilt_path = format!("test_{tag}_rebuilt.db");
1590        for path in [&static_path, &work_path, &rebuilt_path] {
1591            let _ = fs::remove_file(path);
1592        }
1593        let mut active = vec![true; vectors.len()];
1594        let deleted = (0..vectors.len())
1595            .step_by(100)
1596            .map(|id| id as u32)
1597            .collect::<Vec<_>>();
1598        for id in &deleted {
1599            active[*id as usize] = false;
1600        }
1601
1602        let initial =
1603            DiskANN::build_index_with_params(vectors, dist, &static_path, quality_params())
1604                .unwrap();
1605        let started = Instant::now();
1606        let mut update = initial
1607            .begin_updates(vectors.len(), 1.2, &work_path)
1608            .unwrap();
1609        update.delete_batch(&deleted).unwrap();
1610        let (committed, old_to_new) = update.commit_updates_to_static(&static_path).unwrap();
1611        let update_seconds = started.elapsed().as_secs_f64();
1612        let mut committed_map = vec![u32::MAX; committed.num_vectors];
1613        for (old, new) in old_to_new.into_iter().enumerate() {
1614            if let Some(new) = new {
1615                committed_map[new as usize] = old as u32;
1616            }
1617        }
1618
1619        let surviving_ids = active
1620            .iter()
1621            .enumerate()
1622            .filter_map(|(id, live)| live.then_some(id as u32))
1623            .collect::<Vec<_>>();
1624        let surviving = surviving_ids
1625            .iter()
1626            .map(|id| vectors[*id as usize].clone())
1627            .collect::<Vec<_>>();
1628        let started = Instant::now();
1629        let rebuilt =
1630            DiskANN::build_index_with_params(&surviving, dist, &rebuilt_path, quality_params())
1631                .unwrap();
1632        let rebuild_seconds = started.elapsed().as_secs_f64();
1633        let committed_recall =
1634            exact_recall_mapped(&committed, &committed_map, vectors, &active, queries, dist);
1635        let rebuilt_recall =
1636            exact_recall_mapped(&rebuilt, &surviving_ids, vectors, &active, queries, dist);
1637        drop(committed);
1638        drop(rebuilt);
1639        for path in [&static_path, &work_path, &rebuilt_path] {
1640            let _ = fs::remove_file(path);
1641        }
1642        (
1643            committed_recall,
1644            rebuilt_recall,
1645            update_seconds,
1646            rebuild_seconds,
1647        )
1648    }
1649
1650    fn quality_params() -> DiskAnnParams {
1651        DiskAnnParams {
1652            max_degree: 32,
1653            build_beam_width: 128,
1654            alpha: 1.2,
1655            extra_seeds: 1,
1656        }
1657    }
1658
1659    #[test]
1660    fn test_small_index_l2() {
1661        let path = "test_small_l2.db";
1662        let _ = fs::remove_file(path);
1663
1664        let vectors = vec![
1665            vec![0.0, 0.0],
1666            vec![1.0, 0.0],
1667            vec![0.0, 1.0],
1668            vec![1.0, 1.0],
1669            vec![0.5, 0.5],
1670        ];
1671
1672        let index = DiskANN::<f32, DistL2>::build_index_default(&vectors, DistL2, path).unwrap();
1673
1674        let q = vec![0.1, 0.1];
1675        let nns = index.search(&q, 3, 8);
1676        assert_eq!(nns.len(), 3);
1677
1678        let v = index.get_vector(nns[0] as usize);
1679        assert!(euclid(&q, &v) < 1.0);
1680
1681        let _ = fs::remove_file(path);
1682    }
1683
1684    #[test]
1685    fn update_session_commits_as_ordinary_static_index() {
1686        let static_path = "test_update_commit_static.db";
1687        let work_path = "test_update_commit_work.db";
1688        let _ = fs::remove_file(static_path);
1689        let _ = fs::remove_file(work_path);
1690        let vectors = (0..200)
1691            .map(|id| vec![id as f32, (id % 11) as f32])
1692            .collect::<Vec<_>>();
1693        let static_index = DiskANN::build_index_default(&vectors, DistL2, static_path).unwrap();
1694        let mut update = static_index.begin_updates(220, 1.2, work_path).unwrap();
1695        assert!(update.is_updating());
1696        assert!(update.delete(40).unwrap().is_some());
1697        let replacement = vec![40.25, 7.0];
1698        update.insert(replacement.clone(), 128).unwrap();
1699        let (committed, id_map) = update.commit_updates_to_static(static_path).unwrap();
1700        assert_eq!(id_map.len(), 220);
1701        assert!(!committed.is_updating());
1702        assert_eq!(committed.num_vectors, 200);
1703        assert_eq!(committed.search(&replacement, 1, 128).len(), 1);
1704        drop(committed);
1705
1706        let reopened = DiskANN::<f32, DistL2>::open_index_with(static_path, DistL2).unwrap();
1707        assert!(!reopened.is_updating());
1708        assert_eq!(reopened.num_vectors, 200);
1709        assert_eq!(reopened.search(&replacement, 1, 128).len(), 1);
1710        let _ = fs::remove_file(static_path);
1711        let _ = fs::remove_file(work_path);
1712    }
1713
1714    #[test]
1715    fn test_cosine() {
1716        let path = "test_cosine.db";
1717        let _ = fs::remove_file(path);
1718
1719        let vectors = vec![
1720            vec![1.0, 0.0, 0.0],
1721            vec![0.0, 1.0, 0.0],
1722            vec![0.0, 0.0, 1.0],
1723            vec![1.0, 1.0, 0.0],
1724            vec![1.0, 0.0, 1.0],
1725        ];
1726
1727        let index =
1728            DiskANN::<f32, DistCosine>::build_index_default(&vectors, DistCosine, path).unwrap();
1729
1730        let q = vec![2.0, 0.0, 0.0];
1731        let nns = index.search(&q, 2, 8);
1732        assert_eq!(nns.len(), 2);
1733
1734        let v = index.get_vector(nns[0] as usize);
1735        let dot = v.iter().zip(&q).map(|(a, b)| a * b).sum::<f32>();
1736        let n1 = v.iter().map(|x| x * x).sum::<f32>().sqrt();
1737        let n2 = q.iter().map(|x| x * x).sum::<f32>().sqrt();
1738        let cos = dot / (n1 * n2);
1739        assert!(cos > 0.7);
1740
1741        let _ = fs::remove_file(path);
1742    }
1743
1744    #[test]
1745    fn test_persistence_and_open() {
1746        let path = "test_persist.db";
1747        let _ = fs::remove_file(path);
1748
1749        let vectors = vec![
1750            vec![0.0, 0.0],
1751            vec![1.0, 0.0],
1752            vec![0.0, 1.0],
1753            vec![1.0, 1.0],
1754        ];
1755
1756        {
1757            let _idx = DiskANN::<f32, DistL2>::build_index_default(&vectors, DistL2, path).unwrap();
1758        }
1759
1760        let idx2 = DiskANN::<f32, DistL2>::open_index_default_metric(path).unwrap();
1761        assert_eq!(idx2.num_vectors, 4);
1762        assert_eq!(idx2.dim, 2);
1763
1764        let q = vec![0.9, 0.9];
1765        let res = idx2.search(&q, 2, 8);
1766        assert_eq!(res[0], 3);
1767
1768        let _ = fs::remove_file(path);
1769    }
1770
1771    #[test]
1772    fn test_grid_connectivity() {
1773        let path = "test_grid.db";
1774        let _ = fs::remove_file(path);
1775
1776        let mut vectors = Vec::new();
1777        for i in 0..5 {
1778            for j in 0..5 {
1779                vectors.push(vec![i as f32, j as f32]);
1780            }
1781        }
1782
1783        let index = DiskANN::<f32, DistL2>::build_index_with_params(
1784            &vectors,
1785            DistL2,
1786            path,
1787            DiskAnnParams {
1788                max_degree: 4,
1789                build_beam_width: 64,
1790                alpha: 1.5,
1791                extra_seeds: DISKANN_DEFAULT_EXTRA_SEEDS,
1792            },
1793        )
1794        .unwrap();
1795
1796        for target in 0..vectors.len() {
1797            let q = &vectors[target];
1798            let nns = index.search(q, 10, 32);
1799            if !nns.contains(&(target as u32)) {
1800                let v = index.get_vector(nns[0] as usize);
1801                assert!(euclid(q, &v) < 2.0);
1802            }
1803            for &nb in nns.iter().take(5) {
1804                let v = index.get_vector(nb as usize);
1805                assert!(euclid(q, &v) < 5.0);
1806            }
1807        }
1808
1809        let _ = fs::remove_file(path);
1810    }
1811
1812    #[test]
1813    fn test_medium_random() {
1814        let path = "test_medium.db";
1815        let _ = fs::remove_file(path);
1816
1817        let n = 200usize;
1818        let d = 32usize;
1819        let mut rng = rand::thread_rng();
1820        let vectors: Vec<Vec<f32>> = (0..n)
1821            .map(|_| (0..d).map(|_| rng.r#gen::<f32>()).collect())
1822            .collect();
1823
1824        let index = DiskANN::<f32, DistL2>::build_index_with_params(
1825            &vectors,
1826            DistL2,
1827            path,
1828            DiskAnnParams {
1829                max_degree: 32,
1830                build_beam_width: 128,
1831                alpha: 1.2,
1832                extra_seeds: DISKANN_DEFAULT_EXTRA_SEEDS,
1833            },
1834        )
1835        .unwrap();
1836
1837        let q: Vec<f32> = (0..d).map(|_| rng.r#gen::<f32>()).collect();
1838        let res = index.search(&q, 10, 64);
1839        assert_eq!(res.len(), 10);
1840
1841        let dists: Vec<f32> = res
1842            .iter()
1843            .map(|&id| {
1844                let v = index.get_vector(id as usize);
1845                euclid(&q, &v)
1846            })
1847            .collect();
1848        let mut sorted = dists.clone();
1849        sorted.sort_by(|a, b| a.total_cmp(b));
1850        assert_eq!(dists, sorted);
1851
1852        let _ = fs::remove_file(path);
1853    }
1854
1855    #[test]
1856    fn test_regular_l2_recall() {
1857        let path = "test_regular_l2_recall.db";
1858        let _ = fs::remove_file(path);
1859        let mut rng = StdRng::seed_from_u64(11);
1860        let vectors: Vec<Vec<f32>> = (0..500)
1861            .map(|_| (0..24).map(|_| rng.r#gen::<f32>()).collect())
1862            .collect();
1863        let queries: Vec<Vec<f32>> = (0..40)
1864            .map(|_| (0..24).map(|_| rng.r#gen::<f32>()).collect())
1865            .collect();
1866
1867        let index =
1868            DiskANN::build_index_with_params(&vectors, DistL2, path, quality_params()).unwrap();
1869        let recall = exact_recall(&index, &vectors, &queries, DistL2, 10, 256);
1870        assert!(recall >= 0.95, "regular L2 recall was {recall}");
1871        let _ = fs::remove_file(path);
1872    }
1873
1874    #[test]
1875    fn test_clustered_l2_recall() {
1876        let path = "test_clustered_l2_recall.db";
1877        let _ = fs::remove_file(path);
1878        let mut rng = StdRng::seed_from_u64(23);
1879        let dim = 24usize;
1880        let clusters = 12usize;
1881        let mut vectors = Vec::with_capacity(clusters * 50);
1882        let mut queries = Vec::with_capacity(clusters * 3);
1883
1884        for cluster in 0..clusters {
1885            let mut center = vec![0.0f32; dim];
1886            center[cluster] = 40.0;
1887            center[(cluster + 7) % dim] = -25.0;
1888            for _ in 0..50 {
1889                vectors.push(
1890                    center
1891                        .iter()
1892                        .map(|value| value + rng.gen_range(-0.4f32..0.4f32))
1893                        .collect(),
1894                );
1895            }
1896            for _ in 0..3 {
1897                queries.push(
1898                    center
1899                        .iter()
1900                        .map(|value| value + rng.gen_range(-0.4f32..0.4f32))
1901                        .collect(),
1902                );
1903            }
1904        }
1905
1906        let index =
1907            DiskANN::build_index_with_params(&vectors, DistL2, path, quality_params()).unwrap();
1908        let recall = exact_recall(&index, &vectors, &queries, DistL2, 10, 256);
1909        assert!(recall >= 0.95, "clustered L2 recall was {recall}");
1910        let _ = fs::remove_file(path);
1911    }
1912
1913    #[test]
1914    fn test_cosine_recall() {
1915        let path = "test_cosine_recall.db";
1916        let _ = fs::remove_file(path);
1917        let mut rng = StdRng::seed_from_u64(37);
1918        let vectors: Vec<Vec<f32>> = (0..500)
1919            .map(|_| (0..32).map(|_| rng.gen_range(-1.0f32..1.0f32)).collect())
1920            .collect();
1921        let queries: Vec<Vec<f32>> = (0..40)
1922            .map(|_| (0..32).map(|_| rng.gen_range(-1.0f32..1.0f32)).collect())
1923            .collect();
1924
1925        let index =
1926            DiskANN::build_index_with_params(&vectors, DistCosine, path, quality_params()).unwrap();
1927        let recall = exact_recall(&index, &vectors, &queries, DistCosine, 10, 256);
1928        assert!(recall >= 0.95, "cosine recall was {recall}");
1929        let _ = fs::remove_file(path);
1930    }
1931
1932    #[test]
1933    fn test_jaccard_recall() {
1934        let path = "test_jaccard_recall.db";
1935        let _ = fs::remove_file(path);
1936        let mut rng = StdRng::seed_from_u64(41);
1937        let vectors: Vec<Vec<u32>> = (0..400)
1938            .map(|_| (0..32).map(|_| rng.gen_range(0u32..8u32)).collect())
1939            .collect();
1940        let queries: Vec<Vec<u32>> = (0..40)
1941            .map(|_| (0..32).map(|_| rng.gen_range(0u32..8u32)).collect())
1942            .collect();
1943
1944        let index = DiskANN::build_index_with_params(&vectors, DistJaccard, path, quality_params())
1945            .unwrap();
1946        let recall = exact_recall(&index, &vectors, &queries, DistJaccard, 10, 256);
1947        assert!(recall >= 0.95, "Jaccard recall was {recall}");
1948        let _ = fs::remove_file(path);
1949    }
1950
1951    #[test]
1952    fn test_merit_clustered_l1_delete() {
1953        let mut rng = StdRng::seed_from_u64(81);
1954        let mut vectors = Vec::with_capacity(10_000);
1955        let mut queries = Vec::with_capacity(100);
1956        for cluster in 0..50 {
1957            let center = (0..32)
1958                .map(|dim| (((cluster * 37 + dim * 13) % 101) as f32 - 50.0) * 8.0)
1959                .collect::<Vec<_>>();
1960            for _ in 0..200 {
1961                vectors.push(
1962                    center
1963                        .iter()
1964                        .map(|value| value + rng.gen_range(-0.15f32..0.15))
1965                        .collect(),
1966                );
1967            }
1968            for _ in 0..2 {
1969                queries.push(
1970                    center
1971                        .iter()
1972                        .map(|value| value + rng.gen_range(-0.15f32..0.15))
1973                        .collect(),
1974                );
1975            }
1976        }
1977        let (updated, rebuilt, update_s, rebuild_s) =
1978            merit_clustered_delete(&vectors, &queries, DistL1, "merit_clustered_l1");
1979        println!(
1980            "clustered L1 MERIT: updated={updated:.6}, rebuilt={rebuilt:.6}, delta={:.6}, update={update_s:.3}s, rebuild={rebuild_s:.3}s",
1981            updated - rebuilt
1982        );
1983        assert!(updated >= 0.95, "clustered L1 MERIT recall was {updated}");
1984        assert!(
1985            updated + 0.02 >= rebuilt,
1986            "clustered L1 delta was {}",
1987            updated - rebuilt
1988        );
1989    }
1990
1991    #[test]
1992    fn test_merit_clustered_jaccard_delete() {
1993        let mut rng = StdRng::seed_from_u64(82);
1994        let mut vectors = Vec::with_capacity(10_000);
1995        let mut queries = Vec::with_capacity(100);
1996        for cluster in 0..50 {
1997            let mut center = vec![1u32; 64];
1998            for marker in 0..8 {
1999                center[(cluster * 11 + marker * 7) % 64] = 30 + (cluster % 7) as u32;
2000            }
2001            for _ in 0..200 {
2002                vectors.push(
2003                    center
2004                        .iter()
2005                        .map(|value| value + rng.gen_range(0u32..3))
2006                        .collect(),
2007                );
2008            }
2009            for _ in 0..2 {
2010                queries.push(
2011                    center
2012                        .iter()
2013                        .map(|value| value + rng.gen_range(0u32..3))
2014                        .collect(),
2015                );
2016            }
2017        }
2018        let (updated, rebuilt, update_s, rebuild_s) =
2019            merit_clustered_delete(&vectors, &queries, DistJaccard, "merit_clustered_jaccard");
2020        println!(
2021            "clustered Jaccard MERIT: updated={updated:.6}, rebuilt={rebuilt:.6}, delta={:.6}, update={update_s:.3}s, rebuild={rebuild_s:.3}s",
2022            updated - rebuilt
2023        );
2024        assert!(
2025            updated >= 0.95,
2026            "clustered Jaccard MERIT recall was {updated}"
2027        );
2028        assert!(
2029            updated + 0.02 >= rebuilt,
2030            "clustered Jaccard delta was {}",
2031            updated - rebuilt
2032        );
2033    }
2034}