Skip to main content

adk_session/
sqlite.rs

1use crate::history::{
2    HistoryOperation, HistoryOutcome, ImportSessionRequest, RewriteHistoryRequest, SessionHistory,
3};
4use crate::service::{
5    ambiguous_session_id, identity_not_found, session_already_exists, session_id_not_found,
6    session_not_found_for, validate_scope, validate_session_id,
7};
8use crate::{
9    AppendEventRequest, CreateRequest, DeleteRequest, Event, Events, GetRequest, KEY_PREFIX_TEMP,
10    ListRequest, Session, SessionService, State, state_utils,
11};
12use adk_core::Result;
13use adk_core::identity::AdkIdentity;
14use async_trait::async_trait;
15use chrono::{DateTime, Utc};
16use serde_json::Value;
17use sqlx::{
18    Row,
19    sqlite::{SqliteConnectOptions, SqliteConnection, SqlitePool, SqliteRow, SqliteSynchronous},
20};
21use std::collections::HashMap;
22use std::str::FromStr;
23use std::time::Duration;
24use uuid::Uuid;
25
26/// Decodes a stored event row, logging and skipping a row that no longer deserializes
27/// so one corrupt event does not hide the rest of the session history.
28fn decode_event_row(row: &SqliteRow, session_id: &str) -> Option<Event> {
29    fn decode(row: &SqliteRow) -> std::result::Result<Event, String> {
30        let llm_response =
31            serde_json::from_str(row.try_get("llm_response").map_err(|e| e.to_string())?)
32                .map_err(|e| format!("llm_response: {e}"))?;
33        let actions = serde_json::from_str(row.try_get("actions").map_err(|e| e.to_string())?)
34            .map_err(|e| format!("actions: {e}"))?;
35        let long_running_tool_ids =
36            serde_json::from_str(row.try_get("long_running_tool_ids").map_err(|e| e.to_string())?)
37                .map_err(|e| format!("long_running_tool_ids: {e}"))?;
38        let timestamp: String = row.try_get("timestamp").map_err(|e| e.to_string())?;
39        let timestamp = DateTime::parse_from_rfc3339(&timestamp)
40            .map_err(|e| format!("timestamp: {e}"))?
41            .with_timezone(&Utc);
42        Ok(Event {
43            id: row.try_get("id").map_err(|e| e.to_string())?,
44            timestamp,
45            invocation_id: row.try_get("invocation_id").map_err(|e| e.to_string())?,
46            branch: row.try_get("branch").map_err(|e| e.to_string())?,
47            author: row.try_get("author").map_err(|e| e.to_string())?,
48            llm_request: None,
49            llm_response,
50            actions,
51            long_running_tool_ids,
52            provider_metadata: HashMap::new(),
53        })
54    }
55
56    match decode(row) {
57        Ok(event) => Some(event),
58        Err(error) => {
59            let event_id: String = row.try_get("id").unwrap_or_else(|_| "<unknown>".to_string());
60            tracing::warn!(
61                session.id = %session_id,
62                event.id = %event_id,
63                error = %error,
64                "skipping stored event that failed to deserialize"
65            );
66            None
67        }
68    }
69}
70
71/// SQLite-backed session service using `sqlx`.
72pub struct SqliteSessionService {
73    pool: SqlitePool,
74}
75
76impl SqliteSessionService {
77    /// Connect to SQLite and create a connection pool.
78    ///
79    /// Enables foreign keys via `PRAGMA foreign_keys = ON`. A writer waits up to 30 seconds
80    /// for the database lock, so concurrent appends to a file database queue behind
81    /// `BEGIN IMMEDIATE` instead of failing with `database is locked`.
82    ///
83    /// A file database is switched to write-ahead-log mode (`journal_mode = WAL`), which
84    /// persists in the file: SQLite creates `<file>-wal` and `<file>-shm` beside it while it
85    /// is open, readers never block the writer, and a commit appends to the log instead of
86    /// rewriting a rollback journal. Every connection keeps `synchronous = FULL`, so each
87    /// committed event is synced to disk and survives power loss, as the action ledger and
88    /// approval stores require when they share the file. A file another process holds in
89    /// rollback mode keeps that mode, and a warning is logged. To trade the last commits
90    /// before a power loss for fewer syncs (`synchronous = NORMAL`), or to stay in rollback
91    /// mode on a filesystem without shared memory, build the pool yourself and use
92    /// [`from_pool`](Self::from_pool).
93    ///
94    /// # Errors
95    ///
96    /// Returns an error when the URL is invalid, the database cannot be opened, or foreign
97    /// keys cannot be enabled.
98    ///
99    /// # Example
100    ///
101    /// ```rust,no_run
102    /// use adk_session::SqliteSessionService;
103    ///
104    /// # async fn example() -> adk_core::Result<()> {
105    /// let service = SqliteSessionService::new("sqlite:sessions.db?mode=rwc").await?;
106    /// service.migrate().await?;
107    /// # Ok(())
108    /// # }
109    /// ```
110    pub async fn new(database_url: &str) -> Result<Self> {
111        let options = SqliteConnectOptions::from_str(database_url)
112            .map_err(|e| adk_core::AdkError::session(format!("invalid sqlite url: {e}")))?
113            .busy_timeout(BUSY_TIMEOUT)
114            .synchronous(SqliteSynchronous::Full);
115        let pool = SqlitePool::connect_with(options)
116            .await
117            .map_err(|e| adk_core::AdkError::session(format!("database connection failed: {e}")))?;
118        sqlx::query("PRAGMA foreign_keys = ON").execute(&pool).await.map_err(|e| {
119            adk_core::AdkError::session(format!("failed to enable sqlite foreign keys: {}", e))
120        })?;
121        // The switch needs the file to itself, so it is not a connect option: a file another
122        // process holds in rollback mode would fail every new connection instead of keeping
123        // its mode. An in-memory database reports `memory` and has no log.
124        match sqlx::query_scalar::<_, String>("PRAGMA journal_mode = WAL").fetch_one(&pool).await {
125            Ok(mode) if !matches!(mode.to_ascii_lowercase().as_str(), "wal" | "memory") => {
126                tracing::warn!(journal.mode = %mode, "sqlite session store stays out of WAL mode");
127            }
128            Ok(_) => {}
129            Err(error) => {
130                tracing::warn!(error = %error, "sqlite session store keeps its journal mode");
131            }
132        }
133        Ok(Self { pool })
134    }
135
136    /// Create a session service from an existing connection pool.
137    ///
138    /// Use this to share a pool with tuned settings across multiple
139    /// services, or in tests where you need direct pool access.
140    ///
141    /// **Note:** The caller is responsible for enabling foreign keys
142    /// (`PRAGMA foreign_keys = ON`) on the pool if needed, and for its journal mode and
143    /// `synchronous` setting: unlike [`new`](Self::new), this does not switch the file to
144    /// write-ahead-log mode.
145    ///
146    /// # Example
147    ///
148    /// A pool in WAL mode with `synchronous = NORMAL`: a commit is not synced on its own, so a
149    /// power loss can drop the last commits, never the file's consistency.
150    ///
151    /// ```rust,no_run
152    /// use adk_session::SqliteSessionService;
153    /// use sqlx::sqlite::{SqliteConnectOptions, SqliteJournalMode, SqlitePool, SqliteSynchronous};
154    /// use std::str::FromStr;
155    ///
156    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
157    /// let options = SqliteConnectOptions::from_str("sqlite:sessions.db?mode=rwc")?
158    ///     .foreign_keys(true)
159    ///     .journal_mode(SqliteJournalMode::Wal)
160    ///     .synchronous(SqliteSynchronous::Normal);
161    /// let service = SqliteSessionService::from_pool(SqlitePool::connect_with(options).await?);
162    /// service.migrate().await?;
163    /// # Ok(())
164    /// # }
165    /// ```
166    pub fn from_pool(pool: SqlitePool) -> Self {
167        Self { pool }
168    }
169
170    /// Returns a reference to the underlying connection pool.
171    pub fn pool(&self) -> &SqlitePool {
172        &self.pool
173    }
174
175    /// The registry table used to track applied migration versions.
176    const REGISTRY_TABLE: &'static str = "_adk_session_migrations";
177
178    /// Compiled-in migration steps for the SQLite session backend.
179    ///
180    /// Each entry is `(version, description, sql)`. Version 1 is the baseline
181    /// that creates the initial schema matching the original `CREATE TABLE IF
182    /// NOT EXISTS` statements. Version 2 adds `sessions.initial_state`, the session state a
183    /// session was created with, which rewind rebuilds from; it is `NULL` for sessions created
184    /// before it. Version 3 indexes `events` by session in read order, so loading, rewinding
185    /// or deleting one session reads that session's rows instead of every event in the file.
186    const SQLITE_SESSION_MIGRATIONS: &'static [(i64, &'static str, &'static str)] = &[
187        (
188            1,
189            "create initial session tables",
190            "\
191CREATE TABLE IF NOT EXISTS sessions (\
192    app_name TEXT NOT NULL, \
193    user_id TEXT NOT NULL, \
194    session_id TEXT NOT NULL, \
195    state TEXT NOT NULL, \
196    created_at TEXT NOT NULL, \
197    updated_at TEXT NOT NULL, \
198    PRIMARY KEY (app_name, user_id, session_id)\
199);\
200CREATE TABLE IF NOT EXISTS events (\
201    id TEXT NOT NULL, \
202    app_name TEXT NOT NULL, \
203    user_id TEXT NOT NULL, \
204    session_id TEXT NOT NULL, \
205    invocation_id TEXT NOT NULL, \
206    branch TEXT NOT NULL, \
207    author TEXT NOT NULL, \
208    timestamp TEXT NOT NULL, \
209    llm_response TEXT NOT NULL, \
210    actions TEXT NOT NULL, \
211    long_running_tool_ids TEXT NOT NULL, \
212    PRIMARY KEY (id, app_name, user_id, session_id), \
213    FOREIGN KEY (app_name, user_id, session_id) \
214        REFERENCES sessions(app_name, user_id, session_id) \
215        ON DELETE CASCADE\
216);\
217CREATE TABLE IF NOT EXISTS app_states (\
218    app_name TEXT PRIMARY KEY, \
219    state TEXT NOT NULL, \
220    updated_at TEXT NOT NULL\
221);\
222CREATE TABLE IF NOT EXISTS user_states (\
223    app_name TEXT NOT NULL, \
224    user_id TEXT NOT NULL, \
225    state TEXT NOT NULL, \
226    updated_at TEXT NOT NULL, \
227    PRIMARY KEY (app_name, user_id)\
228);",
229        ),
230        (
231            2,
232            "record the session state each session was created with",
233            "ALTER TABLE sessions ADD COLUMN initial_state TEXT;",
234        ),
235        (
236            3,
237            "index events by session in read order",
238            "CREATE INDEX IF NOT EXISTS idx_events_session_ts \
239             ON events (app_name, user_id, session_id, timestamp);",
240        ),
241    ];
242
243    /// Run all pending schema migrations for this backend.
244    pub async fn migrate(&self) -> Result<()> {
245        let pool = &self.pool;
246        crate::migration::sqlite_runner::run_sql_migrations(
247            pool,
248            Self::REGISTRY_TABLE,
249            Self::SQLITE_SESSION_MIGRATIONS,
250            || async {
251                let row = sqlx::query(
252                    "SELECT COUNT(*) AS cnt FROM sqlite_master \
253                     WHERE type='table' AND name='sessions'",
254                )
255                .fetch_one(pool)
256                .await
257                .map_err(|e| {
258                    adk_core::AdkError::session(format!("baseline detection failed: {e}"))
259                })?;
260                let count: i64 = row.try_get("cnt").unwrap_or(0);
261                Ok(count > 0)
262            },
263        )
264        .await
265    }
266
267    /// Returns the highest applied migration version, or 0 if no registry
268    /// exists or the registry is empty.
269    ///
270    /// # Errors
271    ///
272    /// Returns an error when the registry cannot be read for any reason other
273    /// than the table being absent, such as a lost connection or a missing
274    /// privilege.
275    pub async fn schema_version(&self) -> Result<i64> {
276        crate::migration::sqlite_runner::sql_schema_version(&self.pool, Self::REGISTRY_TABLE).await
277    }
278}
279
280/// How long a connection waits for the database lock before `database is locked`.
281///
282/// Concurrent appends to a file database queue behind [`BEGIN_WRITE`]; sqlx's default of
283/// five seconds is shorter than that queue on a slow disk.
284const BUSY_TIMEOUT: Duration = Duration::from_secs(30);
285
286/// Statement that opens every transaction which reads state and writes it back.
287///
288/// `BEGIN IMMEDIATE` takes the database write lock before the first read, so a concurrent
289/// writer waits for the commit instead of overwriting a delta it never read.
290const BEGIN_WRITE: &str = "BEGIN IMMEDIATE";
291
292type StateMap = HashMap<String, Value>;
293
294/// Decodes a stored state column; a missing row is empty state.
295fn decode_state(json: Option<&str>) -> Result<StateMap> {
296    match json {
297        Some(json) => serde_json::from_str(json)
298            .map_err(|e| adk_core::AdkError::session(format!("deserialize failed: {e}"))),
299        None => Ok(HashMap::new()),
300    }
301}
302
303fn encode_state(state: &StateMap) -> Result<String> {
304    serde_json::to_string(state)
305        .map_err(|e| adk_core::AdkError::session(format!("serialize failed: {e}")))
306}
307
308/// Reads the current app and user state tiers.
309async fn read_tiers(
310    conn: &mut SqliteConnection,
311    app_name: &str,
312    user_id: &str,
313) -> Result<(StateMap, StateMap)> {
314    let app_state: Option<String> =
315        sqlx::query_scalar("SELECT state FROM app_states WHERE app_name = ?")
316            .bind(app_name)
317            .fetch_optional(&mut *conn)
318            .await
319            .map_err(|e| adk_core::AdkError::session(format!("query failed: {e}")))?;
320    let user_state: Option<String> =
321        sqlx::query_scalar("SELECT state FROM user_states WHERE app_name = ? AND user_id = ?")
322            .bind(app_name)
323            .bind(user_id)
324            .fetch_optional(&mut *conn)
325            .await
326            .map_err(|e| adk_core::AdkError::session(format!("query failed: {e}")))?;
327    Ok((decode_state(app_state.as_deref())?, decode_state(user_state.as_deref())?))
328}
329
330/// Merges each non-empty tier delta into the stored tier and returns both tiers after
331/// the write.
332///
333/// Runs inside a [`BEGIN_WRITE`] transaction, so no other writer commits between the read
334/// and the write.
335async fn apply_tier_deltas(
336    conn: &mut SqliteConnection,
337    app_name: &str,
338    user_id: &str,
339    app_delta: StateMap,
340    user_delta: StateMap,
341    now: DateTime<Utc>,
342) -> Result<(StateMap, StateMap)> {
343    let (mut app_state, mut user_state) = read_tiers(conn, app_name, user_id).await?;
344
345    if !app_delta.is_empty() {
346        app_state.extend(app_delta);
347        sqlx::query(
348            "INSERT OR REPLACE INTO app_states (app_name, state, updated_at) VALUES (?, ?, ?)",
349        )
350        .bind(app_name)
351        .bind(encode_state(&app_state)?)
352        .bind(now.to_rfc3339())
353        .execute(&mut *conn)
354        .await
355        .map_err(|e| adk_core::AdkError::session(format!("insert failed: {e}")))?;
356    }
357
358    if !user_delta.is_empty() {
359        user_state.extend(user_delta);
360        sqlx::query(
361            "INSERT OR REPLACE INTO user_states (app_name, user_id, state, updated_at) \
362             VALUES (?, ?, ?, ?)",
363        )
364        .bind(app_name)
365        .bind(user_id)
366        .bind(encode_state(&user_state)?)
367        .bind(now.to_rfc3339())
368        .execute(&mut *conn)
369        .await
370        .map_err(|e| adk_core::AdkError::session(format!("insert failed: {e}")))?;
371    }
372
373    Ok((app_state, user_state))
374}
375
376/// Applies `event` to the session `(app_name, user_id, session_id)` inside a
377/// [`BEGIN_WRITE`] transaction: merges each tier's delta, bumps `updated_at`, and inserts
378/// the event.
379async fn apply_event(
380    conn: &mut SqliteConnection,
381    app_name: &str,
382    user_id: &str,
383    session_id: &str,
384    event: &Event,
385) -> Result<()> {
386    let stored: Option<String> = sqlx::query_scalar(
387        "SELECT state FROM sessions WHERE app_name = ? AND user_id = ? AND session_id = ?",
388    )
389    .bind(app_name)
390    .bind(user_id)
391    .bind(session_id)
392    .fetch_optional(&mut *conn)
393    .await
394    .map_err(|e| adk_core::AdkError::session(format!("query failed: {e}")))?;
395    let Some(stored) = stored else {
396        return Err(session_not_found_for(app_name, user_id, session_id));
397    };
398
399    let (app_delta, user_delta, session_delta) =
400        state_utils::extract_state_deltas(&event.actions.state_delta);
401    apply_tier_deltas(conn, app_name, user_id, app_delta, user_delta, event.timestamp).await?;
402
403    if session_delta.is_empty() {
404        sqlx::query(
405            "UPDATE sessions SET updated_at = ? WHERE app_name = ? AND user_id = ? AND session_id = ?",
406        )
407        .bind(event.timestamp.to_rfc3339())
408        .bind(app_name)
409        .bind(user_id)
410        .bind(session_id)
411        .execute(&mut *conn)
412        .await
413        .map_err(|e| adk_core::AdkError::session(format!("update failed: {e}")))?;
414    } else {
415        // Rows written by earlier releases also hold a copy of the app and user tiers; the
416        // rewrite keeps only the session tier.
417        let (_, _, mut session_state) =
418            state_utils::extract_state_deltas(&decode_state(Some(&stored))?);
419        session_state.extend(session_delta);
420        sqlx::query(
421            "UPDATE sessions SET state = ?, updated_at = ? \
422             WHERE app_name = ? AND user_id = ? AND session_id = ?",
423        )
424        .bind(encode_state(&session_state)?)
425        .bind(event.timestamp.to_rfc3339())
426        .bind(app_name)
427        .bind(user_id)
428        .bind(session_id)
429        .execute(&mut *conn)
430        .await
431        .map_err(|e| adk_core::AdkError::session(format!("update failed: {e}")))?;
432    }
433
434    insert_event(conn, app_name, user_id, session_id, event).await
435}
436
437/// Inserts `event` into the session's events without touching any state.
438async fn insert_event(
439    conn: &mut SqliteConnection,
440    app_name: &str,
441    user_id: &str,
442    session_id: &str,
443    event: &Event,
444) -> Result<()> {
445    let llm_response_json = serde_json::to_string(&event.llm_response)
446        .map_err(|e| adk_core::AdkError::session(format!("serialize failed: {e}")))?;
447    let actions_json = serde_json::to_string(&event.actions)
448        .map_err(|e| adk_core::AdkError::session(format!("serialize failed: {e}")))?;
449    let tool_ids_json = serde_json::to_string(&event.long_running_tool_ids)
450        .map_err(|e| adk_core::AdkError::session(format!("serialize failed: {e}")))?;
451
452    sqlx::query(
453        "INSERT INTO events (id, app_name, user_id, session_id, invocation_id, branch, author, \
454         timestamp, llm_response, actions, long_running_tool_ids) \
455         VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
456    )
457    .bind(&event.id)
458    .bind(app_name)
459    .bind(user_id)
460    .bind(session_id)
461    .bind(&event.invocation_id)
462    .bind(&event.branch)
463    .bind(&event.author)
464    .bind(event.timestamp.to_rfc3339())
465    .bind(&llm_response_json)
466    .bind(&actions_json)
467    .bind(&tool_ids_json)
468    .execute(&mut *conn)
469    .await
470    .map_err(|e| adk_core::AdkError::session(format!("insert failed: {e}")))?;
471
472    Ok(())
473}
474
475/// Reads the history of `identity` in read order, with the row ID of each decoded event.
476async fn load_history(
477    conn: &mut SqliteConnection,
478    identity: &AdkIdentity,
479) -> Result<(SessionHistory, Vec<i64>)> {
480    let (app_name, user_id, session_id) =
481        (identity.app_name.as_ref(), identity.user_id.as_ref(), identity.session_id.as_ref());
482    let row = sqlx::query(
483        "SELECT state, initial_state FROM sessions \
484         WHERE app_name = ? AND user_id = ? AND session_id = ?",
485    )
486    .bind(app_name)
487    .bind(user_id)
488    .bind(session_id)
489    .fetch_optional(&mut *conn)
490    .await
491    .map_err(|e| adk_core::AdkError::session(format!("query failed: {e}")))?
492    .ok_or_else(|| identity_not_found(identity))?;
493    // Rows written by earlier releases also hold a copy of the app and user tiers.
494    let (_, _, stored) = state_utils::extract_state_deltas(&decode_state(Some(row.get("state")))?);
495    let initial: Option<String> = row.get("initial_state");
496    let initial = initial.as_deref().map(|json| decode_state(Some(json))).transpose()?;
497
498    let rows = sqlx::query(
499        "SELECT *, rowid AS seq FROM events \
500         WHERE app_name = ? AND user_id = ? AND session_id = ? ORDER BY timestamp, rowid",
501    )
502    .bind(app_name)
503    .bind(user_id)
504    .bind(session_id)
505    .fetch_all(&mut *conn)
506    .await
507    .map_err(|e| adk_core::AdkError::session(format!("query failed: {e}")))?;
508    let mut events = Vec::with_capacity(rows.len());
509    let mut seqs = Vec::with_capacity(rows.len());
510    for row in &rows {
511        if let Some(event) = decode_event_row(row, session_id) {
512            seqs.push(row.get::<i64, _>("seq"));
513            events.push(event);
514        }
515    }
516    Ok((SessionHistory::new(events, stored, initial), seqs))
517}
518
519#[async_trait]
520impl SessionService for SqliteSessionService {
521    async fn create(&self, req: CreateRequest) -> Result<Box<dyn Session>> {
522        req.try_identity()?;
523        let session_id = req.session_id.unwrap_or_else(|| Uuid::new_v4().to_string());
524        let now = Utc::now();
525
526        let (app_delta, user_delta, session_state) = state_utils::extract_state_deltas(&req.state);
527
528        let mut tx = self
529            .pool
530            .begin_with(BEGIN_WRITE)
531            .await
532            .map_err(|e| adk_core::AdkError::session(format!("transaction failed: {e}")))?;
533
534        let (app_state, user_state) =
535            apply_tier_deltas(&mut tx, &req.app_name, &req.user_id, app_delta, user_delta, now)
536                .await?;
537
538        let encoded = encode_state(&session_state)?;
539        // A conflicting insert fails the transaction, which rolls back the tier writes above.
540        sqlx::query(
541            "INSERT INTO sessions \
542             (app_name, user_id, session_id, state, initial_state, created_at, updated_at) \
543             VALUES (?, ?, ?, ?, ?, ?, ?)",
544        )
545        .bind(&req.app_name)
546        .bind(&req.user_id)
547        .bind(&session_id)
548        .bind(&encoded)
549        .bind(&encoded)
550        .bind(now.to_rfc3339())
551        .bind(now.to_rfc3339())
552        .execute(&mut *tx)
553        .await
554        .map_err(|e| match e {
555            sqlx::Error::Database(db) if db.is_unique_violation() => {
556                session_already_exists(&req.app_name, &req.user_id, &session_id)
557            }
558            other => adk_core::AdkError::session(format!("insert failed: {other}")),
559        })?;
560
561        tx.commit()
562            .await
563            .map_err(|e| adk_core::AdkError::session(format!("commit failed: {e}")))?;
564
565        Ok(Box::new(DatabaseSession {
566            app_name: req.app_name,
567            user_id: req.user_id,
568            session_id,
569            state: state_utils::merge_states(&app_state, &user_state, &session_state),
570            events: Vec::new(),
571            updated_at: now,
572        }))
573    }
574
575    async fn get(&self, req: GetRequest) -> Result<Box<dyn Session>> {
576        req.try_identity()?;
577        let row = sqlx::query(
578            "SELECT s.state, s.updated_at, a.state AS app_state, u.state AS user_state \
579             FROM sessions s \
580             LEFT JOIN app_states a ON a.app_name = s.app_name \
581             LEFT JOIN user_states u ON u.app_name = s.app_name AND u.user_id = s.user_id \
582             WHERE s.app_name = ? AND s.user_id = ? AND s.session_id = ?",
583        )
584        .bind(&req.app_name)
585        .bind(&req.user_id)
586        .bind(&req.session_id)
587        .fetch_optional(&self.pool)
588        .await
589        .map_err(|e| adk_core::AdkError::session(format!("query failed: {e}")))?
590        .ok_or_else(|| crate::service::session_not_found(&req))?;
591
592        let state = state_utils::merge_current_tiers(
593            &decode_state(row.get("app_state"))?,
594            &decode_state(row.get("user_state"))?,
595            &decode_state(Some(row.get("state")))?,
596        );
597        let updated_at: String = row.get("updated_at");
598        let updated_at = DateTime::parse_from_rfc3339(&updated_at)
599            .map_err(|e| adk_core::AdkError::session(format!("parse date failed: {}", e)))?
600            .with_timezone(&Utc);
601
602        // Timestamps are RFC 3339 strings in one format, so text order is time order. The
603        // inner query keeps the most recent `num_recent_events` (-1 is no limit); the outer
604        // one restores chronological order.
605        let after = req.after.map(|after| after.to_rfc3339());
606        let limit = req.num_recent_events.map_or(-1, |n| i64::try_from(n).unwrap_or(i64::MAX));
607        let events: Vec<Event> = sqlx::query(
608            "SELECT * FROM (\
609                 SELECT *, rowid AS seq FROM events \
610                 WHERE app_name = ? AND user_id = ? AND session_id = ? \
611                   AND (? IS NULL OR timestamp >= ?) \
612                 ORDER BY timestamp DESC, rowid DESC LIMIT ?\
613             ) ORDER BY timestamp, seq",
614        )
615        .bind(&req.app_name)
616        .bind(&req.user_id)
617        .bind(&req.session_id)
618        .bind(&after)
619        .bind(&after)
620        .bind(limit)
621        .fetch_all(&self.pool)
622        .await
623        .map_err(|e| adk_core::AdkError::session(format!("query failed: {}", e)))?
624        .iter()
625        .filter_map(|row| decode_event_row(row, &req.session_id))
626        .collect();
627
628        Ok(Box::new(DatabaseSession {
629            app_name: req.app_name,
630            user_id: req.user_id,
631            session_id: req.session_id,
632            state,
633            events,
634            updated_at,
635        }))
636    }
637
638    async fn list(&self, req: ListRequest) -> Result<Vec<Box<dyn Session>>> {
639        validate_scope(&req.app_name, &req.user_id)?;
640        let limit = req.limit.map(|l| l as i64).unwrap_or(i64::MAX);
641        let offset = req.offset.unwrap_or(0) as i64;
642
643        let mut conn =
644            self.pool.acquire().await.map_err(|e| {
645                adk_core::AdkError::session(format!("database connection failed: {e}"))
646            })?;
647        let (app_state, user_state) = read_tiers(&mut conn, &req.app_name, &req.user_id).await?;
648
649        let rows = sqlx::query(
650            "SELECT session_id, state, updated_at FROM sessions \
651             WHERE app_name = ? AND user_id = ? \
652             ORDER BY updated_at DESC, session_id DESC LIMIT ? OFFSET ?",
653        )
654        .bind(&req.app_name)
655        .bind(&req.user_id)
656        .bind(limit)
657        .bind(offset)
658        .fetch_all(&mut *conn)
659        .await
660        .map_err(|e| adk_core::AdkError::session(format!("query failed: {}", e)))?;
661
662        let mut sessions = Vec::new();
663        for row in rows {
664            let stored: StateMap = serde_json::from_str(row.get("state")).unwrap_or_default();
665            let updated_at: String = row.get("updated_at");
666            let updated_at = DateTime::parse_from_rfc3339(&updated_at)
667                .map(|dt| dt.with_timezone(&Utc))
668                .unwrap_or_else(|_| Utc::now());
669
670            sessions.push(Box::new(DatabaseSession {
671                app_name: req.app_name.clone(),
672                user_id: req.user_id.clone(),
673                session_id: row.get("session_id"),
674                state: state_utils::merge_current_tiers(&app_state, &user_state, &stored),
675                events: Vec::new(),
676                updated_at,
677            }) as Box<dyn Session>);
678        }
679
680        Ok(sessions)
681    }
682
683    async fn delete(&self, req: DeleteRequest) -> Result<()> {
684        req.try_identity()?;
685        let mut tx = self
686            .pool
687            .begin()
688            .await
689            .map_err(|e| adk_core::AdkError::session(format!("transaction failed: {}", e)))?;
690
691        // Explicitly remove events first for deterministic cleanup across sqlite
692        // configurations where foreign-key enforcement may differ.
693        sqlx::query("DELETE FROM events WHERE app_name = ? AND user_id = ? AND session_id = ?")
694            .bind(&req.app_name)
695            .bind(&req.user_id)
696            .bind(&req.session_id)
697            .execute(&mut *tx)
698            .await
699            .map_err(|e| adk_core::AdkError::session(format!("delete events failed: {}", e)))?;
700
701        sqlx::query("DELETE FROM sessions WHERE app_name = ? AND user_id = ? AND session_id = ?")
702            .bind(&req.app_name)
703            .bind(&req.user_id)
704            .bind(&req.session_id)
705            .execute(&mut *tx)
706            .await
707            .map_err(|e| adk_core::AdkError::session(format!("delete failed: {}", e)))?;
708
709        tx.commit()
710            .await
711            .map_err(|e| adk_core::AdkError::session(format!("commit failed: {}", e)))?;
712
713        Ok(())
714    }
715
716    async fn delete_all_sessions(&self, app_name: &str, user_id: &str) -> Result<()> {
717        validate_scope(app_name, user_id)?;
718        let mut tx = self
719            .pool
720            .begin()
721            .await
722            .map_err(|e| adk_core::AdkError::session(format!("transaction failed: {}", e)))?;
723
724        sqlx::query("DELETE FROM events WHERE app_name = ? AND user_id = ?")
725            .bind(app_name)
726            .bind(user_id)
727            .execute(&mut *tx)
728            .await
729            .map_err(|e| {
730                adk_core::AdkError::session(format!("delete_all_sessions failed: {}", e))
731            })?;
732
733        sqlx::query("DELETE FROM sessions WHERE app_name = ? AND user_id = ?")
734            .bind(app_name)
735            .bind(user_id)
736            .execute(&mut *tx)
737            .await
738            .map_err(|e| {
739                adk_core::AdkError::session(format!("delete_all_sessions failed: {}", e))
740            })?;
741
742        sqlx::query("DELETE FROM user_states WHERE app_name = ? AND user_id = ?")
743            .bind(app_name)
744            .bind(user_id)
745            .execute(&mut *tx)
746            .await
747            .map_err(|e| {
748                adk_core::AdkError::session(format!("delete_all_sessions failed: {}", e))
749            })?;
750
751        tx.commit()
752            .await
753            .map_err(|e| adk_core::AdkError::session(format!("commit failed: {}", e)))?;
754
755        Ok(())
756    }
757
758    async fn append_event(&self, session_id: &str, mut event: Event) -> Result<()> {
759        validate_session_id(session_id)?;
760        event.actions.state_delta.retain(|k, _| !k.starts_with(KEY_PREFIX_TEMP));
761
762        let mut tx = self
763            .pool
764            .begin_with(BEGIN_WRITE)
765            .await
766            .map_err(|e| adk_core::AdkError::session(format!("transaction failed: {}", e)))?;
767
768        let session_rows =
769            sqlx::query("SELECT app_name, user_id FROM sessions WHERE session_id = ?")
770                .bind(session_id)
771                .fetch_all(&mut *tx)
772                .await
773                .map_err(|e| adk_core::AdkError::session(format!("query failed: {}", e)))?;
774
775        if session_rows.is_empty() {
776            return Err(session_id_not_found(session_id));
777        }
778        if session_rows.len() > 1 {
779            return Err(ambiguous_session_id(session_id));
780        }
781
782        let row = &session_rows[0];
783        let app_name: String = row.get("app_name");
784        let user_id: String = row.get("user_id");
785
786        apply_event(&mut tx, &app_name, &user_id, session_id, &event).await?;
787
788        tx.commit()
789            .await
790            .map_err(|e| adk_core::AdkError::session(format!("commit failed: {}", e)))?;
791
792        Ok(())
793    }
794
795    async fn append_event_for_identity(&self, req: AppendEventRequest) -> Result<()> {
796        let mut event = req.event;
797        event.actions.state_delta.retain(|k, _| !k.starts_with(KEY_PREFIX_TEMP));
798
799        let mut tx = self
800            .pool
801            .begin_with(BEGIN_WRITE)
802            .await
803            .map_err(|e| adk_core::AdkError::session(format!("transaction failed: {}", e)))?;
804
805        apply_event(
806            &mut tx,
807            req.identity.app_name.as_ref(),
808            req.identity.user_id.as_ref(),
809            req.identity.session_id.as_ref(),
810            &event,
811        )
812        .await?;
813
814        tx.commit()
815            .await
816            .map_err(|e| adk_core::AdkError::session(format!("commit failed: {}", e)))?;
817
818        Ok(())
819    }
820
821    async fn history(&self, identity: &AdkIdentity) -> Result<SessionHistory> {
822        let mut conn = self
823            .pool
824            .acquire()
825            .await
826            .map_err(|e| adk_core::AdkError::session(format!("connection failed: {e}")))?;
827        Ok(load_history(&mut conn, identity).await?.0)
828    }
829
830    async fn rewrite_history(&self, req: RewriteHistoryRequest) -> Result<HistoryOutcome> {
831        self.rewrite(req).await
832    }
833
834    async fn import_session(&self, req: ImportSessionRequest) -> Result<Box<dyn Session>> {
835        let (app_name, user_id, session_id) = (
836            req.identity.app_name.as_ref(),
837            req.identity.user_id.as_ref(),
838            req.identity.session_id.as_ref(),
839        );
840        let (_, _, state) = state_utils::extract_state_deltas(&req.state);
841        let (_, _, initial_state) = state_utils::extract_state_deltas(&req.initial_state);
842        let updated_at = req.events.last().map_or_else(Utc::now, |event| event.timestamp);
843
844        let mut tx = self
845            .pool
846            .begin_with(BEGIN_WRITE)
847            .await
848            .map_err(|e| adk_core::AdkError::session(format!("transaction failed: {e}")))?;
849        sqlx::query(
850            "INSERT INTO sessions \
851             (app_name, user_id, session_id, state, initial_state, created_at, updated_at) \
852             VALUES (?, ?, ?, ?, ?, ?, ?)",
853        )
854        .bind(app_name)
855        .bind(user_id)
856        .bind(session_id)
857        .bind(encode_state(&state)?)
858        .bind(encode_state(&initial_state)?)
859        .bind(Utc::now().to_rfc3339())
860        .bind(updated_at.to_rfc3339())
861        .execute(&mut *tx)
862        .await
863        .map_err(|e| match e {
864            sqlx::Error::Database(db) if db.is_unique_violation() => {
865                session_already_exists(app_name, user_id, session_id)
866            }
867            other => adk_core::AdkError::session(format!("insert failed: {other}")),
868        })?;
869        for event in &req.events {
870            insert_event(&mut tx, app_name, user_id, session_id, event).await?;
871        }
872        let (app_state, user_state) = read_tiers(&mut tx, app_name, user_id).await?;
873        tx.commit()
874            .await
875            .map_err(|e| adk_core::AdkError::session(format!("commit failed: {e}")))?;
876
877        Ok(Box::new(DatabaseSession {
878            app_name: app_name.to_string(),
879            user_id: user_id.to_string(),
880            session_id: session_id.to_string(),
881            state: state_utils::merge_states(&app_state, &user_state, &state),
882            events: req.events,
883            updated_at,
884        }))
885    }
886}
887
888impl SqliteSessionService {
889    /// Applies a history rewrite in one [`BEGIN_WRITE`] transaction: reads the history, checks
890    /// and plans the rewrite, then deletes the removed rows, updates the replaced ones in
891    /// place, and writes the rebuilt session state.
892    async fn rewrite(&self, req: RewriteHistoryRequest) -> Result<HistoryOutcome> {
893        let identity = &req.identity;
894        let (app_name, user_id, session_id) =
895            (identity.app_name.as_ref(), identity.user_id.as_ref(), identity.session_id.as_ref());
896        let mut tx = self
897            .pool
898            .begin_with(BEGIN_WRITE)
899            .await
900            .map_err(|e| adk_core::AdkError::session(format!("transaction failed: {e}")))?;
901
902        let (history, seqs) = load_history(&mut tx, identity).await?;
903        let rewritten = history.rewrite(identity, &req.rewrite, req.expected_version.as_deref())?;
904        let change = &rewritten.change;
905
906        if change.operation == HistoryOperation::Rewind {
907            // Read order is (timestamp, rowid), so the kept events are those up to the last
908            // kept row; every later row goes, including rows that no longer decode.
909            let keep = rewritten.events.len();
910            match keep.checked_sub(1).map(|last| (&history.events[last], seqs[last])) {
911                Some((last, seq)) => sqlx::query(
912                    "DELETE FROM events WHERE app_name = ? AND user_id = ? AND session_id = ? \
913                     AND (timestamp > ? OR (timestamp = ? AND rowid > ?))",
914                )
915                .bind(app_name)
916                .bind(user_id)
917                .bind(session_id)
918                .bind(last.timestamp.to_rfc3339())
919                .bind(last.timestamp.to_rfc3339())
920                .bind(seq),
921                None => sqlx::query(
922                    "DELETE FROM events WHERE app_name = ? AND user_id = ? AND session_id = ?",
923                )
924                .bind(app_name)
925                .bind(user_id)
926                .bind(session_id),
927            }
928            .execute(&mut *tx)
929            .await
930            .map_err(|e| adk_core::AdkError::session(format!("delete events failed: {e}")))?;
931        } else {
932            for event_id in &change.removed {
933                sqlx::query(
934                    "DELETE FROM events \
935                     WHERE app_name = ? AND user_id = ? AND session_id = ? AND id = ?",
936                )
937                .bind(app_name)
938                .bind(user_id)
939                .bind(session_id)
940                .bind(event_id)
941                .execute(&mut *tx)
942                .await
943                .map_err(|e| adk_core::AdkError::session(format!("delete event failed: {e}")))?;
944            }
945            for event in rewritten.events.iter().filter(|e| change.replaced.contains(&e.id)) {
946                sqlx::query(
947                    "UPDATE events SET invocation_id = ?, branch = ?, author = ?, \
948                     llm_response = ?, actions = ?, long_running_tool_ids = ? \
949                     WHERE app_name = ? AND user_id = ? AND session_id = ? AND id = ?",
950                )
951                .bind(&event.invocation_id)
952                .bind(&event.branch)
953                .bind(&event.author)
954                .bind(
955                    serde_json::to_string(&event.llm_response).map_err(|e| {
956                        adk_core::AdkError::session(format!("serialize failed: {e}"))
957                    })?,
958                )
959                .bind(
960                    serde_json::to_string(&event.actions).map_err(|e| {
961                        adk_core::AdkError::session(format!("serialize failed: {e}"))
962                    })?,
963                )
964                .bind(
965                    serde_json::to_string(&event.long_running_tool_ids).map_err(|e| {
966                        adk_core::AdkError::session(format!("serialize failed: {e}"))
967                    })?,
968                )
969                .bind(app_name)
970                .bind(user_id)
971                .bind(session_id)
972                .bind(&event.id)
973                .execute(&mut *tx)
974                .await
975                .map_err(|e| adk_core::AdkError::session(format!("update event failed: {e}")))?;
976            }
977        }
978
979        let now = Utc::now();
980        sqlx::query(
981            "UPDATE sessions SET state = ?, updated_at = ? \
982             WHERE app_name = ? AND user_id = ? AND session_id = ?",
983        )
984        .bind(encode_state(&rewritten.state)?)
985        .bind(now.to_rfc3339())
986        .bind(app_name)
987        .bind(user_id)
988        .bind(session_id)
989        .execute(&mut *tx)
990        .await
991        .map_err(|e| adk_core::AdkError::session(format!("update failed: {e}")))?;
992        let (app_state, user_state) = read_tiers(&mut tx, app_name, user_id).await?;
993
994        tx.commit()
995            .await
996            .map_err(|e| adk_core::AdkError::session(format!("commit failed: {e}")))?;
997
998        let session = Box::new(DatabaseSession {
999            app_name: app_name.to_string(),
1000            user_id: user_id.to_string(),
1001            session_id: session_id.to_string(),
1002            state: state_utils::merge_states(&app_state, &user_state, &rewritten.state),
1003            events: rewritten.events,
1004            updated_at: now,
1005        });
1006        Ok(HistoryOutcome::new(session, rewritten.change))
1007    }
1008}
1009
1010struct DatabaseSession {
1011    app_name: String,
1012    user_id: String,
1013    session_id: String,
1014    state: HashMap<String, Value>,
1015    events: Vec<Event>,
1016    updated_at: DateTime<Utc>,
1017}
1018
1019impl Session for DatabaseSession {
1020    fn id(&self) -> &str {
1021        &self.session_id
1022    }
1023
1024    fn app_name(&self) -> &str {
1025        &self.app_name
1026    }
1027
1028    fn user_id(&self) -> &str {
1029        &self.user_id
1030    }
1031
1032    fn state(&self) -> &dyn State {
1033        self
1034    }
1035
1036    fn events(&self) -> &dyn Events {
1037        self
1038    }
1039
1040    fn last_update_time(&self) -> DateTime<Utc> {
1041        self.updated_at
1042    }
1043
1044    fn take_events(&mut self) -> Vec<Event> {
1045        std::mem::take(&mut self.events)
1046    }
1047}
1048
1049impl State for DatabaseSession {
1050    fn get(&self, key: &str) -> Option<Value> {
1051        self.state.get(key).cloned()
1052    }
1053
1054    fn set(&mut self, key: String, value: Value) {
1055        if let Err(msg) = adk_core::validate_state_key(&key) {
1056            tracing::warn!(key = %key, "rejecting invalid state key: {msg}");
1057            return;
1058        }
1059        self.state.insert(key, value);
1060    }
1061
1062    fn all(&self) -> HashMap<String, Value> {
1063        self.state.clone()
1064    }
1065}
1066
1067impl Events for DatabaseSession {
1068    fn all(&self) -> Vec<Event> {
1069        self.events.clone()
1070    }
1071
1072    fn len(&self) -> usize {
1073        self.events.len()
1074    }
1075
1076    fn at(&self, index: usize) -> Option<&Event> {
1077        self.events.get(index)
1078    }
1079}