Skip to main content

adk_core/
schedule.rs

1//! Schedules that enqueue durable runs: cron, one-shot, and fixed-interval.
2//!
3//! A [`ScheduleStore`] keeps each [`Schedule`] with its next fire time and a revision.
4//! A scheduler on any number of replicas polls [`due`](ScheduleStore::due), plans the
5//! firings with [`plan_fires`], enqueues one run per fire time, and moves the schedule
6//! on with [`advance`](ScheduleStore::advance) — a compare-and-swap on the revision.
7//!
8//! # Firing rule
9//!
10//! Every fire time enqueues a run whose idempotency key is
11//! [`firing_idempotency_key`]`(id, fire_time)` = `schedule:{id}:{fire_time RFC 3339}`.
12//! Replicas that plan the same fire time produce the same key, and the run store's
13//! idempotent enqueue turns them into one run. The advance CAS then lets one replica
14//! move the schedule on; the others see `false` and drop their plan. A replica that
15//! crashes between enqueue and advance leaves the schedule due, and the next replica
16//! re-plans the same fire times, which enqueue nothing new.
17//!
18//! # Missed fires
19//!
20//! When the scheduler falls behind (a restart, an outage), several occurrences can be
21//! due at once. [`MissedFirePolicy`] picks which of them fire:
22//!
23//! | Policy | Fires |
24//! |--------|-------|
25//! | [`Skip`](MissedFirePolicy::Skip) | The latest due occurrence, only if it is no more than `grace` late; nothing otherwise |
26//! | [`FireOnce`](MissedFirePolicy::FireOnce) | The latest due occurrence, however late |
27//! | [`CatchUp(n)`](MissedFirePolicy::CatchUp) | The latest `n` due occurrences, oldest first |
28//!
29//! # Cron
30//!
31//! Cron expressions use the `cron` crate's syntax with an optional leading seconds
32//! field: five fields (`min hour dom month dow`) or six or seven (`sec min hour dom
33//! month dow [year]`). They are evaluated in the IANA time zone of the spec
34//! (`chrono-tz`), so `0 9 * * Mon-Fri` in `Europe/Berlin` fires at 09:00 local time
35//! across daylight-saving changes. A local time skipped by a spring-forward change does
36//! not fire; a local time repeated by a fall-back change fires once, at its first
37//! instant. Evaluating cron specs needs the `cron` feature of `adk-core`; without it
38//! they fail with `schedule.cron_unavailable`.
39//!
40//! The day-of-week field counts days by the number of fields:
41//!
42//! | Expression | Sunday | Monday to Saturday | `1-5` fires |
43//! |------------|--------|--------------------|-------------|
44//! | Five fields | `0` or `7` | `1` to `6` | Monday to Friday |
45//! | Six or seven fields | `1` | `2` to `7` | Sunday to Thursday |
46//!
47//! Five fields follow Unix cron; six and seven keep the `cron` crate's numbering. Day
48//! names (`Mon-Fri`, `SAT,SUN`) mean the same days in both. A five-field day-of-week
49//! field takes `*`, `?`, days, ranges, lists and steps (`*/2`, `1-5/2`). A day fires only
50//! when it matches both the day-of-month and the day-of-week field.
51//!
52//! # Backend primitives
53//!
54//! | Operation | SQL | Redis | MongoDB | Neo4j, Firestore |
55//! |-----------|-----|-------|---------|------------------|
56//! | `advance` CAS | `UPDATE ... WHERE id = $1 AND revision = $2` | Lua compare of the revision field | `updateOne` filtered on `revision` | Transaction that checks the revision |
57//! | `due` | Index on `(paused, next_fire_at)` | Sorted set of next fire times | Index on `nextFireAt` | Indexed query |
58
59use std::collections::BTreeMap;
60use std::time::Duration;
61
62use async_trait::async_trait;
63use chrono::{DateTime, SecondsFormat, Utc};
64use serde::{Deserialize, Serialize};
65use tokio::sync::Mutex;
66
67use crate::run_store::NewRun;
68use crate::{AdkError, ErrorCategory, ErrorComponent, Result};
69
70/// Error code returned for an unknown schedule identifier.
71pub const SCHEDULE_NOT_FOUND_CODE: &str = "schedule.not_found";
72/// Error code returned for an invalid schedule or spec.
73pub const INVALID_SCHEDULE_CODE: &str = "schedule.invalid";
74
75/// How late an occurrence may fire under [`MissedFirePolicy::Skip`] by default.
76pub const DEFAULT_MISFIRE_GRACE: Duration = Duration::from_secs(60);
77
78/// When a schedule fires.
79///
80/// # Example
81///
82/// ```rust
83/// use adk_core::schedule::ScheduleSpec;
84///
85/// let spec = ScheduleSpec::Cron { expr: "0 9 * * Mon-Fri".into(), timezone: "Europe/Berlin".into() };
86/// assert_eq!(serde_json::to_value(&spec).unwrap()["cron"]["timezone"], "Europe/Berlin");
87/// ```
88#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
89#[serde(rename_all = "camelCase")]
90#[non_exhaustive]
91pub enum ScheduleSpec {
92    /// A cron expression evaluated in an IANA time zone such as `UTC` or `America/New_York`.
93    Cron {
94        /// The cron expression (five, six, or seven fields). Five fields count the days of
95        /// the week as Unix cron does (0 and 7 are Sunday); six and seven as the `cron`
96        /// crate does (1 is Sunday). See the [module documentation](crate::schedule).
97        expr: String,
98        /// The IANA time zone name.
99        timezone: String,
100    },
101    /// Once, at this instant.
102    At(DateTime<Utc>),
103    /// Repeatedly, this far apart, counted from the first fire time.
104    Every(Duration),
105}
106
107/// Which due occurrences fire when several are due at once.
108#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
109#[serde(rename_all = "camelCase")]
110#[non_exhaustive]
111pub enum MissedFirePolicy {
112    /// Fire the latest occurrence only when it is on time.
113    Skip,
114    /// Fire the latest occurrence, however late.
115    FireOnce,
116    /// Fire up to this many of the latest occurrences, oldest first; at least 1.
117    CatchUp(u32),
118}
119
120/// Spreads the fires of schedules that share a cadence, so a fleet of schedules on
121/// `0 * * * *` does not start every run in the same second.
122///
123/// Each fire is delayed by an offset that is a fixed share of a window, the share derived
124/// from the schedule's key and the jitter's [`seed`](Self::seed): the same schedule is
125/// delayed by the same share on every replica and after every restart, and two schedules
126/// are usually delayed by different shares. The window is [`percent`](Self::percent) of the
127/// gap to the next occurrence, at most [`max`](Self::max):
128///
129/// | Field | Bound |
130/// |-------|-------|
131/// | `percent` | 0 to 50; `new` clamps a larger value to 50 |
132/// | `max` | Any duration; the window is never longer |
133/// | offset | `0 <= offset < window <= gap / 2`, in whole milliseconds |
134///
135/// A delayed fire therefore lands before the next occurrence is due. The occurrence keeps
136/// its scheduled time as its identity — its idempotency key, its watermark and the
137/// missed-fire plan all use the scheduled time — so jitter moves when a fire runs, never
138/// which fires run. A one-shot [`ScheduleSpec::At`] has no next occurrence and is not
139/// delayed.
140///
141/// [`Jitter::default`] is 15 percent of the gap, at most nine minutes. Schedulers apply no
142/// jitter unless one is configured.
143///
144/// # Example
145///
146/// ```rust
147/// use std::time::Duration;
148/// use adk_core::schedule::{Jitter, ScheduleSpec};
149/// use chrono::{TimeZone, Utc};
150///
151/// let jitter = Jitter::new(15, Duration::from_secs(9 * 60));
152/// let at = Utc.with_ymd_and_hms(2026, 11, 18, 9, 0, 0).unwrap();
153/// let hourly = ScheduleSpec::Cron { expr: "0 * * * *".into(), timezone: "UTC".into() };
154/// let offset = jitter.offset_in(&hourly, "nightly-report", at);
155/// assert!(offset < Duration::from_secs(9 * 60));
156/// assert_eq!(offset, jitter.offset_in(&hourly, "nightly-report", at), "deterministic");
157/// assert_eq!(jitter.offset_in(&ScheduleSpec::At(at), "once", at), Duration::ZERO);
158/// ```
159#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
160#[non_exhaustive]
161pub struct Jitter {
162    /// The share of the gap to the next occurrence a fire may be delayed by, in percent.
163    pub percent: u8,
164    /// The longest a fire is delayed, whatever the gap.
165    pub max: Duration,
166    /// Folded into every schedule's share, so deployments that name their schedules alike
167    /// spread differently ([`salted`](Self::salted)).
168    pub seed: u64,
169}
170
171impl Default for Jitter {
172    /// 15 percent of the gap to the next occurrence, at most nine minutes.
173    fn default() -> Self {
174        Self::new(Self::DEFAULT_PERCENT, Self::DEFAULT_MAX)
175    }
176}
177
178impl Jitter {
179    /// The share of [`Jitter::default`], in percent.
180    pub const DEFAULT_PERCENT: u8 = 15;
181    /// The longest delay of [`Jitter::default`].
182    pub const DEFAULT_MAX: Duration = Duration::from_secs(9 * 60);
183    /// The largest share a jitter takes, so a delayed fire stays clear of the next one.
184    pub const MAX_PERCENT: u8 = 50;
185
186    /// A jitter of `percent` of the gap to the next occurrence, at most `max`; `percent`
187    /// above [`MAX_PERCENT`](Self::MAX_PERCENT) is clamped to it.
188    pub fn new(percent: u8, max: Duration) -> Self {
189        Self { percent: percent.min(Self::MAX_PERCENT), max, seed: 0 }
190    }
191
192    /// Folds `salt` into the seed, such as a tenant or application name, so its schedules
193    /// spread differently from another deployment's schedules of the same names.
194    ///
195    /// # Example
196    ///
197    /// ```rust
198    /// use adk_core::schedule::Jitter;
199    ///
200    /// assert_ne!(Jitter::default().salted("tenant-a").seed, Jitter::default().salted("tenant-b").seed);
201    /// ```
202    #[must_use]
203    pub fn salted(mut self, salt: &str) -> Self {
204        self.seed = fnv1a(self.seed ^ FNV_OFFSET, salt.as_bytes());
205        self
206    }
207
208    /// The window a fire at `at` may be delayed within: `percent` of the gap to `next`, at
209    /// most `max`; zero without a next occurrence.
210    pub fn window(&self, at: DateTime<Utc>, next: Option<DateTime<Utc>>) -> Duration {
211        let Some(gap) = next.and_then(|next| (next - at).to_std().ok()) else {
212            return Duration::ZERO;
213        };
214        let share = gap.as_nanos() * u128::from(self.percent.min(Self::MAX_PERCENT)) / 100;
215        Duration::from_nanos(u64::try_from(share).unwrap_or(u64::MAX)).min(self.max)
216    }
217
218    /// How long the fire of the schedule `key` at `at` is delayed, when the occurrence after
219    /// it is `next`: the schedule's share of [`window`](Self::window), rounded down to whole
220    /// milliseconds, so stores that keep milliseconds agree on it.
221    pub fn offset(&self, key: &str, at: DateTime<Utc>, next: Option<DateTime<Utc>>) -> Duration {
222        let window = self.window(at, next).as_nanos();
223        let share = u128::from(mix(fnv1a(self.seed ^ FNV_OFFSET, key.as_bytes())));
224        // `share / 2^64` is in [0, 1), so the offset is strictly inside the window.
225        let nanos = (window * share) >> 64;
226        Duration::from_millis(u64::try_from(nanos / 1_000_000).unwrap_or(u64::MAX))
227    }
228
229    /// [`offset`](Self::offset) with the next occurrence read from `spec`; zero when `spec`
230    /// has none or cannot be evaluated.
231    pub fn offset_in(&self, spec: &ScheduleSpec, key: &str, at: DateTime<Utc>) -> Duration {
232        self.offset(key, at, spec.next_after(at).ok().flatten())
233    }
234}
235
236const FNV_OFFSET: u64 = 0xcbf2_9ce4_8422_2325;
237
238/// FNV-1a over `bytes` from `state`: stable across processes and platforms, unlike the
239/// standard library's randomly keyed hasher.
240fn fnv1a(mut state: u64, bytes: &[u8]) -> u64 {
241    for byte in bytes {
242        state ^= u64::from(*byte);
243        state = state.wrapping_mul(0x0100_0000_01b3);
244    }
245    state
246}
247
248/// The murmur3 finalizer: spreads a change in any bit of `hash` over all of them, so keys
249/// that differ in one character get unrelated shares.
250fn mix(mut hash: u64) -> u64 {
251    hash ^= hash >> 33;
252    hash = hash.wrapping_mul(0xff51_afd7_ed55_8ccd);
253    hash ^= hash >> 33;
254    hash = hash.wrapping_mul(0xc4ce_b9fe_1a85_ec53);
255    hash ^ (hash >> 33)
256}
257
258/// A schedule and the run template it enqueues.
259///
260/// # Example
261///
262/// ```rust
263/// use adk_core::run_store::NewRun;
264/// use adk_core::schedule::{MissedFirePolicy, Schedule, ScheduleSpec};
265/// use chrono::{TimeZone, Utc};
266///
267/// let at = Utc.with_ymd_and_hms(2026, 10, 15, 9, 0, 0).unwrap();
268/// let schedule = Schedule::new(
269///     "nightly-report",
270///     ScheduleSpec::At(at),
271///     NewRun::new("default", "reports", "system", "report_agent", serde_json::json!({})),
272///     MissedFirePolicy::FireOnce,
273/// )
274/// .with_next_fire_at(at);
275/// let run = schedule.run_for(at);
276/// assert_eq!(run.idempotency_key.as_deref(), Some("schedule:nightly-report:2026-10-15T09:00:00Z"));
277/// assert_eq!(
278///     run.principal.unwrap().on_behalf_of,
279///     Some(adk_core::SubjectRef::service("system"))
280/// );
281/// ```
282#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
283#[serde(rename_all = "camelCase")]
284pub struct Schedule {
285    /// The schedule identifier.
286    pub id: String,
287    /// When the schedule fires.
288    pub spec: ScheduleSpec,
289    /// The run each firing enqueues; its idempotency key is replaced per firing.
290    pub run: NewRun,
291    /// Which due occurrences fire when several are due at once.
292    pub missed: MissedFirePolicy,
293    /// A paused schedule is never due.
294    pub paused: bool,
295    /// The next occurrence to fire; `None` when the schedule has no more occurrences.
296    #[serde(default, skip_serializing_if = "Option::is_none")]
297    pub next_fire_at: Option<DateTime<Utc>>,
298    /// Set by the store; increases by one on every change.
299    pub revision: u64,
300}
301
302impl Schedule {
303    /// Creates an unpaused schedule with no next fire time and revision 0.
304    pub fn new(
305        id: impl Into<String>,
306        spec: ScheduleSpec,
307        run: NewRun,
308        missed: MissedFirePolicy,
309    ) -> Self {
310        Self { id: id.into(), spec, run, missed, paused: false, next_fire_at: None, revision: 0 }
311    }
312
313    /// Sets the next fire time.
314    pub fn with_next_fire_at(mut self, at: DateTime<Utc>) -> Self {
315        self.next_fire_at = Some(at);
316        self
317    }
318
319    /// Sets whether the schedule is paused.
320    pub fn with_paused(mut self, paused: bool) -> Self {
321        self.paused = paused;
322        self
323    }
324
325    /// Returns the run to enqueue for `fire_time`, keyed by [`firing_idempotency_key`].
326    ///
327    /// The run acts for its user as a service ([`NewRun::with_service_subject`]).
328    pub fn run_for(&self, fire_time: DateTime<Utc>) -> NewRun {
329        let mut run = self.run.clone().with_service_subject();
330        run.idempotency_key = Some(firing_idempotency_key(&self.id, fire_time));
331        run
332    }
333
334    /// Returns the run a manual "run now" of this schedule enqueues for `request_id`, keyed
335    /// by [`manual_idempotency_key`]: the template a fire enqueues, with its concurrency key,
336    /// so a run now and a fire are subject to the same overlap rule. The schedule itself is
337    /// not changed: its next fire time and revision stay where they are.
338    ///
339    /// # Example
340    ///
341    /// ```rust
342    /// use std::time::Duration;
343    /// use adk_core::run_store::NewRun;
344    /// use adk_core::schedule::{MissedFirePolicy, Schedule, ScheduleSpec};
345    ///
346    /// let schedule = Schedule::new(
347    ///     "nightly-report",
348    ///     ScheduleSpec::Every(Duration::from_secs(3600)),
349    ///     NewRun::new("default", "reports", "system", "report_agent", serde_json::json!({})),
350    ///     MissedFirePolicy::FireOnce,
351    /// );
352    /// let run = schedule.run_now("req-1");
353    /// assert_eq!(run.idempotency_key.as_deref(), Some("schedule:nightly-report:manual:req-1"));
354    /// ```
355    pub fn run_now(&self, request_id: &str) -> NewRun {
356        let mut run = self.run.clone().with_service_subject();
357        run.idempotency_key = Some(manual_idempotency_key(&self.id, request_id));
358        run
359    }
360
361    /// Checks the fields every store requires: a non-empty id, a valid run template, a
362    /// positive interval, and a positive catch-up count. Cron syntax is checked by
363    /// [`ScheduleSpec::next_after`].
364    ///
365    /// # Errors
366    ///
367    /// Returns [`INVALID_SCHEDULE_CODE`], or the run template's validation error.
368    pub fn validate(&self) -> Result<()> {
369        if self.id.is_empty() {
370            return Err(invalid_schedule_error("id must not be empty"));
371        }
372        if matches!(self.spec, ScheduleSpec::Every(interval) if interval.is_zero()) {
373            return Err(invalid_schedule_error("an Every interval must be greater than zero"));
374        }
375        if self.missed == MissedFirePolicy::CatchUp(0) {
376            return Err(invalid_schedule_error("CatchUp must fire at least one occurrence"));
377        }
378        self.run.validate()
379    }
380
381    fn same_definition(&self, other: &Self) -> bool {
382        self.spec == other.spec
383            && self.run == other.run
384            && self.missed == other.missed
385            && self.paused == other.paused
386            && self.next_fire_at == other.next_fire_at
387    }
388}
389
390/// Returns the idempotency key of the run a schedule enqueues for one fire time:
391/// `schedule:{id}:{fire_time RFC 3339}`, in UTC with the shortest exact fraction.
392///
393/// # Example
394///
395/// ```rust
396/// use chrono::{TimeZone, Utc};
397///
398/// let at = Utc.with_ymd_and_hms(2026, 10, 15, 9, 0, 0).unwrap();
399/// assert_eq!(adk_core::schedule::firing_idempotency_key("daily", at), "schedule:daily:2026-10-15T09:00:00Z");
400/// ```
401pub fn firing_idempotency_key(schedule_id: &str, fire_time: DateTime<Utc>) -> String {
402    format!("schedule:{schedule_id}:{}", fire_time.to_rfc3339_opts(SecondsFormat::AutoSi, true))
403}
404
405/// Returns the idempotency key of the run a manual "run now" of a schedule enqueues:
406/// `schedule:{id}:manual:{request id}`. A fire's key ends in a timestamp, which starts with a
407/// digit, so the two never collide; a retried request with the same id enqueues nothing new.
408///
409/// # Example
410///
411/// ```rust
412/// assert_eq!(adk_core::schedule::manual_idempotency_key("daily", "req-1"), "schedule:daily:manual:req-1");
413/// ```
414pub fn manual_idempotency_key(schedule_id: &str, request_id: &str) -> String {
415    format!("schedule:{schedule_id}:manual:{request_id}")
416}
417
418/// The fire times a scheduler enqueues for one due schedule, and where it moves next.
419#[derive(Debug, Clone, PartialEq, Eq)]
420pub struct FirePlan {
421    /// The occurrences to fire, oldest first.
422    pub fire_times: Vec<DateTime<Utc>>,
423    /// The first occurrence after `now`, for [`ScheduleStore::advance`].
424    pub next_fire_at: Option<DateTime<Utc>>,
425}
426
427/// Plans the firings of a schedule that is due at `due_at`, as seen at `now`.
428///
429/// `due_at` (the schedule's stored `next_fire_at`) is itself an occurrence; the others
430/// follow from `spec`. Occurrences in `[due_at, now]` are due, and `missed` picks which
431/// fire (see the [module documentation](crate::schedule)). `grace` bounds lateness
432/// under [`MissedFirePolicy::Skip`]. When `due_at` is after `now` nothing fires and
433/// the schedule stays at `due_at`.
434///
435/// # Example
436///
437/// ```rust
438/// use std::time::Duration;
439/// use adk_core::schedule::{plan_fires, MissedFirePolicy, ScheduleSpec, DEFAULT_MISFIRE_GRACE};
440/// use chrono::{TimeZone, Utc};
441///
442/// let due = Utc.with_ymd_and_hms(2026, 10, 15, 9, 0, 0).unwrap();
443/// let now = due + chrono::Duration::minutes(35);
444/// let plan = plan_fires(&ScheduleSpec::Every(Duration::from_secs(600)), MissedFirePolicy::CatchUp(2), due, now, DEFAULT_MISFIRE_GRACE)?;
445/// assert_eq!(plan.fire_times, vec![due + chrono::Duration::minutes(20), due + chrono::Duration::minutes(30)]);
446/// assert_eq!(plan.next_fire_at, Some(due + chrono::Duration::minutes(40)));
447/// # Ok::<(), adk_core::AdkError>(())
448/// ```
449///
450/// # Errors
451///
452/// Returns [`INVALID_SCHEDULE_CODE`] for an invalid cron expression, time zone,
453/// interval, or catch-up count, and `schedule.cron_unavailable` for a cron spec when
454/// the `cron` feature is off.
455pub fn plan_fires(
456    spec: &ScheduleSpec,
457    missed: MissedFirePolicy,
458    due_at: DateTime<Utc>,
459    now: DateTime<Utc>,
460    grace: Duration,
461) -> Result<FirePlan> {
462    if due_at > now {
463        return Ok(FirePlan { fire_times: Vec::new(), next_fire_at: Some(due_at) });
464    }
465    let wanted = match missed {
466        MissedFirePolicy::Skip | MissedFirePolicy::FireOnce => 1,
467        MissedFirePolicy::CatchUp(0) => {
468            return Err(invalid_schedule_error("CatchUp must fire at least one occurrence"));
469        }
470        MissedFirePolicy::CatchUp(count) => count as usize,
471    };
472    let mut plan = match spec {
473        ScheduleSpec::At(_) => FirePlan { fire_times: vec![due_at], next_fire_at: None },
474        ScheduleSpec::Every(interval) => {
475            let step = chrono::Duration::from_std(*interval)
476                .ok()
477                .filter(|step| *step > chrono::Duration::zero())
478                .ok_or_else(|| invalid_schedule_error("an Every interval must be positive"))?;
479            let step_nanos = step.num_nanoseconds().unwrap_or(i64::MAX).max(1);
480            let elapsed = (now - due_at).num_nanoseconds().unwrap_or(i64::MAX);
481            let latest = elapsed / step_nanos;
482            let first = (latest - wanted as i64 + 1).max(0);
483            let at = |k: i64| {
484                due_at
485                    .checked_add_signed(chrono::Duration::nanoseconds(k.saturating_mul(step_nanos)))
486            };
487            FirePlan {
488                fire_times: (first..=latest).filter_map(at).collect(),
489                next_fire_at: at(latest + 1),
490            }
491        }
492        ScheduleSpec::Cron { expr, timezone } => {
493            cron::latest_and_next(expr, timezone, due_at, now, wanted)?
494        }
495    };
496    if missed == MissedFirePolicy::Skip {
497        let late = plan
498            .fire_times
499            .last()
500            .is_some_and(|last| (now - *last).to_std().unwrap_or_default() > grace);
501        if late {
502            plan.fire_times.clear();
503        }
504    }
505    Ok(plan)
506}
507
508impl ScheduleSpec {
509    /// Returns the first occurrence strictly after `after`; the first fire time of a new
510    /// schedule is `spec.next_after(now)` (or the instant itself for [`ScheduleSpec::At`]).
511    ///
512    /// For [`At`](Self::At) this is the instant when it is after `after`; for
513    /// [`Every`](Self::Every) it is `after + interval`.
514    ///
515    /// # Example
516    ///
517    /// ```rust
518    /// use std::time::Duration;
519    /// use adk_core::schedule::ScheduleSpec;
520    /// use chrono::{TimeZone, Utc};
521    ///
522    /// let now = Utc.with_ymd_and_hms(2026, 10, 15, 9, 0, 0).unwrap();
523    /// let next = ScheduleSpec::Every(Duration::from_secs(60)).next_after(now)?;
524    /// assert_eq!(next, Some(Utc.with_ymd_and_hms(2026, 10, 15, 9, 1, 0).unwrap()));
525    /// # Ok::<(), adk_core::AdkError>(())
526    /// ```
527    ///
528    /// # Errors
529    ///
530    /// Same as [`plan_fires`].
531    pub fn next_after(&self, after: DateTime<Utc>) -> Result<Option<DateTime<Utc>>> {
532        match self {
533            Self::At(at) => Ok((*at > after).then_some(*at)),
534            Self::Every(interval) => chrono::Duration::from_std(*interval)
535                .ok()
536                .filter(|step| *step > chrono::Duration::zero())
537                .map(|step| after.checked_add_signed(step))
538                .ok_or_else(|| invalid_schedule_error("an Every interval must be positive")),
539            Self::Cron { expr, timezone } => {
540                Ok(cron::latest_and_next(expr, timezone, after, after, 0)?.next_fire_at)
541            }
542        }
543    }
544}
545
546#[cfg(feature = "cron")]
547mod cron {
548    use std::str::FromStr;
549
550    use chrono::{DateTime, LocalResult, TimeZone, Utc};
551    use chrono_tz::Tz;
552
553    use super::invalid_schedule_error;
554    use crate::Result;
555
556    fn parse(expr: &str, timezone: &str) -> Result<(::cron::Schedule, Tz)> {
557        let fields: Vec<&str> = expr.split_whitespace().collect();
558        let expanded = match fields.as_slice() {
559            // The crate counts 1 as Sunday, so a five-field weekday reaches it as day names.
560            [minute, hour, day, month, weekday] => {
561                let weekday = unix_weekdays(weekday).map_err(|reason| {
562                    invalid_schedule_error(&format!(
563                        "cron expression '{expr}' does not parse: the day of the week \
564                         '{weekday}' {reason}"
565                    ))
566                })?;
567                format!("0 {minute} {hour} {day} {month} {weekday}")
568            }
569            _ => expr.to_string(),
570        };
571        let schedule = ::cron::Schedule::from_str(&expanded).map_err(|error| {
572            invalid_schedule_error(&format!("cron expression '{expr}' does not parse: {error}"))
573        })?;
574        let tz = timezone.parse::<Tz>().map_err(|_| {
575            invalid_schedule_error(&format!(
576                "time zone '{timezone}' is not an IANA name such as 'UTC' or 'Europe/Berlin'"
577            ))
578        })?;
579        Ok((schedule, tz))
580    }
581
582    /// The day names a five-field day-of-week `field` selects under Unix numbering — 0 and 7
583    /// are Sunday, 1 to 6 Monday to Saturday — as a list the `cron` crate reads; `*` and `?`
584    /// unchanged. `Err` says why the field does not parse.
585    fn unix_weekdays(field: &str) -> std::result::Result<String, String> {
586        const NAMES: [&str; 7] = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
587        if field == "*" || field == "?" {
588            return Ok(field.to_string());
589        }
590        let day = |text: &str| -> std::result::Result<usize, String> {
591            if let Ok(number) = text.parse::<usize>() {
592                return match number {
593                    0..=7 => Ok(number),
594                    _ => Err(format!("names day {number}; days are 0 to 7, 0 and 7 Sunday")),
595                };
596            }
597            match text.to_ascii_lowercase().as_str() {
598                "sun" | "sunday" => Ok(0),
599                "mon" | "monday" => Ok(1),
600                "tue" | "tues" | "tuesday" => Ok(2),
601                "wed" | "wednesday" => Ok(3),
602                "thu" | "thurs" | "thursday" => Ok(4),
603                "fri" | "friday" => Ok(5),
604                "sat" | "saturday" => Ok(6),
605                _ => Err(format!("holds '{text}', which is neither a day number nor a day name")),
606            }
607        };
608        let mut selected = [false; 7];
609        for part in field.split(',') {
610            let (base, step) = match part.split_once('/') {
611                Some((base, step)) => match step.parse::<usize>() {
612                    Ok(step) if step > 0 => (base, Some(step)),
613                    _ => return Err(format!("has the step '{step}'; a step is 1 or more")),
614                },
615                None => (part, None),
616            };
617            // A day with a step runs to the end of the week, as `*` spans all of it.
618            let (start, end) = match (base, base.split_once('-')) {
619                ("*" | "?", _) => (0, 7),
620                (_, Some((start, end))) => (day(start)?, day(end)?),
621                (_, None) => {
622                    let start = day(base)?;
623                    (start, if step.is_some() { 7 } else { start })
624                }
625            };
626            if start > end {
627                return Err(format!("has the range '{base}', which runs backwards"));
628            }
629            for value in (start..=end).step_by(step.unwrap_or(1)) {
630                selected[value % 7] = true;
631            }
632        }
633        let names: Vec<&str> =
634            NAMES.iter().zip(selected).filter_map(|(name, on)| on.then_some(*name)).collect();
635        Ok(names.join(","))
636    }
637
638    /// The later instant of a local time repeated by a fall-back change is skipped, so
639    /// each local time fires once.
640    fn is_repeat(at: &DateTime<Tz>) -> bool {
641        matches!(at.timezone().from_local_datetime(&at.naive_local()), LocalResult::Ambiguous(first, _) if first != *at)
642    }
643
644    /// Returns up to `wanted` occurrences in `[due_at, now]` (always including `due_at`),
645    /// oldest first, and the first occurrence after `now`.
646    pub(super) fn latest_and_next(
647        expr: &str,
648        timezone: &str,
649        due_at: DateTime<Utc>,
650        now: DateTime<Utc>,
651        wanted: usize,
652    ) -> Result<super::FirePlan> {
653        let (schedule, tz) = parse(expr, timezone)?;
654        let next = schedule
655            .after(&now.with_timezone(&tz))
656            .find(|at| !is_repeat(at))
657            .map(|at| at.with_timezone(&Utc));
658        let mut latest = Vec::with_capacity(wanted);
659        // Walks back from just past `now`, so the cost is the number of fires kept.
660        let start = (now + chrono::Duration::seconds(1)).with_timezone(&tz);
661        for at in schedule.after(&start).rev() {
662            if latest.len() >= wanted {
663                break;
664            }
665            let at = at.with_timezone(&Utc);
666            if at <= due_at {
667                break;
668            }
669            if at <= now && !is_repeat(&at.with_timezone(&tz)) {
670                latest.push(at);
671            }
672        }
673        if latest.len() < wanted {
674            latest.push(due_at);
675        }
676        latest.reverse();
677        Ok(super::FirePlan { fire_times: latest, next_fire_at: next })
678    }
679}
680
681#[cfg(not(feature = "cron"))]
682mod cron {
683    use chrono::{DateTime, Utc};
684
685    use crate::{AdkError, ErrorCategory, ErrorComponent, Result};
686
687    pub(super) fn latest_and_next(
688        _expr: &str,
689        _timezone: &str,
690        _due_at: DateTime<Utc>,
691        _now: DateTime<Utc>,
692        _wanted: usize,
693    ) -> Result<super::FirePlan> {
694        Err(AdkError::new(
695            ErrorComponent::Agent,
696            ErrorCategory::Unsupported,
697            "schedule.cron_unavailable",
698            "cron schedules need the `cron` feature of adk-core; enable it in Cargo.toml",
699        ))
700    }
701}
702
703/// Stores schedules and lets one replica at a time advance each.
704///
705/// Every backend passes `adk_core::schedule_store_conformance_tests!` (feature `conformance`).
706#[async_trait]
707pub trait ScheduleStore: Send + Sync {
708    /// Inserts or replaces the schedule with `schedule.id` and returns the stored one.
709    ///
710    /// The store assigns the revision: 1 on insert, the previous revision plus one on a
711    /// change. Upserting a definition identical to the stored one (spec, run, missed
712    /// policy, paused flag, next fire time) changes nothing, so replicas registering the
713    /// same schedule at startup do not disturb an advance in flight.
714    ///
715    /// # Errors
716    ///
717    /// Returns the [`Schedule::validate`] error.
718    async fn upsert(&self, schedule: Schedule) -> Result<Schedule>;
719
720    /// Returns a schedule, or `None` when it does not exist.
721    async fn get(&self, id: &str) -> Result<Option<Schedule>>;
722
723    /// Returns every schedule, ordered by id.
724    async fn list(&self) -> Result<Vec<Schedule>>;
725
726    /// Deletes a schedule.
727    ///
728    /// # Errors
729    ///
730    /// Returns [`SCHEDULE_NOT_FOUND_CODE`] for an unknown schedule.
731    async fn delete(&self, id: &str) -> Result<()>;
732
733    /// Pauses or resumes a schedule and returns it; the revision moves only on a change.
734    ///
735    /// # Errors
736    ///
737    /// Returns [`SCHEDULE_NOT_FOUND_CODE`] for an unknown schedule.
738    async fn set_paused(&self, id: &str, paused: bool) -> Result<Schedule>;
739
740    /// Returns up to `limit` unpaused schedules whose `next_fire_at` is at or before
741    /// `now`, earliest first, ties by id.
742    async fn due(&self, now: DateTime<Utc>, limit: usize) -> Result<Vec<Schedule>>;
743
744    /// Sets `next_fire_at` when the stored revision equals `expected_revision`, and
745    /// returns `false` when another replica advanced or changed the schedule first.
746    ///
747    /// # Errors
748    ///
749    /// Returns [`SCHEDULE_NOT_FOUND_CODE`] for an unknown schedule.
750    async fn advance(
751        &self,
752        id: &str,
753        expected_revision: u64,
754        next_fire_at: Option<DateTime<Utc>>,
755    ) -> Result<bool>;
756}
757
758/// Builds the error a schedule store returns for an unknown schedule.
759///
760/// # Example
761///
762/// ```rust
763/// assert!(adk_core::schedule::schedule_not_found_error("daily").is_not_found());
764/// ```
765pub fn schedule_not_found_error(id: &str) -> AdkError {
766    AdkError::not_found(
767        ErrorComponent::Agent,
768        SCHEDULE_NOT_FOUND_CODE,
769        format!("schedule store has no schedule '{id}'; upsert it first"),
770    )
771}
772
773/// Builds the error returned for an invalid schedule.
774///
775/// # Example
776///
777/// ```rust
778/// let error = adk_core::schedule::invalid_schedule_error("id must not be empty");
779/// assert_eq!(error.code, adk_core::schedule::INVALID_SCHEDULE_CODE);
780/// ```
781pub fn invalid_schedule_error(reason: &str) -> AdkError {
782    AdkError::new(
783        ErrorComponent::Agent,
784        ErrorCategory::InvalidInput,
785        INVALID_SCHEDULE_CODE,
786        format!("invalid schedule: {reason}"),
787    )
788}
789
790/// Process-local [`ScheduleStore`].
791///
792/// Holds no time-dependent state, so it takes no clock: [`due`](ScheduleStore::due)
793/// receives the time from the scheduler.
794///
795/// # Example
796///
797/// ```rust
798/// use std::time::Duration;
799/// use adk_core::run_store::NewRun;
800/// use adk_core::schedule::{InMemoryScheduleStore, MissedFirePolicy, Schedule, ScheduleSpec, ScheduleStore};
801/// use chrono::Utc;
802///
803/// # futures::executor::block_on(async {
804/// let store = InMemoryScheduleStore::new();
805/// let now = Utc::now();
806/// let schedule = Schedule::new(
807///     "heartbeat",
808///     ScheduleSpec::Every(Duration::from_secs(60)),
809///     NewRun::new("default", "ops", "system", "probe", serde_json::json!({})),
810///     MissedFirePolicy::Skip,
811/// )
812/// .with_next_fire_at(now);
813/// let stored = store.upsert(schedule).await?;
814/// assert_eq!(store.due(now, 10).await?.len(), 1);
815/// assert!(store.advance("heartbeat", stored.revision, Some(now + chrono::Duration::minutes(1))).await?);
816/// # Ok::<(), adk_core::AdkError>(())
817/// # }).unwrap();
818/// ```
819#[derive(Debug, Default)]
820pub struct InMemoryScheduleStore {
821    schedules: Mutex<BTreeMap<String, Schedule>>,
822}
823
824impl InMemoryScheduleStore {
825    /// Creates an empty store.
826    pub fn new() -> Self {
827        Self::default()
828    }
829}
830
831#[async_trait]
832impl ScheduleStore for InMemoryScheduleStore {
833    async fn upsert(&self, mut schedule: Schedule) -> Result<Schedule> {
834        schedule.validate()?;
835        let mut schedules = self.schedules.lock().await;
836        if let Some(existing) = schedules.get(&schedule.id) {
837            if existing.same_definition(&schedule) {
838                return Ok(existing.clone());
839            }
840            schedule.revision = existing.revision + 1;
841        } else {
842            schedule.revision = 1;
843        }
844        schedules.insert(schedule.id.clone(), schedule.clone());
845        Ok(schedule)
846    }
847
848    async fn get(&self, id: &str) -> Result<Option<Schedule>> {
849        Ok(self.schedules.lock().await.get(id).cloned())
850    }
851
852    async fn list(&self) -> Result<Vec<Schedule>> {
853        Ok(self.schedules.lock().await.values().cloned().collect())
854    }
855
856    async fn delete(&self, id: &str) -> Result<()> {
857        self.schedules
858            .lock()
859            .await
860            .remove(id)
861            .map(|_| ())
862            .ok_or_else(|| schedule_not_found_error(id))
863    }
864
865    async fn set_paused(&self, id: &str, paused: bool) -> Result<Schedule> {
866        let mut schedules = self.schedules.lock().await;
867        let schedule = schedules.get_mut(id).ok_or_else(|| schedule_not_found_error(id))?;
868        if schedule.paused != paused {
869            schedule.paused = paused;
870            schedule.revision += 1;
871        }
872        Ok(schedule.clone())
873    }
874
875    async fn due(&self, now: DateTime<Utc>, limit: usize) -> Result<Vec<Schedule>> {
876        let schedules = self.schedules.lock().await;
877        let mut due: Vec<_> = schedules
878            .values()
879            .filter(|schedule| {
880                !schedule.paused && schedule.next_fire_at.is_some_and(|at| at <= now)
881            })
882            .cloned()
883            .collect();
884        due.sort_by(|a, b| (a.next_fire_at, &a.id).cmp(&(b.next_fire_at, &b.id)));
885        due.truncate(limit);
886        Ok(due)
887    }
888
889    async fn advance(
890        &self,
891        id: &str,
892        expected_revision: u64,
893        next_fire_at: Option<DateTime<Utc>>,
894    ) -> Result<bool> {
895        let mut schedules = self.schedules.lock().await;
896        let schedule = schedules.get_mut(id).ok_or_else(|| schedule_not_found_error(id))?;
897        if schedule.revision != expected_revision {
898            return Ok(false);
899        }
900        schedule.next_fire_at = next_fire_at;
901        schedule.revision += 1;
902        Ok(true)
903    }
904}
905
906#[cfg(test)]
907mod tests {
908    use super::*;
909    use chrono::TimeZone;
910
911    fn at(day: u32, hour: u32, minute: u32) -> DateTime<Utc> {
912        Utc.with_ymd_and_hms(2026, 10, day, hour, minute, 0).single().unwrap()
913    }
914
915    #[test]
916    fn every_policies() {
917        let spec = ScheduleSpec::Every(Duration::from_secs(600));
918        let due = at(15, 9, 0);
919        let now = at(15, 9, 35);
920        let grace = DEFAULT_MISFIRE_GRACE;
921        let plan = |missed| plan_fires(&spec, missed, due, now, grace).unwrap();
922        let next = Some(at(15, 9, 40));
923        assert_eq!(
924            plan(MissedFirePolicy::FireOnce),
925            FirePlan { fire_times: vec![at(15, 9, 30)], next_fire_at: next }
926        );
927        assert_eq!(
928            plan(MissedFirePolicy::Skip),
929            FirePlan { fire_times: vec![], next_fire_at: next }
930        );
931        assert_eq!(
932            plan(MissedFirePolicy::CatchUp(10)),
933            FirePlan {
934                fire_times: vec![at(15, 9, 0), at(15, 9, 10), at(15, 9, 20), at(15, 9, 30)],
935                next_fire_at: next
936            }
937        );
938        let on_time = plan_fires(&spec, MissedFirePolicy::Skip, due, at(15, 9, 0), grace).unwrap();
939        assert_eq!(on_time, FirePlan { fire_times: vec![due], next_fire_at: Some(at(15, 9, 10)) });
940        let early = plan_fires(&spec, MissedFirePolicy::Skip, due, at(15, 8, 0), grace).unwrap();
941        assert_eq!(early, FirePlan { fire_times: vec![], next_fire_at: Some(due) });
942    }
943
944    #[test]
945    fn at_fires_once() {
946        let due = at(15, 9, 0);
947        let plan = plan_fires(
948            &ScheduleSpec::At(due),
949            MissedFirePolicy::FireOnce,
950            due,
951            at(15, 12, 0),
952            DEFAULT_MISFIRE_GRACE,
953        )
954        .unwrap();
955        assert_eq!(plan, FirePlan { fire_times: vec![due], next_fire_at: None });
956        assert_eq!(ScheduleSpec::At(due).next_after(at(15, 8, 0)).unwrap(), Some(due));
957        assert_eq!(ScheduleSpec::At(due).next_after(due).unwrap(), None);
958    }
959
960    #[test]
961    fn invalid_specs_are_refused() {
962        let zero = ScheduleSpec::Every(Duration::ZERO);
963        assert_eq!(zero.next_after(at(15, 0, 0)).unwrap_err().code, INVALID_SCHEDULE_CODE);
964        let error = plan_fires(
965            &ScheduleSpec::At(at(15, 0, 0)),
966            MissedFirePolicy::CatchUp(0),
967            at(15, 0, 0),
968            at(15, 0, 0),
969            DEFAULT_MISFIRE_GRACE,
970        )
971        .unwrap_err();
972        assert_eq!(error.code, INVALID_SCHEDULE_CODE);
973    }
974
975    #[test]
976    fn firing_keys_are_canonical() {
977        let fractional = at(15, 9, 0) + chrono::Duration::milliseconds(250);
978        assert_eq!(
979            firing_idempotency_key("a:b/ü", fractional),
980            "schedule:a:b/ü:2026-10-15T09:00:00.250Z"
981        );
982    }
983
984    #[cfg(feature = "cron")]
985    mod cron_specs {
986        use super::*;
987
988        fn cron(expr: &str, timezone: &str) -> ScheduleSpec {
989            ScheduleSpec::Cron { expr: expr.into(), timezone: timezone.into() }
990        }
991
992        #[test]
993        fn five_and_six_field_expressions() {
994            let five = cron("*/15 * * * *", "UTC");
995            let six = cron("0 */15 * * * *", "UTC");
996            assert_eq!(five.next_after(at(15, 9, 1)).unwrap(), Some(at(15, 9, 15)));
997            assert_eq!(six.next_after(at(15, 9, 1)).unwrap(), Some(at(15, 9, 15)));
998        }
999
1000        /// The next `count` fire times after `from`.
1001        fn fires(spec: &ScheduleSpec, from: DateTime<Utc>, count: usize) -> Vec<DateTime<Utc>> {
1002            let mut cursor = from;
1003            let mut all = Vec::with_capacity(count);
1004            while all.len() < count {
1005                cursor = spec.next_after(cursor).unwrap().unwrap();
1006                all.push(cursor);
1007            }
1008            all
1009        }
1010
1011        // October 2026: the 18th and 25th are Sundays, the 24th and 31st Saturdays.
1012        #[test]
1013        fn five_fields_count_weekdays_as_unix_cron_does() {
1014            let weekdays = cron("0 9 * * 1-5", "UTC");
1015            assert_eq!(
1016                fires(&weekdays, at(18, 12, 0), 6),
1017                vec![
1018                    at(19, 9, 0),
1019                    at(20, 9, 0),
1020                    at(21, 9, 0),
1021                    at(22, 9, 0),
1022                    at(23, 9, 0),
1023                    at(26, 9, 0)
1024                ],
1025                "Monday to Friday, never Saturday or Sunday"
1026            );
1027            assert_eq!(weekdays.next_after(at(24, 10, 0)).unwrap(), Some(at(26, 9, 0)));
1028            assert_eq!(fires(&cron("0 9 * * Mon-Fri", "UTC"), at(18, 12, 0), 6), {
1029                fires(&weekdays, at(18, 12, 0), 6)
1030            });
1031        }
1032
1033        #[test]
1034        fn zero_and_seven_are_sunday_and_six_is_saturday() {
1035            for sunday in ["0", "7", "Sun", "0,7"] {
1036                let spec = cron(&format!("0 9 * * {sunday}"), "UTC");
1037                assert_eq!(
1038                    fires(&spec, at(23, 10, 0), 2),
1039                    vec![at(25, 9, 0), Utc.with_ymd_and_hms(2026, 11, 1, 9, 0, 0).unwrap()],
1040                    "{sunday}"
1041                );
1042            }
1043            let saturday = cron("0 9 * * 6", "UTC");
1044            assert_eq!(fires(&saturday, at(23, 10, 0), 2), vec![at(24, 9, 0), at(31, 9, 0)]);
1045            let weekend = cron("30 7 * * 6,0", "UTC");
1046            assert_eq!(
1047                fires(&weekend, at(23, 10, 0), 3),
1048                vec![at(24, 7, 30), at(25, 7, 30), at(31, 7, 30)]
1049            );
1050            // A range may end on 7.
1051            let friday_to_sunday = cron("0 9 * * 5-7", "UTC");
1052            assert_eq!(
1053                fires(&friday_to_sunday, at(22, 10, 0), 4),
1054                vec![at(23, 9, 0), at(24, 9, 0), at(25, 9, 0), at(30, 9, 0)]
1055            );
1056        }
1057
1058        #[test]
1059        fn five_field_weekday_steps() {
1060            // Monday, Wednesday and Friday.
1061            let odd = cron("0 9 * * 1-5/2", "UTC");
1062            assert_eq!(
1063                fires(&odd, at(25, 10, 0), 3),
1064                vec![at(26, 9, 0), at(28, 9, 0), at(30, 9, 0)]
1065            );
1066            // Sunday, Wednesday and Saturday.
1067            let every_third = cron("0 9 * * */3", "UTC");
1068            assert_eq!(
1069                fires(&every_third, at(24, 10, 0), 3),
1070                vec![at(25, 9, 0), at(28, 9, 0), at(31, 9, 0)]
1071            );
1072        }
1073
1074        #[test]
1075        fn six_and_seven_fields_keep_the_crates_numbering() {
1076            // 1 is Sunday, so 1-5 is Sunday to Thursday.
1077            let six = cron("0 0 9 * * 1-5", "UTC");
1078            assert_eq!(
1079                fires(&six, at(23, 10, 0), 5),
1080                vec![at(25, 9, 0), at(26, 9, 0), at(27, 9, 0), at(28, 9, 0), at(29, 9, 0)]
1081            );
1082            let seven = cron("0 0 9 * * 7 2026", "UTC");
1083            assert_eq!(seven.next_after(at(23, 10, 0)).unwrap(), Some(at(24, 9, 0)));
1084        }
1085
1086        #[test]
1087        fn bad_five_field_weekdays_are_refused() {
1088            for field in ["8", "5-1", "5L", "*/0", "MON#2", "1,", "Fri-Sun"] {
1089                let error =
1090                    cron(&format!("0 9 * * {field}"), "UTC").next_after(at(15, 0, 0)).unwrap_err();
1091                assert_eq!(error.code, INVALID_SCHEDULE_CODE, "{field}");
1092                assert!(error.message.contains("day of the week"), "{field}: {}", error.message);
1093            }
1094        }
1095
1096        #[test]
1097        fn catch_up_and_fire_once() {
1098            let spec = cron("0 * * * *", "UTC");
1099            let due = at(15, 9, 0);
1100            let now = at(15, 12, 30);
1101            let catch_up =
1102                plan_fires(&spec, MissedFirePolicy::CatchUp(3), due, now, DEFAULT_MISFIRE_GRACE)
1103                    .unwrap();
1104            assert_eq!(
1105                catch_up,
1106                FirePlan {
1107                    fire_times: vec![at(15, 10, 0), at(15, 11, 0), at(15, 12, 0)],
1108                    next_fire_at: Some(at(15, 13, 0))
1109                }
1110            );
1111            let all =
1112                plan_fires(&spec, MissedFirePolicy::CatchUp(100), due, now, DEFAULT_MISFIRE_GRACE)
1113                    .unwrap();
1114            assert_eq!(
1115                all.fire_times,
1116                vec![at(15, 9, 0), at(15, 10, 0), at(15, 11, 0), at(15, 12, 0)]
1117            );
1118            let once =
1119                plan_fires(&spec, MissedFirePolicy::FireOnce, due, now, DEFAULT_MISFIRE_GRACE)
1120                    .unwrap();
1121            assert_eq!(once.fire_times, vec![at(15, 12, 0)]);
1122            let skip =
1123                plan_fires(&spec, MissedFirePolicy::Skip, due, now, DEFAULT_MISFIRE_GRACE).unwrap();
1124            assert!(skip.fire_times.is_empty());
1125            let on_time =
1126                plan_fires(&spec, MissedFirePolicy::Skip, due, at(15, 9, 0), DEFAULT_MISFIRE_GRACE)
1127                    .unwrap();
1128            assert_eq!(on_time.fire_times, vec![due]);
1129        }
1130
1131        #[test]
1132        fn time_zones_and_daylight_saving() {
1133            // Berlin leaves summer time on 25 October 2026: 09:00 local is 07:00 UTC before, 08:00 after.
1134            let spec = cron("0 9 * * *", "Europe/Berlin");
1135            assert_eq!(spec.next_after(at(24, 0, 0)).unwrap(), Some(at(24, 7, 0)));
1136            assert_eq!(spec.next_after(at(25, 0, 0)).unwrap(), Some(at(25, 8, 0)));
1137
1138            // 02:30 local happens twice on 25 October and fires once, at the first instant (00:30 UTC).
1139            let repeated = cron("0 30 2 * * *", "Europe/Berlin");
1140            let first = Utc.with_ymd_and_hms(2026, 10, 25, 0, 30, 0).unwrap();
1141            assert_eq!(repeated.next_after(at(25, 0, 0)).unwrap(), Some(first));
1142            assert_eq!(
1143                repeated.next_after(first).unwrap(),
1144                Some(Utc.with_ymd_and_hms(2026, 10, 26, 1, 30, 0).unwrap())
1145            );
1146            let plan = plan_fires(
1147                &repeated,
1148                MissedFirePolicy::CatchUp(5),
1149                first,
1150                at(25, 12, 0),
1151                DEFAULT_MISFIRE_GRACE,
1152            )
1153            .unwrap();
1154            assert_eq!(plan.fire_times, vec![first]);
1155        }
1156
1157        #[test]
1158        fn bad_expressions_and_zones_are_refused() {
1159            assert_eq!(
1160                cron("not cron", "UTC").next_after(at(15, 0, 0)).unwrap_err().code,
1161                INVALID_SCHEDULE_CODE
1162            );
1163            assert_eq!(
1164                cron("* * * * *", "Mars/Olympus").next_after(at(15, 0, 0)).unwrap_err().code,
1165                INVALID_SCHEDULE_CODE
1166            );
1167        }
1168    }
1169
1170    mod jitter {
1171        use proptest::prelude::*;
1172
1173        use super::*;
1174
1175        #[test]
1176        fn a_fire_lands_before_the_next_occurrence() {
1177            let jitter = Jitter::new(90, Duration::from_secs(3600));
1178            assert_eq!(jitter.percent, Jitter::MAX_PERCENT, "clamped to half the gap");
1179            let at = at(15, 9, 0);
1180            let next = Some(at + chrono::Duration::minutes(10));
1181            assert_eq!(jitter.window(at, next), Duration::from_secs(300));
1182            for key in ["a", "b", "nightly", "report-17"] {
1183                assert!(jitter.offset(key, at, next) < Duration::from_secs(300));
1184            }
1185            assert_eq!(jitter.window(at, None), Duration::ZERO);
1186            assert_eq!(
1187                Jitter::new(0, Duration::from_secs(60)).offset("a", at, next),
1188                Duration::ZERO
1189            );
1190        }
1191
1192        #[test]
1193        fn the_default_caps_a_daily_schedule_at_nine_minutes() {
1194            let daily = ScheduleSpec::Cron { expr: "0 9 * * *".into(), timezone: "UTC".into() };
1195            let at = at(15, 9, 0);
1196            let jitter = Jitter::default();
1197            assert_eq!(jitter.window(at, daily.next_after(at).unwrap()), Jitter::DEFAULT_MAX);
1198            let every_minute = ScheduleSpec::Every(Duration::from_secs(60));
1199            assert_eq!(
1200                jitter.window(at, every_minute.next_after(at).unwrap()),
1201                Duration::from_secs(9),
1202                "15 percent of a minute"
1203            );
1204        }
1205
1206        #[test]
1207        fn schedules_and_salts_spread_apart() {
1208            let jitter = Jitter::new(50, Duration::from_secs(3600));
1209            let at = at(15, 9, 0);
1210            let next = Some(at + chrono::Duration::hours(2));
1211            let offsets: std::collections::BTreeSet<Duration> =
1212                (0..64).map(|n| jitter.offset(&format!("job-{n}"), at, next)).collect();
1213            assert!(offsets.len() > 60, "64 schedules take {} distinct offsets", offsets.len());
1214            let salted = jitter.salted("tenant-a");
1215            assert_ne!(salted.offset("job-1", at, next), jitter.offset("job-1", at, next));
1216            assert_eq!(salted, jitter.salted("tenant-a"), "a salt is deterministic");
1217        }
1218
1219        #[test]
1220        fn run_now_keeps_the_concurrency_key_and_leaves_the_schedule() {
1221            let run = NewRun::new("default", "ops", "system", "probe", serde_json::json!({}))
1222                .with_concurrency_key("cron:probe", crate::OnConflict::Reject);
1223            let schedule = Schedule::new(
1224                "probe",
1225                ScheduleSpec::Every(Duration::from_secs(60)),
1226                run,
1227                MissedFirePolicy::Skip,
1228            )
1229            .with_next_fire_at(at(15, 9, 0));
1230            let manual = schedule.run_now("r1");
1231            assert_eq!(manual.idempotency_key.as_deref(), Some("schedule:probe:manual:r1"));
1232            assert_eq!(manual.concurrency_key.as_deref(), Some("cron:probe"));
1233            assert_ne!(manual.idempotency_key, schedule.run_for(at(15, 9, 0)).idempotency_key);
1234        }
1235
1236        proptest! {
1237            #![proptest_config(ProptestConfig::with_cases(256))]
1238
1239            /// Every offset is below the window, the window at most `max` and half the gap,
1240            /// and the same key always takes the same offset.
1241            #[test]
1242            fn offsets_stay_inside_the_window(
1243                key in "[a-z0-9:-]{1,24}",
1244                percent in 0u8..=255,
1245                max_ms in 0u64..=86_400_000,
1246                gap_ms in 1i64..=7 * 86_400_000,
1247                seed in any::<u64>(),
1248            ) {
1249                let mut jitter = Jitter::new(percent, Duration::from_millis(max_ms));
1250                jitter.seed = seed;
1251                let at = at(15, 9, 0);
1252                let next = at + chrono::Duration::milliseconds(gap_ms);
1253                let window = jitter.window(at, Some(next));
1254                let offset = jitter.offset(&key, at, Some(next));
1255                prop_assert!(window <= Duration::from_millis(max_ms));
1256                prop_assert!(window.as_nanos() * 2 <= u128::from(gap_ms.unsigned_abs()) * 1_000_000);
1257                prop_assert!(offset <= window);
1258                prop_assert!(window.is_zero() || offset < window);
1259                prop_assert!(at + chrono::Duration::from_std(offset).unwrap() < next);
1260                prop_assert_eq!(offset, jitter.offset(&key, at, Some(next)));
1261            }
1262        }
1263    }
1264}