Skip to main content

ares_vector/
index.rs

1//! HNSW index wrapper.
2//!
3//! This module wraps the hnsw_rs library to provide a simpler interface
4//! and additional functionality like ID mapping.
5
6use crate::config::HnswConfig;
7use crate::distance::DistanceMetric;
8use crate::error::{Error, Result};
9use crate::types::{SearchResult, VectorId, VectorMetadata};
10use anndists::dist::distances::{DistCosine, DistDot, DistL1, DistL2};
11use hnsw_rs::hnsw::Hnsw;
12use parking_lot::RwLock;
13use serde::{Deserialize, Serialize};
14use std::collections::HashMap;
15use std::fmt;
16use std::sync::atomic::{AtomicUsize, Ordering};
17use tracing::{debug, trace};
18
19type IndexResult<T> = std::result::Result<T, IndexConfigError>;
20
21// =============================================================================
22// Pure PostgreSQL index helpers (R46)
23// =============================================================================
24
25/// Minimum HNSW `m` (max edges per node) for [`IndexConfig`].
26pub const MIN_HNSW_M: u16 = 4;
27/// Maximum HNSW `m` for [`IndexConfig`].
28pub const MAX_HNSW_M: u16 = 100;
29/// Minimum HNSW `ef_construction` for [`IndexConfig`].
30pub const MIN_HNSW_EF_CONSTRUCTION: u32 = 10;
31/// Maximum HNSW `ef_construction` for [`IndexConfig`].
32pub const MAX_HNSW_EF_CONSTRUCTION: u32 = 1000;
33/// Default HNSW `m` used in [`IndexConfig`].
34pub const DEFAULT_INDEX_M: u16 = 16;
35/// Default HNSW `ef_construction` used in [`IndexConfig`].
36pub const DEFAULT_INDEX_EF_CONSTRUCTION: u32 = 64;
37/// Default vector dimensions in [`IndexConfig`].
38pub const DEFAULT_INDEX_DIMENSIONS: usize = 384;
39
40/// PostgreSQL / pgvector index access method.
41#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
42#[serde(rename_all = "snake_case")]
43pub enum IndexType {
44    /// HNSW approximate nearest-neighbor index.
45    #[default]
46    Hnsw,
47    /// IVFFlat inverted-file index.
48    Ivfflat,
49    /// Flat / sequential scan (pgvector extension, no ANN index).
50    Flat,
51}
52
53/// Validation failures for [`IndexConfig`] and SQL builders.
54#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
55pub enum IndexConfigError {
56    /// HNSW `m` is outside [`MIN_HNSW_M`]..=[`MAX_HNSW_M`].
57    #[error("invalid M: {0} (must be {MIN_HNSW_M}-{MAX_HNSW_M})")]
58    InvalidM(u16),
59    /// HNSW `ef_construction` is outside allowed bounds.
60    #[error("invalid ef_construction: {0} (must be {MIN_HNSW_EF_CONSTRUCTION}-{MAX_HNSW_EF_CONSTRUCTION})")]
61    InvalidEfConstruction(u32),
62    /// Index type cannot be used for the requested operation.
63    #[error("unsupported index type: {0:?}")]
64    UnsupportedIndexType(IndexType),
65    /// Vector dimensionality must be greater than zero.
66    #[error("dimensions must be greater than zero")]
67    InvalidDimensions,
68    /// Distance metric has no pgvector operator mapping.
69    #[error("unsupported distance metric for pgvector: {0}")]
70    UnsupportedDistance(DistanceMetric),
71    /// Table or column name is not a valid SQL identifier.
72    #[error("invalid SQL identifier: {0}")]
73    InvalidIdentifier(String),
74}
75
76/// Serializable pgvector index configuration.
77#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
78pub struct IndexConfig {
79    /// Embedding dimensionality.
80    #[serde(default = "default_index_dimensions")]
81    pub dimensions: usize,
82    /// Index access method.
83    #[serde(default)]
84    pub index_type: IndexType,
85    /// Distance metric / opclass selection.
86    #[serde(default)]
87    pub distance: DistanceMetric,
88    /// HNSW `m` parameter.
89    #[serde(default = "default_index_m")]
90    pub m: u16,
91    /// HNSW `ef_construction` parameter.
92    #[serde(default = "default_index_ef_construction")]
93    pub ef_construction: u32,
94}
95
96impl Default for IndexConfig {
97    fn default() -> Self {
98        Self {
99            dimensions: default_index_dimensions(),
100            index_type: IndexType::default(),
101            distance: DistanceMetric::default(),
102            m: default_index_m(),
103            ef_construction: default_index_ef_construction(),
104        }
105    }
106}
107
108impl fmt::Display for IndexConfig {
109    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
110        write!(
111            f,
112            "{} index ({}-dim, {}, m={}, ef={})",
113            index_type_string(self.index_type),
114            self.dimensions,
115            self.distance,
116            self.m,
117            self.ef_construction
118        )
119    }
120}
121
122/// Default index dimensions for serde.
123pub fn default_index_dimensions() -> usize {
124    DEFAULT_INDEX_DIMENSIONS
125}
126
127/// Default HNSW `m` for serde.
128pub fn default_index_m() -> u16 {
129    DEFAULT_INDEX_M
130}
131
132/// Default HNSW `ef_construction` for serde.
133pub fn default_index_ef_construction() -> u32 {
134    DEFAULT_INDEX_EF_CONSTRUCTION
135}
136
137/// PostgreSQL index or extension keyword for an [`IndexType`].
138pub fn index_type_string(index_type: IndexType) -> &'static str {
139    match index_type {
140        IndexType::Hnsw => "hnsw",
141        IndexType::Ivfflat => "ivfflat",
142        IndexType::Flat => "vector",
143    }
144}
145
146/// pgvector distance operator for ORDER BY / WHERE clauses.
147pub fn distance_operator(metric: DistanceMetric) -> IndexResult<&'static str> {
148    crate::distance::distance_operator(metric).ok_or(IndexConfigError::UnsupportedDistance(metric))
149}
150
151/// pgvector opclass suffix used when creating indexes.
152pub fn distance_ops_class(metric: DistanceMetric) -> IndexResult<&'static str> {
153    match metric {
154        DistanceMetric::Cosine => Ok("vector_cosine_ops"),
155        DistanceMetric::Euclidean => Ok("vector_l2_ops"),
156        DistanceMetric::DotProduct => Ok("vector_ip_ops"),
157        DistanceMetric::Manhattan => Err(IndexConfigError::UnsupportedDistance(metric)),
158    }
159}
160
161/// Format HNSW `WITH` clause parameters for PostgreSQL DDL.
162pub fn hnsw_param_string(m: u16, ef_construction: u32) -> String {
163    format!("m = {m}, ef_construction = {ef_construction}")
164}
165
166/// Return the PostgreSQL access method or error for types that do not use one.
167pub fn index_access_method(index_type: IndexType) -> IndexResult<&'static str> {
168    match index_type {
169        IndexType::Hnsw => Ok("hnsw"),
170        IndexType::Ivfflat => Ok("ivfflat"),
171        IndexType::Flat => Err(IndexConfigError::UnsupportedIndexType(IndexType::Flat)),
172    }
173}
174
175fn quote_sql_identifier(raw: &str) -> IndexResult<String> {
176    let name = raw.trim();
177    if name.is_empty() {
178        return Err(IndexConfigError::InvalidIdentifier(
179            "empty identifier".into(),
180        ));
181    }
182    if name.chars().next().is_some_and(|c| c.is_ascii_digit()) {
183        return Err(IndexConfigError::InvalidIdentifier(name.into()));
184    }
185    if !name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
186        return Err(IndexConfigError::InvalidIdentifier(name.into()));
187    }
188    Ok(format!("\"{}\"", name.replace('"', "\"\"")))
189}
190
191fn index_name_suffix(index_type: IndexType) -> &'static str {
192    match index_type {
193        IndexType::Hnsw => "hnsw",
194        IndexType::Ivfflat => "ivfflat",
195        IndexType::Flat => "flat",
196    }
197}
198
199/// Validate dimensions, distance mapping, and HNSW tuning parameters.
200pub fn validate_index_config(config: &IndexConfig) -> IndexResult<()> {
201    if config.dimensions == 0 {
202        return Err(IndexConfigError::InvalidDimensions);
203    }
204    distance_ops_class(config.distance)?;
205    if config.index_type == IndexType::Hnsw {
206        if config.m < MIN_HNSW_M || config.m > MAX_HNSW_M {
207            return Err(IndexConfigError::InvalidM(config.m));
208        }
209        if config.ef_construction < MIN_HNSW_EF_CONSTRUCTION
210            || config.ef_construction > MAX_HNSW_EF_CONSTRUCTION
211        {
212            return Err(IndexConfigError::InvalidEfConstruction(
213                config.ef_construction,
214            ));
215        }
216    }
217    Ok(())
218}
219
220/// Build `CREATE INDEX` SQL for a pgvector embedding column.
221pub fn build_create_index_sql(
222    table: &str,
223    column: &str,
224    config: &IndexConfig,
225) -> IndexResult<String> {
226    validate_index_config(config)?;
227    if config.index_type == IndexType::Flat {
228        return Ok(String::new());
229    }
230
231    let table_id = quote_sql_identifier(table)?;
232    let column_id = quote_sql_identifier(column)?;
233    let ops = distance_ops_class(config.distance)?;
234    let suffix = index_name_suffix(config.index_type);
235    let index_name = format!("{}_{}_{}_idx", table.trim(), column.trim(), suffix);
236    let index_name_id = quote_sql_identifier(&index_name)?;
237    let method = index_type_string(config.index_type);
238
239    let stmt = match config.index_type {
240        IndexType::Hnsw => {
241            let with_clause = hnsw_param_string(config.m, config.ef_construction);
242            format!(
243                "CREATE INDEX IF NOT EXISTS {index_name_id} ON {table_id} \
244                 USING {method} ({column_id} {ops}) WITH ({with_clause})"
245            )
246        }
247        IndexType::Ivfflat => format!(
248            "CREATE INDEX IF NOT EXISTS {index_name_id} ON {table_id} \
249             USING {method} ({column_id} {ops}) WITH (lists = 100)"
250        ),
251        IndexType::Flat => String::new(),
252    };
253    Ok(stmt)
254}
255
256/// Thread-safe HNSW index with ID mapping.
257pub struct HnswIndex {
258    /// The underlying HNSW index (boxed for type erasure).
259    inner: RwLock<IndexInner>,
260    /// Mapping from string IDs to internal numeric IDs.
261    id_to_internal: RwLock<HashMap<VectorId, usize>>,
262    /// Mapping from internal numeric IDs to string IDs.
263    internal_to_id: RwLock<HashMap<usize, VectorId>>,
264    /// Stored vectors for retrieval.
265    vectors: RwLock<HashMap<usize, Vec<f32>>>,
266    /// Stored metadata.
267    metadata: RwLock<HashMap<usize, VectorMetadata>>,
268    /// Counter for generating internal IDs.
269    next_internal_id: AtomicUsize,
270    /// Vector dimensions.
271    dimensions: usize,
272    /// Distance metric.
273    metric: DistanceMetric,
274    /// HNSW configuration.
275    config: HnswConfig,
276}
277
278/// Type-erased inner index.
279enum IndexInner {
280    Cosine(Hnsw<'static, f32, DistCosine>),
281    Euclidean(Hnsw<'static, f32, DistL2>),
282    DotProduct(Hnsw<'static, f32, DistDot>),
283    Manhattan(Hnsw<'static, f32, DistL1>),
284}
285
286impl HnswIndex {
287    /// Create a new HNSW index.
288    ///
289    /// # Arguments
290    ///
291    /// * `dimensions` - Dimensionality of vectors.
292    /// * `metric` - Distance metric to use.
293    /// * `config` - HNSW configuration.
294    pub fn new(dimensions: usize, metric: DistanceMetric, config: HnswConfig) -> Result<Self> {
295        if dimensions == 0 {
296            return Err(Error::InvalidVector("Dimensions must be > 0".to_string()));
297        }
298
299        let max_elements = 1_000_000; // Initial capacity
300        let max_layer = 16;
301
302        let inner = match metric {
303            DistanceMetric::Cosine => {
304                let hnsw = Hnsw::new(
305                    config.m,
306                    max_elements,
307                    max_layer,
308                    config.ef_construction,
309                    DistCosine {},
310                );
311                IndexInner::Cosine(hnsw)
312            }
313            DistanceMetric::Euclidean => {
314                let hnsw = Hnsw::new(
315                    config.m,
316                    max_elements,
317                    max_layer,
318                    config.ef_construction,
319                    DistL2 {},
320                );
321                IndexInner::Euclidean(hnsw)
322            }
323            DistanceMetric::DotProduct => {
324                let hnsw = Hnsw::new(
325                    config.m,
326                    max_elements,
327                    max_layer,
328                    config.ef_construction,
329                    DistDot {},
330                );
331                IndexInner::DotProduct(hnsw)
332            }
333            DistanceMetric::Manhattan => {
334                let hnsw = Hnsw::new(
335                    config.m,
336                    max_elements,
337                    max_layer,
338                    config.ef_construction,
339                    DistL1 {},
340                );
341                IndexInner::Manhattan(hnsw)
342            }
343        };
344
345        Ok(Self {
346            inner: RwLock::new(inner),
347            id_to_internal: RwLock::new(HashMap::new()),
348            internal_to_id: RwLock::new(HashMap::new()),
349            vectors: RwLock::new(HashMap::new()),
350            metadata: RwLock::new(HashMap::new()),
351            next_internal_id: AtomicUsize::new(0),
352            dimensions,
353            metric,
354            config,
355        })
356    }
357
358    /// Get the vector dimensions.
359    pub fn dimensions(&self) -> usize {
360        self.dimensions
361    }
362
363    /// Get the distance metric.
364    pub fn metric(&self) -> DistanceMetric {
365        self.metric
366    }
367
368    /// Get the number of vectors in the index.
369    pub fn len(&self) -> usize {
370        self.id_to_internal.read().len()
371    }
372
373    /// Check if the index is empty.
374    pub fn is_empty(&self) -> bool {
375        self.len() == 0
376    }
377
378    /// Check if a vector exists.
379    pub fn contains(&self, id: &str) -> bool {
380        self.id_to_internal.read().contains_key(id)
381    }
382
383    /// Insert a vector into the index.
384    ///
385    /// If a vector with the same ID exists, it will be updated.
386    pub fn insert(&self, id: &str, vector: &[f32], meta: Option<VectorMetadata>) -> Result<()> {
387        // Validate dimensions
388        if vector.len() != self.dimensions {
389            return Err(Error::DimensionMismatch {
390                expected: self.dimensions,
391                actual: vector.len(),
392            });
393        }
394
395        // Validate vector values
396        if vector.iter().any(|v| v.is_nan() || v.is_infinite()) {
397            return Err(Error::InvalidVector(
398                "Vector contains NaN or Inf".to_string(),
399            ));
400        }
401
402        // Check if this is an update
403        let internal_id = {
404            let id_map = self.id_to_internal.read();
405            if let Some(&existing_id) = id_map.get(id) {
406                // Update: reuse internal ID
407                existing_id
408            } else {
409                // Insert: generate new internal ID
410                self.next_internal_id.fetch_add(1, Ordering::SeqCst)
411            }
412        };
413
414        // Store mappings
415        {
416            let mut id_to_internal = self.id_to_internal.write();
417            let mut internal_to_id = self.internal_to_id.write();
418            id_to_internal.insert(id.to_string(), internal_id);
419            internal_to_id.insert(internal_id, id.to_string());
420        }
421
422        // Store vector
423        {
424            let mut vectors = self.vectors.write();
425            vectors.insert(internal_id, vector.to_vec());
426        }
427
428        // Store metadata
429        if let Some(m) = meta {
430            let mut metadata = self.metadata.write();
431            metadata.insert(internal_id, m);
432        }
433
434        // Insert into HNSW index
435        let inner = self.inner.write();
436        match &*inner {
437            IndexInner::Cosine(hnsw) => {
438                hnsw.insert((vector, internal_id));
439            }
440            IndexInner::Euclidean(hnsw) => {
441                hnsw.insert((vector, internal_id));
442            }
443            IndexInner::DotProduct(hnsw) => {
444                hnsw.insert((vector, internal_id));
445            }
446            IndexInner::Manhattan(hnsw) => {
447                hnsw.insert((vector, internal_id));
448            }
449        }
450
451        trace!(id, internal_id, "Inserted vector");
452        Ok(())
453    }
454
455    /// Insert multiple vectors in batch.
456    ///
457    /// More efficient than calling `insert` repeatedly.
458    pub fn insert_batch<'a, I>(&self, vectors: I) -> Result<usize>
459    where
460        I: IntoIterator<Item = (&'a str, &'a [f32], Option<VectorMetadata>)>,
461    {
462        let mut count = 0;
463        let mut batch_data: Vec<(Vec<f32>, usize)> = Vec::new();
464
465        for (id, vector, meta) in vectors {
466            // Validate
467            if vector.len() != self.dimensions {
468                return Err(Error::DimensionMismatch {
469                    expected: self.dimensions,
470                    actual: vector.len(),
471                });
472            }
473
474            if vector.iter().any(|v| v.is_nan() || v.is_infinite()) {
475                return Err(Error::InvalidVector(format!(
476                    "Vector '{}' contains NaN or Inf",
477                    id
478                )));
479            }
480
481            let internal_id = {
482                let id_map = self.id_to_internal.read();
483                id_map
484                    .get(id)
485                    .copied()
486                    .unwrap_or_else(|| self.next_internal_id.fetch_add(1, Ordering::SeqCst))
487            };
488
489            // Store mappings
490            {
491                let mut id_to_internal = self.id_to_internal.write();
492                let mut internal_to_id = self.internal_to_id.write();
493                id_to_internal.insert(id.to_string(), internal_id);
494                internal_to_id.insert(internal_id, id.to_string());
495            }
496
497            // Store vector and metadata
498            {
499                let mut vectors = self.vectors.write();
500                vectors.insert(internal_id, vector.to_vec());
501            }
502
503            if let Some(m) = meta {
504                let mut metadata = self.metadata.write();
505                metadata.insert(internal_id, m);
506            }
507
508            batch_data.push((vector.to_vec(), internal_id));
509            count += 1;
510        }
511
512        // Batch insert into HNSW
513        if !batch_data.is_empty() {
514            let inner = self.inner.write();
515            let refs: Vec<(&Vec<f32>, usize)> = batch_data.iter().map(|(v, id)| (v, *id)).collect();
516
517            match &*inner {
518                IndexInner::Cosine(hnsw) => {
519                    if self.config.parallel_construction {
520                        hnsw.parallel_insert(&refs);
521                    } else {
522                        for (v, id) in refs {
523                            hnsw.insert((v, id));
524                        }
525                    }
526                }
527                IndexInner::Euclidean(hnsw) => {
528                    if self.config.parallel_construction {
529                        hnsw.parallel_insert(&refs);
530                    } else {
531                        for (v, id) in refs {
532                            hnsw.insert((v, id));
533                        }
534                    }
535                }
536                IndexInner::DotProduct(hnsw) => {
537                    if self.config.parallel_construction {
538                        hnsw.parallel_insert(&refs);
539                    } else {
540                        for (v, id) in refs {
541                            hnsw.insert((v, id));
542                        }
543                    }
544                }
545                IndexInner::Manhattan(hnsw) => {
546                    if self.config.parallel_construction {
547                        hnsw.parallel_insert(&refs);
548                    } else {
549                        for (v, id) in refs {
550                            hnsw.insert((v, id));
551                        }
552                    }
553                }
554            }
555        }
556
557        debug!(count, "Batch inserted vectors");
558        Ok(count)
559    }
560
561    /// Delete a vector from the index.
562    ///
563    /// Note: HNSW doesn't support true deletion. The vector is marked as
564    /// deleted but still occupies space until compaction.
565    pub fn delete(&self, id: &str) -> Result<bool> {
566        let internal_id = {
567            let mut id_to_internal = self.id_to_internal.write();
568            let Some(internal_id) = id_to_internal.remove(id) else {
569                return Ok(false);
570            };
571            internal_id
572        };
573
574        // Remove from mappings
575        {
576            let mut internal_to_id = self.internal_to_id.write();
577            internal_to_id.remove(&internal_id);
578        }
579
580        // Remove stored data
581        {
582            let mut vectors = self.vectors.write();
583            vectors.remove(&internal_id);
584        }
585
586        {
587            let mut metadata = self.metadata.write();
588            metadata.remove(&internal_id);
589        }
590
591        // Note: HNSW doesn't have a delete method, so the point remains
592        // in the index but won't be returned in results since we removed
593        // the ID mapping. A compaction/rebuild would remove it fully.
594
595        trace!(id, internal_id, "Deleted vector");
596        Ok(true)
597    }
598
599    /// Delete multiple vectors.
600    pub fn delete_batch(&self, ids: &[&str]) -> Result<usize> {
601        let mut count = 0;
602        for id in ids {
603            if self.delete(id)? {
604                count += 1;
605            }
606        }
607        Ok(count)
608    }
609
610    /// Search for similar vectors.
611    pub fn search(&self, query: &[f32], limit: usize) -> Result<Vec<SearchResult>> {
612        if query.len() != self.dimensions {
613            return Err(Error::DimensionMismatch {
614                expected: self.dimensions,
615                actual: query.len(),
616            });
617        }
618
619        let ef_search = std::cmp::max(self.config.ef_search, limit);
620        let inner = self.inner.read();
621
622        let neighbors = match &*inner {
623            IndexInner::Cosine(hnsw) => hnsw.search(query, limit, ef_search),
624            IndexInner::Euclidean(hnsw) => hnsw.search(query, limit, ef_search),
625            IndexInner::DotProduct(hnsw) => hnsw.search(query, limit, ef_search),
626            IndexInner::Manhattan(hnsw) => hnsw.search(query, limit, ef_search),
627        };
628
629        let internal_to_id = self.internal_to_id.read();
630        let metadata = self.metadata.read();
631
632        let results: Vec<SearchResult> = neighbors
633            .into_iter()
634            .filter_map(|neighbor| {
635                let internal_id = neighbor.d_id;
636                let id = internal_to_id.get(&internal_id)?;
637
638                // Convert distance to similarity score
639                let score = self.distance_to_score(neighbor.distance);
640
641                Some(SearchResult {
642                    id: id.clone(),
643                    score,
644                    metadata: metadata.get(&internal_id).cloned(),
645                })
646            })
647            .collect();
648
649        Ok(results)
650    }
651
652    /// Search with a minimum score threshold.
653    pub fn search_with_threshold(
654        &self,
655        query: &[f32],
656        limit: usize,
657        min_score: f32,
658    ) -> Result<Vec<SearchResult>> {
659        let results = self.search(query, limit)?;
660        Ok(results
661            .into_iter()
662            .filter(|r| r.score >= min_score)
663            .collect())
664    }
665
666    /// Get a vector by ID.
667    pub fn get(&self, id: &str) -> Option<(Vec<f32>, Option<VectorMetadata>)> {
668        let internal_id = *self.id_to_internal.read().get(id)?;
669        let vector = self.vectors.read().get(&internal_id)?.clone();
670        let meta = self.metadata.read().get(&internal_id).cloned();
671        Some((vector, meta))
672    }
673
674    /// Update a vector.
675    pub fn update(&self, id: &str, vector: &[f32], meta: Option<VectorMetadata>) -> Result<()> {
676        if !self.contains(id) {
677            return Err(Error::VectorNotFound(id.to_string()));
678        }
679        self.insert(id, vector, meta)
680    }
681
682    /// Compact the index by rebuilding it.
683    ///
684    /// This removes deleted vectors and optimizes the graph structure.
685    pub fn compact(&self) -> Result<()> {
686        // Collect all valid vectors
687        let id_to_internal = self.id_to_internal.read();
688        let vectors = self.vectors.read();
689        let metadata = self.metadata.read();
690
691        let valid_data: Vec<_> = id_to_internal
692            .iter()
693            .filter_map(|(id, &internal_id)| {
694                let vector = vectors.get(&internal_id)?;
695                let meta = metadata.get(&internal_id).cloned();
696                Some((id.clone(), vector.clone(), meta))
697            })
698            .collect();
699
700        drop(id_to_internal);
701        drop(vectors);
702        drop(metadata);
703
704        // Clear existing data
705        self.id_to_internal.write().clear();
706        self.internal_to_id.write().clear();
707        self.vectors.write().clear();
708        self.metadata.write().clear();
709        self.next_internal_id.store(0, Ordering::SeqCst);
710
711        // Rebuild index
712        let max_elements = valid_data.len().max(1_000_000);
713        let max_layer = 16;
714
715        let new_inner = match self.metric {
716            DistanceMetric::Cosine => IndexInner::Cosine(Hnsw::new(
717                self.config.m,
718                max_elements,
719                max_layer,
720                self.config.ef_construction,
721                DistCosine {},
722            )),
723            DistanceMetric::Euclidean => IndexInner::Euclidean(Hnsw::new(
724                self.config.m,
725                max_elements,
726                max_layer,
727                self.config.ef_construction,
728                DistL2 {},
729            )),
730            DistanceMetric::DotProduct => IndexInner::DotProduct(Hnsw::new(
731                self.config.m,
732                max_elements,
733                max_layer,
734                self.config.ef_construction,
735                DistDot {},
736            )),
737            DistanceMetric::Manhattan => IndexInner::Manhattan(Hnsw::new(
738                self.config.m,
739                max_elements,
740                max_layer,
741                self.config.ef_construction,
742                DistL1 {},
743            )),
744        };
745
746        *self.inner.write() = new_inner;
747
748        // Re-insert all vectors
749        let batch: Vec<_> = valid_data
750            .iter()
751            .map(|(id, v, m)| (id.as_str(), v.as_slice(), m.clone()))
752            .collect();
753
754        self.insert_batch(batch)?;
755
756        debug!(count = valid_data.len(), "Compacted index");
757        Ok(())
758    }
759
760    /// Estimate memory usage in bytes.
761    pub fn memory_usage(&self) -> usize {
762        let vectors = self.vectors.read();
763        let metadata = self.metadata.read();
764
765        // Vector storage
766        let vector_bytes: usize = vectors.values().map(|v| v.len() * 4).sum();
767
768        // ID mappings (rough estimate)
769        let id_bytes: usize = self.id_to_internal.read().keys().map(|s| s.len()).sum();
770
771        // Metadata (rough estimate)
772        let meta_bytes: usize = metadata.len() * 100; // Rough estimate
773
774        // HNSW graph (rough estimate: ~M * 4 bytes per connection per vector)
775        let graph_bytes = vectors.len() * self.config.m * 4 * 16; // Approximate
776
777        vector_bytes + id_bytes + meta_bytes + graph_bytes
778    }
779
780    /// Export all vectors for persistence.
781    ///
782    /// Returns an iterator over (id, vector, metadata) tuples.
783    pub fn export_all(&self) -> Vec<(String, Vec<f32>, Option<VectorMetadata>)> {
784        let id_to_internal = self.id_to_internal.read();
785        let vectors = self.vectors.read();
786        let metadata = self.metadata.read();
787
788        id_to_internal
789            .iter()
790            .filter_map(|(id, &internal_id)| {
791                let vector = vectors.get(&internal_id)?.clone();
792                let meta = metadata.get(&internal_id).cloned();
793                Some((id.clone(), vector, meta))
794            })
795            .collect()
796    }
797
798    /// Convert HNSW distance to a similarity score (higher = more similar).
799    fn distance_to_score(&self, distance: f32) -> f32 {
800        match self.metric {
801            DistanceMetric::Cosine => {
802                // HNSW uses 1 - cos_sim as distance, so score = 1 - distance
803                1.0 - distance
804            }
805            DistanceMetric::DotProduct => {
806                // Higher dot product = more similar, HNSW may negate it
807                -distance
808            }
809            DistanceMetric::Euclidean | DistanceMetric::Manhattan => {
810                // Transform distance to similarity: 1 / (1 + dist)
811                1.0 / (1.0 + distance)
812            }
813        }
814    }
815}
816
817#[cfg(test)]
818mod tests {
819    use super::*;
820    use crate::types::MetadataValue;
821
822    fn default_config() -> HnswConfig {
823        HnswConfig::default()
824    }
825
826    #[test]
827    fn test_insert_and_search() {
828        let index = HnswIndex::new(3, DistanceMetric::Cosine, default_config()).unwrap();
829
830        index.insert("vec1", &[1.0, 0.0, 0.0], None).unwrap();
831        index.insert("vec2", &[0.0, 1.0, 0.0], None).unwrap();
832        index.insert("vec3", &[0.9, 0.1, 0.0], None).unwrap();
833
834        assert_eq!(index.len(), 3);
835
836        let results = index.search(&[1.0, 0.0, 0.0], 10).unwrap();
837        assert!(!results.is_empty());
838        assert_eq!(results[0].id, "vec1");
839    }
840
841    #[test]
842    fn test_dimension_mismatch() {
843        let index = HnswIndex::new(3, DistanceMetric::Cosine, default_config()).unwrap();
844
845        let result = index.insert("vec1", &[1.0, 0.0], None);
846        assert!(matches!(result, Err(Error::DimensionMismatch { .. })));
847    }
848
849    #[test]
850    fn test_delete() {
851        let index = HnswIndex::new(3, DistanceMetric::Cosine, default_config()).unwrap();
852
853        index.insert("vec1", &[1.0, 0.0, 0.0], None).unwrap();
854        assert_eq!(index.len(), 1);
855
856        let deleted = index.delete("vec1").unwrap();
857        assert!(deleted);
858        assert_eq!(index.len(), 0);
859
860        let deleted_again = index.delete("vec1").unwrap();
861        assert!(!deleted_again);
862    }
863
864    #[test]
865    fn test_get() {
866        let index = HnswIndex::new(3, DistanceMetric::Cosine, default_config()).unwrap();
867
868        let meta =
869            VectorMetadata::from_pairs([("key", MetadataValue::String("value".to_string()))]);
870        index.insert("vec1", &[1.0, 2.0, 3.0], Some(meta)).unwrap();
871
872        let (vector, metadata) = index.get("vec1").unwrap();
873        assert_eq!(vector, vec![1.0, 2.0, 3.0]);
874        assert!(metadata.is_some());
875    }
876
877    #[test]
878    fn test_contains() {
879        let index = HnswIndex::new(3, DistanceMetric::Cosine, default_config()).unwrap();
880
881        assert!(!index.contains("vec1"));
882        index.insert("vec1", &[1.0, 0.0, 0.0], None).unwrap();
883        assert!(index.contains("vec1"));
884    }
885
886    #[test]
887    fn test_new_zero_dimensions() {
888        let result = HnswIndex::new(0, DistanceMetric::Cosine, default_config());
889        assert!(matches!(result, Err(Error::InvalidVector(_))));
890    }
891
892    #[test]
893    fn test_new_defaults() {
894        let index = HnswIndex::new(4, DistanceMetric::Euclidean, HnswConfig::default()).unwrap();
895        assert_eq!(index.dimensions(), 4);
896        assert_eq!(index.metric(), DistanceMetric::Euclidean);
897        assert!(index.is_empty());
898        assert_eq!(index.len(), 0);
899    }
900
901    #[test]
902    fn test_invalid_vector_nan() {
903        let index = HnswIndex::new(2, DistanceMetric::Cosine, default_config()).unwrap();
904        let result = index.insert("bad", &[f32::NAN, 0.0], None);
905        assert!(matches!(result, Err(Error::InvalidVector(_))));
906    }
907
908    #[test]
909    fn test_all_distance_metrics_search() {
910        for metric in [
911            DistanceMetric::Cosine,
912            DistanceMetric::Euclidean,
913            DistanceMetric::DotProduct,
914            DistanceMetric::Manhattan,
915        ] {
916            let index = HnswIndex::new(3, metric, default_config()).unwrap();
917            index.insert("a", &[1.0, 0.0, 0.0], None).unwrap();
918            index.insert("b", &[0.0, 1.0, 0.0], None).unwrap();
919            let results = index.search(&[1.0, 0.0, 0.0], 5).unwrap();
920            assert!(!results.is_empty());
921            assert_eq!(results[0].id, "a");
922        }
923    }
924
925    #[test]
926    fn test_insert_batch_and_export() {
927        let index = HnswIndex::new(2, DistanceMetric::Cosine, default_config()).unwrap();
928        let v1 = [1.0f32, 0.0];
929        let v2 = [0.0f32, 1.0];
930        let count = index
931            .insert_batch([("v1", &v1[..], None), ("v2", &v2[..], None)])
932            .unwrap();
933        assert_eq!(count, 2);
934        assert_eq!(index.len(), 2);
935
936        let exported = index.export_all();
937        assert_eq!(exported.len(), 2);
938        let ids: Vec<_> = exported.into_iter().map(|(id, _, _)| id).collect();
939        assert!(ids.contains(&"v1".to_string()));
940        assert!(ids.contains(&"v2".to_string()));
941    }
942
943    #[test]
944    fn test_update_and_vector_not_found() {
945        let index = HnswIndex::new(2, DistanceMetric::Cosine, default_config()).unwrap();
946        index.insert("v1", &[1.0, 0.0], None).unwrap();
947
948        index.update("v1", &[0.5, 0.5], None).unwrap();
949        let (vector, _) = index.get("v1").unwrap();
950        assert_eq!(vector, vec![0.5, 0.5]);
951
952        let err = index.update("missing", &[1.0, 0.0], None).unwrap_err();
953        assert!(matches!(err, Error::VectorNotFound(_)));
954    }
955
956    #[test]
957    fn test_get_missing_returns_none() {
958        let index = HnswIndex::new(2, DistanceMetric::Cosine, default_config()).unwrap();
959        assert!(index.get("nope").is_none());
960    }
961
962    #[test]
963    fn test_search_dimension_mismatch() {
964        let index = HnswIndex::new(3, DistanceMetric::Cosine, default_config()).unwrap();
965        let err = index.search(&[1.0, 0.0], 5).unwrap_err();
966        assert!(matches!(err, Error::DimensionMismatch { .. }));
967    }
968
969    #[test]
970    fn test_search_with_threshold() {
971        let index = HnswIndex::new(3, DistanceMetric::Cosine, default_config()).unwrap();
972        index.insert("near", &[1.0, 0.0, 0.0], None).unwrap();
973        index.insert("far", &[0.0, 1.0, 0.0], None).unwrap();
974
975        let results = index
976            .search_with_threshold(&[1.0, 0.0, 0.0], 10, 0.99)
977            .unwrap();
978        assert_eq!(results.len(), 1);
979        assert_eq!(results[0].id, "near");
980    }
981
982    #[test]
983    fn test_delete_batch_and_compact() {
984        let index = HnswIndex::new(3, DistanceMetric::Cosine, default_config()).unwrap();
985        index.insert("a", &[1.0, 0.0, 0.0], None).unwrap();
986        index.insert("b", &[0.0, 1.0, 0.0], None).unwrap();
987        assert_eq!(index.delete_batch(&["a", "missing"]).unwrap(), 1);
988        index.compact().unwrap();
989        assert_eq!(index.len(), 1);
990        assert!(!index.contains("a"));
991        assert!(index.contains("b"));
992    }
993
994    #[test]
995    fn test_memory_usage_positive() {
996        let index = HnswIndex::new(8, DistanceMetric::Cosine, default_config()).unwrap();
997        index.insert("v", &[1.0; 8], None).unwrap();
998        assert!(index.memory_usage() > 0);
999    }
1000    // =====================================================================
1001    // Pure PostgreSQL index helpers (R46)
1002    // =====================================================================
1003
1004    fn sample_index_config(index_type: IndexType, distance: DistanceMetric) -> IndexConfig {
1005        IndexConfig {
1006            dimensions: 384,
1007            index_type,
1008            distance,
1009            m: DEFAULT_INDEX_M,
1010            ef_construction: DEFAULT_INDEX_EF_CONSTRUCTION,
1011        }
1012    }
1013
1014    #[test]
1015    fn index_type_hnsw_serde_roundtrip() {
1016        let json = serde_json::to_string(&IndexType::Hnsw).expect("serialize");
1017        assert_eq!(json, "\"hnsw\"");
1018        let back: IndexType = serde_json::from_str(&json).expect("deserialize");
1019        assert_eq!(back, IndexType::Hnsw);
1020    }
1021
1022    #[test]
1023    fn index_type_ivfflat_serde_roundtrip() {
1024        let json = serde_json::to_string(&IndexType::Ivfflat).expect("serialize");
1025        assert_eq!(json, "\"ivfflat\"");
1026        let back: IndexType = serde_json::from_str(&json).expect("deserialize");
1027        assert_eq!(back, IndexType::Ivfflat);
1028    }
1029
1030    #[test]
1031    fn index_type_flat_serde_roundtrip() {
1032        let json = serde_json::to_string(&IndexType::Flat).expect("serialize");
1033        assert_eq!(json, "\"flat\"");
1034        let back: IndexType = serde_json::from_str(&json).expect("deserialize");
1035        assert_eq!(back, IndexType::Flat);
1036    }
1037
1038    #[test]
1039    fn index_config_serde_roundtrip_all_index_types_and_distances() {
1040        for index_type in [IndexType::Hnsw, IndexType::Ivfflat, IndexType::Flat] {
1041            for distance in [
1042                DistanceMetric::Cosine,
1043                DistanceMetric::Euclidean,
1044                DistanceMetric::DotProduct,
1045            ] {
1046                let config = sample_index_config(index_type, distance);
1047                let json = serde_json::to_string(&config).expect("serialize");
1048                let restored: IndexConfig = serde_json::from_str(&json).expect("deserialize");
1049                assert_eq!(restored, config);
1050            }
1051        }
1052    }
1053
1054    #[test]
1055    fn index_config_deserializes_with_defaults() {
1056        let json = r#"{"dimensions":1536}"#;
1057        let config: IndexConfig = serde_json::from_str(json).expect("deserialize");
1058        assert_eq!(config.dimensions, 1536);
1059        assert_eq!(config.index_type, IndexType::Hnsw);
1060        assert_eq!(config.distance, DistanceMetric::Cosine);
1061        assert_eq!(config.m, DEFAULT_INDEX_M);
1062        assert_eq!(config.ef_construction, DEFAULT_INDEX_EF_CONSTRUCTION);
1063    }
1064
1065    #[test]
1066    fn hnsw_param_string_formats_m_and_ef_construction() {
1067        assert_eq!(hnsw_param_string(24, 200), "m = 24, ef_construction = 200");
1068    }
1069
1070    #[test]
1071    fn hnsw_param_string_uses_default_constants() {
1072        let defaults = IndexConfig::default();
1073        assert_eq!(
1074            hnsw_param_string(defaults.m, defaults.ef_construction),
1075            "m = 16, ef_construction = 64"
1076        );
1077    }
1078
1079    #[test]
1080    fn validate_index_config_accepts_defaults() {
1081        assert!(validate_index_config(&IndexConfig::default()).is_ok());
1082    }
1083
1084    #[test]
1085    fn validate_index_config_rejects_zero_dimensions() {
1086        let config = IndexConfig {
1087            dimensions: 0,
1088            ..IndexConfig::default()
1089        };
1090        assert!(matches!(
1091            validate_index_config(&config),
1092            Err(IndexConfigError::InvalidDimensions)
1093        ));
1094    }
1095
1096    #[test]
1097    fn validate_index_config_rejects_m_below_min() {
1098        let config = IndexConfig {
1099            m: MIN_HNSW_M - 1,
1100            ..IndexConfig::default()
1101        };
1102        assert!(matches!(
1103            validate_index_config(&config),
1104            Err(IndexConfigError::InvalidM(3))
1105        ));
1106    }
1107
1108    #[test]
1109    fn validate_index_config_rejects_m_above_max() {
1110        let config = IndexConfig {
1111            m: MAX_HNSW_M + 1,
1112            ..IndexConfig::default()
1113        };
1114        assert!(matches!(
1115            validate_index_config(&config),
1116            Err(IndexConfigError::InvalidM(101))
1117        ));
1118    }
1119
1120    #[test]
1121    fn validate_index_config_rejects_ef_below_min() {
1122        let config = IndexConfig {
1123            ef_construction: MIN_HNSW_EF_CONSTRUCTION - 1,
1124            ..IndexConfig::default()
1125        };
1126        assert!(matches!(
1127            validate_index_config(&config),
1128            Err(IndexConfigError::InvalidEfConstruction(9))
1129        ));
1130    }
1131
1132    #[test]
1133    fn validate_index_config_rejects_ef_above_max() {
1134        let config = IndexConfig {
1135            ef_construction: MAX_HNSW_EF_CONSTRUCTION + 1,
1136            ..IndexConfig::default()
1137        };
1138        assert!(matches!(
1139            validate_index_config(&config),
1140            Err(IndexConfigError::InvalidEfConstruction(1001))
1141        ));
1142    }
1143
1144    #[test]
1145    fn validate_index_config_accepts_boundary_m_and_ef() {
1146        let config = IndexConfig {
1147            m: MIN_HNSW_M,
1148            ef_construction: MAX_HNSW_EF_CONSTRUCTION,
1149            ..IndexConfig::default()
1150        };
1151        assert!(validate_index_config(&config).is_ok());
1152    }
1153
1154    #[test]
1155    fn validate_index_config_skips_hnsw_bounds_for_ivfflat() {
1156        let config = IndexConfig {
1157            index_type: IndexType::Ivfflat,
1158            m: 1,
1159            ef_construction: 1,
1160            ..IndexConfig::default()
1161        };
1162        assert!(validate_index_config(&config).is_ok());
1163    }
1164
1165    #[test]
1166    fn build_create_index_sql_quotes_table_and_column() {
1167        let config = sample_index_config(IndexType::Hnsw, DistanceMetric::Cosine);
1168        let sql = build_create_index_sql("documents", "embedding", &config).expect("sql");
1169        assert!(sql.contains("ON \"documents\""));
1170        assert!(sql.contains("(\"embedding\" vector_cosine_ops)"));
1171    }
1172
1173    #[test]
1174    fn build_create_index_sql_includes_hnsw_suffix_and_defaults() {
1175        let config = IndexConfig::default();
1176        let sql = build_create_index_sql("docs", "vec", &config).expect("sql");
1177        assert!(sql.contains("docs_vec_hnsw_idx"));
1178        assert!(sql.contains("USING hnsw"));
1179        assert!(sql.contains("m = 16, ef_construction = 64"));
1180    }
1181
1182    #[test]
1183    fn build_create_index_sql_ivfflat_suffix_and_lists() {
1184        let config = sample_index_config(IndexType::Ivfflat, DistanceMetric::Euclidean);
1185        let sql = build_create_index_sql("docs", "vec", &config).expect("sql");
1186        assert!(sql.contains("docs_vec_ivfflat_idx"));
1187        assert!(sql.contains("USING ivfflat"));
1188        assert!(sql.contains("lists = 100"));
1189        assert!(sql.contains("vector_l2_ops"));
1190    }
1191
1192    #[test]
1193    fn build_create_index_sql_flat_returns_empty() {
1194        let config = sample_index_config(IndexType::Flat, DistanceMetric::DotProduct);
1195        let sql = build_create_index_sql("docs", "vec", &config).expect("sql");
1196        assert!(sql.is_empty());
1197    }
1198
1199    #[test]
1200    fn build_create_index_sql_rejects_invalid_table_name() {
1201        let config = IndexConfig::default();
1202        assert!(build_create_index_sql("bad-name", "embedding", &config).is_err());
1203    }
1204
1205    #[test]
1206    fn index_type_string_maps_postgres_names() {
1207        assert_eq!(index_type_string(IndexType::Hnsw), "hnsw");
1208        assert_eq!(index_type_string(IndexType::Ivfflat), "ivfflat");
1209        assert_eq!(index_type_string(IndexType::Flat), "vector");
1210    }
1211
1212    #[test]
1213    fn distance_operator_maps_pgvector_operators() {
1214        assert_eq!(
1215            distance_operator(DistanceMetric::Euclidean).expect("l2"),
1216            "<->"
1217        );
1218        assert_eq!(
1219            distance_operator(DistanceMetric::DotProduct).expect("dot"),
1220            "<#>"
1221        );
1222        assert_eq!(
1223            distance_operator(DistanceMetric::Cosine).expect("cosine"),
1224            "<=>"
1225        );
1226    }
1227
1228    #[test]
1229    fn distance_operator_rejects_manhattan() {
1230        assert!(matches!(
1231            distance_operator(DistanceMetric::Manhattan),
1232            Err(IndexConfigError::UnsupportedDistance(
1233                DistanceMetric::Manhattan
1234            ))
1235        ));
1236    }
1237
1238    #[test]
1239    fn index_access_method_errors_for_flat() {
1240        assert!(matches!(
1241            index_access_method(IndexType::Flat),
1242            Err(IndexConfigError::UnsupportedIndexType(IndexType::Flat))
1243        ));
1244    }
1245
1246    #[test]
1247    fn index_config_error_invalid_m_display() {
1248        let msg = IndexConfigError::InvalidM(2).to_string();
1249        assert!(msg.contains("invalid M"));
1250        assert!(msg.contains('2'));
1251    }
1252
1253    #[test]
1254    fn index_config_error_invalid_ef_display() {
1255        let msg = IndexConfigError::InvalidEfConstruction(5).to_string();
1256        assert!(msg.contains("ef_construction"));
1257        assert!(msg.contains('5'));
1258    }
1259
1260    #[test]
1261    fn index_config_error_unsupported_index_type_display() {
1262        let msg = IndexConfigError::UnsupportedIndexType(IndexType::Flat).to_string();
1263        assert!(msg.contains("unsupported index type"));
1264    }
1265
1266    #[test]
1267    fn index_config_debug_clone_and_display_preview() {
1268        let config = IndexConfig::default();
1269        let cloned = config.clone();
1270        assert_eq!(config, cloned);
1271        let dbg = format!("{config:?}");
1272        assert!(dbg.contains("dimensions"));
1273        let preview = config.to_string();
1274        assert!(preview.contains("hnsw index"));
1275        assert!(preview.contains("384-dim"));
1276    }
1277
1278    #[test]
1279    fn index_type_debug_and_clone() {
1280        #[allow(clippy::clone_on_copy)] // the test asserts Clone stays implemented
1281        let ty = IndexType::Ivfflat;
1282        let cloned = ty;
1283        assert_eq!(ty, cloned);
1284        assert!(format!("{ty:?}").contains("Ivfflat"));
1285    }
1286
1287    #[test]
1288    fn index_config_error_debug_and_clone() {
1289        let err = IndexConfigError::InvalidM(7);
1290        let cloned = err.clone();
1291        assert_eq!(err, cloned);
1292        assert!(format!("{err:?}").contains("InvalidM"));
1293    }
1294}