Skip to main content

kitchen_services/
jobs.rs

1//! What runs in the background, in one place (from lumen's job registry): each job has a kind
2//! (`histology`, `model`, `export`…), a name saying what it is doing, how far it is, and a cancel
3//! flag. Only one job that drives the GPU runs at a time (a second is refused, saying what
4//! runs). The status bar lists them with a cancel button each; the work itself (off the UI
5//! thread) updates its job through its [`JobHandle`], which ends the job when dropped (finished,
6//! failed or cancelled alike).
7//!
8//! A job can leave an outcome ([`JobHandle::finish`]: what it found, or why it failed), kept for
9//! a while after it ends. A command that starts a job returns [`job_reply`] (`{"job": id}`), so
10//! whoever ran it (an agent through the MCP host) can wait for the job ([`is_running`]) and read
11//! its [`outcome`].
12
13use std::collections::VecDeque;
14use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
15use std::sync::{Arc, Mutex, OnceLock};
16
17/// A job running.
18#[derive(Debug, Clone)]
19pub struct Job {
20    /// Its id (unique in this run of the app).
21    pub id: u64,
22    /// What kind of work it is (`model`, `export`).
23    pub kind: String,
24    /// What it is doing now ("Finding cells: tile 3 of 12").
25    pub name: String,
26    /// How far (0..1), when known.
27    pub progress: Option<f32>,
28    /// Whether it drives the GPU (one such job at a time).
29    pub gpu: bool,
30    /// Set to ask it to stop.
31    pub cancel: Arc<AtomicBool>,
32}
33
34#[derive(Default)]
35struct Inner {
36    list: Vec<Job>,
37    next: u64,
38    /// The outcomes of the latest jobs that left one (newest last).
39    outcomes: VecDeque<(u64, Result<serde_json::Value, String>)>,
40}
41
42/// Outcomes kept after their jobs end.
43const KEPT_OUTCOMES: usize = 64;
44
45/// What a command that started job `id` returns: `{"job": id}`.
46pub fn job_reply(id: u64) -> serde_json::Value {
47    serde_json::json!({ "job": id })
48}
49
50/// The job a command's result names (`{"job": id, …}`), if any.
51pub fn job_of(result: &serde_json::Value) -> Option<u64> {
52    result.get("job").and_then(serde_json::Value::as_u64)
53}
54
55/// Whether the job `id` is still running.
56pub fn is_running(id: u64) -> bool {
57    inner().lock().unwrap_or_else(|e| e.into_inner()).list.iter().any(|o| o.id == id)
58}
59
60/// The outcome the job `id` left, once it ended (`None`: running, or it left none and has been
61/// forgotten).
62pub fn outcome(id: u64) -> Option<Result<serde_json::Value, String>> {
63    inner()
64        .lock()
65        .unwrap_or_else(|e| e.into_inner())
66        .outcomes
67        .iter()
68        .rev()
69        .find(|(i, _)| *i == id)
70        .map(|(_, o)| o.clone())
71}
72
73fn inner() -> &'static Mutex<Inner> {
74    static J: OnceLock<Mutex<Inner>> = OnceLock::new();
75    J.get_or_init(Default::default)
76}
77
78static GENERATION: AtomicU64 = AtomicU64::new(0);
79
80fn with<T>(f: impl FnOnce(&mut Inner) -> T) -> T {
81    let mut g = inner().lock().unwrap_or_else(|e| e.into_inner());
82    let out = f(&mut g);
83    GENERATION.fetch_add(1, Ordering::Relaxed);
84    out
85}
86
87/// Starts a job; refused while another GPU job runs (when this one is one too).
88pub fn start(kind: impl Into<String>, name: &str, gpu: bool) -> Result<JobHandle, String> {
89    let kind = kind.into();
90    with(|j| {
91        if gpu && let Some(other) = j.list.iter().find(|o| o.gpu) {
92            return Err(format!("{} is still running", other.name));
93        }
94        j.next += 1;
95        let cancel = Arc::new(AtomicBool::new(false));
96        crate::activity::job_started(j.next, &kind, name);
97        j.list.push(Job { id: j.next, kind, name: name.to_string(), progress: None, gpu, cancel: cancel.clone() });
98        Ok(JobHandle { id: j.next, cancel })
99    })
100}
101
102/// The jobs running, oldest first.
103pub fn running() -> Vec<Job> {
104    let g = inner().lock().unwrap_or_else(|e| e.into_inner());
105    g.list.clone()
106}
107
108/// The latest job of `kind`.
109pub fn of(kind: &str) -> Option<Job> {
110    running().into_iter().rev().find(|o| o.kind == kind)
111}
112
113/// Asks every job of `kind` to stop (when its work next checks).
114pub fn cancel(kind: &str) {
115    with(|j| j.list.iter().filter(|o| o.kind == kind).for_each(|o| o.cancel.store(true, Ordering::Relaxed)));
116}
117
118/// Asks the job `id` to stop.
119pub fn cancel_id(id: u64) {
120    with(|j| j.list.iter().filter(|o| o.id == id).for_each(|o| o.cancel.store(true, Ordering::Relaxed)));
121}
122
123/// A number that changes whenever a job starts, moves or ends (the status bar redraws then).
124pub fn generation() -> u64 {
125    GENERATION.load(Ordering::Relaxed)
126}
127
128/// A running job, held by the work doing it.
129pub struct JobHandle {
130    /// The job's id.
131    pub id: u64,
132    /// Set when someone asked it to stop.
133    pub cancel: Arc<AtomicBool>,
134}
135
136impl JobHandle {
137    /// Says what it is doing now, and how far.
138    pub fn set(&self, name: &str, progress: Option<f32>) {
139        with(|j| {
140            if let Some(o) = j.list.iter_mut().find(|o| o.id == self.id) {
141                o.name = name.to_string();
142                o.progress = progress;
143            }
144        });
145    }
146
147    /// Whether someone asked it to stop.
148    pub fn cancelled(&self) -> bool {
149        self.cancel.load(Ordering::Relaxed)
150    }
151
152    /// Leaves the job's outcome (what it found, or why it failed), read by [`outcome`] once the
153    /// job ends. The last call wins.
154    pub fn finish(&self, outcome: Result<serde_json::Value, String>) {
155        let id = self.id;
156        with(|j| {
157            j.outcomes.retain(|(i, _)| *i != id);
158            j.outcomes.push_back((id, outcome));
159            while j.outcomes.len() > KEPT_OUTCOMES {
160                j.outcomes.pop_front();
161            }
162        });
163    }
164}
165
166impl Drop for JobHandle {
167    fn drop(&mut self) {
168        let id = self.id;
169        let stopped = self.cancelled();
170        with(|j| {
171            j.list.retain(|o| o.id != id);
172            // A job that left no outcome: it was stopped, or it just ended
173            if !j.outcomes.iter().any(|(i, _)| *i == id) {
174                j.outcomes
175                    .push_back((id, if stopped { Err("stopped".to_string()) } else { Ok(serde_json::Value::Null) }));
176                while j.outcomes.len() > KEPT_OUTCOMES {
177                    j.outcomes.pop_front();
178                }
179            }
180        });
181        crate::activity::job_ended(id);
182    }
183}
184
185#[cfg(test)]
186mod tests {
187    #[test]
188    fn one_gpu_job_at_a_time_and_a_job_ends_with_its_handle() {
189        let g0 = super::generation();
190        let a = super::start("test-a", "first", true).unwrap();
191        assert!(super::start("test-b", "second", true).is_err(), "a second GPU job is refused");
192        let cpu = super::start("test-c", "on the CPU", false).unwrap();
193        a.set("first: half", Some(0.5));
194        assert_eq!(super::of("test-a").unwrap().progress, Some(0.5));
195        super::cancel("test-a");
196        assert!(a.cancelled());
197        super::cancel_id(cpu.id);
198        assert!(cpu.cancelled());
199        drop(a);
200        assert!(super::of("test-a").is_none());
201        assert!(super::start("test-b", "second", true).is_ok(), "free again");
202        drop(cpu);
203        assert!(super::generation() > g0);
204    }
205
206    #[test]
207    fn a_job_leaves_its_outcome() {
208        let a = super::start("test-outcome", "counting", false).unwrap();
209        let id = a.id;
210        assert!(super::is_running(id) && super::outcome(id).is_none());
211        assert_eq!(super::job_of(&super::job_reply(id)), Some(id));
212        a.finish(Ok(serde_json::json!({"cells": 12})));
213        drop(a);
214        assert!(!super::is_running(id));
215        assert_eq!(super::outcome(id), Some(Ok(serde_json::json!({"cells": 12}))));
216        let b = super::start("test-outcome", "stopped", false).unwrap();
217        b.cancel.store(true, std::sync::atomic::Ordering::Relaxed);
218        let id = b.id;
219        drop(b);
220        assert_eq!(super::outcome(id), Some(Err("stopped".to_string())));
221    }
222}