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    /// Replaces every chunk of one source in one transaction: deletes
397    /// the old rows, keyword rows and index entries, writes `records` and
398    /// marks the source `done` with `content_hash`. Every record's meta
399    /// must carry `scope` and `source` equal to the arguments. Output: the
400    /// number of records written, or an error that writes nothing.
401    pub async fn replace_source(&self, scope: &str, source: &str, records: Vec<VectorRecord>, content_hash: &str) -> Result<usize, CoreError> {
402        let settings = read_cached(&self.state).settings.clone();
403        check_source(scope, source, &settings)?;
404        if content_hash.is_empty() || content_hash.len() > HASH_BYTES_MAX {
405            return Err(CoreError::Store(format!("content_hash must be 1 to {HASH_BYTES_MAX} bytes")));
406        }
407        check_records(&records, &settings, self.state.dims)?;
408        for (position, record) in records.iter().enumerate() {
409            let scope_ok = record.meta.get(SCOPE_KEY).map(String::as_str) == Some(scope);
410            let source_ok = record.meta.get(SOURCE_KEY).map(String::as_str) == Some(source);
411            if !scope_ok || !source_ok {
412                return Err(CoreError::Store(format!(
413                    "record {position} must carry meta {SCOPE_KEY} and {SOURCE_KEY} equal to the replaced source"
414                )));
415            }
416        }
417        let state = Arc::clone(&self.state);
418        let scope = scope.to_string();
419        let source = source.to_string();
420        let content_hash = content_hash.to_string();
421        let now_ms = self.store.inner.clock.now_ms();
422        self.store
423            .call(move |conn| {
424                let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate).map_err(db)?;
425                let mut cached = write_cached(&state);
426                reload_if_needed(&tx, &state, &mut cached)?;
427                cached.stale = true;
428                delete_source_rows(&tx, &state, &mut cached, &scope, &source)?;
429                {
430                    let mut owned = tx.prepare_cached("SELECT 1 FROM chunk WHERE index_name = ?1 AND id = ?2").map_err(db)?;
431                    for record in &records {
432                        if owned.exists(params![state.name, record.id]).map_err(db)? {
433                            return Err(CoreError::Store(format!("record id {} belongs to another source", cut_utf8(&record.id, 64))));
434                        }
435                    }
436                }
437                let keys = write_rows(&tx, &state.name, &records)?;
438                for (key, record) in keys.iter().zip(&records) {
439                    cached.index.insert(*key, &record.vector).map_err(index_err)?;
440                }
441                let changes = cached.index.take_changes();
442                write_pages(&tx, &state.name, changes)?;
443                tx.execute(
444                    "INSERT INTO ingest_source (index_name, scope, source, content_hash, chunks, status, error, at_ms) \
445                     VALUES (?1, ?2, ?3, ?4, ?5, 'done', NULL, ?6) \
446                     ON CONFLICT (index_name, scope, source) DO UPDATE SET \
447                     content_hash = excluded.content_hash, chunks = excluded.chunks, status = 'done', error = NULL, at_ms = excluded.at_ms",
448                    params![state.name, scope, source, content_hash, records.len() as i64, now_ms],
449                )
450                .map_err(db)?;
451                let generation = bump_generation(&tx, &state.name)?;
452                tx.commit().map_err(db)?;
453                cached.generation = generation;
454                cached.stale = false;
455                Ok(records.len())
456            })
457            .await
458    }
459
460    /// Lists every source of `scope` that has an ingest status row, done
461    /// or failed, sorted. Input: the scope. Output: the sources, so a
462    /// folder ingest can find the ones whose file is gone.
463    pub async fn sources(&self, scope: &str) -> Result<Vec<String>, CoreError> {
464        let state = Arc::clone(&self.state);
465        let scope = scope.to_string();
466        self.store
467            .call(move |conn| {
468                let mut stmt = conn
469                    .prepare("SELECT source FROM ingest_source WHERE index_name = ?1 AND scope = ?2 ORDER BY source")
470                    .map_err(db)?;
471                let rows = stmt.query_map(params![state.name, scope], |row| row.get(0)).map_err(db)?;
472                rows.collect::<Result<Vec<String>, _>>().map_err(db)
473            })
474            .await
475    }
476
477    /// Removes one source in one transaction: its chunk, meta and keyword
478    /// rows, its index entries and pages, and its ingest status row.
479    /// Input: the scope and source. Output: the chunks removed, 0 when
480    /// the source had none, or an error that removes nothing.
481    pub async fn remove_source(&self, scope: &str, source: &str) -> Result<usize, CoreError> {
482        let settings = read_cached(&self.state).settings.clone();
483        check_source(scope, source, &settings)?;
484        let state = Arc::clone(&self.state);
485        let scope = scope.to_string();
486        let source = source.to_string();
487        self.store
488            .call(move |conn| {
489                let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate).map_err(db)?;
490                let mut cached = write_cached(&state);
491                reload_if_needed(&tx, &state, &mut cached)?;
492                cached.stale = true;
493                let removed = delete_source_rows(&tx, &state, &mut cached, &scope, &source)?;
494                let changes = cached.index.take_changes();
495                write_pages(&tx, &state.name, changes)?;
496                tx.execute(
497                    "DELETE FROM ingest_source WHERE index_name = ?1 AND scope = ?2 AND source = ?3",
498                    params![state.name, scope, source],
499                )
500                .map_err(db)?;
501                let generation = bump_generation(&tx, &state.name)?;
502                tx.commit().map_err(db)?;
503                cached.generation = generation;
504                cached.stale = false;
505                Ok(removed)
506            })
507            .await
508    }
509
510    /// Returns the content hash of a source last replaced with success.
511    /// Input: the scope and source. Output: the hash, or `None` when the
512    /// source was never ingested or its last attempt failed.
513    pub async fn source_hash(&self, scope: &str, source: &str) -> Result<Option<String>, CoreError> {
514        let name = self.state.name.clone();
515        let scope = scope.to_string();
516        let source = source.to_string();
517        self.store
518            .call(move |conn| {
519                conn.query_row(
520                    "SELECT content_hash FROM ingest_source \
521                     WHERE index_name = ?1 AND scope = ?2 AND source = ?3 AND status = 'done'",
522                    params![name, scope, source],
523                    |row| row.get(0),
524                )
525                .optional()
526                .map_err(db)
527            })
528            .await
529    }
530
531    /// Records that ingesting a source failed, with the error cut to
532    /// 1 024 bytes. The source's chunks stay as they were, and
533    /// `source_hash` returns `None` so the next run retries it.
534    /// Output: `Ok`, or `CoreError::Store`.
535    pub async fn record_failed_source(&self, scope: &str, source: &str, error: &str) -> Result<(), CoreError> {
536        let settings = read_cached(&self.state).settings.clone();
537        check_source(scope, source, &settings)?;
538        let error = cut_utf8(error, ERROR_BYTES_MAX);
539        let error = if error.is_empty() { String::from("unknown error") } else { error.to_string() };
540        assert!(error.len() <= ERROR_BYTES_MAX, "error text over its cap");
541        let name = self.state.name.clone();
542        let scope = scope.to_string();
543        let source = source.to_string();
544        let now_ms = self.store.inner.clock.now_ms();
545        self.store
546            .call(move |conn| {
547                let chunks: i64 = conn
548                    .query_row(
549                        "SELECT chunks FROM ingest_source WHERE index_name = ?1 AND scope = ?2 AND source = ?3",
550                        params![name, scope, source],
551                        |row| row.get(0),
552                    )
553                    .optional()
554                    .map_err(db)?
555                    .unwrap_or(0);
556                let written = conn
557                    .execute(
558                        "INSERT INTO ingest_source (index_name, scope, source, content_hash, chunks, status, error, at_ms) \
559                         VALUES (?1, ?2, ?3, '', ?4, 'failed', ?5, ?6) \
560                         ON CONFLICT (index_name, scope, source) DO UPDATE SET \
561                         status = 'failed', error = excluded.error, at_ms = excluded.at_ms",
562                        params![name, scope, source, chunks, error, now_ms],
563                    )
564                    .map_err(db)?;
565                assert_eq!(written, 1);
566                Ok(())
567            })
568            .await
569    }
570}
571
572#[async_trait]
573impl VectorStore for SqliteVectors {
574    fn dims(&self) -> usize {
575        self.state.dims
576    }
577
578    async fn upsert(&self, records: Vec<VectorRecord>) -> Result<(), CoreError> {
579        let settings = read_cached(&self.state).settings.clone();
580        check_records(&records, &settings, self.state.dims)?;
581        if records.is_empty() {
582            return Ok(());
583        }
584        let state = Arc::clone(&self.state);
585        let mut span = trace_span!(Trace::Knowledge, "vectors.upsert", index = self.state.name.as_str(), records = records.len());
586        let result = span.instrument(self.store.call(move |conn| {
587            let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate).map_err(db)?;
588            let mut cached = write_cached(&state);
589            reload_if_needed(&tx, &state, &mut cached)?;
590            cached.stale = true;
591            let keys = write_rows(&tx, &state.name, &records)?;
592            for (key, record) in keys.iter().zip(&records) {
593                cached.index.insert(*key, &record.vector).map_err(index_err)?;
594            }
595            let changes = cached.index.take_changes();
596            write_pages(&tx, &state.name, changes)?;
597            let generation = bump_generation(&tx, &state.name)?;
598            tx.commit().map_err(db)?;
599            cached.generation = generation;
600            cached.stale = false;
601            Ok(())
602        }))
603        .await;
604        if let Err(e) = &result {
605            span.fail(e.to_string());
606        }
607        result
608    }
609
610    async fn search(&self, query: &[f32], k: usize, filter: &Filter) -> Result<Vec<Scored>, CoreError> {
611        if query.len() != self.state.dims {
612            return Err(CoreError::DimensionMismatch { expected: self.state.dims, actual: query.len() });
613        }
614        let settings = read_cached(&self.state).settings.clone();
615        if filter.0.len() > settings.max_meta_pairs {
616            return Err(CoreError::Store(format!(
617                "filter has {} pairs, above max_meta_pairs {}",
618                filter.0.len(),
619                settings.max_meta_pairs
620            )));
621        }
622        let state = Arc::clone(&self.state);
623        let query = query.to_vec();
624        let pairs: Vec<(String, String)> = filter.0.iter().map(|(k, v)| (k.clone(), v.clone())).collect();
625        self.store
626            .call(move |conn| {
627                for _ in 0..SNAPSHOT_TRIES {
628                    let tx = conn.transaction().map_err(db)?;
629                    let generation = read_generation(&tx, &state.name)?;
630                    let cached = read_cached(&state);
631                    if state.cached.is_poisoned() || cached.stale || cached.generation != generation {
632                        drop(cached);
633                        drop(tx);
634                        refresh(conn, &state)?;
635                        continue;
636                    }
637                    return search_snapshot(&tx, &state, &cached, &query, k, &pairs);
638                }
639                Err(CoreError::Store(format!("index changed under {SNAPSHOT_TRIES} searches in a row; try again")))
640            })
641            .await
642    }
643}
644
645/// Deletes every chunk of one source, with its meta and keyword rows,
646/// and removes the chunks from the cached index, inside the caller's
647/// write transaction. Input: the transaction, state, cache, scope and
648/// source. Output: the number of chunks deleted.
649fn delete_source_rows(tx: &Connection, state: &IndexState, cached: &mut Cached, scope: &str, source: &str) -> Result<usize, CoreError> {
650    assert!(cached.stale, "source rows change only under a stale cache");
651    let old: Vec<(i64, String)> = {
652        let mut stmt = tx
653            .prepare(
654                "SELECT c.key, c.text FROM chunk c \
655                 JOIN chunk_meta s ON s.chunk_key = c.key AND s.key = ?2 AND s.value = ?3 \
656                 JOIN chunk_meta o ON o.chunk_key = c.key AND o.key = ?4 AND o.value = ?5 \
657                 WHERE c.index_name = ?1 ORDER BY c.key",
658            )
659            .map_err(db)?;
660        let rows = stmt
661            .query_map(params![state.name, SCOPE_KEY, scope, SOURCE_KEY, source], |row| Ok((row.get(0)?, row.get(1)?)))
662            .map_err(db)?;
663        rows.collect::<Result<_, _>>().map_err(db)?
664    };
665    for (key, text) in &old {
666        delete_row(tx, *key, text)?;
667        cached.index.remove(to_id(*key)?);
668    }
669    Ok(old.len())
670}
671
672/// Searches the cached index and reads the hits inside one read
673/// transaction whose generation matches the cache, so a hit's score and
674/// its text come from the same committed version. Input: the open
675/// transaction, the state, its matching cache, query, k and filter pairs.
676fn search_snapshot(tx: &rusqlite::Transaction<'_>, state: &IndexState, cached: &Cached, query: &[f32], k: usize, pairs: &[(String, String)]) -> Result<Vec<Scored>, CoreError> {
677    let allowed = if pairs.is_empty() { None } else { Some(allowed_keys(tx, &state.name, pairs)?) };
678    if allowed.as_ref().is_some_and(HashSet::is_empty) {
679        return Ok(Vec::new());
680    }
681    let neighbors = {
682        let allow_fn = |id: u64| allowed.as_ref().is_none_or(|set| set.contains(&id));
683        let allow: Option<&dyn Fn(u64) -> bool> = if allowed.is_some() { Some(&allow_fn) } else { None };
684        cached.index.search(query, k, allow).map_err(index_err)?
685    };
686    let mut stmt = tx
687        .prepare_cached("SELECT id, text, meta_json FROM chunk WHERE key = ?1 AND index_name = ?2")
688        .map_err(db)?;
689    let mut hits = Vec::with_capacity(neighbors.len());
690    for neighbor in &neighbors {
691        let key = i64::try_from(neighbor.id).map_err(|_| CoreError::Store("index id out of range".into()))?;
692        let row: Option<(String, String, String)> = stmt
693            .query_row(params![key, state.name], |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)))
694            .optional()
695            .map_err(db)?;
696        let Some((id, text, meta_json)) = row else {
697            continue;
698        };
699        let meta: BTreeMap<String, String> =
700            serde_json::from_str(&meta_json).map_err(|e| CoreError::Store(format!("corrupt store: chunk meta: {e}")))?;
701        hits.push(Scored { id, score: neighbor.score, text, meta });
702    }
703    assert!(hits.len() <= k, "search returned more than k hits");
704    Ok(hits)
705}
706
707#[async_trait]
708impl KeywordStore for SqliteVectors {
709    async fn search_text(&self, query: &str, k: usize, filter: &Filter) -> Result<Vec<Scored>, CoreError> {
710        let settings = read_cached(&self.state).settings.clone();
711        let chars = query.chars().count();
712        if chars > settings.max_query_chars {
713            return Err(CoreError::Store(format!("query is {chars} chars, above max_query_chars {}", settings.max_query_chars)));
714        }
715        if k > MAX_K {
716            return Err(CoreError::Store(format!("k must be at most {MAX_K}, got {k}")));
717        }
718        if filter.0.len() > settings.max_meta_pairs {
719            return Err(CoreError::Store(format!(
720                "filter has {} pairs, above max_meta_pairs {}",
721                filter.0.len(),
722                settings.max_meta_pairs
723            )));
724        }
725        let (terms, fts) = fts_query(query);
726        if terms.len() > settings.max_query_terms {
727            return Err(CoreError::Store(format!(
728                "query has {} terms, above max_query_terms {}",
729                terms.len(),
730                settings.max_query_terms
731            )));
732        }
733        if terms.is_empty() || k == 0 {
734            return Ok(Vec::new());
735        }
736        let name = self.state.name.clone();
737        let pairs: Vec<(String, String)> = filter.0.iter().map(|(k, v)| (k.clone(), v.clone())).collect();
738        self.store
739            .call(move |conn| {
740                let limit = 3 + 2 * pairs.len();
741                let sql = format!(
742                    "SELECT c.id, c.text, c.meta_json, -bm25(chunk_fts) AS score \
743                     FROM chunk_fts JOIN chunk c ON c.key = chunk_fts.rowid \
744                     WHERE chunk_fts MATCH ?1 AND c.index_name = ?2{} \
745                     ORDER BY score DESC, c.id ASC LIMIT ?{limit}",
746                    meta_clauses("c.key", pairs.len(), 3)
747                );
748                let mut values: Vec<rusqlite::types::Value> = vec![fts.into(), name.into()];
749                for (key, value) in pairs {
750                    values.push(key.into());
751                    values.push(value.into());
752                }
753                values.push((k as i64).into());
754                let mut stmt = conn.prepare(&sql).map_err(db)?;
755                let rows = stmt
756                    .query_map(params_from_iter(values), |row| {
757                        Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?, row.get::<_, String>(2)?, row.get::<_, f64>(3)?))
758                    })
759                    .map_err(db)?;
760                let mut hits = Vec::new();
761                for row in rows {
762                    let (id, text, meta_json, score) = row.map_err(db)?;
763                    let meta: BTreeMap<String, String> =
764                        serde_json::from_str(&meta_json).map_err(|e| CoreError::Store(format!("corrupt store: chunk meta: {e}")))?;
765                    hits.push(Scored { id, score: score as f32, text, meta });
766                }
767                assert!(hits.len() <= k, "keyword search returned more than k hits");
768                assert!(hits.windows(2).all(|w| w[0].score >= w[1].score), "keyword hits sorted by score");
769                Ok(hits)
770            })
771            .await
772    }
773}
774
775/// Takes the write lock of a cached index. A lock poisoned by a panic
776/// mid-update is taken anyway and marked stale, so the next step reloads
777/// it from the file. Output: the guard.
778fn write_cached(state: &IndexState) -> RwLockWriteGuard<'_, Cached> {
779    match state.cached.write() {
780        Ok(guard) => guard,
781        Err(poisoned) => {
782            let mut guard = poisoned.into_inner();
783            guard.stale = true;
784            state.cached.clear_poison();
785            guard
786        }
787    }
788}
789
790/// Takes the read lock of a cached index, poisoned or not. Callers
791/// that search first run `refresh`, which reloads a poisoned index.
792/// Output: the guard.
793fn read_cached(state: &IndexState) -> RwLockReadGuard<'_, Cached> {
794    match state.cached.read() {
795        Ok(guard) => guard,
796        Err(poisoned) => poisoned.into_inner(),
797    }
798}
799
800/// Reloads the index when another connection wrote since it was loaded,
801/// or when it is stale or poisoned. Input: the connection, outside any
802/// transaction. Output: `Ok` once memory matches the file.
803fn refresh(conn: &mut Connection, state: &IndexState) -> Result<(), CoreError> {
804    let generation = read_generation(conn, &state.name)?;
805    if !state.cached.is_poisoned() {
806        let cached = read_cached(state);
807        if cached.generation == generation && !cached.stale {
808            return Ok(());
809        }
810    }
811    let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate).map_err(db)?;
812    let mut cached = write_cached(state);
813    reload_if_needed(&tx, state, &mut cached)?;
814    tx.commit().map_err(db)?;
815    Ok(())
816}
817
818/// Loads the index from the file when its generation differs from the
819/// cached one or the cache is stale. Pages refused as corrupt are
820/// rebuilt from vectors and rewritten. Input: a connection inside a
821/// write transaction. Output: `Ok` with `cached` fresh.
822fn reload_if_needed(conn: &Connection, state: &IndexState, cached: &mut Cached) -> Result<(), CoreError> {
823    let generation = read_generation(conn, &state.name)?;
824    if cached.generation == generation && !cached.stale {
825        return Ok(());
826    }
827    let kind = stored_kind(conn, &state.name)?;
828    let mut index = new_index(&kind, state.dims, cached.settings.quantization).map_err(index_err)?;
829    let vectors = load_vectors(conn, &state.name, state.dims)?;
830    let pages = load_pages(conn, &state.name)?;
831    let rebuilt = match index.restore(&mut vectors.into_iter(), &mut pages.into_iter()) {
832        Ok(()) => {
833            index.take_changes();
834            false
835        }
836        Err(IndexError::CorruptPage(_)) => {
837            index = build_from_file(conn, &kind, state.dims, cached.settings.quantization, &state.name)?;
838            true
839        }
840        Err(e) => return Err(index_err(e)),
841    };
842    if rebuilt {
843        conn.execute("DELETE FROM index_page WHERE index_name = ?1", [&state.name]).map_err(db)?;
844        let changes = index.take_changes();
845        write_pages(conn, &state.name, changes)?;
846        cached.report.rebuilds += 1;
847    }
848    cached.index = index;
849    cached.generation = generation;
850    cached.stale = false;
851    cached.report.loads += 1;
852    Ok(())
853}
854
855/// Rebuilds the index under the kind in `cached.settings`, rewrites all
856/// pages and stores the new kind, all in the caller's transaction. The
857/// cache stays stale: the caller publishes the generation after commit.
858/// Input: a connection inside a write transaction. Output: the new generation.
859fn rebuild_kind(conn: &Connection, state: &IndexState, cached: &mut Cached) -> Result<i64, CoreError> {
860    let kind = cached.settings.kind.clone();
861    let index = build_from_file(conn, &kind, state.dims, cached.settings.quantization, &state.name)?;
862    conn.execute(
863        "UPDATE vector_index SET kind = ?2, params_json = ?3 WHERE name = ?1",
864        params![state.name, kind_name(&kind)?, params_json(&kind)?],
865    )
866    .map_err(db)?;
867    cached.index = index;
868    conn.execute("DELETE FROM index_page WHERE index_name = ?1", [&state.name]).map_err(db)?;
869    let changes = cached.index.take_changes();
870    write_pages(conn, &state.name, changes)?;
871    let generation = bump_generation(conn, &state.name)?;
872    assert!(cached.stale, "a rebuilt index stays stale until its commit");
873    cached.report.loads += 1;
874    Ok(generation)
875}
876
877/// Builds a fresh index by inserting every stored vector of `name`.
878/// Input: the connection, kind, dims, format and name. Output: the index
879/// with its page changes not yet taken.
880fn build_from_file(conn: &Connection, kind: &IndexKind, dims: usize, quantization: Quantization, name: &str) -> Result<Box<dyn VectorIndex>, CoreError> {
881    let mut index = new_index(kind, dims, quantization).map_err(index_err)?;
882    for (id, vector) in load_vectors(conn, name, dims)? {
883        index.insert(id, &vector).map_err(index_err)?;
884    }
885    Ok(index)
886}
887
888/// Reads every stored vector of `name` in key order, checking each blob
889/// is `4 * dims` bytes. Input: the connection, name and dims. Output:
890/// pairs of index id and vector, or `CoreError::Store` on a bad blob.
891fn load_vectors(conn: &Connection, name: &str, dims: usize) -> Result<Vec<(u64, Vec<f32>)>, CoreError> {
892    let mut stmt = conn.prepare("SELECT key, vector FROM chunk WHERE index_name = ?1 ORDER BY key").map_err(db)?;
893    let rows = stmt.query_map([name], |row| Ok((row.get::<_, i64>(0)?, row.get::<_, Vec<u8>>(1)?))).map_err(db)?;
894    let mut out = Vec::new();
895    for row in rows {
896        let (key, bytes) = row.map_err(db)?;
897        out.push((to_id(key)?, decode(&bytes, dims)?));
898    }
899    Ok(out)
900}
901
902/// Reads every stored page of `name` in page order. Page 0 is the
903/// header and page `n >= 1` is node `n`. Input: the connection and the
904/// name. Output: the pages, or `CoreError::Store`.
905fn load_pages(conn: &Connection, name: &str) -> Result<Vec<(PageKey, Vec<u8>)>, CoreError> {
906    let mut stmt = conn.prepare("SELECT page, bytes FROM index_page WHERE index_name = ?1 ORDER BY page").map_err(db)?;
907    let rows = stmt.query_map([name], |row| Ok((row.get::<_, i64>(0)?, row.get::<_, Vec<u8>>(1)?))).map_err(db)?;
908    let mut out = Vec::new();
909    for row in rows {
910        let (page, bytes) = row.map_err(db)?;
911        let key = if page == 0 { PageKey::Header } else { PageKey::Node(to_id(page)?) };
912        out.push((key, bytes));
913    }
914    Ok(out)
915}
916
917/// Applies page changes to `index_page`. Input: a connection inside a
918/// write transaction, the name and the changes. Output: `Ok`, or
919/// `CoreError::Store` for a page key the store cannot map.
920fn write_pages(conn: &Connection, name: &str, changes: Vec<PageChange>) -> Result<(), CoreError> {
921    for change in changes {
922        match change {
923            PageChange::Put(key, bytes) => {
924                conn.prepare_cached(
925                    "INSERT INTO index_page (index_name, page, bytes) VALUES (?1, ?2, ?3) \
926                     ON CONFLICT (index_name, page) DO UPDATE SET bytes = excluded.bytes",
927                )
928                .map_err(db)?
929                .execute(params![name, page_number(key)?, bytes])
930                .map_err(db)?;
931            }
932            PageChange::Delete(key) => {
933                conn.prepare_cached("DELETE FROM index_page WHERE index_name = ?1 AND page = ?2")
934                    .map_err(db)?
935                    .execute(params![name, page_number(key)?])
936                    .map_err(db)?;
937            }
938            _ => return Err(CoreError::Store("unknown index page change".into())),
939        }
940    }
941    Ok(())
942}
943
944/// Maps a page key to its `index_page.page` number: 0 for the header,
945/// `n` for node `n`. Input: the key. Output: the number, or
946/// `CoreError::Store` for node 0, a number past `i64` or an unknown key.
947fn page_number(key: PageKey) -> Result<i64, CoreError> {
948    match key {
949        PageKey::Header => Ok(0),
950        PageKey::Node(n) if n >= 1 => i64::try_from(n).map_err(|_| CoreError::Store("page number out of range".into())),
951        _ => Err(CoreError::Store("unknown index page key".into())),
952    }
953}
954
955/// Writes or updates the rows of `records`: the chunk, its meta pairs
956/// and its keyword row. An existing id keeps its key, so the index entry
957/// is replaced in place. Input: a connection inside a write transaction.
958/// Output: the index id of each record, in order.
959fn write_rows(conn: &Connection, name: &str, records: &[VectorRecord]) -> Result<Vec<u64>, CoreError> {
960    let mut keys = Vec::with_capacity(records.len());
961    for record in records {
962        let meta_json = serde_json::to_string(&record.meta).map_err(|e| CoreError::Store(format!("chunk meta: {e}")))?;
963        let vector = encode(&record.vector);
964        let old: Option<(i64, String)> = conn
965            .prepare_cached("SELECT key, text FROM chunk WHERE index_name = ?1 AND id = ?2")
966            .map_err(db)?
967            .query_row(params![name, record.id], |row| Ok((row.get(0)?, row.get(1)?)))
968            .optional()
969            .map_err(db)?;
970        let key = match old {
971            Some((key, old_text)) => {
972                conn.prepare_cached("INSERT INTO chunk_fts (chunk_fts, rowid, text) VALUES ('delete', ?1, ?2)")
973                    .map_err(db)?
974                    .execute(params![key, old_text])
975                    .map_err(db)?;
976                conn.prepare_cached("UPDATE chunk SET text = ?2, meta_json = ?3, vector = ?4 WHERE key = ?1")
977                    .map_err(db)?
978                    .execute(params![key, record.text, meta_json, vector])
979                    .map_err(db)?;
980                conn.prepare_cached("DELETE FROM chunk_meta WHERE chunk_key = ?1")
981                    .map_err(db)?
982                    .execute([key])
983                    .map_err(db)?;
984                key
985            }
986            None => {
987                conn.prepare_cached("INSERT INTO chunk (index_name, id, text, meta_json, vector) VALUES (?1, ?2, ?3, ?4, ?5)")
988                    .map_err(db)?
989                    .execute(params![name, record.id, record.text, meta_json, vector])
990                    .map_err(db)?;
991                conn.last_insert_rowid()
992            }
993        };
994        assert!(key >= 1, "chunk keys start at 1");
995        for (meta_key, value) in &record.meta {
996            conn.prepare_cached("INSERT INTO chunk_meta (chunk_key, key, value) VALUES (?1, ?2, ?3)")
997                .map_err(db)?
998                .execute(params![key, meta_key, value])
999                .map_err(db)?;
1000        }
1001        conn.prepare_cached("INSERT INTO chunk_fts (rowid, text) VALUES (?1, ?2)")
1002            .map_err(db)?
1003            .execute(params![key, record.text])
1004            .map_err(db)?;
1005        keys.push(to_id(key)?);
1006    }
1007    assert_eq!(keys.len(), records.len());
1008    Ok(keys)
1009}
1010
1011/// Deletes one chunk: its keyword row, meta pairs and row. `text` must
1012/// be the stored text, which the FTS5 `delete` command needs. Input: a
1013/// connection inside a write transaction. Output: `Ok`.
1014fn delete_row(conn: &Connection, key: i64, text: &str) -> Result<(), CoreError> {
1015    conn.prepare_cached("INSERT INTO chunk_fts (chunk_fts, rowid, text) VALUES ('delete', ?1, ?2)")
1016        .map_err(db)?
1017        .execute(params![key, text])
1018        .map_err(db)?;
1019    conn.prepare_cached("DELETE FROM chunk_meta WHERE chunk_key = ?1").map_err(db)?.execute([key]).map_err(db)?;
1020    let deleted = conn.prepare_cached("DELETE FROM chunk WHERE key = ?1").map_err(db)?.execute([key]).map_err(db)?;
1021    assert_eq!(deleted, 1, "deleted chunk exists");
1022    Ok(())
1023}
1024
1025/// Returns the keys of chunks of `name` whose meta has every pair.
1026/// Values are bound as parameters; only the pair count shapes the SQL.
1027/// Input: a connection, the name and at least one pair. Output: the keys.
1028fn allowed_keys(conn: &Connection, name: &str, pairs: &[(String, String)]) -> Result<HashSet<u64>, CoreError> {
1029    assert!(!pairs.is_empty(), "an empty filter allows every key");
1030    let sql = format!("SELECT key FROM chunk WHERE index_name = ?1{}", meta_clauses("key", pairs.len(), 2));
1031    let mut values: Vec<&str> = vec![name];
1032    for (key, value) in pairs {
1033        values.push(key);
1034        values.push(value);
1035    }
1036    let mut stmt = conn.prepare(&sql).map_err(db)?;
1037    let rows = stmt.query_map(params_from_iter(values), |row| row.get::<_, i64>(0)).map_err(db)?;
1038    let mut out = HashSet::new();
1039    for row in rows {
1040        out.insert(to_id(row.map_err(db)?)?);
1041    }
1042    Ok(out)
1043}
1044
1045/// Builds one `AND <column> IN (...)` clause per filter pair, with the
1046/// key and value of pair `i` bound at `?first + 2i` and the next number.
1047/// Input: the key column, the pair count and the first parameter number.
1048/// Output: SQL text shaped by the count alone, never by a value.
1049fn meta_clauses(column: &str, pairs: usize, first: usize) -> String {
1050    let mut sql = String::new();
1051    for position in 0..pairs {
1052        let k = first + 2 * position;
1053        sql.push_str(&format!(" AND {column} IN (SELECT chunk_key FROM chunk_meta WHERE key = ?{k} AND value = ?{})", k + 1));
1054    }
1055    sql
1056}
1057
1058/// Turns caller text into an FTS5 query of plain terms: split on every
1059/// non-alphanumeric char, lowercased, each term quoted, joined with `OR`.
1060/// No operator, column filter, prefix or `NEAR` survives. Input: the
1061/// text. Output: the terms and the query, empty when no term is left.
1062fn fts_query(text: &str) -> (Vec<String>, String) {
1063    let terms: Vec<String> = text.split(|c: char| !c.is_alphanumeric()).filter(|t| !t.is_empty()).map(str::to_lowercase).collect();
1064    let quoted: Vec<String> = terms.iter().map(|t| format!("\"{}\"", t.replace('"', "\"\""))).collect();
1065    (terms, quoted.join(" OR "))
1066}
1067
1068/// Reads the generation of index `name`. Input: a connection and the
1069/// name. Output: the generation, or `CoreError::Store` when the row is
1070/// gone.
1071fn read_generation(conn: &Connection, name: &str) -> Result<i64, CoreError> {
1072    conn.query_row("SELECT generation FROM vector_index WHERE name = ?1", [name], |row| row.get(0))
1073        .optional()
1074        .map_err(db)?
1075        .ok_or_else(|| CoreError::Store(format!("vector index {name} is missing")))
1076}
1077
1078/// Raises the generation of index `name` by one, so other connections
1079/// see the write. Input: a connection inside a write transaction.
1080/// Output: the new generation.
1081fn bump_generation(conn: &Connection, name: &str) -> Result<i64, CoreError> {
1082    let before = read_generation(conn, name)?;
1083    let updated = conn.execute("UPDATE vector_index SET generation = generation + 1 WHERE name = ?1", [name]).map_err(db)?;
1084    assert_eq!(updated, 1, "vector index row exists");
1085    let after = read_generation(conn, name)?;
1086    assert_eq!(after, before + 1, "generation rises by one");
1087    Ok(after)
1088}
1089
1090/// Reads the stored kind and params of index `name`. Input: a
1091/// connection and the name. Output: the kind, or `CoreError::Store` for
1092/// an unknown kind or params that do not parse.
1093fn stored_kind(conn: &Connection, name: &str) -> Result<IndexKind, CoreError> {
1094    let (kind, params): (String, String) = conn
1095        .query_row("SELECT kind, params_json FROM vector_index WHERE name = ?1", [name], |row| Ok((row.get(0)?, row.get(1)?)))
1096        .map_err(db)?;
1097    match kind.as_str() {
1098        KIND_BRUTE => Ok(IndexKind::BruteForce),
1099        KIND_HNSW => {
1100            let corrupt = || CoreError::Store(format!("corrupt store: hnsw params of {name}"));
1101            let value: serde_json::Value = serde_json::from_str(&params).map_err(|_| corrupt())?;
1102            let uint = |field: &str| value.get(field).and_then(serde_json::Value::as_u64).ok_or_else(corrupt);
1103            let size = |field: &str| uint(field).and_then(|n| usize::try_from(n).map_err(|_| corrupt()));
1104            let fraction = value.get("max_deleted_fraction").and_then(serde_json::Value::as_f64).ok_or_else(corrupt)?;
1105            let params = HnswParams::default()
1106                .with_m(size("m")?)
1107                .with_ef_construction(size("ef_construction")?)
1108                .with_ef_search(size("ef_search")?)
1109                .with_seed(uint("seed")?)
1110                .with_max_deleted_fraction(fraction as f32);
1111            Ok(IndexKind::Hnsw(params))
1112        }
1113        _ => Err(CoreError::Store(format!("corrupt store: unknown index kind of {name}"))),
1114    }
1115}
1116
1117/// Returns the `vector_index.kind` text of a kind.
1118/// Input: the kind. Output: `brute_force` or `hnsw`, or
1119/// `CoreError::Store` for a kind this store does not know.
1120fn kind_name(kind: &IndexKind) -> Result<&'static str, CoreError> {
1121    match kind {
1122        IndexKind::BruteForce => Ok(KIND_BRUTE),
1123        IndexKind::Hnsw(_) => Ok(KIND_HNSW),
1124        _ => Err(CoreError::Store("unsupported index kind".into())),
1125    }
1126}
1127
1128/// Returns the `vector_index.params_json` text of a kind: `{}` for
1129/// brute force, the five HNSW params otherwise. The same kind always
1130/// gives the same text, so stored and wanted params compare as text.
1131fn params_json(kind: &IndexKind) -> Result<String, CoreError> {
1132    match kind {
1133        IndexKind::BruteForce => Ok(String::from("{}")),
1134        IndexKind::Hnsw(p) => Ok(serde_json::json!({
1135            "m": p.m(),
1136            "ef_construction": p.ef_construction(),
1137            "ef_search": p.ef_search(),
1138            "seed": p.seed(),
1139            "max_deleted_fraction": p.max_deleted_fraction(),
1140        })
1141        .to_string()),
1142        _ => Err(CoreError::Store("unsupported index kind".into())),
1143    }
1144}
1145
1146/// Maps an index error to a store error. A dimension mismatch keeps its
1147/// own `CoreError` variant; every other failure is `CoreError::Store`.
1148/// Input: the index error. Output: the core error.
1149fn index_err(e: IndexError) -> CoreError {
1150    match e {
1151        IndexError::DimensionMismatch { expected, actual } => CoreError::DimensionMismatch { expected, actual },
1152        other => CoreError::Store(format!("vector index: {other}")),
1153    }
1154}
1155
1156/// Checks an index name: 1 to 64 chars, each a lowercase ASCII letter,
1157/// a digit or `_`. Input: the name. Output: `Ok`, or `CoreError::Store`.
1158fn check_name(name: &str) -> Result<(), CoreError> {
1159    let ok = (1..=NAME_BYTES_MAX).contains(&name.len()) && name.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_');
1160    if ok {
1161        Ok(())
1162    } else {
1163        Err(CoreError::Store(format!("vector index name must match [a-z0-9_]{{1,{NAME_BYTES_MAX}}}")))
1164    }
1165}
1166
1167/// Checks settings: `dims` in `1..=MAX_DIMS` and every bound above 0.
1168/// Input: the settings. Output: `Ok`, or `CoreError::Store` naming the
1169/// first bad value.
1170fn check_settings(settings: &VectorSettings) -> Result<(), CoreError> {
1171    if settings.dims == 0 || settings.dims > MAX_DIMS {
1172        return Err(CoreError::Store(format!("dims must be 1 to {MAX_DIMS}, got {}", settings.dims)));
1173    }
1174    for (field, value) in [
1175        ("max_text_bytes", settings.max_text_bytes),
1176        ("max_meta_pairs", settings.max_meta_pairs),
1177        ("max_meta_key_bytes", settings.max_meta_key_bytes),
1178        ("max_meta_value_bytes", settings.max_meta_value_bytes),
1179        ("max_batch", settings.max_batch),
1180        ("max_query_terms", settings.max_query_terms),
1181        ("max_query_chars", settings.max_query_chars),
1182    ] {
1183        if value == 0 {
1184            return Err(CoreError::Store(format!("{field} must be at least 1")));
1185        }
1186    }
1187    Ok(())
1188}
1189
1190/// Checks a scope and source used as meta values: not empty and within
1191/// `max_meta_value_bytes`. Input: both and the settings. Output: `Ok`,
1192/// or `CoreError::Store`.
1193fn check_source(scope: &str, source: &str, settings: &VectorSettings) -> Result<(), CoreError> {
1194    for (field, value) in [(SCOPE_KEY, scope), (SOURCE_KEY, source)] {
1195        if value.is_empty() || value.len() > settings.max_meta_value_bytes {
1196            return Err(CoreError::Store(format!("{field} must be 1 to {} bytes", settings.max_meta_value_bytes)));
1197        }
1198    }
1199    Ok(())
1200}
1201
1202/// Checks a batch before anything is written: its size, and per record
1203/// the id length, dimension, finite components, text bytes and meta
1204/// bounds. Input: the records, settings and dims. Output: `Ok`, or the
1205/// first failure, naming the record position and never its text.
1206fn check_records(records: &[VectorRecord], settings: &VectorSettings, dims: usize) -> Result<(), CoreError> {
1207    if records.len() > settings.max_batch {
1208        return Err(CoreError::Store(format!("batch of {} records, above max_batch {}", records.len(), settings.max_batch)));
1209    }
1210    for (position, record) in records.iter().enumerate() {
1211        if record.id.is_empty() || record.id.len() > ID_BYTES_MAX {
1212            return Err(CoreError::Store(format!("record {position}: id must be 1 to {ID_BYTES_MAX} bytes")));
1213        }
1214        if record.vector.len() != dims {
1215            return Err(CoreError::DimensionMismatch { expected: dims, actual: record.vector.len() });
1216        }
1217        if record.vector.iter().any(|x| !x.is_finite()) {
1218            return Err(CoreError::Store(format!("record {position}: vector has a non-finite component")));
1219        }
1220        if record.text.len() > settings.max_text_bytes {
1221            return Err(CoreError::Store(format!(
1222                "record {position}: text is {} bytes, above max_text_bytes {}",
1223                record.text.len(),
1224                settings.max_text_bytes
1225            )));
1226        }
1227        if record.meta.len() > settings.max_meta_pairs {
1228            return Err(CoreError::Store(format!(
1229                "record {position}: {} meta pairs, above max_meta_pairs {}",
1230                record.meta.len(),
1231                settings.max_meta_pairs
1232            )));
1233        }
1234        for (key, value) in &record.meta {
1235            if key.is_empty() || key.len() > settings.max_meta_key_bytes {
1236                return Err(CoreError::Store(format!("record {position}: meta key must be 1 to {} bytes", settings.max_meta_key_bytes)));
1237            }
1238            if value.len() > settings.max_meta_value_bytes {
1239                return Err(CoreError::Store(format!("record {position}: meta value above {} bytes", settings.max_meta_value_bytes)));
1240            }
1241        }
1242    }
1243    Ok(())
1244}
1245
1246/// Encodes a vector as little-endian f32 bytes, `4 * len` long.
1247/// Input: the vector. Output: the bytes stored in `chunk.vector`.
1248/// The inverse of `decode`.
1249fn encode(vector: &[f32]) -> Vec<u8> {
1250    let bytes: Vec<u8> = vector.iter().flat_map(|x| x.to_le_bytes()).collect();
1251    assert_eq!(bytes.len(), vector.len() * 4);
1252    bytes
1253}
1254
1255/// Decodes a stored vector blob. Input: the bytes and the index dims.
1256/// Output: the vector, or `CoreError::Store` when the blob is not
1257/// `4 * dims` bytes. The inverse of `encode`.
1258fn decode(bytes: &[u8], dims: usize) -> Result<Vec<f32>, CoreError> {
1259    if bytes.len() != dims * 4 {
1260        return Err(CoreError::Store(format!("corrupt store: vector of {} bytes, expected {}", bytes.len(), dims * 4)));
1261    }
1262    Ok(bytes.chunks_exact(4).map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])).collect())
1263}
1264
1265/// Converts a stored chunk key or page number to an index id.
1266/// Input: the stored value. Output: the id, or `CoreError::Store` for a
1267/// value below 1, which the schema never writes.
1268fn to_id(key: i64) -> Result<u64, CoreError> {
1269    match u64::try_from(key) {
1270        Ok(id) if id >= 1 => Ok(id),
1271        _ => Err(CoreError::Store(format!("corrupt store: key {key}"))),
1272    }
1273}
1274
1275/// Cuts `text` to at most `max` bytes on a char boundary.
1276/// Input: the text and the cap. Output: the longest prefix that fits.
1277/// Never splits a UTF-8 char.
1278fn cut_utf8(text: &str, max: usize) -> &str {
1279    if text.len() <= max {
1280        return text;
1281    }
1282    let mut end = max;
1283    while !text.is_char_boundary(end) {
1284        end -= 1;
1285    }
1286    &text[..end]
1287}
1288
1289#[cfg(test)]
1290mod tests {
1291    use super::*;
1292
1293    #[test]
1294    fn vector_bytes_round_trip() {
1295        let v = vec![0.0, -1.5, f32::MIN_POSITIVE, 3.25];
1296        assert_eq!(decode(&encode(&v), 4).unwrap(), v);
1297        assert!(decode(&encode(&v), 3).is_err());
1298    }
1299
1300    #[test]
1301    fn names_follow_the_pattern() {
1302        assert!(check_name("docs_2").is_ok());
1303        for bad in ["", "Docs", "a-b", "a b", "é", &"a".repeat(65)] {
1304            assert!(check_name(bad).is_err(), "{bad}");
1305        }
1306    }
1307
1308    #[test]
1309    fn hnsw_params_round_trip_through_json() {
1310        let kind = IndexKind::Hnsw(HnswParams::default().with_m(8).with_seed(u64::MAX).with_max_deleted_fraction(0.3));
1311        let conn = Connection::open_in_memory().unwrap();
1312        conn.execute_batch("CREATE TABLE vector_index (name TEXT, kind TEXT, params_json TEXT)").unwrap();
1313        conn.execute("INSERT INTO vector_index VALUES ('x', ?1, ?2)", params![kind_name(&kind).unwrap(), params_json(&kind).unwrap()])
1314            .unwrap();
1315        assert_eq!(stored_kind(&conn, "x").unwrap(), kind);
1316    }
1317
1318    #[test]
1319    fn fts_query_quotes_plain_terms() {
1320        assert_eq!(fts_query("NEAR(a b)").1, "\"near\" OR \"a\" OR \"b\"");
1321        assert_eq!(fts_query("text:secret a*").1, "\"text\" OR \"secret\" OR \"a\"");
1322        assert_eq!(fts_query("\" ^ * ()").0.len(), 0);
1323        assert_eq!(fts_query("Café-au-lait").0, ["café", "au", "lait"]);
1324    }
1325
1326    #[test]
1327    fn cut_never_splits_a_char() {
1328        assert_eq!(cut_utf8("abc", 5), "abc");
1329        assert_eq!(cut_utf8("aé", 2), "a");
1330        assert_eq!(cut_utf8("aé", 3), "aé");
1331    }
1332}