Skip to main content

troupekit_store_sqlite/
vectors.rs

1use crate::{db, SqliteStore};
2use async_trait::async_trait;
3use rusqlite::{params, params_from_iter, Connection, OptionalExtension, TransactionBehavior};
4use std::collections::{BTreeMap, HashSet};
5use std::sync::{Arc, RwLock, RwLockReadGuard, RwLockWriteGuard};
6use troupekit_core::error::CoreError;
7use troupekit_core::store::{Filter, KeywordStore, Scored, VectorRecord, VectorStore};
8use troupekit_index::{
9    new_index, HnswParams, IndexError, IndexKind, PageChange, PageKey, Quantization, VectorIndex,
10    MAX_DIMS, MAX_K,
11};
12use troupekit_trace::{trace_span, Trace};
13
14const NAME_BYTES_MAX: usize = 64;
15const ID_BYTES_MAX: usize = 256;
16const ERROR_BYTES_MAX: usize = 1024;
17const SNAPSHOT_TRIES: usize = 4;
18const HASH_BYTES_MAX: usize = 256;
19const MAX_TEXT_BYTES_DEFAULT: usize = 1024 * 1024;
20const MAX_META_PAIRS_DEFAULT: usize = 64;
21const MAX_META_KEY_BYTES_DEFAULT: usize = 256;
22const MAX_META_VALUE_BYTES_DEFAULT: usize = 4096;
23const MAX_BATCH_DEFAULT: usize = 10_000;
24const MAX_QUERY_TERMS_DEFAULT: usize = 32;
25const MAX_QUERY_CHARS_DEFAULT: usize = 2_000;
26const KIND_BRUTE: &str = "brute_force";
27const KIND_HNSW: &str = "hnsw";
28const SCOPE_KEY: &str = "scope";
29const SOURCE_KEY: &str = "source";
30
31/// Settings of one named vector index. `dims` is required; the rest has
32/// safe defaults: brute force, f32 in memory, 1 MiB of text per chunk,
33/// 64 meta pairs of at most 256 and 4 096 bytes, 10 000 records per call,
34/// keyword queries of 32 terms and 2 000 chars. Built with `new(dims)`.
35#[non_exhaustive]
36#[derive(Debug, Clone, PartialEq)]
37pub struct VectorSettings {
38    dims: usize,
39    kind: IndexKind,
40    quantization: Quantization,
41    max_text_bytes: usize,
42    max_meta_pairs: usize,
43    max_meta_key_bytes: usize,
44    max_meta_value_bytes: usize,
45    max_batch: usize,
46    max_query_terms: usize,
47    max_query_chars: usize,
48}
49
50impl VectorSettings {
51    /// Starts settings for vectors of `dims` dimensions.
52    /// Input: `dims`, checked in `1..=65 536` when the index opens.
53    /// Output: settings with every other value at its default.
54    pub fn new(dims: usize) -> Self {
55        Self {
56            dims,
57            kind: IndexKind::default(),
58            quantization: Quantization::default(),
59            max_text_bytes: MAX_TEXT_BYTES_DEFAULT,
60            max_meta_pairs: MAX_META_PAIRS_DEFAULT,
61            max_meta_key_bytes: MAX_META_KEY_BYTES_DEFAULT,
62            max_meta_value_bytes: MAX_META_VALUE_BYTES_DEFAULT,
63            max_batch: MAX_BATCH_DEFAULT,
64            max_query_terms: MAX_QUERY_TERMS_DEFAULT,
65            max_query_chars: MAX_QUERY_CHARS_DEFAULT,
66        }
67    }
68
69    /// Sets the index kind. A kind or HNSW params other than the stored
70    /// ones rebuild the index and rewrite its pages when it opens.
71    /// Default `IndexKind::BruteForce`.
72    pub fn with_kind(mut self, kind: IndexKind) -> Self {
73        self.kind = kind;
74        self
75    }
76
77    /// Sets the in-memory vector format. The file always keeps f32, so a
78    /// change only reloads memory. The last `vectors` call for a name sets
79    /// it for every handle of that name. Default `Quantization::F32`.
80    pub fn with_quantization(mut self, quantization: Quantization) -> Self {
81        self.quantization = quantization;
82        self
83    }
84
85    /// Sets the largest chunk text in bytes.
86    /// A larger record fails the whole call with `CoreError::Store`.
87    /// Default 1 MiB.
88    pub fn with_max_text_bytes(mut self, bytes: usize) -> Self {
89        self.max_text_bytes = bytes;
90        self
91    }
92
93    /// Sets the most meta pairs on one record and in one search filter.
94    /// More fails the call with `CoreError::Store`.
95    /// Default 64.
96    pub fn with_max_meta_pairs(mut self, pairs: usize) -> Self {
97        self.max_meta_pairs = pairs;
98        self
99    }
100
101    /// Sets the longest meta key in bytes.
102    /// A longer key fails the call with `CoreError::Store`.
103    /// Default 256.
104    pub fn with_max_meta_key_bytes(mut self, bytes: usize) -> Self {
105        self.max_meta_key_bytes = bytes;
106        self
107    }
108
109    /// Sets the longest meta value in bytes.
110    /// A longer value fails the call with `CoreError::Store`.
111    /// Default 4 096.
112    pub fn with_max_meta_value_bytes(mut self, bytes: usize) -> Self {
113        self.max_meta_value_bytes = bytes;
114        self
115    }
116
117    /// Sets the most records one `upsert` or `replace_source` writes,
118    /// which bounds one transaction.
119    /// Default 10 000.
120    pub fn with_max_batch(mut self, records: usize) -> Self {
121        self.max_batch = records;
122        self
123    }
124
125    /// Sets the most terms in one keyword query, which bounds the FTS5
126    /// work per call. More terms fail with `CoreError::Store`.
127    /// Default 32.
128    pub fn with_max_query_terms(mut self, terms: usize) -> Self {
129        self.max_query_terms = terms;
130        self
131    }
132
133    /// Sets the longest keyword query in chars.
134    /// A longer query fails with `CoreError::Store`.
135    /// Default 2 000.
136    pub fn with_max_query_chars(mut self, chars: usize) -> Self {
137        self.max_query_chars = chars;
138        self
139    }
140
141    /// Returns the dimension of every vector and query.
142    /// It is fixed per index name once the index exists.
143    /// Required, no default.
144    pub fn dims(&self) -> usize {
145        self.dims
146    }
147
148    /// Returns the index kind.
149    /// Brute force is exact; HNSW is approximate and faster.
150    /// Default `IndexKind::BruteForce`.
151    pub fn kind(&self) -> &IndexKind {
152        &self.kind
153    }
154
155    /// Returns the in-memory vector format.
156    /// The file always keeps f32.
157    /// Default `Quantization::F32`.
158    pub fn quantization(&self) -> Quantization {
159        self.quantization
160    }
161
162    /// Returns the largest chunk text in bytes.
163    /// Checked on every record before anything is written.
164    /// Default 1 MiB.
165    pub fn max_text_bytes(&self) -> usize {
166        self.max_text_bytes
167    }
168
169    /// Returns the most meta pairs per record and per filter.
170    /// Checked before anything is written or searched.
171    /// Default 64.
172    pub fn max_meta_pairs(&self) -> usize {
173        self.max_meta_pairs
174    }
175
176    /// Returns the longest meta key in bytes.
177    /// Checked on every record before anything is written.
178    /// Default 256.
179    pub fn max_meta_key_bytes(&self) -> usize {
180        self.max_meta_key_bytes
181    }
182
183    /// Returns the longest meta value in bytes.
184    /// Checked on every record before anything is written.
185    /// Default 4 096.
186    pub fn max_meta_value_bytes(&self) -> usize {
187        self.max_meta_value_bytes
188    }
189
190    /// Returns the most records per write call.
191    /// It bounds one transaction.
192    /// Default 10 000.
193    pub fn max_batch(&self) -> usize {
194        self.max_batch
195    }
196
197    /// Returns the most terms in one keyword query.
198    /// Checked before the query reaches FTS5.
199    /// Default 32.
200    pub fn max_query_terms(&self) -> usize {
201        self.max_query_terms
202    }
203
204    /// Returns the longest keyword query in chars.
205    /// Checked before the query reaches FTS5.
206    /// Default 2 000.
207    pub fn max_query_chars(&self) -> usize {
208        self.max_query_chars
209    }
210}
211
212/// How often the index behind a handle was loaded from the file and how
213/// often its pages were refused and rebuilt from vectors, counted since
214/// the store opened. Shared by every handle of the same name.
215#[non_exhaustive]
216#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
217pub struct OpenReport {
218    loads: usize,
219    rebuilds: usize,
220}
221
222impl OpenReport {
223    /// Returns how many times the index was loaded from the file.
224    /// The first open counts as one; each reload after another
225    /// connection's write or a failed call adds one.
226    pub fn loads(&self) -> usize {
227        self.loads
228    }
229
230    /// Returns how many times stored pages were refused as corrupt and
231    /// the index was rebuilt from the stored vectors.
232    /// Zero on a healthy file.
233    pub fn rebuilds(&self) -> usize {
234        self.rebuilds
235    }
236}
237
238/// The in-memory index of one name and what the file looked like when
239/// it was loaded. `stale` forces a reload before the next call, so memory
240/// never runs ahead of the file after a failed write.
241pub(crate) struct Cached {
242    index: Box<dyn VectorIndex>,
243    settings: VectorSettings,
244    generation: i64,
245    stale: bool,
246    report: OpenReport,
247}
248
249/// One named index shared by every handle of a store: its name, its
250/// fixed dimension and the cached index behind a lock. Lock order is
251/// always connection, then this lock.
252pub(crate) struct IndexState {
253    name: String,
254    dims: usize,
255    cached: RwLock<Cached>,
256}
257
258/// A named vector index in the store file, with text, metadata and a
259/// keyword index kept in the same transactions. Cheap to clone; clones
260/// and other handles of the same name share one in-memory index. Every
261/// call checks the dimension and the bounds of its `VectorSettings`.
262#[derive(Clone)]
263pub struct SqliteVectors {
264    store: SqliteStore,
265    state: Arc<IndexState>,
266}
267
268impl std::fmt::Debug for SqliteVectors {
269    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
270        f.debug_struct("SqliteVectors")
271            .field("name", &self.state.name)
272            .field("dims", &self.state.dims)
273            .finish_non_exhaustive()
274    }
275}
276
277/// Applies this handle's FTS5 `secure-delete` wish to the file, where the
278/// option is persistent and shared by every handle. It may be raised,
279/// never lowered: a handle asking for off on a file that has it on is
280/// refused, so one store cannot weaken deletes for another.
281/// Output: `Ok`, or `CoreError::Store` naming the conflict.
282fn fts_secure_delete(tx: &rusqlite::Transaction<'_>, wanted: bool) -> Result<(), CoreError> {
283    let stored: Option<i64> = tx
284        .query_row("SELECT v FROM chunk_fts_config WHERE k = 'secure-delete'", [], |row| row.get(0))
285        .optional()
286        .map_err(db)?;
287    let on = stored == Some(1);
288    if wanted && !on {
289        tx.execute("INSERT INTO chunk_fts (chunk_fts, rank) VALUES ('secure-delete', 1)", []).map_err(db)?;
290    }
291    if !wanted && on {
292        return Err(CoreError::Store(
293            "this file has FTS5 secure-delete on; a store with secure_delete(false) may not turn it off for other handles".into(),
294        ));
295    }
296    Ok(())
297}
298
299impl SqliteStore {
300    /// Opens the vector index `name`, creating it on first use.
301    /// Input: a name of 1 to 64 chars in `[a-z0-9_]` and its settings.
302    /// Output: a handle, `CoreError::DimensionMismatch` when the stored
303    /// index has other dims, or `CoreError::Store` for bad settings.
304    pub async fn vectors(
305        &self,
306        name: &str,
307        settings: VectorSettings,
308    ) -> Result<SqliteVectors, CoreError> {
309        check_name(name)?;
310        check_settings(&settings)?;
311        let wanted_kind = kind_name(settings.kind())?;
312        let wanted_params = params_json(settings.kind())?;
313        let name = name.to_string();
314        let store = self.clone();
315        let now_ms = self.inner.clock.now_ms();
316        let secure_delete = self.inner.secure_delete;
317        let state = self
318            .call(move |conn| {
319                let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate).map_err(db)?;
320                fts_secure_delete(&tx, secure_delete)?;
321                let row: Option<(i64, String, String)> = tx
322                    .query_row(
323                        "SELECT dims, kind, params_json FROM vector_index WHERE name = ?1",
324                        [&name],
325                        |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),
326                    )
327                    .optional()
328                    .map_err(db)?;
329                let kind_changed = match row {
330                    None => {
331                        tx.execute(
332                            "INSERT INTO vector_index (name, dims, kind, params_json, generation, created_at_ms) \
333                             VALUES (?1, ?2, ?3, ?4, 0, ?5)",
334                            params![name, settings.dims as i64, wanted_kind, wanted_params, now_ms],
335                        )
336                        .map_err(db)?;
337                        false
338                    }
339                    Some((dims, kind, params)) => {
340                        if usize::try_from(dims).ok() != Some(settings.dims) {
341                            return Err(CoreError::DimensionMismatch {
342                                expected: usize::try_from(dims).unwrap_or(0),
343                                actual: settings.dims,
344                            });
345                        }
346                        kind != wanted_kind || params != wanted_params
347                    }
348                };
349                let (state, inserted) = {
350                    let mut map = match store.inner.vectors.lock() {
351                        Ok(map) => map,
352                        Err(poisoned) => poisoned.into_inner(),
353                    };
354                    match map.get(&name) {
355                        Some(state) => (Arc::clone(state), false),
356                        None => {
357                            let placeholder = new_index(&IndexKind::BruteForce, settings.dims, Quantization::F32).map_err(index_err)?;
358                            let state = Arc::new(IndexState {
359                                name: name.clone(),
360                                dims: settings.dims,
361                                cached: RwLock::new(Cached {
362                                    index: placeholder,
363                                    settings: settings.clone(),
364                                    generation: -1,
365                                    stale: true,
366                                    report: OpenReport::default(),
367                                }),
368                            });
369                            map.insert(name.clone(), Arc::clone(&state));
370                            (state, true)
371                        }
372                    }
373                };
374                assert_eq!(state.dims, settings.dims, "cached dims differ from the stored row");
375                let mut cached = write_cached(&state);
376                let previous = cached.settings.clone();
377                if cached.settings != settings {
378                    cached.settings = settings;
379                    cached.stale = true;
380                }
381                let loaded = if kind_changed {
382                    cached.stale = true;
383                    rebuild_kind(&tx, &state, &mut cached).map(Some)
384                } else {
385                    reload_if_needed(&tx, &state, &mut cached).map(|()| None)
386                };
387                let rebuilt_at = match loaded.and_then(|at| tx.commit().map(|()| at).map_err(db)) {
388                    Ok(at) => at,
389                    Err(e) => {
390                        cached.settings = previous;
391                        cached.stale = true;
392                        drop(cached);
393                        if inserted {
394                            forget_state(&store, &state);
395                        }
396                        return Err(e);
397                    }
398                };
399                if let Some(generation) = rebuilt_at {
400                    cached.generation = generation;
401                    cached.stale = false;
402                }
403                assert!(!cached.stale, "an opened index is fresh");
404                drop(cached);
405                Ok(state)
406            })
407            .await?;
408        Ok(SqliteVectors {
409            store: self.clone(),
410            state,
411        })
412    }
413}
414
415/// Removes the cache entry of `state` that a failed first open put in,
416/// so a later open with other dims or settings starts clean. Only the
417/// same `Arc` is removed. Input: the store and the state. Output: none.
418fn forget_state(store: &SqliteStore, state: &Arc<IndexState>) {
419    let mut map = match store.inner.vectors.lock() {
420        Ok(map) => map,
421        Err(poisoned) => poisoned.into_inner(),
422    };
423    if map.get(&state.name).is_some_and(|cached| Arc::ptr_eq(cached, state)) {
424        map.remove(&state.name);
425    }
426    assert!(map.get(&state.name).is_none_or(|cached| !Arc::ptr_eq(cached, state)));
427}
428
429impl SqliteVectors {
430    /// Returns how often this index was loaded and rebuilt since the
431    /// store opened. Input: none. Output: the counts, shared by every
432    /// handle of the same name.
433    pub fn open_report(&self) -> OpenReport {
434        read_cached(&self.state).report
435    }
436
437    /// Returns the live ids in the index after a freshness check, so a
438    /// write from another connection is counted. Input: none. Output:
439    /// the count, or `CoreError::Store`.
440    pub async fn len(&self) -> Result<usize, CoreError> {
441        let state = Arc::clone(&self.state);
442        self.store
443            .call(move |conn| {
444                refresh(conn, &state)?;
445                Ok(read_cached(&state).index.len())
446            })
447            .await
448    }
449
450    /// Returns whether the index holds no live ids, after the same
451    /// freshness check as `len`. Input: none. Output: `true` when empty,
452    /// or `CoreError::Store`.
453    pub async fn is_empty(&self) -> Result<bool, CoreError> {
454        Ok(self.len().await? == 0)
455    }
456
457    /// Replaces every chunk of one source in one transaction: deletes
458    /// the old rows, keyword rows and index entries, writes `records` and
459    /// marks the source `done` with `content_hash`. Every record's meta
460    /// must carry `scope` and `source` equal to the arguments. Output: the
461    /// number of records written, or an error that writes nothing.
462    pub async fn replace_source(
463        &self,
464        scope: &str,
465        source: &str,
466        records: Vec<VectorRecord>,
467        content_hash: &str,
468    ) -> Result<usize, CoreError> {
469        let settings = read_cached(&self.state).settings.clone();
470        check_source(scope, source, &settings)?;
471        if content_hash.is_empty() || content_hash.len() > HASH_BYTES_MAX {
472            return Err(CoreError::Store(format!(
473                "content_hash must be 1 to {HASH_BYTES_MAX} bytes"
474            )));
475        }
476        check_records(&records, &settings, self.state.dims)?;
477        for (position, record) in records.iter().enumerate() {
478            let scope_ok = record.meta.get(SCOPE_KEY).map(String::as_str) == Some(scope);
479            let source_ok = record.meta.get(SOURCE_KEY).map(String::as_str) == Some(source);
480            if !scope_ok || !source_ok {
481                return Err(CoreError::Store(format!(
482                    "record {position} must carry meta {SCOPE_KEY} and {SOURCE_KEY} equal to the replaced source"
483                )));
484            }
485        }
486        let state = Arc::clone(&self.state);
487        let scope = scope.to_string();
488        let source = source.to_string();
489        let content_hash = content_hash.to_string();
490        let now_ms = self.store.inner.clock.now_ms();
491        self.store
492            .call(move |conn| {
493                let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate).map_err(db)?;
494                let mut cached = write_cached(&state);
495                reload_if_needed(&tx, &state, &mut cached)?;
496                cached.stale = true;
497                delete_source_rows(&tx, &state, &mut cached, &scope, &source)?;
498                {
499                    let mut owned = tx.prepare_cached("SELECT 1 FROM chunk WHERE index_name = ?1 AND id = ?2").map_err(db)?;
500                    for record in &records {
501                        if owned.exists(params![state.name, record.id]).map_err(db)? {
502                            return Err(CoreError::Store(format!("record id {} belongs to another source", cut_utf8(&record.id, 64))));
503                        }
504                    }
505                }
506                let keys = write_rows(&tx, &state.name, &records)?;
507                for (key, record) in keys.iter().zip(&records) {
508                    cached.index.insert(*key, &record.vector).map_err(index_err)?;
509                }
510                let changes = cached.index.take_changes();
511                write_pages(&tx, &state.name, changes)?;
512                tx.execute(
513                    "INSERT INTO ingest_source (index_name, scope, source, content_hash, chunks, status, error, at_ms) \
514                     VALUES (?1, ?2, ?3, ?4, ?5, 'done', NULL, ?6) \
515                     ON CONFLICT (index_name, scope, source) DO UPDATE SET \
516                     content_hash = excluded.content_hash, chunks = excluded.chunks, status = 'done', error = NULL, at_ms = excluded.at_ms",
517                    params![state.name, scope, source, content_hash, records.len() as i64, now_ms],
518                )
519                .map_err(db)?;
520                let generation = bump_generation(&tx, &state.name)?;
521                tx.commit().map_err(db)?;
522                cached.generation = generation;
523                cached.stale = false;
524                Ok(records.len())
525            })
526            .await
527    }
528
529    /// Lists every source of `scope` that has an ingest status row, done
530    /// or failed, sorted. Input: the scope. Output: the sources, so a
531    /// folder ingest can find the ones whose file is gone.
532    pub async fn sources(&self, scope: &str) -> Result<Vec<String>, CoreError> {
533        let state = Arc::clone(&self.state);
534        let scope = scope.to_string();
535        self.store
536            .call(move |conn| {
537                let mut stmt = conn
538                    .prepare("SELECT source FROM ingest_source WHERE index_name = ?1 AND scope = ?2 ORDER BY source")
539                    .map_err(db)?;
540                let rows = stmt.query_map(params![state.name, scope], |row| row.get(0)).map_err(db)?;
541                rows.collect::<Result<Vec<String>, _>>().map_err(db)
542            })
543            .await
544    }
545
546    /// Removes one source in one transaction: its chunk, meta and keyword
547    /// rows, its index entries and pages, and its ingest status row.
548    /// Input: the scope and source. Output: the chunks removed, 0 when
549    /// the source had none, or an error that removes nothing.
550    pub async fn remove_source(&self, scope: &str, source: &str) -> Result<usize, CoreError> {
551        let settings = read_cached(&self.state).settings.clone();
552        check_source(scope, source, &settings)?;
553        let state = Arc::clone(&self.state);
554        let scope = scope.to_string();
555        let source = source.to_string();
556        self.store
557            .call(move |conn| {
558                let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate).map_err(db)?;
559                let mut cached = write_cached(&state);
560                reload_if_needed(&tx, &state, &mut cached)?;
561                cached.stale = true;
562                let removed = delete_source_rows(&tx, &state, &mut cached, &scope, &source)?;
563                let changes = cached.index.take_changes();
564                write_pages(&tx, &state.name, changes)?;
565                tx.execute(
566                    "DELETE FROM ingest_source WHERE index_name = ?1 AND scope = ?2 AND source = ?3",
567                    params![state.name, scope, source],
568                )
569                .map_err(db)?;
570                let generation = bump_generation(&tx, &state.name)?;
571                tx.commit().map_err(db)?;
572                cached.generation = generation;
573                cached.stale = false;
574                Ok(removed)
575            })
576            .await
577    }
578
579    /// Returns the content hash of a source last replaced with success.
580    /// Input: the scope and source. Output: the hash, or `None` when the
581    /// source was never ingested or its last attempt failed.
582    pub async fn source_hash(
583        &self,
584        scope: &str,
585        source: &str,
586    ) -> Result<Option<String>, CoreError> {
587        let name = self.state.name.clone();
588        let scope = scope.to_string();
589        let source = source.to_string();
590        self.store
591            .call(move |conn| {
592                conn.query_row(
593                    "SELECT content_hash FROM ingest_source \
594                     WHERE index_name = ?1 AND scope = ?2 AND source = ?3 AND status = 'done'",
595                    params![name, scope, source],
596                    |row| row.get(0),
597                )
598                .optional()
599                .map_err(db)
600            })
601            .await
602    }
603
604    /// Records that ingesting a source failed, with the error cut to
605    /// 1 024 bytes. The source's chunks stay as they were, and
606    /// `source_hash` returns `None` so the next run retries it.
607    /// Output: `Ok`, or `CoreError::Store`.
608    pub async fn record_failed_source(
609        &self,
610        scope: &str,
611        source: &str,
612        error: &str,
613    ) -> Result<(), CoreError> {
614        let settings = read_cached(&self.state).settings.clone();
615        check_source(scope, source, &settings)?;
616        let error = cut_utf8(error, ERROR_BYTES_MAX);
617        let error = if error.is_empty() {
618            String::from("unknown error")
619        } else {
620            error.to_string()
621        };
622        assert!(error.len() <= ERROR_BYTES_MAX, "error text over its cap");
623        let name = self.state.name.clone();
624        let scope = scope.to_string();
625        let source = source.to_string();
626        let now_ms = self.store.inner.clock.now_ms();
627        self.store
628            .call(move |conn| {
629                let chunks: i64 = conn
630                    .query_row(
631                        "SELECT chunks FROM ingest_source WHERE index_name = ?1 AND scope = ?2 AND source = ?3",
632                        params![name, scope, source],
633                        |row| row.get(0),
634                    )
635                    .optional()
636                    .map_err(db)?
637                    .unwrap_or(0);
638                let written = conn
639                    .execute(
640                        "INSERT INTO ingest_source (index_name, scope, source, content_hash, chunks, status, error, at_ms) \
641                         VALUES (?1, ?2, ?3, '', ?4, 'failed', ?5, ?6) \
642                         ON CONFLICT (index_name, scope, source) DO UPDATE SET \
643                         status = 'failed', error = excluded.error, at_ms = excluded.at_ms",
644                        params![name, scope, source, chunks, error, now_ms],
645                    )
646                    .map_err(db)?;
647                assert_eq!(written, 1);
648                Ok(())
649            })
650            .await
651    }
652}
653
654#[async_trait]
655impl VectorStore for SqliteVectors {
656    fn dims(&self) -> usize {
657        self.state.dims
658    }
659
660    async fn upsert(&self, records: Vec<VectorRecord>) -> Result<(), CoreError> {
661        let settings = read_cached(&self.state).settings.clone();
662        check_records(&records, &settings, self.state.dims)?;
663        if records.is_empty() {
664            return Ok(());
665        }
666        let state = Arc::clone(&self.state);
667        let mut span = trace_span!(
668            Trace::Knowledge,
669            "vectors.upsert",
670            index = self.state.name.as_str(),
671            records = records.len()
672        );
673        let result = span
674            .instrument(self.store.call(move |conn| {
675                let tx = conn
676                    .transaction_with_behavior(TransactionBehavior::Immediate)
677                    .map_err(db)?;
678                let mut cached = write_cached(&state);
679                reload_if_needed(&tx, &state, &mut cached)?;
680                cached.stale = true;
681                let keys = write_rows(&tx, &state.name, &records)?;
682                for (key, record) in keys.iter().zip(&records) {
683                    cached
684                        .index
685                        .insert(*key, &record.vector)
686                        .map_err(index_err)?;
687                }
688                let changes = cached.index.take_changes();
689                write_pages(&tx, &state.name, changes)?;
690                let generation = bump_generation(&tx, &state.name)?;
691                tx.commit().map_err(db)?;
692                cached.generation = generation;
693                cached.stale = false;
694                Ok(())
695            }))
696            .await;
697        if let Err(e) = &result {
698            span.fail(e.to_string());
699        }
700        result
701    }
702
703    async fn search(
704        &self,
705        query: &[f32],
706        k: usize,
707        filter: &Filter,
708    ) -> Result<Vec<Scored>, CoreError> {
709        if query.len() != self.state.dims {
710            return Err(CoreError::DimensionMismatch {
711                expected: self.state.dims,
712                actual: query.len(),
713            });
714        }
715        if !query.iter().all(|v| v.is_finite()) {
716            return Err(CoreError::Store("query vector must be finite".into()));
717        }
718        if k > MAX_K {
719            return Err(CoreError::Store(format!("k must be at most {MAX_K}, got {k}")));
720        }
721        let settings = read_cached(&self.state).settings.clone();
722        if filter.0.len() > settings.max_meta_pairs {
723            return Err(CoreError::Store(format!(
724                "filter has {} pairs, above max_meta_pairs {}",
725                filter.0.len(),
726                settings.max_meta_pairs
727            )));
728        }
729        let state = Arc::clone(&self.state);
730        let query = query.to_vec();
731        let pairs: Vec<(String, String)> = filter
732            .0
733            .iter()
734            .map(|(k, v)| (k.clone(), v.clone()))
735            .collect();
736        self.store
737            .call(move |conn| {
738                for _ in 0..SNAPSHOT_TRIES {
739                    let tx = conn.transaction().map_err(db)?;
740                    let generation = read_generation(&tx, &state.name)?;
741                    let cached = read_cached(&state);
742                    if state.cached.is_poisoned() || cached.stale || cached.generation != generation
743                    {
744                        drop(cached);
745                        drop(tx);
746                        refresh(conn, &state)?;
747                        continue;
748                    }
749                    return search_snapshot(&tx, &state, &cached, &query, k, &pairs);
750                }
751                Err(CoreError::Store(format!(
752                    "index changed under {SNAPSHOT_TRIES} searches in a row; try again"
753                )))
754            })
755            .await
756    }
757}
758
759/// Deletes every chunk of one source, with its meta and keyword rows,
760/// and removes the chunks from the cached index, inside the caller's
761/// write transaction. Input: the transaction, state, cache, scope and
762/// source. Output: the number of chunks deleted.
763fn delete_source_rows(
764    tx: &Connection,
765    state: &IndexState,
766    cached: &mut Cached,
767    scope: &str,
768    source: &str,
769) -> Result<usize, CoreError> {
770    assert!(cached.stale, "source rows change only under a stale cache");
771    let old: Vec<(i64, String)> = {
772        let mut stmt = tx
773            .prepare(
774                "SELECT c.key, c.text FROM chunk c \
775                 JOIN chunk_meta s ON s.chunk_key = c.key AND s.key = ?2 AND s.value = ?3 \
776                 JOIN chunk_meta o ON o.chunk_key = c.key AND o.key = ?4 AND o.value = ?5 \
777                 WHERE c.index_name = ?1 ORDER BY c.key",
778            )
779            .map_err(db)?;
780        let rows = stmt
781            .query_map(
782                params![state.name, SCOPE_KEY, scope, SOURCE_KEY, source],
783                |row| Ok((row.get(0)?, row.get(1)?)),
784            )
785            .map_err(db)?;
786        rows.collect::<Result<_, _>>().map_err(db)?
787    };
788    for (key, text) in &old {
789        delete_row(tx, *key, text)?;
790        cached.index.remove(to_id(*key)?);
791    }
792    Ok(old.len())
793}
794
795/// Searches the cached index and reads the hits inside one read
796/// transaction whose generation matches the cache, so a hit's score and
797/// its text come from the same committed version. Input: the open
798/// transaction, the state, its matching cache, query, k and filter pairs.
799fn search_snapshot(
800    tx: &rusqlite::Transaction<'_>,
801    state: &IndexState,
802    cached: &Cached,
803    query: &[f32],
804    k: usize,
805    pairs: &[(String, String)],
806) -> Result<Vec<Scored>, CoreError> {
807    let allowed = if pairs.is_empty() {
808        None
809    } else {
810        Some(allowed_keys(tx, &state.name, pairs)?)
811    };
812    if allowed.as_ref().is_some_and(HashSet::is_empty) {
813        return Ok(Vec::new());
814    }
815    let neighbors = {
816        let allow_fn = |id: u64| allowed.as_ref().is_none_or(|set| set.contains(&id));
817        let allow: Option<&dyn Fn(u64) -> bool> = if allowed.is_some() {
818            Some(&allow_fn)
819        } else {
820            None
821        };
822        cached.index.search(query, k, allow).map_err(index_err)?
823    };
824    let mut stmt = tx
825        .prepare_cached("SELECT id, text, meta_json FROM chunk WHERE key = ?1 AND index_name = ?2")
826        .map_err(db)?;
827    let mut hits = Vec::with_capacity(neighbors.len());
828    for neighbor in &neighbors {
829        let key = i64::try_from(neighbor.id)
830            .map_err(|_| CoreError::Store("index id out of range".into()))?;
831        let row: Option<(String, String, String)> = stmt
832            .query_row(params![key, state.name], |row| {
833                Ok((row.get(0)?, row.get(1)?, row.get(2)?))
834            })
835            .optional()
836            .map_err(db)?;
837        let Some((id, text, meta_json)) = row else {
838            continue;
839        };
840        let meta: BTreeMap<String, String> = serde_json::from_str(&meta_json)
841            .map_err(|e| CoreError::Store(format!("corrupt store: chunk meta: {e}")))?;
842        hits.push(Scored {
843            id,
844            score: neighbor.score,
845            text,
846            meta,
847        });
848    }
849    assert!(hits.len() <= k, "search returned more than k hits");
850    Ok(hits)
851}
852
853#[async_trait]
854impl KeywordStore for SqliteVectors {
855    async fn search_text(
856        &self,
857        query: &str,
858        k: usize,
859        filter: &Filter,
860    ) -> Result<Vec<Scored>, CoreError> {
861        let settings = read_cached(&self.state).settings.clone();
862        let chars = query.chars().count();
863        if chars > settings.max_query_chars {
864            return Err(CoreError::Store(format!(
865                "query is {chars} chars, above max_query_chars {}",
866                settings.max_query_chars
867            )));
868        }
869        if k > MAX_K {
870            return Err(CoreError::Store(format!(
871                "k must be at most {MAX_K}, got {k}"
872            )));
873        }
874        if filter.0.len() > settings.max_meta_pairs {
875            return Err(CoreError::Store(format!(
876                "filter has {} pairs, above max_meta_pairs {}",
877                filter.0.len(),
878                settings.max_meta_pairs
879            )));
880        }
881        let (terms, fts) = fts_query(query);
882        if terms.len() > settings.max_query_terms {
883            return Err(CoreError::Store(format!(
884                "query has {} terms, above max_query_terms {}",
885                terms.len(),
886                settings.max_query_terms
887            )));
888        }
889        if terms.is_empty() || k == 0 {
890            return Ok(Vec::new());
891        }
892        let name = self.state.name.clone();
893        let pairs: Vec<(String, String)> = filter
894            .0
895            .iter()
896            .map(|(k, v)| (k.clone(), v.clone()))
897            .collect();
898        self.store
899            .call(move |conn| {
900                let limit = 3 + 2 * pairs.len();
901                let sql = format!(
902                    "SELECT c.id, c.text, c.meta_json, -bm25(chunk_fts) AS score \
903                     FROM chunk_fts JOIN chunk c ON c.key = chunk_fts.rowid \
904                     WHERE chunk_fts MATCH ?1 AND c.index_name = ?2{} \
905                     ORDER BY score DESC, c.id ASC LIMIT ?{limit}",
906                    meta_clauses("c.key", pairs.len(), 3)
907                );
908                let mut values: Vec<rusqlite::types::Value> = vec![fts.into(), name.into()];
909                for (key, value) in pairs {
910                    values.push(key.into());
911                    values.push(value.into());
912                }
913                values.push((k as i64).into());
914                let mut stmt = conn.prepare(&sql).map_err(db)?;
915                let rows = stmt
916                    .query_map(params_from_iter(values), |row| {
917                        Ok((
918                            row.get::<_, String>(0)?,
919                            row.get::<_, String>(1)?,
920                            row.get::<_, String>(2)?,
921                            row.get::<_, f64>(3)?,
922                        ))
923                    })
924                    .map_err(db)?;
925                let mut hits = Vec::new();
926                for row in rows {
927                    let (id, text, meta_json, score) = row.map_err(db)?;
928                    let meta: BTreeMap<String, String> = serde_json::from_str(&meta_json)
929                        .map_err(|e| CoreError::Store(format!("corrupt store: chunk meta: {e}")))?;
930                    hits.push(Scored {
931                        id,
932                        score: score as f32,
933                        text,
934                        meta,
935                    });
936                }
937                assert!(hits.len() <= k, "keyword search returned more than k hits");
938                assert!(
939                    hits.windows(2).all(|w| w[0].score >= w[1].score),
940                    "keyword hits sorted by score"
941                );
942                Ok(hits)
943            })
944            .await
945    }
946}
947
948/// Takes the write lock of a cached index. A lock poisoned by a panic
949/// mid-update is taken anyway and marked stale, so the next step reloads
950/// it from the file. Output: the guard.
951fn write_cached(state: &IndexState) -> RwLockWriteGuard<'_, Cached> {
952    match state.cached.write() {
953        Ok(guard) => guard,
954        Err(poisoned) => {
955            let mut guard = poisoned.into_inner();
956            guard.stale = true;
957            state.cached.clear_poison();
958            guard
959        }
960    }
961}
962
963/// Takes the read lock of a cached index, poisoned or not. Callers
964/// that search first run `refresh`, which reloads a poisoned index.
965/// Output: the guard.
966fn read_cached(state: &IndexState) -> RwLockReadGuard<'_, Cached> {
967    match state.cached.read() {
968        Ok(guard) => guard,
969        Err(poisoned) => poisoned.into_inner(),
970    }
971}
972
973/// Reloads the index when another connection wrote since it was loaded,
974/// or when it is stale or poisoned. Input: the connection, outside any
975/// transaction. Output: `Ok` once memory matches the file.
976fn refresh(conn: &mut Connection, state: &IndexState) -> Result<(), CoreError> {
977    let generation = read_generation(conn, &state.name)?;
978    if !state.cached.is_poisoned() {
979        let cached = read_cached(state);
980        if cached.generation == generation && !cached.stale {
981            return Ok(());
982        }
983    }
984    let tx = conn
985        .transaction_with_behavior(TransactionBehavior::Immediate)
986        .map_err(db)?;
987    let mut cached = write_cached(state);
988    reload_if_needed(&tx, state, &mut cached)?;
989    tx.commit().map_err(db)?;
990    Ok(())
991}
992
993/// Loads the index from the file when its generation differs from the
994/// cached one or the cache is stale. Pages refused as corrupt are
995/// rebuilt from vectors and rewritten. Input: a connection inside a
996/// write transaction. Output: `Ok` with `cached` fresh.
997fn reload_if_needed(
998    conn: &Connection,
999    state: &IndexState,
1000    cached: &mut Cached,
1001) -> Result<(), CoreError> {
1002    let generation = read_generation(conn, &state.name)?;
1003    if cached.generation == generation && !cached.stale {
1004        return Ok(());
1005    }
1006    let kind = stored_kind(conn, &state.name)?;
1007    let mut index =
1008        new_index(&kind, state.dims, cached.settings.quantization).map_err(index_err)?;
1009    let vectors = load_vectors(conn, &state.name, state.dims)?;
1010    let pages = load_pages(conn, &state.name)?;
1011    let rebuilt = match index.restore(&mut vectors.into_iter(), &mut pages.into_iter()) {
1012        Ok(()) => {
1013            index.take_changes();
1014            false
1015        }
1016        Err(IndexError::CorruptPage(_)) => {
1017            index = build_from_file(
1018                conn,
1019                &kind,
1020                state.dims,
1021                cached.settings.quantization,
1022                &state.name,
1023            )?;
1024            true
1025        }
1026        Err(e) => return Err(index_err(e)),
1027    };
1028    if rebuilt {
1029        conn.execute(
1030            "DELETE FROM index_page WHERE index_name = ?1",
1031            [&state.name],
1032        )
1033        .map_err(db)?;
1034        let changes = index.take_changes();
1035        write_pages(conn, &state.name, changes)?;
1036        cached.report.rebuilds += 1;
1037    }
1038    cached.index = index;
1039    cached.generation = generation;
1040    cached.stale = false;
1041    cached.report.loads += 1;
1042    Ok(())
1043}
1044
1045/// Rebuilds the index under the kind in `cached.settings`, rewrites all
1046/// pages and stores the new kind, all in the caller's transaction. The
1047/// cache stays stale: the caller publishes the generation after commit.
1048/// Input: a connection inside a write transaction. Output: the new generation.
1049fn rebuild_kind(
1050    conn: &Connection,
1051    state: &IndexState,
1052    cached: &mut Cached,
1053) -> Result<i64, CoreError> {
1054    let kind = cached.settings.kind.clone();
1055    let index = build_from_file(
1056        conn,
1057        &kind,
1058        state.dims,
1059        cached.settings.quantization,
1060        &state.name,
1061    )?;
1062    conn.execute(
1063        "UPDATE vector_index SET kind = ?2, params_json = ?3 WHERE name = ?1",
1064        params![state.name, kind_name(&kind)?, params_json(&kind)?],
1065    )
1066    .map_err(db)?;
1067    cached.index = index;
1068    conn.execute(
1069        "DELETE FROM index_page WHERE index_name = ?1",
1070        [&state.name],
1071    )
1072    .map_err(db)?;
1073    let changes = cached.index.take_changes();
1074    write_pages(conn, &state.name, changes)?;
1075    let generation = bump_generation(conn, &state.name)?;
1076    assert!(cached.stale, "a rebuilt index stays stale until its commit");
1077    cached.report.loads += 1;
1078    Ok(generation)
1079}
1080
1081/// Builds a fresh index by inserting every stored vector of `name`.
1082/// Input: the connection, kind, dims, format and name. Output: the index
1083/// with its page changes not yet taken.
1084fn build_from_file(
1085    conn: &Connection,
1086    kind: &IndexKind,
1087    dims: usize,
1088    quantization: Quantization,
1089    name: &str,
1090) -> Result<Box<dyn VectorIndex>, CoreError> {
1091    let mut index = new_index(kind, dims, quantization).map_err(index_err)?;
1092    for (id, vector) in load_vectors(conn, name, dims)? {
1093        index.insert(id, &vector).map_err(index_err)?;
1094    }
1095    Ok(index)
1096}
1097
1098/// Reads every stored vector of `name` in key order, checking each blob
1099/// is `4 * dims` bytes. Input: the connection, name and dims. Output:
1100/// pairs of index id and vector, or `CoreError::Store` on a bad blob.
1101fn load_vectors(
1102    conn: &Connection,
1103    name: &str,
1104    dims: usize,
1105) -> Result<Vec<(u64, Vec<f32>)>, CoreError> {
1106    let mut stmt = conn
1107        .prepare("SELECT key, vector FROM chunk WHERE index_name = ?1 ORDER BY key")
1108        .map_err(db)?;
1109    let rows = stmt
1110        .query_map([name], |row| {
1111            Ok((row.get::<_, i64>(0)?, row.get::<_, Vec<u8>>(1)?))
1112        })
1113        .map_err(db)?;
1114    let mut out = Vec::new();
1115    for row in rows {
1116        let (key, bytes) = row.map_err(db)?;
1117        out.push((to_id(key)?, decode(&bytes, dims)?));
1118    }
1119    Ok(out)
1120}
1121
1122/// Reads every stored page of `name` in page order. Page 0 is the
1123/// header and page `n >= 1` is node `n`. Input: the connection and the
1124/// name. Output: the pages, or `CoreError::Store`.
1125fn load_pages(conn: &Connection, name: &str) -> Result<Vec<(PageKey, Vec<u8>)>, CoreError> {
1126    let mut stmt = conn
1127        .prepare("SELECT page, bytes FROM index_page WHERE index_name = ?1 ORDER BY page")
1128        .map_err(db)?;
1129    let rows = stmt
1130        .query_map([name], |row| {
1131            Ok((row.get::<_, i64>(0)?, row.get::<_, Vec<u8>>(1)?))
1132        })
1133        .map_err(db)?;
1134    let mut out = Vec::new();
1135    for row in rows {
1136        let (page, bytes) = row.map_err(db)?;
1137        let key = if page == 0 {
1138            PageKey::Header
1139        } else {
1140            PageKey::Node(to_id(page)?)
1141        };
1142        out.push((key, bytes));
1143    }
1144    Ok(out)
1145}
1146
1147/// Applies page changes to `index_page`. Input: a connection inside a
1148/// write transaction, the name and the changes. Output: `Ok`, or
1149/// `CoreError::Store` for a page key the store cannot map.
1150fn write_pages(conn: &Connection, name: &str, changes: Vec<PageChange>) -> Result<(), CoreError> {
1151    for change in changes {
1152        match change {
1153            PageChange::Put(key, bytes) => {
1154                conn.prepare_cached(
1155                    "INSERT INTO index_page (index_name, page, bytes) VALUES (?1, ?2, ?3) \
1156                     ON CONFLICT (index_name, page) DO UPDATE SET bytes = excluded.bytes",
1157                )
1158                .map_err(db)?
1159                .execute(params![name, page_number(key)?, bytes])
1160                .map_err(db)?;
1161            }
1162            PageChange::Delete(key) => {
1163                conn.prepare_cached("DELETE FROM index_page WHERE index_name = ?1 AND page = ?2")
1164                    .map_err(db)?
1165                    .execute(params![name, page_number(key)?])
1166                    .map_err(db)?;
1167            }
1168            _ => return Err(CoreError::Store("unknown index page change".into())),
1169        }
1170    }
1171    Ok(())
1172}
1173
1174/// Maps a page key to its `index_page.page` number: 0 for the header,
1175/// `n` for node `n`. Input: the key. Output: the number, or
1176/// `CoreError::Store` for node 0, a number past `i64` or an unknown key.
1177fn page_number(key: PageKey) -> Result<i64, CoreError> {
1178    match key {
1179        PageKey::Header => Ok(0),
1180        PageKey::Node(n) if n >= 1 => {
1181            i64::try_from(n).map_err(|_| CoreError::Store("page number out of range".into()))
1182        }
1183        _ => Err(CoreError::Store("unknown index page key".into())),
1184    }
1185}
1186
1187/// Writes or updates the rows of `records`: the chunk, its meta pairs
1188/// and its keyword row. An existing id keeps its key, so the index entry
1189/// is replaced in place. Input: a connection inside a write transaction.
1190/// Output: the index id of each record, in order.
1191fn write_rows(
1192    conn: &Connection,
1193    name: &str,
1194    records: &[VectorRecord],
1195) -> Result<Vec<u64>, CoreError> {
1196    let mut keys = Vec::with_capacity(records.len());
1197    for record in records {
1198        let meta_json = serde_json::to_string(&record.meta)
1199            .map_err(|e| CoreError::Store(format!("chunk meta: {e}")))?;
1200        let vector = encode(&record.vector);
1201        let old: Option<(i64, String)> = conn
1202            .prepare_cached("SELECT key, text FROM chunk WHERE index_name = ?1 AND id = ?2")
1203            .map_err(db)?
1204            .query_row(params![name, record.id], |row| {
1205                Ok((row.get(0)?, row.get(1)?))
1206            })
1207            .optional()
1208            .map_err(db)?;
1209        let key = match old {
1210            Some((key, old_text)) => {
1211                conn.prepare_cached(
1212                    "INSERT INTO chunk_fts (chunk_fts, rowid, text) VALUES ('delete', ?1, ?2)",
1213                )
1214                .map_err(db)?
1215                .execute(params![key, old_text])
1216                .map_err(db)?;
1217                conn.prepare_cached(
1218                    "UPDATE chunk SET text = ?2, meta_json = ?3, vector = ?4 WHERE key = ?1",
1219                )
1220                .map_err(db)?
1221                .execute(params![key, record.text, meta_json, vector])
1222                .map_err(db)?;
1223                conn.prepare_cached("DELETE FROM chunk_meta WHERE chunk_key = ?1")
1224                    .map_err(db)?
1225                    .execute([key])
1226                    .map_err(db)?;
1227                key
1228            }
1229            None => {
1230                conn.prepare_cached("INSERT INTO chunk (index_name, id, text, meta_json, vector) VALUES (?1, ?2, ?3, ?4, ?5)")
1231                    .map_err(db)?
1232                    .execute(params![name, record.id, record.text, meta_json, vector])
1233                    .map_err(db)?;
1234                conn.last_insert_rowid()
1235            }
1236        };
1237        assert!(key >= 1, "chunk keys start at 1");
1238        for (meta_key, value) in &record.meta {
1239            conn.prepare_cached(
1240                "INSERT INTO chunk_meta (chunk_key, key, value) VALUES (?1, ?2, ?3)",
1241            )
1242            .map_err(db)?
1243            .execute(params![key, meta_key, value])
1244            .map_err(db)?;
1245        }
1246        conn.prepare_cached("INSERT INTO chunk_fts (rowid, text) VALUES (?1, ?2)")
1247            .map_err(db)?
1248            .execute(params![key, record.text])
1249            .map_err(db)?;
1250        keys.push(to_id(key)?);
1251    }
1252    assert_eq!(keys.len(), records.len());
1253    Ok(keys)
1254}
1255
1256/// Deletes one chunk: its keyword row, meta pairs and row. `text` must
1257/// be the stored text, which the FTS5 `delete` command needs. Input: a
1258/// connection inside a write transaction. Output: `Ok`.
1259fn delete_row(conn: &Connection, key: i64, text: &str) -> Result<(), CoreError> {
1260    conn.prepare_cached("INSERT INTO chunk_fts (chunk_fts, rowid, text) VALUES ('delete', ?1, ?2)")
1261        .map_err(db)?
1262        .execute(params![key, text])
1263        .map_err(db)?;
1264    conn.prepare_cached("DELETE FROM chunk_meta WHERE chunk_key = ?1")
1265        .map_err(db)?
1266        .execute([key])
1267        .map_err(db)?;
1268    let deleted = conn
1269        .prepare_cached("DELETE FROM chunk WHERE key = ?1")
1270        .map_err(db)?
1271        .execute([key])
1272        .map_err(db)?;
1273    assert_eq!(deleted, 1, "deleted chunk exists");
1274    Ok(())
1275}
1276
1277/// Returns the keys of chunks of `name` whose meta has every pair.
1278/// Values are bound as parameters; only the pair count shapes the SQL.
1279/// Input: a connection, the name and at least one pair. Output: the keys.
1280fn allowed_keys(
1281    conn: &Connection,
1282    name: &str,
1283    pairs: &[(String, String)],
1284) -> Result<HashSet<u64>, CoreError> {
1285    assert!(!pairs.is_empty(), "an empty filter allows every key");
1286    let sql = format!(
1287        "SELECT key FROM chunk WHERE index_name = ?1{}",
1288        meta_clauses("key", pairs.len(), 2)
1289    );
1290    let mut values: Vec<&str> = vec![name];
1291    for (key, value) in pairs {
1292        values.push(key);
1293        values.push(value);
1294    }
1295    let mut stmt = conn.prepare(&sql).map_err(db)?;
1296    let rows = stmt
1297        .query_map(params_from_iter(values), |row| row.get::<_, i64>(0))
1298        .map_err(db)?;
1299    let mut out = HashSet::new();
1300    for row in rows {
1301        out.insert(to_id(row.map_err(db)?)?);
1302    }
1303    Ok(out)
1304}
1305
1306/// Builds one `AND <column> IN (...)` clause per filter pair, with the
1307/// key and value of pair `i` bound at `?first + 2i` and the next number.
1308/// Input: the key column, the pair count and the first parameter number.
1309/// Output: SQL text shaped by the count alone, never by a value.
1310fn meta_clauses(column: &str, pairs: usize, first: usize) -> String {
1311    let mut sql = String::new();
1312    for position in 0..pairs {
1313        let k = first + 2 * position;
1314        sql.push_str(&format!(
1315            " AND {column} IN (SELECT chunk_key FROM chunk_meta WHERE key = ?{k} AND value = ?{})",
1316            k + 1
1317        ));
1318    }
1319    sql
1320}
1321
1322/// Turns caller text into an FTS5 query of plain terms: split on every
1323/// non-alphanumeric char, lowercased, each term quoted, joined with `OR`.
1324/// No operator, column filter, prefix or `NEAR` survives. Input: the
1325/// text. Output: the terms and the query, empty when no term is left.
1326fn fts_query(text: &str) -> (Vec<String>, String) {
1327    let terms: Vec<String> = text
1328        .split(|c: char| !c.is_alphanumeric() && !is_combining_mark(c))
1329        .filter(|t| t.chars().any(char::is_alphanumeric))
1330        .map(str::to_lowercase)
1331        .collect();
1332    let quoted: Vec<String> = terms.iter().map(|t| format!("\"{}\"", t.replace('"', "\"\""))).collect();
1333    (terms, quoted.join(" OR "))
1334}
1335
1336/// Tells whether `c` is in a combining diacritical mark block, so a
1337/// decomposed `e` plus U+0301 stays one term and the unicode61 tokenizer
1338/// folds it like the composed form. Input: a char. Output: the answer.
1339fn is_combining_mark(c: char) -> bool {
1340    matches!(c, '\u{0300}'..='\u{036F}' | '\u{1AB0}'..='\u{1AFF}' | '\u{1DC0}'..='\u{1DFF}' | '\u{20D0}'..='\u{20FF}' | '\u{FE20}'..='\u{FE2F}')
1341}
1342
1343/// Reads the generation of index `name`. Input: a connection and the
1344/// name. Output: the generation, or `CoreError::Store` when the row is
1345/// gone.
1346fn read_generation(conn: &Connection, name: &str) -> Result<i64, CoreError> {
1347    conn.query_row(
1348        "SELECT generation FROM vector_index WHERE name = ?1",
1349        [name],
1350        |row| row.get(0),
1351    )
1352    .optional()
1353    .map_err(db)?
1354    .ok_or_else(|| CoreError::Store(format!("vector index {name} is missing")))
1355}
1356
1357/// Raises the generation of index `name` by one, so other connections
1358/// see the write. Input: a connection inside a write transaction.
1359/// Output: the new generation.
1360fn bump_generation(conn: &Connection, name: &str) -> Result<i64, CoreError> {
1361    let before = read_generation(conn, name)?;
1362    let updated = conn
1363        .execute(
1364            "UPDATE vector_index SET generation = generation + 1 WHERE name = ?1",
1365            [name],
1366        )
1367        .map_err(db)?;
1368    assert_eq!(updated, 1, "vector index row exists");
1369    let after = read_generation(conn, name)?;
1370    assert_eq!(after, before + 1, "generation rises by one");
1371    Ok(after)
1372}
1373
1374/// Reads the stored kind and params of index `name`. Input: a
1375/// connection and the name. Output: the kind, or `CoreError::Store` for
1376/// an unknown kind or params that do not parse.
1377fn stored_kind(conn: &Connection, name: &str) -> Result<IndexKind, CoreError> {
1378    let (kind, params): (String, String) = conn
1379        .query_row(
1380            "SELECT kind, params_json FROM vector_index WHERE name = ?1",
1381            [name],
1382            |row| Ok((row.get(0)?, row.get(1)?)),
1383        )
1384        .map_err(db)?;
1385    match kind.as_str() {
1386        KIND_BRUTE => Ok(IndexKind::BruteForce),
1387        KIND_HNSW => {
1388            let corrupt = || CoreError::Store(format!("corrupt store: hnsw params of {name}"));
1389            let value: serde_json::Value = serde_json::from_str(&params).map_err(|_| corrupt())?;
1390            let uint = |field: &str| {
1391                value
1392                    .get(field)
1393                    .and_then(serde_json::Value::as_u64)
1394                    .ok_or_else(corrupt)
1395            };
1396            let size =
1397                |field: &str| uint(field).and_then(|n| usize::try_from(n).map_err(|_| corrupt()));
1398            let fraction = value
1399                .get("max_deleted_fraction")
1400                .and_then(serde_json::Value::as_f64)
1401                .ok_or_else(corrupt)?;
1402            let params = HnswParams::default()
1403                .with_m(size("m")?)
1404                .with_ef_construction(size("ef_construction")?)
1405                .with_ef_search(size("ef_search")?)
1406                .with_seed(uint("seed")?)
1407                .with_max_deleted_fraction(fraction as f32);
1408            Ok(IndexKind::Hnsw(params))
1409        }
1410        _ => Err(CoreError::Store(format!(
1411            "corrupt store: unknown index kind of {name}"
1412        ))),
1413    }
1414}
1415
1416/// Returns the `vector_index.kind` text of a kind.
1417/// Input: the kind. Output: `brute_force` or `hnsw`, or
1418/// `CoreError::Store` for a kind this store does not know.
1419fn kind_name(kind: &IndexKind) -> Result<&'static str, CoreError> {
1420    match kind {
1421        IndexKind::BruteForce => Ok(KIND_BRUTE),
1422        IndexKind::Hnsw(_) => Ok(KIND_HNSW),
1423        _ => Err(CoreError::Store("unsupported index kind".into())),
1424    }
1425}
1426
1427/// Returns the `vector_index.params_json` text of a kind: `{}` for
1428/// brute force, the five HNSW params otherwise. The same kind always
1429/// gives the same text, so stored and wanted params compare as text.
1430fn params_json(kind: &IndexKind) -> Result<String, CoreError> {
1431    match kind {
1432        IndexKind::BruteForce => Ok(String::from("{}")),
1433        IndexKind::Hnsw(p) => Ok(serde_json::json!({
1434            "m": p.m(),
1435            "ef_construction": p.ef_construction(),
1436            "ef_search": p.ef_search(),
1437            "seed": p.seed(),
1438            "max_deleted_fraction": p.max_deleted_fraction(),
1439        })
1440        .to_string()),
1441        _ => Err(CoreError::Store("unsupported index kind".into())),
1442    }
1443}
1444
1445/// Maps an index error to a store error. A dimension mismatch keeps its
1446/// own `CoreError` variant; every other failure is `CoreError::Store`.
1447/// Input: the index error. Output: the core error.
1448fn index_err(e: IndexError) -> CoreError {
1449    match e {
1450        IndexError::DimensionMismatch { expected, actual } => {
1451            CoreError::DimensionMismatch { expected, actual }
1452        }
1453        other => CoreError::Store(format!("vector index: {other}")),
1454    }
1455}
1456
1457/// Checks an index name: 1 to 64 chars, each a lowercase ASCII letter,
1458/// a digit or `_`. Input: the name. Output: `Ok`, or `CoreError::Store`.
1459fn check_name(name: &str) -> Result<(), CoreError> {
1460    let ok = (1..=NAME_BYTES_MAX).contains(&name.len())
1461        && name
1462            .bytes()
1463            .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_');
1464    if ok {
1465        Ok(())
1466    } else {
1467        Err(CoreError::Store(format!(
1468            "vector index name must match [a-z0-9_]{{1,{NAME_BYTES_MAX}}}"
1469        )))
1470    }
1471}
1472
1473/// Checks settings: `dims` in `1..=MAX_DIMS` and every bound above 0.
1474/// Input: the settings. Output: `Ok`, or `CoreError::Store` naming the
1475/// first bad value.
1476fn check_settings(settings: &VectorSettings) -> Result<(), CoreError> {
1477    if settings.dims == 0 || settings.dims > MAX_DIMS {
1478        return Err(CoreError::Store(format!(
1479            "dims must be 1 to {MAX_DIMS}, got {}",
1480            settings.dims
1481        )));
1482    }
1483    for (field, value) in [
1484        ("max_text_bytes", settings.max_text_bytes),
1485        ("max_meta_pairs", settings.max_meta_pairs),
1486        ("max_meta_key_bytes", settings.max_meta_key_bytes),
1487        ("max_meta_value_bytes", settings.max_meta_value_bytes),
1488        ("max_batch", settings.max_batch),
1489        ("max_query_terms", settings.max_query_terms),
1490        ("max_query_chars", settings.max_query_chars),
1491    ] {
1492        if value == 0 {
1493            return Err(CoreError::Store(format!("{field} must be at least 1")));
1494        }
1495    }
1496    Ok(())
1497}
1498
1499/// Checks a scope and source used as meta values: not empty and within
1500/// `max_meta_value_bytes`. Input: both and the settings. Output: `Ok`,
1501/// or `CoreError::Store`.
1502fn check_source(scope: &str, source: &str, settings: &VectorSettings) -> Result<(), CoreError> {
1503    for (field, value) in [(SCOPE_KEY, scope), (SOURCE_KEY, source)] {
1504        if value.is_empty() || value.len() > settings.max_meta_value_bytes {
1505            return Err(CoreError::Store(format!(
1506                "{field} must be 1 to {} bytes",
1507                settings.max_meta_value_bytes
1508            )));
1509        }
1510    }
1511    Ok(())
1512}
1513
1514/// Checks a batch before anything is written: its size, and per record
1515/// the id length, dimension, finite components, text bytes and meta
1516/// bounds. Input: the records, settings and dims. Output: `Ok`, or the
1517/// first failure, naming the record position and never its text.
1518fn check_records(
1519    records: &[VectorRecord],
1520    settings: &VectorSettings,
1521    dims: usize,
1522) -> Result<(), CoreError> {
1523    if records.len() > settings.max_batch {
1524        return Err(CoreError::Store(format!(
1525            "batch of {} records, above max_batch {}",
1526            records.len(),
1527            settings.max_batch
1528        )));
1529    }
1530    for (position, record) in records.iter().enumerate() {
1531        if record.id.is_empty() || record.id.len() > ID_BYTES_MAX {
1532            return Err(CoreError::Store(format!(
1533                "record {position}: id must be 1 to {ID_BYTES_MAX} bytes"
1534            )));
1535        }
1536        if record.vector.len() != dims {
1537            return Err(CoreError::DimensionMismatch {
1538                expected: dims,
1539                actual: record.vector.len(),
1540            });
1541        }
1542        if record.vector.iter().any(|x| !x.is_finite()) {
1543            return Err(CoreError::Store(format!(
1544                "record {position}: vector has a non-finite component"
1545            )));
1546        }
1547        if record.text.len() > settings.max_text_bytes {
1548            return Err(CoreError::Store(format!(
1549                "record {position}: text is {} bytes, above max_text_bytes {}",
1550                record.text.len(),
1551                settings.max_text_bytes
1552            )));
1553        }
1554        if record.meta.len() > settings.max_meta_pairs {
1555            return Err(CoreError::Store(format!(
1556                "record {position}: {} meta pairs, above max_meta_pairs {}",
1557                record.meta.len(),
1558                settings.max_meta_pairs
1559            )));
1560        }
1561        for (key, value) in &record.meta {
1562            if key.is_empty() || key.len() > settings.max_meta_key_bytes {
1563                return Err(CoreError::Store(format!(
1564                    "record {position}: meta key must be 1 to {} bytes",
1565                    settings.max_meta_key_bytes
1566                )));
1567            }
1568            if value.len() > settings.max_meta_value_bytes {
1569                return Err(CoreError::Store(format!(
1570                    "record {position}: meta value above {} bytes",
1571                    settings.max_meta_value_bytes
1572                )));
1573            }
1574        }
1575    }
1576    Ok(())
1577}
1578
1579/// Encodes a vector as little-endian f32 bytes, `4 * len` long.
1580/// Input: the vector. Output: the bytes stored in `chunk.vector`.
1581/// The inverse of `decode`.
1582fn encode(vector: &[f32]) -> Vec<u8> {
1583    let bytes: Vec<u8> = vector.iter().flat_map(|x| x.to_le_bytes()).collect();
1584    assert_eq!(bytes.len(), vector.len() * 4);
1585    bytes
1586}
1587
1588/// Decodes a stored vector blob. Input: the bytes and the index dims.
1589/// Output: the vector, or `CoreError::Store` when the blob is not
1590/// `4 * dims` bytes. The inverse of `encode`.
1591fn decode(bytes: &[u8], dims: usize) -> Result<Vec<f32>, CoreError> {
1592    if bytes.len() != dims * 4 {
1593        return Err(CoreError::Store(format!(
1594            "corrupt store: vector of {} bytes, expected {}",
1595            bytes.len(),
1596            dims * 4
1597        )));
1598    }
1599    Ok(bytes.as_chunks::<4>().0.iter().map(|c| f32::from_le_bytes(*c)).collect())
1600}
1601
1602/// Converts a stored chunk key or page number to an index id.
1603/// Input: the stored value. Output: the id, or `CoreError::Store` for a
1604/// value below 1, which the schema never writes.
1605fn to_id(key: i64) -> Result<u64, CoreError> {
1606    match u64::try_from(key) {
1607        Ok(id) if id >= 1 => Ok(id),
1608        _ => Err(CoreError::Store(format!("corrupt store: key {key}"))),
1609    }
1610}
1611
1612/// Cuts `text` to at most `max` bytes on a char boundary.
1613/// Input: the text and the cap. Output: the longest prefix that fits.
1614/// Never splits a UTF-8 char.
1615fn cut_utf8(text: &str, max: usize) -> &str {
1616    if text.len() <= max {
1617        return text;
1618    }
1619    let mut end = max;
1620    while !text.is_char_boundary(end) {
1621        end -= 1;
1622    }
1623    &text[..end]
1624}
1625
1626#[cfg(test)]
1627mod tests {
1628    use super::*;
1629
1630    #[test]
1631    fn vector_bytes_round_trip() {
1632        let v = vec![0.0, -1.5, f32::MIN_POSITIVE, 3.25];
1633        assert_eq!(decode(&encode(&v), 4).unwrap(), v);
1634        assert!(decode(&encode(&v), 3).is_err());
1635    }
1636
1637    #[test]
1638    fn names_follow_the_pattern() {
1639        assert!(check_name("docs_2").is_ok());
1640        for bad in ["", "Docs", "a-b", "a b", "é", &"a".repeat(65)] {
1641            assert!(check_name(bad).is_err(), "{bad}");
1642        }
1643    }
1644
1645    #[test]
1646    fn hnsw_params_round_trip_through_json() {
1647        let kind = IndexKind::Hnsw(
1648            HnswParams::default()
1649                .with_m(8)
1650                .with_seed(u64::MAX)
1651                .with_max_deleted_fraction(0.3),
1652        );
1653        let conn = Connection::open_in_memory().unwrap();
1654        conn.execute_batch("CREATE TABLE vector_index (name TEXT, kind TEXT, params_json TEXT)")
1655            .unwrap();
1656        conn.execute(
1657            "INSERT INTO vector_index VALUES ('x', ?1, ?2)",
1658            params![kind_name(&kind).unwrap(), params_json(&kind).unwrap()],
1659        )
1660        .unwrap();
1661        assert_eq!(stored_kind(&conn, "x").unwrap(), kind);
1662    }
1663
1664    #[test]
1665    fn fts_query_quotes_plain_terms() {
1666        assert_eq!(fts_query("NEAR(a b)").1, "\"near\" OR \"a\" OR \"b\"");
1667        assert_eq!(
1668            fts_query("text:secret a*").1,
1669            "\"text\" OR \"secret\" OR \"a\""
1670        );
1671        assert_eq!(fts_query("\" ^ * ()").0.len(), 0);
1672        assert_eq!(fts_query("Café-au-lait").0, ["café", "au", "lait"]);
1673        assert_eq!(fts_query("Re\u{301}sume\u{301} x").0, ["re\u{301}sume\u{301}", "x"]);
1674        assert_eq!(fts_query("a \u{301} b").0, ["a", "b"]);
1675    }
1676
1677    #[test]
1678    fn cut_never_splits_a_char() {
1679        assert_eq!(cut_utf8("abc", 5), "abc");
1680        assert_eq!(cut_utf8("aé", 2), "a");
1681        assert_eq!(cut_utf8("aé", 3), "aé");
1682    }
1683}