Skip to main content

agentmux_srv_core/backend/jobs/
verdict.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//
4//! What a run concluded for the Jobs tab: whether it failed, and whether its
5//! job is failing (docs/specs/SPEC_JOBS_AND_TEMPLATES_2026_10_24.md §3.4), and
6//! the state a job is in (§3.3).
7
8use crate::backend::storage::cron::CronJob;
9use crate::backend::storage::job_runs::{reason, state, JobRun};
10
11/// Infrastructure statuses that fail a run (§3.4).
12const FAILED_INFRA: &[&str] = &["error", "timeout", "over_budget", "interrupted"];
13
14/// Whether `run` failed (§3.4): its infrastructure status is `error`,
15/// `timeout`, `over_budget` or `interrupted`, it was `missed` or `lost`, or
16/// it concluded `failed`. A pending fire that expired was never delivered:
17/// a miss. `findings` is no failure, and neither is a skip.
18pub fn run_failed(run: &JobRun) -> bool {
19    FAILED_INFRA.contains(&run.infra.as_str())
20        || run.state == state::MISSED
21        || run.state == "lost"
22        || (run.state == state::PENDING && run.reason == reason::EXPIRED)
23        || run.outcome == "failed"
24}
25
26/// Whether `run` says how the job is doing: a finished run, or a failure.
27/// Skips, and runs still scheduled, pending or running, say nothing yet.
28/// The store's `job_run_last_decisive` picks the newest such run in SQL.
29#[cfg(test)]
30fn decisive(run: &JobRun) -> bool {
31    (run.state == state::FINISHED || run_failed(run)) && run.links.get("retried_by").is_none()
32}
33
34/// Whether a job is failing, from its newest decisive run
35/// (`Store::job_run_last_decisive`): that run failed. The next success ends
36/// it (§3.4's incident), however many skips come between.
37pub fn job_failing(last_decisive: Option<&JobRun>) -> bool {
38    last_decisive.is_some_and(run_failed)
39}
40
41/// A job's state in the tab (§3.3).
42pub mod job_state {
43    pub const ACTIVE: &str = "active";
44    pub const PAUSED: &str = "paused";
45    /// Every job is paused by the operator.
46    pub const PAUSED_ALL: &str = "paused_all";
47    /// Disabled by its own limit (`max_fires`, `max_age_secs`), not paused.
48    pub const ENDED: &str = "ended";
49}
50
51/// Whether a disabled job was stopped by its own limit rather than paused:
52/// it reached `max_fires`, or its age bound passed by `now_secs`.
53pub fn ended_by_limit(job: &CronJob, now_secs: i64) -> bool {
54    job.max_fires.is_some_and(|max| job.fire_count >= max)
55        || job.max_age_secs.is_some_and(|age| now_secs - job.created_at >= age)
56}
57
58/// The state of cron job `job` (§3.3).
59pub fn cron_job_state(job: &CronJob, paused_all: bool, now_secs: i64) -> &'static str {
60    if !job.enabled {
61        return if ended_by_limit(job, now_secs) { job_state::ENDED } else { job_state::PAUSED };
62    }
63    if paused_all {
64        job_state::PAUSED_ALL
65    } else {
66        job_state::ACTIVE
67    }
68}
69
70#[cfg(test)]
71mod tests {
72    use super::*;
73
74    fn run(state: &str, infra: &str, outcome: &str, reason: &str) -> JobRun {
75        JobRun {
76            state: state.into(),
77            infra: infra.into(),
78            outcome: outcome.into(),
79            reason: reason.into(),
80            ..Default::default()
81        }
82    }
83
84    #[test]
85    fn a_run_fails_on_its_infrastructure_a_miss_or_its_own_verdict() {
86        for failed in [
87            run("finished", "error", "unknown", ""),
88            run("finished", "timeout", "unknown", ""),
89            run("finished", "over_budget", "unknown", ""),
90            run("finished", "interrupted", "ok", ""),
91            run("missed", "", "unknown", "target_stopped"),
92            run("lost", "", "unknown", ""),
93            run("pending", "", "unknown", "expired"),
94            run("finished", "ok", "failed", ""),
95        ] {
96            assert!(run_failed(&failed), "{failed:?}");
97        }
98        for fine in [
99            run("finished", "ok", "ok", ""),
100            run("finished", "ok", "findings", ""),
101            run("finished", "ok", "unknown", ""),
102            run("skipped", "", "unknown", "paused"),
103            run("skipped", "", "unknown", "paused_all"),
104            run("pending", "", "unknown", "superseded"),
105            run("pending", "", "unknown", "target_stopped"),
106            run("running", "", "unknown", ""),
107        ] {
108            assert!(!run_failed(&fine), "{fine:?}");
109        }
110    }
111
112    /// The store's SQL pick of the newest decisive run agrees with
113    /// [`decisive`] on every shape of run.
114    #[test]
115    fn the_store_and_this_agree_on_which_runs_are_decisive() {
116        let store = crate::backend::storage::store::Store::open_in_memory().unwrap();
117        store.job_runs_ensure_schema().unwrap();
118        let shapes = [
119            run("finished", "ok", "ok", ""),
120            run("finished", "ok", "unknown", ""),
121            run("finished", "error", "unknown", ""),
122            run("missed", "", "unknown", "target_stopped"),
123            run("lost", "", "unknown", ""),
124            run("pending", "", "unknown", "expired"),
125            run("pending", "", "unknown", "superseded"),
126            run("pending", "", "unknown", "target_stopped"),
127            run("skipped", "", "unknown", "paused"),
128            run("scheduled", "", "unknown", ""),
129            run("running", "", "unknown", ""),
130            run("running", "interrupted", "unknown", ""),
131            run("running", "", "failed", ""),
132        ];
133        for (i, shape) in shapes.iter().enumerate() {
134            let mut r = shape.clone();
135            r.id = format!("r{i}");
136            r.job_id = format!("j{i}");
137            r.job_source = "cron".into();
138            r.trigger = "schedule".into();
139            r.links = serde_json::json!({});
140            store.job_run_insert(&r).unwrap();
141            let picked = store.job_run_last_decisive(&r.job_id).unwrap().is_some();
142            assert_eq!(picked, decisive(&r), "{r:?}");
143        }
144    }
145
146    #[test]
147    fn a_job_is_failing_when_its_newest_decisive_run_failed() {
148        assert!(job_failing(Some(&run("finished", "error", "unknown", ""))));
149        assert!(!job_failing(Some(&run("finished", "ok", "ok", ""))));
150        assert!(!job_failing(None), "nothing decisive yet");
151    }
152
153    #[test]
154    fn a_disabled_job_is_paused_unless_its_own_limit_stopped_it() {
155        let mut job = crate::backend::cron::test_job("j", "p", "t", "", "");
156        assert_eq!(cron_job_state(&job, false, 0), job_state::ACTIVE);
157        assert_eq!(cron_job_state(&job, true, 0), job_state::PAUSED_ALL);
158        job.enabled = false;
159        assert_eq!(cron_job_state(&job, true, 0), job_state::PAUSED, "its own pause shows over Pause all");
160        job.max_fires = Some(3);
161        job.fire_count = 3;
162        assert_eq!(cron_job_state(&job, false, 0), job_state::ENDED);
163        job.max_fires = None;
164        job.max_age_secs = Some(60);
165        assert_eq!(cron_job_state(&job, false, 59), job_state::PAUSED);
166        assert_eq!(cron_job_state(&job, false, 60), job_state::ENDED);
167    }
168}