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 Fleet {
42 #[command(subcommand)]
43 command: remote::fleet::Cli,
44 },
45 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 Identity {
104 #[arg(long)]
105 init: bool,
106 },
107 Init {
108 #[arg(long)]
109 capacity: usize,
110 #[arg(long)]
112 allow_commands: bool,
113 },
114 Commands {
116 #[arg(long, conflicts_with = "disable", required_unless_present = "disable")]
117 enable: bool,
118 #[arg(long)]
119 disable: bool,
120 },
121 Doctor,
122 Capabilities,
124}
125#[derive(Subcommand)]
126enum Files {
127 Put {
129 #[arg(long)]
130 source: PathBuf,
131 #[arg(long)]
132 sha256: String,
133 #[arg(long)]
134 bytes: u64,
135 },
136 Get {
138 sha256: String,
139 #[arg(long)]
140 bytes: u64,
141 #[arg(long)]
142 destination: PathBuf,
143 },
144 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 {
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 Execution {
180 id: String,
181 },
182 Wait {
183 id: String,
184 #[arg(long, default_value_t = 60.0)]
185 timeout: f64,
186 },
187 Cancel {
190 id: String,
191 #[arg(long)]
192 now: bool,
193 },
194 Reconcile,
195 Repair {
196 id: String,
197 },
198 Progress {
201 id: String,
202 #[arg(long, default_value_t = 0)]
204 offset: usize,
205 #[arg(long, default_value_t = 1000)]
207 limit: usize,
208 },
209 Artifact {
213 id: String,
214 name: String,
215 #[arg(long)]
217 offset: Option<usize>,
218 #[arg(long)]
220 limit: Option<usize>,
221 },
222}
223static SIGNALS: AtomicUsize = AtomicUsize::new(0);
226extern "C" fn stop_handler(_: i32) {
227 SIGNALS.fetch_add(1, Ordering::Relaxed);
228}
229fn install_stop_handlers() {
232 for signal in [libc::SIGINT, libc::SIGTERM, libc::SIGHUP] {
233 unsafe {
234 libc::signal(signal, stop_handler as *const () as libc::sighandler_t);
235 }
236 }
237}
238const IMMEDIATE_GRACE: Duration = Duration::from_secs(1);
240const MAX_DESCRIPTION: usize = 1 << 20;
244#[derive(Clone, Copy, Debug, PartialEq, PartialOrd)]
245enum Stop {
246 None,
247 Graceful,
248 Immediate,
249}
250fn stop_request(dir: &Path) -> Stop {
253 let from_signals = match SIGNALS.load(Ordering::Relaxed) {
254 0 => Stop::None,
255 1 => Stop::Graceful,
256 _ => Stop::Immediate,
257 };
258 let path = dir.join("cancel.request");
259 let from_file = if !path.exists() {
260 Stop::None
261 } else {
262 match read(&path) {
263 Ok(v) if v["reason"] == "timed_out" => Stop::None,
264 Ok(v) if v["mode"] == "graceful" => Stop::Graceful,
265 _ => Stop::Immediate,
267 }
268 };
269 if from_file > from_signals {
270 from_file
271 } else {
272 from_signals
273 }
274}
275fn stop_rank(marker: &Result<Value>) -> u8 {
279 match marker {
280 Ok(v) if v.as_object().is_some_and(|o| o.is_empty()) => 0,
281 Ok(v) if v["reason"] == "timed_out" => 1,
282 Ok(v) if v["mode"] == "graceful" => 2,
283 _ => 3,
284 }
285}
286fn publish_stop(dir: &Path, marker: Value) -> Result<bool> {
294 let _guard = lock(&dir.join("cancel.lock"))?;
295 let path = dir.join("cancel.request");
296 if stop_rank(&Ok(marker.clone())) <= stop_rank(&optional(&path)) {
297 return Ok(false);
298 }
299 write_atomic_json(&path, &marker)?;
300 Ok(true)
301}
302fn read(path: &Path) -> Result<Value> {
303 let bytes = fs::read(path).map_err(|e| format!("{}: {e}", path.display()))?;
304 Ok(serde_json::from_slice(&bytes).map_err(|e| format!("{}: {e}", path.display()))?)
305}
306fn optional(path: &Path) -> Result<Value> {
307 if path.exists() {
308 read(path)
309 } else {
310 Ok(json!({}))
311 }
312}
313fn state_write(path: &Path, state: &Value) -> Result<()> {
314 append_checked(
315 &path.with_file_name("events.jsonl"),
316 1,
317 &json!({"event":"state","state":state["state"],"at":now(),"id":state["id"]}),
318 )?;
319 write_atomic_json(path, state)?;
320 Ok(())
321}
322fn terminal(state: &Value) -> bool {
323 matches!(
324 state.as_str(),
325 Some("completed" | "failed" | "cancelled" | "timed_out" | "interrupted")
326 )
327}
328fn now() -> f64 {
329 SystemTime::now()
330 .duration_since(UNIX_EPOCH)
331 .unwrap()
332 .as_secs_f64()
333}
334fn boot() -> Result<String> {
335 Ok(fs::read_to_string("/proc/sys/kernel/random/boot_id")?
336 .trim()
337 .to_owned())
338}
339fn output(value: Value) -> Result<()> {
340 println!("{}", serde_json::to_string_pretty(&value)?);
341 Ok(())
342}
343fn spec(path: &Path) -> Result<Request> {
344 Request::parse(&fs::read(path).map_err(|e| format!("{}: {e}", path.display()))?)
345}
346fn invalid(e: Error) -> Error {
349 if e.downcast_ref::<Coded>().is_some() {
350 e
351 } else {
352 coded("invalid_job", e.to_string())
353 }
354}
355fn staged(
359 root: &Path,
360 input: &Path,
361) -> Result<(Request, Value, Vec<u8>, tempfile::TempDir, Value)> {
362 let raw = fs::read(input).map_err(|e| invalid(format!("{}: {e}", input.display()).into()))?;
363 let submitted: Value = serde_json::from_slice(&raw)
364 .map_err(|e| invalid(format!("{}: {e}", input.display()).into()))?;
365 let mut s = Request::parse(&raw)?;
366 let w = worker(root, s.worker())?;
367 let exe = Path::new(w["executable"].as_str().ok_or("invalid executable")?);
368 let bytes = fs::read(exe)?;
369 if w["digest"] != digest(&bytes) {
370 return Err(coded(
371 "worker_changed",
372 "worker changed since registration; register again explicitly",
373 ));
374 }
375 let tmp = tempfile::Builder::new()
378 .prefix(".staging-")
379 .tempdir_in(root)?;
380 let executable = tmp.path().join("worker");
381 fs::write(&executable, &bytes)?;
382 {
383 use std::os::unix::fs::PermissionsExt;
384 fs::set_permissions(&executable, fs::Permissions::from_mode(0o700))?;
385 }
386 if let Request::Job(ref mut job) = s {
387 if !protocol_supported(&w["description"]["protocol"])
388 || !w["description"]["profiles"]
389 .as_array()
390 .is_some_and(|a| a.iter().any(|v| v.as_str() == Some(&job.payload_schema)))
391 {
392 return Err(coded(
393 "unsupported_profile",
394 format!(
395 "worker {} does not support payload schema {}",
396 job.worker, job.payload_schema
397 ),
398 ));
399 }
400 stage_inputs(
401 job,
402 input
403 .parent()
404 .filter(|p| !p.as_os_str().is_empty())
405 .unwrap_or(Path::new(".")),
406 tmp.path(),
407 )
408 .map_err(|e| coded("invalid_job", format!("input: {e}")))?;
409 write_atomic_json(&tmp.path().join("request.json"), job)?;
410 install_stop_handlers();
413 let (status, out, err) = bounded_command_until(
414 &[
415 executable.to_string_lossy().into_owned(),
416 "validate".into(),
417 tmp.path()
418 .join("request.json")
419 .to_string_lossy()
420 .into_owned(),
421 ],
422 vec![],
423 Duration::from_secs(30),
424 4 * 1024 * 1024,
425 &|| SIGNALS.load(Ordering::Relaxed) > 0,
426 )
427 .map_err(|e| match e.kind() {
428 std::io::ErrorKind::TimedOut => {
429 coded("invalid_job", "worker validation took longer than 30 s")
430 }
431 _ if e.to_string().contains("exceeds configured cap") => coded(
432 "invalid_job",
433 "the resolved job exceeds the 4 MiB validation output; keep inline starts or points well below 4 MiB",
434 ),
435 _ => e.into(),
436 })?;
437 if !status.success() {
438 return Err(coded(
439 "invalid_job",
440 format!(
441 "worker validation failed: {}",
442 String::from_utf8_lossy(&err)
443 ),
444 ));
445 }
446 let answer: Value = serde_json::from_slice(&out)?;
447 let resolved: JobSpec = serde_json::from_value(answer["resolved"].clone())?;
448 resolved.validate()?;
449 let mut envelope = resolved.clone();
450 envelope.payload = job.payload.clone();
451 envelope.task_count = job.task_count;
452 if envelope != *job || resolved.task_count.is_none() {
453 return Err("worker changed shared envelope or omitted task count".into());
454 }
455 *job = resolved;
456 }
457 Ok((s, w, bytes, tmp, submitted))
458}
459fn attempt_processes_gone(dir: &Path) -> bool {
463 let locks = matches!(lock_is_free(&dir.join("job.lock")), Ok(true))
464 && matches!(lock_is_free(&dir.join("worker.lock")), Ok(true));
465 if !locks {
466 return false;
467 }
468 let current = boot().ok();
472 let earlier_boot = |v: &Value| current.is_some() && v["boot_id"].as_str() != current.as_deref();
473 if let Ok(p) = read(&dir.join("worker-process.json")) {
474 return earlier_boot(&p)
475 || p["pgid"]
476 .as_u64()
477 .and_then(|n| u32::try_from(n).ok())
478 .is_some_and(|pid| group_stopped(pid).unwrap_or(false));
479 }
480 read(&dir.join("job.json"))
481 .is_ok_and(|s| terminal(&s["state"]) || never_started(&s) || earlier_boot(&s))
482}
483fn never_started(job: &Value) -> bool {
489 job["state"] == "waiting"
490 || (matches!(job["state"].as_str(), Some("submitted" | "starting"))
491 && job["unit"].is_null())
492}
493fn never_admitted(root: &Path, id: &str, dir: &Path) -> Result<bool> {
498 if dir.join("worker-process.json").exists()
499 || !never_started(&read(&dir.join("job.json"))?)
500 || !matches!(lock_is_free(&dir.join("job.lock")), Ok(true))
501 || !matches!(lock_is_free(&dir.join("worker.lock")), Ok(true))
502 {
503 return Ok(false);
504 }
505 let _g = lock(&root.join("slots.lock"))?;
506 Ok(optional(&root.join("slots.json"))?[id].is_null())
507}
508fn capacity(root: &Path) -> Result<u64> {
509 let path = root.join("node.json");
510 if !path.exists() {
511 return Err(coded(
512 "node_not_initialized",
513 "node init --capacity required",
514 ));
515 }
516 read(&path)?["capacity"]
517 .as_u64()
518 .ok_or_else(|| "node.json has no valid capacity".into())
519}
520fn worker(root: &Path, id: &str) -> Result<Value> {
521 let w = optional(&root.join("workers.json"))?[id].clone();
522 if w.is_null() {
523 return Err(coded(
524 "unknown_worker",
525 format!("register worker {id} first"),
526 ));
527 }
528 Ok(w)
529}
530fn directory(root: &Path, id: &str) -> Result<PathBuf> {
531 if id.len() != 32 || !id.bytes().all(|b| b.is_ascii_hexdigit()) {
532 return Err(coded("unknown_job", format!("invalid job id {id:?}")));
533 }
534 let entry = optional(&root.join("requests.json"))?[id].clone();
535 Ok(PathBuf::from(entry["directory"].as_str().ok_or_else(
536 || coded("unknown_job", format!("no job {id} on this node")),
537 )?))
538}
539fn check_systemd() -> Result<()> {
540 let (s, out, _) = bounded_command(
541 &[
542 "systemctl".into(),
543 "--user".into(),
544 "show".into(),
545 "--property=Version".into(),
546 ],
547 vec![],
548 Duration::from_secs(10),
549 65536,
550 )?;
551 if !s.success()
552 || !String::from_utf8_lossy(&out)
553 .lines()
554 .any(|x| x.starts_with("Version=") && x.len() > 8)
555 {
556 return Err(coded(
557 "systemd_unavailable",
558 "systemd user manager unavailable; use foreground run",
559 ));
560 }
561 Ok(())
562}
563fn prepare(
564 root: &Path,
565 input: &Path,
566 dest: Option<PathBuf>,
567 detached: bool,
568) -> Result<(String, bool)> {
569 if read(input).map_err(invalid)?["schema_version"] == command::SCHEMA {
570 return command::prepare(root, input, dest, detached);
571 }
572 let (mut resolved, w, bytes, tmp, submitted) = staged(root, input)?;
573 let node = capacity(root)?;
574 if resolved.slots() as u64 > node {
575 return Err(coded(
576 "capacity_exceeded",
577 format!(
578 "the job requests {} CPU slots but the node capacity is {node}; it can never be admitted here",
579 resolved.slots()
580 ),
581 ));
582 }
583 let executable = Path::new(
584 w["executable"]
585 .as_str()
586 .ok_or("invalid worker registration")?,
587 );
588 let hash = digest(&bytes);
589 let id = digest(resolved.request_key().as_bytes())[..32].to_owned();
590 let identity = digest(&serde_json::to_vec(
591 &json!({"spec":resolved,"worker_digest":hash}),
592 )?);
593 let _guard = lock(&root.join("registry.lock"))?;
594 let mut requests = optional(&root.join("requests.json"))?;
595 if !requests[&id].is_null() {
596 if requests[&id]["identity"] != identity {
597 return Err(coded(
598 "request_key_conflict",
599 format!(
600 "request_key conflict: {:?} already names job {id} with a different normalized spec or worker; use a new key",
601 resolved.request_key()
602 ),
603 ));
604 }
605 return Ok((id, false));
606 }
607 if detached {
608 check_systemd()?;
609 }
610 let dir = dest.unwrap_or_else(|| root.join("jobs").join(&id));
611 let dir = if dir.is_absolute() {
612 dir
613 } else {
614 std::env::current_dir()?.join(dir)
615 };
616 if dir.exists() {
617 return Err("output already exists; refusing overwrite".into());
618 }
619 let parent = dir.parent().ok_or("output has no parent")?;
620 fs::create_dir_all(parent)?;
621 fs::create_dir(&dir)?;
622 fs::File::open(parent)?.sync_all()?;
624 let dir = fs::canonicalize(dir)?;
625 if let Request::Job(ref mut job) = resolved {
626 stage_inputs(job, tmp.path(), &dir)?;
627 }
628 write_atomic_json(&dir.join("submitted.json"), &submitted)?;
629 write_atomic_json(&dir.join("resolved.json"), &resolved)?;
630 fs::write(dir.join("worker"), bytes)?;
631 #[cfg(unix)]
632 {
633 use std::os::unix::fs::PermissionsExt;
634 fs::set_permissions(dir.join("worker"), fs::Permissions::from_mode(0o700))?;
635 }
636 fs::File::open(dir.join("worker"))?.sync_all()?;
637 let unit = if detached {
638 Some(match resolved {
639 Request::Legacy(_) => format!("fcmaes-{id}.service"),
640 Request::Job(_) => format!("optimization-job-{id}.service"),
641 })
642 } else {
643 None
644 };
645 write_atomic_json(
646 &dir.join("provenance.json"),
647 &json!({"worker_digest":hash,"registered_executable":executable,"identity":identity,"build":w["description"]["build"],"unit":unit,"boot_id":boot()?,"attempt_id":id}),
648 )?;
649 state_write(
650 &dir.join("job.json"),
651 &json!({"id":id,"state":"submitted","submitted_at":now(),"unit":unit,"boot_id":boot()?}),
652 )?;
653 requests[&id] = json!({"identity":identity,"directory":dir});
654 write_atomic_json(&root.join("requests.json"), &requests)?;
655 Ok((id, true))
656}
657fn submit(root: &Path, id: &str) -> Result<()> {
658 let dir = directory(root, id)?;
659 let mut state = read(&dir.join("job.json"))?;
660 state["state"] = json!("starting");
661 state_write(&dir.join("job.json"), &state)?;
662 let unit = state["unit"].as_str().ok_or("missing unit")?;
663 let exe = std::env::current_exe()?;
664 let args = vec![
665 "systemd-run".into(),
666 "--user".into(),
667 "--quiet".into(),
668 format!("--unit={unit}"),
669 "--property=KillMode=control-group".into(),
670 "--property=Restart=no".into(),
671 "--property=TimeoutStopSec=5s".into(),
672 format!("--working-directory={}", dir.display()),
673 exe.to_string_lossy().into_owned(),
674 "--root".into(),
675 root.to_string_lossy().into_owned(),
676 "launch".into(),
677 id.into(),
678 ];
679 match bounded_command(&args, vec![], Duration::from_secs(15), 65536) {
680 Ok((s, _, _)) if s.success() => Ok(()),
681 _ => Err(coded(
682 "start_unknown",
683 format!(
684 "start acknowledgement unknown for {unit}; inspect recorded unit; repeating submit will NOT launch again"
685 ),
686 )),
687 }
688}
689fn launch(root: &Path, id: &str) -> Result<()> {
690 if is_command(&directory(root, id)?)? {
691 execution::launch(root, id, command::Adapter::load)
692 } else {
693 execution::launch(root, id, optimization::Adapter::load)
694 }
695}
696fn is_command(dir: &Path) -> Result<bool> {
697 Ok(optional(&dir.join("job.json"))?["kind"] == "command")
698}
699fn get(root: &Path, id: &str) -> Result<Value> {
700 let dir = directory(root, id)?;
701 let mut v = read(&dir.join("job.json"))?;
702 v["directory"] = json!(dir);
703 if !is_command(&dir)? {
704 let s = spec(&dir.join("resolved.json"))?;
705 for (k, value) in result::progress(&dir, &s)?
707 .as_object()
708 .ok_or("bad progress")?
709 {
710 v[k] = value.clone();
711 }
712 }
713 if !terminal(&v["state"]) && v["boot_id"].as_str() != Some(&boot()?) {
714 v["observed_state"] = json!("interrupted_after_reboot");
715 }
716 if matches!(v["state"].as_str(), Some("waiting" | "running"))
719 && v["observed_state"].is_null()
720 && matches!(lock_is_free(&dir.join("job.lock")), Ok(true))
721 {
722 v["observed_state"] = json!("launcher_lost");
723 v["recovery"] = json!("run `jobs repair` after the worker has exited");
724 }
725 if matches!(
726 v["state"].as_str(),
727 Some("waiting" | "starting" | "running")
728 ) && let Some(unit) = v["unit"].as_str()
729 {
730 let args = vec![
731 "systemctl".into(),
732 "--user".into(),
733 "show".into(),
734 unit.into(),
735 "--property=ActiveState".into(),
736 ];
737 v["service_observation"] =
738 match bounded_command(&args, vec![], Duration::from_secs(3), 4096) {
739 Ok((s, out, _)) if s.success() => json!(String::from_utf8_lossy(&out).trim()),
740 _ => json!("unknown; reservation retained"),
741 };
742 }
743 if dir.join("cancel.request").exists() {
744 v["cancel_requested"] = json!(true);
745 }
746 Ok(v)
747}
748fn repair(root: &Path, id: &str) -> Result<Value> {
749 let dir = directory(root, id)?;
750 if terminal(&read(&dir.join("job.json"))?["state"]) {
751 return Err(coded(
752 "already_terminal",
753 "attempt already finalized; repair is for interrupted attempts",
754 ));
755 }
756 let unadmitted = never_admitted(root, id, &dir)?;
758 if !attempt_processes_gone(&dir) {
759 if matches!(lock_is_free(&dir.join("worker.lock")), Ok(false)) {
764 return Err(coded("attempt_active", "worker still owns this attempt"));
765 }
766 if matches!(lock_is_free(&dir.join("job.lock")), Ok(false)) {
767 return Err(coded("attempt_active", "launcher still owns this attempt"));
768 }
769 return Err(coded(
770 "liveness_unknown",
771 "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",
772 ));
773 }
774 let owner = fs::OpenOptions::new()
775 .create(true)
776 .truncate(false)
777 .read(true)
778 .write(true)
779 .open(dir.join("job.lock"))?;
780 fs2::FileExt::try_lock_exclusive(&owner)
781 .map_err(|_| coded("attempt_active", "launcher still owns this attempt"))?;
782 let worker = fs::OpenOptions::new()
783 .create(true)
784 .truncate(false)
785 .read(true)
786 .write(true)
787 .open(dir.join("worker.lock"))?;
788 fs2::FileExt::try_lock_exclusive(&worker)
789 .map_err(|_| coded("attempt_active", "worker still owns this attempt"))?;
790 let state = read(&dir.join("job.json"))?;
791 if matches!(
792 state["state"].as_str(),
793 Some("completed" | "failed" | "cancelled" | "timed_out" | "interrupted")
794 ) {
795 return Err(coded(
796 "already_terminal",
797 "attempt already finalized; repair is for interrupted attempts",
798 ));
799 }
800 {
803 let _g = lock(&root.join("slots.lock"))?;
804 let mut ledger = optional(&root.join("slots.json"))?;
805 reconcile_ledger(root, &mut ledger)?;
806 ledger.as_object_mut().ok_or("invalid ledger")?.remove(id);
807 write_atomic_json(&root.join("slots.json"), &ledger)?;
808 }
809 let started = state["state"] == "running";
810 if is_command(&dir)? {
811 command::repair(&dir, started)?;
812 } else {
813 optimization::repair(&dir, unadmitted, started)?;
814 }
815 get(root, id)
816}
817fn main_result() -> Result<()> {
818 let cli = match Cli::try_parse() {
821 Ok(cli) => cli,
822 Err(e)
823 if matches!(
824 e.kind(),
825 clap::error::ErrorKind::DisplayHelp
826 | clap::error::ErrorKind::DisplayVersion
827 | clap::error::ErrorKind::DisplayHelpOnMissingArgumentOrSubcommand
828 ) =>
829 {
830 e.exit()
831 }
832 Err(e) => return Err(coded("invalid_command", e.render().to_string())),
833 };
834 if matches!(
835 &cli.command,
836 Cmd::Remote {
837 command: Remote::Serve
838 }
839 ) {
840 return remote::serve();
841 }
842 let selected = cli
843 .root
844 .or_else(|| std::env::var_os("FCMAES_RUN_ROOT").map(PathBuf::from))
845 .unwrap_or_else(|| {
846 let legacy = std::env::current_exe()
847 .ok()
848 .is_some_and(|p| p.file_stem().is_some_and(|s| s == "fcmaes-run"));
849 PathBuf::from(if legacy {
850 ".fcmaes-jobs"
851 } else {
852 ".optimization-jobs"
853 })
854 });
855 if let Cmd::Node {
856 command: Node::Capabilities,
857 } = &cli.command
858 {
859 return output(execution::capabilities(&selected)?);
860 }
861 fs::create_dir_all(&selected)?;
862 let root = fs::canonicalize(&selected)?;
863 match cli.command {
864 Cmd::Remote { .. } => unreachable!(),
865 Cmd::Fleet { command } => output(remote::fleet::run(&root, command)?),
866 Cmd::Node {
867 command: Node::Identity { init },
868 } => output(remote::node::identity(&root, init)?),
869 Cmd::Node {
870 command:
871 Node::Init {
872 capacity: c,
873 allow_commands,
874 },
875 } => {
876 if c == 0 {
877 return Err("capacity must be positive".into());
878 }
879 let _g = lock(&root.join("slots.lock"))?;
880 if root.join("node.json").exists() {
881 return Err("node already initialized; keep its capacity stable".into());
882 }
883 write_atomic_json(
884 &root.join("node.json"),
885 &json!({"capacity":c,"allow_commands":allow_commands,"node_id":remote::node::fresh_id()?}),
886 )?;
887 let warnings = host::warnings(Some(c as u64), &host::host());
890 output(json!({"capacity":c,"warnings":warnings}))
891 }
892 Cmd::Node {
893 command: Node::Commands { enable, disable: _ },
894 } => {
895 capacity(&root)?;
896 let _guard = lock(&root.join("slots.lock"))?;
897 let mut node = read(&root.join("node.json"))?;
898 node["allow_commands"] = json!(enable);
899 write_atomic_json(&root.join("node.json"), &node)?;
900 output(node)
901 }
902 Cmd::Files { command } => output(match command {
903 Files::Put {
904 source,
905 sha256,
906 bytes,
907 } => files::put(&root, &source, bytes, &sha256)?,
908 Files::Get {
909 sha256,
910 bytes,
911 destination,
912 } => files::get(&root, &sha256, bytes, &destination)?,
913 Files::Cleanup => files::cleanup(&root)?,
914 }),
915 Cmd::Node {
916 command: Node::Doctor,
917 } => {
918 let host = host::host();
919 let capacity = capacity(&root).ok();
920 output(
921 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)?}),
922 )
923 }
924 Cmd::Node {
925 command: Node::Capabilities,
926 } => output(execution::capabilities(&root)?),
927 Cmd::Workers {
928 command: Workers::Add { id, executable },
929 } => {
930 if !safe_name(&id) {
931 return Err("invalid worker id".into());
932 }
933 let executable = fs::canonicalize(executable)?;
934 let registered_hash = digest(&fs::read(&executable)?);
935 let (status, out, _) = bounded_command(
936 &[executable.to_string_lossy().into_owned(), "describe".into()],
937 vec![],
938 Duration::from_secs(10),
939 MAX_DESCRIPTION,
940 )
941 .map_err(|e| {
942 if e.to_string().contains("exceeds configured cap") {
943 format!("the worker's describe output exceeds {MAX_DESCRIPTION} bytes").into()
944 } else {
945 Error::from(e)
946 }
947 })?;
948 let description: Value = serde_json::from_slice(&out)?;
949 let generic = protocol_supported(&description["protocol"])
950 && description["profiles"]
951 .as_array()
952 .is_some_and(|p| !p.is_empty() && p.iter().all(Value::is_string));
953 let compatible = id == "native"
954 && ["protocol", "problems", "optimizers", "parallelism"]
955 .iter()
956 .all(|k| description[*k] == discovery()[*k]);
957 if !status.success()
958 || (!generic && !compatible)
959 || registered_hash != digest(&fs::read(&executable)?)
960 {
961 return Err("worker capability profile mismatch or executable changed".into());
962 }
963 let _g = lock(&root.join("registry.lock"))?;
964 let mut w = optional(&root.join("workers.json"))?;
965 w[&id] = json!({"executable":executable,"digest":digest(&fs::read(&executable)?),"description":description});
966 write_atomic_json(&root.join("workers.json"), &w)?;
967 output(w)
968 }
969 Cmd::Workers {
970 command: Workers::List,
971 } => output(optional(&root.join("workers.json"))?),
972 Cmd::Problems {
973 command: Problems::List,
974 } => {
975 if std::env::current_exe()?
976 .file_stem()
977 .is_some_and(|name| name == "fcmaes-run")
978 {
979 output(discovery())
980 } else {
981 output(
982 json!({"legacy":discovery(),"registered":optional(&root.join("workers.json"))?}),
983 )
984 }
985 }
986 Cmd::Problems {
987 command: Problems::Describe { id },
988 } => {
989 let registry = optional(&root.join("workers.json"))?;
990 if !registry[&id].is_null() {
991 output(registry[&id]["description"].clone())
992 } else {
993 let d = discovery();
994 output(
995 d["problems"]
996 .as_array()
997 .unwrap()
998 .iter()
999 .find(|p| p["id"] == id)
1000 .ok_or("unknown worker/problem")?
1001 .clone(),
1002 )
1003 }
1004 }
1005 Cmd::Validate { spec: p }
1006 if read(&p).map_err(invalid)?["schema_version"] == command::SCHEMA =>
1007 {
1008 output(command::check(&root, &p)?)
1009 }
1010 Cmd::Validate { spec: p } => match spec(&p).map_err(invalid)? {
1011 Request::Legacy(s) => output(
1012 json!({"valid":true,"requested_evaluations":s.requested()?,"maximum_actual_evaluations":s.maximum_evaluations()?,"resolved":s}),
1013 ),
1014 Request::Job(_) => {
1015 let (s, _, _, _, _) = staged(&root, &p)?;
1016 output(json!({"valid":true,"resolved":s}))
1017 }
1018 },
1019 Cmd::Run {
1020 spec: p,
1021 output: dest,
1022 } => {
1023 let (id, new) = prepare(&root, &p, dest, false)?;
1024 if new {
1025 launch(&root, &id)?;
1026 }
1027 output(get(&root, &id)?)
1028 }
1029 Cmd::Submit { spec: p } => {
1030 let (id, new) = prepare(&root, &p, None, true)?;
1031 if new {
1032 submit(&root, &id)?;
1033 }
1034 output(get(&root, &id)?)
1035 }
1036 Cmd::Launch { id } => launch(&root, &id),
1037 Cmd::Result { path } if path.is_dir() && is_command(&path)? => {
1038 output(command::result(&path)?)
1039 }
1040 Cmd::Result { path } => output(read(&if path.is_dir() {
1041 path.join("run.json")
1042 } else {
1043 path
1044 })?),
1045 Cmd::Compare { paths } => {
1046 for path in &paths {
1047 if path.is_dir() && is_command(path)? {
1048 return Err(coded(
1049 "unsupported_job_kind",
1050 "compare accepts optimization results; command results have no mathematical claims",
1051 ));
1052 }
1053 }
1054 let runs = paths
1055 .iter()
1056 .map(|p| {
1057 read(&if p.is_dir() {
1058 p.join("run.json")
1059 } else {
1060 p.clone()
1061 })
1062 })
1063 .collect::<Result<Vec<_>>>()?;
1064 output(result::compare(&runs)?)
1065 }
1066 Cmd::Jobs { command } => match command {
1067 Jobs::Collect {
1068 id,
1069 name,
1070 destination,
1071 } => output(command::collect(
1072 &directory(&root, &id)?,
1073 &name,
1074 &destination,
1075 )?),
1076 Jobs::Events { id } => {
1077 let dir = directory(&root, &id)?;
1078 output(json!(read_checked::<Value>(&dir.join("events.jsonl"), 1)?))
1079 }
1080 Jobs::List => {
1081 let requests = optional(&root.join("requests.json"))?;
1082 let mut jobs = vec![];
1083 for id in requests.as_object().ok_or("bad requests")?.keys() {
1084 jobs.push(
1085 get(&root, id).unwrap_or_else(|e| json!({"id":id,"error":e.to_string()})),
1086 );
1087 }
1088 output(json!(jobs))
1089 }
1090 Jobs::Get { id } => output(get(&root, &id)?),
1091 Jobs::Execution { id } => output(execution::record(&directory(&root, &id)?)?),
1092 Jobs::Wait { id, timeout } => {
1093 if !timeout.is_finite() || timeout <= 0.0 {
1094 return Err("positive finite timeout required".into());
1095 }
1096 let t = Instant::now();
1097 loop {
1098 let v = get(&root, &id)?;
1099 if matches!(
1100 v["state"].as_str(),
1101 Some("completed" | "failed" | "cancelled" | "timed_out" | "interrupted")
1102 ) || !v["observed_state"].is_null()
1103 || t.elapsed().as_secs_f64() >= timeout
1104 {
1105 return output(v);
1106 }
1107 thread::sleep(Duration::from_millis(250));
1108 }
1109 }
1110 Jobs::Cancel { id, now: immediate } => {
1111 let dir = directory(&root, &id)?;
1112 let state = read(&dir.join("job.json"))?["state"].clone();
1115 if terminal(&state) {
1116 return Err(coded(
1117 "already_terminal",
1118 format!(
1119 "job {id} already ended as {}; nothing to cancel",
1120 state.as_str().unwrap_or_default()
1121 ),
1122 ));
1123 }
1124 let mode = if immediate { "immediate" } else { "graceful" };
1127 publish_stop(&dir, json!({"mode":mode,"requested_at":now()}))?;
1128 output(get(&root, &id)?)
1129 }
1130 Jobs::Reconcile => {
1131 let _g = lock(&root.join("slots.lock"))?;
1132 let mut l = optional(&root.join("slots.json"))?;
1133 reconcile_ledger(&root, &mut l)?;
1134 write_atomic_json(&root.join("slots.json"), &l)?;
1135 output(l)
1136 }
1137 Jobs::Repair { id } => output(repair(&root, &id)?),
1138 Jobs::Progress { id, offset, limit } => {
1139 if !(1..=10000).contains(&limit) {
1140 return Err(coded("invalid_command", "limit must be 1..10000"));
1141 }
1142 let dir = directory(&root, &id)?;
1143 if !is_command(&dir)? {
1144 return Err(coded(
1145 "unsupported_job_kind",
1146 "progress files belong to command jobs; use jobs artifact for optimization jobs",
1147 ));
1148 }
1149 output(command::progress(&dir, &id, offset, limit)?)
1150 }
1151 Jobs::Artifact {
1152 id,
1153 name,
1154 offset,
1155 limit,
1156 } => {
1157 let dir = directory(&root, &id)?;
1158 if is_command(&dir)? {
1159 return Err(coded(
1160 "unsupported_job_kind",
1161 "use jobs collect for binary command outputs",
1162 ));
1163 }
1164 let unknown = |why: &[String]| {
1165 coded(
1166 "unknown_artifact",
1167 format!(
1168 "job {id} has no artifact {name:?}{}",
1169 if why.is_empty() {
1170 String::new()
1171 } else {
1172 format!(" ({})", why.join("; "))
1173 }
1174 ),
1175 )
1176 };
1177 let sealed = dir.join("run.json").exists();
1180 let (file, format, sha256) = if sealed {
1181 let run = read(&dir.join("run.json"))?;
1182 let file = run["artifacts"][&name]
1183 .as_str()
1184 .ok_or_else(|| unknown(&[]))?;
1185 let index = &run["runner"]["artifact_index"][&name];
1186 let format = index["format"]
1188 .as_str()
1189 .unwrap_or(if name == artifact::RESULTS {
1190 "records"
1191 } else {
1192 "file"
1193 });
1194 (
1195 file.to_string(),
1196 format.to_string(),
1197 index["sha256"].as_str().map(String::from),
1198 )
1199 } else {
1200 let (list, errors) = artifact::all_or_results(&dir);
1201 let d = list
1202 .into_iter()
1203 .find(|d| d.name == name)
1204 .ok_or_else(|| unknown(&errors))?;
1205 (d.file, d.format, None)
1206 };
1207 let path = match fs::canonicalize(dir.join(&file)) {
1208 Ok(path) => path,
1209 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
1210 return Err(coded(
1211 "unknown_artifact",
1212 format!("artifact {name:?} of job {id} has no file yet"),
1213 ));
1214 }
1215 Err(e) => return Err(e.into()),
1216 };
1217 if !path.starts_with(fs::canonicalize(&dir)?) || !path.is_file() {
1218 return Err("artifact escapes job directory or is no file".into());
1219 }
1220 let paged = offset.is_some() || limit.is_some();
1223 if let Some(sealed) = sha256
1224 && !paged
1225 && artifact::digest_file(&path)?.1 != sealed
1226 {
1227 return Err(format!(
1228 "artifact {name:?} changed after the job ended: its SHA-256 differs from the manifest"
1229 )
1230 .into());
1231 }
1232 let mut value = if paged {
1233 if format != "records" {
1234 return Err(coded(
1235 "invalid_command",
1236 format!(
1237 "artifact {name:?} has format {format}; only records artifacts have pages"
1238 ),
1239 ));
1240 }
1241 artifact::page(&path, offset.unwrap_or(0), limit.unwrap_or(100))?
1242 } else {
1243 artifact::content(&path, &format)?
1244 };
1245 value["name"] = json!(name);
1246 value["file"] = json!(file);
1247 value["final"] = json!(sealed);
1248 output(value)
1249 }
1250 },
1251 }
1252}
1253pub fn main() {
1257 if !cfg!(target_os = "linux") {
1258 eprintln!("Linux is required for process supervision");
1259 std::process::exit(2);
1260 }
1261 if let Err(e) = main_result() {
1262 let code = error_code(&e);
1263 eprintln!(
1264 "{}",
1265 json!({"error":{"code":code,"message":e.to_string(),"retryable":retryable(code)}})
1266 );
1267 std::process::exit(2);
1268 }
1269}
1270
1271#[cfg(test)]
1272mod tests {
1273 use super::*;
1274
1275 #[test]
1276 fn stop_requests_only_escalate() {
1277 let dir = tempfile::tempdir().unwrap();
1278 let marker = |dir: &Path| read(&dir.join("cancel.request")).unwrap();
1279 let timeout = json!({"mode":"graceful","reason":"timed_out"});
1280 let graceful = json!({"mode":"graceful"});
1281 let immediate = json!({"mode":"immediate"});
1282 assert!(publish_stop(dir.path(), timeout.clone()).unwrap());
1283 assert!(!publish_stop(dir.path(), timeout.clone()).unwrap());
1284 assert!(publish_stop(dir.path(), graceful.clone()).unwrap());
1286 assert!(!publish_stop(dir.path(), timeout).unwrap());
1287 assert!(publish_stop(dir.path(), immediate.clone()).unwrap());
1288 assert!(!publish_stop(dir.path(), graceful).unwrap());
1290 assert_eq!(marker(dir.path()), immediate);
1291 fs::write(dir.path().join("cancel.request"), b"{").unwrap();
1293 assert!(!publish_stop(dir.path(), immediate).unwrap());
1294 }
1295}