Skip to main content

troupekit_store_sqlite/
lib.rs

1//! SQLite storage for Troupekit. One `SqliteStore` over one file implements
2//! `CheckpointStore`, `MemoryLog`, `BlobStore`, `JobQueue` and `UsageLedger`,
3//! so a run survives a process kill and resumes from its last saved step.
4//! `SqliteStore::vectors` opens named vector indexes in the same file.
5
6#![doc(
7    html_logo_url = "https://raw.githubusercontent.com/ChaoticQubit/troupekit/main/assets/brand/logo-mark.svg",
8    html_favicon_url = "https://raw.githubusercontent.com/ChaoticQubit/troupekit/main/assets/brand/favicon.svg"
9)]
10
11mod queue;
12mod schema;
13mod stores;
14mod vectors;
15
16use rusqlite::config::DbConfig;
17use rusqlite::{Connection, OpenFlags};
18use std::collections::HashMap;
19use std::path::{Path, PathBuf};
20use std::sync::{Arc, Mutex};
21use std::time::Duration;
22use troupekit_core::clock::{Clock, SystemClock};
23use troupekit_core::error::CoreError;
24#[cfg(any(feature = "sqlcipher", feature = "sqlcipher-system"))]
25use troupekit_core::secret::Secret;
26pub use troupekit_index::{HnswParams, IndexKind, Quantization};
27pub use vectors::{OpenReport, SqliteVectors, VectorSettings};
28
29/// The schema version this troupekit writes and reads up to.
30/// It equals the number of migration steps. A file at a higher version is
31/// refused, a file at a lower one is migrated on open.
32pub const SCHEMA_VERSION: u32 = schema::STEPS.len() as u32;
33
34const _: () = assert!(SCHEMA_VERSION > 0);
35
36const BYTES_LIMIT_SQLITE: u64 = 1_000_000_000;
37const STATE_BYTES_MAX_DEFAULT: u64 = 64 * 1024 * 1024;
38const BLOB_BYTES_MAX_DEFAULT: u64 = 64 * 1024 * 1024;
39const HISTORY_STEPS_MAX_DEFAULT: u64 = 100_000;
40const BUSY_TIMEOUT_MS_DEFAULT: u32 = 5_000;
41
42/// How hard a commit is pushed to disk, per connection. `Full` survives
43/// power loss: every commit uses `fullfsync`, which Apple platforms need.
44/// `Normal` is faster and can lose the last commits on power loss, never on
45/// a process kill; WAL checkpoints still use `fullfsync`, so no corruption.
46#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
47#[non_exhaustive]
48pub enum Durability {
49    #[default]
50    Full,
51    Normal,
52}
53
54#[derive(Debug, Clone, Copy, PartialEq, Eq)]
55pub(crate) struct Limits {
56    pub(crate) state_bytes_max: u64,
57    pub(crate) blob_bytes_max: u64,
58    pub(crate) history_steps_max: u64,
59}
60
61/// Settings for `SqliteStore`, each with a safe default: full durability,
62/// the system clock, 64 MiB caps on one state and one blob, 100 000 history
63/// steps, a 5 000 ms busy timeout and secure delete on. `open` validates
64/// them and opens the file.
65#[derive(Clone)]
66pub struct SqliteStoreBuilder {
67    path: PathBuf,
68    durability: Durability,
69    clock: Arc<dyn Clock>,
70    limits: Limits,
71    busy_timeout_ms: u32,
72    secure_delete: bool,
73    #[cfg(any(feature = "sqlcipher", feature = "sqlcipher-system"))]
74    key: Option<Secret>,
75}
76
77impl std::fmt::Debug for SqliteStoreBuilder {
78    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
79        f.debug_struct("SqliteStoreBuilder")
80            .field("path", &self.path)
81            .field("durability", &self.durability)
82            .field("limits", &self.limits)
83            .field("busy_timeout_ms", &self.busy_timeout_ms)
84            .field("secure_delete", &self.secure_delete)
85            .finish_non_exhaustive()
86    }
87}
88
89impl SqliteStoreBuilder {
90    /// Sets how hard commits are pushed to disk.
91    /// Input: the level. Output: the builder. Default `Durability::Full`.
92    pub fn durability(mut self, durability: Durability) -> Self {
93        self.durability = durability;
94        self
95    }
96
97    /// Sets the time source of the job queue. Share it with the runner's io
98    /// so leases and due times agree. Input: the clock. Output: the builder.
99    /// Default `SystemClock`.
100    pub fn clock(mut self, clock: Arc<dyn Clock>) -> Self {
101        self.clock = clock;
102        self
103    }
104
105    /// Sets the largest serialized checkpoint state `save` accepts, in bytes.
106    /// Input: 1 to 1 000 000 000. Output: the builder. Default 64 MiB.
107    pub fn max_state_bytes(mut self, bytes: u64) -> Self {
108        self.limits.state_bytes_max = bytes;
109        self
110    }
111
112    /// Sets the largest blob `put` accepts, in bytes.
113    /// Input: 1 to 1 000 000 000. Output: the builder. Default 64 MiB.
114    pub fn max_blob_bytes(mut self, bytes: u64) -> Self {
115        self.limits.blob_bytes_max = bytes;
116        self
117    }
118
119    /// Sets the most kept steps `history` returns before it errors.
120    /// Input: at least 1. Output: the builder. Default 100 000.
121    pub fn max_history_steps(mut self, steps: u64) -> Self {
122        self.limits.history_steps_max = steps;
123        self
124    }
125
126    /// Sets how long a writer waits for another handle's lock, in ms.
127    /// Input: any value, 0 fails at once. Output: the builder. Default 5 000.
128    pub fn busy_timeout_ms(mut self, ms: u32) -> Self {
129        self.busy_timeout_ms = ms;
130        self
131    }
132
133    /// Sets whether deleted rows are overwritten: SQLite `secure_delete` on
134    /// the connection and FTS5 `secure-delete` on the keyword index, so a
135    /// removed chunk's text and vector leave the file. Cost: every delete
136    /// writes zeros over freed space, more disk writes and slower deletes.
137    /// Input: on or off. Output: the builder. Default on.
138    pub fn secure_delete(mut self, on: bool) -> Self {
139        self.secure_delete = on;
140        self
141    }
142
143    /// Opens the file encrypted with SQLCipher under `key`. The key is sent
144    /// first on the connection and never appears in `Debug` or an error.
145    /// Input: the key. Output: the builder. Default: no key, plain file.
146    #[cfg(any(feature = "sqlcipher", feature = "sqlcipher-system"))]
147    pub fn key(mut self, key: Secret) -> Self {
148        self.key = Some(key);
149        self
150    }
151
152    /// Validates the settings, creates the file when missing, refuses a
153    /// foreign or newer file and migrates an older one. Needs a tokio
154    /// runtime. Output: the store, or `CoreError::Store`.
155    pub async fn open(self) -> Result<SqliteStore, CoreError> {
156        validate(&self.limits)?;
157        let settings = self.clone();
158        let conn = tokio::task::spawn_blocking(move || open_connection(&settings))
159            .await
160            .unwrap_or_else(join_failed)?;
161        Ok(SqliteStore {
162            inner: Arc::new(Inner {
163                conn: Mutex::new(conn),
164                clock: self.clock,
165                limits: self.limits,
166                path: self.path,
167                secure_delete: self.secure_delete,
168                vectors: Mutex::new(HashMap::new()),
169            }),
170        })
171    }
172}
173
174fn validate(limits: &Limits) -> Result<(), CoreError> {
175    for (name, value) in [
176        ("max_state_bytes", limits.state_bytes_max),
177        ("max_blob_bytes", limits.blob_bytes_max),
178    ] {
179        if value == 0 || value > BYTES_LIMIT_SQLITE {
180            return Err(CoreError::Store(format!(
181                "{name} must be 1 to {BYTES_LIMIT_SQLITE}, got {value}"
182            )));
183        }
184    }
185    if limits.history_steps_max == 0 {
186        return Err(CoreError::Store(
187            "max_history_steps must be at least 1".into(),
188        ));
189    }
190    Ok(())
191}
192
193/// Creates the store file when it does not exist yet, so the read-write
194/// open that follows finds it on every platform. On Unix the new file is
195/// 0600. Input: the path. Output: `Ok` when it created the file or found
196/// an entry there, `CoreError::Store` when it cannot be created.
197fn create_private(path: &Path) -> Result<(), CoreError> {
198    if path.exists() {
199        return Ok(());
200    }
201    let mut options = std::fs::OpenOptions::new();
202    options.write(true).create_new(true);
203    #[cfg(unix)]
204    std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
205    options.open(path).map(drop).or_else(|e| match e.kind() {
206        std::io::ErrorKind::AlreadyExists => Ok(()),
207        _ => Err(CoreError::Store(format!("cannot create store: {e}"))),
208    })
209}
210
211fn open_connection(settings: &SqliteStoreBuilder) -> Result<Connection, CoreError> {
212    create_private(&settings.path)?;
213    let flags = OpenFlags::SQLITE_OPEN_READ_WRITE | OpenFlags::SQLITE_OPEN_NO_MUTEX;
214    let mut conn = Connection::open_with_flags(&settings.path, flags)
215        .map_err(|e| CoreError::Store(format!("cannot open store: {e}")))?;
216    #[cfg(any(feature = "sqlcipher", feature = "sqlcipher-system"))]
217    if let Some(key) = &settings.key {
218        conn.pragma_update(None, "key", key.expose())
219            .map_err(|_| wrong_key())?;
220    }
221    conn.query_row("SELECT COUNT(*) FROM sqlite_schema", [], |row| {
222        row.get::<_, i64>(0)
223    })
224    .map_err(|e| match e.sqlite_error_code() {
225        Some(rusqlite::ErrorCode::NotADatabase) => wrong_key(),
226        _ => db(e),
227    })?;
228    conn.busy_timeout(Duration::from_millis(u64::from(settings.busy_timeout_ms)))
229        .map_err(db)?;
230    schema::check_header(schema::read_header(&conn)?, SCHEMA_VERSION)?;
231    let mode: String = conn
232        .pragma_update_and_check(None, "journal_mode", "WAL", |row| row.get(0))
233        .map_err(db)?;
234    if !mode.eq_ignore_ascii_case("wal") {
235        return Err(CoreError::Store(format!(
236            "store cannot use WAL, got {mode}"
237        )));
238    }
239    let (synchronous, fullfsync) = match settings.durability {
240        Durability::Full => ("FULL", true),
241        Durability::Normal => ("NORMAL", false),
242    };
243    let checkpoint_fullfsync = true;
244    conn.pragma_update(None, "synchronous", synchronous)
245        .map_err(db)?;
246    conn.pragma_update(None, "fullfsync", fullfsync)
247        .map_err(db)?;
248    conn.pragma_update(None, "checkpoint_fullfsync", checkpoint_fullfsync)
249        .map_err(db)?;
250    conn.pragma_update(None, "trusted_schema", "OFF")
251        .map_err(db)?;
252    conn.pragma_update(None, "secure_delete", settings.secure_delete)
253        .map_err(db)?;
254    conn.set_db_config(DbConfig::SQLITE_DBCONFIG_DEFENSIVE, true)
255        .map_err(db)?;
256    let version = schema::migrate(&mut conn, schema::STEPS)?;
257    assert_eq!(version, SCHEMA_VERSION);
258    assert_eq!(schema::read_header(&conn)?.user_version, SCHEMA_VERSION);
259    Ok(conn)
260}
261
262fn wrong_key() -> CoreError {
263    CoreError::Store("cannot open store: wrong key or not a database".into())
264}
265
266/// Maps a rusqlite error to `CoreError::Store`. The text names what failed
267/// and never holds a bound value, so state, blob bytes and keys stay out.
268/// Input: the error. Output: the store error.
269pub(crate) fn db(e: rusqlite::Error) -> CoreError {
270    CoreError::Store(format!("sqlite: {e}"))
271}
272
273fn join_failed<T>(e: tokio::task::JoinError) -> Result<T, CoreError> {
274    if e.is_panic() {
275        std::panic::resume_unwind(e.into_panic());
276    }
277    Err(CoreError::Store(format!("store task did not finish: {e}")))
278}
279
280struct Inner {
281    conn: Mutex<Connection>,
282    clock: Arc<dyn Clock>,
283    limits: Limits,
284    path: PathBuf,
285    secure_delete: bool,
286    vectors: Mutex<HashMap<String, Arc<vectors::IndexState>>>,
287}
288
289/// Durable Troupekit store over one SQLite file in WAL mode. Cheap to
290/// clone; clones share one connection. Every call runs on tokio's blocking
291/// pool, so it needs a tokio runtime. A caller that stops waiting does not
292/// stop the call: it runs to its commit or rollback.
293#[derive(Clone)]
294pub struct SqliteStore {
295    inner: Arc<Inner>,
296}
297
298impl std::fmt::Debug for SqliteStore {
299    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
300        f.debug_struct("SqliteStore")
301            .field("path", &self.inner.path)
302            .field("limits", &self.inner.limits)
303            .finish_non_exhaustive()
304    }
305}
306
307impl SqliteStore {
308    /// Starts a builder for the file at `path` with every setting at its
309    /// default. Input: the file path. Output: the builder; nothing is
310    /// opened until `open`.
311    pub fn builder(path: impl AsRef<Path>) -> SqliteStoreBuilder {
312        SqliteStoreBuilder {
313            path: path.as_ref().to_path_buf(),
314            durability: Durability::Full,
315            clock: Arc::new(SystemClock),
316            limits: Limits {
317                state_bytes_max: STATE_BYTES_MAX_DEFAULT,
318                blob_bytes_max: BLOB_BYTES_MAX_DEFAULT,
319                history_steps_max: HISTORY_STEPS_MAX_DEFAULT,
320            },
321            busy_timeout_ms: BUSY_TIMEOUT_MS_DEFAULT,
322            secure_delete: true,
323            #[cfg(any(feature = "sqlcipher", feature = "sqlcipher-system"))]
324            key: None,
325        }
326    }
327
328    /// Opens the file at `path` with every setting at its default.
329    /// Same as `SqliteStore::builder(path).open()`.
330    /// Output: the store, or `CoreError::Store`.
331    pub async fn open(path: impl AsRef<Path>) -> Result<SqliteStore, CoreError> {
332        Self::builder(path).open().await
333    }
334
335    pub(crate) fn limits(&self) -> Limits {
336        self.inner.limits
337    }
338
339    /// Runs `f` with the locked connection on the blocking pool. A panic in
340    /// `f` reaches the caller; a transaction guard open in `f` rolls back as
341    /// it unwinds. A poisoned lock is taken and any open transaction is
342    /// rolled back first. Output: what `f` returns.
343    pub(crate) async fn call<T, F>(&self, f: F) -> Result<T, CoreError>
344    where
345        T: Send + 'static,
346        F: FnOnce(&mut Connection) -> Result<T, CoreError> + Send + 'static,
347    {
348        let inner = Arc::clone(&self.inner);
349        let scope = troupekit_trace::current();
350        tokio::task::spawn_blocking(move || match scope {
351            Some(scope) => scope.enter(|| run_locked(&inner, f)),
352            None => run_locked(&inner, f),
353        })
354        .await
355        .unwrap_or_else(|e| join_failed(e))
356    }
357}
358
359/// Runs `f` on the locked connection of `inner`, on the calling thread.
360/// A poisoned lock is taken and any open transaction is rolled back first.
361/// Input: the shared state and the work. Output: what `f` returns.
362fn run_locked<T, F>(inner: &Inner, f: F) -> Result<T, CoreError>
363where
364    F: FnOnce(&mut Connection) -> Result<T, CoreError>,
365{
366    let mut conn = match inner.conn.lock() {
367        Ok(conn) => conn,
368        Err(poisoned) => {
369            let conn = poisoned.into_inner();
370            if !conn.is_autocommit() {
371                conn.execute_batch("ROLLBACK").map_err(db)?;
372            }
373            inner.conn.clear_poison();
374            conn
375        }
376    };
377    assert!(
378        conn.is_autocommit(),
379        "a store call starts outside a transaction"
380    );
381    let out = f(&mut conn);
382    assert!(conn.is_autocommit(), "a store call left a transaction open");
383    out
384}
385
386#[cfg(test)]
387mod tests {
388    use super::*;
389    use rusqlite::TransactionBehavior;
390
391    async fn temp_store(
392        builder: impl FnOnce(SqliteStoreBuilder) -> SqliteStoreBuilder,
393    ) -> (tempfile::TempDir, SqliteStore) {
394        let dir = tempfile::tempdir().unwrap();
395        let store = builder(SqliteStore::builder(dir.path().join("t.db")))
396            .open()
397            .await
398            .unwrap();
399        (dir, store)
400    }
401
402    async fn pragma(store: &SqliteStore, name: &'static str) -> i64 {
403        store
404            .call(move |conn| {
405                conn.pragma_query_value(None, name, |row| row.get(0))
406                    .map_err(db)
407            })
408            .await
409            .unwrap()
410    }
411
412    #[tokio::test]
413    async fn defaults_are_the_safe_values() {
414        let builder = SqliteStore::builder("unused.db");
415        assert_eq!(builder.durability, Durability::Full);
416        assert_eq!(builder.limits.state_bytes_max, 64 * 1024 * 1024);
417        assert_eq!(builder.limits.blob_bytes_max, 64 * 1024 * 1024);
418        assert_eq!(builder.limits.history_steps_max, 100_000);
419        assert_eq!(builder.busy_timeout_ms, 5_000);
420        assert!(builder.secure_delete);
421        let before = SystemClock.now_ms();
422        assert!(builder.clock.now_ms() >= before);
423        let (_dir, store) = temp_store(|b| b).await;
424        assert_eq!(pragma(&store, "synchronous").await, 2);
425        assert_eq!(pragma(&store, "fullfsync").await, 1);
426        assert_eq!(pragma(&store, "checkpoint_fullfsync").await, 1);
427        assert_eq!(pragma(&store, "busy_timeout").await, 5_000);
428        assert_eq!(pragma(&store, "trusted_schema").await, 0);
429        assert_eq!(pragma(&store, "secure_delete").await, 1);
430    }
431
432    #[tokio::test]
433    async fn secure_delete_off_reaches_the_connection() {
434        let (_dir, store) = temp_store(|b| b.secure_delete(false)).await;
435        assert_eq!(pragma(&store, "secure_delete").await, 0);
436    }
437
438    #[tokio::test]
439    async fn durability_normal_sets_synchronous_normal() {
440        let (_dir, store) = temp_store(|b| b.durability(Durability::Normal)).await;
441        assert_eq!(pragma(&store, "synchronous").await, 1);
442        assert_eq!(pragma(&store, "fullfsync").await, 0);
443        assert_eq!(pragma(&store, "checkpoint_fullfsync").await, 1);
444    }
445
446    #[tokio::test]
447    async fn busy_timeout_setting_reaches_the_connection() {
448        let (_dir, store) = temp_store(|b| b.busy_timeout_ms(1234)).await;
449        assert_eq!(pragma(&store, "busy_timeout").await, 1234);
450    }
451
452    #[tokio::test]
453    async fn zero_cap_is_refused() {
454        let dir = tempfile::tempdir().unwrap();
455        let path = dir.path().join("t.db");
456        for builder in [
457            SqliteStore::builder(&path).max_state_bytes(0),
458            SqliteStore::builder(&path).max_blob_bytes(0),
459            SqliteStore::builder(&path).max_history_steps(0),
460        ] {
461            let err = builder.open().await.unwrap_err();
462            assert!(matches!(err, CoreError::Store(_)), "{err:?}");
463        }
464        assert!(!path.exists());
465    }
466
467    #[tokio::test]
468    async fn cap_above_sqlite_limit_is_refused() {
469        let dir = tempfile::tempdir().unwrap();
470        let path = dir.path().join("t.db");
471        for builder in [
472            SqliteStore::builder(&path).max_state_bytes(1_000_000_001),
473            SqliteStore::builder(&path).max_blob_bytes(1_000_000_001),
474        ] {
475            let err = builder.open().await.unwrap_err();
476            assert!(
477                matches!(&err, CoreError::Store(m) if m.contains("1000000000")),
478                "{err:?}"
479            );
480        }
481        assert!(SqliteStore::builder(&path)
482            .max_blob_bytes(1_000_000_000)
483            .open()
484            .await
485            .is_ok());
486    }
487
488    #[tokio::test]
489    async fn panic_in_a_store_call_reaches_the_caller() {
490        let (_dir, store) = temp_store(|b| b).await;
491        let task = tokio::spawn(async move {
492            store
493                .call(|_conn| -> Result<(), CoreError> { panic!("boom in call") })
494                .await
495        });
496        let err = task.await.unwrap_err();
497        assert!(err.is_panic());
498        let payload = err.into_panic();
499        assert_eq!(payload.downcast_ref::<&str>(), Some(&"boom in call"));
500    }
501
502    #[tokio::test]
503    async fn panic_inside_a_transaction_rolls_it_back() {
504        let (_dir, store) = temp_store(|b| b).await;
505        let clone = store.clone();
506        let task = tokio::spawn(async move {
507            clone
508                .call(|conn| -> Result<(), CoreError> {
509                    let tx = conn
510                        .transaction_with_behavior(TransactionBehavior::Immediate)
511                        .unwrap();
512                    tx.execute(
513                        "INSERT INTO blob_entry (path, bytes) VALUES ('p', x'01')",
514                        [],
515                    )
516                    .unwrap();
517                    panic!("boom in transaction")
518                })
519                .await
520        });
521        assert!(task.await.unwrap_err().is_panic());
522        let rows: i64 = store
523            .call(|conn| {
524                conn.query_row("SELECT COUNT(*) FROM blob_entry", [], |r| r.get(0))
525                    .map_err(db)
526            })
527            .await
528            .unwrap();
529        assert_eq!(rows, 0);
530    }
531
532    #[tokio::test]
533    async fn store_stays_usable_after_a_panicked_call() {
534        let (_dir, store) = temp_store(|b| b).await;
535        let clone = store.clone();
536        let task = tokio::spawn(async move {
537            clone
538                .call(|_conn| -> Result<(), CoreError> { panic!("boom") })
539                .await
540        });
541        assert!(task.await.unwrap_err().is_panic());
542        assert!(store.inner.conn.is_poisoned());
543        let written = store
544            .call(|conn| {
545                conn.execute(
546                    "INSERT INTO blob_entry (path, bytes) VALUES ('q', x'02')",
547                    [],
548                )
549                .map_err(db)
550            })
551            .await
552            .unwrap();
553        assert_eq!(written, 1);
554        assert_eq!(pragma(&store, "user_version").await, i64::from(SCHEMA_VERSION));
555    }
556}
557