Skip to main content

optimization_runner/
lib.rs

1#![doc = include_str!("../README.md")]
2mod host;
3pub mod mcp;
4
5use clap::{Parser, Subcommand};
6use optimization_job_api::{legacy::discovery, process::*, result, storage::*, *};
7use serde_json::{Value, json};
8use std::{
9    fs,
10    path::{Path, PathBuf},
11    process::{Command, Stdio},
12    sync::atomic::{AtomicUsize, Ordering},
13    thread,
14    time::{Duration, Instant, SystemTime, UNIX_EPOCH},
15};
16#[derive(Parser)]
17#[command(
18    version,
19    about = "Durable optimization jobs: fcmaes, LP-IP and SQP (Linux)"
20)]
21struct Cli {
22    #[arg(long, global = true, env = "OPTIMIZATION_RUN_ROOT")]
23    root: Option<PathBuf>,
24    #[arg(long, global = true)]
25    json: bool,
26    #[command(subcommand)]
27    command: Cmd,
28}
29#[derive(Subcommand)]
30enum Cmd {
31    Node {
32        #[command(subcommand)]
33        command: Node,
34    },
35    Workers {
36        #[command(subcommand)]
37        command: Workers,
38    },
39    Problems {
40        #[command(subcommand)]
41        command: Problems,
42    },
43    Validate {
44        #[arg(long)]
45        spec: PathBuf,
46    },
47    Run {
48        #[arg(long)]
49        spec: PathBuf,
50        #[arg(long)]
51        output: Option<PathBuf>,
52    },
53    Submit {
54        #[arg(long)]
55        spec: PathBuf,
56    },
57    Jobs {
58        #[command(subcommand)]
59        command: Jobs,
60    },
61    Result {
62        path: PathBuf,
63    },
64    Compare {
65        #[arg(required=true,num_args=2..)]
66        paths: Vec<PathBuf>,
67    },
68    #[command(hide = true)]
69    Launch {
70        id: String,
71    },
72}
73#[derive(Subcommand)]
74enum Node {
75    Init {
76        #[arg(long)]
77        capacity: usize,
78    },
79    Doctor,
80}
81#[derive(Subcommand)]
82enum Workers {
83    Add {
84        #[arg(long)]
85        id: String,
86        #[arg(long)]
87        executable: PathBuf,
88    },
89    List,
90}
91#[derive(Subcommand)]
92enum Problems {
93    List,
94    Describe { id: String },
95}
96#[derive(Subcommand)]
97enum Jobs {
98    List,
99    Events {
100        id: String,
101    },
102    Get {
103        id: String,
104    },
105    Wait {
106        id: String,
107        #[arg(long, default_value_t = 60.0)]
108        timeout: f64,
109    },
110    /// Stop a job. By default the active retry wave finishes and is kept;
111    /// `--now` kills the worker after one second and loses the active wave.
112    Cancel {
113        id: String,
114        #[arg(long)]
115        now: bool,
116    },
117    Reconcile,
118    Repair {
119        id: String,
120    },
121    /// Read an artifact, also while the job runs: its whole content (at
122    /// most 1 MiB), or with `--offset`/`--limit` a page of the checked
123    /// records of a `records` artifact.
124    Artifact {
125        id: String,
126        name: String,
127        /// First record of the page (records artifacts only).
128        #[arg(long)]
129        offset: Option<usize>,
130        /// Records of the page, 1 to 10000 (default 100 when only --offset is given).
131        #[arg(long)]
132        limit: Option<usize>,
133    },
134}
135/// Number of SIGINT/SIGTERM/SIGHUP received: one requests a graceful stop,
136/// two or more an immediate one.
137static SIGNALS: AtomicUsize = AtomicUsize::new(0);
138extern "C" fn stop_handler(_: i32) {
139    SIGNALS.fetch_add(1, Ordering::Relaxed);
140}
141/// SIGHUP matters for foreground runs: a closed terminal or agent shell must
142/// stop the job instead of orphaning the worker.
143fn install_stop_handlers() {
144    for signal in [libc::SIGINT, libc::SIGTERM, libc::SIGHUP] {
145        unsafe {
146            libc::signal(signal, stop_handler as *const () as libc::sighandler_t);
147        }
148    }
149}
150/// Kill delay after an immediate stop request.
151const IMMEDIATE_GRACE: Duration = Duration::from_secs(1);
152/// Largest `describe` output a worker may register: its profiles, models
153/// and options, and the JSON Schemas of its payloads and inputs with
154/// runnable examples ([guide](https://github.com/dietmarwo/optimization-jobs/blob/main/docs/job-api.md#discovery-for-agents)).
155const MAX_DESCRIPTION: usize = 1 << 20;
156#[derive(Clone, Copy, Debug, PartialEq, PartialOrd)]
157enum Stop {
158    None,
159    Graceful,
160    Immediate,
161}
162/// Pending stop request from signals or `cancel.request`. The launcher's own
163/// timeout marker (reason `timed_out`) is not a cancellation.
164fn stop_request(dir: &Path) -> Stop {
165    let from_signals = match SIGNALS.load(Ordering::Relaxed) {
166        0 => Stop::None,
167        1 => Stop::Graceful,
168        _ => Stop::Immediate,
169    };
170    let path = dir.join("cancel.request");
171    let from_file = if !path.exists() {
172        Stop::None
173    } else {
174        match read(&path) {
175            Ok(v) if v["reason"] == "timed_out" => Stop::None,
176            Ok(v) if v["mode"] == "graceful" => Stop::Graceful,
177            // An unreadable or unknown request is treated as the stronger one.
178            _ => Stop::Immediate,
179        }
180    };
181    if from_file > from_signals {
182        from_file
183    } else {
184        from_signals
185    }
186}
187/// Strength of a published stop request: no marker, the launcher's own
188/// timeout marker, a graceful cancellation, an immediate one. An unreadable
189/// marker counts as immediate, as in [`stop_request`].
190fn stop_rank(marker: &Result<Value>) -> u8 {
191    match marker {
192        Ok(v) if v.as_object().is_some_and(|o| o.is_empty()) => 0,
193        Ok(v) if v["reason"] == "timed_out" => 1,
194        Ok(v) if v["mode"] == "graceful" => 2,
195        _ => 3,
196    }
197}
198/// Publishes `marker` as `cancel.request` unless a request at least as
199/// strong is already there, and returns whether it did. Requests only
200/// escalate: the CLI (`jobs cancel`), the launcher's timeout and its signal
201/// handler all write through here under `cancel.lock`, a short-held lock of
202/// its own (`job.lock` is held by the launcher for its whole life), so a
203/// graceful request read before an immediate one was written can no longer
204/// replace it.
205fn publish_stop(dir: &Path, marker: Value) -> Result<bool> {
206    let _guard = lock(&dir.join("cancel.lock"))?;
207    let path = dir.join("cancel.request");
208    if stop_rank(&Ok(marker.clone())) <= stop_rank(&optional(&path)) {
209        return Ok(false);
210    }
211    write_atomic_json(&path, &marker)?;
212    Ok(true)
213}
214fn read(path: &Path) -> Result<Value> {
215    let bytes = fs::read(path).map_err(|e| format!("{}: {e}", path.display()))?;
216    Ok(serde_json::from_slice(&bytes).map_err(|e| format!("{}: {e}", path.display()))?)
217}
218fn optional(path: &Path) -> Result<Value> {
219    if path.exists() {
220        read(path)
221    } else {
222        Ok(json!({}))
223    }
224}
225fn state_write(path: &Path, state: &Value) -> Result<()> {
226    append_checked(
227        &path.with_file_name("events.jsonl"),
228        1,
229        &json!({"event":"state","state":state["state"],"at":now(),"id":state["id"]}),
230    )?;
231    write_atomic_json(path, state)?;
232    Ok(())
233}
234fn terminal(state: &Value) -> bool {
235    matches!(
236        state.as_str(),
237        Some("completed" | "failed" | "cancelled" | "timed_out" | "interrupted")
238    )
239}
240fn now() -> f64 {
241    SystemTime::now()
242        .duration_since(UNIX_EPOCH)
243        .unwrap()
244        .as_secs_f64()
245}
246fn boot() -> Result<String> {
247    Ok(fs::read_to_string("/proc/sys/kernel/random/boot_id")?
248        .trim()
249        .to_owned())
250}
251fn output(value: Value) -> Result<()> {
252    println!("{}", serde_json::to_string_pretty(&value)?);
253    Ok(())
254}
255fn spec(path: &Path) -> Result<Request> {
256    Request::parse(&fs::read(path).map_err(|e| format!("{}: {e}", path.display()))?)
257}
258/// An error of the submitted job itself: `invalid_job`, unless it already
259/// has a code.
260fn invalid(e: Error) -> Error {
261    if e.downcast_ref::<Coded>().is_some() {
262        e
263    } else {
264        coded("invalid_job", e.to_string())
265    }
266}
267/// Stages and validates the job file `input`, read once: the parsed request,
268/// the worker registration, the worker executable, the staging directory and
269/// the file's JSON as submitted.
270fn staged(
271    root: &Path,
272    input: &Path,
273) -> Result<(Request, Value, Vec<u8>, tempfile::TempDir, Value)> {
274    let raw = fs::read(input).map_err(|e| invalid(format!("{}: {e}", input.display()).into()))?;
275    let submitted: Value = serde_json::from_slice(&raw)
276        .map_err(|e| invalid(format!("{}: {e}", input.display()).into()))?;
277    let mut s = Request::parse(&raw)?;
278    let w = worker(root, s.worker())?;
279    let exe = Path::new(w["executable"].as_str().ok_or("invalid executable")?);
280    let bytes = fs::read(exe)?;
281    if w["digest"] != digest(&bytes) {
282        return Err(coded(
283            "worker_changed",
284            "worker changed since registration; register again explicitly",
285        ));
286    }
287    // The node root must allow execution anyway (attempts run their staged
288    // worker there); TMPDIR may be mounted noexec.
289    let tmp = tempfile::Builder::new()
290        .prefix(".staging-")
291        .tempdir_in(root)?;
292    let executable = tmp.path().join("worker");
293    fs::write(&executable, &bytes)?;
294    {
295        use std::os::unix::fs::PermissionsExt;
296        fs::set_permissions(&executable, fs::Permissions::from_mode(0o700))?;
297    }
298    if let Request::Job(ref mut job) = s {
299        if !protocol_supported(&w["description"]["protocol"])
300            || !w["description"]["profiles"]
301                .as_array()
302                .is_some_and(|a| a.iter().any(|v| v.as_str() == Some(&job.payload_schema)))
303        {
304            return Err(coded(
305                "unsupported_profile",
306                format!(
307                    "worker {} does not support payload schema {}",
308                    job.worker, job.payload_schema
309                ),
310            ));
311        }
312        stage_inputs(
313            job,
314            input
315                .parent()
316                .filter(|p| !p.as_os_str().is_empty())
317                .unwrap_or(Path::new(".")),
318            tmp.path(),
319        )
320        .map_err(|e| coded("invalid_job", format!("input: {e}")))?;
321        write_atomic_json(&tmp.path().join("request.json"), job)?;
322        // A signal during validation stops the validator too: it runs in its
323        // own process group, which a terminal's SIGINT does not reach.
324        install_stop_handlers();
325        let (status, out, err) = bounded_command_until(
326            &[
327                executable.to_string_lossy().into_owned(),
328                "validate".into(),
329                tmp.path()
330                    .join("request.json")
331                    .to_string_lossy()
332                    .into_owned(),
333            ],
334            vec![],
335            Duration::from_secs(30),
336            4 * 1024 * 1024,
337            &|| SIGNALS.load(Ordering::Relaxed) > 0,
338        )
339        .map_err(|e| match e.kind() {
340            std::io::ErrorKind::TimedOut => {
341                coded("invalid_job", "worker validation took longer than 30 s")
342            }
343            _ if e.to_string().contains("exceeds configured cap") => coded(
344                "invalid_job",
345                "the resolved job exceeds the 4 MiB validation output; keep inline starts or points well below 4 MiB",
346            ),
347            _ => e.into(),
348        })?;
349        if !status.success() {
350            return Err(coded(
351                "invalid_job",
352                format!(
353                    "worker validation failed: {}",
354                    String::from_utf8_lossy(&err)
355                ),
356            ));
357        }
358        let answer: Value = serde_json::from_slice(&out)?;
359        let resolved: JobSpec = serde_json::from_value(answer["resolved"].clone())?;
360        resolved.validate()?;
361        let mut envelope = resolved.clone();
362        envelope.payload = job.payload.clone();
363        envelope.task_count = job.task_count;
364        if envelope != *job || resolved.task_count.is_none() {
365            return Err("worker changed shared envelope or omitted task count".into());
366        }
367        *job = resolved;
368    }
369    Ok((s, w, bytes, tmp, submitted))
370}
371/// True when neither the launcher (`job.lock`) nor the worker (`worker.lock`)
372/// of an attempt is alive. Both hold their lock for their whole lifetime and
373/// the native worker starts no processes of its own. Errors count as alive.
374fn attempt_processes_gone(dir: &Path) -> bool {
375    let locks = matches!(lock_is_free(&dir.join("job.lock")), Ok(true))
376        && matches!(lock_is_free(&dir.join("worker.lock")), Ok(true));
377    if !locks {
378        return false;
379    }
380    // Nothing of an attempt survives a reboot: its processes and transient
381    // unit ended with the boot that recorded them, and a recorded process
382    // group ID may since belong to an unrelated process.
383    let current = boot().ok();
384    let earlier_boot = |v: &Value| current.is_some() && v["boot_id"].as_str() != current.as_deref();
385    if let Ok(p) = read(&dir.join("worker-process.json")) {
386        return earlier_boot(&p)
387            || p["pgid"]
388                .as_u64()
389                .and_then(|n| u32::try_from(n).ok())
390                .is_some_and(|pid| group_stopped(pid).unwrap_or(false));
391    }
392    read(&dir.join("job.json"))
393        .is_ok_and(|s| terminal(&s["state"]) || never_started(&s) || earlier_boot(&s))
394}
395/// Without a recorded process group, a worker can exist only if the attempt
396/// reached `running`, which is recorded before the worker is spawned. A
397/// queued attempt (or a foreground one not yet launched) whose launcher is
398/// gone therefore has no worker. Detached `submitted`/`starting` attempts may
399/// still be started by their unit, so they do not count.
400fn never_started(job: &Value) -> bool {
401    job["state"] == "waiting"
402        || (matches!(job["state"].as_str(), Some("submitted" | "starting"))
403            && job["unit"].is_null())
404}
405/// True when an attempt's launcher died before admission: it never started a
406/// worker, holds no lock, has no process record and no slot reservation. Such
407/// an attempt did provably zero work and can be sealed with complete
408/// (empty) accounting.
409fn never_admitted(root: &Path, id: &str, dir: &Path) -> Result<bool> {
410    if dir.join("worker-process.json").exists()
411        || !never_started(&read(&dir.join("job.json"))?)
412        || !matches!(lock_is_free(&dir.join("job.lock")), Ok(true))
413        || !matches!(lock_is_free(&dir.join("worker.lock")), Ok(true))
414    {
415        return Ok(false);
416    }
417    let _g = lock(&root.join("slots.lock"))?;
418    Ok(optional(&root.join("slots.json"))?[id].is_null())
419}
420fn capacity(root: &Path) -> Result<u64> {
421    let path = root.join("node.json");
422    if !path.exists() {
423        return Err(coded(
424            "node_not_initialized",
425            "node init --capacity required",
426        ));
427    }
428    read(&path)?["capacity"]
429        .as_u64()
430        .ok_or_else(|| "node.json has no valid capacity".into())
431}
432fn worker(root: &Path, id: &str) -> Result<Value> {
433    let w = optional(&root.join("workers.json"))?[id].clone();
434    if w.is_null() {
435        return Err(coded(
436            "unknown_worker",
437            format!("register worker {id} first"),
438        ));
439    }
440    Ok(w)
441}
442fn directory(root: &Path, id: &str) -> Result<PathBuf> {
443    if id.len() != 32 || !id.bytes().all(|b| b.is_ascii_hexdigit()) {
444        return Err(coded("unknown_job", format!("invalid job id {id:?}")));
445    }
446    let entry = optional(&root.join("requests.json"))?[id].clone();
447    Ok(PathBuf::from(entry["directory"].as_str().ok_or_else(
448        || coded("unknown_job", format!("no job {id} on this node")),
449    )?))
450}
451fn check_systemd() -> Result<()> {
452    let (s, out, _) = bounded_command(
453        &[
454            "systemctl".into(),
455            "--user".into(),
456            "show".into(),
457            "--property=Version".into(),
458        ],
459        vec![],
460        Duration::from_secs(10),
461        65536,
462    )?;
463    if !s.success()
464        || !String::from_utf8_lossy(&out)
465            .lines()
466            .any(|x| x.starts_with("Version=") && x.len() > 8)
467    {
468        return Err(coded(
469            "systemd_unavailable",
470            "systemd user manager unavailable; use foreground run",
471        ));
472    }
473    Ok(())
474}
475fn prepare(
476    root: &Path,
477    input: &Path,
478    dest: Option<PathBuf>,
479    detached: bool,
480) -> Result<(String, bool)> {
481    let (mut resolved, w, bytes, tmp, submitted) = staged(root, input)?;
482    let node = capacity(root)?;
483    if resolved.slots() as u64 > node {
484        return Err(coded(
485            "capacity_exceeded",
486            format!(
487                "the job requests {} CPU slots but the node capacity is {node}; it can never be admitted here",
488                resolved.slots()
489            ),
490        ));
491    }
492    let executable = Path::new(
493        w["executable"]
494            .as_str()
495            .ok_or("invalid worker registration")?,
496    );
497    let hash = digest(&bytes);
498    let id = digest(resolved.request_key().as_bytes())[..32].to_owned();
499    let identity = digest(&serde_json::to_vec(
500        &json!({"spec":resolved,"worker_digest":hash}),
501    )?);
502    let _guard = lock(&root.join("registry.lock"))?;
503    let mut requests = optional(&root.join("requests.json"))?;
504    if !requests[&id].is_null() {
505        if requests[&id]["identity"] != identity {
506            return Err(coded(
507                "request_key_conflict",
508                format!(
509                    "request_key conflict: {:?} already names job {id} with a different normalized spec or worker; use a new key",
510                    resolved.request_key()
511                ),
512            ));
513        }
514        return Ok((id, false));
515    }
516    if detached {
517        check_systemd()?;
518    }
519    let dir = dest.unwrap_or_else(|| root.join("jobs").join(&id));
520    let dir = if dir.is_absolute() {
521        dir
522    } else {
523        std::env::current_dir()?.join(dir)
524    };
525    if dir.exists() {
526        return Err("output already exists; refusing overwrite".into());
527    }
528    let parent = dir.parent().ok_or("output has no parent")?;
529    fs::create_dir_all(parent)?;
530    fs::create_dir(&dir)?;
531    // requests.json will point here; make the directory entry durable first.
532    fs::File::open(parent)?.sync_all()?;
533    let dir = fs::canonicalize(dir)?;
534    if let Request::Job(ref mut job) = resolved {
535        stage_inputs(job, tmp.path(), &dir)?;
536    }
537    write_atomic_json(&dir.join("submitted.json"), &submitted)?;
538    write_atomic_json(&dir.join("resolved.json"), &resolved)?;
539    fs::write(dir.join("worker"), bytes)?;
540    #[cfg(unix)]
541    {
542        use std::os::unix::fs::PermissionsExt;
543        fs::set_permissions(dir.join("worker"), fs::Permissions::from_mode(0o700))?;
544    }
545    fs::File::open(dir.join("worker"))?.sync_all()?;
546    let unit = if detached {
547        Some(match resolved {
548            Request::Legacy(_) => format!("fcmaes-{id}.service"),
549            Request::Job(_) => format!("optimization-job-{id}.service"),
550        })
551    } else {
552        None
553    };
554    write_atomic_json(
555        &dir.join("provenance.json"),
556        &json!({"worker_digest":hash,"registered_executable":executable,"identity":identity,"build":w["description"]["build"],"unit":unit,"boot_id":boot()?,"attempt_id":id}),
557    )?;
558    state_write(
559        &dir.join("job.json"),
560        &json!({"id":id,"state":"submitted","submitted_at":now(),"unit":unit,"boot_id":boot()?}),
561    )?;
562    requests[&id] = json!({"identity":identity,"directory":dir});
563    write_atomic_json(&root.join("requests.json"), &requests)?;
564    Ok((id, true))
565}
566fn submit(root: &Path, id: &str) -> Result<()> {
567    let dir = directory(root, id)?;
568    let mut state = read(&dir.join("job.json"))?;
569    state["state"] = json!("starting");
570    state_write(&dir.join("job.json"), &state)?;
571    let unit = state["unit"].as_str().ok_or("missing unit")?;
572    let exe = std::env::current_exe()?;
573    let args = vec![
574        "systemd-run".into(),
575        "--user".into(),
576        "--quiet".into(),
577        format!("--unit={unit}"),
578        "--property=KillMode=control-group".into(),
579        "--property=Restart=no".into(),
580        "--property=TimeoutStopSec=5s".into(),
581        format!("--working-directory={}", dir.display()),
582        exe.to_string_lossy().into_owned(),
583        "--root".into(),
584        root.to_string_lossy().into_owned(),
585        "launch".into(),
586        id.into(),
587    ];
588    match bounded_command(&args, vec![], Duration::from_secs(15), 65536) {
589        Ok((s, _, _)) if s.success() => Ok(()),
590        _ => Err(coded(
591            "start_unknown",
592            format!(
593                "start acknowledgement unknown for {unit}; inspect recorded unit; repeating submit will NOT launch again"
594            ),
595        )),
596    }
597}
598/// Drop reservations whose holders are provably gone: a previous boot, an
599/// inactive systemd unit with an empty cgroup, or an attempt whose launcher
600/// and worker locks are both free. Unknown liveness keeps the reservation.
601fn reconcile_ledger(root: &Path, ledger: &mut Value) -> Result<()> {
602    let current_boot = boot()?;
603    let keys: Vec<String> = ledger
604        .as_object()
605        .ok_or("invalid ledger")?
606        .keys()
607        .cloned()
608        .collect();
609    for id in keys {
610        let r = &ledger[&id];
611        let old_boot = r["boot_id"].as_str().is_some_and(|b| b != current_boot);
612        // A running service owns its reservation. A missing/unknown manager state is not proof of death.
613        let stopped = if let Some(unit) = r["unit"].as_str() {
614            let args = vec![
615                "systemctl".into(),
616                "--user".into(),
617                "show".into(),
618                unit.into(),
619                "--property=ActiveState,ControlGroup".into(),
620            ];
621            match bounded_command(&args, vec![], Duration::from_secs(5), 16384) {
622                Ok((s, out, _)) if s.success() => {
623                    let v = String::from_utf8_lossy(&out);
624                    let inactive = v
625                        .lines()
626                        .any(|x| x == "ActiveState=inactive" || x == "ActiveState=failed");
627                    let cg = v.lines().find_map(|x| x.strip_prefix("ControlGroup="));
628                    // Only accept manager-empty cgroup, or an explicitly unpopulated cgroup.events.
629                    let empty = match cg {
630                        Some("") => true,
631                        Some(c) if c.starts_with('/') && !c.contains("..") => {
632                            fs::read_to_string(format!("/sys/fs/cgroup{c}/cgroup.events"))
633                                .map(|s| s.lines().any(|x| x == "populated 0"))
634                                .unwrap_or(false)
635                        }
636                        _ => false,
637                    };
638                    inactive && empty
639                }
640                _ => false,
641            }
642        } else {
643            false
644        };
645        // Foreground jobs have no unit; a launcher killed by SIGKILL (or a
646        // closed terminal) would otherwise hold its slots until reboot.
647        let gone = directory(root, &id)
648            .map(|dir| attempt_processes_gone(&dir))
649            .unwrap_or(false);
650        if old_boot || stopped || gone {
651            ledger.as_object_mut().unwrap().remove(&id);
652        }
653    }
654    Ok(())
655}
656fn admit(root: &Path, id: &str, dir: &Path, slots: usize) -> Result<bool> {
657    if stop_request(dir) != Stop::None {
658        return Ok(false);
659    }
660    let _guard = lock(&root.join("slots.lock"))?;
661    let mut ledger = optional(&root.join("slots.json"))?;
662    reconcile_ledger(root, &mut ledger)?;
663    let used = ledger
664        .as_object()
665        .ok_or("bad ledger")?
666        .values()
667        .try_fold(0u64, |s, v| {
668            s.checked_add(v["slots"].as_u64().ok_or("bad slots")?)
669                .ok_or("slots overflow")
670        })?;
671    if ledger.get(id).is_some() {
672        return Err("attempt already reserved; refusing duplicate launch".into());
673    }
674    let accepted = used
675        .checked_add(slots as u64)
676        .is_some_and(|n| n <= capacity(root).unwrap_or(0));
677    if accepted {
678        let p = read(&dir.join("provenance.json"))?;
679        ledger[id] = json!({"slots":slots,"boot_id":boot()?,"unit":p["unit"],"launcher_pid":std::process::id()});
680    }
681    write_atomic_json(&root.join("slots.json"), &ledger)?;
682    Ok(accepted)
683}
684fn release(root: &Path, id: &str) -> Result<()> {
685    let _g = lock(&root.join("slots.lock"))?;
686    let mut l = optional(&root.join("slots.json"))?;
687    l.as_object_mut().ok_or("invalid ledger")?.remove(id);
688    write_atomic_json(&root.join("slots.json"), &l)?;
689    Ok(())
690}
691fn finish(dir: &Path, spec: &Request, status: &str, exact: bool, elapsed: f64) -> Result<()> {
692    let p = read(&dir.join("provenance.json"))?;
693    let worker_digest = p["worker_digest"].as_str().ok_or("missing worker digest")?;
694    // A journal that cannot be replayed (for example a worker that wrote an
695    // invalid record) still ends the attempt: `failed`, with no trusted
696    // results or work totals, instead of a job left `running` forever.
697    let (status, mut run) = match result::manifest(dir, spec, status, exact, elapsed, worker_digest)
698    {
699        Ok(run) => (status, run),
700        Err(e) => (
701            "failed",
702            result::unreadable_manifest(spec, elapsed, worker_digest, &e.to_string()),
703        ),
704    };
705    run["runner"]["attempt_id"] = p["attempt_id"].clone();
706    run["runner"]["build"] = p["build"].clone();
707    write_atomic_json(&dir.join("run.json"), &run)?;
708    let mut state = read(&dir.join("job.json"))?;
709    state["state"] = json!(status);
710    state["finished_at"] = json!(now());
711    state_write(&dir.join("job.json"), &state)?;
712    Ok(())
713}
714fn launch(root: &Path, id: &str) -> Result<()> {
715    let dir = directory(root, id)?;
716    let _owner = lock(&dir.join("job.lock"))?;
717    let mut state = read(&dir.join("job.json"))?;
718    if !matches!(state["state"].as_str(), Some("submitted" | "starting")) {
719        return Err("attempt already started; no implicit restart".into());
720    }
721    let s = spec(&dir.join("resolved.json"))?;
722    install_stop_handlers();
723    state["state"] = json!("waiting");
724    state_write(&dir.join("job.json"), &state)?;
725    let queue = Instant::now();
726    loop {
727        if stop_request(&dir) != Stop::None {
728            finish(&dir, &s, "cancelled", true, 0.0)?;
729            return Ok(());
730        }
731        if admit(root, id, &dir, s.slots())? {
732            break;
733        }
734        thread::sleep(Duration::from_millis(200));
735    }
736    let start = Instant::now();
737    state["state"] = json!("running");
738    state["started_at"] = json!(now());
739    state["queue_seconds"] = json!(queue.elapsed().as_secs_f64());
740    if let Err(e) = state_write(&dir.join("job.json"), &state) {
741        release(root, id)?;
742        return Err(e);
743    }
744    let mut safely_stopped = true;
745    let outcome = execute_worker(&dir, &s, start, &mut safely_stopped);
746    // execute_worker always reaps/cleans the group once spawn succeeds.
747    if safely_stopped {
748        release(root, id)?;
749    }
750    match outcome {
751        Ok((status, exact)) => finish(&dir, &s, &status, exact, start.elapsed().as_secs_f64()),
752        Err(e) => {
753            let _ = finish(&dir, &s, "failed", false, start.elapsed().as_secs_f64());
754            Err(e)
755        }
756    }
757}
758fn execute_worker(
759    dir: &Path,
760    s: &Request,
761    start: Instant,
762    safely_stopped: &mut bool,
763) -> Result<(String, bool)> {
764    let p = read(&dir.join("provenance.json"))?;
765    if json!(digest(&fs::read(dir.join("worker"))?)) != p["worker_digest"] {
766        return Err("staged worker digest mismatch".into());
767    }
768    let stdout = fs::File::create(dir.join("stdout.log"))?;
769    let stderr = fs::File::create(dir.join("stderr.log"))?;
770    let mut cmd = Command::new(dir.join("worker"));
771    cmd.arg("execute")
772        .arg(dir)
773        .current_dir(dir)
774        .stdin(Stdio::null())
775        .stdout(Stdio::piped())
776        .stderr(Stdio::piped())
777        .env_clear()
778        .env("PATH", "/usr/bin:/bin")
779        .env("OMP_NUM_THREADS", "1")
780        .env("OPENBLAS_NUM_THREADS", "1")
781        .env("MKL_NUM_THREADS", "1");
782    group(&mut cmd);
783    let mut child = cmd.spawn()?;
784    let pgid = child.id();
785    *safely_stopped = false;
786    if let Err(e) = write_atomic_json(
787        &dir.join("worker-process.json"),
788        &json!({"pgid":pgid,"boot_id":boot()?}),
789    ) {
790        terminate_process_group(&mut child);
791        let _ = child.wait();
792        *safely_stopped = group_stopped(pgid).unwrap_or(false);
793        return Err(e.into());
794    }
795    let a = child.stdout.take().unwrap();
796    let b = child.stderr.take().unwrap();
797    let ta = thread::spawn(move || drain_file(a, stdout, 1_048_576));
798    let tb = thread::spawn(move || drain_file(b, stderr, 1_048_576));
799    // The worker checks `cancel.request` between retry waves. A graceful stop
800    // lets the active wave finish; the wall-time deadline plus the declared
801    // grace, or an immediate stop, kills the worker group.
802    let wall = Duration::from_secs_f64(s.wall());
803    let hard_deadline = start + wall + Duration::from_secs_f64(s.grace());
804    let mut reason = None;
805    let mut immediate_deadline: Option<Instant> = None;
806    let mut signalled = 0;
807    let polled = (|| -> Result<std::process::ExitStatus> {
808        loop {
809            if let Some(exit) = child.try_wait()? {
810                return Ok(exit);
811            }
812            let request = stop_request(dir);
813            if reason.is_none() {
814                if request != Stop::None {
815                    reason = Some("cancelled");
816                } else if start.elapsed() >= wall {
817                    reason = Some("timed_out");
818                    // A cancellation published since the request was read
819                    // stays: the marker never replaces a stronger one.
820                    publish_stop(dir, json!({"mode":"graceful","reason":"timed_out"}))?;
821                }
822            }
823            // A signal-only request must still reach the worker; one already
824            // published at that strength or above stays as it is.
825            let from_signals = SIGNALS.load(Ordering::Relaxed);
826            if from_signals > signalled {
827                signalled = from_signals;
828                let mode = if from_signals > 1 {
829                    "immediate"
830                } else {
831                    "graceful"
832                };
833                publish_stop(
834                    dir,
835                    json!({"mode":mode,"reason":"signal","requested_at":now()}),
836                )?;
837            }
838            if request == Stop::Immediate && immediate_deadline.is_none() {
839                immediate_deadline = Some(Instant::now() + IMMEDIATE_GRACE);
840            }
841            let deadline = immediate_deadline.map_or(hard_deadline, |d| d.min(hard_deadline));
842            if Instant::now() >= deadline {
843                terminate_process_group(&mut child);
844                return Ok(child.wait()?);
845            }
846            thread::sleep(Duration::from_millis(10));
847        }
848    })();
849    terminate_process_group(&mut child);
850    let _ = child.wait();
851    let verify = Instant::now();
852    loop {
853        match group_stopped(pgid) {
854            Ok(true) => break,
855            _ if verify.elapsed() < Duration::from_secs(2) => {
856                thread::sleep(Duration::from_millis(10))
857            }
858            _ => {
859                write_atomic_json(
860                    &dir.join("containment.unknown"),
861                    &json!({"pgid":pgid,"reason":"group liveness unknown; slots retained"}),
862                )?;
863                return Err("worker group termination unverified; reservation retained".into());
864            }
865        }
866    }
867    *safely_stopped = true;
868    ta.join().map_err(|_| "stdout drainer panic")??;
869    tb.join().map_err(|_| "stderr drainer panic")??;
870    let exit = polled?;
871    let worker = if exit.success() {
872        worker_outcome(dir, s)?
873    } else {
874        None
875    };
876    let normal = worker.is_some();
877    let status = match (reason, worker) {
878        (Some(reason), _) => reason.to_string(),
879        (None, Some((status, _))) => status,
880        (None, None) => "failed".into(),
881    };
882    Ok((status, normal))
883}
884/// The worker's own `run.json`, if it is a complete manifest consistent with
885/// the journal: returns its status and elapsed time.
886fn worker_outcome(dir: &Path, s: &Request) -> Result<Option<(String, f64)>> {
887    result::worker_outcome(dir, s)
888}
889fn get(root: &Path, id: &str) -> Result<Value> {
890    let dir = directory(root, id)?;
891    let mut v = read(&dir.join("job.json"))?;
892    v["directory"] = json!(dir);
893    let s = spec(&dir.join("resolved.json"))?;
894    // A corrupt journal is an error here; `jobs list` reports it per job.
895    for (k, value) in result::progress(&dir, &s)?
896        .as_object()
897        .ok_or("bad progress")?
898    {
899        v[k] = value.clone();
900    }
901    if !terminal(&v["state"]) && v["boot_id"].as_str() != Some(&boot()?) {
902        v["observed_state"] = json!("interrupted_after_reboot");
903    }
904    // A launcher holds job.lock for its whole lifetime, so a free lock in an
905    // active state means it died (SIGKILL, closed terminal) without finishing.
906    if matches!(v["state"].as_str(), Some("waiting" | "running"))
907        && v["observed_state"].is_null()
908        && matches!(lock_is_free(&dir.join("job.lock")), Ok(true))
909    {
910        v["observed_state"] = json!("launcher_lost");
911        v["recovery"] = json!("run `jobs repair` after the worker has exited");
912    }
913    if matches!(
914        v["state"].as_str(),
915        Some("waiting" | "starting" | "running")
916    ) && let Some(unit) = v["unit"].as_str()
917    {
918        let args = vec![
919            "systemctl".into(),
920            "--user".into(),
921            "show".into(),
922            unit.into(),
923            "--property=ActiveState".into(),
924        ];
925        v["service_observation"] =
926            match bounded_command(&args, vec![], Duration::from_secs(3), 4096) {
927                Ok((s, out, _)) if s.success() => json!(String::from_utf8_lossy(&out).trim()),
928                _ => json!("unknown; reservation retained"),
929            };
930    }
931    if dir.join("cancel.request").exists() {
932        v["cancel_requested"] = json!(true);
933    }
934    Ok(v)
935}
936fn main_result() -> Result<()> {
937    // Usage errors are coded like every other error; help and version print
938    // normally.
939    let cli = match Cli::try_parse() {
940        Ok(cli) => cli,
941        Err(e)
942            if matches!(
943                e.kind(),
944                clap::error::ErrorKind::DisplayHelp
945                    | clap::error::ErrorKind::DisplayVersion
946                    | clap::error::ErrorKind::DisplayHelpOnMissingArgumentOrSubcommand
947            ) =>
948        {
949            e.exit()
950        }
951        Err(e) => return Err(coded("invalid_command", e.render().to_string())),
952    };
953    let selected = cli
954        .root
955        .or_else(|| std::env::var_os("FCMAES_RUN_ROOT").map(PathBuf::from))
956        .unwrap_or_else(|| {
957            let legacy = std::env::current_exe()
958                .ok()
959                .is_some_and(|p| p.file_stem().is_some_and(|s| s == "fcmaes-run"));
960            PathBuf::from(if legacy {
961                ".fcmaes-jobs"
962            } else {
963                ".optimization-jobs"
964            })
965        });
966    fs::create_dir_all(&selected)?;
967    let root = fs::canonicalize(&selected)?;
968    match cli.command {
969        Cmd::Node {
970            command: Node::Init { capacity: c },
971        } => {
972            if c == 0 {
973                return Err("capacity must be positive".into());
974            }
975            let _g = lock(&root.join("slots.lock"))?;
976            if root.join("node.json").exists() {
977                return Err("node already initialized; keep its capacity stable".into());
978            }
979            write_atomic_json(&root.join("node.json"), &json!({"capacity":c}))?;
980            // The owner may mean a capacity beyond what this process can use
981            // (another cgroup runs the jobs, say): a warning, not an error.
982            let warnings = host::warnings(Some(c as u64), &host::host());
983            output(json!({"capacity":c,"warnings":warnings}))
984        }
985        Cmd::Node {
986            command: Node::Doctor,
987        } => {
988            let host = host::host();
989            let capacity = capacity(&root).ok();
990            output(
991                json!({"systemd_user_manager":check_systemd().is_ok(),"boot_id":boot()?,"capacity":capacity,"logout_survival":"requires user manager lingering; verify on host","host":host,"warnings":host::warnings(capacity, &host)}),
992            )
993        }
994        Cmd::Workers {
995            command: Workers::Add { id, executable },
996        } => {
997            if !safe_name(&id) {
998                return Err("invalid worker id".into());
999            }
1000            let executable = fs::canonicalize(executable)?;
1001            let registered_hash = digest(&fs::read(&executable)?);
1002            let (status, out, _) = bounded_command(
1003                &[executable.to_string_lossy().into_owned(), "describe".into()],
1004                vec![],
1005                Duration::from_secs(10),
1006                MAX_DESCRIPTION,
1007            )
1008            .map_err(|e| {
1009                if e.to_string().contains("exceeds configured cap") {
1010                    format!("the worker's describe output exceeds {MAX_DESCRIPTION} bytes").into()
1011                } else {
1012                    Error::from(e)
1013                }
1014            })?;
1015            let description: Value = serde_json::from_slice(&out)?;
1016            let generic = protocol_supported(&description["protocol"])
1017                && description["profiles"]
1018                    .as_array()
1019                    .is_some_and(|p| !p.is_empty() && p.iter().all(Value::is_string));
1020            let compatible = id == "native"
1021                && ["protocol", "problems", "optimizers", "parallelism"]
1022                    .iter()
1023                    .all(|k| description[*k] == discovery()[*k]);
1024            if !status.success()
1025                || (!generic && !compatible)
1026                || registered_hash != digest(&fs::read(&executable)?)
1027            {
1028                return Err("worker capability profile mismatch or executable changed".into());
1029            }
1030            let _g = lock(&root.join("registry.lock"))?;
1031            let mut w = optional(&root.join("workers.json"))?;
1032            w[&id] = json!({"executable":executable,"digest":digest(&fs::read(&executable)?),"description":description});
1033            write_atomic_json(&root.join("workers.json"), &w)?;
1034            output(w)
1035        }
1036        Cmd::Workers {
1037            command: Workers::List,
1038        } => output(optional(&root.join("workers.json"))?),
1039        Cmd::Problems {
1040            command: Problems::List,
1041        } => {
1042            if std::env::current_exe()?
1043                .file_stem()
1044                .is_some_and(|name| name == "fcmaes-run")
1045            {
1046                output(discovery())
1047            } else {
1048                output(
1049                    json!({"legacy":discovery(),"registered":optional(&root.join("workers.json"))?}),
1050                )
1051            }
1052        }
1053        Cmd::Problems {
1054            command: Problems::Describe { id },
1055        } => {
1056            let registry = optional(&root.join("workers.json"))?;
1057            if !registry[&id].is_null() {
1058                output(registry[&id]["description"].clone())
1059            } else {
1060                let d = discovery();
1061                output(
1062                    d["problems"]
1063                        .as_array()
1064                        .unwrap()
1065                        .iter()
1066                        .find(|p| p["id"] == id)
1067                        .ok_or("unknown worker/problem")?
1068                        .clone(),
1069                )
1070            }
1071        }
1072        Cmd::Validate { spec: p } => match spec(&p).map_err(invalid)? {
1073            Request::Legacy(s) => output(
1074                json!({"valid":true,"requested_evaluations":s.requested()?,"maximum_actual_evaluations":s.maximum_evaluations()?,"resolved":s}),
1075            ),
1076            Request::Job(_) => {
1077                let (s, _, _, _, _) = staged(&root, &p)?;
1078                output(json!({"valid":true,"resolved":s}))
1079            }
1080        },
1081        Cmd::Run {
1082            spec: p,
1083            output: dest,
1084        } => {
1085            let (id, new) = prepare(&root, &p, dest, false)?;
1086            if new {
1087                launch(&root, &id)?;
1088            }
1089            output(get(&root, &id)?)
1090        }
1091        Cmd::Submit { spec: p } => {
1092            let (id, new) = prepare(&root, &p, None, true)?;
1093            if new {
1094                submit(&root, &id)?;
1095            }
1096            output(get(&root, &id)?)
1097        }
1098        Cmd::Launch { id } => launch(&root, &id),
1099        Cmd::Result { path } => output(read(&if path.is_dir() {
1100            path.join("run.json")
1101        } else {
1102            path
1103        })?),
1104        Cmd::Compare { paths } => {
1105            let runs = paths
1106                .iter()
1107                .map(|p| {
1108                    read(&if p.is_dir() {
1109                        p.join("run.json")
1110                    } else {
1111                        p.clone()
1112                    })
1113                })
1114                .collect::<Result<Vec<_>>>()?;
1115            output(result::compare(&runs)?)
1116        }
1117        Cmd::Jobs { command } => match command {
1118            Jobs::Events { id } => {
1119                let dir = directory(&root, &id)?;
1120                output(json!(read_checked::<Value>(&dir.join("events.jsonl"), 1)?))
1121            }
1122            Jobs::List => {
1123                let requests = optional(&root.join("requests.json"))?;
1124                let mut jobs = vec![];
1125                for id in requests.as_object().ok_or("bad requests")?.keys() {
1126                    jobs.push(
1127                        get(&root, id).unwrap_or_else(|e| json!({"id":id,"error":e.to_string()})),
1128                    );
1129                }
1130                output(json!(jobs))
1131            }
1132            Jobs::Get { id } => output(get(&root, &id)?),
1133            Jobs::Wait { id, timeout } => {
1134                if !timeout.is_finite() || timeout <= 0.0 {
1135                    return Err("positive finite timeout required".into());
1136                }
1137                let t = Instant::now();
1138                loop {
1139                    let v = get(&root, &id)?;
1140                    if matches!(
1141                        v["state"].as_str(),
1142                        Some("completed" | "failed" | "cancelled" | "timed_out" | "interrupted")
1143                    ) || !v["observed_state"].is_null()
1144                        || t.elapsed().as_secs_f64() >= timeout
1145                    {
1146                        return output(v);
1147                    }
1148                    thread::sleep(Duration::from_millis(250));
1149                }
1150            }
1151            Jobs::Cancel { id, now: immediate } => {
1152                let dir = directory(&root, &id)?;
1153                // Like a 409: a finished job has nothing to stop, and a late
1154                // request must not look as if it had stopped anything.
1155                let state = read(&dir.join("job.json"))?["state"].clone();
1156                if terminal(&state) {
1157                    return Err(coded(
1158                        "already_terminal",
1159                        format!(
1160                            "job {id} already ended as {}; nothing to cancel",
1161                            state.as_str().unwrap_or_default()
1162                        ),
1163                    ));
1164                }
1165                // Never downgrade: an immediate request stays immediate, also
1166                // when a graceful one races it (publish_stop serializes them).
1167                let mode = if immediate { "immediate" } else { "graceful" };
1168                publish_stop(&dir, json!({"mode":mode,"requested_at":now()}))?;
1169                output(get(&root, &id)?)
1170            }
1171            Jobs::Reconcile => {
1172                let _g = lock(&root.join("slots.lock"))?;
1173                let mut l = optional(&root.join("slots.json"))?;
1174                reconcile_ledger(&root, &mut l)?;
1175                write_atomic_json(&root.join("slots.json"), &l)?;
1176                output(l)
1177            }
1178            Jobs::Repair { id } => {
1179                let dir = directory(&root, &id)?;
1180                if terminal(&read(&dir.join("job.json"))?["state"]) {
1181                    return Err(coded(
1182                        "already_terminal",
1183                        "attempt already finalized; repair is for interrupted attempts",
1184                    ));
1185                }
1186                // Decided before the reservation is touched below.
1187                let unadmitted = never_admitted(&root, &id, &dir)?;
1188                if !attempt_processes_gone(&dir) {
1189                    // A held lock is a live launcher or worker: waiting helps.
1190                    // Without one, liveness stays unknown (a process group
1191                    // that still exists, or a detached unit that may yet
1192                    // start); waiting alone may never settle it.
1193                    if matches!(lock_is_free(&dir.join("worker.lock")), Ok(false)) {
1194                        return Err(coded("attempt_active", "worker still owns this attempt"));
1195                    }
1196                    if matches!(lock_is_free(&dir.join("job.lock")), Ok(false)) {
1197                        return Err(coded("attempt_active", "launcher still owns this attempt"));
1198                    }
1199                    return Err(coded(
1200                        "liveness_unknown",
1201                        "no process holds this attempt, but its process group still exists or its detached unit may still start; inspect it (jobs get, systemctl --user) before repairing",
1202                    ));
1203                }
1204                let owner = fs::OpenOptions::new()
1205                    .create(true)
1206                    .truncate(false)
1207                    .read(true)
1208                    .write(true)
1209                    .open(dir.join("job.lock"))?;
1210                fs2::FileExt::try_lock_exclusive(&owner)
1211                    .map_err(|_| coded("attempt_active", "launcher still owns this attempt"))?;
1212                let worker = fs::OpenOptions::new()
1213                    .create(true)
1214                    .truncate(false)
1215                    .read(true)
1216                    .write(true)
1217                    .open(dir.join("worker.lock"))?;
1218                fs2::FileExt::try_lock_exclusive(&worker)
1219                    .map_err(|_| coded("attempt_active", "worker still owns this attempt"))?;
1220                let state = read(&dir.join("job.json"))?;
1221                if matches!(
1222                    state["state"].as_str(),
1223                    Some("completed" | "failed" | "cancelled" | "timed_out" | "interrupted")
1224                ) {
1225                    return Err(coded(
1226                        "already_terminal",
1227                        "attempt already finalized; repair is for interrupted attempts",
1228                    ));
1229                }
1230                // Holding both locks proves the launcher and worker are gone, so
1231                // this attempt's reservation can be released.
1232                {
1233                    let _g = lock(&root.join("slots.lock"))?;
1234                    let mut ledger = optional(&root.join("slots.json"))?;
1235                    reconcile_ledger(&root, &mut ledger)?;
1236                    ledger.as_object_mut().ok_or("invalid ledger")?.remove(&id);
1237                    write_atomic_json(&root.join("slots.json"), &ledger)?;
1238                }
1239                let s = spec(&dir.join("resolved.json"))?;
1240                // A journal corrupt before its final line is not repaired; no
1241                // record of it is trusted and `finish` seals the attempt failed.
1242                let replayable = result::repair(&dir, &s).is_ok();
1243                // An orphaned worker may have finished on its own after the
1244                // launcher died; keep its exact result.
1245                if unadmitted {
1246                    // No worker ever ran: the attempt did provably zero work.
1247                    finish(&dir, &s, "interrupted", true, 0.0)?;
1248                } else if let Some((status, elapsed)) = replayable
1249                    .then(|| worker_outcome(&dir, &s))
1250                    .transpose()?
1251                    .flatten()
1252                {
1253                    finish(&dir, &s, &status, true, elapsed)?;
1254                } else {
1255                    finish(&dir, &s, "interrupted", false, 0.0)?;
1256                    // The execution duration is unknown after launcher loss.
1257                    let mut r = read(&dir.join("run.json"))?;
1258                    r["elapsed_seconds"] = Value::Null;
1259                    write_atomic_json(&dir.join("run.json"), &r)?;
1260                }
1261                output(get(&root, &id)?)
1262            }
1263            Jobs::Artifact {
1264                id,
1265                name,
1266                offset,
1267                limit,
1268            } => {
1269                let dir = directory(&root, &id)?;
1270                let unknown = |why: &[String]| {
1271                    coded(
1272                        "unknown_artifact",
1273                        format!(
1274                            "job {id} has no artifact {name:?}{}",
1275                            if why.is_empty() {
1276                                String::new()
1277                            } else {
1278                                format!(" ({})", why.join("; "))
1279                            }
1280                        ),
1281                    )
1282                };
1283                // A sealed attempt serves what its manifest lists, checked
1284                // against the recorded digest; a running one its declarations.
1285                let sealed = dir.join("run.json").exists();
1286                let (file, format, sha256) = if sealed {
1287                    let run = read(&dir.join("run.json"))?;
1288                    let file = run["artifacts"][&name]
1289                        .as_str()
1290                        .ok_or_else(|| unknown(&[]))?;
1291                    let index = &run["runner"]["artifact_index"][&name];
1292                    // Manifests before artifact indexes list `results` only.
1293                    let format = index["format"]
1294                        .as_str()
1295                        .unwrap_or(if name == artifact::RESULTS {
1296                            "records"
1297                        } else {
1298                            "file"
1299                        });
1300                    (
1301                        file.to_string(),
1302                        format.to_string(),
1303                        index["sha256"].as_str().map(String::from),
1304                    )
1305                } else {
1306                    let (list, errors) = artifact::all_or_results(&dir);
1307                    let d = list
1308                        .into_iter()
1309                        .find(|d| d.name == name)
1310                        .ok_or_else(|| unknown(&errors))?;
1311                    (d.file, d.format, None)
1312                };
1313                let path = match fs::canonicalize(dir.join(&file)) {
1314                    Ok(path) => path,
1315                    Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
1316                        return Err(coded(
1317                            "unknown_artifact",
1318                            format!("artifact {name:?} of job {id} has no file yet"),
1319                        ));
1320                    }
1321                    Err(e) => return Err(e.into()),
1322                };
1323                if !path.starts_with(fs::canonicalize(&dir)?) || !path.is_file() {
1324                    return Err("artifact escapes job directory or is no file".into());
1325                }
1326                // A whole read checks the whole file, a torn final record
1327                // included (it was sealed too); pages check their records.
1328                let paged = offset.is_some() || limit.is_some();
1329                if let Some(sealed) = sha256
1330                    && !paged
1331                    && artifact::digest_file(&path)?.1 != sealed
1332                {
1333                    return Err(format!(
1334                        "artifact {name:?} changed after the job ended: its SHA-256 differs from the manifest"
1335                    )
1336                    .into());
1337                }
1338                let mut value = if paged {
1339                    if format != "records" {
1340                        return Err(coded(
1341                            "invalid_command",
1342                            format!(
1343                                "artifact {name:?} has format {format}; only records artifacts have pages"
1344                            ),
1345                        ));
1346                    }
1347                    artifact::page(&path, offset.unwrap_or(0), limit.unwrap_or(100))?
1348                } else {
1349                    artifact::content(&path, &format)?
1350                };
1351                value["name"] = json!(name);
1352                value["file"] = json!(file);
1353                value["final"] = json!(sealed);
1354                output(value)
1355            }
1356        },
1357    }
1358}
1359pub fn main() {
1360    if !cfg!(target_os = "linux") {
1361        eprintln!("Linux is required for process supervision");
1362        std::process::exit(2);
1363    }
1364    if let Err(e) = main_result() {
1365        let code = error_code(&e);
1366        eprintln!(
1367            "{}",
1368            json!({"error":{"code":code,"message":e.to_string(),"retryable":retryable(code)}})
1369        );
1370        std::process::exit(2);
1371    }
1372}
1373
1374#[cfg(test)]
1375mod tests {
1376    use super::*;
1377
1378    #[test]
1379    fn stop_requests_only_escalate() {
1380        let dir = tempfile::tempdir().unwrap();
1381        let marker = |dir: &Path| read(&dir.join("cancel.request")).unwrap();
1382        let timeout = json!({"mode":"graceful","reason":"timed_out"});
1383        let graceful = json!({"mode":"graceful"});
1384        let immediate = json!({"mode":"immediate"});
1385        assert!(publish_stop(dir.path(), timeout.clone()).unwrap());
1386        assert!(!publish_stop(dir.path(), timeout.clone()).unwrap());
1387        // A cancellation replaces the launcher's timeout marker ...
1388        assert!(publish_stop(dir.path(), graceful.clone()).unwrap());
1389        assert!(!publish_stop(dir.path(), timeout).unwrap());
1390        assert!(publish_stop(dir.path(), immediate.clone()).unwrap());
1391        // ... and nothing replaces an immediate one.
1392        assert!(!publish_stop(dir.path(), graceful).unwrap());
1393        assert_eq!(marker(dir.path()), immediate);
1394        // An unreadable marker counts as the strongest request.
1395        fs::write(dir.path().join("cancel.request"), b"{").unwrap();
1396        assert!(!publish_stop(dir.path(), immediate).unwrap());
1397    }
1398}