agentmux_srv_core/backend/jobs/
watchdog.rs1use 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;
35const PASS_MS: u64 = 5 * 60 * 1000;
37const SETTLE_MS: u64 = 2 * 60 * 1000;
39const LOOKBACK_MS: i64 = 7 * DAY_MS;
42const MAX_SLOTS_LOOKED_AT: usize = 2000;
44const MAX_MISSES_PER_PASS: usize = 50;
47const SLOT_SLACK_MS: i64 = 60 * 1000;
49const UNKNOWN_JOB_MAX_RUN_MS: i64 = DAY_MS;
51const BY_WATCHDOG: &str = "watchdog";
53
54pub struct WatchedSchedule {
56 pub schedule: JobSchedule,
57 pub grace_ms: i64,
58}
59
60pub struct WatchedJob {
62 pub id: String,
63 pub name: String,
64 pub since_ms: i64,
66 pub schedule: Option<WatchedSchedule>,
68 pub max_run_ms: i64,
70}
71
72pub trait WatchedJobs {
74 fn watched_jobs(&self) -> Vec<WatchedJob>;
75}
76
77impl 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#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
104pub struct Watched {
105 pub missed: usize,
106 pub lost: usize,
107}
108
109impl RunLedger {
110 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 fn give_up_slots(&self, job: &WatchedJob, now_ms: i64) -> usize {
152 let Some(watched) = &job.schedule else { return 0 };
153 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 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 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 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 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
212fn 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
217pub 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
237const LOCAL_GRACE_MS: i64 = JITTER_MAX_MS + 3 * 60 * 1000;
242const SUSPEND_GAP_MS: i64 = 2 * PASS_MS as i64 + SETTLE_MS as i64;
245
246pub struct LocalWatch {
250 started_ms: i64,
251 last_pass_ms: Option<i64>,
252 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
262fn 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 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 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 *seen = (sig, now_ms);
289 }
290 seen.1
291 }
292 None => {
293 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 seen.1 = seen.1.max(now_ms - LOCAL_GRACE_MS);
308 }
309 }
310 written
311 }
312
313 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 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 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
352pub 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 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;