hakodb 0.20.1

Embedded & Cloud-native Document Engine
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
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
//! NoSQL-native vector similarity (P0: exact KNN, no ANN structure).
//!
//! Embeddings ride `Value::Binary` as LE `f32[]` — no new `Value` variant,
//! small vectors stay `PutInlined` so the index reads them with zero blob
//! resolution. One metric per index, fixed dim, validated at creation.
//! P1 (HNSW) plugs into the same `VectorDef` registry; P0 exact doubles as
//! its recall oracle.

use crate::error::{HakoError, Result};

/// Distance metric. One per index (like one definition per FTS field).
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum Metric {
    Cosine,
    L2,
    /// Inner product (#141-8): similarity = dot product. As a DISTANCE the
    /// engine exposes the negation (`-dot`), keeping the "lower is closer"
    /// contract every metric shares — including the HNSW comparators, which
    /// are metric-agnostic by construction.
    InnerProduct,
}

impl Metric {
    pub fn from_u32(v: u32) -> Result<Self> {
        match v {
            0 => Ok(Metric::Cosine),
            1 => Ok(Metric::L2),
            2 => Ok(Metric::InnerProduct),
            _ => Err(HakoError::Corrupt(format!(
                "unknown vector metric {v} (0=cosine, 1=l2, 2=inner_product)"
            ))),
        }
    }

    pub fn name(&self) -> &'static str {
        match self {
            Metric::Cosine => "cosine",
            Metric::L2 => "l2",
            Metric::InnerProduct => "inner_product",
        }
    }
}

/// P0 registration: definition only (no RAM structure yet — the P0 scan is
/// brute-force exact). P1's HNSW lives behind this same registry entry.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct VectorDef {
    pub dim: u32,
    pub metric: Metric,
    /// HNSW M override (#141-1). None = per-dim derived (hnsw_m_for_dim).
    #[serde(default)]
    pub m: Option<usize>,
    /// ef_construction override (#141-1). None = per-dim derived.
    #[serde(default)]
    pub ef_construction: Option<usize>,
    /// Query-time beam override (#141-1). None = the executor's derived
    /// formula (max_ids*8, clamped 128/256..20000).
    #[serde(default)]
    pub ef_search: Option<usize>,
}

/// Configurable HNSW parameters (#141-1). `None` fields ride the derived
/// defaults; values validate/clamp when the graph builds (M clamped to
/// 16..=64, ef_construction floored at 32).
#[derive(Debug, Clone, Copy, Default)]
pub struct HnswParams {
    pub m: Option<usize>,
    pub ef_construction: Option<usize>,
    pub ef_search: Option<usize>,
}

/// Max dims per index (Turso allows 65536; embedded starts tighter —
/// loosen when a consumer shows up with bigger models).
pub const MAX_DIM: u32 = 4096;

pub fn validate_dim(dim: u32) -> Result<()> {
    if dim == 0 || dim > MAX_DIM {
        return Err(HakoError::Corrupt(format!(
            "vector dim {dim} out of range 1..={MAX_DIM}"
        )));
    }
    Ok(())
}

/// Decode LE f32s from a `Value::Binary` payload. Length (not dim) is
/// checked here; dim agreement with the index is the caller's job.
pub fn decode_f32s(bytes: &[u8]) -> Result<Vec<f32>> {
    if !bytes.len().is_multiple_of(4) {
        return Err(HakoError::Corrupt(format!(
            "vector bytes {} not a multiple of 4",
            bytes.len()
        )));
    }
    Ok(bytes
        .chunks_exact(4)
        .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]]))
        .collect())
}

/// Encode f32s to the LE Binary carrier.
pub fn encode_f32s(v: &[f32]) -> Vec<u8> {
    let mut out = Vec::with_capacity(v.len() * 4);
    for x in v {
        out.extend_from_slice(&x.to_le_bytes());
    }
    out
}

/// Cosine distance in [0, 2]. Zero-norm inputs (degenerate zero vectors)
/// score 1.0 — maximally dissimilar, never NaN (NaN would poison top-K
/// heaps via total_cmp).
pub fn cosine_distance(a: &[f32], b: &[f32]) -> f64 {
    debug_assert_eq!(a.len(), b.len());
    let (dot, na, nb) = simd::cosine_parts(a, b);
    let denom = na.sqrt() * nb.sqrt();
    if denom == 0.0 {
        return 1.0;
    }
    1.0 - dot / denom
}

/// Squared Euclidean distance (sqrt-free: ordering-identical to L2, and
/// top-K only needs order).
pub fn l2_distance_squared(a: &[f32], b: &[f32]) -> f64 {
    debug_assert_eq!(a.len(), b.len());
    simd::l2_f32_f32(a, b)
}

/// Inner-product DISTANCE (#141-8): negated dot product. Dot itself is a
/// similarity (higher = closer), so the negation preserves the engine's
/// "distance, lower is closer" contract across all three metrics - the
/// HNSW comparators stay metric-agnostic. Unbounded below by design.
pub fn inner_product_distance(a: &[f32], b: &[f32]) -> f64 {
    debug_assert_eq!(a.len(), b.len());
    -simd::dot_f32_f32(a, b)
}

/// Dispatch on the index metric. Length mismatch is a caller bug (the
/// planner gates dim before any row is scored); saturate to +inf so a bad
/// row sorts last instead of panicking a query worker.
pub fn distance(metric: Metric, a: &[f32], b: &[f32]) -> f64 {
    if a.len() != b.len() {
        return f64::INFINITY;
    }
    match metric {
        Metric::Cosine => cosine_distance(a, b),
        Metric::L2 => l2_distance_squared(a, b),
        Metric::InnerProduct => inner_product_distance(a, b),
    }
}

// ---------------------------------------------------------------------------
// V1 (#168 SIMD lever / #172 kajian): runtime-detected AVX2 distance kernels.
//
// Three hot dots pay for this module:
// - rescore (`cosine/l2/ip`): f32·f32 accumulated in f64 — ~20-40 calls/query
// - walk (`q_dist`): f32 query · int8 node, f64 — one per HNSW hop visited
// - construction (`node_dist`): int8·int8 — integer dot, EXACT both paths
//
// AVX2 semantics: per-element rounding stays the scalar two-step (multiply
// rounds, add rounds — Rust contracts no FMA), so lanes compute scalar-
// identical terms; only the addition tree differs (4 partial f64 lanes vs
// sequential). The integer kernel is associative-exact everywhere. Fallback
// = the original sequential loops, so a non-AVX2 machine keeps today's
// arithmetic; each build remains self-deterministic (sorted tiebreaks ride
// id ordering, not distance bits).
mod scalars {
    /// Sequential reference kernels — the ORIGINAL arithmetic, kept as the
    /// non-AVX2 execution path and as the test oracle.
    pub fn dot_f32_i8(q: &[f32], v: &[i8]) -> f64 {
        q.iter().zip(v).map(|(x, b)| *x as f64 * *b as f64).sum()
    }
    pub fn dot_f32_f32(a: &[f32], b: &[f32]) -> f64 {
        a.iter().zip(b).map(|(x, y)| *x as f64 * *y as f64).sum()
    }
    pub fn l2_f32_f32(a: &[f32], b: &[f32]) -> f64 {
        a.iter()
            .zip(b)
            .map(|(x, y)| {
                let d = *x as f64 - *y as f64;
                d * d
            })
            .sum()
    }
    pub fn cosine_parts(a: &[f32], b: &[f32]) -> (f64, f64, f64) {
        let mut dot = 0.0f64;
        let mut na = 0.0f64;
        let mut nb = 0.0f64;
        for i in 0..a.len() {
            let (x, y) = (a[i] as f64, b[i] as f64);
            dot += x * y;
            na += x * x;
            nb += y * y;
        }
        (dot, na, nb)
    }
    pub fn dot_i8_i8(a: &[i8], b: &[i8]) -> i64 {
        a.iter().zip(b).map(|(x, y)| *x as i64 * *y as i64).sum()
    }
}

#[cfg(target_arch = "x86_64")]
mod simd {
    use super::scalars;
    use std::sync::OnceLock;

    pub fn have_avx2() -> bool {
        static OK: OnceLock<bool> = OnceLock::new();
        *OK.get_or_init(|| std::arch::is_x86_feature_detected!("avx2"))
    }

    pub fn dot_f32_i8(q: &[f32], v: &[i8]) -> f64 {
        if have_avx2() {
            unsafe { return dot_f32_i8_avx2(q, v) };
        }
        scalars::dot_f32_i8(q, v)
    }
    pub fn dot_f32_f32(a: &[f32], b: &[f32]) -> f64 {
        if have_avx2() {
            unsafe { return dot_f32_f32_avx2(a, b) };
        }
        scalars::dot_f32_f32(a, b)
    }
    pub fn l2_f32_f32(a: &[f32], b: &[f32]) -> f64 {
        if have_avx2() {
            unsafe { return l2_f32_f32_avx2(a, b) };
        }
        scalars::l2_f32_f32(a, b)
    }
    pub fn cosine_parts(a: &[f32], b: &[f32]) -> (f64, f64, f64) {
        if have_avx2() {
            unsafe { return cosine_parts_avx2(a, b) };
        }
        scalars::cosine_parts(a, b)
    }
    pub fn dot_i8_i8(a: &[i8], b: &[i8]) -> i64 {
        // Exact integer paths — associativity-safe, so AVX2 is bit-identical
        // to the fallback (no reduction-order caveat, unlike the f64 lanes).
        if have_avx2() && a.len() <= 100_000 {
            unsafe { return dot_i8_i8_avx2(a, b) };
        }
        scalars::dot_i8_i8(a, b)
    }

    /// f32·int8 → f64: 8 f32 per iteration; i8 sign-extends to i32 then to
    /// f64 lanes; per lane it keeps multiply-then-add (the scalar's
    /// two-rounding steps elementwise); tail ≤ 7 uses the same scalar
    /// expressions. Horizontal fold order = (l0+l2)+(l1+l3) + tail — fp
    /// addition order differs from sequential, see the module header.
    #[target_feature(enable = "avx2")]
    unsafe fn dot_f32_i8_avx2(q: &[f32], v: &[i8]) -> f64 {
        use std::arch::x86_64::*;
        let n = q.len().min(v.len());
        let limbs = n & !7;
        let mut acc = _mm256_setzero_pd();
        let mut i = 0;
        while i < limbs {
            let x = _mm256_loadu_ps(q.as_ptr().add(i));
            let b32 = _mm256_cvtepi8_epi32(_mm_loadl_epi64(v.as_ptr().add(i) as *const __m128i));
            let xl = _mm256_cvtps_pd(_mm256_castps256_ps128(x));
            let xh = _mm256_cvtps_pd(_mm256_extractf128_ps::<1>(x));
            let bl = _mm256_cvtepi32_pd(_mm256_castsi256_si128(b32));
            let bh = _mm256_cvtepi32_pd(_mm256_extracti128_si256::<1>(b32));
            acc = _mm256_add_pd(acc, _mm256_mul_pd(xl, bl));
            acc = _mm256_add_pd(acc, _mm256_mul_pd(xh, bh));
            i += 8;
        }
        let mut p = fold4(acc);
        while i < n {
            p += q[i] as f64 * v[i] as f64;
            i += 1;
        }
        p
    }

    #[target_feature(enable = "avx2")]
    unsafe fn dot_f32_f32_avx2(a: &[f32], b: &[f32]) -> f64 {
        use std::arch::x86_64::*;
        let n = a.len().min(b.len());
        let limbs = n & !7;
        let mut acc = _mm256_setzero_pd();
        let mut i = 0;
        while i < limbs {
            let x = _mm256_loadu_ps(a.as_ptr().add(i));
            let y = _mm256_loadu_ps(b.as_ptr().add(i));
            let xl = _mm256_cvtps_pd(_mm256_castps256_ps128(x));
            let xh = _mm256_cvtps_pd(_mm256_extractf128_ps::<1>(x));
            let yl = _mm256_cvtps_pd(_mm256_castps256_ps128(y));
            let yh = _mm256_cvtps_pd(_mm256_extractf128_ps::<1>(y));
            acc = _mm256_add_pd(acc, _mm256_mul_pd(xl, yl));
            acc = _mm256_add_pd(acc, _mm256_mul_pd(xh, yh));
            i += 8;
        }
        let mut p = fold4(acc);
        while i < n {
            p += a[i] as f64 * b[i] as f64;
            i += 1;
        }
        p
    }

    #[target_feature(enable = "avx2")]
    unsafe fn l2_f32_f32_avx2(a: &[f32], b: &[f32]) -> f64 {
        use std::arch::x86_64::*;
        let n = a.len().min(b.len());
        let limbs = n & !7;
        let mut acc = _mm256_setzero_pd();
        let mut i = 0;
        while i < limbs {
            let x = _mm256_loadu_ps(a.as_ptr().add(i));
            let y = _mm256_loadu_ps(b.as_ptr().add(i));
            let xl = _mm256_cvtps_pd(_mm256_castps256_ps128(x));
            let xh = _mm256_cvtps_pd(_mm256_extractf128_ps::<1>(x));
            let yl = _mm256_cvtps_pd(_mm256_castps256_ps128(y));
            let yh = _mm256_cvtps_pd(_mm256_extractf128_ps::<1>(y));
            let dl = _mm256_sub_pd(xl, yl);
            let dh = _mm256_sub_pd(xh, yh);
            acc = _mm256_add_pd(acc, _mm256_mul_pd(dl, dl));
            acc = _mm256_add_pd(acc, _mm256_mul_pd(dh, dh));
            i += 8;
        }
        let mut p = fold4(acc);
        while i < n {
            let d = a[i] as f64 - b[i] as f64;
            p += d * d;
            i += 1;
        }
        p
    }

    /// (dot, ‖a‖², ‖b‖²) in one pass — three 4-lane f64 accumulators.
    #[target_feature(enable = "avx2")]
    unsafe fn cosine_parts_avx2(a: &[f32], b: &[f32]) -> (f64, f64, f64) {
        use std::arch::x86_64::*;
        let n = a.len().min(b.len());
        let limbs = n & !7;
        let (mut acc, mut ma, mut mb) = (_mm256_setzero_pd(), _mm256_setzero_pd(), _mm256_setzero_pd());
        let mut i = 0;
        while i < limbs {
            let x = _mm256_loadu_ps(a.as_ptr().add(i));
            let y = _mm256_loadu_ps(b.as_ptr().add(i));
            let (xl, xh) = (_mm256_cvtps_pd(_mm256_castps256_ps128(x)), _mm256_cvtps_pd(_mm256_extractf128_ps::<1>(x)));
            let (yl, yh) = (_mm256_cvtps_pd(_mm256_castps256_ps128(y)), _mm256_cvtps_pd(_mm256_extractf128_ps::<1>(y)));
            acc = _mm256_add_pd(acc, _mm256_mul_pd(xl, yl));
            acc = _mm256_add_pd(acc, _mm256_mul_pd(xh, yh));
            ma = _mm256_add_pd(ma, _mm256_mul_pd(xl, xl));
            ma = _mm256_add_pd(ma, _mm256_mul_pd(xh, xh));
            mb = _mm256_add_pd(mb, _mm256_mul_pd(yl, yl));
            mb = _mm256_add_pd(mb, _mm256_mul_pd(yh, yh));
            i += 8;
        }
        let (mut d, mut n1, mut n2) = (fold4(acc), fold4(ma), fold4(mb));
        while i < n {
            let (x, y) = (a[i] as f64, b[i] as f64);
            d += x * y;
            n1 += x * x;
            n2 += y * y;
            i += 1;
        }
        (d, n1, n2)
    }

    /// Horizontal fold of four f64 lanes: (l0+l2)+(l1+l3) — addition order
    /// differs from sequential, see the module header.
    #[inline]
    unsafe fn fold4(acc: std::arch::x86_64::__m256d) -> f64 {
        use std::arch::x86_64::*;
        let lo = _mm256_extractf128_pd::<0>(acc);
        let hi = _mm256_extractf128_pd::<1>(acc);
        let p2 = _mm_add_pd(lo, hi); // (l0+l2, l1+l3)
        let s = _mm_add_sd(p2, _mm_unpackhi_pd(p2, p2));
        _mm_cvtsd_f64(s)
    }

    /// int8·int8 exact, 32-byte chunks: i16 widen, `madd` pairs (element
    /// products ≤ 16384, pair sums ≤ 32768 — no i16/i32 overflow), i32
    /// lanes folded exactly; tail scalar. Exact for dim ≤ 100k (guarded in
    /// the dispatcher) — else the sequential path (also exact).
    #[target_feature(enable = "avx2")]
    unsafe fn dot_i8_i8_avx2(a: &[i8], b: &[i8]) -> i64 {
        use std::arch::x86_64::*;
        let n = a.len().min(b.len());
        let limbs = n & !31;
        let mut acc = _mm256_setzero_si256();
        let mut i = 0;
        while i < limbs {
            let ax = _mm256_loadu_si256(a.as_ptr().add(i) as *const __m256i);
            let bx = _mm256_loadu_si256(b.as_ptr().add(i) as *const __m256i);
            let al = _mm256_cvtepi8_epi16(_mm256_castsi256_si128(ax));
            let bl = _mm256_cvtepi8_epi16(_mm256_castsi256_si128(bx));
            let ah = _mm256_cvtepi8_epi16(_mm256_extracti128_si256::<1>(ax));
            let bh = _mm256_cvtepi8_epi16(_mm256_extracti128_si256::<1>(bx));
            acc = _mm256_add_epi32(acc, _mm256_madd_epi16(al, bl));
            acc = _mm256_add_epi32(acc, _mm256_madd_epi16(ah, bh));
            i += 32;
        }
        // exact horizontal i32 fold
        let lo = _mm256_extracti128_si256::<0>(acc);
        let hi = _mm256_extracti128_si256::<1>(acc);
        let p = _mm_add_epi32(lo, hi);
        let p2 = _mm_add_epi32(p, _mm_shuffle_epi32::<0b01_01_01_01>(p));
        let p3 = _mm_add_epi32(p2, _mm_shuffle_epi32::<0b10_10_10_10>(p2));
        let mut tot = _mm_cvtsi128_si32(p3) as i64;
        while i < n {
            tot += a[i] as i64 * b[i] as i64;
            i += 1;
        }
        tot
    }
}

#[cfg(not(target_arch = "x86_64"))]
mod simd {
    pub use super::scalars::{cosine_parts, dot_f32_f32, dot_f32_i8, dot_i8_i8, l2_f32_f32};
    pub fn have_avx2() -> bool {
        false
    }
}

// P1: HNSW (in-RAM, per collection+field).
// From-scratch (~200 lines) instead of a new dependency: the algorithm is
// small, the tree already depends on nothing ANN-shaped, and a fixed-seed
// xorshift keeps inserts/searches bit-deterministic for tests. Literate
// parameters (M=16, ef_construction=200) — standard values, not tuned.
//
// Correctness contract with the engine:
// - Deletes are EXTERNAL: nodes are never removed here; the executor
//   filters candidates against storage liveness (same rule as the P0
//   exact scan). Re-put updates the vector in place (links kept —
//   position may be suboptimal, never wrong).
// - `complete` gates ANN use: only a full backfill/rebuild pass sets it.
//   Anything else (fresh registration, stale snapshot skip, clear) leaves
//   brute-force exact in charge — slower, never wrong.
// - NOT persisted to ram_indexes.bin in P1 (rebuild on open; P2 may
//   persist if rebuild proves slow). Sync needs nothing: peers rebuild
//   from the docs they already replicate.

// P3: parameters scale with dim (duel verdict 2026-10-10: fixed M=16
// starves high-dim graphs — recall 0.62 at D=384 vs Turso 0.92).
// M ≈ 3√D mirrors Turso's max_neighbors default; ef_construction steps
// up where int8 routing error compounds (D≥128). D≤16 keeps the old
// values exactly (3√16=12 → clamped to 16; ef 200).
const HNSW_M_MIN: usize = 16;
const HNSW_M_MAX: usize = 64;
const HNSW_EF_CONSTRUCTION_BASE: usize = 200;
const HNSW_EF_CONSTRUCTION_HIGH_DIM: usize = 300;
const HNSW_HIGH_DIM: usize = 128;

/// Neighbor budget for `dim`: clamp(3√D, 16, 64). D=32→17, D=128→34,
/// D=384→59, D=4096→64.
pub fn hnsw_m_for_dim(dim: usize) -> usize {
    let m = (3.0 * (dim as f64).sqrt()).round() as usize;
    m.clamp(HNSW_M_MIN, HNSW_M_MAX)
}

fn hnsw_ef_construction_for_dim(dim: usize) -> usize {
    if dim >= HNSW_HIGH_DIM {
        HNSW_EF_CONSTRUCTION_HIGH_DIM
    } else {
        HNSW_EF_CONSTRUCTION_BASE
    }
}

struct HnswNode {
    /// int8-quantized vector + scale (dequant = iv * scale). Asymmetric
    /// design: docs keep full f32 (exact rescore reads them), the graph
    /// keeps 1 byte/dim. Cosine needs no dequant at all (scale cancels —
    /// see node_dist); L2 folds the scale into one multiply per dim.
    ivec: Vec<i8>,
    scale: f32,
    /// Scale-free shape norm Σivec² (f64: 127²·4096 ≈ 6.6e7 needs the
    /// headroom). Precomputed once — every cosine call reuses it.
    sum_sq: f64,
    /// links[level] = neighbor internal idxs.
    links: Vec<Vec<usize>>,
}

/// Symmetric int8 quantization: scale = max_abs/127 so the largest
/// component maps exactly. Zero vector → all-zero + scale 1 (dequant
/// stays exactly 0, cosine guards still apply downstream).
fn quantize(v: &[f32]) -> (Vec<i8>, f32) {
    let max = v.iter().map(|x| x.abs()).fold(0.0f32, f32::max);
    if max == 0.0 {
        return (vec![0; v.len()], 1.0);
    }
    let s = max / 127.0;
    (
        v.iter()
            .map(|x| (x / s).round().clamp(-128.0, 127.0) as i8)
            .collect(),
        s,
    )
}

#[derive(Clone, Copy)]
struct Cand {
    dist: f64,
    idx: usize,
}

impl PartialEq for Cand {
    fn eq(&self, other: &Self) -> bool {
        self.dist.to_bits() == other.dist.to_bits() && self.idx == other.idx
    }
}
impl Eq for Cand {}
impl PartialOrd for Cand {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}
impl Ord for Cand {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        // Max-heap by distance (farthest on top for eviction), idx
        // breaks ties so the order is total and deterministic. NaN-free
        // by construction (see cosine_distance), so total_cmp is exact.
        self.dist
            .total_cmp(&other.dist)
            .then_with(|| self.idx.cmp(&other.idx))
    }
}

pub struct HnswIndex {
    dim: usize,
    metric: Metric,
    /// Per-dim budgets (see hnsw_m_for_dim): M neighbors kept,
    /// Mmax/Mmax0 link caps, ef_construction beam at build.
    m: usize,
    mmax: usize,
    mmax0: usize,
    ef_construction: usize,
    level_mult: f64,
    nodes: Vec<HnswNode>,
    id_to_idx: std::collections::HashMap<String, usize>,
    /// Reverse map: internal idx → doc id. Stable — nodes are never
    /// removed (deletes are external), so idxs never shift.
    idx_to_id: Vec<String>,
    entry: Option<usize>,
    rng: u64,
    complete: bool,
}

impl HnswIndex {
    pub fn new(dim: usize, metric: Metric, params: HnswParams) -> Self {
        // Overrides (#141-1) clamp to the envelopes the derived defaults
        // use: M within 16..=64, ef_construction floored at 32.
        let m = params
            .m
            .unwrap_or_else(|| hnsw_m_for_dim(dim))
            .clamp(HNSW_M_MIN, HNSW_M_MAX);
        Self {
            dim,
            metric,
            m,
            mmax: m,
            mmax0: 2 * m,
            ef_construction: params
                .ef_construction
                .unwrap_or_else(|| hnsw_ef_construction_for_dim(dim))
                .max(32),
            level_mult: 1.0 / (m as f64).ln(),
            nodes: Vec::new(),
            id_to_idx: std::collections::HashMap::new(),
            idx_to_id: Vec::new(),
            entry: None,
            // Fixed seed: deterministic inserts/searches across runs
            // (tests pin behavior); randomness quality is irrelevant —
            // levels only need geometric spread, not crypto.
            rng: 0x9E3779B97F4A7C15,
            complete: false,
        }
    }

    pub fn len(&self) -> usize {
        self.nodes.len()
    }

    pub fn is_empty(&self) -> bool {
        self.nodes.is_empty()
    }

    pub fn complete(&self) -> bool {
        self.complete
    }

    /// Rough resident-bytes estimate (#141-7): quantized vectors (1
    /// byte/dim + scale + shape norm), neighbor lists at CAP (level 0
    /// keeps `mmax0`, upper levels `mmax`), and the id maps (~2 × 24 B
    /// per entry). Upper levels are usually sparse, so this over-counts —
    /// it is an upper bound, documented as such.
    pub fn bytes_estimate(&self) -> u64 {
        let n = self.nodes.len() as u64;
        if n == 0 {
            return 0;
        }
        let vec_bytes = self.dim as u64 + 16;
        let links_bytes = 8 * (self.mmax0 as u64 + self.mmax as u64);
        let id_bytes = 48; // id_to_idx + idx_to_id entry, ~2 × 24 B
        n * (vec_bytes + links_bytes + id_bytes)
    }

    pub fn set_complete(&mut self, v: bool) {
        self.complete = v;
    }

    pub fn clear(&mut self) {
        self.nodes.clear();
        self.id_to_idx.clear();
        self.idx_to_id.clear();
        self.entry = None;
        self.complete = false;
    }

    /// Doc id for an internal idx from `search` (caller-verified in range).
    pub fn id_of(&self, idx: usize) -> &str {
        &self.idx_to_id[idx]
    }

    fn next_random(&mut self) -> f64 {
        // xorshift64*: (0,1]-ish; clamp away from 0 so ln() stays finite.
        self.rng ^= self.rng << 13;
        self.rng ^= self.rng >> 7;
        self.rng ^= self.rng << 17;
        ((self.rng >> 11) as f64) / ((1u64 << 53) as f64).max(f64::MIN_POSITIVE)
    }

    fn random_level(&mut self) -> usize {
        (-self.next_random().ln() * self.level_mult) as usize
    }

    /// Σq² for a full-precision query (precomputed once per search/insert,
    /// reused by every distance call on the path).
    fn query_norm_sq(q: &[f32]) -> f64 {
        q.iter().map(|x| (*x as f64) * (*x as f64)).sum()
    }

    /// Query(full f32) vs node(int8): asymmetric by design — the query
    /// stays full precision, the node dequantizes implicitly. Cosine's
    /// scale cancels (shape-only); L2 folds scale into the dot term.
    /// Zero-norm either side → 1.0 (cosine) — same guard as the exact path.
    fn q_dist(&self, q: &[f32], qn: f64, idx: usize) -> f64 {
        let n = &self.nodes[idx];
        let dot = simd::dot_f32_i8(q, &n.ivec);
        match self.metric {
            Metric::Cosine => {
                let denom = qn.sqrt() * n.sum_sq.sqrt();
                if denom == 0.0 { 1.0 } else { 1.0 - dot / denom }
            }
            Metric::L2 => {
                let s = n.scale as f64;
                qn + s * s * n.sum_sq - 2.0 * s * dot
            }
            // IP on quantized bytes: the node vector is scale*ivec, so the
            // true dot - and its negated distance - needs the scale back.
            Metric::InnerProduct => -(n.scale as f64) * dot,
        }
    }

    /// Node vs node on quantized bytes (integer dot, exact): drives the
    /// diversity heuristic and link shrinking without any dequant
    /// temporaries.
    fn node_dist(&self, a: usize, b: usize) -> f64 {
        let (na, nb) = (&self.nodes[a], &self.nodes[b]);
        let dot = simd::dot_i8_i8(&na.ivec, &nb.ivec);
        match self.metric {
            Metric::Cosine => {
                let denom = (na.sum_sq * nb.sum_sq).sqrt();
                if denom == 0.0 { 1.0 } else { 1.0 - dot as f64 / denom }
            }
            Metric::L2 => {
                let (sa, sb) = (na.scale as f64, nb.scale as f64);
                sa * sa * na.sum_sq + sb * sb * nb.sum_sq - 2.0 * sa * sb * dot as f64
            }
            Metric::InnerProduct => -(na.scale as f64) * (nb.scale as f64) * (dot as f64),
        }
    }

    /// Insert or update. Wrong-dim vectors are ignored (fail-closed, same
    /// rule as the planner gate). Updates re-quantize in place and keep
    /// existing links.
    pub fn upsert(&mut self, id: &str, vec: Vec<f32>) {
        if vec.len() != self.dim {
            return;
        }
        if let Some(&idx) = self.id_to_idx.get(id) {
            let (ivec, scale) = quantize(&vec);
            let n = &mut self.nodes[idx];
            n.sum_sq = ivec.iter().map(|x| (*x as f64) * (*x as f64)).sum();
            n.ivec = ivec;
            n.scale = scale;
            return;
        }
        let level = self.random_level();
        let idx = self.nodes.len();
        let (ivec, scale) = quantize(&vec);
        let sum_sq = ivec.iter().map(|x| (*x as f64) * (*x as f64)).sum();
        self.nodes.push(HnswNode {
            ivec,
            scale,
            sum_sq,
            links: vec![Vec::new(); level + 1],
        });
        self.id_to_idx.insert(id.to_string(), idx);
        self.idx_to_id.push(id.to_string());

        let Some(mut cur) = self.entry else {
            self.entry = Some(idx);
            return;
        };
        let top = self.nodes[cur].links.len() - 1;
        // Insert-time routing uses the FULL-precision vector (better than
        // the quantized copy the node now stores).
        let qn = Self::query_norm_sq(&vec);
        // Greedy descent to the insertion levels.
        for l in ((level + 1)..=top).rev() {
            cur = self.greedy_closest(&vec, qn, cur, l);
        }
        for l in (0..=level.min(top)).rev() {
            let cand = self.search_layer(&vec, qn, &[cur], self.ef_construction, l);
            if cand.is_empty() {
                continue;
            }
            // Select M (link caps enforced separately by shrink).
            let neighbors = self.select_neighbors(cand, self.m);
            if neighbors.is_empty() {
                continue;
            }
            cur = neighbors[0];
            let mmax = if l == 0 { self.mmax0 } else { self.mmax };
            for nb in &neighbors {
                self.add_link(idx, *nb, l);
                self.add_link(*nb, idx, l);
            }
            self.shrink_links(idx, l, mmax);
            for nb in &neighbors {
                self.shrink_links(*nb, l, mmax);
            }
        }
        if level > top {
            self.entry = Some(idx);
        }
    }

    /// Greedy single-best descent at one level (ef=1 beam).
    fn greedy_closest(&self, q: &[f32], qn: f64, entry: usize, level: usize) -> usize {
        let mut best = entry;
        let mut best_d = self.q_dist(q, qn, entry);
        // ponytail: fixed-point loop, not a worklist — one pass per
        // improvement, terminates when no neighbor is closer.
        loop {
            let mut improved = false;
            for &nb in &self.nodes[best].links[level] {
                let d = self.q_dist(q, qn, nb);
                if d < best_d {
                    best_d = d;
                    best = nb;
                    improved = true;
                }
            }
            if !improved {
                return best;
            }
        }
    }

    /// Beam search at one level from `entries`, keeping `ef` best.
    /// Returns (dist, idx) sorted ascending. `visited`/`tag` dedupe across
    /// layers without a HashSet alloc per call.
    fn search_layer(
        &self,
        q: &[f32],
        qn: f64,
        entries: &[usize],
        ef: usize,
        level: usize,
    ) -> Vec<(f64, usize)> {
        use std::collections::BinaryHeap;
        use std::cmp::Reverse;
        let ef = ef.max(1);
        let mut visited = vec![false; self.nodes.len()];
        let mut cands: BinaryHeap<Reverse<Cand>> = BinaryHeap::new();
        let mut result: BinaryHeap<Cand> = BinaryHeap::new();
        for &e in entries {
            if e < self.nodes.len() && !visited[e] {
                visited[e] = true;
                let d = self.q_dist(q, qn, e);
                cands.push(Reverse(Cand { dist: d, idx: e }));
                result.push(Cand { dist: d, idx: e });
                if result.len() > ef {
                    result.pop();
                }
            }
        }
        while let Some(Reverse(c)) = cands.pop() {
            // Stop when the closest unexpanded candidate is farther than
            // the worst kept result — nothing beyond can improve it.
            if result.len() >= ef {
                if let Some(worst) = result.peek() {
                    if c.dist > worst.dist {
                        break;
                    }
                }
            }
            for &nb in &self.nodes[c.idx].links[level] {
                if !visited[nb] {
                    visited[nb] = true;
                    let d = self.q_dist(q, qn, nb);
                    let mut push = result.len() < ef;
                    if !push {
                        if let Some(worst) = result.peek() {
                            push = d < worst.dist;
                        }
                    }
                    if push {
                        cands.push(Reverse(Cand { dist: d, idx: nb }));
                        result.push(Cand { dist: d, idx: nb });
                        if result.len() > ef {
                            result.pop();
                        }
                    }
                }
            }
        }
        let mut out: Vec<(f64, usize)> = result.into_iter().map(|c| (c.dist, c.idx)).collect();
        out.sort_by(|a, b| a.0.total_cmp(&b.0).then_with(|| a.1.cmp(&b.1)));
        out
    }

    /// Standard HNSW neighbor-selection heuristic: closest first, keep a
    /// candidate only if no kept neighbor lies between it and the query
    /// (diversity over raw proximity — what keeps recall high on
    /// clustered data vs naive keep-M-closest). `cand` carries
    /// query-distances, so q itself is not needed.
    fn select_neighbors(&self, mut cand: Vec<(f64, usize)>, m: usize) -> Vec<usize> {
        cand.sort_by(|a, b| a.0.total_cmp(&b.0).then_with(|| a.1.cmp(&b.1)));
        let mut out: Vec<usize> = Vec::with_capacity(m);
        'next: for (d, idx) in cand {
            for &kept in &out {
                if self.node_dist(idx, kept) < d {
                    continue 'next;
                }
            }
            out.push(idx);
            if out.len() >= m {
                break;
            }
        }
        out
    }

    fn add_link(&mut self, a: usize, b: usize, level: usize) {
        if a == b {
            return;
        }
        if !self.nodes[a].links[level].contains(&b) {
            self.nodes[a].links[level].push(b);
        }
    }

    fn shrink_links(&mut self, idx: usize, level: usize, mmax: usize) {
        if self.nodes[idx].links[level].len() <= mmax {
            return;
        }
        let cand: Vec<(f64, usize)> = self.nodes[idx].links[level]
            .iter()
            .map(|&nb| (self.node_dist(idx, nb), nb))
            .collect();
        self.nodes[idx].links[level] = self.select_neighbors(cand, mmax);
    }

    /// Top-`ef` candidate internal idxs for `query`, nearest-first.
    /// Callers map idx → doc id, verify liveness/filters, and exact-rescore.
    pub fn search(&self, query: &[f32], ef: usize) -> Vec<(f64, usize)> {
        let entry = match self.entry {
            Some(e) => e,
            None => return Vec::new(),
        };
        if query.len() != self.dim {
            return Vec::new();
        }
        let qn = Self::query_norm_sq(query);
        let top = self.nodes[entry].links.len() - 1;
        let mut cur = entry;
        for l in (1..=top).rev() {
            cur = self.greedy_closest(query, qn, cur, l);
        }
        self.search_layer(query, qn, &[cur], ef, 0)
    }
}

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

    #[test]
    fn cosine_basics() {
        let a = vec![1.0, 0.0];
        assert_eq!(cosine_distance(&a, &a), 0.0);
        // Orthogonal => 1.0.
        assert!((cosine_distance(&a, &[0.0, 1.0]) - 1.0).abs() < 1e-6);
        // Opposite => 2.0. Scale-invariant.
        assert!((cosine_distance(&a, &[-3.0, 0.0]) - 2.0).abs() < 1e-6);
        assert!((cosine_distance(&[2.0, 0.0], &[5.0, 0.0])).abs() < 1e-6);
    }

    #[test]
    fn cosine_zero_vector_never_nan() {
        let d = cosine_distance(&[0.0, 0.0], &[1.0, 2.0]);
        assert!(d.is_finite());
        assert_eq!(d, 1.0);
        assert!(cosine_distance(&[0.0], &[0.0]).is_finite());
    }

    #[test]
    fn l2_squared_ordering() {
        let q = vec![1.0, 1.0];
        // (3,4)-offset => 9+... (dx=2,dy=2) => 8; (dx=1,dy=0) => 1.
        assert_eq!(l2_distance_squared(&q, &[3.0, 3.0]), 8.0);
        assert_eq!(l2_distance_squared(&q, &[2.0, 1.0]), 1.0);
        assert_eq!(l2_distance_squared(&q, &q), 0.0);
    }

    /// V1 SIMD kernels agree with the sequential oracle: fp kernels within
    /// 1e-9 (AVX folds 4 lanes — addition order, not element math, differs),
    /// int8·int8 bit-exact (integer associativity).
    #[test]
    fn simd_kernels_match_sequential() {
        let f = |i: usize| ((i % 13) as f32 / 7.0) - 0.9 + (i % 5) as f32 * 0.01;
        let g = |i: usize| ((i * 11 + 3) % 17) as f32 / 9.0 - 1.0;
        for n in [1usize, 7, 8, 9, 32, 33, 96, 4096] {
            let a: Vec<f32> = (0..n).map(f).collect();
            let b: Vec<f32> = (0..n).map(g).collect();
            let (d, na, nb) = simd::cosine_parts(&a, &b);
            let s = scalars::cosine_parts(&a, &b);
            let tol = 1e-9 * (n as f64).max(1.0);
            assert!((d - s.0).abs() <= tol, "cosine dot n={n}: {} vs {}", d, s.0);
            assert!((na - s.1).abs() <= tol, "norm a n={n}");
            assert!((nb - s.2).abs() <= tol, "norm b n={n}");
            assert!((simd::l2_f32_f32(&a, &b) - scalars::l2_f32_f32(&a, &b)).abs() <= tol);
            assert!((simd::dot_f32_f32(&a, &b) - scalars::dot_f32_f32(&a, &b)).abs() <= tol);
            let q8: Vec<i8> = (0..n).map(|i| ((i * 7 + 1) % 251) as i64 as i8).collect();
            let v8: Vec<i8> = (0..n).map(|i| ((i * 5 + 2) % 255) as i64 as i8).collect();
            assert_eq!(
                simd::dot_i8_i8(&q8, &v8),
                scalars::dot_i8_i8(&q8, &v8),
                "int8 dot n={n}"
            );
            assert_eq!(simd::dot_i8_i8(&v8, &q8), scalars::dot_i8_i8(&v8, &q8));
            // f32·i8 with the same int8 fixtures
            let qf: Vec<f32> = v8.iter().map(|x| *x as f32 * 0.5).collect();
            assert!(
                (simd::dot_f32_i8(&qf, &q8) - scalars::dot_f32_i8(&qf, &q8)).abs()
                    <= tol * 2.0
            );
        }
    }

    #[test]
    fn roundtrip_bytes() {
        let v = vec![0.5, -1.25, 3.0];
        let b = encode_f32s(&v);
        assert_eq!(b.len(), 12);
        assert_eq!(decode_f32s(&b).expect("decode"), v);
        assert!(decode_f32s(&b[..5]).is_err());
    }

    #[test]
    fn dim_mismatch_sorts_last() {
        assert_eq!(distance(Metric::Cosine, &[1.0], &[1.0, 2.0]), f64::INFINITY);
    }

    #[test]
    fn metric_names() {
        assert_eq!(Metric::from_u32(0).expect("m"), Metric::Cosine);
        assert_eq!(Metric::from_u32(1).expect("m"), Metric::L2);
        assert!(Metric::from_u32(7).is_err());
        assert_eq!(Metric::Cosine.name(), "cosine");
    }

    #[test]
    fn dim_scaled_params() {
        // P3 duel verdict: clamp(3√D,16,64); D≤16 keeps legacy values.
        assert_eq!(hnsw_m_for_dim(2), 16);
        assert_eq!(hnsw_m_for_dim(16), 16);
        assert_eq!(hnsw_m_for_dim(32), 17);
        assert_eq!(hnsw_m_for_dim(128), 34);
        assert_eq!(hnsw_m_for_dim(384), 59);
        assert_eq!(hnsw_m_for_dim(4096), 64);
        let lo = HnswIndex::new(8, Metric::Cosine, HnswParams::default());
        assert_eq!((lo.m, lo.mmax, lo.mmax0, lo.ef_construction), (16, 16, 32, 200));
        let hi = HnswIndex::new(384, Metric::Cosine, HnswParams::default());
        assert_eq!((hi.m, hi.mmax, hi.mmax0, hi.ef_construction), (59, 59, 118, 300));
    }

    #[test]
    fn hnsw_recall_high_dim() {
        // P3 gate: 300 pts dim 128 (the slope that warned at 0.94) must
        // clear 0.95 at the wider beam M=34/ef=256 pairing the executor
        // now uses for D≥128.
        let mut rng = FixtureRng(0x51);
        let pts: Vec<Vec<f32>> = (0..300).map(|_| (0..128).map(|_| rng.next_f32()).collect()).collect();
        let queries: Vec<Vec<f32>> = (0..10).map(|_| (0..128).map(|_| rng.next_f32()).collect()).collect();
        let r = hnsw_recall(&pts, &queries, 10, Metric::Cosine, 256);
        assert!(r >= 0.95, "high-dim recall {r}");
    }

    #[test]
    fn quantize_error_bound() {
        // Half-step bound: |dequant - x| <= s/2 (+ float dust).
        let v: Vec<f32> = (0..64).map(|i| ((i * 37) % 101) as f32 / 50.0 - 1.0).collect();
        let (iv, s) = quantize(&v);
        assert_eq!(iv.len(), 64);
        assert!((s - 1.0 / 127.0).abs() < 1e-9, "max_abs=1 => s=1/127, got {s}");
        for (i, &x) in v.iter().enumerate() {
            assert!((iv[i] as f32 * s - x).abs() <= s / 2.0 + 1e-6, "i={i} x={x}");
        }
        let (z, s0) = quantize(&[0.0; 8]);
        assert!(z.iter().all(|&x| x == 0));
        assert_eq!(s0, 1.0);
    }

    // --- P1 HNSW ---

    fn brute_top(q: &[f32], pts: &[Vec<f32>], k: usize, m: Metric) -> Vec<usize> {
        let mut scored: Vec<(f64, usize)> = pts
            .iter()
            .enumerate()
            .map(|(i, p)| (distance(m, q, p), i))
            .collect();
        scored.sort_by(|a, b| a.0.total_cmp(&b.0).then_with(|| a.1.cmp(&b.1)));
        scored.into_iter().take(k).map(|(_, i)| i).collect()
    }

    /// Deterministic PRNG (xorshift64, fixed seed) — fixtures must not
    /// depend on global RNG state.
    struct FixtureRng(u64);
    impl FixtureRng {
        fn next_f32(&mut self) -> f32 {
            self.0 ^= self.0 << 13;
            self.0 ^= self.0 >> 7;
            self.0 ^= self.0 << 17;
            ((self.0 >> 11) as f64 / (1u64 << 53) as f64) as f32 * 2.0 - 1.0
        }
    }

    fn hnsw_recall(pts: &[Vec<f32>], queries: &[Vec<f32>], k: usize, m: Metric, ef: usize) -> f64 {
        let dim = pts[0].len();
        let mut h = HnswIndex::new(dim, m, HnswParams::default());
        for (i, p) in pts.iter().enumerate() {
            h.upsert(&i.to_string(), p.clone());
        }
        let mut hit = 0usize;
        for q in queries {
            let want = brute_top(q, pts, k, m);
            let got: Vec<usize> = h
                .search(q, ef)
                .into_iter()
                .take(k)
                .map(|(_, idx)| idx)
                .collect();
            for id in &got {
                if want.contains(id) {
                    hit += 1;
                }
            }
        }
        hit as f64 / (queries.len() * k) as f64
    }

    #[test]
    fn hnsw_tiny_is_exact() {
        let pts = vec![
            vec![1.0, 0.0],
            vec![0.0, 1.0],
            vec![1.0, 1.0],
            vec![10.0, 0.0],
        ];
        assert_eq!(hnsw_recall(&pts, &pts, 2, Metric::Cosine, 10), 1.0);
        assert_eq!(hnsw_recall(&pts, &pts, 4, Metric::L2, 10), 1.0);
    }

    #[test]
    fn hnsw_recall_on_random() {
        // 500 pts, dim 16, uniform in [-1,1): ANN must (near-)match the
        // P0 exact oracle. Deterministic seed — same graph every run.
        let mut rng = FixtureRng(0x12345678);
        let pts: Vec<Vec<f32>> = (0..500).map(|_| (0..16).map(|_| rng.next_f32()).collect()).collect();
        let queries: Vec<Vec<f32>> = (0..20).map(|_| (0..16).map(|_| rng.next_f32()).collect()).collect();
        let r_cos = hnsw_recall(&pts, &queries, 10, Metric::Cosine, 100);
        let r_l2 = hnsw_recall(&pts, &queries, 10, Metric::L2, 100);
        assert!(r_cos >= 0.95, "cosine recall {r_cos}");
        assert!(r_l2 >= 0.95, "l2 recall {r_l2}");
    }

    #[test]
    fn hnsw_update_and_wrong_dim() {
        let mut h = HnswIndex::new(2, Metric::L2, HnswParams::default());
        h.upsert("a", vec![0.0, 0.0]);
        h.upsert("b", vec![10.0, 0.0]);
        let top: Vec<usize> = h.search(&[0.1, 0.0], 2).into_iter().map(|(_, i)| i).collect();
        assert_eq!(top[0], h.id_to_idx["a"]);
        // Move b strictly closer to the query: update-in-place must
        // take effect (exact ties break by insertion idx, so offset it).
        h.upsert("b", vec![0.05, 0.0]);
        let top: Vec<usize> = h.search(&[0.1, 0.0], 2).into_iter().map(|(_, i)| i).collect();
        assert_eq!(top[0], h.id_to_idx["b"]);
        // Wrong dim ignored, count unchanged.
        h.upsert("c", vec![1.0, 2.0, 3.0]);
        assert_eq!(h.len(), 2);
        assert!(!h.id_to_idx.contains_key("c"));
    }

    #[test]
    fn hnsw_clear_and_determinism() {
        let mut h1 = HnswIndex::new(2, Metric::Cosine, HnswParams::default());
        let mut h2 = HnswIndex::new(2, Metric::Cosine, HnswParams::default());
        for i in 0..50 {
            let v = vec![i as f32 * 0.1, (i % 7) as f32];
            h1.upsert(&i.to_string(), v.clone());
            h2.upsert(&i.to_string(), v);
        }
        let q = vec![1.0, 1.0];
        let r1: Vec<(u64, usize)> = h1.search(&q, 5).into_iter().map(|(d, i)| (d.to_bits(), i)).collect();
        let r2: Vec<(u64, usize)> = h2.search(&q, 5).into_iter().map(|(d, i)| (d.to_bits(), i)).collect();
        assert_eq!(r1, r2, "fixed seed => identical graphs");
        h1.clear();
        assert!(h1.is_empty());
        assert!(h1.search(&q, 5).is_empty());
        assert!(!h1.complete());
    }
}