Skip to main content

optimization_runner/
lib.rs

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