velesdb-core 1.7.2

High-performance vector database engine written in Rust
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
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
//! Tests for native HNSW implementation.

#![allow(clippy::cast_precision_loss, deprecated)]

use super::distance::{CpuDistance, SimdDistance};
use super::graph::NativeHnsw;
use crate::distance::DistanceMetric;

#[test]
fn test_native_hnsw_basic_insert_search() {
    let engine = SimdDistance::new(DistanceMetric::Cosine);
    let hnsw = NativeHnsw::new(engine, 16, 100, 1000);

    // Insert 100 vectors
    for i in 0..100_u64 {
        let v: Vec<f32> = (0..128).map(|j| ((i + j) as f32 * 0.01).sin()).collect();
        hnsw.insert(&v).expect("test");
    }

    assert_eq!(hnsw.len(), 100);

    // Search for first vector
    let query: Vec<f32> = (0..128).map(|j| (j as f32 * 0.01).sin()).collect();
    let results = hnsw.search(&query, 10, 50);

    assert_eq!(results.len(), 10);
    // First result should be node 0 or very close
    assert!(results[0].1 < 0.1, "First result should be very close");
}

#[test]
fn test_native_hnsw_recall() {
    let engine = SimdDistance::new(DistanceMetric::Cosine);
    // Reduced parameters for faster test execution
    let hnsw = NativeHnsw::new(engine, 16, 100, 500);

    // Reduced from 1000×768D to 200×128D for faster test execution
    let vectors: Vec<Vec<f32>> = (0..200)
        .map(|i| {
            (0..128)
                .map(|j| ((i * 128 + j) as f32 * 0.001).sin())
                .collect()
        })
        .collect();

    for v in &vectors {
        hnsw.insert(v).expect("test");
    }

    // Test recall with multiple queries
    let mut total_recall = 0.0;
    let n_queries = 5;
    let k = 10;

    for q_idx in 0..n_queries {
        let query = &vectors[q_idx * 40]; // Use existing vectors as queries

        // Get HNSW results
        let hnsw_results: Vec<usize> = hnsw
            .search(query, k, 128)
            .iter()
            .map(|(id, _)| *id)
            .collect();

        // Compute ground truth (brute force)
        let mut distances: Vec<(usize, f32)> = vectors
            .iter()
            .enumerate()
            .map(|(i, v)| {
                let dist = cosine_distance(query, v);
                (i, dist)
            })
            .collect();
        distances.sort_by(|a, b| a.1.partial_cmp(&b.1).unwrap());
        let ground_truth: Vec<usize> = distances.iter().take(k).map(|(i, _)| *i).collect();

        // Calculate recall
        let hits = hnsw_results
            .iter()
            .filter(|id| ground_truth.contains(id))
            .count();
        total_recall += hits as f64 / k as f64;
    }

    let avg_recall = total_recall / n_queries as f64;
    assert!(
        avg_recall >= 0.8,
        "Recall should be at least 80%, got {:.1}%",
        avg_recall * 100.0
    );
}

fn cosine_distance(a: &[f32], b: &[f32]) -> f32 {
    let dot: f32 = a.iter().zip(b.iter()).map(|(x, y)| x * y).sum();
    let norm_a: f32 = a.iter().map(|x| x * x).sum::<f32>().sqrt();
    let norm_b: f32 = b.iter().map(|x| x * x).sum::<f32>().sqrt();
    if norm_a == 0.0 || norm_b == 0.0 {
        1.0
    } else {
        1.0 - (dot / (norm_a * norm_b))
    }
}

#[test]
fn test_cpu_vs_simd_consistency() {
    let cpu_engine = CpuDistance::new(DistanceMetric::Euclidean);
    let simd_engine = SimdDistance::new(DistanceMetric::Euclidean);

    let cpu_hnsw = NativeHnsw::new(cpu_engine, 16, 100, 100);
    let simd_hnsw = NativeHnsw::new(simd_engine, 16, 100, 100);

    // Insert same vectors
    for i in 0..50_u64 {
        let v: Vec<f32> = (0..64).map(|j| (i + j) as f32).collect();
        cpu_hnsw.insert(&v).expect("test");
        simd_hnsw.insert(&v).expect("test");
    }

    // Search should return similar results
    let query: Vec<f32> = (0..64).map(|j| j as f32).collect();
    let cpu_results = cpu_hnsw.search(&query, 5, 30);
    let simd_results = simd_hnsw.search(&query, 5, 30);

    // First result should match
    assert_eq!(
        cpu_results[0].0, simd_results[0].0,
        "CPU and SIMD should find same nearest neighbor"
    );
}

// =============================================================================
// Phase 2: VAMANA α diversification tests (TDD)
// =============================================================================

#[test]
fn test_native_hnsw_with_alpha_diversification() {
    // Test that higher alpha produces more diverse neighbors
    let engine = SimdDistance::new(DistanceMetric::Cosine);

    // Create index with alpha=1.2 (VAMANA-style diversification)
    let hnsw = NativeHnsw::with_alpha(engine, 16, 100, 100, 1.2);

    // Insert clustered vectors (two clusters)
    for i in 0..25_u64 {
        // Cluster 1: vectors near [1, 0, 0, ...]
        let v: Vec<f32> = (0..32)
            .map(|j| {
                if j == 0 {
                    1.0
                } else {
                    (i as f32 + j as f32) * 0.001
                }
            })
            .collect();
        hnsw.insert(&v).expect("test");
    }
    for i in 0..25_u64 {
        // Cluster 2: vectors near [0, 1, 0, ...]
        let v: Vec<f32> = (0..32)
            .map(|j| {
                if j == 1 {
                    1.0
                } else {
                    (i as f32 + j as f32) * 0.001
                }
            })
            .collect();
        hnsw.insert(&v).expect("test");
    }

    assert_eq!(hnsw.len(), 50);

    // Search should work correctly
    let query: Vec<f32> = (0..32).map(|j| if j == 0 { 0.9 } else { 0.01 }).collect();
    let results = hnsw.search(&query, 5, 50);

    assert!(!results.is_empty(), "Should return results");
}

#[test]
fn test_native_hnsw_alpha_default_is_one() {
    // Default alpha should be 1.0 (standard HNSW behavior)
    let engine = SimdDistance::new(DistanceMetric::Euclidean);
    let hnsw = NativeHnsw::new(engine, 16, 100, 100);

    assert!(
        (hnsw.get_alpha() - 1.0).abs() < f32::EPSILON,
        "Default alpha should be 1.0"
    );
}

#[test]
fn test_native_hnsw_alpha_affects_graph_structure() {
    // With alpha > 1.0, the graph should have more diverse connections
    let engine1 = SimdDistance::new(DistanceMetric::Euclidean);
    let engine2 = SimdDistance::new(DistanceMetric::Euclidean);

    let hnsw_standard = NativeHnsw::new(engine1, 16, 100, 100);
    let hnsw_diverse = NativeHnsw::with_alpha(engine2, 16, 100, 100, 1.2);

    // Insert same vectors
    for i in 0..30_u64 {
        let v: Vec<f32> = (0..32).map(|j| (i + j) as f32 * 0.1).collect();
        hnsw_standard.insert(&v).expect("test");
        hnsw_diverse.insert(&v).expect("test");
    }

    // Both should have same count
    assert_eq!(hnsw_standard.len(), hnsw_diverse.len());
}

// =============================================================================
// Phase 3: Multi-Entry Points tests
// =============================================================================

#[test]
fn test_search_multi_entry_returns_results() {
    let engine = SimdDistance::new(DistanceMetric::Cosine);
    let hnsw = NativeHnsw::new(engine, 16, 100, 100);

    // Insert vectors
    for i in 0..50_u64 {
        let v: Vec<f32> = (0..32).map(|j| ((i + j) as f32 * 0.01).sin()).collect();
        hnsw.insert(&v).expect("test");
    }

    let query: Vec<f32> = (0..32).map(|j| (j as f32 * 0.01).sin()).collect();

    // Multi-entry search with 3 probes
    let results = hnsw.search_multi_entry(&query, 5, 50, 3);

    assert!(!results.is_empty(), "Should return results");
    assert!(results.len() <= 5, "Should not exceed k");
}

#[test]
fn test_search_multi_entry_vs_standard() {
    let engine = SimdDistance::new(DistanceMetric::Euclidean);
    let hnsw = NativeHnsw::new(engine, 16, 100, 100);

    // Insert vectors
    for i in 0..30_u64 {
        let v: Vec<f32> = (0..32).map(|j| (i + j) as f32 * 0.1).collect();
        hnsw.insert(&v).expect("test");
    }

    let query: Vec<f32> = (0..32).map(|j| j as f32 * 0.05).collect();

    // Both searches should return results
    let standard = hnsw.search(&query, 5, 50);
    let multi = hnsw.search_multi_entry(&query, 5, 50, 2);

    assert!(!standard.is_empty());
    assert!(!multi.is_empty());
}

// =============================================================================
// BUG-CORE-001: Deadlock Prevention Tests (TDD)
// =============================================================================
// These tests verify that concurrent insert + search operations do not deadlock.
// The root cause was lock order inversion between search_layer (vectors→layers)
// and add_bidirectional_connection (layers→vectors).

#[test]
fn test_concurrent_insert_search_no_deadlock() {
    use std::sync::Arc;
    use std::thread;
    use std::time::Duration;

    let engine = SimdDistance::new(DistanceMetric::Euclidean);
    let hnsw = Arc::new(NativeHnsw::new(engine, 16, 100, 500));

    // Pre-populate with some vectors
    for i in 0..50_u64 {
        let v: Vec<f32> = (0..32).map(|j| (i + j) as f32 * 0.1).collect();
        hnsw.insert(&v).expect("test");
    }

    let mut handles = vec![];

    // Spawn insert threads
    for t in 0..4 {
        let hnsw_clone = Arc::clone(&hnsw);
        handles.push(thread::spawn(move || {
            for i in 0..25_u64 {
                let v: Vec<f32> = (0..32).map(|j| ((t * 100 + i) + j) as f32 * 0.01).collect();
                hnsw_clone.insert(&v).expect("test");
            }
        }));
    }

    // Spawn search threads concurrently
    for _ in 0..4 {
        let hnsw_clone = Arc::clone(&hnsw);
        handles.push(thread::spawn(move || {
            for i in 0..25_u64 {
                let query: Vec<f32> = (0..32).map(|j| (i + j) as f32 * 0.05).collect();
                let _ = hnsw_clone.search(&query, 5, 30);
            }
        }));
    }

    // Wait for all threads with timeout (deadlock detection)
    for handle in handles {
        // If this hangs, we have a deadlock
        let result = handle.join();
        assert!(result.is_ok(), "Thread should complete without panic");
    }

    // Verify index is in consistent state
    assert!(hnsw.len() >= 50, "Should have at least initial vectors");
}

#[test]
fn test_parallel_insert_stress_no_deadlock() {
    use std::sync::Arc;
    use std::thread;

    let engine = SimdDistance::new(DistanceMetric::Cosine);
    let hnsw = Arc::new(NativeHnsw::new(engine, 32, 200, 1000));

    let num_threads = 8;
    let vectors_per_thread = 50;
    let mut handles = vec![];

    // Stress test: many parallel inserts
    for t in 0..num_threads {
        let hnsw_clone = Arc::clone(&hnsw);
        handles.push(thread::spawn(move || {
            for i in 0..vectors_per_thread {
                let idx = t * vectors_per_thread + i;
                let v: Vec<f32> = (0..64)
                    .map(|j| ((idx * 64 + j) as f32 * 0.001).sin())
                    .collect();
                hnsw_clone.insert(&v).expect("test");
            }
        }));
    }

    // All threads must complete (no deadlock)
    for handle in handles {
        handle.join().expect("Thread should not panic");
    }

    // Final count may be less due to race conditions, but should be substantial
    let final_count = hnsw.len();
    assert!(
        final_count >= (num_threads * vectors_per_thread) / 2,
        "Should have inserted many vectors, got {final_count}"
    );

    // Search should still work after parallel inserts
    let query: Vec<f32> = (0..64).map(|j| (j as f32 * 0.001).sin()).collect();
    let results = hnsw.search(&query, 10, 50);
    assert!(
        !results.is_empty(),
        "Search should return results after parallel inserts"
    );
}

#[test]
fn test_mixed_operations_no_deadlock() {
    use std::sync::Arc;
    use std::thread;

    let engine = SimdDistance::new(DistanceMetric::Euclidean);
    let hnsw = Arc::new(NativeHnsw::new(engine, 16, 100, 300));

    // Pre-populate
    for i in 0..30_u64 {
        let v: Vec<f32> = (0..32).map(|j| (i + j) as f32 * 0.1).collect();
        hnsw.insert(&v).expect("test");
    }

    let mut handles = vec![];

    // Mix of operations: insert, search, multi-entry search
    for t in 0..3 {
        let hnsw_clone = Arc::clone(&hnsw);
        handles.push(thread::spawn(move || {
            for i in 0..20_u64 {
                let v: Vec<f32> = (0..32).map(|j| ((t * 100 + i) + j) as f32 * 0.01).collect();
                hnsw_clone.insert(&v).expect("test");
            }
        }));
    }

    for _ in 0..2 {
        let hnsw_clone = Arc::clone(&hnsw);
        handles.push(thread::spawn(move || {
            for i in 0..30_u64 {
                let query: Vec<f32> = (0..32).map(|j| (i + j) as f32 * 0.05).collect();
                let _ = hnsw_clone.search(&query, 5, 30);
            }
        }));
    }

    for _ in 0..2 {
        let hnsw_clone = Arc::clone(&hnsw);
        handles.push(thread::spawn(move || {
            for i in 0..20_u64 {
                let query: Vec<f32> = (0..32).map(|j| (i + j) as f32 * 0.03).collect();
                let _ = hnsw_clone.search_multi_entry(&query, 5, 30, 2);
            }
        }));
    }

    // All threads must complete
    for handle in handles {
        handle
            .join()
            .expect("Thread should complete without deadlock");
    }

    assert!(hnsw.len() >= 30, "Index should have vectors");
}

// =============================================================================
// Phase 3, Plan 04: Concurrency Family 1 — Parallel Insert/Search/Delete
// =============================================================================
// Validates correctness under concurrent operations with explicit invariant
// assertions (not just "no panic"). Exercises lock-order paths and safety
// counters introduced in Plan 03-03.

/// Stress test: concurrent inserts from many threads with deterministic
/// post-condition on total count and graph searchability.
#[test]
fn test_concurrent_insert_deterministic_count() {
    use std::sync::Arc;
    use std::thread;

    let engine = SimdDistance::new(DistanceMetric::Cosine);
    let hnsw = Arc::new(NativeHnsw::new(engine, 16, 100, 2000));

    let num_threads = 8;
    let vectors_per_thread = 100;
    let mut handles = vec![];

    for t in 0..num_threads {
        let hnsw_clone = Arc::clone(&hnsw);
        handles.push(thread::spawn(move || {
            for i in 0..vectors_per_thread {
                let idx = t * vectors_per_thread + i;
                let v: Vec<f32> = (0..64)
                    .map(|j| ((idx * 64 + j) as f32 * 0.001).sin())
                    .collect();
                hnsw_clone.insert(&v).expect("test");
            }
        }));
    }

    for handle in handles {
        handle.join().expect("Thread should complete without panic");
    }

    // Deterministic assertion: all inserts must be reflected in count
    let final_count = hnsw.len();
    assert_eq!(
        final_count,
        num_threads * vectors_per_thread,
        "Every insert must be counted; got {final_count} expected {}",
        num_threads * vectors_per_thread
    );

    // Verify graph is searchable and returns correct k
    let query: Vec<f32> = (0..64).map(|j| (j as f32 * 0.001).sin()).collect();
    let results = hnsw.search(&query, 20, 50);
    assert_eq!(
        results.len(),
        20,
        "Search should return exactly k results from populated graph"
    );
    // Results must be sorted by distance
    for window in results.windows(2) {
        assert!(
            window[0].1 <= window[1].1,
            "Results must be sorted by distance: {} > {}",
            window[0].1,
            window[1].1
        );
    }
}

/// Concurrent insert + search with search correctness assertions.
/// Verifies that search always returns valid node IDs and sorted distances
/// even while inserts are actively modifying the graph.
#[test]
fn test_concurrent_insert_search_correctness() {
    use std::sync::Arc;
    use std::thread;

    let engine = SimdDistance::new(DistanceMetric::Euclidean);
    let hnsw = Arc::new(NativeHnsw::new(engine, 16, 100, 1000));

    // Pre-populate to ensure searches have data
    for i in 0..100_u64 {
        let v: Vec<f32> = (0..32).map(|j| (i + j) as f32 * 0.1).collect();
        hnsw.insert(&v).expect("test");
    }

    let mut handles = vec![];

    // 4 insert threads
    for t in 0..4_u64 {
        let hnsw_clone = Arc::clone(&hnsw);
        handles.push(thread::spawn(move || {
            for i in 0..50_u64 {
                let v: Vec<f32> = (0..32)
                    .map(|j| ((t * 1000 + i) + j) as f32 * 0.01)
                    .collect();
                hnsw_clone.insert(&v).expect("test");
            }
        }));
    }

    // 4 search threads with correctness assertions
    for t in 0..4_u64 {
        let hnsw_clone = Arc::clone(&hnsw);
        handles.push(thread::spawn(move || {
            for i in 0..50_u64 {
                let query: Vec<f32> = (0..32).map(|j| ((t * 500 + i) + j) as f32 * 0.02).collect();
                let results = hnsw_clone.search(&query, 5, 30);
                // Must respect k limit
                assert!(results.len() <= 5, "Search must return at most k results");
                // All returned node IDs must be within valid range
                let current_len = hnsw_clone.len();
                for &(node_id, dist) in &results {
                    assert!(
                        node_id < current_len + 200,
                        "Node ID {node_id} should be in valid range"
                    );
                    assert!(
                        dist.is_finite(),
                        "Distance must be finite, got {dist} for node {node_id}"
                    );
                }
                // Results should be distance-sorted
                for window in results.windows(2) {
                    assert!(
                        window[0].1 <= window[1].1,
                        "Results must be sorted by distance"
                    );
                }
            }
        }));
    }

    for handle in handles {
        handle
            .join()
            .expect("Thread should complete without deadlock");
    }

    // Post-condition: index grew correctly
    let final_count = hnsw.len();
    assert!(
        final_count >= 300,
        "Should have at least 100 initial + 200 inserted, got {final_count}"
    );

    // Safety counters: no invariant violations
    let snapshot = super::graph::safety_counters::HNSW_COUNTERS.snapshot();
    assert_eq!(
        snapshot.invariant_violation_total, 0,
        "Concurrent insert+search must not trigger lock-order violations"
    );
}

/// Concurrent insert + multi-entry search interleaving.
/// Validates that multi-entry search remains consistent under concurrent writes.
#[test]
fn test_concurrent_insert_multi_entry_search() {
    use std::sync::Arc;
    use std::thread;

    let engine = SimdDistance::new(DistanceMetric::Cosine);
    let hnsw = Arc::new(NativeHnsw::new(engine, 16, 100, 600));

    // Pre-populate
    for i in 0..50_u64 {
        let v: Vec<f32> = (0..32).map(|j| ((i + j) as f32 * 0.01).sin()).collect();
        hnsw.insert(&v).expect("test");
    }

    let mut handles = vec![];

    // Inserters
    for t in 0..3_u64 {
        let hnsw_clone = Arc::clone(&hnsw);
        handles.push(thread::spawn(move || {
            for i in 0..30_u64 {
                let v: Vec<f32> = (0..32)
                    .map(|j| ((t * 100 + i) + j) as f32 * 0.005)
                    .collect();
                hnsw_clone.insert(&v).expect("test");
            }
        }));
    }

    // Multi-entry searchers
    for _ in 0..3_u64 {
        let hnsw_clone = Arc::clone(&hnsw);
        handles.push(thread::spawn(move || {
            for i in 0..30_u64 {
                let query: Vec<f32> = (0..32).map(|j| (i + j) as f32 * 0.03).collect();
                let results = hnsw_clone.search_multi_entry(&query, 5, 30, 3);
                assert!(results.len() <= 5, "Multi-entry search must respect k");
                // Verify distance monotonicity
                for window in results.windows(2) {
                    assert!(
                        window[0].1 <= window[1].1,
                        "Multi-entry results must be sorted by distance"
                    );
                }
            }
        }));
    }

    for handle in handles {
        handle.join().expect("Thread must complete (no deadlock)");
    }

    assert!(
        hnsw.len() >= 50,
        "Index must retain at least pre-populated vectors"
    );
}

// =============================================================================
// BUG-04 / QUAL-01: Lock-order safety + observability counters
// =============================================================================

#[test]
fn test_hnsw_no_deadlock_during_parallel_insert_search() {
    use std::sync::Arc;
    use std::thread;

    let engine = SimdDistance::new(DistanceMetric::Cosine);
    let hnsw = Arc::new(NativeHnsw::new(engine, 16, 100, 500));

    // Pre-populate so search has data to traverse
    for i in 0..100_u64 {
        let v: Vec<f32> = (0..64).map(|j| ((i + j) as f32 * 0.01).sin()).collect();
        hnsw.insert(&v).expect("test");
    }

    let mut handles = vec![];

    // 4 insert threads
    for t in 0..4 {
        let hnsw_clone = Arc::clone(&hnsw);
        handles.push(thread::spawn(move || {
            for i in 0..50_u64 {
                let v: Vec<f32> = (0..64)
                    .map(|j| ((t * 1000 + i) + j) as f32 * 0.001)
                    .collect();
                hnsw_clone.insert(&v).expect("test");
            }
        }));
    }

    // 4 search threads
    for t in 0..4 {
        let hnsw_clone = Arc::clone(&hnsw);
        handles.push(thread::spawn(move || {
            for i in 0..50_u64 {
                let query: Vec<f32> = (0..64)
                    .map(|j| ((t * 500 + i) + j) as f32 * 0.002)
                    .collect();
                let results = hnsw_clone.search(&query, 10, 50);
                assert!(
                    results.len() <= 10,
                    "Search should return at most k results"
                );
            }
        }));
    }

    // All threads must complete (no deadlock)
    for handle in handles {
        handle
            .join()
            .expect("Thread should complete without deadlock");
    }

    // Verify consistent state
    let final_count = hnsw.len();
    assert!(
        final_count >= 100,
        "Should have at least initial 100 vectors, got {final_count}"
    );

    // Verify safety counters are accessible and no invariant violations
    let snapshot = super::graph::safety_counters::HNSW_COUNTERS.snapshot();
    assert_eq!(
        snapshot.invariant_violation_total, 0,
        "No lock-order violations should occur with correct lock ordering"
    );
}

// =============================================================================
// Concurrency Family 1b: Delete-Aware Contention (NativeHnswIndex level)
// =============================================================================
// These tests exercise soft-delete paths under concurrent insert/search/delete
// operations to verify tombstone consistency and search exclusion correctness.

#[test]
fn test_concurrent_insert_delete_search_at_index_level() {
    use crate::distance::DistanceMetric as DM;
    use crate::index::hnsw::native_index::NativeHnswIndex;
    use crate::index::VectorIndex;
    use std::sync::Arc;
    use std::thread;

    let index = Arc::new(NativeHnswIndex::new(32, DM::Euclidean).expect("test"));

    // Pre-populate with IDs 0..99
    for i in 0u64..100 {
        let v: Vec<f32> = (0..32).map(|j| (i + j) as f32 * 0.1).collect();
        index.insert(i, &v).expect("test");
    }
    assert_eq!(index.len(), 100);

    let mut handles = vec![];

    // 2 insert threads: IDs 1000..1099
    for t in 0..2u64 {
        let idx = Arc::clone(&index);
        handles.push(thread::spawn(move || {
            for i in 0..50u64 {
                let id = 1000 + t * 50 + i;
                let v: Vec<f32> = (0..32).map(|j| (id + j) as f32 * 0.01).collect();
                idx.insert(id, &v).expect("test");
            }
        }));
    }

    // 2 delete threads: remove IDs 0..49 (soft-delete)
    for t in 0..2u64 {
        let idx = Arc::clone(&index);
        handles.push(thread::spawn(move || {
            for i in 0..25u64 {
                let id = t * 25 + i;
                let _ = idx.remove(id);
            }
        }));
    }

    // 2 search threads: verify search works during mutations
    for _ in 0..2 {
        let idx = Arc::clone(&index);
        handles.push(thread::spawn(move || {
            for i in 0..30u64 {
                let query: Vec<f32> = (0..32).map(|j| (i + j) as f32 * 0.05).collect();
                let results = idx.search(&query, 10);
                // Search results must respect k
                assert!(results.len() <= 10, "Search must respect k limit");
                // All returned IDs must be valid (not deleted from mappings)
                // and distances must be finite
                for sr in &results {
                    assert!(
                        sr.score.is_finite(),
                        "Distance must be finite for ID {}",
                        sr.id
                    );
                }
            }
        }));
    }

    for handle in handles {
        handle
            .join()
            .expect("Thread must complete without deadlock");
    }

    // Post-conditions:
    // NativeHnswIndex::len() returns live mapping count (excluding soft-deletes).
    // Live count = 100 initial + 100 new inserts - 50 deleted = 150
    let live_len = index.len();
    assert_eq!(
        live_len, 150,
        "Live count must reflect inserts minus deletes: got {live_len}"
    );

    // Verify deleted IDs (0..49) are excluded from search results.
    // This is the core soft-delete invariant.
    let query: Vec<f32> = (0..32).map(|j| j as f32 * 0.1).collect();
    let results = index.search(&query, 50);
    for sr in &results {
        assert!(
            !(0..50).contains(&sr.id),
            "Soft-deleted ID {} must not appear in search results",
            sr.id
        );
    }

    // Newly inserted IDs (1000..1099) must be findable
    let query_new: Vec<f32> = (0..32).map(|j| (1050 + j) as f32 * 0.01).collect();
    let results_new = index.search(&query_new, 10);
    assert!(
        !results_new.is_empty(),
        "Newly inserted vectors must be searchable"
    );
}

/// Verify that concurrent deletes + searches never return stale/deleted entries.
#[test]
fn test_delete_exclusion_under_concurrent_search() {
    use crate::distance::DistanceMetric as DM;
    use crate::index::hnsw::native_index::NativeHnswIndex;
    use crate::index::VectorIndex;
    use std::sync::atomic::{AtomicBool, Ordering as AtomOrd};
    use std::sync::Arc;
    use std::thread;

    let index = Arc::new(NativeHnswIndex::new(16, DM::Cosine).expect("test"));

    // Pre-populate with IDs 0..199
    for i in 0u64..200 {
        let v: Vec<f32> = (0..16).map(|j| ((i + j) as f32 * 0.01).sin()).collect();
        index.insert(i, &v).expect("test");
    }

    let violation_found = Arc::new(AtomicBool::new(false));
    let mut handles = vec![];

    // Delete thread: remove even IDs
    {
        let idx = Arc::clone(&index);
        handles.push(thread::spawn(move || {
            for i in (0u64..200).step_by(2) {
                idx.remove(i);
            }
        }));
    }

    // Search threads: check that deleted IDs don't appear after deletion completes
    for _ in 0..4 {
        let idx = Arc::clone(&index);
        let vf = Arc::clone(&violation_found);
        handles.push(thread::spawn(move || {
            for i in 0..50u64 {
                let query: Vec<f32> = (0..16).map(|j| ((i + j) as f32 * 0.02).sin()).collect();
                let results = idx.search(&query, 20);
                // During concurrent deletion, we may or may not see some IDs.
                // But search results must always have finite distances.
                for sr in &results {
                    if !sr.score.is_finite() {
                        vf.store(true, AtomOrd::Relaxed);
                    }
                }
            }
        }));
    }

    for handle in handles {
        handle.join().expect("Thread must complete");
    }

    assert!(
        !violation_found.load(AtomOrd::Relaxed),
        "No non-finite distances should appear during concurrent delete+search"
    );

    // After all deletes complete, live count reflects removed mappings.
    // 200 initial - 100 even IDs deleted = 100 remaining.
    let live_len = index.len();
    assert_eq!(live_len, 100, "Live count must exclude soft-deleted IDs");

    // All even IDs must be gone from search results (soft-delete exclusion).
    let query: Vec<f32> = (0..16).map(|j| (j as f32 * 0.01).sin()).collect();
    let results = index.search(&query, 200);
    for sr in &results {
        assert!(
            sr.id % 2 != 0,
            "Soft-deleted even ID {} must not appear in post-delete search",
            sr.id
        );
    }
    // Verify odd IDs are still returned
    assert!(
        !results.is_empty(),
        "Odd IDs should still be searchable after deleting even IDs"
    );
}

// =============================================================================
// F-22: Pre-normalization for Cosine metric
// =============================================================================

#[test]
fn test_prenormalized_cosine_recall_matches_standard() {
    use super::distance::CachedSimdDistance;

    let dim = 128;

    // Standard (non-prenormalized) cosine index
    let engine_std = SimdDistance::new(DistanceMetric::Cosine);
    let hnsw_std = NativeHnsw::new(engine_std, 16, 100, 500);

    // Pre-normalized cosine index
    let engine_pre = CachedSimdDistance::new_prenormalized(DistanceMetric::Cosine, dim);
    let hnsw_pre = NativeHnsw::new(engine_pre, 16, 100, 500);

    let vectors: Vec<Vec<f32>> = (0..200)
        .map(|i| {
            (0..dim)
                .map(|j| ((i * dim + j) as f32 * 0.001).sin())
                .collect()
        })
        .collect();

    // Insert same vectors into both indexes
    for v in &vectors {
        hnsw_std.insert(v).expect("test");
        hnsw_pre.insert(v).expect("test");
    }

    // Verify search recall for pre-normalized vs standard
    let k = 10;
    for q_idx in [0, 40, 80, 120, 160] {
        let query = &vectors[q_idx];

        let results_std = hnsw_std.search(query, k, 128);
        let results_pre = hnsw_pre.search(query, k, 128);

        // Both should return results
        assert_eq!(results_std.len(), k, "standard should return {k} results");
        assert_eq!(results_pre.len(), k, "prenorm should return {k} results");

        // HNSW is approximate and graph construction is distance-order sensitive.
        // Compare recall quality and best-distance parity instead of exact top-1 ID.
        assert!(
            (results_std[0].1 - results_pre[0].1).abs() < 1e-4,
            "Best distance should stay aligned across cosine paths (q={q_idx})"
        );

        // Verify overlap: at least 80% of top-k results should match
        let std_ids: Vec<usize> = results_std.iter().map(|(id, _)| *id).collect();
        let pre_ids: Vec<usize> = results_pre.iter().map(|(id, _)| *id).collect();
        let overlap = std_ids.iter().filter(|id| pre_ids.contains(id)).count();
        assert!(
            overlap >= k * 8 / 10,
            "Recall overlap too low at q={q_idx}: {overlap}/{k}"
        );
    }
}

#[test]
fn test_prenormalized_search_distances_are_consistent() {
    use super::distance::CachedSimdDistance;

    let dim = 64;
    let engine = CachedSimdDistance::new_prenormalized(DistanceMetric::Cosine, dim);
    let hnsw = NativeHnsw::new(engine, 16, 100, 100);

    for i in 0..50_u64 {
        let v: Vec<f32> = (0..dim)
            .map(|j| ((i + j as u64) as f32 * 0.01).sin())
            .collect();
        hnsw.insert(&v).expect("test");
    }

    let query: Vec<f32> = (0..dim).map(|j| (j as f32 * 0.01).sin()).collect();
    let results = hnsw.search(&query, 10, 50);

    // All distances should be in valid range [0, 2] for cosine
    for &(_, dist) in &results {
        assert!(
            dist.is_finite() && (-1e-6..=2.0 + 1e-6).contains(&dist),
            "Cosine distance {dist} out of valid range"
        );
    }
    // Results should be sorted by distance
    for window in results.windows(2) {
        assert!(
            window[0].1 <= window[1].1,
            "Results must be sorted: {} > {}",
            window[0].1,
            window[1].1
        );
    }
}

#[test]
fn test_safety_counters_accessible_after_operations() {
    let engine = SimdDistance::new(DistanceMetric::Euclidean);
    let hnsw = NativeHnsw::new(engine, 16, 100, 100);

    for i in 0..20_u64 {
        let v: Vec<f32> = (0..32).map(|j| (i + j) as f32 * 0.1).collect();
        hnsw.insert(&v).expect("test");
    }

    let query: Vec<f32> = (0..32).map(|j| j as f32 * 0.05).collect();
    let _ = hnsw.search(&query, 5, 30);

    // Counters should be readable without panic
    let snapshot = super::graph::safety_counters::HNSW_COUNTERS.snapshot();

    // No invariant violations expected with correct lock ordering
    assert_eq!(
        snapshot.invariant_violation_total, 0,
        "Correct lock ordering should produce zero violations"
    );
    // Corruption counter should be zero for normal operations
    assert_eq!(
        snapshot.corruption_detected_total, 0,
        "Normal operations should not trigger corruption signals"
    );
}