tapirus 1.2.1

Embedded multi-model database with SQL, vector search and local AI memory
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
//! Hierarchical Navigable Small World (HNSW) Vector Index.
//!
//! Approximate nearest neighbor search with explicit construction/search budgets.

use crate::error::{Error, Result};
use crate::traits::VectorIndexEngine;
use crate::vector::{DistanceMetric, cosine_distance, euclidean_distance};
use std::cmp::Ordering;
use std::collections::{BinaryHeap, HashSet};

/// Candidate with smallest distance prioritized (Min-Heap)
#[derive(Debug, Clone, PartialEq)]
struct MinCandidate {
    id: u64,
    distance: f32,
}

impl Eq for MinCandidate {}

impl Ord for MinCandidate {
    fn cmp(&self, other: &Self) -> Ordering {
        other
            .distance
            .partial_cmp(&self.distance)
            .unwrap_or(Ordering::Equal)
    }
}

impl PartialOrd for MinCandidate {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

/// Candidate with largest distance prioritized (Max-Heap)
#[derive(Debug, Clone, PartialEq)]
struct MaxCandidate {
    id: u64,
    distance: f32,
}

impl Eq for MaxCandidate {}

impl Ord for MaxCandidate {
    fn cmp(&self, other: &Self) -> Ordering {
        self.distance
            .partial_cmp(&other.distance)
            .unwrap_or(Ordering::Equal)
    }
}

impl PartialOrd for MaxCandidate {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

/// Configuration parameters for tuning the HNSW graph construction and search
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq)]
pub struct HnswConfig {
    /// Max neighbors per node at layer > 0 (default: 16)
    pub m: usize,
    /// Max neighbors per node at layer 0 (default: 32)
    pub m0: usize,
    /// Size of dynamic candidate list during construction (default: 64)
    pub ef_construction: usize,
    /// Size of dynamic candidate list during search (default: 32)
    pub ef_search: usize,
    /// Whether to enable 8-bit scalar quantization (SQ8) to reduce RAM by 4x
    pub quantize_sq8: bool,
}

impl Default for HnswConfig {
    fn default() -> Self {
        Self {
            m: 16,
            m0: 32,
            ef_construction: 64,
            ef_search: 32,
            quantize_sq8: false,
        }
    }
}

/// A node in the HNSW multi-layer graph
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct HnswNode {
    /// Unique record ID
    pub id: u64,
    /// Vector embedding values
    pub vector: Vec<f32>,
    /// Top layer this node appears in (0 is bottom layer)
    pub top_layer: usize,
    /// Adjacency lists for each layer: `layer_neighbors[layer] = Vec<u64>`
    pub layer_neighbors: Vec<Vec<u64>>,
    /// Optional 8-bit scalar quantized representation for ultra-fast low-memory search
    #[serde(default)]
    pub quantized: Option<crate::vector::QuantizedVector8>,
}

/// Persistent disk snapshot of an HNSW multi-layer graph topology
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct HnswSnapshot {
    /// Vector dimensionality
    pub dimensions: usize,
    /// Distance metric
    pub metric: DistanceMetric,
    /// Index hyperparameter configuration
    pub config: HnswConfig,
    /// Entry point node ID in the graph
    pub entry_point: Option<u64>,
    /// Maximum level reached in the hierarchy
    pub max_level: usize,
    /// All node records in the index
    pub nodes: Vec<HnswNode>,
    /// List of deleted node IDs marked as tombstones
    pub tombstones: Vec<u64>,
}

/// In-memory Hierarchical Navigable Small World index
#[derive(Debug, Clone)]
pub struct HnswIndex {
    /// Number of dimensions per vector
    pub dimensions: usize,
    /// Distance metric
    pub metric: DistanceMetric,
    /// Max neighbors per node at layer > 0
    pub m: usize,
    /// Max neighbors per node at layer 0 (typically 2 * m)
    pub m0: usize,
    /// Size of dynamic candidate list during construction
    pub ef_construction: usize,
    /// Size of dynamic candidate list during search
    pub ef_search: usize,
    /// Active HNSW configuration
    pub config: HnswConfig,
    /// Entry point node ID
    pub entry_point: Option<u64>,
    /// Maximum level currently in the index
    pub max_level: usize,
    /// Level multiplier parameter `1 / ln(M)`
    pub ml: f64,
    /// Stored nodes
    pub nodes: std::collections::HashMap<u64, HnswNode>,
    /// Set of tombstoned/deleted node IDs awaiting vacuum
    pub tombstones: HashSet<u64>,
    /// Internal SplitMix64 uniform PRNG state
    pub rng_state: u64,
}

impl HnswIndex {
    /// Create a new HNSW index with target dimensions and distance metric
    pub fn new(dimensions: usize, metric: DistanceMetric) -> Self {
        let seed = web_time::SystemTime::now()
            .duration_since(web_time::UNIX_EPOCH)
            .map(|d| d.as_nanos() as u64)
            .unwrap_or(0x9e3779b97f4a7c15);
        Self::with_config_and_seed(dimensions, metric, HnswConfig::default(), seed)
    }

    /// Create a new HNSW index with custom seed for reproducible testing
    pub fn with_seed(dimensions: usize, metric: DistanceMetric, seed: u64) -> Self {
        Self::with_config_and_seed(dimensions, metric, HnswConfig::default(), seed)
    }

    /// Create a new HNSW index with custom configuration
    pub fn with_config(dimensions: usize, metric: DistanceMetric, config: HnswConfig) -> Self {
        let seed = web_time::SystemTime::now()
            .duration_since(web_time::UNIX_EPOCH)
            .map(|d| d.as_nanos() as u64)
            .unwrap_or(0x9e3779b97f4a7c15);
        Self::with_config_and_seed(dimensions, metric, config, seed)
    }

    /// Create a new HNSW index with custom configuration and random seed
    pub fn with_config_and_seed(
        dimensions: usize,
        metric: DistanceMetric,
        config: HnswConfig,
        seed: u64,
    ) -> Self {
        let m = config.m.max(2);
        let m0 = config.m0.max(2);
        let ef_construction = config.ef_construction.max(m);
        let ef_search = config.ef_search.max(1);
        let ml = 1.0 / (m as f64).ln();

        Self {
            dimensions,
            metric,
            m,
            m0,
            ef_construction,
            ef_search,
            config,
            entry_point: None,
            max_level: 0,
            ml,
            nodes: std::collections::HashMap::new(),
            tombstones: HashSet::new(),
            rng_state: if seed == 0 { 0xdeadbeefcafebabe } else { seed },
        }
    }

    /// Create a new HNSW index with explicit configurable parameters
    pub fn with_params(
        dimensions: usize,
        metric: DistanceMetric,
        m: usize,
        ef_construction: usize,
        ef_search: usize,
        quantize_sq8: bool,
    ) -> Self {
        let config = HnswConfig {
            m,
            m0: m * 2,
            ef_construction,
            ef_search,
            quantize_sq8,
        };
        Self::with_config(dimensions, metric, config)
    }

    /// Export the entire HNSW topology and nodes as a serializable snapshot for persistent disk storage
    pub fn export_snapshot(&self) -> HnswSnapshot {
        HnswSnapshot {
            dimensions: self.dimensions,
            metric: self.metric,
            config: self.config.clone(),
            entry_point: self.entry_point,
            max_level: self.max_level,
            nodes: self.nodes.values().cloned().collect(),
            tombstones: self.tombstones.iter().copied().collect(),
        }
    }

    /// Restore a fully structured HNSW index in O(N) from a persistent snapshot without re-indexing
    pub fn import_snapshot(snapshot: HnswSnapshot) -> Self {
        let m = snapshot.config.m.max(2);
        let m0 = snapshot.config.m0.max(2);
        let ml = 1.0 / (m as f64).ln();
        let mut nodes = std::collections::HashMap::new();
        for node in snapshot.nodes {
            nodes.insert(node.id, node);
        }
        let tombstones = snapshot.tombstones.into_iter().collect();

        Self {
            dimensions: snapshot.dimensions,
            metric: snapshot.metric,
            m,
            m0,
            ef_construction: snapshot.config.ef_construction,
            ef_search: snapshot.config.ef_search,
            config: snapshot.config,
            entry_point: snapshot.entry_point,
            max_level: snapshot.max_level,
            ml,
            nodes,
            tombstones,
            rng_state: 0xdeadbeefcafebabe,
        }
    }

    /// Compute distance between query and node, utilizing 8-bit scalar quantization if enabled
    #[inline]
    pub fn compute_node_distance(
        &self,
        query: &[f32],
        node: &HnswNode,
        metric: DistanceMetric,
    ) -> f32 {
        if let Some(ref q) = node.quantized {
            match metric {
                DistanceMetric::Cosine => q.asymmetric_cosine_distance(query),
                DistanceMetric::Euclidean => q.asymmetric_l2_distance_squared(query).sqrt(),
                DistanceMetric::DotProduct => {
                    let dot = q.asymmetric_dot_product(query);
                    if dot.is_finite() { -dot } else { f32::MAX }
                }
            }
        } else {
            self.distance_with_metric(query, &node.vector, metric)
        }
    }

    /// Calculate distance between two vectors using configured metric
    #[inline]
    pub fn distance(&self, a: &[f32], b: &[f32]) -> f32 {
        self.distance_with_metric(a, b, self.metric)
    }

    /// Calculate distance between two vectors using an explicit metric override
    #[inline]
    pub fn distance_with_metric(&self, a: &[f32], b: &[f32], metric: DistanceMetric) -> f32 {
        match metric {
            DistanceMetric::Cosine => cosine_distance(a, b),
            DistanceMetric::Euclidean => euclidean_distance(a, b),
            DistanceMetric::DotProduct => {
                let dot: f32 = a.iter().zip(b.iter()).map(|(x, y)| x * y).sum();
                if dot.is_finite() { -dot } else { f32::MAX }
            }
        }
    }

    /// Number of active (non-tombstoned) vectors stored in the index
    pub fn len(&self) -> usize {
        self.nodes.len().saturating_sub(self.tombstones.len())
    }

    /// Check if index is empty
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Mark a vector as deleted via tombstone (soft delete in O(1))
    pub fn mark_deleted(&mut self, id: u64) -> bool {
        if self.nodes.contains_key(&id) {
            self.tombstones.insert(id)
        } else {
            false
        }
    }

    /// Check if a node ID is tombstoned/deleted
    pub fn is_deleted(&self, id: u64) -> bool {
        self.tombstones.contains(&id)
    }

    /// Rebuild active topology and remove tombstones. Failure preserves this index.
    pub fn rebuild(&mut self) -> Result<usize> {
        let removed = self.tombstones.len();
        let config = HnswConfig {
            m: self.m,
            m0: self.m0,
            ef_construction: self.ef_construction,
            ef_search: self.ef_search,
            ..self.config.clone()
        };
        let mut rebuilt =
            Self::with_config_and_seed(self.dimensions, self.metric, config, self.rng_state);
        let mut active: Vec<_> = self
            .nodes
            .values()
            .filter(|node| !self.tombstones.contains(&node.id))
            .collect();
        active.sort_by_key(|node| node.id);
        for node in active {
            rebuilt.insert_vector(node.id, &node.vector)?;
        }
        *self = rebuilt;
        Ok(removed)
    }

    /// Purge tombstones and rebuild graph connections. Use `rebuild` to report errors.
    pub fn vacuum(&mut self) -> usize {
        if self.tombstones.is_empty() {
            return 0;
        }
        self.rebuild().unwrap_or(0)
    }

    /// Remove a vector node from HNSW index by ID
    pub fn remove_vector(&mut self, id: u64) -> bool {
        if self.nodes.remove(&id).is_some() {
            self.tombstones.remove(&id);
            for node in self.nodes.values_mut() {
                for neighbors in node.layer_neighbors.iter_mut() {
                    neighbors.retain(|&nid| nid != id);
                }
            }
            if self.entry_point == Some(id) {
                let mut best_ep = None;
                let mut best_level = 0;
                for (&nid, node) in &self.nodes {
                    if best_ep.is_none() || node.top_layer > best_level {
                        best_ep = Some(nid);
                        best_level = node.top_layer;
                    }
                }
                self.entry_point = best_ep;
                self.max_level = best_level;
            }
            true
        } else {
            false
        }
    }

    /// Generate uniform pseudo-random float in (0.0, 1.0) using SplitMix64
    pub fn next_random_f64(&mut self) -> f64 {
        self.rng_state = self.rng_state.wrapping_add(0x9e3779b97f4a7c15);
        let mut z = self.rng_state;
        z = (z ^ (z >> 30)).wrapping_mul(0xbf58476d1ce4e5b9);
        z = (z ^ (z >> 27)).wrapping_mul(0x94d049bb133111eb);
        let r = z ^ (z >> 31);
        let val = (r as f64) / (u64::MAX as f64);
        val.clamp(0.0000001, 0.9999999)
    }

    /// Generate random layer level for new node using uniform logarithmic scaling (Malkov & Yashunin, 2018)
    fn random_level(&mut self) -> usize {
        let rand_val = self.next_random_f64();
        let level = (-rand_val.ln() * self.ml).floor() as usize;
        level.min(16)
    }

    /// Search layer for nearest neighbors
    fn search_layer(
        &self,
        query: &[f32],
        entry_points: &[u64],
        ef: usize,
        layer: usize,
    ) -> Vec<(u64, f32)> {
        self.search_layer_with_metric(query, entry_points, ef, layer, self.metric)
    }

    /// Search layer for nearest neighbors using an explicit metric override
    fn search_layer_with_metric(
        &self,
        query: &[f32],
        entry_points: &[u64],
        ef: usize,
        layer: usize,
        metric: DistanceMetric,
    ) -> Vec<(u64, f32)> {
        let mut visited: HashSet<u64> = entry_points.iter().copied().collect();
        let mut candidates = BinaryHeap::new(); // Min-heap: closest explored first
        let mut nearest = BinaryHeap::new(); // Max-heap: furthest on top for eviction

        for &ep in entry_points {
            if let Some(node) = self.nodes.get(&ep) {
                let dist = self.compute_node_distance(query, node, metric);
                candidates.push(MinCandidate {
                    id: ep,
                    distance: dist,
                });
                nearest.push(MaxCandidate {
                    id: ep,
                    distance: dist,
                });
            }
        }

        while let Some(curr) = candidates.pop() {
            let furthest_dist = nearest.peek().map(|c| c.distance).unwrap_or(f32::MAX);
            if curr.distance > furthest_dist && nearest.len() >= ef {
                break;
            }

            if let Some(node) = self.nodes.get(&curr.id)
                && layer < node.layer_neighbors.len()
            {
                for &neighbor_id in &node.layer_neighbors[layer] {
                    if visited.insert(neighbor_id)
                        && let Some(neighbor) = self.nodes.get(&neighbor_id)
                    {
                        let dist = self.compute_node_distance(query, neighbor, metric);
                        if dist < furthest_dist || nearest.len() < ef {
                            candidates.push(MinCandidate {
                                id: neighbor_id,
                                distance: dist,
                            });
                            nearest.push(MaxCandidate {
                                id: neighbor_id,
                                distance: dist,
                            });

                            if nearest.len() > ef {
                                nearest.pop(); // Evict furthest
                            }
                        }
                    }
                }
            }
        }

        let mut sorted: Vec<(u64, f32)> = nearest.into_iter().map(|c| (c.id, c.distance)).collect();
        sorted.sort_by(|a, b| a.1.partial_cmp(&b.1).unwrap_or(Ordering::Equal));
        sorted
    }

    // Keep neighbors in different directions. Taking only the closest candidates
    // creates redundant local links and poor high-dimensional recall.
    fn diverse_neighbors(
        &self,
        candidates: &[(u64, f32)],
        limit: usize,
        inserted: Option<(u64, &[f32])>,
    ) -> Vec<u64> {
        if candidates.len() <= limit {
            return candidates.iter().map(|(id, _)| *id).collect();
        }
        let vector = |id: u64| -> Option<&[f32]> {
            if let Some((new_id, new_vector)) = inserted
                && new_id == id
            {
                return Some(new_vector);
            }
            self.nodes.get(&id).map(|node| node.vector.as_slice())
        };
        let mut selected = Vec::with_capacity(limit);
        let mut pruned = Vec::new();
        for &(id, anchor_distance) in candidates {
            let Some(candidate) = vector(id) else {
                continue;
            };
            let redundant = selected.iter().any(|neighbor| {
                vector(*neighbor)
                    .is_some_and(|other| self.distance(candidate, other) < anchor_distance)
            });
            if !redundant {
                selected.push(id);
                if selected.len() == limit {
                    break;
                }
            } else {
                pruned.push(id);
            }
        }
        // Keep the requested graph degree when geometric pruning is too
        // aggressive. Sparse reciprocal links make distant regions unreachable.
        selected.extend(pruned.into_iter().take(limit - selected.len()));
        selected
    }

    /// Search K-nearest neighbors for a query vector with optional candidate ID pre-filtering
    pub fn search_knn_filtered(
        &self,
        query: &[f32],
        k: usize,
        metric: DistanceMetric,
        filter: Option<&std::collections::HashSet<u64>>,
    ) -> Result<Vec<(u64, f32)>> {
        self.search_knn_where(
            query,
            k,
            metric,
            (filter, false),
            |_| true,
            self.nodes.len(),
        )
    }

    pub(crate) fn search_knn_where(
        &self,
        query: &[f32],
        k: usize,
        metric: DistanceMetric,
        filter_options: (Option<&HashSet<u64>>, bool),
        accept: impl Fn(u64) -> bool,
        max_ef: usize,
    ) -> Result<Vec<(u64, f32)>> {
        let (filter, filter_active) = filter_options;
        if query.len() != self.dimensions {
            return Err(Error::DimensionMismatch(self.dimensions, query.len()));
        }
        if query.iter().any(|value| !value.is_finite()) {
            return Err(Error::ConstraintViolation(
                "Query vector components must be finite".into(),
            ));
        }

        if k == 0 || self.nodes.is_empty() {
            return Ok(Vec::new());
        }

        // Small allow-lists are cheaper and more accurate to score directly.
        if let Some(allowed) = filter
            && allowed.len() <= self.ef_search.max(k)
        {
            let mut matches: Vec<_> = allowed
                .iter()
                .filter(|id| !self.tombstones.contains(id))
                .filter(|id| accept(**id))
                .filter_map(|id| {
                    self.nodes
                        .get(id)
                        .map(|node| (*id, self.compute_node_distance(query, node, metric)))
                })
                .collect();
            matches.sort_by(|a, b| a.1.total_cmp(&b.1).then_with(|| a.0.cmp(&b.0)));
            matches.truncate(k);
            return Ok(matches);
        }

        let mut curr_entry = match self.entry_point {
            Some(ep) => ep,
            None => return Ok(Vec::new()),
        };

        // 1. Greedily traverse down to layer 0
        for l in (1..=self.max_level).rev() {
            let mut changed = true;
            while changed {
                changed = false;
                if let Some(curr_node) = self.nodes.get(&curr_entry) {
                    let curr_dist = self.compute_node_distance(query, curr_node, metric);

                    if l < curr_node.layer_neighbors.len() {
                        for &neighbor_id in &curr_node.layer_neighbors[l] {
                            if let Some(neighbor) = self.nodes.get(&neighbor_id) {
                                let dist = self.compute_node_distance(query, neighbor, metric);
                                if dist < curr_dist {
                                    curr_entry = neighbor_id;
                                    changed = true;
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }

        // 2. Search bottom layer 0 with ef_search (expanded if filtering is active)
        let ef_multiplier = if filter.is_some() || filter_active {
            4
        } else {
            1
        };
        let ef_cap = max_ef.max(k).min(self.nodes.len());
        let mut ef = self
            .ef_search
            .max(k)
            .saturating_mul(ef_multiplier)
            .min(ef_cap);
        loop {
            let candidates = self.search_layer_with_metric(query, &[curr_entry], ef, 0, metric);
            let results: Vec<_> = candidates
                .into_iter()
                .filter(|(id, _)| {
                    !self.tombstones.contains(id)
                        && filter.is_none_or(|allowed| allowed.contains(id))
                        && accept(*id)
                })
                .take(k)
                .collect();
            if results.len() >= k.min(self.len()) || ef >= ef_cap {
                return Ok(results);
            }
            ef = ef.saturating_mul(2).min(ef_cap);
        }
    }

    /// Search K-nearest neighbors for a query vector
    pub fn search_knn(
        &self,
        query: &[f32],
        k: usize,
        metric: DistanceMetric,
    ) -> Result<Vec<(u64, f32)>> {
        self.search_knn_filtered(query, k, metric, None)
    }
}

impl VectorIndexEngine for HnswIndex {
    fn insert_vector(&mut self, id: u64, vector: &[f32]) -> Result<()> {
        if vector.len() != self.dimensions {
            return Err(Error::DimensionMismatch(self.dimensions, vector.len()));
        }
        if vector.iter().any(|value| !value.is_finite()) {
            return Err(Error::ConstraintViolation(
                "Vector components must be finite".into(),
            ));
        }

        // Clean up previous connections if ID already exists
        if self.nodes.contains_key(&id) {
            self.remove_vector(id);
        }

        let node_level = self.random_level();
        let mut layer_neighbors = vec![Vec::new(); node_level + 1];

        if let Some(mut curr_entry) = self.entry_point {
            let curr_max_level = self.max_level;

            // 1. Greedily traverse down from top layer to node_level + 1
            if curr_max_level > node_level {
                for l in (node_level + 1..=curr_max_level).rev() {
                    let mut changed = true;
                    while changed {
                        changed = false;
                        if let Some(curr_node) = self.nodes.get(&curr_entry) {
                            let curr_dist =
                                self.compute_node_distance(vector, curr_node, self.metric);
                            if l < curr_node.layer_neighbors.len() {
                                for &neighbor_id in &curr_node.layer_neighbors[l] {
                                    if let Some(neighbor) = self.nodes.get(&neighbor_id) {
                                        let dist = self.compute_node_distance(
                                            vector,
                                            neighbor,
                                            self.metric,
                                        );
                                        if dist < curr_dist {
                                            curr_entry = neighbor_id;
                                            changed = true;
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

            // 2. From min(node_level, curr_max_level) down to 0, find neighbors and connect
            let mut ep = vec![curr_entry];
            for l in (0..=node_level.min(curr_max_level)).rev() {
                let candidates = self.search_layer(vector, &ep, self.ef_construction, l);
                let max_neighbors = if l == 0 { self.m0 } else { self.m };

                let neighbor_ids = self.diverse_neighbors(&candidates, max_neighbors, None);

                layer_neighbors[l] = neighbor_ids.clone();

                // Connect bidirectionally
                for &nid in &neighbor_ids {
                    let Some(neighbor_node) = self.nodes.get(&nid) else {
                        continue;
                    };
                    if l >= neighbor_node.layer_neighbors.len() {
                        continue;
                    }
                    let mut connections = neighbor_node.layer_neighbors[l].clone();
                    connections.push(id);
                    if connections.len() > max_neighbors {
                        // Prune by geometric diversity, including the new reverse
                        // edge, rather than retaining a cluster of redundant links.
                        let anchor = &neighbor_node.vector;
                        let mut ranked: Vec<_> = connections
                            .into_iter()
                            .filter_map(|candidate| {
                                let candidate_vector = if candidate == id {
                                    vector
                                } else {
                                    &self.nodes.get(&candidate)?.vector
                                };
                                Some((candidate, self.distance(anchor, candidate_vector)))
                            })
                            .collect();
                        ranked.sort_by(|a, b| a.1.total_cmp(&b.1).then_with(|| a.0.cmp(&b.0)));
                        connections =
                            self.diverse_neighbors(&ranked, max_neighbors, Some((id, vector)));
                    }
                    self.nodes
                        .get_mut(&nid)
                        .expect("existing neighbor")
                        .layer_neighbors[l] = connections;
                }

                // All construction candidates remain entry points for the next
                // layer; selected outgoing links are a separate bounded subset.
                ep = candidates
                    .into_iter()
                    .map(|(candidate, _)| candidate)
                    .collect();
            }

            if node_level > self.max_level {
                self.max_level = node_level;
                self.entry_point = Some(id);
            }
        } else {
            // First node in index
            self.entry_point = Some(id);
            self.max_level = node_level;
        }

        let quantized = if self.config.quantize_sq8 {
            Some(crate::vector::QuantizedVector8::quantize(vector))
        } else {
            None
        };

        let node = HnswNode {
            id,
            vector: vector.to_vec(),
            top_layer: node_level,
            layer_neighbors,
            quantized,
        };

        self.nodes.insert(id, node);
        Ok(())
    }

    fn search_knn(
        &self,
        query: &[f32],
        k: usize,
        metric: DistanceMetric,
    ) -> Result<Vec<(u64, f32)>> {
        self.search_knn_filtered(query, k, metric, None)
    }
}

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

    #[test]
    fn test_hnsw_knn_search() {
        let mut index = HnswIndex::new(3, DistanceMetric::Cosine);

        let v1 = vec![1.0, 0.0, 0.0];
        let v2 = vec![0.0, 1.0, 0.0];
        let v3 = vec![0.0, 0.0, 1.0];
        let v4 = vec![0.95, 0.05, 0.0]; // Very close to v1

        index.insert_vector(1, &v1).expect("Insert v1");
        index.insert_vector(2, &v2).expect("Insert v2");
        index.insert_vector(3, &v3).expect("Insert v3");
        index.insert_vector(4, &v4).expect("Insert v4");

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

        // Search for vector closest to v1
        let query = vec![0.98, 0.02, 0.0];
        let neighbors = index
            .search_knn(&query, 2, DistanceMetric::Cosine)
            .expect("KNN search");

        assert_eq!(neighbors.len(), 2);
        let top_ids: Vec<u64> = neighbors.iter().map(|(id, _)| *id).collect();
        assert!(
            top_ids.contains(&1) && top_ids.contains(&4),
            "Expected [1, 4] in top 2, got {:?}",
            top_ids
        );
    }

    #[test]
    fn test_hnsw_tombstone_and_vacuum() {
        let mut index = HnswIndex::new(3, DistanceMetric::Cosine);

        let v1 = vec![1.0, 0.0, 0.0];
        let v2 = vec![0.98, 0.02, 0.0];
        let v3 = vec![0.0, 1.0, 0.0];

        index.insert_vector(1, &v1).expect("Insert v1");
        index.insert_vector(2, &v2).expect("Insert v2");
        index.insert_vector(3, &v3).expect("Insert v3");

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

        // Soft delete v1 via tombstone
        assert!(index.mark_deleted(1));
        assert!(index.is_deleted(1));
        assert_eq!(index.len(), 2);

        // Search for vector closest to v1: v1 must NOT be returned
        let query = vec![1.0, 0.0, 0.0];
        let results = index
            .search_knn(&query, 2, DistanceMetric::Cosine)
            .expect("KNN search");
        assert_eq!(results[0].0, 2); // v2 is closest non-deleted node
        assert!(!results.iter().any(|(id, _)| *id == 1));

        // Vacuum should purge v1 from physical storage
        let purged = index.vacuum();
        assert_eq!(purged, 1);
        assert_eq!(index.len(), 2);
        assert!(!index.nodes.contains_key(&1));
    }

    #[test]
    fn test_hnsw_random_level_logarithmic_distribution() {
        let mut index = HnswIndex::with_seed(3, DistanceMetric::Cosine, 42);
        let mut level_counts = [0usize; 17];

        // Sample 1,000 layer levels
        for _ in 0..1000 {
            let level = index.random_level();
            assert!(level <= 16);
            level_counts[level] += 1;
        }

        // Level 0 must have the highest frequency (base layer)
        assert!(level_counts[0] > level_counts[1], "Level 0 must dominate");
        // Layer counts should exhibit monotonic decay
        assert!(level_counts[1] >= level_counts[2]);
        // Total samples at higher levels should be smaller
        let higher_levels: usize = level_counts[3..].iter().sum();
        assert!(higher_levels < level_counts[0]);
    }
}