next-plaid 1.2.0

CPU-based PLAID implementation for multi-vector search using ndarray
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
//! Memory-mapped file support for efficient large index loading.
//!
//! This module provides utilities for loading large arrays from disk using
//! memory-mapped files, avoiding the need to load entire arrays into RAM.
//!
//! Two formats are supported:
//! - Custom raw binary format (legacy): 8-byte header with shape, then raw data
//! - NPY format: Standard NumPy format with header, used for index files

use std::collections::HashMap;
use std::fs;
use std::fs::File;
use std::io::{BufReader, BufWriter, Write};
use std::path::Path;

use byteorder::{LittleEndian, ReadBytesExt};
use fs2::FileExt;
use memmap2::{Mmap, MmapMut};
use ndarray::{Array1, Array2, ArrayView1, ArrayView2};

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

/// RAII guard for file-based locking to coordinate concurrent processes.
/// The lock is released when this guard is dropped.
struct FileLockGuard {
    _file: File,
}

impl FileLockGuard {
    /// Acquire an exclusive lock on the given lock file path.
    /// Creates the lock file if it doesn't exist.
    /// Blocks until the lock is acquired.
    fn acquire(lock_path: &Path) -> Result<Self> {
        let file = std::fs::OpenOptions::new()
            .read(true)
            .write(true)
            .create(true)
            .truncate(false)
            .open(lock_path)
            .map_err(|e| {
                Error::IndexLoad(format!("Failed to open lock file {:?}: {}", lock_path, e))
            })?;

        file.lock_exclusive().map_err(|e| {
            Error::IndexLoad(format!("Failed to acquire lock on {:?}: {}", lock_path, e))
        })?;

        Ok(Self { _file: file })
    }
}

impl Drop for FileLockGuard {
    fn drop(&mut self) {
        // Lock is automatically released when file is closed
        let _ = self._file.unlock();
    }
}

/// A memory-mapped array of f32 values.
///
/// This struct provides zero-copy access to large arrays stored on disk.
pub struct MmapArray2F32 {
    _mmap: Mmap,
    shape: (usize, usize),
    data_offset: usize,
}

impl MmapArray2F32 {
    /// Load a 2D f32 array from a raw binary file.
    ///
    /// The file format is:
    /// - 8 bytes: nrows (i64 little-endian)
    /// - 8 bytes: ncols (i64 little-endian)
    /// - nrows * ncols * 4 bytes: f32 data (little-endian)
    pub fn from_raw_file(path: &Path) -> Result<Self> {
        let file = File::open(path)
            .map_err(|e| Error::IndexLoad(format!("Failed to open file {:?}: {}", path, e)))?;

        let mmap = unsafe {
            Mmap::map(&file)
                .map_err(|e| Error::IndexLoad(format!("Failed to mmap file {:?}: {}", path, e)))?
        };

        if mmap.len() < 16 {
            return Err(Error::IndexLoad("File too small for header".into()));
        }

        // Read shape from header
        let mut cursor = std::io::Cursor::new(&mmap[..16]);
        let nrows = cursor
            .read_i64::<LittleEndian>()
            .map_err(|e| Error::IndexLoad(format!("Failed to read nrows: {}", e)))?
            as usize;
        let ncols = cursor
            .read_i64::<LittleEndian>()
            .map_err(|e| Error::IndexLoad(format!("Failed to read ncols: {}", e)))?
            as usize;

        let expected_size = 16 + nrows * ncols * 4;
        if mmap.len() < expected_size {
            return Err(Error::IndexLoad(format!(
                "File size {} too small for shape ({}, {})",
                mmap.len(),
                nrows,
                ncols
            )));
        }

        Ok(Self {
            _mmap: mmap,
            shape: (nrows, ncols),
            data_offset: 16,
        })
    }

    /// Get the shape of the array.
    pub fn shape(&self) -> (usize, usize) {
        self.shape
    }

    /// Get the number of rows.
    pub fn nrows(&self) -> usize {
        self.shape.0
    }

    /// Get the number of columns.
    pub fn ncols(&self) -> usize {
        self.shape.1
    }

    /// Get a view of a row.
    pub fn row(&self, idx: usize) -> ArrayView1<'_, f32> {
        let start = self.data_offset + idx * self.shape.1 * 4;
        let bytes = &self._mmap[start..start + self.shape.1 * 4];

        // Safety: We've verified the bounds and alignment
        let data =
            unsafe { std::slice::from_raw_parts(bytes.as_ptr() as *const f32, self.shape.1) };

        ArrayView1::from_shape(self.shape.1, data).unwrap()
    }

    /// Load a range of rows into an owned Array2.
    pub fn load_rows(&self, start: usize, end: usize) -> Array2<f32> {
        let nrows = end - start;
        let byte_start = self.data_offset + start * self.shape.1 * 4;
        let byte_end = self.data_offset + end * self.shape.1 * 4;
        let bytes = &self._mmap[byte_start..byte_end];

        // Safety: We've verified the bounds
        let data = unsafe {
            std::slice::from_raw_parts(bytes.as_ptr() as *const f32, nrows * self.shape.1)
        };

        Array2::from_shape_vec((nrows, self.shape.1), data.to_vec()).unwrap()
    }

    /// Convert to an owned Array2 (loads all data into memory).
    pub fn to_owned(&self) -> Array2<f32> {
        self.load_rows(0, self.shape.0)
    }
}

/// A memory-mapped array of u8 values.
pub struct MmapArray2U8 {
    _mmap: Mmap,
    shape: (usize, usize),
    data_offset: usize,
}

impl MmapArray2U8 {
    /// Load a 2D u8 array from a raw binary file.
    pub fn from_raw_file(path: &Path) -> Result<Self> {
        let file = File::open(path)
            .map_err(|e| Error::IndexLoad(format!("Failed to open file {:?}: {}", path, e)))?;

        let mmap = unsafe {
            Mmap::map(&file)
                .map_err(|e| Error::IndexLoad(format!("Failed to mmap file {:?}: {}", path, e)))?
        };

        if mmap.len() < 16 {
            return Err(Error::IndexLoad("File too small for header".into()));
        }

        let mut cursor = std::io::Cursor::new(&mmap[..16]);
        let nrows = cursor
            .read_i64::<LittleEndian>()
            .map_err(|e| Error::IndexLoad(format!("Failed to read nrows: {}", e)))?
            as usize;
        let ncols = cursor
            .read_i64::<LittleEndian>()
            .map_err(|e| Error::IndexLoad(format!("Failed to read ncols: {}", e)))?
            as usize;

        let expected_size = 16 + nrows * ncols;
        if mmap.len() < expected_size {
            return Err(Error::IndexLoad(format!(
                "File size {} too small for shape ({}, {})",
                mmap.len(),
                nrows,
                ncols
            )));
        }

        Ok(Self {
            _mmap: mmap,
            shape: (nrows, ncols),
            data_offset: 16,
        })
    }

    /// Get the shape of the array.
    pub fn shape(&self) -> (usize, usize) {
        self.shape
    }

    /// Get a view of the data as ArrayView2.
    pub fn view(&self) -> ArrayView2<'_, u8> {
        let bytes = &self._mmap[self.data_offset..self.data_offset + self.shape.0 * self.shape.1];
        ArrayView2::from_shape(self.shape, bytes).unwrap()
    }

    /// Load a range of rows into an owned Array2.
    pub fn load_rows(&self, start: usize, end: usize) -> Array2<u8> {
        let nrows = end - start;
        let byte_start = self.data_offset + start * self.shape.1;
        let byte_end = self.data_offset + end * self.shape.1;
        let bytes = &self._mmap[byte_start..byte_end];

        Array2::from_shape_vec((nrows, self.shape.1), bytes.to_vec()).unwrap()
    }

    /// Convert to an owned Array2.
    pub fn to_owned(&self) -> Array2<u8> {
        self.load_rows(0, self.shape.0)
    }
}

/// A memory-mapped array of i64 values.
pub struct MmapArray1I64 {
    _mmap: Mmap,
    len: usize,
    data_offset: usize,
}

impl MmapArray1I64 {
    /// Load a 1D i64 array from a raw binary file.
    pub fn from_raw_file(path: &Path) -> Result<Self> {
        let file = File::open(path)
            .map_err(|e| Error::IndexLoad(format!("Failed to open file {:?}: {}", path, e)))?;

        let mmap = unsafe {
            Mmap::map(&file)
                .map_err(|e| Error::IndexLoad(format!("Failed to mmap file {:?}: {}", path, e)))?
        };

        if mmap.len() < 8 {
            return Err(Error::IndexLoad("File too small for header".into()));
        }

        let mut cursor = std::io::Cursor::new(&mmap[..8]);
        let len = cursor
            .read_i64::<LittleEndian>()
            .map_err(|e| Error::IndexLoad(format!("Failed to read length: {}", e)))?
            as usize;

        let expected_size = 8 + len * 8;
        if mmap.len() < expected_size {
            return Err(Error::IndexLoad(format!(
                "File size {} too small for length {}",
                mmap.len(),
                len
            )));
        }

        Ok(Self {
            _mmap: mmap,
            len,
            data_offset: 8,
        })
    }

    /// Get the length of the array.
    pub fn len(&self) -> usize {
        self.len
    }

    /// Returns true if the array is empty.
    pub fn is_empty(&self) -> bool {
        self.len == 0
    }

    /// Get a value at an index.
    pub fn get(&self, idx: usize) -> i64 {
        let start = self.data_offset + idx * 8;
        let bytes = &self._mmap[start..start + 8];
        i64::from_le_bytes(bytes.try_into().unwrap())
    }

    /// Convert to an owned Array1.
    pub fn to_owned(&self) -> Array1<i64> {
        let bytes = &self._mmap[self.data_offset..self.data_offset + self.len * 8];

        // Safety: We've verified the bounds
        let data = unsafe { std::slice::from_raw_parts(bytes.as_ptr() as *const i64, self.len) };

        Array1::from_vec(data.to_vec())
    }
}

/// Write an `Array2<f32>` to a raw binary file format.
pub fn write_array2_f32(array: &Array2<f32>, path: &Path) -> Result<()> {
    use std::io::Write;

    let file = File::create(path)
        .map_err(|e| Error::IndexLoad(format!("Failed to create file {:?}: {}", path, e)))?;
    let mut writer = std::io::BufWriter::new(file);

    let nrows = array.nrows() as i64;
    let ncols = array.ncols() as i64;

    writer
        .write_all(&nrows.to_le_bytes())
        .map_err(|e| Error::IndexLoad(format!("Failed to write nrows: {}", e)))?;
    writer
        .write_all(&ncols.to_le_bytes())
        .map_err(|e| Error::IndexLoad(format!("Failed to write ncols: {}", e)))?;

    for val in array.iter() {
        writer
            .write_all(&val.to_le_bytes())
            .map_err(|e| Error::IndexLoad(format!("Failed to write data: {}", e)))?;
    }

    writer
        .flush()
        .map_err(|e| Error::IndexLoad(format!("Failed to flush: {}", e)))?;

    Ok(())
}

/// Write an `Array2<u8>` to a raw binary file format.
pub fn write_array2_u8(array: &Array2<u8>, path: &Path) -> Result<()> {
    use std::io::Write;

    let file = File::create(path)
        .map_err(|e| Error::IndexLoad(format!("Failed to create file {:?}: {}", path, e)))?;
    let mut writer = std::io::BufWriter::new(file);

    let nrows = array.nrows() as i64;
    let ncols = array.ncols() as i64;

    writer
        .write_all(&nrows.to_le_bytes())
        .map_err(|e| Error::IndexLoad(format!("Failed to write nrows: {}", e)))?;
    writer
        .write_all(&ncols.to_le_bytes())
        .map_err(|e| Error::IndexLoad(format!("Failed to write ncols: {}", e)))?;

    for row in array.rows() {
        writer
            .write_all(row.as_slice().unwrap())
            .map_err(|e| Error::IndexLoad(format!("Failed to write data: {}", e)))?;
    }

    writer
        .flush()
        .map_err(|e| Error::IndexLoad(format!("Failed to flush: {}", e)))?;

    Ok(())
}

/// Write an `Array1<i64>` to a raw binary file format.
pub fn write_array1_i64(array: &Array1<i64>, path: &Path) -> Result<()> {
    use std::io::Write;

    let file = File::create(path)
        .map_err(|e| Error::IndexLoad(format!("Failed to create file {:?}: {}", path, e)))?;
    let mut writer = std::io::BufWriter::new(file);

    let len = array.len() as i64;

    writer
        .write_all(&len.to_le_bytes())
        .map_err(|e| Error::IndexLoad(format!("Failed to write length: {}", e)))?;

    for val in array.iter() {
        writer
            .write_all(&val.to_le_bytes())
            .map_err(|e| Error::IndexLoad(format!("Failed to write data: {}", e)))?;
    }

    writer
        .flush()
        .map_err(|e| Error::IndexLoad(format!("Failed to flush: {}", e)))?;

    Ok(())
}

// ============================================================================
// NPY Format Memory-Mapped Arrays
// ============================================================================

/// NPY file magic bytes
const NPY_MAGIC: &[u8] = b"\x93NUMPY";

/// Parse dtype from NPY header string (e.g., "<f2" for float16, "<f4" for float32)
fn parse_dtype_from_header(header: &str) -> Result<String> {
    // Find 'descr': '...'
    let descr_start = header
        .find("'descr':")
        .ok_or_else(|| Error::IndexLoad("No descr in NPY header".into()))?;

    let after_descr = &header[descr_start + 8..];
    let quote_start = after_descr
        .find('\'')
        .ok_or_else(|| Error::IndexLoad("No dtype quote in NPY header".into()))?;
    let rest = &after_descr[quote_start + 1..];
    let quote_end = rest
        .find('\'')
        .ok_or_else(|| Error::IndexLoad("Unclosed dtype quote in NPY header".into()))?;

    Ok(rest[..quote_end].to_string())
}

/// Detect NPY file dtype without loading the entire file
pub fn detect_npy_dtype(path: &Path) -> Result<String> {
    let file = File::open(path)
        .map_err(|e| Error::IndexLoad(format!("Failed to open NPY file {:?}: {}", path, e)))?;

    let mmap = unsafe {
        Mmap::map(&file)
            .map_err(|e| Error::IndexLoad(format!("Failed to mmap NPY file {:?}: {}", path, e)))?
    };

    if mmap.len() < 10 {
        return Err(Error::IndexLoad("NPY file too small".into()));
    }

    // Check magic
    if &mmap[..6] != NPY_MAGIC {
        return Err(Error::IndexLoad("Invalid NPY magic".into()));
    }

    let major_version = mmap[6];

    // Read header length
    let header_len = if major_version == 1 {
        u16::from_le_bytes([mmap[8], mmap[9]]) as usize
    } else if major_version == 2 {
        if mmap.len() < 12 {
            return Err(Error::IndexLoad("NPY v2 file too small".into()));
        }
        u32::from_le_bytes([mmap[8], mmap[9], mmap[10], mmap[11]]) as usize
    } else {
        return Err(Error::IndexLoad(format!(
            "Unsupported NPY version: {}",
            major_version
        )));
    };

    let header_start = if major_version == 1 { 10 } else { 12 };
    let header_end = header_start + header_len;

    if mmap.len() < header_end {
        return Err(Error::IndexLoad("NPY header exceeds file size".into()));
    }

    let header_str = std::str::from_utf8(&mmap[header_start..header_end])
        .map_err(|e| Error::IndexLoad(format!("Invalid NPY header encoding: {}", e)))?;

    parse_dtype_from_header(header_str)
}

/// Convert a float16 NPY file to float32 in place
pub fn convert_f16_to_f32_npy(path: &Path) -> Result<()> {
    use half::f16;
    use std::io::Read;

    // Read the entire file
    let mut file = File::open(path)
        .map_err(|e| Error::IndexLoad(format!("Failed to open {:?}: {}", path, e)))?;
    let mut data = Vec::new();
    file.read_to_end(&mut data)
        .map_err(|e| Error::IndexLoad(format!("Failed to read {:?}: {}", path, e)))?;

    if data.len() < 10 || &data[..6] != NPY_MAGIC {
        return Err(Error::IndexLoad("Invalid NPY file".into()));
    }

    let major_version = data[6];
    let header_start = if major_version == 1 { 10 } else { 12 };
    let header_len = if major_version == 1 {
        u16::from_le_bytes([data[8], data[9]]) as usize
    } else {
        u32::from_le_bytes([data[8], data[9], data[10], data[11]]) as usize
    };
    let header_end = header_start + header_len;

    // Parse header to get shape
    let header_str = std::str::from_utf8(&data[header_start..header_end])
        .map_err(|e| Error::IndexLoad(format!("Invalid header: {}", e)))?;
    let shape = parse_shape_from_header(header_str)?;

    // Calculate total elements
    let total_elements: usize = shape.iter().product();
    let f16_data = &data[header_end..header_end + total_elements * 2];

    // Convert f16 to f32
    let mut f32_data = Vec::with_capacity(total_elements * 4);
    for chunk in f16_data.chunks(2) {
        let f16_val = f16::from_le_bytes([chunk[0], chunk[1]]);
        let f32_val: f32 = f16_val.to_f32();
        f32_data.extend_from_slice(&f32_val.to_le_bytes());
    }

    // Write new file with f32 dtype
    let file = File::create(path)
        .map_err(|e| Error::IndexLoad(format!("Failed to create {:?}: {}", path, e)))?;
    let mut writer = BufWriter::new(file);

    if shape.len() == 1 {
        write_npy_header_1d(&mut writer, shape[0], "<f4")?;
    } else if shape.len() == 2 {
        write_npy_header_2d(&mut writer, shape[0], shape[1], "<f4")?;
    } else {
        return Err(Error::IndexLoad("Unsupported shape dimensions".into()));
    }

    writer
        .write_all(&f32_data)
        .map_err(|e| Error::IndexLoad(format!("Failed to write data: {}", e)))?;
    writer.flush()?;

    Ok(())
}

/// Convert an int64 NPY file to int32 in place
pub fn convert_i64_to_i32_npy(path: &Path) -> Result<()> {
    use std::io::Read;

    // Read the entire file
    let mut file = File::open(path)
        .map_err(|e| Error::IndexLoad(format!("Failed to open {:?}: {}", path, e)))?;
    let mut data = Vec::new();
    file.read_to_end(&mut data)
        .map_err(|e| Error::IndexLoad(format!("Failed to read {:?}: {}", path, e)))?;

    if data.len() < 10 || &data[..6] != NPY_MAGIC {
        return Err(Error::IndexLoad("Invalid NPY file".into()));
    }

    let major_version = data[6];
    let header_start = if major_version == 1 { 10 } else { 12 };
    let header_len = if major_version == 1 {
        u16::from_le_bytes([data[8], data[9]]) as usize
    } else {
        u32::from_le_bytes([data[8], data[9], data[10], data[11]]) as usize
    };
    let header_end = header_start + header_len;

    // Parse header to get shape
    let header_str = std::str::from_utf8(&data[header_start..header_end])
        .map_err(|e| Error::IndexLoad(format!("Invalid header: {}", e)))?;
    let shape = parse_shape_from_header(header_str)?;

    if shape.len() != 1 {
        return Err(Error::IndexLoad("Expected 1D array for i64->i32".into()));
    }

    let len = shape[0];
    let i64_data = &data[header_end..header_end + len * 8];

    // Convert i64 to i32
    let mut i32_data = Vec::with_capacity(len * 4);
    for chunk in i64_data.chunks(8) {
        let i64_val = i64::from_le_bytes(chunk.try_into().unwrap());
        let i32_val = i64_val as i32;
        i32_data.extend_from_slice(&i32_val.to_le_bytes());
    }

    // Write new file with i32 dtype
    let file = File::create(path)
        .map_err(|e| Error::IndexLoad(format!("Failed to create {:?}: {}", path, e)))?;
    let mut writer = BufWriter::new(file);

    write_npy_header_1d(&mut writer, len, "<i4")?;

    writer
        .write_all(&i32_data)
        .map_err(|e| Error::IndexLoad(format!("Failed to write data: {}", e)))?;
    writer.flush()?;

    Ok(())
}

/// Re-save a u8 NPY file to ensure dtype descriptor is "|u1" (platform-independent)
///
/// Note: We can't use ndarray_npy::ReadNpyExt here because it doesn't accept "<u1"
/// descriptor, so we manually read the raw data and resave with "|u1".
pub fn normalize_u8_npy(path: &Path) -> Result<()> {
    use std::io::Read;

    // Read the entire file
    let mut file = File::open(path)
        .map_err(|e| Error::IndexLoad(format!("Failed to open {:?}: {}", path, e)))?;
    let mut data = Vec::new();
    file.read_to_end(&mut data)
        .map_err(|e| Error::IndexLoad(format!("Failed to read {:?}: {}", path, e)))?;

    if data.len() < 10 || &data[..6] != NPY_MAGIC {
        return Err(Error::IndexLoad("Invalid NPY file".into()));
    }

    let major_version = data[6];
    let header_start = if major_version == 1 { 10 } else { 12 };
    let header_len = if major_version == 1 {
        u16::from_le_bytes([data[8], data[9]]) as usize
    } else {
        u32::from_le_bytes([data[8], data[9], data[10], data[11]]) as usize
    };
    let header_end = header_start + header_len;

    // Parse header to get shape
    let header_str = std::str::from_utf8(&data[header_start..header_end])
        .map_err(|e| Error::IndexLoad(format!("Invalid header: {}", e)))?;
    let shape = parse_shape_from_header(header_str)?;

    if shape.len() != 2 {
        return Err(Error::IndexLoad(
            "Expected 2D array for u8 normalization".into(),
        ));
    }

    let nrows = shape[0];
    let ncols = shape[1];
    let u8_data = &data[header_end..header_end + nrows * ncols];

    // Re-write with explicit "|u1" dtype
    let new_file = File::create(path)
        .map_err(|e| Error::IndexLoad(format!("Failed to create {:?}: {}", path, e)))?;
    let mut writer = BufWriter::new(new_file);

    write_npy_header_2d(&mut writer, nrows, ncols, "|u1")?;

    writer
        .write_all(u8_data)
        .map_err(|e| Error::IndexLoad(format!("Failed to write data: {}", e)))?;
    writer.flush()?;

    Ok(())
}

/// Parse NPY header and return (shape, data_offset, is_fortran_order)
fn parse_npy_header(mmap: &Mmap) -> Result<(Vec<usize>, usize, bool)> {
    if mmap.len() < 10 {
        return Err(Error::IndexLoad("NPY file too small".into()));
    }

    // Check magic
    if &mmap[..6] != NPY_MAGIC {
        return Err(Error::IndexLoad("Invalid NPY magic".into()));
    }

    let major_version = mmap[6];
    let _minor_version = mmap[7];

    // Read header length
    let header_len = if major_version == 1 {
        u16::from_le_bytes([mmap[8], mmap[9]]) as usize
    } else if major_version == 2 {
        if mmap.len() < 12 {
            return Err(Error::IndexLoad("NPY v2 file too small".into()));
        }
        u32::from_le_bytes([mmap[8], mmap[9], mmap[10], mmap[11]]) as usize
    } else {
        return Err(Error::IndexLoad(format!(
            "Unsupported NPY version: {}",
            major_version
        )));
    };

    let header_start = if major_version == 1 { 10 } else { 12 };
    let header_end = header_start + header_len;

    if mmap.len() < header_end {
        return Err(Error::IndexLoad("NPY header exceeds file size".into()));
    }

    // Parse header dict (simplified Python dict parsing)
    let header_str = std::str::from_utf8(&mmap[header_start..header_end])
        .map_err(|e| Error::IndexLoad(format!("Invalid NPY header encoding: {}", e)))?;

    // Extract shape from header like: {'descr': '<i8', 'fortran_order': False, 'shape': (12345,), }
    let shape = parse_shape_from_header(header_str)?;
    let fortran_order = header_str.contains("'fortran_order': True");

    Ok((shape, header_end, fortran_order))
}

/// Parse shape tuple from NPY header string
fn parse_shape_from_header(header: &str) -> Result<Vec<usize>> {
    // Find 'shape': (...)
    let shape_start = header
        .find("'shape':")
        .ok_or_else(|| Error::IndexLoad("No shape in NPY header".into()))?;

    let after_shape = &header[shape_start + 8..];
    let paren_start = after_shape
        .find('(')
        .ok_or_else(|| Error::IndexLoad("No shape tuple in NPY header".into()))?;
    let paren_end = after_shape
        .find(')')
        .ok_or_else(|| Error::IndexLoad("Unclosed shape tuple in NPY header".into()))?;

    let shape_content = &after_shape[paren_start + 1..paren_end];

    // Parse comma-separated numbers
    let mut shape = Vec::new();
    for part in shape_content.split(',') {
        let trimmed = part.trim();
        if !trimmed.is_empty() {
            let dim: usize = trimmed.parse().map_err(|e| {
                Error::IndexLoad(format!("Invalid shape dimension '{}': {}", trimmed, e))
            })?;
            shape.push(dim);
        }
    }

    Ok(shape)
}

/// Memory-mapped NPY array for i64 values (used for codes).
///
/// This struct provides zero-copy access to 1D i64 arrays stored in NPY format.
pub struct MmapNpyArray1I64 {
    _mmap: Mmap,
    len: usize,
    data_offset: usize,
}

impl MmapNpyArray1I64 {
    /// Create an empty instance backed by an anonymous mmap (no file).
    ///
    /// Used to release file-backed mmap handles before file operations on Windows,
    /// where deleting or renaming a memory-mapped file causes OS error 1224.
    pub fn empty() -> Self {
        let mmap = MmapMut::map_anon(1)
            .expect("failed to create anonymous mmap")
            .make_read_only()
            .expect("failed to make anonymous mmap read-only");
        Self {
            _mmap: mmap,
            len: 0,
            data_offset: 0,
        }
    }

    /// Load a 1D i64 array from an NPY file.
    pub fn from_npy_file(path: &Path) -> Result<Self> {
        let file = File::open(path)
            .map_err(|e| Error::IndexLoad(format!("Failed to open NPY file {:?}: {}", path, e)))?;

        let mmap = unsafe {
            Mmap::map(&file).map_err(|e| {
                Error::IndexLoad(format!("Failed to mmap NPY file {:?}: {}", path, e))
            })?
        };

        let (shape, data_offset, _fortran_order) = parse_npy_header(&mmap)?;

        if shape.is_empty() {
            return Err(Error::IndexLoad("Empty shape in NPY file".into()));
        }

        let len = shape[0];

        // Verify file size
        let expected_size = data_offset + len * 8;
        if mmap.len() < expected_size {
            return Err(Error::IndexLoad(format!(
                "NPY file size {} too small for {} elements",
                mmap.len(),
                len
            )));
        }

        Ok(Self {
            _mmap: mmap,
            len,
            data_offset,
        })
    }

    /// Get the length of the array.
    pub fn len(&self) -> usize {
        self.len
    }

    /// Returns true if the array is empty.
    pub fn is_empty(&self) -> bool {
        self.len == 0
    }

    /// Get a slice of the data as &[i64].
    ///
    /// Returns a `Vec<i64>` instead of &[i64] to handle unaligned data safely.
    ///
    /// # Safety
    /// The caller must ensure start <= end <= len.
    pub fn slice(&self, start: usize, end: usize) -> Vec<i64> {
        let count = end - start;
        let mut result = Vec::with_capacity(count);

        for i in start..end {
            result.push(self.get(i));
        }

        result
    }

    /// Get a value at an index.
    pub fn get(&self, idx: usize) -> i64 {
        let start = self.data_offset + idx * 8;
        let bytes = &self._mmap[start..start + 8];
        i64::from_le_bytes(bytes.try_into().unwrap())
    }
}

/// Memory-mapped NPY array for f32 values (used for centroids).
///
/// This struct provides zero-copy access to 2D f32 arrays stored in NPY format.
/// Unlike loading into an owned `Array2<f32>`, this approach lets the OS manage
/// paging, reducing resident memory usage for large centroid matrices.
pub struct MmapNpyArray2F32 {
    _mmap: Mmap,
    shape: (usize, usize),
    data_offset: usize,
}

impl MmapNpyArray2F32 {
    /// Load a 2D f32 array from an NPY file.
    pub fn from_npy_file(path: &Path) -> Result<Self> {
        let file = File::open(path)
            .map_err(|e| Error::IndexLoad(format!("Failed to open NPY file {:?}: {}", path, e)))?;

        let mmap = unsafe {
            Mmap::map(&file).map_err(|e| {
                Error::IndexLoad(format!("Failed to mmap NPY file {:?}: {}", path, e))
            })?
        };

        let (shape_vec, data_offset, _fortran_order) = parse_npy_header(&mmap)?;

        if shape_vec.len() != 2 {
            return Err(Error::IndexLoad(format!(
                "Expected 2D array, got {}D",
                shape_vec.len()
            )));
        }

        let shape = (shape_vec[0], shape_vec[1]);

        // Verify file size (f32 = 4 bytes)
        let expected_size = data_offset + shape.0 * shape.1 * 4;
        if mmap.len() < expected_size {
            return Err(Error::IndexLoad(format!(
                "NPY file size {} too small for shape {:?}",
                mmap.len(),
                shape
            )));
        }

        Ok(Self {
            _mmap: mmap,
            shape,
            data_offset,
        })
    }

    /// Get the shape of the array.
    pub fn shape(&self) -> (usize, usize) {
        self.shape
    }

    /// Get the number of rows.
    pub fn nrows(&self) -> usize {
        self.shape.0
    }

    /// Get the number of columns.
    pub fn ncols(&self) -> usize {
        self.shape.1
    }

    /// Get a view of the entire array as ArrayView2.
    ///
    /// This provides zero-copy access to the memory-mapped data.
    pub fn view(&self) -> ArrayView2<'_, f32> {
        let byte_start = self.data_offset;
        let byte_end = self.data_offset + self.shape.0 * self.shape.1 * 4;
        let bytes = &self._mmap[byte_start..byte_end];

        // Safety: We've verified bounds and f32 is 4-byte aligned in NPY format
        let data = unsafe {
            std::slice::from_raw_parts(bytes.as_ptr() as *const f32, self.shape.0 * self.shape.1)
        };

        ArrayView2::from_shape(self.shape, data).unwrap()
    }

    /// Get a view of a single row.
    pub fn row(&self, idx: usize) -> ArrayView1<'_, f32> {
        let byte_start = self.data_offset + idx * self.shape.1 * 4;
        let bytes = &self._mmap[byte_start..byte_start + self.shape.1 * 4];

        // Safety: We've verified bounds and alignment
        let data =
            unsafe { std::slice::from_raw_parts(bytes.as_ptr() as *const f32, self.shape.1) };

        ArrayView1::from_shape(self.shape.1, data).unwrap()
    }

    /// Get a view of rows [start..end] as ArrayView2.
    pub fn slice_rows(&self, start: usize, end: usize) -> ArrayView2<'_, f32> {
        let nrows = end - start;
        let byte_start = self.data_offset + start * self.shape.1 * 4;
        let byte_end = self.data_offset + end * self.shape.1 * 4;
        let bytes = &self._mmap[byte_start..byte_end];

        // Safety: We've verified bounds
        let data = unsafe {
            std::slice::from_raw_parts(bytes.as_ptr() as *const f32, nrows * self.shape.1)
        };

        ArrayView2::from_shape((nrows, self.shape.1), data).unwrap()
    }

    /// Convert to an owned Array2 (loads all data into memory).
    ///
    /// Use this only when you need an owned copy; prefer `view()` for read-only access.
    pub fn to_owned(&self) -> Array2<f32> {
        self.view().to_owned()
    }
}

/// Memory-mapped NPY array for u8 values (used for residuals).
///
/// This struct provides zero-copy access to 2D u8 arrays stored in NPY format.
pub struct MmapNpyArray2U8 {
    _mmap: Mmap,
    shape: (usize, usize),
    data_offset: usize,
}

impl MmapNpyArray2U8 {
    /// Create an empty instance backed by an anonymous mmap (no file).
    ///
    /// Used to release file-backed mmap handles before file operations on Windows,
    /// where deleting or renaming a memory-mapped file causes OS error 1224.
    pub fn empty() -> Self {
        let mmap = MmapMut::map_anon(1)
            .expect("failed to create anonymous mmap")
            .make_read_only()
            .expect("failed to make anonymous mmap read-only");
        Self {
            _mmap: mmap,
            shape: (0, 0),
            data_offset: 0,
        }
    }

    /// Load a 2D u8 array from an NPY file.
    pub fn from_npy_file(path: &Path) -> Result<Self> {
        let file = File::open(path)
            .map_err(|e| Error::IndexLoad(format!("Failed to open NPY file {:?}: {}", path, e)))?;

        let mmap = unsafe {
            Mmap::map(&file).map_err(|e| {
                Error::IndexLoad(format!("Failed to mmap NPY file {:?}: {}", path, e))
            })?
        };

        let (shape_vec, data_offset, _fortran_order) = parse_npy_header(&mmap)?;

        if shape_vec.len() != 2 {
            return Err(Error::IndexLoad(format!(
                "Expected 2D array, got {}D",
                shape_vec.len()
            )));
        }

        let shape = (shape_vec[0], shape_vec[1]);

        // Verify file size
        let expected_size = data_offset + shape.0 * shape.1;
        if mmap.len() < expected_size {
            return Err(Error::IndexLoad(format!(
                "NPY file size {} too small for shape {:?}",
                mmap.len(),
                shape
            )));
        }

        Ok(Self {
            _mmap: mmap,
            shape,
            data_offset,
        })
    }

    /// Get the shape of the array.
    pub fn shape(&self) -> (usize, usize) {
        self.shape
    }

    /// Get the number of rows.
    pub fn nrows(&self) -> usize {
        self.shape.0
    }

    /// Get the number of columns.
    pub fn ncols(&self) -> usize {
        self.shape.1
    }

    /// Get a view of rows [start..end] as ArrayView2.
    pub fn slice_rows(&self, start: usize, end: usize) -> ArrayView2<'_, u8> {
        let nrows = end - start;
        let byte_start = self.data_offset + start * self.shape.1;
        let byte_end = self.data_offset + end * self.shape.1;
        let bytes = &self._mmap[byte_start..byte_end];

        ArrayView2::from_shape((nrows, self.shape.1), bytes).unwrap()
    }

    /// Get a view of the entire array.
    pub fn view(&self) -> ArrayView2<'_, u8> {
        self.slice_rows(0, self.shape.0)
    }

    /// Get a single row as a slice.
    pub fn row(&self, idx: usize) -> &[u8] {
        let byte_start = self.data_offset + idx * self.shape.1;
        let byte_end = byte_start + self.shape.1;
        &self._mmap[byte_start..byte_end]
    }
}

// ============================================================================
// Merged File Creation
// ============================================================================

/// Manifest entry for tracking chunk files
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ChunkManifestEntry {
    pub rows: usize,
    pub mtime: f64,
}

/// Manifest for merged files, including metadata about the merge
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct MergeManifest {
    /// Chunk information
    pub chunks: HashMap<String, ChunkManifestEntry>,
    /// Number of padding rows used in the merge
    #[serde(default)]
    pub padding_rows: usize,
    /// Number of chunks expected (for fast-path validation)
    #[serde(default)]
    pub num_chunks: usize,
    /// Mtime of metadata.json at merge time (detects any index modifications)
    #[serde(default)]
    pub metadata_mtime: f64,
    /// Total rows in the merged file (including padding)
    #[serde(default)]
    pub total_rows: usize,
    /// Number of columns (for 2D arrays like residuals)
    #[serde(default)]
    pub ncols: usize,
}

/// Legacy manifest type (for backwards compatibility during migration)
pub type ChunkManifest = HashMap<String, ChunkManifestEntry>;

/// Load manifest from disk if it exists
/// Handles both new MergeManifest format and legacy ChunkManifest format
fn load_merge_manifest(manifest_path: &Path) -> Option<MergeManifest> {
    if manifest_path.exists() {
        if let Ok(file) = File::open(manifest_path) {
            // Try to load as new format first
            let reader = BufReader::new(file);
            if let Ok(manifest) = serde_json::from_reader::<_, MergeManifest>(reader) {
                return Some(manifest);
            }
            // Try legacy format
            if let Ok(file) = File::open(manifest_path) {
                if let Ok(chunks) =
                    serde_json::from_reader::<_, ChunkManifest>(BufReader::new(file))
                {
                    // Convert legacy format - missing padding info means we need to regenerate
                    return Some(MergeManifest {
                        chunks,
                        padding_rows: 0,
                        total_rows: 0,
                        ncols: 0,
                        num_chunks: 0,
                        metadata_mtime: 0.0,
                    });
                }
            }
        }
    }
    None
}

/// Save manifest to disk atomically (write to temp file, then rename)
fn save_merge_manifest(manifest_path: &Path, manifest: &MergeManifest) -> Result<()> {
    let temp_path = manifest_path.with_extension("manifest.json.tmp");

    // Write to temp file
    let file = File::create(&temp_path)
        .map_err(|e| Error::IndexLoad(format!("Failed to create temp manifest: {}", e)))?;
    let mut writer = BufWriter::new(file);
    serde_json::to_writer(&mut writer, manifest)
        .map_err(|e| Error::IndexLoad(format!("Failed to write manifest: {}", e)))?;
    writer
        .flush()
        .map_err(|e| Error::IndexLoad(format!("Failed to flush manifest: {}", e)))?;

    // Sync to disk
    writer
        .into_inner()
        .map_err(|e| Error::IndexLoad(format!("Failed to get inner file: {}", e)))?
        .sync_all()
        .map_err(|e| Error::IndexLoad(format!("Failed to sync manifest: {}", e)))?;

    // Atomic rename
    fs::rename(&temp_path, manifest_path)
        .map_err(|e| Error::IndexLoad(format!("Failed to rename manifest: {}", e)))?;

    Ok(())
}

/// Get file modification time as f64 seconds since epoch
fn get_mtime(path: &Path) -> Result<f64> {
    let metadata = fs::metadata(path)
        .map_err(|e| Error::IndexLoad(format!("Failed to get metadata for {:?}: {}", path, e)))?;
    let mtime = metadata
        .modified()
        .map_err(|e| Error::IndexLoad(format!("Failed to get mtime: {}", e)))?;
    let duration = mtime
        .duration_since(std::time::UNIX_EPOCH)
        .map_err(|e| Error::IndexLoad(format!("Invalid mtime: {}", e)))?;
    Ok(duration.as_secs_f64())
}

/// Build the NPY header dict string and compute the total header size (magic + version + len + padded dict).
fn npy_header_layout(header_dict: &str) -> (usize, usize) {
    let header_len = header_dict.len();
    let padding = (64 - ((10 + header_len) % 64)) % 64;
    let total = 10 + header_len + padding + 1; // +1 for the trailing newline
    (padding, total)
}

fn npy_header_dict_1d(len: usize, dtype: &str) -> String {
    format!(
        "{{'descr': '{}', 'fortran_order': False, 'shape': ({},), }}",
        dtype, len
    )
}

fn npy_header_dict_2d(nrows: usize, ncols: usize, dtype: &str) -> String {
    format!(
        "{{'descr': '{}', 'fortran_order': False, 'shape': ({}, {}), }}",
        dtype, nrows, ncols
    )
}

/// Compute the NPY header size for a 1D array (without writing).
fn npy_header_size_1d(len: usize, dtype: &str) -> usize {
    let dict = npy_header_dict_1d(len, dtype);
    npy_header_layout(&dict).1
}

/// Compute the NPY header size for a 2D array (without writing).
fn npy_header_size_2d(nrows: usize, ncols: usize, dtype: &str) -> usize {
    let dict = npy_header_dict_2d(nrows, ncols, dtype);
    npy_header_layout(&dict).1
}

/// Write an NPY header (shared implementation for 1D and 2D).
fn write_npy_header(writer: &mut impl Write, header_dict: &str) -> Result<usize> {
    let (padding, total) = npy_header_layout(header_dict);
    let padded_header = format!("{}{}\n", header_dict, " ".repeat(padding));

    // Write magic + version (v1.0)
    writer
        .write_all(NPY_MAGIC)
        .map_err(|e| Error::IndexLoad(format!("Failed to write NPY magic: {}", e)))?;
    writer
        .write_all(&[1, 0])
        .map_err(|e| Error::IndexLoad(format!("Failed to write version: {}", e)))?;

    // Write header length (2 bytes for v1.0)
    let header_len_bytes = (padded_header.len() as u16).to_le_bytes();
    writer
        .write_all(&header_len_bytes)
        .map_err(|e| Error::IndexLoad(format!("Failed to write header len: {}", e)))?;

    // Write header
    writer
        .write_all(padded_header.as_bytes())
        .map_err(|e| Error::IndexLoad(format!("Failed to write header: {}", e)))?;

    Ok(total)
}

/// Write NPY header for a 1D array
fn write_npy_header_1d(writer: &mut impl Write, len: usize, dtype: &str) -> Result<usize> {
    write_npy_header(writer, &npy_header_dict_1d(len, dtype))
}

/// Write NPY header for a 2D array
fn write_npy_header_2d(
    writer: &mut impl Write,
    nrows: usize,
    ncols: usize,
    dtype: &str,
) -> Result<usize> {
    write_npy_header(writer, &npy_header_dict_2d(nrows, ncols, dtype))
}

/// Information about a chunk file for merging
struct ChunkInfo {
    path: std::path::PathBuf,
    filename: String,
    rows: usize,
    mtime: f64,
}

/// Merge chunked codes NPY files into a single merged file.
///
/// Uses incremental persistence with manifest tracking to skip unchanged chunks.
/// Uses atomic writes to prevent corruption from interrupted writes.
/// Uses file-based locking to coordinate concurrent processes.
/// Returns the path to the merged file.
pub fn merge_codes_chunks(
    index_path: &Path,
    num_chunks: usize,
    padding_rows: usize,
) -> Result<std::path::PathBuf> {
    use ndarray_npy::ReadNpyExt;

    let merged_path = index_path.join("merged_codes.npy");
    let manifest_path = index_path.join("merged_codes.manifest.json");
    let temp_path = index_path.join("merged_codes.npy.tmp");
    let lock_path = index_path.join("merged_codes.lock");

    // Fast path: if manifest exists with matching params, metadata.json hasn't changed,
    // and merged file exists with correct size, skip chunk scanning entirely.
    let metadata_json_path = index_path.join("metadata.json");
    let current_metadata_mtime = get_mtime(&metadata_json_path).unwrap_or(0.0);
    if let Some(ref manifest) = load_merge_manifest(&manifest_path) {
        let mtime_matches = manifest.metadata_mtime > 0.0
            && (manifest.metadata_mtime - current_metadata_mtime).abs() < 0.001;
        if manifest.num_chunks == num_chunks
            && manifest.padding_rows == padding_rows
            && manifest.chunks.len() == num_chunks
            && manifest.total_rows > 0
            && mtime_matches
            && merged_path.exists()
        {
            if let Ok(meta) = std::fs::metadata(&merged_path) {
                let expected_size = npy_header_size_1d(manifest.total_rows, "<i8")
                    + manifest.total_rows * std::mem::size_of::<i64>();
                if meta.len() == expected_size as u64 {
                    return Ok(merged_path);
                }
            }
        }
    }

    // Acquire exclusive lock to prevent concurrent merge operations.
    // This is critical for multi-process scenarios (e.g., multiple API workers).
    let _lock = FileLockGuard::acquire(&lock_path)?;

    // After acquiring the lock, re-check if merge is still needed.
    // Another process might have completed the merge while we were waiting.

    // Load previous manifest (re-read after acquiring lock)
    let old_manifest = load_merge_manifest(&manifest_path);

    // Scan chunks and detect changes
    let mut chunks: Vec<ChunkInfo> = Vec::new();
    let mut total_rows = 0usize;
    let mut chain_broken = false;

    for i in 0..num_chunks {
        let filename = format!("{}.codes.npy", i);
        let path = index_path.join(&filename);

        if path.exists() {
            let mtime = get_mtime(&path)?;

            // Get shape by reading header only
            let file = File::open(&path)?;
            let arr: Array1<i64> = Array1::read_npy(file)?;
            let rows = arr.len();

            if rows > 0 {
                total_rows += rows;

                // Check if this chunk changed
                let is_clean = if let Some(ref manifest) = old_manifest {
                    manifest
                        .chunks
                        .get(&filename)
                        .is_some_and(|entry| entry.mtime == mtime && entry.rows == rows)
                } else {
                    false
                };

                if !is_clean {
                    chain_broken = true;
                }

                chunks.push(ChunkInfo {
                    path,
                    filename,
                    rows,
                    mtime,
                });
            }
        }
    }

    if total_rows == 0 {
        return Err(Error::IndexLoad("No data to merge".into()));
    }

    let final_rows = total_rows + padding_rows;

    // Check if we need to rewrite:
    // 1. Merged file doesn't exist
    // 2. Chunks have changed
    // 3. Padding has changed (stored in manifest)
    // 4. Total rows don't match (safety check)
    let padding_changed = old_manifest
        .as_ref()
        .map(|m| m.padding_rows != padding_rows)
        .unwrap_or(true);
    let total_rows_mismatch = old_manifest
        .as_ref()
        .map(|m| m.total_rows != final_rows)
        .unwrap_or(true);

    let needs_full_rewrite =
        !merged_path.exists() || chain_broken || padding_changed || total_rows_mismatch;

    if needs_full_rewrite {
        // Write to temp file first (atomic write pattern)
        let file = File::create(&temp_path)
            .map_err(|e| Error::IndexLoad(format!("Failed to create temp merged file: {}", e)))?;
        let mut writer = BufWriter::new(file);

        // Write header
        let header_size = write_npy_header_1d(&mut writer, final_rows, "<i8")?;

        // Write chunk data
        let mut written_rows = 0usize;
        for chunk in &chunks {
            let file = File::open(&chunk.path)?;
            let arr: Array1<i64> = Array1::read_npy(file)?;
            for &val in arr.iter() {
                writer.write_all(&val.to_le_bytes())?;
            }
            written_rows += arr.len();
        }

        // Write padding zeros
        for _ in 0..padding_rows {
            writer.write_all(&0i64.to_le_bytes())?;
        }
        written_rows += padding_rows;

        // Flush and sync to disk
        writer
            .flush()
            .map_err(|e| Error::IndexLoad(format!("Failed to flush merged file: {}", e)))?;
        let file = writer
            .into_inner()
            .map_err(|e| Error::IndexLoad(format!("Failed to get inner file: {}", e)))?;
        file.sync_all()
            .map_err(|e| Error::IndexLoad(format!("Failed to sync merged file to disk: {}", e)))?;

        // Verify file size before renaming
        let expected_size = header_size + written_rows * 8;
        let actual_size = fs::metadata(&temp_path)
            .map_err(|e| Error::IndexLoad(format!("Failed to get temp file metadata: {}", e)))?
            .len() as usize;

        if actual_size != expected_size {
            // Clean up temp file and return error
            let _ = fs::remove_file(&temp_path);
            return Err(Error::IndexLoad(format!(
                "Merged codes file size mismatch: expected {} bytes, got {} bytes",
                expected_size, actual_size
            )));
        }

        // Atomic rename (overwrites existing file)
        fs::rename(&temp_path, &merged_path)
            .map_err(|e| Error::IndexLoad(format!("Failed to rename merged file: {}", e)))?;
    } else {
        // Validate existing merged file before using it
        if merged_path.exists() {
            let file_size = fs::metadata(&merged_path)
                .map_err(|e| {
                    Error::IndexLoad(format!("Failed to get merged file metadata: {}", e))
                })?
                .len() as usize;

            // NPY header is at least 64 bytes, data is final_rows * 8 bytes
            let min_expected_size = 64 + final_rows * 8;
            if file_size < min_expected_size {
                // File is corrupted, force regeneration by recursing with empty manifest
                let _ = fs::remove_file(&merged_path);
                let _ = fs::remove_file(&manifest_path);
                // Lock is held, so we can safely drop it before recursing
                drop(_lock);
                return merge_codes_chunks(index_path, num_chunks, padding_rows);
            }
        }
    }

    // Build and save manifest with full metadata
    let mut chunk_map = HashMap::new();
    for chunk in &chunks {
        chunk_map.insert(
            chunk.filename.clone(),
            ChunkManifestEntry {
                rows: chunk.rows,
                mtime: chunk.mtime,
            },
        );
    }
    let new_manifest = MergeManifest {
        chunks: chunk_map,
        padding_rows,
        total_rows: final_rows,
        ncols: 0, // Not used for 1D codes array
        num_chunks,
        metadata_mtime: current_metadata_mtime,
    };
    save_merge_manifest(&manifest_path, &new_manifest)?;

    Ok(merged_path)
}

/// Merge chunked residuals NPY files into a single merged file.
///
/// Uses atomic writes to prevent corruption from interrupted writes.
/// Uses file-based locking to coordinate concurrent processes.
pub fn merge_residuals_chunks(
    index_path: &Path,
    num_chunks: usize,
    padding_rows: usize,
) -> Result<std::path::PathBuf> {
    use ndarray_npy::ReadNpyExt;

    let merged_path = index_path.join("merged_residuals.npy");
    let manifest_path = index_path.join("merged_residuals.manifest.json");
    let temp_path = index_path.join("merged_residuals.npy.tmp");
    let lock_path = index_path.join("merged_residuals.lock");

    // Fast path: if manifest exists with matching params, metadata.json hasn't changed,
    // and merged file has correct size, skip chunk scanning entirely.
    let metadata_json_path = index_path.join("metadata.json");
    let current_metadata_mtime = get_mtime(&metadata_json_path).unwrap_or(0.0);
    if let Some(ref manifest) = load_merge_manifest(&manifest_path) {
        if manifest.num_chunks == num_chunks
            && manifest.padding_rows == padding_rows
            && manifest.chunks.len() == num_chunks
            && manifest.total_rows > 0
            && manifest.ncols > 0
            && manifest.metadata_mtime > 0.0
            && (manifest.metadata_mtime - current_metadata_mtime).abs() < 0.001
            && merged_path.exists()
        {
            if let Ok(meta) = std::fs::metadata(&merged_path) {
                let expected_size = npy_header_size_2d(manifest.total_rows, manifest.ncols, "|u1")
                    + manifest.total_rows * manifest.ncols;
                if meta.len() == expected_size as u64 {
                    return Ok(merged_path);
                }
            }
        }
    }

    // Acquire exclusive lock to prevent concurrent merge operations.
    // This is critical for multi-process scenarios (e.g., multiple API workers).
    let _lock = FileLockGuard::acquire(&lock_path)?;

    // After acquiring the lock, re-check if merge is still needed.
    // Another process might have completed the merge while we were waiting.

    // Load previous manifest (re-read after acquiring lock)
    let old_manifest = load_merge_manifest(&manifest_path);

    // Scan chunks and detect changes
    let mut chunks: Vec<ChunkInfo> = Vec::new();
    let mut total_rows = 0usize;
    let mut ncols = 0usize;
    let mut chain_broken = false;

    for i in 0..num_chunks {
        let filename = format!("{}.residuals.npy", i);
        let path = index_path.join(&filename);

        if path.exists() {
            let mtime = get_mtime(&path)?;

            // Get shape by reading header
            let file = File::open(&path)?;
            let arr: Array2<u8> = Array2::read_npy(file)?;
            let rows = arr.nrows();
            ncols = arr.ncols();

            if rows > 0 {
                total_rows += rows;

                let is_clean = if let Some(ref manifest) = old_manifest {
                    manifest
                        .chunks
                        .get(&filename)
                        .is_some_and(|entry| entry.mtime == mtime && entry.rows == rows)
                } else {
                    false
                };

                if !is_clean {
                    chain_broken = true;
                }

                chunks.push(ChunkInfo {
                    path,
                    filename,
                    rows,
                    mtime,
                });
            }
        }
    }

    if total_rows == 0 || ncols == 0 {
        return Err(Error::IndexLoad("No residual data to merge".into()));
    }

    let final_rows = total_rows + padding_rows;

    // Check if we need to rewrite:
    // 1. Merged file doesn't exist
    // 2. Chunks have changed
    // 3. Padding has changed
    // 4. Total rows or ncols don't match
    let padding_changed = old_manifest
        .as_ref()
        .map(|m| m.padding_rows != padding_rows)
        .unwrap_or(true);
    let total_rows_mismatch = old_manifest
        .as_ref()
        .map(|m| m.total_rows != final_rows)
        .unwrap_or(true);
    let ncols_mismatch = old_manifest
        .as_ref()
        .map(|m| m.ncols != ncols && m.ncols != 0)
        .unwrap_or(false);

    let needs_full_rewrite = !merged_path.exists()
        || chain_broken
        || padding_changed
        || total_rows_mismatch
        || ncols_mismatch;

    if needs_full_rewrite {
        // Write to temp file first (atomic write pattern)
        let file = File::create(&temp_path)
            .map_err(|e| Error::IndexLoad(format!("Failed to create temp merged file: {}", e)))?;
        let mut writer = BufWriter::new(file);

        // Write header
        let header_size = write_npy_header_2d(&mut writer, final_rows, ncols, "|u1")?;

        // Write chunk data
        let mut written_rows = 0usize;
        for chunk in &chunks {
            let file = File::open(&chunk.path)?;
            let arr: Array2<u8> = Array2::read_npy(file)?;
            for row in arr.rows() {
                writer.write_all(row.as_slice().unwrap())?;
            }
            written_rows += arr.nrows();
        }

        // Write padding zeros
        let zero_row = vec![0u8; ncols];
        for _ in 0..padding_rows {
            writer.write_all(&zero_row)?;
        }
        written_rows += padding_rows;

        // Flush and sync to disk
        writer
            .flush()
            .map_err(|e| Error::IndexLoad(format!("Failed to flush merged residuals: {}", e)))?;
        let file = writer
            .into_inner()
            .map_err(|e| Error::IndexLoad(format!("Failed to get inner file: {}", e)))?;
        file.sync_all().map_err(|e| {
            Error::IndexLoad(format!("Failed to sync merged residuals to disk: {}", e))
        })?;

        // Verify file size before renaming
        let expected_size = header_size + written_rows * ncols;
        let actual_size = fs::metadata(&temp_path)
            .map_err(|e| Error::IndexLoad(format!("Failed to get temp file metadata: {}", e)))?
            .len() as usize;

        if actual_size != expected_size {
            // Clean up temp file and return error
            let _ = fs::remove_file(&temp_path);
            return Err(Error::IndexLoad(format!(
                "Merged residuals file size mismatch: expected {} bytes, got {} bytes",
                expected_size, actual_size
            )));
        }

        // Atomic rename
        fs::rename(&temp_path, &merged_path)
            .map_err(|e| Error::IndexLoad(format!("Failed to rename merged residuals: {}", e)))?;
    } else {
        // Validate existing merged file before using it
        if merged_path.exists() {
            let file_size = fs::metadata(&merged_path)
                .map_err(|e| {
                    Error::IndexLoad(format!("Failed to get merged file metadata: {}", e))
                })?
                .len() as usize;

            // NPY header is at least 64 bytes, data is final_rows * ncols bytes
            let min_expected_size = 64 + final_rows * ncols;
            if file_size < min_expected_size {
                // File is corrupted, force regeneration
                let _ = fs::remove_file(&merged_path);
                let _ = fs::remove_file(&manifest_path);
                // Lock is held, so we can safely drop it before recursing
                drop(_lock);
                return merge_residuals_chunks(index_path, num_chunks, padding_rows);
            }
        }
    }

    // Build and save manifest with full metadata
    let mut chunk_map = HashMap::new();
    for chunk in &chunks {
        chunk_map.insert(
            chunk.filename.clone(),
            ChunkManifestEntry {
                rows: chunk.rows,
                mtime: chunk.mtime,
            },
        );
    }
    let new_manifest = MergeManifest {
        chunks: chunk_map,
        padding_rows,
        total_rows: final_rows,
        ncols,
        num_chunks,
        metadata_mtime: current_metadata_mtime,
    };
    save_merge_manifest(&manifest_path, &new_manifest)?;

    Ok(merged_path)
}

/// Clear merged files and manifests to force regeneration on next load.
///
/// This should be called after index updates to ensure the merged files
/// are regenerated with the latest data. The function silently ignores
/// missing files.
///
/// Acquires file locks to prevent racing with concurrent merge operations
/// in multi-process deployments.
pub fn clear_merged_files(index_path: &Path) -> Result<()> {
    // Acquire locks to prevent racing with ongoing merge operations.
    // This is important in multi-process scenarios where one process might
    // be loading (merging) while another is updating (clearing).
    let codes_lock_path = index_path.join("merged_codes.lock");
    let residuals_lock_path = index_path.join("merged_residuals.lock");
    let _codes_lock = FileLockGuard::acquire(&codes_lock_path)?;
    let _residuals_lock = FileLockGuard::acquire(&residuals_lock_path)?;

    let files_to_remove = [
        "merged_codes.npy",
        "merged_codes.npy.tmp",
        "merged_codes.manifest.json",
        "merged_codes.manifest.json.tmp",
        "merged_residuals.npy",
        "merged_residuals.npy.tmp",
        "merged_residuals.manifest.json",
        "merged_residuals.manifest.json.tmp",
    ];

    for filename in files_to_remove {
        let path = index_path.join(filename);
        if path.exists() {
            fs::remove_file(&path)
                .map_err(|e| Error::IndexLoad(format!("Failed to remove {}: {}", filename, e)))?;
        }
    }

    Ok(())
}

// ============================================================================
// Fast-PLAID Compatibility Conversion
// ============================================================================

/// Convert a fast-plaid index to next-plaid compatible format.
///
/// This function detects and converts:
/// - float16 → float32 for centroids, avg_residual, bucket_cutoffs, bucket_weights
/// - int64 → int32 for ivf_lengths
/// - `<u1` → `|u1` for residuals
///
/// Returns true if any conversion was performed, false if already compatible.
pub fn convert_fastplaid_to_nextplaid(index_path: &Path) -> Result<bool> {
    let mut converted = false;

    // Float files to convert from f16 to f32
    let float_files = [
        "centroids.npy",
        "avg_residual.npy",
        "bucket_cutoffs.npy",
        "bucket_weights.npy",
    ];

    for filename in float_files {
        let path = index_path.join(filename);
        if path.exists() {
            let dtype = detect_npy_dtype(&path)?;
            if dtype == "<f2" {
                eprintln!("  Converting {} from float16 to float32", filename);
                convert_f16_to_f32_npy(&path)?;
                converted = true;
            }
        }
    }

    // Convert ivf_lengths from i64 to i32
    let ivf_lengths_path = index_path.join("ivf_lengths.npy");
    if ivf_lengths_path.exists() {
        let dtype = detect_npy_dtype(&ivf_lengths_path)?;
        if dtype == "<i8" {
            eprintln!("  Converting ivf_lengths.npy from int64 to int32");
            convert_i64_to_i32_npy(&ivf_lengths_path)?;
            converted = true;
        }
    }

    // Normalize residual files to use "|u1" descriptor
    // fast-plaid uses "<u1" which ndarray_npy doesn't accept
    for entry in fs::read_dir(index_path)? {
        let entry = entry?;
        let filename = entry.file_name().to_string_lossy().to_string();
        if filename.ends_with(".residuals.npy") {
            let path = entry.path();
            let dtype = detect_npy_dtype(&path)?;
            if dtype == "<u1" {
                eprintln!(
                    "  Normalizing {} dtype descriptor from <u1 to |u1",
                    filename
                );
                normalize_u8_npy(&path)?;
                converted = true;
            }
        }
    }

    Ok(converted)
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Write;
    use tempfile::NamedTempFile;

    #[test]
    fn test_mmap_array2_f32() {
        // Create a test file
        let mut file = NamedTempFile::new().unwrap();

        // Write header (3 rows, 2 cols)
        file.write_all(&3i64.to_le_bytes()).unwrap();
        file.write_all(&2i64.to_le_bytes()).unwrap();

        // Write data
        for val in [1.0f32, 2.0, 3.0, 4.0, 5.0, 6.0] {
            file.write_all(&val.to_le_bytes()).unwrap();
        }

        file.flush().unwrap();

        // Load and verify
        let mmap = MmapArray2F32::from_raw_file(file.path()).unwrap();
        assert_eq!(mmap.shape(), (3, 2));

        let row0 = mmap.row(0);
        assert_eq!(row0[0], 1.0);
        assert_eq!(row0[1], 2.0);

        let owned = mmap.to_owned();
        assert_eq!(owned[[2, 0]], 5.0);
        assert_eq!(owned[[2, 1]], 6.0);
    }

    #[test]
    fn test_mmap_array1_i64() {
        let mut file = NamedTempFile::new().unwrap();

        // Write header (4 elements)
        file.write_all(&4i64.to_le_bytes()).unwrap();

        // Write data
        for val in [10i64, 20, 30, 40] {
            file.write_all(&val.to_le_bytes()).unwrap();
        }

        file.flush().unwrap();

        let mmap = MmapArray1I64::from_raw_file(file.path()).unwrap();
        assert_eq!(mmap.len(), 4);
        assert_eq!(mmap.get(0), 10);
        assert_eq!(mmap.get(3), 40);

        let owned = mmap.to_owned();
        assert_eq!(owned[1], 20);
        assert_eq!(owned[2], 30);
    }

    #[test]
    fn test_write_read_roundtrip() {
        let file = NamedTempFile::new().unwrap();
        let path = file.path();

        // Create test array
        let array = Array2::from_shape_vec((2, 3), vec![1.0f32, 2.0, 3.0, 4.0, 5.0, 6.0]).unwrap();

        // Write
        write_array2_f32(&array, path).unwrap();

        // Read back
        let mmap = MmapArray2F32::from_raw_file(path).unwrap();
        let loaded = mmap.to_owned();

        assert_eq!(array, loaded);
    }
}