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
//! Lightweight, embedded migration runner for SQL-backed session services.
//!
//! This module provides shared types and free functions that track applied
//! schema versions in a per-backend registry table and execute only unapplied
//! forward-only migration steps.
//!
//! The types (`MigrationStep`, `AppliedMigration`, `MigrationError`) are
//! always compiled. The SQL runner functions (`run_sql_migrations`,
//! `run_sql_migrations_on_connection`, `sql_schema_version`) require the
//! `sqlite` or `postgres` feature.

use chrono::{DateTime, Utc};

/// A single forward-only migration step.
///
/// The struct intentionally does not contain the SQL itself — each backend
/// defines its own step list as `&[(i64, &str, &str)]` tuples of
/// `(version, description, sql)`.
#[derive(Debug, Clone, Copy)]
pub struct MigrationStep {
    /// Monotonically increasing version number, starting at 1.
    pub version: i64,
    /// Human-readable description of what this step does.
    pub description: &'static str,
}

/// Record of an applied migration stored in the registry table.
#[derive(Debug, Clone)]
pub struct AppliedMigration {
    /// The applied version number.
    pub version: i64,
    /// Description recorded at apply time.
    pub description: String,
    /// UTC timestamp of application.
    pub applied_at: DateTime<Utc>,
}

/// Error context for a failed migration step.
#[derive(Debug)]
pub struct MigrationError {
    /// The version that failed.
    pub version: i64,
    /// Description of the failed step.
    pub description: String,
    /// Underlying cause (database error message, etc.).
    pub cause: String,
}

impl std::fmt::Display for MigrationError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "migration v{} ({}) failed: {}", self.version, self.description, self.cause)
    }
}

impl std::error::Error for MigrationError {}

// ---------------------------------------------------------------------------
// SQL runner — macro generates concrete implementations per database backend
// ---------------------------------------------------------------------------

// Registry identifiers are interpolated; migration bodies are trusted executable SQL.
// PostgreSQL truncates identifiers past 63 bytes, so a longer name could address
// another registry.
#[cfg(any(feature = "sqlite", feature = "postgres"))]
fn validate_registry_table(name: &str) -> Result<(), adk_core::AdkError> {
    let mut chars = name.chars();
    if name.len() > 63
        || !chars.next().is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
        || !chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
    {
        return Err(adk_core::AdkError::session(format!(
            "invalid migration registry table `{name}`: use an ASCII identifier of at most 63 bytes \
             starting with a letter or underscore, followed by letters, digits or underscores"
        )));
    }
    Ok(())
}

/// Expands to the body of a migration run, shared by the pool-based and the
/// connection-based entry points.
///
/// `$exec` is expanded at every statement, so `&mut *conn` reborrows a
/// connection afresh for each one.
#[cfg(any(feature = "sqlite", feature = "postgres"))]
macro_rules! sql_migration_body {
    (
        exec: $exec:expr,
        begin: $begin:expr,
        detect: $detect:expr,
        registry_table: $registry_table:expr,
        steps: $steps:expr,
        int_type: $int_type:expr $(,)?
    ) => {{
        let registry_table: &str = $registry_table;
        super::validate_registry_table(registry_table)?;
        let steps: &'static [(i64, &'static str, &'static str)] = $steps;

        // Step 1: Create registry table if missing
        let create_sql = format!(
            "CREATE TABLE IF NOT EXISTS {registry_table} (\
                version {} PRIMARY KEY, \
                description TEXT NOT NULL, \
                applied_at TEXT NOT NULL\
            )",
            $int_type
        );
        sqlx::query(sqlx::AssertSqlSafe(create_sql)).execute($exec).await.map_err(|e| {
            adk_core::AdkError::session(format!("migration registry creation failed: {e}"))
        })?;

        // Step 2: Read current max applied version
        let max_sql = format!("SELECT COALESCE(MAX(version), 0) AS max_v FROM {registry_table}");
        let row =
            sqlx::query(sqlx::AssertSqlSafe(max_sql)).fetch_one($exec).await.map_err(|e| {
                adk_core::AdkError::session(format!("migration registry read failed: {e}"))
            })?;
        let mut max_applied: i64 = row.try_get("max_v").map_err(|e| {
            adk_core::AdkError::session(format!("migration registry read failed: {e}"))
        })?;

        // Step 3: Baseline detection — if registry is empty but
        // tables already exist, record v1 as applied.
        if max_applied == 0 {
            let existing = $detect.await?;
            if existing {
                if let Some(&(v, desc, _)) = steps.first() {
                    let now = Utc::now().to_rfc3339();
                    // Another run may record the same baseline at the same moment.
                    let ins = format!(
                        "INSERT INTO {registry_table} \
                         (version, description, applied_at) \
                         VALUES ($1, $2, $3) ON CONFLICT (version) DO NOTHING"
                    );
                    sqlx::query(sqlx::AssertSqlSafe(ins))
                        .bind(v)
                        .bind(desc)
                        .bind(&now)
                        .execute($exec)
                        .await
                        .map_err(|e| {
                            adk_core::AdkError::session(format!(
                                "{}",
                                MigrationError {
                                    version: v,
                                    description: desc.to_string(),
                                    cause: e.to_string(),
                                }
                            ))
                        })?;
                    max_applied = v;
                }
            }
        }

        // Step 4: Compiled-in max version
        let max_compiled = steps.last().map(|s| s.0).unwrap_or(0);

        // Step 5: Version mismatch check
        if max_applied > max_compiled {
            return Err(adk_core::AdkError::session(format!(
                "schema version mismatch: database is at v{max_applied} \
                 but code only knows up to v{max_compiled}. \
                 Upgrade your ADK version."
            )));
        }

        // Step 6: Execute unapplied steps in transactions
        for &(version, description, sql) in steps {
            if version <= max_applied {
                continue;
            }

            let mut tx = $begin.await.map_err(|e| {
                adk_core::AdkError::session(format!(
                    "{}",
                    MigrationError {
                        version,
                        description: description.to_string(),
                        cause: format!("transaction begin failed: {e}"),
                    }
                ))
            })?;

            // Another run that read the same registry may have applied this step since.
            // On SQLite the transaction holds the write lock (`BEGIN IMMEDIATE`), and the
            // PostgreSQL stores hold an advisory lock, so this read is current.
            let applied_sql =
                format!("SELECT COUNT(*) AS n FROM {registry_table} WHERE version = $1");
            let applied: i64 = sqlx::query(sqlx::AssertSqlSafe(applied_sql))
                .bind(version)
                .fetch_one(&mut *tx)
                .await
                .and_then(|row| row.try_get("n"))
                .map_err(|e| {
                    adk_core::AdkError::session(format!("migration registry read failed: {e}"))
                })?;
            if applied > 0 {
                tx.rollback().await.map_err(|e| {
                    adk_core::AdkError::session(format!("transaction rollback failed: {e}"))
                })?;
                continue;
            }

            // Execute the migration SQL (raw_sql supports multiple
            // semicolon-separated statements in a single call).
            // `Executor::execute` returns a boxed `Send` future; `RawSql::execute` is an
            // `async fn` whose future is not provably `Send` for PostgreSQL connections.
            // Step bodies are `&'static str`, so they need no `AssertSqlSafe`.
            sqlx::Executor::execute(&mut *tx, sqlx::raw_sql(sql)).await.map_err(|e| {
                adk_core::AdkError::session(format!(
                    "{}",
                    MigrationError {
                        version,
                        description: description.to_string(),
                        cause: e.to_string(),
                    }
                ))
            })?;

            // Record the step in the registry
            let now = Utc::now().to_rfc3339();
            let rec = format!(
                "INSERT INTO {registry_table} \
                 (version, description, applied_at) \
                 VALUES ($1, $2, $3)"
            );
            sqlx::query(sqlx::AssertSqlSafe(rec))
                .bind(version)
                .bind(description)
                .bind(&now)
                .execute(&mut *tx)
                .await
                .map_err(|e| {
                    adk_core::AdkError::session(format!(
                        "{}",
                        MigrationError {
                            version,
                            description: description.to_string(),
                            cause: format!("registry record failed: {e}"),
                        }
                    ))
                })?;

            tx.commit().await.map_err(|e| {
                adk_core::AdkError::session(format!(
                    "{}",
                    MigrationError {
                        version,
                        description: description.to_string(),
                        cause: format!("transaction commit failed: {e}"),
                    }
                ))
            })?;
        }

        Ok(())
    }};
}

/// Generates `run_sql_migrations`, `run_sql_migrations_on_connection`, and
/// `sql_schema_version` for a concrete sqlx pool and connection type. Each SQL
/// backend (`sqlite`, `postgres`) gets its own monomorphised copy, avoiding complex
/// generic trait bounds.
#[cfg(any(feature = "sqlite", feature = "postgres"))]
macro_rules! impl_sql_migration_runner {
    (
        $mod_name:ident,
        $pool_ty:ty,
        $conn_ty:ty,
        $int_type:expr,
        $begin_sql:expr,
        $missing_table:expr
    ) => {
        /// SQL migration runner for this database backend.
        pub mod $mod_name {
            use super::MigrationError;
            use chrono::Utc;
            use sqlx::{Connection, Row};
            use std::future::Future;
            use std::pin::Pin;

            /// Run all pending migrations for a SQL backend.
            ///
            /// `registry_table` must be an ASCII identifier of at most 63 bytes,
            /// starting with a letter or underscore. Step bodies are trusted executable SQL, never user input.
            /// Descriptions are bound as values and may contain quotes.
            ///
            /// 1. Creates the registry table if it does not exist.
            /// 2. Calls `detect_existing` to check for pre-existing schema
            ///    tables. If tables exist but the registry is empty, records
            ///    version 1 as already applied (baseline).
            /// 3. Reads the maximum applied version from the registry.
            /// 4. If the database version exceeds the compiled-in maximum,
            ///    returns a version-mismatch error.
            /// 5. Executes each unapplied step inside a transaction and
            ///    records it in the registry.
            ///
            /// Each statement takes a connection from `pool`. Use
            /// [`run_sql_migrations_on_connection`] when every statement must
            /// run on the connection that holds a session-level lock.
            pub async fn run_sql_migrations<F, Fut>(
                pool: &$pool_ty,
                registry_table: &str,
                steps: &'static [(i64, &'static str, &'static str)],
                detect_existing: F,
            ) -> Result<(), adk_core::AdkError>
            where
                F: FnOnce() -> Fut,
                Fut: Future<Output = Result<bool, adk_core::AdkError>>,
            {
                sql_migration_body!(
                    exec: pool,
                    begin: async {
                        match $begin_sql {
                            Some(statement) => pool.begin_with(statement).await,
                            None => pool.begin().await,
                        }
                    },
                    detect: detect_existing(),
                    registry_table: registry_table,
                    steps: steps,
                    int_type: $int_type,
                )
            }

            /// Run all pending migrations on one connection.
            ///
            /// The identifier and trusted-SQL requirements of [`run_sql_migrations`]
            /// apply to this entry point too.
            ///
            /// Performs the same steps as [`run_sql_migrations`], but every
            /// statement, including `detect_existing`, runs on `conn`. A
            /// session-level lock taken on `conn`, such as a PostgreSQL advisory
            /// lock, therefore covers the whole run, and the run needs no second
            /// connection.
            ///
            /// # Errors
            ///
            /// Returns an error when a statement or `detect_existing` fails, or
            /// when the registry records a version newer than the last entry in
            /// `steps`.
            pub async fn run_sql_migrations_on_connection<F>(
                conn: &mut $conn_ty,
                registry_table: &str,
                steps: &'static [(i64, &'static str, &'static str)],
                detect_existing: F,
            ) -> Result<(), adk_core::AdkError>
            where
                F: FnOnce(
                    &mut $conn_ty,
                ) -> Pin<
                    Box<dyn Future<Output = Result<bool, adk_core::AdkError>> + Send + '_>,
                >,
            {
                sql_migration_body!(
                    exec: &mut *conn,
                    begin: async {
                        match $begin_sql {
                            Some(statement) => conn.begin_with(statement).await,
                            None => conn.begin().await,
                        }
                    },
                    detect: detect_existing(&mut *conn),
                    registry_table: registry_table,
                    steps: steps,
                    int_type: $int_type,
                )
            }

            /// Returns the highest applied migration version, or 0 if no
            /// registry table exists or the registry is empty.
            ///
            /// # Errors
            ///
            /// Returns an error when `registry_table` is not an ASCII identifier of
            /// at most 63 bytes, or 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 sql_schema_version(
                pool: &$pool_ty,
                registry_table: &str,
            ) -> Result<i64, adk_core::AdkError> {
                super::validate_registry_table(registry_table)?;
                let sql =
                    format!("SELECT COALESCE(MAX(version), 0) AS max_v FROM {registry_table}");
                let missing_table: fn(&dyn sqlx::error::DatabaseError) -> bool = $missing_table;
                let row = match sqlx::query(sqlx::AssertSqlSafe(sql)).fetch_one(pool).await {
                    Ok(row) => row,
                    Err(sqlx::Error::Database(error)) if missing_table(error.as_ref()) => {
                        return Ok(0);
                    }
                    Err(e) => {
                        return Err(adk_core::AdkError::session(format!(
                            "migration registry read failed: {e}"
                        )));
                    }
                };
                row.try_get("max_v").map_err(|e| {
                    adk_core::AdkError::session(format!("migration registry read failed: {e}"))
                })
            }
        }
    };
}

// SQLite reports a missing table only through its message; PostgreSQL uses
// SQLSTATE 42P01 (undefined_table).
#[cfg(feature = "sqlite")]
impl_sql_migration_runner!(
    sqlite_runner,
    sqlx::SqlitePool,
    sqlx::SqliteConnection,
    "INTEGER",
    // Takes the write lock at once, so a step and its registry check see no other writer.
    Some("BEGIN IMMEDIATE"),
    |error| error.message().starts_with("no such table")
);

#[cfg(feature = "postgres")]
impl_sql_migration_runner!(
    pg_runner,
    sqlx::PgPool,
    sqlx::PgConnection,
    "BIGINT",
    None::<&str>,
    |error| { error.code().as_deref() == Some("42P01") }
);

/// Runs migrations for a PostgreSQL-backed store under a session-level advisory lock
/// keyed by `registry_table`, so concurrent processes migrate one at a time.
///
/// The lock is held on a dedicated connection opened outside `pool`, so a pool with a
/// single connection can still run the statements. Closing that connection releases
/// the lock even when this future is cancelled. Tables are created with
/// `IF NOT EXISTS`, so no baseline detection is needed.
#[cfg(feature = "postgres")]
pub(crate) fn run_pg_migrations_locked(
    pool: &sqlx::PgPool,
    registry_table: &'static str,
    steps: &'static [(i64, &'static str, &'static str)],
) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<(), adk_core::AdkError>> + Send>> {
    use sqlx::Connection;

    // Boxed so the future is checked for `Send` here, with concrete lifetimes; callers
    // inside `async_trait` methods otherwise hit rustc's higher-ranked `Send` inference
    // limits on sqlx executors.
    let pool = pool.clone();
    Box::pin(async move {
        let lock_key = registry_table
            .bytes()
            .fold(0xcbf2_9ce4_8422_2325_u64, |hash, byte| {
                (hash ^ u64::from(byte)).wrapping_mul(0x0100_0000_01b3)
            })
            .cast_signed();
        let mut lock = sqlx::PgConnection::connect_with(&pool.connect_options())
            .await
            .map_err(|e| adk_core::AdkError::session(format!("database connection failed: {e}")))?;
        sqlx::query("SELECT pg_advisory_lock($1)")
            .bind(lock_key)
            .execute(&mut lock)
            .await
            .map_err(|e| {
                adk_core::AdkError::session(format!("advisory lock acquisition failed: {e}"))
            })?;
        let result =
            pg_runner::run_sql_migrations(&pool, registry_table, steps, || async { Ok(false) })
                .await;
        let _ = lock.close().await;
        result
    })
}