areev-trigger 1.10.1

Areev triggers: declared as grains, evaluated by a one-shot idempotent command, safe to invoke concurrently.
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
//! When is this trigger next due?
//!
//! Interval, cron and one-shot are three declarations of one primitive: a
//! function from "when did it last fire" to "when should it fire next". They
//! are kept apart in the vocabulary because they read differently to a person,
//! not because the evaluator treats them differently.
//!
//! Two behaviours here are worth stating because they are the ones people get
//! wrong:
//!
//! **Rate drifts; cron does not.** `interval_secs` anchors to the *last firing*,
//! so a 3-minute job on a 5-minute interval leaves a 2-minute gap and the
//! effective period depends on runtime. `*/5 * * * *` anchors to wall-clock
//! boundaries and does not. Both are correct; users need to know which they
//! chose, so the two are separate kinds rather than one field with a flag.
//!
//! **Catch-up collapses by default.** A laptop closed over a weekend has missed
//! hundreds of occurrences. `Catchup::Last` fires once on resume, which is what
//! anacron does and what systemd's `Persistent=true` means. `All` replays them
//! and `None` drops them; the three-way is Quartz's misfire vocabulary — fire
//! once now / skip / replay all.

use areev_core::types::{Catchup, Trigger, TriggerKind};
use croner::Cron;

use crate::error::{Result, TriggerError};

/// The zone every build understands, with or without zone data.
const SUPPORTED_TIMEZONE: &str = "UTC";

/// Cron evaluates in the trigger's declared IANA zone under the `tz` feature
/// (#297); a build without it keeps refusing anything but UTC, BY NAME.
///
/// The DST policy is declared here rather than inherited, because real
/// implementations disagree and a silent guess is the wrong move:
///
/// * **Gap** (spring forward): fire ONCE, at the first valid instant after
///   the gap. AWS EventBridge and robfig/cron skip the occurrence entirely;
///   Vixie cron fires it immediately. A daily 02:30 job that simply does not
///   run on one day a year is a silent missed obligation, so Areev fires it
///   late rather than not at all.
/// * **Fold** (fall back): fire ONCE, at the EARLIER occurrence. Everyone
///   agrees on this one.
/// * Missed occurrences collapse per the trigger's own `catchup` policy,
///   unchanged.
///
/// Wildcard and step minute fields are evaluated on local WALL time, which
/// is what "every 15 minutes" means to the person who wrote it.
#[cfg(feature = "tz")]
fn resolve_zone(tz: &str) -> Option<chrono_tz::Tz> {
    tz.parse::<chrono_tz::Tz>().ok()
}

/// Parse and validate a declaration's schedule without evaluating it.
///
/// Called at authoring time so a bad expression is refused when it is written
/// rather than discovered as silence.
pub fn validate(trigger: &Trigger) -> Result<()> {
    if let Some(why) = trigger.incoherence() {
        return Err(TriggerError::Malformed { what: why });
    }
    // A workflow reference that cannot be decoded can never start anything,
    // and `incoherence()` only established it is non-empty. Checking it HERE
    // is what puts it in `trigger status`'s `unusable` column (#67) instead
    // of leaving it to report `waiting` forever and fail at fire time (#73).
    // The scheme prefix is stripped first: both spellings are accepted on
    // write, so both have to be readable.
    if let Err(e) = areev_core::error::Hash::from_hex(trigger.workflow_hash()) {
        return Err(TriggerError::UnresolvedWorkflow {
            hash: trigger.workflow.clone(),
            why: format!(
                "{e} — a workflow is named by its 64-hex content address, \
                 optionally prefixed `sha256:`"
            ),
        });
    }
    // A malformed `--context-query` spelling (#92) can never fire — refuse
    // it at authoring time with the parser's own message. The fire path
    // re-parses (fail-closed) for declarations that bypassed validation.
    if let Some(spec) = trigger.context_query.as_deref() {
        if let Err(why) = crate::context::parse_context_query(spec) {
            return Err(TriggerError::Malformed {
                what: format!("context_query: {why}"),
            });
        }
    }
    if trigger.kind == TriggerKind::Schedule {
        let expr = trigger.cron.as_deref().unwrap_or_default();
        parse_cron(expr)?;
        if let Some(tz) = trigger.config_str(areev_core::types::config_keys::TIMEZONE) {
            check_timezone(expr, tz)?;
        }
    }
    if trigger.kind == TriggerKind::Composite {
        // Refuse at authoring time exactly what firing refuses later. A gate
        // naming a member the declaration does not carry can never be
        // satisfied, so the trigger is dead on arrival -- and a dead trigger's
        // only symptom is nothing happening, which is the whole category this
        // validation exists to catch. Same TRG-E008 either way: the code names
        // the defect, not the moment it was noticed.
        //
        // `incoherence()` has already established the predicate is present.
        if let Some(raw) = trigger.predicate.as_ref() {
            let predicate = crate::predicate::from_value(raw)?;
            for referenced in crate::predicate::referenced_members(&predicate) {
                if !trigger.members.contains_key(&referenced) {
                    return Err(TriggerError::UnknownMember {
                        trigger: "being declared".into(),
                        member: referenced,
                    });
                }
            }
        }
    }
    Ok(())
}

/// Validate a declared zone against what THIS build can evaluate (#297).
///
/// An unknown zone name is refused whether or not zone data is compiled in —
/// a typo must never fall back to UTC and fire at the wrong hour while
/// looking correct. A build without the feature names the feature, so an
/// operator meeting the refusal knows what to change rather than believing
/// the zone itself is unsupported.
fn check_timezone(expr: &str, tz: &str) -> Result<()> {
    if tz.eq_ignore_ascii_case(SUPPORTED_TIMEZONE) {
        return Ok(());
    }
    #[cfg(feature = "tz")]
    {
        if resolve_zone(tz).is_some() {
            return Ok(());
        }
        Err(TriggerError::BadSchedule {
            expr: expr.to_string(),
            why: format!(
                "timezone {tz:?} is not an IANA zone name this build's zone data knows \
                 (e.g. \"America/New_York\", \"Asia/Kolkata\", \"UTC\")"
            ),
        })
    }
    #[cfg(not(feature = "tz"))]
    {
        Err(TriggerError::BadSchedule {
            expr: expr.to_string(),
            why: format!(
                "timezone {tz:?} needs zone data this build does not carry — rebuild \
                 areev-trigger with the `tz` feature, or declare the expression in UTC"
            ),
        })
    }
}

/// The zone this trigger DECLARES, for `trigger status` (#297).
///
/// `None` for UTC and for every non-schedule kind — a status surface should
/// say "this is zoned" only when it is.
pub fn declared_zone(trigger: &Trigger) -> Option<String> {
    if trigger.kind != TriggerKind::Schedule {
        return None;
    }
    trigger_zone(trigger)
}

/// `at_ms` rendered in the trigger's own zone (#297), beside the UTC
/// instant.
///
/// On a DST boundary the UTC instant moves by an hour while the local wall
/// time does not, so a surface showing only UTC looks like the schedule
/// drifted.
#[cfg(feature = "tz")]
pub fn render_local(trigger: &Trigger, at_ms: i64) -> Option<String> {
    let tz = declared_zone(trigger)?;
    let zone = resolve_zone(&tz)?;
    let utc = chrono::DateTime::from_timestamp_millis(at_ms)?;
    Some(format!(
        "{} {}",
        utc.with_timezone(&zone).format("%Y-%m-%dT%H:%M:%S%:z"),
        tz
    ))
}

#[cfg(not(feature = "tz"))]
pub fn render_local(_trigger: &Trigger, _at_ms: i64) -> Option<String> {
    None
}

/// The zone a schedule trigger evaluates in.
fn trigger_zone(trigger: &Trigger) -> Option<String> {
    trigger
        .config_str(areev_core::types::config_keys::TIMEZONE)
        .filter(|tz| !tz.eq_ignore_ascii_case(SUPPORTED_TIMEZONE))
        .map(str::to_string)
}

fn parse_cron(expr: &str) -> Result<Cron> {
    Cron::new(expr)
        .with_seconds_optional()
        .parse()
        .map_err(|e| TriggerError::BadSchedule { expr: expr.to_string(), why: e.to_string() })
}

/// The next instant at or after `after_ms` at which `trigger` should fire.
///
/// `None` means "never again", which only a one-shot past its instant can be.
pub fn next_due_after(trigger: &Trigger, after_ms: i64) -> Result<Option<i64>> {
    match trigger.kind {
        TriggerKind::Once => {
            let at = trigger.at_ms.ok_or_else(|| TriggerError::Malformed {
                what: "a once trigger needs at_ms".into(),
            })?;
            Ok(if at > after_ms { Some(at) } else { None })
        }
        TriggerKind::Interval | TriggerKind::Polling => {
            let secs = trigger.interval_secs.ok_or_else(|| TriggerError::Malformed {
                what: format!("a {} trigger needs interval_secs", trigger.kind.as_str()),
            })?;
            Ok(Some(after_ms.saturating_add(i64::from(secs) * 1000)))
        }
        TriggerKind::Schedule => {
            let expr = trigger.cron.as_deref().unwrap_or_default();
            let cron = parse_cron(expr)?;
            let after = chrono::DateTime::from_timestamp_millis(after_ms).ok_or_else(|| {
                TriggerError::BadSchedule {
                    expr: expr.to_string(),
                    why: format!("{after_ms} is not a representable instant"),
                }
            })?;
            match trigger_zone(trigger) {
                None => {
                    let next = cron.find_next_occurrence(&after, false).map_err(|e| {
                        TriggerError::BadSchedule { expr: expr.to_string(), why: e.to_string() }
                    })?;
                    Ok(Some(next.timestamp_millis()))
                }
                Some(tz) => next_local_occurrence(expr, &cron, &tz, after_ms, after),
            }
        }
        // Push and gate kinds are not clocked: they fire when something arrives.
        TriggerKind::Memory | TriggerKind::Webhook | TriggerKind::Manual | TriggerKind::Composite => {
            Ok(None)
        }
    }
}

/// The next occurrence of `cron` in `tz`, strictly after `after_ms` (#297).
///
/// **The fold hazard, and why the loop exists.** Evaluating in local wall
/// time means an instant inside the repeated hour maps to two UTC instants,
/// and the earlier one wins. So `30 1 * * *` asked from 01:10 EST resolves to
/// 01:30 EDT — an instant BEFORE the question. `advance_after_firing`'s
/// `Some(n) if n > next` guard would then break out of its catch-up loop and
/// leave the schedule stuck. The contract here is therefore "strictly after",
/// enforced by searching forward past the fold rather than trusting the
/// zone-aware search to be monotonic.
#[cfg(feature = "tz")]
fn next_local_occurrence(
    expr: &str,
    cron: &Cron,
    tz: &str,
    after_ms: i64,
    after: chrono::DateTime<chrono::Utc>,
) -> Result<Option<i64>> {
    use chrono::TimeZone;
    let zone = resolve_zone(tz).ok_or_else(|| TriggerError::BadSchedule {
        expr: expr.to_string(),
        why: format!("timezone {tz:?} is not a zone name this build knows"),
    })?;
    let mut cursor = after.with_timezone(&zone);
    // A handful of steps is always enough: at most one fold can sit between
    // a question and its answer, and each step advances the cursor by at
    // least the schedule's own period.
    for _ in 0..8 {
        let next = cron.find_next_occurrence(&cursor, false).map_err(|e| {
            TriggerError::BadSchedule { expr: expr.to_string(), why: e.to_string() }
        })?;
        let ms = next.timestamp_millis();
        if ms > after_ms {
            return Ok(Some(ms));
        }
        // Inside the fold: step one second past the answer in LOCAL terms
        // and ask again, which lands on the second pass of the repeated hour.
        cursor = zone.from_utc_datetime(
            &chrono::DateTime::from_timestamp_millis(ms + 1_000)
                .ok_or_else(|| TriggerError::BadSchedule {
                    expr: expr.to_string(),
                    why: "instant out of range while resolving a DST fold".into(),
                })?
                .naive_utc(),
        );
    }
    Err(TriggerError::BadSchedule {
        expr: expr.to_string(),
        why: format!(
            "no occurrence strictly after {after_ms} in {tz} within the DST search bound"
        ),
    })
}

/// Without zone data there is no local evaluation to do — `validate` already
/// refused the declaration, and this is the fail-closed backstop for a
/// declaration that reached the fire path unvalidated (imported in a bundle,
/// say).
#[cfg(not(feature = "tz"))]
fn next_local_occurrence(
    expr: &str,
    _cron: &Cron,
    tz: &str,
    _after_ms: i64,
    _after: chrono::DateTime<chrono::Utc>,
) -> Result<Option<i64>> {
    Err(TriggerError::BadSchedule {
        expr: expr.to_string(),
        why: format!(
            "timezone {tz:?} needs zone data this build does not carry — rebuild \
             areev-trigger with the `tz` feature, or declare the expression in UTC"
        ),
    })
}

/// Where to set `next_due_at` after a firing that happened at `fired_at_ms`,
/// given that it is now `now_ms`.
///
/// This is where catch-up policy lands. If evaluation stalled — the host was
/// asleep, the process was down — the naive next instant can be far in the
/// past, and the question is whether to replay the gap.
pub fn advance_after_firing(trigger: &Trigger, fired_at_ms: i64, now_ms: i64) -> Result<Option<i64>> {
    let Some(mut next) = next_due_after(trigger, fired_at_ms)? else {
        return Ok(None);
    };
    if next > now_ms {
        return Ok(Some(next));
    }
    match trigger.catchup {
        // Replay: leave the schedule where it is and let each stale occurrence
        // fire in turn.
        Catchup::All => Ok(Some(next)),
        // Collapse the backlog into a single firing. Walk forward to the first
        // occurrence still ahead of us; one firing already happened, and the
        // others are missed rather than owed.
        Catchup::Last | Catchup::None => {
            // Bounded so a long-dormant memory with a fast interval cannot spin:
            // a year of one-second occurrences would otherwise be 31 million
            // steps. Past the bound we jump straight off `now`.
            const MAX_STEPS: u32 = 10_000;
            let mut steps = 0;
            while next <= now_ms && steps < MAX_STEPS {
                match next_due_after(trigger, next)? {
                    Some(n) if n > next => next = n,
                    // A schedule that does not advance would loop forever.
                    _ => break,
                }
                steps += 1;
            }
            if next <= now_ms {
                next = next_due_after(trigger, now_ms)?.unwrap_or(next);
            }
            Ok(Some(next))
        }
    }
}

/// When a never-evaluated trigger first becomes due.
///
/// `None` means "now". `Some(t)` means "not yet — at `t`", and the evaluator
/// records it so the trigger wakes at the right moment instead of being asked
/// this question again on every pass.
///
/// The split is between two kinds of cadence:
///
/// - **Relative** (`Interval`, `Polling`) has no baseline to wait out, so it
///   fires at once — the loop gate's rule, and what makes a polling trigger
///   seed its cursor promptly instead of an interval later.
/// - **Absolute** (`Schedule`, `Once`) waits for the instant it names. A cron of
///   `0 9 * * *` must not fire at midnight merely because it was just declared.
/// - **Unclocked** kinds are eligible immediately; what gates them is whether
///   anything arrived, which the evaluator decides.
pub fn initial_due(trigger: &Trigger, now_ms: i64) -> Result<Option<i64>> {
    Ok(match trigger.kind {
        TriggerKind::Schedule => next_due_after(trigger, now_ms)?,
        // A one-shot whose instant has already passed fires once, now.
        TriggerKind::Once => trigger.at_ms.filter(|at| *at > now_ms),
        TriggerKind::Interval
        | TriggerKind::Polling
        | TriggerKind::Memory
        | TriggerKind::Webhook
        | TriggerKind::Manual
        | TriggerKind::Composite => None,
    })
}

/// Is this trigger due at `now_ms`?
///
/// The complete check: state alone cannot answer it, because an absent
/// `next_due_at` means "never evaluated" and what that implies depends on the
/// declaration. See [`initial_due`].
pub fn is_due(trigger: &Trigger, state: &areev_store::TriggerState, now_ms: i64) -> Result<bool> {
    if !state.permits_firing(now_ms) {
        return Ok(false);
    }
    if state.next_due_at.is_some() {
        return Ok(true); // already compared against `now` above
    }
    Ok(initial_due(trigger, now_ms)?.is_none())
}

/// Whether this trigger can never fire again after a firing at `fired_at_ms`.
///
/// Only a one-shot exhausts. The other kinds that return no next instant
/// (`Memory`, `Webhook`, `Manual`, `Composite`) are not clocked at all — they
/// are eligible on every pass and gated by whether anything arrived — so
/// treating "no next instant" as exhaustion would silence them permanently.
pub fn exhausts_after(trigger: &Trigger, fired_at_ms: i64) -> bool {
    trigger.kind == TriggerKind::Once
        && next_due_after(trigger, fired_at_ms).ok().flatten().is_none()
}

/// Back off `next_due_at` after a failure, so a broken connector does not
/// hot-loop against a source that is down.
///
/// Exponential on consecutive failures, capped, and never shorter than the
/// declared interval — a trigger that fails fast should not end up polling
/// *more* often than a healthy one.
pub fn backoff_until(trigger: &Trigger, consecutive_failures: u32, now_ms: i64) -> i64 {
    const BASE_MS: i64 = 30_000;
    const CAP_MS: i64 = 3_600_000;
    let shift = consecutive_failures.saturating_sub(1).min(7);
    let penalty = (BASE_MS << shift).min(CAP_MS);
    let floor = trigger.interval_secs.map(|s| i64::from(s) * 1000).unwrap_or(0);
    now_ms.saturating_add(penalty.max(floor))
}

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

    const WF: &str = "a1b2c3d4e5f60718293a4b5c6d7e8f90a1b2c3d4e5f60718293a4b5c6d7e8f90";
    /// 2026-01-01T00:00:00Z
    const T0: i64 = 1_767_225_600_000;

    fn interval(secs: u32) -> Trigger {
        Trigger::new(TriggerKind::Interval, WF).interval_secs(secs)
    }
    fn schedule(expr: &str) -> Trigger {
        Trigger::new(TriggerKind::Schedule, WF).cron(expr)
    }

    #[test]
    fn interval_anchors_to_the_last_firing() {
        let t = interval(120);
        assert_eq!(next_due_after(&t, T0).unwrap(), Some(T0 + 120_000));
        // …and therefore drifts: firing late pushes the next one out.
        assert_eq!(next_due_after(&t, T0 + 5_000).unwrap(), Some(T0 + 125_000));
    }

    #[test]
    fn cron_anchors_to_wall_clock_boundaries() {
        let t = schedule("*/5 * * * *");
        let first = next_due_after(&t, T0).unwrap().unwrap();
        assert_eq!(first, T0 + 300_000, "next boundary from midnight");
        // Firing late still lands on the boundary — no drift.
        let after_late = next_due_after(&t, T0 + 301_000).unwrap().unwrap();
        assert_eq!(after_late, T0 + 600_000);
    }

    #[test]
    fn a_five_field_weekday_expression_parses_with_posix_numbering() {
        // The trap this guards: the most-downloaded Rust cron crate requires 7
        // fields with mandatory seconds and Quartz day numbering where 1=Sun and
        // 0 is rejected, so it reads this expression as the wrong days.
        let t = schedule("0 9 * * 1-5");
        let next = next_due_after(&t, T0).unwrap().unwrap();
        let dt = chrono::DateTime::from_timestamp_millis(next).unwrap();
        use chrono::{Datelike, Timelike};
        assert_eq!(dt.hour(), 9);
        assert_eq!(dt.minute(), 0);
        let wd = dt.weekday().num_days_from_monday();
        assert!(wd < 5, "must land Mon-Fri, got {:?}", dt.weekday());
    }

    #[test]
    fn a_one_shot_fires_once_and_then_never() {
        let t = Trigger::new(TriggerKind::Once, WF).at_ms(T0 + 1_000);
        assert_eq!(next_due_after(&t, T0).unwrap(), Some(T0 + 1_000));
        assert_eq!(next_due_after(&t, T0 + 1_000).unwrap(), None, "not due at its own instant again");
        assert_eq!(next_due_after(&t, T0 + 9_999).unwrap(), None);
    }

    #[test]
    fn push_and_gate_kinds_are_not_clocked() {
        for kind in [TriggerKind::Webhook, TriggerKind::Manual, TriggerKind::Memory] {
            let t = Trigger::new(kind, WF);
            assert_eq!(next_due_after(&t, T0).unwrap(), None, "{kind:?} should not be clocked");
        }
    }

    #[test]
    fn catchup_last_collapses_a_weekend_of_missed_occurrences() {
        // Fired Friday, evaluated Monday: a 5-minute schedule missed ~800
        // occurrences. Exactly one firing is owed, not eight hundred.
        let t = schedule("*/5 * * * *").catchup(Catchup::Last);
        let three_days = 3 * 86_400_000;
        let next = advance_after_firing(&t, T0, T0 + three_days).unwrap().unwrap();
        assert!(next > T0 + three_days, "must be scheduled ahead of now, not in the backlog");
        assert!(next <= T0 + three_days + 300_000, "and at the very next boundary");
    }

    #[test]
    fn catchup_all_leaves_the_backlog_in_place() {
        let t = schedule("*/5 * * * *").catchup(Catchup::All);
        let three_days = 3 * 86_400_000;
        let next = advance_after_firing(&t, T0, T0 + three_days).unwrap().unwrap();
        assert_eq!(next, T0 + 300_000, "the stale occurrence stays due, to be replayed");
    }

    #[test]
    fn collapsing_is_bounded_for_a_fast_interval_over_a_long_gap() {
        // A one-second interval dormant for a year is ~31M occurrences. The walk
        // must not attempt them.
        let t = interval(1).catchup(Catchup::Last);
        let a_year = 365 * 86_400_000i64;
        let started = std::time::Instant::now();
        let next = advance_after_firing(&t, T0, T0 + a_year).unwrap().unwrap();
        assert!(next > T0 + a_year);
        assert!(started.elapsed().as_millis() < 500, "the collapse walk must be bounded");
    }

    #[test]
    fn a_firing_that_is_still_ahead_of_now_is_left_alone() {
        let t = interval(300);
        let next = advance_after_firing(&t, T0, T0 + 1_000).unwrap().unwrap();
        assert_eq!(next, T0 + 300_000);
    }

    #[test]
    fn backoff_grows_then_caps_and_never_polls_faster_than_the_interval() {
        let t = interval(600); // 10 minutes
        let first = backoff_until(&t, 1, T0) - T0;
        let second = backoff_until(&t, 2, T0) - T0;
        assert!(second >= first, "backoff must not shrink as failures accumulate");

        // Never more often than the declared interval: a failing trigger must
        // not end up hammering a source harder than a healthy one.
        assert!(first >= 600_000, "floor is the declared interval");

        let far = backoff_until(&t, 99, T0) - T0;
        assert!(far <= 3_600_000, "and it caps rather than growing without bound");
    }

    #[test]
    fn an_unparseable_expression_is_refused_with_its_code() {
        let t = schedule("not a cron expression");
        let e = validate(&t).unwrap_err();
        assert_eq!(e.code(), "TRG-E006");
        assert!(e.to_string().starts_with("TRG-E006"));
    }

    #[test]
    fn utc_is_accepted_however_it_is_spelled() {
        let ok = schedule("0 9 * * *").config(serde_json::json!({ "int:timezone": "utc" }));
        assert!(validate(&ok).is_ok());
        let ok = schedule("0 9 * * *").config(serde_json::json!({ "int:timezone": "UTC" }));
        assert!(validate(&ok).is_ok());
    }

    #[test]
    fn an_unknown_zone_name_is_refused_whatever_the_build() {
        // A typo must never fall back to UTC and fire at the wrong hour while
        // looking correct.
        let t = schedule("0 9 * * *")
            .config(serde_json::json!({ "int:timezone": "Mars/Olympus" }));
        let e = validate(&t).unwrap_err();
        assert_eq!(e.code(), "TRG-E006");
    }

    #[cfg(not(feature = "tz"))]
    #[test]
    fn a_build_without_zone_data_refuses_and_names_the_feature() {
        let t = schedule("0 9 * * *")
            .config(serde_json::json!({ "int:timezone": "America/New_York" }));
        let e = validate(&t).unwrap_err();
        assert_eq!(e.code(), "TRG-E006");
        assert!(e.to_string().contains("`tz` feature"), "{e}");
    }

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

        fn zoned(expr: &str, tz: &str) -> Trigger {
            schedule(expr).config(serde_json::json!({ "int:timezone": tz }))
        }

        fn ms(iso: &str) -> i64 {
            areev_core::time::iso8601_to_ms(iso).unwrap()
        }

        #[test]
        fn a_declared_zone_validates() {
            assert!(validate(&zoned("0 8 * * 1", "America/New_York")).is_ok());
            assert!(validate(&zoned("0 9 * * *", "Asia/Kolkata")).is_ok());
        }

        #[test]
        fn a_weekly_local_time_tracks_the_offset_across_the_dst_boundary() {
            // 08:00 New York is 12:00Z in EDT and 13:00Z in EST. Declaring it
            // in UTC means being an hour wrong for half the year — the thing
            // a zone declaration exists to prevent.
            let t = zoned("0 8 * * 1", "America/New_York");
            let first = next_due_after(&t, ms("2026-10-19T12:00:01Z")).unwrap().unwrap();
            assert_eq!(first, ms("2026-10-26T12:00:00Z"), "still EDT");
            let second = next_due_after(&t, first).unwrap().unwrap();
            assert_eq!(second, ms("2026-11-02T13:00:00Z"), "EST after the change");
        }

        #[test]
        fn a_time_skipped_by_spring_forward_fires_once_at_the_next_valid_minute() {
            // 02:30 does not exist on 2026-03-08 in New York: the clock jumps
            // 02:00 EST → 03:00 EDT. Skipping the occurrence entirely (what
            // EventBridge and robfig/cron do) is a silent missed obligation
            // once a year, so Areev fires it LATE rather than not at all —
            // once, at the first valid instant after the gap.
            let t = zoned("30 2 * * *", "America/New_York");
            let gap_day = next_due_after(&t, ms("2026-03-07T12:00:00Z")).unwrap().unwrap();
            assert_eq!(
                gap_day,
                ms("2026-03-08T07:00:00Z"),
                "03:00 EDT — the first valid instant after the gap"
            );
            // Exactly one firing for that day: the next is the following day
            // at 02:30 EDT (06:30Z), not a second pass at the gap.
            let next = next_due_after(&t, gap_day).unwrap().unwrap();
            assert_eq!(next, ms("2026-03-09T06:30:00Z"));
        }

        #[test]
        fn an_ordinary_day_fires_at_the_declared_local_time() {
            // The control for the gap case: 02:30 EST is 07:30Z.
            let t = zoned("30 2 * * *", "America/New_York");
            let fired = next_due_after(&t, ms("2026-03-06T12:00:00Z")).unwrap().unwrap();
            assert_eq!(fired, ms("2026-03-07T07:30:00Z"));
        }

        #[test]
        fn a_repeated_time_fires_once_at_the_earlier_occurrence() {
            // 01:30 happens twice on 2026-11-01 in New York (05:30Z EDT and
            // 06:30Z EST). Firing twice would double-run a daily job.
            let t = zoned("30 1 * * *", "America/New_York");
            let first = next_due_after(&t, ms("2026-11-01T00:00:00Z")).unwrap().unwrap();
            assert_eq!(first, ms("2026-11-01T05:30:00Z"), "the earlier one");
            let next = next_due_after(&t, first).unwrap().unwrap();
            assert_eq!(
                next,
                ms("2026-11-02T06:30:00Z"),
                "the next DAY, not the second pass of the repeated hour"
            );
        }

        #[test]
        fn every_answer_is_strictly_after_the_question_across_the_fold() {
            // The hazard: inside the repeated hour the earlier instant wins,
            // so a naive local search can answer at or before `after_ms` —
            // and `advance_after_firing`'s `n > next` guard would then break
            // out of its loop and leave the schedule stuck.
            let t = zoned("30 1 * * *", "America/New_York");
            let start = ms("2026-11-01T05:00:00Z");
            let end = ms("2026-11-01T07:00:00Z");
            let mut at = start;
            while at < end {
                let got = next_due_after(&t, at).unwrap().unwrap();
                assert!(got > at, "answer {got} must be strictly after {at}");
                at += 60_000;
            }
        }

        #[test]
        fn catchup_last_across_a_dst_boundary_collapses_to_one_firing() {
            let mut t = zoned("30 1 * * *", "America/New_York");
            t.catchup = Catchup::Last;
            let fired = ms("2026-10-30T05:30:00Z");
            let now = ms("2026-11-03T12:00:00Z");
            let next = advance_after_firing(&t, fired, now).unwrap().unwrap();
            assert!(next > now, "one firing ahead, not a backlog: {next}");
        }

        #[test]
        fn an_absent_or_utc_zone_is_unchanged() {
            let utc = schedule("0 9 * * *");
            let zoned_utc = zoned("0 9 * * *", "UTC");
            let at = ms("2026-03-08T00:00:00Z");
            assert_eq!(
                next_due_after(&utc, at).unwrap(),
                next_due_after(&zoned_utc, at).unwrap()
            );
        }
    }

    #[test]
    fn validate_rejects_an_incoherent_declaration_before_the_schedule() {
        let t = Trigger::new(TriggerKind::Interval, WF); // no interval_secs
        let e = validate(&t).unwrap_err();
        assert_eq!(e.code(), "TRG-E001");
    }
}