Skip to main content

optimization_job_api/
worker.rs

1//! Small blocking worker SDK. Solver state is private to each task; results are
2//! committed before a completed task is reported. No solver checkpoint is implied.
3use crate::{
4    JobSpec, PROTOCOL, Request, Result,
5    result::{self, Outcome, Record},
6    storage,
7};
8use serde_json::{Value, json};
9use std::{
10    collections::BTreeMap,
11    fs,
12    path::Path,
13    sync::{
14        Mutex,
15        atomic::{AtomicBool, AtomicUsize, Ordering},
16    },
17    thread,
18    time::{Duration, Instant},
19};
20
21/// What [`Prepared::solve`] returns for one task.
22pub struct TaskResult {
23    /// The task's outcome. It must pass [`Outcome::check`]; otherwise the
24    /// attempt fails before the record reaches the journal.
25    pub outcome: Outcome,
26    /// Named work counters of the task, such as evaluations.
27    pub work: BTreeMap<String, u64>,
28}
29/// A validated job, ready to solve its tasks. [`execute`] calls
30/// [`solve`](Prepared::solve) from up to `outer_workers` threads at once.
31pub trait Prepared: Send + Sync {
32    /// The number of tasks; it becomes the job's `task_count`.
33    fn tasks(&self) -> usize;
34    /// Solves task `task`, counted from 0, within `remaining_seconds` of the
35    /// wall time.
36    fn solve(&self, task: usize, remaining_seconds: f64) -> Result<TaskResult>;
37    /// A cooperative stop. Implementations without solver tokens may finish
38    /// their active task; the runner enforces the process deadline.
39    fn cancel(&self);
40}
41/// The solver behind one worker ID. [`run`] turns it into a worker binary
42/// with the commands `describe`, `validate` and `execute`.
43pub trait Worker {
44    /// The worker's description for `describe`, usually built by
45    /// [`description`].
46    fn describe(&self) -> Value;
47    /// Validate all model data, bounds, starts, budgets and thread support.
48    /// Resolve defaults into payload; no optimization is performed here.
49    fn prepare(&self, spec: &mut JobSpec, base: &Path) -> Result<Box<dyn Prepared>>;
50}
51/// A worker description of protocol [`PROTOCOL`]: the engine and its version,
52/// the profiles, the registered problems and the largest `inner_threads`.
53pub fn description(
54    engine: &str,
55    version: &str,
56    profiles: Value,
57    problems: Value,
58    inner_max: usize,
59) -> Value {
60    json!({"protocol":PROTOCOL,"engine":engine,"build":{"engine_version":version,"job_api_version":env!("CARGO_PKG_VERSION")},"profiles":profiles,"problems":problems,"resources":{"inner_threads_max":inner_max,"cpu_slots":"outer_workers * inner_threads <= cpu_slots; no hidden nested parallelism"},"recovery":"journal_only_no_resume","execution":"native registered models; no deserialized callbacks"})
61}
62fn prepared(worker: &dyn Worker, path: &Path) -> Result<(JobSpec, Box<dyn Prepared>)> {
63    let mut s: JobSpec = serde_json::from_slice(&fs::read(path)?)?;
64    s.validate()?;
65    let expected = s.task_count;
66    let p = worker.prepare(&mut s, path.parent().ok_or("spec parent missing")?)?;
67    if expected.is_some_and(|n| n != p.tasks()) {
68        return Err("task_count disagrees with payload".into());
69    }
70    s.task_count = Some(p.tasks());
71    s.validate()?;
72    Ok((s, p))
73}
74/// Executes the job in the attempt directory `dir`: validates `resolved.json`,
75/// solves the tasks on up to `outer_workers` threads, appends each result to
76/// `results.jsonl` and writes `run.json`. A `cancel.request` file or the wall
77/// time stops the remaining tasks. An attempt that already has a journal or
78/// a manifest is refused: a job is never resumed.
79pub fn execute(worker: &dyn Worker, dir: &Path) -> Result<()> {
80    let _owner = storage::lock(&dir.join("worker.lock"))?;
81    if dir.join("results.jsonl").exists() || dir.join("run.json").exists() {
82        return Err("existing attempt: journal recovery is not solver resume".into());
83    }
84    let start = Instant::now();
85    let (s, p) = prepared(worker, &dir.join("resolved.json"))?;
86    let persisted: JobSpec = serde_json::from_slice(&fs::read(dir.join("resolved.json"))?)?;
87    if s != persisted {
88        return Err("resolved job changed during worker validation".into());
89    }
90    let digest = s.digest()?;
91    let exe_digest = storage::digest(&fs::read(std::env::current_exe()?)?);
92    let journal = fs::OpenOptions::new()
93        .write(true)
94        .create_new(true)
95        .open(dir.join("results.jsonl"))?;
96    journal.sync_all()?;
97    fs::File::open(dir)?.sync_all()?;
98    let next = AtomicUsize::new(0);
99    let stop = AtomicBool::new(false);
100    let done = AtomicBool::new(false);
101    let output = Mutex::new(());
102    let error = Mutex::new(None::<String>);
103    thread::scope(|scope| {
104        let watcher = scope.spawn(|| {
105            while !done.load(Ordering::Acquire) {
106                if dir.join("cancel.request").exists()
107                    || start.elapsed().as_secs_f64() >= s.limits.wall_time_seconds
108                {
109                    stop.store(true, Ordering::Release);
110                    p.cancel();
111                }
112                thread::sleep(Duration::from_millis(5));
113            }
114        });
115        let mut handles = Vec::new();
116        for _ in 0..s.resources.outer_workers.min(p.tasks()) {
117            handles.push(scope.spawn(|| {
118                while !stop.load(Ordering::Acquire) {
119                    // Check locally too: a pre-existing cancel or tiny deadline
120                    // must never rely on watcher scheduling.
121                    if dir.join("cancel.request").exists()
122                        || start.elapsed().as_secs_f64() >= s.limits.wall_time_seconds
123                    {
124                        stop.store(true, Ordering::Release);
125                        p.cancel();
126                        break;
127                    }
128                    let task = next.fetch_add(1, Ordering::Relaxed);
129                    if task >= p.tasks() {
130                        break;
131                    }
132                    let began = Instant::now();
133                    let attempt = (|| -> Result<()> {
134                        let r = p.solve(
135                            task,
136                            (s.limits.wall_time_seconds - start.elapsed().as_secs_f64()).max(0.0),
137                        )?;
138                        // A record the runner would reject must never reach
139                        // the journal, where it would discard every result.
140                        r.outcome
141                            .check()
142                            .map_err(|e| format!("task {task}: invalid outcome: {e}"))?;
143                        let record = Record {
144                            task_id: task,
145                            spec_digest: digest.clone(),
146                            elapsed_seconds: began.elapsed().as_secs_f64(),
147                            outcome: r.outcome,
148                            work: r.work,
149                        };
150                        let _guard = output.lock().map_err(|_| "journal lock poisoned")?;
151                        storage::append_checked(&dir.join("results.jsonl"), 1, &record)?;
152                        Ok(())
153                    })();
154                    if let Err(e) = attempt {
155                        *error.lock().unwrap() = Some(e.to_string());
156                        stop.store(true, Ordering::Release);
157                        p.cancel();
158                        break;
159                    }
160                }
161            }));
162        }
163        for handle in handles {
164            if handle.join().is_err() {
165                *error.lock().unwrap() = Some("task panicked".into());
166                stop.store(true, Ordering::Release);
167                p.cancel();
168            }
169        }
170        done.store(true, Ordering::Release);
171        let _ = watcher.join();
172    });
173    if let Some(e) = error.into_inner().map_err(|_| "task error lock poisoned")? {
174        return Err(e.into());
175    }
176    let marker = fs::read(dir.join("cancel.request"))
177        .ok()
178        .and_then(|b| serde_json::from_slice::<Value>(&b).ok());
179    let timed_out = start.elapsed().as_secs_f64() >= s.limits.wall_time_seconds
180        || marker.as_ref().is_some_and(|m| m["reason"] == "timed_out");
181    let status = if timed_out {
182        "timed_out"
183    } else if stop.load(Ordering::Acquire) || dir.join("cancel.request").exists() {
184        "cancelled"
185    } else {
186        "completed"
187    };
188    let run = result::manifest(
189        dir,
190        &Request::Job(s),
191        status,
192        true,
193        start.elapsed().as_secs_f64(),
194        &exe_digest,
195    )?;
196    storage::write_atomic_json(&dir.join("run.json"), &run)?;
197    Ok(())
198}
199/// The `main` of a worker binary: `describe`, `validate SPEC` or `execute
200/// JOB_DIRECTORY`. It prints its JSON answer, or exits with status 1 and
201/// `{"error":{"code":"worker_error","message":...}}` on standard error.
202pub fn run(worker: impl Worker) {
203    let run = (|| -> Result<()> {
204        let args = std::env::args().collect::<Vec<_>>();
205        let value = match args.get(1).map(String::as_str) {
206            Some("describe") if args.len() == 2 => worker.describe(),
207            Some("validate") if args.len() == 3 => {
208                let (s, _) = prepared(&worker, Path::new(&args[2]))?;
209                json!({"resolved":s})
210            }
211            Some("execute") if args.len() == 3 => {
212                execute(&worker, Path::new(&args[2]))?;
213                json!({"executed":true})
214            }
215            _ => {
216                return Err(
217                    "usage: WORKER describe | validate SPEC | execute JOB_DIRECTORY".into(),
218                );
219            }
220        };
221        println!("{}", serde_json::to_string(&value)?);
222        Ok(())
223    })();
224    if let Err(e) = run {
225        eprintln!(
226            "{}",
227            json!({"error":{"code":"worker_error","message":e.to_string()}})
228        );
229        std::process::exit(1);
230    }
231}