lcpfs 2026.1.102

LCP File System - A ZFS-inspired copy-on-write filesystem for Rust
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
// Copyright 2025 LunaOS Contributors
// SPDX-License-Identifier: Apache-2.0

//! Vector search type definitions.
//!
//! This module provides core data structures for vector embeddings,
//! HNSW graph nodes, and search results used throughout the vector
//! search subsystem.

use alloc::format;
use alloc::string::String;
use alloc::vec;
use alloc::vec::Vec;

// ═══════════════════════════════════════════════════════════════════════════════
// VECTOR EMBEDDING
// ═══════════════════════════════════════════════════════════════════════════════

/// Quantization type for vector embeddings.
///
/// Different quantization levels trade off between precision and storage size:
/// - `F32`: Full precision, 4 bytes per dimension
/// - `F16`: Half precision, 2 bytes per dimension
/// - `Int8`: 8-bit integers, 1 byte per dimension (requires scale factor)
/// - `Binary`: 1-bit, 1/8 byte per dimension (for Hamming distance)
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
#[derive(Default)]
pub enum QuantizationType {
    /// 32-bit floating point (full precision)
    #[default]
    F32 = 0,
    /// 16-bit floating point (half precision)
    F16 = 1,
    /// 8-bit signed integer (requires scale/offset)
    Int8 = 2,
    /// Binary quantization (1-bit per dimension)
    Binary = 3,
}

impl From<u8> for QuantizationType {
    fn from(value: u8) -> Self {
        match value {
            0 => Self::F32,
            1 => Self::F16,
            2 => Self::Int8,
            3 => Self::Binary,
            _ => Self::F32,
        }
    }
}

/// Vector embedding header stored on disk.
///
/// This structure is followed by the actual embedding data, whose format
/// depends on the `quantization` field. The total size is:
/// - F32: header_size + dimensions * 4 bytes
/// - F16: header_size + dimensions * 2 bytes
/// - Int8: header_size + dimensions bytes + 8 bytes (scale + offset)
/// - Binary: header_size + ceil(dimensions / 8) bytes
///
/// # On-Disk Layout
///
/// ```text
/// +------------------+
/// | object_id (8)    |
/// | model_id (4)     |
/// | dimensions (4)   |
/// | quantization (1) |
/// | reserved (7)     |
/// +------------------+
/// | embedding data   |
/// | (variable)       |
/// +------------------+
/// ```
#[derive(Debug, Clone, Copy)]
#[repr(C)]
pub struct VectorEmbeddingHeader {
    /// Object ID this embedding belongs to.
    pub object_id: u64,
    /// Embedding model identifier hash (e.g., hash of "clip-vit-b32").
    pub model_id: u32,
    /// Number of dimensions in the embedding vector.
    pub dimensions: u32,
    /// Quantization type (see [`QuantizationType`]).
    pub quantization: u8,
    /// Reserved for future use.
    pub reserved: [u8; 7],
}

impl VectorEmbeddingHeader {
    /// Size of the header in bytes.
    pub const SIZE: usize = 24;

    /// Create a new embedding header.
    pub fn new(
        object_id: u64,
        model_id: u32,
        dimensions: u32,
        quantization: QuantizationType,
    ) -> Self {
        Self {
            object_id,
            model_id,
            dimensions,
            quantization: quantization as u8,
            reserved: [0u8; 7],
        }
    }

    /// Get the quantization type.
    pub fn quantization_type(&self) -> QuantizationType {
        QuantizationType::from(self.quantization)
    }

    /// Calculate the size of the embedding data in bytes (excluding header).
    pub fn data_size(&self) -> usize {
        match self.quantization_type() {
            QuantizationType::F32 => self.dimensions as usize * 4,
            QuantizationType::F16 => self.dimensions as usize * 2,
            QuantizationType::Int8 => self.dimensions as usize + 8, // +8 for scale/offset
            QuantizationType::Binary => (self.dimensions as usize).div_ceil(8),
        }
    }

    /// Calculate the total size including header and data.
    pub fn total_size(&self) -> usize {
        Self::SIZE + self.data_size()
    }

    /// Serialize to bytes.
    pub fn to_bytes(&self) -> [u8; Self::SIZE] {
        let mut buf = [0u8; Self::SIZE];
        buf[0..8].copy_from_slice(&self.object_id.to_le_bytes());
        buf[8..12].copy_from_slice(&self.model_id.to_le_bytes());
        buf[12..16].copy_from_slice(&self.dimensions.to_le_bytes());
        buf[16] = self.quantization;
        // reserved bytes are already zero
        buf
    }

    /// Deserialize from bytes.
    pub fn from_bytes(buf: &[u8; Self::SIZE]) -> Self {
        Self {
            object_id: u64::from_le_bytes([
                buf[0], buf[1], buf[2], buf[3], buf[4], buf[5], buf[6], buf[7],
            ]),
            model_id: u32::from_le_bytes([buf[8], buf[9], buf[10], buf[11]]),
            dimensions: u32::from_le_bytes([buf[12], buf[13], buf[14], buf[15]]),
            quantization: buf[16],
            reserved: [
                buf[17], buf[18], buf[19], buf[20], buf[21], buf[22], buf[23],
            ],
        }
    }
}

/// Complete vector embedding with data.
#[derive(Debug, Clone)]
pub struct VectorEmbedding {
    /// Header containing metadata.
    pub header: VectorEmbeddingHeader,
    /// The embedding vector data (always stored as f32 in memory).
    pub data: Vec<f32>,
}

impl VectorEmbedding {
    /// Create a new vector embedding.
    pub fn new(object_id: u64, model_id: u32, data: Vec<f32>) -> Self {
        let dimensions = data.len() as u32;
        Self {
            header: VectorEmbeddingHeader::new(
                object_id,
                model_id,
                dimensions,
                QuantizationType::F32,
            ),
            data,
        }
    }

    /// Create with specific quantization type (data is still f32, quantization is for storage).
    pub fn with_quantization(
        object_id: u64,
        model_id: u32,
        data: Vec<f32>,
        quantization: QuantizationType,
    ) -> Self {
        let dimensions = data.len() as u32;
        Self {
            header: VectorEmbeddingHeader::new(object_id, model_id, dimensions, quantization),
            data,
        }
    }

    /// Get the object ID.
    pub fn object_id(&self) -> u64 {
        self.header.object_id
    }

    /// Get the embedding dimensions.
    pub fn dimensions(&self) -> usize {
        self.header.dimensions as usize
    }

    /// Get a reference to the embedding data.
    pub fn as_slice(&self) -> &[f32] {
        &self.data
    }

    /// Compute the L2 norm of the embedding.
    pub fn l2_norm(&self) -> f32 {
        let sum: f32 = self.data.iter().map(|x| x * x).sum();
        libm::sqrtf(sum)
    }

    /// Normalize the embedding to unit length.
    pub fn normalize(&mut self) {
        let norm = self.l2_norm();
        if norm > 1e-10 {
            for x in &mut self.data {
                *x /= norm;
            }
        }
    }

    /// Create a normalized copy.
    pub fn normalized(&self) -> Self {
        let mut copy = self.clone();
        copy.normalize();
        copy
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// HNSW NODE
// ═══════════════════════════════════════════════════════════════════════════════

/// Maximum neighbors per layer in HNSW graph.
pub const HNSW_MAX_NEIGHBORS: usize = 32;

/// HNSW graph node representing connections at a single layer.
///
/// Each node stores its connections to neighboring nodes at one layer
/// of the HNSW graph. Nodes at higher layers have fewer neighbors
/// (typically M for layer 0, M/2 for higher layers).
///
/// # On-Disk Layout
///
/// ```text
/// +--------------------+
/// | object_id (8)      |
/// | layer (1)          |
/// | neighbor_count (1) |
/// | reserved (6)       |
/// | neighbors (32 * 8) |
/// +--------------------+
/// Total: 272 bytes
/// ```
#[derive(Debug, Clone, Copy)]
#[repr(C)]
pub struct HnswNode {
    /// Object ID this node represents.
    pub object_id: u64,
    /// Layer in the HNSW graph (0 = bottom/base layer).
    pub layer: u8,
    /// Number of valid neighbors (0 to HNSW_MAX_NEIGHBORS).
    pub neighbor_count: u8,
    /// Reserved for future use.
    pub reserved: [u8; 6],
    /// Neighbor object IDs (only first `neighbor_count` are valid).
    pub neighbors: [u64; HNSW_MAX_NEIGHBORS],
}

impl HnswNode {
    /// Size of an HNSW node in bytes.
    pub const SIZE: usize = 8 + 1 + 1 + 6 + (HNSW_MAX_NEIGHBORS * 8);

    /// Create a new empty HNSW node.
    pub fn new(object_id: u64, layer: u8) -> Self {
        Self {
            object_id,
            layer,
            neighbor_count: 0,
            reserved: [0u8; 6],
            neighbors: [0u64; HNSW_MAX_NEIGHBORS],
        }
    }

    /// Add a neighbor to this node.
    ///
    /// Returns `true` if the neighbor was added, `false` if the node is full.
    pub fn add_neighbor(&mut self, neighbor_id: u64) -> bool {
        if (self.neighbor_count as usize) < HNSW_MAX_NEIGHBORS {
            self.neighbors[self.neighbor_count as usize] = neighbor_id;
            self.neighbor_count += 1;
            true
        } else {
            false
        }
    }

    /// Remove a neighbor from this node.
    ///
    /// Returns `true` if the neighbor was found and removed.
    pub fn remove_neighbor(&mut self, neighbor_id: u64) -> bool {
        for i in 0..self.neighbor_count as usize {
            if self.neighbors[i] == neighbor_id {
                // Shift remaining neighbors down
                for j in i..self.neighbor_count as usize - 1 {
                    self.neighbors[j] = self.neighbors[j + 1];
                }
                self.neighbor_count -= 1;
                self.neighbors[self.neighbor_count as usize] = 0;
                return true;
            }
        }
        false
    }

    /// Check if this node has a specific neighbor.
    pub fn has_neighbor(&self, neighbor_id: u64) -> bool {
        for i in 0..self.neighbor_count as usize {
            if self.neighbors[i] == neighbor_id {
                return true;
            }
        }
        false
    }

    /// Get the valid neighbors as a slice.
    pub fn get_neighbors(&self) -> &[u64] {
        &self.neighbors[..self.neighbor_count as usize]
    }

    /// Set neighbors from a slice (overwrites existing).
    pub fn set_neighbors(&mut self, neighbors: &[u64]) {
        let count = neighbors.len().min(HNSW_MAX_NEIGHBORS);
        self.neighbors[..count].copy_from_slice(&neighbors[..count]);
        self.neighbor_count = count as u8;
    }

    /// Serialize to bytes.
    pub fn to_bytes(&self) -> [u8; Self::SIZE] {
        let mut buf = [0u8; Self::SIZE];
        buf[0..8].copy_from_slice(&self.object_id.to_le_bytes());
        buf[8] = self.layer;
        buf[9] = self.neighbor_count;
        // reserved bytes are already zero
        for (i, &neighbor) in self.neighbors.iter().enumerate() {
            let offset = 16 + i * 8;
            buf[offset..offset + 8].copy_from_slice(&neighbor.to_le_bytes());
        }
        buf
    }

    /// Deserialize from bytes.
    pub fn from_bytes(buf: &[u8; Self::SIZE]) -> Self {
        let object_id = u64::from_le_bytes([
            buf[0], buf[1], buf[2], buf[3], buf[4], buf[5], buf[6], buf[7],
        ]);
        let layer = buf[8];
        let neighbor_count = buf[9];
        let reserved = [buf[10], buf[11], buf[12], buf[13], buf[14], buf[15]];

        let mut neighbors = [0u64; HNSW_MAX_NEIGHBORS];
        for (i, neighbor) in neighbors.iter_mut().enumerate() {
            let offset = 16 + i * 8;
            *neighbor = u64::from_le_bytes([
                buf[offset],
                buf[offset + 1],
                buf[offset + 2],
                buf[offset + 3],
                buf[offset + 4],
                buf[offset + 5],
                buf[offset + 6],
                buf[offset + 7],
            ]);
        }

        Self {
            object_id,
            layer,
            neighbor_count,
            reserved,
            neighbors,
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// SEARCH RESULTS
// ═══════════════════════════════════════════════════════════════════════════════

/// Result from a vector similarity search.
#[derive(Debug, Clone)]
pub struct VectorSearchResult {
    /// Object ID of the matching file/object.
    pub object_id: u64,
    /// File path (if available).
    pub path: Option<String>,
    /// Similarity score (higher is more similar, 0.0-1.0 for cosine).
    pub score: f32,
    /// Raw distance from query vector (interpretation depends on metric).
    pub distance: f32,
}

impl VectorSearchResult {
    /// Create a new search result.
    pub fn new(object_id: u64, score: f32, distance: f32) -> Self {
        Self {
            object_id,
            path: None,
            score,
            distance,
        }
    }

    /// Create with path.
    pub fn with_path(object_id: u64, path: String, score: f32, distance: f32) -> Self {
        Self {
            object_id,
            path: Some(path),
            score,
            distance,
        }
    }
}

impl PartialEq for VectorSearchResult {
    fn eq(&self, other: &Self) -> bool {
        self.object_id == other.object_id
    }
}

impl Eq for VectorSearchResult {}

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

impl Ord for VectorSearchResult {
    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
        // Higher score = better, so reverse comparison for max-heap behavior
        other
            .score
            .partial_cmp(&self.score)
            .unwrap_or(core::cmp::Ordering::Equal)
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// DISTANCE METRICS
// ═══════════════════════════════════════════════════════════════════════════════

/// Distance metric for vector similarity.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum DistanceMetric {
    /// Cosine similarity (1 - cosine distance).
    #[default]
    Cosine,
    /// Euclidean (L2) distance.
    Euclidean,
    /// Dot product (inner product).
    DotProduct,
    /// Manhattan (L1) distance.
    Manhattan,
    /// Hamming distance (for binary vectors).
    Hamming,
}

impl DistanceMetric {
    /// Convert a string to a distance metric.
    pub fn from_str(s: &str) -> Option<Self> {
        match s.to_lowercase().as_str() {
            "cosine" | "cos" => Some(Self::Cosine),
            "euclidean" | "l2" | "euclid" => Some(Self::Euclidean),
            "dot" | "dotproduct" | "inner" => Some(Self::DotProduct),
            "manhattan" | "l1" => Some(Self::Manhattan),
            "hamming" => Some(Self::Hamming),
            _ => None,
        }
    }

    /// Get the name of this metric.
    pub fn name(&self) -> &'static str {
        match self {
            Self::Cosine => "cosine",
            Self::Euclidean => "euclidean",
            Self::DotProduct => "dot",
            Self::Manhattan => "manhattan",
            Self::Hamming => "hamming",
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// INDEX TYPES
// ═══════════════════════════════════════════════════════════════════════════════

/// Type of vector index.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum IndexType {
    /// Hierarchical Navigable Small World graph (default).
    #[default]
    Hnsw,
    /// Inverted File index (for very large datasets).
    Ivf,
    /// Flat/brute-force (exact search, no approximation).
    Flat,
}

impl IndexType {
    /// Convert from string.
    pub fn from_str(s: &str) -> Option<Self> {
        match s.to_lowercase().as_str() {
            "hnsw" => Some(Self::Hnsw),
            "ivf" => Some(Self::Ivf),
            "flat" | "brute" => Some(Self::Flat),
            _ => None,
        }
    }

    /// Get the name of this index type.
    pub fn name(&self) -> &'static str {
        match self {
            Self::Hnsw => "hnsw",
            Self::Ivf => "ivf",
            Self::Flat => "flat",
        }
    }
}

/// Index parameters for building a vector index.
#[derive(Debug, Clone)]
pub struct IndexParams {
    /// Index type.
    pub index_type: IndexType,
    /// Distance metric.
    pub metric: DistanceMetric,
    /// HNSW M parameter (max neighbors per node at layer 0).
    pub hnsw_m: usize,
    /// HNSW ef_construction (beam width during build).
    pub hnsw_ef_construction: usize,
    /// HNSW ef_search (beam width during search).
    pub hnsw_ef_search: usize,
    /// IVF number of clusters.
    pub ivf_nlist: usize,
    /// IVF number of clusters to probe during search.
    pub ivf_nprobe: usize,
}

impl Default for IndexParams {
    fn default() -> Self {
        Self {
            index_type: IndexType::Hnsw,
            metric: DistanceMetric::Cosine,
            hnsw_m: 16,
            hnsw_ef_construction: 200,
            hnsw_ef_search: 50,
            ivf_nlist: 100,
            ivf_nprobe: 10,
        }
    }
}

/// Metadata about a vector index stored in dataset properties.
#[derive(Debug, Clone)]
pub struct VectorIndexMeta {
    /// Index type name.
    pub index_type: IndexType,
    /// Number of vectors indexed.
    pub vector_count: u64,
    /// Embedding dimensions.
    pub dimensions: u32,
    /// Distance metric.
    pub distance_metric: DistanceMetric,
    /// HNSW M parameter.
    pub hnsw_m: u16,
    /// HNSW ef_construction parameter.
    pub hnsw_ef_construction: u16,
    /// Maximum layer in the HNSW graph.
    pub max_layer: u8,
    /// Entry point object ID.
    pub entry_point: u64,
}

impl Default for VectorIndexMeta {
    fn default() -> Self {
        Self {
            index_type: IndexType::Hnsw,
            vector_count: 0,
            dimensions: 0,
            distance_metric: DistanceMetric::Cosine,
            hnsw_m: 16,
            hnsw_ef_construction: 200,
            max_layer: 0,
            entry_point: 0,
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// SEARCH FILTER
// ═══════════════════════════════════════════════════════════════════════════════

/// Filter for constraining vector search results.
#[derive(Debug, Clone, Default)]
pub struct SearchFilter {
    /// File extension filter (e.g., ["jpg", "png"]).
    pub extensions: Option<Vec<String>>,
    /// Minimum file size in bytes.
    pub min_size: Option<u64>,
    /// Maximum file size in bytes.
    pub max_size: Option<u64>,
    /// Modified after this timestamp (Unix seconds).
    pub modified_after: Option<u64>,
    /// Modified before this timestamp (Unix seconds).
    pub modified_before: Option<u64>,
    /// Path must start with this prefix.
    pub path_prefix: Option<String>,
    /// Minimum similarity score (0.0-1.0).
    pub min_score: Option<f32>,
}

impl SearchFilter {
    /// Create a new empty filter.
    pub fn new() -> Self {
        Self::default()
    }

    /// Filter by file extensions.
    pub fn with_extensions(mut self, extensions: Vec<String>) -> Self {
        self.extensions = Some(extensions);
        self
    }

    /// Filter by minimum size.
    pub fn with_min_size(mut self, size: u64) -> Self {
        self.min_size = Some(size);
        self
    }

    /// Filter by maximum size.
    pub fn with_max_size(mut self, size: u64) -> Self {
        self.max_size = Some(size);
        self
    }

    /// Filter by modification time.
    pub fn with_modified_after(mut self, timestamp: u64) -> Self {
        self.modified_after = Some(timestamp);
        self
    }

    /// Filter by path prefix.
    pub fn with_path_prefix(mut self, prefix: String) -> Self {
        self.path_prefix = Some(prefix);
        self
    }

    /// Filter by minimum score.
    pub fn with_min_score(mut self, score: f32) -> Self {
        self.min_score = Some(score);
        self
    }

    /// Check if a result passes this filter (basic check without file metadata).
    pub fn matches_basic(&self, result: &VectorSearchResult) -> bool {
        // Check minimum score
        if let Some(min_score) = self.min_score {
            if result.score < min_score {
                return false;
            }
        }

        // Check path prefix
        if let (Some(prefix), Some(path)) = (&self.path_prefix, &result.path) {
            if !path.starts_with(prefix) {
                return false;
            }
        }

        // Check extension
        if let (Some(extensions), Some(path)) = (&self.extensions, &result.path) {
            let has_valid_ext = extensions.iter().any(|ext| {
                path.to_lowercase()
                    .ends_with(&format!(".{}", ext.to_lowercase()))
            });
            if !has_valid_ext {
                return false;
            }
        }

        true
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// ERRORS
// ═══════════════════════════════════════════════════════════════════════════════

/// Errors that can occur during vector operations.
#[derive(Debug, Clone)]
pub enum VectorError {
    /// Embedding dimensions mismatch.
    DimensionMismatch {
        /// Expected dimensions.
        expected: usize,
        /// Actual dimensions.
        actual: usize,
    },
    /// Vector index not found.
    IndexNotFound,
    /// Object not found in index.
    ObjectNotFound(u64),
    /// Index is empty.
    EmptyIndex,
    /// Invalid quantization type.
    InvalidQuantization(u8),
    /// Serialization error.
    SerializationError,
    /// IO error.
    IoError(alloc::string::String),
    /// Index is corrupted.
    CorruptedIndex,
    /// Dataset not found.
    DatasetNotFound(String),
    /// Feature not supported.
    NotSupported(String),
}

impl core::fmt::Display for VectorError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            Self::DimensionMismatch { expected, actual } => {
                write!(
                    f,
                    "dimension mismatch: expected {}, got {}",
                    expected, actual
                )
            }
            Self::IndexNotFound => write!(f, "vector index not found"),
            Self::ObjectNotFound(id) => write!(f, "object {} not found in index", id),
            Self::EmptyIndex => write!(f, "vector index is empty"),
            Self::InvalidQuantization(q) => write!(f, "invalid quantization type: {}", q),
            Self::SerializationError => write!(f, "serialization error"),
            Self::IoError(msg) => write!(f, "IO error: {}", msg),
            Self::CorruptedIndex => write!(f, "corrupted vector index"),
            Self::DatasetNotFound(name) => write!(f, "dataset not found: {}", name),
            Self::NotSupported(feature) => write!(f, "feature not supported: {}", feature),
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// TESTS
// ═══════════════════════════════════════════════════════════════════════════════

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

    #[test]
    fn test_vector_embedding_header_serialization() {
        let header = VectorEmbeddingHeader::new(12345, 42, 512, QuantizationType::F32);
        let bytes = header.to_bytes();
        let restored = VectorEmbeddingHeader::from_bytes(&bytes);

        assert_eq!(restored.object_id, 12345);
        assert_eq!(restored.model_id, 42);
        assert_eq!(restored.dimensions, 512);
        assert_eq!(restored.quantization_type(), QuantizationType::F32);
    }

    #[test]
    fn test_vector_embedding_data_size() {
        let header_f32 = VectorEmbeddingHeader::new(1, 1, 512, QuantizationType::F32);
        assert_eq!(header_f32.data_size(), 512 * 4);

        let header_f16 = VectorEmbeddingHeader::new(1, 1, 512, QuantizationType::F16);
        assert_eq!(header_f16.data_size(), 512 * 2);

        let header_int8 = VectorEmbeddingHeader::new(1, 1, 512, QuantizationType::Int8);
        assert_eq!(header_int8.data_size(), 512 + 8);

        let header_binary = VectorEmbeddingHeader::new(1, 1, 512, QuantizationType::Binary);
        assert_eq!(header_binary.data_size(), 64);
    }

    #[test]
    fn test_hnsw_node_neighbors() {
        let mut node = HnswNode::new(1, 0);
        assert_eq!(node.neighbor_count, 0);

        assert!(node.add_neighbor(2));
        assert!(node.add_neighbor(3));
        assert!(node.add_neighbor(4));

        assert_eq!(node.neighbor_count, 3);
        assert!(node.has_neighbor(2));
        assert!(node.has_neighbor(3));
        assert!(!node.has_neighbor(5));

        assert!(node.remove_neighbor(3));
        assert_eq!(node.neighbor_count, 2);
        assert!(!node.has_neighbor(3));

        let neighbors = node.get_neighbors();
        assert_eq!(neighbors.len(), 2);
        assert_eq!(neighbors[0], 2);
        assert_eq!(neighbors[1], 4);
    }

    #[test]
    fn test_hnsw_node_serialization() {
        let mut node = HnswNode::new(12345, 2);
        node.add_neighbor(100);
        node.add_neighbor(200);
        node.add_neighbor(300);

        let bytes = node.to_bytes();
        let restored = HnswNode::from_bytes(&bytes);

        assert_eq!(restored.object_id, 12345);
        assert_eq!(restored.layer, 2);
        assert_eq!(restored.neighbor_count, 3);
        assert_eq!(restored.neighbors[0], 100);
        assert_eq!(restored.neighbors[1], 200);
        assert_eq!(restored.neighbors[2], 300);
    }

    #[test]
    fn test_vector_embedding_normalize() {
        let mut embedding = VectorEmbedding::new(1, 1, vec![3.0, 4.0]);
        embedding.normalize();

        let norm = embedding.l2_norm();
        assert!((norm - 1.0).abs() < 1e-6);
        assert!((embedding.data[0] - 0.6).abs() < 1e-6);
        assert!((embedding.data[1] - 0.8).abs() < 1e-6);
    }

    #[test]
    fn test_search_result_ordering() {
        let mut results = [
            VectorSearchResult::new(1, 0.5, 0.5),
            VectorSearchResult::new(2, 0.9, 0.1),
            VectorSearchResult::new(3, 0.7, 0.3),
        ];

        results.sort();

        // Higher score should come first
        assert_eq!(results[0].object_id, 2);
        assert_eq!(results[1].object_id, 3);
        assert_eq!(results[2].object_id, 1);
    }

    #[test]
    fn test_search_filter() {
        let filter = SearchFilter::new()
            .with_min_score(0.5)
            .with_extensions(vec!["jpg".into(), "png".into()]);

        let good = VectorSearchResult::with_path(1, "/photos/cat.jpg".into(), 0.8, 0.2);
        let low_score = VectorSearchResult::with_path(2, "/photos/dog.jpg".into(), 0.3, 0.7);
        let wrong_ext = VectorSearchResult::with_path(3, "/docs/readme.txt".into(), 0.9, 0.1);

        assert!(filter.matches_basic(&good));
        assert!(!filter.matches_basic(&low_score));
        assert!(!filter.matches_basic(&wrong_ext));
    }

    #[test]
    fn test_distance_metric_from_str() {
        assert_eq!(
            DistanceMetric::from_str("cosine"),
            Some(DistanceMetric::Cosine)
        );
        assert_eq!(
            DistanceMetric::from_str("L2"),
            Some(DistanceMetric::Euclidean)
        );
        assert_eq!(
            DistanceMetric::from_str("dot"),
            Some(DistanceMetric::DotProduct)
        );
        assert_eq!(DistanceMetric::from_str("invalid"), None);
    }
}