manifoldb 0.1.4

A multi-paradigm embedded database for graph, vector, and relational data
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
//! Vector index management for HNSW indexes.
//!
//! This module provides functionality for:
//! - Building HNSW indexes from existing entity data
//! - Maintaining indexes during DML operations (INSERT/UPDATE/DELETE)
//! - Loading and persisting indexes to storage
//!
//! # Example
//!
//! ```ignore
//! use manifoldb::vector::{HnswIndexBuilder, IndexManager};
//!
//! // Create an HNSW index on a vector column
//! let mut tx = db.begin()?;
//! HnswIndexBuilder::new("embeddings_idx", "documents", "embedding")
//!     .dimension(384)
//!     .distance_metric(DistanceMetric::Cosine)
//!     .build(&mut tx)?;
//! tx.commit()?;
//! ```

use manifoldb_core::{Entity, EntityId, PointId, TransactionError, Value};
use manifoldb_storage::Transaction;
use manifoldb_vector::distance::DistanceMetric;
use manifoldb_vector::index::{
    clear_index_tx, delete_node_tx, hnsw_table_name, load_graph_tx, load_metadata_tx,
    save_graph_tx, search_layer_filtered, FilteredSearchConfig, HnswConfig, HnswGraph,
    HnswIndexEntry, HnswNode, HnswRegistry, SearchResult,
};
use manifoldb_vector::types::Embedding;

use crate::collection::VectorConfig;
use crate::transaction::DatabaseTransaction;

/// Error type for vector index operations.
#[derive(Debug, thiserror::Error)]
pub enum VectorIndexError {
    /// The index already exists.
    #[error("Index already exists: {0}")]
    IndexExists(String),

    /// The index was not found.
    #[error("Index not found: {0}")]
    IndexNotFound(String),

    /// The table was not found.
    #[error("Table not found: {0}")]
    TableNotFound(String),

    /// The column was not found.
    #[error("Column not found: {0}")]
    ColumnNotFound(String),

    /// Dimension mismatch between vectors.
    #[error("Dimension mismatch: expected {expected}, got {actual}")]
    DimensionMismatch {
        /// Expected dimension.
        expected: usize,
        /// Actual dimension.
        actual: usize,
    },

    /// Invalid vector data.
    #[error("Invalid vector in entity {entity_id}: {reason}")]
    InvalidVector {
        /// Entity ID with invalid vector.
        entity_id: EntityId,
        /// Reason for the error.
        reason: String,
    },

    /// Transaction error.
    #[error("Transaction error: {0}")]
    Transaction(#[from] TransactionError),

    /// Vector operation error.
    #[error("Vector error: {0}")]
    Vector(#[from] manifoldb_vector::error::VectorError),

    /// Storage error.
    #[error("Storage error: {0}")]
    Storage(String),

    /// Direct storage error.
    #[error("Storage error: {0}")]
    StorageError(#[from] manifoldb_storage::StorageError),
}

/// Builder for creating HNSW indexes.
pub struct HnswIndexBuilder {
    name: String,
    table: String,
    column: String,
    dimension: Option<usize>,
    distance_metric: DistanceMetric,
    config: HnswConfig,
}

impl HnswIndexBuilder {
    /// Create a new HNSW index builder.
    ///
    /// # Arguments
    ///
    /// * `name` - The unique name for this index
    /// * `table` - The table (entity label) this index is on
    /// * `column` - The column (property name) containing vector data
    #[must_use]
    pub fn new(
        name: impl Into<String>,
        table: impl Into<String>,
        column: impl Into<String>,
    ) -> Self {
        Self {
            name: name.into(),
            table: table.into(),
            column: column.into(),
            dimension: None,
            distance_metric: DistanceMetric::Cosine,
            config: HnswConfig::default(),
        }
    }

    /// Set the dimension of vectors in this index.
    ///
    /// If not set, the dimension will be inferred from the first vector found.
    #[must_use]
    pub const fn dimension(mut self, dimension: usize) -> Self {
        self.dimension = Some(dimension);
        self
    }

    /// Set the distance metric.
    #[must_use]
    pub const fn distance_metric(mut self, metric: DistanceMetric) -> Self {
        self.distance_metric = metric;
        self
    }

    /// Set the M parameter (max connections per node).
    #[must_use]
    pub fn m(mut self, m: usize) -> Self {
        self.config.m = m;
        self.config.m_max0 = 2 * m;
        self
    }

    /// Set the ef_construction parameter.
    #[must_use]
    pub fn ef_construction(mut self, ef: usize) -> Self {
        self.config.ef_construction = ef;
        self
    }

    /// Set the ef_search parameter.
    #[must_use]
    pub fn ef_search(mut self, ef: usize) -> Self {
        self.config.ef_search = ef;
        self
    }

    /// Build the index, inserting all existing data.
    ///
    /// This reads vectors from the `CollectionVectorStore` for the specified
    /// collection and vector name, then inserts them into the HNSW index.
    ///
    /// # Vector Source
    ///
    /// Vectors are read from the `collection_vectors` table, NOT from entity
    /// properties. This aligns with the architecture where vectors are stored
    /// separately from entities for efficiency.
    pub fn build<T: Transaction>(
        self,
        tx: &mut DatabaseTransaction<T>,
    ) -> Result<(), VectorIndexError> {
        use crate::collection::{CollectionManager, CollectionName};
        use manifoldb_storage::Cursor;
        use manifoldb_vector::{
            encoding::{decode_collection_vector_key, encode_collection_vector_prefix},
            TABLE_COLLECTION_VECTORS,
        };
        use std::ops::Bound;

        // Check if index already exists
        let storage = tx.storage_ref()?;
        if HnswRegistry::exists(storage, &self.name)? {
            return Err(VectorIndexError::IndexExists(self.name));
        }

        // Parse collection name
        let collection_name = CollectionName::new(&self.table)
            .map_err(|e| VectorIndexError::Storage(e.to_string()))?;

        // Get collection to get its ID
        let collection_id = CollectionManager::get(tx, &collection_name)
            .map_err(|e| VectorIndexError::Storage(e.to_string()))?
            .map(|c| c.id());

        // Collect vectors from CollectionVectorStore
        let mut vectors: Vec<(EntityId, Embedding)> = Vec::new();
        let mut inferred_dimension: Option<usize> = self.dimension;

        // If collection exists, read vectors from it
        if let Some(coll_id) = collection_id {
            let prefix = encode_collection_vector_prefix(coll_id);
            let prefix_end = {
                let mut end = prefix.clone();
                for byte in end.iter_mut().rev() {
                    if *byte < 0xFF {
                        *byte += 1;
                        break;
                    }
                }
                end
            };

            // Use the hash of the vector name for filtering
            let target_hash = manifoldb_vector::encoding::hash_name(&self.column);

            let storage = tx.storage_ref()?;
            let mut cursor = storage.range(
                TABLE_COLLECTION_VECTORS,
                Bound::Included(prefix.as_slice()),
                Bound::Excluded(prefix_end.as_slice()),
            )?;

            while let Some((ref key, ref value)) = cursor.next()? {
                // Decode key to check if it matches our vector name
                if let Some(decoded) = decode_collection_vector_key(&key) {
                    if decoded.vector_name_hash == target_hash {
                        // Decode the vector data
                        if let Ok((vector_data, _)) = manifoldb_vector::decode_vector_value(&value)
                        {
                            if let Some(dense) = vector_data.as_dense() {
                                let embedding = Embedding::new(dense.to_vec())
                                    .map_err(|e| VectorIndexError::Vector(e))?;

                                // Check/infer dimension
                                match inferred_dimension {
                                    None => inferred_dimension = Some(embedding.len()),
                                    Some(dim) if dim != embedding.len() => {
                                        return Err(VectorIndexError::DimensionMismatch {
                                            expected: dim,
                                            actual: embedding.len(),
                                        });
                                    }
                                    _ => {}
                                }

                                vectors.push((decoded.entity_id, embedding));
                            }
                        }
                    }
                }
            }
        }

        // Determine final dimension (use 1 if no vectors found; will be validated on first insert)
        let dimension = inferred_dimension.unwrap_or(1);

        // Build the HNSW graph in memory
        let mut graph = HnswGraph::new(dimension, self.distance_metric);

        // Insert all vectors using the HNSW algorithm
        for (entity_id, embedding) in vectors {
            insert_into_graph(&mut graph, entity_id, embedding, &self.config)?;
        }

        // Save to storage
        let table_name = hnsw_table_name(&self.name);
        let storage = tx.storage_mut_ref()?;
        save_graph_tx(storage, &table_name, &graph, &self.config)?;

        // Register the index
        let entry = HnswIndexEntry::new(
            &self.name,
            &self.table,
            &self.column,
            dimension,
            self.distance_metric,
            &self.config,
        );
        HnswRegistry::register(storage, &entry)?;

        Ok(())
    }
}

/// Drop an HNSW index.
pub fn drop_index<T: Transaction>(
    tx: &mut DatabaseTransaction<T>,
    name: &str,
    if_exists: bool,
) -> Result<bool, VectorIndexError> {
    let storage = tx.storage_ref()?;

    // Check if index exists
    if !HnswRegistry::exists(storage, name)? {
        if if_exists {
            return Ok(false);
        }
        return Err(VectorIndexError::IndexNotFound(name.to_string()));
    }

    let table_name = hnsw_table_name(name);

    // Clear the index data
    let storage = tx.storage_mut_ref()?;
    clear_index_tx(storage, &table_name)?;

    // Remove from registry
    HnswRegistry::drop(storage, name)?;

    Ok(true)
}

/// Load an HNSW index graph from storage.
pub fn load_index<T: Transaction>(
    tx: &DatabaseTransaction<T>,
    name: &str,
) -> Result<(HnswGraph, HnswConfig), VectorIndexError> {
    let storage = tx.storage_ref()?;

    // Get the registry entry
    let entry = HnswRegistry::get(storage, name)?
        .ok_or_else(|| VectorIndexError::IndexNotFound(name.to_string()))?;

    let table_name = hnsw_table_name(name);

    // Load metadata
    let metadata = load_metadata_tx(storage, &table_name)?
        .ok_or_else(|| VectorIndexError::IndexNotFound(name.to_string()))?;

    // Load the graph
    let graph = load_graph_tx(storage, &table_name, &metadata)?;

    Ok((graph, entry.config()))
}

/// Find an HNSW index for a given table and column.
pub fn find_index_for_column<T: Transaction>(
    tx: &DatabaseTransaction<T>,
    table: &str,
    column: &str,
) -> Result<Option<String>, VectorIndexError> {
    let storage = tx.storage_ref()?;

    // List all indexes for this table
    let indexes = HnswRegistry::list_for_table(storage, table)?;

    // Find one that matches the column
    for entry in indexes {
        if entry.column == column {
            return Ok(Some(entry.name.clone()));
        }
    }

    Ok(None)
}

/// Perform an HNSW search without filtering.
pub fn search_index<T: Transaction>(
    tx: &DatabaseTransaction<T>,
    index_name: &str,
    query: &Embedding,
    k: usize,
    ef_search: Option<usize>,
) -> Result<Vec<SearchResult>, VectorIndexError> {
    let (graph, config) = load_index(tx, index_name)?;

    if graph.dimension != query.len() {
        return Err(VectorIndexError::DimensionMismatch {
            expected: graph.dimension,
            actual: query.len(),
        });
    }

    if graph.nodes.is_empty() {
        return Ok(Vec::new());
    }

    let entry_point =
        graph.entry_point.ok_or_else(|| VectorIndexError::Storage("no entry point".to_string()))?;

    // ef_search defaults to configured value, but is always at least k
    let ef = ef_search.unwrap_or(config.ef_search).max(k);

    // Search from top layer to layer 1, using ef=1 (greedy)
    let mut current_ep = vec![entry_point];

    for layer in (1..=graph.max_layer).rev() {
        let candidates =
            manifoldb_vector::index::search_layer(&graph, query, &current_ep, 1, layer);
        current_ep = candidates.into_iter().map(|c| c.entity_id).collect();
        if current_ep.is_empty() {
            current_ep = vec![entry_point];
        }
    }

    // Search layer 0 with full ef
    let candidates = manifoldb_vector::index::search_layer(&graph, query, &current_ep, ef, 0);

    // Return top k results
    let results: Vec<SearchResult> = candidates
        .into_iter()
        .take(k)
        .map(|c| SearchResult::new(c.entity_id, c.distance))
        .collect();

    Ok(results)
}

/// Perform a filtered HNSW search.
///
/// This applies the filter during graph traversal, which is more efficient
/// than post-filtering when the filter is selective.
pub fn search_index_filtered<T, F>(
    tx: &DatabaseTransaction<T>,
    index_name: &str,
    query: &Embedding,
    k: usize,
    predicate: F,
    ef_search: Option<usize>,
    filter_config: Option<FilteredSearchConfig>,
) -> Result<Vec<SearchResult>, VectorIndexError>
where
    T: Transaction,
    F: Fn(EntityId) -> bool,
{
    let (graph, config) = load_index(tx, index_name)?;

    if graph.dimension != query.len() {
        return Err(VectorIndexError::DimensionMismatch {
            expected: graph.dimension,
            actual: query.len(),
        });
    }

    if graph.nodes.is_empty() {
        return Ok(Vec::new());
    }

    let entry_point =
        graph.entry_point.ok_or_else(|| VectorIndexError::Storage("no entry point".to_string()))?;

    // Get filtered search config
    let fc = filter_config.unwrap_or_default();

    // Calculate adjusted ef_search for filtering
    let base_ef = ef_search.unwrap_or(config.ef_search).max(k);
    let ef = fc.adjusted_ef(base_ef, None);

    // Search from top layer to layer 1, using ef=1 (greedy)
    // Note: We don't filter in upper layers - just find a good entry point
    let mut current_ep = vec![entry_point];

    for layer in (1..=graph.max_layer).rev() {
        let candidates =
            manifoldb_vector::index::search_layer(&graph, query, &current_ep, 1, layer);
        current_ep = candidates.into_iter().map(|c| c.entity_id).collect();
        if current_ep.is_empty() {
            current_ep = vec![entry_point];
        }
    }

    // Search layer 0 with filter applied during traversal
    let candidates = search_layer_filtered(&graph, query, &current_ep, ef, 0, &predicate);

    // Return top k results
    let results: Vec<SearchResult> = candidates
        .into_iter()
        .take(k)
        .map(|c| SearchResult::new(c.entity_id, c.distance))
        .collect();

    Ok(results)
}

/// Update an entity in the HNSW index.
///
/// If the entity has a vector property that matches an indexed column,
/// the index is updated accordingly.
pub fn update_entity_in_indexes<T: Transaction>(
    tx: &mut DatabaseTransaction<T>,
    entity: &Entity,
    old_entity: Option<&Entity>,
) -> Result<(), VectorIndexError> {
    // Collect index names and columns first to avoid borrowing issues
    let mut index_operations: Vec<(String, Option<Embedding>, Option<Embedding>)> = Vec::new();

    {
        let storage = tx.storage_ref()?;

        // Find all indexes for this entity's labels
        for label in &entity.labels {
            let indexes = HnswRegistry::list_for_table(storage, label.as_str())?;

            for entry in indexes {
                let old_embedding =
                    old_entity.and_then(|e| extract_embedding(e, &entry.column).ok().flatten());
                let new_embedding = extract_embedding(entity, &entry.column)?;
                index_operations.push((entry.name.clone(), old_embedding, new_embedding));
            }
        }
    }

    // Now perform the operations
    for (index_name, old_embedding, new_embedding) in index_operations {
        match (old_embedding, new_embedding) {
            (None, Some(embedding)) => {
                // Insert: new vector where none existed
                add_to_index(tx, &index_name, entity.id, embedding)?;
            }
            (Some(_), None) => {
                // Delete: vector removed
                remove_from_index(tx, &index_name, entity.id)?;
            }
            (Some(old), Some(new)) if old.as_slice() != new.as_slice() => {
                // Update: vector changed
                remove_from_index(tx, &index_name, entity.id)?;
                add_to_index(tx, &index_name, entity.id, new)?;
            }
            _ => {
                // No change
            }
        }
    }

    Ok(())
}

/// Remove an entity from all HNSW indexes.
pub fn remove_entity_from_indexes<T: Transaction>(
    tx: &mut DatabaseTransaction<T>,
    entity: &Entity,
) -> Result<(), VectorIndexError> {
    // Collect index names first to avoid borrowing issues
    let mut indexes_to_update: Vec<String> = Vec::new();

    {
        let storage = tx.storage_ref()?;

        // Find all indexes for this entity's labels
        for label in &entity.labels {
            let indexes = HnswRegistry::list_for_table(storage, label.as_str())?;

            for entry in indexes {
                if extract_embedding(entity, &entry.column)?.is_some() {
                    indexes_to_update.push(entry.name.clone());
                }
            }
        }
    }

    // Now perform the removals
    for index_name in indexes_to_update {
        remove_from_index(tx, &index_name, entity.id)?;
    }

    Ok(())
}

/// Add an entity to an HNSW index.
fn add_to_index<T: Transaction>(
    tx: &mut DatabaseTransaction<T>,
    index_name: &str,
    entity_id: EntityId,
    embedding: Embedding,
) -> Result<(), VectorIndexError> {
    let (mut graph, config) = load_index(tx, index_name)?;

    // Check dimension
    if graph.dimension != embedding.len() && !graph.nodes.is_empty() {
        return Err(VectorIndexError::DimensionMismatch {
            expected: graph.dimension,
            actual: embedding.len(),
        });
    }

    // Update dimension if this is the first node
    if graph.nodes.is_empty() {
        graph.dimension = embedding.len();
    }

    // Insert into graph
    insert_into_graph(&mut graph, entity_id, embedding, &config)?;

    // Save updated graph
    let table_name = hnsw_table_name(index_name);
    let storage = tx.storage_mut_ref()?;
    save_graph_tx(storage, &table_name, &graph, &config)?;

    Ok(())
}

/// Remove an entity from an HNSW index.
fn remove_from_index<T: Transaction>(
    tx: &mut DatabaseTransaction<T>,
    index_name: &str,
    entity_id: EntityId,
) -> Result<(), VectorIndexError> {
    let (mut graph, config) = load_index(tx, index_name)?;

    // Get node's max_layer before removing (needed for storage deletion)
    let max_layer = graph.nodes.get(&entity_id).map(|n| n.max_layer);

    // Remove the node from the in-memory graph
    remove_from_graph(&mut graph, entity_id)?;

    let table_name = hnsw_table_name(index_name);
    let storage = tx.storage_mut_ref()?;

    // Delete the node from storage (if it existed)
    if let Some(max_layer) = max_layer {
        delete_node_tx(storage, &table_name, entity_id, max_layer)?;
    }

    // Save updated graph (metadata and any modified neighbor connections)
    save_graph_tx(storage, &table_name, &graph, &config)?;

    Ok(())
}

/// Extract an embedding from an entity's property.
fn extract_embedding(entity: &Entity, column: &str) -> Result<Option<Embedding>, VectorIndexError> {
    match entity.get_property(column) {
        Some(Value::Vector(v)) => {
            let embedding = Embedding::new(v.clone()).map_err(|e| {
                VectorIndexError::InvalidVector { entity_id: entity.id, reason: e.to_string() }
            })?;
            Ok(Some(embedding))
        }
        Some(_) => Ok(None), // Non-vector property
        None => Ok(None),    // No such property
    }
}

/// Insert a vector into an HNSW graph.
fn insert_into_graph(
    graph: &mut HnswGraph,
    entity_id: EntityId,
    embedding: Embedding,
    config: &HnswConfig,
) -> Result<(), VectorIndexError> {
    // Generate random level for this node
    let level = generate_level(config.ml, config.m);

    // Create the new node
    let node = HnswNode::new(entity_id, embedding.clone(), level);

    if graph.nodes.is_empty() {
        // First node becomes entry point
        graph.entry_point = Some(entity_id);
        graph.max_layer = level;
        graph.nodes.insert(entity_id, node);
        return Ok(());
    }

    // Find entry point
    let entry_point =
        graph.entry_point.ok_or_else(|| VectorIndexError::Storage("no entry point".to_string()))?;

    // Search for insertion point from top to level+1
    let mut current = entry_point;
    for layer in (level + 1..=graph.max_layer).rev() {
        current = search_layer_greedy(graph, &embedding, current, layer)?;
    }

    // For each layer from level down to 0
    for layer in (0..=level.min(graph.max_layer)).rev() {
        // Find neighbors at this layer
        let neighbors =
            search_layer_candidates(graph, &embedding, current, layer, config.ef_construction)?;

        // Select best neighbors
        let m = if layer == 0 { config.m_max0 } else { config.m };
        let selected: Vec<EntityId> = neighbors.into_iter().take(m).collect();

        // Add connections
        graph.nodes.entry(entity_id).or_insert_with(|| node.clone()).connections[layer]
            .clone_from(&selected);

        // Add reverse connections
        for &neighbor_id in &selected {
            if let Some(neighbor) = graph.nodes.get_mut(&neighbor_id) {
                if layer < neighbor.connections.len() {
                    let neighbor_m = if layer == 0 { config.m_max0 } else { config.m };
                    if !neighbor.connections[layer].contains(&entity_id) {
                        neighbor.connections[layer].push(entity_id);
                        // Prune if necessary
                        if neighbor.connections[layer].len() > neighbor_m {
                            prune_connections(graph, neighbor_id, layer, neighbor_m)?;
                        }
                    }
                }
            }
        }

        // Update current for next layer
        if !selected.is_empty() {
            current = selected[0];
        }
    }

    // Node was already inserted via entry().or_insert_with() in the loop above

    // Update entry point if needed
    if level > graph.max_layer {
        graph.max_layer = level;
        graph.entry_point = Some(entity_id);
    }

    Ok(())
}

/// Remove a vector from an HNSW graph.
fn remove_from_graph(graph: &mut HnswGraph, entity_id: EntityId) -> Result<(), VectorIndexError> {
    // Get the node's max_layer before removing
    let max_layer = match graph.nodes.get(&entity_id) {
        Some(node) => node.max_layer,
        None => return Ok(()), // Node doesn't exist, nothing to do
    };

    // Remove connections from neighbors
    for layer in 0..=max_layer {
        if let Some(node) = graph.nodes.get(&entity_id) {
            let neighbors = node.connections.get(layer).cloned().unwrap_or_default();
            for neighbor_id in neighbors {
                if let Some(neighbor) = graph.nodes.get_mut(&neighbor_id) {
                    if layer < neighbor.connections.len() {
                        neighbor.connections[layer].retain(|&id| id != entity_id);
                    }
                }
            }
        }
    }

    // Remove the node
    graph.nodes.remove(&entity_id);

    // Update entry point if necessary
    if graph.entry_point == Some(entity_id) {
        // Find a new entry point - prefer highest layer node
        graph.entry_point = graph.nodes.iter().max_by_key(|(_, n)| n.max_layer).map(|(&id, _)| id);

        // Update max_layer
        graph.max_layer = graph.nodes.values().map(|n| n.max_layer).max().unwrap_or(0);
    }

    Ok(())
}

/// Generate a random level for a new node using the standard HNSW formula.
fn generate_level(ml: f64, _m: usize) -> usize {
    use std::hash::{Hash, Hasher};

    // Use a simple hash-based randomization for deterministic testing
    let mut hasher = std::collections::hash_map::DefaultHasher::new();
    std::time::SystemTime::now().hash(&mut hasher);
    let random = hasher.finish();

    let r = (random as f64) / (u64::MAX as f64);
    (-r.ln() * ml).floor() as usize
}

/// Search layer greedily, returning the closest node to the query.
fn search_layer_greedy(
    graph: &HnswGraph,
    query: &Embedding,
    entry: EntityId,
    layer: usize,
) -> Result<EntityId, VectorIndexError> {
    let mut current = entry;
    let mut current_dist = compute_distance(graph, query, current)?;

    loop {
        let mut changed = false;

        if let Some(node) = graph.nodes.get(&current) {
            if layer < node.connections.len() {
                for &neighbor_id in &node.connections[layer] {
                    let dist = compute_distance(graph, query, neighbor_id)?;
                    if dist < current_dist {
                        current = neighbor_id;
                        current_dist = dist;
                        changed = true;
                    }
                }
            }
        }

        if !changed {
            break;
        }
    }

    Ok(current)
}

/// Search layer for candidates, returning the closest nodes.
fn search_layer_candidates(
    graph: &HnswGraph,
    query: &Embedding,
    entry: EntityId,
    layer: usize,
    ef: usize,
) -> Result<Vec<EntityId>, VectorIndexError> {
    use std::cmp::Reverse;
    use std::collections::{BinaryHeap, HashSet};

    #[derive(PartialEq)]
    struct Candidate {
        distance: f32,
        id: EntityId,
    }

    impl Eq for Candidate {}

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

    impl Ord for Candidate {
        fn cmp(&self, other: &Self) -> std::cmp::Ordering {
            self.distance.partial_cmp(&other.distance).unwrap_or(std::cmp::Ordering::Equal)
        }
    }

    let entry_dist = compute_distance(graph, query, entry)?;

    let mut visited = HashSet::new();
    visited.insert(entry);

    // Min-heap for candidates to explore
    let mut candidates = BinaryHeap::new();
    candidates.push(Reverse(Candidate { distance: entry_dist, id: entry }));

    // Max-heap for results (we want to keep the closest ef nodes)
    let mut results = BinaryHeap::new();
    results.push(Candidate { distance: entry_dist, id: entry });

    while let Some(Reverse(Candidate { distance: current_dist, id: current })) = candidates.pop() {
        // Get worst distance in results
        let worst_dist = results.peek().map(|c| c.distance).unwrap_or(f32::MAX);

        if current_dist > worst_dist && results.len() >= ef {
            break;
        }

        if let Some(node) = graph.nodes.get(&current) {
            if layer < node.connections.len() {
                for &neighbor_id in &node.connections[layer] {
                    if visited.insert(neighbor_id) {
                        let dist = compute_distance(graph, query, neighbor_id)?;

                        if results.len() < ef || dist < worst_dist {
                            candidates.push(Reverse(Candidate { distance: dist, id: neighbor_id }));
                            results.push(Candidate { distance: dist, id: neighbor_id });

                            if results.len() > ef {
                                results.pop();
                            }
                        }
                    }
                }
            }
        }
    }

    // Convert results to sorted vector
    let mut result_vec: Vec<_> = results.into_iter().map(|c| (c.distance, c.id)).collect();
    result_vec.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(std::cmp::Ordering::Equal));

    Ok(result_vec.into_iter().map(|(_, id)| id).collect())
}

/// Prune connections at a layer to maintain the maximum connection limit.
fn prune_connections(
    graph: &mut HnswGraph,
    node_id: EntityId,
    layer: usize,
    max_connections: usize,
) -> Result<(), VectorIndexError> {
    let node = match graph.nodes.get(&node_id) {
        Some(n) => n,
        None => return Ok(()),
    };

    if layer >= node.connections.len() {
        return Ok(());
    }

    let embedding = node.embedding.clone();
    let connections = node.connections[layer].clone();

    // Sort by distance and keep closest
    let mut distances: Vec<(f32, EntityId)> = Vec::new();
    for &neighbor_id in &connections {
        if let Some(neighbor) = graph.nodes.get(&neighbor_id) {
            let dist =
                compute_distance_embeddings(&embedding, &neighbor.embedding, graph.distance_metric);
            distances.push((dist, neighbor_id));
        }
    }

    distances.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(std::cmp::Ordering::Equal));

    let new_connections: Vec<EntityId> =
        distances.into_iter().take(max_connections).map(|(_, id)| id).collect();

    if let Some(node) = graph.nodes.get_mut(&node_id) {
        if layer < node.connections.len() {
            node.connections[layer] = new_connections;
        }
    }

    Ok(())
}

/// Compute distance between a query and a node.
fn compute_distance(
    graph: &HnswGraph,
    query: &Embedding,
    node_id: EntityId,
) -> Result<f32, VectorIndexError> {
    let node = graph
        .nodes
        .get(&node_id)
        .ok_or_else(|| VectorIndexError::Storage(format!("node not found: {:?}", node_id)))?;

    Ok(compute_distance_embeddings(query, &node.embedding, graph.distance_metric))
}

/// Compute distance between two embeddings.
fn compute_distance_embeddings(a: &Embedding, b: &Embedding, metric: DistanceMetric) -> f32 {
    let a = a.as_slice();
    let b = b.as_slice();

    match metric {
        DistanceMetric::Euclidean => {
            a.iter().zip(b.iter()).map(|(x, y)| (x - y).powi(2)).sum::<f32>().sqrt()
        }
        DistanceMetric::Cosine => {
            let dot: f32 = a.iter().zip(b.iter()).map(|(x, y)| x * y).sum();
            let norm_a: f32 = a.iter().map(|x| x * x).sum::<f32>().sqrt();
            let norm_b: f32 = b.iter().map(|x| x * x).sum::<f32>().sqrt();
            if norm_a == 0.0 || norm_b == 0.0 {
                f32::MAX
            } else {
                1.0 - (dot / (norm_a * norm_b))
            }
        }
        DistanceMetric::DotProduct => -a.iter().zip(b.iter()).map(|(x, y)| x * y).sum::<f32>(),
        DistanceMetric::Manhattan => a.iter().zip(b.iter()).map(|(x, y)| (x - y).abs()).sum(),
        DistanceMetric::Chebyshev => {
            a.iter().zip(b.iter()).map(|(x, y)| (x - y).abs()).fold(0.0f32, f32::max)
        }
    }
}

// ============================================================================
// Named Vector Collection Integration
// ============================================================================

/// Create HNSW indexes for all dense vectors in a collection.
///
/// This is called when a collection is created to automatically set up
/// indexes based on the vector configurations.
///
/// # Arguments
///
/// * `tx` - The database transaction
/// * `collection_name` - The collection name
/// * `vectors` - Iterator of (vector_name, config) pairs
///
/// # Returns
///
/// A list of index names that were created.
pub fn create_indexes_for_collection<T: Transaction>(
    tx: &mut DatabaseTransaction<T>,
    collection_name: &str,
    vectors: impl IntoIterator<Item = (String, VectorConfig)>,
) -> Result<Vec<String>, VectorIndexError> {
    use crate::collection::IndexMethod;

    let mut created = Vec::new();

    for (vector_name, config) in vectors {
        // Only create HNSW indexes for dense vectors with HNSW config
        if let Some(dimension) = config.dimension() {
            if let IndexMethod::Hnsw(hnsw_params) = &config.index.method {
                // Extract distance metric (only for dense vectors)
                let distance_metric = match &config.distance {
                    crate::collection::DistanceType::Dense(m) => *m,
                    _ => continue, // Skip non-dense vectors
                };

                // Convert HnswParams to HnswConfig
                let hnsw_config = HnswConfig {
                    m: hnsw_params.m,
                    m_max0: hnsw_params.m_max0,
                    ef_construction: hnsw_params.ef_construction,
                    ef_search: hnsw_params.ef_search,
                    ..HnswConfig::default()
                };

                let index_name = create_index_for_named_vector(
                    tx,
                    collection_name,
                    &vector_name,
                    dimension,
                    distance_metric,
                    &hnsw_config,
                )?;

                created.push(index_name);
            }
        }
    }

    Ok(created)
}

/// Create an HNSW index for a specific named vector in a collection.
///
/// Uses the standard naming convention: `{collection}_{vector_name}_hnsw`
pub fn create_index_for_named_vector<T: Transaction>(
    tx: &mut DatabaseTransaction<T>,
    collection_name: &str,
    vector_name: &str,
    dimension: usize,
    distance_metric: DistanceMetric,
    config: &HnswConfig,
) -> Result<String, VectorIndexError> {
    let index_name = HnswRegistry::index_name_for_vector(collection_name, vector_name);

    // Check if index already exists
    let storage = tx.storage_ref()?;
    if HnswRegistry::exists(storage, &index_name)? {
        return Err(VectorIndexError::IndexExists(index_name));
    }

    // Create an empty HNSW graph
    let graph = HnswGraph::new(dimension, distance_metric);

    // Save to storage
    let table_name = hnsw_table_name(&index_name);
    let storage = tx.storage_mut_ref()?;
    save_graph_tx(storage, &table_name, &graph, config)?;

    // Register the index with collection and vector name metadata
    let entry = HnswIndexEntry::for_named_vector(
        collection_name,
        vector_name,
        dimension,
        distance_metric,
        config,
    );
    HnswRegistry::register(storage, &entry)?;

    Ok(index_name)
}

/// Drop all HNSW indexes for a collection.
///
/// This is called when a collection is deleted.
pub fn drop_indexes_for_collection<T: Transaction>(
    tx: &mut DatabaseTransaction<T>,
    collection_name: &str,
) -> Result<Vec<String>, VectorIndexError> {
    let mut dropped = Vec::new();

    // Get all indexes for this collection
    let entries = {
        let storage = tx.storage_ref()?;
        HnswRegistry::list_for_collection(storage, collection_name)?
    };

    // Drop each index
    for entry in entries {
        drop_index(tx, &entry.name, true)?;
        dropped.push(entry.name);
    }

    Ok(dropped)
}

/// Find an HNSW index for a collection's named vector.
///
/// Returns the index name if found.
pub fn find_index_for_named_vector<T: Transaction>(
    tx: &DatabaseTransaction<T>,
    collection_name: &str,
    vector_name: &str,
) -> Result<Option<String>, VectorIndexError> {
    let storage = tx.storage_ref()?;

    if let Some(entry) = HnswRegistry::get_for_named_vector(storage, collection_name, vector_name)?
    {
        return Ok(Some(entry.name.clone()));
    }

    Ok(None)
}

/// Check if an HNSW index exists for a collection's named vector.
pub fn has_index_for_named_vector<T: Transaction>(
    tx: &DatabaseTransaction<T>,
    collection_name: &str,
    vector_name: &str,
) -> Result<bool, VectorIndexError> {
    let storage = tx.storage_ref()?;
    Ok(HnswRegistry::exists_for_named_vector(storage, collection_name, vector_name)?)
}

/// List all HNSW index entries for a collection.
pub fn list_indexes_for_collection<T: Transaction>(
    tx: &DatabaseTransaction<T>,
    collection_name: &str,
) -> Result<Vec<HnswIndexEntry>, VectorIndexError> {
    let storage = tx.storage_ref()?;
    Ok(HnswRegistry::list_for_collection(storage, collection_name)?)
}

/// Update a named vector in the HNSW index when a point is upserted.
///
/// This adds or updates the point's vector in the appropriate HNSW index.
/// For updates, we remove the old entry first to ensure the new embedding is used.
pub fn update_point_vector_in_index<T: Transaction>(
    tx: &mut DatabaseTransaction<T>,
    collection_name: &str,
    vector_name: &str,
    point_id: PointId,
    vector_data: &[f32],
) -> Result<(), VectorIndexError> {
    let index_name = HnswRegistry::index_name_for_vector(collection_name, vector_name);

    // Check if index exists
    let storage = tx.storage_ref()?;
    if !HnswRegistry::exists(storage, &index_name)? {
        // No index for this vector, nothing to do
        return Ok(());
    }

    // Create embedding
    let embedding = Embedding::new(vector_data.to_vec())?;

    // Convert PointId to EntityId for HNSW compatibility
    let entity_id = EntityId::new(point_id.as_u64());

    // For updates: remove old entry first if it exists, then add new one
    // This ensures the new embedding is used and connections are recalculated
    remove_from_index(tx, &index_name, entity_id)?;
    add_to_index(tx, &index_name, entity_id, embedding)?;

    Ok(())
}

/// Remove a point's vector from the HNSW index.
pub fn remove_point_vector_from_index<T: Transaction>(
    tx: &mut DatabaseTransaction<T>,
    collection_name: &str,
    vector_name: &str,
    point_id: PointId,
) -> Result<(), VectorIndexError> {
    let index_name = HnswRegistry::index_name_for_vector(collection_name, vector_name);

    // Check if index exists
    let storage = tx.storage_ref()?;
    if !HnswRegistry::exists(storage, &index_name)? {
        // No index for this vector, nothing to do
        return Ok(());
    }

    // Convert PointId to EntityId for HNSW compatibility
    let entity_id = EntityId::new(point_id.as_u64());

    // Remove from index
    remove_from_index(tx, &index_name, entity_id)?;

    Ok(())
}

/// Remove a point from all HNSW indexes in a collection.
pub fn remove_point_from_collection_indexes<T: Transaction>(
    tx: &mut DatabaseTransaction<T>,
    collection_name: &str,
    point_id: PointId,
) -> Result<(), VectorIndexError> {
    // Get all indexes for this collection
    let entries = {
        let storage = tx.storage_ref()?;
        HnswRegistry::list_for_collection(storage, collection_name)?
    };

    // Convert PointId to EntityId
    let entity_id = EntityId::new(point_id.as_u64());

    // Remove from each index
    for entry in entries {
        remove_from_index(tx, &entry.name, entity_id)?;
    }

    Ok(())
}

/// Search a collection's named vector index.
///
/// This is a convenience function that looks up the index by collection
/// and vector name, then performs the search.
pub fn search_named_vector_index<T: Transaction>(
    tx: &DatabaseTransaction<T>,
    collection_name: &str,
    vector_name: &str,
    query: &Embedding,
    k: usize,
    ef_search: Option<usize>,
) -> Result<Vec<SearchResult>, VectorIndexError> {
    let index_name = HnswRegistry::index_name_for_vector(collection_name, vector_name);
    search_index(tx, &index_name, query, k, ef_search)
}

/// Search a collection's named vector index with filtering.
pub fn search_named_vector_index_filtered<T, F>(
    tx: &DatabaseTransaction<T>,
    collection_name: &str,
    vector_name: &str,
    query: &Embedding,
    k: usize,
    predicate: F,
    ef_search: Option<usize>,
    filter_config: Option<FilteredSearchConfig>,
) -> Result<Vec<SearchResult>, VectorIndexError>
where
    T: Transaction,
    F: Fn(EntityId) -> bool,
{
    let index_name = HnswRegistry::index_name_for_vector(collection_name, vector_name);
    search_index_filtered(tx, &index_name, query, k, predicate, ef_search, filter_config)
}

// ============================================================================
// CollectionVectorProvider adapter for VectorIndexCoordinator
// ============================================================================

use manifoldb_core::CollectionId;
use manifoldb_query::exec::CollectionVectorProvider;
use manifoldb_storage::StorageEngine;
use manifoldb_vector::error::VectorError;
use manifoldb_vector::index::VectorIndexCoordinator;
use manifoldb_vector::types::VectorData;

/// An adapter that implements [`CollectionVectorProvider`] for [`VectorIndexCoordinator`].
///
/// This allows the query executor to interact with the collection-based vector
/// storage through the standard provider interface.
pub struct CollectionVectorAdapter<E: StorageEngine> {
    coordinator: VectorIndexCoordinator<E>,
}

impl<E: StorageEngine> CollectionVectorAdapter<E> {
    /// Create a new adapter wrapping a `VectorIndexCoordinator`.
    pub fn new(coordinator: VectorIndexCoordinator<E>) -> Self {
        Self { coordinator }
    }

    /// Get a reference to the underlying coordinator.
    pub fn coordinator(&self) -> &VectorIndexCoordinator<E> {
        &self.coordinator
    }

    /// Get a mutable reference to the underlying coordinator.
    pub fn coordinator_mut(&mut self) -> &mut VectorIndexCoordinator<E> {
        &mut self.coordinator
    }

    /// Consume the adapter and return the underlying coordinator.
    pub fn into_coordinator(self) -> VectorIndexCoordinator<E> {
        self.coordinator
    }
}

impl<E: StorageEngine + Send + Sync + 'static> CollectionVectorProvider
    for CollectionVectorAdapter<E>
{
    fn upsert_vector(
        &self,
        collection_id: CollectionId,
        entity_id: EntityId,
        collection_name: &str,
        vector_name: &str,
        data: &VectorData,
    ) -> Result<(), VectorError> {
        self.coordinator.upsert_vector(collection_id, entity_id, collection_name, vector_name, data)
    }

    fn delete_vector(
        &self,
        collection_id: CollectionId,
        entity_id: EntityId,
        collection_name: &str,
        vector_name: &str,
    ) -> Result<bool, VectorError> {
        self.coordinator.delete_vector(collection_id, entity_id, collection_name, vector_name)
    }

    fn delete_entity_vectors(
        &self,
        collection_id: CollectionId,
        entity_id: EntityId,
        collection_name: &str,
    ) -> Result<usize, VectorError> {
        self.coordinator.delete_entity_vectors(collection_id, entity_id, collection_name)
    }

    fn get_vector(
        &self,
        collection_id: CollectionId,
        entity_id: EntityId,
        vector_name: &str,
    ) -> Result<Option<VectorData>, VectorError> {
        self.coordinator.get_vector(collection_id, entity_id, vector_name)
    }

    fn get_all_vectors(
        &self,
        collection_id: CollectionId,
        entity_id: EntityId,
    ) -> Result<std::collections::HashMap<String, VectorData>, VectorError> {
        self.coordinator.get_all_vectors(collection_id, entity_id)
    }

    fn search(
        &self,
        collection_name: &str,
        vector_name: &str,
        query: &Embedding,
        k: usize,
        ef_search: Option<usize>,
    ) -> Result<Vec<SearchResult>, VectorError> {
        self.coordinator.search(collection_name, vector_name, query, k, ef_search)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::collection::{CollectionManager, CollectionName};
    use crate::transaction::TransactionManager;
    use manifoldb_storage::backends::RedbEngine;
    use manifoldb_vector::{
        encode_vector_value, encoding::encode_collection_vector_key, VectorData,
        TABLE_COLLECTION_VECTORS,
    };

    /// Helper to store a vector in the CollectionVectorStore for testing
    fn store_vector_for_test<T: Transaction>(
        tx: &mut DatabaseTransaction<T>,
        collection_name: &str,
        entity_id: EntityId,
        vector_name: &str,
        data: &[f32],
    ) {
        let coll_name = CollectionName::new(collection_name).unwrap();

        // Get or create collection
        let collection_id = match CollectionManager::get(tx, &coll_name).unwrap() {
            Some(collection) => collection.id(),
            None => {
                let collection =
                    CollectionManager::create(tx, &coll_name, std::iter::empty()).unwrap();
                collection.id()
            }
        };

        // Store vector
        let key = encode_collection_vector_key(collection_id, entity_id, vector_name);
        let value = encode_vector_value(&VectorData::Dense(data.to_vec()), vector_name);
        let storage = tx.storage_mut().unwrap();
        storage.put(TABLE_COLLECTION_VECTORS, &key, &value).unwrap();
    }

    #[test]
    fn test_hnsw_index_builder() {
        let engine = RedbEngine::in_memory().unwrap();
        let manager = TransactionManager::new(engine);

        // Create some entities with vectors stored in CollectionVectorStore
        {
            let mut tx = manager.begin_write().unwrap();

            let entity1 = tx.create_entity().unwrap().with_label("documents");
            tx.put_entity(&entity1).unwrap();
            store_vector_for_test(
                &mut tx,
                "documents",
                entity1.id,
                "embedding",
                &[0.1f32, 0.2, 0.3, 0.4],
            );

            let entity2 = tx.create_entity().unwrap().with_label("documents");
            tx.put_entity(&entity2).unwrap();
            store_vector_for_test(
                &mut tx,
                "documents",
                entity2.id,
                "embedding",
                &[0.2f32, 0.3, 0.4, 0.5],
            );

            let entity3 = tx.create_entity().unwrap().with_label("documents");
            tx.put_entity(&entity3).unwrap();
            store_vector_for_test(
                &mut tx,
                "documents",
                entity3.id,
                "embedding",
                &[0.3f32, 0.4, 0.5, 0.6],
            );

            tx.commit().unwrap();
        }

        // Create the index
        {
            let mut tx = manager.begin_write().unwrap();

            HnswIndexBuilder::new("test_idx", "documents", "embedding")
                .dimension(4)
                .distance_metric(DistanceMetric::Cosine)
                .m(4)
                .ef_construction(16)
                .build(&mut tx)
                .unwrap();

            tx.commit().unwrap();
        }

        // Verify index was created
        {
            let tx = manager.begin_read().unwrap();
            let (graph, config) = load_index(&tx, "test_idx").unwrap();

            assert_eq!(graph.dimension, 4);
            assert_eq!(graph.nodes.len(), 3);
            assert_eq!(config.m, 4);
        }
    }

    #[test]
    fn test_drop_index() {
        let engine = RedbEngine::in_memory().unwrap();
        let manager = TransactionManager::new(engine);

        // Create an index
        {
            let mut tx = manager.begin_write().unwrap();

            HnswIndexBuilder::new("to_drop", "test", "vec").dimension(4).build(&mut tx).unwrap();

            tx.commit().unwrap();
        }

        // Verify it exists
        {
            let tx = manager.begin_read().unwrap();
            assert!(load_index(&tx, "to_drop").is_ok());
        }

        // Drop it
        {
            let mut tx = manager.begin_write().unwrap();
            assert!(drop_index(&mut tx, "to_drop", false).unwrap());
            tx.commit().unwrap();
        }

        // Verify it's gone
        {
            let tx = manager.begin_read().unwrap();
            assert!(load_index(&tx, "to_drop").is_err());
        }
    }

    /// Test that UPDATE works correctly when HNSW index has only one entity.
    ///
    /// This tests the fix for the "no entry point" error that occurs when:
    /// 1. A single entity is inserted into an HNSW index
    /// 2. That entity is removed (UPDATE = remove old + insert new)
    /// 3. The old node was not deleted from storage, causing reload to fail
    #[test]
    fn test_update_single_entity_hnsw() {
        let engine = RedbEngine::in_memory().unwrap();
        let manager = TransactionManager::new(engine);

        // Step 1: Create a single entity with a vector stored in CollectionVectorStore
        let entity_id;
        {
            let mut tx = manager.begin_write().unwrap();

            let entity = tx.create_entity().unwrap().with_label("docs");
            entity_id = entity.id;
            tx.put_entity(&entity).unwrap();

            // Store vector in CollectionVectorStore
            store_vector_for_test(
                &mut tx,
                "docs",
                entity_id,
                "embedding",
                &[1.0f32, 0.0, 0.0, 0.0],
            );

            tx.commit().unwrap();
        }

        // Step 2: Create an HNSW index on the embedding column
        {
            let mut tx = manager.begin_write().unwrap();

            HnswIndexBuilder::new("single_entity_idx", "docs", "embedding")
                .dimension(4)
                .distance_metric(DistanceMetric::Cosine)
                .m(4)
                .ef_construction(16)
                .build(&mut tx)
                .unwrap();

            tx.commit().unwrap();
        }

        // Verify index has exactly one node and one entry point
        {
            let tx = manager.begin_read().unwrap();
            let (graph, _) = load_index(&tx, "single_entity_idx").unwrap();

            assert_eq!(graph.nodes.len(), 1);
            assert_eq!(graph.entry_point, Some(entity_id));
        }

        // Step 3: Simulate UPDATE by removing and re-adding with new vector
        // This is what happens when an entity's vector is updated
        {
            let mut tx = manager.begin_write().unwrap();

            // Remove the old vector
            remove_from_index(&mut tx, "single_entity_idx", entity_id).unwrap();

            // Add the new vector
            let new_embedding = Embedding::new(vec![0.0f32, 0.0, 0.0, 1.0]).unwrap();
            add_to_index(&mut tx, "single_entity_idx", entity_id, new_embedding).unwrap();

            tx.commit().unwrap();
        }

        // Step 4: Verify the index can be loaded and searched after the update
        // This is where the bug would manifest - loading would fail with "no entry point"
        {
            let tx = manager.begin_read().unwrap();
            let (graph, _) = load_index(&tx, "single_entity_idx").unwrap();

            // Should still have one node
            assert_eq!(graph.nodes.len(), 1);
            // Entry point should be set
            assert_eq!(graph.entry_point, Some(entity_id));

            // The vector should be the new value
            let node = graph.nodes.get(&entity_id).unwrap();
            assert_eq!(node.embedding.as_slice(), &[0.0f32, 0.0, 0.0, 1.0]);
        }

        // Step 5: Verify search works with the updated vector
        {
            let tx = manager.begin_read().unwrap();
            let query = Embedding::new(vec![0.0f32, 0.0, 0.0, 1.0]).unwrap();
            let results = search_index(&tx, "single_entity_idx", &query, 1, None).unwrap();

            assert_eq!(results.len(), 1);
            assert_eq!(results[0].entity_id, entity_id);
            // Distance should be 0 (same vector)
            assert!(results[0].distance < 0.0001);
        }
    }
}