Skip to main content

adk_session/
redis_runtime.rs

1//! Redis-backed [`LeaseStore`](adk_core::LeaseStore), [`DurableRunStore`](adk_core::DurableRunStore), [`ScheduleStore`](adk_core::ScheduleStore), and
2//! [`GovernanceStateStore`](adk_core::GovernanceStateStore).
3//!
4//! Every conditional change runs as one Lua script, which Redis executes atomically, so
5//! any number of processes sharing a server see one lease winner, one claim per run and
6//! epoch, one schedule advance per revision, and one governance change per epoch. Keys
7//! carry no expiry: lease and claim deadlines are timestamps compared inside the
8//! scripts against the caller's clock, so the durable truth never depends on Redis
9//! evicting or expiring a key.
10//!
11//! # Key layout
12//!
13//! | Key | Type | Contents |
14//! |-----|------|----------|
15//! | `adk:lease:{<resource>}` | Hash | `owner`, `epoch`, `expires` (µs), `released` |
16//! | `{adk:runs}:run:<run id>` | Hash | One run: the enqueued record as JSON (`base`) plus its mutable fields (`state`, `attempt`, `lease_epoch`, `lease_owner`, `lease_expires`, `not_before`, `checkpoint`, `result`, `error`, `revision`, ...) |
17//! | `{adk:runs}:seq` | String | The enqueue counter that orders runs |
18//! | `{adk:runs}:ready:<queue>` | Sorted set | Runs that may be claimable now, scored by enqueue order |
19//! | `{adk:runs}:timers:<queue>` | Sorted set | Runs that become claimable at a time (delays, waits, lease expiry), scored by that time in µs |
20//! | `{adk:runs}:holders:<queue>:<key>` | Sorted set | Unfinished runs holding a concurrency key, by enqueue order |
21//! | `{adk:runs}:idem:<queue>` | Hash | Idempotency key → run id |
22//! | `{adk:runs}:queue:<queue>`, `{adk:runs}:all` | Sorted set | Every run of a queue, and every run, by enqueue order |
23//! | `{adk:runs}:finished` | Sorted set | Finished runs by finish time, for `prune` |
24//! | `{adk:schedules}:defs`, `{adk:schedules}:revs` | Hash | Schedule id → JSON definition, and → revision |
25//! | `{adk:schedules}:due` | Sorted set | Unpaused schedules with a next fire time, scored by it in µs |
26//! | `{adk:governance}:states`, `{adk:governance}:epochs` | Hash | Scope key → JSON state, and → epoch |
27//!
28//! Queue, key, and resource segments are hex-encoded, so no identifier can spill into the
29//! next segment or move a key's hash slot. Each store keeps its keys under one hash tag,
30//! so the scripts that compute key names from stored fields touch a single Redis Cluster
31//! slot.
32//!
33//! # Atomicity
34//!
35//! | Operation | Script |
36//! |-----------|--------|
37//! | Lease `acquire`, `renew`, `release` | Reads the resource hash, compares owner, epoch, expiry, and the released flag, then writes |
38//! | Run `enqueue` | Checks the idempotency index, reads the key holders, applies `Reject` or `Interrupt`, then writes the run and its indexes |
39//! | Run `claim` | Moves due timers to the ready set, walks it oldest first re-checking each run's state and time, skips key-blocked runs, fails exhausted recoveries, then claims one run at the next epoch |
40//! | `heartbeat`, `set_checkpoint`, `wait`, `finish` | Compares the state and `lease_epoch` before writing (fencing) |
41//! | `wake`, `request_cancel` | Reads the state and writes the transition |
42//! | `prune` | Deletes finished runs older than the cut-off in batches, with their index entries |
43//! | Schedule `upsert`, `set_paused`, `advance` | Compare-and-swap on the stored revision |
44//! | Governance `set` | Compare-and-swap on the stored epoch |
45//!
46//! The ready set re-checks every candidate against the caller's clock, so replicas whose
47//! clocks disagree never claim a run early. Timestamps are stored as integer
48//! microseconds, compared in Lua as double-precision numbers, which is exact for dates
49//! before the year 2255.
50
51use std::collections::HashMap;
52use std::sync::{Arc, LazyLock};
53use std::time::Duration;
54
55use adk_core::governance_state::{
56    GovernanceScope, GovernanceState, GovernanceStateStore, governance_conflict_error,
57};
58use adk_core::lease::{Lease, LeaseStore, lease_stale_epoch_error};
59use adk_core::principal::SubjectRef;
60use adk_core::run_store::{
61    ClaimedRun, DurableRunStore, Enqueued, NewRun, OnConflict, RunFilter, RunOutcome, RunRecord,
62    RunState, run_not_found_error, run_stale_epoch_error,
63};
64use adk_core::schedule::{Schedule, ScheduleStore, schedule_not_found_error};
65use adk_core::{AdkError, Clock, Result, SystemClock};
66use async_trait::async_trait;
67use chrono::{DateTime, Utc};
68use fred::prelude::*;
69
70use crate::durable_common::{
71    GOVERNANCE_STORAGE, LEASE_STORAGE, RUN_STORAGE, SCHEDULE_STORAGE, deadline, hex,
72    same_definition, state_name, storage_error, stored_now,
73};
74use crate::redis_stores::{connect, load_scripts};
75
76/// Attempts at a compare-and-swap that loses to concurrent writers before giving up.
77const CAS_ATTEMPTS: usize = 64;
78
79/// Runs deleted per `prune` script call.
80const PRUNE_BATCH: usize = 500;
81
82fn micros(at: DateTime<Utc>) -> String {
83    at.timestamp_micros().to_string()
84}
85
86fn from_micros(text: &str, code: &'static str, field: &str) -> Result<DateTime<Utc>> {
87    text.parse::<i64>()
88        .ok()
89        .and_then(DateTime::from_timestamp_micros)
90        .ok_or_else(|| storage_error(code, format!("stored field '{field}' is corrupt: '{text}'")))
91}
92
93/// Flattens a script reply of scalars into strings.
94fn strings(value: Value, code: &'static str) -> Result<Vec<String>> {
95    value
96        .into_array()
97        .into_iter()
98        .map(|item| {
99            item.into_string()
100                .ok_or_else(|| storage_error(code, "redis script returned a non-text value"))
101        })
102        .collect()
103}
104
105/// Splits a `{status, payload}` script reply.
106fn status_reply(value: Value, code: &'static str) -> Result<(String, Value)> {
107    let mut items = value.into_array().into_iter();
108    let status = items
109        .next()
110        .and_then(Value::into_string)
111        .ok_or_else(|| storage_error(code, "redis script returned no status"))?;
112    Ok((status, items.next().unwrap_or(Value::Null)))
113}
114
115// ---------------------------------------------------------------------------
116// Leases
117// ---------------------------------------------------------------------------
118
119/// KEYS: the resource hash. ARGV: owner, now (µs), expiry (µs). Returns the new epoch,
120/// or -1 when another owner holds a live lease.
121const LEASE_ACQUIRE_SCRIPT: &str = r#"
122local h = redis.call('HMGET', KEYS[1], 'owner', 'epoch', 'expires', 'released')
123if h[2] and h[4] ~= '1' and tonumber(h[3]) > tonumber(ARGV[2]) and h[1] ~= ARGV[1] then
124  return -1
125end
126local epoch = redis.call('HINCRBY', KEYS[1], 'epoch', 1)
127redis.call('HSET', KEYS[1], 'owner', ARGV[1], 'expires', ARGV[3], 'released', '0')
128return epoch
129"#;
130
131/// KEYS: the resource hash. ARGV: owner, epoch, expiry (µs). Returns 1 when renewed.
132const LEASE_RENEW_SCRIPT: &str = r#"
133local h = redis.call('HMGET', KEYS[1], 'owner', 'epoch', 'released')
134if h[1] ~= ARGV[1] or h[2] ~= ARGV[2] or h[3] == '1' then return 0 end
135redis.call('HSET', KEYS[1], 'expires', ARGV[3])
136return 1
137"#;
138
139/// KEYS: the resource hash. ARGV: owner, epoch. Returns 1 when released.
140const LEASE_RELEASE_SCRIPT: &str = r#"
141local h = redis.call('HMGET', KEYS[1], 'owner', 'epoch')
142if h[1] ~= ARGV[1] or h[2] ~= ARGV[2] then return 0 end
143redis.call('HSET', KEYS[1], 'released', '1')
144return 1
145"#;
146
147fn lease_key(resource: &str) -> String {
148    format!("adk:lease:{{{}}}", hex(resource))
149}
150
151/// Redis-backed [`LeaseStore`].
152///
153/// One hash per resource; every grant, renewal, and release is one Lua script, so
154/// concurrent acquirers in any number of processes see one winner. The hash is never
155/// deleted, so epochs keep counting after a release. See the
156/// [module documentation](self) for the layout.
157///
158/// # Example
159///
160/// ```rust,no_run
161/// use std::time::Duration;
162/// use adk_core::LeaseStore;
163/// use adk_session::RedisLeaseStore;
164///
165/// # async fn demo() -> adk_core::Result<()> {
166/// let leases = RedisLeaseStore::new("redis://localhost:6379").await?;
167/// leases.migrate().await?;
168/// if let Some(lease) = leases.acquire("scheduler", "replica-1", Duration::from_secs(30)).await? {
169///     leases.renew(&lease, Duration::from_secs(30)).await?;
170/// }
171/// # Ok(())
172/// # }
173/// ```
174#[derive(Debug, Clone)]
175pub struct RedisLeaseStore {
176    client: Client,
177    clock: Arc<dyn Clock>,
178}
179
180impl RedisLeaseStore {
181    /// Connects to `url`.
182    ///
183    /// # Errors
184    ///
185    /// Returns `session.lease_store.storage` when the server cannot be reached.
186    pub async fn new(url: &str) -> Result<Self> {
187        let client = connect(url).await.map_err(|e| storage_error(LEASE_STORAGE, e))?;
188        Ok(Self::from_client(client))
189    }
190
191    /// Uses an initialized client, such as one shared with other Redis stores.
192    pub fn from_client(client: Client) -> Self {
193        Self { client, clock: Arc::new(SystemClock) }
194    }
195
196    /// Sets the clock that decides expiry.
197    pub fn with_clock(mut self, clock: Arc<dyn Clock>) -> Self {
198        self.clock = clock;
199        self
200    }
201
202    /// Loads the store's scripts into the server's script cache.
203    ///
204    /// # Errors
205    ///
206    /// Returns `session.lease_store.storage` when the server rejects a script.
207    pub async fn migrate(&self) -> Result<()> {
208        load_scripts(
209            &self.client,
210            &[LEASE_ACQUIRE_SCRIPT, LEASE_RENEW_SCRIPT, LEASE_RELEASE_SCRIPT],
211        )
212        .await
213        .map_err(|e| storage_error(LEASE_STORAGE, e))
214    }
215}
216
217#[async_trait]
218impl LeaseStore for RedisLeaseStore {
219    async fn acquire(&self, resource: &str, owner: &str, ttl: Duration) -> Result<Option<Lease>> {
220        let now = stored_now(self.clock.now());
221        let expires_at = deadline(now, ttl, "lease.invalid_ttl")?;
222        let epoch: i64 = self
223            .client
224            .eval(
225                LEASE_ACQUIRE_SCRIPT,
226                vec![lease_key(resource)],
227                vec![owner.to_string(), micros(now), micros(expires_at)],
228            )
229            .await
230            .map_err(|e| storage_error(LEASE_STORAGE, format!("lease acquire failed: {e}")))?;
231        Ok(u64::try_from(epoch).ok().map(|epoch| Lease {
232            resource: resource.to_string(),
233            owner: owner.to_string(),
234            epoch,
235            expires_at,
236        }))
237    }
238
239    async fn renew(&self, lease: &Lease, ttl: Duration) -> Result<Lease> {
240        let expires_at = deadline(stored_now(self.clock.now()), ttl, "lease.invalid_ttl")?;
241        let renewed: i64 = self
242            .client
243            .eval(
244                LEASE_RENEW_SCRIPT,
245                vec![lease_key(&lease.resource)],
246                vec![lease.owner.clone(), lease.epoch.to_string(), micros(expires_at)],
247            )
248            .await
249            .map_err(|e| storage_error(LEASE_STORAGE, format!("lease renew failed: {e}")))?;
250        if renewed == 0 {
251            return Err(lease_stale_epoch_error(&lease.resource, lease.epoch));
252        }
253        Ok(Lease { expires_at, ..lease.clone() })
254    }
255
256    async fn release(&self, lease: &Lease) -> Result<()> {
257        let _: i64 = self
258            .client
259            .eval(
260                LEASE_RELEASE_SCRIPT,
261                vec![lease_key(&lease.resource)],
262                vec![lease.owner.clone(), lease.epoch.to_string()],
263            )
264            .await
265            .map_err(|e| storage_error(LEASE_STORAGE, format!("lease release failed: {e}")))?;
266        Ok(())
267    }
268
269    async fn current(&self, resource: &str) -> Result<Option<Lease>> {
270        let now = self.clock.now();
271        let fields: Vec<Option<String>> = self
272            .client
273            .hmget(lease_key(resource), vec!["owner", "epoch", "expires", "released"])
274            .await
275            .map_err(|e| storage_error(LEASE_STORAGE, format!("lease read failed: {e}")))?;
276        let [Some(owner), Some(epoch), Some(expires), released] =
277            <[Option<String>; 4]>::try_from(fields).map_err(|_| {
278                storage_error(LEASE_STORAGE, "lease read returned the wrong field count")
279            })?
280        else {
281            return Ok(None);
282        };
283        let expires_at = from_micros(&expires, LEASE_STORAGE, "expires")?;
284        if released.as_deref() == Some("1") || expires_at <= now {
285            return Ok(None);
286        }
287        let epoch = epoch.parse().map_err(|_| {
288            storage_error(LEASE_STORAGE, format!("stored epoch '{epoch}' is corrupt"))
289        })?;
290        Ok(Some(Lease { resource: resource.to_string(), owner, epoch, expires_at }))
291    }
292}
293
294// ---------------------------------------------------------------------------
295// Runs
296// ---------------------------------------------------------------------------
297
298/// Helpers every run script starts with. A run hash stores its queue (`qk`) and
299/// concurrency key (`ck`) in hex, which is how the scripts find its index keys.
300const RUN_PRELUDE: &str = r#"
301local PFX = '{adk:runs}:'
302local function run_key(id) return PFX .. 'run:' .. id end
303local function bump(key, now)
304  redis.call('HINCRBY', key, 'revision', 1)
305  redis.call('HSET', key, 'updated', now)
306end
307local function settle(id, key, now)
308  local h = redis.call('HMGET', key, 'qk', 'ck')
309  redis.call('ZREM', PFX .. 'ready:' .. h[1], id)
310  redis.call('ZREM', PFX .. 'timers:' .. h[1], id)
311  if h[2] then redis.call('ZREM', PFX .. 'holders:' .. h[1] .. ':' .. h[2], id) end
312  redis.call('ZADD', PFX .. 'finished', now, id)
313end
314local function cancel(id, key, now)
315  local state = redis.call('HGET', key, 'state')
316  if state == 'queued' or state == 'waiting' then
317    redis.call('HSET', key, 'state', 'cancelled')
318    redis.call('HDEL', key, 'lease_owner', 'lease_expires')
319    bump(key, now)
320    settle(id, key, now)
321  elseif state == 'running' then
322    redis.call('HSET', key, 'cancel_requested', '1')
323    bump(key, now)
324  end
325end
326local function fence(key, epoch)
327  local h = redis.call('HMGET', key, 'state', 'lease_epoch')
328  if not h[1] then return 'missing' end
329  if h[1] ~= 'running' or h[2] ~= epoch then return 'stale' end
330  return nil
331end
332"#;
333
334/// ARGV: run id, queue (hex), idempotency key or '', concurrency key (hex) or '',
335/// policy, now (µs), not-before (µs) or '', then field/value pairs for the new hash.
336/// Returns `{'existing', fields}`, `{'rejected', blocking id}`, or `{'created', fields}`.
337const RUN_ENQUEUE_BODY: &str = r#"
338local id, qk, ikey, ck, policy, now, nb = ARGV[1], ARGV[2], ARGV[3], ARGV[4], ARGV[5], ARGV[6], ARGV[7]
339if ikey ~= '' then
340  local existing = redis.call('HGET', PFX .. 'idem:' .. qk, ikey)
341  if existing then
342    local fields = redis.call('HGETALL', run_key(existing))
343    if #fields > 0 then return {'existing', fields} end
344  end
345end
346local holders_key = PFX .. 'holders:' .. qk .. ':' .. ck
347if ck ~= '' then
348  local holders = redis.call('ZRANGE', holders_key, 0, -1)
349  if policy == 'reject' and #holders > 0 then return {'rejected', holders[1]} end
350  if policy == 'interrupt' then
351    for _, holder in ipairs(holders) do cancel(holder, run_key(holder), now) end
352  end
353end
354local seq = redis.call('INCR', PFX .. 'seq')
355local key = run_key(id)
356redis.call('HSET', key, 'seq', seq, 'qk', qk, 'state', 'queued', 'attempt', '0',
357  'lease_epoch', '0', 'revision', '1', 'updated', now, 'cancel_requested', '0', 'wake_pending', '0')
358for i = 8, #ARGV, 2 do redis.call('HSET', key, ARGV[i], ARGV[i + 1]) end
359if ck ~= '' then
360  redis.call('HSET', key, 'ck', ck)
361  redis.call('ZADD', holders_key, seq, id)
362end
363if ikey ~= '' then redis.call('HSET', PFX .. 'idem:' .. qk, ikey, id) end
364redis.call('ZADD', PFX .. 'all', seq, id)
365redis.call('ZADD', PFX .. 'queue:' .. qk, seq, id)
366if nb ~= '' then
367  redis.call('HSET', key, 'not_before', nb)
368  redis.call('ZADD', PFX .. 'timers:' .. qk, nb, id)
369else
370  redis.call('ZADD', PFX .. 'ready:' .. qk, seq, id)
371end
372return {'created', redis.call('HGETALL', key)}
373"#;
374
375/// ARGV: queue (hex), worker, now (µs), lease expiry (µs). Returns the claimed run's
376/// fields, or nil when nothing is claimable.
377const RUN_CLAIM_BODY: &str = r#"
378local qk, worker, now, expires = ARGV[1], ARGV[2], ARGV[3], ARGV[4]
379local nowv = tonumber(now)
380local ready, timers = PFX .. 'ready:' .. qk, PFX .. 'timers:' .. qk
381for _, id in ipairs(redis.call('ZRANGEBYSCORE', timers, '-inf', now)) do
382  local seq = redis.call('HGET', run_key(id), 'seq')
383  redis.call('ZREM', timers, id)
384  if seq then redis.call('ZADD', ready, seq, id) end
385end
386local offset = 0
387while true do
388  local batch = redis.call('ZRANGE', ready, offset, offset + 63)
389  if #batch == 0 then return false end
390  local kept = 0
391  for _, id in ipairs(batch) do
392    local key = run_key(id)
393    local h = redis.call('HMGET', key, 'state', 'not_before', 'lease_expires', 'attempt',
394      'max_attempts', 'ck')
395    local state, verdict, at = h[1], 'drop', nil
396    if state == 'queued' then
397      if h[2] and tonumber(h[2]) > nowv then at = h[2] else verdict = 'claim' end
398    elseif state == 'waiting' then
399      if h[2] and tonumber(h[2]) <= nowv then verdict = 'claim' else at = h[2] end
400    elseif state == 'running' then
401      if h[3] and tonumber(h[3]) > nowv then
402        at = h[3]
403      elseif tonumber(h[4]) >= tonumber(h[5]) then
404        redis.call('HSET', key, 'state', 'failed', 'error',
405          'attempts exhausted: the lease of attempt ' .. h[4] .. ' of ' .. h[5] .. ' expired')
406        redis.call('HDEL', key, 'lease_owner', 'lease_expires')
407        bump(key, now)
408        settle(id, key, now)
409      else
410        verdict = 'claim'
411      end
412    end
413    if verdict == 'claim' and state == 'queued' and h[6] then
414      local first = redis.call('ZRANGE', PFX .. 'holders:' .. qk .. ':' .. h[6], 0, 0)
415      if first[1] ~= id then verdict = 'keep' end
416    end
417    if verdict == 'claim' then
418      if state ~= 'waiting' then redis.call('HINCRBY', key, 'attempt', 1) end
419      redis.call('HINCRBY', key, 'lease_epoch', 1)
420      redis.call('HSET', key, 'state', 'running', 'lease_owner', worker, 'lease_expires', expires,
421        'heartbeat', now)
422      redis.call('HDEL', key, 'not_before')
423      bump(key, now)
424      redis.call('ZREM', ready, id)
425      redis.call('ZADD', timers, expires, id)
426      return redis.call('HGETALL', key)
427    elseif verdict == 'keep' then
428      kept = kept + 1
429    else
430      redis.call('ZREM', ready, id)
431      if at then redis.call('ZADD', timers, at, id) end
432    end
433  end
434  offset = offset + kept
435end
436"#;
437
438/// ARGV: run id, epoch, now (µs), lease expiry (µs). Returns 'missing', 'stale', or the
439/// `cancel_requested` flag.
440const RUN_HEARTBEAT_BODY: &str = r#"
441local key = run_key(ARGV[1])
442local refused = fence(key, ARGV[2])
443if refused then return refused end
444redis.call('HSET', key, 'lease_expires', ARGV[4], 'heartbeat', ARGV[3])
445bump(key, ARGV[3])
446redis.call('ZADD', PFX .. 'timers:' .. redis.call('HGET', key, 'qk'), ARGV[4], ARGV[1])
447return redis.call('HGET', key, 'cancel_requested')
448"#;
449
450/// ARGV: run id, epoch, now (µs), checkpoint JSON. Returns 'missing', 'stale', or 'ok'.
451const RUN_CHECKPOINT_BODY: &str = r#"
452local key = run_key(ARGV[1])
453local refused = fence(key, ARGV[2])
454if refused then return refused end
455redis.call('HSET', key, 'checkpoint', ARGV[4])
456bump(key, ARGV[3])
457return 'ok'
458"#;
459
460/// ARGV: run id, epoch, now (µs), wait end (µs) or ''. Returns 'missing', 'stale', or 'ok'.
461const RUN_WAIT_BODY: &str = r#"
462local id, now = ARGV[1], ARGV[3]
463local key = run_key(id)
464local refused = fence(key, ARGV[2])
465if refused then return refused end
466local nb = ARGV[4]
467if redis.call('HGET', key, 'wake_pending') == '1' then nb = now end
468redis.call('HSET', key, 'state', 'waiting', 'wake_pending', '0')
469redis.call('HDEL', key, 'lease_owner', 'lease_expires')
470local timers = PFX .. 'timers:' .. redis.call('HGET', key, 'qk')
471if nb ~= '' then
472  redis.call('HSET', key, 'not_before', nb)
473  redis.call('ZADD', timers, nb, id)
474else
475  redis.call('HDEL', key, 'not_before')
476  redis.call('ZREM', timers, id)
477end
478bump(key, now)
479return 'ok'
480"#;
481
482/// ARGV: run id, now (µs). Returns 'missing' or 'ok'.
483const RUN_WAKE_BODY: &str = r#"
484local id, now = ARGV[1], ARGV[2]
485local key = run_key(id)
486local state = redis.call('HGET', key, 'state')
487if not state then return 'missing' end
488if state == 'waiting' then
489  redis.call('HSET', key, 'not_before', now)
490  redis.call('ZADD', PFX .. 'timers:' .. redis.call('HGET', key, 'qk'), now, id)
491  bump(key, now)
492elseif state == 'running' then
493  redis.call('HSET', key, 'wake_pending', '1')
494  bump(key, now)
495end
496return 'ok'
497"#;
498
499/// ARGV: run id, epoch, now (µs), outcome (`completed`, `failed`, `cancelled`), result
500/// JSON or error text, retryable flag, the end of a retry's backoff (µs) or ''. Returns
501/// `{'missing'}`, `{'stale'}`, or `{'ok', fields}`.
502const RUN_FINISH_BODY: &str = r#"
503local id, now, kind = ARGV[1], ARGV[3], ARGV[4]
504local key = run_key(id)
505local refused = fence(key, ARGV[2])
506if refused then return {refused} end
507local h = redis.call('HMGET', key, 'attempt', 'max_attempts', 'cancel_requested', 'qk', 'seq')
508local state = 'cancelled'
509if kind == 'completed' then
510  state = 'completed'
511  redis.call('HSET', key, 'result', ARGV[5])
512elseif kind == 'failed' then
513  redis.call('HSET', key, 'error', ARGV[5])
514  if ARGV[6] == '1' and tonumber(h[1]) < tonumber(h[2]) and h[3] ~= '1' then
515    state = 'queued'
516  else
517    state = 'failed'
518  end
519end
520redis.call('HSET', key, 'state', state, 'wake_pending', '0')
521redis.call('HDEL', key, 'lease_owner', 'lease_expires')
522bump(key, now)
523redis.call('ZREM', PFX .. 'timers:' .. h[4], id)
524if state == 'queued' and ARGV[7] ~= '' then
525  redis.call('HSET', key, 'not_before', ARGV[7])
526  redis.call('ZADD', PFX .. 'timers:' .. h[4], ARGV[7], id)
527elseif state == 'queued' then
528  redis.call('ZADD', PFX .. 'ready:' .. h[4], h[5], id)
529else
530  settle(id, key, now)
531end
532return {'ok', redis.call('HGETALL', key)}
533"#;
534
535/// ARGV: run id, now (µs). Returns 'missing' or 'ok'.
536const RUN_CANCEL_BODY: &str = r#"
537local key = run_key(ARGV[1])
538if redis.call('EXISTS', key) == 0 then return 'missing' end
539cancel(ARGV[1], key, ARGV[2])
540return 'ok'
541"#;
542
543/// ARGV: index (`all` or `queue:<hex>`), limit (0 for none), states (comma separated, ''
544/// for any), then app, user, session, and concurrency key, each `=value` or '' for any.
545/// Returns the matching runs' fields, oldest first.
546const RUN_LIST_BODY: &str = r#"
547local limit = tonumber(ARGV[2])
548local states = {}
549for state in string.gmatch(ARGV[3], '[^,]+') do states[state] = true end
550local wanted = {ARGV[4], ARGV[5], ARGV[6], ARGV[7]}
551local out = {}
552for _, id in ipairs(redis.call('ZRANGE', PFX .. ARGV[1], 0, -1)) do
553  local key = run_key(id)
554  local h = redis.call('HMGET', key, 'state', 'app', 'user', 'session', 'ckey')
555  local matches = h[1] and (ARGV[3] == '' or states[h[1]])
556  for i = 1, 4 do
557    if matches and wanted[i] ~= '' and (not h[i + 1] or '=' .. h[i + 1] ~= wanted[i]) then
558      matches = false
559    end
560  end
561  if matches then
562    table.insert(out, redis.call('HGETALL', key))
563    if limit > 0 and #out >= limit then break end
564  end
565end
566return out
567"#;
568
569/// ARGV: cut-off (µs), batch size. Returns `{deleted, examined}`.
570const RUN_PRUNE_BODY: &str = r#"
571local ids = redis.call('ZRANGEBYSCORE', PFX .. 'finished', '-inf', '(' .. ARGV[1], 'LIMIT', 0,
572  tonumber(ARGV[2]))
573local deleted = 0
574for _, id in ipairs(ids) do
575  local key = run_key(id)
576  local h = redis.call('HMGET', key, 'state', 'qk', 'ikey')
577  if h[1] == 'queued' or h[1] == 'running' or h[1] == 'waiting' then
578    redis.call('ZREM', PFX .. 'finished', id)
579  else
580    if h[2] and h[3] and redis.call('HGET', PFX .. 'idem:' .. h[2], h[3]) == id then
581      redis.call('HDEL', PFX .. 'idem:' .. h[2], h[3])
582    end
583    if h[2] then redis.call('ZREM', PFX .. 'queue:' .. h[2], id) end
584    redis.call('ZREM', PFX .. 'all', id)
585    redis.call('ZREM', PFX .. 'finished', id)
586    if h[1] then
587      redis.call('DEL', key)
588      deleted = deleted + 1
589    end
590  end
591end
592return {deleted, #ids}
593"#;
594
595/// The run scripts, each prefixed with [`RUN_PRELUDE`], built once.
596static RUN_SCRIPTS: LazyLock<RunScripts> = LazyLock::new(RunScripts::new);
597
598struct RunScripts {
599    enqueue: String,
600    claim: String,
601    heartbeat: String,
602    checkpoint: String,
603    wait: String,
604    wake: String,
605    finish: String,
606    cancel: String,
607    list: String,
608    prune: String,
609}
610
611impl RunScripts {
612    fn new() -> Self {
613        let script = |body: &str| format!("{RUN_PRELUDE}{body}");
614        Self {
615            enqueue: script(RUN_ENQUEUE_BODY),
616            claim: script(RUN_CLAIM_BODY),
617            heartbeat: script(RUN_HEARTBEAT_BODY),
618            checkpoint: script(RUN_CHECKPOINT_BODY),
619            wait: script(RUN_WAIT_BODY),
620            wake: script(RUN_WAKE_BODY),
621            finish: script(RUN_FINISH_BODY),
622            cancel: script(RUN_CANCEL_BODY),
623            list: script(RUN_LIST_BODY),
624            prune: script(RUN_PRUNE_BODY),
625        }
626    }
627
628    fn all(&self) -> [&str; 10] {
629        [
630            &self.enqueue,
631            &self.claim,
632            &self.heartbeat,
633            &self.checkpoint,
634            &self.wait,
635            &self.wake,
636            &self.finish,
637            &self.cancel,
638            &self.list,
639            &self.prune,
640        ]
641    }
642}
643
644fn run_error(message: impl std::fmt::Display) -> AdkError {
645    storage_error(RUN_STORAGE, message)
646}
647
648fn parse_state(text: &str) -> Result<RunState> {
649    [
650        RunState::Queued,
651        RunState::Running,
652        RunState::Waiting,
653        RunState::Completed,
654        RunState::Failed,
655        RunState::Cancelled,
656    ]
657    .into_iter()
658    .find(|state| state_name(*state) == text)
659    .ok_or_else(|| run_error(format!("stored run state '{text}' is unknown")))
660}
661
662/// Rebuilds a [`RunRecord`] from a run hash's field/value pairs.
663fn record_from_fields(pairs: Vec<String>) -> Result<RunRecord> {
664    let mut fields: HashMap<String, String> = HashMap::new();
665    let mut pairs = pairs.into_iter();
666    while let (Some(field), Some(value)) = (pairs.next(), pairs.next()) {
667        fields.insert(field, value);
668    }
669    let base = fields.remove("base").ok_or_else(|| run_error("stored run has no 'base' field"))?;
670    let mut record: RunRecord = serde_json::from_str(&base)
671        .map_err(|e| run_error(format!("stored run 'base' is corrupt: {e}")))?;
672    let mut take = |name: &str| fields.remove(name);
673    let number = |text: Option<String>, name: &str| -> Result<u64> {
674        let text = text.ok_or_else(|| run_error(format!("stored run has no '{name}' field")))?;
675        text.parse().map_err(|_| run_error(format!("stored run '{name}' is corrupt: '{text}'")))
676    };
677    let time = |text: Option<String>, name: &str| -> Result<Option<DateTime<Utc>>> {
678        text.map(|text| from_micros(&text, RUN_STORAGE, name)).transpose()
679    };
680    let json = |text: Option<String>, name: &str| -> Result<Option<serde_json::Value>> {
681        text.map(|text| {
682            serde_json::from_str(&text)
683                .map_err(|e| run_error(format!("stored run '{name}' is corrupt: {e}")))
684        })
685        .transpose()
686    };
687
688    record.state = parse_state(&take("state").unwrap_or_default())?;
689    record.attempt = u32::try_from(number(take("attempt"), "attempt")?)
690        .map_err(|_| run_error("stored run 'attempt' is out of range"))?;
691    record.lease_epoch = number(take("lease_epoch"), "lease_epoch")?;
692    record.revision = number(take("revision"), "revision")?;
693    record.lease_owner = take("lease_owner");
694    record.lease_expires_at = time(take("lease_expires"), "lease_expires")?;
695    record.heartbeat_at = time(take("heartbeat"), "heartbeat")?;
696    record.not_before = time(take("not_before"), "not_before")?;
697    record.updated_at = time(take("updated"), "updated")?
698        .ok_or_else(|| run_error("stored run has no 'updated' field"))?;
699    record.checkpoint = json(take("checkpoint"), "checkpoint")?
700        .map(serde_json::from_value)
701        .transpose()
702        .map_err(|e| run_error(format!("stored run 'checkpoint' is corrupt: {e}")))?;
703    record.result = json(take("result"), "result")?;
704    record.error = take("error");
705    record.cancel_requested = take("cancel_requested").as_deref() == Some("1");
706    record.wake_pending = take("wake_pending").as_deref() == Some("1");
707    Ok(record)
708}
709
710fn policy_name(policy: OnConflict) -> &'static str {
711    match policy {
712        OnConflict::Reject => "reject",
713        OnConflict::Interrupt => "interrupt",
714        _ => "enqueue",
715    }
716}
717
718/// Redis-backed [`DurableRunStore`].
719///
720/// Each run is one hash; ready runs, timers, key holders, and idempotency keys are
721/// indexes kept by the same scripts that change the run. See the
722/// [module documentation](self) for the layout and the script behind each operation.
723///
724/// # Example
725///
726/// ```rust,no_run
727/// use std::time::Duration;
728/// use adk_core::run_store::{DurableRunStore, NewRun, RunOutcome};
729/// use adk_session::RedisRunStore;
730///
731/// # async fn demo() -> adk_core::Result<()> {
732/// let runs = RedisRunStore::new("redis://localhost:6379").await?;
733/// runs.migrate().await?;
734/// runs.enqueue(NewRun::new("default", "app", "user", "agent", serde_json::json!({}))).await?;
735/// if let Some(claimed) = runs.claim("default", "worker-1", Duration::from_secs(30)).await? {
736///     let id = &claimed.record.run_id;
737///     runs.finish(id, claimed.epoch, RunOutcome::Completed(serde_json::json!("done"))).await?;
738/// }
739/// # Ok(())
740/// # }
741/// ```
742#[derive(Debug, Clone)]
743pub struct RedisRunStore {
744    client: Client,
745    clock: Arc<dyn Clock>,
746}
747
748impl RedisRunStore {
749    /// Connects to `url`.
750    ///
751    /// # Errors
752    ///
753    /// Returns `session.run_store.storage` when the server cannot be reached.
754    pub async fn new(url: &str) -> Result<Self> {
755        Ok(Self::from_client(connect(url).await.map_err(run_error)?))
756    }
757
758    /// Uses an initialized client, such as one shared with other Redis stores.
759    pub fn from_client(client: Client) -> Self {
760        Self { client, clock: Arc::new(SystemClock) }
761    }
762
763    /// Sets the clock that decides delays, waits, and lease expiry.
764    pub fn with_clock(mut self, clock: Arc<dyn Clock>) -> Self {
765        self.clock = clock;
766        self
767    }
768
769    /// Loads the store's scripts into the server's script cache.
770    ///
771    /// # Errors
772    ///
773    /// Returns `session.run_store.storage` when the server rejects a script.
774    pub async fn migrate(&self) -> Result<()> {
775        load_scripts(&self.client, &RUN_SCRIPTS.all()).await.map_err(run_error)
776    }
777
778    fn now(&self) -> DateTime<Utc> {
779        stored_now(self.clock.now())
780    }
781
782    async fn eval(&self, script: &str, args: Vec<String>) -> Result<Value> {
783        self.client
784            .eval(script, Vec::<String>::new(), args)
785            .await
786            .map_err(|e| run_error(format!("run store script failed: {e}")))
787    }
788
789    /// Maps a fenced script's `missing` or `stale` verdict to the contract error.
790    fn refusal(verdict: &str, run_id: &str, epoch: u64) -> Option<AdkError> {
791        match verdict {
792            "missing" => Some(run_not_found_error(run_id)),
793            "stale" => Some(run_stale_epoch_error(run_id, epoch)),
794            _ => None,
795        }
796    }
797
798    async fn fenced(
799        &self,
800        script: &str,
801        run_id: &str,
802        epoch: u64,
803        extra: Vec<String>,
804    ) -> Result<String> {
805        let mut args = vec![run_id.to_string(), epoch.to_string(), micros(self.now())];
806        args.extend(extra);
807        let verdict = self
808            .eval(script, args)
809            .await?
810            .into_string()
811            .ok_or_else(|| run_error("run store script returned no verdict"))?;
812        match Self::refusal(&verdict, run_id, epoch) {
813            Some(error) => Err(error),
814            None => Ok(verdict),
815        }
816    }
817}
818
819#[async_trait]
820impl DurableRunStore for RedisRunStore {
821    async fn enqueue(&self, run: NewRun) -> Result<Enqueued> {
822        run.validate()?;
823        let now = self.now();
824        let run_id = uuid::Uuid::new_v4().to_string();
825        let not_before = run.not_before.map(stored_now);
826        let record = RunRecord::queued(run_id.clone(), NewRun { not_before, ..run }, now);
827        let base = serde_json::to_string(&record)
828            .map_err(|e| run_error(format!("run serialize failed: {e}")))?;
829
830        let mut args = vec![
831            run_id,
832            hex(&record.queue),
833            record.idempotency_key.clone().unwrap_or_default(),
834            record.concurrency_key.as_deref().map(hex).unwrap_or_default(),
835            policy_name(record.on_conflict).to_string(),
836            micros(now),
837            not_before.filter(|at| *at > now).map(micros).unwrap_or_default(),
838        ];
839        let mut field = |name: &str, value: String| args.extend([name.to_string(), value]);
840        field("base", base);
841        field("app", record.app_name.clone());
842        field("user", record.user_id.clone());
843        field("max_attempts", record.max_attempts.to_string());
844        if let Some(session) = &record.session_id {
845            field("session", session.clone());
846        }
847        if let Some(key) = &record.concurrency_key {
848            field("ckey", key.clone());
849        }
850        if let Some(key) = &record.idempotency_key {
851            field("ikey", key.clone());
852        }
853        if let Some(at) = not_before.filter(|at| *at <= now) {
854            field("not_before", micros(at));
855        }
856
857        let (status, payload) =
858            status_reply(self.eval(&RUN_SCRIPTS.enqueue, args).await?, RUN_STORAGE)?;
859        match status.as_str() {
860            "created" => Ok(Enqueued::Created(record_from_fields(strings(payload, RUN_STORAGE)?)?)),
861            "existing" => {
862                Ok(Enqueued::Existing(record_from_fields(strings(payload, RUN_STORAGE)?)?))
863            }
864            "rejected" => Ok(Enqueued::Rejected {
865                blocking_run_id: payload
866                    .into_string()
867                    .ok_or_else(|| run_error("enqueue script named no blocking run"))?,
868            }),
869            other => Err(run_error(format!("unexpected enqueue script reply '{other}'"))),
870        }
871    }
872
873    async fn claim(&self, queue: &str, worker: &str, ttl: Duration) -> Result<Option<ClaimedRun>> {
874        let now = self.now();
875        let expires_at = deadline(now, ttl, "run_store.invalid_ttl")?;
876        let reply = self
877            .eval(
878                &RUN_SCRIPTS.claim,
879                vec![hex(queue), worker.to_string(), micros(now), micros(expires_at)],
880            )
881            .await?;
882        if reply.is_null() {
883            return Ok(None);
884        }
885        let record = record_from_fields(strings(reply, RUN_STORAGE)?)?;
886        Ok(Some(ClaimedRun { epoch: record.lease_epoch, record }))
887    }
888
889    async fn heartbeat(&self, run_id: &str, epoch: u64, ttl: Duration) -> Result<bool> {
890        let expires_at = deadline(self.now(), ttl, "run_store.invalid_ttl")?;
891        let flag =
892            self.fenced(&RUN_SCRIPTS.heartbeat, run_id, epoch, vec![micros(expires_at)]).await?;
893        Ok(flag == "1")
894    }
895
896    async fn set_checkpoint(
897        &self,
898        run_id: &str,
899        epoch: u64,
900        checkpoint: adk_core::run_store::RunCheckpointRef,
901    ) -> Result<()> {
902        let json = serde_json::to_string(&checkpoint)
903            .map_err(|e| run_error(format!("checkpoint serialize failed: {e}")))?;
904        self.fenced(&RUN_SCRIPTS.checkpoint, run_id, epoch, vec![json]).await.map(drop)
905    }
906
907    async fn wait(&self, run_id: &str, epoch: u64, until: Option<DateTime<Utc>>) -> Result<()> {
908        let until = until.map(stored_now).map(micros).unwrap_or_default();
909        self.fenced(&RUN_SCRIPTS.wait, run_id, epoch, vec![until]).await.map(drop)
910    }
911
912    async fn wake(&self, run_id: &str) -> Result<()> {
913        let verdict = self
914            .eval(&RUN_SCRIPTS.wake, vec![run_id.to_string(), micros(self.now())])
915            .await?
916            .into_string();
917        match verdict.as_deref() {
918            Some("missing") => Err(run_not_found_error(run_id)),
919            _ => Ok(()),
920        }
921    }
922
923    async fn finish(&self, run_id: &str, epoch: u64, outcome: RunOutcome) -> Result<RunRecord> {
924        let now = self.now();
925        let mut retry_at = None;
926        let (kind, payload, retryable) = match outcome {
927            RunOutcome::Completed(result) => (
928                "completed",
929                serde_json::to_string(&result)
930                    .map_err(|e| run_error(format!("result serialize failed: {e}")))?,
931                false,
932            ),
933            RunOutcome::Failed { error, retryable, backoff } => {
934                retry_at = backoff.map(|backoff| micros(stored_now(now + backoff)));
935                ("failed", error, retryable)
936            }
937            RunOutcome::Cancelled => ("cancelled", String::new(), false),
938        };
939        let args = vec![
940            run_id.to_string(),
941            epoch.to_string(),
942            micros(now),
943            kind.to_string(),
944            payload,
945            if retryable { "1" } else { "0" }.to_string(),
946            retry_at.unwrap_or_default(),
947        ];
948        let (status, fields) =
949            status_reply(self.eval(&RUN_SCRIPTS.finish, args).await?, RUN_STORAGE)?;
950        if let Some(error) = Self::refusal(&status, run_id, epoch) {
951            return Err(error);
952        }
953        record_from_fields(strings(fields, RUN_STORAGE)?)
954    }
955
956    async fn request_cancel(&self, run_id: &str) -> Result<()> {
957        let verdict = self
958            .eval(&RUN_SCRIPTS.cancel, vec![run_id.to_string(), micros(self.now())])
959            .await?
960            .into_string();
961        match verdict.as_deref() {
962            Some("missing") => Err(run_not_found_error(run_id)),
963            _ => Ok(()),
964        }
965    }
966
967    async fn get(&self, run_id: &str) -> Result<Option<RunRecord>> {
968        let fields: Vec<String> = self
969            .client
970            .hgetall::<HashMap<String, String>, _>(format!("{{adk:runs}}:run:{run_id}"))
971            .await
972            .map_err(|e| run_error(format!("run read failed: {e}")))?
973            .into_iter()
974            .flat_map(|(field, value)| [field, value])
975            .collect();
976        if fields.is_empty() {
977            return Ok(None);
978        }
979        record_from_fields(fields).map(Some)
980    }
981
982    async fn list(&self, filter: RunFilter) -> Result<Vec<RunRecord>> {
983        let wanted =
984            |value: &Option<String>| value.as_ref().map(|v| format!("={v}")).unwrap_or_default();
985        let index =
986            filter.queue.as_deref().map_or("all".to_string(), |q| format!("queue:{}", hex(q)));
987        let states: Vec<_> = filter.states.iter().map(|state| state_name(*state)).collect();
988        let args = vec![
989            index,
990            filter.limit.unwrap_or(0).to_string(),
991            states.join(","),
992            wanted(&filter.app_name),
993            wanted(&filter.user_id),
994            wanted(&filter.session_id),
995            wanted(&filter.concurrency_key),
996        ];
997        let reply = self.eval(&RUN_SCRIPTS.list, args).await?;
998        reply
999            .into_array()
1000            .into_iter()
1001            .map(|run| strings(run, RUN_STORAGE).and_then(record_from_fields))
1002            .collect()
1003    }
1004
1005    async fn prune(&self, finished_before: DateTime<Utc>) -> Result<u64> {
1006        let mut total = 0u64;
1007        loop {
1008            let reply = self
1009                .eval(&RUN_SCRIPTS.prune, vec![micros(finished_before), PRUNE_BATCH.to_string()])
1010                .await?;
1011            let counts = strings(reply, RUN_STORAGE)?;
1012            let count = |index: usize| counts.get(index).and_then(|text| text.parse::<u64>().ok());
1013            let (Some(deleted), Some(examined)) = (count(0), count(1)) else {
1014                return Err(run_error("prune script returned no counts"));
1015            };
1016            total += deleted;
1017            if examined < PRUNE_BATCH as u64 {
1018                return Ok(total);
1019            }
1020        }
1021    }
1022}
1023
1024// ---------------------------------------------------------------------------
1025// Schedules
1026// ---------------------------------------------------------------------------
1027
1028const SCHEDULE_DEFS: &str = "{adk:schedules}:defs";
1029const SCHEDULE_REVS: &str = "{adk:schedules}:revs";
1030const SCHEDULE_DUE: &str = "{adk:schedules}:due";
1031
1032/// KEYS: defs, revs, due. ARGV: id, expected revision (0 when absent), new revision,
1033/// definition JSON, due score (µs) or ''. Returns 1 when written, 0 when the revision moved.
1034const SCHEDULE_CAS_SCRIPT: &str = r#"
1035local current = tonumber(redis.call('HGET', KEYS[2], ARGV[1])) or 0
1036if current ~= tonumber(ARGV[2]) then return 0 end
1037redis.call('HSET', KEYS[1], ARGV[1], ARGV[4])
1038redis.call('HSET', KEYS[2], ARGV[1], ARGV[3])
1039if ARGV[5] ~= '' then
1040  redis.call('ZADD', KEYS[3], ARGV[5], ARGV[1])
1041else
1042  redis.call('ZREM', KEYS[3], ARGV[1])
1043end
1044return 1
1045"#;
1046
1047/// KEYS: defs, revs, due. ARGV: id. Returns 1 when deleted, 0 when absent.
1048const SCHEDULE_DELETE_SCRIPT: &str = r#"
1049if redis.call('HDEL', KEYS[1], ARGV[1]) == 0 then return 0 end
1050redis.call('HDEL', KEYS[2], ARGV[1])
1051redis.call('ZREM', KEYS[3], ARGV[1])
1052return 1
1053"#;
1054
1055fn schedule_error(message: impl std::fmt::Display) -> AdkError {
1056    storage_error(SCHEDULE_STORAGE, message)
1057}
1058
1059fn schedule_keys() -> Vec<String> {
1060    vec![SCHEDULE_DEFS.to_string(), SCHEDULE_REVS.to_string(), SCHEDULE_DUE.to_string()]
1061}
1062
1063fn parse_schedule(json: &str) -> Result<Schedule> {
1064    serde_json::from_str(json)
1065        .map_err(|e| schedule_error(format!("stored schedule is corrupt: {e}")))
1066}
1067
1068/// Redis-backed [`ScheduleStore`].
1069///
1070/// Definitions and revisions live in two hashes keyed by schedule id, and unpaused
1071/// schedules with a next fire time sit in a sorted set by that time, which `due` reads.
1072/// Every change is a compare-and-swap on the revision inside one Lua script.
1073///
1074/// # Example
1075///
1076/// ```rust,no_run
1077/// use std::time::Duration;
1078/// use adk_core::run_store::NewRun;
1079/// use adk_core::schedule::{MissedFirePolicy, Schedule, ScheduleSpec, ScheduleStore};
1080/// use adk_session::RedisScheduleStore;
1081///
1082/// # async fn demo() -> adk_core::Result<()> {
1083/// let schedules = RedisScheduleStore::new("redis://localhost:6379").await?;
1084/// schedules.migrate().await?;
1085/// let heartbeat = Schedule::new(
1086///     "heartbeat",
1087///     ScheduleSpec::Every(Duration::from_secs(60)),
1088///     NewRun::new("default", "ops", "system", "probe", serde_json::json!({})),
1089///     MissedFirePolicy::Skip,
1090/// )
1091/// .with_next_fire_at(chrono::Utc::now());
1092/// schedules.upsert(heartbeat).await?;
1093/// # Ok(())
1094/// # }
1095/// ```
1096#[derive(Debug, Clone)]
1097pub struct RedisScheduleStore {
1098    client: Client,
1099}
1100
1101impl RedisScheduleStore {
1102    /// Connects to `url`.
1103    ///
1104    /// # Errors
1105    ///
1106    /// Returns `session.schedule_store.storage` when the server cannot be reached.
1107    pub async fn new(url: &str) -> Result<Self> {
1108        Ok(Self::from_client(connect(url).await.map_err(schedule_error)?))
1109    }
1110
1111    /// Uses an initialized client, such as one shared with other Redis stores.
1112    pub fn from_client(client: Client) -> Self {
1113        Self { client }
1114    }
1115
1116    /// Loads the store's scripts into the server's script cache.
1117    ///
1118    /// # Errors
1119    ///
1120    /// Returns `session.schedule_store.storage` when the server rejects a script.
1121    pub async fn migrate(&self) -> Result<()> {
1122        load_scripts(&self.client, &[SCHEDULE_CAS_SCRIPT, SCHEDULE_DELETE_SCRIPT])
1123            .await
1124            .map_err(schedule_error)
1125    }
1126
1127    /// Reads a schedule. Its JSON carries the revision, written by the same script that
1128    /// writes the revision hash.
1129    async fn read(&self, id: &str) -> Result<Option<Schedule>> {
1130        let json: Option<String> = self
1131            .client
1132            .hget(SCHEDULE_DEFS, id)
1133            .await
1134            .map_err(|e| schedule_error(format!("schedule read failed: {e}")))?;
1135        json.as_deref().map(parse_schedule).transpose()
1136    }
1137
1138    /// Writes `schedule` (with its new revision) when the stored revision is `expected`.
1139    async fn write(&self, schedule: &Schedule, expected: u64) -> Result<bool> {
1140        let json = serde_json::to_string(schedule)
1141            .map_err(|e| schedule_error(format!("schedule serialize failed: {e}")))?;
1142        let due = if schedule.paused {
1143            String::new()
1144        } else {
1145            schedule.next_fire_at.map(micros).unwrap_or_default()
1146        };
1147        let written: i64 = self
1148            .client
1149            .eval(
1150                SCHEDULE_CAS_SCRIPT,
1151                schedule_keys(),
1152                vec![
1153                    schedule.id.clone(),
1154                    expected.to_string(),
1155                    schedule.revision.to_string(),
1156                    json,
1157                    due,
1158                ],
1159            )
1160            .await
1161            .map_err(|e| schedule_error(format!("schedule write failed: {e}")))?;
1162        Ok(written == 1)
1163    }
1164
1165    /// Applies `change` to the stored schedule with a revision compare-and-swap, retrying
1166    /// when another writer changed it first. `change` returns `false` for no change.
1167    async fn update(&self, id: &str, change: impl Fn(&mut Schedule) -> bool) -> Result<Schedule> {
1168        for _ in 0..CAS_ATTEMPTS {
1169            let mut schedule = self.read(id).await?.ok_or_else(|| schedule_not_found_error(id))?;
1170            let expected = schedule.revision;
1171            if !change(&mut schedule) {
1172                return Ok(schedule);
1173            }
1174            schedule.revision = expected + 1;
1175            if self.write(&schedule, expected).await? {
1176                return Ok(schedule);
1177            }
1178        }
1179        Err(schedule_error(format!(
1180            "schedule '{id}' lost {CAS_ATTEMPTS} compare-and-swap attempts to concurrent writers"
1181        )))
1182    }
1183}
1184
1185#[async_trait]
1186impl ScheduleStore for RedisScheduleStore {
1187    async fn upsert(&self, schedule: Schedule) -> Result<Schedule> {
1188        schedule.validate()?;
1189        let schedule = Schedule { next_fire_at: schedule.next_fire_at.map(stored_now), ..schedule };
1190        for _ in 0..CAS_ATTEMPTS {
1191            let stored = self.read(&schedule.id).await?;
1192            if let Some(stored) = &stored
1193                && same_definition(stored, &schedule)
1194            {
1195                return Ok(stored.clone());
1196            }
1197            let expected = stored.map_or(0, |stored| stored.revision);
1198            let next = Schedule { revision: expected + 1, ..schedule.clone() };
1199            if self.write(&next, expected).await? {
1200                return Ok(next);
1201            }
1202        }
1203        Err(schedule_error(format!(
1204            "schedule '{}' lost {CAS_ATTEMPTS} compare-and-swap attempts to concurrent writers",
1205            schedule.id
1206        )))
1207    }
1208
1209    async fn get(&self, id: &str) -> Result<Option<Schedule>> {
1210        self.read(id).await
1211    }
1212
1213    async fn list(&self) -> Result<Vec<Schedule>> {
1214        let all: HashMap<String, String> = self
1215            .client
1216            .hgetall(SCHEDULE_DEFS)
1217            .await
1218            .map_err(|e| schedule_error(format!("schedule read failed: {e}")))?;
1219        let mut schedules =
1220            all.values().map(|json| parse_schedule(json)).collect::<Result<Vec<_>>>()?;
1221        schedules.sort_by(|a, b| a.id.cmp(&b.id));
1222        Ok(schedules)
1223    }
1224
1225    async fn delete(&self, id: &str) -> Result<()> {
1226        let deleted: i64 = self
1227            .client
1228            .eval(SCHEDULE_DELETE_SCRIPT, schedule_keys(), vec![id.to_string()])
1229            .await
1230            .map_err(|e| schedule_error(format!("schedule delete failed: {e}")))?;
1231        if deleted == 0 {
1232            return Err(schedule_not_found_error(id));
1233        }
1234        Ok(())
1235    }
1236
1237    async fn set_paused(&self, id: &str, paused: bool) -> Result<Schedule> {
1238        self.update(id, |schedule| {
1239            let changed = schedule.paused != paused;
1240            schedule.paused = paused;
1241            changed
1242        })
1243        .await
1244    }
1245
1246    async fn due(&self, now: DateTime<Utc>, limit: usize) -> Result<Vec<Schedule>> {
1247        if limit == 0 {
1248            return Ok(Vec::new());
1249        }
1250        let ids: Vec<String> = self
1251            .client
1252            .zrangebyscore(
1253                SCHEDULE_DUE,
1254                "-inf",
1255                now.timestamp_micros(),
1256                false,
1257                Some((0, i64::try_from(limit).unwrap_or(i64::MAX))),
1258            )
1259            .await
1260            .map_err(|e| schedule_error(format!("schedule due read failed: {e}")))?;
1261        let mut due = Vec::with_capacity(ids.len());
1262        for id in ids {
1263            if let Some(schedule) = self.read(&id).await? {
1264                due.push(schedule);
1265            }
1266        }
1267        Ok(due)
1268    }
1269
1270    async fn advance(
1271        &self,
1272        id: &str,
1273        expected_revision: u64,
1274        next_fire_at: Option<DateTime<Utc>>,
1275    ) -> Result<bool> {
1276        let mut schedule = self.read(id).await?.ok_or_else(|| schedule_not_found_error(id))?;
1277        if schedule.revision != expected_revision {
1278            return Ok(false);
1279        }
1280        schedule.next_fire_at = next_fire_at.map(stored_now);
1281        schedule.revision = expected_revision + 1;
1282        self.write(&schedule, expected_revision).await
1283    }
1284}
1285
1286// ---------------------------------------------------------------------------
1287// Governance state
1288// ---------------------------------------------------------------------------
1289
1290const GOVERNANCE_STATES: &str = "{adk:governance}:states";
1291const GOVERNANCE_EPOCHS: &str = "{adk:governance}:epochs";
1292
1293/// KEYS: states, epochs. ARGV: scope key, expected epoch, state JSON at the next epoch.
1294/// Returns `{1, epoch}` when written, or `{0, current epoch}` when the epoch moved.
1295const GOVERNANCE_SET_SCRIPT: &str = r#"
1296local current = tonumber(redis.call('HGET', KEYS[2], ARGV[1])) or 0
1297if current ~= tonumber(ARGV[2]) then return {0, current} end
1298redis.call('HSET', KEYS[1], ARGV[1], ARGV[3])
1299redis.call('HINCRBY', KEYS[2], ARGV[1], 1)
1300return {1, current + 1}
1301"#;
1302
1303fn governance_error(message: impl std::fmt::Display) -> AdkError {
1304    storage_error(GOVERNANCE_STORAGE, message)
1305}
1306
1307fn parse_governance(json: &str) -> Result<GovernanceState> {
1308    serde_json::from_str(json)
1309        .map_err(|e| governance_error(format!("stored governance state is corrupt: {e}")))
1310}
1311
1312/// Redis-backed [`GovernanceStateStore`].
1313///
1314/// States live in one hash keyed by [`GovernanceScope::key`], with each scope's epoch in a
1315/// second hash; `set` compares and bumps the epoch inside one Lua script.
1316///
1317/// # Example
1318///
1319/// ```rust,no_run
1320/// use adk_core::governance_state::{GovernanceScope, GovernanceStateStore};
1321/// use adk_core::principal::SubjectRef;
1322/// use adk_session::RedisGovernanceStateStore;
1323///
1324/// # async fn demo() -> adk_core::Result<()> {
1325/// let governance = RedisGovernanceStateStore::new("redis://localhost:6379").await?;
1326/// governance.migrate().await?;
1327/// let epoch = governance.get(&GovernanceScope::Org).await?.map_or(0, |state| state.epoch);
1328/// governance
1329///     .set(GovernanceScope::Org, epoch, true, Some("incident".into()), Some(SubjectRef::human("oncall")))
1330///     .await?;
1331/// # Ok(())
1332/// # }
1333/// ```
1334#[derive(Debug, Clone)]
1335pub struct RedisGovernanceStateStore {
1336    client: Client,
1337    clock: Arc<dyn Clock>,
1338}
1339
1340impl RedisGovernanceStateStore {
1341    /// Connects to `url`.
1342    ///
1343    /// # Errors
1344    ///
1345    /// Returns `session.governance_store.storage` when the server cannot be reached.
1346    pub async fn new(url: &str) -> Result<Self> {
1347        Ok(Self::from_client(connect(url).await.map_err(governance_error)?))
1348    }
1349
1350    /// Uses an initialized client, such as one shared with other Redis stores.
1351    pub fn from_client(client: Client) -> Self {
1352        Self { client, clock: Arc::new(SystemClock) }
1353    }
1354
1355    /// Sets the clock that stamps `issued_at`.
1356    pub fn with_clock(mut self, clock: Arc<dyn Clock>) -> Self {
1357        self.clock = clock;
1358        self
1359    }
1360
1361    /// Loads the store's script into the server's script cache.
1362    ///
1363    /// # Errors
1364    ///
1365    /// Returns `session.governance_store.storage` when the server rejects the script.
1366    pub async fn migrate(&self) -> Result<()> {
1367        load_scripts(&self.client, &[GOVERNANCE_SET_SCRIPT]).await.map_err(governance_error)
1368    }
1369}
1370
1371#[async_trait]
1372impl GovernanceStateStore for RedisGovernanceStateStore {
1373    async fn get(&self, scope: &GovernanceScope) -> Result<Option<GovernanceState>> {
1374        let json: Option<String> = self
1375            .client
1376            .hget(GOVERNANCE_STATES, scope.key())
1377            .await
1378            .map_err(|e| governance_error(format!("governance read failed: {e}")))?;
1379        json.as_deref().map(parse_governance).transpose()
1380    }
1381
1382    async fn set(
1383        &self,
1384        scope: GovernanceScope,
1385        expected_epoch: u64,
1386        frozen: bool,
1387        reason: Option<String>,
1388        issued_by: Option<SubjectRef>,
1389    ) -> Result<GovernanceState> {
1390        let state = GovernanceState {
1391            scope,
1392            frozen,
1393            reason,
1394            issued_by,
1395            issued_at: stored_now(self.clock.now()),
1396            epoch: expected_epoch + 1,
1397        };
1398        let json = serde_json::to_string(&state)
1399            .map_err(|e| governance_error(format!("governance serialize failed: {e}")))?;
1400        let reply: Vec<i64> = self
1401            .client
1402            .eval(
1403                GOVERNANCE_SET_SCRIPT,
1404                vec![GOVERNANCE_STATES.to_string(), GOVERNANCE_EPOCHS.to_string()],
1405                vec![state.scope.key(), expected_epoch.to_string(), json],
1406            )
1407            .await
1408            .map_err(|e| governance_error(format!("governance write failed: {e}")))?;
1409        match reply.as_slice() {
1410            [1, _] => Ok(state),
1411            [0, current] => Err(governance_conflict_error(
1412                &state.scope,
1413                expected_epoch,
1414                u64::try_from(*current).unwrap_or(0),
1415            )),
1416            other => Err(governance_error(format!("unexpected governance script reply {other:?}"))),
1417        }
1418    }
1419
1420    async fn list(&self) -> Result<Vec<GovernanceState>> {
1421        let all: HashMap<String, String> = self
1422            .client
1423            .hgetall(GOVERNANCE_STATES)
1424            .await
1425            .map_err(|e| governance_error(format!("governance read failed: {e}")))?;
1426        let mut states: Vec<(String, GovernanceState)> = all
1427            .into_iter()
1428            .map(|(key, json)| parse_governance(&json).map(|state| (key, state)))
1429            .collect::<Result<_>>()?;
1430        states.sort_by(|a, b| a.0.cmp(&b.0));
1431        Ok(states.into_iter().map(|(_, state)| state).collect())
1432    }
1433}
1434
1435#[cfg(test)]
1436mod tests {
1437    use super::*;
1438    use chrono::TimeZone;
1439
1440    #[test]
1441    fn records_round_trip_through_hash_fields() {
1442        let now = Utc.with_ymd_and_hms(2026, 10, 15, 12, 0, 0).unwrap();
1443        let mut record = RunRecord::queued(
1444            "run-1",
1445            NewRun::new("q/ü", "app", "user", "agent", serde_json::json!({ "x": {} })),
1446            now,
1447        );
1448        let base = serde_json::to_string(&record).unwrap();
1449        record.state = RunState::Running;
1450        record.attempt = 2;
1451        record.lease_epoch = 3;
1452        record.lease_owner = Some("w".into());
1453        record.lease_expires_at = Some(now + chrono::Duration::seconds(30));
1454        record.revision = 4;
1455        record.result = Some(serde_json::json!({ "empty": {}, "list": [] }));
1456        let fields = [
1457            ("base", base),
1458            ("state", "running".to_string()),
1459            ("attempt", "2".to_string()),
1460            ("lease_epoch", "3".to_string()),
1461            ("revision", "4".to_string()),
1462            ("lease_owner", "w".to_string()),
1463            ("lease_expires", micros(now + chrono::Duration::seconds(30))),
1464            ("updated", micros(now)),
1465            ("result", r#"{"empty":{},"list":[]}"#.to_string()),
1466            ("cancel_requested", "0".to_string()),
1467        ]
1468        .into_iter()
1469        .flat_map(|(field, value)| [field.to_string(), value])
1470        .collect();
1471        assert_eq!(record_from_fields(fields).unwrap(), record);
1472    }
1473
1474    #[test]
1475    fn keys_cannot_move_hash_slots() {
1476        assert_eq!(lease_key("a}{b"), "adk:lease:{617d7b62}");
1477        assert_eq!(parse_state("waiting").unwrap(), RunState::Waiting);
1478        assert!(parse_state("paused").is_err());
1479        assert_eq!(policy_name(OnConflict::Interrupt), "interrupt");
1480    }
1481}