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