Skip to main content

adk_session/
postgres.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::{PgConnection, PgPool, Row};
18use std::collections::HashMap;
19use tracing::instrument;
20use uuid::Uuid;
21
22/// PostgreSQL-backed session service.
23///
24/// Uses `sqlx::PgPool` for connection pooling and supports the full
25/// three-tier state model (app, user, session) with `JSONB` columns
26/// and `TIMESTAMPTZ` timestamps.
27///
28/// # Example
29///
30/// ```rust,ignore
31/// let service = PostgresSessionService::new("postgres://user:pass@localhost/mydb").await?;
32/// service.migrate().await?;
33/// ```
34pub struct PostgresSessionService {
35    pool: PgPool,
36}
37
38impl PostgresSessionService {
39    /// Connect to PostgreSQL and create a connection pool.
40    ///
41    /// Creates a new pool with default settings. For production use,
42    /// prefer [`from_pool`](Self::from_pool) to share a tuned pool.
43    pub async fn new(database_url: &str) -> Result<Self> {
44        let pool = PgPool::connect(database_url)
45            .await
46            .map_err(|e| adk_core::AdkError::session(format!("database connection failed: {e}")))?;
47        Ok(Self { pool })
48    }
49
50    /// Create a session service from an existing connection pool.
51    ///
52    /// Use this to share a pool with tuned settings (max connections,
53    /// idle timeout, etc.) across multiple services.
54    ///
55    /// # Example
56    ///
57    /// ```rust,ignore
58    /// use sqlx::postgres::PgPoolOptions;
59    ///
60    /// let pool = PgPoolOptions::new()
61    ///     .max_connections(20)
62    ///     .min_connections(5)
63    ///     .idle_timeout(std::time::Duration::from_secs(300))
64    ///     .connect("postgres://user:pass@localhost/mydb")
65    ///     .await?;
66    ///
67    /// let service = PostgresSessionService::from_pool(pool);
68    /// ```
69    pub fn from_pool(pool: PgPool) -> Self {
70        Self { pool }
71    }
72
73    /// The registry table used to track applied migration versions.
74    const REGISTRY_TABLE: &'static str = "_adk_session_migrations";
75
76    /// Advisory lock key that [`migrate`](Self::migrate) holds while it runs.
77    ///
78    /// Concurrent instances take this `pg_advisory_lock` key so only one migrates at a
79    /// time. The value is an FNV-1a hash of the registry table name, and `pg_locks` shows
80    /// it with the high 32 bits in `classid` and the low 32 bits in `objid`.
81    pub const ADVISORY_LOCK_KEY: i64 = {
82        // Simple FNV-1a-style hash of "_adk_session_migrations" at compile time
83        let bytes = Self::REGISTRY_TABLE.as_bytes();
84        let mut hash: u64 = 0xcbf29ce484222325;
85        let mut i = 0;
86        while i < bytes.len() {
87            hash ^= bytes[i] as u64;
88            hash = hash.wrapping_mul(0x100000001b3);
89            i += 1;
90        }
91        hash as i64
92    };
93
94    /// Compiled-in migration steps for the PostgreSQL session backend.
95    ///
96    /// Each entry is `(version, description, sql)`. Version 1 is the baseline
97    /// that creates the initial schema with PostgreSQL-native types (`JSONB`,
98    /// `TIMESTAMPTZ`) and indexes for common query patterns. Version 2 adds `events.seq`, an
99    /// insertion sequence that orders events with equal timestamps; existing rows are numbered
100    /// in their physical order. Version 3 adds `sessions.initial_state`, the session state a
101    /// session was created with, which history rewrites rebuild from; it is `NULL` for sessions
102    /// created before it.
103    const PG_SESSION_MIGRATIONS: &'static [(i64, &'static str, &'static str)] = &[
104        (
105            1,
106            "create initial session tables",
107            "\
108CREATE TABLE IF NOT EXISTS sessions (\
109    app_name TEXT NOT NULL, \
110    user_id TEXT NOT NULL, \
111    session_id TEXT NOT NULL, \
112    state JSONB NOT NULL DEFAULT '{}', \
113    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), \
114    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), \
115    PRIMARY KEY (app_name, user_id, session_id)\
116);\
117CREATE TABLE IF NOT EXISTS events (\
118    id TEXT NOT NULL, \
119    app_name TEXT NOT NULL, \
120    user_id TEXT NOT NULL, \
121    session_id TEXT NOT NULL, \
122    invocation_id TEXT NOT NULL, \
123    branch TEXT NOT NULL, \
124    author TEXT NOT NULL, \
125    timestamp TIMESTAMPTZ NOT NULL, \
126    llm_response JSONB NOT NULL, \
127    actions JSONB NOT NULL, \
128    long_running_tool_ids JSONB NOT NULL, \
129    PRIMARY KEY (id, app_name, user_id, session_id), \
130    FOREIGN KEY (app_name, user_id, session_id) \
131        REFERENCES sessions(app_name, user_id, session_id) \
132        ON DELETE CASCADE\
133);\
134CREATE TABLE IF NOT EXISTS app_states (\
135    app_name TEXT PRIMARY KEY, \
136    state JSONB NOT NULL DEFAULT '{}', \
137    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()\
138);\
139CREATE TABLE IF NOT EXISTS user_states (\
140    app_name TEXT NOT NULL, \
141    user_id TEXT NOT NULL, \
142    state JSONB NOT NULL DEFAULT '{}', \
143    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), \
144    PRIMARY KEY (app_name, user_id)\
145);\
146CREATE INDEX IF NOT EXISTS idx_sessions_app_user ON sessions(app_name, user_id);\
147CREATE INDEX IF NOT EXISTS idx_events_session_ts ON events(session_id, timestamp);",
148        ),
149        (
150            2,
151            "order events with equal timestamps by insertion",
152            "ALTER TABLE events ADD COLUMN IF NOT EXISTS seq BIGSERIAL;\
153CREATE INDEX IF NOT EXISTS idx_events_session_order \
154    ON events(app_name, user_id, session_id, timestamp, seq);",
155        ),
156        (
157            3,
158            "record the session state each session was created with",
159            "ALTER TABLE sessions ADD COLUMN IF NOT EXISTS initial_state JSONB;",
160        ),
161    ];
162
163    /// Create the required tables and indexes if they do not exist.
164    ///
165    /// Tables created: `sessions`, `events`, `app_states`, `user_states`.
166    /// Uses PostgreSQL-native types (`JSONB`, `TIMESTAMPTZ`) and standard
167    /// foreign key constraints with `ON DELETE CASCADE`.
168    ///
169    /// Migrations are protected by a PostgreSQL advisory lock to prevent
170    /// concurrent migration races from multiple application instances. The
171    /// lock, every migration statement, and the unlock run on one connection,
172    /// which is closed afterwards instead of returning to the pool.
173    pub async fn migrate(&self) -> Result<()> {
174        let mut conn =
175            self.pool.acquire().await.map_err(|e| {
176                adk_core::AdkError::session(format!("database connection failed: {e}"))
177            })?;
178        // A session-level advisory lock belongs to this connection. Closing it on
179        // drop releases the lock even when this future is cancelled, rather than
180        // leaving it held by an idle pooled connection.
181        conn.close_on_drop();
182
183        sqlx::query("SELECT pg_advisory_lock($1)")
184            .bind(Self::ADVISORY_LOCK_KEY)
185            .execute(&mut *conn)
186            .await
187            .map_err(|e| {
188                adk_core::AdkError::session(format!("advisory lock acquisition failed: {e}"))
189            })?;
190
191        let result = crate::migration::pg_runner::run_sql_migrations_on_connection(
192            &mut conn,
193            Self::REGISTRY_TABLE,
194            Self::PG_SESSION_MIGRATIONS,
195            |conn| {
196                Box::pin(async move {
197                    let row = sqlx::query(
198                        "SELECT EXISTS(\
199                             SELECT 1 FROM information_schema.tables \
200                             WHERE table_schema = current_schema() \
201                               AND table_name = 'sessions'\
202                         ) AS exists_flag",
203                    )
204                    .fetch_one(conn)
205                    .await
206                    .map_err(|e| {
207                        adk_core::AdkError::session(format!("baseline detection failed: {e}"))
208                    })?;
209                    let exists: bool = row.try_get("exists_flag").unwrap_or(false);
210                    Ok(exists)
211                })
212            },
213        )
214        .await;
215
216        // Released explicitly so the next instance proceeds without waiting for
217        // the connection to close; closing the connection releases it regardless.
218        let _ = sqlx::query("SELECT pg_advisory_unlock($1)")
219            .bind(Self::ADVISORY_LOCK_KEY)
220            .execute(&mut *conn)
221            .await;
222
223        result
224    }
225
226    /// Returns the highest applied migration version, or 0 if no registry
227    /// exists or the registry is empty.
228    ///
229    /// # Errors
230    ///
231    /// Returns an error when the registry cannot be read for any reason other
232    /// than the table being absent, such as a lost connection or a missing
233    /// privilege.
234    pub async fn schema_version(&self) -> Result<i64> {
235        crate::migration::pg_runner::sql_schema_version(&self.pool, Self::REGISTRY_TABLE).await
236    }
237}
238
239type StateMap = HashMap<String, Value>;
240
241/// Marks a string stored in escaped form.
242///
243/// `JSONB` cannot hold U+0000, so a string or object key that contains it is stored as this
244/// prefix followed by the string with `%` written as `%25` and U+0000 as `%00`. A string that
245/// already starts with the prefix is escaped the same way, so reading back is exact. The prefix
246/// starts with a private-use character, and strings without U+0000 are stored unchanged.
247const NUL_ESCAPE_PREFIX: &str = "\u{e000}adk-nul:";
248
249fn needs_escape(text: &str) -> bool {
250    text.contains('\0') || text.starts_with(NUL_ESCAPE_PREFIX)
251}
252
253fn escape_text(text: String) -> String {
254    if !needs_escape(&text) {
255        return text;
256    }
257    let mut escaped = String::with_capacity(NUL_ESCAPE_PREFIX.len() + text.len() + 8);
258    escaped.push_str(NUL_ESCAPE_PREFIX);
259    for c in text.chars() {
260        match c {
261            '%' => escaped.push_str("%25"),
262            '\0' => escaped.push_str("%00"),
263            other => escaped.push(other),
264        }
265    }
266    escaped
267}
268
269fn unescape_text(text: String) -> String {
270    let Some(rest) = text.strip_prefix(NUL_ESCAPE_PREFIX) else { return text };
271    let mut decoded = String::with_capacity(rest.len());
272    let mut chars = rest.chars();
273    while let Some(c) = chars.next() {
274        if c != '%' {
275            decoded.push(c);
276            continue;
277        }
278        let code: String = chars.by_ref().take(2).collect();
279        match code.as_str() {
280            "25" => decoded.push('%'),
281            "00" => decoded.push('\0'),
282            other => {
283                decoded.push('%');
284                decoded.push_str(other);
285            }
286        }
287    }
288    decoded
289}
290
291/// Rewrites every string and object key of `value` with `rewrite`, in place.
292fn rewrite_strings(value: &mut Value, rewrite: fn(String) -> String, applies: fn(&str) -> bool) {
293    match value {
294        Value::String(text) => {
295            if applies(text) {
296                *text = rewrite(std::mem::take(text));
297            }
298        }
299        Value::Array(items) => {
300            for item in items {
301                rewrite_strings(item, rewrite, applies);
302            }
303        }
304        Value::Object(map) => {
305            if map.keys().any(|key| applies(key)) {
306                *map = std::mem::take(map)
307                    .into_iter()
308                    .map(|(key, value)| (if applies(&key) { rewrite(key) } else { key }, value))
309                    .collect();
310            }
311            for item in map.values_mut() {
312                rewrite_strings(item, rewrite, applies);
313            }
314        }
315        Value::Null | Value::Bool(_) | Value::Number(_) => {}
316    }
317}
318
319/// Serializes `value` for a `JSONB` column; see [`NUL_ESCAPE_PREFIX`].
320fn to_jsonb<T: serde::Serialize + ?Sized>(value: &T) -> Result<Value> {
321    let mut value = serde_json::to_value(value)
322        .map_err(|e| adk_core::AdkError::session(format!("serialize failed: {e}")))?;
323    rewrite_strings(&mut value, escape_text, needs_escape);
324    Ok(value)
325}
326
327/// Reverses [`to_jsonb`] on a value read from a `JSONB` column.
328fn from_jsonb(mut value: Value) -> Value {
329    rewrite_strings(&mut value, unescape_text, |text| text.starts_with(NUL_ESCAPE_PREFIX));
330    value
331}
332
333/// Converts a stored `JSONB` state object; a missing row or a non-object is empty state.
334fn decode_state(value: Option<Value>) -> StateMap {
335    match value.map(from_jsonb) {
336        Some(Value::Object(map)) => map.into_iter().collect(),
337        _ => HashMap::new(),
338    }
339}
340
341fn encode_state(state: &StateMap) -> Result<Value> {
342    to_jsonb(state)
343}
344
345/// Reads the current app and user state tiers.
346async fn read_tiers(
347    conn: &mut PgConnection,
348    app_name: &str,
349    user_id: &str,
350) -> Result<(StateMap, StateMap)> {
351    let app_state: Option<Value> =
352        sqlx::query_scalar("SELECT state FROM app_states WHERE app_name = $1")
353            .bind(app_name)
354            .fetch_optional(&mut *conn)
355            .await
356            .map_err(|e| adk_core::AdkError::session(format!("query failed: {e}")))?;
357    let user_state: Option<Value> =
358        sqlx::query_scalar("SELECT state FROM user_states WHERE app_name = $1 AND user_id = $2")
359            .bind(app_name)
360            .bind(user_id)
361            .fetch_optional(&mut *conn)
362            .await
363            .map_err(|e| adk_core::AdkError::session(format!("query failed: {e}")))?;
364    Ok((decode_state(app_state), decode_state(user_state)))
365}
366
367/// Merges each non-empty tier delta into the stored tier.
368///
369/// `state || delta` is evaluated against the latest committed row while holding its row
370/// lock, so concurrent writers of different keys never overwrite each other.
371async fn apply_tier_deltas(
372    conn: &mut PgConnection,
373    app_name: &str,
374    user_id: &str,
375    app_delta: &StateMap,
376    user_delta: &StateMap,
377    now: DateTime<Utc>,
378) -> Result<()> {
379    if !app_delta.is_empty() {
380        sqlx::query(
381            "INSERT INTO app_states (app_name, state, updated_at) VALUES ($1, $2, $3) \
382             ON CONFLICT (app_name) DO UPDATE \
383             SET state = app_states.state || EXCLUDED.state, updated_at = EXCLUDED.updated_at",
384        )
385        .bind(app_name)
386        .bind(encode_state(app_delta)?)
387        .bind(now)
388        .execute(&mut *conn)
389        .await
390        .map_err(|e| adk_core::AdkError::session(format!("insert failed: {e}")))?;
391    }
392
393    if !user_delta.is_empty() {
394        sqlx::query(
395            "INSERT INTO user_states (app_name, user_id, state, updated_at) \
396             VALUES ($1, $2, $3, $4) \
397             ON CONFLICT (app_name, user_id) DO UPDATE \
398             SET state = user_states.state || EXCLUDED.state, updated_at = EXCLUDED.updated_at",
399        )
400        .bind(app_name)
401        .bind(user_id)
402        .bind(encode_state(user_delta)?)
403        .bind(now)
404        .execute(&mut *conn)
405        .await
406        .map_err(|e| adk_core::AdkError::session(format!("insert failed: {e}")))?;
407    }
408
409    Ok(())
410}
411
412/// Applies `event` to the session `(app_name, user_id, session_id)`: merges each tier's
413/// delta, bumps `updated_at`, and inserts the event.
414///
415/// Row locks are taken session, app, user. Every writer takes the app row before the user
416/// row and `create` locks no existing session row, so concurrent writers cannot deadlock.
417async fn apply_event(
418    conn: &mut PgConnection,
419    app_name: &str,
420    user_id: &str,
421    session_id: &str,
422    event: &Event,
423) -> Result<()> {
424    let (app_delta, user_delta, session_delta) =
425        state_utils::extract_state_deltas(&event.actions.state_delta);
426
427    let updated = sqlx::query(
428        "UPDATE sessions SET state = state || $1, updated_at = $2 \
429         WHERE app_name = $3 AND user_id = $4 AND session_id = $5",
430    )
431    .bind(encode_state(&session_delta)?)
432    .bind(event.timestamp)
433    .bind(app_name)
434    .bind(user_id)
435    .bind(session_id)
436    .execute(&mut *conn)
437    .await
438    .map_err(|e| adk_core::AdkError::session(format!("update failed: {e}")))?;
439    if updated.rows_affected() == 0 {
440        return Err(session_not_found_for(app_name, user_id, session_id));
441    }
442
443    apply_tier_deltas(conn, app_name, user_id, &app_delta, &user_delta, event.timestamp).await?;
444
445    insert_event(conn, app_name, user_id, session_id, event).await
446}
447
448/// Inserts `event` into the session's events without touching any state.
449async fn insert_event(
450    conn: &mut PgConnection,
451    app_name: &str,
452    user_id: &str,
453    session_id: &str,
454    event: &Event,
455) -> Result<()> {
456    let llm_response_value = to_jsonb(&event.llm_response)?;
457    let actions_value = to_jsonb(&event.actions)?;
458    let tool_ids_value = to_jsonb(&event.long_running_tool_ids)?;
459
460    sqlx::query(
461        r#"INSERT INTO events (id, app_name, user_id, session_id, invocation_id, branch, author, timestamp, llm_response, actions, long_running_tool_ids)
462           VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)"#,
463    )
464    .bind(&event.id)
465    .bind(app_name)
466    .bind(user_id)
467    .bind(session_id)
468    .bind(&event.invocation_id)
469    .bind(&event.branch)
470    .bind(&event.author)
471    .bind(event.timestamp)
472    .bind(&llm_response_value)
473    .bind(&actions_value)
474    .bind(&tool_ids_value)
475    .execute(&mut *conn)
476    .await
477    .map_err(|e| adk_core::AdkError::session(format!("insert failed: {e}")))?;
478
479    Ok(())
480}
481
482/// Decodes a stored event row, logging and skipping a row that no longer deserializes so one
483/// corrupt event does not hide the rest of the session history.
484fn decode_event_row(row: &sqlx::postgres::PgRow, session_id: &str) -> Option<Event> {
485    let event_id: String = row.get("id");
486    let column = |name: &str| from_jsonb(row.get(name));
487    let decoded = serde_json::from_value(column("llm_response")).and_then(|llm_response| {
488        Ok((
489            llm_response,
490            serde_json::from_value(column("actions"))?,
491            serde_json::from_value(column("long_running_tool_ids"))?,
492        ))
493    });
494    let (llm_response, actions, long_running_tool_ids) = match decoded {
495        Ok(parts) => parts,
496        Err(error) => {
497            tracing::warn!(
498                session.id = %session_id,
499                event.id = %event_id,
500                error = %error,
501                "skipping stored event that failed to deserialize"
502            );
503            return None;
504        }
505    };
506    Some(Event {
507        id: event_id,
508        timestamp: row.get("timestamp"),
509        invocation_id: row.get("invocation_id"),
510        branch: row.get("branch"),
511        author: row.get("author"),
512        llm_request: None,
513        llm_response,
514        actions,
515        long_running_tool_ids,
516        provider_metadata: HashMap::new(),
517    })
518}
519
520/// Reads the history of `identity` in read order, with the `seq` of each decoded event.
521/// `lock` takes the session row's write lock, which every append also takes, first.
522async fn load_history(
523    conn: &mut PgConnection,
524    identity: &AdkIdentity,
525    lock: bool,
526) -> Result<(SessionHistory, Vec<i64>)> {
527    let (app_name, user_id, session_id) =
528        (identity.app_name.as_ref(), identity.user_id.as_ref(), identity.session_id.as_ref());
529    let query = if lock {
530        "SELECT state, initial_state FROM sessions \
531         WHERE app_name = $1 AND user_id = $2 AND session_id = $3 FOR UPDATE"
532    } else {
533        "SELECT state, initial_state FROM sessions \
534         WHERE app_name = $1 AND user_id = $2 AND session_id = $3"
535    };
536    let row = sqlx::query(query)
537        .bind(app_name)
538        .bind(user_id)
539        .bind(session_id)
540        .fetch_optional(&mut *conn)
541        .await
542        .map_err(|e| adk_core::AdkError::session(format!("query failed: {e}")))?
543        .ok_or_else(|| identity_not_found(identity))?;
544    let (_, _, stored) = state_utils::extract_state_deltas(&decode_state(row.get("state")));
545    let initial: Option<Value> = row.get("initial_state");
546    let initial = initial.map(|value| decode_state(Some(value)));
547
548    let rows = sqlx::query(
549        "SELECT * FROM events WHERE app_name = $1 AND user_id = $2 AND session_id = $3 \
550         ORDER BY timestamp, seq",
551    )
552    .bind(app_name)
553    .bind(user_id)
554    .bind(session_id)
555    .fetch_all(&mut *conn)
556    .await
557    .map_err(|e| adk_core::AdkError::session(format!("query failed: {e}")))?;
558    let mut events = Vec::with_capacity(rows.len());
559    let mut seqs = Vec::with_capacity(rows.len());
560    for row in &rows {
561        if let Some(event) = decode_event_row(row, session_id) {
562            seqs.push(row.get::<i64, _>("seq"));
563            events.push(event);
564        }
565    }
566    Ok((SessionHistory::new(events, stored, initial), seqs))
567}
568
569#[async_trait]
570impl SessionService for PostgresSessionService {
571    #[instrument(skip_all, fields(app_name = %req.app_name, user_id = %req.user_id))]
572    async fn create(&self, req: CreateRequest) -> Result<Box<dyn Session>> {
573        req.try_identity()?;
574        let session_id = req.session_id.unwrap_or_else(|| Uuid::new_v4().to_string());
575        let now = Utc::now();
576
577        let (app_delta, user_delta, session_state) = state_utils::extract_state_deltas(&req.state);
578
579        let mut tx = self
580            .pool
581            .begin()
582            .await
583            .map_err(|e| adk_core::AdkError::session(format!("transaction failed: {e}")))?;
584
585        apply_tier_deltas(&mut tx, &req.app_name, &req.user_id, &app_delta, &user_delta, now)
586            .await?;
587        let (app_state, user_state) = read_tiers(&mut tx, &req.app_name, &req.user_id).await?;
588
589        sqlx::query(
590            r#"INSERT INTO sessions (app_name, user_id, session_id, state, initial_state, created_at, updated_at)
591               VALUES ($1, $2, $3, $4, $4, $5, $6)"#,
592        )
593        .bind(&req.app_name)
594        .bind(&req.user_id)
595        .bind(&session_id)
596        .bind(encode_state(&session_state)?)
597        .bind(now)
598        .bind(now)
599        .execute(&mut *tx)
600        .await
601        .map_err(|e| match e {
602            // The failed insert aborts the transaction, which rolls back the tier writes above.
603            sqlx::Error::Database(db) if db.is_unique_violation() => {
604                session_already_exists(&req.app_name, &req.user_id, &session_id)
605            }
606            other => adk_core::AdkError::session(format!("insert failed: {other}")),
607        })?;
608
609        tx.commit()
610            .await
611            .map_err(|e| adk_core::AdkError::session(format!("commit failed: {e}")))?;
612
613        Ok(Box::new(PostgresSession {
614            app_name: req.app_name,
615            user_id: req.user_id,
616            session_id,
617            state: state_utils::merge_states(&app_state, &user_state, &session_state),
618            events: Vec::new(),
619            updated_at: now,
620        }))
621    }
622
623    #[instrument(skip_all, fields(app_name = %req.app_name, user_id = %req.user_id, session_id = %req.session_id))]
624    async fn get(&self, req: GetRequest) -> Result<Box<dyn Session>> {
625        req.try_identity()?;
626        let row = sqlx::query(
627            "SELECT s.state, s.updated_at, a.state AS app_state, u.state AS user_state \
628             FROM sessions s \
629             LEFT JOIN app_states a ON a.app_name = s.app_name \
630             LEFT JOIN user_states u ON u.app_name = s.app_name AND u.user_id = s.user_id \
631             WHERE s.app_name = $1 AND s.user_id = $2 AND s.session_id = $3",
632        )
633        .bind(&req.app_name)
634        .bind(&req.user_id)
635        .bind(&req.session_id)
636        .fetch_optional(&self.pool)
637        .await
638        .map_err(|e| adk_core::AdkError::session(format!("query failed: {e}")))?
639        .ok_or_else(|| crate::service::session_not_found(&req))?;
640
641        let state = state_utils::merge_current_tiers(
642            &decode_state(row.get("app_state")),
643            &decode_state(row.get("user_state")),
644            &decode_state(row.get("state")),
645        );
646        let updated_at: DateTime<Utc> = row.get("updated_at");
647
648        // The inner query keeps the most recent `num_recent_events` (NULL is no limit); the
649        // outer one restores chronological order.
650        let limit = req.num_recent_events.map(|n| i64::try_from(n).unwrap_or(i64::MAX));
651        let events: Vec<Event> = sqlx::query(
652            "SELECT * FROM (\
653                 SELECT * FROM events \
654                 WHERE app_name = $1 AND user_id = $2 AND session_id = $3 \
655                   AND ($4::timestamptz IS NULL OR timestamp >= $4) \
656                 ORDER BY timestamp DESC, seq DESC LIMIT $5\
657             ) recent ORDER BY timestamp, seq",
658        )
659        .bind(&req.app_name)
660        .bind(&req.user_id)
661        .bind(&req.session_id)
662        .bind(req.after)
663        .bind(limit)
664        .fetch_all(&self.pool)
665        .await
666        .map_err(|e| adk_core::AdkError::session(format!("query failed: {e}")))?
667        .iter()
668        .filter_map(|row| decode_event_row(row, &req.session_id))
669        .collect();
670
671        Ok(Box::new(PostgresSession {
672            app_name: req.app_name,
673            user_id: req.user_id,
674            session_id: req.session_id,
675            state,
676            events,
677            updated_at,
678        }))
679    }
680
681    #[instrument(skip_all, fields(app_name = %req.app_name, user_id = %req.user_id))]
682    async fn list(&self, req: ListRequest) -> Result<Vec<Box<dyn Session>>> {
683        validate_scope(&req.app_name, &req.user_id)?;
684        let limit = req.limit.unwrap_or(i64::MAX as usize) as i64;
685        let offset = req.offset.unwrap_or(0) as i64;
686
687        let mut conn =
688            self.pool.acquire().await.map_err(|e| {
689                adk_core::AdkError::session(format!("database connection failed: {e}"))
690            })?;
691        let (app_state, user_state) = read_tiers(&mut conn, &req.app_name, &req.user_id).await?;
692
693        let rows = sqlx::query(
694            "SELECT session_id, state, updated_at FROM sessions \
695             WHERE app_name = $1 AND user_id = $2 \
696             ORDER BY updated_at DESC, session_id DESC LIMIT $3 OFFSET $4",
697        )
698        .bind(&req.app_name)
699        .bind(&req.user_id)
700        .bind(limit)
701        .bind(offset)
702        .fetch_all(&mut *conn)
703        .await
704        .map_err(|e| adk_core::AdkError::session(format!("query failed: {e}")))?;
705
706        let mut sessions = Vec::new();
707        for row in rows {
708            let stored = decode_state(row.get("state"));
709            let updated_at: DateTime<Utc> = row.get("updated_at");
710
711            sessions.push(Box::new(PostgresSession {
712                app_name: req.app_name.clone(),
713                user_id: req.user_id.clone(),
714                session_id: row.get("session_id"),
715                state: state_utils::merge_current_tiers(&app_state, &user_state, &stored),
716                events: Vec::new(),
717                updated_at,
718            }) as Box<dyn Session>);
719        }
720
721        Ok(sessions)
722    }
723
724    #[instrument(skip_all, fields(app_name = %req.app_name, user_id = %req.user_id, session_id = %req.session_id))]
725    async fn delete(&self, req: DeleteRequest) -> Result<()> {
726        req.try_identity()?;
727        // CASCADE handles events deletion automatically in PostgreSQL
728        sqlx::query(
729            "DELETE FROM sessions WHERE app_name = $1 AND user_id = $2 AND session_id = $3",
730        )
731        .bind(&req.app_name)
732        .bind(&req.user_id)
733        .bind(&req.session_id)
734        .execute(&self.pool)
735        .await
736        .map_err(|e| adk_core::AdkError::session(format!("delete failed: {e}")))?;
737
738        Ok(())
739    }
740
741    #[instrument(skip_all, fields(session_id = %session_id))]
742    async fn append_event(&self, session_id: &str, mut event: Event) -> Result<()> {
743        validate_session_id(session_id)?;
744        event.actions.state_delta.retain(|k, _| !k.starts_with(KEY_PREFIX_TEMP));
745
746        let mut tx = self
747            .pool
748            .begin()
749            .await
750            .map_err(|e| adk_core::AdkError::session(format!("transaction failed: {e}")))?;
751
752        let session_rows =
753            sqlx::query("SELECT app_name, user_id FROM sessions WHERE session_id = $1")
754                .bind(session_id)
755                .fetch_all(&mut *tx)
756                .await
757                .map_err(|e| adk_core::AdkError::session(format!("query failed: {e}")))?;
758
759        if session_rows.is_empty() {
760            return Err(session_id_not_found(session_id));
761        }
762        if session_rows.len() > 1 {
763            return Err(ambiguous_session_id(session_id));
764        }
765
766        let row = &session_rows[0];
767        let app_name: String = row.get("app_name");
768        let user_id: String = row.get("user_id");
769
770        apply_event(&mut tx, &app_name, &user_id, session_id, &event).await?;
771
772        tx.commit()
773            .await
774            .map_err(|e| adk_core::AdkError::session(format!("commit failed: {e}")))?;
775
776        Ok(())
777    }
778
779    #[instrument(skip_all, fields(
780        app_name = %req.identity.app_name,
781        user_id = %req.identity.user_id,
782        session_id = %req.identity.session_id,
783    ))]
784    async fn append_event_for_identity(&self, req: AppendEventRequest) -> Result<()> {
785        let mut event = req.event;
786        event.actions.state_delta.retain(|k, _| !k.starts_with(KEY_PREFIX_TEMP));
787
788        let mut tx = self
789            .pool
790            .begin()
791            .await
792            .map_err(|e| adk_core::AdkError::session(format!("transaction failed: {e}")))?;
793
794        apply_event(
795            &mut tx,
796            req.identity.app_name.as_ref(),
797            req.identity.user_id.as_ref(),
798            req.identity.session_id.as_ref(),
799            &event,
800        )
801        .await?;
802
803        tx.commit()
804            .await
805            .map_err(|e| adk_core::AdkError::session(format!("commit failed: {e}")))?;
806
807        Ok(())
808    }
809
810    #[instrument(skip_all, fields(app_name = %app_name, user_id = %user_id))]
811    async fn delete_all_sessions(&self, app_name: &str, user_id: &str) -> Result<()> {
812        validate_scope(app_name, user_id)?;
813        let mut tx = self
814            .pool
815            .begin()
816            .await
817            .map_err(|e| adk_core::AdkError::session(format!("transaction failed: {e}")))?;
818        // CASCADE handles events deletion automatically
819        sqlx::query("DELETE FROM sessions WHERE app_name = $1 AND user_id = $2")
820            .bind(app_name)
821            .bind(user_id)
822            .execute(&mut *tx)
823            .await
824            .map_err(|e| adk_core::AdkError::session(format!("delete_all_sessions failed: {e}")))?;
825        sqlx::query("DELETE FROM user_states WHERE app_name = $1 AND user_id = $2")
826            .bind(app_name)
827            .bind(user_id)
828            .execute(&mut *tx)
829            .await
830            .map_err(|e| adk_core::AdkError::session(format!("delete_all_sessions failed: {e}")))?;
831        tx.commit()
832            .await
833            .map_err(|e| adk_core::AdkError::session(format!("commit failed: {e}")))?;
834        Ok(())
835    }
836
837    #[instrument(skip_all)]
838    async fn history(&self, identity: &AdkIdentity) -> Result<SessionHistory> {
839        let mut conn = self
840            .pool
841            .acquire()
842            .await
843            .map_err(|e| adk_core::AdkError::session(format!("connection failed: {e}")))?;
844        Ok(load_history(&mut conn, identity, false).await?.0)
845    }
846
847    async fn rewrite_history(&self, req: RewriteHistoryRequest) -> Result<HistoryOutcome> {
848        self.rewrite(req).await
849    }
850
851    async fn import_session(&self, req: ImportSessionRequest) -> Result<Box<dyn Session>> {
852        let (app_name, user_id, session_id) = (
853            req.identity.app_name.as_ref(),
854            req.identity.user_id.as_ref(),
855            req.identity.session_id.as_ref(),
856        );
857        let (_, _, state) = state_utils::extract_state_deltas(&req.state);
858        let (_, _, initial_state) = state_utils::extract_state_deltas(&req.initial_state);
859        let updated_at = req.events.last().map_or_else(Utc::now, |event| event.timestamp);
860
861        let mut tx = self
862            .pool
863            .begin()
864            .await
865            .map_err(|e| adk_core::AdkError::session(format!("transaction failed: {e}")))?;
866        sqlx::query(
867            "INSERT INTO sessions \
868             (app_name, user_id, session_id, state, initial_state, created_at, updated_at) \
869             VALUES ($1, $2, $3, $4, $5, $6, $7)",
870        )
871        .bind(app_name)
872        .bind(user_id)
873        .bind(session_id)
874        .bind(encode_state(&state)?)
875        .bind(encode_state(&initial_state)?)
876        .bind(Utc::now())
877        .bind(updated_at)
878        .execute(&mut *tx)
879        .await
880        .map_err(|e| match e {
881            sqlx::Error::Database(db) if db.is_unique_violation() => {
882                session_already_exists(app_name, user_id, session_id)
883            }
884            other => adk_core::AdkError::session(format!("insert failed: {other}")),
885        })?;
886        for event in &req.events {
887            insert_event(&mut tx, app_name, user_id, session_id, event).await?;
888        }
889        let (app_state, user_state) = read_tiers(&mut tx, app_name, user_id).await?;
890        tx.commit()
891            .await
892            .map_err(|e| adk_core::AdkError::session(format!("commit failed: {e}")))?;
893
894        Ok(Box::new(PostgresSession {
895            app_name: app_name.to_string(),
896            user_id: user_id.to_string(),
897            session_id: session_id.to_string(),
898            state: state_utils::merge_states(&app_state, &user_state, &state),
899            events: req.events,
900            updated_at,
901        }))
902    }
903
904    async fn health_check(&self) -> Result<()> {
905        sqlx::query("SELECT 1")
906            .execute(&self.pool)
907            .await
908            .map_err(|e| adk_core::AdkError::session(format!("health check failed: {e}")))?;
909        Ok(())
910    }
911}
912
913impl PostgresSessionService {
914    /// Applies a history rewrite in one transaction that holds the session row's lock: reads
915    /// the history, checks and plans the rewrite, then deletes the removed rows, updates the
916    /// replaced ones in place, and writes the rebuilt session state.
917    async fn rewrite(&self, req: RewriteHistoryRequest) -> Result<HistoryOutcome> {
918        let identity = &req.identity;
919        let (app_name, user_id, session_id) =
920            (identity.app_name.as_ref(), identity.user_id.as_ref(), identity.session_id.as_ref());
921        let mut tx = self
922            .pool
923            .begin()
924            .await
925            .map_err(|e| adk_core::AdkError::session(format!("transaction failed: {e}")))?;
926
927        let (history, seqs) = load_history(&mut tx, identity, true).await?;
928        let rewritten = history.rewrite(identity, &req.rewrite, req.expected_version.as_deref())?;
929        let change = &rewritten.change;
930
931        if change.operation == HistoryOperation::Rewind {
932            // Every row after the last kept one goes, including rows that no longer decode.
933            let keep = rewritten.events.len();
934            match keep.checked_sub(1).map(|last| (history.events[last].timestamp, seqs[last])) {
935                Some((timestamp, seq)) => sqlx::query(
936                    "DELETE FROM events WHERE app_name = $1 AND user_id = $2 AND session_id = $3 \
937                     AND (timestamp, seq) > ($4, $5)",
938                )
939                .bind(app_name)
940                .bind(user_id)
941                .bind(session_id)
942                .bind(timestamp)
943                .bind(seq),
944                None => sqlx::query(
945                    "DELETE FROM events WHERE app_name = $1 AND user_id = $2 AND session_id = $3",
946                )
947                .bind(app_name)
948                .bind(user_id)
949                .bind(session_id),
950            }
951            .execute(&mut *tx)
952            .await
953            .map_err(|e| adk_core::AdkError::session(format!("delete events failed: {e}")))?;
954        } else {
955            sqlx::query(
956                "DELETE FROM events WHERE app_name = $1 AND user_id = $2 AND session_id = $3 \
957                 AND id = ANY($4)",
958            )
959            .bind(app_name)
960            .bind(user_id)
961            .bind(session_id)
962            .bind(&change.removed)
963            .execute(&mut *tx)
964            .await
965            .map_err(|e| adk_core::AdkError::session(format!("delete events failed: {e}")))?;
966            for event in rewritten.events.iter().filter(|e| change.replaced.contains(&e.id)) {
967                sqlx::query(
968                    "UPDATE events SET invocation_id = $1, branch = $2, author = $3, \
969                     llm_response = $4, actions = $5, long_running_tool_ids = $6 \
970                     WHERE app_name = $7 AND user_id = $8 AND session_id = $9 AND id = $10",
971                )
972                .bind(&event.invocation_id)
973                .bind(&event.branch)
974                .bind(&event.author)
975                .bind(to_jsonb(&event.llm_response)?)
976                .bind(to_jsonb(&event.actions)?)
977                .bind(to_jsonb(&event.long_running_tool_ids)?)
978                .bind(app_name)
979                .bind(user_id)
980                .bind(session_id)
981                .bind(&event.id)
982                .execute(&mut *tx)
983                .await
984                .map_err(|e| adk_core::AdkError::session(format!("update event failed: {e}")))?;
985            }
986        }
987
988        let now = Utc::now();
989        sqlx::query(
990            "UPDATE sessions SET state = $1, updated_at = $2 \
991             WHERE app_name = $3 AND user_id = $4 AND session_id = $5",
992        )
993        .bind(encode_state(&rewritten.state)?)
994        .bind(now)
995        .bind(app_name)
996        .bind(user_id)
997        .bind(session_id)
998        .execute(&mut *tx)
999        .await
1000        .map_err(|e| adk_core::AdkError::session(format!("update failed: {e}")))?;
1001        let (app_state, user_state) = read_tiers(&mut tx, app_name, user_id).await?;
1002
1003        tx.commit()
1004            .await
1005            .map_err(|e| adk_core::AdkError::session(format!("commit failed: {e}")))?;
1006
1007        let session = Box::new(PostgresSession {
1008            app_name: app_name.to_string(),
1009            user_id: user_id.to_string(),
1010            session_id: session_id.to_string(),
1011            state: state_utils::merge_states(&app_state, &user_state, &rewritten.state),
1012            events: rewritten.events,
1013            updated_at: now,
1014        });
1015        Ok(HistoryOutcome::new(session, rewritten.change))
1016    }
1017}
1018
1019struct PostgresSession {
1020    app_name: String,
1021    user_id: String,
1022    session_id: String,
1023    state: HashMap<String, Value>,
1024    events: Vec<Event>,
1025    updated_at: DateTime<Utc>,
1026}
1027
1028impl Session for PostgresSession {
1029    fn id(&self) -> &str {
1030        &self.session_id
1031    }
1032
1033    fn app_name(&self) -> &str {
1034        &self.app_name
1035    }
1036
1037    fn user_id(&self) -> &str {
1038        &self.user_id
1039    }
1040
1041    fn state(&self) -> &dyn State {
1042        self
1043    }
1044
1045    fn events(&self) -> &dyn Events {
1046        self
1047    }
1048
1049    fn last_update_time(&self) -> DateTime<Utc> {
1050        self.updated_at
1051    }
1052
1053    fn take_events(&mut self) -> Vec<Event> {
1054        std::mem::take(&mut self.events)
1055    }
1056}
1057
1058impl State for PostgresSession {
1059    fn get(&self, key: &str) -> Option<Value> {
1060        self.state.get(key).cloned()
1061    }
1062
1063    fn set(&mut self, key: String, value: Value) {
1064        if let Err(msg) = adk_core::validate_state_key(&key) {
1065            tracing::warn!(key = %key, "rejecting invalid state key: {msg}");
1066            return;
1067        }
1068        self.state.insert(key, value);
1069    }
1070
1071    fn all(&self) -> HashMap<String, Value> {
1072        self.state.clone()
1073    }
1074}
1075
1076impl Events for PostgresSession {
1077    fn all(&self) -> Vec<Event> {
1078        self.events.clone()
1079    }
1080
1081    fn len(&self) -> usize {
1082        self.events.len()
1083    }
1084
1085    fn at(&self, index: usize) -> Option<&Event> {
1086        self.events.get(index)
1087    }
1088}
1089
1090#[cfg(test)]
1091mod tests {
1092    use super::*;
1093    use serde_json::json;
1094
1095    #[test]
1096    fn jsonb_escaping_round_trips_nul_percent_and_the_prefix() {
1097        let original = json!({
1098            "plain": "no escape needed",
1099            "nul": "PK\u{0}\u{3}binary",
1100            "percent": "100% and %00 and \u{0}",
1101            "lookalike": format!("{NUL_ESCAPE_PREFIX}%00 literal"),
1102            "key\u{0}with nul": ["a\u{0}b", {"nested\u{0}": "c\u{0}"}],
1103            "numbers": [1, 2.5, null, true],
1104        });
1105
1106        let stored = to_jsonb(&original).unwrap();
1107        assert!(!stored.to_string().contains("\\u0000"), "no U+0000 reaches JSONB: {stored}");
1108        assert_eq!(stored["plain"], json!("no escape needed"), "plain strings are stored as is");
1109        assert_eq!(from_jsonb(stored), original);
1110    }
1111
1112    #[test]
1113    fn jsonb_reading_leaves_unescaped_strings_alone() {
1114        let legacy = json!({"text": "50% off", "odd": "%zz"});
1115        assert_eq!(from_jsonb(legacy.clone()), legacy);
1116    }
1117}