polyc-controller 2026.8.3

Conversation CRD + kube reconciler for the polychrome control plane.
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
//! The one place that predicts when a [`RoutineSchedule`] fires next (#1491).
//!
//! Before this module existed, the in-process routine scheduler was the only
//! code that knew how to turn a `cron` (or `once`) schedule into real fire
//! instants — so the confirmation card and the inspector had no way to show a
//! human the same times the scheduler would actually use (INV-RL10). This
//! module lifts that math into one pure, clock-injected callable every
//! surface shares: no IO, no clock — every function here takes the instant to
//! reason from (`after`/`since`/`now`) as an argument, mirroring this crate's
//! other pure decision cores.
//!
//! # Composing `saffron` (UTC-only) with `chrono-tz` (wall-clock aware)
//!
//! [`saffron::Cron`] only evaluates a [`DateTime<Utc>`]'s calendar fields
//! (minute/hour/day/month/weekday) — it never reads the `Utc` tag itself, so
//! feeding it a real UTC instant only tells it what a routine's schedule
//! means in UTC, not in the routine's own local wall-clock time. To evaluate
//! the schedule against the routine's *local* time instead, `cron_next_after`
//! plays the same trick every tz-naive cron engine composed with a real tz
//! library needs: convert the real UTC instant to the routine's local wall
//! clock, re-tag those SAME calendar fields as if they were UTC (a
//! [`Utc::from_utc_datetime`] on the local naive value — call this the "fake
//! UTC" representation), ask `saffron` for its next match in that
//! representation, then re-interpret the match's calendar fields as real
//! local wall-clock time via [`chrono_tz::Tz::from_local_datetime`] to get
//! back a real UTC instant.
//!
//! That last step is where daylight saving time has to be handled
//! explicitly, because a local wall-clock naive time is not always a 1:1
//! stand-in for a real instant:
//!
//! - **Spring-forward gap** (a local time that never happens, e.g. 2:30 AM on
//!   the day clocks jump from 2:00 to 3:00): [`chrono_tz::Tz::from_local_datetime`]
//!   returns [`chrono::LocalResult::None`]. `cron_next_after` treats this
//!   candidate as a non-match and keeps searching forward — the tick is
//!   skipped, never fired late and never fired twice.
//! - **Fall-back repeat** (a local time that happens twice, e.g. 1:30 AM on
//!   the day clocks fall from 2:00 back to 1:00): `from_local_datetime`
//!   returns [`chrono::LocalResult::Ambiguous`]. `cron_next_after`
//!   deterministically picks the EARLIER of the two real instants. Since
//!   `saffron` iterates over local calendar fields (not real instants), that
//!   one ambiguous wall-clock minute is a single candidate in its iteration
//!   regardless of DST — picking one of its two real realizations is what
//!   makes the tick fire exactly once, not what causes it to.
//!
//! # Standard-cron day-of-week, not `saffron`'s own
//!
//! `saffron` numbers weekdays `1 = Sunday … 7 = Saturday`; this project's
//! admin-facing contract promises standard cron's `0 = Sunday, 1 = Monday …
//! 6 = Saturday` (with `7` also accepted as a second spelling of Sunday).
//! Both parse sites below run `expression` through
//! `crate::cron_dow::normalize_cron_dow` before handing it to
//! `saffron::Cron::from_str` — the same translation
//! `crate::routine_reconcile::validate_schedule` checks an expression
//! against at admission, so a routine that validates and a routine that
//! fires agree on which calendar days a day-of-week field names (#1644).
//!
//! # What stays out of this module
//!
//! [`crate::routine::RoutineSchedule::Once`] is a schedule variant `saffron`
//! has no notion of at all — every public function here handles it directly,
//! alongside `cron`, so a caller never special-cases the variant itself.
//! Fire-time *policy* (whether a due tick is fresh enough to fire, or so
//! stale it should be logged and skipped) is deliberately NOT here: that is
//! the in-process scheduler's own `CATCH_UP_WINDOW`/`classify_tick`
//! (`polyc_control_plane::routine_scheduler::tick`) — separable from
//! predicting *when* a schedule fires, which is all this module answers.

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

use crate::cron_dow::normalize_cron_dow;
use crate::routine::RoutineSchedule;

/// One predicted fire instant, carrying the zone it was computed in so a
/// caller can render both the routine's local wall-clock time and UTC
/// without re-deriving either from the raw [`RoutineSchedule`].
///
/// A `cron` schedule's zone is `spec.timezone` (or [`Tz::UTC`] when unset); a
/// `once` schedule's zone is always [`Tz::UTC`], since its instant is an
/// explicit RFC3339 timestamp with no separate wall-clock zone of its own.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ScheduledFire {
    /// The real UTC instant this fire occurs at.
    pub at: DateTime<Utc>,
    /// The zone to render [`Self::at`] in for a human-facing "local time"
    /// alongside UTC.
    pub zone: Tz,
}

impl ScheduledFire {
    /// [`Self::at`] rendered in [`Self::zone`]'s local wall-clock time.
    #[must_use]
    pub fn local(&self) -> DateTime<Tz> {
        self.at.with_timezone(&self.zone)
    }
}

/// A `cron` schedule's timezone field, defaulting to UTC — the same default
/// [`crate::routine_reconcile::validate_spec`] admits.
fn zone_or_utc(timezone: Option<&str>) -> Tz {
    timezone
        .and_then(|z| z.parse::<Tz>().ok())
        .unwrap_or(Tz::UTC)
}

/// `schedule`'s own zone.
///
/// A `cron` schedule's `timezone` field (or [`Tz::UTC`] when unset), and
/// always [`Tz::UTC`] for `once` (see [`ScheduledFire`]'s doc). The
/// approval-preview builder (`#1496`, [`crate::routine_preview`]) falls back
/// to this when no admin zone is known — labeling the fallback, never
/// silently guessing one.
#[must_use]
pub fn schedule_zone(schedule: &RoutineSchedule) -> Tz {
    match schedule {
        RoutineSchedule::Cron { timezone, .. } => zone_or_utc(timezone.as_deref()),
        RoutineSchedule::Once { .. } => Tz::UTC,
    }
}

/// Re-tag a real UTC instant's `tz`-local wall-clock fields as a "fake UTC"
/// [`DateTime<Utc>`] — the representation [`saffron::Cron`] evaluates its
/// calendar-field match against. See the module docs.
fn fake_utc_of_local(instant: DateTime<Utc>, tz: Tz) -> DateTime<Utc> {
    Utc.from_utc_datetime(&instant.with_timezone(&tz).naive_local())
}

/// The next instant, strictly after `after`, that `cron` matches when
/// evaluated against `tz`'s local wall clock — `None` only if `cron` can
/// never match any calendar date at all (e.g. `"* * 31 11 *"`, since November
/// has no 31st day). Pure; see the module docs for the DST handling.
///
/// # Fall-back and `after`'s own strictly-after contract
///
/// The ordinary case picks the EARLIER of an ambiguous wall-clock minute's two
/// real realizations (see the module docs) — but when `after` itself already
/// falls inside the repeated hour (a caller re-seeding from a real instant
/// that landed there, e.g. [`due_ticks`]'s own `cursor` advance), the earlier
/// realization can be at or before `after`. Returning it anyway would violate
/// this function's own strictly-after contract — and [`due_ticks`]'s — so a
/// realization that isn't strictly after `after` is discarded in favor of the
/// candidate's OTHER (later) realization when that one still qualifies, and
/// only when NEITHER realization clears `after` (or the candidate is a
/// spring-forward gap that never happens at all) does the search advance to
/// the next calendar match. This never fires an ambiguous minute twice: at
/// most one of its two realizations is ever returned for a given `after`.
fn cron_next_after(cron: &saffron::Cron, tz: Tz, after: DateTime<Utc>) -> Option<DateTime<Utc>> {
    let mut cursor = fake_utc_of_local(after, tz);
    loop {
        let candidate = cron.next_after(cursor)?;
        // `candidate`'s calendar fields ARE the local wall-clock candidate
        // (that's the entire "fake UTC" trick) — re-tag them as real `tz`
        // wall-clock time to find out what (if any) real instant(s) it names.
        let candidate_naive = candidate.naive_utc();
        let realizations: Vec<DateTime<Utc>> = match tz.from_local_datetime(&candidate_naive) {
            LocalResult::Single(local) => vec![local.with_timezone(&Utc)],
            // Fall-back repeat: this wall-clock minute names two real
            // instants. `saffron` only ever produces it once per iteration
            // (it iterates local calendar fields, not real instants), so
            // returning at most one of the two below still fires this tick
            // exactly once regardless of which one qualifies.
            LocalResult::Ambiguous(earlier, later) => {
                vec![earlier.with_timezone(&Utc), later.with_timezone(&Utc)]
            }
            // Spring-forward gap: this wall-clock minute never happens.
            LocalResult::None => Vec::new(),
        };
        // The soonest realization that's strictly after `after` — see this
        // function's doc for why a realization at or before `after` (only
        // reachable via the `Ambiguous` case) must never be returned.
        if let Some(instant) = realizations.into_iter().filter(|i| *i > after).min() {
            return Some(instant);
        }
        // Nothing here qualified: advance past this candidate (in the same
        // fake-UTC representation) and keep searching — never fired late,
        // never fired twice.
        cursor = candidate;
    }
}

/// Every instant `cron` (evaluated against `tz`'s local wall clock) matches
/// in `(since, now]` — strictly after `since`, up to and including `now` —
/// in ascending order. Pure; `since`/`now` are both caller-injected, never
/// read from the system clock.
fn due_ticks(
    cron: &saffron::Cron,
    tz: Tz,
    since: DateTime<Utc>,
    now: DateTime<Utc>,
) -> Vec<DateTime<Utc>> {
    let mut out = Vec::new();
    let mut cursor = since;
    while let Some(next) = cron_next_after(cron, tz, cursor) {
        if next > now {
            break;
        }
        out.push(next);
        cursor = next;
    }
    out
}

/// The next time `schedule` fires strictly after `after`.
///
/// For either [`RoutineSchedule`] variant — the single implementation the
/// confirmation card, the inspector, and the in-process scheduler all
/// consume (INV-RL10).
///
/// `None` when there is no next fire at all: a `cron` expression that fails
/// to parse or can never match any calendar date (both should not happen —
/// [`crate::routine_reconcile::validate_spec`] already rejected them at
/// admission), or a `once` instant that fails to parse as RFC3339 (same
/// reasoning), or one whose instant is not strictly after `after` — which is
/// exactly INV-RL9's "never shows a next fire again" once a `once` schedule
/// has fired.
#[must_use]
pub fn next_fire_after(schedule: &RoutineSchedule, after: DateTime<Utc>) -> Option<ScheduledFire> {
    match schedule {
        RoutineSchedule::Cron {
            expression,
            timezone,
        } => {
            let cron = normalize_cron_dow(expression)
                .parse::<saffron::Cron>()
                .ok()?;
            let tz = zone_or_utc(timezone.as_deref());
            cron_next_after(&cron, tz, after).map(|at| ScheduledFire { at, zone: tz })
        }
        RoutineSchedule::Once { at } => {
            let instant = at.parse::<DateTime<Utc>>().ok()?;
            (instant > after).then_some(ScheduledFire {
                at: instant,
                zone: Tz::UTC,
            })
        }
    }
}

/// Up to `n` fires of `schedule` strictly after `after`, in ascending order.
///
/// The "next-N-fires" preview the confirmation card and the inspector render
/// (zone info via [`ScheduledFire::zone`] renders both local time and UTC).
///
/// Fewer than `n` entries when `schedule` runs out first: a `once` schedule
/// yields at most one entry ever (its own instant, and only while still in
/// the future — never a second entry, and none at all once it has fired); a
/// `cron` expression that can never match again yields zero.
#[must_use]
pub fn next_n_fires_after(
    schedule: &RoutineSchedule,
    after: DateTime<Utc>,
    n: usize,
) -> Vec<ScheduledFire> {
    let mut fires = Vec::with_capacity(n);
    let mut cursor = after;
    while fires.len() < n {
        let Some(fire) = next_fire_after(schedule, cursor) else {
            break;
        };
        cursor = fire.at;
        fires.push(fire);
    }
    fires
}

/// Every instant `schedule` fires in `(since, now]`, in ascending order.
///
/// `None` only when `schedule` fails to parse (a `cron` expression, or a
/// `once` instant as RFC3339) — should not happen, since
/// [`crate::routine_reconcile::validate_spec`] already rejected it at
/// admission. A `once` schedule reports at most its own single instant, and
/// only when it falls strictly after `since` and at or before `now`.
#[must_use]
pub fn due_fires(
    schedule: &RoutineSchedule,
    since: DateTime<Utc>,
    now: DateTime<Utc>,
) -> Option<Vec<DateTime<Utc>>> {
    match schedule {
        RoutineSchedule::Cron {
            expression,
            timezone,
        } => {
            let cron = normalize_cron_dow(expression)
                .parse::<saffron::Cron>()
                .ok()?;
            let tz = zone_or_utc(timezone.as_deref());
            Some(due_ticks(&cron, tz, since, now))
        }
        RoutineSchedule::Once { at } => {
            let instant = at.parse::<DateTime<Utc>>().ok()?;
            Some(if since < instant && instant <= now {
                vec![instant]
            } else {
                Vec::new()
            })
        }
    }
}

/// [`due_fires`] plus [`next_fire_after`] (evaluated at `now`) in one call.
///
/// What the in-process scheduler's tick loop needs each pass. `None` only
/// when `schedule` fails to parse (see [`due_fires`]'s doc); otherwise always
/// `Some`, with the next-fire half independently `None` when there isn't one
/// (see [`next_fire_after`]'s doc).
#[must_use]
pub fn due_fires_and_next(
    schedule: &RoutineSchedule,
    since: DateTime<Utc>,
    now: DateTime<Utc>,
) -> Option<(Vec<DateTime<Utc>>, Option<ScheduledFire>)> {
    let due = due_fires(schedule, since, now)?;
    Some((due, next_fire_after(schedule, now)))
}

#[cfg(test)]
mod tests {
    #![allow(clippy::pedantic, clippy::nursery, missing_docs)]

    use super::*;

    fn utc(s: &str) -> DateTime<Utc> {
        s.parse().expect("valid RFC3339")
    }

    fn cron_schedule(expr: &str, timezone: Option<&str>) -> RoutineSchedule {
        RoutineSchedule::Cron {
            expression: expr.to_owned(),
            timezone: timezone.map(str::to_owned),
        }
    }

    fn once_schedule(at: &str) -> RoutineSchedule {
        RoutineSchedule::Once { at: at.to_owned() }
    }

    /// One [`due_fires`] table case: a schedule, a `(since, now]` window, and
    /// the exact ticks expected in ascending order.
    struct DueFiresCase {
        name: &'static str,
        schedule: RoutineSchedule,
        since: DateTime<Utc>,
        now: DateTime<Utc>,
        expected: Vec<DateTime<Utc>>,
    }

    /// Table-driven, seeded from the scheduler's own DST cases
    /// (`crates/control-plane/src/routine_scheduler/tick.rs:233-318`, prior to
    /// this module's extraction) plus the `once` cases this issue adds.
    #[test]
    fn due_fires_table() {
        let cases = vec![
            DueFiresCase {
                name: "every_10_minutes_utc_finds_every_tick_in_the_window",
                schedule: cron_schedule("*/10 * * * *", None),
                since: utc("2026-07-20T00:00:00Z"),
                now: utc("2026-07-20T00:35:00Z"),
                expected: vec![
                    utc("2026-07-20T00:10:00Z"),
                    utc("2026-07-20T00:20:00Z"),
                    utc("2026-07-20T00:30:00Z"),
                ],
            },
            DueFiresCase {
                name: "excludes_since_and_includes_now",
                schedule: cron_schedule("*/10 * * * *", None),
                since: utc("2026-07-20T00:10:00Z"),
                now: utc("2026-07-20T00:20:00Z"),
                expected: vec![utc("2026-07-20T00:20:00Z")],
            },
            DueFiresCase {
                name: "empty_when_nothing_is_due_yet",
                schedule: cron_schedule("0 9 * * *", None),
                since: utc("2026-07-20T09:00:00Z"),
                now: utc("2026-07-20T10:00:00Z"),
                expected: vec![],
            },
            DueFiresCase {
                name: "spring_forward_gap_is_skipped_not_fired",
                // `America/New_York` jumps from 01:59:59 to 03:00:00 on
                // 2026-03-08 — the 2:30 AM local candidate that day never
                // happens and must be skipped, not reinterpreted or fired
                // twice; the next real fire is the FOLLOWING day.
                schedule: cron_schedule("30 2 * * *", Some("America/New_York")),
                since: utc("2026-03-07T00:00:00Z"),
                now: utc("2026-03-10T00:00:00Z"),
                // 2026-03-07 02:30 EST (UTC-5) = 07:30 UTC; 2026-03-08 (gap
                // day) skipped entirely; 2026-03-09 02:30 EDT (UTC-4) = 06:30
                // UTC.
                expected: vec![utc("2026-03-07T07:30:00Z"), utc("2026-03-09T06:30:00Z")],
            },
            DueFiresCase {
                name: "fall_back_ambiguous_time_fires_once_per_day",
                // `America/New_York` repeats 01:00:00-01:59:59 on 2026-11-01
                // (clocks fall from 2:00 EDT back to 1:00 EST) — the 1:30 AM
                // local candidate that day happens TWICE but must fire only
                // once, resolving to the EARLIER (EDT) realization.
                schedule: cron_schedule("30 1 * * *", Some("America/New_York")),
                since: utc("2026-10-31T00:00:00Z"),
                now: utc("2026-11-02T00:00:00Z"),
                expected: vec![utc("2026-10-31T05:30:00Z"), utc("2026-11-01T05:30:00Z")],
            },
            DueFiresCase {
                name: "fall_back_never_regresses_before_since",
                // Regression case: `since` itself falls inside the SECOND
                // (EST) pass through the repeated hour, so the earlier (EDT)
                // realization of the next candidate would be at-or-before
                // `since` — the later (EST) realization must be returned
                // instead, never a tick at or before `since`.
                schedule: cron_schedule("30 1 * * *", Some("America/New_York")),
                since: utc("2026-11-01T06:10:00Z"),
                now: utc("2026-11-01T12:00:00Z"),
                expected: vec![utc("2026-11-01T06:30:00Z")],
            },
            // ── day-of-week (#1644) ──────────────────────────────────────
            //
            // `saffron` numbers weekdays `1 = Sunday … 7 = Saturday`;
            // standard cron numbers them `0 = Sunday, 1 = Monday … 6 =
            // Saturday` (with `7` also Sunday). Before `normalize_cron_dow`
            // translated ahead of every parse, `1-5` (meant Mon-Fri) matched
            // `saffron`'s own `1-5` (Sun-Thu) instead — firing Sunday,
            // never firing Friday. All fixed dates below fall in the week of
            // 2026-07-20, where 2026-07-24 is a Friday (the same date this
            // issue's live repro used).
            DueFiresCase {
                name: "standard_weekday_range_fires_monday_through_friday_never_a_weekend",
                schedule: cron_schedule("30 11 * * 1-5", None),
                since: utc("2026-07-24T00:00:00Z"), // Friday, start of day
                now: utc("2026-08-01T00:00:00Z"),   // the following Saturday, start of day
                expected: vec![
                    utc("2026-07-24T11:30:00Z"), // Fri
                    utc("2026-07-27T11:30:00Z"), // Mon
                    utc("2026-07-28T11:30:00Z"), // Tue
                    utc("2026-07-29T11:30:00Z"), // Wed
                    utc("2026-07-30T11:30:00Z"), // Thu
                    utc("2026-07-31T11:30:00Z"), // Fri
                                                 // NOT 2026-07-25 (Sat) or 2026-07-26 (Sun).
                ],
            },
            DueFiresCase {
                name: "standard_sunday_zero_fires_on_sundays",
                schedule: cron_schedule("0 9 * * 0", None),
                since: utc("2026-07-24T00:00:00Z"),
                now: utc("2026-08-02T09:00:00Z"),
                expected: vec![utc("2026-07-26T09:00:00Z"), utc("2026-08-02T09:00:00Z")],
            },
            DueFiresCase {
                name: "standard_sunday_seven_also_fires_on_sundays",
                // `7` is standard cron's second spelling of Sunday — must
                // produce the exact same fires as `0` above.
                schedule: cron_schedule("0 9 * * 7", None),
                since: utc("2026-07-24T00:00:00Z"),
                now: utc("2026-08-02T09:00:00Z"),
                expected: vec![utc("2026-07-26T09:00:00Z"), utc("2026-08-02T09:00:00Z")],
            },
            DueFiresCase {
                name: "standard_saturday_six_fires_on_saturdays",
                schedule: cron_schedule("0 9 * * 6", None),
                since: utc("2026-07-24T00:00:00Z"),
                now: utc("2026-08-01T09:00:00Z"),
                expected: vec![utc("2026-07-25T09:00:00Z"), utc("2026-08-01T09:00:00Z")],
            },
            DueFiresCase {
                name: "standard_weekday_step_fires_monday_wednesday_friday",
                schedule: cron_schedule("0 9 * * 1-5/2", None),
                since: utc("2026-07-24T00:00:00Z"),
                now: utc("2026-07-31T09:00:00Z"),
                expected: vec![
                    utc("2026-07-24T09:00:00Z"), // Fri
                    utc("2026-07-27T09:00:00Z"), // Mon
                    utc("2026-07-29T09:00:00Z"), // Wed
                    utc("2026-07-31T09:00:00Z"), // Fri
                ],
            },
            DueFiresCase {
                name: "once_not_yet_due_reports_nothing",
                schedule: once_schedule("2026-07-20T00:10:00Z"),
                since: utc("2026-07-20T00:05:00Z"),
                now: utc("2026-07-20T00:09:00Z"),
                expected: vec![],
            },
            DueFiresCase {
                name: "once_due_fires_exactly_at_its_instant",
                schedule: once_schedule("2026-07-20T00:10:00Z"),
                since: utc("2026-07-20T00:05:00Z"),
                now: utc("2026-07-20T00:10:00Z"),
                expected: vec![utc("2026-07-20T00:10:00Z")],
            },
            DueFiresCase {
                name: "once_already_fired_is_never_due_again",
                schedule: once_schedule("2026-07-20T00:10:00Z"),
                // `since` has advanced past the fired instant.
                since: utc("2026-07-20T00:10:00Z"),
                now: utc("2026-07-20T00:20:00Z"),
                expected: vec![],
            },
        ];

        for case in cases {
            let actual = due_fires(&case.schedule, case.since, case.now)
                .unwrap_or_else(|| panic!("case {}: schedule must parse", case.name));
            assert_eq!(actual, case.expected, "case {}", case.name);
        }
    }

    /// One [`next_fire_after`] table case.
    struct NextFireCase {
        name: &'static str,
        schedule: RoutineSchedule,
        after: DateTime<Utc>,
        expected: Option<DateTime<Utc>>,
    }

    #[test]
    fn next_fire_after_table() {
        let cases = vec![
            NextFireCase {
                name: "composes_a_named_timezone_outside_dst",
                // 09:00 America/New_York, which on this date (outside any
                // DST transition) is UTC-4 (EDT).
                schedule: cron_schedule("0 9 * * *", Some("America/New_York")),
                after: utc("2026-07-20T00:00:00Z"),
                expected: Some(utc("2026-07-20T13:00:00Z")),
            },
            NextFireCase {
                name: "never_regresses_before_after_across_a_fall_back_ambiguity",
                // `after` falls inside the SECOND (EST) pass through
                // `America/New_York`'s repeated 01:00-01:59 local hour on the
                // fall-back day; the candidate's EARLIER (EDT) realization is
                // before `after`, so the LATER (EST) realization — still the
                // same wall-clock day — must be returned instead.
                schedule: cron_schedule("30 1 * * *", Some("America/New_York")),
                after: utc("2026-11-01T06:10:00Z"),
                expected: Some(utc("2026-11-01T06:30:00Z")),
            },
            NextFireCase {
                name: "standard_weekday_range_skips_the_weekend_to_the_next_monday",
                // #1644: `after` is just past Friday's fire, so the next one
                // must be the FOLLOWING Monday, never Saturday or Sunday.
                schedule: cron_schedule("30 11 * * 1-5", None),
                after: utc("2026-07-24T12:00:00Z"), // just after Friday's 11:30 fire
                expected: Some(utc("2026-07-27T11:30:00Z")), // the following Monday
            },
            NextFireCase {
                name: "a_cron_that_never_matches_has_no_next_fire",
                // November has no 31st day.
                schedule: cron_schedule("* * 31 11 *", None),
                after: utc("2026-07-20T00:00:00Z"),
                expected: None,
            },
            NextFireCase {
                name: "once_previews_its_own_instant_while_future",
                schedule: once_schedule("2026-07-20T00:10:00Z"),
                after: utc("2026-07-20T00:09:00Z"),
                expected: Some(utc("2026-07-20T00:10:00Z")),
            },
            NextFireCase {
                name: "once_shows_no_next_fire_once_its_instant_is_reached",
                schedule: once_schedule("2026-07-20T00:10:00Z"),
                after: utc("2026-07-20T00:10:00Z"),
                expected: None,
            },
            NextFireCase {
                name: "once_never_shows_a_next_fire_again_once_completed",
                schedule: once_schedule("2026-07-20T00:10:00Z"),
                after: utc("2026-07-20T00:20:00Z"),
                expected: None,
            },
        ];

        for case in cases {
            let actual = next_fire_after(&case.schedule, case.after).map(|f| f.at);
            assert_eq!(actual, case.expected, "case {}", case.name);
        }
    }

    #[test]
    fn next_fire_after_returns_none_for_an_unparseable_cron_expression() {
        let schedule = cron_schedule("not a cron expression", None);
        assert_eq!(
            next_fire_after(&schedule, utc("2026-07-20T00:00:00Z")),
            None
        );
    }

    #[test]
    fn next_fire_after_returns_none_for_an_unparseable_once_instant() {
        let schedule = once_schedule("not-a-timestamp");
        assert_eq!(
            next_fire_after(&schedule, utc("2026-07-20T00:00:00Z")),
            None
        );
    }

    #[test]
    fn due_fires_returns_none_for_an_unparseable_cron_expression() {
        let schedule = cron_schedule("not a cron expression", None);
        assert_eq!(
            due_fires(
                &schedule,
                utc("2026-07-20T00:00:00Z"),
                utc("2026-07-20T00:10:00Z")
            ),
            None
        );
    }

    #[test]
    fn due_fires_returns_none_for_an_unparseable_once_instant() {
        let schedule = once_schedule("not-a-timestamp");
        assert_eq!(
            due_fires(
                &schedule,
                utc("2026-07-20T00:00:00Z"),
                utc("2026-07-20T00:10:00Z")
            ),
            None
        );
    }

    #[test]
    fn scheduled_fire_local_renders_the_schedules_own_zone() {
        let tz: Tz = "America/New_York".parse().unwrap();
        let fire = ScheduledFire {
            at: utc("2026-07-20T13:00:00Z"),
            zone: tz,
        };
        assert_eq!(
            fire.local().naive_local(),
            utc("2026-07-20T09:00:00Z").naive_utc()
        );
    }

    /// Next-N: a `cron` schedule's preview carries the same zone every entry,
    /// renderable as local plus UTC (acceptance criterion 4).
    #[test]
    fn next_n_fires_after_returns_ascending_instants_with_zone_info() {
        let schedule = cron_schedule("0 9 * * *", Some("America/New_York"));
        let fires = next_n_fires_after(&schedule, utc("2026-07-20T00:00:00Z"), 3);
        let tz: Tz = "America/New_York".parse().unwrap();
        assert_eq!(
            fires.iter().map(|f| f.at).collect::<Vec<_>>(),
            vec![
                utc("2026-07-20T13:00:00Z"),
                utc("2026-07-21T13:00:00Z"),
                utc("2026-07-22T13:00:00Z"),
            ]
        );
        assert!(fires.iter().all(|f| f.zone == tz));
    }

    /// Next-N: a `once` schedule yields exactly its single instant, never a
    /// second entry even when more are requested (INV-RL9's "at most once").
    #[test]
    fn next_n_fires_after_a_once_schedule_yields_only_its_single_instant() {
        let schedule = once_schedule("2026-07-20T00:10:00Z");
        let fires = next_n_fires_after(&schedule, utc("2026-07-20T00:00:00Z"), 5);
        assert_eq!(fires.len(), 1);
        assert_eq!(fires[0].at, utc("2026-07-20T00:10:00Z"));
        assert_eq!(fires[0].zone, Tz::UTC);
    }

    /// Next-N: nothing once a `once` schedule has completed — the "nothing
    /// once completed" half of acceptance criterion 3.
    #[test]
    fn next_n_fires_after_a_completed_once_schedule_yields_nothing() {
        let schedule = once_schedule("2026-07-20T00:10:00Z");
        let fires = next_n_fires_after(&schedule, utc("2026-07-20T00:20:00Z"), 5);
        assert!(fires.is_empty());
    }

    #[test]
    fn schedule_zone_reads_a_crons_own_timezone_and_defaults_to_utc() {
        assert_eq!(
            schedule_zone(&cron_schedule("0 9 * * *", Some("America/New_York"))),
            "America/New_York".parse::<Tz>().unwrap()
        );
        assert_eq!(schedule_zone(&cron_schedule("0 9 * * *", None)), Tz::UTC);
    }

    #[test]
    fn schedule_zone_is_always_utc_for_a_once_schedule() {
        assert_eq!(
            schedule_zone(&once_schedule("2026-07-20T00:10:00Z")),
            Tz::UTC
        );
    }

    #[test]
    fn due_fires_and_next_matches_due_fires_plus_next_fire_after() {
        let schedule = cron_schedule("*/10 * * * *", None);
        let since = utc("2026-07-20T00:00:00Z");
        let now = utc("2026-07-20T00:35:00Z");
        let (due, next) = due_fires_and_next(&schedule, since, now).expect("valid schedule");
        assert_eq!(due, due_fires(&schedule, since, now).unwrap());
        assert_eq!(next, next_fire_after(&schedule, now));
    }

    /// #1644: the callable [`due_fires_and_next`] the in-process scheduler
    /// calls each tick agrees with its own [`due_fires`]/[`next_fire_after`]
    /// halves for a day-of-week schedule too — the confirmation card
    /// (`next_fire_after`/`next_n_fires_after`) and the scheduler
    /// (`due_fires_and_next`) never disagree about which weekday a
    /// standard-cron day-of-week field names (INV-RL10).
    #[test]
    fn due_fires_and_next_matches_for_a_day_of_week_schedule() {
        let schedule = cron_schedule("30 11 * * 1-5", None);
        let since = utc("2026-07-24T00:00:00Z");
        let now = utc("2026-08-01T00:00:00Z");
        let (due, next) = due_fires_and_next(&schedule, since, now).expect("valid schedule");
        assert_eq!(due, due_fires(&schedule, since, now).unwrap());
        assert_eq!(next, next_fire_after(&schedule, now));
        // And the days it actually predicts are Mon-Fri, never a weekend.
        assert_eq!(
            due,
            vec![
                utc("2026-07-24T11:30:00Z"),
                utc("2026-07-27T11:30:00Z"),
                utc("2026-07-28T11:30:00Z"),
                utc("2026-07-29T11:30:00Z"),
                utc("2026-07-30T11:30:00Z"),
                utc("2026-07-31T11:30:00Z"),
            ]
        );
        assert_eq!(
            next,
            Some(ScheduledFire {
                at: utc("2026-08-03T11:30:00Z"),
                zone: Tz::UTC
            })
        );
    }
}