leann-core 0.2.3

LEANN is a revolutionary vector database that democratizes personal AI. Transform your laptop into a powerful RAG system that can index and search through millions of documents while using 97% less storage than traditional solutions without accuracy loss.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
//! Backend abstraction for LEANN index engines.
//!
//! Dispatches build, read, and search operations to the appropriate backend
//! (currently HNSW only) via enum matching. Zero runtime overhead — the
//! compiler devirtualizes each match arm.

use std::collections::HashMap;
use std::io::Cursor;
use std::path::Path;

use anyhow::Result;
use ndarray::Array2;
use tracing::info;

use crate::hnsw::build::build_hnsw_with_threads;
use crate::hnsw::csr::convert_to_csr;
use crate::hnsw::graph::{HnswConfig, HnswGraph, VectorStorage};
use crate::hnsw::io::{read_hnsw_index, write_hnsw_compact, write_hnsw_standard};
use crate::hnsw::search::{SearchParams, search_hnsw, search_hnsw_recompute};
use crate::index::DistanceMetric;

// Re-export search types so callers don't need to reach into hnsw::search.
pub use crate::hnsw::search::PruningStrategy;

// ---------------------------------------------------------------------------
// BackendConfig
// ---------------------------------------------------------------------------

/// Backend-specific build configuration.
///
/// Each variant holds all parameters needed to build an index with that backend.
#[derive(Debug)]
pub enum BackendConfig {
    Hnsw {
        m: usize,
        ef_construction: usize,
        distance_metric: DistanceMetric,
        is_compact: bool,
        is_recompute: bool,
        num_threads: usize,
        seed: Option<u64>,
    },
    // Future: Ivf { nlist: usize, distance_metric: DistanceMetric },
}

impl BackendConfig {
    /// Default HNSW configuration (matches `HnswConfig::default()`).
    pub fn hnsw_default() -> Self {
        let defaults = HnswConfig::default();
        Self::Hnsw {
            m: defaults.m,
            ef_construction: defaults.ef_construction,
            distance_metric: defaults.distance_metric,
            is_compact: defaults.is_compact,
            is_recompute: defaults.is_recompute,
            num_threads: std::thread::available_parallelism()
                .map(|n| n.get())
                .unwrap_or(1),
            seed: defaults.seed,
        }
    }

    /// Create a default config for the given backend name.
    pub fn from_name(name: &str) -> Result<Self> {
        match name {
            "hnsw" => Ok(Self::hnsw_default()),
            other => anyhow::bail!(
                "Backend '{}' is not supported. Available backends: hnsw",
                other
            ),
        }
    }

    /// Backend name string (for serialization into `IndexMeta`).
    pub fn name(&self) -> &str {
        match self {
            Self::Hnsw { .. } => "hnsw",
        }
    }

    /// Distance metric for this backend configuration.
    pub fn distance_metric(&self) -> DistanceMetric {
        match self {
            Self::Hnsw {
                distance_metric, ..
            } => *distance_metric,
        }
    }

    /// Set the distance metric.
    pub fn set_distance_metric(&mut self, metric: DistanceMetric) {
        match self {
            Self::Hnsw {
                distance_metric, ..
            } => *distance_metric = metric,
        }
    }

    /// Set M parameter (HNSW only).
    pub fn set_m(&mut self, val: usize) {
        match self {
            Self::Hnsw { m, .. } => *m = val,
        }
    }

    /// Set efConstruction parameter (HNSW only).
    pub fn set_ef_construction(&mut self, val: usize) {
        match self {
            Self::Hnsw {
                ef_construction, ..
            } => *ef_construction = val,
        }
    }

    /// Set compact mode (HNSW only).
    pub fn set_compact(&mut self, val: bool) {
        match self {
            Self::Hnsw { is_compact, .. } => *is_compact = val,
        }
    }

    /// Set recompute mode (HNSW only).
    pub fn set_recompute(&mut self, val: bool) {
        match self {
            Self::Hnsw { is_recompute, .. } => *is_recompute = val,
        }
    }

    /// Set number of build threads (HNSW only).
    pub fn set_num_threads(&mut self, val: usize) {
        match self {
            Self::Hnsw { num_threads, .. } => *num_threads = val.max(1),
        }
    }

    /// Convert to `backend_kwargs` map for `IndexMeta` serialization.
    pub fn to_backend_kwargs(&self) -> HashMap<String, serde_json::Value> {
        match self {
            Self::Hnsw {
                m,
                ef_construction,
                distance_metric,
                is_compact,
                is_recompute,
                ..
            } => {
                let mut kwargs = HashMap::new();
                kwargs.insert("M".to_string(), serde_json::json!(m));
                kwargs.insert(
                    "efConstruction".to_string(),
                    serde_json::json!(ef_construction),
                );
                kwargs.insert(
                    "distance_metric".to_string(),
                    serde_json::json!(match distance_metric {
                        DistanceMetric::L2 => "l2",
                        DistanceMetric::Cosine => "cosine",
                        DistanceMetric::Mips => "mips",
                    }),
                );
                kwargs.insert("is_compact".to_string(), serde_json::json!(is_compact));
                kwargs.insert("is_recompute".to_string(), serde_json::json!(is_recompute));
                kwargs
            }
        }
    }

    /// Extract an `HnswConfig` from this configuration (panics if not HNSW).
    pub fn to_hnsw_config(&self) -> HnswConfig {
        match self {
            Self::Hnsw {
                m,
                ef_construction,
                distance_metric,
                is_compact,
                is_recompute,
                seed,
                ..
            } => HnswConfig {
                m: *m,
                ef_construction: *ef_construction,
                ef_search: 64, // search-time param, not stored in build config
                distance_metric: *distance_metric,
                is_compact: *is_compact,
                is_recompute: *is_recompute,
                seed: *seed,
            },
        }
    }

    /// Whether this config uses compact storage.
    pub fn is_compact(&self) -> bool {
        match self {
            Self::Hnsw { is_compact, .. } => *is_compact,
        }
    }

    /// Whether this config uses recompute mode.
    pub fn is_recompute(&self) -> bool {
        match self {
            Self::Hnsw { is_recompute, .. } => *is_recompute,
        }
    }
}

// ---------------------------------------------------------------------------
// BackendIndex
// ---------------------------------------------------------------------------

/// A loaded backend index, ready for search.
pub enum BackendIndex {
    Hnsw(HnswGraph),
    // Future: Ivf { ... },
}

impl std::fmt::Debug for BackendIndex {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Hnsw(g) => f
                .debug_struct("BackendIndex::Hnsw")
                .field("ntotal", &g.ntotal)
                .field("dimensions", &g.dimensions)
                .finish(),
        }
    }
}

impl BackendIndex {
    /// Total number of indexed vectors.
    pub fn ntotal(&self) -> usize {
        match self {
            Self::Hnsw(g) => g.ntotal,
        }
    }

    /// Dimensionality of indexed vectors.
    pub fn dimensions(&self) -> usize {
        match self {
            Self::Hnsw(g) => g.dimensions,
        }
    }

    /// Whether vector storage has been pruned (recompute mode).
    pub fn is_pruned(&self) -> bool {
        match self {
            Self::Hnsw(g) => g.is_pruned(),
        }
    }
}

// ---------------------------------------------------------------------------
// Dispatch functions
// ---------------------------------------------------------------------------

/// Build an index and write it to disk.
///
/// Handles graph construction, optional CSR compaction, optional vector storage,
/// and serialization — the full pipeline from embeddings to on-disk index.
pub fn build_backend(
    config: &BackendConfig,
    embeddings: &Array2<f32>,
    index_file: &Path,
    progress: Option<&dyn crate::hnsw::IndexProgress>,
) -> Result<()> {
    match config {
        BackendConfig::Hnsw {
            num_threads,
            is_recompute,
            is_compact,
            distance_metric,
            ..
        } => {
            let hnsw_config = config.to_hnsw_config();

            info!(
                "Building HNSW graph (M={}, efConstruction={})",
                hnsw_config.m, hnsw_config.ef_construction
            );
            let mut graph =
                build_hnsw_with_threads(embeddings, &hnsw_config, *num_threads, progress)?;

            // Store vectors if not using recompute
            if !is_recompute {
                let flat: Vec<f32> = embeddings.iter().copied().collect();
                let storage_bytes = flat
                    .iter()
                    .flat_map(|f| f.to_le_bytes())
                    .collect::<Vec<u8>>();

                let fourcc = match distance_metric {
                    DistanceMetric::L2 => u32::from_le_bytes(*b"IxFl"),
                    _ => u32::from_le_bytes(*b"IxFI"),
                };

                graph.vector_storage = VectorStorage::Raw {
                    fourcc,
                    data: storage_bytes,
                };
            }

            // Convert to CSR if compact mode
            let graph = if *is_compact {
                info!("Converting to compact CSR format");
                convert_to_csr(&graph)?
            } else {
                graph
            };

            // Write index file
            let mut file = std::fs::File::create(index_file)?;
            if graph.is_compact() {
                write_hnsw_compact(&mut file, &graph)?;
            } else {
                write_hnsw_standard(&mut file, &graph)?;
            }

            Ok(())
        }
    }
}

/// Read an index from disk.
pub fn read_backend_index(backend_name: &str, index_file: &Path) -> Result<BackendIndex> {
    match backend_name {
        "hnsw" => {
            let index_data = std::fs::read(index_file)?;
            let mut cursor = Cursor::new(index_data);
            let graph = read_hnsw_index(&mut cursor)?;
            Ok(BackendIndex::Hnsw(graph))
        }
        other => anyhow::bail!("Unknown backend '{}' — cannot read index", other),
    }
}

/// Search using stored vectors.
pub fn search_backend(
    index: &BackendIndex,
    query: &[f32],
    top_k: usize,
    params: &SearchParams,
) -> (Vec<usize>, Vec<f32>) {
    match index {
        BackendIndex::Hnsw(graph) => {
            match &graph.vector_storage {
                VectorStorage::Raw { data, .. } => {
                    let flat_vectors: Vec<f32> = data
                        .chunks_exact(4)
                        .map(|b| f32::from_le_bytes(b.try_into().unwrap()))
                        .collect();
                    search_hnsw(graph, query, top_k, &flat_vectors, params)
                }
                VectorStorage::Null => {
                    // No stored vectors — return empty results.
                    // Caller should use search_backend_recompute instead.
                    (Vec::new(), Vec::new())
                }
            }
        }
    }
}

/// Search using recomputed distances (embedding provider callback).
pub fn search_backend_recompute<F>(
    index: &BackendIndex,
    query: &[f32],
    top_k: usize,
    params: &SearchParams,
    compute_distance: F,
) -> (Vec<usize>, Vec<f32>)
where
    F: FnMut(&[usize], &[f32], &mut [f32]),
{
    match index {
        BackendIndex::Hnsw(graph) => {
            search_hnsw_recompute(graph, query, top_k, params, compute_distance)
        }
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    #[test]
    fn test_backend_config_hnsw_default() {
        let cfg = BackendConfig::hnsw_default();
        assert_eq!(cfg.name(), "hnsw");
        assert_eq!(cfg.distance_metric(), DistanceMetric::Mips);
        assert!(cfg.is_compact());
        assert!(cfg.is_recompute());
    }

    #[test]
    fn test_backend_config_from_name() {
        assert!(BackendConfig::from_name("hnsw").is_ok());
        assert!(BackendConfig::from_name("ivf").is_err());
        assert!(BackendConfig::from_name("unknown").is_err());
    }

    #[test]
    fn test_backend_config_setters() {
        let mut cfg = BackendConfig::hnsw_default();
        cfg.set_m(16);
        cfg.set_ef_construction(100);
        cfg.set_compact(false);
        cfg.set_recompute(false);
        cfg.set_distance_metric(DistanceMetric::L2);
        cfg.set_num_threads(4);

        assert!(!cfg.is_compact());
        assert!(!cfg.is_recompute());
        assert_eq!(cfg.distance_metric(), DistanceMetric::L2);

        let hnsw = cfg.to_hnsw_config();
        assert_eq!(hnsw.m, 16);
        assert_eq!(hnsw.ef_construction, 100);
        assert!(!hnsw.is_compact);
        assert!(!hnsw.is_recompute);
        assert_eq!(hnsw.distance_metric, DistanceMetric::L2);
    }

    #[test]
    fn test_backend_kwargs_serialization() {
        let cfg = BackendConfig::hnsw_default();
        let kwargs = cfg.to_backend_kwargs();
        assert_eq!(kwargs["M"], serde_json::json!(32));
        assert_eq!(kwargs["efConstruction"], serde_json::json!(200));
        assert_eq!(kwargs["distance_metric"], serde_json::json!("mips"));
        assert_eq!(kwargs["is_compact"], serde_json::json!(true));
        assert_eq!(kwargs["is_recompute"], serde_json::json!(true));
    }

    #[test]
    fn test_read_backend_index_unknown() {
        let tmp = tempfile::NamedTempFile::new().unwrap();
        let result = read_backend_index("unknown", tmp.path());
        assert!(result.is_err());
    }
}