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