rabitq-rs 0.9.0

Advanced vector search: RaBitQ quantization with IVF and MSTG (Multi-Scale Tree Graph) index
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
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
use std::cmp::Ordering;
use std::collections::BinaryHeap;
use std::convert::TryFrom;
use std::fs::File;
use std::io::{self, BufReader, BufWriter, Read, Write};
use std::path::Path;

use crc32fast::Hasher;

use rand::prelude::*;
use rayon::prelude::*;
use roaring::RoaringBitmap;

use crate::kmeans::{run_kmeans, KMeansResult};
use crate::math::{dot, l2_distance_sqr};
use crate::quantizer::{quantize_with_centroid, QuantizedVector, RabitqConfig};
use crate::rotation::{DynamicRotator, RotatorType};
use crate::simd;
use crate::{Metric, RabitqError};

/// Parameters for IVF search.
#[derive(Debug, Clone, Copy)]
pub struct SearchParams {
    pub top_k: usize,
    pub nprobe: usize,
}

fn write_u32<W: Write>(writer: &mut W, value: u32, hasher: Option<&mut Hasher>) -> io::Result<()> {
    let bytes = value.to_le_bytes();
    if let Some(h) = hasher {
        h.update(&bytes);
    }
    writer.write_all(&bytes)
}

fn write_u64<W: Write>(writer: &mut W, value: u64, hasher: Option<&mut Hasher>) -> io::Result<()> {
    let bytes = value.to_le_bytes();
    if let Some(h) = hasher {
        h.update(&bytes);
    }
    writer.write_all(&bytes)
}

fn write_f32<W: Write>(writer: &mut W, value: f32, hasher: Option<&mut Hasher>) -> io::Result<()> {
    let bytes = value.to_le_bytes();
    if let Some(h) = hasher {
        h.update(&bytes);
    }
    writer.write_all(&bytes)
}

fn read_u8<R: Read>(reader: &mut R, hasher: Option<&mut Hasher>) -> io::Result<u8> {
    let mut buf = [0u8; 1];
    reader.read_exact(&mut buf)?;
    if let Some(h) = hasher {
        h.update(&buf);
    }
    Ok(buf[0])
}

fn read_u32<R: Read>(reader: &mut R, hasher: Option<&mut Hasher>) -> io::Result<u32> {
    let mut buf = [0u8; 4];
    reader.read_exact(&mut buf)?;
    if let Some(h) = hasher {
        h.update(&buf);
    }
    Ok(u32::from_le_bytes(buf))
}

fn read_u64<R: Read>(reader: &mut R, hasher: Option<&mut Hasher>) -> io::Result<u64> {
    let mut buf = [0u8; 8];
    reader.read_exact(&mut buf)?;
    if let Some(h) = hasher {
        h.update(&buf);
    }
    Ok(u64::from_le_bytes(buf))
}

fn read_f32<R: Read>(reader: &mut R, hasher: Option<&mut Hasher>) -> io::Result<f32> {
    let mut buf = [0u8; 4];
    reader.read_exact(&mut buf)?;
    if let Some(h) = hasher {
        h.update(&buf);
    }
    Ok(f32::from_le_bytes(buf))
}

fn usize_from_u64(value: u64) -> Result<usize, RabitqError> {
    usize::try_from(value)
        .map_err(|_| RabitqError::InvalidPersistence("value exceeds platform limits"))
}

fn metric_to_tag(metric: Metric) -> u8 {
    match metric {
        Metric::L2 => 0,
        Metric::InnerProduct => 1,
    }
}

fn tag_to_metric(tag: u8) -> Option<Metric> {
    match tag {
        0 => Some(Metric::L2),
        1 => Some(Metric::InnerProduct),
        _ => None,
    }
}

impl SearchParams {
    pub fn new(top_k: usize, nprobe: usize) -> Self {
        Self { top_k, nprobe }
    }
}

/// Result entry returned by IVF search.
#[derive(Debug, Clone, PartialEq)]
pub struct SearchResult {
    pub id: usize,
    pub score: f32,
}

#[derive(Debug, Default, Clone)]
pub(crate) struct SearchDiagnostics {
    pub estimated: usize,
    pub skipped_by_lower_bound: usize,
    pub extended_evaluations: usize,
}

const PERSIST_MAGIC: [u8; 4] = *b"RBQ1";
const PERSIST_VERSION: u32 = 3; // V3: Unified memory layout with ClusterData

// ============================================================================
// Unified Memory Layout Data Structures (Phase 1 Optimization)
// ============================================================================

/// Generic 64-byte cache line aligned wrapper
/// Ensures data is aligned to cache line boundaries for optimal performance
#[repr(C, align(64))]
#[derive(Debug, Clone)]
#[allow(dead_code)]
struct AlignedVec<T> {
    data: Vec<T>,
}

impl<T> AlignedVec<T> {
    #[allow(dead_code)]
    fn new() -> Self {
        Self { data: Vec::new() }
    }

    #[allow(dead_code)]
    fn with_capacity(capacity: usize) -> Self {
        Self {
            data: Vec::with_capacity(capacity),
        }
    }
}

impl<T> std::ops::Deref for AlignedVec<T> {
    type Target = Vec<T>;

    fn deref(&self) -> &Self::Target {
        &self.data
    }
}

impl<T> std::ops::DerefMut for AlignedVec<T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.data
    }
}

/// Unified cluster data with contiguous memory layout
/// Eliminates V1/V2 split and scattered allocations
/// Reference: OPTIMIZATION_PLAN.md Phase 1
/// 64-byte cache line aligned for better cache efficiency
#[repr(C, align(64))]
#[derive(Debug, Clone)]
struct ClusterData {
    /// Cluster centroid
    centroid: Vec<f32>,

    /// Vector IDs (all vectors in cluster)
    ids: Vec<usize>,

    /// Single contiguous memory block for all batches
    /// Layout: [Batch 0][Batch 1]...[Batch N]
    /// Each batch layout:
    ///   - packed_binary_codes: padded_dim * 32 / 8 bytes
    ///   - f_add: 32 * 4 bytes (f32)
    ///   - f_rescale: 32 * 4 bytes (f32)
    ///   - f_error: 32 * 4 bytes (f32)
    batch_data: Vec<u8>,

    /// Packed extended codes (per-vector, C++-style on-demand unpacking)
    /// Each vector: Vec<u8> containing bit-packed ex_code
    /// Memory-efficient: ~(padded_dim * ex_bits / 8) bytes per vector
    /// Unpacked on-demand only after lower-bound filtering (mimics C++ estimator.hpp:85-103)
    /// Reference: OPTIMIZATION_PLAN.md - removes 4.4x memory overhead from pre-unpacking
    ex_codes_packed: Vec<Vec<u8>>,

    /// Per-vector ex parameters
    f_add_ex: Vec<f32>,
    f_rescale_ex: Vec<f32>,

    /// Per-vector reconstruction parameters (for fetch_embedding)
    delta: Vec<f32>,
    vl: Vec<f32>,

    /// Metadata
    num_vectors: usize,
    padded_dim: usize,
    ex_bits: usize,
}

impl ClusterData {
    /// Calculate bytes per batch in contiguous layout
    #[inline(always)]
    fn batch_stride(padded_dim: usize) -> usize {
        let binary_codes_bytes = padded_dim * simd::FASTSCAN_BATCH_SIZE / 8;
        let params_bytes = std::mem::size_of::<f32>() * simd::FASTSCAN_BATCH_SIZE * 3; // f_add, f_rescale, f_error
        binary_codes_bytes + params_bytes
    }

    /// Get number of complete batches
    #[inline(always)]
    fn num_complete_batches(&self) -> usize {
        self.num_vectors / simd::FASTSCAN_BATCH_SIZE
    }

    /// Get number of remainder vectors
    #[inline(always)]
    fn num_remainder_vectors(&self) -> usize {
        self.num_vectors % simd::FASTSCAN_BATCH_SIZE
    }

    /// Zero-copy access to packed binary codes for a batch
    #[inline(always)]
    fn batch_bin_codes(&self, batch_idx: usize) -> &[u8] {
        let stride = Self::batch_stride(self.padded_dim);
        let offset = batch_idx * stride;
        let len = self.padded_dim * simd::FASTSCAN_BATCH_SIZE / 8;
        &self.batch_data[offset..offset + len]
    }

    /// Zero-copy access to f_add parameters for a batch
    #[inline(always)]
    fn batch_f_add(&self, batch_idx: usize) -> &[f32] {
        let stride = Self::batch_stride(self.padded_dim);
        let offset = batch_idx * stride + (self.padded_dim * simd::FASTSCAN_BATCH_SIZE / 8);
        unsafe {
            std::slice::from_raw_parts(
                self.batch_data[offset..].as_ptr() as *const f32,
                simd::FASTSCAN_BATCH_SIZE,
            )
        }
    }

    /// Zero-copy access to f_rescale parameters for a batch
    #[inline(always)]
    fn batch_f_rescale(&self, batch_idx: usize) -> &[f32] {
        let stride = Self::batch_stride(self.padded_dim);
        let binary_bytes = self.padded_dim * simd::FASTSCAN_BATCH_SIZE / 8;
        let f_add_bytes = std::mem::size_of::<f32>() * simd::FASTSCAN_BATCH_SIZE;
        let offset = batch_idx * stride + binary_bytes + f_add_bytes;
        unsafe {
            std::slice::from_raw_parts(
                self.batch_data[offset..].as_ptr() as *const f32,
                simd::FASTSCAN_BATCH_SIZE,
            )
        }
    }

    /// Zero-copy access to f_error parameters for a batch
    #[inline(always)]
    fn batch_f_error(&self, batch_idx: usize) -> &[f32] {
        let stride = Self::batch_stride(self.padded_dim);
        let binary_bytes = self.padded_dim * simd::FASTSCAN_BATCH_SIZE / 8;
        let f_add_bytes = std::mem::size_of::<f32>() * simd::FASTSCAN_BATCH_SIZE;
        let f_rescale_bytes = std::mem::size_of::<f32>() * simd::FASTSCAN_BATCH_SIZE;
        let offset = batch_idx * stride + binary_bytes + f_add_bytes + f_rescale_bytes;
        unsafe {
            std::slice::from_raw_parts(
                self.batch_data[offset..].as_ptr() as *const f32,
                simd::FASTSCAN_BATCH_SIZE,
            )
        }
    }

    /// Get f_add for a single vector (for naive search)
    #[allow(dead_code)]
    fn get_vector_f_add(&self, vec_idx: usize) -> f32 {
        let batch_idx = vec_idx / simd::FASTSCAN_BATCH_SIZE;
        let in_batch_idx = vec_idx % simd::FASTSCAN_BATCH_SIZE;
        self.batch_f_add(batch_idx)[in_batch_idx]
    }

    /// Get f_rescale for a single vector (for naive search)
    #[allow(dead_code)]
    fn get_vector_f_rescale(&self, vec_idx: usize) -> f32 {
        let batch_idx = vec_idx / simd::FASTSCAN_BATCH_SIZE;
        let in_batch_idx = vec_idx % simd::FASTSCAN_BATCH_SIZE;
        self.batch_f_rescale(batch_idx)[in_batch_idx]
    }

    /// Mutable access to batch binary codes
    #[allow(dead_code)]
    fn batch_bin_codes_mut(&mut self, batch_idx: usize) -> &mut [u8] {
        let stride = Self::batch_stride(self.padded_dim);
        let offset = batch_idx * stride;
        let len = self.padded_dim * simd::FASTSCAN_BATCH_SIZE / 8;
        &mut self.batch_data[offset..offset + len]
    }

    /// Mutable access to f_add parameters
    #[allow(dead_code)]
    fn batch_f_add_mut(&mut self, batch_idx: usize) -> &mut [f32] {
        let stride = Self::batch_stride(self.padded_dim);
        let offset = batch_idx * stride + (self.padded_dim * simd::FASTSCAN_BATCH_SIZE / 8);
        unsafe {
            std::slice::from_raw_parts_mut(
                self.batch_data[offset..].as_mut_ptr() as *mut f32,
                simd::FASTSCAN_BATCH_SIZE,
            )
        }
    }

    /// Mutable access to f_rescale parameters
    #[allow(dead_code)]
    fn batch_f_rescale_mut(&mut self, batch_idx: usize) -> &mut [f32] {
        let stride = Self::batch_stride(self.padded_dim);
        let binary_bytes = self.padded_dim * simd::FASTSCAN_BATCH_SIZE / 8;
        let f_add_bytes = std::mem::size_of::<f32>() * simd::FASTSCAN_BATCH_SIZE;
        let offset = batch_idx * stride + binary_bytes + f_add_bytes;
        unsafe {
            std::slice::from_raw_parts_mut(
                self.batch_data[offset..].as_mut_ptr() as *mut f32,
                simd::FASTSCAN_BATCH_SIZE,
            )
        }
    }

    /// Mutable access to f_error parameters
    #[allow(dead_code)]
    fn batch_f_error_mut(&mut self, batch_idx: usize) -> &mut [f32] {
        let stride = Self::batch_stride(self.padded_dim);
        let binary_bytes = self.padded_dim * simd::FASTSCAN_BATCH_SIZE / 8;
        let f_add_bytes = std::mem::size_of::<f32>() * simd::FASTSCAN_BATCH_SIZE;
        let f_rescale_bytes = std::mem::size_of::<f32>() * simd::FASTSCAN_BATCH_SIZE;
        let offset = batch_idx * stride + binary_bytes + f_add_bytes + f_rescale_bytes;
        unsafe {
            std::slice::from_raw_parts_mut(
                self.batch_data[offset..].as_mut_ptr() as *mut f32,
                simd::FASTSCAN_BATCH_SIZE,
            )
        }
    }

    /// Create new empty cluster
    #[allow(dead_code)]
    fn new(centroid: Vec<f32>, padded_dim: usize, ex_bits: usize) -> Self {
        Self {
            centroid,
            ids: Vec::new(),
            batch_data: Vec::new(),
            ex_codes_packed: Vec::new(),
            f_add_ex: Vec::new(),
            f_rescale_ex: Vec::new(),
            delta: Vec::new(),
            vl: Vec::new(),
            num_vectors: 0,
            padded_dim,
            ex_bits,
        }
    }

    /// Calculate memory usage in bytes
    fn memory_usage(&self) -> usize {
        let ex_codes_heap: usize = self.ex_codes_packed.iter().map(|v| v.capacity()).sum();

        std::mem::size_of::<Self>()
            + self.centroid.len() * 4
            + self.ids.capacity() * std::mem::size_of::<usize>()
            + self.batch_data.capacity()
            + self.ex_codes_packed.capacity() * std::mem::size_of::<Vec<u8>>()
            + ex_codes_heap
            + self.f_add_ex.capacity() * 4
            + self.f_rescale_ex.capacity() * 4
            + self.delta.capacity() * 4
            + self.vl.capacity() * 4
    }

    /// Build ClusterData from quantized vectors
    /// Implements unified memory layout with:
    /// 1. Contiguous batch storage (eliminates scattered Vec allocations)
    /// 2. Pre-unpacked ex_codes (avoids repeated unpacking)
    fn from_quantized_vectors(
        centroid: Vec<f32>,
        ids: Vec<usize>,
        vectors: Vec<QuantizedVector>,
        padded_dim: usize,
        ex_bits: usize,
    ) -> Self {
        let num_vectors = vectors.len();
        let num_complete_batches = num_vectors / simd::FASTSCAN_BATCH_SIZE;
        let num_remainder = num_vectors % simd::FASTSCAN_BATCH_SIZE;

        let total_batches = if num_remainder > 0 {
            num_complete_batches + 1
        } else {
            num_complete_batches
        };

        // Allocate contiguous memory for all batches
        let stride = Self::batch_stride(padded_dim);
        let mut batch_data = crate::memory::allocate_aligned_vec::<u8>(stride * total_batches);

        // Pre-allocate storage for packed ex_codes and parameters
        let mut ex_codes_packed = Vec::with_capacity(num_vectors);
        let mut f_add_ex = Vec::with_capacity(num_vectors);
        let mut f_rescale_ex = Vec::with_capacity(num_vectors);
        let mut delta = Vec::with_capacity(num_vectors);
        let mut vl = Vec::with_capacity(num_vectors);

        let dim_bytes = padded_dim / 8;

        // Process complete batches
        for batch_idx in 0..num_complete_batches {
            let start_idx = batch_idx * simd::FASTSCAN_BATCH_SIZE;
            let end_idx = start_idx + simd::FASTSCAN_BATCH_SIZE;
            let batch_vectors = &vectors[start_idx..end_idx];

            // Pack this batch into contiguous memory
            Self::pack_batch_into_memory(
                batch_vectors,
                &mut batch_data,
                batch_idx,
                padded_dim,
                ex_bits,
                &mut ex_codes_packed,
                &mut f_add_ex,
                &mut f_rescale_ex,
                &mut delta,
                &mut vl,
            );
        }

        // Process remainder vectors
        if num_remainder > 0 {
            let start_idx = num_complete_batches * simd::FASTSCAN_BATCH_SIZE;
            let batch_vectors = &vectors[start_idx..];

            // Pad with zeros
            let mut padded_vectors = batch_vectors.to_vec();
            let ex_bytes_per_vec = if ex_bits > 0 {
                padded_dim * ex_bits / 8
            } else {
                0
            };
            padded_vectors.resize(
                simd::FASTSCAN_BATCH_SIZE,
                QuantizedVector {
                    binary_code_packed: vec![0u8; dim_bytes],
                    ex_code_packed: vec![0u8; ex_bytes_per_vec],
                    ex_bits: ex_bits as u8,
                    dim: padded_dim,
                    delta: 0.0,
                    vl: 0.0,
                    f_add: 0.0,
                    f_rescale: 0.0,
                    f_error: 0.0,
                    residual_norm: 0.0,
                    f_add_ex: 0.0,
                    f_rescale_ex: 0.0,
                },
            );

            // Call pack_batch_into_memory_partial to handle partial batches correctly
            Self::pack_batch_into_memory_partial(
                &padded_vectors,
                num_remainder, // actual number of vectors
                &mut batch_data,
                num_complete_batches,
                padded_dim,
                ex_bits,
                &mut ex_codes_packed,
                &mut f_add_ex,
                &mut f_rescale_ex,
                &mut delta,
                &mut vl,
            );
        }

        Self {
            centroid,
            ids,
            batch_data,
            ex_codes_packed,
            f_add_ex,
            f_rescale_ex,
            delta,
            vl,
            num_vectors,
            padded_dim,
            ex_bits,
        }
    }

    /// Pack 32 vectors into contiguous batch memory
    /// Pack a partial batch into memory (handles the last batch with < 32 vectors)
    #[allow(clippy::too_many_arguments)]
    fn pack_batch_into_memory_partial(
        vectors: &[QuantizedVector],
        actual_count: usize, // actual number of vectors (before padding)
        batch_data: &mut [u8],
        batch_idx: usize,
        padded_dim: usize,
        ex_bits: usize,
        ex_codes_packed: &mut Vec<Vec<u8>>,
        f_add_ex: &mut Vec<f32>,
        f_rescale_ex: &mut Vec<f32>,
        delta: &mut Vec<f32>,
        vl: &mut Vec<f32>,
    ) {
        assert_eq!(vectors.len(), simd::FASTSCAN_BATCH_SIZE);
        assert!(actual_count <= simd::FASTSCAN_BATCH_SIZE);

        let stride = Self::batch_stride(padded_dim);
        let dim_bytes = padded_dim / 8;

        // Calculate offsets in contiguous memory
        let batch_offset = batch_idx * stride;
        let binary_bytes = padded_dim * simd::FASTSCAN_BATCH_SIZE / 8;

        // Collect binary codes into flat buffer (including padding)
        let mut binary_codes_flat = Vec::with_capacity(simd::FASTSCAN_BATCH_SIZE * dim_bytes);
        for vec in vectors.iter() {
            binary_codes_flat.extend_from_slice(&vec.binary_code_packed);
        }

        // Pack binary codes using FastScan layout
        let packed_codes = &mut batch_data[batch_offset..batch_offset + binary_bytes];
        simd::pack_codes(
            &binary_codes_flat,
            simd::FASTSCAN_BATCH_SIZE,
            dim_bytes,
            packed_codes,
        );

        // Get mutable slices for parameters
        let f_add_offset = batch_offset + binary_bytes;
        let f_rescale_offset =
            f_add_offset + std::mem::size_of::<f32>() * simd::FASTSCAN_BATCH_SIZE;
        let f_error_offset =
            f_rescale_offset + std::mem::size_of::<f32>() * simd::FASTSCAN_BATCH_SIZE;

        unsafe {
            let f_add_slice = std::slice::from_raw_parts_mut(
                batch_data[f_add_offset..].as_mut_ptr() as *mut f32,
                simd::FASTSCAN_BATCH_SIZE,
            );
            let f_rescale_slice = std::slice::from_raw_parts_mut(
                batch_data[f_rescale_offset..].as_mut_ptr() as *mut f32,
                simd::FASTSCAN_BATCH_SIZE,
            );
            let f_error_slice = std::slice::from_raw_parts_mut(
                batch_data[f_error_offset..].as_mut_ptr() as *mut f32,
                simd::FASTSCAN_BATCH_SIZE,
            );

            // Copy parameters (including padding)
            for (i, vec) in vectors.iter().enumerate() {
                f_add_slice[i] = vec.f_add;
                f_rescale_slice[i] = vec.f_rescale;
                f_error_slice[i] = vec.f_error;
            }
        }

        // Store packed ex_codes - ONLY for actual vectors, not padding!
        // C++-style: Keep codes packed, unpack on-demand during search
        for vec in vectors.iter().take(actual_count) {
            // Store packed ex_code (no unpacking!)
            if ex_bits > 0 {
                ex_codes_packed.push(vec.ex_code_packed.clone());
                f_add_ex.push(vec.f_add_ex);
                f_rescale_ex.push(vec.f_rescale_ex);
            } else {
                ex_codes_packed.push(Vec::new());
                f_add_ex.push(0.0);
                f_rescale_ex.push(0.0);
            }
            // Store reconstruction parameters
            delta.push(vec.delta);
            vl.push(vec.vl);
        }
    }

    #[allow(clippy::too_many_arguments)]
    fn pack_batch_into_memory(
        vectors: &[QuantizedVector],
        batch_data: &mut [u8],
        batch_idx: usize,
        padded_dim: usize,
        ex_bits: usize,
        ex_codes_packed: &mut Vec<Vec<u8>>,
        f_add_ex: &mut Vec<f32>,
        f_rescale_ex: &mut Vec<f32>,
        delta: &mut Vec<f32>,
        vl: &mut Vec<f32>,
    ) {
        assert_eq!(vectors.len(), simd::FASTSCAN_BATCH_SIZE);

        let stride = Self::batch_stride(padded_dim);
        let dim_bytes = padded_dim / 8;

        // Calculate offsets in contiguous memory
        let batch_offset = batch_idx * stride;
        let binary_bytes = padded_dim * simd::FASTSCAN_BATCH_SIZE / 8;

        // Collect binary codes into flat buffer
        let mut binary_codes_flat = Vec::with_capacity(simd::FASTSCAN_BATCH_SIZE * dim_bytes);
        for vec in vectors.iter() {
            binary_codes_flat.extend_from_slice(&vec.binary_code_packed);
        }

        // Pack binary codes using FastScan layout
        let packed_codes = &mut batch_data[batch_offset..batch_offset + binary_bytes];
        simd::pack_codes(
            &binary_codes_flat,
            simd::FASTSCAN_BATCH_SIZE,
            dim_bytes,
            packed_codes,
        );

        // Get mutable slices for parameters (using pointer arithmetic like C++)
        let f_add_offset = batch_offset + binary_bytes;
        let f_rescale_offset =
            f_add_offset + std::mem::size_of::<f32>() * simd::FASTSCAN_BATCH_SIZE;
        let f_error_offset =
            f_rescale_offset + std::mem::size_of::<f32>() * simd::FASTSCAN_BATCH_SIZE;

        unsafe {
            let f_add_slice = std::slice::from_raw_parts_mut(
                batch_data[f_add_offset..].as_mut_ptr() as *mut f32,
                simd::FASTSCAN_BATCH_SIZE,
            );
            let f_rescale_slice = std::slice::from_raw_parts_mut(
                batch_data[f_rescale_offset..].as_mut_ptr() as *mut f32,
                simd::FASTSCAN_BATCH_SIZE,
            );
            let f_error_slice = std::slice::from_raw_parts_mut(
                batch_data[f_error_offset..].as_mut_ptr() as *mut f32,
                simd::FASTSCAN_BATCH_SIZE,
            );

            // Copy parameters
            for (i, vec) in vectors.iter().enumerate() {
                f_add_slice[i] = vec.f_add;
                f_rescale_slice[i] = vec.f_rescale;
                f_error_slice[i] = vec.f_error;
            }
        }

        // Store packed ex_codes for all vectors in batch
        // C++-style: Keep codes packed, unpack on-demand during search
        for vec in vectors.iter() {
            // Store packed ex_code (no unpacking!)
            if ex_bits > 0 {
                ex_codes_packed.push(vec.ex_code_packed.clone());
                f_add_ex.push(vec.f_add_ex);
                f_rescale_ex.push(vec.f_rescale_ex);
            } else {
                ex_codes_packed.push(Vec::new());
                f_add_ex.push(0.0);
                f_rescale_ex.push(0.0);
            }
            // Store reconstruction parameters
            delta.push(vec.delta);
            vl.push(vec.vl);
        }
    }
}

// ============================================================================
// Quantized vector for temporary use during training
// ============================================================================

/// Temporary structure used during index construction
/// After construction, vectors are packed into ClusterData's unified memory layout
#[derive(Debug, Clone)]
#[allow(dead_code)]
struct TemporaryQuantizedVector {
    binary_code_packed: Vec<u8>,
    ex_code_packed: Vec<u8>,
    f_add: f32,
    f_rescale: f32,
    f_error: f32,
    f_add_ex: f32,
    f_rescale_ex: f32,
}

/// Lookup table for batch FastScan search
/// Mimics C++ Lut class from lut.hpp
struct QueryLut {
    /// Quantized lookup table (i8 values for SIMD)
    lut_i8: Vec<i8>,
    /// Quantization delta factor
    delta: f32,
    /// Sum of vl across all lookup tables
    sum_vl_lut: f32,
}

/// High-accuracy LUT with separated low8/high8 components
/// Used for high-dimensional data (dim > 2048) to prevent overflow
struct QueryLutHighAcc {
    /// Low 8 bits of LUT values (u8 for unsigned values)
    lut_low8: Vec<u8>,
    /// High 8 bits of LUT values (u8 for unsigned values)
    lut_high8: Vec<u8>,
    /// Quantization delta factor
    delta: f32,
    /// Sum of vl across all lookup tables
    sum_vl_lut: f32,
}

impl QueryLutHighAcc {
    /// Build high-accuracy LUT from rotated query
    /// Splits quantized values into low8 and high8 components
    fn new(rotated_query: &[f32], padded_dim: usize) -> Self {
        assert!(
            padded_dim.is_multiple_of(4),
            "padded_dim must be multiple of 4 for LUT"
        );

        // First compute float values like regular LUT
        // pack_lut_f32 packs 4 dimensions into 16 LUT entries, repeated for each batch
        let lut_size = (padded_dim / 4) * 16 * (padded_dim / 32);
        let mut lut_f32 = vec![0.0f32; lut_size];
        simd::pack_lut_f32(rotated_query, &mut lut_f32);

        // Compute delta and sum_vl_lut
        let sum: f32 = lut_f32.iter().sum();
        let (delta, sum_vl) = if lut_f32.iter().all(|&x| x.abs() < f32::EPSILON) {
            (1.0, 0.0)
        } else {
            let max_val = lut_f32.iter().map(|x| x.abs()).fold(0.0f32, f32::max);
            // Use larger range for high-accuracy mode (16-bit instead of 8-bit)
            let delta = max_val / 32767.0; // i16::MAX
            let sum_vl = sum / delta;
            (delta, sum_vl)
        };

        // Quantize to 16-bit signed values first
        let mut lut_i16 = vec![0i16; lut_f32.len()];
        for (i, &val) in lut_f32.iter().enumerate() {
            let quantized = (val / delta).round();
            lut_i16[i] = quantized.clamp(i16::MIN as f32, i16::MAX as f32) as i16;
        }

        // Split into low8 and high8 components
        let mut lut_low8 = vec![0u8; lut_i16.len()];
        let mut lut_high8 = vec![0u8; lut_i16.len()];

        for (i, &val) in lut_i16.iter().enumerate() {
            // Convert i16 to u16 by adding 32768 (shift to unsigned range)
            let unsigned_val = (val as i32 + 32768) as u16;
            lut_low8[i] = (unsigned_val & 0xFF) as u8;
            lut_high8[i] = ((unsigned_val >> 8) & 0xFF) as u8;
        }

        Self {
            lut_low8,
            lut_high8,
            delta,
            sum_vl_lut: sum_vl,
        }
    }
}

impl QueryLut {
    /// Build LUT from rotated query
    /// Reference: C++ Lut constructor in lut.hpp:27-53
    fn new(rotated_query: &[f32], padded_dim: usize) -> Self {
        assert!(
            padded_dim.is_multiple_of(4),
            "padded_dim must be multiple of 4 for LUT"
        );

        let table_length = padded_dim * 4; // padded_dim << 2

        // Step 1: Generate float LUT using pack_lut_f32
        let mut lut_float = vec![0.0f32; table_length];
        simd::pack_lut_f32(rotated_query, &mut lut_float);

        // Step 2: Find min and max of LUT
        let vl_lut = lut_float
            .iter()
            .copied()
            .min_by(|a, b| a.total_cmp(b))
            .unwrap_or(0.0);
        let vr_lut = lut_float
            .iter()
            .copied()
            .max_by(|a, b| a.total_cmp(b))
            .unwrap_or(0.0);

        // Step 3: Compute delta for i8 quantization (8 bits)
        let delta = (vr_lut - vl_lut) / 255.0f32; // (1 << 8) - 1 = 255

        // Step 4: Quantize float LUT to i8
        let mut lut_i8 = vec![0i8; table_length];
        if delta > 0.0 {
            for i in 0..table_length {
                let quantized = ((lut_float[i] - vl_lut) / delta).round();
                // Must convert to u8 first, then to i8 to avoid saturation
                // f32 as i8 saturates at 127, but we need wrapping behavior (128-255 -> -128 to -1)
                lut_i8[i] = (quantized.clamp(0.0, 255.0) as u8) as i8;
            }
        }

        // Step 5: Compute sum_vl_lut
        let num_table = table_length / 16;
        let sum_vl_lut = vl_lut * (num_table as f32);

        Self {
            lut_i8,
            delta,
            sum_vl_lut,
        }
    }
}

/// Precomputed query constants to avoid repeated calculations during search.
struct QueryPrecomputed {
    rotated_query: Vec<f32>,
    query_norm: f32,
    k1x_sum_q: f32, // c1 × sum_query (precomputed)
    kbx_sum_q: f32, // cb × sum_query (precomputed)
    binary_scale: f32,
    /// Optional LUT for FastScan batch search
    lut: Option<QueryLut>,
    /// Optional high-accuracy LUT for high-dimensional data
    lut_highacc: Option<QueryLutHighAcc>,
}

impl QueryPrecomputed {
    fn new(rotated_query: Vec<f32>, ex_bits: usize) -> Self {
        let sum_query: f32 = rotated_query.iter().sum();
        let query_norm: f32 = rotated_query.iter().map(|v| v * v).sum::<f32>().sqrt();
        let c1 = -0.5f32;
        let cb = -((1 << ex_bits) as f32 - 0.5);
        let binary_scale = (1 << ex_bits) as f32;

        Self {
            rotated_query,
            query_norm,
            k1x_sum_q: c1 * sum_query,
            kbx_sum_q: cb * sum_query,
            binary_scale,
            lut: None,         // LUT built on demand for batch search
            lut_highacc: None, // High-accuracy LUT built on demand for high-dimensional data
        }
    }

    /// Build LUT for FastScan batch search
    /// Should be called once per query before searching clusters
    fn build_lut(&mut self, padded_dim: usize) {
        // Decide whether to use high-accuracy mode based on dimension
        // Use high-accuracy for dimensions > 2048 to prevent overflow
        let use_highacc = padded_dim > 2048;

        if use_highacc {
            if self.lut_highacc.is_none() {
                self.lut_highacc = Some(QueryLutHighAcc::new(&self.rotated_query, padded_dim));
            }
        } else if self.lut.is_none() {
            self.lut = Some(QueryLut::new(&self.rotated_query, padded_dim));
        }
    }
}

#[derive(Debug, Clone)]
struct HeapCandidate {
    id: usize,
    distance: f32,
    score: f32,
}

#[derive(Debug, Clone)]
struct HeapEntry {
    candidate: HeapCandidate,
}

impl PartialEq for HeapEntry {
    fn eq(&self, other: &Self) -> bool {
        self.candidate
            .distance
            .to_bits()
            .eq(&other.candidate.distance.to_bits())
            && self.candidate.id == other.candidate.id
    }
}

impl Eq for HeapEntry {}

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

impl Ord for HeapEntry {
    fn cmp(&self, other: &Self) -> Ordering {
        self.candidate.distance.total_cmp(&other.candidate.distance)
    }
}

/// IVF + RaBitQ index implemented in Rust.
#[derive(Debug, Clone)]
pub struct IvfRabitqIndex {
    dim: usize,
    padded_dim: usize,
    metric: Metric,
    rotator: DynamicRotator,
    /// Unified cluster data with optimized memory layout (Phase 1 optimization)
    clusters: Vec<ClusterData>,
    ex_bits: usize,
    /// Function pointer for ex-code inner product on packed data (Phase 3 optimization)
    /// Selected based on ex_bits at index construction time
    ip_func: crate::simd::ExIpFunc,
}

impl IvfRabitqIndex {
    /// Train a new index from the provided dataset.
    pub fn train(
        data: &[Vec<f32>],
        nlist: usize,
        total_bits: usize,
        metric: Metric,
        rotator_type: RotatorType,
        seed: u64,
        use_faster_config: bool,
    ) -> Result<Self, RabitqError> {
        if data.is_empty() {
            return Err(RabitqError::InvalidConfig(
                "training data must be non-empty",
            ));
        }
        if nlist == 0 {
            return Err(RabitqError::InvalidConfig("nlist must be positive"));
        }
        if total_bits == 0 || total_bits > 16 {
            return Err(RabitqError::InvalidConfig(
                "total_bits must be between 1 and 16",
            ));
        }

        let dim = data[0].len();
        if data.iter().any(|v| v.len() != dim) {
            return Err(RabitqError::InvalidConfig(
                "input vectors must share the same dimension",
            ));
        }
        if nlist > data.len() {
            return Err(RabitqError::InvalidConfig(
                "nlist cannot exceed number of vectors",
            ));
        }

        println!(
            "Training k-means on original data ({} clusters, {} iterations)...",
            nlist, 30
        );
        let mut rng = StdRng::seed_from_u64(seed ^ 0x5a5a_5a5a5a5a5a5a);
        let KMeansResult {
            centroids,
            assignments,
            ..
        } = run_kmeans(data, nlist, 30, &mut rng);
        println!("K-means training complete");

        let rotator = DynamicRotator::new(dim, rotator_type, seed);
        let padded_dim = rotator.padded_dim();

        // Log huge pages status
        crate::memory::log_huge_page_status();

        println!("Rotating data vectors...");
        let rotated_data: Vec<Vec<f32>> = data.par_iter().map(|v| rotator.rotate(v)).collect();
        println!("Rotating centroids...");
        let rotated_centroids: Vec<Vec<f32>> =
            centroids.par_iter().map(|c| rotator.rotate(c)).collect();

        Self::build_from_rotated(
            dim,
            padded_dim,
            metric,
            rotator,
            rotated_centroids,
            &rotated_data,
            &assignments,
            total_bits,
            seed,
            use_faster_config,
        )
    }

    /// Train an index using externally provided centroids and cluster assignments.
    #[allow(clippy::too_many_arguments)]
    pub fn train_with_clusters(
        data: &[Vec<f32>],
        centroids: &[Vec<f32>],
        assignments: &[usize],
        total_bits: usize,
        metric: Metric,
        rotator_type: RotatorType,
        seed: u64,
        use_faster_config: bool,
    ) -> Result<Self, RabitqError> {
        if data.is_empty() {
            return Err(RabitqError::InvalidConfig(
                "training data must be non-empty",
            ));
        }
        if centroids.is_empty() {
            return Err(RabitqError::InvalidConfig("centroids must be non-empty"));
        }
        if assignments.len() != data.len() {
            return Err(RabitqError::InvalidConfig(
                "assignments length must match data length",
            ));
        }
        if total_bits == 0 || total_bits > 16 {
            return Err(RabitqError::InvalidConfig(
                "total_bits must be between 1 and 16",
            ));
        }

        let dim = data[0].len();
        if data.iter().any(|v| v.len() != dim) {
            return Err(RabitqError::InvalidConfig(
                "input vectors must share the same dimension",
            ));
        }
        if centroids.iter().any(|c| c.len() != dim) {
            return Err(RabitqError::InvalidConfig(
                "centroids must match the data dimensionality",
            ));
        }

        let nlist = centroids.len();
        if nlist == 0 {
            return Err(RabitqError::InvalidConfig("nlist must be positive"));
        }
        if nlist > data.len() {
            return Err(RabitqError::InvalidConfig(
                "nlist cannot exceed number of vectors",
            ));
        }
        if assignments.iter().any(|&cid| cid >= nlist) {
            return Err(RabitqError::InvalidConfig(
                "assignments reference invalid cluster ids",
            ));
        }

        let rotator = DynamicRotator::new(dim, rotator_type, seed);
        let padded_dim = rotator.padded_dim();

        // Log huge pages status
        crate::memory::log_huge_page_status();

        let rotated_data: Vec<Vec<f32>> = data.par_iter().map(|v| rotator.rotate(v)).collect();
        let rotated_centroids: Vec<Vec<f32>> =
            centroids.par_iter().map(|c| rotator.rotate(c)).collect();

        Self::build_from_rotated(
            dim,
            padded_dim,
            metric,
            rotator,
            rotated_centroids,
            &rotated_data,
            assignments,
            total_bits,
            seed,
            use_faster_config,
        )
    }

    #[allow(clippy::too_many_arguments)]
    fn build_from_rotated(
        dim: usize,
        padded_dim: usize,
        metric: Metric,
        rotator: DynamicRotator,
        rotated_centroids: Vec<Vec<f32>>,
        rotated_data: &[Vec<f32>],
        assignments: &[usize],
        total_bits: usize,
        seed: u64,
        use_faster_config: bool,
    ) -> Result<Self, RabitqError> {
        if assignments.len() != rotated_data.len() {
            return Err(RabitqError::InvalidConfig(
                "assignments length must match number of vectors",
            ));
        }
        if total_bits == 0 || total_bits > 16 {
            return Err(RabitqError::InvalidConfig(
                "total_bits must be between 1 and 16",
            ));
        }

        let centroids = rotated_centroids;
        if centroids.is_empty() {
            return Err(RabitqError::InvalidConfig("nlist must be positive"));
        }

        let config = if use_faster_config {
            RabitqConfig::faster(padded_dim, total_bits, seed)
        } else {
            RabitqConfig::new(total_bits)
        };

        // Group vector indices by cluster
        let mut cluster_indices: Vec<Vec<usize>> = vec![Vec::new(); centroids.len()];
        for (idx, &cluster_id) in assignments.iter().enumerate() {
            if cluster_id >= centroids.len() {
                return Err(RabitqError::InvalidConfig(
                    "assignments reference invalid cluster ids",
                ));
            }
            cluster_indices[cluster_id].push(idx);
        }

        // Parallelize quantization across clusters and within clusters
        println!("Quantizing vectors...");
        use std::sync::atomic::{AtomicUsize, Ordering};
        let progress_counter = AtomicUsize::new(0);
        let total_clusters = centroids.len();

        let cluster_data: Vec<(Vec<usize>, Vec<QuantizedVector>)> = centroids
            .par_iter()
            .enumerate()
            .map(|(cluster_id, centroid)| {
                let indices = &cluster_indices[cluster_id];
                let quantized_vectors: Vec<QuantizedVector> = indices
                    .par_iter()
                    .map(|&idx| {
                        quantize_with_centroid(&rotated_data[idx], centroid, &config, metric)
                    })
                    .collect();

                let completed = progress_counter.fetch_add(1, Ordering::Relaxed) + 1;
                if completed.is_multiple_of((total_clusters / 20).max(1))
                    || completed == total_clusters
                {
                    println!(
                        "  Quantized {}/{} clusters ({:.1}%)",
                        completed,
                        total_clusters,
                        100.0 * completed as f64 / total_clusters as f64
                    );
                }

                (indices.clone(), quantized_vectors)
            })
            .collect();
        println!("Quantization complete");

        // Build unified clusters with optimized memory layout
        println!("Building clusters with unified memory layout...");
        let clusters: Vec<ClusterData> = cluster_data
            .into_iter()
            .enumerate()
            .map(|(cluster_id, (indices, quantized_vectors))| {
                ClusterData::from_quantized_vectors(
                    centroids[cluster_id].clone(),
                    indices,
                    quantized_vectors,
                    padded_dim,
                    total_bits.saturating_sub(1),
                )
            })
            .collect();
        println!("Cluster construction complete");

        let ex_bits = total_bits.saturating_sub(1);
        let ip_func = crate::simd::select_excode_ipfunc(ex_bits);

        Ok(Self {
            dim,
            padded_dim,
            metric,
            rotator,
            clusters,
            ex_bits,
            ip_func,
        })
    }

    /// Number of stored vectors.
    pub fn len(&self) -> usize {
        self.clusters.iter().map(|c| c.ids.len()).sum()
    }

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

    /// Number of IVF clusters maintained by the index.
    pub fn cluster_count(&self) -> usize {
        self.clusters.len()
    }

    /// Estimate total memory usage in bytes
    pub fn memory_usage(&self) -> usize {
        let clusters_mem: usize = self.clusters.iter().map(|c| c.memory_usage()).sum();
        std::mem::size_of::<Self>() + clusters_mem
    }

    /// Estimate total memory usage in MB
    pub fn estimate_memory_mb(&self) -> f32 {
        self.memory_usage() as f32 / (1024.0 * 1024.0)
    }

    /// Fetch the original embedding for a given vector ID.
    ///
    /// This function reconstructs the approximate original vector from its quantized representation.
    /// The reconstruction involves:
    /// 1. Finding the cluster and local index for the vector ID
    /// 2. Reconstructing the vector in rotated space using the quantized codes
    /// 3. Applying inverse rotation to recover the original (unrotated) vector
    ///
    /// # Returns
    /// - `Some(Vec<f32>)` containing the reconstructed vector if the ID exists
    /// - `None` if the ID is not found in the index
    ///
    /// # Note
    /// The returned vector is an approximation due to quantization losses.
    /// The accuracy depends on the `total_bits` parameter used during training.
    pub fn fetch_embedding(&self, vector_id: usize) -> Option<Vec<f32>> {
        // Find which cluster contains this vector ID
        for cluster in &self.clusters {
            if let Some(local_idx) = cluster.ids.iter().position(|&id| id == vector_id) {
                // Found the vector, now reconstruct it

                // Step 1: Extract quantized codes
                let ex_bits = self.ex_bits;

                // Extract binary code from batch data
                let batch_idx = local_idx / simd::FASTSCAN_BATCH_SIZE;
                let in_batch_idx = local_idx % simd::FASTSCAN_BATCH_SIZE;

                // Unpack binary code for this vector from FastScan layout
                let batch_bin_codes = cluster.batch_bin_codes(batch_idx);
                let dim_bytes = self.padded_dim / 8;
                let mut binary_code_unpacked = vec![0u8; self.padded_dim];

                // Use the existing unpack_single_vector function
                simd::unpack_single_vector(
                    batch_bin_codes,
                    in_batch_idx,
                    dim_bytes,
                    &mut binary_code_unpacked,
                );

                // Extract ex_code (already stored per-vector)
                let ex_code_packed = &cluster.ex_codes_packed[local_idx];
                let mut ex_code_unpacked = vec![0u16; self.padded_dim];
                if ex_bits > 0 {
                    simd::unpack_ex_code(
                        ex_code_packed,
                        &mut ex_code_unpacked,
                        self.padded_dim,
                        ex_bits as u8,
                    );
                }

                // Step 2: Reconstruct full code
                let mut code = vec![0u16; self.padded_dim];
                for i in 0..self.padded_dim {
                    code[i] = ex_code_unpacked[i] + ((binary_code_unpacked[i] as u16) << ex_bits);
                }

                // Step 3: Reconstruct in rotated space
                let delta = cluster.delta[local_idx];
                let vl = cluster.vl[local_idx];
                let mut rotated_reconstructed = vec![0.0f32; self.padded_dim];
                for i in 0..self.padded_dim {
                    rotated_reconstructed[i] = cluster.centroid[i] + delta * code[i] as f32 + vl;
                }

                // Step 4: Apply inverse rotation to get original space vector
                let original_vector = self.rotator.inverse_rotate(&rotated_reconstructed);

                return Some(original_vector);
            }
        }

        None
    }

    /// Persist the index to the provided filesystem path.
    pub fn save_to_path<P: AsRef<Path>>(&self, path: P) -> Result<(), RabitqError> {
        let file = File::create(path)?;
        let writer = BufWriter::new(file);
        self.save_to_writer(writer)
    }

    /// Persist the index using the supplied writer.
    pub fn save_to_writer<W: Write>(&self, writer: W) -> Result<(), RabitqError> {
        let mut writer = BufWriter::new(writer);
        writer.write_all(&PERSIST_MAGIC)?;
        write_u32(&mut writer, PERSIST_VERSION, None)?;

        let mut hasher = Hasher::new();

        let dim = u32::try_from(self.dim)
            .map_err(|_| RabitqError::InvalidPersistence("dimension exceeds persistence limits"))?;
        write_u32(&mut writer, dim, Some(&mut hasher))?;

        let padded_dim = u32::try_from(self.padded_dim).map_err(|_| {
            RabitqError::InvalidPersistence("padded_dim exceeds persistence limits")
        })?;
        write_u32(&mut writer, padded_dim, Some(&mut hasher))?;

        let metric_tag = metric_to_tag(self.metric);
        writer.write_all(&[metric_tag])?;
        hasher.update(&[metric_tag]);

        let rotator_type_tag = self.rotator.rotator_type() as u8;
        writer.write_all(&[rotator_type_tag])?;
        hasher.update(&[rotator_type_tag]);

        let ex_bits = u8::try_from(self.ex_bits)
            .map_err(|_| RabitqError::InvalidPersistence("ex_bits exceeds persistence limits"))?;
        writer.write_all(&[ex_bits])?;
        hasher.update(&[ex_bits]);

        let total_bits = self
            .ex_bits
            .checked_add(1)
            .ok_or(RabitqError::InvalidPersistence("total_bits overflow"))?;
        let total_bits_u8 = u8::try_from(total_bits).map_err(|_| {
            RabitqError::InvalidPersistence("total_bits exceeds persistence limits")
        })?;
        writer.write_all(&[total_bits_u8])?;
        hasher.update(&[total_bits_u8]);

        let vector_count = u64::try_from(self.len()).map_err(|_| {
            RabitqError::InvalidPersistence("vector count exceeds persistence limits")
        })?;
        write_u64(&mut writer, vector_count, Some(&mut hasher))?;

        let cluster_count = u64::try_from(self.clusters.len()).map_err(|_| {
            RabitqError::InvalidPersistence("cluster count exceeds persistence limits")
        })?;
        write_u64(&mut writer, cluster_count, Some(&mut hasher))?;

        // Save rotator state (much smaller than full matrix for FHT)
        let rotator_data = self.rotator.serialize();
        let rotator_len = u64::try_from(rotator_data.len())
            .map_err(|_| RabitqError::InvalidPersistence("rotator data too large"))?;
        eprintln!("DEBUG SAVE: rotator_len={}", rotator_len);
        write_u64(&mut writer, rotator_len, Some(&mut hasher))?;
        writer.write_all(&rotator_data)?;
        hasher.update(&rotator_data);

        // V3: Save ClusterData with unified memory layout
        eprintln!("DEBUG SAVE: Saving {} clusters", self.clusters.len());
        for (i, cluster) in self.clusters.iter().enumerate() {
            eprintln!(
                "DEBUG SAVE: Cluster {}: num_vectors={}, batch_data.len()={}",
                i,
                cluster.num_vectors,
                cluster.batch_data.len()
            );
            if cluster.centroid.len() != self.padded_dim {
                return Err(RabitqError::InvalidPersistence(
                    "cluster centroid dimension mismatch",
                ));
            }
            if cluster.ids.len() != cluster.num_vectors {
                return Err(RabitqError::InvalidPersistence(
                    "cluster id/vector count mismatch",
                ));
            }

            // Save centroid
            for &value in &cluster.centroid {
                write_f32(&mut writer, value, Some(&mut hasher))?;
            }

            // Save vector count
            let entry_count = u64::try_from(cluster.num_vectors).map_err(|_| {
                RabitqError::InvalidPersistence("cluster entry count exceeds persistence limits")
            })?;
            write_u64(&mut writer, entry_count, Some(&mut hasher))?;

            // Save vector IDs
            for &id in &cluster.ids {
                let encoded = u64::try_from(id).map_err(|_| {
                    RabitqError::InvalidPersistence("vector id exceeds persistence limits")
                })?;
                write_u64(&mut writer, encoded, Some(&mut hasher))?;
            }

            // Save batch_data (contiguous memory block)
            let batch_data_len = u64::try_from(cluster.batch_data.len()).map_err(|_| {
                RabitqError::InvalidPersistence("batch_data size exceeds persistence limits")
            })?;

            // DEBUG: Output cluster info
            // eprintln!("Serializing cluster: num_vectors={}, batch_data.len()={}",
            //           cluster.num_vectors, cluster.batch_data.len());

            write_u64(&mut writer, batch_data_len, Some(&mut hasher))?;
            writer.write_all(&cluster.batch_data)?;
            hasher.update(&cluster.batch_data);

            // Save packed ex_codes (C++-style on-demand unpacking)
            eprintln!(
                "DEBUG SAVE: Cluster {}: ex_codes_packed.len()={}",
                i,
                cluster.ex_codes_packed.len()
            );
            for (j, ex_code_packed) in cluster.ex_codes_packed.iter().enumerate() {
                let ex_code_len = u64::try_from(ex_code_packed.len()).map_err(|_| {
                    RabitqError::InvalidPersistence(
                        "ex_code_packed length exceeds persistence limits",
                    )
                })?;
                if j < 2 {
                    eprintln!(
                        "DEBUG SAVE: Cluster {}: ex_code_packed[{}].len()={}",
                        i, j, ex_code_len
                    );
                }
                write_u64(&mut writer, ex_code_len, Some(&mut hasher))?;
                writer.write_all(ex_code_packed)?;
                hasher.update(ex_code_packed);
            }

            // Save ex parameters
            for &val in &cluster.f_add_ex {
                write_f32(&mut writer, val, Some(&mut hasher))?;
            }
            for &val in &cluster.f_rescale_ex {
                write_f32(&mut writer, val, Some(&mut hasher))?;
            }

            // Write delta (reconstruction parameters)
            for &val in &cluster.delta {
                write_f32(&mut writer, val, Some(&mut hasher))?;
            }

            // Write vl (reconstruction parameters)
            for &val in &cluster.vl {
                write_f32(&mut writer, val, Some(&mut hasher))?;
            }
        }

        let checksum = hasher.finalize();
        write_u32(&mut writer, checksum, None)?;

        writer.flush()?;
        Ok(())
    }

    /// Load an index from the provided filesystem path.
    pub fn load_from_path<P: AsRef<Path>>(path: P) -> Result<Self, RabitqError> {
        let file = File::open(path)?;
        let reader = BufReader::new(file);
        Self::load_from_reader(reader)
    }

    /// Load an index from a persisted byte stream.
    pub fn load_from_reader<R: Read>(reader: R) -> Result<Self, RabitqError> {
        let mut reader = BufReader::new(reader);
        let mut magic = [0u8; 4];
        reader.read_exact(&mut magic)?;
        if magic != PERSIST_MAGIC {
            return Err(RabitqError::InvalidPersistence("unrecognized file header"));
        }

        let version = read_u32(&mut reader, None)?;
        if version != 3 {
            return Err(RabitqError::InvalidPersistence(
                "unsupported index format version (expected V3 with unified memory layout)",
            ));
        }

        let mut hasher = Hasher::new();

        let dim = read_u32(&mut reader, Some(&mut hasher))? as usize;
        if dim == 0 {
            return Err(RabitqError::InvalidPersistence(
                "dimension must be positive",
            ));
        }

        let padded_dim = read_u32(&mut reader, Some(&mut hasher))? as usize;
        if padded_dim < dim {
            return Err(RabitqError::InvalidPersistence("padded_dim must be >= dim"));
        }

        let metric_tag = read_u8(&mut reader, Some(&mut hasher))?;
        let metric = tag_to_metric(metric_tag)
            .ok_or(RabitqError::InvalidPersistence("unknown metric tag"))?;

        let rotator_type_tag = read_u8(&mut reader, Some(&mut hasher))?;
        let rotator_type = RotatorType::from_u8(rotator_type_tag)
            .ok_or(RabitqError::InvalidPersistence("unknown rotator type tag"))?;

        let ex_bits = read_u8(&mut reader, Some(&mut hasher))? as usize;
        if ex_bits > 16 {
            return Err(RabitqError::InvalidPersistence("ex_bits out of range"));
        }

        let total_bits = read_u8(&mut reader, Some(&mut hasher))? as usize;
        if total_bits == 0 || total_bits > 16 {
            return Err(RabitqError::InvalidPersistence("total_bits out of range"));
        }
        if total_bits.saturating_sub(1) != ex_bits {
            return Err(RabitqError::InvalidPersistence(
                "total_bits does not match ex_bits",
            ));
        }

        let expected_vectors = usize_from_u64(read_u64(&mut reader, Some(&mut hasher))?)?;
        eprintln!("DEBUG LOAD: expected_vectors={}", expected_vectors);

        let cluster_count = usize_from_u64(read_u64(&mut reader, Some(&mut hasher))?)?;
        eprintln!("DEBUG LOAD: cluster_count={}", cluster_count);

        let rotator_data_len = usize_from_u64(read_u64(&mut reader, Some(&mut hasher))?)?;
        eprintln!("DEBUG LOAD: rotator_data_len={}", rotator_data_len);

        let mut rotator_data = vec![0u8; rotator_data_len];
        reader.read_exact(&mut rotator_data)?;
        hasher.update(&rotator_data);

        let rotator = DynamicRotator::deserialize(dim, padded_dim, rotator_type, &rotator_data)?;

        // V3: Load ClusterData with unified memory layout
        let mut clusters = Vec::with_capacity(cluster_count);
        eprintln!("DEBUG LOAD: Loading {} clusters", cluster_count);
        for i in 0..cluster_count {
            eprintln!("DEBUG LOAD: Loading cluster {}", i);
            // Load centroid
            let mut centroid = vec![0f32; padded_dim];
            for value in centroid.iter_mut() {
                *value = read_f32(&mut reader, Some(&mut hasher))?;
            }

            // Load vector count
            let num_vectors = usize_from_u64(read_u64(&mut reader, Some(&mut hasher))?)?;
            eprintln!("DEBUG LOAD: Cluster {}: num_vectors={}", i, num_vectors);

            // Validate num_vectors is reasonable (防止破坏的数据导致内存分配溢出)
            const MAX_CLUSTER_SIZE: usize = 1_000_000; // 1M vectors per cluster is very large
            if num_vectors > MAX_CLUSTER_SIZE {
                return Err(RabitqError::InvalidPersistence(
                    "cluster size exceeds reasonable limits - possible corruption",
                ));
            }

            // Load vector IDs
            let mut ids = Vec::with_capacity(num_vectors);
            for _ in 0..num_vectors {
                ids.push(usize_from_u64(read_u64(&mut reader, Some(&mut hasher))?)?);
            }

            // Load batch_data (contiguous memory block)
            let batch_data_len = usize_from_u64(read_u64(&mut reader, Some(&mut hasher))?)?;

            // Validate batch_data_len is reasonable
            let total_batches = num_vectors.div_ceil(simd::FASTSCAN_BATCH_SIZE);
            let expected_batch_data_len = ClusterData::batch_stride(padded_dim) * total_batches;
            if batch_data_len != expected_batch_data_len {
                eprintln!("DEBUG: batch_data_len mismatch");
                eprintln!("  num_vectors: {}", num_vectors);
                eprintln!("  padded_dim: {}", padded_dim);
                eprintln!("  total_batches: {}", total_batches);
                eprintln!("  batch_stride: {}", ClusterData::batch_stride(padded_dim));
                eprintln!("  expected: {}", expected_batch_data_len);
                eprintln!("  actual: {}", batch_data_len);
                return Err(RabitqError::InvalidPersistence(
                    "batch_data length mismatch - possible corruption or version incompatibility",
                ));
            }

            let mut batch_data = crate::memory::allocate_aligned_vec::<u8>(batch_data_len);
            reader.read_exact(&mut batch_data)?;
            hasher.update(&batch_data);

            // Load packed ex_codes (C++-style on-demand unpacking)
            eprintln!(
                "DEBUG LOAD: Cluster {}: Loading {} ex_codes_packed",
                i, num_vectors
            );
            let mut ex_codes_packed = Vec::with_capacity(num_vectors);
            for j in 0..num_vectors {
                let ex_code_len = usize_from_u64(read_u64(&mut reader, Some(&mut hasher))?)?;
                if j < 2 {
                    eprintln!(
                        "DEBUG LOAD: Cluster {}: ex_code_packed[{}].len()={}",
                        i, j, ex_code_len
                    );
                }

                // Validate ex_code_len is reasonable
                // When ex_bits = 0, ex_code_len should be 0
                // When ex_bits > 0, ex_code_len should equal (padded_dim * ex_bits / 8)
                let expected_ex_code_len = if ex_bits > 0 {
                    padded_dim * ex_bits / 8
                } else {
                    0
                };
                if ex_code_len != expected_ex_code_len {
                    return Err(RabitqError::InvalidPersistence(
                        "ex_code_packed length mismatch - possible corruption or version incompatibility",
                    ));
                }

                let mut ex_code_packed = vec![0u8; ex_code_len];
                reader.read_exact(&mut ex_code_packed)?;
                hasher.update(&ex_code_packed);
                ex_codes_packed.push(ex_code_packed);
            }

            // Load ex parameters
            let mut f_add_ex = Vec::with_capacity(num_vectors);
            for _ in 0..num_vectors {
                f_add_ex.push(read_f32(&mut reader, Some(&mut hasher))?);
            }

            let mut f_rescale_ex = Vec::with_capacity(num_vectors);
            for _ in 0..num_vectors {
                f_rescale_ex.push(read_f32(&mut reader, Some(&mut hasher))?);
            }

            // Read delta (reconstruction parameters)
            let mut delta = Vec::with_capacity(num_vectors);
            for _ in 0..num_vectors {
                delta.push(read_f32(&mut reader, Some(&mut hasher))?);
            }

            // Read vl (reconstruction parameters)
            let mut vl = Vec::with_capacity(num_vectors);
            for _ in 0..num_vectors {
                vl.push(read_f32(&mut reader, Some(&mut hasher))?);
            }

            clusters.push(ClusterData {
                centroid,
                ids,
                batch_data,
                ex_codes_packed,
                f_add_ex,
                f_rescale_ex,
                delta,
                vl,
                num_vectors,
                padded_dim,
                ex_bits,
            });
        }

        let actual_vectors: usize = clusters.iter().map(|c| c.num_vectors).sum();
        if actual_vectors != expected_vectors {
            return Err(RabitqError::InvalidPersistence(
                "vector count metadata mismatch",
            ));
        }

        let computed_checksum = hasher.finalize();
        let stored_checksum = read_u32(&mut reader, None)?;
        if computed_checksum != stored_checksum {
            return Err(RabitqError::InvalidPersistence("checksum mismatch"));
        }

        println!("Loaded index with unified memory layout (V3)");

        let ip_func = crate::simd::select_excode_ipfunc(ex_bits);

        Ok(Self {
            dim,
            padded_dim,
            metric,
            rotator,
            clusters,
            ex_bits,
            ip_func,
        })
    }

    /// Search for the nearest neighbours of the provided query vector.
    pub fn search(
        &self,
        query: &[f32],
        params: SearchParams,
    ) -> Result<Vec<SearchResult>, RabitqError> {
        self.search_fastscan(query, params, None, None)
    }

    /// Search for the nearest neighbours of the provided query vector,
    /// filtering results to only include vector IDs present in the provided bitmap.
    ///
    /// # Arguments
    /// * `query` - The query vector
    /// * `params` - Search parameters (top_k, nprobe)
    /// * `filter` - A RoaringBitmap containing valid candidate vector IDs
    ///
    /// # Returns
    /// A vector of search results, sorted by score, containing only IDs present in the filter.
    pub fn search_filtered(
        &self,
        query: &[f32],
        params: SearchParams,
        filter: &RoaringBitmap,
    ) -> Result<Vec<SearchResult>, RabitqError> {
        self.search_fastscan(query, params, None, Some(filter))
    }

    /// Batch search for multiple queries in parallel using rayon
    ///
    /// # Performance
    /// Expected speedup: 2-8x on typical CPUs (depends on core count and batch size)
    ///
    /// # Arguments
    /// * `queries` - Slice of query vectors
    /// * `params` - Search parameters (top_k, nprobe)
    ///
    /// # Returns
    /// A vector of search results for each query, in the same order as the input queries
    pub fn batch_search(
        &self,
        queries: &[&[f32]],
        params: SearchParams,
    ) -> Vec<Result<Vec<SearchResult>, RabitqError>> {
        queries
            .par_iter()
            .map(|query| self.search(query, params))
            .collect()
    }

    fn search_fastscan(
        &self,
        query: &[f32],
        params: SearchParams,
        mut diagnostics: Option<&mut SearchDiagnostics>,
        filter: Option<&RoaringBitmap>,
    ) -> Result<Vec<SearchResult>, RabitqError> {
        if self.is_empty() {
            return Err(RabitqError::EmptyIndex);
        }
        if query.len() != self.dim {
            return Err(RabitqError::DimensionMismatch {
                expected: self.dim,
                got: query.len(),
            });
        }

        // FastScan V2 is the default search method (Session 10)
        // Binary code bit order fixed in Session 9 (MSB-first to match C++)
        // Session 11: FastScan now supports all bit configurations (ex_bits >= 0)

        // Precompute query constants once to avoid repeated calculations
        let rotated_query = self.rotator.rotate(query);
        let mut query_precomp = QueryPrecomputed::new(rotated_query, self.ex_bits);

        // Build LUT for FastScan batch search
        query_precomp.build_lut(self.padded_dim);

        let mut cluster_scores: Vec<(usize, f32)> = Vec::with_capacity(self.clusters.len());
        for (cid, cluster) in self.clusters.iter().enumerate() {
            let score = match self.metric {
                Metric::L2 => l2_distance_sqr(&query_precomp.rotated_query, &cluster.centroid),
                Metric::InnerProduct => dot(&query_precomp.rotated_query, &cluster.centroid),
            };
            cluster_scores.push((cid, score));
        }

        let nprobe = params.nprobe.max(1).min(self.clusters.len());
        if params.top_k == 0 {
            return Ok(Vec::new());
        }

        // Optimization: Use partial sort instead of full sort
        // Only need the top nprobe clusters, not all clusters sorted
        // For nlist=4096, nprobe=64: saves ~90% of sorting work (10x faster)
        //
        // Important: Use stable secondary sort key (cluster ID) to ensure deterministic
        // behavior across architectures (x86 vs ARM). This prevents test failures on M1
        // while maintaining x86 performance.
        if nprobe < cluster_scores.len() {
            match self.metric {
                Metric::L2 => {
                    // Partition so that the nprobe smallest scores are at the front
                    // Use cluster ID as tiebreaker for deterministic ordering
                    cluster_scores.select_nth_unstable_by(nprobe, |a, b| {
                        a.1.total_cmp(&b.1).then_with(|| a.0.cmp(&b.0))
                    });
                    // Sort only the first nprobe elements
                    cluster_scores[..nprobe]
                        .sort_unstable_by(|a, b| a.1.total_cmp(&b.1).then_with(|| a.0.cmp(&b.0)));
                }
                Metric::InnerProduct => {
                    // Partition so that the nprobe largest scores are at the front
                    // Use cluster ID as tiebreaker for deterministic ordering
                    cluster_scores.select_nth_unstable_by(nprobe, |a, b| {
                        b.1.total_cmp(&a.1).then_with(|| a.0.cmp(&b.0))
                    });
                    // Sort only the first nprobe elements
                    cluster_scores[..nprobe]
                        .sort_unstable_by(|a, b| b.1.total_cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
                }
            }
        } else {
            // If nprobe >= cluster count, sort all (rare case)
            // Use cluster ID as tiebreaker for deterministic ordering
            match self.metric {
                Metric::L2 => cluster_scores
                    .sort_unstable_by(|a, b| a.1.total_cmp(&b.1).then_with(|| a.0.cmp(&b.0))),
                Metric::InnerProduct => cluster_scores
                    .sort_unstable_by(|a, b| b.1.total_cmp(&a.1).then_with(|| a.0.cmp(&b.0))),
            }
        }

        // Debug: print selected clusters (disabled)
        // println!("Selected {} clusters (nprobe={}): {:?}",
        //     cluster_scores.iter().take(nprobe).count(),
        //     nprobe,
        //     cluster_scores.iter().take(nprobe).map(|(cid, score)| (*cid, *score)).collect::<Vec<_>>()
        // );

        let mut heap: BinaryHeap<HeapEntry> = BinaryHeap::new();

        // Use FastScan batch search with unified memory layout
        for &(cid, _) in cluster_scores.iter().take(nprobe) {
            let cluster = &self.clusters[cid];

            let centroid_dist = l2_distance_sqr(&query_precomp.rotated_query, &cluster.centroid);
            let dot_query_centroid = dot(&query_precomp.rotated_query, &cluster.centroid);
            let g_add = match self.metric {
                Metric::L2 => centroid_dist,
                Metric::InnerProduct => -dot_query_centroid,
            };
            let centroid_norm = centroid_dist.sqrt();
            let g_error = centroid_norm;

            // Use batched search (3-10x faster than naive, further optimized with unified layout)
            self.search_cluster_v2_batched(
                cid,
                cluster,
                &query_precomp,
                g_add,
                g_error,
                dot_query_centroid,
                filter,
                &mut heap,
                params.top_k,
                &mut diagnostics,
            );
        }

        let mut candidates: Vec<HeapCandidate> = heap
            .into_sorted_vec()
            .into_iter()
            .map(|entry| entry.candidate)
            .collect();

        match self.metric {
            Metric::L2 => candidates.sort_by(|a, b| a.distance.total_cmp(&b.distance)),
            Metric::InnerProduct => candidates.sort_by(|a, b| b.score.total_cmp(&a.score)),
        }

        Ok(candidates
            .into_iter()
            .map(|candidate| SearchResult {
                id: candidate.id,
                score: match self.metric {
                    Metric::L2 => candidate.distance,
                    Metric::InnerProduct => candidate.score,
                },
            })
            .collect())
    }

    /// Helper method to search a cluster using batch FastScan with unified memory layout
    /// This processes vectors in batches of 32 for better SIMD performance
    /// Reference: C++ split_batch_estdist in estimator.hpp:25-71
    #[allow(clippy::too_many_arguments)]
    fn search_cluster_v2_batched(
        &self,
        _cluster_id: usize,
        cluster: &ClusterData,
        query_precomp: &QueryPrecomputed,
        g_add: f32,
        g_error: f32,
        dot_query_centroid: f32,
        filter: Option<&RoaringBitmap>,
        heap: &mut BinaryHeap<HeapEntry>,
        top_k: usize,
        diagnostics: &mut Option<&mut SearchDiagnostics>,
    ) {
        // Check if we should use high-accuracy mode
        let use_highacc = self.padded_dim > 2048;

        let lut_view = if use_highacc {
            query_precomp.lut_highacc.as_ref().map(|lut| {
                crate::fastscan_kernel::FastScanLutView::HighAcc {
                    lut_low8: &lut.lut_low8,
                    lut_high8: &lut.lut_high8,
                    delta: lut.delta,
                    sum_vl_lut: lut.sum_vl_lut,
                }
            })
        } else {
            query_precomp
                .lut
                .as_ref()
                .map(|lut| crate::fastscan_kernel::FastScanLutView::Regular {
                    lut_i8: &lut.lut_i8,
                    delta: lut.delta,
                    sum_vl_lut: lut.sum_vl_lut,
                })
        };

        let Some(lut_view) = lut_view else {
            return; // No LUT available, fallback needed
        };

        // Process complete batches (32 vectors each)
        let num_batches = cluster.num_complete_batches();
        let num_remainder = cluster.num_remainder_vectors();
        let total_batches = if num_remainder > 0 {
            num_batches + 1
        } else {
            num_batches
        };

        for batch_idx in 0..total_batches {
            let batch_start = batch_idx * simd::FASTSCAN_BATCH_SIZE;
            let batch_end = (batch_start + simd::FASTSCAN_BATCH_SIZE).min(cluster.num_vectors);
            let actual_batch_size = batch_end - batch_start;

            // Rely on CPU hardware prefetcher (like C++ version)
            // Manual prefetching removed to avoid cache pollution

            // Step 1: Accumulate distances using FastScan SIMD with zero-copy access
            // Get batch parameters using zero-copy slices
            let batch_f_add = cluster.batch_f_add(batch_idx);
            let batch_f_rescale = cluster.batch_f_rescale(batch_idx);
            let batch_f_error = cluster.batch_f_error(batch_idx);

            // Allocate output arrays on stack (no heap allocation)
            let mut ip_x0_qr_values = [0.0f32; simd::FASTSCAN_BATCH_SIZE];
            let mut est_distances = [0.0f32; simd::FASTSCAN_BATCH_SIZE];
            let mut lower_bounds = [0.0f32; simd::FASTSCAN_BATCH_SIZE];

            crate::fastscan_kernel::compute_fastscan_batch(
                lut_view,
                cluster.batch_bin_codes(batch_idx),
                self.padded_dim,
                batch_f_add,
                batch_f_rescale,
                batch_f_error,
                g_add,
                g_error,
                query_precomp.k1x_sum_q,
                &mut ip_x0_qr_values,
                &mut est_distances,
                &mut lower_bounds,
            );

            // Step 2: Process each vector in the batch (pruning and ex-code evaluation)
            // Distances are now pre-computed in vectorized fashion (matching C++ Eigen)
            for i in 0..actual_batch_size {
                let global_idx = batch_start + i;
                let vector_id = cluster.ids[global_idx];

                // Apply filter if provided
                if let Some(filter_bitmap) = filter {
                    if !filter_bitmap.contains(vector_id as u32) {
                        continue;
                    }
                }

                // Use pre-computed values (vectorized above)
                let ip_x0_qr = ip_x0_qr_values[i];
                let est_distance = est_distances[i];
                let lower_bound = crate::fastscan_kernel::sanitize_lower_bound(
                    lower_bounds[i],
                    self.metric,
                    dot_query_centroid,
                    query_precomp.query_norm,
                );

                // Step 3: Check against current k-th distance
                let distk = if heap.len() < top_k {
                    f32::INFINITY
                } else {
                    heap.peek()
                        .map(|entry| entry.candidate.distance)
                        .unwrap_or(f32::INFINITY)
                };

                if lower_bound >= distk {
                    if let Some(diag) = diagnostics.as_deref_mut() {
                        diag.skipped_by_lower_bound += 1;
                    }
                    continue;
                }

                // Step 4: Compute final distance with ex-codes if available
                let mut distance = est_distance;
                if self.ex_bits > 0 {
                    if let Some(diag) = diagnostics.as_deref_mut() {
                        diag.extended_evaluations += 1;
                    }

                    distance = crate::fastscan_kernel::refine_distance_with_ex(
                        &query_precomp.rotated_query,
                        &cluster.ex_codes_packed[global_idx],
                        self.padded_dim,
                        self.ex_bits,
                        ip_x0_qr,
                        query_precomp.binary_scale,
                        query_precomp.kbx_sum_q,
                        g_add,
                        cluster.f_add_ex[global_idx],
                        cluster.f_rescale_ex[global_idx],
                        Some(self.ip_func),
                    );
                }

                if !distance.is_finite() {
                    continue;
                }

                let score = match self.metric {
                    Metric::L2 => distance,
                    Metric::InnerProduct => -distance,
                };

                if let Some(diag) = diagnostics.as_deref_mut() {
                    diag.estimated += 1;
                }

                // Step 7: Update heap
                heap.push(HeapEntry {
                    candidate: HeapCandidate {
                        id: vector_id,
                        distance,
                        score,
                    },
                });

                if heap.len() > top_k {
                    heap.pop();
                }
            }
        }
    }

    #[cfg(test)]
    pub(crate) fn search_with_diagnostics(
        &self,
        query: &[f32],
        params: SearchParams,
    ) -> Result<(Vec<SearchResult>, SearchDiagnostics), RabitqError> {
        let mut diagnostics = SearchDiagnostics::default();
        let results = self.search_fastscan(query, params, Some(&mut diagnostics), None)?;
        Ok((results, diagnostics))
    }

    #[cfg(test)]
    pub(crate) fn search_naive(
        &self,
        query: &[f32],
        params: SearchParams,
    ) -> Result<Vec<SearchResult>, RabitqError> {
        if self.is_empty() {
            return Err(RabitqError::EmptyIndex);
        }
        if query.len() != self.dim {
            return Err(RabitqError::DimensionMismatch {
                expected: self.dim,
                got: query.len(),
            });
        }

        let rotated_query = self.rotator.rotate(query);
        let mut cluster_scores: Vec<(usize, f32)> = Vec::with_capacity(self.clusters.len());
        for (cid, cluster) in self.clusters.iter().enumerate() {
            let score = match self.metric {
                Metric::L2 => l2_distance_sqr(&rotated_query, &cluster.centroid),
                Metric::InnerProduct => dot(&rotated_query, &cluster.centroid),
            };
            cluster_scores.push((cid, score));
        }

        match self.metric {
            Metric::L2 => cluster_scores.sort_by(|a, b| a.1.total_cmp(&b.1)),
            Metric::InnerProduct => cluster_scores.sort_by(|a, b| b.1.total_cmp(&a.1)),
        }

        let nprobe = params.nprobe.max(1).min(self.clusters.len());
        let mut candidates = Vec::new();
        let sum_query: f32 = rotated_query.iter().sum();
        let c1 = -0.5f32;
        let binary_scale = (1 << self.ex_bits) as f32;
        let cb = -((1 << self.ex_bits) as f32 - 0.5);
        for &(cid, _) in cluster_scores.iter().take(nprobe) {
            let cluster = &self.clusters[cid];
            let centroid_dist = l2_distance_sqr(&rotated_query, &cluster.centroid);
            let dot_query_centroid = dot(&rotated_query, &cluster.centroid);
            let g_add = match self.metric {
                Metric::L2 => centroid_dist,
                Metric::InnerProduct => -dot_query_centroid,
            };
            for vec_idx in 0..cluster.num_vectors {
                // Extract data for this vector using ClusterData API
                let f_add = cluster.get_vector_f_add(vec_idx);
                let f_rescale = cluster.get_vector_f_rescale(vec_idx);

                // Unpack binary code on-demand from FastScan batch layout
                // Note: This is only used in naive search (test code)
                let batch_idx = vec_idx / simd::FASTSCAN_BATCH_SIZE;
                let in_batch_idx = vec_idx % simd::FASTSCAN_BATCH_SIZE;
                let packed_codes = cluster.batch_bin_codes(batch_idx);

                // Unpack binary code for this vector
                let dim_bytes = self.padded_dim / 8;
                let mut binary_code = vec![0u8; self.padded_dim];
                simd::unpack_single_vector(packed_codes, in_batch_idx, dim_bytes, &mut binary_code);

                let mut binary_dot = 0.0f32;
                for (&bit, &q_val) in binary_code.iter().zip(rotated_query.iter()) {
                    binary_dot += (bit as f32) * q_val;
                }
                let binary_term = binary_dot + c1 * sum_query;
                let mut distance = f_add + g_add + f_rescale * binary_term;

                if self.ex_bits > 0 {
                    // Direct SIMD dot product on packed data (C++-style, Phase 3)
                    let ex_code_packed = &cluster.ex_codes_packed[vec_idx];
                    let ex_dot = (self.ip_func)(&rotated_query, ex_code_packed, self.padded_dim);
                    let total_term = binary_scale * binary_dot + ex_dot + cb * sum_query;
                    distance = cluster.f_add_ex[vec_idx]
                        + g_add
                        + cluster.f_rescale_ex[vec_idx] * total_term;
                }
                if !distance.is_finite() {
                    continue;
                }
                let score = match self.metric {
                    Metric::L2 => distance,
                    Metric::InnerProduct => -distance,
                };
                candidates.push(SearchResult {
                    id: cluster.ids[vec_idx],
                    score,
                });
            }
        }

        match self.metric {
            Metric::L2 => candidates.sort_by(|a, b| a.score.total_cmp(&b.score)),
            Metric::InnerProduct => candidates.sort_by(|a, b| b.score.total_cmp(&a.score)),
        }

        candidates.truncate(params.top_k.min(candidates.len()));
        Ok(candidates)
    }
}

#[cfg(test)]
mod batch_search_tests {
    use super::*;
    use crate::quantizer::RabitqConfig;
    use rand::rngs::StdRng;
    use rand::{Rng, SeedableRng};

    fn random_vector(dim: usize, rng: &mut StdRng) -> Vec<f32> {
        (0..dim).map(|_| rng.gen::<f32>() * 2.0 - 1.0).collect()
    }

    #[test]
    fn test_lut_accumulate_matches_direct_dot() {
        // Minimal test to verify LUT-based dot product matches direct computation
        let dim = 64;
        let padded_dim = 64;
        let _ex_bits = 0;
        let mut rng = StdRng::seed_from_u64(12345);

        // Create a single vector
        let rotator = DynamicRotator::new(dim, RotatorType::FhtKacRotator, 42);
        let data_vec = random_vector(dim, &mut rng);
        let rotated_data = rotator.rotate(&data_vec);

        let query_vec = random_vector(dim, &mut rng);
        let rotated_query = rotator.rotate(&query_vec);

        // Quantize the data vector
        let config = RabitqConfig::new(1);
        let centroid = vec![0.0f32; padded_dim];
        let quantized =
            crate::quantizer::quantize_with_centroid(&rotated_data, &centroid, &config, Metric::L2);

        // V1: Direct dot product
        let binary_code_unpacked = quantized.unpack_binary_code();
        let binary_dot_v1 = crate::simd::dot_u8_f32(&binary_code_unpacked, &rotated_query);
        println!("V1 binary_dot: {:.6}", binary_dot_v1);
        println!(
            "First 16 binary_code_unpacked: {:?}",
            &binary_code_unpacked[0..16.min(binary_code_unpacked.len())]
        );
        println!(
            "First 16 rotated_query: {:?}",
            &rotated_query[0..16.min(rotated_query.len())]
        );

        // V2: LUT-based approach
        // Build LUT
        let table_length = padded_dim * 4;
        let mut lut_float = vec![0.0f32; table_length];
        crate::simd::pack_lut_f32(&rotated_query, &mut lut_float);

        // Quantize LUT
        let vl_lut = lut_float
            .iter()
            .copied()
            .min_by(|a, b| a.total_cmp(b))
            .unwrap_or(0.0);
        let vr_lut = lut_float
            .iter()
            .copied()
            .max_by(|a, b| a.total_cmp(b))
            .unwrap_or(0.0);
        let delta = (vr_lut - vl_lut) / 255.0f32;

        let mut lut_i8 = vec![0i8; table_length];
        if delta > 0.0 {
            for i in 0..table_length {
                let quantized = ((lut_float[i] - vl_lut) / delta).round();
                // Must convert to u8 first, then to i8 to avoid saturation
                // f32 as i8 saturates at 127, but we need wrapping behavior (128-255 -> -128 to -1)
                lut_i8[i] = (quantized.clamp(0.0, 255.0) as u8) as i8;
            }
        }

        let num_table = table_length / 16;
        let sum_vl_lut = vl_lut * (num_table as f32);

        println!("LUT delta: {:.6}, sum_vl_lut: {:.6}", delta, sum_vl_lut);
        println!("First 16 lut_float: {:?}", &lut_float[0..16]);

        // Print first 32 bytes of LUT as i8 and u8 for comparison
        print!("First 32 lut_i8 bytes (as i8): ");
        for val in lut_i8.iter().take(32) {
            print!("{} ", val);
        }
        println!();
        print!("First 32 lut_i8 bytes (as u8): ");
        for val in lut_i8.iter().take(32) {
            print!("{} ", *val as u8);
        }
        println!();

        // Print first few bytes of packed code
        println!(
            "First 2 packed bytes: {:08b} {:08b}",
            quantized.binary_code_packed[0], quantized.binary_code_packed[1]
        );

        // Manually compute what accumulate should return
        // Now with MSB-first packing, packed[0] bit 7 = binary_code_unpacked[0]
        let mut manual_accu_via_direct = 0.0f32;
        for (i, _) in rotated_query.iter().enumerate().take(padded_dim) {
            manual_accu_via_direct += binary_code_unpacked[i] as f32 * rotated_query[i];
        }
        println!(
            "Manual via direct dot product: {:.6}",
            manual_accu_via_direct
        );

        // Pack the binary code
        let dim_bytes = padded_dim / 8;
        let mut packed_codes = vec![0u8; 32 * dim_bytes];
        crate::simd::pack_codes(
            &quantized.binary_code_packed,
            1,
            dim_bytes,
            &mut packed_codes,
        );

        // Print packed_codes for comparison with C++
        print!("Rust packed_codes (all {} bytes): ", packed_codes.len());
        for (i, byte) in packed_codes.iter().enumerate() {
            if i > 0 && i % 16 == 0 {
                print!("\n  ");
            }
            print!("{:02x} ", byte);
        }
        println!();

        // Accumulate
        let mut accu_res = [0u16; 32];
        crate::simd::accumulate_batch_avx2(&packed_codes, &lut_i8, padded_dim, &mut accu_res);

        let accu = accu_res[0] as f32;
        let ip_x0_qr = delta * accu + sum_vl_lut;
        println!("V2 accu: {:.6}, ip_x0_qr: {:.6}", accu, ip_x0_qr);

        // Manually compute what accu should be using lut_float
        let mut expected_result = 0.0f32;
        for (i, _) in rotated_query.iter().enumerate().take(dim) {
            expected_result += binary_code_unpacked[i] as f32 * rotated_query[i];
        }
        println!("Expected (direct): {:.6}", expected_result);

        // Compute expected LUT accumulation manually
        // Each codebook covers 4 dimensions, and the 4-bit code indexes into 16 LUT entries
        let mut expected_accu_via_lut = 0i32;
        for codebook_idx in 0..(padded_dim / 4) {
            // Get the 4-bit code for this codebook from binary_code_unpacked
            // binary_code_unpacked is in MSB-first order within each byte
            let dim_base = codebook_idx * 4;
            let mut code = 0u8;
            for bit_idx in 0..4 {
                if binary_code_unpacked[dim_base + bit_idx] != 0 {
                    // KPOS tells us which bit position corresponds to which dimension
                    // But the code itself is just the 4 binary bits packed
                    code |= 1 << (3 - bit_idx); // MSB-first: dim_base+0 is MSB (bit 3)
                }
            }
            let lut_val = lut_i8[codebook_idx * 16 + code as usize];
            println!(
                "  Codebook {}: dims {}-{}, binary=[{},{},{},{}], code={}, lut_i8[{}]={}",
                codebook_idx,
                dim_base,
                dim_base + 3,
                binary_code_unpacked[dim_base],
                binary_code_unpacked[dim_base + 1],
                binary_code_unpacked[dim_base + 2],
                binary_code_unpacked[dim_base + 3],
                code,
                codebook_idx * 16 + code as usize,
                lut_val
            );
            expected_accu_via_lut += lut_val as i32;
        }
        println!("Expected accu via LUT: {}", expected_accu_via_lut);
        let expected_ip_x0_qr_via_lut = delta * (expected_accu_via_lut as f32) + sum_vl_lut;
        println!(
            "Expected ip_x0_qr via LUT: {:.6}",
            expected_ip_x0_qr_via_lut
        );

        // They should match within tolerance
        let diff = (binary_dot_v1 - ip_x0_qr).abs();
        println!("Difference: {:.6}", diff);
        assert!(
            diff < 0.01,
            "LUT-based result {:.6} doesn't match direct dot {:.6}",
            ip_x0_qr,
            binary_dot_v1
        );
    }

    #[test]
    fn test_batch_search_matches_per_vector_l2() {
        // Test parameters
        let dim = 64;
        let padded_dim = 64;
        let num_vectors = 96; // 3 batches of 32
        let ex_bits = 0; // Start with 1-bit only (no extended code)
        let total_bits = 1;
        let metric = Metric::L2;
        let mut rng = StdRng::seed_from_u64(12345);

        // Generate test data
        let centroid = vec![0.0f32; padded_dim];
        let mut data = Vec::with_capacity(num_vectors);
        let mut ids = Vec::with_capacity(num_vectors);
        for i in 0..num_vectors {
            data.push(random_vector(dim, &mut rng));
            ids.push(i);
        }

        // Quantize vectors
        let config = RabitqConfig::new(total_bits);
        let rotator = DynamicRotator::new(dim, RotatorType::FhtKacRotator, 42);
        let rotated_data: Vec<Vec<f32>> = data.iter().map(|v| rotator.rotate(v)).collect();
        let quantized_vectors: Vec<QuantizedVector> = rotated_data
            .iter()
            .map(|v| quantize_with_centroid(v, &centroid, &config, metric))
            .collect();

        // Create cluster with unified memory layout
        let cluster = ClusterData::from_quantized_vectors(
            centroid.clone(),
            ids.clone(),
            quantized_vectors.clone(),
            padded_dim,
            ex_bits,
        );

        // Generate query
        let query = random_vector(dim, &mut rng);
        let rotated_query = rotator.rotate(&query);
        let mut query_precomp = QueryPrecomputed::new(rotated_query.clone(), ex_bits);
        query_precomp.build_lut(padded_dim);

        // Debug LUT parameters
        if let Some(ref lut) = query_precomp.lut {
            println!("\n=== L2 Test LUT params ===");
            println!(
                "delta={:.6}, sum_vl_lut={:.6}, k1x_sum_q={:.6}",
                lut.delta, lut.sum_vl_lut, query_precomp.k1x_sum_q
            );
            println!("First 8 LUT values: {:?}\n", &lut.lut_i8[0..8]);
        }

        // Compute cluster statistics
        let centroid_dist = l2_distance_sqr(&rotated_query, &centroid);
        let dot_query_centroid = dot(&rotated_query, &centroid);
        let g_add = centroid_dist;
        let g_error = centroid_dist.sqrt();

        // Simulate index for batch search
        let ip_func = crate::simd::select_excode_ipfunc(ex_bits);
        let index = IvfRabitqIndex {
            dim,
            padded_dim,
            metric,
            rotator: rotator.clone(),
            clusters: vec![cluster.clone()],
            ex_bits,
            ip_func,
        };

        // Batch search (unified memory layout)
        let mut heap: BinaryHeap<HeapEntry> = BinaryHeap::new();
        let top_k = 10;
        let mut diag = SearchDiagnostics::default();
        let mut diagnostics = Some(&mut diag);
        index.search_cluster_v2_batched(
            0, // Single cluster test
            &cluster,
            &query_precomp,
            g_add,
            g_error,
            dot_query_centroid,
            None,
            &mut heap,
            top_k,
            &mut diagnostics,
        );

        // Convert heap to sorted vector
        let mut results: Vec<HeapCandidate> = heap
            .into_sorted_vec()
            .into_iter()
            .map(|e| e.candidate)
            .collect();
        results.sort_by(|a, b| a.distance.total_cmp(&b.distance));

        // Verify we got reasonable results
        assert!(!results.is_empty(), "Should find at least one result");
        assert!(results.len() <= top_k, "Should not exceed top_k");

        // Print results for debugging
        println!("\n=== Search Results (top 10) ===");
        for (i, r) in results.iter().take(10).enumerate() {
            println!("  [{}] ID={}, distance={:.6}", i, r.id, r.distance);
        }

        // Verify all distances are finite and non-negative for L2
        for r in &results {
            assert!(r.distance.is_finite(), "Distance should be finite");
            assert!(r.distance >= 0.0, "L2 distance should be non-negative");
        }

        // Verify results are sorted by distance (ascending for L2)
        for i in 0..results.len().saturating_sub(1) {
            assert!(
                results[i].distance <= results[i + 1].distance,
                "Results should be sorted by distance ascending"
            );
        }
    }

    #[test]
    fn test_batch_search_matches_per_vector_ip() {
        // Test parameters
        let dim = 64;
        let padded_dim = 64;
        let num_vectors = 64; // 2 batches of 32
        let ex_bits = 0; // Start with 1-bit only
        let total_bits = 1;
        let metric = Metric::InnerProduct;
        let mut rng = StdRng::seed_from_u64(54321);

        // Generate test data
        let centroid = vec![0.0f32; padded_dim];
        let mut data = Vec::with_capacity(num_vectors);
        let mut ids = Vec::with_capacity(num_vectors);
        for i in 0..num_vectors {
            data.push(random_vector(dim, &mut rng));
            ids.push(i);
        }

        // Quantize vectors
        let config = RabitqConfig::new(total_bits);
        let rotator = DynamicRotator::new(dim, RotatorType::FhtKacRotator, 42);
        let rotated_data: Vec<Vec<f32>> = data.iter().map(|v| rotator.rotate(v)).collect();
        let quantized_vectors: Vec<QuantizedVector> = rotated_data
            .iter()
            .map(|v| quantize_with_centroid(v, &centroid, &config, metric))
            .collect();

        // Create unified cluster
        let cluster = ClusterData::from_quantized_vectors(
            centroid.clone(),
            ids.clone(),
            quantized_vectors,
            padded_dim,
            ex_bits,
        );

        // Generate query
        let query = random_vector(dim, &mut rng);
        let rotated_query = rotator.rotate(&query);
        let mut query_precomp = QueryPrecomputed::new(rotated_query.clone(), ex_bits);
        query_precomp.build_lut(padded_dim);

        // Compute cluster statistics
        let dot_query_centroid = dot(&rotated_query, &centroid);
        let g_add = -dot_query_centroid;
        let centroid_norm = centroid.iter().map(|x| x * x).sum::<f32>().sqrt();
        let g_error = centroid_norm;

        // Simulate index
        let ip_func = crate::simd::select_excode_ipfunc(ex_bits);
        let index = IvfRabitqIndex {
            dim,
            padded_dim,
            metric,
            rotator: rotator.clone(),
            clusters: vec![cluster.clone()],
            ex_bits,
            ip_func,
        };

        // Perform batch search
        let mut heap: BinaryHeap<HeapEntry> = BinaryHeap::new();
        let top_k = 5;
        let mut diag = SearchDiagnostics::default();
        let mut diagnostics = Some(&mut diag);
        index.search_cluster_v2_batched(
            0, // Single cluster test
            &cluster,
            &query_precomp,
            g_add,
            g_error,
            dot_query_centroid,
            None,
            &mut heap,
            top_k,
            &mut diagnostics,
        );

        // Convert and sort results by score (IP uses score, not distance)
        let mut results: Vec<HeapCandidate> = heap
            .into_sorted_vec()
            .into_iter()
            .map(|e| e.candidate)
            .collect();
        results.sort_by(|a, b| b.score.total_cmp(&a.score));

        // Verify we got reasonable results
        assert!(!results.is_empty(), "Should find at least one result");
        assert!(results.len() <= top_k, "Should not exceed top_k");

        // Verify all scores are finite
        for r in &results {
            assert!(r.score.is_finite(), "Score should be finite");
            assert!(r.distance.is_finite(), "Distance should be finite");
        }

        // Verify results are sorted by score (descending for IP)
        for i in 0..results.len().saturating_sub(1) {
            assert!(
                results[i].score >= results[i + 1].score,
                "Results should be sorted by score descending"
            );
        }
    }
}