use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;
use async_trait::async_trait;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use tokio::sync::Mutex;
use crate::lease::deadline;
use crate::principal::ActingContext;
use crate::{AdkError, Clock, ErrorCategory, ErrorComponent, Result, SystemClock};
pub const RUN_STALE_EPOCH_CODE: &str = "run_store.stale_epoch";
pub const RUN_NOT_FOUND_CODE: &str = "run_store.not_found";
pub const INVALID_RUN_CODE: &str = "run_store.invalid_run";
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub enum RunState {
Queued,
Running,
Waiting,
Completed,
Failed,
Cancelled,
}
impl RunState {
pub fn is_terminal(self) -> bool {
matches!(self, Self::Completed | Self::Failed | Self::Cancelled)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "camelCase", rename_all_fields = "camelCase")]
#[non_exhaustive]
pub enum RunCheckpointRef {
Session {
session_id: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
invocation_id: Option<String>,
},
AwaitingApproval {
session_id: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
invocation_id: Option<String>,
fingerprints: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
expires_at: Option<DateTime<Utc>>,
},
Graph {
thread_id: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
checkpoint_id: Option<String>,
},
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub enum OnConflict {
Reject,
#[default]
Enqueue,
Interrupt,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NewRun {
pub queue: String,
pub app_name: String,
pub user_id: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub session_id: Option<String>,
pub target: String,
pub input: Value,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub idempotency_key: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub concurrency_key: Option<String>,
#[serde(default)]
pub on_conflict: OnConflict,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub not_before: Option<DateTime<Utc>>,
pub max_attempts: u32,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub principal: Option<ActingContext>,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub authenticated: bool,
}
impl NewRun {
pub const DEFAULT_MAX_ATTEMPTS: u32 = 3;
pub fn new(
queue: impl Into<String>,
app_name: impl Into<String>,
user_id: impl Into<String>,
target: impl Into<String>,
input: Value,
) -> Self {
Self {
queue: queue.into(),
app_name: app_name.into(),
user_id: user_id.into(),
session_id: None,
target: target.into(),
input,
idempotency_key: None,
concurrency_key: None,
on_conflict: OnConflict::Enqueue,
not_before: None,
max_attempts: Self::DEFAULT_MAX_ATTEMPTS,
principal: None,
authenticated: false,
}
}
pub fn with_session_id(mut self, session_id: impl Into<String>) -> Self {
self.session_id = Some(session_id.into());
self
}
pub fn with_idempotency_key(mut self, key: impl Into<String>) -> Self {
self.idempotency_key = Some(key.into());
self
}
pub fn with_concurrency_key(mut self, key: impl Into<String>, on_conflict: OnConflict) -> Self {
self.concurrency_key = Some(key.into());
self.on_conflict = on_conflict;
self
}
pub fn with_not_before(mut self, at: DateTime<Utc>) -> Self {
self.not_before = Some(at);
self
}
pub fn with_max_attempts(mut self, max_attempts: u32) -> Self {
self.max_attempts = max_attempts;
self
}
pub fn with_principal(mut self, principal: ActingContext) -> Self {
self.principal = Some(principal);
self
}
#[must_use]
pub fn with_service_subject(mut self) -> Self {
let subject = crate::SubjectRef::service(&self.user_id);
match &mut self.principal {
Some(principal) => {
principal.on_behalf_of.get_or_insert(subject);
}
None => {
self.principal = Some(
ActingContext::new(crate::AgentPrincipal::derived(
&self.app_name,
&self.target,
))
.on_behalf_of(subject),
);
}
}
self
}
#[must_use]
pub fn with_authenticated_user(mut self) -> Self {
self.authenticated = true;
self
}
pub fn validate(&self) -> Result<()> {
let empty = [
("queue", self.queue.is_empty()),
("appName", self.app_name.is_empty()),
("userId", self.user_id.is_empty()),
("target", self.target.is_empty()),
("idempotencyKey", self.idempotency_key.as_deref() == Some("")),
("concurrencyKey", self.concurrency_key.as_deref() == Some("")),
];
if let Some((field, _)) = empty.iter().find(|(_, is_empty)| *is_empty) {
return Err(invalid_run_error(&format!("{field} must not be empty")));
}
if self.max_attempts == 0 {
return Err(invalid_run_error("maxAttempts must be at least 1"));
}
Ok(())
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RunRecord {
pub run_id: String,
pub queue: String,
pub app_name: String,
pub user_id: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub session_id: Option<String>,
pub target: String,
pub input: Value,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub idempotency_key: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub concurrency_key: Option<String>,
#[serde(default)]
pub on_conflict: OnConflict,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub not_before: Option<DateTime<Utc>>,
pub max_attempts: u32,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub principal: Option<ActingContext>,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub authenticated: bool,
pub state: RunState,
pub attempt: u32,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub lease_owner: Option<String>,
pub lease_epoch: u64,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub lease_expires_at: Option<DateTime<Utc>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub heartbeat_at: Option<DateTime<Utc>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub checkpoint: Option<RunCheckpointRef>,
#[serde(default)]
pub cancel_requested: bool,
#[serde(default)]
pub wake_pending: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub result: Option<Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub error: Option<String>,
pub created_at: DateTime<Utc>,
pub updated_at: DateTime<Utc>,
pub revision: u64,
}
impl RunRecord {
pub fn queued(run_id: impl Into<String>, run: NewRun, now: DateTime<Utc>) -> Self {
Self {
run_id: run_id.into(),
queue: run.queue,
app_name: run.app_name,
user_id: run.user_id,
session_id: run.session_id,
target: run.target,
input: run.input,
idempotency_key: run.idempotency_key,
concurrency_key: run.concurrency_key,
on_conflict: run.on_conflict,
not_before: run.not_before,
max_attempts: run.max_attempts,
principal: run.principal,
authenticated: run.authenticated,
state: RunState::Queued,
attempt: 0,
lease_owner: None,
lease_epoch: 0,
lease_expires_at: None,
heartbeat_at: None,
checkpoint: None,
cancel_requested: false,
wake_pending: false,
result: None,
error: None,
created_at: now,
updated_at: now,
revision: 1,
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum Enqueued {
Created(RunRecord),
Existing(RunRecord),
Rejected {
blocking_run_id: String,
},
}
impl Enqueued {
pub fn record(&self) -> Option<&RunRecord> {
match self {
Self::Created(record) | Self::Existing(record) => Some(record),
Self::Rejected { .. } => None,
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct ClaimedRun {
pub record: RunRecord,
pub epoch: u64,
}
#[derive(Debug, Clone, PartialEq)]
pub enum RunOutcome {
Completed(Value),
Failed {
error: String,
retryable: bool,
backoff: Option<Duration>,
},
Cancelled,
}
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub struct RetryBackoff {
pub initial: Duration,
pub max: Duration,
pub multiplier: f64,
}
impl Default for RetryBackoff {
fn default() -> Self {
Self::new(Duration::from_secs(5), Duration::from_secs(600))
}
}
impl RetryBackoff {
pub fn new(initial: Duration, max: Duration) -> Self {
Self { initial, max, multiplier: 2.0 }
}
pub fn none() -> Self {
Self::new(Duration::ZERO, Duration::ZERO)
}
#[must_use]
pub fn with_multiplier(mut self, multiplier: f64) -> Self {
self.multiplier = multiplier;
self
}
pub fn delay(&self, attempt: u32, retry_after: Option<Duration>) -> Duration {
let exponent = i32::try_from(attempt.saturating_sub(1)).unwrap_or(i32::MAX);
let base = self.initial.as_secs_f64() * self.multiplier.max(1.0).powi(exponent);
let base = base.min(self.max.as_secs_f64());
let jittered = Duration::from_secs_f64(base * (0.5 + 0.5 * unit_random()));
jittered.max(retry_after.unwrap_or_default()).min(self.max)
}
}
fn unit_random() -> f64 {
use std::hash::{BuildHasher, Hasher};
let mut hasher = std::collections::hash_map::RandomState::new().build_hasher();
hasher.write_u128(
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |elapsed| elapsed.as_nanos()),
);
(hasher.finish() >> 11) as f64 / (1_u64 << 53) as f64
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct RunFilter {
pub queue: Option<String>,
pub states: Vec<RunState>,
pub app_name: Option<String>,
pub user_id: Option<String>,
pub session_id: Option<String>,
pub concurrency_key: Option<String>,
pub limit: Option<usize>,
}
impl RunFilter {
pub fn queue(mut self, queue: impl Into<String>) -> Self {
self.queue = Some(queue.into());
self
}
pub fn states(mut self, states: impl IntoIterator<Item = RunState>) -> Self {
self.states = states.into_iter().collect();
self
}
pub fn app_name(mut self, app_name: impl Into<String>) -> Self {
self.app_name = Some(app_name.into());
self
}
pub fn user_id(mut self, user_id: impl Into<String>) -> Self {
self.user_id = Some(user_id.into());
self
}
pub fn session_id(mut self, session_id: impl Into<String>) -> Self {
self.session_id = Some(session_id.into());
self
}
pub fn concurrency_key(mut self, key: impl Into<String>) -> Self {
self.concurrency_key = Some(key.into());
self
}
pub fn limit(mut self, limit: usize) -> Self {
self.limit = Some(limit);
self
}
pub fn matches(&self, record: &RunRecord) -> bool {
fn field(want: &Option<String>, have: Option<&str>) -> bool {
want.as_deref().is_none_or(|want| have == Some(want))
}
field(&self.queue, Some(&record.queue))
&& (self.states.is_empty() || self.states.contains(&record.state))
&& field(&self.app_name, Some(&record.app_name))
&& field(&self.user_id, Some(&record.user_id))
&& field(&self.session_id, record.session_id.as_deref())
&& field(&self.concurrency_key, record.concurrency_key.as_deref())
}
}
#[async_trait]
pub trait DurableRunStore: Send + Sync {
async fn enqueue(&self, run: NewRun) -> Result<Enqueued>;
async fn claim(&self, queue: &str, worker: &str, ttl: Duration) -> Result<Option<ClaimedRun>>;
async fn heartbeat(&self, run_id: &str, epoch: u64, ttl: Duration) -> Result<bool>;
async fn set_checkpoint(
&self,
run_id: &str,
epoch: u64,
checkpoint: RunCheckpointRef,
) -> Result<()>;
async fn wait(&self, run_id: &str, epoch: u64, until: Option<DateTime<Utc>>) -> Result<()>;
async fn wake(&self, run_id: &str) -> Result<()>;
async fn finish(&self, run_id: &str, epoch: u64, outcome: RunOutcome) -> Result<RunRecord>;
async fn request_cancel(&self, run_id: &str) -> Result<()>;
async fn get(&self, run_id: &str) -> Result<Option<RunRecord>>;
async fn list(&self, filter: RunFilter) -> Result<Vec<RunRecord>>;
async fn prune(&self, finished_before: DateTime<Utc>) -> Result<u64>;
}
pub fn run_stale_epoch_error(run_id: &str, epoch: u64) -> AdkError {
AdkError::new(
ErrorComponent::Agent,
ErrorCategory::Conflict,
RUN_STALE_EPOCH_CODE,
format!(
"run '{run_id}' is no longer held at epoch {epoch}; another worker recovered it or it \
finished, so stop work on it without writing results"
),
)
}
pub fn run_not_found_error(run_id: &str) -> AdkError {
AdkError::not_found(
ErrorComponent::Agent,
RUN_NOT_FOUND_CODE,
format!("run store has no run '{run_id}'; it was never enqueued or was pruned"),
)
}
pub fn invalid_run_error(reason: &str) -> AdkError {
AdkError::new(
ErrorComponent::Agent,
ErrorCategory::InvalidInput,
INVALID_RUN_CODE,
format!("cannot enqueue run: {reason}"),
)
}
#[derive(Debug)]
struct RunEntry {
record: RunRecord,
seq: u64,
}
impl RunEntry {
fn order(&self) -> (DateTime<Utc>, u64) {
(self.record.created_at, self.seq)
}
}
#[derive(Debug, Default)]
struct RunTable {
runs: HashMap<String, RunEntry>,
by_idempotency_key: HashMap<(String, String), String>,
next_seq: u64,
}
impl RunTable {
fn holders(&self, queue: &str, key: &str) -> Vec<(String, (DateTime<Utc>, u64))> {
let mut holders: Vec<_> = self
.runs
.values()
.filter(|entry| {
entry.record.queue == queue
&& entry.record.concurrency_key.as_deref() == Some(key)
&& !entry.record.state.is_terminal()
})
.map(|entry| (entry.record.run_id.clone(), entry.order()))
.collect();
holders.sort_by_key(|(_, order)| *order);
holders
}
fn fenced(&mut self, run_id: &str, epoch: u64) -> Result<&mut RunRecord> {
let entry = self.runs.get_mut(run_id).ok_or_else(|| run_not_found_error(run_id))?;
if entry.record.state != RunState::Running || entry.record.lease_epoch != epoch {
return Err(run_stale_epoch_error(run_id, epoch));
}
Ok(&mut entry.record)
}
}
fn touch(record: &mut RunRecord, now: DateTime<Utc>) {
record.updated_at = now;
record.revision += 1;
}
fn release_lease(record: &mut RunRecord) {
record.lease_owner = None;
record.lease_expires_at = None;
}
#[derive(Debug)]
pub struct InMemoryRunStore {
table: Mutex<RunTable>,
clock: Arc<dyn Clock>,
}
impl Default for InMemoryRunStore {
fn default() -> Self {
Self::new()
}
}
impl InMemoryRunStore {
pub fn new() -> Self {
Self { table: Mutex::new(RunTable::default()), clock: Arc::new(SystemClock) }
}
pub fn with_clock(mut self, clock: Arc<dyn Clock>) -> Self {
self.clock = clock;
self
}
}
#[async_trait]
impl DurableRunStore for InMemoryRunStore {
async fn enqueue(&self, run: NewRun) -> Result<Enqueued> {
run.validate()?;
let now = self.clock.now();
let mut table = self.table.lock().await;
if let Some(key) = &run.idempotency_key
&& let Some(existing) = table.by_idempotency_key.get(&(run.queue.clone(), key.clone()))
&& let Some(entry) = table.runs.get(existing)
{
return Ok(Enqueued::Existing(entry.record.clone()));
}
if let Some(key) = &run.concurrency_key {
let holders = table.holders(&run.queue, key);
match run.on_conflict {
OnConflict::Reject => {
if let Some((blocking_run_id, _)) = holders.into_iter().next() {
return Ok(Enqueued::Rejected { blocking_run_id });
}
}
OnConflict::Interrupt => {
for (run_id, _) in holders {
if let Some(entry) = table.runs.get_mut(&run_id) {
let record = &mut entry.record;
if record.state == RunState::Running {
record.cancel_requested = true;
} else {
record.state = RunState::Cancelled;
release_lease(record);
}
touch(record, now);
}
}
}
OnConflict::Enqueue => {}
}
}
let run_id = uuid::Uuid::new_v4().to_string();
if let Some(key) = &run.idempotency_key {
table.by_idempotency_key.insert((run.queue.clone(), key.clone()), run_id.clone());
}
let record = RunRecord::queued(run_id.clone(), run, now);
let seq = table.next_seq;
table.next_seq += 1;
table.runs.insert(run_id, RunEntry { record: record.clone(), seq });
Ok(Enqueued::Created(record))
}
async fn claim(&self, queue: &str, worker: &str, ttl: Duration) -> Result<Option<ClaimedRun>> {
let now = self.clock.now();
let expires_at = deadline(now, ttl, "run_store.invalid_ttl")?;
let mut table = self.table.lock().await;
let mut candidates: Vec<_> = table
.runs
.values()
.filter(|entry| entry.record.queue == queue && !entry.record.state.is_terminal())
.map(|entry| (entry.order(), entry.record.run_id.clone()))
.collect();
candidates.sort();
for (order, run_id) in candidates {
let Some(entry) = table.runs.get(&run_id) else { continue };
let record = &entry.record;
let started = match record.state {
RunState::Queued => {
let delayed = record.not_before.is_some_and(|at| at > now);
let blocked = record.concurrency_key.as_deref().is_some_and(|key| {
table.holders(queue, key).first().is_some_and(|(_, first)| *first < order)
});
if delayed || blocked {
continue;
}
1
}
RunState::Waiting => {
if record.not_before.is_none_or(|at| at > now) {
continue;
}
0
}
RunState::Running => {
if record.lease_expires_at.is_some_and(|at| at > now) {
continue;
}
1
}
RunState::Completed | RunState::Failed | RunState::Cancelled => continue,
};
let Some(entry) = table.runs.get_mut(&run_id) else { continue };
let record = &mut entry.record;
if record.state == RunState::Running && record.attempt >= record.max_attempts {
record.state = RunState::Failed;
record.error = Some(format!(
"attempts exhausted: the lease of attempt {} of {} expired",
record.attempt, record.max_attempts
));
release_lease(record);
touch(record, now);
continue;
}
record.state = RunState::Running;
record.attempt += started;
record.lease_epoch += 1;
record.lease_owner = Some(worker.to_string());
record.lease_expires_at = Some(expires_at);
record.heartbeat_at = Some(now);
record.not_before = None;
touch(record, now);
return Ok(Some(ClaimedRun { epoch: record.lease_epoch, record: record.clone() }));
}
Ok(None)
}
async fn heartbeat(&self, run_id: &str, epoch: u64, ttl: Duration) -> Result<bool> {
let now = self.clock.now();
let expires_at = deadline(now, ttl, "run_store.invalid_ttl")?;
let mut table = self.table.lock().await;
let record = table.fenced(run_id, epoch)?;
record.lease_expires_at = Some(expires_at);
record.heartbeat_at = Some(now);
touch(record, now);
Ok(record.cancel_requested)
}
async fn set_checkpoint(
&self,
run_id: &str,
epoch: u64,
checkpoint: RunCheckpointRef,
) -> Result<()> {
let now = self.clock.now();
let mut table = self.table.lock().await;
let record = table.fenced(run_id, epoch)?;
record.checkpoint = Some(checkpoint);
touch(record, now);
Ok(())
}
async fn wait(&self, run_id: &str, epoch: u64, until: Option<DateTime<Utc>>) -> Result<()> {
let now = self.clock.now();
let mut table = self.table.lock().await;
let record = table.fenced(run_id, epoch)?;
record.state = RunState::Waiting;
record.not_before = if record.wake_pending { Some(now) } else { until };
record.wake_pending = false;
release_lease(record);
touch(record, now);
Ok(())
}
async fn wake(&self, run_id: &str) -> Result<()> {
let now = self.clock.now();
let mut table = self.table.lock().await;
let entry = table.runs.get_mut(run_id).ok_or_else(|| run_not_found_error(run_id))?;
let record = &mut entry.record;
match record.state {
RunState::Waiting => record.not_before = Some(now),
RunState::Running => record.wake_pending = true,
RunState::Queued | RunState::Completed | RunState::Failed | RunState::Cancelled => {
return Ok(());
}
}
touch(record, now);
Ok(())
}
async fn finish(&self, run_id: &str, epoch: u64, outcome: RunOutcome) -> Result<RunRecord> {
let now = self.clock.now();
let mut table = self.table.lock().await;
let record = table.fenced(run_id, epoch)?;
match outcome {
RunOutcome::Completed(result) => {
record.state = RunState::Completed;
record.result = Some(result);
}
RunOutcome::Failed { error, retryable, backoff } => {
let retry =
retryable && record.attempt < record.max_attempts && !record.cancel_requested;
record.state = if retry { RunState::Queued } else { RunState::Failed };
if retry {
record.not_before = backoff.map(|backoff| now + backoff);
}
record.error = Some(error);
}
RunOutcome::Cancelled => record.state = RunState::Cancelled,
}
record.wake_pending = false;
release_lease(record);
touch(record, now);
Ok(record.clone())
}
async fn request_cancel(&self, run_id: &str) -> Result<()> {
let now = self.clock.now();
let mut table = self.table.lock().await;
let entry = table.runs.get_mut(run_id).ok_or_else(|| run_not_found_error(run_id))?;
let record = &mut entry.record;
match record.state {
RunState::Queued | RunState::Waiting => {
record.state = RunState::Cancelled;
release_lease(record);
}
RunState::Running => record.cancel_requested = true,
RunState::Completed | RunState::Failed | RunState::Cancelled => return Ok(()),
}
touch(record, now);
Ok(())
}
async fn get(&self, run_id: &str) -> Result<Option<RunRecord>> {
Ok(self.table.lock().await.runs.get(run_id).map(|entry| entry.record.clone()))
}
async fn list(&self, filter: RunFilter) -> Result<Vec<RunRecord>> {
let table = self.table.lock().await;
let mut matching: Vec<_> =
table.runs.values().filter(|entry| filter.matches(&entry.record)).collect();
matching.sort_by_key(|entry| entry.order());
let limit = filter.limit.unwrap_or(usize::MAX);
Ok(matching.into_iter().take(limit).map(|entry| entry.record.clone()).collect())
}
async fn prune(&self, finished_before: DateTime<Utc>) -> Result<u64> {
let mut table = self.table.lock().await;
let pruned: Vec<_> = table
.runs
.values()
.filter(|entry| {
entry.record.state.is_terminal() && entry.record.updated_at < finished_before
})
.map(|entry| entry.record.run_id.clone())
.collect();
for run_id in &pruned {
if let Some(entry) = table.runs.remove(run_id)
&& let Some(key) = entry.record.idempotency_key
{
table.by_idempotency_key.remove(&(entry.record.queue, key));
}
}
Ok(pruned.len() as u64)
}
}