aidaemon-store-sqlite 0.29.0

SQLite run store for aidaemon agents (journal and checkpoints); implementation crate of the aidaemon SDK, no stability promise (use it through aidaemon-sdk)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
//! # aidaemon-store-sqlite
//!
//! A SQLite implementation of [`aidaemon_core::RunStore`]: an append-only
//! event journal (`run_events`) plus the latest [`RunState`] snapshot per run
//! (`run_states`), with versioned migrations.
//!
//! Beyond the trait, [`SqliteStore`] offers query helpers an application
//! needs after a restart: [`SqliteStore::interrupted_runs`] (waiting on a
//! human decision, settle with `Agent::resume`) and
//! [`SqliteStore::in_flight_runs`] (stopped mid tool batch, continue with
//! `Agent::run_from`).
//!
//! With the `channels` feature, [`SqliteApprovalStore`] keeps a
//! `ChannelRunner`'s open approvals in the same database, so they survive a
//! restart (it is the crate that depends on `aidaemon-channels`, not the
//! other way round, so channels stay free of SQL).
//!
//! With the `client-events` feature, [`SqliteClientEventLog`] is the Client
//! Gateway's durable event log (resume by `seq`) and its remembered command
//! replies, in the same database.
//!
//! [`maintenance`] keeps a long-lived database healthy: planner statistics
//! ([`maintenance::optimize`]) and consistent live copies
//! ([`maintenance::snapshot`]). Write transactions on a shared database
//! should begin with `BEGIN IMMEDIATE` (`pool.begin_with("BEGIN IMMEDIATE")`):
//! under WAL a deferred one that reads first fails when another connection
//! commits before it writes.
//!
//! ```no_run
//! # async fn demo() -> Result<(), aidaemon_store_sqlite::Error> {
//! use std::sync::Arc;
//! use aidaemon_store_sqlite::SqliteStore;
//!
//! let store = Arc::new(SqliteStore::open("runs.db").await?);
//! for state in store.in_flight_runs().await? {
//!     // agent.run_from(state, CancellationToken::new()).await
//!     # let _ = state;
//! }
//! # Ok(()) }
//! ```

// Feature unification only (cargo-hakari); keeps the unused-dependency lint quiet.
use workspace_hack as _;

#[cfg(feature = "channels")]
mod approvals;
#[cfg(feature = "client-events")]
mod client_events;
pub mod maintenance;
mod migrations;

#[cfg(feature = "channels")]
pub use approvals::SqliteApprovalStore;
#[cfg(feature = "client-events")]
pub use client_events::{ClientEventRow, DeviceRow, PairingRow, SqliteClientEventLog};

use std::path::Path;
use std::str::FromStr;
use std::time::Duration;

use aidaemon_core::{Event, RunId, RunState, RunStatus, RunStore, StoreError};
use async_trait::async_trait;
use serde_json::Value;
use sqlx::Row;
use sqlx::sqlite::{
    SqliteConnectOptions, SqliteJournalMode, SqlitePool, SqlitePoolOptions, SqliteSynchronous,
};

pub use migrations::{
    MIGRATIONS, MigrateError, Migration, apply as apply_migrations, latest_version,
    recorded_version,
};

const NOW: &str = "strftime('%Y-%m-%dT%H:%M:%fZ', 'now')";

/// Errors from this crate. Converted to [`StoreError`] at the trait boundary.
#[derive(Debug, thiserror::Error)]
pub enum Error {
    #[error("sqlite: {0}")]
    Sqlx(#[from] sqlx::Error),
    #[error("json: {0}")]
    Json(#[from] serde_json::Error),
    #[error(
        "database schema version {found} is newer than this build supports ({supported}); \
         upgrade aidaemon-store-sqlite or use a different database file"
    )]
    SchemaTooNew { found: i64, supported: i64 },
    #[error("migration {version} ({name}) failed: {source}")]
    Migration {
        version: i64,
        name: &'static str,
        source: sqlx::Error,
    },
}

impl From<Error> for StoreError {
    fn from(err: Error) -> Self {
        StoreError(err.to_string())
    }
}

/// One journal row as stored.
#[derive(Debug, Clone, PartialEq)]
pub struct StoredEvent {
    pub run_id: String,
    /// 1-based, gap-free, assigned atomically per run.
    pub seq: i64,
    /// The event's serde tag, e.g. `"tool_finished"`.
    pub event_type: String,
    pub payload: Value,
    /// RFC 3339 UTC timestamp with milliseconds.
    pub created_at: String,
}

impl StoredEvent {
    /// Decode the payload. Fails for event types this build does not know.
    pub fn event(&self) -> Result<Event, serde_json::Error> {
        serde_json::from_value(self.payload.clone())
    }
}

/// SQLite-backed [`RunStore`]. Cheap to clone (wraps a pool).
#[derive(Debug, Clone)]
pub struct SqliteStore {
    pool: SqlitePool,
}

impl SqliteStore {
    /// Open (creating if needed) a database file. Uses WAL,
    /// `synchronous=NORMAL`, foreign keys and a busy timeout, then migrates
    /// and refreshes planner statistics ([`maintenance::optimize`]).
    pub async fn open(path: impl AsRef<Path>) -> Result<Self, Error> {
        let options = SqliteConnectOptions::new()
            .filename(path)
            .create_if_missing(true)
            .journal_mode(SqliteJournalMode::Wal)
            .synchronous(SqliteSynchronous::Normal)
            .foreign_keys(true)
            .busy_timeout(Duration::from_secs(10))
            // A 64 MiB page cache, memory-mapped reads and in-memory temp
            // B-trees: the settings the aidaemon daemon runs with.
            .pragma("cache_size", "-65536")
            .pragma("mmap_size", "268435456")
            .pragma("temp_store", "MEMORY");
        let pool = SqlitePoolOptions::new()
            .max_connections(8)
            .connect_with(options)
            .await?;
        let store = Self::from_pool(pool).await?;
        maintenance::optimize(&store.pool, maintenance::Optimize::AtOpen).await?;
        Ok(store)
    }

    /// A private in-memory database (one connection, lives as long as the
    /// store). Handy for tests.
    pub async fn open_in_memory() -> Result<Self, Error> {
        let options = SqliteConnectOptions::from_str("sqlite::memory:")?.foreign_keys(true);
        let pool = SqlitePoolOptions::new()
            .max_connections(1)
            .min_connections(1)
            .idle_timeout(None)
            .max_lifetime(None)
            .connect_with(options)
            .await?;
        Self::from_pool(pool).await
    }

    /// Use an existing pool (its connection options are kept as given) and
    /// apply migrations.
    pub async fn from_pool(pool: SqlitePool) -> Result<Self, Error> {
        migrations::run(&pool).await?;
        Ok(Self { pool })
    }

    pub fn pool(&self) -> &SqlitePool {
        &self.pool
    }

    /// The schema version recorded in the database.
    pub async fn schema_version(&self) -> Result<i64, Error> {
        migrations::current_version(&self.pool).await
    }

    /// Append one event and return its sequence number. The number is
    /// computed inside the insert statement, which SQLite runs under the
    /// write lock, so concurrent appends to one run never collide or skip.
    pub async fn append(&self, run_id: RunId, event: &Event) -> Result<i64, Error> {
        let payload = serde_json::to_value(event)?;
        let event_type = payload
            .get("type")
            .and_then(Value::as_str)
            .unwrap_or("unknown")
            .to_string();
        let run_id = run_id.to_string();
        let seq: i64 = sqlx::query_scalar(sqlx::AssertSqlSafe(format!(
            "INSERT INTO run_events (run_id, seq, event_type, payload, created_at)
             SELECT ?1, COALESCE(MAX(seq), 0) + 1, ?2, ?3, {NOW}
             FROM run_events WHERE run_id = ?1
             RETURNING seq"
        )))
        .bind(&run_id)
        .bind(event_type)
        .bind(payload.to_string())
        .fetch_one(&self.pool)
        .await?;
        Ok(seq)
    }

    /// Whether the last thing the run journaled was its end. A run that was
    /// resumed and then cut short journals something after its pause. A run
    /// paused for an answer journals `finished` with an `Interrupted` status:
    /// that is a pause, not an end, so it is still waiting.
    pub async fn run_ended(&self, run_id: RunId) -> Result<bool, Error> {
        let last: Option<(String, String)> = sqlx::query_as(
            "SELECT event_type, payload FROM run_events WHERE run_id = ? \
             ORDER BY seq DESC LIMIT 1",
        )
        .bind(run_id.to_string())
        .fetch_optional(&self.pool)
        .await?;
        let Some((event_type, payload)) = last else {
            return Ok(false);
        };
        if event_type != "finished" {
            return Ok(false);
        }
        let paused = serde_json::from_str::<Event>(&payload).is_ok_and(|event| {
            matches!(
                event,
                Event::Finished {
                    status: RunStatus::Interrupted { .. },
                    ..
                }
            )
        });
        Ok(!paused)
    }

    /// The run's journal in order, decoded.
    pub async fn events(&self, run_id: RunId) -> Result<Vec<Event>, Error> {
        self.raw_events(run_id)
            .await?
            .iter()
            .map(|e| e.event().map_err(Error::from))
            .collect()
    }

    /// The run's journal in order, as stored.
    pub async fn raw_events(&self, run_id: RunId) -> Result<Vec<StoredEvent>, Error> {
        let rows = sqlx::query(
            "SELECT run_id, seq, event_type, payload, created_at
             FROM run_events WHERE run_id = ? ORDER BY seq",
        )
        .bind(run_id.to_string())
        .fetch_all(&self.pool)
        .await?;
        rows.into_iter()
            .map(|row| {
                let payload: String = row.try_get("payload")?;
                Ok(StoredEvent {
                    run_id: row.try_get("run_id")?,
                    seq: row.try_get("seq")?,
                    event_type: row.try_get("event_type")?,
                    payload: serde_json::from_str(&payload)?,
                    created_at: row.try_get("created_at")?,
                })
            })
            .collect()
    }

    /// Insert or replace the snapshot for `state.run_id`.
    pub async fn upsert_state(&self, state: &RunState) -> Result<(), Error> {
        let json = serde_json::to_string(state)?;
        sqlx::query(sqlx::AssertSqlSafe(format!(
            "INSERT INTO run_states (run_id, agent_id, session_id, state, updated_at)
             VALUES (?, ?, ?, ?, {NOW})
             ON CONFLICT (run_id) DO UPDATE SET
                agent_id = excluded.agent_id,
                session_id = excluded.session_id,
                state = excluded.state,
                updated_at = excluded.updated_at"
        )))
        .bind(state.run_id.to_string())
        .bind(&state.agent_id)
        .bind(&state.session_id)
        .bind(json)
        .execute(&self.pool)
        .await?;
        Ok(())
    }

    /// The latest snapshot of one run.
    pub async fn state(&self, run_id: RunId) -> Result<Option<RunState>, Error> {
        let row: Option<String> =
            sqlx::query_scalar("SELECT state FROM run_states WHERE run_id = ?")
                .bind(run_id.to_string())
                .fetch_optional(&self.pool)
                .await?;
        row.map(|s| serde_json::from_str(&s).map_err(Error::from))
            .transpose()
    }

    /// Every run of a session, least recently updated first.
    pub async fn runs_for_session(&self, session_id: &str) -> Result<Vec<RunState>, Error> {
        self.states_where("session_id = ?", Some(session_id), false, None)
            .await
    }

    /// The most recently updated run of a session.
    pub async fn latest_state_for_session(
        &self,
        session_id: &str,
    ) -> Result<Option<RunState>, Error> {
        let mut states = self
            .states_where("session_id = ?", Some(session_id), true, Some(1))
            .await?;
        Ok(states.pop())
    }

    /// Runs paused on an interruption (`pending` set). Settle each with
    /// `Agent::resume`. A child run is not listed: it was started by its
    /// parent's tool call, and an answer reaches it through the parent, whose
    /// state holds it. Resuming its own row would run it behind the parent's
    /// back and again when the parent resumes.
    pub async fn interrupted_runs(&self) -> Result<Vec<RunState>, Error> {
        self.states_where(
            "json_extract(state, '$.pending') IS NOT NULL \
             AND json_extract(state, '$.parent_run') IS NULL",
            None,
            false,
            None,
        )
        .await
    }

    /// Runs whose last checkpoint was taken mid tool batch (`in_flight`
    /// set): the process stopped while tools ran. Continue each with
    /// `Agent::run_from`, which re-runs idempotent calls and marks the rest
    /// indeterminate.
    pub async fn in_flight_runs(&self) -> Result<Vec<RunState>, Error> {
        self.states_where(
            "json_extract(state, '$.in_flight') IS NOT NULL",
            None,
            false,
            None,
        )
        .await
    }

    /// The store's clock, in the format its checkpoints are stamped with:
    /// a mark to compare later checkpoints against
    /// ([`SqliteStore::unfinished_runs_since`]).
    pub async fn clock(&self) -> Result<String, Error> {
        let now: String = sqlx::query_scalar(sqlx::AssertSqlSafe(format!("SELECT {NOW}")))
            .fetch_one(&self.pool)
            .await?;
        Ok(now)
    }

    /// Top-level runs that never ended and were last checkpointed at or
    /// after `since` (a [`SqliteStore::clock`] mark), each still the latest
    /// run of its session: the turns a process stop cut off. A run paused
    /// for an answer is listed too; a child run is not (its parent holds it).
    pub async fn unfinished_runs_since(&self, since: &str) -> Result<Vec<RunState>, Error> {
        let candidates = self
            .states_where_since(
                "json_extract(state, '$.parent_run') IS NULL AND updated_at >= ?",
                since,
            )
            .await?;
        let mut unfinished = Vec::new();
        for state in candidates {
            if self.run_ended(state.run_id).await? {
                continue;
            }
            let latest = self.latest_state_for_session(&state.session_id).await?;
            if latest.is_some_and(|latest| latest.run_id == state.run_id) {
                unfinished.push(state);
            }
        }
        Ok(unfinished)
    }

    /// Sub-agent runs that never ended, were last checkpointed at or after
    /// `since` and whose parent run has ended: background sub-agents a
    /// process stop cut off (a child of a cut-off turn is held by that
    /// turn's run, which has not ended). Oldest checkpoint first.
    pub async fn unfinished_background_runs_since(
        &self,
        since: &str,
    ) -> Result<Vec<RunState>, Error> {
        let candidates = self
            .states_where_since(
                "json_extract(state, '$.parent_run') IS NOT NULL AND updated_at >= ?",
                since,
            )
            .await?;
        let mut unfinished = Vec::new();
        for state in candidates {
            let Some(parent) = state.parent_run else {
                continue;
            };
            if self.run_ended(state.run_id).await? || !self.run_ended(parent).await? {
                continue;
            }
            unfinished.push(state);
        }
        Ok(unfinished)
    }

    async fn states_where_since(
        &self,
        predicate: &str,
        since: &str,
    ) -> Result<Vec<RunState>, Error> {
        // `predicate` is a crate-internal constant, never caller input.
        let sql =
            format!("SELECT state FROM run_states WHERE {predicate} ORDER BY updated_at, rowid");
        sqlx::query_scalar::<_, String>(sqlx::AssertSqlSafe(&*sql))
            .bind(since)
            .fetch_all(&self.pool)
            .await?
            .iter()
            .map(|s| serde_json::from_str(s).map_err(Error::from))
            .collect()
    }

    async fn states_where(
        &self,
        predicate: &str,
        bind: Option<&str>,
        newest_first: bool,
        limit: Option<u32>,
    ) -> Result<Vec<RunState>, Error> {
        // `predicate` is a crate-internal constant, never caller input.
        let dir = if newest_first { "DESC" } else { "ASC" };
        let limit = limit.map(|n| format!(" LIMIT {n}")).unwrap_or_default();
        let sql = format!(
            "SELECT state FROM run_states WHERE {predicate}
             ORDER BY updated_at {dir}, rowid {dir}{limit}"
        );
        let mut query = sqlx::query_scalar::<_, String>(sqlx::AssertSqlSafe(&*sql));
        if let Some(value) = bind {
            query = query.bind(value);
        }
        query
            .fetch_all(&self.pool)
            .await?
            .iter()
            .map(|s| serde_json::from_str(s).map_err(Error::from))
            .collect()
    }

    /// Close the pool, checkpointing the WAL.
    pub async fn close(&self) {
        self.pool.close().await;
    }
}

#[async_trait]
impl RunStore for SqliteStore {
    async fn append_event(&self, run_id: RunId, event: &Event) -> Result<(), StoreError> {
        self.append(run_id, event).await?;
        Ok(())
    }

    async fn save_state(&self, state: &RunState) -> Result<(), StoreError> {
        Ok(self.upsert_state(state).await?)
    }

    async fn load_state(&self, run_id: RunId) -> Result<Option<RunState>, StoreError> {
        Ok(self.state(run_id).await?)
    }
}

/// Erase every run of one session from the journal and the checkpoints, and
/// what the Client Gateway logged of it, in the caller's transaction (a
/// `/wipe` deletes conversation text atomically).
///
/// `run_events` is append-only: a trigger aborts every `DELETE`. This is the
/// one sanctioned exception. It drops the guard, deletes the session's rows
/// and restores the guard inside the same transaction, so no other delete can
/// slip through. The trigger body must match migration 1.
pub async fn erase_session_in_tx(
    tx: &mut sqlx::Transaction<'_, sqlx::Sqlite>,
    session_id: &str,
) -> Result<(), Error> {
    // A pool the run store was never opened on has no journal to erase, and
    // `/wipe` must still succeed there.
    // What the Client Gateway sent clients of it, when it ever ran on
    // this database: all but each owner's newest event, which keeps the
    // numbering (the gateway's own erase removes that one after logging
    // the erase itself).
    let client_log: Option<String> = sqlx::query_scalar(
        "SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'client_events'",
    )
    .fetch_optional(&mut **tx)
    .await?;
    if client_log.is_some() {
        sqlx::query(
            "DELETE FROM client_events
             WHERE session_id = ?1
               AND seq < (SELECT MAX(n.seq) FROM client_events n
                          WHERE n.owner = client_events.owner)",
        )
        .bind(session_id)
        .execute(&mut **tx)
        .await?;
    }
    let journaled: Option<String> = sqlx::query_scalar(
        "SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'run_states'",
    )
    .fetch_optional(&mut **tx)
    .await?;
    if journaled.is_none() {
        return Ok(());
    }
    sqlx::query("DROP TRIGGER IF EXISTS run_events_no_delete")
        .execute(&mut **tx)
        .await?;
    sqlx::query(
        "DELETE FROM run_events
         WHERE run_id IN (SELECT run_id FROM run_states WHERE session_id = ?)",
    )
    .bind(session_id)
    .execute(&mut **tx)
    .await?;
    sqlx::query(
        "CREATE TRIGGER run_events_no_delete BEFORE DELETE ON run_events
         BEGIN SELECT RAISE(ABORT, 'run_events is append-only'); END",
    )
    .execute(&mut **tx)
    .await?;
    sqlx::query("DELETE FROM run_states WHERE session_id = ?")
        .bind(session_id)
        .execute(&mut **tx)
        .await?;
    Ok(())
}