chassisdb 0.9.1

Chassis: an embedded vector index for local semantic search, in one file.
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
//! Chassis - an embedded vector index for local semantic search
//!
//! Chassis keeps an index of vectors in one file and searches it inside your
//! process, with no server. You store vectors under your own ids; the records
//! they stand for stay in your application's storage.
//!
//! # Features
//!
//! - On-disk storage using memory-mapped I/O
//! - One file: two checksummed header copies, then append-only regions aligned to 64 KiB
//! - One writer per file; concurrent searches from its threads and from `IndexReader`s in other
//!   processes
//! - Explicit durability control via flush()
//! - Zero external dependencies (no daemons or services)
//!
//! # Example
//!
//! ```no_run
//! use chassisdb::{VectorIndex, IndexOptions};
//!
//! # fn main() -> anyhow::Result<()> {
//! // Open or create an index
//! let mut index = VectorIndex::open("embeddings.chassis", 768, IndexOptions::default())?;
//!
//! // Insert vectors
//! let embedding = vec![0.1; 768];
//! let id = index.add(&embedding)?;
//!
//! // Flush to disk for durability
//! index.flush()?;
//!
//! // Search for nearest neighbors
//! let query = vec![0.1; 768];
//! let results = index.search(&query, 10)?;
//! # Ok(())
//! # }
//! ```
//!
//! # Design Philosophy
//!
//! Chassis is intentionally simple and focused. It does not aim to be:
//! - A database server
//! - A cloud service
//! - A distributed system
//! - A query engine
//!
//! These concerns are left to the application. Chassis is embedded the way
//! SQLite is: a library in your process, with everything in one file.

// Every unsafe block says why it is sound, in a `// SAFETY:` comment.
#![warn(clippy::undocumented_unsafe_blocks)]

pub mod distance;
mod error;
mod half;
mod header;
mod hnsw;
mod legacy;
mod prefetch;
mod storage;

#[cfg(test)]
mod power_loss;

#[cfg(feature = "internals")]
pub use hnsw::*;

pub use distance::{DistanceMetric, cosine_distance, euclidean_distance};
pub use error::{Error, ErrorKind, Result};
pub use half::Precision;
pub use hnsw::SearchResult;
// The layers below the index, for this crate's tests and benchmarks: public, they would make
// every change to them a breaking one, and `HnswGraph` could write a record that corrupts the file.
#[cfg(feature = "internals")]
pub use header::{MAGIC, VERSION};
#[cfg(feature = "internals")]
pub use hnsw::{HnswGraph, HnswParams, NodeRecordParams};
#[cfg(feature = "internals")]
pub use storage::Storage;
#[cfg(not(feature = "internals"))]
use {
    hnsw::{HnswGraph, HnswParams},
    storage::Storage,
};

/// The README's example, compiled with the doctests so that it stays true.
#[cfg(doctest)]
#[doc = include_str!("../README.md")]
struct ReadmeDoctests;
#[cfg(all(doctest, chassis_skill))]
#[doc = include_str!("../../plugins/chassis/skills/chassis/SKILL.md")]
struct SkillDoctests;

use error::fail;
use hnsw::layer_from_uniform;
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use std::sync::{Mutex, OnceLock};

/// Configuration options for VectorIndex
#[derive(Debug, Clone)]
pub struct IndexOptions {
    /// Maximum connections per node (M parameter)
    pub max_connections: u16,

    /// Construction quality parameter (efConstruction)
    pub ef_construction: usize,

    /// Search quality parameter (efSearch)
    pub ef_search: usize,

    /// How vectors are compared. Set when the index is created; reopening needs the same one.
    pub metric: DistanceMetric,

    /// What the file keeps of each component of a vector (ADR-0018). Set when the index is
    /// created; reopening needs the same one. A reader takes it from the file.
    pub precision: Precision,

    /// Ask the operating system to keep the vectors on huge pages (ADR-0016). On an index too
    /// large for the CPU's caches, searches are up to a quarter faster and batch builds a little
    /// faster. Only on Linux, and only where the kernel and filesystem keep files on huge
    /// pages (ext4 on Linux 6.17 does); elsewhere it does nothing. Off by default: with it a
    /// page not yet in memory is read 2 MB at a time, which an index much larger than memory
    /// pays for on every miss.
    pub huge_pages: bool,

    /// Read the whole index into memory on another thread from the moment it is opened
    /// (ADR-0019), so that searches stop waiting for the disk one page at a time. For an index
    /// that fits in memory; one much larger would push everything else out. Off by default. It
    /// takes Linux 5.14 or macOS: an older Linux reads only some of the index, and Windows none.
    pub warm: bool,
}

impl Default for IndexOptions {
    fn default() -> Self {
        Self {
            max_connections: 16,
            ef_construction: 200,
            ef_search: 50,
            metric: DistanceMetric::Euclidean,
            precision: Precision::Full,
            huge_pages: false,
            warm: false,
        }
    }
}

/// Public facade for Chassis vector index
///
/// This struct provides the main API for interacting with a Chassis index.
/// It handles crash consistency, ghost node recovery, and provides a clean
/// interface for vector insertion and search.
#[derive(Debug)]
pub struct VectorIndex {
    /// Internal HNSW graph (owns the storage)
    graph: HnswGraph,

    /// Configuration options
    options: IndexOptions,

    /// Layer multiplier cache: 1.0 / ln(M)
    ml: f32,

    /// Built on first use once some id differs from its slot (ADR-0007)
    ids: OnceLock<IdTable>,

    /// Held while the id table is built, so threads looking up ids at once build it once
    building: Mutex<()>,

    /// Where the index file is, for `compact` to replace it
    path: PathBuf,
}

impl VectorIndex {
    /// Open or create a vector index
    ///
    /// # Arguments
    ///
    /// * `path` - Path to the index file
    /// * `dims` - Number of dimensions per vector
    /// * `options` - Index configuration options
    ///
    /// A file in format v1 or v2 is migrated to v3 first (ADR-0008). After a crash, slots written
    /// after the last flush are simply reused.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The file cannot be opened or created
    /// - The file is corrupted
    /// - Dimension mismatch with existing index
    /// - The file was created with a different `max_connections`
    pub fn open<P: AsRef<Path>>(path: P, dims: u32, options: IndexOptions) -> Result<Self> {
        let params = hnsw_params(&options);
        // Compaction and migration rename a new file over this one: through a symlink that would
        // replace the link and leave the file it points to behind. Only links are resolved, so
        // errors name the path as given (on Windows a canonical one starts `\\?\`).
        let mut path = path.as_ref().to_path_buf();
        if path.symlink_metadata().is_ok_and(|meta| meta.file_type().is_symlink()) {
            path = std::fs::canonicalize(&path).unwrap_or(path);
        }
        let storage = Storage::open_with_precision(
            &path,
            dims,
            params.to_record_params(),
            options.metric,
            options.precision,
        )?;
        if storage.metric() != options.metric {
            let (held, asked) = (metric_name(storage.metric()), metric_name(options.metric));
            fail!(
                OptionsMismatch,
                "The index at {} was created with {held} distance, so it has to be opened with \
                 {held} distance too, not {asked}\nhelp: open it with the {held} metric, or \
                 create a new index at another path for {asked} distance",
                path.display()
            );
        }
        if storage.precision() != options.precision {
            let (held, asked) =
                (precision_name(storage.precision()), precision_name(options.precision));
            fail!(
                OptionsMismatch,
                "The index at {} keeps its vectors in {held} precision, so it has to be opened \
                 with {held} precision too, not {asked}\nhelp: open it with {held} precision, or \
                 create a new index at another path for {asked} precision",
                path.display()
            );
        }
        let graph = HnswGraph::open_no_reset(storage, params)?;
        // This is the one writer, so no compaction is running: a copy here is a crashed one's.
        let _ = std::fs::remove_file(storage::sibling(&path, "compacting"));
        let (ids, building) = (OnceLock::new(), Mutex::new(()));
        let mut index = Self { graph, ml: params.ml, options, ids, building, path };
        index.apply_options();
        Ok(index)
    }

    /// What `huge_pages` and `warm` ask of a newly opened file.
    fn apply_options(&mut self) {
        if self.options.huge_pages {
            self.use_huge_pages();
        }
        if self.options.warm {
            self.warm();
        }
    }

    /// Add a vector and return the id assigned to it: one past the largest id used so far.
    ///
    /// Ids are never reused by `add`, even after a delete. Use `add_with_id` to choose the id.
    ///
    /// The vector, its id and its graph record go into the next slot; the slot counts only once
    /// linking finishes, so a failed or interrupted add leaves a slot the next add reuses.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - Vector dimensions don't match index dimensions
    /// - Storage write fails
    /// - Graph write fails
    pub fn add(&mut self, vector: &[f32]) -> Result<u64> {
        check_finite(vector, "The vector")?;
        let id = self.next_ids(1)?.start;
        self.insert(id, vector)?;
        Ok(id)
    }

    /// The ids `add` gives the next `count` vectors. `u64::MAX` is reserved, so they can run out.
    fn next_ids(&mut self, count: u64) -> Result<std::ops::Range<u64>> {
        let first =
            if self.graph.custom_ids { self.id_table()?.next } else { self.graph.node_count() };
        match first.checked_add(count) {
            Some(end) => Ok(first..end),
            None => {
                fail!(
                    Full,
                    "No ids are left for add to give: the largest in use is {}\nhelp: choose \
                     free ids yourself with add_with_id",
                    u64::MAX - 1
                )
            }
        }
    }

    /// Add a vector under the caller's `id`. Search results report this id.
    ///
    /// # Errors
    ///
    /// Returns an error if a live vector already has `id` (delete it first to replace it), if
    /// `id` is `u64::MAX` (reserved), or for the same reasons as `add`.
    pub fn add_with_id(&mut self, id: u64, vector: &[f32]) -> Result<()> {
        check_id(id)?;
        check_finite(vector, "The vector")?;
        if self.slot_of(id)?.is_some() {
            fail!(
                IdInUse,
                "Id {id} is already in use\nhelp: delete it first to replace its vector, or use \
                 another id"
            );
        }
        // Ids differ from slots from here on, but only once the vector is in: a refused one
        // mustn't leave the file paying for an id table.
        let switch = !self.graph.custom_ids && id != self.graph.node_count();
        if switch {
            self.id_table()?;
        }
        self.insert(id, vector)?;
        self.graph.custom_ids |= switch;
        Ok(())
    }

    /// Add many vectors at once, given back to back, `dims` floats each, and return their ids,
    /// assigned as `add` assigns them. Linking runs on every core, so a large batch builds many
    /// times faster than adding one vector at a time; the graph then depends on thread timing
    /// (ADR-0010). All or nothing: after an error, none of the batch is added.
    ///
    /// # Errors
    ///
    /// Returns an error if `vectors` isn't a whole number of vectors of the index's dimensions,
    /// or if storing or linking them fails.
    pub fn add_batch(&mut self, vectors: &[f32]) -> Result<Vec<u64>> {
        let count = self.batch_len(vectors)? as u64;
        let ids: Vec<u64> = self.next_ids(count)?.collect();
        self.insert_batch(&ids, vectors)?;
        Ok(ids)
    }

    /// `add_with_id` for many vectors at once: `ids[i]` is the id of the `i`-th vector in
    /// `vectors`. Linking runs on every core, as for `add_batch`. All or nothing.
    ///
    /// # Errors
    ///
    /// Returns an error if the counts differ, an id is `u64::MAX`, repeats, or already exists, or
    /// storing or linking fails.
    pub fn add_batch_with_ids(&mut self, ids: &[u64], vectors: &[f32]) -> Result<()> {
        let count = self.batch_len(vectors)?;
        if count != ids.len() {
            fail!(
                InvalidArgument,
                "{} ids were given for {count} vectors\nhelp: give one id per vector, in the same \
                 order",
                ids.len()
            );
        }
        let mut seen = HashSet::with_capacity(ids.len());
        for &id in ids {
            check_id(id)?;
            if !seen.insert(id) {
                fail!(
                    InvalidArgument,
                    "Id {id} is given twice in the batch\nhelp: give each vector its own id"
                );
            }
            if self.slot_of(id)?.is_some() {
                fail!(
                    IdInUse,
                    "Id {id} is already in use\nhelp: delete it first to replace its vector, or use \
                 another id"
                );
            }
        }
        let first = self.graph.node_count();
        let switch =
            !self.graph.custom_ids && ids.iter().zip(first..).any(|(&id, slot)| id != slot);
        if switch {
            self.id_table()?;
        }
        self.insert_batch(ids, vectors)?;
        self.graph.custom_ids |= switch;
        Ok(())
    }

    fn dims(&self) -> usize {
        self.graph.storage.dimensions() as usize
    }

    /// Vectors in a batch, which must be a whole number of them.
    fn batch_len(&self, vectors: &[f32]) -> Result<usize> {
        let dims = self.dims();
        if !vectors.len().is_multiple_of(dims) {
            fail!(
                DimensionMismatch,
                "A batch of {} floats is not a whole number of vectors of {dims}\nhelp: pass the \
                 vectors back to back, {dims} floats each",
                vectors.len()
            );
        }
        for (row, vector) in vectors.chunks_exact(dims).enumerate() {
            check_finite(vector, &format!("Vector {row} of the batch"))?;
        }
        Ok(vectors.len() / dims)
    }

    /// Writes every vector and an empty record for it, then links them all on every core.
    fn insert_batch(&mut self, ids: &[u64], vectors: &[f32]) -> Result<()> {
        if ids.is_empty() {
            return Ok(());
        }
        match self.graph.storage.metric() {
            DistanceMetric::Euclidean => self.insert_stored(ids, vectors),
            DistanceMetric::Cosine => {
                let rows = vectors.chunks_exact(self.dims()).map(distance::unit);
                self.insert_stored(ids, &rows.collect::<anyhow::Result<Vec<_>>>()?.concat())
            }
        }
    }

    /// `insert_batch` for vectors already in their stored form: unit length in a cosine index.
    fn insert_stored(&mut self, ids: &[u64], vectors: &[f32]) -> Result<()> {
        if ids.is_empty() {
            return Ok(());
        }
        // The whole batch before any of it is written: `append` would stop part way.
        if self.graph.storage.precision() == Precision::Half {
            half::check(vectors, self.dims())?;
        }
        let layers: Vec<usize> = ids.iter().map(|_| self.select_layer()).collect();
        let first = self.graph.node_count();
        let saved = (self.graph.entry_point, self.graph.max_layer);
        let linked = self.write_and_link(first, ids, vectors, &layers);
        if let Err(e) = linked {
            self.graph.node_count = first;
            (self.graph.entry_point, self.graph.max_layer) = saved;
            self.graph.storage.truncate_logical(first);
            return Err(e.into());
        }
        self.graph.storage.publish_routing(self.graph.node_count);
        if let Some(table) = self.ids.get_mut() {
            table.slots.extend(ids.iter().copied().zip(first..));
            table.next = table.next.max(ids.iter().max().map_or(0, |&id| id + 1));
        }
        Ok(())
    }

    fn write_and_link(
        &mut self,
        first: u64,
        ids: &[u64],
        vectors: &[f32],
        layers: &[usize],
    ) -> anyhow::Result<()> {
        let dims = self.dims();
        let storage = &mut self.graph.storage;
        storage.truncate_logical(first);
        // A batch writes its vectors once and for all, so they may go straight onto huge pages.
        storage.huge_pages_up_to(first + ids.len() as u64);
        for ((&id, vector), &layer) in ids.iter().zip(vectors.chunks_exact(dims)).zip(layers) {
            let slot = storage.append(id, vector)?;
            storage.write_record(slot, &vec![Vec::new(); layer + 1])?;
        }
        // An empty graph's first node is its entry point, with nothing to link to.
        let start = if self.graph.entry_point.is_none() {
            (self.graph.entry_point, self.graph.max_layer) = (Some(first), layers[0]);
            1
        } else {
            0
        };
        let threads = std::thread::available_parallelism().map_or(1, |n| n.get());
        let ef = self.options.ef_construction;
        self.graph.link_batch(first + start as u64, &layers[start..], ef, threads.min(ids.len()))
    }

    /// Delete the vector with `id`. Returns false if no live vector has that id.
    ///
    /// Search stops returning it immediately. Like an add, the delete is durable after the next
    /// `flush()`; a crash before then rolls it back.
    ///
    /// # Errors
    ///
    /// Returns an error if the index file cannot be read.
    pub fn delete(&mut self, id: u64) -> Result<bool> {
        let Some(slot) = self.slot_of(id)? else {
            return Ok(false);
        };
        self.graph.mark_deleted(slot)?;
        if let Some(table) = self.ids.get_mut() {
            table.slots.remove(&id);
        }
        Ok(true)
    }

    /// Slot of the live vector with `id`.
    fn slot_of(&self, id: u64) -> Result<Option<u64>> {
        if !self.graph.custom_ids {
            let live = id < self.graph.node_count() && !self.graph.is_deleted(id)?;
            return Ok(live.then_some(id));
        }
        Ok(self.id_table()?.slots.get(&id).copied())
    }

    /// The id table, built by one scan of the graph on first use.
    // ponytail: O(n) scan once per process when custom ids are in use; persist the table if
    // open-to-first-write latency on large indexes matters.
    fn id_table(&self) -> Result<&IdTable> {
        if let Some(table) = self.ids.get() {
            return Ok(table);
        }
        // A panic while building leaves nothing half built: the table is set only once whole.
        let _building = self.building.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
        if let Some(table) = self.ids.get() {
            return Ok(table);
        }
        let live = self.graph.node_count() - self.graph.deleted_count;
        let mut pairs = Vec::with_capacity(live as usize);
        // A compaction removed the deleted slots that showed which ids were used (ADR-0011).
        let mut next = self.graph.storage.next_id();
        for slot in 0..self.graph.node_count() {
            let id = self.graph.id_of(slot)?;
            next = next.max(id + 1);
            if !self.graph.is_deleted(slot)? {
                pairs.push((id, slot));
            }
        }
        // Filling from a Vec keeps the loop small enough to overlap the table's cache misses.
        let mut slots = IdMap::with_capacity_and_hasher(pairs.len(), IdHasher::default());
        slots.extend(pairs);
        Ok(self.ids.get_or_init(|| IdTable { slots, next }))
    }

    fn insert(&mut self, id: u64, vector: &[f32]) -> Result<()> {
        let dims = self.graph.storage.dimensions() as usize;
        if vector.len() != dims {
            fail!(
                DimensionMismatch,
                "The vector has {} components, but this index holds vectors of {dims}\nhelp: make \
                 the vector with the same model as the index's vectors",
                vector.len()
            );
        }

        let unit;
        let vector = match self.graph.storage.metric() {
            DistanceMetric::Euclidean => vector,
            DistanceMetric::Cosine => {
                unit = distance::unit(vector)?;
                &unit[..]
            }
        };

        // STEP 1: Persist vector and id, reusing the slot of an add that failed part way
        let slot = self.graph.node_count();
        self.graph.storage.truncate_logical(slot);
        let new_id = self.graph.storage.append(id, vector)?;
        // In half precision the vector is linked as kept, which is not quite as given.
        let kept;
        let vector = match self.graph.storage.precision() {
            Precision::Full => vector,
            Precision::Half => {
                kept = self.graph.storage.get_vector(new_id)?;
                &kept[..]
            }
        };

        // STEP 2: Determine layer for new node
        let layer = self.select_layer();
        let layer_count = layer + 1;

        // STEP 3: Neighbor selection (in-memory phase); an empty graph has none
        let neighbors = match self.graph.entry_point {
            Some(entry) if self.graph.node_count() > 0 => {
                let start = (entry, self.graph.max_layer);
                let ef = self.options.ef_construction;
                self.graph.find_neighbors(vector, new_id, layer, start, ef)?
            }
            _ => vec![vec![]; layer_count],
        };

        // STEP 4: Atomic write (disk phase)
        // Node is written but invisible (node_count not incremented)
        self.graph.write_node_with_id_and_backlinks(new_id, id, layer_count, &neighbors)?;

        // STEP 5: Publish (commit phase)
        // Node becomes visible to readers
        self.graph.publish_node(new_id, layer_count)?;

        if let Some(table) = self.ids.get_mut() {
            table.slots.insert(id, new_id);
            table.next = table.next.max(id + 1);
        }
        Ok(())
    }

    /// Search for k nearest neighbors
    ///
    /// # Arguments
    ///
    /// * `query` - Query vector (must match index dimensions)
    /// * `k` - Number of nearest neighbors to return
    ///
    /// # Returns
    ///
    /// Returns a vector of search results, sorted by distance (ascending), identified by the
    /// ids given to `add`/`add_with_id`. Deleted vectors are never returned.
    ///
    /// # Errors
    ///
    /// Returns an error if `k` is 0 or the query has other dimensions than the index
    pub fn search(&self, query: &[f32], k: usize) -> Result<Vec<SearchResult>> {
        search_graph(&self.graph, query, k, self.options.ef_search, None)
    }

    /// Like `search`, among only the vectors whose id `filter` accepts. When walking the graph
    /// would cost more than checking every vector, as when few match, it checks every vector and
    /// returns the exact nearest.
    ///
    /// # Errors
    ///
    /// Returns an error if `k` is 0 or the query has other dimensions than the index
    pub fn search_filtered(
        &self,
        query: &[f32],
        k: usize,
        filter: impl Fn(u64) -> bool,
    ) -> Result<Vec<SearchResult>> {
        search_graph(&self.graph, query, k, self.options.ef_search, Some(&filter))
    }

    /// Flush all changes to disk
    ///
    /// Dropping the index doesn't flush: adds and deletes since the last flush are discarded, as
    /// after a crash.
    ///
    /// This method ensures durability by:
    /// 1. Flushing vector data to disk
    /// 2. Flushing graph metadata to disk
    ///
    /// # Performance Warning
    ///
    /// This operation is expensive (1-50ms depending on storage device).
    /// Batch multiple add() calls and flush() once at the end.
    ///
    /// # Errors
    ///
    /// Returns an error if the flush fails
    pub fn flush(&mut self) -> Result<()> {
        Ok(self.graph.commit()?)
    }

    /// Discards every add, delete and `user_version` since the last flush, as closing the index
    /// and opening it again would, without letting go of the writer's lock. Call it where a
    /// write's transaction in your own store rolls back, before the next flush commits what that
    /// write left.
    ///
    /// # Errors
    ///
    /// Returns an error if the file can't be read or synced. Later flushes then fail: close the
    /// index and open it again, which recovers it to its last flush.
    pub fn rollback(&mut self) -> Result<()> {
        let storage = self.graph.storage.reopened(&self.path)?;
        let graph = HnswGraph::open_no_reset(storage, hnsw_params(&self.options));
        self.graph = graph.inspect_err(|_| self.graph.storage.poison())?;
        self.ids = OnceLock::new();
        self.apply_options();
        Ok(())
    }

    /// Rewrites the index without its deleted vectors and with a newly built graph, then replaces
    /// the file with the copy (ADR-0011). Ids don't change. Like `flush`, it makes every add and
    /// delete so far durable. It takes as long as building the index, on every core, and needs
    /// free disk for a second copy of the live vectors. Readers in other processes keep searching
    /// and move to the new file by themselves.
    ///
    /// # Errors
    ///
    /// Returns an error, leaving the index as it was, if the copy can't be written or, on
    /// Windows, another process has the index open.
    pub fn compact(&mut self) -> Result<()> {
        // Windows has to close this file before the rename and reopen it if the rename fails,
        // which shows only what was flushed.
        self.flush()?;
        let temp = storage::sibling(&self.path, "compacting");
        let swapped = self.compacted_copy(&temp).and_then(|fresh| {
            self.graph.storage.set_superseded(true)?;
            self.swap_in(fresh, &temp)
        });
        if swapped.is_err() {
            let _ = std::fs::remove_file(&temp);
        }
        swapped
    }

    /// A flushed index at `temp` holding this one's live vectors under their ids.
    fn compacted_copy(&mut self, temp: &Path) -> Result<Self> {
        match std::fs::remove_file(temp) {
            Err(e) if e.kind() != std::io::ErrorKind::NotFound => return Err(e.into()),
            _ => {}
        }
        let next_id = self.id_table()?.next;
        let dims = self.dims();
        let mut fresh = Self::open(temp, dims as u32, self.options.clone())?;
        fresh.id_table()?;
        let count = self.graph.node_count();
        // About 32 MiB of vectors at a time.
        let chunk = ((32 << 20) / (dims * 4)).max(1);
        let (mut ids, mut vectors) = (Vec::new(), Vec::new());
        for start in (0..count).step_by(chunk) {
            ids.clear();
            vectors.clear();
            for slot in start..(start + chunk as u64).min(count) {
                if !self.graph.is_deleted(slot)? {
                    ids.push(self.graph.id_of(slot)?);
                    vectors.extend_from_slice(&self.graph.storage.vector(slot)?);
                }
            }
            let first = fresh.graph.node_count();
            fresh.graph.custom_ids |= ids.iter().zip(first..).any(|(&id, slot)| id != slot);
            fresh.insert_stored(&ids, &vectors)?;
        }
        // The deleted slots showed which ids were used; without them the header has to, and
        // `add` must stop taking the slot number for the next id.
        fresh.graph.custom_ids |= next_id != fresh.graph.node_count();
        fresh.ids.get_mut().expect("built above").next = next_id;
        let user_version = self.graph.storage.user_version();
        fresh.graph.storage.carry_over(next_id, self.graph.storage.epoch() + 1, user_version);
        fresh.flush()?;
        Ok(fresh)
    }

    /// Renames the compacted copy at `temp` over this index's file and continues on it. A failed
    /// rename leaves this index on its old file, with the superseded flag cleared.
    #[cfg(unix)]
    fn swap_in(&mut self, mut fresh: Self, temp: &Path) -> Result<()> {
        if let Err(e) = std::fs::rename(temp, &self.path) {
            self.graph.storage.set_superseded(false)?;
            return Err(e.into());
        }
        fresh.path = std::mem::take(&mut self.path);
        fresh.graph.storage.moved_to(&fresh.path);
        *self = fresh;
        // Either file may be at the path after a power loss; they hold the same vectors.
        Ok(storage::sync_dir(&self.path)?)
    }

    /// Windows can't rename over a file with open handles, so this index moves to the copy before
    /// the rename, and reopens the old file, which clears its superseded flag, if that fails. If
    /// the old file can't be reopened either, this index is left on the copy, which the next open
    /// of the path removes, so it refuses to flush anything more.
    #[cfg(windows)]
    fn swap_in(&mut self, fresh: Self, temp: &Path) -> Result<()> {
        let (path, dims, options) = (self.path.clone(), self.dims() as u32, self.options.clone());
        drop(std::mem::replace(self, fresh));
        if let Err(e) = storage::rename_over(temp, &path) {
            match Self::open(&path, dims, options) {
                Ok(old) => *self = old,
                Err(reopen) => {
                    self.graph.storage.poison();
                    let e = e.context(format!("and the index couldn't be reopened: {reopen}"));
                    return Err(e.into());
                }
            }
            return Err(e.into());
        }
        self.graph.storage.moved_to(&path);
        self.path = path;
        Ok(())
    }

    /// Asks for huge pages from here on, as opening with `IndexOptions::huge_pages` does.
    pub fn use_huge_pages(&mut self) {
        self.options.huge_pages = true;
        self.graph.storage.use_huge_pages();
    }

    /// Reads what the index holds into memory on another thread, as opening with
    /// `IndexOptions::warm` does, without waiting for it: searches go on meanwhile. While that is
    /// under way, asking again does nothing. The option is on from here on, so a file opened
    /// again, as a reader does after a compaction, is read in too.
    pub fn warm(&mut self) {
        self.options.warm = true;
        self.graph.storage.warm();
    }

    /// The vector with `id`, or `None` if no live vector has it. It comes back as the index keeps
    /// it: scaled to length 1 in a cosine index, and rounded in half precision.
    ///
    /// # Errors
    ///
    /// Returns an error if the index file cannot be read.
    pub fn get(&self, id: u64) -> Result<Option<Vec<f32>>> {
        let Some(slot) = self.slot_of(id)? else {
            return Ok(None);
        };
        Ok(Some(self.graph.storage.get_vector(slot)?))
    }

    /// Whether a live vector has `id`.
    ///
    /// # Errors
    ///
    /// Returns an error if the index file cannot be read.
    pub fn contains(&self, id: u64) -> Result<bool> {
        Ok(self.slot_of(id)?.is_some())
    }

    /// The ids of the live vectors, in the order they were added.
    ///
    /// # Errors
    ///
    /// Returns an error if the index file cannot be read.
    pub fn ids(&self) -> Result<Vec<u64>> {
        live_ids(&self.graph)
    }

    /// Checks what opening can't: that every live vector is within a search's reach, and that
    /// every vector is made of finite numbers. It reads the whole graph and every vector.
    ///
    /// # Errors
    ///
    /// Returns an error if the index file cannot be read.
    pub fn check(&self) -> Result<Check> {
        Ok(Check { unreachable: unreachable(&self.graph)?, not_finite: not_finite(&self.graph)? })
    }

    /// Get the number of live (not deleted) vectors in the index
    pub fn len(&self) -> u64 {
        self.graph.node_count() - self.graph.deleted_count
    }

    /// Deleted vectors the file still holds, until `compact` removes them.
    pub fn deleted_count(&self) -> u64 {
        self.graph.deleted_count
    }

    /// Your application's number for the index, as SQLite's `user_version` is for a database: 0
    /// until you set one. The next `flush` commits it with the data (ADR-0023), so after a crash
    /// it says which flush the index holds. Keep the same number in your own store, in the
    /// transaction that `flush` sits in, and compare the two on open and as each write begins.
    /// It is the number last set, flushed or not; `rollback` sets it back to the flushed one.
    pub fn user_version(&self) -> u64 {
        self.graph.storage.user_version()
    }

    /// Sets the number the next `flush` commits with the data; see `user_version`. Until then,
    /// a crash leaves the one flushed before.
    pub fn set_user_version(&mut self, version: u64) {
        self.graph.storage.set_user_version(version);
    }

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

    /// Get the dimensionality of vectors in this index
    pub fn dimensions(&self) -> u32 {
        self.graph.storage.dimensions()
    }

    /// The distance metric the index was created with
    pub fn metric(&self) -> DistanceMetric {
        self.graph.storage.metric()
    }

    /// What the file keeps of each component of a vector
    pub fn precision(&self) -> Precision {
        self.graph.storage.precision()
    }

    // Private helper methods

    /// Select layer for a new node using exponential decay
    fn select_layer(&self) -> usize {
        let uniform: f32 = rand::random();
        layer_from_uniform(uniform, self.ml, self.graph.record_params.max_layers)
    }
}

type IdMap = HashMap<u64, u64, IdHasher>;

struct IdTable {
    /// id → slot of each live vector
    slots: IdMap,
    /// One past the largest id ever stored
    next: u64,
}

/// A count, not every id: `{:?}` on an index shouldn't print millions of them.
impl std::fmt::Debug for IdTable {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("IdTable").field("ids", &self.slots.len()).field("next", &self.next).finish()
    }
}

/// A reader's id → slot map for the slots below `mapped`, extended as lookups need: a later slot
/// replaces an earlier one with its id, since an id is given again only after its vector is deleted.
#[derive(Default)]
struct MappedIds {
    slots: IdMap,
    mapped: u64,
}

impl std::fmt::Debug for MappedIds {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("MappedIds")
            .field("ids", &self.slots.len())
            .field("mapped", &self.mapped)
            .finish()
    }
}

/// Hashes an id with one 64×64→128-bit multiply folded to 64 bits, keyed per table: ids are
/// integers, so SipHash's byte-stream work buys nothing here.
#[derive(Clone, Copy)]
struct IdHasher(u64);

impl Default for IdHasher {
    fn default() -> Self {
        Self(rand::random())
    }
}

impl std::hash::BuildHasher for IdHasher {
    type Hasher = Self;
    fn build_hasher(&self) -> Self {
        *self
    }
}

impl std::hash::Hasher for IdHasher {
    fn finish(&self) -> u64 {
        self.0
    }
    fn write(&mut self, bytes: &[u8]) {
        for chunk in bytes.chunks(8) {
            let mut word = [0u8; 8];
            word[..chunk.len()].copy_from_slice(chunk);
            self.write_u64(u64::from_le_bytes(word));
        }
    }
    fn write_u64(&mut self, id: u64) {
        let product = u128::from(id ^ self.0) * 0x9e37_79b9_7f4a_7c15;
        self.0 = (product as u64) ^ ((product >> 64) as u64);
    }
}

/// Searches as the file's metric defines, reporting the caller's ids. A cosine index stores unit
/// vectors, so the query is scaled too, and for unit vectors 1 − cos = L2² / 2.
fn search_graph(
    graph: &HnswGraph,
    query: &[f32],
    k: usize,
    ef: usize,
    filter: Option<&dyn Fn(u64) -> bool>,
) -> Result<Vec<SearchResult>> {
    if k == 0 {
        fail!(
            InvalidArgument,
            "k is 0, but has to be at least 1\nhelp: pass how many results to return, such as 10"
        );
    }
    let dims = graph.storage.dimensions() as usize;
    if query.len() != dims {
        fail!(
            DimensionMismatch,
            "The query has {} components, but this index holds vectors of {dims}\nhelp: make the \
             query with the same model as the index's vectors",
            query.len()
        );
    }
    check_finite(query, "The query")?;
    let search = |query: &[f32]| match filter {
        None => graph.search(query, k, ef),
        Some(filter) => graph.search_filtered(query, k, ef, &|slot| {
            Ok(filter(if graph.custom_ids { graph.id_of(slot)? } else { slot }))
        }),
    };
    let mut results = match graph.storage.metric() {
        DistanceMetric::Euclidean => search(query)?,
        DistanceMetric::Cosine => {
            let query = distance::unit(query)?;
            let mut results = search(&query)?;
            for result in &mut results {
                // Rounding can take antipodal vectors a hair past 2.
                result.distance = (result.distance * result.distance / 2.0).min(2.0);
            }
            results
        }
    };
    if graph.custom_ids {
        for result in &mut results {
            result.id = graph.id_of(result.id)?;
        }
    }
    Ok(results)
}

/// Ids of the vectors a search of `graph` can return, in slot order.
/// What `check` found: in an index in good order, both lists are empty.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Check {
    /// Live vectors that no path through the graph reaches from its entry point, so no search
    /// returns them. Damage leaves them, and `compact` builds the graph again. A sound graph can
    /// have a few too: on data with no structure, such as uniform random numbers in hundreds of
    /// dimensions, and among many exact copies of one vector.
    pub unreachable: Vec<u64>,
    /// Vectors with a component that isn't a finite number, which only damage to the file leaves,
    /// since `add` refuses them. Delete them and add them again from your own data.
    pub not_finite: Vec<u64>,
}

impl Check {
    /// Whether the check found nothing wrong.
    pub fn is_ok(&self) -> bool {
        self.unreachable.is_empty() && self.not_finite.is_empty()
    }
}

/// The ids of live vectors that no path from the entry point reaches. Search descends through the
/// upper layers before it searches layer 0, so the walk follows every layer's links.
fn unreachable(graph: &HnswGraph) -> Result<Vec<u64>> {
    let count = graph.node_count();
    let mut reached = vec![false; count as usize];
    let mut next: Vec<u64> = graph.entry_point.into_iter().collect();
    next.iter().for_each(|&slot| reached[slot as usize] = true);
    while let Some(slot) = next.pop() {
        for layer in 0..graph.storage.layer_count(slot)? {
            for neighbor in graph.neighbors_iter_from_mmap(slot, layer)? {
                // A link past the count is one a crash left; search passes it by as well. Marked
                // when found, so each slot waits in `next` once at most.
                if neighbor < count && !std::mem::replace(&mut reached[neighbor as usize], true) {
                    next.push(neighbor);
                }
            }
        }
    }
    let mut ids = Vec::new();
    for slot in 0..count {
        if !reached[slot as usize] && !graph.is_deleted(slot)? {
            ids.push(graph.id_of(slot)?);
        }
    }
    Ok(ids)
}

/// The ids of live vectors with a component that isn't a finite number.
fn not_finite(graph: &HnswGraph) -> Result<Vec<u64>> {
    let mut ids = Vec::new();
    for slot in 0..graph.node_count() {
        if !graph.is_deleted(slot)? && graph.storage.vector(slot)?.iter().any(|x| !x.is_finite()) {
            ids.push(graph.id_of(slot)?);
        }
    }
    Ok(ids)
}

fn live_ids(graph: &HnswGraph) -> Result<Vec<u64>> {
    let mut ids = Vec::new();
    for slot in 0..graph.node_count() {
        if !graph.is_deleted(slot)? {
            ids.push(graph.id_of(slot)?);
        }
    }
    Ok(ids)
}

/// Refuses a vector with a component that isn't a finite number: it would have no distance to
/// anything. `what` names it in the message.
fn check_finite(vector: &[f32], what: &str) -> Result<()> {
    if let Some(i) = vector.iter().position(|x| !x.is_finite()) {
        fail!(
            InvalidArgument,
            "{what} has {} at component {i}, but every component has to be a finite number\nhelp: \
             check how it was made; a division by zero, as in normalizing a zero vector, gives NaN",
            vector[i]
        );
    }
    Ok(())
}

fn check_id(id: u64) -> Result<()> {
    if id == u64::MAX {
        fail!(InvalidArgument, "Id {id} is reserved\nhelp: ids go from 0 to {}", u64::MAX - 1);
    }
    Ok(())
}

fn metric_name(metric: DistanceMetric) -> &'static str {
    match metric {
        DistanceMetric::Euclidean => "euclidean",
        DistanceMetric::Cosine => "cosine",
    }
}

fn precision_name(precision: Precision) -> &'static str {
    match precision {
        Precision::Half => "half",
        _ => "full",
    }
}

fn hnsw_params(options: &IndexOptions) -> HnswParams {
    HnswParams {
        max_connections: options.max_connections,
        ml: 1.0 / f32::from(options.max_connections).ln(),
        max_layers: 16, // Fixed for now
    }
}

/// Searches an index while a `VectorIndex` in another process may be writing it (ADR-0008,
/// decision 5). Any number of readers can open the same file; they take no lock.
///
/// Every search first takes a new snapshot: it returns vectors committed by the writer's last
/// `flush()`, and none deleted by it, while routing through everything the writer has added since,
/// so a long unflushed batch costs readers little recall.
#[derive(Debug)]
pub struct IndexReader {
    graph: HnswGraph,
    ef_search: usize,
    /// What it was opened with, to open the file that replaces this one after a compaction
    path: PathBuf,
    dims: u32,
    options: IndexOptions,
    ids: Option<MappedIds>,
}

impl IndexReader {
    /// Opens `path` for searching.
    ///
    /// # Errors
    ///
    /// Returns an error if the file is missing, uses file format 1 or 2 (open it once with
    /// `VectorIndex::open` to migrate it), has other dimensions, was created with another
    /// `max_connections`, or is corrupt.
    pub fn open<P: AsRef<Path>>(path: P, dims: u32, options: IndexOptions) -> Result<Self> {
        let path = path.as_ref().to_path_buf();
        let storage = Storage::open_read_only(&path, dims)?;
        let graph = HnswGraph::reader(storage, hnsw_params(&options))?;
        let mut reader =
            Self { graph, ef_search: options.ef_search, path, dims, options, ids: None };
        if reader.options.huge_pages {
            reader.use_huge_pages();
        }
        if reader.options.warm {
            reader.warm();
        }
        Ok(reader)
    }

    /// Takes a new snapshot, moving to the file a compaction put at the path (ADR-0011). Until
    /// that file is there, and if it never arrives, this file's snapshot stands.
    fn sync(&mut self) -> Result<()> {
        self.graph.refresh()?;
        if self.graph.storage.superseded() && !self.graph.storage.is_at(&self.path)? {
            *self = Self::open(&self.path, self.dims, self.options.clone())?;
        }
        Ok(())
    }

    /// Search for the `k` nearest committed vectors, by the ids given to `add`/`add_with_id`.
    ///
    /// # Errors
    ///
    /// Returns an error if `k` is 0, the query has other dimensions, or the file is corrupt.
    pub fn search(&mut self, query: &[f32], k: usize) -> Result<Vec<SearchResult>> {
        self.sync()?;
        search_graph(&self.graph, query, k, self.ef_search, None)
    }

    /// Like `search`, among only the vectors whose id `filter` accepts; see
    /// `VectorIndex::search_filtered`.
    ///
    /// # Errors
    ///
    /// Returns an error if `k` is 0, the query has other dimensions, or the file is corrupt.
    pub fn search_filtered(
        &mut self,
        query: &[f32],
        k: usize,
        filter: impl Fn(u64) -> bool,
    ) -> Result<Vec<SearchResult>> {
        self.sync()?;
        search_graph(&self.graph, query, k, self.ef_search, Some(&filter))
    }

    /// Get the dimensionality of vectors in this index
    pub fn dimensions(&self) -> u32 {
        self.graph.storage.dimensions()
    }

    /// The distance metric the index was created with
    pub fn metric(&self) -> DistanceMetric {
        self.graph.storage.metric()
    }

    /// What the file keeps of each component of a vector
    pub fn precision(&self) -> Precision {
        self.graph.storage.precision()
    }

    /// Take a new snapshot without searching, so `len` reflects the writer's latest flush.
    ///
    /// # Errors
    ///
    /// Returns an error if the file is corrupt.
    pub fn refresh(&mut self) -> Result<()> {
        self.sync()
    }

    /// Identifies the last snapshot (see `len`): committed slots and the last delete flush. Two snapshots with
    /// the same value have the same contents, so it can key a cache of search results, unless a
    /// power loss discarded a flush readers had already seen.
    pub fn snapshot(&self) -> (u64, u64) {
        self.graph.view.map_or((0, 0), |view| (view.committed, view.epoch))
    }

    /// Asks for huge pages from here on, as opening with `IndexOptions::huge_pages` does.
    pub fn use_huge_pages(&mut self) {
        self.options.huge_pages = true;
        self.graph.storage.use_huge_pages();
    }

    /// Reads what the index holds into memory on another thread, as opening with
    /// `IndexOptions::warm` does, without waiting for it: searches go on meanwhile. While that is
    /// under way, asking again does nothing. The option is on from here on, so a file opened
    /// again, as a reader does after a compaction, is read in too.
    pub fn warm(&mut self) {
        self.options.warm = true;
        self.graph.storage.warm();
    }

    /// The committed vector with `id`, as `VectorIndex::get` returns it, or `None`.
    ///
    /// # Errors
    ///
    /// Returns an error if the file is corrupt.
    pub fn get(&mut self, id: u64) -> Result<Option<Vec<f32>>> {
        let Some(slot) = self.slot_of(id)? else {
            return Ok(None);
        };
        Ok(Some(self.graph.storage.get_vector(slot)?))
    }

    /// Whether a committed vector has `id`.
    ///
    /// # Errors
    ///
    /// Returns an error if the file is corrupt.
    pub fn contains(&mut self, id: u64) -> Result<bool> {
        Ok(self.slot_of(id)?.is_some())
    }

    /// The ids of the committed vectors, in the order they were added.
    ///
    /// # Errors
    ///
    /// Returns an error if the file is corrupt.
    pub fn ids(&mut self) -> Result<Vec<u64>> {
        self.sync()?;
        live_ids(&self.graph)
    }

    /// `VectorIndex::check` on a new snapshot. While a writer changes the file, a vector it is
    /// linking can show as unreachable for a moment; check again to be sure.
    ///
    /// # Errors
    ///
    /// Returns an error if the file is corrupt.
    pub fn check(&mut self) -> Result<Check> {
        self.sync()?;
        Ok(Check { unreachable: unreachable(&self.graph)?, not_finite: not_finite(&self.graph)? })
    }

    /// Slot of the vector with `id` in a new snapshot, if the snapshot has it.
    fn slot_of(&mut self, id: u64) -> Result<Option<u64>> {
        self.sync()?;
        let graph = &self.graph;
        let committed = graph.view.map_or(0, |view| view.committed);
        let slot = if graph.custom_ids {
            // ponytail: the first lookup maps every committed slot, O(n) once per snapshot file.
            let ids = self.ids.get_or_insert_with(MappedIds::default);
            ids.slots.reserve(committed.saturating_sub(ids.mapped) as usize);
            for slot in ids.mapped..committed {
                ids.slots.insert(graph.id_of(slot)?, slot);
                ids.mapped = slot + 1;
            }
            ids.slots.get(&id).copied()
        } else {
            Some(id)
        };
        match slot {
            Some(slot) if slot < committed && !graph.is_deleted(slot)? => Ok(Some(slot)),
            _ => Ok(None),
        }
    }

    /// Live vectors as of the last snapshot. `search`, `get`, `contains`, `ids` and `refresh` each
    /// take a new one, so a search's result can be gone by the `get` after it.
    pub fn len(&self) -> u64 {
        self.graph.view.map_or(0, |view| view.committed) - self.graph.deleted_count
    }

    /// Deleted vectors in the last snapshot that the file still holds; see `len`.
    pub fn deleted_count(&self) -> u64 {
        self.graph.deleted_count
    }

    /// The application's number in the last snapshot (see `len` and
    /// `VectorIndex::user_version`): the one committed with the flush the snapshot shows.
    pub fn user_version(&self) -> u64 {
        self.graph.storage.user_version()
    }

    /// Whether the last snapshot had no live vectors.
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }
}

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

    fn random_vector(id: u64) -> Vec<f32> {
        let mut x = id.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1;
        (0..16)
            .map(|_| {
                x ^= x << 13;
                x ^= x >> 7;
                x ^= x << 17;
                (x >> 40) as f32 / (1u64 << 24) as f32
            })
            .collect()
    }

    #[test]
    fn test_asking_to_warm_turns_the_option_on_for_a_reopen() {
        let file = NamedTempFile::new().unwrap();
        let mut index = VectorIndex::open(file.path(), 16, IndexOptions::default()).unwrap();
        index.add(&random_vector(0)).unwrap();
        index.flush().unwrap();
        let mut reader = IndexReader::open(file.path(), 16, IndexOptions::default()).unwrap();
        index.warm();
        reader.warm();
        assert!(index.options.warm && reader.options.warm);
    }

    /// 2,500 vectors: sampled every second slot, so a filter on odd slots meets an unjittered
    /// sample nowhere.
    fn filter_index(file: &NamedTempFile) -> VectorIndex {
        let options = IndexOptions { ef_construction: 64, ..IndexOptions::default() };
        let mut index = VectorIndex::open(file.path(), 16, options).unwrap();
        for id in 0..2500 {
            index.add(&random_vector(id)).unwrap();
        }
        index
    }

    #[test]
    fn test_filtered_search_estimates_matches_and_picks_its_path() {
        let file = NamedTempFile::new().unwrap();
        let mut index = filter_index(&file);
        let graph = &index.graph;
        let estimate = |allow: &dyn Fn(u64) -> bool| graph.estimated_matches(&|s| Ok(allow(s)));
        assert_eq!(estimate(&|_| true).unwrap(), 2500);
        assert_eq!(estimate(&|_| false).unwrap(), 0);
        let odd = estimate(&|slot| slot % 2 == 1).unwrap();
        assert!((1000..=1500).contains(&odd), "odd slots estimated at {odd}");

        let query = random_vector(99_999);
        let nearest = index.search(&query, 1).unwrap()[0].id;
        let path = |allow: &dyn Fn(u64) -> bool| {
            index.graph.search_filtered_reporting(&query, 10, 50, &|s| Ok(allow(s))).unwrap()
        };
        let (found, scanned) = path(&|slot| slot != nearest);
        assert!(!scanned && found.len() == 10, "a broad filter walks the graph");
        let (found, scanned) = path(&|slot| slot % 250 == 7);
        assert!(scanned && found.len() == 10, "a selective filter scans");

        for slot in (0..2500).step_by(2) {
            index.delete(slot).unwrap();
        }
        let live = index.graph.estimated_matches(&|_| Ok(true)).unwrap();
        assert!((1000..=1500).contains(&live), "deleted slots counted as matches: {live}");
    }

    /// A rename that fails after the copy is built: the path is a directory with a file in it.
    #[cfg(unix)]
    #[test]
    fn test_a_failed_swap_clears_the_flag_and_removes_the_copy() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("index.chassis");
        let mut index = VectorIndex::open(&path, 16, IndexOptions::default()).unwrap();
        for id in 0..50 {
            index.add(&random_vector(id)).unwrap();
        }
        index.flush().unwrap();
        let blocked = dir.path().join("blocked");
        std::fs::create_dir(&blocked).unwrap();
        std::fs::write(blocked.join("file"), b"").unwrap();
        index.path = blocked.clone();

        assert!(index.compact().is_err());
        assert!(!dir.path().join("blocked.compacting").exists(), "the copy was left behind");
        assert!(!index.graph.storage.superseded(), "readers would wait for a file that won't come");
        index.path = path.clone();
        assert_eq!(index.search(&random_vector(7), 1).unwrap()[0].id, 7);
        let mut reader = IndexReader::open(&path, 16, IndexOptions::default()).unwrap();
        assert!(!reader.graph.storage.superseded());
        assert_eq!(reader.search(&random_vector(7), 1).unwrap()[0].id, 7);
        index.compact().unwrap();
        assert_eq!(index.len(), 50);
    }

    #[test]
    fn test_a_superseded_flag_left_by_a_crash_is_cleared() {
        let file = NamedTempFile::new().unwrap();
        let mut index = VectorIndex::open(file.path(), 16, IndexOptions::default()).unwrap();
        for id in 0..50 {
            index.add(&random_vector(id)).unwrap();
        }
        index.flush().unwrap();
        // A compaction that died after flagging the file and before renaming its copy over it.
        index.graph.storage.set_superseded(true).unwrap();
        drop(index);

        // The file is still the one at the path, so a reader's snapshot of it stands.
        let mut reader = IndexReader::open(file.path(), 16, IndexOptions::default()).unwrap();
        assert!(reader.graph.storage.superseded());
        assert_eq!(reader.search(&random_vector(7), 1).unwrap()[0].id, 7);

        let mut index = VectorIndex::open(file.path(), 16, IndexOptions::default()).unwrap();
        assert!(!index.graph.storage.superseded(), "the next writer clears the flag");
        index.add(&random_vector(50)).unwrap();
        index.flush().unwrap();
        assert_eq!(reader.search(&random_vector(50), 1).unwrap()[0].id, 50);
        assert!(!reader.graph.storage.superseded());
    }

    /// Every committed node's neighbors on every layer, each list in id order.
    fn lists(index: &VectorIndex) -> Vec<Vec<Vec<u64>>> {
        let graph = &index.graph;
        let list = |slot, layer| {
            let mut ids: Vec<u64> = graph.neighbors_iter_from_mmap(slot, layer).unwrap().collect();
            ids.sort_unstable();
            ids
        };
        let layers = |slot| graph.storage.layer_count(slot).unwrap();
        (0..graph.node_count())
            .map(|slot| (0..layers(slot)).map(|l| list(slot, l)).collect())
            .collect()
    }

    /// 300 flushed vectors, then 1,700 more that aren't flushed, added both ways.
    fn index_with_unflushed_adds(path: &Path) -> (VectorIndex, Vec<Vec<Vec<u64>>>) {
        let mut index = VectorIndex::open(path, 16, IndexOptions::default()).unwrap();
        let flat = |ids: std::ops::Range<u64>| ids.flat_map(random_vector).collect::<Vec<f32>>();
        index.add_batch(&flat(0..300)).unwrap();
        index.flush().unwrap();
        let committed = lists(&index);
        for id in 300..600 {
            index.add(&random_vector(id)).unwrap();
        }
        index.add_batch(&flat(600..2000)).unwrap();
        (index, committed)
    }

    #[test]
    fn test_adds_lost_to_a_crash_leave_no_trace_in_committed_lists() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("index.chassis");
        let undo = storage::sibling(&path, "undo");
        let (index, committed) = index_with_unflushed_adds(&path);
        assert_ne!(lists(&index)[..300], committed[..], "the adds changed committed lists");
        assert!(undo.exists());
        drop(index);

        let mut index = VectorIndex::open(&path, 16, IndexOptions::default()).unwrap();
        assert_eq!(lists(&index), committed);
        assert!(!undo.exists(), "rolling back removes the undo file");

        // A flush has nothing to undo, and a reopen after it changes nothing.
        index.add(&random_vector(300)).unwrap();
        assert!(undo.exists());
        index.flush().unwrap();
        assert!(!undo.exists(), "a flush removes the undo file");
        let flushed = lists(&index);
        drop(index);
        let index = VectorIndex::open(&path, 16, IndexOptions::default()).unwrap();
        assert_eq!(lists(&index), flushed);
    }

    #[test]
    fn test_a_rollback_leaves_what_a_reopen_would_and_keeps_the_lock() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("index.chassis");
        let (mut index, committed) = index_with_unflushed_adds(&path);
        index.add_with_id(5000, &random_vector(5000)).unwrap();
        assert!(index.delete(5).unwrap());
        index.set_user_version(7);
        index.rollback().unwrap();
        assert_eq!(lists(&index), committed);
        assert_eq!((index.len(), index.deleted_count(), index.user_version()), (300, 0, 0));
        assert!(index.contains(5).unwrap() && !index.contains(5000).unwrap());
        assert!(!storage::sibling(&path, "undo").exists());
        let second = VectorIndex::open(&path, 16, IndexOptions::default());
        assert_eq!(second.unwrap_err().kind(), ErrorKind::Locked);

        // It writes on from the flush, as a reopened index would.
        assert_eq!(index.add(&random_vector(300)).unwrap(), 300);
        index.flush().unwrap();
        let flushed = lists(&index);
        drop(index);
        let index = VectorIndex::open(&path, 16, IndexOptions::default()).unwrap();
        assert_eq!(lists(&index), flushed);
        assert_eq!(index.len(), 301);
        assert!(index.check().unwrap().is_ok());
    }

    #[test]
    fn test_a_rollback_forgets_the_ids_given_since_the_flush() {
        let file = NamedTempFile::new().unwrap();
        let mut index = VectorIndex::open(file.path(), 16, IndexOptions::default()).unwrap();
        index.add_with_id(10, &random_vector(10)).unwrap();
        index.flush().unwrap();
        index.add_with_id(20, &random_vector(20)).unwrap();
        index.rollback().unwrap();
        assert!(!index.contains(20).unwrap());
        assert_eq!(index.add(&random_vector(11)).unwrap(), 11, "the next id is past 10, not 20");
    }

    /// Random writes, some flushed, then a rollback: it must find what opening a copy of the
    /// file and its undo file, as a crash leaves them, finds.
    #[test]
    fn test_a_rollback_finds_what_opening_after_a_crash_finds() {
        for seed in 1..=40u64 {
            let mut x = seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1;
            let mut rng = move |n: u64| {
                x ^= x << 13;
                x ^= x >> 7;
                x ^= x << 17;
                x % n
            };
            let dir = tempfile::tempdir().unwrap();
            let path = dir.path().join("a.chassis");
            let mut options = IndexOptions::default();
            if seed % 3 == 0 {
                options.metric = DistanceMetric::Cosine;
            }
            if seed % 4 == 0 {
                options.precision = Precision::Half;
            }
            let mut index = VectorIndex::open(&path, 16, options.clone()).unwrap();
            let (custom, mut next) = (seed % 2 == 0, 0u64);
            let mut write = |index: &mut VectorIndex, rng: &mut dyn FnMut(u64) -> u64| {
                let vector = |id: u64| random_vector(id + seed * 7919);
                match rng(10) {
                    0..=3 => {
                        let ids: Vec<u64> = (0..1 + rng(40)).map(|i| next + i * 3).collect();
                        let flat: Vec<f32> = ids.iter().flat_map(|&id| vector(id)).collect();
                        next = if custom {
                            index.add_batch_with_ids(&ids, &flat).unwrap();
                            ids[ids.len() - 1] + 3
                        } else {
                            index.add_batch(&flat).unwrap().last().unwrap() + 1
                        };
                    }
                    4..=5 if custom => {
                        index.add_with_id(next, &vector(next)).unwrap();
                        next += 2;
                    }
                    4..=5 => next = index.add(&vector(next)).unwrap() + 1,
                    6..=8 => {
                        let ids = index.ids().unwrap();
                        if !ids.is_empty() {
                            index.delete(ids[rng(ids.len() as u64) as usize]).unwrap();
                        }
                    }
                    _ => index.set_user_version(rng(1000)),
                }
            };
            for _ in 0..rng(12) {
                write(&mut index, &mut rng);
            }
            index.flush().unwrap();
            if seed % 5 == 0 {
                index.compact().unwrap();
            }
            for _ in 0..rng(20) {
                write(&mut index, &mut rng);
            }
            if seed % 7 == 0 {
                index.flush().unwrap();
                for _ in 0..rng(10) {
                    write(&mut index, &mut rng);
                }
            }
            let crashed = dir.path().join("b.chassis");
            std::fs::copy(&path, &crashed).unwrap();
            let undo = storage::sibling(&path, "undo");
            if undo.exists() {
                std::fs::copy(&undo, storage::sibling(&crashed, "undo")).unwrap();
            }
            index.rollback().unwrap();
            if seed % 6 == 0 {
                index.rollback().unwrap();
            }
            let state = |index: &VectorIndex| {
                let mut ids = index.ids().unwrap();
                ids.sort_unstable();
                let vectors: Vec<_> = ids.iter().map(|&id| index.get(id).unwrap()).collect();
                let found: Vec<Vec<u64>> = (0..5u64)
                    .map(|q| {
                        let hits = index.search(&random_vector(q + 100_000), 10).unwrap();
                        hits.iter().map(|hit| hit.id).collect()
                    })
                    .collect();
                let graph = &index.graph;
                let shape = (graph.entry_point, graph.max_layer, graph.custom_ids);
                let counts = (index.len(), index.deleted_count(), index.user_version());
                format!("{:?}", (lists(index), ids, vectors, found, shape, counts, index.check()))
            };
            let reopened = VectorIndex::open(&crashed, 16, options.clone()).unwrap();
            assert_eq!(state(&index), state(&reopened), "seed {seed}");
            drop(reopened);

            // Writes go on from there, and a crash after more of them rolls back to the same.
            let committed = lists(&index);
            for _ in 0..1 + rng(15) {
                write(&mut index, &mut rng);
            }
            drop(index);
            let index = VectorIndex::open(&path, 16, options).unwrap();
            assert_eq!(lists(&index), committed, "seed {seed}, after a crash");
        }
    }

    #[test]
    fn test_an_undo_file_saved_from_an_earlier_commit_is_ignored() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("index.chassis");
        let undo = storage::sibling(&path, "undo");
        let (mut index, _) = index_with_unflushed_adds(&path);
        let stale = std::fs::read(&undo).unwrap();
        index.flush().unwrap();
        let flushed = lists(&index);
        drop(index);

        // As if a crash had come between the commit and removing the file.
        std::fs::write(&undo, stale).unwrap();
        let index = VectorIndex::open(&path, 16, IndexOptions::default()).unwrap();
        assert_eq!(lists(&index), flushed);
        assert!(!undo.exists());
    }

    #[test]
    fn test_a_torn_undo_file_restores_the_entries_it_holds_whole() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("index.chassis");
        let undo = storage::sibling(&path, "undo");
        let (index, committed) = index_with_unflushed_adds(&path);
        drop(index);
        let saved = std::fs::read(&undo).unwrap();
        std::fs::write(&undo, &saved[..saved.len() - 3]).unwrap();

        let differing = |index: &VectorIndex| {
            let restored = lists(index);
            (0..300).filter(|&slot| restored[slot] != committed[slot]).count()
        };
        let index = VectorIndex::open(&path, 16, IndexOptions::default()).unwrap();
        assert_eq!(differing(&index), 1, "only the node whose entry was torn keeps lost links");
        drop(index);

        // An entry that fails its checksum ends the file there: here, at its first entry.
        let mut index = VectorIndex::open(&path, 16, IndexOptions::default()).unwrap();
        index.add_batch(&(300..2000).flat_map(random_vector).collect::<Vec<f32>>()).unwrap();
        drop(index);
        let mut saved = std::fs::read(&undo).unwrap();
        saved[23] ^= 1; // a neighbor in the first entry
        std::fs::write(&undo, &saved).unwrap();
        let index = VectorIndex::open(&path, 16, IndexOptions::default()).unwrap();
        assert!(differing(&index) > 100, "nothing after the corrupt entry is trusted");
    }

    /// A crash under a release without the undo file leaves links to slots that are gone. They
    /// aren't saved with a list, and they don't stop it being written back.
    #[test]
    fn test_links_an_older_crash_left_dont_stop_a_rollback() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("index.chassis");
        let (index, _) = index_with_unflushed_adds(&path);
        drop(index);
        std::fs::remove_file(storage::sibling(&path, "undo")).unwrap();

        let committed_only = |index: &VectorIndex| -> Vec<Vec<Vec<u64>>> {
            let keep = |ids: Vec<u64>| ids.into_iter().filter(|&id| id < 300).collect();
            lists(index).into_iter().map(|node| node.into_iter().map(keep).collect()).collect()
        };
        let mut index = VectorIndex::open(&path, 16, IndexOptions::default()).unwrap();
        assert_ne!(lists(&index), committed_only(&index), "links to lost slots remain");
        let before = committed_only(&index);
        index.add_batch(&(300..2000).flat_map(random_vector).collect::<Vec<f32>>()).unwrap();
        drop(index);

        let index = VectorIndex::open(&path, 16, IndexOptions::default()).unwrap();
        assert_eq!(committed_only(&index), before);
    }

    #[test]
    fn test_adds_lost_after_a_compaction_are_rolled_back_too() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("index.chassis");
        let (mut index, _) = index_with_unflushed_adds(&path);
        index.compact().unwrap();
        let committed = lists(&index);
        index.add_batch(&(2000..4000).flat_map(random_vector).collect::<Vec<f32>>()).unwrap();
        assert!(storage::sibling(&path, "undo").exists(), "the undo file follows the rename");
        drop(index);

        let index = VectorIndex::open(&path, 16, IndexOptions::default()).unwrap();
        assert_eq!(lists(&index), committed);
    }

    #[test]
    fn test_a_new_index_built_in_one_go_saves_nothing() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("index.chassis");
        let mut index = VectorIndex::open(&path, 16, IndexOptions::default()).unwrap();
        index.add_batch(&(0..500).flat_map(random_vector).collect::<Vec<f32>>()).unwrap();
        for id in 500..600 {
            index.add(&random_vector(id)).unwrap();
        }
        assert!(!storage::sibling(&path, "undo").exists(), "nothing committed could change");
    }

    /// A new node's neighbors are selected from the distances its search computed; a backlink
    /// computes them itself. Both must select alike.
    #[test]
    fn test_selecting_from_known_distances_matches_computing_them() {
        let file = NamedTempFile::new().unwrap();
        let index = filter_index(&file);
        let graph = &index.graph;
        for base in [0u64, 7, 1234, 2499] {
            let ids: Vec<u64> = (0..300).map(|i| (base + 1 + i * 8) % 2500).collect();
            let from = graph.storage.get_vector_slice(base).unwrap();
            let to = |id| graph.storage.get_vector_slice(id).unwrap();
            let mut near: Vec<(u64, f32)> =
                ids.iter().map(|&id| (id, euclidean_distance(from, to(id)))).collect();
            near.sort_by(|a, b| a.1.total_cmp(&b.1));
            for max in [8, 32] {
                let computed = graph.select_neighbors_heuristic(base, &ids, 0, max, None).unwrap();
                assert_eq!(graph.select_diverse(&near, max, None).unwrap(), computed);
                assert!(!computed.is_empty() && computed.len() <= max);
            }
        }
    }

    #[test]
    fn test_the_descent_stops_where_no_neighbor_is_nearer() {
        let file = NamedTempFile::new().unwrap();
        let mut index = VectorIndex::open(file.path(), 16, IndexOptions::default()).unwrap();
        let vectors: Vec<f32> = (0..3000).flat_map(random_vector).collect();
        index.add_batch(&vectors).unwrap();
        let graph = &index.graph;
        let entry = graph.entry_point.unwrap();
        let to = |query: &[f32], slot| {
            euclidean_distance(query, graph.storage.get_vector_slice(slot).unwrap())
        };
        assert!(graph.max_layer > 0);
        for query in (5000..5020).map(random_vector) {
            for layer in 1..=graph.max_layer {
                let found = graph.search_layer_greedy(&query, entry, layer).unwrap();
                let nearest = to(&query, found);
                assert!(nearest <= to(&query, entry));
                let mut neighbors = graph.neighbors_iter_from_mmap(found, layer).unwrap();
                assert!(neighbors.all(|n| to(&query, n) >= nearest), "layer {layer}");
            }
        }
    }

    #[test]
    fn test_batch_entry_point_is_on_the_top_layer() {
        for existing in [0, 50] {
            let file = NamedTempFile::new().unwrap();
            let mut index = VectorIndex::open(file.path(), 16, IndexOptions::default()).unwrap();
            for id in 0..existing {
                index.add(&random_vector(id)).unwrap();
            }
            let vectors: Vec<f32> = (existing..existing + 3000).flat_map(random_vector).collect();
            index.add_batch(&vectors).unwrap();
            let graph = &index.graph;
            let layers = |slot| graph.storage.layer_count(slot).unwrap() - 1;
            let top = (0..graph.node_count()).map(layers).max().unwrap();
            assert!(top > 0, "3,050 draws should reach layer 1");
            assert_eq!((graph.max_layer, layers(graph.entry_point.unwrap())), (top, top));
        }
    }

    #[test]
    fn test_filtered_scan_is_exact_with_a_nan_vector() {
        let file = NamedTempFile::new().unwrap();
        let mut index = VectorIndex::open(file.path(), 16, IndexOptions::default()).unwrap();
        // `add` refuses one now; a file from before could hold one.
        index.insert(0, &[f32::NAN; 16]).unwrap();
        for id in 1..300 {
            index.add(&random_vector(id)).unwrap();
        }
        let allow = |slot: u64| slot.is_multiple_of(10);
        let (found, scanned) = index
            .graph
            .search_filtered_reporting(&random_vector(150), 3, 50, &|s| Ok(allow(s)))
            .unwrap();
        assert!(scanned);
        assert_eq!(found[0].id, 150, "{found:?}");
    }

    #[test]
    fn test_vector_index_create_and_add() {
        let temp_file = NamedTempFile::new().unwrap();
        let mut index = VectorIndex::open(temp_file.path(), 128, IndexOptions::default()).unwrap();

        assert_eq!(index.len(), 0);
        assert!(index.is_empty());
        assert_eq!(index.dimensions(), 128);

        // Add a vector
        let vector = vec![0.1; 128];
        let id = index.add(&vector).unwrap();

        assert_eq!(id, 0);
        assert_eq!(index.len(), 1);
        assert!(!index.is_empty());
    }

    #[test]
    fn test_vector_index_dimension_mismatch() {
        let temp_file = NamedTempFile::new().unwrap();
        let mut index = VectorIndex::open(temp_file.path(), 128, IndexOptions::default()).unwrap();

        // Try to add vector with wrong dimensions
        let vector = vec![0.1; 64];
        let result = index.add(&vector);

        assert_eq!(result.unwrap_err().kind(), ErrorKind::DimensionMismatch);
    }

    #[test]
    fn test_vector_index_search() {
        let temp_file = NamedTempFile::new().unwrap();
        let mut index = VectorIndex::open(temp_file.path(), 128, IndexOptions::default()).unwrap();

        // Add some vectors
        for i in 0..10 {
            let mut vector = vec![0.0; 128];
            vector[0] = i as f32 / 10.0;
            index.add(&vector).unwrap();
        }

        // Search
        let query = vec![0.5; 128];
        let results = index.search(&query, 5).unwrap();

        assert!(results.len() <= 5);
        assert!(results.len() <= 10);
    }

    #[test]
    fn test_vector_index_persistence() {
        let temp_file = NamedTempFile::new().unwrap();
        let path = temp_file.path().to_owned();

        // Create and populate index
        {
            let mut index = VectorIndex::open(&path, 128, IndexOptions::default()).unwrap();

            for i in 0..5 {
                let mut vector = vec![0.0; 128];
                vector[0] = i as f32;
                index.add(&vector).unwrap();
            }

            index.flush().unwrap();
        }

        // Reopen and verify
        {
            let index = VectorIndex::open(&path, 128, IndexOptions::default()).unwrap();
            assert_eq!(index.len(), 5);

            let mut query = vec![0.0; 128];
            query[0] = 2.0;

            let results = index.search(&query, 3).unwrap();
            assert!(!results.is_empty());
        }
    }

    #[test]
    fn test_ghost_node_recovery() {
        let temp_file = NamedTempFile::new().unwrap();
        let path = temp_file.path().to_owned();

        // Simulate ghost node: insert vector but don't publish node
        {
            let storage = Storage::open(&path, 128).unwrap();
            let params = HnswParams::default();
            let mut graph = HnswGraph::open(storage, params).unwrap();

            // A vector written but never linked when the graph flushes (creates ghost node)
            let vector = vec![1.0; 128];
            graph.storage.insert(&vector).unwrap();
            graph.commit().unwrap();

            // Don't add to graph - this creates a ghost node
            assert_eq!(graph.storage.count(), 1);
            assert_eq!(graph.node_count(), 0);
        }

        // Reopen with VectorIndex - should handle ghost node
        {
            let mut index = VectorIndex::open(&path, 128, IndexOptions::default()).unwrap();

            // Ghost node should be ignored (not counted)
            assert_eq!(index.len(), 0);

            // Next add should reclaim the ghost node space
            let vector = vec![2.0; 128];
            let id = index.add(&vector).unwrap();

            // Should reuse the ghost node's ID (0)
            assert_eq!(id, 0);
            assert_eq!(index.len(), 1);
        }
    }

    #[test]
    fn test_diverse_neighbor_selection() {
        let temp_file = NamedTempFile::new().unwrap();
        let mut index = VectorIndex::open(temp_file.path(), 128, IndexOptions::default()).unwrap();

        // Add vectors in a line (should create diverse neighborhoods)
        for i in 0..20 {
            let mut vector = vec![0.0; 128];
            vector[0] = i as f32;
            index.add(&vector).unwrap();
        }

        // Verify graph was built
        assert_eq!(index.len(), 20);

        // Search should work
        let query = vec![10.0; 128];
        let results = index.search(&query, 5).unwrap();
        assert!(!results.is_empty());
    }
}