Skip to main content

agentmux_srv_core/backend/jobs/
watchdog.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The watchdog for cloud jobs (docs/specs/SPEC_JOBS_AND_TEMPLATES_2026_10_24.md §4.4).
5//!
6//! A scheduler can't report its own outage, so this compares what should have run with what the ledger has:
7//!
8//! - **A slot with no report.** A cloud job's expected slot plus its grace has passed and the ledger has no run for
9//!   it: a `missed` row (`no_report`) takes the slot. A late event for that slot takes the row over and it reads
10//!   "late" (`storage::job_cloud`), so a slot is one row whichever way it ends.
11//! - **A run that stopped reporting.** A `started` run with no `finished` event, and no heartbeat, within the job's
12//!   `maxDurationMinutes` becomes `lost`.
13//! - **A local slot nothing handled** (the second half of this file). A local job's slot passed while AgentMux was
14//!   running and the ledger has no row for it, not even a skip: the job's scheduler task is gone or stalled. A
15//!   `missed` row (`not_started`) takes the slot.
16//!
17//! Both are failures the incident keeper judges like any other (§3.4): several misses of one job are one incident,
18//! one task and one alert. A pass runs every five minutes, and once after start-up, a little late so that what the
19//! relay held while this computer was off has been handed over first.
20
21use std::collections::BTreeSet;
22use std::sync::Arc;
23
24use agentmux_common::time::now_ms;
25
26use super::{RunLedger, SOURCE_CLOUD, SOURCE_CRON, TRIGGER_SCHEDULE};
27use crate::backend::cron::schedule::{JobSchedule, JITTER_MAX_MS};
28use crate::backend::job_templates::cloud::CloudExpect;
29use crate::backend::job_templates::JobTemplates;
30use crate::backend::storage::cron::CronJob;
31use crate::backend::storage::job_runs::{reason, state, JobRun};
32use crate::backend::storage::store::Store;
33
34const DAY_MS: i64 = 24 * 3600 * 1000;
35/// Between two passes.
36const PASS_MS: u64 = 5 * 60 * 1000;
37/// Before the first pass.
38const SETTLE_MS: u64 = 2 * 60 * 1000;
39/// How far back a pass looks for slots without a report: an event older than this is refused anyway (§4.2), so a
40/// slot given up on earlier could not turn late.
41const LOOKBACK_MS: i64 = 7 * DAY_MS;
42/// Slots read per job in a pass, newest first.
43const MAX_SLOTS_LOOKED_AT: usize = 2000;
44/// Misses written per job in a pass: the newest. A job that reports every minute and was cut off for a day is one
45/// incident whatever the count, and its ledger is not filled with a day of rows.
46const MAX_MISSES_PER_PASS: usize = 50;
47/// A run that started this long before its slot, or a clock this far off, still belongs to the slot.
48const SLOT_SLACK_MS: i64 = 60 * 1000;
49/// How long a run of a job nobody approves any more may go without a report before it is `lost`.
50const UNKNOWN_JOB_MAX_RUN_MS: i64 = DAY_MS;
51/// Who gave up on a slot.
52const BY_WATCHDOG: &str = "watchdog";
53
54/// The schedule a cloud job reports on, and how long after a slot its report may be.
55pub struct WatchedSchedule {
56    pub schedule: JobSchedule,
57    pub grace_ms: i64,
58}
59
60/// A cloud job as the watchdog needs it.
61pub struct WatchedJob {
62    pub id: String,
63    pub name: String,
64    /// When it was approved: no slot before this is a miss.
65    pub since_ms: i64,
66    /// `None` for a job that events start.
67    pub schedule: Option<WatchedSchedule>,
68    /// How long a run may go without a report before it is `lost`.
69    pub max_run_ms: i64,
70}
71
72/// Where the cloud jobs to watch come from.
73pub trait WatchedJobs {
74    fn watched_jobs(&self) -> Vec<WatchedJob>;
75}
76
77/// The cloud templates the operator approved.
78impl WatchedJobs for Arc<JobTemplates> {
79    fn watched_jobs(&self) -> Vec<WatchedJob> {
80        self.approved_clouds()
81            .into_iter()
82            .filter_map(|t| {
83                let m = &t.manifest;
84                let schedule = match m.expect.as_ref()? {
85                    CloudExpect::Never(_) => None,
86                    CloudExpect::Schedule(s) => {
87                        Some(WatchedSchedule { schedule: JobSchedule::cron(&s.cron, &s.tz).ok()?, grace_ms: i64::from(s.grace_minutes) * 60_000 })
88                    }
89                };
90                Some(WatchedJob {
91                    id: t.id.clone(),
92                    name: m.name.clone(),
93                    since_ms: t.approved_at_ms,
94                    schedule,
95                    max_run_ms: i64::from(m.max_duration_minutes?) * 60_000,
96                })
97            })
98            .collect()
99    }
100}
101
102/// What a pass gave up on.
103#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
104pub struct Watched {
105    pub missed: usize,
106    pub lost: usize,
107}
108
109impl RunLedger {
110    /// One pass of the watchdog over `jobs` at `now_ms`. Blocking. A job that gave up a slot or a run is told to the
111    /// Jobs tab and the incident keeper. Running it again changes nothing.
112    pub fn watch_cloud(&self, jobs: &[WatchedJob], now_ms: i64) -> Watched {
113        let mut out = Watched::default();
114        let mut touched: BTreeSet<&str> = BTreeSet::new();
115        for job in jobs {
116            let missed = self.give_up_slots(job, now_ms);
117            out.missed += missed;
118            if missed > 0 {
119                touched.insert(&job.id);
120            }
121        }
122        let running = match self.store().job_cloud_running() {
123            Ok(runs) => runs,
124            Err(e) => {
125                tracing::warn!(target: "jobs", error = %e, "jobs: the watchdog couldn't read the running cloud runs");
126                Vec::new()
127            }
128        };
129        let mut lost_jobs = BTreeSet::new();
130        for run in running {
131            let max_run_ms = jobs.iter().find(|j| j.id == run.job_id).map_or(UNKNOWN_JOB_MAX_RUN_MS, |j| j.max_run_ms);
132            if now_ms <= last_heard_from(&run) + max_run_ms {
133                continue;
134            }
135            match self.store().job_cloud_lose(&run.id, now_ms, max_run_ms) {
136                Ok(true) => {
137                    out.lost += 1;
138                    lost_jobs.insert(run.job_id);
139                }
140                Ok(false) => {}
141                Err(e) => tracing::warn!(target: "jobs", error = %e, run = %run.id, "jobs: the watchdog couldn't give up on a run"),
142            }
143        }
144        for job_id in touched.into_iter().map(str::to_string).chain(lost_jobs) {
145            self.changed(&job_id);
146        }
147        out
148    }
149
150    /// A `missed` row for each slot of `job` whose grace has passed with no run for it; how many it wrote.
151    fn give_up_slots(&self, job: &WatchedJob, now_ms: i64) -> usize {
152        let Some(watched) = &job.schedule else { return 0 };
153        // Only slots after the job's newest row: what the ledger already shows is judged, and a backlog cut to the
154        // newest misses is not filled in behind them by later passes.
155        let newest_row = match self.store().job_run_last(&job.id) {
156            Ok(last) => last.map_or(0, |r| r.started_at_ms),
157            Err(e) => {
158                tracing::warn!(target: "jobs", error = %e, job = %job.id, "jobs: the watchdog couldn't read a cloud job's runs");
159                return 0;
160            }
161        };
162        let after = job.since_ms.max(now_ms - LOOKBACK_MS).max(newest_row);
163        // Newest first, so a long silence is cut to its newest misses and a job that reports every minute costs at most
164        // `MAX_SLOTS_LOOKED_AT` reads however long it was silent.
165        let mut uncovered = Vec::new();
166        let mut before = now_ms - watched.grace_ms + 1;
167        for _ in 0..MAX_SLOTS_LOOKED_AT {
168            let Some(slot) = watched.schedule.prev_before(before) else { break };
169            if slot <= after {
170                break;
171            }
172            before = slot;
173            // A slot owns the runs from just before it to just before the next slot. Each boundary is worked out from
174            // the two slots it separates (at most `SLOT_SLACK_MS` before the later, never past the middle), so one run
175            // can't belong to two slots whatever the gaps between them are.
176            let prev = watched.schedule.prev_before(slot).unwrap_or(slot - DAY_MS);
177            let next = watched.schedule.next_after(slot).unwrap_or(slot + DAY_MS);
178            let (from, until) = (slot - SLOT_SLACK_MS.min((slot - prev) / 2), next - SLOT_SLACK_MS.min((next - slot) / 2));
179            match self.store().job_cloud_slot_covered(&job.id, slot, from, until) {
180                Ok(true) => {}
181                Ok(false) => uncovered.push((slot, from, until)),
182                Err(e) => {
183                    tracing::warn!(target: "jobs", error = %e, job = %job.id, "jobs: the watchdog couldn't read a cloud job's runs");
184                    return 0;
185                }
186            }
187            if uncovered.len() == MAX_MISSES_PER_PASS {
188                break;
189            }
190        }
191        let mut written = 0;
192        for (slot, from, until) in uncovered.into_iter().rev() {
193            let mut run = JobRun::new(&format!("watchdog:{}:{slot}", job.id), &job.id, SOURCE_CLOUD, &job.name, TRIGGER_SCHEDULE, state::MISSED, slot);
194            run.scheduled_for_ms = Some(slot);
195            run.triggered_by = BY_WATCHDOG.to_string();
196            run.reason = reason::NO_REPORT.to_string();
197            // The window of start times that were this slot's: a late report that names no slot is matched by it.
198            run.links = serde_json::json!({ "window_from": from, "window_until": until });
199            run.ended_at_ms = Some(now_ms);
200            run.recorded_by = self.recorded_by.clone();
201            match self.store().job_cloud_give_up_slot(&run, from, until) {
202                Ok(true) => written += 1,
203                // A report came in since the slot was read, or another pass or channel gave up on it first.
204                Ok(false) => {}
205                Err(e) => tracing::warn!(target: "jobs", error = %e, job = %job.id, "jobs: the watchdog couldn't record a missed slot"),
206            }
207        }
208        written
209    }
210}
211
212/// When the run last reported: its start, or its latest heartbeat.
213fn last_heard_from(run: &JobRun) -> i64 {
214    run.links.get("heartbeat_ms").and_then(|v| v.as_i64()).unwrap_or(0).max(run.started_at_ms)
215}
216
217/// Start the watchdog: a first pass shortly after start-up, then one every five minutes. Needs a tokio runtime;
218/// without one it does nothing.
219pub fn start(ledger: Arc<RunLedger>, jobs: Arc<dyn WatchedJobs + Send + Sync>) {
220    let Ok(rt) = tokio::runtime::Handle::try_current() else { return };
221    rt.spawn(async move {
222        tokio::time::sleep(std::time::Duration::from_millis(SETTLE_MS)).await;
223        loop {
224            let (ledger, jobs) = (ledger.clone(), jobs.clone());
225            let _ = tokio::task::spawn_blocking(move || {
226                let got = ledger.watch_cloud(&jobs.watched_jobs(), now_ms());
227                if got != Watched::default() {
228                    tracing::info!(target: "jobs", missed = got.missed, lost = got.lost, "jobs: the watchdog gave up on cloud runs");
229                }
230            })
231            .await;
232            tokio::time::sleep(std::time::Duration::from_millis(PASS_MS)).await;
233        }
234    });
235}
236
237// ── Local jobs ──────────────────────────────────────────────────────────────────────────────────────────────
238
239/// How long after its slot a local job may take to write its row: the scheduler fires up to `JITTER_MAX_MS` after a
240/// slot and writes the row as it does, so a slot is only judged once this has passed.
241const LOCAL_GRACE_MS: i64 = JITTER_MAX_MS + 3 * 60 * 1000;
242/// A pass this much after the last means the computer was asleep or stopped: its scheduler tasks woke late and fire
243/// what they can, so nothing before that pass is judged.
244const SUSPEND_GAP_MS: i64 = 2 * PASS_MS as i64 + SETTLE_MS as i64;
245
246/// What the watchdog remembers between passes about the local jobs it watches. Only what happened while it ran
247/// counts: a slot from before its first pass belongs to the start-up catch-up (`app_not_running`), and one from
248/// before a job was edited or turned on again belongs to the old schedule.
249pub struct LocalWatch {
250    started_ms: i64,
251    last_pass_ms: Option<i64>,
252    /// Per job: its schedule when last seen, and the time after which its slots are judged.
253    seen: std::collections::HashMap<String, (String, i64)>,
254}
255
256impl LocalWatch {
257    pub fn new(started_ms: i64) -> Self {
258        Self { started_ms, last_pass_ms: None, seen: std::collections::HashMap::new() }
259    }
260}
261
262/// Everything about a job that decides its slots.
263fn schedule_signature(job: &CronJob) -> String {
264    format!("{}|{}|{}|{:?}|{:?}|{}", job.trigger_kind, job.expression, job.tz, job.every_secs, job.once_at_ms, job.created_at)
265}
266
267impl RunLedger {
268    /// One pass over the enabled local jobs `jobs` at `now_ms`: a `missed` row (`not_started`) for each slot past its
269    /// grace with no row of any kind. Returns how many it wrote. Blocking; running it again changes nothing.
270    pub fn watch_local(&self, watch: &mut LocalWatch, jobs: &[CronJob], now_ms: i64) -> usize {
271        let first_pass = watch.last_pass_ms.is_none();
272        let resumed = watch.last_pass_ms.is_some_and(|last| now_ms - last > SUSPEND_GAP_MS);
273        watch.last_pass_ms = Some(now_ms);
274        let live: BTreeSet<&str> = jobs.iter().map(|j| j.id.as_str()).collect();
275        // A job that is paused, deleted or done is forgotten, so its slots after it comes back are judged from then.
276        watch.seen.retain(|id, _| live.contains(id.as_str()));
277        let mut written = 0;
278        for job in jobs {
279            let Ok(schedule) = JobSchedule::of(job) else { continue };
280            if !matches!(schedule, JobSchedule::Cron { .. } | JobSchedule::Every { .. }) {
281                continue;
282            }
283            let sig = schedule_signature(job);
284            let baseline = match watch.seen.get_mut(&job.id) {
285                Some(seen) => {
286                    if seen.0 != sig || resumed {
287                        // Edited, or the computer slept: judge only what comes after this pass.
288                        *seen = (sig, now_ms);
289                    }
290                    seen.1
291                }
292                None => {
293                    // On the first pass a job's slots count from where the watchdog begins; a job that appears later, or
294                    // comes back, from now.
295                    let from = if first_pass { watch.started_ms } else { now_ms };
296                    watch.seen.insert(job.id.clone(), (sig, from));
297                    from
298                }
299            };
300            let missed = self.give_up_local_slots(job, &schedule, baseline, now_ms);
301            if missed > 0 {
302                written += missed;
303                self.changed(&job.id);
304            }
305            if let Some(seen) = watch.seen.get_mut(&job.id) {
306                // What was judged is not looked at again.
307                seen.1 = seen.1.max(now_ms - LOCAL_GRACE_MS);
308            }
309        }
310        written
311    }
312
313    /// A `missed` row for each slot of `job` in `(baseline_ms, now_ms - grace]` with no row; how many were written.
314    fn give_up_local_slots(&self, job: &CronJob, schedule: &JobSchedule, baseline_ms: i64, now_ms: i64) -> usize {
315        let until = now_ms - LOCAL_GRACE_MS;
316        let mut uncovered = Vec::new();
317        for slot in schedule.after(baseline_ms).take(MAX_SLOTS_LOOKED_AT) {
318            if slot > until {
319                break;
320            }
321            match self.store().job_run_slot_taken(&job.id, slot) {
322                Ok(true) => {}
323                Ok(false) => uncovered.push(slot),
324                Err(e) => {
325                    tracing::warn!(target: "jobs", error = %e, job = %job.id, "jobs: the watchdog couldn't read a local job's runs");
326                    return 0;
327                }
328            }
329        }
330        // The newest misses, as for a cloud job: a job that missed a day of minutes is one incident either way.
331        let skip = uncovered.len().saturating_sub(MAX_MISSES_PER_PASS);
332        let mut written = 0;
333        for slot in uncovered.into_iter().skip(skip) {
334            let mut run = JobRun::new(&format!("watchdog:{}:{slot}", job.id), &job.id, SOURCE_CRON, &job.name, TRIGGER_SCHEDULE, state::MISSED, slot);
335            run.scheduled_for_ms = Some(slot);
336            run.triggered_by = BY_WATCHDOG.to_string();
337            run.reason = reason::NOT_STARTED.to_string();
338            run.target_agent_uid = job.target_uid.clone();
339            run.ended_at_ms = Some(now_ms);
340            run.recorded_by = self.recorded_by.clone();
341            // The slot's unique index is the lease: a row the scheduler wrote since the read above wins.
342            match self.store().job_run_insert(&run) {
343                Ok(true) => written += 1,
344                Ok(false) => {}
345                Err(e) => tracing::warn!(target: "jobs", error = %e, job = %job.id, "jobs: the watchdog couldn't record a missed local slot"),
346            }
347        }
348        written
349    }
350}
351
352/// Start the local half of the watchdog over the cron jobs in `shared`: a first pass shortly after start-up, then one
353/// every five minutes. Needs a tokio runtime; without one it does nothing.
354pub fn start_local(ledger: Arc<RunLedger>, shared: Arc<Store>) {
355    let Ok(rt) = tokio::runtime::Handle::try_current() else { return };
356    rt.spawn(async move {
357        tokio::time::sleep(std::time::Duration::from_millis(SETTLE_MS)).await;
358        // Counted from the first pass, not from start-up: the scheduler's catch-up for the slots missed while AgentMux
359        // was off writes one collapsed row for all of them, so a slot in that stretch has no row of its own.
360        let mut watch = LocalWatch::new(now_ms());
361        loop {
362            let (ledger, shared) = (ledger.clone(), shared.clone());
363            let moved = tokio::task::spawn_blocking(move || {
364                let missed = match shared.cron_list_enabled() {
365                    Ok(jobs) => ledger.watch_local(&mut watch, &jobs, now_ms()),
366                    Err(e) => {
367                        tracing::warn!(target: "jobs", error = %e, "jobs: the watchdog couldn't list the cron jobs");
368                        0
369                    }
370                };
371                (watch, missed)
372            })
373            .await;
374            match moved {
375                Ok((back, missed)) => {
376                    watch = back;
377                    if missed > 0 {
378                        tracing::info!(target: "jobs", missed, "jobs: the watchdog gave up on local slots nothing started");
379                    }
380                }
381                Err(_) => return,
382            }
383            tokio::time::sleep(std::time::Duration::from_millis(PASS_MS)).await;
384        }
385    });
386}
387
388#[cfg(test)]
389#[path = "watchdog_tests.rs"]
390mod tests;
391
392#[cfg(test)]
393#[path = "watchdog_local_tests.rs"]
394mod local_tests;