adk_core/run_store.rs
1//! Durable runs: a queue of agent or workflow runs that workers claim under fenced leases.
2//!
3//! A [`DurableRunStore`] holds the durable truth about every run: its input, state,
4//! attempt count, lease, checkpoint, and outcome. Workers [`claim`](DurableRunStore::claim)
5//! runs, [`heartbeat`](DurableRunStore::heartbeat) while they work, and
6//! [`finish`](DurableRunStore::finish) them. Every worker write carries the run's lease
7//! epoch, and a store refuses a write whose epoch is not current with
8//! `run_store.stale_epoch`, so a worker that stalled and lost its run can never
9//! overwrite the work of the worker that recovered it.
10//!
11//! # Lifecycle
12//!
13//! | From | Event | To | Attempt | Epoch |
14//! |------|-------|----|---------|-------|
15//! | — | `enqueue` | `Queued` | 0 | 0 |
16//! | `Queued` | `claim` (`not_before` passed, no earlier run holds its concurrency key) | `Running` | + 1 | + 1 |
17//! | `Running` | `claim` after the lease expired (recovery) | `Running` | + 1 | + 1 |
18//! | `Running` | `wait` | `Waiting` (lease released) | — | — |
19//! | `Waiting` | `claim` once the wait's `until` passed or `wake` was called | `Running` | — | + 1 |
20//! | `Running` | `finish(Completed)` | `Completed` | — | — |
21//! | `Running` | `finish(Failed { retryable: true, backoff })` with attempts left and no cancel request | `Queued`, claimable once `backoff` has passed | — | — |
22//! | `Running` | `finish(Failed)` otherwise | `Failed` | — | — |
23//! | `Running` | `finish(Cancelled)` | `Cancelled` | — | — |
24//! | `Queued`, `Waiting` | `request_cancel` | `Cancelled` | — | — |
25//! | `Running` | `request_cancel` | `Running`, `cancel_requested` (seen by the next heartbeat) | — | — |
26//!
27//! A recovery claim of a run that already used `max_attempts` attempts fails the run
28//! with an `attempts exhausted` error instead of claiming it.
29//!
30//! A `wake` that arrives while the run is still `Running` (an approval decided before
31//! the worker parked the run) is kept in `wake_pending`, and the next `wait` parks the
32//! run as already woken, so the wake is never lost.
33//!
34//! # Double texting
35//!
36//! Runs that share a `concurrency_key` in one queue run one at a time, in enqueue
37//! order. [`OnConflict`] picks what `enqueue` does when an unfinished run holds the key:
38//!
39//! | Policy | Effect |
40//! |--------|--------|
41//! | [`Reject`](OnConflict::Reject) | Returns [`Enqueued::Rejected`] naming the oldest unfinished run |
42//! | [`Enqueue`](OnConflict::Enqueue) | Queues the run behind the unfinished ones |
43//! | [`Interrupt`](OnConflict::Interrupt) | Cancels queued and waiting runs, requests cancellation of running ones, and queues the run behind them |
44//!
45//! # Backend primitives
46//!
47//! | Operation | SQL | Redis | MongoDB | Neo4j, Firestore |
48//! |-----------|-----|-------|---------|------------------|
49//! | Idempotent `enqueue` | Unique index on `(queue, idempotency_key)`, `INSERT ... ON CONFLICT DO NOTHING` then read | Lua: check the key index, then write | Unique index, `insert_one`, read on duplicate-key error | Transaction over the key node or document |
50//! | Single-winner `claim` | `SELECT ... FOR UPDATE SKIP LOCKED` (PostgreSQL) or `BEGIN IMMEDIATE` (SQLite), then `UPDATE` | One Lua script per claim | `findOneAndUpdate` on state and epoch | Transaction that reads the candidate and writes the new epoch |
51//! | Fenced writes | `UPDATE ... WHERE run_id = $1 AND lease_epoch = $2 AND state = 'running'` | Lua compare of the epoch field | `updateOne` filtered on `leaseEpoch` | Transaction that checks the epoch |
52//! | `prune` | `DELETE ... WHERE state IN (...) AND updated_at < $1` | Sorted set of finished runs by time | `deleteMany` | Batched transactional deletes |
53
54use std::collections::HashMap;
55use std::sync::Arc;
56use std::time::Duration;
57
58use async_trait::async_trait;
59use chrono::{DateTime, Utc};
60use serde::{Deserialize, Serialize};
61use serde_json::Value;
62use tokio::sync::Mutex;
63
64use crate::lease::deadline;
65use crate::principal::ActingContext;
66use crate::{AdkError, Clock, ErrorCategory, ErrorComponent, Result, SystemClock};
67
68/// Error code returned when a worker write carries an epoch that is not current.
69pub const RUN_STALE_EPOCH_CODE: &str = "run_store.stale_epoch";
70/// Error code returned for an unknown run identifier.
71pub const RUN_NOT_FOUND_CODE: &str = "run_store.not_found";
72/// Error code returned for a [`NewRun`] that fails validation.
73pub const INVALID_RUN_CODE: &str = "run_store.invalid_run";
74
75/// Where a run is in its lifecycle.
76///
77/// # Example
78///
79/// ```rust
80/// use adk_core::run_store::RunState;
81///
82/// assert!(RunState::Completed.is_terminal());
83/// assert!(!RunState::Waiting.is_terminal());
84/// ```
85#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
86#[serde(rename_all = "camelCase")]
87#[non_exhaustive]
88pub enum RunState {
89 /// Waiting for a worker to claim it.
90 Queued,
91 /// Claimed by a worker under a lease.
92 Running,
93 /// Parked until a timer passes or `wake` is called; holds no lease.
94 Waiting,
95 /// Finished with a result.
96 Completed,
97 /// Finished with an error.
98 Failed,
99 /// Cancelled before or during execution.
100 Cancelled,
101}
102
103impl RunState {
104 /// Whether the run has finished and never changes state again.
105 pub fn is_terminal(self) -> bool {
106 matches!(self, Self::Completed | Self::Failed | Self::Cancelled)
107 }
108}
109
110/// Where a run's progress is checkpointed, so a recovering worker resumes it.
111///
112/// # Example
113///
114/// ```rust
115/// use adk_core::run_store::RunCheckpointRef;
116///
117/// let checkpoint = RunCheckpointRef::Graph { thread_id: "t1".into(), checkpoint_id: Some("c7".into()) };
118/// assert_eq!(serde_json::to_value(&checkpoint).unwrap()["kind"], "graph");
119/// ```
120#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
121#[serde(tag = "kind", rename_all = "camelCase", rename_all_fields = "camelCase")]
122#[non_exhaustive]
123pub enum RunCheckpointRef {
124 /// A session, optionally at one invocation.
125 Session {
126 /// The session identifier.
127 session_id: String,
128 /// The last invocation recorded in the session.
129 #[serde(default, skip_serializing_if = "Option::is_none")]
130 invocation_id: Option<String>,
131 },
132 /// A session whose run is parked until tool calls held for approval are decided.
133 ///
134 /// A worker records it before [`wait`](DurableRunStore::wait)ing; the claim that
135 /// follows a [`wake`](DurableRunStore::wake) resumes the same session, and the agent
136 /// dispatches each held call that has a decision.
137 AwaitingApproval {
138 /// The session identifier.
139 session_id: String,
140 /// The invocation that held the calls.
141 #[serde(default, skip_serializing_if = "Option::is_none")]
142 invocation_id: Option<String>,
143 /// The fingerprints of the held calls, the keys their decisions are recorded under.
144 fingerprints: Vec<String>,
145 /// When the hold expires; `None` waits until woken.
146 #[serde(default, skip_serializing_if = "Option::is_none")]
147 expires_at: Option<DateTime<Utc>>,
148 },
149 /// A graph thread, optionally at one checkpoint.
150 Graph {
151 /// The graph thread identifier.
152 thread_id: String,
153 /// The checkpoint within the thread.
154 #[serde(default, skip_serializing_if = "Option::is_none")]
155 checkpoint_id: Option<String>,
156 },
157}
158
159/// What `enqueue` does when an unfinished run holds the same concurrency key.
160#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
161#[serde(rename_all = "camelCase")]
162#[non_exhaustive]
163pub enum OnConflict {
164 /// Refuse the new run.
165 Reject,
166 /// Queue the new run behind the unfinished ones.
167 #[default]
168 Enqueue,
169 /// Cancel the unfinished runs and queue the new one behind them.
170 Interrupt,
171}
172
173/// A run to enqueue.
174///
175/// # Example
176///
177/// ```rust
178/// use adk_core::run_store::{NewRun, OnConflict};
179/// use serde_json::json;
180///
181/// let run = NewRun::new("default", "billing", "user-1", "invoice_agent", json!({"text": "hi"}))
182/// .with_idempotency_key("webhook:evt_123")
183/// .with_concurrency_key("thread:42", OnConflict::Interrupt)
184/// .with_max_attempts(5);
185/// assert!(run.validate().is_ok());
186/// ```
187#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
188#[serde(rename_all = "camelCase")]
189pub struct NewRun {
190 /// The queue workers claim from.
191 pub queue: String,
192 /// The application the run belongs to.
193 pub app_name: String,
194 /// The user the run belongs to.
195 pub user_id: String,
196 /// The session the run continues, if any.
197 #[serde(default, skip_serializing_if = "Option::is_none")]
198 pub session_id: Option<String>,
199 /// The agent or workflow name to run.
200 pub target: String,
201 /// The run's input.
202 pub input: Value,
203 /// Unique per queue: enqueueing an existing key returns the existing run until it is pruned.
204 #[serde(default, skip_serializing_if = "Option::is_none")]
205 pub idempotency_key: Option<String>,
206 /// Runs sharing a key in one queue run one at a time.
207 #[serde(default, skip_serializing_if = "Option::is_none")]
208 pub concurrency_key: Option<String>,
209 /// What happens when an unfinished run holds `concurrency_key`.
210 #[serde(default)]
211 pub on_conflict: OnConflict,
212 /// The run is not claimed before this time.
213 #[serde(default, skip_serializing_if = "Option::is_none")]
214 pub not_before: Option<DateTime<Utc>>,
215 /// The most attempts the run may take, counting recoveries; at least 1.
216 pub max_attempts: u32,
217 /// The agent identity the run acts under.
218 #[serde(default, skip_serializing_if = "Option::is_none")]
219 pub principal: Option<ActingContext>,
220 /// Whether `user_id` is an identity a server authenticated when the run was enqueued, so
221 /// the run executes as an authenticated user (spec 3.1 §9.2 I6). Set it with
222 /// [`with_authenticated_user`](Self::with_authenticated_user).
223 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
224 pub authenticated: bool,
225}
226
227impl NewRun {
228 /// The `max_attempts` a run gets from [`NewRun::new`].
229 pub const DEFAULT_MAX_ATTEMPTS: u32 = 3;
230
231 /// Creates a run with no keys, no delay, no principal, [`OnConflict::Enqueue`], and
232 /// [`DEFAULT_MAX_ATTEMPTS`](Self::DEFAULT_MAX_ATTEMPTS).
233 pub fn new(
234 queue: impl Into<String>,
235 app_name: impl Into<String>,
236 user_id: impl Into<String>,
237 target: impl Into<String>,
238 input: Value,
239 ) -> Self {
240 Self {
241 queue: queue.into(),
242 app_name: app_name.into(),
243 user_id: user_id.into(),
244 session_id: None,
245 target: target.into(),
246 input,
247 idempotency_key: None,
248 concurrency_key: None,
249 on_conflict: OnConflict::Enqueue,
250 not_before: None,
251 max_attempts: Self::DEFAULT_MAX_ATTEMPTS,
252 principal: None,
253 authenticated: false,
254 }
255 }
256
257 /// Sets the session the run continues.
258 pub fn with_session_id(mut self, session_id: impl Into<String>) -> Self {
259 self.session_id = Some(session_id.into());
260 self
261 }
262
263 /// Sets the idempotency key.
264 pub fn with_idempotency_key(mut self, key: impl Into<String>) -> Self {
265 self.idempotency_key = Some(key.into());
266 self
267 }
268
269 /// Sets the concurrency key and the policy applied when it is held.
270 pub fn with_concurrency_key(mut self, key: impl Into<String>, on_conflict: OnConflict) -> Self {
271 self.concurrency_key = Some(key.into());
272 self.on_conflict = on_conflict;
273 self
274 }
275
276 /// Delays the run until `at`.
277 pub fn with_not_before(mut self, at: DateTime<Utc>) -> Self {
278 self.not_before = Some(at);
279 self
280 }
281
282 /// Sets the most attempts the run may take.
283 pub fn with_max_attempts(mut self, max_attempts: u32) -> Self {
284 self.max_attempts = max_attempts;
285 self
286 }
287
288 /// Sets the agent identity the run acts under.
289 ///
290 /// A worker honours a stored principal only when it may act as the principal's agent
291 /// and the principal's subject is the run's user (or a delegation rule allows it);
292 /// see `DurableWorker` in `adk-server`.
293 pub fn with_principal(mut self, principal: ActingContext) -> Self {
294 self.principal = Some(principal);
295 self
296 }
297
298 /// Marks the run as created by a service rather than a person: it acts for its
299 /// `user_id` as a [`SubjectKind::Service`](crate::SubjectKind::Service).
300 ///
301 /// A run with no principal gets the derived principal of its target acting for the
302 /// service; a principal that names no subject gains the service as its subject; a
303 /// principal that names one is kept. Schedulers, webhook ingress, and queue ingress
304 /// mark the runs they create.
305 ///
306 /// # Example
307 ///
308 /// ```rust
309 /// use adk_core::{AgentPrincipal, NewRun, SubjectRef};
310 /// use serde_json::json;
311 ///
312 /// let run = NewRun::new("default", "ops", "nightly-close", "closer", json!({}))
313 /// .with_service_subject();
314 /// let principal = run.principal.unwrap();
315 /// assert_eq!(principal.agent, AgentPrincipal::derived("ops", "closer"));
316 /// assert_eq!(principal.on_behalf_of, Some(SubjectRef::service("nightly-close")));
317 /// ```
318 #[must_use]
319 pub fn with_service_subject(mut self) -> Self {
320 let subject = crate::SubjectRef::service(&self.user_id);
321 match &mut self.principal {
322 Some(principal) => {
323 principal.on_behalf_of.get_or_insert(subject);
324 }
325 None => {
326 self.principal = Some(
327 ActingContext::new(crate::AgentPrincipal::derived(
328 &self.app_name,
329 &self.target,
330 ))
331 .on_behalf_of(subject),
332 );
333 }
334 }
335 self
336 }
337
338 /// Marks `user_id` as an identity a server authenticated when it enqueued the run, so a
339 /// worker runs it as an authenticated user: its tools see
340 /// [`is_authenticated`](crate::ReadonlyContext::is_authenticated) answer `true`, as an
341 /// interactive run on that server does (spec 3.1 §9.2 I6). `adk-server` marks the runs and
342 /// cron jobs an authenticated caller submits; only code that authenticated the user
343 /// should call it.
344 ///
345 /// # Example
346 ///
347 /// ```rust
348 /// use adk_core::NewRun;
349 /// use serde_json::json;
350 ///
351 /// let run = NewRun::new("default", "ops", "alice", "closer", json!({})).with_authenticated_user();
352 /// assert!(run.authenticated);
353 /// ```
354 #[must_use]
355 pub fn with_authenticated_user(mut self) -> Self {
356 self.authenticated = true;
357 self
358 }
359
360 /// Checks the fields every store requires.
361 ///
362 /// # Errors
363 ///
364 /// Returns [`INVALID_RUN_CODE`] when `queue`, `app_name`, `user_id`, or `target` is
365 /// empty, a key is present but empty, or `max_attempts` is zero.
366 pub fn validate(&self) -> Result<()> {
367 let empty = [
368 ("queue", self.queue.is_empty()),
369 ("appName", self.app_name.is_empty()),
370 ("userId", self.user_id.is_empty()),
371 ("target", self.target.is_empty()),
372 ("idempotencyKey", self.idempotency_key.as_deref() == Some("")),
373 ("concurrencyKey", self.concurrency_key.as_deref() == Some("")),
374 ];
375 if let Some((field, _)) = empty.iter().find(|(_, is_empty)| *is_empty) {
376 return Err(invalid_run_error(&format!("{field} must not be empty")));
377 }
378 if self.max_attempts == 0 {
379 return Err(invalid_run_error("maxAttempts must be at least 1"));
380 }
381 Ok(())
382 }
383}
384
385/// A run as the store holds it.
386#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
387#[serde(rename_all = "camelCase")]
388pub struct RunRecord {
389 /// The store-assigned run identifier.
390 pub run_id: String,
391 /// The queue workers claim from.
392 pub queue: String,
393 /// The application the run belongs to.
394 pub app_name: String,
395 /// The user the run belongs to.
396 pub user_id: String,
397 /// The session the run continues, if any.
398 #[serde(default, skip_serializing_if = "Option::is_none")]
399 pub session_id: Option<String>,
400 /// The agent or workflow name to run.
401 pub target: String,
402 /// The run's input.
403 pub input: Value,
404 /// The idempotency key the run was enqueued with.
405 #[serde(default, skip_serializing_if = "Option::is_none")]
406 pub idempotency_key: Option<String>,
407 /// The concurrency key the run was enqueued with.
408 #[serde(default, skip_serializing_if = "Option::is_none")]
409 pub concurrency_key: Option<String>,
410 /// The double-texting policy the run was enqueued with.
411 #[serde(default)]
412 pub on_conflict: OnConflict,
413 /// Not claimed before this time; while `Waiting`, the time the wait ends.
414 #[serde(default, skip_serializing_if = "Option::is_none")]
415 pub not_before: Option<DateTime<Utc>>,
416 /// The most attempts the run may take.
417 pub max_attempts: u32,
418 /// The agent identity the run acts under.
419 #[serde(default, skip_serializing_if = "Option::is_none")]
420 pub principal: Option<ActingContext>,
421 /// Whether `user_id` was authenticated when the run was enqueued; see
422 /// [`NewRun::authenticated`].
423 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
424 pub authenticated: bool,
425 /// Where the run is in its lifecycle.
426 pub state: RunState,
427 /// Attempts started so far, counting recoveries; 0 until first claimed.
428 pub attempt: u32,
429 /// The worker holding the lease while `Running`.
430 #[serde(default, skip_serializing_if = "Option::is_none")]
431 pub lease_owner: Option<String>,
432 /// The fencing epoch of the latest claim; 0 until first claimed.
433 pub lease_epoch: u64,
434 /// When the current lease lapses.
435 #[serde(default, skip_serializing_if = "Option::is_none")]
436 pub lease_expires_at: Option<DateTime<Utc>>,
437 /// The last claim or heartbeat.
438 #[serde(default, skip_serializing_if = "Option::is_none")]
439 pub heartbeat_at: Option<DateTime<Utc>>,
440 /// Where the run's progress is checkpointed.
441 #[serde(default, skip_serializing_if = "Option::is_none")]
442 pub checkpoint: Option<RunCheckpointRef>,
443 /// Whether cancellation was requested while the run was `Running`.
444 #[serde(default)]
445 pub cancel_requested: bool,
446 /// Whether `wake` arrived while the run was `Running`, before it parked.
447 #[serde(default)]
448 pub wake_pending: bool,
449 /// The result of a completed run.
450 #[serde(default, skip_serializing_if = "Option::is_none")]
451 pub result: Option<Value>,
452 /// The error of the latest failed attempt.
453 #[serde(default, skip_serializing_if = "Option::is_none")]
454 pub error: Option<String>,
455 /// When the run was enqueued.
456 pub created_at: DateTime<Utc>,
457 /// When the run last changed; for a finished run, when it finished.
458 pub updated_at: DateTime<Utc>,
459 /// Increases by one on every change.
460 pub revision: u64,
461}
462
463impl RunRecord {
464 /// Builds the record a store writes for a newly enqueued run.
465 ///
466 /// # Example
467 ///
468 /// ```rust
469 /// use adk_core::run_store::{NewRun, RunRecord, RunState};
470 ///
471 /// let run = NewRun::new("q", "app", "user", "agent", serde_json::Value::Null);
472 /// let record = RunRecord::queued("run-1", run, chrono::Utc::now());
473 /// assert_eq!((record.state, record.attempt, record.lease_epoch, record.revision), (RunState::Queued, 0, 0, 1));
474 /// ```
475 pub fn queued(run_id: impl Into<String>, run: NewRun, now: DateTime<Utc>) -> Self {
476 Self {
477 run_id: run_id.into(),
478 queue: run.queue,
479 app_name: run.app_name,
480 user_id: run.user_id,
481 session_id: run.session_id,
482 target: run.target,
483 input: run.input,
484 idempotency_key: run.idempotency_key,
485 concurrency_key: run.concurrency_key,
486 on_conflict: run.on_conflict,
487 not_before: run.not_before,
488 max_attempts: run.max_attempts,
489 principal: run.principal,
490 authenticated: run.authenticated,
491 state: RunState::Queued,
492 attempt: 0,
493 lease_owner: None,
494 lease_epoch: 0,
495 lease_expires_at: None,
496 heartbeat_at: None,
497 checkpoint: None,
498 cancel_requested: false,
499 wake_pending: false,
500 result: None,
501 error: None,
502 created_at: now,
503 updated_at: now,
504 revision: 1,
505 }
506 }
507}
508
509/// The result of [`DurableRunStore::enqueue`].
510#[derive(Debug, Clone, PartialEq)]
511pub enum Enqueued {
512 /// A new run was created.
513 Created(RunRecord),
514 /// A run with the same idempotency key already exists in the queue.
515 Existing(RunRecord),
516 /// [`OnConflict::Reject`] refused the run because an unfinished run holds its concurrency key.
517 Rejected {
518 /// The oldest unfinished run holding the key.
519 blocking_run_id: String,
520 },
521}
522
523impl Enqueued {
524 /// Returns the created or existing record, or `None` when rejected.
525 pub fn record(&self) -> Option<&RunRecord> {
526 match self {
527 Self::Created(record) | Self::Existing(record) => Some(record),
528 Self::Rejected { .. } => None,
529 }
530 }
531}
532
533/// A run a worker claimed, with the epoch its writes must carry.
534#[derive(Debug, Clone, PartialEq)]
535pub struct ClaimedRun {
536 /// The run after the claim.
537 pub record: RunRecord,
538 /// The fencing epoch of this claim.
539 pub epoch: u64,
540}
541
542/// How a worker ends an attempt.
543#[derive(Debug, Clone, PartialEq)]
544pub enum RunOutcome {
545 /// The run finished with a result.
546 Completed(Value),
547 /// The attempt failed; `retryable` failures requeue while attempts remain.
548 Failed {
549 /// What went wrong.
550 error: String,
551 /// Whether another attempt may succeed.
552 retryable: bool,
553 /// How long a requeued run waits before its next attempt, as its `not_before`;
554 /// `None` makes it claimable at once. [`RetryBackoff::delay`] computes one.
555 backoff: Option<Duration>,
556 },
557 /// The run stopped after a cancellation request.
558 Cancelled,
559}
560
561/// Exponential backoff with jitter between the attempts of a run whose failure is retryable,
562/// so a provider that refuses with `429` or `503` is not asked again at once.
563///
564/// | Input | Wait before the next attempt |
565/// |-------|------------------------------|
566/// | Attempt `n` failed | `initial × multiplier^(n−1)`, capped at `max`, then a random part of its upper half dropped, so runs that failed together retry apart |
567/// | The error carries a retry hint (`Retry-After`) | At least the hint, still capped at `max` |
568///
569/// The defaults wait about 5, 10 and 20 seconds after the first three attempts, never
570/// longer than 10 minutes. [`none`](Self::none) retries at once.
571///
572/// # Example
573///
574/// ```rust
575/// use std::time::Duration;
576/// use adk_core::run_store::RetryBackoff;
577///
578/// let backoff = RetryBackoff::new(Duration::from_secs(2), Duration::from_secs(60));
579/// let first = backoff.delay(1, None);
580/// assert!(first >= Duration::from_secs(1) && first <= Duration::from_secs(2));
581/// // A provider that asks for 30 seconds gets them.
582/// assert!(backoff.delay(1, Some(Duration::from_secs(30))) >= Duration::from_secs(30));
583/// assert_eq!(RetryBackoff::none().delay(3, None), Duration::ZERO);
584/// ```
585#[derive(Debug, Clone, Copy, PartialEq)]
586#[non_exhaustive]
587pub struct RetryBackoff {
588 /// The wait after the first attempt fails, before jitter.
589 pub initial: Duration,
590 /// The longest wait, retry hints included.
591 pub max: Duration,
592 /// What each further attempt multiplies the wait by.
593 pub multiplier: f64,
594}
595
596impl Default for RetryBackoff {
597 fn default() -> Self {
598 Self::new(Duration::from_secs(5), Duration::from_secs(600))
599 }
600}
601
602impl RetryBackoff {
603 /// Waits from `initial`, doubling per attempt, at most `max`.
604 pub fn new(initial: Duration, max: Duration) -> Self {
605 Self { initial, max, multiplier: 2.0 }
606 }
607
608 /// No wait: a retryable failure is claimable again at once.
609 pub fn none() -> Self {
610 Self::new(Duration::ZERO, Duration::ZERO)
611 }
612
613 /// Sets what each further attempt multiplies the wait by.
614 #[must_use]
615 pub fn with_multiplier(mut self, multiplier: f64) -> Self {
616 self.multiplier = multiplier;
617 self
618 }
619
620 /// The wait before the attempt after `attempt` (1-based) failed, with the error's
621 /// `retry_after` hint when it has one.
622 pub fn delay(&self, attempt: u32, retry_after: Option<Duration>) -> Duration {
623 let exponent = i32::try_from(attempt.saturating_sub(1)).unwrap_or(i32::MAX);
624 let base = self.initial.as_secs_f64() * self.multiplier.max(1.0).powi(exponent);
625 let base = base.min(self.max.as_secs_f64());
626 let jittered = Duration::from_secs_f64(base * (0.5 + 0.5 * unit_random()));
627 jittered.max(retry_after.unwrap_or_default()).min(self.max)
628 }
629}
630
631/// A random number in `[0, 1)`, from the standard library's randomly keyed hasher.
632fn unit_random() -> f64 {
633 use std::hash::{BuildHasher, Hasher};
634 let mut hasher = std::collections::hash_map::RandomState::new().build_hasher();
635 hasher.write_u128(
636 std::time::SystemTime::now()
637 .duration_since(std::time::UNIX_EPOCH)
638 .map_or(0, |elapsed| elapsed.as_nanos()),
639 );
640 (hasher.finish() >> 11) as f64 / (1_u64 << 53) as f64
641}
642
643/// Selects runs for [`DurableRunStore::list`]. Every set field must match.
644///
645/// # Example
646///
647/// ```rust
648/// use adk_core::run_store::{RunFilter, RunState};
649///
650/// let filter = RunFilter::default().queue("default").states([RunState::Queued, RunState::Running]).limit(50);
651/// assert_eq!(filter.limit, Some(50));
652/// ```
653#[derive(Debug, Clone, Default, PartialEq, Eq)]
654#[non_exhaustive]
655pub struct RunFilter {
656 /// Only runs in this queue.
657 pub queue: Option<String>,
658 /// Only runs in one of these states; empty matches every state.
659 pub states: Vec<RunState>,
660 /// Only runs of this application.
661 pub app_name: Option<String>,
662 /// Only runs of this user.
663 pub user_id: Option<String>,
664 /// Only runs continuing this session.
665 pub session_id: Option<String>,
666 /// Only runs holding this concurrency key.
667 pub concurrency_key: Option<String>,
668 /// At most this many runs, oldest first.
669 pub limit: Option<usize>,
670}
671
672impl RunFilter {
673 /// Only runs in `queue`.
674 pub fn queue(mut self, queue: impl Into<String>) -> Self {
675 self.queue = Some(queue.into());
676 self
677 }
678
679 /// Only runs in one of `states`.
680 pub fn states(mut self, states: impl IntoIterator<Item = RunState>) -> Self {
681 self.states = states.into_iter().collect();
682 self
683 }
684
685 /// Only runs of `app_name`.
686 pub fn app_name(mut self, app_name: impl Into<String>) -> Self {
687 self.app_name = Some(app_name.into());
688 self
689 }
690
691 /// Only runs of `user_id`.
692 pub fn user_id(mut self, user_id: impl Into<String>) -> Self {
693 self.user_id = Some(user_id.into());
694 self
695 }
696
697 /// Only runs continuing `session_id`.
698 pub fn session_id(mut self, session_id: impl Into<String>) -> Self {
699 self.session_id = Some(session_id.into());
700 self
701 }
702
703 /// Only runs holding `concurrency_key`.
704 pub fn concurrency_key(mut self, key: impl Into<String>) -> Self {
705 self.concurrency_key = Some(key.into());
706 self
707 }
708
709 /// At most `limit` runs.
710 pub fn limit(mut self, limit: usize) -> Self {
711 self.limit = Some(limit);
712 self
713 }
714
715 /// Whether `record` matches every set field except `limit`.
716 pub fn matches(&self, record: &RunRecord) -> bool {
717 fn field(want: &Option<String>, have: Option<&str>) -> bool {
718 want.as_deref().is_none_or(|want| have == Some(want))
719 }
720 field(&self.queue, Some(&record.queue))
721 && (self.states.is_empty() || self.states.contains(&record.state))
722 && field(&self.app_name, Some(&record.app_name))
723 && field(&self.user_id, Some(&record.user_id))
724 && field(&self.session_id, record.session_id.as_deref())
725 && field(&self.concurrency_key, record.concurrency_key.as_deref())
726 }
727}
728
729/// The durable queue of runs.
730///
731/// Named `DurableRunStore` so it does not clash with `adk_server::background::RunStore`,
732/// the server's process-local record of background runs.
733///
734/// Every backend passes `adk_core::run_store_conformance_tests!` (feature `conformance`).
735/// The [module documentation](crate::run_store) lists the lifecycle and the primitive
736/// each backend uses for each guarantee.
737#[async_trait]
738pub trait DurableRunStore: Send + Sync {
739 /// Adds a run.
740 ///
741 /// An existing run with the same `(queue, idempotency_key)` is returned as
742 /// [`Enqueued::Existing`] before any concurrency check. Concurrent enqueues of one
743 /// key create exactly one run.
744 ///
745 /// # Errors
746 ///
747 /// Returns [`INVALID_RUN_CODE`] when [`NewRun::validate`] fails.
748 async fn enqueue(&self, run: NewRun) -> Result<Enqueued>;
749
750 /// Claims the oldest claimable run in `queue` for `worker` with a lease of `ttl`.
751 ///
752 /// Claimable, oldest enqueued first: a `Queued` run whose `not_before` passed and
753 /// that no earlier unfinished run with its concurrency key precedes; a `Waiting` run
754 /// whose wait ended or that was woken; a `Running` run whose lease expired
755 /// (recovery). The run's epoch increases by one on every claim. Concurrent claims
756 /// never return the same run at the same epoch.
757 ///
758 /// # Errors
759 ///
760 /// Returns `run_store.invalid_ttl` for a zero `ttl`.
761 async fn claim(&self, queue: &str, worker: &str, ttl: Duration) -> Result<Option<ClaimedRun>>;
762
763 /// Extends the lease to `ttl` from now and returns whether cancellation was requested.
764 ///
765 /// # Errors
766 ///
767 /// Returns [`RUN_STALE_EPOCH_CODE`] when the run is not `Running` at `epoch`, and
768 /// [`RUN_NOT_FOUND_CODE`] for an unknown run.
769 async fn heartbeat(&self, run_id: &str, epoch: u64, ttl: Duration) -> Result<bool>;
770
771 /// Records where the run's progress is checkpointed.
772 ///
773 /// # Errors
774 ///
775 /// Same as [`heartbeat`](Self::heartbeat).
776 async fn set_checkpoint(
777 &self,
778 run_id: &str,
779 epoch: u64,
780 checkpoint: RunCheckpointRef,
781 ) -> Result<()>;
782
783 /// Releases the lease and parks the run until `until` passes or [`wake`](Self::wake)
784 /// is called. `None` parks it until woken.
785 ///
786 /// # Errors
787 ///
788 /// Same as [`heartbeat`](Self::heartbeat).
789 async fn wait(&self, run_id: &str, epoch: u64, until: Option<DateTime<Utc>>) -> Result<()>;
790
791 /// Makes a `Waiting` run claimable now; records a pending wake for a `Running` run;
792 /// does nothing for a queued or finished run.
793 ///
794 /// # Errors
795 ///
796 /// Returns [`RUN_NOT_FOUND_CODE`] for an unknown run.
797 async fn wake(&self, run_id: &str) -> Result<()>;
798
799 /// Ends the attempt with `outcome` and returns the updated run.
800 ///
801 /// `Failed { retryable: true }` requeues the run while `attempt < max_attempts` and
802 /// no cancellation was requested; every other outcome is terminal.
803 ///
804 /// # Errors
805 ///
806 /// Same as [`heartbeat`](Self::heartbeat).
807 async fn finish(&self, run_id: &str, epoch: u64, outcome: RunOutcome) -> Result<RunRecord>;
808
809 /// Cancels a queued or waiting run, or flags a running one for its worker to stop.
810 /// A finished run is left unchanged.
811 ///
812 /// # Errors
813 ///
814 /// Returns [`RUN_NOT_FOUND_CODE`] for an unknown run.
815 async fn request_cancel(&self, run_id: &str) -> Result<()>;
816
817 /// Returns a run, or `None` when it does not exist or was pruned.
818 async fn get(&self, run_id: &str) -> Result<Option<RunRecord>>;
819
820 /// Returns the runs matching `filter`, oldest enqueued first.
821 async fn list(&self, filter: RunFilter) -> Result<Vec<RunRecord>>;
822
823 /// Deletes finished runs whose `updated_at` is before `finished_before` and returns
824 /// how many were deleted. Their idempotency keys become free again.
825 async fn prune(&self, finished_before: DateTime<Utc>) -> Result<u64>;
826}
827
828/// Builds the error a run store returns when a worker write carries a stale epoch.
829///
830/// # Example
831///
832/// ```rust
833/// let error = adk_core::run_store::run_stale_epoch_error("run-1", 2);
834/// assert_eq!(error.code, adk_core::run_store::RUN_STALE_EPOCH_CODE);
835/// ```
836pub fn run_stale_epoch_error(run_id: &str, epoch: u64) -> AdkError {
837 AdkError::new(
838 ErrorComponent::Agent,
839 ErrorCategory::Conflict,
840 RUN_STALE_EPOCH_CODE,
841 format!(
842 "run '{run_id}' is no longer held at epoch {epoch}; another worker recovered it or it \
843 finished, so stop work on it without writing results"
844 ),
845 )
846}
847
848/// Builds the error a run store returns for an unknown run.
849///
850/// # Example
851///
852/// ```rust
853/// let error = adk_core::run_store::run_not_found_error("run-1");
854/// assert!(error.is_not_found());
855/// ```
856pub fn run_not_found_error(run_id: &str) -> AdkError {
857 AdkError::not_found(
858 ErrorComponent::Agent,
859 RUN_NOT_FOUND_CODE,
860 format!("run store has no run '{run_id}'; it was never enqueued or was pruned"),
861 )
862}
863
864/// Builds the error a run store returns for an invalid [`NewRun`].
865///
866/// # Example
867///
868/// ```rust
869/// let error = adk_core::run_store::invalid_run_error("queue must not be empty");
870/// assert_eq!(error.code, adk_core::run_store::INVALID_RUN_CODE);
871/// ```
872pub fn invalid_run_error(reason: &str) -> AdkError {
873 AdkError::new(
874 ErrorComponent::Agent,
875 ErrorCategory::InvalidInput,
876 INVALID_RUN_CODE,
877 format!("cannot enqueue run: {reason}"),
878 )
879}
880
881#[derive(Debug)]
882struct RunEntry {
883 record: RunRecord,
884 seq: u64,
885}
886
887impl RunEntry {
888 fn order(&self) -> (DateTime<Utc>, u64) {
889 (self.record.created_at, self.seq)
890 }
891}
892
893#[derive(Debug, Default)]
894struct RunTable {
895 runs: HashMap<String, RunEntry>,
896 by_idempotency_key: HashMap<(String, String), String>,
897 next_seq: u64,
898}
899
900impl RunTable {
901 /// Unfinished runs in `queue` holding `key`, oldest first.
902 fn holders(&self, queue: &str, key: &str) -> Vec<(String, (DateTime<Utc>, u64))> {
903 let mut holders: Vec<_> = self
904 .runs
905 .values()
906 .filter(|entry| {
907 entry.record.queue == queue
908 && entry.record.concurrency_key.as_deref() == Some(key)
909 && !entry.record.state.is_terminal()
910 })
911 .map(|entry| (entry.record.run_id.clone(), entry.order()))
912 .collect();
913 holders.sort_by_key(|(_, order)| *order);
914 holders
915 }
916
917 fn fenced(&mut self, run_id: &str, epoch: u64) -> Result<&mut RunRecord> {
918 let entry = self.runs.get_mut(run_id).ok_or_else(|| run_not_found_error(run_id))?;
919 if entry.record.state != RunState::Running || entry.record.lease_epoch != epoch {
920 return Err(run_stale_epoch_error(run_id, epoch));
921 }
922 Ok(&mut entry.record)
923 }
924}
925
926fn touch(record: &mut RunRecord, now: DateTime<Utc>) {
927 record.updated_at = now;
928 record.revision += 1;
929}
930
931fn release_lease(record: &mut RunRecord) {
932 record.lease_owner = None;
933 record.lease_expires_at = None;
934}
935
936/// Process-local [`DurableRunStore`].
937///
938/// Runs do not survive a restart. Use it for tests and single-process deployments;
939/// use a durable backend when runs must outlive the process.
940///
941/// # Example
942///
943/// ```rust
944/// use std::time::Duration;
945/// use adk_core::run_store::{DurableRunStore, InMemoryRunStore, NewRun, RunOutcome, RunState};
946/// use serde_json::json;
947///
948/// # futures::executor::block_on(async {
949/// let store = InMemoryRunStore::new();
950/// store.enqueue(NewRun::new("default", "app", "user", "agent", json!({}))).await?;
951/// let claimed = store.claim("default", "worker-1", Duration::from_secs(30)).await?.unwrap();
952/// let done = store.finish(&claimed.record.run_id, claimed.epoch, RunOutcome::Completed(json!("ok"))).await?;
953/// assert_eq!(done.state, RunState::Completed);
954/// # Ok::<(), adk_core::AdkError>(())
955/// # }).unwrap();
956/// ```
957#[derive(Debug)]
958pub struct InMemoryRunStore {
959 table: Mutex<RunTable>,
960 clock: Arc<dyn Clock>,
961}
962
963impl Default for InMemoryRunStore {
964 fn default() -> Self {
965 Self::new()
966 }
967}
968
969impl InMemoryRunStore {
970 /// Creates an empty store that reads the system clock.
971 pub fn new() -> Self {
972 Self { table: Mutex::new(RunTable::default()), clock: Arc::new(SystemClock) }
973 }
974
975 /// Sets the clock that decides delays, waits, and lease expiry.
976 pub fn with_clock(mut self, clock: Arc<dyn Clock>) -> Self {
977 self.clock = clock;
978 self
979 }
980}
981
982#[async_trait]
983impl DurableRunStore for InMemoryRunStore {
984 async fn enqueue(&self, run: NewRun) -> Result<Enqueued> {
985 run.validate()?;
986 let now = self.clock.now();
987 let mut table = self.table.lock().await;
988 if let Some(key) = &run.idempotency_key
989 && let Some(existing) = table.by_idempotency_key.get(&(run.queue.clone(), key.clone()))
990 && let Some(entry) = table.runs.get(existing)
991 {
992 return Ok(Enqueued::Existing(entry.record.clone()));
993 }
994 if let Some(key) = &run.concurrency_key {
995 let holders = table.holders(&run.queue, key);
996 match run.on_conflict {
997 OnConflict::Reject => {
998 if let Some((blocking_run_id, _)) = holders.into_iter().next() {
999 return Ok(Enqueued::Rejected { blocking_run_id });
1000 }
1001 }
1002 OnConflict::Interrupt => {
1003 for (run_id, _) in holders {
1004 if let Some(entry) = table.runs.get_mut(&run_id) {
1005 let record = &mut entry.record;
1006 if record.state == RunState::Running {
1007 record.cancel_requested = true;
1008 } else {
1009 record.state = RunState::Cancelled;
1010 release_lease(record);
1011 }
1012 touch(record, now);
1013 }
1014 }
1015 }
1016 OnConflict::Enqueue => {}
1017 }
1018 }
1019 let run_id = uuid::Uuid::new_v4().to_string();
1020 if let Some(key) = &run.idempotency_key {
1021 table.by_idempotency_key.insert((run.queue.clone(), key.clone()), run_id.clone());
1022 }
1023 let record = RunRecord::queued(run_id.clone(), run, now);
1024 let seq = table.next_seq;
1025 table.next_seq += 1;
1026 table.runs.insert(run_id, RunEntry { record: record.clone(), seq });
1027 Ok(Enqueued::Created(record))
1028 }
1029
1030 async fn claim(&self, queue: &str, worker: &str, ttl: Duration) -> Result<Option<ClaimedRun>> {
1031 let now = self.clock.now();
1032 let expires_at = deadline(now, ttl, "run_store.invalid_ttl")?;
1033 let mut table = self.table.lock().await;
1034 let mut candidates: Vec<_> = table
1035 .runs
1036 .values()
1037 .filter(|entry| entry.record.queue == queue && !entry.record.state.is_terminal())
1038 .map(|entry| (entry.order(), entry.record.run_id.clone()))
1039 .collect();
1040 candidates.sort();
1041 for (order, run_id) in candidates {
1042 let Some(entry) = table.runs.get(&run_id) else { continue };
1043 let record = &entry.record;
1044 let started = match record.state {
1045 RunState::Queued => {
1046 let delayed = record.not_before.is_some_and(|at| at > now);
1047 let blocked = record.concurrency_key.as_deref().is_some_and(|key| {
1048 table.holders(queue, key).first().is_some_and(|(_, first)| *first < order)
1049 });
1050 if delayed || blocked {
1051 continue;
1052 }
1053 1
1054 }
1055 RunState::Waiting => {
1056 if record.not_before.is_none_or(|at| at > now) {
1057 continue;
1058 }
1059 0
1060 }
1061 RunState::Running => {
1062 if record.lease_expires_at.is_some_and(|at| at > now) {
1063 continue;
1064 }
1065 1
1066 }
1067 RunState::Completed | RunState::Failed | RunState::Cancelled => continue,
1068 };
1069 let Some(entry) = table.runs.get_mut(&run_id) else { continue };
1070 let record = &mut entry.record;
1071 if record.state == RunState::Running && record.attempt >= record.max_attempts {
1072 record.state = RunState::Failed;
1073 record.error = Some(format!(
1074 "attempts exhausted: the lease of attempt {} of {} expired",
1075 record.attempt, record.max_attempts
1076 ));
1077 release_lease(record);
1078 touch(record, now);
1079 continue;
1080 }
1081 record.state = RunState::Running;
1082 record.attempt += started;
1083 record.lease_epoch += 1;
1084 record.lease_owner = Some(worker.to_string());
1085 record.lease_expires_at = Some(expires_at);
1086 record.heartbeat_at = Some(now);
1087 record.not_before = None;
1088 touch(record, now);
1089 return Ok(Some(ClaimedRun { epoch: record.lease_epoch, record: record.clone() }));
1090 }
1091 Ok(None)
1092 }
1093
1094 async fn heartbeat(&self, run_id: &str, epoch: u64, ttl: Duration) -> Result<bool> {
1095 let now = self.clock.now();
1096 let expires_at = deadline(now, ttl, "run_store.invalid_ttl")?;
1097 let mut table = self.table.lock().await;
1098 let record = table.fenced(run_id, epoch)?;
1099 record.lease_expires_at = Some(expires_at);
1100 record.heartbeat_at = Some(now);
1101 touch(record, now);
1102 Ok(record.cancel_requested)
1103 }
1104
1105 async fn set_checkpoint(
1106 &self,
1107 run_id: &str,
1108 epoch: u64,
1109 checkpoint: RunCheckpointRef,
1110 ) -> Result<()> {
1111 let now = self.clock.now();
1112 let mut table = self.table.lock().await;
1113 let record = table.fenced(run_id, epoch)?;
1114 record.checkpoint = Some(checkpoint);
1115 touch(record, now);
1116 Ok(())
1117 }
1118
1119 async fn wait(&self, run_id: &str, epoch: u64, until: Option<DateTime<Utc>>) -> Result<()> {
1120 let now = self.clock.now();
1121 let mut table = self.table.lock().await;
1122 let record = table.fenced(run_id, epoch)?;
1123 record.state = RunState::Waiting;
1124 record.not_before = if record.wake_pending { Some(now) } else { until };
1125 record.wake_pending = false;
1126 release_lease(record);
1127 touch(record, now);
1128 Ok(())
1129 }
1130
1131 async fn wake(&self, run_id: &str) -> Result<()> {
1132 let now = self.clock.now();
1133 let mut table = self.table.lock().await;
1134 let entry = table.runs.get_mut(run_id).ok_or_else(|| run_not_found_error(run_id))?;
1135 let record = &mut entry.record;
1136 match record.state {
1137 RunState::Waiting => record.not_before = Some(now),
1138 RunState::Running => record.wake_pending = true,
1139 RunState::Queued | RunState::Completed | RunState::Failed | RunState::Cancelled => {
1140 return Ok(());
1141 }
1142 }
1143 touch(record, now);
1144 Ok(())
1145 }
1146
1147 async fn finish(&self, run_id: &str, epoch: u64, outcome: RunOutcome) -> Result<RunRecord> {
1148 let now = self.clock.now();
1149 let mut table = self.table.lock().await;
1150 let record = table.fenced(run_id, epoch)?;
1151 match outcome {
1152 RunOutcome::Completed(result) => {
1153 record.state = RunState::Completed;
1154 record.result = Some(result);
1155 }
1156 RunOutcome::Failed { error, retryable, backoff } => {
1157 let retry =
1158 retryable && record.attempt < record.max_attempts && !record.cancel_requested;
1159 record.state = if retry { RunState::Queued } else { RunState::Failed };
1160 if retry {
1161 record.not_before = backoff.map(|backoff| now + backoff);
1162 }
1163 record.error = Some(error);
1164 }
1165 RunOutcome::Cancelled => record.state = RunState::Cancelled,
1166 }
1167 record.wake_pending = false;
1168 release_lease(record);
1169 touch(record, now);
1170 Ok(record.clone())
1171 }
1172
1173 async fn request_cancel(&self, run_id: &str) -> Result<()> {
1174 let now = self.clock.now();
1175 let mut table = self.table.lock().await;
1176 let entry = table.runs.get_mut(run_id).ok_or_else(|| run_not_found_error(run_id))?;
1177 let record = &mut entry.record;
1178 match record.state {
1179 RunState::Queued | RunState::Waiting => {
1180 record.state = RunState::Cancelled;
1181 release_lease(record);
1182 }
1183 RunState::Running => record.cancel_requested = true,
1184 RunState::Completed | RunState::Failed | RunState::Cancelled => return Ok(()),
1185 }
1186 touch(record, now);
1187 Ok(())
1188 }
1189
1190 async fn get(&self, run_id: &str) -> Result<Option<RunRecord>> {
1191 Ok(self.table.lock().await.runs.get(run_id).map(|entry| entry.record.clone()))
1192 }
1193
1194 async fn list(&self, filter: RunFilter) -> Result<Vec<RunRecord>> {
1195 let table = self.table.lock().await;
1196 let mut matching: Vec<_> =
1197 table.runs.values().filter(|entry| filter.matches(&entry.record)).collect();
1198 matching.sort_by_key(|entry| entry.order());
1199 let limit = filter.limit.unwrap_or(usize::MAX);
1200 Ok(matching.into_iter().take(limit).map(|entry| entry.record.clone()).collect())
1201 }
1202
1203 async fn prune(&self, finished_before: DateTime<Utc>) -> Result<u64> {
1204 let mut table = self.table.lock().await;
1205 let pruned: Vec<_> = table
1206 .runs
1207 .values()
1208 .filter(|entry| {
1209 entry.record.state.is_terminal() && entry.record.updated_at < finished_before
1210 })
1211 .map(|entry| entry.record.run_id.clone())
1212 .collect();
1213 for run_id in &pruned {
1214 if let Some(entry) = table.runs.remove(run_id)
1215 && let Some(key) = entry.record.idempotency_key
1216 {
1217 table.by_idempotency_key.remove(&(entry.record.queue, key));
1218 }
1219 }
1220 Ok(pruned.len() as u64)
1221 }
1222}