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