1use std::collections::BTreeSet;
40use std::sync::{Arc, Weak};
41
42use agentmux_common::time::now_ms;
43use serde_json::json;
44
45use super::verdict::run_failed;
46use crate::backend::mps::Broker;
47use crate::backend::reactive::sanitize::quote_in_system_note;
48use crate::backend::storage::cron::CronJob;
49use crate::backend::storage::job_incidents::{IncidentCursor, JobIncident};
50use crate::backend::storage::job_runs::{infra, reason, state, JobRun};
51use crate::backend::storage::store::Store;
52use crate::backend::storage::work_board::{requested, NewCard, WorkEvent};
53use crate::backend::storage::work_queue::{work_state, WorkItem};
54
55pub const TASK_KIND: &str = "job-failure";
58pub const FILED_BY: &str = "jobs";
59
60pub const PASS_MAX: i64 = 500;
62
63pub const SWEEP_MS: u64 = 5 * 60 * 1000;
66
67pub fn notify_key(job_id: &str) -> String {
69 format!("job:{job_id}")
70}
71
72#[derive(Debug, Clone, PartialEq, Eq)]
76pub struct Leader {
77 pub uid: String,
78 pub name: String,
79}
80
81#[derive(Debug, Clone, PartialEq)]
83pub enum Step {
84 Opened { incident: JobIncident, leader: Option<Leader>, note: String, notify_body: String },
86 FailedAgain { count: i64 },
88 Recovered,
90 Reopened { incident: JobIncident, count: i64 },
93}
94
95#[derive(Default)]
98struct Walked {
99 steps: Vec<Step>,
100 more: bool,
101 error: Option<crate::backend::storage::StoreError>,
102}
103
104pub struct Incidents {
106 store: Arc<Store>,
108 mstore: Option<Arc<Store>>,
111 jobs: Option<Arc<Store>>,
114 broker: Arc<Broker>,
115 queue: std::sync::OnceLock<tokio::sync::mpsc::UnboundedSender<String>>,
116 #[cfg(any(test, feature = "test-support"))]
118 fail_on: std::sync::Mutex<Option<String>>,
119 #[cfg(any(test, feature = "test-support"))]
121 on_apply: std::sync::Mutex<Option<(String, Box<dyn FnOnce() + Send>)>>,
122 #[cfg(any(test, feature = "test-support"))]
124 router: std::sync::Mutex<Option<Vec<(String, String, String)>>>,
125}
126
127impl Incidents {
128 pub fn new(store: Arc<Store>, mstore: Option<Arc<Store>>, jobs: Option<Arc<Store>>, broker: Arc<Broker>) -> Arc<Self> {
130 Arc::new(Incidents {
131 store,
132 mstore,
133 jobs,
134 broker,
135 queue: std::sync::OnceLock::new(),
136 #[cfg(any(test, feature = "test-support"))]
137 fail_on: std::sync::Mutex::new(None),
138 #[cfg(any(test, feature = "test-support"))]
139 on_apply: std::sync::Mutex::new(None),
140 #[cfg(any(test, feature = "test-support"))]
141 router: std::sync::Mutex::new(None),
142 })
143 }
144
145 pub fn start(self: &Arc<Self>) {
150 let Ok(rt) = tokio::runtime::Handle::try_current() else { return };
151 let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel::<String>();
152 if self.queue.set(tx).is_err() {
153 return;
154 }
155 let weak: Weak<Incidents> = Arc::downgrade(self);
156 rt.spawn(async move {
157 let mut sweep = tokio::time::interval(std::time::Duration::from_millis(SWEEP_MS));
158 sweep.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
159 loop {
160 let mut due = BTreeSet::new();
161 tokio::select! {
162 got = rx.recv() => match got {
163 Some(job_id) => {
164 due.insert(job_id);
165 }
166 None => return,
167 },
168 _ = sweep.tick() => {
169 let Some(me) = weak.upgrade() else { return };
170 due.extend(tokio::task::spawn_blocking(move || me.owned_jobs()).await.unwrap_or_default());
171 }
172 }
173 while let Ok(more) = rx.try_recv() {
174 due.insert(more);
175 }
176 for job_id in due {
177 let Some(me) = weak.upgrade() else { return };
178 let _ = tokio::task::spawn_blocking(move || me.assess(&job_id)).await;
179 }
180 }
181 });
182 }
183
184 pub fn nudge(&self, job_id: &str) {
186 if let Some(tx) = self.queue.get() {
187 let _ = tx.send(job_id.to_string());
188 }
189 }
190
191 fn owned_jobs(&self) -> Vec<String> {
193 let cloud = crate::backend::job_templates::service().map(|t| t.approved_clouds()).unwrap_or_default().into_iter().map(|t| t.id);
194 self.jobs.as_ref().and_then(|s| s.cron_list().ok()).unwrap_or_default().into_iter().map(|j| j.id).chain(cloud).collect()
195 }
196
197 fn cloud_job(&self, job_id: &str) -> Option<CronJob> {
200 let template = crate::backend::job_templates::service()?.approved_cloud(job_id)?;
201 let owner = template
202 .manifest
203 .owner
204 .as_deref()
205 .and_then(|o| self.mstore.as_ref().and_then(|m| crate::backend::agent_resolve::resolve_agent_id(m, o).ok()))
206 .unwrap_or_default();
207 Some(CronJob { id: template.id, name: template.manifest.name, owner, ..Default::default() })
208 }
209
210 pub fn assess(&self, job_id: &str) -> Vec<Step> {
214 let cron = self.jobs.as_ref().and_then(|s| s.cron_get(job_id).ok().flatten());
215 let Some(job) = cron.or_else(|| self.cloud_job(job_id)) else {
216 return Vec::new();
217 };
218 let walked = self.walk(&job);
219 for step in &walked.steps {
220 match step {
221 Step::Opened { incident, leader: Some(leader), note, .. } => self.note_leader(incident, leader, note),
222 Step::Opened { .. } | Step::FailedAgain { .. } | Step::Reopened { .. } => {}
223 Step::Recovered => {
224 if let Some(router) = crate::backend::notify::router::get(&self.broker) {
225 router.resolve(¬ify_key(job_id), crate::backend::notify::policy::Family::Job);
226 }
227 }
228 }
229 }
230 self.notify_pending(job_id);
233 if let Some(e) = &walked.error {
234 tracing::warn!(job_id, error = %e, "jobs: couldn't judge an incident");
236 }
237 if !walked.steps.is_empty() {
238 self.changed(job_id);
239 }
240 if walked.more {
241 self.nudge(job_id);
242 }
243 walked.steps
244 }
245
246 fn walk(&self, job: &CronJob) -> Walked {
254 let mut walked = Walked::default();
255 let now = now_ms();
256 let started = self.end_if_task_closed(&job.id, now).and_then(|_| {
257 let cursor = self.store.job_incident_cursor(&job.id)?;
258 let after = cursor.as_ref().map(|c| (c.ended_at_ms, c.run_id.as_str()));
259 let runs = self.store.job_runs_decisive_after(&job.id, after, PASS_MAX)?;
260 Ok((cursor, runs))
261 });
262 let (mut cursor, runs) = match started {
263 Ok(got) => got,
264 Err(e) => {
265 walked.error = Some(e);
266 return walked;
267 }
268 };
269 walked.more = runs.len() as i64 >= PASS_MAX;
270 for run in runs {
271 if run.job_source == super::SOURCE_CRON || run.job_source == super::SOURCE_CLOUD {
272 match self.apply(job, &run, now) {
273 Ok(step) => walked.steps.extend(step),
274 Err(e) => {
275 walked.error = Some(e);
276 walked.more = false;
277 return walked;
278 }
279 }
280 }
281 let next = IncidentCursor { ended_at_ms: run.ended_at_ms.unwrap_or_default(), run_id: run.id.clone() };
282 match self.store.job_incident_cursor_advance(&job.id, cursor.as_ref(), &next, &run.outcome) {
283 Ok(true) => cursor = Some(next),
284 Ok(false) => {
288 walked.more = false;
289 return walked;
290 }
291 Err(e) => {
292 walked.error = Some(e);
293 walked.more = false;
294 return walked;
295 }
296 }
297 }
298 walked
299 }
300
301 fn end_if_task_closed(&self, job_id: &str, now: i64) -> Result<bool, crate::backend::storage::StoreError> {
304 match self.store.job_incident_open_for(job_id)? {
305 Some(open) if self.task_closed(&open.work_id) => self.store.job_incident_end_task_closed(&open.id, now),
306 _ => Ok(false),
307 }
308 }
309
310 fn apply(&self, job: &CronJob, run: &JobRun, now: i64) -> Result<Option<Step>, crate::backend::storage::StoreError> {
312 #[cfg(any(test, feature = "test-support"))]
313 {
314 if self.fail_on.lock().unwrap().as_deref() == Some(run.id.as_str()) {
315 return Err(crate::backend::storage::StoreError::NotFound);
316 }
317 let hook = {
318 let mut slot = self.on_apply.lock().unwrap();
319 if slot.as_ref().is_some_and(|(id, _)| *id == run.id) { slot.take() } else { None }
320 };
321 if let Some((_, f)) = hook {
322 f();
323 }
324 }
325 if !run_failed(run) {
326 let recovered = self.store.job_incidents_recover(&job.id, &run.id, now)?;
327 if recovered.is_empty() {
328 return Ok(None);
329 }
330 let at = run.ended_at_ms.unwrap_or(now);
331 for inc in &recovered {
332 let streak = if inc.failures == 1 { "1 failure".to_string() } else { format!("{} failures in a row", inc.failures) };
333 self.history(&inc.work_id, &format!("recovered at {}: the job's last run succeeded, after {streak}", clock(at)));
334 }
335 return Ok(Some(Step::Recovered));
336 }
337 if self.store.job_incident_run_counted(&run.id)? {
338 return Ok(None);
339 }
340 if let Some(inc) = self.store.job_incident_recovered_by(&job.id, &run.id)? {
345 if !self.task_closed(&inc.work_id) {
346 if let Some(count) = self.store.job_incident_reopen(&inc.id, &run.id, now)? {
347 self.link_run(&run.id, &inc);
348 let line = format!("failed after all: the run of {} reported it failed, {count} in a row", clock(failed_at(run)));
349 self.history(&inc.work_id, &line);
350 return Ok(Some(Step::Reopened { incident: inc, count }));
351 }
352 }
353 }
354 self.end_if_task_closed(&job.id, now)?;
355 let Some(inc) = self.store.job_incident_open_for(&job.id)? else { return self.open(job, run, now) };
356 let Some(count) = self.store.job_incident_fail_again(&inc.id, &inc.last_run_id, &run.id, now)? else {
357 return Ok(None);
358 };
359 self.link_run(&run.id, &inc);
360 if worth_a_line(count) {
361 let line = format!("failed again at {} ({}), {count} in a row", clock(failed_at(run)), failure_words(run));
362 self.history(&inc.work_id, &line);
363 }
364 Ok(Some(Step::FailedAgain { count }))
365 }
366
367 fn open(&self, job: &CronJob, run: &JobRun, now: i64) -> Result<Option<Step>, crate::backend::storage::StoreError> {
368 let leader = self.leader(job);
369 let mut incident = JobIncident {
370 id: uuid::Uuid::new_v4().to_string(),
371 job_id: run.job_id.clone(),
372 job_source: run.job_source.clone(),
373 job_name: run.job_name.clone(),
374 owner_uid: leader.as_ref().map(|l| l.uid.clone()).unwrap_or_default(),
375 first_run_id: run.id.clone(),
376 last_run_id: run.id.clone(),
377 failures: 1,
378 opened_at_ms: now,
379 last_failed_at_ms: now,
380 notified: false,
381 ..Default::default()
382 };
383 if !self.store.job_incident_open(&incident)? {
384 return Ok(None);
385 }
386 match self.file_task(run, leader.as_ref(), now) {
387 Ok((work_id, num)) => {
388 self.store.job_incident_set_task(&incident.id, &work_id, num)?;
389 incident.work_id = work_id;
390 incident.task_num = Some(num);
391 self.link_run(&run.id, &incident);
392 }
393 Err(e) => tracing::warn!(job_id = %run.job_id, error = %e, "jobs: couldn't file an incident's task"),
394 }
395 let note = note_text(run, incident.task_num);
396 let notify_body = notify_body(run, incident.task_num);
397 Ok(Some(Step::Opened { incident, leader, note, notify_body }))
398 }
399
400 fn leader(&self, job: &CronJob) -> Option<Leader> {
404 owning_leader(self.mstore.as_ref(), job)
405 }
406
407 fn file_task(&self, run: &JobRun, leader: Option<&Leader>, now: i64) -> Result<(String, i64), crate::backend::storage::StoreError> {
410 let item = WorkItem {
411 id: uuid::Uuid::new_v4().to_string(),
412 title: task_title(run),
413 payload: task_body(run),
414 kind: TASK_KIND.to_string(),
415 target_agent: leader.map(|l| l.name.clone()).unwrap_or_default(),
416 target_group: String::new(),
417 priority: 0,
418 state: String::new(),
419 claimed_by: String::new(),
420 target_agent_uid: leader.map(|l| l.uid.clone()).unwrap_or_default(),
421 claimed_by_uid: String::new(),
422 claim_expires: None,
423 attempts: 0,
424 max_attempts: 3,
425 created_by: FILED_BY.to_string(),
426 created_by_uid: String::new(),
427 created_at: now,
428 updated_at: now,
429 not_before: None,
430 result: String::new(),
431 };
432 self.store.work_queue_enqueue(&item)?;
433 let card = NewCard {
434 review_required: false,
435 requested_by: FILED_BY.to_string(),
436 requested_by_kind: requested::OTHER.to_string(),
437 filed_by: FILED_BY.to_string(),
438 ..Default::default()
439 };
440 let num = self.store.work_card_create(&item.id, &card, now)?;
441 let event = WorkEvent {
442 work_id: item.id.clone(),
443 at: now,
444 actor: FILED_BY.to_string(),
445 actor_kind: "system".to_string(),
446 kind: "created".to_string(),
447 to_state: work_state::OPEN.to_string(),
448 ..Default::default()
449 };
450 self.store.work_event_add(&event)?;
451 Ok((item.id, num))
452 }
453
454 fn task_closed(&self, work_id: &str) -> bool {
456 if work_id.is_empty() {
457 return false;
458 }
459 match self.store.work_queue_get(work_id) {
460 Ok(Some(t)) => matches!(t.state.as_str(), work_state::DONE | work_state::CANCELLED | work_state::FAILED),
461 Ok(None) => true,
462 Err(_) => false,
463 }
464 }
465
466 fn history(&self, work_id: &str, body: &str) {
468 if work_id.is_empty() {
469 return;
470 }
471 let event = WorkEvent {
472 work_id: work_id.to_string(),
473 at: now_ms(),
474 actor: FILED_BY.to_string(),
475 actor_kind: "system".to_string(),
476 kind: "updated".to_string(),
477 body: body.to_string(),
478 ..Default::default()
479 };
480 if let Err(e) = self.store.work_event_add(&event) {
481 tracing::warn!(work_id, error = %e, "jobs: couldn't add to an incident's task");
482 }
483 }
484
485 fn link_run(&self, run_id: &str, incident: &JobIncident) {
487 let Some(num) = incident.task_num else { return };
488 let link = json!({ "kanban_task": { "id": incident.work_id, "num": num } });
489 if let Err(e) = self.store.job_run_add_links(run_id, &link) {
490 tracing::warn!(run_id, error = %e, "jobs: couldn't link a run to its incident");
491 }
492 }
493
494 fn note_leader(&self, incident: &JobIncident, leader: &Leader, note: &str) {
496 if let Err(e) = crate::backend::reactive::get_global_handler().deliver_system_note(&leader.uid, note) {
497 tracing::info!(job_id = %incident.job_id, error = %e, "jobs: the owning leader didn't get the incident note");
498 }
499 }
500
501 fn notify_pending(&self, job_id: &str) {
504 let Ok(Some(inc)) = self.store.job_incident_open_for(job_id) else { return };
505 if inc.notified {
506 return;
507 }
508 let Some(run) = self.store.job_run_get(&inc.last_run_id).ok().flatten() else { return };
509 if !self.notify(¬ify_key(job_id), &inc.job_name, notify_body(&run, inc.task_num)) {
510 tracing::info!(job_id, "jobs: no notification router yet; the incident is notified at a later look");
511 return;
512 }
513 if let Err(e) = self.store.job_incident_mark_notified(&inc.id) {
514 tracing::warn!(job_id, error = %e, "jobs: couldn't mark an incident notified");
515 }
516 }
517
518 fn notify(&self, key: &str, job_name: &str, body: String) -> bool {
521 #[cfg(any(test, feature = "test-support"))]
522 {
523 let mut router = self.router.lock().unwrap();
524 return match router.as_mut() {
525 Some(sent) => {
526 sent.push((key.to_string(), job_name.to_string(), body));
527 true
528 }
529 None => false,
530 };
531 }
532 #[cfg(not(any(test, feature = "test-support")))]
533 match crate::backend::notify::router::get(&self.broker) {
534 Some(router) => {
535 router.job_failed(key, job_name, body);
536 true
537 }
538 None => false,
539 }
540 }
541
542 fn changed(&self, job_id: &str) {
544 let event = crate::backend::mps_events::JobsChangedEvent { job_id: job_id.to_string() };
545 self.broker.publish_event::<crate::backend::mps_events::JobsChanged>(&event, vec![], 0);
546 self.broker.publish_event::<crate::backend::mps_events::WorkQueueChanged>(&(), vec![], 0);
547 }
548}
549
550pub fn owning_leader(mstore: Option<&Arc<Store>>, job: &CronJob) -> Option<Leader> {
554 let owner = job.owner_uid();
555 if owner.is_empty() {
556 return None;
557 }
558 let mstore = mstore?;
559 let name_of = |uid: &str| mstore.agent_def_get(uid).ok().flatten().map(|d| d.name);
560 let lead = crate::backend::agent_seat::effective_seat_by_id(mstore, owner).and_then(|s| s.lead);
561 let uid = lead.filter(|l| name_of(l).is_some()).unwrap_or_else(|| owner.to_string());
562 let name = name_of(&uid)?;
563 Some(Leader { uid, name })
564}
565
566pub fn worth_a_line(count: i64) -> bool {
571 if count <= 5 {
572 return true;
573 }
574 let mut n = count;
575 while n % 10 == 0 {
576 n /= 10;
577 }
578 matches!(n, 1 | 2 | 5)
579}
580
581fn failed_at(run: &JobRun) -> i64 {
583 run.ended_at_ms.unwrap_or(run.started_at_ms)
584}
585
586fn clock(at_ms: i64) -> String {
588 chrono::DateTime::from_timestamp_millis(at_ms).map(|t| t.format("%H:%M UTC").to_string()).unwrap_or_default()
589}
590
591pub fn failure_words(run: &JobRun) -> String {
594 if run.state == state::MISSED || run.state == "lost" || (run.state == state::PENDING && run.reason == reason::EXPIRED) {
595 return match run.reason.as_str() {
596 reason::TARGET_STOPPED => "missed: its agent wasn't running".to_string(),
597 reason::EXPIRED => "missed: its agent didn't come back before the next run".to_string(),
598 reason::NO_REPORT if run.state == state::MISSED => "missed: no report came in for it".to_string(),
599 reason::NOT_STARTED if run.state == state::MISSED => "missed: the scheduler never started it".to_string(),
600 _ if run.state == "lost" => "lost: it stopped reporting".to_string(),
601 _ => "missed".to_string(),
602 };
603 }
604 match run.infra.as_str() {
605 infra::ERROR => return "it couldn't be delivered or ran into an error".to_string(),
606 "timeout" => return "it timed out".to_string(),
607 "over_budget" => return "it reached its spending cap".to_string(),
608 infra::INTERRUPTED => return "it was interrupted".to_string(),
609 _ => {}
610 }
611 if run.outcome == "failed" {
612 return "its agent reported it failed".to_string();
613 }
614 "failed".to_string()
615}
616
617pub fn task_title(run: &JobRun) -> String {
619 format!("Job failed: {} ({})", one_line(&run.job_name), failure_words(run))
620}
621
622fn one_line(text: &str) -> String {
623 text.split_whitespace().collect::<Vec<_>>().join(" ")
624}
625
626fn when(at_ms: i64) -> String {
627 chrono::DateTime::from_timestamp_millis(at_ms).map(|t| t.format("%Y-%m-%d %H:%M UTC").to_string()).unwrap_or_default()
628}
629
630pub fn task_body(run: &JobRun) -> String {
634 let mut lines = vec![format!("The job \"{}\" failed: {}.", one_line(&run.job_name), failure_words(run)), String::new()];
635 lines.push(format!("Run {}", run.id));
636 if let Some(slot) = run.scheduled_for_ms {
637 lines.push(format!("- Due: {}", when(slot)));
638 }
639 lines.push(format!("- Started: {}", when(run.started_at_ms)));
640 let reason = if run.reason.is_empty() { String::new() } else { format!(" ({})", run.reason) };
641 lines.push(format!("- State: {}{reason}", run.state));
642 if !run.infra.is_empty() {
643 lines.push(format!("- Infrastructure: {}", run.infra));
644 }
645 lines.push(format!("- Outcome: {}", run.outcome));
646 if !run.summary.is_empty() {
647 lines.push(format!("- Summary, as the run reported it: {}", one_line(&run.summary)));
648 }
649 if let Some(block) = run.links.pointer("/transcript/block_id").and_then(|v| v.as_str()) {
650 lines.push(format!("- Transcript: the agent pane {block} (History)"));
651 }
652 if let Some(reported) = run.links.get("reported").and_then(|v| v.as_array()) {
653 for link in reported.iter().take(5) {
654 let url = link.as_str().or_else(|| link.get("url").and_then(|u| u.as_str())).unwrap_or("");
655 if url.starts_with("https://") {
656 lines.push(format!("- Link: {url}"));
657 }
658 }
659 }
660 lines.push(String::new());
661 lines.push(format!(
662 "Every run of the job is in Warden > Jobs > {}. While the job keeps failing, each failure is added to this \
663 task's history; its next success adds \"recovered\", and the task stays open for you to finish.",
664 one_line(&run.job_name)
665 ));
666 lines.join("\n")
667}
668
669pub fn note_text(run: &JobRun, task_num: Option<i64>) -> String {
672 let task = task_num.map(|n| format!(" Kanban #{n} is yours to look into.")).unwrap_or_default();
673 format!(
674 "[AgentMux] Job \"{}\" failed at {} ({}).{task} Its runs are in Warden > Jobs.",
675 quote_in_system_note(&run.job_name),
676 clock(failed_at(run)),
677 failure_words(run)
678 )
679}
680
681pub fn notify_body(run: &JobRun, task_num: Option<i64>) -> String {
683 let words = failure_words(run);
684 let mut first = words.chars();
685 let words = first.next().map(|c| c.to_uppercase().chain(first).collect::<String>()).unwrap_or_default();
686 match task_num {
687 Some(n) => format!("{words}. Kanban #{n}."),
688 None => format!("{words}."),
689 }
690}
691
692#[cfg(test)]
693#[path = "incidents_tests.rs"]
694mod tests;