Skip to main content

briefcase_core/storage/
sqlite.rs

1#[cfg(feature = "async")]
2use super::{FlushResult, StorageBackend};
3use super::{SnapshotQuery, StorageError};
4use crate::models::{DecisionSnapshot, Snapshot, SnapshotType};
5use rusqlite::{params, Connection, OptionalExtension};
6use serde_json;
7use std::path::Path;
8use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
9use std::time::Duration;
10#[cfg(feature = "async")]
11use tokio::task;
12
13#[derive(Debug, Clone, PartialEq)]
14pub enum CompressionType {
15    None,
16    Gzip,
17}
18
19/// How long a statement waits on a lock held by another connection before
20/// failing with SQLITE_BUSY.
21const BUSY_TIMEOUT: Duration = Duration::from_secs(5);
22
23/// Format of the `created_at` column. Fixed-width UTC, so string comparison
24/// in SQL orders rows chronologically; every write and every range bound must
25/// go through [`format_created_at`].
26const CREATED_AT_FORMAT: &str = "%Y-%m-%d %H:%M:%S%.3f";
27
28pub(crate) fn format_created_at(timestamp: &chrono::DateTime<chrono::Utc>) -> String {
29    timestamp.format(CREATED_AT_FORMAT).to_string()
30}
31
32/// Schema migrations, applied in order. `PRAGMA user_version` records how many
33/// have run, so each runs exactly once per database; append new ones at the
34/// end and never edit or reorder an entry that has shipped.
35const MIGRATIONS: &[&str] = &[
36    // v1: batch writes used to store `created_at` as RFC 3339 while single
37    // writes and range queries used CREATED_AT_FORMAT, so batch-written rows
38    // fell outside every time-range query. Rewrite them to the one format.
39    r#"UPDATE snapshots
40       SET created_at = strftime('%Y-%m-%d %H:%M:%f', created_at)
41       WHERE created_at LIKE '%T%'
42         AND strftime('%Y-%m-%d %H:%M:%f', created_at) IS NOT NULL"#,
43    // v2: tables for the opt-in hash-chained mode (`chain` feature). Empty
44    // and unused unless a handle opts in, so plain databases behave exactly
45    // as before. The triggers stop ordinary UPDATE/DELETE statements; they
46    // are a guard against accidents, not against someone who can drop them
47    // (that is what `verify` is for).
48    r#"CREATE TABLE IF NOT EXISTS chain_entries (
49           seq INTEGER PRIMARY KEY,
50           record_id TEXT NOT NULL UNIQUE,
51           kind TEXT NOT NULL,
52           hash_scheme TEXT NOT NULL,
53           record_json TEXT NOT NULL,
54           record_hash TEXT NOT NULL,
55           prev_hash TEXT NOT NULL UNIQUE,
56           entry_hash TEXT NOT NULL,
57           recorded_at TEXT NOT NULL
58       );
59       CREATE TABLE IF NOT EXISTS chain_checkpoints (
60           checkpoint_no INTEGER PRIMARY KEY,
61           from_seq INTEGER NOT NULL,
62           seq INTEGER NOT NULL,
63           head_hash TEXT NOT NULL,
64           merkle_root TEXT NOT NULL,
65           prev_checkpoint_hash TEXT NOT NULL,
66           created_at TEXT NOT NULL,
67           hash_scheme TEXT NOT NULL,
68           key_id TEXT,
69           public_key TEXT,
70           signature TEXT,
71           checkpoint_hash TEXT NOT NULL
72       );
73       CREATE TABLE IF NOT EXISTS chain_meta (
74           key TEXT PRIMARY KEY,
75           value TEXT NOT NULL
76       );
77       CREATE TRIGGER IF NOT EXISTS chain_entries_no_update
78           BEFORE UPDATE ON chain_entries
79           BEGIN SELECT RAISE(ABORT, 'chain_entries is append-only'); END;
80       CREATE TRIGGER IF NOT EXISTS chain_entries_no_delete
81           BEFORE DELETE ON chain_entries
82           BEGIN SELECT RAISE(ABORT, 'chain_entries is append-only'); END;
83       CREATE TRIGGER IF NOT EXISTS chain_checkpoints_no_update
84           BEFORE UPDATE ON chain_checkpoints
85           BEGIN SELECT RAISE(ABORT, 'chain_checkpoints is append-only'); END;
86       CREATE TRIGGER IF NOT EXISTS chain_checkpoints_no_delete
87           BEFORE DELETE ON chain_checkpoints
88           BEGIN SELECT RAISE(ABORT, 'chain_checkpoints is append-only'); END;"#,
89];
90
91pub struct SqliteBackend {
92    pub conn: Arc<Mutex<Connection>>,
93    /// See [`SqliteBackend::with_append_only`].
94    pub(crate) append_only: bool,
95    /// Set by [`SqliteBackend::with_chain`].
96    #[cfg(feature = "chain")]
97    pub(crate) chain: Option<Arc<super::chain::ChainConfig>>,
98}
99
100/// The two write statements. `INSERT OR REPLACE` is the default and lets a
101/// save overwrite the row holding the same id; a plain `INSERT` fails on the
102/// primary key instead, which append-only mode turns into
103/// [`StorageError::AlreadyExists`].
104const UPSERT_SQL: &str = r#"
105            INSERT OR REPLACE INTO snapshots (
106                id, snapshot_type, data_json, created_at, created_by, checksum
107            ) VALUES (?, ?, ?, ?, ?, ?)
108            "#;
109pub(crate) const INSERT_ONLY_SQL: &str = r#"
110            INSERT INTO snapshots (
111                id, snapshot_type, data_json, created_at, created_by, checksum
112            ) VALUES (?, ?, ?, ?, ?, ?)
113            "#;
114
115/// Map a failed write. A primary-key conflict can only happen under the plain
116/// `INSERT` of append-only mode, and it means the id is already stored.
117pub(crate) fn insert_error(id: &str, e: rusqlite::Error) -> StorageError {
118    if let rusqlite::Error::SqliteFailure(ref code, _) = e {
119        if code.extended_code == rusqlite::ffi::SQLITE_CONSTRAINT_PRIMARYKEY {
120            return StorageError::AlreadyExists(format!(
121                "snapshot {} is already stored and this backend is append-only",
122                id
123            ));
124        }
125    }
126    StorageError::ConnectionError(format!("Failed to insert snapshot: {}", e))
127}
128
129impl SqliteBackend {
130    /// Create or open a SQLite database at the given path.
131    ///
132    /// On Unix a new database file is created owner-only (0600) before SQLite
133    /// opens it, so it is never readable by other users at any point; existing
134    /// files and WAL siblings are tightened best-effort (a file another owner
135    /// shares with this process stays usable even though chmod fails).
136    /// Directory permissions are the caller's responsibility.
137    pub fn new(path: impl AsRef<Path>) -> Result<Self, StorageError> {
138        let path = path.as_ref();
139        Self::precreate_owner_only(path);
140        let conn = Connection::open(path).map_err(|e| {
141            StorageError::ConnectionError(format!("Failed to open database: {}", e))
142        })?;
143
144        let backend = Self {
145            conn: Arc::new(Mutex::new(conn)),
146            append_only: false,
147            #[cfg(feature = "chain")]
148            chain: None,
149        };
150
151        // Run migrations
152        {
153            let conn_guard = backend.lock_conn();
154            Self::run_migrations(&conn_guard)?;
155        }
156
157        Self::restrict_file_permissions(path);
158
159        Ok(backend)
160    }
161
162    /// Create the database file with mode 0600 if it does not exist yet.
163    /// SQLite treats an empty file as an empty database. Failures are left
164    /// for Connection::open to surface with its own error.
165    #[cfg(unix)]
166    fn precreate_owner_only(path: &Path) {
167        use std::os::unix::fs::OpenOptionsExt;
168
169        let _ = std::fs::OpenOptions::new()
170            .write(true)
171            .create_new(true)
172            .mode(0o600)
173            .open(path);
174    }
175
176    #[cfg(not(unix))]
177    fn precreate_owner_only(_path: &Path) {}
178
179    /// Best-effort: restrict the database file and any existing -wal/-shm
180    /// siblings to owner-only access. SQLite creates future siblings with the
181    /// database file's permissions.
182    #[cfg(unix)]
183    fn restrict_file_permissions(path: &Path) {
184        use std::os::unix::fs::PermissionsExt;
185
186        let mut targets = vec![path.to_path_buf()];
187        for suffix in ["-wal", "-shm"] {
188            let mut os = path.as_os_str().to_os_string();
189            os.push(suffix);
190            targets.push(std::path::PathBuf::from(os));
191        }
192
193        for target in targets {
194            if target.exists() {
195                let _ = std::fs::set_permissions(&target, std::fs::Permissions::from_mode(0o600));
196            }
197        }
198    }
199
200    #[cfg(not(unix))]
201    fn restrict_file_permissions(_path: &Path) {}
202
203    /// Create an in-memory database (for testing)
204    pub fn in_memory() -> Result<Self, StorageError> {
205        let conn = Connection::open(":memory:").map_err(|e| {
206            StorageError::ConnectionError(format!("Failed to create in-memory database: {}", e))
207        })?;
208
209        let backend = Self {
210            conn: Arc::new(Mutex::new(conn)),
211            append_only: false,
212            #[cfg(feature = "chain")]
213            chain: None,
214        };
215
216        // Run migrations
217        {
218            let conn_guard = backend.lock_conn();
219            Self::run_migrations(&conn_guard)?;
220        }
221
222        Ok(backend)
223    }
224
225    /// Opt in to append-only writes. Off by default, where saving an id that
226    /// is already stored replaces the row. When on, such a save fails with
227    /// [`StorageError::AlreadyExists`] and leaves the stored row untouched (a
228    /// batch save is rejected as a whole), and `delete` fails with
229    /// [`StorageError::PermissionDenied`], so a recorded decision cannot be
230    /// rewritten through this handle. The flag belongs to the handle, not the
231    /// database file: another handle opened without it can still overwrite.
232    pub fn with_append_only(mut self, append_only: bool) -> Self {
233        self.append_only = append_only;
234        self
235    }
236
237    /// Whether this handle refuses to overwrite or delete stored snapshots.
238    pub fn is_append_only(&self) -> bool {
239        self.append_only
240    }
241
242    fn write_sql(&self) -> &'static str {
243        if self.append_only {
244            INSERT_ONLY_SQL
245        } else {
246            UPSERT_SQL
247        }
248    }
249
250    /// Lock the connection. A panic in another thread while it held the lock
251    /// poisons the mutex, but the connection itself is still usable (SQLite
252    /// rolls back the interrupted statement), so recover the guard rather
253    /// than turning every later call into a panic.
254    pub(crate) fn lock_conn(&self) -> MutexGuard<'_, Connection> {
255        self.conn.lock().unwrap_or_else(PoisonError::into_inner)
256    }
257
258    /// Run database migrations
259    fn run_migrations(conn: &Connection) -> Result<(), StorageError> {
260        conn.busy_timeout(BUSY_TIMEOUT).map_err(|e| {
261            StorageError::ConnectionError(format!("Failed to set busy timeout: {}", e))
262        })?;
263
264        // Enable WAL mode for better concurrent access
265        conn.pragma_update(None, "journal_mode", "WAL")
266            .map_err(|e| StorageError::ConnectionError(format!("Failed to set WAL mode: {}", e)))?;
267
268        // Enable foreign keys
269        conn.pragma_update(None, "foreign_keys", "ON")
270            .map_err(|e| {
271                StorageError::ConnectionError(format!("Failed to enable foreign keys: {}", e))
272            })?;
273
274        // Create snapshots table
275        conn.execute(
276            r#"
277            CREATE TABLE IF NOT EXISTS snapshots (
278                id TEXT PRIMARY KEY,
279                snapshot_type TEXT NOT NULL,
280                data_json TEXT NOT NULL,
281                created_at DATETIME NOT NULL,
282                created_by TEXT,
283                checksum TEXT
284            )
285            "#,
286            [],
287        )
288        .map_err(|e| {
289            StorageError::ConnectionError(format!("Failed to create snapshots table: {}", e))
290        })?;
291
292        // Create index
293        conn.execute(
294            "CREATE INDEX IF NOT EXISTS idx_snapshots_created_at ON snapshots(created_at)",
295            [],
296        )
297        .map_err(|e| StorageError::ConnectionError(format!("Failed to create index: {}", e)))?;
298
299        Self::apply_versioned_migrations(conn)
300    }
301
302    /// Apply every entry of [`MIGRATIONS`] the database has not seen yet.
303    /// Each runs in its own transaction together with the `user_version`
304    /// bump, so a failure leaves the database at the last completed version.
305    fn apply_versioned_migrations(conn: &Connection) -> Result<(), StorageError> {
306        let read_version = |conn: &Connection| -> Result<usize, rusqlite::Error> {
307            let version: i64 = conn.pragma_query_value(None, "user_version", |row| row.get(0))?;
308            Ok(usize::try_from(version).unwrap_or(0))
309        };
310        let failed = |version: usize, e: rusqlite::Error| {
311            StorageError::ConnectionError(format!(
312                "Migration to schema version {} failed: {}",
313                version, e
314            ))
315        };
316
317        let applied = read_version(conn).map_err(|e| failed(0, e))?;
318        for (index, sql) in MIGRATIONS.iter().enumerate().skip(applied) {
319            let version = index + 1;
320            let migrate = || -> Result<(), rusqlite::Error> {
321                conn.execute_batch("BEGIN IMMEDIATE")?;
322                // Another process may have migrated while this one waited
323                // for the write lock; check again now that it is held.
324                if read_version(conn)? < version {
325                    conn.execute_batch(sql)?;
326                    conn.pragma_update(None, "user_version", version as i64)?;
327                }
328                conn.execute_batch("COMMIT")
329            };
330            if let Err(e) = migrate() {
331                let _ = conn.execute_batch("ROLLBACK");
332                return Err(failed(version, e));
333            }
334        }
335
336        Ok(())
337    }
338
339    pub fn save_internal(&self, snapshot: &Snapshot) -> Result<String, StorageError> {
340        #[cfg(feature = "chain")]
341        if self.chain.is_some() {
342            return self
343                .save_snapshots_chained(std::slice::from_ref(snapshot))
344                .map(|mut ids| ids.remove(0));
345        }
346        let conn_guard = self.lock_conn();
347        let snapshot_id = snapshot.metadata.snapshot_id.to_string();
348
349        let data_json = serde_json::to_string(snapshot)
350            .map_err(|e| StorageError::SerializationError(e.to_string()))?;
351
352        conn_guard
353            .execute(
354                self.write_sql(),
355                params![
356                    snapshot_id,
357                    format!("{:?}", snapshot.snapshot_type),
358                    data_json,
359                    format_created_at(&snapshot.metadata.timestamp),
360                    snapshot.metadata.created_by,
361                    snapshot.metadata.checksum,
362                ],
363            )
364            .map_err(|e| insert_error(&snapshot_id, e))?;
365
366        Ok(snapshot_id)
367    }
368
369    pub fn save_decision_internal(
370        &self,
371        decision: &DecisionSnapshot,
372    ) -> Result<String, StorageError> {
373        // For simplicity, we'll save decisions as individual snapshots
374        let snapshot = Snapshot {
375            metadata: decision.metadata.clone(),
376            decisions: vec![decision.clone()],
377            snapshot_type: SnapshotType::Decision,
378        };
379
380        self.save_internal(&snapshot)
381    }
382
383    /// Write many decisions inside one transaction, so a batch costs one
384    /// commit rather than one per decision. Either all rows land or none do.
385    pub fn save_decisions_internal(
386        &self,
387        decisions: &[DecisionSnapshot],
388    ) -> Result<Vec<String>, StorageError> {
389        #[cfg(feature = "chain")]
390        if self.chain.is_some() {
391            let snapshots: Vec<Snapshot> = decisions
392                .iter()
393                .map(|decision| Snapshot {
394                    metadata: decision.metadata.clone(),
395                    decisions: vec![decision.clone()],
396                    snapshot_type: SnapshotType::Decision,
397                })
398                .collect();
399            return self.save_snapshots_chained(&snapshots);
400        }
401        let write_sql = self.write_sql();
402        let mut conn_guard = self.lock_conn();
403        let tx = conn_guard
404            .transaction()
405            .map_err(|e| StorageError::ConnectionError(format!("Failed to begin: {}", e)))?;
406
407        let mut ids = Vec::with_capacity(decisions.len());
408        for decision in decisions {
409            let snapshot = Snapshot {
410                metadata: decision.metadata.clone(),
411                decisions: vec![decision.clone()],
412                snapshot_type: SnapshotType::Decision,
413            };
414            let snapshot_id = snapshot.metadata.snapshot_id.to_string();
415            let data_json = serde_json::to_string(&snapshot)
416                .map_err(|e| StorageError::SerializationError(e.to_string()))?;
417
418            tx.execute(
419                write_sql,
420                params![
421                    snapshot_id,
422                    format!("{:?}", snapshot.snapshot_type),
423                    data_json,
424                    format_created_at(&snapshot.metadata.timestamp),
425                    snapshot.metadata.created_by,
426                    snapshot.metadata.checksum,
427                ],
428            )
429            .map_err(|e| insert_error(&snapshot_id, e))?;
430            ids.push(snapshot_id);
431        }
432
433        tx.commit()
434            .map_err(|e| StorageError::ConnectionError(format!("Failed to commit: {}", e)))?;
435        Ok(ids)
436    }
437
438    /// Delete a snapshot by id; `Ok(false)` when no such id is stored.
439    /// Refused with `PermissionDenied` in append-only mode.
440    pub fn delete_internal(&self, snapshot_id: &str) -> Result<bool, StorageError> {
441        if self.append_only {
442            return Err(StorageError::PermissionDenied(format!(
443                "cannot delete snapshot {}: this backend is append-only",
444                snapshot_id
445            )));
446        }
447        let rows_affected = self
448            .lock_conn()
449            .execute("DELETE FROM snapshots WHERE id = ?", params![snapshot_id])
450            .map_err(|e| {
451                StorageError::ConnectionError(format!("Failed to delete snapshot: {}", e))
452            })?;
453
454        Ok(rows_affected > 0)
455    }
456
457    pub fn load_internal(&self, snapshot_id: &str) -> Result<Snapshot, StorageError> {
458        let conn_guard = self.lock_conn();
459
460        let row: Option<(String,)> = conn_guard
461            .query_row(
462                "SELECT data_json FROM snapshots WHERE id = ?",
463                params![snapshot_id],
464                |row| Ok((row.get(0)?,)),
465            )
466            .optional()
467            .map_err(|e| {
468                StorageError::ConnectionError(format!("Failed to query snapshot: {}", e))
469            })?;
470
471        match row {
472            Some((data_json,)) => {
473                let snapshot: Snapshot = serde_json::from_str(&data_json)
474                    .map_err(|e| StorageError::SerializationError(e.to_string()))?;
475                Ok(snapshot)
476            }
477            None => Err(StorageError::NotFound(format!(
478                "Snapshot {} not found",
479                snapshot_id
480            ))),
481        }
482    }
483
484    pub fn query_internal(&self, query: SnapshotQuery) -> Result<Vec<Snapshot>, StorageError> {
485        let conn_guard = self.lock_conn();
486
487        let mut sql = "SELECT data_json FROM snapshots WHERE 1=1".to_string();
488        let mut params_vec: Vec<String> = Vec::new();
489
490        // Build WHERE clause
491        if let Some(start_time) = query.start_time {
492            sql.push_str(" AND created_at >= ?");
493            params_vec.push(format_created_at(&start_time));
494        }
495
496        if let Some(end_time) = query.end_time {
497            sql.push_str(" AND created_at <= ?");
498            params_vec.push(format_created_at(&end_time));
499        }
500
501        // Add ordering and pagination
502        sql.push_str(" ORDER BY created_at DESC");
503
504        // Content filters run in Rust after the SQL query; when any are
505        // present, pagination also runs in Rust so LIMIT/OFFSET consumes
506        // filtered matches instead of raw rows.
507        let has_content_filters = query.function_name.is_some()
508            || query.module_name.is_some()
509            || query.model_name.is_some()
510            || query.tags.is_some();
511
512        if !has_content_filters {
513            // SQLite only accepts OFFSET after LIMIT; -1 means "no limit".
514            match (query.limit, query.offset) {
515                (Some(limit), _) => {
516                    sql.push_str(" LIMIT ?");
517                    params_vec.push(limit.to_string());
518                }
519                (None, Some(_)) => sql.push_str(" LIMIT -1"),
520                (None, None) => {}
521            }
522
523            if let Some(offset) = query.offset {
524                sql.push_str(" OFFSET ?");
525                params_vec.push(offset.to_string());
526            }
527        }
528
529        // Execute query
530        let mut stmt = conn_guard
531            .prepare(&sql)
532            .map_err(|e| StorageError::InvalidQuery(format!("Invalid query: {}", e)))?;
533
534        let param_refs: Vec<&dyn rusqlite::ToSql> = params_vec
535            .iter()
536            .map(|p| p as &dyn rusqlite::ToSql)
537            .collect();
538
539        let rows = stmt
540            .query_map(param_refs.as_slice(), |row| row.get::<_, String>(0))
541            .map_err(|e| StorageError::ConnectionError(format!("Query failed: {}", e)))?;
542
543        // With content filters the page is cut in Rust, so the scan stops as
544        // soon as it holds offset+limit matches. Without that bound a limited
545        // query over a large table would deserialize every row in the range
546        // before discarding all but the page.
547        let wanted = if has_content_filters {
548            query
549                .limit
550                .map(|limit| limit.saturating_add(query.offset.unwrap_or(0)))
551        } else {
552            None
553        };
554
555        let mut snapshots = Vec::new();
556        for row in rows {
557            let data_json =
558                row.map_err(|e| StorageError::ConnectionError(format!("Row error: {}", e)))?;
559            let snapshot: Snapshot = serde_json::from_str(&data_json)
560                .map_err(|e| StorageError::SerializationError(e.to_string()))?;
561
562            // Apply additional filters that require checking the snapshot content
563            if self.matches_query_filters(&snapshot, &query) {
564                snapshots.push(snapshot);
565                if wanted.is_some_and(|wanted| snapshots.len() >= wanted) {
566                    break;
567                }
568            }
569        }
570
571        if has_content_filters {
572            let offset = query.offset.unwrap_or(0);
573            if offset >= snapshots.len() {
574                return Ok(Vec::new());
575            }
576            snapshots.drain(..offset);
577            if let Some(limit) = query.limit {
578                snapshots.truncate(limit);
579            }
580        }
581
582        Ok(snapshots)
583    }
584
585    fn matches_query_filters(&self, snapshot: &Snapshot, query: &SnapshotQuery) -> bool {
586        // Check function name, module name, model name, tags in decisions
587        if query.function_name.is_some()
588            || query.module_name.is_some()
589            || query.model_name.is_some()
590            || query.tags.is_some()
591        {
592            for decision in &snapshot.decisions {
593                if let Some(function_name) = &query.function_name {
594                    if decision.function_name != *function_name {
595                        continue;
596                    }
597                }
598
599                if let Some(module_name) = &query.module_name {
600                    if decision.module_name.as_ref() != Some(module_name) {
601                        continue;
602                    }
603                }
604
605                if let Some(model_name) = &query.model_name {
606                    if let Some(model_params) = &decision.model_parameters {
607                        if model_params.model_name != *model_name {
608                            continue;
609                        }
610                    } else {
611                        continue;
612                    }
613                }
614
615                if let Some(query_tags) = &query.tags {
616                    let mut all_tags_match = true;
617                    for (key, value) in query_tags {
618                        if decision.tags.get(key) != Some(value) {
619                            all_tags_match = false;
620                            break;
621                        }
622                    }
623                    if !all_tags_match {
624                        continue;
625                    }
626                }
627
628                // If we get here, this decision matches all filters
629                return true;
630            }
631
632            // No decisions matched the filters
633            return false;
634        }
635
636        // No content filters, so it matches
637        true
638    }
639}
640
641#[cfg(feature = "async")]
642#[async_trait::async_trait]
643impl StorageBackend for SqliteBackend {
644    async fn save(&self, snapshot: &Snapshot) -> Result<String, StorageError> {
645        let snapshot_clone = snapshot.clone();
646        let self_clone = self.clone();
647
648        task::spawn_blocking(move || self_clone.save_internal(&snapshot_clone))
649            .await
650            .map_err(|e| StorageError::ConnectionError(format!("Task join error: {}", e)))?
651    }
652
653    async fn save_decision(&self, decision: &DecisionSnapshot) -> Result<String, StorageError> {
654        let decision_clone = decision.clone();
655        let self_clone = self.clone();
656
657        task::spawn_blocking(move || self_clone.save_decision_internal(&decision_clone))
658            .await
659            .map_err(|e| StorageError::ConnectionError(format!("Task join error: {}", e)))?
660    }
661
662    async fn save_decisions(
663        &self,
664        decisions: &[DecisionSnapshot],
665    ) -> Result<Vec<String>, StorageError> {
666        let batch = decisions.to_vec();
667        let self_clone = self.clone();
668
669        task::spawn_blocking(move || self_clone.save_decisions_internal(&batch))
670            .await
671            .map_err(|e| StorageError::ConnectionError(format!("Task join error: {}", e)))?
672    }
673
674    async fn load(&self, snapshot_id: &str) -> Result<Snapshot, StorageError> {
675        let id = snapshot_id.to_string();
676        let self_clone = self.clone();
677
678        task::spawn_blocking(move || self_clone.load_internal(&id))
679            .await
680            .map_err(|e| StorageError::ConnectionError(format!("Task join error: {}", e)))?
681    }
682
683    async fn load_decision(&self, decision_id: &str) -> Result<DecisionSnapshot, StorageError> {
684        let snapshot = self.load(decision_id).await?;
685        if let Some(decision) = snapshot.decisions.first() {
686            Ok(decision.clone())
687        } else {
688            Err(StorageError::NotFound(format!(
689                "Decision {} not found",
690                decision_id
691            )))
692        }
693    }
694
695    async fn query(&self, query: SnapshotQuery) -> Result<Vec<Snapshot>, StorageError> {
696        let self_clone = self.clone();
697
698        task::spawn_blocking(move || self_clone.query_internal(query))
699            .await
700            .map_err(|e| StorageError::ConnectionError(format!("Task join error: {}", e)))?
701    }
702
703    async fn delete(&self, snapshot_id: &str) -> Result<bool, StorageError> {
704        let id = snapshot_id.to_string();
705        let self_clone = self.clone();
706
707        task::spawn_blocking(move || self_clone.delete_internal(&id))
708            .await
709            .map_err(|e| StorageError::ConnectionError(format!("Task join error: {}", e)))?
710    }
711
712    async fn flush(&self) -> Result<FlushResult, StorageError> {
713        let self_clone = self.clone();
714
715        task::spawn_blocking(move || {
716            let conn_guard = self_clone.lock_conn();
717
718            // Force WAL checkpoint
719            conn_guard
720                .query_row("PRAGMA wal_checkpoint(TRUNCATE)", [], |_| Ok(()))
721                .map_err(|e| {
722                    StorageError::ConnectionError(format!("Failed to checkpoint WAL: {}", e))
723                })?;
724
725            // Get stats
726            let snapshot_count: i64 = conn_guard
727                .query_row("SELECT COUNT(*) FROM snapshots", [], |row| row.get(0))
728                .unwrap_or(0);
729
730            Ok(FlushResult {
731                snapshots_written: snapshot_count as usize,
732                bytes_written: 0, // SQLite doesn't easily report this
733                checkpoint_id: None,
734            })
735        })
736        .await
737        .map_err(|e| StorageError::ConnectionError(format!("Task join error: {}", e)))?
738    }
739
740    async fn health_check(&self) -> Result<bool, StorageError> {
741        let self_clone = self.clone();
742
743        task::spawn_blocking(move || {
744            let conn_guard = self_clone.lock_conn();
745
746            // Simple query to check connection
747            let _: i64 = conn_guard
748                .query_row("SELECT 1", [], |row| row.get(0))
749                .map_err(|e| {
750                    StorageError::ConnectionError(format!("Health check failed: {}", e))
751                })?;
752
753            Ok(true)
754        })
755        .await
756        .map_err(|e| StorageError::ConnectionError(format!("Task join error: {}", e)))?
757    }
758}
759
760impl Clone for SqliteBackend {
761    fn clone(&self) -> Self {
762        Self {
763            conn: Arc::clone(&self.conn),
764            append_only: self.append_only,
765            #[cfg(feature = "chain")]
766            chain: self.chain.clone(),
767        }
768    }
769}
770
771#[cfg(test)]
772mod tests {
773    use super::*;
774    use crate::models::*;
775    use serde_json::json;
776
777    async fn create_test_snapshot() -> Snapshot {
778        let input = Input::new("test_input", json!("value"), "string");
779        let output = Output::new("test_output", json!("result"), "string");
780        let model_params = ModelParameters::new("gpt-4");
781
782        let decision = DecisionSnapshot::new("test_function")
783            .with_module("test_module")
784            .add_input(input)
785            .add_output(output)
786            .with_model_parameters(model_params)
787            .add_tag("env", "test");
788
789        let mut snapshot = Snapshot::new(SnapshotType::Session);
790        snapshot.add_decision(decision);
791        snapshot
792    }
793
794    #[tokio::test]
795    async fn test_default_backend_still_replaces_by_id() {
796        let backend = SqliteBackend::in_memory().unwrap();
797        assert!(!backend.is_append_only());
798
799        let first = DecisionSnapshot::new("original");
800        let mut second = DecisionSnapshot::new("rewritten");
801        second.metadata.snapshot_id = first.metadata.snapshot_id;
802
803        let id = backend.save_decision(&first).await.unwrap();
804        assert_eq!(backend.save_decision(&second).await.unwrap(), id);
805        let stored = backend.load_decision(&id).await.unwrap();
806        assert_eq!(stored.function_name, "rewritten");
807        assert!(backend.delete(&id).await.unwrap());
808    }
809
810    #[tokio::test]
811    async fn test_append_only_rejects_an_existing_id() {
812        let backend = SqliteBackend::in_memory().unwrap().with_append_only(true);
813        assert!(backend.is_append_only());
814        // Clones share the flag along with the connection.
815        assert!(backend.clone().is_append_only());
816
817        let first = DecisionSnapshot::new("original");
818        let mut second = DecisionSnapshot::new("rewritten");
819        second.metadata.snapshot_id = first.metadata.snapshot_id;
820
821        let id = backend.save_decision(&first).await.unwrap();
822        let err = backend.save_decision(&second).await.unwrap_err();
823        assert!(matches!(err, StorageError::AlreadyExists(_)), "{err:?}");
824
825        // Same through `save`, and the stored row is untouched.
826        let mut snapshot = Snapshot::new(SnapshotType::Session);
827        snapshot.metadata.snapshot_id = first.metadata.snapshot_id;
828        let err = backend.save(&snapshot).await.unwrap_err();
829        assert!(matches!(err, StorageError::AlreadyExists(_)), "{err:?}");
830        let stored = backend.load_decision(&id).await.unwrap();
831        assert_eq!(stored.function_name, "original");
832
833        // A new id still saves.
834        backend
835            .save_decision(&DecisionSnapshot::new("another"))
836            .await
837            .unwrap();
838    }
839
840    #[tokio::test]
841    async fn test_append_only_rejects_a_batch_as_a_whole() {
842        let backend = SqliteBackend::in_memory().unwrap().with_append_only(true);
843        let stored = DecisionSnapshot::new("original");
844        backend.save_decision(&stored).await.unwrap();
845
846        let fresh = DecisionSnapshot::new("fresh");
847        let fresh_id = fresh.metadata.snapshot_id.to_string();
848        let mut clash = DecisionSnapshot::new("rewritten");
849        clash.metadata.snapshot_id = stored.metadata.snapshot_id;
850
851        let err = backend.save_decisions(&[fresh, clash]).await.unwrap_err();
852        assert!(matches!(err, StorageError::AlreadyExists(_)), "{err:?}");
853        // The transaction rolled back: the fresh decision did not land.
854        assert!(matches!(
855            backend.load_decision(&fresh_id).await,
856            Err(StorageError::NotFound(_))
857        ));
858    }
859
860    #[tokio::test]
861    async fn test_append_only_refuses_delete() {
862        let backend = SqliteBackend::in_memory().unwrap().with_append_only(true);
863        let id = backend
864            .save_decision(&DecisionSnapshot::new("original"))
865            .await
866            .unwrap();
867
868        let err = backend.delete(&id).await.unwrap_err();
869        assert!(matches!(err, StorageError::PermissionDenied(_)), "{err:?}");
870        assert!(backend.load_decision(&id).await.is_ok());
871    }
872
873    #[tokio::test]
874    async fn test_sqlite_in_memory() {
875        let backend = SqliteBackend::in_memory().unwrap();
876        assert!(backend.health_check().await.unwrap());
877    }
878
879    #[tokio::test]
880    async fn test_save_and_load_snapshot() {
881        let backend = SqliteBackend::in_memory().unwrap();
882        let snapshot = create_test_snapshot().await;
883
884        let snapshot_id = backend.save(&snapshot).await.unwrap();
885        let loaded_snapshot = backend.load(&snapshot_id).await.unwrap();
886
887        assert_eq!(snapshot.decisions.len(), loaded_snapshot.decisions.len());
888        assert_eq!(snapshot.snapshot_type, loaded_snapshot.snapshot_type);
889    }
890
891    #[tokio::test]
892    async fn test_query_by_function_name() {
893        let backend = SqliteBackend::in_memory().unwrap();
894        let snapshot = create_test_snapshot().await;
895        backend.save(&snapshot).await.unwrap();
896
897        let query = SnapshotQuery::new().with_function_name("test_function");
898        let results = backend.query(query).await.unwrap();
899
900        assert_eq!(results.len(), 1);
901        assert_eq!(results[0].decisions[0].function_name, "test_function");
902    }
903
904    #[tokio::test]
905    async fn test_query_content_filter_with_pagination_keeps_matches() {
906        let backend = SqliteBackend::in_memory().unwrap();
907
908        let make = |fn_name: &str, hours_ago: i64| {
909            let mut snapshot = Snapshot::new(SnapshotType::Session);
910            snapshot.add_decision(DecisionSnapshot::new(fn_name));
911            snapshot.metadata.timestamp = chrono::Utc::now() - chrono::Duration::hours(hours_ago);
912            snapshot
913        };
914
915        // Only the oldest of three snapshots matches the filter
916        backend.save(&make("target", 3)).await.unwrap();
917        backend.save(&make("other", 2)).await.unwrap();
918        backend.save(&make("other", 1)).await.unwrap();
919
920        let query = SnapshotQuery::new()
921            .with_function_name("target")
922            .with_limit(2);
923        let results = backend.query(query).await.unwrap();
924        assert_eq!(results.len(), 1);
925        assert_eq!(results[0].decisions[0].function_name, "target");
926
927        // Offset applies to filtered matches, not raw rows
928        let query = SnapshotQuery::new()
929            .with_function_name("target")
930            .with_offset(1);
931        let results = backend.query(query).await.unwrap();
932        assert_eq!(results.len(), 0);
933    }
934
935    #[tokio::test]
936    async fn test_query_content_filter_stops_once_the_page_is_full() {
937        // A content-filtered query must stop reading as soon as it has
938        // offset+limit matches, rather than deserializing every row in the
939        // range and truncating afterwards. The unreadable older row stands in
940        // for the rows a large table would otherwise pay to deserialize: if
941        // the scan reaches it, the query fails instead of returning the page.
942        let backend = SqliteBackend::in_memory().unwrap();
943
944        let make = |hours_ago: i64| {
945            let mut snapshot = Snapshot::new(SnapshotType::Session);
946            snapshot.add_decision(DecisionSnapshot::new("target"));
947            snapshot.metadata.timestamp = chrono::Utc::now() - chrono::Duration::hours(hours_ago);
948            snapshot
949        };
950
951        backend.save(&make(1)).await.unwrap();
952        backend.save(&make(2)).await.unwrap();
953        {
954            let conn = backend.lock_conn();
955            conn.execute(
956                "INSERT INTO snapshots (id, snapshot_type, created_at, data_json) \
957                 VALUES ('poison', 'Session', '1999-01-01 00:00:00.000', 'not json')",
958                [],
959            )
960            .unwrap();
961        }
962
963        let query = SnapshotQuery::new()
964            .with_function_name("target")
965            .with_limit(2);
966        let results = backend.query(query).await.unwrap();
967        assert_eq!(results.len(), 2);
968    }
969
970    #[cfg(unix)]
971    #[test]
972    fn test_new_creates_owner_only_files() {
973        use std::os::unix::fs::PermissionsExt;
974
975        let dir = tempfile::tempdir().unwrap();
976        let db_path = dir.path().join("decisions.db");
977        let _backend = SqliteBackend::new(&db_path).unwrap();
978
979        let mode = std::fs::metadata(&db_path).unwrap().permissions().mode() & 0o777;
980        assert_eq!(mode, 0o600, "db file mode {:o}", mode);
981
982        for suffix in ["-wal", "-shm"] {
983            let sibling = dir.path().join(format!("decisions.db{}", suffix));
984            if sibling.exists() {
985                let mode = std::fs::metadata(&sibling).unwrap().permissions().mode() & 0o777;
986                assert_eq!(mode, 0o600, "{} mode {:o}", sibling.display(), mode);
987            }
988        }
989    }
990
991    #[cfg(unix)]
992    #[test]
993    fn test_new_tightens_existing_loose_file() {
994        use std::os::unix::fs::PermissionsExt;
995
996        let dir = tempfile::tempdir().unwrap();
997        let db_path = dir.path().join("decisions.db");
998        drop(SqliteBackend::new(&db_path).unwrap());
999        std::fs::set_permissions(&db_path, std::fs::Permissions::from_mode(0o644)).unwrap();
1000
1001        drop(SqliteBackend::new(&db_path).unwrap());
1002
1003        let mode = std::fs::metadata(&db_path).unwrap().permissions().mode() & 0o777;
1004        assert_eq!(mode, 0o600, "db file mode {:o}", mode);
1005    }
1006
1007    #[tokio::test]
1008    async fn test_batch_saved_decisions_are_found_by_time_range() {
1009        let backend = SqliteBackend::in_memory().unwrap();
1010        let single = DecisionSnapshot::new("single");
1011        let batched = vec![DecisionSnapshot::new("b1"), DecisionSnapshot::new("b2")];
1012
1013        backend.save_decision(&single).await.unwrap();
1014        backend.save_decisions(&batched).await.unwrap();
1015
1016        let now = chrono::Utc::now();
1017        let query = SnapshotQuery::new().with_time_range(
1018            now - chrono::Duration::hours(1),
1019            now + chrono::Duration::hours(1),
1020        );
1021        let results = backend.query(query).await.unwrap();
1022        assert_eq!(results.len(), 3, "batch-saved rows must be in range");
1023
1024        // A range that excludes them must still exclude them.
1025        let query = SnapshotQuery::new().with_time_range(
1026            now - chrono::Duration::hours(3),
1027            now - chrono::Duration::hours(2),
1028        );
1029        assert_eq!(backend.query(query).await.unwrap().len(), 0);
1030    }
1031
1032    #[test]
1033    fn test_migration_normalises_legacy_rfc3339_created_at() {
1034        let dir = tempfile::tempdir().unwrap();
1035        let db_path = dir.path().join("legacy.db");
1036
1037        let mut snapshot = Snapshot::new(SnapshotType::Decision);
1038        snapshot.add_decision(DecisionSnapshot::new("legacy"));
1039        let ts = chrono::Utc::now() - chrono::Duration::minutes(5);
1040        snapshot.metadata.timestamp = ts;
1041
1042        // A database written before versioned migrations existed: version 0,
1043        // with a row in the old batch-write format.
1044        {
1045            let backend = SqliteBackend::new(&db_path).unwrap();
1046            let conn = backend.lock_conn();
1047            conn.execute(
1048                "INSERT INTO snapshots (id, snapshot_type, data_json, created_at) \
1049                 VALUES (?, 'Decision', ?, ?)",
1050                params![
1051                    snapshot.metadata.snapshot_id.to_string(),
1052                    serde_json::to_string(&snapshot).unwrap(),
1053                    ts.to_rfc3339(),
1054                ],
1055            )
1056            .unwrap();
1057            conn.pragma_update(None, "user_version", 0).unwrap();
1058        }
1059
1060        let backend = SqliteBackend::new(&db_path).unwrap();
1061        let query = SnapshotQuery::new().with_time_range(
1062            ts - chrono::Duration::minutes(1),
1063            ts + chrono::Duration::minutes(1),
1064        );
1065        let results = backend.query_internal(query).unwrap();
1066        assert_eq!(results.len(), 1);
1067
1068        let conn = backend.lock_conn();
1069        let stored: String = conn
1070            .query_row("SELECT created_at FROM snapshots", [], |r| r.get(0))
1071            .unwrap();
1072        assert!(!stored.contains('T'), "created_at not normalised: {stored}");
1073        assert_eq!(&stored[..19], &format_created_at(&ts)[..19]);
1074        let version: i64 = conn
1075            .pragma_query_value(None, "user_version", |r| r.get(0))
1076            .unwrap();
1077        assert_eq!(version, MIGRATIONS.len() as i64);
1078    }
1079
1080    #[tokio::test]
1081    async fn test_query_offset_without_limit() {
1082        let backend = SqliteBackend::in_memory().unwrap();
1083        for _ in 0..3 {
1084            backend.save(&create_test_snapshot().await).await.unwrap();
1085        }
1086
1087        let results = backend
1088            .query(SnapshotQuery::new().with_offset(1))
1089            .await
1090            .unwrap();
1091        assert_eq!(results.len(), 2);
1092    }
1093
1094    #[test]
1095    fn test_poisoned_lock_does_not_panic_later_calls() {
1096        let backend = SqliteBackend::in_memory().unwrap();
1097        let clone = backend.clone();
1098        let _ = std::thread::spawn(move || {
1099            let _guard = clone.conn.lock().unwrap();
1100            panic!("poison the connection mutex");
1101        })
1102        .join();
1103
1104        assert!(backend.conn.is_poisoned());
1105        let id = backend
1106            .save_decision_internal(&DecisionSnapshot::new("after_poison"))
1107            .unwrap();
1108        assert!(backend.load_internal(&id).is_ok());
1109    }
1110
1111    #[test]
1112    fn test_busy_timeout_is_set() {
1113        let backend = SqliteBackend::in_memory().unwrap();
1114        let timeout: i64 = backend
1115            .lock_conn()
1116            .pragma_query_value(None, "busy_timeout", |r| r.get(0))
1117            .unwrap();
1118        assert_eq!(timeout, BUSY_TIMEOUT.as_millis() as i64);
1119    }
1120
1121    #[tokio::test]
1122    async fn test_delete_snapshot() {
1123        let backend = SqliteBackend::in_memory().unwrap();
1124        let snapshot = create_test_snapshot().await;
1125
1126        let snapshot_id = backend.save(&snapshot).await.unwrap();
1127        assert!(backend.delete(&snapshot_id).await.unwrap());
1128
1129        let result = backend.load(&snapshot_id).await;
1130        assert!(matches!(result, Err(StorageError::NotFound(_))));
1131    }
1132}