Skip to main content

adk_session/
run_store.rs

1//! SQL-backed [`DurableRunStore`](adk_core::DurableRunStore) implementations.
2//!
3//! One row per run in `adk_runs`. `seq` is assigned by the database and breaks ties in
4//! enqueue order, so runs are ordered by `(created_at_us, seq)`.
5//!
6//! | Guarantee | Primitive |
7//! |-----------|-----------|
8//! | Idempotent enqueue | Unique index on `(queue, idempotency_key)`; `INSERT ... ON CONFLICT DO NOTHING`, then the existing run is read |
9//! | Double texting | The concurrency-key holders are read and `Reject` / `Interrupt` applied in the enqueue transaction, which PostgreSQL serializes per `(queue, concurrency_key)` with `pg_advisory_xact_lock` and SQLite with `BEGIN IMMEDIATE` |
10//! | Single claim winner | PostgreSQL: `SELECT ... ORDER BY created_at_us, seq LIMIT 1 FOR UPDATE OF r SKIP LOCKED`, then `UPDATE ... WHERE seq = $1`, in one transaction; SQLite: the same statements under `BEGIN IMMEDIATE` |
11//! | Fenced worker writes | `UPDATE ... WHERE run_id = $r AND lease_epoch = $e AND state = 'running'`; no row changed is `run_store.stale_epoch` (or `run_store.not_found` when the run does not exist) |
12//! | `wake`, `request_cancel` | One `UPDATE` whose `CASE` arms act on the state the row has when the write lands |
13//! | `prune` | `DELETE ... WHERE seq IN (SELECT ... LIMIT 500)`, repeated until a batch comes back short |
14//!
15//! | Index | Serves |
16//! |-------|--------|
17//! | `adk_runs_idempotency` (unique) | Idempotent enqueue |
18//! | `adk_runs_claim`, partial on unfinished states | `claim` in enqueue order |
19//! | `adk_runs_concurrency`, partial on unfinished states | Concurrency-key holders in `enqueue` and `claim` |
20//! | `adk_runs_finished`, partial on finished states | `prune` |
21//! | `adk_runs_owner` | `list` by application, user, and session |
22
23use std::sync::Arc;
24use std::time::Duration;
25
26use adk_core::run_store::{run_not_found_error, run_stale_epoch_error};
27use adk_core::{
28    ClaimedRun, Clock, DurableRunStore, Enqueued, NewRun, OnConflict, Result, RunCheckpointRef,
29    RunFilter, RunOutcome, RunRecord, RunState, SystemClock,
30};
31use chrono::{DateTime, Utc};
32use serde::Serialize;
33use serde::de::DeserializeOwned;
34
35use crate::durable_sql::{
36    deadline, from_json, from_micros, micros, now, storage_error, to_i64, to_json, to_u32, to_u64,
37};
38
39const CODE: &str = "session.run_store.storage";
40
41const REGISTRY_TABLE: &str = "_adk_run_migrations";
42
43/// Rows deleted per `prune` statement, so one call never holds a long lock.
44const PRUNE_BATCH: i64 = 500;
45
46/// Indexes shared by both dialects; `seq` is the only column whose definition differs.
47macro_rules! run_indexes {
48    () => {
49        "\
50CREATE UNIQUE INDEX IF NOT EXISTS adk_runs_idempotency ON adk_runs (queue, idempotency_key);\
51CREATE INDEX IF NOT EXISTS adk_runs_claim ON adk_runs (queue, created_at_us, seq) \
52    WHERE state IN ('queued', 'running', 'waiting');\
53CREATE INDEX IF NOT EXISTS adk_runs_concurrency ON adk_runs (queue, concurrency_key, created_at_us, seq) \
54    WHERE state IN ('queued', 'running', 'waiting');\
55CREATE INDEX IF NOT EXISTS adk_runs_finished ON adk_runs (updated_at_us) \
56    WHERE state IN ('completed', 'failed', 'cancelled');\
57CREATE INDEX IF NOT EXISTS adk_runs_owner ON adk_runs (app_name, user_id, session_id);"
58    };
59}
60
61macro_rules! run_table {
62    ($seq:literal) => {
63        concat!(
64            "CREATE TABLE IF NOT EXISTS adk_runs (",
65            $seq,
66            ", \
67    run_id TEXT NOT NULL UNIQUE, \
68    queue TEXT NOT NULL, \
69    app_name TEXT NOT NULL, \
70    user_id TEXT NOT NULL, \
71    session_id TEXT, \
72    target TEXT NOT NULL, \
73    input TEXT NOT NULL, \
74    idempotency_key TEXT, \
75    concurrency_key TEXT, \
76    on_conflict TEXT NOT NULL, \
77    not_before_us BIGINT, \
78    max_attempts BIGINT NOT NULL, \
79    principal TEXT, \
80    state TEXT NOT NULL, \
81    attempt BIGINT NOT NULL, \
82    lease_owner TEXT, \
83    lease_epoch BIGINT NOT NULL, \
84    lease_expires_at_us BIGINT, \
85    heartbeat_at_us BIGINT, \
86    checkpoint TEXT, \
87    cancel_requested BOOLEAN NOT NULL, \
88    wake_pending BOOLEAN NOT NULL, \
89    result TEXT, \
90    error TEXT, \
91    created_at_us BIGINT NOT NULL, \
92    updated_at_us BIGINT NOT NULL, \
93    revision BIGINT NOT NULL\
94);",
95            run_indexes!()
96        )
97    };
98}
99
100macro_rules! run_columns {
101    () => {
102        "run_id, queue, app_name, user_id, session_id, target, input, idempotency_key, \
103         concurrency_key, on_conflict, not_before_us, max_attempts, principal, state, attempt, \
104         lease_owner, lease_epoch, lease_expires_at_us, heartbeat_at_us, checkpoint, \
105         cancel_requested, wake_pending, result, error, created_at_us, updated_at_us, revision, \
106         authenticated"
107    };
108}
109
110// Parameters appear in ascending order in every statement, so SQLite, which numbers
111// `$N` parameters by first appearance, binds them as PostgreSQL does.
112const INSERT: &str = concat!(
113    "INSERT INTO adk_runs (",
114    run_columns!(),
115    ") VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, \
116     $19, $20, $21, $22, $23, $24, $25, $26, $27, $28) \
117     ON CONFLICT (queue, idempotency_key) DO NOTHING"
118);
119
120const GET: &str = concat!("SELECT ", run_columns!(), " FROM adk_runs WHERE run_id = $1");
121
122const BY_KEY: &str =
123    concat!("SELECT ", run_columns!(), " FROM adk_runs WHERE queue = $1 AND idempotency_key = $2");
124
125const EXISTS: &str = "SELECT 1 FROM adk_runs WHERE run_id = $1";
126
127const OLDEST_HOLDER: &str = "\
128SELECT run_id FROM adk_runs \
129WHERE queue = $1 AND concurrency_key = $2 AND state IN ('queued', 'running', 'waiting') \
130ORDER BY created_at_us, seq LIMIT 1";
131
132/// Cancels queued and waiting holders and flags running ones. One statement, so a holder
133/// that a worker parks or claims concurrently is handled in the state it lands in.
134const INTERRUPT: &str = "\
135UPDATE adk_runs SET \
136    cancel_requested = CASE WHEN state = 'running' THEN TRUE ELSE cancel_requested END, \
137    lease_owner = CASE WHEN state = 'running' THEN lease_owner ELSE NULL END, \
138    lease_expires_at_us = CASE WHEN state = 'running' THEN lease_expires_at_us ELSE NULL END, \
139    state = CASE WHEN state = 'running' THEN state ELSE 'cancelled' END, \
140    updated_at_us = $1, revision = revision + 1 \
141WHERE queue = $2 AND concurrency_key = $3 AND state IN ('queued', 'running', 'waiting')";
142
143/// Claimable runs in queue order: a queued run that is due and has no earlier unfinished
144/// run with its concurrency key, a waiting run whose wait ended, or a running run whose
145/// lease expired.
146macro_rules! claim_candidate {
147    ($lock:literal) => {
148        concat!(
149            "SELECT r.seq, r.state, r.attempt, r.max_attempts FROM adk_runs r \
150             WHERE r.queue = $1 AND r.state IN ('queued', 'running', 'waiting') AND ( \
151                 (r.state = 'queued' \
152                     AND (r.not_before_us IS NULL OR r.not_before_us <= $2) \
153                     AND (r.concurrency_key IS NULL OR NOT EXISTS ( \
154                         SELECT 1 FROM adk_runs h \
155                         WHERE h.queue = r.queue AND h.concurrency_key = r.concurrency_key \
156                             AND h.state IN ('queued', 'running', 'waiting') \
157                             AND (h.created_at_us < r.created_at_us \
158                                 OR (h.created_at_us = r.created_at_us AND h.seq < r.seq))))) \
159                 OR (r.state = 'waiting' AND r.not_before_us IS NOT NULL AND r.not_before_us <= $2) \
160                 OR (r.state = 'running' \
161                     AND (r.lease_expires_at_us IS NULL OR r.lease_expires_at_us <= $2))) \
162             ORDER BY r.created_at_us, r.seq LIMIT 1",
163            $lock
164        )
165    };
166}
167
168const CLAIM: &str = concat!(
169    "UPDATE adk_runs SET \
170         attempt = attempt + CASE WHEN state = 'waiting' THEN 0 ELSE 1 END, \
171         state = 'running', lease_epoch = lease_epoch + 1, lease_owner = $1, \
172         lease_expires_at_us = $2, heartbeat_at_us = $3, not_before_us = NULL, \
173         updated_at_us = $3, revision = revision + 1 \
174     WHERE seq = $4 RETURNING ",
175    run_columns!()
176);
177
178const EXHAUST: &str = "\
179UPDATE adk_runs SET state = 'failed', error = $1, lease_owner = NULL, \
180    lease_expires_at_us = NULL, updated_at_us = $2, revision = revision + 1 \
181WHERE seq = $3";
182
183const HEARTBEAT: &str = "\
184UPDATE adk_runs SET lease_expires_at_us = $1, heartbeat_at_us = $2, updated_at_us = $2, \
185    revision = revision + 1 \
186WHERE run_id = $3 AND lease_epoch = $4 AND state = 'running' \
187RETURNING cancel_requested";
188
189const SET_CHECKPOINT: &str = "\
190UPDATE adk_runs SET checkpoint = $1, updated_at_us = $2, revision = revision + 1 \
191WHERE run_id = $3 AND lease_epoch = $4 AND state = 'running'";
192
193/// A wake that arrived while the run was running parks it as already woken.
194const WAIT: &str = "\
195UPDATE adk_runs SET state = 'waiting', \
196    not_before_us = CASE WHEN wake_pending THEN $1 ELSE $2 END, \
197    wake_pending = FALSE, lease_owner = NULL, lease_expires_at_us = NULL, \
198    updated_at_us = $1, revision = revision + 1 \
199WHERE run_id = $3 AND lease_epoch = $4 AND state = 'running'";
200
201const WAKE: &str = "\
202UPDATE adk_runs SET \
203    not_before_us = CASE WHEN state = 'waiting' THEN $1 ELSE not_before_us END, \
204    wake_pending = CASE WHEN state = 'running' THEN TRUE ELSE wake_pending END, \
205    updated_at_us = $1, revision = revision + 1 \
206WHERE run_id = $2 AND state IN ('waiting', 'running')";
207
208/// A retryable failure requeues while attempts remain and no cancellation was requested,
209/// claimable from `$2`, the end of its backoff (`NULL`: at once).
210const FINISH: &str = concat!(
211    "UPDATE adk_runs SET \
212         not_before_us = CASE WHEN $1 AND attempt < max_attempts AND NOT cancel_requested \
213             THEN $2 ELSE not_before_us END, \
214         state = CASE WHEN $1 AND attempt < max_attempts AND NOT cancel_requested \
215             THEN 'queued' ELSE $3 END, \
216         result = COALESCE($4, result), error = COALESCE($5, error), \
217         wake_pending = FALSE, lease_owner = NULL, lease_expires_at_us = NULL, \
218         updated_at_us = $6, revision = revision + 1 \
219     WHERE run_id = $7 AND lease_epoch = $8 AND state = 'running' RETURNING ",
220    run_columns!()
221);
222
223const REQUEST_CANCEL: &str = "\
224UPDATE adk_runs SET \
225    cancel_requested = CASE WHEN state = 'running' THEN TRUE ELSE cancel_requested END, \
226    lease_owner = CASE WHEN state = 'running' THEN lease_owner ELSE NULL END, \
227    lease_expires_at_us = CASE WHEN state = 'running' THEN lease_expires_at_us ELSE NULL END, \
228    state = CASE WHEN state = 'running' THEN state ELSE 'cancelled' END, \
229    updated_at_us = $1, revision = revision + 1 \
230WHERE run_id = $2 AND state IN ('queued', 'running', 'waiting')";
231
232const PRUNE: &str = "\
233DELETE FROM adk_runs WHERE seq IN (\
234    SELECT seq FROM adk_runs \
235    WHERE state IN ('completed', 'failed', 'cancelled') AND updated_at_us < $1 \
236    LIMIT $2)";
237
238fn failed(e: sqlx::Error) -> adk_core::AdkError {
239    storage_error(CODE, format!("run store query failed: {e}"))
240}
241
242/// The stored name of a serde unit variant, such as `"queued"` for [`RunState::Queued`].
243fn variant_name<T: Serialize>(value: &T) -> Result<String> {
244    match serde_json::to_value(value) {
245        Ok(serde_json::Value::String(name)) => Ok(name),
246        Ok(other) => Err(storage_error(CODE, format!("{other} is not a unit variant"))),
247        Err(e) => Err(storage_error(CODE, format!("serialize failed: {e}"))),
248    }
249}
250
251fn from_variant_name<T: DeserializeOwned>(column: &str, name: String) -> Result<T> {
252    serde_json::from_value(serde_json::Value::String(name))
253        .map_err(|e| storage_error(CODE, format!("column '{column}' is corrupt: {e}")))
254}
255
256fn optional_json<T: DeserializeOwned>(column: &str, json: Option<String>) -> Result<Option<T>> {
257    json.map(|json| from_json(CODE, column, &json)).transpose()
258}
259
260fn optional_time(column: &str, us: Option<i64>) -> Result<Option<DateTime<Utc>>> {
261    us.map(|us| from_micros(CODE, column, us)).transpose()
262}
263
264/// A new run's columns that need encoding: JSON text, variant names, and microseconds.
265struct RunRow {
266    input: String,
267    on_conflict: String,
268    not_before_us: Option<i64>,
269    principal: Option<String>,
270    state: String,
271    created_at_us: i64,
272}
273
274impl RunRow {
275    fn new(record: &RunRecord) -> Result<Self> {
276        Ok(Self {
277            input: to_json(CODE, &record.input)?,
278            on_conflict: variant_name(&record.on_conflict)?,
279            not_before_us: record.not_before.map(|at| micros(at).1),
280            principal: record.principal.as_ref().map(|p| to_json(CODE, p)).transpose()?,
281            state: variant_name(&record.state)?,
282            created_at_us: micros(record.created_at).1,
283        })
284    }
285}
286
287/// Decodes a row selected with [`run_columns!`].
288macro_rules! decode_run {
289    ($row:expr) => {{
290        use sqlx::Row;
291        let row = $row;
292        let column = |name: &str, e: sqlx::Error| {
293            storage_error(CODE, format!("run store column '{name}' unreadable: {e}"))
294        };
295        macro_rules! get {
296            ($name:literal) => {
297                row.try_get($name).map_err(|e| column($name, e))?
298            };
299        }
300        let input: String = get!("input");
301        let on_conflict: String = get!("on_conflict");
302        let state: String = get!("state");
303        let max_attempts: i64 = get!("max_attempts");
304        let attempt: i64 = get!("attempt");
305        let lease_epoch: i64 = get!("lease_epoch");
306        let revision: i64 = get!("revision");
307        let created_at_us: i64 = get!("created_at_us");
308        let updated_at_us: i64 = get!("updated_at_us");
309        let record: Result<RunRecord> = Ok(RunRecord {
310            run_id: get!("run_id"),
311            queue: get!("queue"),
312            app_name: get!("app_name"),
313            user_id: get!("user_id"),
314            session_id: get!("session_id"),
315            target: get!("target"),
316            input: from_json(CODE, "input", &input)?,
317            idempotency_key: get!("idempotency_key"),
318            concurrency_key: get!("concurrency_key"),
319            on_conflict: from_variant_name::<OnConflict>("on_conflict", on_conflict)?,
320            not_before: optional_time("not_before_us", get!("not_before_us"))?,
321            max_attempts: to_u32(CODE, "max_attempts", max_attempts)?,
322            principal: optional_json("principal", get!("principal"))?,
323            state: from_variant_name::<RunState>("state", state)?,
324            attempt: to_u32(CODE, "attempt", attempt)?,
325            lease_owner: get!("lease_owner"),
326            lease_epoch: to_u64(CODE, "lease_epoch", lease_epoch)?,
327            lease_expires_at: optional_time("lease_expires_at_us", get!("lease_expires_at_us"))?,
328            heartbeat_at: optional_time("heartbeat_at_us", get!("heartbeat_at_us"))?,
329            checkpoint: optional_json::<RunCheckpointRef>("checkpoint", get!("checkpoint"))?,
330            cancel_requested: get!("cancel_requested"),
331            wake_pending: get!("wake_pending"),
332            result: optional_json("result", get!("result"))?,
333            error: get!("error"),
334            created_at: from_micros(CODE, "created_at_us", created_at_us)?,
335            updated_at: from_micros(CODE, "updated_at_us", updated_at_us)?,
336            revision: to_u64(CODE, "revision", revision)?,
337            authenticated: get!("authenticated"),
338        });
339        record
340    }};
341}
342
343macro_rules! sql_run_store {
344    (
345        $(#[$doc:meta])*
346        $name:ident, $pool:ty, $db:ty,
347        begin = $begin:literal,
348        lock = $lock:literal,
349        serialize_key = $serialize_key:expr,
350        $migrate:expr
351    ) => {
352        $(#[$doc])*
353        #[derive(Debug, Clone)]
354        pub struct $name {
355            pool: $pool,
356            clock: Arc<dyn Clock>,
357        }
358
359        impl $name {
360            /// Connects to `database_url` and creates a connection pool.
361            ///
362            /// Call [`migrate`](Self::migrate) before first use.
363            ///
364            /// # Errors
365            ///
366            /// Returns `session.run_store.storage` when the database cannot be reached.
367            pub async fn new(database_url: &str) -> Result<Self> {
368                let pool = <$pool>::connect(database_url).await.map_err(|e| {
369                    storage_error(CODE, format!("run store connection failed: {e}"))
370                })?;
371                Ok(Self::from_pool(pool))
372            }
373
374            /// Uses an existing pool, such as the one the session service holds.
375            pub fn from_pool(pool: $pool) -> Self {
376                Self { pool, clock: Arc::new(SystemClock) }
377            }
378
379            /// Sets the clock that decides delays, waits, and lease expiry.
380            pub fn with_clock(mut self, clock: Arc<dyn Clock>) -> Self {
381                self.clock = clock;
382                self
383            }
384
385            /// Creates or upgrades the run table and its indexes.
386            ///
387            /// # Errors
388            ///
389            /// Returns an error when a migration statement fails.
390            pub async fn migrate(&self) -> Result<()> {
391                let migrate = $migrate;
392                migrate(&self.pool).await
393            }
394
395            async fn by_key(&self, queue: &str, key: &str) -> Result<Option<RunRecord>> {
396                let row = sqlx::query(BY_KEY)
397                    .bind(queue)
398                    .bind(key)
399                    .fetch_optional(&self.pool)
400                    .await
401                    .map_err(failed)?;
402                row.map(|row| decode_run!(&row)).transpose()
403            }
404
405            /// The error for a fenced write that changed no row.
406            async fn refused(&self, run_id: &str, epoch: u64) -> adk_core::AdkError {
407                match sqlx::query_scalar::<_, i32>(EXISTS)
408                    .bind(run_id)
409                    .fetch_optional(&self.pool)
410                    .await
411                {
412                    Ok(Some(_)) => run_stale_epoch_error(run_id, epoch),
413                    Ok(None) => run_not_found_error(run_id),
414                    Err(e) => failed(e),
415                }
416            }
417
418            /// Applies the double-texting policy inside the enqueue transaction and
419            /// returns the blocking run when `Reject` refuses the new run.
420            async fn apply_conflict_policy(
421                tx: &mut sqlx::Transaction<'static, $db>,
422                run: &NewRun,
423                now_us: i64,
424            ) -> Result<Option<String>> {
425                let Some(key) = &run.concurrency_key else { return Ok(None) };
426                let serialize_key = $serialize_key;
427                serialize_key(&mut **tx, &run.queue, key).await?;
428                match run.on_conflict {
429                    OnConflict::Reject => sqlx::query_scalar(OLDEST_HOLDER)
430                        .bind(&run.queue)
431                        .bind(key)
432                        .fetch_optional(&mut **tx)
433                        .await
434                        .map_err(failed),
435                    OnConflict::Interrupt => {
436                        sqlx::query(INTERRUPT)
437                            .bind(now_us)
438                            .bind(&run.queue)
439                            .bind(key)
440                            .execute(&mut **tx)
441                            .await
442                            .map_err(failed)?;
443                        Ok(None)
444                    }
445                    OnConflict::Enqueue => Ok(None),
446                    // `OnConflict` is non-exhaustive; a policy this store does not know
447                    // is refused rather than silently treated as another.
448                    other => Err(adk_core::run_store::invalid_run_error(&format!(
449                        "on_conflict policy {other:?} is not supported by this run store"
450                    ))),
451                }
452            }
453        }
454
455        #[async_trait::async_trait]
456        impl DurableRunStore for $name {
457            async fn enqueue(&self, run: NewRun) -> Result<Enqueued> {
458                run.validate()?;
459                // A concurrent enqueue of the same key wins the unique index; the next
460                // pass reads its run. A run pruned in between makes a further pass.
461                for _ in 0..3 {
462                    if let Some(key) = &run.idempotency_key
463                        && let Some(existing) = self.by_key(&run.queue, key).await?
464                    {
465                        return Ok(Enqueued::Existing(existing));
466                    }
467                    let (now, now_us) = now(&*self.clock);
468                    let mut tx = self.pool.begin_with($begin).await.map_err(failed)?;
469                    if let Some(blocking_run_id) =
470                        Self::apply_conflict_policy(&mut tx, &run, now_us).await?
471                    {
472                        tx.rollback().await.map_err(failed)?;
473                        return Ok(Enqueued::Rejected { blocking_run_id });
474                    }
475                    let record =
476                        RunRecord::queued(uuid::Uuid::new_v4().to_string(), run.clone(), now);
477                    let row = RunRow::new(&record)?;
478                    let inserted = sqlx::query(INSERT)
479                        .bind(&record.run_id)
480                        .bind(&record.queue)
481                        .bind(&record.app_name)
482                        .bind(&record.user_id)
483                        .bind(record.session_id.as_deref())
484                        .bind(&record.target)
485                        .bind(&row.input)
486                        .bind(record.idempotency_key.as_deref())
487                        .bind(record.concurrency_key.as_deref())
488                        .bind(&row.on_conflict)
489                        .bind(row.not_before_us)
490                        .bind(i64::from(record.max_attempts))
491                        .bind(row.principal.as_deref())
492                        .bind(&row.state)
493                        .bind(0_i64)
494                        .bind(None::<String>)
495                        .bind(0_i64)
496                        .bind(None::<i64>)
497                        .bind(None::<i64>)
498                        .bind(None::<String>)
499                        .bind(false)
500                        .bind(false)
501                        .bind(None::<String>)
502                        .bind(None::<String>)
503                        .bind(row.created_at_us)
504                        .bind(row.created_at_us)
505                        .bind(1_i64)
506                        .bind(record.authenticated)
507                        .execute(&mut *tx)
508                        .await
509                        .map_err(failed)?;
510                    if inserted.rows_affected() == 1 {
511                        tx.commit().await.map_err(failed)?;
512                        let mut record = record;
513                        record.not_before = record.not_before.map(|at| micros(at).0);
514                        return Ok(Enqueued::Created(record));
515                    }
516                    tx.rollback().await.map_err(failed)?;
517                }
518                Err(storage_error(
519                    CODE,
520                    "the run holding this idempotency key was pruned while enqueueing three \
521                     times; retry the enqueue",
522                ))
523            }
524
525            async fn claim(
526                &self,
527                queue: &str,
528                worker: &str,
529                ttl: Duration,
530            ) -> Result<Option<ClaimedRun>> {
531                let (now, now_us) = now(&*self.clock);
532                let (_, expires_us) = deadline(now, ttl, "run_store.invalid_ttl")?;
533                let mut tx = self.pool.begin_with($begin).await.map_err(failed)?;
534                loop {
535                    let candidate: Option<(i64, String, i64, i64)> =
536                        sqlx::query_as(claim_candidate!($lock))
537                            .bind(queue)
538                            .bind(now_us)
539                            .fetch_optional(&mut *tx)
540                            .await
541                            .map_err(failed)?;
542                    let Some((seq, state, attempt, max_attempts)) = candidate else {
543                        tx.commit().await.map_err(failed)?;
544                        return Ok(None);
545                    };
546                    if state == "running" && attempt >= max_attempts {
547                        sqlx::query(EXHAUST)
548                            .bind(format!(
549                                "attempts exhausted: the lease of attempt {attempt} of \
550                                 {max_attempts} expired"
551                            ))
552                            .bind(now_us)
553                            .bind(seq)
554                            .execute(&mut *tx)
555                            .await
556                            .map_err(failed)?;
557                        continue;
558                    }
559                    let row = sqlx::query(CLAIM)
560                        .bind(worker)
561                        .bind(expires_us)
562                        .bind(now_us)
563                        .bind(seq)
564                        .fetch_one(&mut *tx)
565                        .await
566                        .map_err(failed)?;
567                    let record = decode_run!(&row)?;
568                    tx.commit().await.map_err(failed)?;
569                    return Ok(Some(ClaimedRun { epoch: record.lease_epoch, record }));
570                }
571            }
572
573            async fn heartbeat(&self, run_id: &str, epoch: u64, ttl: Duration) -> Result<bool> {
574                let (now, now_us) = now(&*self.clock);
575                let (_, expires_us) = deadline(now, ttl, "run_store.invalid_ttl")?;
576                let Ok(stored_epoch) = to_i64(CODE, epoch) else {
577                    return Err(self.refused(run_id, epoch).await);
578                };
579                let cancel_requested: Option<bool> = sqlx::query_scalar(HEARTBEAT)
580                    .bind(expires_us)
581                    .bind(now_us)
582                    .bind(run_id)
583                    .bind(stored_epoch)
584                    .fetch_optional(&self.pool)
585                    .await
586                    .map_err(failed)?;
587                match cancel_requested {
588                    Some(cancel_requested) => Ok(cancel_requested),
589                    None => Err(self.refused(run_id, epoch).await),
590                }
591            }
592
593            async fn set_checkpoint(
594                &self,
595                run_id: &str,
596                epoch: u64,
597                checkpoint: RunCheckpointRef,
598            ) -> Result<()> {
599                let (_, now_us) = now(&*self.clock);
600                let Ok(stored_epoch) = to_i64(CODE, epoch) else {
601                    return Err(self.refused(run_id, epoch).await);
602                };
603                let updated = sqlx::query(SET_CHECKPOINT)
604                    .bind(to_json(CODE, &checkpoint)?)
605                    .bind(now_us)
606                    .bind(run_id)
607                    .bind(stored_epoch)
608                    .execute(&self.pool)
609                    .await
610                    .map_err(failed)?;
611                if updated.rows_affected() == 0 {
612                    return Err(self.refused(run_id, epoch).await);
613                }
614                Ok(())
615            }
616
617            async fn wait(
618                &self,
619                run_id: &str,
620                epoch: u64,
621                until: Option<DateTime<Utc>>,
622            ) -> Result<()> {
623                let (_, now_us) = now(&*self.clock);
624                let Ok(stored_epoch) = to_i64(CODE, epoch) else {
625                    return Err(self.refused(run_id, epoch).await);
626                };
627                let updated = sqlx::query(WAIT)
628                    .bind(now_us)
629                    .bind(until.map(|at| micros(at).1))
630                    .bind(run_id)
631                    .bind(stored_epoch)
632                    .execute(&self.pool)
633                    .await
634                    .map_err(failed)?;
635                if updated.rows_affected() == 0 {
636                    return Err(self.refused(run_id, epoch).await);
637                }
638                Ok(())
639            }
640
641            async fn wake(&self, run_id: &str) -> Result<()> {
642                let (_, now_us) = now(&*self.clock);
643                let updated = sqlx::query(WAKE)
644                    .bind(now_us)
645                    .bind(run_id)
646                    .execute(&self.pool)
647                    .await
648                    .map_err(failed)?;
649                if updated.rows_affected() == 0 && self.get(run_id).await?.is_none() {
650                    return Err(run_not_found_error(run_id));
651                }
652                Ok(())
653            }
654
655            async fn finish(
656                &self,
657                run_id: &str,
658                epoch: u64,
659                outcome: RunOutcome,
660            ) -> Result<RunRecord> {
661                let (now_at, now_us) = now(&*self.clock);
662                let Ok(stored_epoch) = to_i64(CODE, epoch) else {
663                    return Err(self.refused(run_id, epoch).await);
664                };
665                let (retryable, backoff, state, result, error) = match outcome {
666                    RunOutcome::Completed(result) => {
667                        (false, None, RunState::Completed, Some(to_json(CODE, &result)?), None)
668                    }
669                    RunOutcome::Failed { error, retryable, backoff } => {
670                        (retryable, backoff, RunState::Failed, None, Some(error))
671                    }
672                    RunOutcome::Cancelled => (false, None, RunState::Cancelled, None, None),
673                };
674                let retry_at = backoff.map(|backoff| micros(now_at + backoff).1);
675                let row = sqlx::query(FINISH)
676                    .bind(retryable)
677                    .bind(retry_at)
678                    .bind(variant_name(&state)?)
679                    .bind(result)
680                    .bind(error)
681                    .bind(now_us)
682                    .bind(run_id)
683                    .bind(stored_epoch)
684                    .fetch_optional(&self.pool)
685                    .await
686                    .map_err(failed)?;
687                match row {
688                    Some(row) => decode_run!(&row),
689                    None => Err(self.refused(run_id, epoch).await),
690                }
691            }
692
693            async fn request_cancel(&self, run_id: &str) -> Result<()> {
694                let (_, now_us) = now(&*self.clock);
695                let updated = sqlx::query(REQUEST_CANCEL)
696                    .bind(now_us)
697                    .bind(run_id)
698                    .execute(&self.pool)
699                    .await
700                    .map_err(failed)?;
701                if updated.rows_affected() == 0 && self.get(run_id).await?.is_none() {
702                    return Err(run_not_found_error(run_id));
703                }
704                Ok(())
705            }
706
707            async fn get(&self, run_id: &str) -> Result<Option<RunRecord>> {
708                let row =
709                    sqlx::query(GET).bind(run_id).fetch_optional(&self.pool).await.map_err(failed)?;
710                row.map(|row| decode_run!(&row)).transpose()
711            }
712
713            async fn list(&self, filter: RunFilter) -> Result<Vec<RunRecord>> {
714                let mut query = sqlx::QueryBuilder::<$db>::new(concat!(
715                    "SELECT ",
716                    run_columns!(),
717                    " FROM adk_runs WHERE TRUE"
718                ));
719                let fields = [
720                    (" AND queue = ", &filter.queue),
721                    (" AND app_name = ", &filter.app_name),
722                    (" AND user_id = ", &filter.user_id),
723                    (" AND session_id = ", &filter.session_id),
724                    (" AND concurrency_key = ", &filter.concurrency_key),
725                ];
726                for (clause, value) in fields {
727                    if let Some(value) = value {
728                        query.push(clause).push_bind(value.clone());
729                    }
730                }
731                if !filter.states.is_empty() {
732                    query.push(" AND state IN (");
733                    let mut states = query.separated(", ");
734                    for state in &filter.states {
735                        states.push_bind(variant_name(state)?);
736                    }
737                    query.push(")");
738                }
739                query.push(" ORDER BY created_at_us, seq");
740                if let Some(limit) = filter.limit {
741                    query.push(" LIMIT ").push_bind(i64::try_from(limit).unwrap_or(i64::MAX));
742                }
743                let rows = query.build().fetch_all(&self.pool).await.map_err(failed)?;
744                rows.iter().map(|row| decode_run!(row)).collect()
745            }
746
747            async fn prune(&self, finished_before: DateTime<Utc>) -> Result<u64> {
748                let cutoff = micros(finished_before).1;
749                let mut pruned = 0;
750                loop {
751                    let deleted = sqlx::query(PRUNE)
752                        .bind(cutoff)
753                        .bind(PRUNE_BATCH)
754                        .execute(&self.pool)
755                        .await
756                        .map_err(failed)?
757                        .rows_affected();
758                    pruned += deleted;
759                    if deleted < PRUNE_BATCH.cast_unsigned() {
760                        return Ok(pruned);
761                    }
762                }
763            }
764        }
765    };
766}
767
768/// Adds `authenticated` (spec 3.1 ยง9.2 I6); rows written before it read as unauthenticated.
769#[cfg(any(feature = "sqlite", feature = "postgres"))]
770const ADD_AUTHENTICATED: &str =
771    "ALTER TABLE adk_runs ADD COLUMN authenticated BOOLEAN NOT NULL DEFAULT FALSE";
772
773#[cfg(feature = "sqlite")]
774const SQLITE_MIGRATIONS: &[(i64, &str, &str)] = &[
775    (1, "create run table", run_table!("seq INTEGER PRIMARY KEY AUTOINCREMENT")),
776    (2, "add authenticated", ADD_AUTHENTICATED),
777];
778
779#[cfg(feature = "sqlite")]
780sql_run_store! {
781    /// SQLite-backed [`DurableRunStore`].
782    ///
783    /// `enqueue` and `claim` run under `BEGIN IMMEDIATE`, which takes SQLite's write lock
784    /// before the first read, so concurrent claimers in any number of processes sharing
785    /// the database file never claim one run twice. Worker writes are single fenced
786    /// `UPDATE` statements.
787    ///
788    /// # Example
789    ///
790    /// ```rust,no_run
791    /// use std::time::Duration;
792    /// use adk_core::{DurableRunStore, NewRun, RunOutcome};
793    /// use adk_session::SqliteRunStore;
794    /// use serde_json::json;
795    ///
796    /// # async fn example() -> adk_core::Result<()> {
797    /// let store = SqliteRunStore::new("sqlite://runtime.db?mode=rwc").await?;
798    /// store.migrate().await?;
799    /// store.enqueue(NewRun::new("default", "app", "user", "agent", json!({"text": "hi"}))).await?;
800    /// if let Some(claimed) = store.claim("default", "worker-1", Duration::from_secs(30)).await? {
801    ///     store.finish(&claimed.record.run_id, claimed.epoch, RunOutcome::Completed(json!("ok"))).await?;
802    /// }
803    /// # Ok(())
804    /// # }
805    /// ```
806    SqliteRunStore, sqlx::SqlitePool, sqlx::Sqlite,
807    begin = "BEGIN IMMEDIATE",
808    lock = "",
809    // `BEGIN IMMEDIATE` already serializes every enqueue.
810    serialize_key = |_: &mut sqlx::SqliteConnection, _: &str, _: &str| async { Ok::<_, adk_core::AdkError>(()) },
811    |pool: &sqlx::SqlitePool| {
812        let pool = pool.clone();
813        async move {
814            crate::migration::sqlite_runner::run_sql_migrations(
815                &pool,
816                REGISTRY_TABLE,
817                SQLITE_MIGRATIONS,
818                || async { Ok(false) },
819            )
820            .await
821        }
822    }
823}
824
825#[cfg(feature = "postgres")]
826const POSTGRES_MIGRATIONS: &[(i64, &str, &str)] = &[
827    (1, "create run table", run_table!("seq BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY")),
828    (2, "add authenticated", ADD_AUTHENTICATED),
829];
830
831#[cfg(feature = "postgres")]
832sql_run_store! {
833    /// PostgreSQL-backed [`DurableRunStore`]. [`migrate`](Self::migrate) takes an
834    /// advisory lock, so concurrent processes can call it at startup.
835    ///
836    /// `claim` selects the oldest claimable run with `FOR UPDATE SKIP LOCKED` and updates
837    /// it in the same transaction, so concurrent workers in any number of processes each
838    /// take a different run without waiting on one another. Enqueues that share a
839    /// `(queue, concurrency_key)` are serialized with `pg_advisory_xact_lock`, so
840    /// `Reject` and `Interrupt` see every earlier holder.
841    ///
842    /// # Example
843    ///
844    /// ```rust,no_run
845    /// use std::time::Duration;
846    /// use adk_core::{DurableRunStore, NewRun, OnConflict};
847    /// use adk_session::PostgresRunStore;
848    /// use serde_json::json;
849    ///
850    /// # async fn example() -> adk_core::Result<()> {
851    /// let store = PostgresRunStore::new("postgres://localhost/app").await?;
852    /// store.migrate().await?;
853    /// let run = NewRun::new("default", "app", "user", "agent", json!({"text": "hi"}))
854    ///     .with_idempotency_key("webhook:evt_123")
855    ///     .with_concurrency_key("thread:42", OnConflict::Interrupt);
856    /// store.enqueue(run).await?;
857    /// let claimed = store.claim("default", "worker-1", Duration::from_secs(30)).await?;
858    /// # let _ = claimed;
859    /// # Ok(())
860    /// # }
861    /// ```
862    PostgresRunStore, sqlx::PgPool, sqlx::Postgres,
863    begin = "BEGIN",
864    lock = " FOR UPDATE OF r SKIP LOCKED",
865    serialize_key = pg_serialize_key,
866    |pool: &sqlx::PgPool| {
867        let pool = pool.clone();
868        async move {
869            crate::migration::run_pg_migrations_locked(&pool, REGISTRY_TABLE, POSTGRES_MIGRATIONS)
870                .await
871        }
872    }
873}
874
875/// Holds a transaction-scoped advisory lock on `(queue, key)` until the enqueue commits.
876#[cfg(feature = "postgres")]
877fn pg_serialize_key<'c>(
878    conn: &'c mut sqlx::PgConnection,
879    queue: &str,
880    key: &str,
881) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<()>> + Send + 'c>> {
882    // Two pairs whose names hash alike share a lock, which only serializes their enqueues.
883    let name = format!("adk_runs\u{1f}{queue}\u{1f}{key}");
884    Box::pin(async move {
885        sqlx::query("SELECT pg_advisory_xact_lock(hashtextextended($1, 0))")
886            .bind(name)
887            .execute(conn)
888            .await
889            .map_err(failed)?;
890        Ok(())
891    })
892}