Skip to main content

aidaemon_store_sqlite/
lib.rs

1//! # aidaemon-store-sqlite
2//!
3//! A SQLite implementation of [`aidaemon_core::RunStore`]: an append-only
4//! event journal (`run_events`) plus the latest [`RunState`] snapshot per run
5//! (`run_states`), with versioned migrations.
6//!
7//! Beyond the trait, [`SqliteStore`] offers query helpers an application
8//! needs after a restart: [`SqliteStore::interrupted_runs`] (waiting on a
9//! human decision, settle with `Agent::resume`) and
10//! [`SqliteStore::in_flight_runs`] (stopped mid tool batch, continue with
11//! `Agent::run_from`).
12//!
13//! With the `channels` feature, [`SqliteApprovalStore`] keeps a
14//! `ChannelRunner`'s open approvals in the same database, so they survive a
15//! restart (it is the crate that depends on `aidaemon-channels`, not the
16//! other way round, so channels stay free of SQL).
17//!
18//! With the `client-events` feature, [`SqliteClientEventLog`] is the Client
19//! Gateway's durable event log (resume by `seq`) and its remembered command
20//! replies, in the same database.
21//!
22//! [`maintenance`] keeps a long-lived database healthy: planner statistics
23//! ([`maintenance::optimize`]) and consistent live copies
24//! ([`maintenance::snapshot`]). Write transactions on a shared database
25//! should begin with `BEGIN IMMEDIATE` (`pool.begin_with("BEGIN IMMEDIATE")`):
26//! under WAL a deferred one that reads first fails when another connection
27//! commits before it writes.
28//!
29//! ```no_run
30//! # async fn demo() -> Result<(), aidaemon_store_sqlite::Error> {
31//! use std::sync::Arc;
32//! use aidaemon_store_sqlite::SqliteStore;
33//!
34//! let store = Arc::new(SqliteStore::open("runs.db").await?);
35//! for state in store.in_flight_runs().await? {
36//!     // agent.run_from(state, CancellationToken::new()).await
37//!     # let _ = state;
38//! }
39//! # Ok(()) }
40//! ```
41
42#[cfg(feature = "channels")]
43mod approvals;
44#[cfg(feature = "client-events")]
45mod client_events;
46pub mod maintenance;
47mod migrations;
48
49#[cfg(feature = "channels")]
50pub use approvals::SqliteApprovalStore;
51#[cfg(feature = "client-events")]
52pub use client_events::{ClientEventRow, DeviceRow, PairingRow, SqliteClientEventLog};
53
54use std::path::Path;
55use std::str::FromStr;
56use std::time::Duration;
57
58use aidaemon_core::{Event, RunId, RunState, RunStatus, RunStore, StoreError};
59use async_trait::async_trait;
60use serde_json::Value;
61use sqlx::Row;
62use sqlx::sqlite::{
63    SqliteConnectOptions, SqliteJournalMode, SqlitePool, SqlitePoolOptions, SqliteSynchronous,
64};
65
66pub use migrations::{MIGRATIONS, Migration, latest_version};
67
68const NOW: &str = "strftime('%Y-%m-%dT%H:%M:%fZ', 'now')";
69
70/// Errors from this crate. Converted to [`StoreError`] at the trait boundary.
71#[derive(Debug, thiserror::Error)]
72pub enum Error {
73    #[error("sqlite: {0}")]
74    Sqlx(#[from] sqlx::Error),
75    #[error("json: {0}")]
76    Json(#[from] serde_json::Error),
77    #[error(
78        "database schema version {found} is newer than this build supports ({supported}); \
79         upgrade aidaemon-store-sqlite or use a different database file"
80    )]
81    SchemaTooNew { found: i64, supported: i64 },
82    #[error("migration {version} ({name}) failed: {source}")]
83    Migration {
84        version: i64,
85        name: &'static str,
86        source: sqlx::Error,
87    },
88}
89
90impl From<Error> for StoreError {
91    fn from(err: Error) -> Self {
92        StoreError(err.to_string())
93    }
94}
95
96/// One journal row as stored.
97#[derive(Debug, Clone, PartialEq)]
98pub struct StoredEvent {
99    pub run_id: String,
100    /// 1-based, gap-free, assigned atomically per run.
101    pub seq: i64,
102    /// The event's serde tag, e.g. `"tool_finished"`.
103    pub event_type: String,
104    pub payload: Value,
105    /// RFC 3339 UTC timestamp with milliseconds.
106    pub created_at: String,
107}
108
109impl StoredEvent {
110    /// Decode the payload. Fails for event types this build does not know.
111    pub fn event(&self) -> Result<Event, serde_json::Error> {
112        serde_json::from_value(self.payload.clone())
113    }
114}
115
116/// SQLite-backed [`RunStore`]. Cheap to clone (wraps a pool).
117#[derive(Debug, Clone)]
118pub struct SqliteStore {
119    pool: SqlitePool,
120}
121
122impl SqliteStore {
123    /// Open (creating if needed) a database file. Uses WAL,
124    /// `synchronous=NORMAL`, foreign keys and a busy timeout, then migrates
125    /// and refreshes planner statistics ([`maintenance::optimize`]).
126    pub async fn open(path: impl AsRef<Path>) -> Result<Self, Error> {
127        let options = SqliteConnectOptions::new()
128            .filename(path)
129            .create_if_missing(true)
130            .journal_mode(SqliteJournalMode::Wal)
131            .synchronous(SqliteSynchronous::Normal)
132            .foreign_keys(true)
133            .busy_timeout(Duration::from_secs(10))
134            // A 64 MiB page cache, memory-mapped reads and in-memory temp
135            // B-trees: the settings the aidaemon daemon runs with.
136            .pragma("cache_size", "-65536")
137            .pragma("mmap_size", "268435456")
138            .pragma("temp_store", "MEMORY");
139        let pool = SqlitePoolOptions::new()
140            .max_connections(8)
141            .connect_with(options)
142            .await?;
143        let store = Self::from_pool(pool).await?;
144        maintenance::optimize(&store.pool, maintenance::Optimize::AtOpen).await?;
145        Ok(store)
146    }
147
148    /// A private in-memory database (one connection, lives as long as the
149    /// store). Handy for tests.
150    pub async fn open_in_memory() -> Result<Self, Error> {
151        let options = SqliteConnectOptions::from_str("sqlite::memory:")?.foreign_keys(true);
152        let pool = SqlitePoolOptions::new()
153            .max_connections(1)
154            .min_connections(1)
155            .idle_timeout(None)
156            .max_lifetime(None)
157            .connect_with(options)
158            .await?;
159        Self::from_pool(pool).await
160    }
161
162    /// Use an existing pool (its connection options are kept as given) and
163    /// apply migrations.
164    pub async fn from_pool(pool: SqlitePool) -> Result<Self, Error> {
165        migrations::run(&pool).await?;
166        Ok(Self { pool })
167    }
168
169    pub fn pool(&self) -> &SqlitePool {
170        &self.pool
171    }
172
173    /// The schema version recorded in the database.
174    pub async fn schema_version(&self) -> Result<i64, Error> {
175        migrations::current_version(&self.pool).await
176    }
177
178    /// Append one event and return its sequence number. The number is
179    /// computed inside the insert statement, which SQLite runs under the
180    /// write lock, so concurrent appends to one run never collide or skip.
181    pub async fn append(&self, run_id: RunId, event: &Event) -> Result<i64, Error> {
182        let payload = serde_json::to_value(event)?;
183        let event_type = payload
184            .get("type")
185            .and_then(Value::as_str)
186            .unwrap_or("unknown")
187            .to_string();
188        let run_id = run_id.to_string();
189        let seq: i64 = sqlx::query_scalar(sqlx::AssertSqlSafe(format!(
190            "INSERT INTO run_events (run_id, seq, event_type, payload, created_at)
191             SELECT ?1, COALESCE(MAX(seq), 0) + 1, ?2, ?3, {NOW}
192             FROM run_events WHERE run_id = ?1
193             RETURNING seq"
194        )))
195        .bind(&run_id)
196        .bind(event_type)
197        .bind(payload.to_string())
198        .fetch_one(&self.pool)
199        .await?;
200        Ok(seq)
201    }
202
203    /// Whether the last thing the run journaled was its end. A run that was
204    /// resumed and then cut short journals something after its pause. A run
205    /// paused for an answer journals `finished` with an `Interrupted` status:
206    /// that is a pause, not an end, so it is still waiting.
207    pub async fn run_ended(&self, run_id: RunId) -> Result<bool, Error> {
208        let last: Option<(String, String)> = sqlx::query_as(
209            "SELECT event_type, payload FROM run_events WHERE run_id = ? \
210             ORDER BY seq DESC LIMIT 1",
211        )
212        .bind(run_id.to_string())
213        .fetch_optional(&self.pool)
214        .await?;
215        let Some((event_type, payload)) = last else {
216            return Ok(false);
217        };
218        if event_type != "finished" {
219            return Ok(false);
220        }
221        let paused = serde_json::from_str::<Event>(&payload).is_ok_and(|event| {
222            matches!(
223                event,
224                Event::Finished {
225                    status: RunStatus::Interrupted { .. },
226                    ..
227                }
228            )
229        });
230        Ok(!paused)
231    }
232
233    /// The run's journal in order, decoded.
234    pub async fn events(&self, run_id: RunId) -> Result<Vec<Event>, Error> {
235        self.raw_events(run_id)
236            .await?
237            .iter()
238            .map(|e| e.event().map_err(Error::from))
239            .collect()
240    }
241
242    /// The run's journal in order, as stored.
243    pub async fn raw_events(&self, run_id: RunId) -> Result<Vec<StoredEvent>, Error> {
244        let rows = sqlx::query(
245            "SELECT run_id, seq, event_type, payload, created_at
246             FROM run_events WHERE run_id = ? ORDER BY seq",
247        )
248        .bind(run_id.to_string())
249        .fetch_all(&self.pool)
250        .await?;
251        rows.into_iter()
252            .map(|row| {
253                let payload: String = row.try_get("payload")?;
254                Ok(StoredEvent {
255                    run_id: row.try_get("run_id")?,
256                    seq: row.try_get("seq")?,
257                    event_type: row.try_get("event_type")?,
258                    payload: serde_json::from_str(&payload)?,
259                    created_at: row.try_get("created_at")?,
260                })
261            })
262            .collect()
263    }
264
265    /// Insert or replace the snapshot for `state.run_id`.
266    pub async fn upsert_state(&self, state: &RunState) -> Result<(), Error> {
267        let json = serde_json::to_string(state)?;
268        sqlx::query(sqlx::AssertSqlSafe(format!(
269            "INSERT INTO run_states (run_id, agent_id, session_id, state, updated_at)
270             VALUES (?, ?, ?, ?, {NOW})
271             ON CONFLICT (run_id) DO UPDATE SET
272                agent_id = excluded.agent_id,
273                session_id = excluded.session_id,
274                state = excluded.state,
275                updated_at = excluded.updated_at"
276        )))
277        .bind(state.run_id.to_string())
278        .bind(&state.agent_id)
279        .bind(&state.session_id)
280        .bind(json)
281        .execute(&self.pool)
282        .await?;
283        Ok(())
284    }
285
286    /// The latest snapshot of one run.
287    pub async fn state(&self, run_id: RunId) -> Result<Option<RunState>, Error> {
288        let row: Option<String> =
289            sqlx::query_scalar("SELECT state FROM run_states WHERE run_id = ?")
290                .bind(run_id.to_string())
291                .fetch_optional(&self.pool)
292                .await?;
293        row.map(|s| serde_json::from_str(&s).map_err(Error::from))
294            .transpose()
295    }
296
297    /// Every run of a session, least recently updated first.
298    pub async fn runs_for_session(&self, session_id: &str) -> Result<Vec<RunState>, Error> {
299        self.states_where("session_id = ?", Some(session_id), false, None)
300            .await
301    }
302
303    /// The most recently updated run of a session.
304    pub async fn latest_state_for_session(
305        &self,
306        session_id: &str,
307    ) -> Result<Option<RunState>, Error> {
308        let mut states = self
309            .states_where("session_id = ?", Some(session_id), true, Some(1))
310            .await?;
311        Ok(states.pop())
312    }
313
314    /// Runs paused on an interruption (`pending` set). Settle each with
315    /// `Agent::resume`. A child run is not listed: it was started by its
316    /// parent's tool call, and an answer reaches it through the parent, whose
317    /// state holds it. Resuming its own row would run it behind the parent's
318    /// back and again when the parent resumes.
319    pub async fn interrupted_runs(&self) -> Result<Vec<RunState>, Error> {
320        self.states_where(
321            "json_extract(state, '$.pending') IS NOT NULL \
322             AND json_extract(state, '$.parent_run') IS NULL",
323            None,
324            false,
325            None,
326        )
327        .await
328    }
329
330    /// Runs whose last checkpoint was taken mid tool batch (`in_flight`
331    /// set): the process stopped while tools ran. Continue each with
332    /// `Agent::run_from`, which re-runs idempotent calls and marks the rest
333    /// indeterminate.
334    pub async fn in_flight_runs(&self) -> Result<Vec<RunState>, Error> {
335        self.states_where(
336            "json_extract(state, '$.in_flight') IS NOT NULL",
337            None,
338            false,
339            None,
340        )
341        .await
342    }
343
344    /// The store's clock, in the format its checkpoints are stamped with:
345    /// a mark to compare later checkpoints against
346    /// ([`SqliteStore::unfinished_runs_since`]).
347    pub async fn clock(&self) -> Result<String, Error> {
348        let now: String = sqlx::query_scalar(sqlx::AssertSqlSafe(format!("SELECT {NOW}")))
349            .fetch_one(&self.pool)
350            .await?;
351        Ok(now)
352    }
353
354    /// Top-level runs that never ended and were last checkpointed at or
355    /// after `since` (a [`SqliteStore::clock`] mark), each still the latest
356    /// run of its session: the turns a process stop cut off. A run paused
357    /// for an answer is listed too; a child run is not (its parent holds it).
358    pub async fn unfinished_runs_since(&self, since: &str) -> Result<Vec<RunState>, Error> {
359        let candidates = self
360            .states_where_since(
361                "json_extract(state, '$.parent_run') IS NULL AND updated_at >= ?",
362                since,
363            )
364            .await?;
365        let mut unfinished = Vec::new();
366        for state in candidates {
367            if self.run_ended(state.run_id).await? {
368                continue;
369            }
370            let latest = self.latest_state_for_session(&state.session_id).await?;
371            if latest.is_some_and(|latest| latest.run_id == state.run_id) {
372                unfinished.push(state);
373            }
374        }
375        Ok(unfinished)
376    }
377
378    async fn states_where_since(
379        &self,
380        predicate: &str,
381        since: &str,
382    ) -> Result<Vec<RunState>, Error> {
383        // `predicate` is a crate-internal constant, never caller input.
384        let sql =
385            format!("SELECT state FROM run_states WHERE {predicate} ORDER BY updated_at, rowid");
386        sqlx::query_scalar::<_, String>(sqlx::AssertSqlSafe(&*sql))
387            .bind(since)
388            .fetch_all(&self.pool)
389            .await?
390            .iter()
391            .map(|s| serde_json::from_str(s).map_err(Error::from))
392            .collect()
393    }
394
395    async fn states_where(
396        &self,
397        predicate: &str,
398        bind: Option<&str>,
399        newest_first: bool,
400        limit: Option<u32>,
401    ) -> Result<Vec<RunState>, Error> {
402        // `predicate` is a crate-internal constant, never caller input.
403        let dir = if newest_first { "DESC" } else { "ASC" };
404        let limit = limit.map(|n| format!(" LIMIT {n}")).unwrap_or_default();
405        let sql = format!(
406            "SELECT state FROM run_states WHERE {predicate}
407             ORDER BY updated_at {dir}, rowid {dir}{limit}"
408        );
409        let mut query = sqlx::query_scalar::<_, String>(sqlx::AssertSqlSafe(&*sql));
410        if let Some(value) = bind {
411            query = query.bind(value);
412        }
413        query
414            .fetch_all(&self.pool)
415            .await?
416            .iter()
417            .map(|s| serde_json::from_str(s).map_err(Error::from))
418            .collect()
419    }
420
421    /// Close the pool, checkpointing the WAL.
422    pub async fn close(&self) {
423        self.pool.close().await;
424    }
425}
426
427#[async_trait]
428impl RunStore for SqliteStore {
429    async fn append_event(&self, run_id: RunId, event: &Event) -> Result<(), StoreError> {
430        self.append(run_id, event).await?;
431        Ok(())
432    }
433
434    async fn save_state(&self, state: &RunState) -> Result<(), StoreError> {
435        Ok(self.upsert_state(state).await?)
436    }
437
438    async fn load_state(&self, run_id: RunId) -> Result<Option<RunState>, StoreError> {
439        Ok(self.state(run_id).await?)
440    }
441}
442
443/// Erase every run of one session from the journal and the checkpoints, in
444/// the caller's transaction (a `/wipe` deletes conversation text atomically).
445///
446/// `run_events` is append-only: a trigger aborts every `DELETE`. This is the
447/// one sanctioned exception. It drops the guard, deletes the session's rows
448/// and restores the guard inside the same transaction, so no other delete can
449/// slip through. The trigger body must match migration 1.
450pub async fn erase_session_in_tx(
451    tx: &mut sqlx::Transaction<'_, sqlx::Sqlite>,
452    session_id: &str,
453) -> Result<(), Error> {
454    // A pool the run store was never opened on has no journal to erase, and
455    // `/wipe` must still succeed there.
456    let journaled: Option<String> = sqlx::query_scalar(
457        "SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'run_states'",
458    )
459    .fetch_optional(&mut **tx)
460    .await?;
461    if journaled.is_none() {
462        return Ok(());
463    }
464    sqlx::query("DROP TRIGGER IF EXISTS run_events_no_delete")
465        .execute(&mut **tx)
466        .await?;
467    sqlx::query(
468        "DELETE FROM run_events
469         WHERE run_id IN (SELECT run_id FROM run_states WHERE session_id = ?)",
470    )
471    .bind(session_id)
472    .execute(&mut **tx)
473    .await?;
474    sqlx::query(
475        "CREATE TRIGGER run_events_no_delete BEFORE DELETE ON run_events
476         BEGIN SELECT RAISE(ABORT, 'run_events is append-only'); END",
477    )
478    .execute(&mut **tx)
479    .await?;
480    sqlx::query("DELETE FROM run_states WHERE session_id = ?")
481        .bind(session_id)
482        .execute(&mut **tx)
483        .await?;
484    Ok(())
485}