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