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