adk-core 3.0.0

Core traits and types for Rust Agent Development Kit (ADK-Rust) agents, tools, sessions, and events
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
//! Schedules that enqueue durable runs: cron, one-shot, and fixed-interval.
//!
//! A [`ScheduleStore`] keeps each [`Schedule`] with its next fire time and a revision.
//! A scheduler on any number of replicas polls [`due`](ScheduleStore::due), plans the
//! firings with [`plan_fires`], enqueues one run per fire time, and moves the schedule
//! on with [`advance`](ScheduleStore::advance) — a compare-and-swap on the revision.
//!
//! # Firing rule
//!
//! Every fire time enqueues a run whose idempotency key is
//! [`firing_idempotency_key`]`(id, fire_time)` = `schedule:{id}:{fire_time RFC 3339}`.
//! Replicas that plan the same fire time produce the same key, and the run store's
//! idempotent enqueue turns them into one run. The advance CAS then lets one replica
//! move the schedule on; the others see `false` and drop their plan. A replica that
//! crashes between enqueue and advance leaves the schedule due, and the next replica
//! re-plans the same fire times, which enqueue nothing new.
//!
//! # Missed fires
//!
//! When the scheduler falls behind (a restart, an outage), several occurrences can be
//! due at once. [`MissedFirePolicy`] picks which of them fire:
//!
//! | Policy | Fires |
//! |--------|-------|
//! | [`Skip`](MissedFirePolicy::Skip) | The latest due occurrence, only if it is no more than `grace` late; nothing otherwise |
//! | [`FireOnce`](MissedFirePolicy::FireOnce) | The latest due occurrence, however late |
//! | [`CatchUp(n)`](MissedFirePolicy::CatchUp) | The latest `n` due occurrences, oldest first |
//!
//! # Cron
//!
//! Cron expressions use the `cron` crate's syntax with an optional leading seconds
//! field: five fields (`min hour dom month dow`) or six or seven (`sec min hour dom
//! month dow [year]`). They are evaluated in the IANA time zone of the spec
//! (`chrono-tz`), so `0 9 * * Mon-Fri` in `Europe/Berlin` fires at 09:00 local time
//! across daylight-saving changes. A local time skipped by a spring-forward change does
//! not fire; a local time repeated by a fall-back change fires once, at its first
//! instant. Evaluating cron specs needs the `cron` feature of `adk-core`; without it
//! they fail with `schedule.cron_unavailable`.
//!
//! The day-of-week field counts days by the number of fields:
//!
//! | Expression | Sunday | Monday to Saturday | `1-5` fires |
//! |------------|--------|--------------------|-------------|
//! | Five fields | `0` or `7` | `1` to `6` | Monday to Friday |
//! | Six or seven fields | `1` | `2` to `7` | Sunday to Thursday |
//!
//! Five fields follow Unix cron; six and seven keep the `cron` crate's numbering. Day
//! names (`Mon-Fri`, `SAT,SUN`) mean the same days in both. A five-field day-of-week
//! field takes `*`, `?`, days, ranges, lists and steps (`*/2`, `1-5/2`). A day fires only
//! when it matches both the day-of-month and the day-of-week field.
//!
//! # Backend primitives
//!
//! | Operation | SQL | Redis | MongoDB | Neo4j, Firestore |
//! |-----------|-----|-------|---------|------------------|
//! | `advance` CAS | `UPDATE ... WHERE id = $1 AND revision = $2` | Lua compare of the revision field | `updateOne` filtered on `revision` | Transaction that checks the revision |
//! | `due` | Index on `(paused, next_fire_at)` | Sorted set of next fire times | Index on `nextFireAt` | Indexed query |

use std::collections::BTreeMap;
use std::time::Duration;

use async_trait::async_trait;
use chrono::{DateTime, SecondsFormat, Utc};
use serde::{Deserialize, Serialize};
use tokio::sync::Mutex;

use crate::run_store::NewRun;
use crate::{AdkError, ErrorCategory, ErrorComponent, Result};

/// Error code returned for an unknown schedule identifier.
pub const SCHEDULE_NOT_FOUND_CODE: &str = "schedule.not_found";
/// Error code returned for an invalid schedule or spec.
pub const INVALID_SCHEDULE_CODE: &str = "schedule.invalid";

/// How late an occurrence may fire under [`MissedFirePolicy::Skip`] by default.
pub const DEFAULT_MISFIRE_GRACE: Duration = Duration::from_secs(60);

/// When a schedule fires.
///
/// # Example
///
/// ```rust
/// use adk_core::schedule::ScheduleSpec;
///
/// let spec = ScheduleSpec::Cron { expr: "0 9 * * Mon-Fri".into(), timezone: "Europe/Berlin".into() };
/// assert_eq!(serde_json::to_value(&spec).unwrap()["cron"]["timezone"], "Europe/Berlin");
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub enum ScheduleSpec {
    /// A cron expression evaluated in an IANA time zone such as `UTC` or `America/New_York`.
    Cron {
        /// The cron expression (five, six, or seven fields). Five fields count the days of
        /// the week as Unix cron does (0 and 7 are Sunday); six and seven as the `cron`
        /// crate does (1 is Sunday). See the [module documentation](crate::schedule).
        expr: String,
        /// The IANA time zone name.
        timezone: String,
    },
    /// Once, at this instant.
    At(DateTime<Utc>),
    /// Repeatedly, this far apart, counted from the first fire time.
    Every(Duration),
}

/// Which due occurrences fire when several are due at once.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub enum MissedFirePolicy {
    /// Fire the latest occurrence only when it is on time.
    Skip,
    /// Fire the latest occurrence, however late.
    FireOnce,
    /// Fire up to this many of the latest occurrences, oldest first; at least 1.
    CatchUp(u32),
}

/// Spreads the fires of schedules that share a cadence, so a fleet of schedules on
/// `0 * * * *` does not start every run in the same second.
///
/// Each fire is delayed by an offset that is a fixed share of a window, the share derived
/// from the schedule's key and the jitter's [`seed`](Self::seed): the same schedule is
/// delayed by the same share on every replica and after every restart, and two schedules
/// are usually delayed by different shares. The window is [`percent`](Self::percent) of the
/// gap to the next occurrence, at most [`max`](Self::max):
///
/// | Field | Bound |
/// |-------|-------|
/// | `percent` | 0 to 50; `new` clamps a larger value to 50 |
/// | `max` | Any duration; the window is never longer |
/// | offset | `0 <= offset < window <= gap / 2`, in whole milliseconds |
///
/// A delayed fire therefore lands before the next occurrence is due. The occurrence keeps
/// its scheduled time as its identity — its idempotency key, its watermark and the
/// missed-fire plan all use the scheduled time — so jitter moves when a fire runs, never
/// which fires run. A one-shot [`ScheduleSpec::At`] has no next occurrence and is not
/// delayed.
///
/// [`Jitter::default`] is 15 percent of the gap, at most nine minutes. Schedulers apply no
/// jitter unless one is configured.
///
/// # Example
///
/// ```rust
/// use std::time::Duration;
/// use adk_core::schedule::{Jitter, ScheduleSpec};
/// use chrono::{TimeZone, Utc};
///
/// let jitter = Jitter::new(15, Duration::from_secs(9 * 60));
/// let at = Utc.with_ymd_and_hms(2026, 11, 18, 9, 0, 0).unwrap();
/// let hourly = ScheduleSpec::Cron { expr: "0 * * * *".into(), timezone: "UTC".into() };
/// let offset = jitter.offset_in(&hourly, "nightly-report", at);
/// assert!(offset < Duration::from_secs(9 * 60));
/// assert_eq!(offset, jitter.offset_in(&hourly, "nightly-report", at), "deterministic");
/// assert_eq!(jitter.offset_in(&ScheduleSpec::At(at), "once", at), Duration::ZERO);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct Jitter {
    /// The share of the gap to the next occurrence a fire may be delayed by, in percent.
    pub percent: u8,
    /// The longest a fire is delayed, whatever the gap.
    pub max: Duration,
    /// Folded into every schedule's share, so deployments that name their schedules alike
    /// spread differently ([`salted`](Self::salted)).
    pub seed: u64,
}

impl Default for Jitter {
    /// 15 percent of the gap to the next occurrence, at most nine minutes.
    fn default() -> Self {
        Self::new(Self::DEFAULT_PERCENT, Self::DEFAULT_MAX)
    }
}

impl Jitter {
    /// The share of [`Jitter::default`], in percent.
    pub const DEFAULT_PERCENT: u8 = 15;
    /// The longest delay of [`Jitter::default`].
    pub const DEFAULT_MAX: Duration = Duration::from_secs(9 * 60);
    /// The largest share a jitter takes, so a delayed fire stays clear of the next one.
    pub const MAX_PERCENT: u8 = 50;

    /// A jitter of `percent` of the gap to the next occurrence, at most `max`; `percent`
    /// above [`MAX_PERCENT`](Self::MAX_PERCENT) is clamped to it.
    pub fn new(percent: u8, max: Duration) -> Self {
        Self { percent: percent.min(Self::MAX_PERCENT), max, seed: 0 }
    }

    /// Folds `salt` into the seed, such as a tenant or application name, so its schedules
    /// spread differently from another deployment's schedules of the same names.
    ///
    /// # Example
    ///
    /// ```rust
    /// use adk_core::schedule::Jitter;
    ///
    /// assert_ne!(Jitter::default().salted("tenant-a").seed, Jitter::default().salted("tenant-b").seed);
    /// ```
    #[must_use]
    pub fn salted(mut self, salt: &str) -> Self {
        self.seed = fnv1a(self.seed ^ FNV_OFFSET, salt.as_bytes());
        self
    }

    /// The window a fire at `at` may be delayed within: `percent` of the gap to `next`, at
    /// most `max`; zero without a next occurrence.
    pub fn window(&self, at: DateTime<Utc>, next: Option<DateTime<Utc>>) -> Duration {
        let Some(gap) = next.and_then(|next| (next - at).to_std().ok()) else {
            return Duration::ZERO;
        };
        let share = gap.as_nanos() * u128::from(self.percent.min(Self::MAX_PERCENT)) / 100;
        Duration::from_nanos(u64::try_from(share).unwrap_or(u64::MAX)).min(self.max)
    }

    /// How long the fire of the schedule `key` at `at` is delayed, when the occurrence after
    /// it is `next`: the schedule's share of [`window`](Self::window), rounded down to whole
    /// milliseconds, so stores that keep milliseconds agree on it.
    pub fn offset(&self, key: &str, at: DateTime<Utc>, next: Option<DateTime<Utc>>) -> Duration {
        let window = self.window(at, next).as_nanos();
        let share = u128::from(mix(fnv1a(self.seed ^ FNV_OFFSET, key.as_bytes())));
        // `share / 2^64` is in [0, 1), so the offset is strictly inside the window.
        let nanos = (window * share) >> 64;
        Duration::from_millis(u64::try_from(nanos / 1_000_000).unwrap_or(u64::MAX))
    }

    /// [`offset`](Self::offset) with the next occurrence read from `spec`; zero when `spec`
    /// has none or cannot be evaluated.
    pub fn offset_in(&self, spec: &ScheduleSpec, key: &str, at: DateTime<Utc>) -> Duration {
        self.offset(key, at, spec.next_after(at).ok().flatten())
    }
}

const FNV_OFFSET: u64 = 0xcbf2_9ce4_8422_2325;

/// FNV-1a over `bytes` from `state`: stable across processes and platforms, unlike the
/// standard library's randomly keyed hasher.
fn fnv1a(mut state: u64, bytes: &[u8]) -> u64 {
    for byte in bytes {
        state ^= u64::from(*byte);
        state = state.wrapping_mul(0x0100_0000_01b3);
    }
    state
}

/// The murmur3 finalizer: spreads a change in any bit of `hash` over all of them, so keys
/// that differ in one character get unrelated shares.
fn mix(mut hash: u64) -> u64 {
    hash ^= hash >> 33;
    hash = hash.wrapping_mul(0xff51_afd7_ed55_8ccd);
    hash ^= hash >> 33;
    hash = hash.wrapping_mul(0xc4ce_b9fe_1a85_ec53);
    hash ^ (hash >> 33)
}

/// A schedule and the run template it enqueues.
///
/// # Example
///
/// ```rust
/// use adk_core::run_store::NewRun;
/// use adk_core::schedule::{MissedFirePolicy, Schedule, ScheduleSpec};
/// use chrono::{TimeZone, Utc};
///
/// let at = Utc.with_ymd_and_hms(2026, 10, 15, 9, 0, 0).unwrap();
/// let schedule = Schedule::new(
///     "nightly-report",
///     ScheduleSpec::At(at),
///     NewRun::new("default", "reports", "system", "report_agent", serde_json::json!({})),
///     MissedFirePolicy::FireOnce,
/// )
/// .with_next_fire_at(at);
/// let run = schedule.run_for(at);
/// assert_eq!(run.idempotency_key.as_deref(), Some("schedule:nightly-report:2026-10-15T09:00:00Z"));
/// assert_eq!(
///     run.principal.unwrap().on_behalf_of,
///     Some(adk_core::SubjectRef::service("system"))
/// );
/// ```
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Schedule {
    /// The schedule identifier.
    pub id: String,
    /// When the schedule fires.
    pub spec: ScheduleSpec,
    /// The run each firing enqueues; its idempotency key is replaced per firing.
    pub run: NewRun,
    /// Which due occurrences fire when several are due at once.
    pub missed: MissedFirePolicy,
    /// A paused schedule is never due.
    pub paused: bool,
    /// The next occurrence to fire; `None` when the schedule has no more occurrences.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub next_fire_at: Option<DateTime<Utc>>,
    /// Set by the store; increases by one on every change.
    pub revision: u64,
}

impl Schedule {
    /// Creates an unpaused schedule with no next fire time and revision 0.
    pub fn new(
        id: impl Into<String>,
        spec: ScheduleSpec,
        run: NewRun,
        missed: MissedFirePolicy,
    ) -> Self {
        Self { id: id.into(), spec, run, missed, paused: false, next_fire_at: None, revision: 0 }
    }

    /// Sets the next fire time.
    pub fn with_next_fire_at(mut self, at: DateTime<Utc>) -> Self {
        self.next_fire_at = Some(at);
        self
    }

    /// Sets whether the schedule is paused.
    pub fn with_paused(mut self, paused: bool) -> Self {
        self.paused = paused;
        self
    }

    /// Returns the run to enqueue for `fire_time`, keyed by [`firing_idempotency_key`].
    ///
    /// The run acts for its user as a service ([`NewRun::with_service_subject`]).
    pub fn run_for(&self, fire_time: DateTime<Utc>) -> NewRun {
        let mut run = self.run.clone().with_service_subject();
        run.idempotency_key = Some(firing_idempotency_key(&self.id, fire_time));
        run
    }

    /// Returns the run a manual "run now" of this schedule enqueues for `request_id`, keyed
    /// by [`manual_idempotency_key`]: the template a fire enqueues, with its concurrency key,
    /// so a run now and a fire are subject to the same overlap rule. The schedule itself is
    /// not changed: its next fire time and revision stay where they are.
    ///
    /// # Example
    ///
    /// ```rust
    /// use std::time::Duration;
    /// use adk_core::run_store::NewRun;
    /// use adk_core::schedule::{MissedFirePolicy, Schedule, ScheduleSpec};
    ///
    /// let schedule = Schedule::new(
    ///     "nightly-report",
    ///     ScheduleSpec::Every(Duration::from_secs(3600)),
    ///     NewRun::new("default", "reports", "system", "report_agent", serde_json::json!({})),
    ///     MissedFirePolicy::FireOnce,
    /// );
    /// let run = schedule.run_now("req-1");
    /// assert_eq!(run.idempotency_key.as_deref(), Some("schedule:nightly-report:manual:req-1"));
    /// ```
    pub fn run_now(&self, request_id: &str) -> NewRun {
        let mut run = self.run.clone().with_service_subject();
        run.idempotency_key = Some(manual_idempotency_key(&self.id, request_id));
        run
    }

    /// Checks the fields every store requires: a non-empty id, a valid run template, a
    /// positive interval, and a positive catch-up count. Cron syntax is checked by
    /// [`ScheduleSpec::next_after`].
    ///
    /// # Errors
    ///
    /// Returns [`INVALID_SCHEDULE_CODE`], or the run template's validation error.
    pub fn validate(&self) -> Result<()> {
        if self.id.is_empty() {
            return Err(invalid_schedule_error("id must not be empty"));
        }
        if matches!(self.spec, ScheduleSpec::Every(interval) if interval.is_zero()) {
            return Err(invalid_schedule_error("an Every interval must be greater than zero"));
        }
        if self.missed == MissedFirePolicy::CatchUp(0) {
            return Err(invalid_schedule_error("CatchUp must fire at least one occurrence"));
        }
        self.run.validate()
    }

    fn same_definition(&self, other: &Self) -> bool {
        self.spec == other.spec
            && self.run == other.run
            && self.missed == other.missed
            && self.paused == other.paused
            && self.next_fire_at == other.next_fire_at
    }
}

/// Returns the idempotency key of the run a schedule enqueues for one fire time:
/// `schedule:{id}:{fire_time RFC 3339}`, in UTC with the shortest exact fraction.
///
/// # Example
///
/// ```rust
/// use chrono::{TimeZone, Utc};
///
/// let at = Utc.with_ymd_and_hms(2026, 10, 15, 9, 0, 0).unwrap();
/// assert_eq!(adk_core::schedule::firing_idempotency_key("daily", at), "schedule:daily:2026-10-15T09:00:00Z");
/// ```
pub fn firing_idempotency_key(schedule_id: &str, fire_time: DateTime<Utc>) -> String {
    format!("schedule:{schedule_id}:{}", fire_time.to_rfc3339_opts(SecondsFormat::AutoSi, true))
}

/// Returns the idempotency key of the run a manual "run now" of a schedule enqueues:
/// `schedule:{id}:manual:{request id}`. A fire's key ends in a timestamp, which starts with a
/// digit, so the two never collide; a retried request with the same id enqueues nothing new.
///
/// # Example
///
/// ```rust
/// assert_eq!(adk_core::schedule::manual_idempotency_key("daily", "req-1"), "schedule:daily:manual:req-1");
/// ```
pub fn manual_idempotency_key(schedule_id: &str, request_id: &str) -> String {
    format!("schedule:{schedule_id}:manual:{request_id}")
}

/// The fire times a scheduler enqueues for one due schedule, and where it moves next.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FirePlan {
    /// The occurrences to fire, oldest first.
    pub fire_times: Vec<DateTime<Utc>>,
    /// The first occurrence after `now`, for [`ScheduleStore::advance`].
    pub next_fire_at: Option<DateTime<Utc>>,
}

/// Plans the firings of a schedule that is due at `due_at`, as seen at `now`.
///
/// `due_at` (the schedule's stored `next_fire_at`) is itself an occurrence; the others
/// follow from `spec`. Occurrences in `[due_at, now]` are due, and `missed` picks which
/// fire (see the [module documentation](crate::schedule)). `grace` bounds lateness
/// under [`MissedFirePolicy::Skip`]. When `due_at` is after `now` nothing fires and
/// the schedule stays at `due_at`.
///
/// # Example
///
/// ```rust
/// use std::time::Duration;
/// use adk_core::schedule::{plan_fires, MissedFirePolicy, ScheduleSpec, DEFAULT_MISFIRE_GRACE};
/// use chrono::{TimeZone, Utc};
///
/// let due = Utc.with_ymd_and_hms(2026, 10, 15, 9, 0, 0).unwrap();
/// let now = due + chrono::Duration::minutes(35);
/// let plan = plan_fires(&ScheduleSpec::Every(Duration::from_secs(600)), MissedFirePolicy::CatchUp(2), due, now, DEFAULT_MISFIRE_GRACE)?;
/// assert_eq!(plan.fire_times, vec![due + chrono::Duration::minutes(20), due + chrono::Duration::minutes(30)]);
/// assert_eq!(plan.next_fire_at, Some(due + chrono::Duration::minutes(40)));
/// # Ok::<(), adk_core::AdkError>(())
/// ```
///
/// # Errors
///
/// Returns [`INVALID_SCHEDULE_CODE`] for an invalid cron expression, time zone,
/// interval, or catch-up count, and `schedule.cron_unavailable` for a cron spec when
/// the `cron` feature is off.
pub fn plan_fires(
    spec: &ScheduleSpec,
    missed: MissedFirePolicy,
    due_at: DateTime<Utc>,
    now: DateTime<Utc>,
    grace: Duration,
) -> Result<FirePlan> {
    if due_at > now {
        return Ok(FirePlan { fire_times: Vec::new(), next_fire_at: Some(due_at) });
    }
    let wanted = match missed {
        MissedFirePolicy::Skip | MissedFirePolicy::FireOnce => 1,
        MissedFirePolicy::CatchUp(0) => {
            return Err(invalid_schedule_error("CatchUp must fire at least one occurrence"));
        }
        MissedFirePolicy::CatchUp(count) => count as usize,
    };
    let mut plan = match spec {
        ScheduleSpec::At(_) => FirePlan { fire_times: vec![due_at], next_fire_at: None },
        ScheduleSpec::Every(interval) => {
            let step = chrono::Duration::from_std(*interval)
                .ok()
                .filter(|step| *step > chrono::Duration::zero())
                .ok_or_else(|| invalid_schedule_error("an Every interval must be positive"))?;
            let step_nanos = step.num_nanoseconds().unwrap_or(i64::MAX).max(1);
            let elapsed = (now - due_at).num_nanoseconds().unwrap_or(i64::MAX);
            let latest = elapsed / step_nanos;
            let first = (latest - wanted as i64 + 1).max(0);
            let at = |k: i64| {
                due_at
                    .checked_add_signed(chrono::Duration::nanoseconds(k.saturating_mul(step_nanos)))
            };
            FirePlan {
                fire_times: (first..=latest).filter_map(at).collect(),
                next_fire_at: at(latest + 1),
            }
        }
        ScheduleSpec::Cron { expr, timezone } => {
            cron::latest_and_next(expr, timezone, due_at, now, wanted)?
        }
    };
    if missed == MissedFirePolicy::Skip {
        let late = plan
            .fire_times
            .last()
            .is_some_and(|last| (now - *last).to_std().unwrap_or_default() > grace);
        if late {
            plan.fire_times.clear();
        }
    }
    Ok(plan)
}

impl ScheduleSpec {
    /// Returns the first occurrence strictly after `after`; the first fire time of a new
    /// schedule is `spec.next_after(now)` (or the instant itself for [`ScheduleSpec::At`]).
    ///
    /// For [`At`](Self::At) this is the instant when it is after `after`; for
    /// [`Every`](Self::Every) it is `after + interval`.
    ///
    /// # Example
    ///
    /// ```rust
    /// use std::time::Duration;
    /// use adk_core::schedule::ScheduleSpec;
    /// use chrono::{TimeZone, Utc};
    ///
    /// let now = Utc.with_ymd_and_hms(2026, 10, 15, 9, 0, 0).unwrap();
    /// let next = ScheduleSpec::Every(Duration::from_secs(60)).next_after(now)?;
    /// assert_eq!(next, Some(Utc.with_ymd_and_hms(2026, 10, 15, 9, 1, 0).unwrap()));
    /// # Ok::<(), adk_core::AdkError>(())
    /// ```
    ///
    /// # Errors
    ///
    /// Same as [`plan_fires`].
    pub fn next_after(&self, after: DateTime<Utc>) -> Result<Option<DateTime<Utc>>> {
        match self {
            Self::At(at) => Ok((*at > after).then_some(*at)),
            Self::Every(interval) => chrono::Duration::from_std(*interval)
                .ok()
                .filter(|step| *step > chrono::Duration::zero())
                .map(|step| after.checked_add_signed(step))
                .ok_or_else(|| invalid_schedule_error("an Every interval must be positive")),
            Self::Cron { expr, timezone } => {
                Ok(cron::latest_and_next(expr, timezone, after, after, 0)?.next_fire_at)
            }
        }
    }
}

#[cfg(feature = "cron")]
mod cron {
    use std::str::FromStr;

    use chrono::{DateTime, LocalResult, TimeZone, Utc};
    use chrono_tz::Tz;

    use super::invalid_schedule_error;
    use crate::Result;

    fn parse(expr: &str, timezone: &str) -> Result<(::cron::Schedule, Tz)> {
        let fields: Vec<&str> = expr.split_whitespace().collect();
        let expanded = match fields.as_slice() {
            // The crate counts 1 as Sunday, so a five-field weekday reaches it as day names.
            [minute, hour, day, month, weekday] => {
                let weekday = unix_weekdays(weekday).map_err(|reason| {
                    invalid_schedule_error(&format!(
                        "cron expression '{expr}' does not parse: the day of the week \
                         '{weekday}' {reason}"
                    ))
                })?;
                format!("0 {minute} {hour} {day} {month} {weekday}")
            }
            _ => expr.to_string(),
        };
        let schedule = ::cron::Schedule::from_str(&expanded).map_err(|error| {
            invalid_schedule_error(&format!("cron expression '{expr}' does not parse: {error}"))
        })?;
        let tz = timezone.parse::<Tz>().map_err(|_| {
            invalid_schedule_error(&format!(
                "time zone '{timezone}' is not an IANA name such as 'UTC' or 'Europe/Berlin'"
            ))
        })?;
        Ok((schedule, tz))
    }

    /// The day names a five-field day-of-week `field` selects under Unix numbering — 0 and 7
    /// are Sunday, 1 to 6 Monday to Saturday — as a list the `cron` crate reads; `*` and `?`
    /// unchanged. `Err` says why the field does not parse.
    fn unix_weekdays(field: &str) -> std::result::Result<String, String> {
        const NAMES: [&str; 7] = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
        if field == "*" || field == "?" {
            return Ok(field.to_string());
        }
        let day = |text: &str| -> std::result::Result<usize, String> {
            if let Ok(number) = text.parse::<usize>() {
                return match number {
                    0..=7 => Ok(number),
                    _ => Err(format!("names day {number}; days are 0 to 7, 0 and 7 Sunday")),
                };
            }
            match text.to_ascii_lowercase().as_str() {
                "sun" | "sunday" => Ok(0),
                "mon" | "monday" => Ok(1),
                "tue" | "tues" | "tuesday" => Ok(2),
                "wed" | "wednesday" => Ok(3),
                "thu" | "thurs" | "thursday" => Ok(4),
                "fri" | "friday" => Ok(5),
                "sat" | "saturday" => Ok(6),
                _ => Err(format!("holds '{text}', which is neither a day number nor a day name")),
            }
        };
        let mut selected = [false; 7];
        for part in field.split(',') {
            let (base, step) = match part.split_once('/') {
                Some((base, step)) => match step.parse::<usize>() {
                    Ok(step) if step > 0 => (base, Some(step)),
                    _ => return Err(format!("has the step '{step}'; a step is 1 or more")),
                },
                None => (part, None),
            };
            // A day with a step runs to the end of the week, as `*` spans all of it.
            let (start, end) = match (base, base.split_once('-')) {
                ("*" | "?", _) => (0, 7),
                (_, Some((start, end))) => (day(start)?, day(end)?),
                (_, None) => {
                    let start = day(base)?;
                    (start, if step.is_some() { 7 } else { start })
                }
            };
            if start > end {
                return Err(format!("has the range '{base}', which runs backwards"));
            }
            for value in (start..=end).step_by(step.unwrap_or(1)) {
                selected[value % 7] = true;
            }
        }
        let names: Vec<&str> =
            NAMES.iter().zip(selected).filter_map(|(name, on)| on.then_some(*name)).collect();
        Ok(names.join(","))
    }

    /// The later instant of a local time repeated by a fall-back change is skipped, so
    /// each local time fires once.
    fn is_repeat(at: &DateTime<Tz>) -> bool {
        matches!(at.timezone().from_local_datetime(&at.naive_local()), LocalResult::Ambiguous(first, _) if first != *at)
    }

    /// Returns up to `wanted` occurrences in `[due_at, now]` (always including `due_at`),
    /// oldest first, and the first occurrence after `now`.
    pub(super) fn latest_and_next(
        expr: &str,
        timezone: &str,
        due_at: DateTime<Utc>,
        now: DateTime<Utc>,
        wanted: usize,
    ) -> Result<super::FirePlan> {
        let (schedule, tz) = parse(expr, timezone)?;
        let next = schedule
            .after(&now.with_timezone(&tz))
            .find(|at| !is_repeat(at))
            .map(|at| at.with_timezone(&Utc));
        let mut latest = Vec::with_capacity(wanted);
        // Walks back from just past `now`, so the cost is the number of fires kept.
        let start = (now + chrono::Duration::seconds(1)).with_timezone(&tz);
        for at in schedule.after(&start).rev() {
            if latest.len() >= wanted {
                break;
            }
            let at = at.with_timezone(&Utc);
            if at <= due_at {
                break;
            }
            if at <= now && !is_repeat(&at.with_timezone(&tz)) {
                latest.push(at);
            }
        }
        if latest.len() < wanted {
            latest.push(due_at);
        }
        latest.reverse();
        Ok(super::FirePlan { fire_times: latest, next_fire_at: next })
    }
}

#[cfg(not(feature = "cron"))]
mod cron {
    use chrono::{DateTime, Utc};

    use crate::{AdkError, ErrorCategory, ErrorComponent, Result};

    pub(super) fn latest_and_next(
        _expr: &str,
        _timezone: &str,
        _due_at: DateTime<Utc>,
        _now: DateTime<Utc>,
        _wanted: usize,
    ) -> Result<super::FirePlan> {
        Err(AdkError::new(
            ErrorComponent::Agent,
            ErrorCategory::Unsupported,
            "schedule.cron_unavailable",
            "cron schedules need the `cron` feature of adk-core; enable it in Cargo.toml",
        ))
    }
}

/// Stores schedules and lets one replica at a time advance each.
///
/// Every backend passes `adk_core::schedule_store_conformance_tests!` (feature `conformance`).
#[async_trait]
pub trait ScheduleStore: Send + Sync {
    /// Inserts or replaces the schedule with `schedule.id` and returns the stored one.
    ///
    /// The store assigns the revision: 1 on insert, the previous revision plus one on a
    /// change. Upserting a definition identical to the stored one (spec, run, missed
    /// policy, paused flag, next fire time) changes nothing, so replicas registering the
    /// same schedule at startup do not disturb an advance in flight.
    ///
    /// # Errors
    ///
    /// Returns the [`Schedule::validate`] error.
    async fn upsert(&self, schedule: Schedule) -> Result<Schedule>;

    /// Returns a schedule, or `None` when it does not exist.
    async fn get(&self, id: &str) -> Result<Option<Schedule>>;

    /// Returns every schedule, ordered by id.
    async fn list(&self) -> Result<Vec<Schedule>>;

    /// Deletes a schedule.
    ///
    /// # Errors
    ///
    /// Returns [`SCHEDULE_NOT_FOUND_CODE`] for an unknown schedule.
    async fn delete(&self, id: &str) -> Result<()>;

    /// Pauses or resumes a schedule and returns it; the revision moves only on a change.
    ///
    /// # Errors
    ///
    /// Returns [`SCHEDULE_NOT_FOUND_CODE`] for an unknown schedule.
    async fn set_paused(&self, id: &str, paused: bool) -> Result<Schedule>;

    /// Returns up to `limit` unpaused schedules whose `next_fire_at` is at or before
    /// `now`, earliest first, ties by id.
    async fn due(&self, now: DateTime<Utc>, limit: usize) -> Result<Vec<Schedule>>;

    /// Sets `next_fire_at` when the stored revision equals `expected_revision`, and
    /// returns `false` when another replica advanced or changed the schedule first.
    ///
    /// # Errors
    ///
    /// Returns [`SCHEDULE_NOT_FOUND_CODE`] for an unknown schedule.
    async fn advance(
        &self,
        id: &str,
        expected_revision: u64,
        next_fire_at: Option<DateTime<Utc>>,
    ) -> Result<bool>;
}

/// Builds the error a schedule store returns for an unknown schedule.
///
/// # Example
///
/// ```rust
/// assert!(adk_core::schedule::schedule_not_found_error("daily").is_not_found());
/// ```
pub fn schedule_not_found_error(id: &str) -> AdkError {
    AdkError::not_found(
        ErrorComponent::Agent,
        SCHEDULE_NOT_FOUND_CODE,
        format!("schedule store has no schedule '{id}'; upsert it first"),
    )
}

/// Builds the error returned for an invalid schedule.
///
/// # Example
///
/// ```rust
/// let error = adk_core::schedule::invalid_schedule_error("id must not be empty");
/// assert_eq!(error.code, adk_core::schedule::INVALID_SCHEDULE_CODE);
/// ```
pub fn invalid_schedule_error(reason: &str) -> AdkError {
    AdkError::new(
        ErrorComponent::Agent,
        ErrorCategory::InvalidInput,
        INVALID_SCHEDULE_CODE,
        format!("invalid schedule: {reason}"),
    )
}

/// Process-local [`ScheduleStore`].
///
/// Holds no time-dependent state, so it takes no clock: [`due`](ScheduleStore::due)
/// receives the time from the scheduler.
///
/// # Example
///
/// ```rust
/// use std::time::Duration;
/// use adk_core::run_store::NewRun;
/// use adk_core::schedule::{InMemoryScheduleStore, MissedFirePolicy, Schedule, ScheduleSpec, ScheduleStore};
/// use chrono::Utc;
///
/// # futures::executor::block_on(async {
/// let store = InMemoryScheduleStore::new();
/// let now = Utc::now();
/// let schedule = Schedule::new(
///     "heartbeat",
///     ScheduleSpec::Every(Duration::from_secs(60)),
///     NewRun::new("default", "ops", "system", "probe", serde_json::json!({})),
///     MissedFirePolicy::Skip,
/// )
/// .with_next_fire_at(now);
/// let stored = store.upsert(schedule).await?;
/// assert_eq!(store.due(now, 10).await?.len(), 1);
/// assert!(store.advance("heartbeat", stored.revision, Some(now + chrono::Duration::minutes(1))).await?);
/// # Ok::<(), adk_core::AdkError>(())
/// # }).unwrap();
/// ```
#[derive(Debug, Default)]
pub struct InMemoryScheduleStore {
    schedules: Mutex<BTreeMap<String, Schedule>>,
}

impl InMemoryScheduleStore {
    /// Creates an empty store.
    pub fn new() -> Self {
        Self::default()
    }
}

#[async_trait]
impl ScheduleStore for InMemoryScheduleStore {
    async fn upsert(&self, mut schedule: Schedule) -> Result<Schedule> {
        schedule.validate()?;
        let mut schedules = self.schedules.lock().await;
        if let Some(existing) = schedules.get(&schedule.id) {
            if existing.same_definition(&schedule) {
                return Ok(existing.clone());
            }
            schedule.revision = existing.revision + 1;
        } else {
            schedule.revision = 1;
        }
        schedules.insert(schedule.id.clone(), schedule.clone());
        Ok(schedule)
    }

    async fn get(&self, id: &str) -> Result<Option<Schedule>> {
        Ok(self.schedules.lock().await.get(id).cloned())
    }

    async fn list(&self) -> Result<Vec<Schedule>> {
        Ok(self.schedules.lock().await.values().cloned().collect())
    }

    async fn delete(&self, id: &str) -> Result<()> {
        self.schedules
            .lock()
            .await
            .remove(id)
            .map(|_| ())
            .ok_or_else(|| schedule_not_found_error(id))
    }

    async fn set_paused(&self, id: &str, paused: bool) -> Result<Schedule> {
        let mut schedules = self.schedules.lock().await;
        let schedule = schedules.get_mut(id).ok_or_else(|| schedule_not_found_error(id))?;
        if schedule.paused != paused {
            schedule.paused = paused;
            schedule.revision += 1;
        }
        Ok(schedule.clone())
    }

    async fn due(&self, now: DateTime<Utc>, limit: usize) -> Result<Vec<Schedule>> {
        let schedules = self.schedules.lock().await;
        let mut due: Vec<_> = schedules
            .values()
            .filter(|schedule| {
                !schedule.paused && schedule.next_fire_at.is_some_and(|at| at <= now)
            })
            .cloned()
            .collect();
        due.sort_by(|a, b| (a.next_fire_at, &a.id).cmp(&(b.next_fire_at, &b.id)));
        due.truncate(limit);
        Ok(due)
    }

    async fn advance(
        &self,
        id: &str,
        expected_revision: u64,
        next_fire_at: Option<DateTime<Utc>>,
    ) -> Result<bool> {
        let mut schedules = self.schedules.lock().await;
        let schedule = schedules.get_mut(id).ok_or_else(|| schedule_not_found_error(id))?;
        if schedule.revision != expected_revision {
            return Ok(false);
        }
        schedule.next_fire_at = next_fire_at;
        schedule.revision += 1;
        Ok(true)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use chrono::TimeZone;

    fn at(day: u32, hour: u32, minute: u32) -> DateTime<Utc> {
        Utc.with_ymd_and_hms(2026, 10, day, hour, minute, 0).single().unwrap()
    }

    #[test]
    fn every_policies() {
        let spec = ScheduleSpec::Every(Duration::from_secs(600));
        let due = at(15, 9, 0);
        let now = at(15, 9, 35);
        let grace = DEFAULT_MISFIRE_GRACE;
        let plan = |missed| plan_fires(&spec, missed, due, now, grace).unwrap();
        let next = Some(at(15, 9, 40));
        assert_eq!(
            plan(MissedFirePolicy::FireOnce),
            FirePlan { fire_times: vec![at(15, 9, 30)], next_fire_at: next }
        );
        assert_eq!(
            plan(MissedFirePolicy::Skip),
            FirePlan { fire_times: vec![], next_fire_at: next }
        );
        assert_eq!(
            plan(MissedFirePolicy::CatchUp(10)),
            FirePlan {
                fire_times: vec![at(15, 9, 0), at(15, 9, 10), at(15, 9, 20), at(15, 9, 30)],
                next_fire_at: next
            }
        );
        let on_time = plan_fires(&spec, MissedFirePolicy::Skip, due, at(15, 9, 0), grace).unwrap();
        assert_eq!(on_time, FirePlan { fire_times: vec![due], next_fire_at: Some(at(15, 9, 10)) });
        let early = plan_fires(&spec, MissedFirePolicy::Skip, due, at(15, 8, 0), grace).unwrap();
        assert_eq!(early, FirePlan { fire_times: vec![], next_fire_at: Some(due) });
    }

    #[test]
    fn at_fires_once() {
        let due = at(15, 9, 0);
        let plan = plan_fires(
            &ScheduleSpec::At(due),
            MissedFirePolicy::FireOnce,
            due,
            at(15, 12, 0),
            DEFAULT_MISFIRE_GRACE,
        )
        .unwrap();
        assert_eq!(plan, FirePlan { fire_times: vec![due], next_fire_at: None });
        assert_eq!(ScheduleSpec::At(due).next_after(at(15, 8, 0)).unwrap(), Some(due));
        assert_eq!(ScheduleSpec::At(due).next_after(due).unwrap(), None);
    }

    #[test]
    fn invalid_specs_are_refused() {
        let zero = ScheduleSpec::Every(Duration::ZERO);
        assert_eq!(zero.next_after(at(15, 0, 0)).unwrap_err().code, INVALID_SCHEDULE_CODE);
        let error = plan_fires(
            &ScheduleSpec::At(at(15, 0, 0)),
            MissedFirePolicy::CatchUp(0),
            at(15, 0, 0),
            at(15, 0, 0),
            DEFAULT_MISFIRE_GRACE,
        )
        .unwrap_err();
        assert_eq!(error.code, INVALID_SCHEDULE_CODE);
    }

    #[test]
    fn firing_keys_are_canonical() {
        let fractional = at(15, 9, 0) + chrono::Duration::milliseconds(250);
        assert_eq!(
            firing_idempotency_key("a:b/ü", fractional),
            "schedule:a:b/ü:2026-10-15T09:00:00.250Z"
        );
    }

    #[cfg(feature = "cron")]
    mod cron_specs {
        use super::*;

        fn cron(expr: &str, timezone: &str) -> ScheduleSpec {
            ScheduleSpec::Cron { expr: expr.into(), timezone: timezone.into() }
        }

        #[test]
        fn five_and_six_field_expressions() {
            let five = cron("*/15 * * * *", "UTC");
            let six = cron("0 */15 * * * *", "UTC");
            assert_eq!(five.next_after(at(15, 9, 1)).unwrap(), Some(at(15, 9, 15)));
            assert_eq!(six.next_after(at(15, 9, 1)).unwrap(), Some(at(15, 9, 15)));
        }

        /// The next `count` fire times after `from`.
        fn fires(spec: &ScheduleSpec, from: DateTime<Utc>, count: usize) -> Vec<DateTime<Utc>> {
            let mut cursor = from;
            let mut all = Vec::with_capacity(count);
            while all.len() < count {
                cursor = spec.next_after(cursor).unwrap().unwrap();
                all.push(cursor);
            }
            all
        }

        // October 2026: the 18th and 25th are Sundays, the 24th and 31st Saturdays.
        #[test]
        fn five_fields_count_weekdays_as_unix_cron_does() {
            let weekdays = cron("0 9 * * 1-5", "UTC");
            assert_eq!(
                fires(&weekdays, at(18, 12, 0), 6),
                vec![
                    at(19, 9, 0),
                    at(20, 9, 0),
                    at(21, 9, 0),
                    at(22, 9, 0),
                    at(23, 9, 0),
                    at(26, 9, 0)
                ],
                "Monday to Friday, never Saturday or Sunday"
            );
            assert_eq!(weekdays.next_after(at(24, 10, 0)).unwrap(), Some(at(26, 9, 0)));
            assert_eq!(fires(&cron("0 9 * * Mon-Fri", "UTC"), at(18, 12, 0), 6), {
                fires(&weekdays, at(18, 12, 0), 6)
            });
        }

        #[test]
        fn zero_and_seven_are_sunday_and_six_is_saturday() {
            for sunday in ["0", "7", "Sun", "0,7"] {
                let spec = cron(&format!("0 9 * * {sunday}"), "UTC");
                assert_eq!(
                    fires(&spec, at(23, 10, 0), 2),
                    vec![at(25, 9, 0), Utc.with_ymd_and_hms(2026, 11, 1, 9, 0, 0).unwrap()],
                    "{sunday}"
                );
            }
            let saturday = cron("0 9 * * 6", "UTC");
            assert_eq!(fires(&saturday, at(23, 10, 0), 2), vec![at(24, 9, 0), at(31, 9, 0)]);
            let weekend = cron("30 7 * * 6,0", "UTC");
            assert_eq!(
                fires(&weekend, at(23, 10, 0), 3),
                vec![at(24, 7, 30), at(25, 7, 30), at(31, 7, 30)]
            );
            // A range may end on 7.
            let friday_to_sunday = cron("0 9 * * 5-7", "UTC");
            assert_eq!(
                fires(&friday_to_sunday, at(22, 10, 0), 4),
                vec![at(23, 9, 0), at(24, 9, 0), at(25, 9, 0), at(30, 9, 0)]
            );
        }

        #[test]
        fn five_field_weekday_steps() {
            // Monday, Wednesday and Friday.
            let odd = cron("0 9 * * 1-5/2", "UTC");
            assert_eq!(
                fires(&odd, at(25, 10, 0), 3),
                vec![at(26, 9, 0), at(28, 9, 0), at(30, 9, 0)]
            );
            // Sunday, Wednesday and Saturday.
            let every_third = cron("0 9 * * */3", "UTC");
            assert_eq!(
                fires(&every_third, at(24, 10, 0), 3),
                vec![at(25, 9, 0), at(28, 9, 0), at(31, 9, 0)]
            );
        }

        #[test]
        fn six_and_seven_fields_keep_the_crates_numbering() {
            // 1 is Sunday, so 1-5 is Sunday to Thursday.
            let six = cron("0 0 9 * * 1-5", "UTC");
            assert_eq!(
                fires(&six, at(23, 10, 0), 5),
                vec![at(25, 9, 0), at(26, 9, 0), at(27, 9, 0), at(28, 9, 0), at(29, 9, 0)]
            );
            let seven = cron("0 0 9 * * 7 2026", "UTC");
            assert_eq!(seven.next_after(at(23, 10, 0)).unwrap(), Some(at(24, 9, 0)));
        }

        #[test]
        fn bad_five_field_weekdays_are_refused() {
            for field in ["8", "5-1", "5L", "*/0", "MON#2", "1,", "Fri-Sun"] {
                let error =
                    cron(&format!("0 9 * * {field}"), "UTC").next_after(at(15, 0, 0)).unwrap_err();
                assert_eq!(error.code, INVALID_SCHEDULE_CODE, "{field}");
                assert!(error.message.contains("day of the week"), "{field}: {}", error.message);
            }
        }

        #[test]
        fn catch_up_and_fire_once() {
            let spec = cron("0 * * * *", "UTC");
            let due = at(15, 9, 0);
            let now = at(15, 12, 30);
            let catch_up =
                plan_fires(&spec, MissedFirePolicy::CatchUp(3), due, now, DEFAULT_MISFIRE_GRACE)
                    .unwrap();
            assert_eq!(
                catch_up,
                FirePlan {
                    fire_times: vec![at(15, 10, 0), at(15, 11, 0), at(15, 12, 0)],
                    next_fire_at: Some(at(15, 13, 0))
                }
            );
            let all =
                plan_fires(&spec, MissedFirePolicy::CatchUp(100), due, now, DEFAULT_MISFIRE_GRACE)
                    .unwrap();
            assert_eq!(
                all.fire_times,
                vec![at(15, 9, 0), at(15, 10, 0), at(15, 11, 0), at(15, 12, 0)]
            );
            let once =
                plan_fires(&spec, MissedFirePolicy::FireOnce, due, now, DEFAULT_MISFIRE_GRACE)
                    .unwrap();
            assert_eq!(once.fire_times, vec![at(15, 12, 0)]);
            let skip =
                plan_fires(&spec, MissedFirePolicy::Skip, due, now, DEFAULT_MISFIRE_GRACE).unwrap();
            assert!(skip.fire_times.is_empty());
            let on_time =
                plan_fires(&spec, MissedFirePolicy::Skip, due, at(15, 9, 0), DEFAULT_MISFIRE_GRACE)
                    .unwrap();
            assert_eq!(on_time.fire_times, vec![due]);
        }

        #[test]
        fn time_zones_and_daylight_saving() {
            // Berlin leaves summer time on 25 October 2026: 09:00 local is 07:00 UTC before, 08:00 after.
            let spec = cron("0 9 * * *", "Europe/Berlin");
            assert_eq!(spec.next_after(at(24, 0, 0)).unwrap(), Some(at(24, 7, 0)));
            assert_eq!(spec.next_after(at(25, 0, 0)).unwrap(), Some(at(25, 8, 0)));

            // 02:30 local happens twice on 25 October and fires once, at the first instant (00:30 UTC).
            let repeated = cron("0 30 2 * * *", "Europe/Berlin");
            let first = Utc.with_ymd_and_hms(2026, 10, 25, 0, 30, 0).unwrap();
            assert_eq!(repeated.next_after(at(25, 0, 0)).unwrap(), Some(first));
            assert_eq!(
                repeated.next_after(first).unwrap(),
                Some(Utc.with_ymd_and_hms(2026, 10, 26, 1, 30, 0).unwrap())
            );
            let plan = plan_fires(
                &repeated,
                MissedFirePolicy::CatchUp(5),
                first,
                at(25, 12, 0),
                DEFAULT_MISFIRE_GRACE,
            )
            .unwrap();
            assert_eq!(plan.fire_times, vec![first]);
        }

        #[test]
        fn bad_expressions_and_zones_are_refused() {
            assert_eq!(
                cron("not cron", "UTC").next_after(at(15, 0, 0)).unwrap_err().code,
                INVALID_SCHEDULE_CODE
            );
            assert_eq!(
                cron("* * * * *", "Mars/Olympus").next_after(at(15, 0, 0)).unwrap_err().code,
                INVALID_SCHEDULE_CODE
            );
        }
    }

    mod jitter {
        use proptest::prelude::*;

        use super::*;

        #[test]
        fn a_fire_lands_before_the_next_occurrence() {
            let jitter = Jitter::new(90, Duration::from_secs(3600));
            assert_eq!(jitter.percent, Jitter::MAX_PERCENT, "clamped to half the gap");
            let at = at(15, 9, 0);
            let next = Some(at + chrono::Duration::minutes(10));
            assert_eq!(jitter.window(at, next), Duration::from_secs(300));
            for key in ["a", "b", "nightly", "report-17"] {
                assert!(jitter.offset(key, at, next) < Duration::from_secs(300));
            }
            assert_eq!(jitter.window(at, None), Duration::ZERO);
            assert_eq!(
                Jitter::new(0, Duration::from_secs(60)).offset("a", at, next),
                Duration::ZERO
            );
        }

        #[test]
        fn the_default_caps_a_daily_schedule_at_nine_minutes() {
            let daily = ScheduleSpec::Cron { expr: "0 9 * * *".into(), timezone: "UTC".into() };
            let at = at(15, 9, 0);
            let jitter = Jitter::default();
            assert_eq!(jitter.window(at, daily.next_after(at).unwrap()), Jitter::DEFAULT_MAX);
            let every_minute = ScheduleSpec::Every(Duration::from_secs(60));
            assert_eq!(
                jitter.window(at, every_minute.next_after(at).unwrap()),
                Duration::from_secs(9),
                "15 percent of a minute"
            );
        }

        #[test]
        fn schedules_and_salts_spread_apart() {
            let jitter = Jitter::new(50, Duration::from_secs(3600));
            let at = at(15, 9, 0);
            let next = Some(at + chrono::Duration::hours(2));
            let offsets: std::collections::BTreeSet<Duration> =
                (0..64).map(|n| jitter.offset(&format!("job-{n}"), at, next)).collect();
            assert!(offsets.len() > 60, "64 schedules take {} distinct offsets", offsets.len());
            let salted = jitter.salted("tenant-a");
            assert_ne!(salted.offset("job-1", at, next), jitter.offset("job-1", at, next));
            assert_eq!(salted, jitter.salted("tenant-a"), "a salt is deterministic");
        }

        #[test]
        fn run_now_keeps_the_concurrency_key_and_leaves_the_schedule() {
            let run = NewRun::new("default", "ops", "system", "probe", serde_json::json!({}))
                .with_concurrency_key("cron:probe", crate::OnConflict::Reject);
            let schedule = Schedule::new(
                "probe",
                ScheduleSpec::Every(Duration::from_secs(60)),
                run,
                MissedFirePolicy::Skip,
            )
            .with_next_fire_at(at(15, 9, 0));
            let manual = schedule.run_now("r1");
            assert_eq!(manual.idempotency_key.as_deref(), Some("schedule:probe:manual:r1"));
            assert_eq!(manual.concurrency_key.as_deref(), Some("cron:probe"));
            assert_ne!(manual.idempotency_key, schedule.run_for(at(15, 9, 0)).idempotency_key);
        }

        proptest! {
            #![proptest_config(ProptestConfig::with_cases(256))]

            /// Every offset is below the window, the window at most `max` and half the gap,
            /// and the same key always takes the same offset.
            #[test]
            fn offsets_stay_inside_the_window(
                key in "[a-z0-9:-]{1,24}",
                percent in 0u8..=255,
                max_ms in 0u64..=86_400_000,
                gap_ms in 1i64..=7 * 86_400_000,
                seed in any::<u64>(),
            ) {
                let mut jitter = Jitter::new(percent, Duration::from_millis(max_ms));
                jitter.seed = seed;
                let at = at(15, 9, 0);
                let next = at + chrono::Duration::milliseconds(gap_ms);
                let window = jitter.window(at, Some(next));
                let offset = jitter.offset(&key, at, Some(next));
                prop_assert!(window <= Duration::from_millis(max_ms));
                prop_assert!(window.as_nanos() * 2 <= u128::from(gap_ms.unsigned_abs()) * 1_000_000);
                prop_assert!(offset <= window);
                prop_assert!(window.is_zero() || offset < window);
                prop_assert!(at + chrono::Duration::from_std(offset).unwrap() < next);
                prop_assert_eq!(offset, jitter.offset(&key, at, Some(next)));
            }
        }
    }
}