adk-session 3.0.0

Session management and state persistence for Rust Agent Development Kit (ADK-Rust) agents
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
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
use crate::history::{
    HistoryOperation, HistoryOutcome, ImportSessionRequest, RewriteHistoryRequest, SessionHistory,
};
use crate::service::{
    ambiguous_session_id, identity_not_found, session_already_exists, session_id_not_found,
    session_not_found_for, validate_scope, validate_session_id,
};
use crate::{
    AppendEventRequest, CreateRequest, DeleteRequest, Event, Events, GetRequest, KEY_PREFIX_TEMP,
    ListRequest, Session, SessionService, State, state_utils,
};
use adk_core::Result;
use adk_core::identity::AdkIdentity;
use async_trait::async_trait;
use chrono::{DateTime, Utc};
use serde_json::Value;
use sqlx::{
    Row,
    sqlite::{SqliteConnectOptions, SqliteConnection, SqlitePool, SqliteRow, SqliteSynchronous},
};
use std::collections::HashMap;
use std::str::FromStr;
use std::time::Duration;
use uuid::Uuid;

/// Decodes a stored event row, logging and skipping a row that no longer deserializes
/// so one corrupt event does not hide the rest of the session history.
fn decode_event_row(row: &SqliteRow, session_id: &str) -> Option<Event> {
    fn decode(row: &SqliteRow) -> std::result::Result<Event, String> {
        let llm_response =
            serde_json::from_str(row.try_get("llm_response").map_err(|e| e.to_string())?)
                .map_err(|e| format!("llm_response: {e}"))?;
        let actions = serde_json::from_str(row.try_get("actions").map_err(|e| e.to_string())?)
            .map_err(|e| format!("actions: {e}"))?;
        let long_running_tool_ids =
            serde_json::from_str(row.try_get("long_running_tool_ids").map_err(|e| e.to_string())?)
                .map_err(|e| format!("long_running_tool_ids: {e}"))?;
        let timestamp: String = row.try_get("timestamp").map_err(|e| e.to_string())?;
        let timestamp = DateTime::parse_from_rfc3339(&timestamp)
            .map_err(|e| format!("timestamp: {e}"))?
            .with_timezone(&Utc);
        Ok(Event {
            id: row.try_get("id").map_err(|e| e.to_string())?,
            timestamp,
            invocation_id: row.try_get("invocation_id").map_err(|e| e.to_string())?,
            branch: row.try_get("branch").map_err(|e| e.to_string())?,
            author: row.try_get("author").map_err(|e| e.to_string())?,
            llm_request: None,
            llm_response,
            actions,
            long_running_tool_ids,
            provider_metadata: HashMap::new(),
        })
    }

    match decode(row) {
        Ok(event) => Some(event),
        Err(error) => {
            let event_id: String = row.try_get("id").unwrap_or_else(|_| "<unknown>".to_string());
            tracing::warn!(
                session.id = %session_id,
                event.id = %event_id,
                error = %error,
                "skipping stored event that failed to deserialize"
            );
            None
        }
    }
}

/// SQLite-backed session service using `sqlx`.
pub struct SqliteSessionService {
    pool: SqlitePool,
}

impl SqliteSessionService {
    /// Connect to SQLite and create a connection pool.
    ///
    /// Enables foreign keys via `PRAGMA foreign_keys = ON`. A writer waits up to 30 seconds
    /// for the database lock, so concurrent appends to a file database queue behind
    /// `BEGIN IMMEDIATE` instead of failing with `database is locked`.
    ///
    /// A file database is switched to write-ahead-log mode (`journal_mode = WAL`), which
    /// persists in the file: SQLite creates `<file>-wal` and `<file>-shm` beside it while it
    /// is open, readers never block the writer, and a commit appends to the log instead of
    /// rewriting a rollback journal. Every connection keeps `synchronous = FULL`, so each
    /// committed event is synced to disk and survives power loss, as the action ledger and
    /// approval stores require when they share the file. A file another process holds in
    /// rollback mode keeps that mode, and a warning is logged. To trade the last commits
    /// before a power loss for fewer syncs (`synchronous = NORMAL`), or to stay in rollback
    /// mode on a filesystem without shared memory, build the pool yourself and use
    /// [`from_pool`](Self::from_pool).
    ///
    /// # Errors
    ///
    /// Returns an error when the URL is invalid, the database cannot be opened, or foreign
    /// keys cannot be enabled.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use adk_session::SqliteSessionService;
    ///
    /// # async fn example() -> adk_core::Result<()> {
    /// let service = SqliteSessionService::new("sqlite:sessions.db?mode=rwc").await?;
    /// service.migrate().await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn new(database_url: &str) -> Result<Self> {
        let options = SqliteConnectOptions::from_str(database_url)
            .map_err(|e| adk_core::AdkError::session(format!("invalid sqlite url: {e}")))?
            .busy_timeout(BUSY_TIMEOUT)
            .synchronous(SqliteSynchronous::Full);
        let pool = SqlitePool::connect_with(options)
            .await
            .map_err(|e| adk_core::AdkError::session(format!("database connection failed: {e}")))?;
        sqlx::query("PRAGMA foreign_keys = ON").execute(&pool).await.map_err(|e| {
            adk_core::AdkError::session(format!("failed to enable sqlite foreign keys: {}", e))
        })?;
        // The switch needs the file to itself, so it is not a connect option: a file another
        // process holds in rollback mode would fail every new connection instead of keeping
        // its mode. An in-memory database reports `memory` and has no log.
        match sqlx::query_scalar::<_, String>("PRAGMA journal_mode = WAL").fetch_one(&pool).await {
            Ok(mode) if !matches!(mode.to_ascii_lowercase().as_str(), "wal" | "memory") => {
                tracing::warn!(journal.mode = %mode, "sqlite session store stays out of WAL mode");
            }
            Ok(_) => {}
            Err(error) => {
                tracing::warn!(error = %error, "sqlite session store keeps its journal mode");
            }
        }
        Ok(Self { pool })
    }

    /// Create a session service from an existing connection pool.
    ///
    /// Use this to share a pool with tuned settings across multiple
    /// services, or in tests where you need direct pool access.
    ///
    /// **Note:** The caller is responsible for enabling foreign keys
    /// (`PRAGMA foreign_keys = ON`) on the pool if needed, and for its journal mode and
    /// `synchronous` setting: unlike [`new`](Self::new), this does not switch the file to
    /// write-ahead-log mode.
    ///
    /// # Example
    ///
    /// A pool in WAL mode with `synchronous = NORMAL`: a commit is not synced on its own, so a
    /// power loss can drop the last commits, never the file's consistency.
    ///
    /// ```rust,no_run
    /// use adk_session::SqliteSessionService;
    /// use sqlx::sqlite::{SqliteConnectOptions, SqliteJournalMode, SqlitePool, SqliteSynchronous};
    /// use std::str::FromStr;
    ///
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let options = SqliteConnectOptions::from_str("sqlite:sessions.db?mode=rwc")?
    ///     .foreign_keys(true)
    ///     .journal_mode(SqliteJournalMode::Wal)
    ///     .synchronous(SqliteSynchronous::Normal);
    /// let service = SqliteSessionService::from_pool(SqlitePool::connect_with(options).await?);
    /// service.migrate().await?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn from_pool(pool: SqlitePool) -> Self {
        Self { pool }
    }

    /// Returns a reference to the underlying connection pool.
    pub fn pool(&self) -> &SqlitePool {
        &self.pool
    }

    /// The registry table used to track applied migration versions.
    const REGISTRY_TABLE: &'static str = "_adk_session_migrations";

    /// Compiled-in migration steps for the SQLite session backend.
    ///
    /// Each entry is `(version, description, sql)`. Version 1 is the baseline
    /// that creates the initial schema matching the original `CREATE TABLE IF
    /// NOT EXISTS` statements. Version 2 adds `sessions.initial_state`, the session state a
    /// session was created with, which rewind rebuilds from; it is `NULL` for sessions created
    /// before it. Version 3 indexes `events` by session in read order, so loading, rewinding
    /// or deleting one session reads that session's rows instead of every event in the file.
    const SQLITE_SESSION_MIGRATIONS: &'static [(i64, &'static str, &'static str)] = &[
        (
            1,
            "create initial session tables",
            "\
CREATE TABLE IF NOT EXISTS sessions (\
    app_name TEXT NOT NULL, \
    user_id TEXT NOT NULL, \
    session_id TEXT NOT NULL, \
    state TEXT NOT NULL, \
    created_at TEXT NOT NULL, \
    updated_at TEXT NOT NULL, \
    PRIMARY KEY (app_name, user_id, session_id)\
);\
CREATE TABLE IF NOT EXISTS events (\
    id TEXT NOT NULL, \
    app_name TEXT NOT NULL, \
    user_id TEXT NOT NULL, \
    session_id TEXT NOT NULL, \
    invocation_id TEXT NOT NULL, \
    branch TEXT NOT NULL, \
    author TEXT NOT NULL, \
    timestamp TEXT NOT NULL, \
    llm_response TEXT NOT NULL, \
    actions TEXT NOT NULL, \
    long_running_tool_ids TEXT NOT NULL, \
    PRIMARY KEY (id, app_name, user_id, session_id), \
    FOREIGN KEY (app_name, user_id, session_id) \
        REFERENCES sessions(app_name, user_id, session_id) \
        ON DELETE CASCADE\
);\
CREATE TABLE IF NOT EXISTS app_states (\
    app_name TEXT PRIMARY KEY, \
    state TEXT NOT NULL, \
    updated_at TEXT NOT NULL\
);\
CREATE TABLE IF NOT EXISTS user_states (\
    app_name TEXT NOT NULL, \
    user_id TEXT NOT NULL, \
    state TEXT NOT NULL, \
    updated_at TEXT NOT NULL, \
    PRIMARY KEY (app_name, user_id)\
);",
        ),
        (
            2,
            "record the session state each session was created with",
            "ALTER TABLE sessions ADD COLUMN initial_state TEXT;",
        ),
        (
            3,
            "index events by session in read order",
            "CREATE INDEX IF NOT EXISTS idx_events_session_ts \
             ON events (app_name, user_id, session_id, timestamp);",
        ),
    ];

    /// Run all pending schema migrations for this backend.
    pub async fn migrate(&self) -> Result<()> {
        let pool = &self.pool;
        crate::migration::sqlite_runner::run_sql_migrations(
            pool,
            Self::REGISTRY_TABLE,
            Self::SQLITE_SESSION_MIGRATIONS,
            || async {
                let row = sqlx::query(
                    "SELECT COUNT(*) AS cnt FROM sqlite_master \
                     WHERE type='table' AND name='sessions'",
                )
                .fetch_one(pool)
                .await
                .map_err(|e| {
                    adk_core::AdkError::session(format!("baseline detection failed: {e}"))
                })?;
                let count: i64 = row.try_get("cnt").unwrap_or(0);
                Ok(count > 0)
            },
        )
        .await
    }

    /// Returns the highest applied migration version, or 0 if no registry
    /// exists or the registry is empty.
    ///
    /// # Errors
    ///
    /// Returns an error when the registry cannot be read for any reason other
    /// than the table being absent, such as a lost connection or a missing
    /// privilege.
    pub async fn schema_version(&self) -> Result<i64> {
        crate::migration::sqlite_runner::sql_schema_version(&self.pool, Self::REGISTRY_TABLE).await
    }
}

/// How long a connection waits for the database lock before `database is locked`.
///
/// Concurrent appends to a file database queue behind [`BEGIN_WRITE`]; sqlx's default of
/// five seconds is shorter than that queue on a slow disk.
const BUSY_TIMEOUT: Duration = Duration::from_secs(30);

/// Statement that opens every transaction which reads state and writes it back.
///
/// `BEGIN IMMEDIATE` takes the database write lock before the first read, so a concurrent
/// writer waits for the commit instead of overwriting a delta it never read.
const BEGIN_WRITE: &str = "BEGIN IMMEDIATE";

type StateMap = HashMap<String, Value>;

/// Decodes a stored state column; a missing row is empty state.
fn decode_state(json: Option<&str>) -> Result<StateMap> {
    match json {
        Some(json) => serde_json::from_str(json)
            .map_err(|e| adk_core::AdkError::session(format!("deserialize failed: {e}"))),
        None => Ok(HashMap::new()),
    }
}

fn encode_state(state: &StateMap) -> Result<String> {
    serde_json::to_string(state)
        .map_err(|e| adk_core::AdkError::session(format!("serialize failed: {e}")))
}

/// Reads the current app and user state tiers.
async fn read_tiers(
    conn: &mut SqliteConnection,
    app_name: &str,
    user_id: &str,
) -> Result<(StateMap, StateMap)> {
    let app_state: Option<String> =
        sqlx::query_scalar("SELECT state FROM app_states WHERE app_name = ?")
            .bind(app_name)
            .fetch_optional(&mut *conn)
            .await
            .map_err(|e| adk_core::AdkError::session(format!("query failed: {e}")))?;
    let user_state: Option<String> =
        sqlx::query_scalar("SELECT state FROM user_states WHERE app_name = ? AND user_id = ?")
            .bind(app_name)
            .bind(user_id)
            .fetch_optional(&mut *conn)
            .await
            .map_err(|e| adk_core::AdkError::session(format!("query failed: {e}")))?;
    Ok((decode_state(app_state.as_deref())?, decode_state(user_state.as_deref())?))
}

/// Merges each non-empty tier delta into the stored tier and returns both tiers after
/// the write.
///
/// Runs inside a [`BEGIN_WRITE`] transaction, so no other writer commits between the read
/// and the write.
async fn apply_tier_deltas(
    conn: &mut SqliteConnection,
    app_name: &str,
    user_id: &str,
    app_delta: StateMap,
    user_delta: StateMap,
    now: DateTime<Utc>,
) -> Result<(StateMap, StateMap)> {
    let (mut app_state, mut user_state) = read_tiers(conn, app_name, user_id).await?;

    if !app_delta.is_empty() {
        app_state.extend(app_delta);
        sqlx::query(
            "INSERT OR REPLACE INTO app_states (app_name, state, updated_at) VALUES (?, ?, ?)",
        )
        .bind(app_name)
        .bind(encode_state(&app_state)?)
        .bind(now.to_rfc3339())
        .execute(&mut *conn)
        .await
        .map_err(|e| adk_core::AdkError::session(format!("insert failed: {e}")))?;
    }

    if !user_delta.is_empty() {
        user_state.extend(user_delta);
        sqlx::query(
            "INSERT OR REPLACE INTO user_states (app_name, user_id, state, updated_at) \
             VALUES (?, ?, ?, ?)",
        )
        .bind(app_name)
        .bind(user_id)
        .bind(encode_state(&user_state)?)
        .bind(now.to_rfc3339())
        .execute(&mut *conn)
        .await
        .map_err(|e| adk_core::AdkError::session(format!("insert failed: {e}")))?;
    }

    Ok((app_state, user_state))
}

/// Applies `event` to the session `(app_name, user_id, session_id)` inside a
/// [`BEGIN_WRITE`] transaction: merges each tier's delta, bumps `updated_at`, and inserts
/// the event.
async fn apply_event(
    conn: &mut SqliteConnection,
    app_name: &str,
    user_id: &str,
    session_id: &str,
    event: &Event,
) -> Result<()> {
    let stored: Option<String> = sqlx::query_scalar(
        "SELECT state FROM sessions WHERE app_name = ? AND user_id = ? AND session_id = ?",
    )
    .bind(app_name)
    .bind(user_id)
    .bind(session_id)
    .fetch_optional(&mut *conn)
    .await
    .map_err(|e| adk_core::AdkError::session(format!("query failed: {e}")))?;
    let Some(stored) = stored else {
        return Err(session_not_found_for(app_name, user_id, session_id));
    };

    let (app_delta, user_delta, session_delta) =
        state_utils::extract_state_deltas(&event.actions.state_delta);
    apply_tier_deltas(conn, app_name, user_id, app_delta, user_delta, event.timestamp).await?;

    if session_delta.is_empty() {
        sqlx::query(
            "UPDATE sessions SET updated_at = ? WHERE app_name = ? AND user_id = ? AND session_id = ?",
        )
        .bind(event.timestamp.to_rfc3339())
        .bind(app_name)
        .bind(user_id)
        .bind(session_id)
        .execute(&mut *conn)
        .await
        .map_err(|e| adk_core::AdkError::session(format!("update failed: {e}")))?;
    } else {
        // Rows written by earlier releases also hold a copy of the app and user tiers; the
        // rewrite keeps only the session tier.
        let (_, _, mut session_state) =
            state_utils::extract_state_deltas(&decode_state(Some(&stored))?);
        session_state.extend(session_delta);
        sqlx::query(
            "UPDATE sessions SET state = ?, updated_at = ? \
             WHERE app_name = ? AND user_id = ? AND session_id = ?",
        )
        .bind(encode_state(&session_state)?)
        .bind(event.timestamp.to_rfc3339())
        .bind(app_name)
        .bind(user_id)
        .bind(session_id)
        .execute(&mut *conn)
        .await
        .map_err(|e| adk_core::AdkError::session(format!("update failed: {e}")))?;
    }

    insert_event(conn, app_name, user_id, session_id, event).await
}

/// Inserts `event` into the session's events without touching any state.
async fn insert_event(
    conn: &mut SqliteConnection,
    app_name: &str,
    user_id: &str,
    session_id: &str,
    event: &Event,
) -> Result<()> {
    let llm_response_json = serde_json::to_string(&event.llm_response)
        .map_err(|e| adk_core::AdkError::session(format!("serialize failed: {e}")))?;
    let actions_json = serde_json::to_string(&event.actions)
        .map_err(|e| adk_core::AdkError::session(format!("serialize failed: {e}")))?;
    let tool_ids_json = serde_json::to_string(&event.long_running_tool_ids)
        .map_err(|e| adk_core::AdkError::session(format!("serialize failed: {e}")))?;

    sqlx::query(
        "INSERT INTO events (id, app_name, user_id, session_id, invocation_id, branch, author, \
         timestamp, llm_response, actions, long_running_tool_ids) \
         VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
    )
    .bind(&event.id)
    .bind(app_name)
    .bind(user_id)
    .bind(session_id)
    .bind(&event.invocation_id)
    .bind(&event.branch)
    .bind(&event.author)
    .bind(event.timestamp.to_rfc3339())
    .bind(&llm_response_json)
    .bind(&actions_json)
    .bind(&tool_ids_json)
    .execute(&mut *conn)
    .await
    .map_err(|e| adk_core::AdkError::session(format!("insert failed: {e}")))?;

    Ok(())
}

/// Reads the history of `identity` in read order, with the row ID of each decoded event.
async fn load_history(
    conn: &mut SqliteConnection,
    identity: &AdkIdentity,
) -> Result<(SessionHistory, Vec<i64>)> {
    let (app_name, user_id, session_id) =
        (identity.app_name.as_ref(), identity.user_id.as_ref(), identity.session_id.as_ref());
    let row = sqlx::query(
        "SELECT state, initial_state FROM sessions \
         WHERE app_name = ? AND user_id = ? AND session_id = ?",
    )
    .bind(app_name)
    .bind(user_id)
    .bind(session_id)
    .fetch_optional(&mut *conn)
    .await
    .map_err(|e| adk_core::AdkError::session(format!("query failed: {e}")))?
    .ok_or_else(|| identity_not_found(identity))?;
    // Rows written by earlier releases also hold a copy of the app and user tiers.
    let (_, _, stored) = state_utils::extract_state_deltas(&decode_state(Some(row.get("state")))?);
    let initial: Option<String> = row.get("initial_state");
    let initial = initial.as_deref().map(|json| decode_state(Some(json))).transpose()?;

    let rows = sqlx::query(
        "SELECT *, rowid AS seq FROM events \
         WHERE app_name = ? AND user_id = ? AND session_id = ? ORDER BY timestamp, rowid",
    )
    .bind(app_name)
    .bind(user_id)
    .bind(session_id)
    .fetch_all(&mut *conn)
    .await
    .map_err(|e| adk_core::AdkError::session(format!("query failed: {e}")))?;
    let mut events = Vec::with_capacity(rows.len());
    let mut seqs = Vec::with_capacity(rows.len());
    for row in &rows {
        if let Some(event) = decode_event_row(row, session_id) {
            seqs.push(row.get::<i64, _>("seq"));
            events.push(event);
        }
    }
    Ok((SessionHistory::new(events, stored, initial), seqs))
}

#[async_trait]
impl SessionService for SqliteSessionService {
    async fn create(&self, req: CreateRequest) -> Result<Box<dyn Session>> {
        req.try_identity()?;
        let session_id = req.session_id.unwrap_or_else(|| Uuid::new_v4().to_string());
        let now = Utc::now();

        let (app_delta, user_delta, session_state) = state_utils::extract_state_deltas(&req.state);

        let mut tx = self
            .pool
            .begin_with(BEGIN_WRITE)
            .await
            .map_err(|e| adk_core::AdkError::session(format!("transaction failed: {e}")))?;

        let (app_state, user_state) =
            apply_tier_deltas(&mut tx, &req.app_name, &req.user_id, app_delta, user_delta, now)
                .await?;

        let encoded = encode_state(&session_state)?;
        // A conflicting insert fails the transaction, which rolls back the tier writes above.
        sqlx::query(
            "INSERT INTO sessions \
             (app_name, user_id, session_id, state, initial_state, created_at, updated_at) \
             VALUES (?, ?, ?, ?, ?, ?, ?)",
        )
        .bind(&req.app_name)
        .bind(&req.user_id)
        .bind(&session_id)
        .bind(&encoded)
        .bind(&encoded)
        .bind(now.to_rfc3339())
        .bind(now.to_rfc3339())
        .execute(&mut *tx)
        .await
        .map_err(|e| match e {
            sqlx::Error::Database(db) if db.is_unique_violation() => {
                session_already_exists(&req.app_name, &req.user_id, &session_id)
            }
            other => adk_core::AdkError::session(format!("insert failed: {other}")),
        })?;

        tx.commit()
            .await
            .map_err(|e| adk_core::AdkError::session(format!("commit failed: {e}")))?;

        Ok(Box::new(DatabaseSession {
            app_name: req.app_name,
            user_id: req.user_id,
            session_id,
            state: state_utils::merge_states(&app_state, &user_state, &session_state),
            events: Vec::new(),
            updated_at: now,
        }))
    }

    async fn get(&self, req: GetRequest) -> Result<Box<dyn Session>> {
        req.try_identity()?;
        let row = sqlx::query(
            "SELECT s.state, s.updated_at, a.state AS app_state, u.state AS user_state \
             FROM sessions s \
             LEFT JOIN app_states a ON a.app_name = s.app_name \
             LEFT JOIN user_states u ON u.app_name = s.app_name AND u.user_id = s.user_id \
             WHERE s.app_name = ? AND s.user_id = ? AND s.session_id = ?",
        )
        .bind(&req.app_name)
        .bind(&req.user_id)
        .bind(&req.session_id)
        .fetch_optional(&self.pool)
        .await
        .map_err(|e| adk_core::AdkError::session(format!("query failed: {e}")))?
        .ok_or_else(|| crate::service::session_not_found(&req))?;

        let state = state_utils::merge_current_tiers(
            &decode_state(row.get("app_state"))?,
            &decode_state(row.get("user_state"))?,
            &decode_state(Some(row.get("state")))?,
        );
        let updated_at: String = row.get("updated_at");
        let updated_at = DateTime::parse_from_rfc3339(&updated_at)
            .map_err(|e| adk_core::AdkError::session(format!("parse date failed: {}", e)))?
            .with_timezone(&Utc);

        // Timestamps are RFC 3339 strings in one format, so text order is time order. The
        // inner query keeps the most recent `num_recent_events` (-1 is no limit); the outer
        // one restores chronological order.
        let after = req.after.map(|after| after.to_rfc3339());
        let limit = req.num_recent_events.map_or(-1, |n| i64::try_from(n).unwrap_or(i64::MAX));
        let events: Vec<Event> = sqlx::query(
            "SELECT * FROM (\
                 SELECT *, rowid AS seq FROM events \
                 WHERE app_name = ? AND user_id = ? AND session_id = ? \
                   AND (? IS NULL OR timestamp >= ?) \
                 ORDER BY timestamp DESC, rowid DESC LIMIT ?\
             ) ORDER BY timestamp, seq",
        )
        .bind(&req.app_name)
        .bind(&req.user_id)
        .bind(&req.session_id)
        .bind(&after)
        .bind(&after)
        .bind(limit)
        .fetch_all(&self.pool)
        .await
        .map_err(|e| adk_core::AdkError::session(format!("query failed: {}", e)))?
        .iter()
        .filter_map(|row| decode_event_row(row, &req.session_id))
        .collect();

        Ok(Box::new(DatabaseSession {
            app_name: req.app_name,
            user_id: req.user_id,
            session_id: req.session_id,
            state,
            events,
            updated_at,
        }))
    }

    async fn list(&self, req: ListRequest) -> Result<Vec<Box<dyn Session>>> {
        validate_scope(&req.app_name, &req.user_id)?;
        let limit = req.limit.map(|l| l as i64).unwrap_or(i64::MAX);
        let offset = req.offset.unwrap_or(0) as i64;

        let mut conn =
            self.pool.acquire().await.map_err(|e| {
                adk_core::AdkError::session(format!("database connection failed: {e}"))
            })?;
        let (app_state, user_state) = read_tiers(&mut conn, &req.app_name, &req.user_id).await?;

        let rows = sqlx::query(
            "SELECT session_id, state, updated_at FROM sessions \
             WHERE app_name = ? AND user_id = ? \
             ORDER BY updated_at DESC, session_id DESC LIMIT ? OFFSET ?",
        )
        .bind(&req.app_name)
        .bind(&req.user_id)
        .bind(limit)
        .bind(offset)
        .fetch_all(&mut *conn)
        .await
        .map_err(|e| adk_core::AdkError::session(format!("query failed: {}", e)))?;

        let mut sessions = Vec::new();
        for row in rows {
            let stored: StateMap = serde_json::from_str(row.get("state")).unwrap_or_default();
            let updated_at: String = row.get("updated_at");
            let updated_at = DateTime::parse_from_rfc3339(&updated_at)
                .map(|dt| dt.with_timezone(&Utc))
                .unwrap_or_else(|_| Utc::now());

            sessions.push(Box::new(DatabaseSession {
                app_name: req.app_name.clone(),
                user_id: req.user_id.clone(),
                session_id: row.get("session_id"),
                state: state_utils::merge_current_tiers(&app_state, &user_state, &stored),
                events: Vec::new(),
                updated_at,
            }) as Box<dyn Session>);
        }

        Ok(sessions)
    }

    async fn delete(&self, req: DeleteRequest) -> Result<()> {
        req.try_identity()?;
        let mut tx = self
            .pool
            .begin()
            .await
            .map_err(|e| adk_core::AdkError::session(format!("transaction failed: {}", e)))?;

        // Explicitly remove events first for deterministic cleanup across sqlite
        // configurations where foreign-key enforcement may differ.
        sqlx::query("DELETE FROM events WHERE app_name = ? AND user_id = ? AND session_id = ?")
            .bind(&req.app_name)
            .bind(&req.user_id)
            .bind(&req.session_id)
            .execute(&mut *tx)
            .await
            .map_err(|e| adk_core::AdkError::session(format!("delete events failed: {}", e)))?;

        sqlx::query("DELETE FROM sessions WHERE app_name = ? AND user_id = ? AND session_id = ?")
            .bind(&req.app_name)
            .bind(&req.user_id)
            .bind(&req.session_id)
            .execute(&mut *tx)
            .await
            .map_err(|e| adk_core::AdkError::session(format!("delete failed: {}", e)))?;

        tx.commit()
            .await
            .map_err(|e| adk_core::AdkError::session(format!("commit failed: {}", e)))?;

        Ok(())
    }

    async fn delete_all_sessions(&self, app_name: &str, user_id: &str) -> Result<()> {
        validate_scope(app_name, user_id)?;
        let mut tx = self
            .pool
            .begin()
            .await
            .map_err(|e| adk_core::AdkError::session(format!("transaction failed: {}", e)))?;

        sqlx::query("DELETE FROM events WHERE app_name = ? AND user_id = ?")
            .bind(app_name)
            .bind(user_id)
            .execute(&mut *tx)
            .await
            .map_err(|e| {
                adk_core::AdkError::session(format!("delete_all_sessions failed: {}", e))
            })?;

        sqlx::query("DELETE FROM sessions WHERE app_name = ? AND user_id = ?")
            .bind(app_name)
            .bind(user_id)
            .execute(&mut *tx)
            .await
            .map_err(|e| {
                adk_core::AdkError::session(format!("delete_all_sessions failed: {}", e))
            })?;

        sqlx::query("DELETE FROM user_states WHERE app_name = ? AND user_id = ?")
            .bind(app_name)
            .bind(user_id)
            .execute(&mut *tx)
            .await
            .map_err(|e| {
                adk_core::AdkError::session(format!("delete_all_sessions failed: {}", e))
            })?;

        tx.commit()
            .await
            .map_err(|e| adk_core::AdkError::session(format!("commit failed: {}", e)))?;

        Ok(())
    }

    async fn append_event(&self, session_id: &str, mut event: Event) -> Result<()> {
        validate_session_id(session_id)?;
        event.actions.state_delta.retain(|k, _| !k.starts_with(KEY_PREFIX_TEMP));

        let mut tx = self
            .pool
            .begin_with(BEGIN_WRITE)
            .await
            .map_err(|e| adk_core::AdkError::session(format!("transaction failed: {}", e)))?;

        let session_rows =
            sqlx::query("SELECT app_name, user_id FROM sessions WHERE session_id = ?")
                .bind(session_id)
                .fetch_all(&mut *tx)
                .await
                .map_err(|e| adk_core::AdkError::session(format!("query failed: {}", e)))?;

        if session_rows.is_empty() {
            return Err(session_id_not_found(session_id));
        }
        if session_rows.len() > 1 {
            return Err(ambiguous_session_id(session_id));
        }

        let row = &session_rows[0];
        let app_name: String = row.get("app_name");
        let user_id: String = row.get("user_id");

        apply_event(&mut tx, &app_name, &user_id, session_id, &event).await?;

        tx.commit()
            .await
            .map_err(|e| adk_core::AdkError::session(format!("commit failed: {}", e)))?;

        Ok(())
    }

    async fn append_event_for_identity(&self, req: AppendEventRequest) -> Result<()> {
        let mut event = req.event;
        event.actions.state_delta.retain(|k, _| !k.starts_with(KEY_PREFIX_TEMP));

        let mut tx = self
            .pool
            .begin_with(BEGIN_WRITE)
            .await
            .map_err(|e| adk_core::AdkError::session(format!("transaction failed: {}", e)))?;

        apply_event(
            &mut tx,
            req.identity.app_name.as_ref(),
            req.identity.user_id.as_ref(),
            req.identity.session_id.as_ref(),
            &event,
        )
        .await?;

        tx.commit()
            .await
            .map_err(|e| adk_core::AdkError::session(format!("commit failed: {}", e)))?;

        Ok(())
    }

    async fn history(&self, identity: &AdkIdentity) -> Result<SessionHistory> {
        let mut conn = self
            .pool
            .acquire()
            .await
            .map_err(|e| adk_core::AdkError::session(format!("connection failed: {e}")))?;
        Ok(load_history(&mut conn, identity).await?.0)
    }

    async fn rewrite_history(&self, req: RewriteHistoryRequest) -> Result<HistoryOutcome> {
        self.rewrite(req).await
    }

    async fn import_session(&self, req: ImportSessionRequest) -> Result<Box<dyn Session>> {
        let (app_name, user_id, session_id) = (
            req.identity.app_name.as_ref(),
            req.identity.user_id.as_ref(),
            req.identity.session_id.as_ref(),
        );
        let (_, _, state) = state_utils::extract_state_deltas(&req.state);
        let (_, _, initial_state) = state_utils::extract_state_deltas(&req.initial_state);
        let updated_at = req.events.last().map_or_else(Utc::now, |event| event.timestamp);

        let mut tx = self
            .pool
            .begin_with(BEGIN_WRITE)
            .await
            .map_err(|e| adk_core::AdkError::session(format!("transaction failed: {e}")))?;
        sqlx::query(
            "INSERT INTO sessions \
             (app_name, user_id, session_id, state, initial_state, created_at, updated_at) \
             VALUES (?, ?, ?, ?, ?, ?, ?)",
        )
        .bind(app_name)
        .bind(user_id)
        .bind(session_id)
        .bind(encode_state(&state)?)
        .bind(encode_state(&initial_state)?)
        .bind(Utc::now().to_rfc3339())
        .bind(updated_at.to_rfc3339())
        .execute(&mut *tx)
        .await
        .map_err(|e| match e {
            sqlx::Error::Database(db) if db.is_unique_violation() => {
                session_already_exists(app_name, user_id, session_id)
            }
            other => adk_core::AdkError::session(format!("insert failed: {other}")),
        })?;
        for event in &req.events {
            insert_event(&mut tx, app_name, user_id, session_id, event).await?;
        }
        let (app_state, user_state) = read_tiers(&mut tx, app_name, user_id).await?;
        tx.commit()
            .await
            .map_err(|e| adk_core::AdkError::session(format!("commit failed: {e}")))?;

        Ok(Box::new(DatabaseSession {
            app_name: app_name.to_string(),
            user_id: user_id.to_string(),
            session_id: session_id.to_string(),
            state: state_utils::merge_states(&app_state, &user_state, &state),
            events: req.events,
            updated_at,
        }))
    }
}

impl SqliteSessionService {
    /// Applies a history rewrite in one [`BEGIN_WRITE`] transaction: reads the history, checks
    /// and plans the rewrite, then deletes the removed rows, updates the replaced ones in
    /// place, and writes the rebuilt session state.
    async fn rewrite(&self, req: RewriteHistoryRequest) -> Result<HistoryOutcome> {
        let identity = &req.identity;
        let (app_name, user_id, session_id) =
            (identity.app_name.as_ref(), identity.user_id.as_ref(), identity.session_id.as_ref());
        let mut tx = self
            .pool
            .begin_with(BEGIN_WRITE)
            .await
            .map_err(|e| adk_core::AdkError::session(format!("transaction failed: {e}")))?;

        let (history, seqs) = load_history(&mut tx, identity).await?;
        let rewritten = history.rewrite(identity, &req.rewrite, req.expected_version.as_deref())?;
        let change = &rewritten.change;

        if change.operation == HistoryOperation::Rewind {
            // Read order is (timestamp, rowid), so the kept events are those up to the last
            // kept row; every later row goes, including rows that no longer decode.
            let keep = rewritten.events.len();
            match keep.checked_sub(1).map(|last| (&history.events[last], seqs[last])) {
                Some((last, seq)) => sqlx::query(
                    "DELETE FROM events WHERE app_name = ? AND user_id = ? AND session_id = ? \
                     AND (timestamp > ? OR (timestamp = ? AND rowid > ?))",
                )
                .bind(app_name)
                .bind(user_id)
                .bind(session_id)
                .bind(last.timestamp.to_rfc3339())
                .bind(last.timestamp.to_rfc3339())
                .bind(seq),
                None => sqlx::query(
                    "DELETE FROM events WHERE app_name = ? AND user_id = ? AND session_id = ?",
                )
                .bind(app_name)
                .bind(user_id)
                .bind(session_id),
            }
            .execute(&mut *tx)
            .await
            .map_err(|e| adk_core::AdkError::session(format!("delete events failed: {e}")))?;
        } else {
            for event_id in &change.removed {
                sqlx::query(
                    "DELETE FROM events \
                     WHERE app_name = ? AND user_id = ? AND session_id = ? AND id = ?",
                )
                .bind(app_name)
                .bind(user_id)
                .bind(session_id)
                .bind(event_id)
                .execute(&mut *tx)
                .await
                .map_err(|e| adk_core::AdkError::session(format!("delete event failed: {e}")))?;
            }
            for event in rewritten.events.iter().filter(|e| change.replaced.contains(&e.id)) {
                sqlx::query(
                    "UPDATE events SET invocation_id = ?, branch = ?, author = ?, \
                     llm_response = ?, actions = ?, long_running_tool_ids = ? \
                     WHERE app_name = ? AND user_id = ? AND session_id = ? AND id = ?",
                )
                .bind(&event.invocation_id)
                .bind(&event.branch)
                .bind(&event.author)
                .bind(
                    serde_json::to_string(&event.llm_response).map_err(|e| {
                        adk_core::AdkError::session(format!("serialize failed: {e}"))
                    })?,
                )
                .bind(
                    serde_json::to_string(&event.actions).map_err(|e| {
                        adk_core::AdkError::session(format!("serialize failed: {e}"))
                    })?,
                )
                .bind(
                    serde_json::to_string(&event.long_running_tool_ids).map_err(|e| {
                        adk_core::AdkError::session(format!("serialize failed: {e}"))
                    })?,
                )
                .bind(app_name)
                .bind(user_id)
                .bind(session_id)
                .bind(&event.id)
                .execute(&mut *tx)
                .await
                .map_err(|e| adk_core::AdkError::session(format!("update event failed: {e}")))?;
            }
        }

        let now = Utc::now();
        sqlx::query(
            "UPDATE sessions SET state = ?, updated_at = ? \
             WHERE app_name = ? AND user_id = ? AND session_id = ?",
        )
        .bind(encode_state(&rewritten.state)?)
        .bind(now.to_rfc3339())
        .bind(app_name)
        .bind(user_id)
        .bind(session_id)
        .execute(&mut *tx)
        .await
        .map_err(|e| adk_core::AdkError::session(format!("update failed: {e}")))?;
        let (app_state, user_state) = read_tiers(&mut tx, app_name, user_id).await?;

        tx.commit()
            .await
            .map_err(|e| adk_core::AdkError::session(format!("commit failed: {e}")))?;

        let session = Box::new(DatabaseSession {
            app_name: app_name.to_string(),
            user_id: user_id.to_string(),
            session_id: session_id.to_string(),
            state: state_utils::merge_states(&app_state, &user_state, &rewritten.state),
            events: rewritten.events,
            updated_at: now,
        });
        Ok(HistoryOutcome::new(session, rewritten.change))
    }
}

struct DatabaseSession {
    app_name: String,
    user_id: String,
    session_id: String,
    state: HashMap<String, Value>,
    events: Vec<Event>,
    updated_at: DateTime<Utc>,
}

impl Session for DatabaseSession {
    fn id(&self) -> &str {
        &self.session_id
    }

    fn app_name(&self) -> &str {
        &self.app_name
    }

    fn user_id(&self) -> &str {
        &self.user_id
    }

    fn state(&self) -> &dyn State {
        self
    }

    fn events(&self) -> &dyn Events {
        self
    }

    fn last_update_time(&self) -> DateTime<Utc> {
        self.updated_at
    }

    fn take_events(&mut self) -> Vec<Event> {
        std::mem::take(&mut self.events)
    }
}

impl State for DatabaseSession {
    fn get(&self, key: &str) -> Option<Value> {
        self.state.get(key).cloned()
    }

    fn set(&mut self, key: String, value: Value) {
        if let Err(msg) = adk_core::validate_state_key(&key) {
            tracing::warn!(key = %key, "rejecting invalid state key: {msg}");
            return;
        }
        self.state.insert(key, value);
    }

    fn all(&self) -> HashMap<String, Value> {
        self.state.clone()
    }
}

impl Events for DatabaseSession {
    fn all(&self) -> Vec<Event> {
        self.events.clone()
    }

    fn len(&self) -> usize {
        self.events.len()
    }

    fn at(&self, index: usize) -> Option<&Event> {
        self.events.get(index)
    }
}