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