sqlitegraph 2.2.2

Embedded graph database with full ACID transactions, HNSW vector search, dual backend support, and comprehensive graph algorithms library
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
//! HNSW Error Types
//!
//! This module defines all error types specific to HNSW operations.
//! These errors provide detailed information about configuration validation
//! failures, index operation errors, and edge cases during vector search.
//!
//! # Error Categories
//!
//! - **Configuration Errors**: Invalid parameters during HNSW setup
//! - **Validation Errors**: Vector dimension mismatches, invalid operations
//! - **Index Errors**: Runtime errors during index operations
//! - **Storage Errors**: I/O and persistence-related failures
//!
//! # Examples
//!
//! ```rust
//! use sqlitegraph::hnsw::{HnswConfig, HnswConfigError};
//!
//! let result = HnswConfig::builder()
//!     .dimension(0)  // Invalid dimension
//!     .build();
//!
//! assert!(matches!(result, Err(HnswConfigError::InvalidDimension)));
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```

use std::fmt;

/// HNSW configuration validation errors
///
/// These errors occur during HNSW configuration creation when parameters
/// fall outside valid ranges or violate HNSW algorithm constraints.
///
/// # Error Variants
///
/// * `InvalidDimension` - Vector dimension is zero or exceeds practical limits
/// * `InvalidMParameter` - Number of connections per node is invalid
/// * `InvalidEfConstruction` - Construction ef parameter is too small
/// * `InvalidEfSearch` - Search ef parameter is invalid
/// * `InvalidMaxLayers` - Maximum layer count is invalid
///
/// # Examples
///
/// ```rust
/// use sqlitegraph::hnsw::errors::HnswConfigError;
///
/// match error {
///     HnswConfigError::InvalidDimension => {
///         println!("Vector dimension must be > 0");
///     }
///     HnswConfigError::InvalidMParameter => {
///         println!("M parameter must be > 0");
///     }
///     // Handle other error types...
/// }
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum HnswConfigError {
    /// Vector dimension is zero or invalid
    InvalidDimension,

    /// Number of connections per node (M) is zero or invalid
    InvalidMParameter,

    /// Construction ef parameter is less than M
    InvalidEfConstruction,

    /// Search ef parameter is zero or invalid
    InvalidEfSearch,

    /// Maximum number of layers is zero or invalid
    InvalidMaxLayers,
}

impl fmt::Display for HnswConfigError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            HnswConfigError::InvalidDimension => {
                write!(f, "Vector dimension must be greater than 0")
            }
            HnswConfigError::InvalidMParameter => {
                write!(
                    f,
                    "M parameter (connections per node) must be greater than 0"
                )
            }
            HnswConfigError::InvalidEfConstruction => {
                write!(f, "ef_construction must be >= M parameter")
            }
            HnswConfigError::InvalidEfSearch => {
                write!(f, "ef_search parameter must be greater than 0")
            }
            HnswConfigError::InvalidMaxLayers => {
                write!(f, "Maximum number of layers must be greater than 0")
            }
        }
    }
}

impl std::error::Error for HnswConfigError {}

/// HNSW index operation errors
///
/// These errors occur during HNSW index operations such as insertion,
/// search, and index maintenance.
///
/// # Error Variants
///
/// * `VectorDimensionMismatch` - Vector length doesn't match configured dimension
/// * `DuplicateVectorId` - Attempting to insert a vector with existing ID
/// * `VectorNotFound` - No vector found with specified ID
/// * `IndexNotInitialized` - Operation attempted on uninitialized index
/// * `IndexCorrupted` - Index structure is corrupted or invalid
///
/// # Examples
///
/// ```rust
/// use sqlitegraph::hnsw::errors::HnswIndexError;
///
/// match error {
///     HnswIndexError::VectorDimensionMismatch { expected, actual } => {
///         println!("Expected {} dimensions, got {}", expected, actual);
///     }
///     HnswIndexError::DuplicateVectorId(id) => {
///         println!("Vector ID {} already exists", id);
///     }
///     // Handle other error types...
/// }
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[derive(Debug, Clone, PartialEq)]
pub enum HnswIndexError {
    /// Vector dimension doesn't match configured dimension
    VectorDimensionMismatch {
        /// Expected dimension count
        expected: usize,
        /// Actual vector dimension count
        actual: usize,
    },

    /// Attempt to insert duplicate vector ID
    DuplicateVectorId(u64),

    /// Vector ID not found in index
    VectorNotFound(u64),

    /// Index operation attempted on uninitialized index
    IndexNotInitialized,

    /// Index structure corruption detected
    IndexCorrupted(String),

    /// Index capacity exceeded
    CapacityExceeded,

    /// Invalid search parameters
    InvalidSearchParameters,

    /// Node not found in layer
    NodeNotFound(u64),

    /// Invalid node ID (non-sequential or out of range)
    InvalidNodeId(u64),

    /// Attempt to connect node to itself
    SelfConnection(u64),
}

/// Vector storage-related errors
#[derive(Debug, Clone, PartialEq)]
pub enum HnswStorageError {
    /// Invalid vector dimension (zero or too large)
    InvalidDimension(usize),

    /// Vector dimension mismatch between data and claimed dimension
    DimensionMismatch { expected: usize, actual: usize },

    /// Vector data contains invalid values (NaN, Inf, etc.)
    InvalidVectorData,

    /// Vector ID not found in storage
    VectorNotFound(u64),

    /// Batch operation size mismatch
    BatchSizeMismatch,

    /// Storage backend not supported
    BackendNotSupported,

    /// Vector size exceeds maximum limits
    VectorTooLarge { size: usize, max_size: usize },

    /// Storage capacity exceeded
    StorageCapacityExceeded,

    /// I/O error during storage operation
    IoError(String),

    /// Database error during persistence operation
    DatabaseError(String),
}

impl fmt::Display for HnswStorageError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            HnswStorageError::InvalidDimension(dim) => {
                write!(f, "Invalid vector dimension: {}", dim)
            }
            HnswStorageError::DimensionMismatch { expected, actual } => {
                write!(
                    f,
                    "Vector dimension mismatch: expected {}, got {}",
                    expected, actual
                )
            }
            HnswStorageError::InvalidVectorData => {
                write!(f, "Vector data contains invalid values (NaN, Inf, etc.)")
            }
            HnswStorageError::VectorNotFound(id) => {
                write!(f, "Vector ID {} not found in storage", id)
            }
            HnswStorageError::BatchSizeMismatch => {
                write!(f, "Batch operation size mismatch")
            }
            HnswStorageError::BackendNotSupported => {
                write!(f, "Storage backend not supported")
            }
            HnswStorageError::VectorTooLarge { size, max_size } => {
                write!(
                    f,
                    "Vector size {} exceeds maximum allowed size {}",
                    size, max_size
                )
            }
            HnswStorageError::StorageCapacityExceeded => {
                write!(f, "Storage capacity exceeded")
            }
            HnswStorageError::IoError(msg) => {
                write!(f, "I/O error: {}", msg)
            }
            HnswStorageError::DatabaseError(msg) => {
                write!(f, "Database error: {}", msg)
            }
        }
    }
}

impl std::error::Error for HnswStorageError {}

impl fmt::Display for HnswIndexError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            HnswIndexError::VectorDimensionMismatch { expected, actual } => {
                write!(
                    f,
                    "Vector dimension mismatch: expected {}, got {}",
                    expected, actual
                )
            }
            HnswIndexError::DuplicateVectorId(id) => {
                write!(f, "Vector ID {} already exists in index", id)
            }
            HnswIndexError::VectorNotFound(id) => {
                write!(f, "Vector ID {} not found in index", id)
            }
            HnswIndexError::IndexNotInitialized => {
                write!(f, "Index not initialized")
            }
            HnswIndexError::IndexCorrupted(msg) => {
                write!(f, "Index corrupted: {}", msg)
            }
            HnswIndexError::CapacityExceeded => {
                write!(f, "Index capacity exceeded")
            }
            HnswIndexError::InvalidSearchParameters => {
                write!(f, "Invalid search parameters")
            }
            HnswIndexError::NodeNotFound(id) => {
                write!(f, "Node {} not found in layer", id)
            }
            HnswIndexError::InvalidNodeId(id) => {
                write!(f, "Invalid node ID: {}", id)
            }
            HnswIndexError::SelfConnection(id) => {
                write!(f, "Attempt to connect node {} to itself", id)
            }
        }
    }
}

impl std::error::Error for HnswIndexError {}

/// Multi-layer HNSW specific errors
///
/// These errors occur during multi-layer HNSW operations such as layer mapping,
/// level distribution, and cross-layer coordination.
///
/// # Error Variants
///
/// * `LayerMappingConflict` - Conflict in layer ID assignment
/// * `InconsistentMapping` - Bidirectional mapping inconsistency
/// * `InconsistentLayerState` - Layer state corruption detected
/// * `LayerMemoryExceeded` - Memory limit exceeded for layer
/// * `CrossLayerSearchFailed` - Cross-layer search operation failed
/// * `LevelDistributionFailure` - Level distribution algorithm failed
#[derive(Debug, Clone, PartialEq)]
pub enum HnswMultiLayerError {
    /// Conflict in layer ID mapping
    LayerMappingConflict {
        /// Global vector ID
        global_id: u64,
        /// Layer ID where conflict occurred
        layer_id: usize,
        /// Assigned local ID
        local_id: u64,
        /// Expected local ID
        expected: u64,
    },

    /// Inconsistent bidirectional mapping
    InconsistentMapping {
        /// Global vector ID
        global_id: u64,
        /// Layer ID where inconsistency detected
        layer_id: usize,
        /// Local ID in mapping
        local_id: u64,
        /// Mapped global ID that differs
        mapped_global: u64,
    },

    /// Inconsistent layer state
    InconsistentLayerState {
        /// Layer ID with inconsistent state
        layer_id: usize,
        /// Expected number of nodes
        expected_nodes: usize,
        /// Actual number of nodes
        actual_nodes: usize,
    },

    /// Layer memory limit exceeded
    LayerMemoryExceeded {
        /// Layer index
        layer: usize,
        /// Required memory in bytes
        required: usize,
        /// Available memory in bytes
        available: usize,
    },

    /// Cross-layer search failure
    CrossLayerSearchFailed {
        /// Source layer
        from_layer: usize,
        /// Target layer
        to_layer: usize,
    },

    /// Level distribution failure
    LevelDistributionFailure {
        /// Number of attempts made
        attempts: usize,
        /// Maximum level attempted
        max_level: usize,
    },
}

impl fmt::Display for HnswMultiLayerError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            HnswMultiLayerError::LayerMappingConflict {
                global_id,
                layer_id,
                local_id,
                expected,
            } => {
                write!(
                    f,
                    "Layer mapping conflict: global ID {} in layer {} assigned local ID {}, expected {}",
                    global_id, layer_id, local_id, expected
                )
            }
            HnswMultiLayerError::InconsistentMapping {
                global_id,
                layer_id,
                local_id,
                mapped_global,
            } => {
                write!(
                    f,
                    "Inconsistent mapping: global ID {} → layer {} → local ID {}, but local {} → global ID {}",
                    global_id, layer_id, local_id, local_id, mapped_global
                )
            }
            HnswMultiLayerError::InconsistentLayerState {
                layer_id,
                expected_nodes,
                actual_nodes,
            } => {
                write!(
                    f,
                    "Inconsistent layer state: layer {} expects {} nodes but has {}",
                    layer_id, expected_nodes, actual_nodes
                )
            }
            HnswMultiLayerError::LayerMemoryExceeded {
                layer,
                required,
                available,
            } => {
                write!(
                    f,
                    "Layer {} memory limit exceeded: required {} bytes, available {} bytes",
                    layer, required, available
                )
            }
            HnswMultiLayerError::CrossLayerSearchFailed {
                from_layer,
                to_layer,
            } => {
                write!(
                    f,
                    "Cross-layer search failed: from layer {} to layer {}",
                    from_layer, to_layer
                )
            }
            HnswMultiLayerError::LevelDistributionFailure {
                attempts,
                max_level,
            } => {
                write!(
                    f,
                    "Level distribution failed after {} attempts, max level {}",
                    attempts, max_level
                )
            }
        }
    }
}

impl std::error::Error for HnswMultiLayerError {}

/// Combined HNSW error type
///
/// This type encompasses all possible HNSW-related errors for convenience
/// when handling errors from HNSW operations.
///
/// # Examples
///
/// ```rust
/// use sqlitegraph::hnsw::errors::HnswError;
///
/// fn handle_hnsw_result(result: Result<(), HnswError>) {
///     match result {
///         Ok(()) => println!("Operation successful"),
///         Err(e) => println!("HNSW error: {}", e),
///     }
/// }
/// ```
#[derive(Debug, Clone, PartialEq)]
pub enum HnswError {
    /// Configuration-related errors
    Config(HnswConfigError),
    /// Index operation errors
    Index(HnswIndexError),

    /// Storage operation errors
    Storage(HnswStorageError),

    /// Multi-layer operation errors
    MultiLayer(HnswMultiLayerError),
}

impl fmt::Display for HnswError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            HnswError::Config(err) => write!(f, "Configuration error: {}", err),
            HnswError::Index(err) => write!(f, "Index error: {}", err),
            HnswError::Storage(err) => write!(f, "Storage error: {}", err),
            HnswError::MultiLayer(err) => write!(f, "Multi-layer error: {}", err),
        }
    }
}

impl std::error::Error for HnswError {}

impl From<HnswConfigError> for HnswError {
    fn from(err: HnswConfigError) -> Self {
        HnswError::Config(err)
    }
}

impl From<HnswIndexError> for HnswError {
    fn from(err: HnswIndexError) -> Self {
        HnswError::Index(err)
    }
}

impl From<HnswStorageError> for HnswError {
    fn from(err: HnswStorageError) -> Self {
        HnswError::Storage(err)
    }
}

impl From<HnswMultiLayerError> for HnswError {
    fn from(err: HnswMultiLayerError) -> Self {
        HnswError::MultiLayer(err)
    }
}

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

    #[test]
    fn test_config_error_display() {
        assert_eq!(
            HnswConfigError::InvalidDimension.to_string(),
            "Vector dimension must be greater than 0"
        );
        assert_eq!(
            HnswConfigError::InvalidMParameter.to_string(),
            "M parameter (connections per node) must be greater than 0"
        );
        assert_eq!(
            HnswConfigError::InvalidEfConstruction.to_string(),
            "ef_construction must be >= M parameter"
        );
        assert_eq!(
            HnswConfigError::InvalidEfSearch.to_string(),
            "ef_search parameter must be greater than 0"
        );
        assert_eq!(
            HnswConfigError::InvalidMaxLayers.to_string(),
            "Maximum number of layers must be greater than 0"
        );
    }

    #[test]
    fn test_index_error_display() {
        let dim_error = HnswIndexError::VectorDimensionMismatch {
            expected: 768,
            actual: 512,
        };
        assert_eq!(
            dim_error.to_string(),
            "Vector dimension mismatch: expected 768, got 512"
        );

        let dup_error = HnswIndexError::DuplicateVectorId(42);
        assert_eq!(
            dup_error.to_string(),
            "Vector ID 42 already exists in index"
        );

        let not_found = HnswIndexError::VectorNotFound(99);
        assert_eq!(not_found.to_string(), "Vector ID 99 not found in index");

        assert_eq!(
            HnswIndexError::IndexNotInitialized.to_string(),
            "Index not initialized"
        );

        let corrupted = HnswIndexError::IndexCorrupted("layer data corrupted".to_string());
        assert_eq!(
            corrupted.to_string(),
            "Index corrupted: layer data corrupted"
        );

        assert_eq!(
            HnswIndexError::CapacityExceeded.to_string(),
            "Index capacity exceeded"
        );

        assert_eq!(
            HnswIndexError::InvalidSearchParameters.to_string(),
            "Invalid search parameters"
        );
    }

    #[test]
    fn test_hnsw_error_display() {
        let config_err = HnswError::Config(HnswConfigError::InvalidDimension);
        assert!(config_err.to_string().contains("Configuration error"));
        assert!(
            config_err
                .to_string()
                .contains("Vector dimension must be greater than 0")
        );

        let index_err = HnswError::Index(HnswIndexError::VectorNotFound(1));
        assert!(index_err.to_string().contains("Index error"));
        assert!(index_err.to_string().contains("Vector ID 1 not found"));
    }

    #[test]
    fn test_error_conversions() {
        let config_err = HnswConfigError::InvalidMParameter;
        let hnsw_err: HnswError = config_err.into();
        assert!(matches!(
            hnsw_err,
            HnswError::Config(HnswConfigError::InvalidMParameter)
        ));

        let index_err = HnswIndexError::DuplicateVectorId(123);
        let hnsw_err: HnswError = index_err.into();
        assert!(matches!(
            hnsw_err,
            HnswError::Index(HnswIndexError::DuplicateVectorId(123))
        ));
    }

    #[test]
    fn test_error_equality() {
        assert_eq!(
            HnswConfigError::InvalidDimension,
            HnswConfigError::InvalidDimension
        );
        assert_ne!(
            HnswConfigError::InvalidDimension,
            HnswConfigError::InvalidMParameter
        );

        let dim_error1 = HnswIndexError::VectorDimensionMismatch {
            expected: 256,
            actual: 128,
        };
        let dim_error2 = HnswIndexError::VectorDimensionMismatch {
            expected: 256,
            actual: 128,
        };
        assert_eq!(dim_error1, dim_error2);

        assert_ne!(
            HnswIndexError::DuplicateVectorId(1),
            HnswIndexError::DuplicateVectorId(2)
        );
    }

    #[test]
    fn test_error_debug_format() {
        let config_err = HnswConfigError::InvalidEfConstruction;
        assert_eq!(format!("{:?}", config_err), "InvalidEfConstruction");

        let index_err = HnswIndexError::VectorDimensionMismatch {
            expected: 768,
            actual: 384,
        };
        let debug_str = format!("{:?}", index_err);
        assert!(debug_str.contains("VectorDimensionMismatch"));
        assert!(debug_str.contains("768"));
        assert!(debug_str.contains("384"));
    }
}