Skip to main content

agentmux_srv_core/backend/cron/
mod.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Persistent cron scheduler for AgentMux.
5//!
6//! Backs each enabled `CronJob` with a tokio task that sleeps until the
7//! next scheduled fire time (its trigger's next slot, [`schedule`]: a cron
8//! expression in the job's time zone, an interval or one time), plus the
9//! job's fixed jitter,
10//! delivers the prompt as `/agentmux/reactive/inject` would — in process
11//! since identity M4c-3 (see [`FireDelivery`]) — and records the fire in the
12//! DB.
13//!
14//! Every fire is a run in the run ledger (`backend::jobs`): its row is
15//! inserted before it fires, which for a slot is the lease two schedulers
16//! sharing a job need, and only a delivered fire counts toward `fire_count`
17//! (docs/specs/SPEC_JOBS_AND_TEMPLATES_2026_10_24.md §3.2). Cron fires are
18//! never held for a stopped agent; what an undelivered fire leaves is the
19//! job's catch-up policy (§5.2): `skip`, a missed run, or `latest`, one
20//! pending fire this scheduler delivers when the agent is back.
21//!
22//! On startup, a `latest` job whose next scheduled time after `last_fired`
23//! is already in the past fires once as catch-up (FIRE_ONCE_NOW — never
24//! replay all missed fires, never cause a cron storm); the slots missed
25//! while AgentMux was off are one collapsed `skipped` row.
26//!
27//! See `docs/specs/SPEC_CRON_LOOP_ROBUSTNESS_2026_06_25.md §3.2`.
28
29pub mod expr;
30pub mod schedule;
31pub mod start;
32
33pub use start::{ActionOutcome, ActionRunner};
34
35use agentmux_common::AUTH_KEY_HEADER;
36use std::collections::HashMap;
37use std::sync::{Arc, Mutex};
38
39use agentmux_common::api_types::InjectRequest;
40use chrono::{DateTime, Utc};
41
42use crate::backend::jobs::admission::Admission;
43use crate::backend::jobs::{self, RunLedger};
44use crate::backend::storage::store::Store;
45use crate::backend::storage::cron::{CronJob, FireProof, WRITER_OPERATOR};
46use crate::backend::mps::Broker;
47use crate::backend::reactive::types::{InjectionRequest, SchedulerFire, SCHEDULER_SENDER};
48
49/// Abort handles for every currently scheduled cron task.
50type HandleMap = Mutex<HashMap<String, tokio::task::AbortHandle>>;
51
52/// Missed slots counted at startup, at most (`jobs::missed_slots`).
53const MISSED_SLOTS_CAP: usize = 100_000;
54
55/// How often pending fires are checked when no agent registers meanwhile.
56const PENDING_SWEEP_EVERY: std::time::Duration = std::time::Duration::from_secs(30);
57
58/// In-process delivery of a fire: the server's shared inject path
59/// (`server::reactive::deliver`, on the instance-key tier), given the job's
60/// request and its creator's UID. Identity M4c-3
61/// (SPEC_AGENT_IDENTITY_CARRIED_NOT_DERIVED_2026_09_23.md §6.5.9): the
62/// scheduler is built before `AppState`, so the server installs this once
63/// `AppState` exists ([`CronScheduler::install_delivery`]), as it installs
64/// agent-turn delivery. Until then a fire POSTs to the route, as before.
65pub type FireDelivery = Arc<
66    dyn Fn(
67            InjectionRequest,
68            String,
69        ) -> std::pin::Pin<Box<dyn std::future::Future<Output = serde_json::Value> + Send>>
70        + Send
71        + Sync,
72>;
73
74/// Whether an agent UID is registered (running) on this instance, so a
75/// pending fire is only attempted once its agent is back.
76pub type AgentPresence = Arc<dyn Fn(&str) -> bool + Send + Sync>;
77
78/// Why a fire reached no one.
79#[derive(Debug, Clone, Copy, PartialEq, Eq)]
80pub(crate) enum MissReason {
81    /// No live agent answered to the job's target UID or name. Cron fires
82    /// are never held, so inject can't tell a stopped agent from a deleted
83    /// one: this covers both.
84    TargetStopped,
85    /// The job names no target at all ([`CronScheduler::deliver`]).
86    TargetMissing,
87}
88
89/// What one fire's delivery decided, computed once in [`CronScheduler::fire`].
90#[derive(Debug, Clone, PartialEq, Eq)]
91pub enum FireOutcome {
92    Delivered { block_id: Option<String> },
93    Missed { reason: MissReason },
94    Failed { error: String },
95}
96
97impl FireOutcome {
98    pub(crate) fn delivered(&self) -> bool {
99        matches!(self, FireOutcome::Delivered { .. })
100    }
101
102    /// The job's `last_miss_reason` for an undelivered fire; `None` when
103    /// delivered.
104    pub(crate) fn miss_reason(&self) -> Option<String> {
105        match self {
106            FireOutcome::Delivered { .. } => None,
107            FireOutcome::Missed { reason: MissReason::TargetStopped } => Some("target_stopped".into()),
108            FireOutcome::Missed { reason: MissReason::TargetMissing } => Some("target_missing".into()),
109            FireOutcome::Failed { error } => Some(format!("failed: {error}")),
110        }
111    }
112}
113
114/// Read a fire's inject answer (`None`: the request itself failed). Cron
115/// fires are never held (`hold_applies`), so a stopped agent answers "agent
116/// not found" like a missing one.
117pub(crate) fn fire_outcome(body: Option<&serde_json::Value>) -> FireOutcome {
118    let Some(body) = body else {
119        return FireOutcome::Failed { error: "inject request failed".to_string() };
120    };
121    if body.get("success").and_then(|v| v.as_bool()) == Some(true) {
122        let block_id = body.get("block_id").and_then(|v| v.as_str()).filter(|s| !s.is_empty()).map(str::to_string);
123        return FireOutcome::Delivered { block_id };
124    }
125    let error = body.get("error").and_then(|v| v.as_str()).unwrap_or("").to_string();
126    if error.starts_with("agent not found") {
127        return FireOutcome::Missed { reason: MissReason::TargetStopped };
128    }
129    FireOutcome::Failed { error }
130}
131
132/// The text a fire delivers: the prompt, then the run line. A slash command
133/// (`/compact`, `/model x`) gets no run line: it would become the command's
134/// arguments. That run is still recorded and followed by its `request_id`;
135/// only its agent can't report an outcome, so it stays `unknown`.
136pub(crate) fn fire_message(prompt: &str, run_id: Option<&str>, late_for: Option<i64>) -> String {
137    match run_id {
138        Some(run_id) if !prompt.trim_start().starts_with('/') => {
139            format!("{prompt}\n\n{}", jobs::brief_line(run_id, late_for, agentmux_common::time::now_ms()))
140        }
141        _ => prompt.to_string(),
142    }
143}
144
145/// Which slot a fire is for (§3.1 `trigger`, `scheduled_for_ms`).
146#[derive(Debug, Clone, PartialEq, Eq)]
147pub enum Slot {
148    /// A scheduled slot, ms epoch.
149    Scheduled(i64),
150    /// The newest slot missed while AgentMux was off, fired at startup.
151    CatchUp(i64),
152    /// Run now, by the operator or an agent uid. Doesn't count toward
153    /// `fire_count` or `last_fired`: those are the schedule's.
154    Manual { triggered_by: String },
155}
156
157/// What a source reports for an `event` job (`CronScheduler::fire_event`).
158#[derive(Debug, Clone)]
159pub struct JobEvent {
160    /// Unique among the source's events; a repeat starts nothing.
161    pub id: String,
162    /// Which source reported it (`definition::event_source`).
163    pub source: String,
164    /// What the run's graph reads as `{{trigger.*}}`: already cut down to the fields the source declares.
165    pub input: serde_json::Value,
166}
167
168/// How a fire ended.
169#[derive(Debug, Clone, PartialEq, Eq)]
170pub struct Fired {
171    /// The run's id in the ledger, when it was recorded.
172    pub run_id: Option<String>,
173    /// `None` when the fire didn't happen: another scheduler had the slot,
174    /// or there was no way to deliver.
175    pub outcome: Option<FireOutcome>,
176    /// Why the run waits to start (policy), when it does: its row is
177    /// `scheduled` with this reason.
178    pub waiting: Option<&'static str>,
179}
180
181/// What `start` found for a job: the newest missed slot, and the earlier
182/// ones as `(first, count)`.
183#[derive(Debug, Clone, Copy, PartialEq, Eq)]
184struct Missed {
185    newest_ms: i64,
186    earlier: Option<(i64, i64)>,
187}
188
189pub struct CronScheduler {
190    handles: HandleMap,
191    /// Where jobs are: `db_jobs` in the shared store.
192    jobs_store: Option<Arc<Store>>,
193    http_client: reqwest::Client,
194    local_url: String,
195    auth_key: String,
196    broker: Arc<Broker>,
197    delivery: std::sync::OnceLock<FireDelivery>,
198    presence: std::sync::OnceLock<AgentPresence>,
199    runs: std::sync::OnceLock<Arc<RunLedger>>,
200    /// Runs the `task` and `spawn` actions ([`ActionRunner`]).
201    actions: std::sync::OnceLock<ActionRunner>,
202    /// Jobs this scheduler disabled for their age bound (`max_age_secs`),
203    /// not paused: their pending fire may still be delivered within that
204    /// bound (`deliver_pending`). Cleared when the job is paused, deleted or
205    /// scheduled again (`cancel_job`). In memory: after a restart such a
206    /// job's pending fire expires like a paused one's.
207    aged_out: Mutex<std::collections::HashSet<String>>,
208}
209
210impl CronScheduler {
211    pub fn new(
212        jobs_store: Option<Arc<Store>>,
213        http_client: reqwest::Client,
214        local_url: String,
215        auth_key: String,
216        broker: Arc<Broker>,
217    ) -> Arc<Self> {
218        Arc::new(Self {
219            handles: Mutex::new(HashMap::new()),
220            jobs_store,
221            http_client,
222            local_url,
223            auth_key,
224            broker,
225            delivery: std::sync::OnceLock::new(),
226            presence: std::sync::OnceLock::new(),
227            runs: std::sync::OnceLock::new(),
228            actions: std::sync::OnceLock::new(),
229            aged_out: Mutex::default(),
230        })
231    }
232
233    /// Deliver fires in process from now on (see [`FireDelivery`]). Once;
234    /// a second install is ignored.
235    pub fn install_delivery(&self, delivery: FireDelivery) {
236        let _ = self.delivery.set(delivery);
237    }
238
239    /// How to tell an agent is back, for pending fires. Once.
240    pub fn install_presence(&self, presence: AgentPresence) {
241        let _ = self.presence.set(presence);
242    }
243
244    /// Record fires in the run ledger from now on. Once; a second install
245    /// is ignored.
246    pub fn install_runs(&self, ledger: Arc<RunLedger>) {
247        let _ = self.runs.set(ledger);
248    }
249
250    /// The run ledger, once installed.
251    pub fn runs(&self) -> Option<&Arc<RunLedger>> {
252        self.runs.get()
253    }
254
255    fn publish_changed(&self) {
256        self.broker.publish_event::<crate::backend::mps_events::CronChanged>(&(), vec![], 0);
257    }
258
259    /// Load all enabled jobs from the DB and schedule them. Call once at startup.
260    pub async fn start(self: &Arc<Self>) {
261        self.start_at(Utc::now()).await;
262    }
263
264    /// [`Self::start`] counting the slots missed while off up to `now_dt`, so a
265    /// test fixes the instant its expected counts are computed from.
266    pub(crate) async fn start_at(self: &Arc<Self>, now_dt: DateTime<Utc>) {
267        let store = match &self.jobs_store {
268            Some(s) => s.clone(),
269            None => {
270                tracing::warn!("cron: no job store — cron scheduler disabled");
271                return;
272            }
273        };
274
275        let jobs = match store.cron_list_enabled() {
276            Ok(j) => j,
277            Err(e) => {
278                tracing::error!(error = %e, "cron: failed to load jobs on startup");
279                return;
280            }
281        };
282
283        let count = jobs.len();
284
285        for job in jobs {
286            let missed = self.missed_while_off(&job, now_dt);
287            self.schedule_job_inner(&job, missed);
288        }
289
290        self.spawn_pending_delivery();
291        tracing::info!(count, "cron: scheduled {} job(s) from DB", count);
292    }
293
294    /// The slots a job missed while AgentMux was off, if any. The base is the
295    /// later of `last_fired` and the job's newest ledger row, so slots the
296    /// ledger already accounts for (a miss while AgentMux ran) aren't counted
297    /// as missed while it was off. Only for a job that has fired before
298    /// (`should_catchup`).
299    fn missed_while_off(&self, job: &CronJob, now_dt: DateTime<Utc>) -> Option<Missed> {
300        if !should_catchup(job, now_dt) {
301            return None;
302        }
303        let mut base_ms = catch_up_base_secs(job).saturating_mul(1000);
304        if let Some(last) = self.runs().and_then(|r| r.store().job_run_last(&job.id).ok().flatten()) {
305            let seen = last.last_skip_at_ms.or(last.scheduled_for_ms).unwrap_or(last.started_at_ms);
306            base_ms = base_ms.max(seen);
307        }
308        let schedule = schedule::JobSchedule::of(job).ok()?;
309        let (newest_ms, earlier) = jobs::missed_slots(&schedule, base_ms, now_dt.timestamp_millis(), MISSED_SLOTS_CAP)?;
310        Some(Missed { newest_ms, earlier })
311    }
312
313    /// Schedule a single job (or reschedule it after a DB change). Replaces
314    /// any existing task for the same `job.id`.
315    pub fn schedule_job(self: &Arc<Self>, job: &CronJob) {
316        self.schedule_job_inner(job, None);
317    }
318
319    fn schedule_job_inner(self: &Arc<Self>, job: &CronJob, missed: Option<Missed>) {
320        self.cancel_job(&job.id);
321
322        let schedule = match schedule::JobSchedule::of(job) {
323            Ok(schedule::JobSchedule::Manual) => return,
324            Ok(s) => s,
325            Err(e) => {
326                tracing::warn!(id = %job.id, expr = %job.expression, error = %e, "cron: invalid trigger — skipping job");
327                return;
328            }
329        };
330        // A one-time job fires at its time; the offset spreads recurring ones.
331        let jitter = if matches!(schedule, schedule::JobSchedule::Once { .. }) { 0 } else { schedule::jitter_ms(&job.id) };
332
333        let sched = self.clone();
334        let job = job.clone();
335        let job_id = job.id.clone();
336
337        let handle = tokio::spawn(async move {
338            // Seeded from the persisted fire_count so max_fires is enforced
339            // across restarts, not per process run.
340            let mut fires: i64 = job.fire_count;
341            // The last slot this loop handled: the next is the one after it,
342            // so the jitter (a fire up to 2 minutes after its slot) never
343            // skips a slot.
344            let mut last_slot: Option<i64> = None;
345            if let Some(m) = missed {
346                // `latest` catches up the newest missed slot; `skip` leaves
347                // every missed slot in the collapsed skip row.
348                let latest = job.catch_up == jobs::CATCH_UP_LATEST;
349                let skipped = match (latest, m.earlier) {
350                    (true, earlier) => earlier,
351                    (false, Some((first, n))) => Some((first, n + 1)),
352                    (false, None) => Some((m.newest_ms, 1)),
353                };
354                if let (Some(runs), Some((first, n))) = (sched.runs(), skipped) {
355                    let (runs, job) = (runs.clone(), job.clone());
356                    let _ = tokio::task::spawn_blocking(move || runs.record_missed_while_off(&job, first, n)).await;
357                }
358                // FIRE_ONCE_NOW, before the first sleep, so the catch-up
359                // counts toward max_fires only when it was delivered.
360                if latest && sched.fire(&job, Slot::CatchUp(m.newest_ms)).await.outcome.is_some_and(|o| o.delivered()) {
361                    fires += 1;
362                }
363            }
364            loop {
365                // Guard at top of loop: if fires was seeded at or above max_fires
366                // (e.g. a catch-up fire brought the persisted count to the cap),
367                // don't fire again before sleeping — this prevents one extra fire
368                // on restart when the catch-up itself hits the limit. Age is
369                // checked the same way (Phase 0, SPEC_AGENT_POLLING_AND_WAKEUP_
370                // HARDENING_2026_08_04.md) — a job created before max_age_secs
371                // existed has max_age_secs = None and is never expired by this.
372                if let Some(max) = job.max_fires {
373                    if fires >= max {
374                        sched.disable_job(&job.id, "max_fires reached");
375                        break;
376                    }
377                }
378                if is_expired_by_age(job.created_at, job.max_age_secs, Utc::now().timestamp()) {
379                    sched.disable_job(&job.id, "max_age_secs reached");
380                    break;
381                }
382                let now_ms = agentmux_common::time::now_ms();
383                let from = last_slot.map_or(now_ms, |l| l.max(now_ms - jitter));
384                let Some(next_ms) = schedule.next_after(from) else {
385                    // A one-time job has had its time.
386                    if matches!(schedule, schedule::JobSchedule::Once { .. }) {
387                        sched.disable_job(&job.id, "once fired");
388                    }
389                    break;
390                };
391                let Some(next) = DateTime::from_timestamp_millis(next_ms) else { break };
392                // Reviewer-caught gap (P1, PR #2418): checking age only in "now"
393                // terms at the top of the loop lets one extra fire slip through
394                // when the cron interval is longer than the remaining time to
395                // expiry — the loop would sleep straight past the expiry bound
396                // and fire anyway, only catching it on the *next* iteration.
397                // Check whether the fire we're about to sleep for would itself
398                // land at/after expiry, and skip it (disable now, don't sleep)
399                // if so — the "hard expiry bound, regardless of fire count"
400                // guarantee has to hold at fire time, not just at loop-top time.
401                if is_expired_by_age(job.created_at, job.max_age_secs, next.timestamp()) {
402                    sched.disable_job(&job.id, "max_age_secs would be reached before the next scheduled fire");
403                    break;
404                }
405                let due = next_ms + jitter - agentmux_common::time::now_ms();
406                tokio::time::sleep(std::time::Duration::from_millis(due.max(0) as u64)).await;
407                last_slot = Some(next_ms);
408                // A pending fire may have been delivered meanwhile: count from
409                // the DB, so max_fires holds across both.
410                if let Some(n) = sched.persisted_fire_count(&job.id) {
411                    fires = fires.max(n);
412                }
413                if job.max_fires.is_some_and(|max| fires >= max) {
414                    sched.disable_job(&job.id, "max_fires reached");
415                    break;
416                }
417                if sched.fire(&job, Slot::Scheduled(next_ms)).await.outcome.is_some_and(|o| o.delivered()) {
418                    fires += 1;
419                }
420                // Post-fire check: enforce max_fires. The top-of-loop guard
421                // handles the restart/seeded-at-cap case; this handles the
422                // normal live-run case.
423                if let Some(max) = job.max_fires {
424                    if fires >= max {
425                        sched.disable_job(&job.id, "max_fires reached");
426                        break;
427                    }
428                }
429            }
430        });
431
432        self.handles.lock().unwrap().insert(job_id, handle.abort_handle());
433    }
434
435    /// Whether a job has a live scheduled task.
436    #[cfg(any(test, feature = "test-support"))]
437    pub fn is_scheduled(&self, id: &str) -> bool {
438        self.handles.lock().unwrap().contains_key(id)
439    }
440
441    /// Stop (abort) a job's scheduled task without removing it from the DB.
442    pub fn cancel_job(&self, id: &str) {
443        self.aged_out.lock().unwrap().remove(id);
444        if let Some(handle) = self.handles.lock().unwrap().remove(id) {
445            handle.abort();
446        }
447    }
448
449    /// Disable a job in the DB (audit trail preserved, unlike delete), drop
450    /// its live task handle, and notify listeners. Shared by every
451    /// self-disabling reason a scheduled job's own loop hits (max_fires,
452    /// max_age_secs) — extracted so those call sites don't each repeat the
453    /// same three-step disable sequence.
454    fn disable_job(&self, job_id: &str, reason: &str) {
455        tracing::info!(id = job_id, reason, "cron: disabling job");
456        if reason.starts_with("max_age_secs") {
457            self.aged_out.lock().unwrap().insert(job_id.to_string());
458        }
459        if let Some(store) = &self.jobs_store {
460            let _ = store.cron_set_enabled(job_id, false);
461        }
462        self.handles.lock().unwrap().remove(job_id);
463        self.publish_changed();
464    }
465
466    /// Run a job now: a `manual` run through the same path as a scheduled
467    /// fire (§3.2), triggered by the operator or an agent uid.
468    pub async fn run_now(&self, job: &CronJob, triggered_by: &str) -> Fired {
469        self.fire(job, Slot::Manual { triggered_by: triggered_by.to_string() }).await
470    }
471
472    /// A source's event for an `event` job: record it (an event the job already heard of starts nothing), let policy
473    /// and the caps decide, and start its drone run with the event's input. A job that is paused or isn't an event job
474    /// ignores it. An event that policy, a cap or Pause all refuses is a `skipped` row, not an error: nobody asked.
475    pub async fn fire_event(&self, job: &CronJob, event: JobEvent) -> Fired {
476        let none = Fired { run_id: None, outcome: None, waiting: None };
477        if !job.enabled || job.trigger_kind != crate::backend::jobs::definition::trigger_kind::EVENT {
478            return none;
479        }
480        let Some(runs) = self.runs().cloned() else { return none };
481        let admitted = {
482            let (runs, owned, id, source, input) = (runs.clone(), job.clone(), event.id.clone(), event.source.clone(), event.input.clone());
483            tokio::task::spawn_blocking(move || runs.admit_event(&owned, &id, &source, &input)).await.unwrap_or(Admission::Unrecorded)
484        };
485        match admitted {
486            Admission::Run(run_id) => {
487                let fired = self.start_run(job, Some(run_id), true, None).await;
488                if matches!(fired.outcome, Some(FireOutcome::Delivered { .. })) {
489                    self.stop_at_max_fires(&job.id);
490                }
491                fired
492            }
493            Admission::Waiting(run_id, why) => {
494                self.publish_changed();
495                Fired { run_id: Some(run_id), outcome: None, waiting: Some(why) }
496            }
497            // A drone run needs a ledger row to follow it: with none recorded there is nothing to start.
498            Admission::Unrecorded | Admission::Taken | Admission::Skipped | Admission::Refused | Admission::Capped(_) => none,
499        }
500    }
501
502    /// Fire a cron job: record the run, deliver the prompt, and record the
503    /// fire in DB when it was delivered.
504    ///
505    /// Identity M3 (spec §5.4): a job that captured its target's UID at
506    /// creation fires BY UID — a job firing at 03:00 must never resolve a
507    /// name. A job with no UID (created before M3, or by a caller that did
508    /// not carry one) fires by name as before, counted.
509    ///
510    /// Identity M4c-3 (§6.5.9): delivered in process ([`FireDelivery`]), with
511    /// the creator's UID as attribution on this instance only — a forwarded
512    /// hop never carries it. **The sender name stays `"cron"`**: showing the
513    /// creator's name unsigned would make every fire of an agent-created job
514    /// look forged (its key is on file under that name) and echo each fire
515    /// into the creator's pane. A job with no captured creator UID fires as
516    /// before, counted.
517    ///
518    /// The run's id is the delivery's `request_id`, and the prompt ends with
519    /// a line naming it, so the agent can report the run's outcome.
520    pub async fn fire(&self, job: &CronJob, slot: Slot) -> Fired {
521        let id = job.id.as_str();
522        let (trigger, scheduled_for, by) = match &slot {
523            Slot::Scheduled(ms) => (jobs::TRIGGER_SCHEDULE, Some(*ms), jobs::BY_SCHEDULER.to_string()),
524            Slot::CatchUp(ms) => (jobs::TRIGGER_CATCH_UP, Some(*ms), jobs::BY_SCHEDULER.to_string()),
525            Slot::Manual { triggered_by } => (jobs::TRIGGER_MANUAL, None, triggered_by.clone()),
526        };
527        if let Some(fired) = self.paused_all_answer(job, scheduled_for).await {
528            return fired;
529        }
530        let admitted = match self.runs() {
531            Some(runs) => {
532                let (runs, owned, by) = (runs.clone(), job.clone(), by);
533                tokio::task::spawn_blocking(move || runs.admit_cron(&owned, trigger, scheduled_for, &by))
534                    .await
535                    .unwrap_or(Admission::Unrecorded)
536            }
537            None => Admission::Unrecorded,
538        };
539        let run_id = match admitted {
540            Admission::Run(run_id) => Some(run_id),
541            Admission::Unrecorded => None,
542            Admission::Taken => {
543                tracing::debug!(id, ?slot, "cron: another scheduler has this slot");
544                return Fired { run_id: None, outcome: None, waiting: None };
545            }
546            Admission::Skipped => return Fired { run_id: None, outcome: None, waiting: None },
547            Admission::Refused => {
548                let error = jobs::OVERLAP_REFUSAL.to_string();
549                return Fired { run_id: None, outcome: Some(FireOutcome::Failed { error }), waiting: None };
550            }
551            Admission::Capped(refusal) => {
552                let error = format!("Run now is refused: {}", refusal.words());
553                return Fired { run_id: None, outcome: Some(FireOutcome::Failed { error }), waiting: None };
554            }
555            Admission::Waiting(run_id, why) => {
556                self.publish_changed();
557                return Fired { run_id: Some(run_id), outcome: None, waiting: Some(why) };
558            }
559        };
560        let late_for = match slot {
561            Slot::CatchUp(ms) => Some(ms),
562            _ => None,
563        };
564        let scheduled = !matches!(slot, Slot::Manual { .. });
565        self.start_run(job, run_id, scheduled, late_for).await
566    }
567
568    /// While the operator has Pause all on (jobs spec §3.3): a slot becomes
569    /// a collapsed `skipped (paused_all)` row and isn't fired, and Run now
570    /// (no slot) is refused. `None` when Pause all is off.
571    async fn paused_all_answer(&self, job: &CronJob, scheduled_for: Option<i64>) -> Option<Fired> {
572        let runs = self.runs()?.clone();
573        let job = job.clone();
574        let answer = tokio::task::spawn_blocking(move || {
575            runs.paused_all()?;
576            Some(match scheduled_for {
577                Some(slot) => {
578                    runs.record_skip_slot(&job, slot, crate::backend::storage::job_runs::reason::PAUSED_ALL);
579                    Fired { run_id: None, outcome: None, waiting: None }
580                }
581                None => Fired {
582                    run_id: None,
583                    outcome: Some(FireOutcome::Failed { error: jobs::PAUSED_ALL_REFUSAL.to_string() }),
584                    waiting: None,
585                },
586            })
587        });
588        answer.await.ok().flatten()
589    }
590
591    /// Deliver `job`'s prompt as run `run_id` (its `request_id`, and the
592    /// brief line), and read the answer. `None` when there is no way to
593    /// deliver at all.
594    async fn deliver(&self, job: &CronJob, run_id: Option<&str>, late_for: Option<i64>) -> Option<FireOutcome> {
595        let id = job.id.as_str();
596        if job.created_by_uid.is_empty() {
597            crate::backend::agent_resolve::record_uid_fallback("m4c.cron_fire_unattributed");
598        }
599        let target_agent = fire_target(&job.target, &job.target_uid).to_string();
600        if target_agent.trim().is_empty() {
601            tracing::warn!(id, "cron: the job names no target");
602            return Some(FireOutcome::Missed { reason: MissReason::TargetMissing });
603        }
604        let message = fire_message(&job.prompt, run_id, late_for);
605        let request_id = run_id.map(str::to_string);
606        let body = match self.delivery.get() {
607            Some(deliver) => {
608                let req = InjectionRequest {
609                    target_agent,
610                    message,
611                    source_agent: Some(SCHEDULER_SENDER.to_string()),
612                    request_id,
613                    scheduler_fire: scheduler_fire_of(job),
614                    ..Default::default()
615                };
616                Some(deliver(req, job.created_by_uid.clone()).await)
617            }
618            None => {
619                if self.local_url.is_empty() || self.auth_key.is_empty() {
620                    tracing::warn!(id, "cron: no local_url/auth_key — skipping fire");
621                    return None;
622                }
623                crate::backend::agent_resolve::record_uid_fallback("m4c.cron_fire_http");
624                self.post_fire(id, target_agent, &message, request_id).await
625            }
626        };
627        let outcome = fire_outcome(body.as_ref());
628        // Inject answers `success: false` when the target is not reachable —
629        // since M3 that includes a UID nobody is registered under. A fire
630        // that reached no one is a failure, and a firing job has nobody to
631        // tell but the log (§5.4) and the run ledger.
632        if outcome.delivered() {
633            tracing::debug!(id, target = %job.target, "cron: fired");
634        } else {
635            tracing::warn!(id, target = %job.target, target_uid = %job.target_uid, ?outcome, "cron: fire was not delivered");
636        }
637        Some(outcome)
638    }
639
640    /// Whether `job` was disabled by this scheduler for its age bound and is
641    /// still inside it (`created_at + max_age_secs`).
642    fn within_age_bound(&self, job: &CronJob, now_ms: i64) -> bool {
643        self.aged_out.lock().unwrap().contains(&job.id)
644            && job.max_age_secs.is_some_and(|age| now_ms < job.created_at.saturating_add(age).saturating_mul(1000))
645    }
646
647    /// Disable a job as its own loop does at a limit (`reason`), for tests.
648    #[cfg(test)]
649    pub(crate) fn disable_for_test(&self, job_id: &str, reason: &str) {
650        self.disable_job(job_id, reason);
651    }
652
653    /// The job's `fire_count` in the DB.
654    fn persisted_fire_count(&self, id: &str) -> Option<i64> {
655        self.jobs_store.as_ref()?.cron_get(id).ok().flatten().map(|j| j.fire_count)
656    }
657
658    /// After a fire the job's own loop didn't make (a pending fire), stop
659    /// that loop if the fire reached `max_fires`; `cron_record_fire` has
660    /// already disabled the job in the DB.
661    fn stop_at_max_fires(&self, id: &str) {
662        let at_max = self
663            .jobs_store
664            .as_ref()
665            .and_then(|s| s.cron_get(id).ok().flatten())
666            .is_some_and(|j| j.max_fires.is_some_and(|max| j.fire_count >= max));
667        if at_max {
668            tracing::info!(id, "cron: a pending fire reached max_fires; stopping the job");
669            self.cancel_job(id);
670        }
671    }
672
673    /// Record a scheduled fire on the job: a delivered one counts
674    /// (`last_fired`, `fire_count`, `max_fires`); one that reached no one is
675    /// a miss (`missed_count`, `last_missed_at`, `last_miss_reason`), which
676    /// Swarm's Cron bucket and `Schedule list` show.
677    fn record_result(&self, id: &str, outcome: &FireOutcome) {
678        if let Some(store) = &self.jobs_store {
679            let now = Utc::now().timestamp();
680            let recorded = match outcome.miss_reason() {
681                None => store.cron_record_fire(id, now),
682                Some(reason) => store.cron_record_miss(id, now, &reason),
683            };
684            if let Err(e) = recorded {
685                tracing::warn!(id, error = %e, "cron: failed to record the fire in DB");
686            }
687        }
688    }
689
690    /// Deliver pending fires (catch-up `latest`) whose agent is back, now and
691    /// whenever an agent registers or every 30 s; expire the ones whose next
692    /// fire time passed or whose job is gone (§5.2).
693    fn spawn_pending_delivery(self: &Arc<Self>) {
694        if self.runs().is_none() {
695            return;
696        }
697        let sched = self.clone();
698        tokio::spawn(async move {
699            loop {
700                sched.deliver_pending().await;
701                sched.run_policy_pass().await;
702                tokio::select! {
703                    _ = jobs::pending_wake().notified() => {}
704                    _ = tokio::time::sleep(PENDING_SWEEP_EVERY) => {}
705                }
706            }
707        });
708    }
709
710    /// One pass over this channel's pending fires. Returns how many were
711    /// delivered.
712    pub(crate) async fn deliver_pending(&self) -> usize {
713        let Some(runs) = self.runs().cloned() else { return 0 };
714        let waiting = {
715            let runs = runs.clone();
716            tokio::task::spawn_blocking(move || runs.waiting_here()).await.unwrap_or_default()
717        };
718        let now = agentmux_common::time::now_ms();
719        let paused_all = {
720            let runs = runs.clone();
721            tokio::task::spawn_blocking(move || runs.paused_all().is_some()).await.unwrap_or(false)
722        };
723        let mut delivered = 0;
724        for run in waiting {
725            let job = self.jobs_store.as_ref().and_then(|s| s.cron_get(&run.job_id).ok().flatten());
726            let expired = match (&job, run.scheduled_for_ms) {
727                (Some(job), Some(slot)) => {
728                    // A pause ends it at once; an age bound only once passed;
729                    // max_fires reached means it may not fire at all.
730                    let stopped = !job.enabled && !self.within_age_bound(job, now);
731                    let at_max = job.max_fires.is_some_and(|max| job.fire_count >= max);
732                    stopped || at_max || jobs::next_slot_after(job, slot).is_none_or(|next| next <= now)
733                }
734                _ => true,
735            };
736            if expired {
737                runs.expire_pending(&run.id);
738                continue;
739            }
740            // Pause all holds it, until it expires as above.
741            if paused_all {
742                continue;
743            }
744            let Some(job) = job else { continue };
745            let back = match (self.presence.get(), job.target_uid.is_empty()) {
746                (Some(present), false) => present(&job.target_uid),
747                // A job by name, or no way to tell: try it.
748                _ => true,
749            };
750            if !back {
751                continue;
752            }
753            // It waits for its place like any other run: policy decides, and a
754            // pending fire that can't start yet stays pending.
755            let may_start = {
756                let (runs, job) = (runs.clone(), job.clone());
757                let run_id = run.id.clone();
758                tokio::task::spawn_blocking(move || runs.pending_may_start(&job, &run_id)).await.unwrap_or(false)
759            };
760            if !may_start {
761                continue;
762            }
763            let delivery_started = agentmux_common::time::now_ms();
764            let Some(outcome) = self.deliver(&job, Some(&run.id), run.scheduled_for_ms).await else {
765                runs.pending_delivery_done(&run.id);
766                continue;
767            };
768            runs.record_pending_delivery(&run, &outcome, delivery_started);
769            runs.pending_delivery_done(&run.id);
770            // Only a delivery is recorded here: the slot already counted as one
771            // miss when it first went undelivered, and a pending fire that
772            // misses again stays pending (it is retried, not a new miss).
773            if outcome.delivered() {
774                self.record_result(&job.id, &outcome);
775                self.stop_at_max_fires(&job.id);
776                delivered += 1;
777                self.publish_changed();
778            }
779        }
780        delivered
781    }
782
783    /// The pre-M4c-3 fire: POST to the local inject route with the instance
784    /// key. Only until [`Self::install_delivery`] runs. `None` when the POST
785    /// itself failed (logged here).
786    async fn post_fire(&self, id: &str, target_agent: String, prompt: &str, request_id: Option<String>) -> Option<serde_json::Value> {
787        let url = format!("{}/agentmux/reactive/inject", self.local_url.trim_end_matches('/'));
788        let req = InjectRequest {
789            target_agent,
790            message: prompt.to_string(),
791            source_agent: Some("cron".to_string()),
792            request_id,
793            ..Default::default()
794        };
795        match self.http_client.post(&url).header(AUTH_KEY_HEADER, &self.auth_key).json(&req).send().await {
796            Ok(r) if r.status().is_success() => Some(r.json().await.unwrap_or_default()),
797            Ok(r) => {
798                tracing::warn!(id, status = %r.status(), "cron: inject returned non-2xx");
799                None
800            }
801            Err(e) => {
802                tracing::warn!(id, error = %e, "cron: inject request failed");
803                None
804            }
805        }
806    }
807}
808
809/// What proves a fire of `job` when this scheduler delivers it in process: the job's name and the identity behind its
810/// definition. `None` when nothing identified who wrote it (it fires unproven, as before). For an agent the name it runs for
811/// is not known here: srv fills it in from the agent's own record, and drops the fact when there is none.
812fn scheduler_fire_of(job: &CronJob) -> Option<SchedulerFire> {
813    let proof = job.fire_proof()?;
814    let name = if job.name.trim().is_empty() { job.id.as_str() } else { job.name.as_str() };
815    Some(match proof {
816        FireProof::Operator => SchedulerFire { job_id: job.id.clone(), job: name.to_string(), proof_uid: String::new(), runs_for: WRITER_OPERATOR.to_string() },
817        FireProof::Agent(uid) => SchedulerFire { job_id: job.id.clone(), job: name.to_string(), proof_uid: uid, runs_for: String::new() },
818    })
819}
820
821/// Determine if a job needs a catch-up fire on startup.
822///
823/// True when there is a scheduled fire time that falls strictly between
824/// `last_fired` and `now` — i.e., the first occurrence of the cron expression
825/// after `last_fired` is already in the past. This is correct regardless of
826/// schedule granularity: a daily job that ran at 09:00 and is restarted at
827/// 09:05 yields a next-after-last of TOMORROW 09:00, which is NOT < now, so
828/// no spurious catch-up fires.
829///
830/// A job that has never fired counts from its creation: a slot after it was
831/// created and already past was missed too (jobs spec §5.2).
832fn should_catchup(job: &CronJob, now_dt: DateTime<Utc>) -> bool {
833    let last = catch_up_base_secs(job);
834    let last_dt = match DateTime::from_timestamp(last, 0) {
835        Some(dt) => dt,
836        None => return false,
837    };
838    let Ok(schedule) = schedule::JobSchedule::of(job) else {
839        return false;
840    };
841    // First scheduled time after last_fired — if it's already past, a fire was missed.
842    match schedule.next_after(last_dt.timestamp_millis()) {
843        Some(next_after_last) => next_after_last < now_dt.timestamp_millis(),
844        None => false,
845    }
846}
847
848/// Where missed slots are counted from: the last fire, or, for a job that
849/// never fired, its creation.
850fn catch_up_base_secs(job: &CronJob) -> i64 {
851    job.last_fired.unwrap_or(job.created_at)
852}
853
854/// True when a job's hard age-expiry bound (`max_age_secs`, seconds since
855/// `created_at`) has been reached. `None` = no bound, never expires by age
856/// (the default for every job created before this field existed, and for
857/// any job that explicitly opts out). See
858/// docs/specs/SPEC_AGENT_POLLING_AND_WAKEUP_HARDENING_2026_08_04.md Phase 0.
859pub(crate) fn is_expired_by_age(created_at: i64, max_age_secs: Option<i64>, now: i64) -> bool {
860    match max_age_secs {
861        Some(max_age) => now - created_at >= max_age,
862        None => false,
863    }
864}
865
866#[cfg(test)]
867mod tests {
868    use super::*;
869
870    #[test]
871    fn is_expired_by_age_none_never_expires() {
872        assert!(!is_expired_by_age(1_000, None, 1_000_000_000));
873    }
874
875    #[test]
876    fn is_expired_by_age_before_bound_is_not_expired() {
877        assert!(!is_expired_by_age(1_000, Some(3_600), 1_000 + 3_599));
878    }
879
880    #[test]
881    fn is_expired_by_age_at_bound_is_expired() {
882        // >= at the boundary, matching the max_fires check's own >= semantics.
883        assert!(is_expired_by_age(1_000, Some(3_600), 1_000 + 3_600));
884    }
885
886    #[test]
887    fn is_expired_by_age_past_bound_is_expired() {
888        assert!(is_expired_by_age(1_000, Some(3_600), 1_000 + 10_000));
889    }
890
891    /// Regression test for PR #2418's P1 review finding: the scheduler now
892    /// calls this same function with the *next scheduled fire's* timestamp,
893    /// not just "now", to decide whether to skip a fire that would land past
894    /// expiry rather than sleeping through the bound and firing anyway. A
895    /// job created 1000s ago with a 3600s bound, checked against a `next`
896    /// fire time far past that bound (e.g. a daily cron job's next fire is
897    /// hours away), must report expired — this is exactly the "would this
898    /// fire itself violate the hard expiry bound" check the loop performs
899    /// before deciding whether to sleep at all.
900    #[test]
901    fn is_expired_by_age_catches_a_next_fire_time_past_the_bound() {
902        let created_at = 1_000;
903        let max_age_secs = Some(3_600);
904        let next_fire_far_in_the_future = created_at + 86_400; // 24h away
905        assert!(is_expired_by_age(created_at, max_age_secs, next_fire_far_in_the_future));
906    }
907}
908
909/// A job for tests: every minute, enabled, never fired, catch-up `skip`.
910#[cfg(any(test, feature = "test-support"))]
911pub fn test_job(id: &str, prompt: &str, target: &str, target_uid: &str, created_by_uid: &str) -> CronJob {
912    CronJob {
913        id: id.to_string(),
914        name: format!("{id} name"),
915        expression: "* * * * *".to_string(),
916        prompt: prompt.to_string(),
917        target: target.to_string(),
918        target_uid: target_uid.to_string(),
919        created_by: "creator".to_string(),
920        created_by_uid: created_by_uid.to_string(),
921        enabled: true,
922        last_fired: None,
923        fire_count: 0,
924        max_fires: None,
925        created_at: 0,
926        max_age_secs: None,
927        catch_up: jobs::CATCH_UP_SKIP.to_string(),
928        ..Default::default()
929    }
930}
931
932/// What a cron fire addresses: the UID when one was captured at creation,
933/// else the name (counted, spec §9.2 — `cron.fire_by_name` reaching zero is
934/// part of M5's exit criterion).
935fn fire_target<'a>(target: &'a str, target_uid: &'a str) -> &'a str {
936    let uid = target_uid.trim();
937    if uid.is_empty() {
938        crate::backend::agent_resolve::record_uid_fallback("cron.fire_by_name");
939        target
940    } else {
941        uid
942    }
943}
944
945#[cfg(test)]
946mod identity_m3_tests {
947    use super::fire_target;
948
949    #[test]
950    fn fires_by_uid_when_captured_and_by_name_otherwise() {
951        assert_eq!(fire_target("AgentY", "4f3c-a91"), "4f3c-a91");
952        assert_eq!(fire_target("AgentY", ""), "AgentY");
953        assert_eq!(fire_target("AgentY", "   "), "AgentY");
954    }
955}
956
957#[cfg(test)]
958mod identity_m4c3_tests {
959    use super::*;
960
961    /// Identity M4c-3 (spec §6.5.9): with delivery installed, a fire goes in
962    /// process — by target UID, as `"cron"`, with the creator's UID beside
963    /// it — and never over HTTP.
964    #[tokio::test]
965    async fn a_fire_is_delivered_in_process_as_cron_with_the_creators_uid() {
966        let sched = CronScheduler::new(
967            None,
968            reqwest::Client::new(),
969            // Unreachable: a fire that fell back to HTTP could not succeed.
970            "http://127.0.0.1:1".to_string(),
971            "test".to_string(),
972            Arc::new(Broker::new()),
973        );
974        let seen: Arc<Mutex<Vec<(InjectionRequest, String)>>> = Arc::default();
975        let sink = seen.clone();
976        sched.install_delivery(Arc::new(move |req, creator_uid| {
977            sink.lock().unwrap().push((req, creator_uid));
978            Box::pin(async { serde_json::json!({"success": true}) })
979        }));
980
981        sched.fire(&test_job("job-1", "check in", "AgentY", "uid-target", "uid-creator"), Slot::Scheduled(0)).await;
982
983        let seen = seen.lock().unwrap();
984        assert_eq!(seen.len(), 1);
985        let (req, creator_uid) = &seen[0];
986        assert_eq!(req.target_agent, "uid-target");
987        assert_eq!(req.message, "check in", "no ledger installed: no run line");
988        assert_eq!(req.source_agent.as_deref(), Some("cron"), "the sender name stays cron");
989        let proof = req.scheduler_fire.as_ref().expect("a job whose creator was identified carries what proves its fire");
990        assert_eq!(proof.proof_uid, "uid-creator", "the creator, named later by srv from its own record");
991        assert_eq!(proof.runs_for, "", "the scheduler does not name it");
992        assert!(!proof.job.is_empty(), "the job's name rides with it");
993        assert_eq!(creator_uid, "uid-creator");
994        assert_eq!(req.audit_source_uid, "", "the delivery path sets it, on this instance only");
995    }
996}
997
998
999#[cfg(test)]
1000mod missed_fire_tests {
1001    use super::*;
1002    use serde_json::json;
1003
1004    fn sched_with(store: Option<Arc<Store>>, answer: serde_json::Value) -> Arc<CronScheduler> {
1005        let sched = CronScheduler::new(
1006            store,
1007            reqwest::Client::new(),
1008            "http://127.0.0.1:1".to_string(),
1009            "test".to_string(),
1010            Arc::new(Broker::new()),
1011        );
1012        sched.install_delivery(Arc::new(move |_, _| {
1013            let answer = answer.clone();
1014            Box::pin(async move { answer })
1015        }));
1016        sched
1017    }
1018
1019    fn store_with(job: &CronJob) -> Arc<Store> {
1020        let store = Arc::new(Store::open_in_memory().expect("store"));
1021        store.apply_identity_schema_for_tests().expect("the identity schema, which holds db_cron_jobs");
1022        store.cron_create(job).expect("create");
1023        store
1024    }
1025
1026    #[test]
1027    fn reads_the_inject_response() {
1028        assert_eq!(
1029            fire_outcome(Some(&json!({"success": true, "block_id": "b-1"}))),
1030            FireOutcome::Delivered { block_id: Some("b-1".into()) }
1031        );
1032        assert_eq!(
1033            fire_outcome(Some(&json!({"success": false, "error": "agent not found: uid-t"}))),
1034            FireOutcome::Missed { reason: MissReason::TargetStopped }
1035        );
1036        assert!(matches!(
1037            fire_outcome(Some(&json!({"success": false, "error": "ambiguous agent name: 'AgentY'"}))),
1038            FireOutcome::Failed { .. }
1039        ));
1040        assert!(matches!(fire_outcome(None), FireOutcome::Failed { .. }));
1041    }
1042
1043    #[test]
1044    fn a_miss_says_why_and_a_delivery_has_no_reason() {
1045        assert_eq!(FireOutcome::Delivered { block_id: None }.miss_reason(), None);
1046        assert_eq!(
1047            FireOutcome::Missed { reason: MissReason::TargetStopped }.miss_reason().as_deref(),
1048            Some("target_stopped")
1049        );
1050        assert_eq!(
1051            FireOutcome::Missed { reason: MissReason::TargetMissing }.miss_reason().as_deref(),
1052            Some("target_missing")
1053        );
1054        assert_eq!(FireOutcome::Failed { error: "x".into() }.miss_reason().as_deref(), Some("failed: x"));
1055    }
1056
1057    /// A scheduled fire nobody received is recorded as a miss with its
1058    /// reason, and `fire_count` (which `max_fires` reads) is left alone.
1059    #[tokio::test]
1060    async fn an_undelivered_fire_is_a_miss_not_a_fire() {
1061        let job = test_job("job-m", "tick", "AgentZ", "uid-z", "uid-y");
1062        let store = store_with(&job);
1063        let sched = sched_with(Some(store.clone()), json!({"success": false, "error": "agent not found: uid-z"}));
1064
1065        let fired = sched.fire(&job, Slot::Scheduled(0)).await;
1066        assert_eq!(fired.outcome, Some(FireOutcome::Missed { reason: MissReason::TargetStopped }));
1067        let stored = store.cron_get("job-m").unwrap().unwrap();
1068        assert_eq!((stored.fire_count, stored.last_fired), (0, None));
1069        assert_eq!((stored.missed_count, stored.last_miss_reason.as_str()), (1, "target_stopped"));
1070        assert!(stored.last_missed_at.is_some());
1071    }
1072
1073    #[tokio::test]
1074    async fn a_delivered_fire_counts_and_leaves_the_miss_record() {
1075        let job = test_job("job-d", "tick", "AgentZ", "uid-z", "uid-y");
1076        let store = store_with(&job);
1077        let sched = sched_with(Some(store.clone()), json!({"success": true, "block_id": "b-1"}));
1078
1079        sched.fire(&job, Slot::Scheduled(0)).await;
1080        let stored = store.cron_get("job-d").unwrap().unwrap();
1081        assert_eq!((stored.fire_count, stored.missed_count), (1, 0));
1082        assert!(stored.last_fired.is_some());
1083    }
1084
1085    /// A job with no target misses without trying to deliver.
1086    #[tokio::test]
1087    async fn a_job_with_no_target_is_a_miss() {
1088        let job = test_job("job-n", "tick", "", "", "uid-y");
1089        let store = store_with(&job);
1090        let sched = sched_with(Some(store.clone()), json!({"success": true}));
1091
1092        let fired = sched.fire(&job, Slot::Scheduled(0)).await;
1093        assert_eq!(fired.outcome, Some(FireOutcome::Missed { reason: MissReason::TargetMissing }));
1094        assert_eq!(store.cron_get("job-n").unwrap().unwrap().last_miss_reason, "target_missing");
1095    }
1096
1097    /// Run now is the ledger's alone: neither a fire nor a miss on the job.
1098    #[tokio::test]
1099    async fn run_now_counts_neither_way() {
1100        let job = test_job("job-r", "tick", "AgentZ", "uid-z", "uid-y");
1101        let store = store_with(&job);
1102        let sched = sched_with(Some(store.clone()), json!({"success": false, "error": "agent not found: uid-z"}));
1103
1104        sched.fire(&job, Slot::Manual { triggered_by: "user".into() }).await;
1105        let stored = store.cron_get("job-r").unwrap().unwrap();
1106        assert_eq!((stored.fire_count, stored.missed_count), (0, 0));
1107    }
1108}