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