optimization-runner 0.6.0

Local runner (optimization-run) and MCP server (optimization-mcp) for versioned optimization jobs on one CPU budget
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
#![doc = include_str!("../README.md")]
#![warn(missing_docs)]
mod admission;
mod command;
mod execution;
mod files;
mod host;
mod optimization;
mod remote;
mod supervision;

use admission::reconcile_ledger;
pub mod mcp;

use clap::{Parser, Subcommand};
use optimization_job_api::{legacy::discovery, process::*, result, storage::*, *};
use serde_json::{Value, json};
use std::{
    fs,
    path::{Path, PathBuf},
    sync::atomic::{AtomicUsize, Ordering},
    thread,
    time::{Duration, Instant, SystemTime, UNIX_EPOCH},
};
#[derive(Parser)]
#[command(
    version,
    about = "Durable local jobs: optimization and opt-in commands (Linux)"
)]
struct Cli {
    #[arg(long, global = true, env = "OPTIMIZATION_RUN_ROOT")]
    root: Option<PathBuf>,
    #[arg(long, global = true)]
    json: bool,
    #[command(subcommand)]
    command: Cmd,
}
#[derive(Subcommand)]
enum Cmd {
    /// Explicit placement on a registered SSH node.
    Fleet {
        #[command(subcommand)]
        command: remote::fleet::Cli,
    },
    /// Fixed remote helper; requests and data use stdin/stdout.
    Remote {
        #[command(subcommand)]
        command: Remote,
    },
    Node {
        #[command(subcommand)]
        command: Node,
    },
    Files {
        #[command(subcommand)]
        command: Files,
    },
    Workers {
        #[command(subcommand)]
        command: Workers,
    },
    Problems {
        #[command(subcommand)]
        command: Problems,
    },
    Validate {
        #[arg(long)]
        spec: PathBuf,
    },
    Run {
        #[arg(long)]
        spec: PathBuf,
        #[arg(long)]
        output: Option<PathBuf>,
    },
    Submit {
        #[arg(long)]
        spec: PathBuf,
    },
    Jobs {
        #[command(subcommand)]
        command: Jobs,
    },
    Result {
        path: PathBuf,
    },
    Compare {
        #[arg(required=true,num_args=2..)]
        paths: Vec<PathBuf>,
    },
    #[command(hide = true)]
    Launch {
        id: String,
    },
}
#[derive(Subcommand)]
enum Remote {
    Serve,
}
#[derive(Subcommand)]
enum Node {
    /// Read an identity; --init adds one to a node made by an older runner.
    Identity {
        #[arg(long)]
        init: bool,
    },
    Init {
        #[arg(long)]
        capacity: usize,
        /// Allow trusted local command jobs (same Unix user, no sandbox).
        #[arg(long)]
        allow_commands: bool,
    },
    /// Change admission policy for new commands; accepted jobs may finish.
    Commands {
        #[arg(long, conflicts_with = "disable", required_unless_present = "disable")]
        enable: bool,
        #[arg(long)]
        disable: bool,
    },
    Doctor,
    /// Versioned execution kinds and record schemas, independent of node setup.
    Capabilities,
}
#[derive(Subcommand)]
enum Files {
    /// Stage a verified binary file, or read bytes from stdin with --source -.
    Put {
        #[arg(long)]
        source: PathBuf,
        #[arg(long)]
        sha256: String,
        #[arg(long)]
        bytes: u64,
    },
    /// Copy a verified blob to a new local file; never replace a destination.
    Get {
        sha256: String,
        #[arg(long)]
        bytes: u64,
        #[arg(long)]
        destination: PathBuf,
    },
    /// Remove interrupted upload partials; retain verified blobs.
    Cleanup,
}
#[derive(Subcommand)]
enum Workers {
    Add {
        #[arg(long)]
        id: String,
        #[arg(long)]
        executable: PathBuf,
    },
    List,
}
#[derive(Subcommand)]
enum Problems {
    List,
    Describe { id: String },
}
#[derive(Subcommand)]
enum Jobs {
    /// Collect a sealed binary command output into a new local file.
    Collect {
        id: String,
        name: String,
        #[arg(long)]
        destination: PathBuf,
    },
    List,
    Events {
        id: String,
    },
    Get {
        id: String,
    },
    /// Read the neutral terminal execution record (new attempts or repaired ones).
    Execution {
        id: String,
    },
    Wait {
        id: String,
        #[arg(long, default_value_t = 60.0)]
        timeout: f64,
    },
    /// Stop a job. By default the active retry wave finishes and is kept;
    /// `--now` kills the worker after one second and loses the active wave.
    Cancel {
        id: String,
        #[arg(long)]
        now: bool,
    },
    Reconcile,
    Repair {
        id: String,
    },
    /// Read the complete JSON lines of a command job's declared progress
    /// file, also while the job runs, a page at a time.
    Progress {
        id: String,
        /// First record of the page.
        #[arg(long, default_value_t = 0)]
        offset: usize,
        /// Records of the page, 1 to 10000.
        #[arg(long, default_value_t = 1000)]
        limit: usize,
    },
    /// Read an artifact, also while the job runs: its whole content (at
    /// most 1 MiB), or with `--offset`/`--limit` a page of the checked
    /// records of a `records` artifact.
    Artifact {
        id: String,
        name: String,
        /// First record of the page (records artifacts only).
        #[arg(long)]
        offset: Option<usize>,
        /// Records of the page, 1 to 10000 (default 100 when only --offset is given).
        #[arg(long)]
        limit: Option<usize>,
    },
}
/// Number of SIGINT/SIGTERM/SIGHUP received: one requests a graceful stop,
/// two or more an immediate one.
static SIGNALS: AtomicUsize = AtomicUsize::new(0);
extern "C" fn stop_handler(_: i32) {
    SIGNALS.fetch_add(1, Ordering::Relaxed);
}
/// SIGHUP matters for foreground runs: a closed terminal or agent shell must
/// stop the job instead of orphaning the worker.
fn install_stop_handlers() {
    for signal in [libc::SIGINT, libc::SIGTERM, libc::SIGHUP] {
        unsafe {
            libc::signal(signal, stop_handler as *const () as libc::sighandler_t);
        }
    }
}
/// Kill delay after an immediate stop request.
const IMMEDIATE_GRACE: Duration = Duration::from_secs(1);
/// Largest `describe` output a worker may register: its profiles, models
/// and options, and the JSON Schemas of its payloads and inputs with
/// runnable examples ([guide](https://github.com/dietmarwo/optimization-jobs/blob/main/docs/job-api.md#discovery-for-agents)).
const MAX_DESCRIPTION: usize = 1 << 20;
#[derive(Clone, Copy, Debug, PartialEq, PartialOrd)]
enum Stop {
    None,
    Graceful,
    Immediate,
}
/// Pending stop request from signals or `cancel.request`. The launcher's own
/// timeout marker (reason `timed_out`) is not a cancellation.
fn stop_request(dir: &Path) -> Stop {
    let from_signals = match SIGNALS.load(Ordering::Relaxed) {
        0 => Stop::None,
        1 => Stop::Graceful,
        _ => Stop::Immediate,
    };
    let path = dir.join("cancel.request");
    let from_file = if !path.exists() {
        Stop::None
    } else {
        match read(&path) {
            Ok(v) if v["reason"] == "timed_out" => Stop::None,
            Ok(v) if v["mode"] == "graceful" => Stop::Graceful,
            // An unreadable or unknown request is treated as the stronger one.
            _ => Stop::Immediate,
        }
    };
    if from_file > from_signals {
        from_file
    } else {
        from_signals
    }
}
/// Strength of a published stop request: no marker, the launcher's own
/// timeout marker, a graceful cancellation, an immediate one. An unreadable
/// marker counts as immediate, as in [`stop_request`].
fn stop_rank(marker: &Result<Value>) -> u8 {
    match marker {
        Ok(v) if v.as_object().is_some_and(|o| o.is_empty()) => 0,
        Ok(v) if v["reason"] == "timed_out" => 1,
        Ok(v) if v["mode"] == "graceful" => 2,
        _ => 3,
    }
}
/// Publishes `marker` as `cancel.request` unless a request at least as
/// strong is already there, and returns whether it did. Requests only
/// escalate: the CLI (`jobs cancel`), the launcher's timeout and its signal
/// handler all write through here under `cancel.lock`, a short-held lock of
/// its own (`job.lock` is held by the launcher for its whole life), so a
/// graceful request read before an immediate one was written can no longer
/// replace it.
fn publish_stop(dir: &Path, marker: Value) -> Result<bool> {
    let _guard = lock(&dir.join("cancel.lock"))?;
    let path = dir.join("cancel.request");
    if stop_rank(&Ok(marker.clone())) <= stop_rank(&optional(&path)) {
        return Ok(false);
    }
    write_atomic_json(&path, &marker)?;
    Ok(true)
}
fn read(path: &Path) -> Result<Value> {
    let bytes = fs::read(path).map_err(|e| format!("{}: {e}", path.display()))?;
    Ok(serde_json::from_slice(&bytes).map_err(|e| format!("{}: {e}", path.display()))?)
}
fn optional(path: &Path) -> Result<Value> {
    if path.exists() {
        read(path)
    } else {
        Ok(json!({}))
    }
}
fn state_write(path: &Path, state: &Value) -> Result<()> {
    append_checked(
        &path.with_file_name("events.jsonl"),
        1,
        &json!({"event":"state","state":state["state"],"at":now(),"id":state["id"]}),
    )?;
    write_atomic_json(path, state)?;
    Ok(())
}
fn terminal(state: &Value) -> bool {
    matches!(
        state.as_str(),
        Some("completed" | "failed" | "cancelled" | "timed_out" | "interrupted")
    )
}
fn now() -> f64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap()
        .as_secs_f64()
}
fn boot() -> Result<String> {
    Ok(fs::read_to_string("/proc/sys/kernel/random/boot_id")?
        .trim()
        .to_owned())
}
fn output(value: Value) -> Result<()> {
    println!("{}", serde_json::to_string_pretty(&value)?);
    Ok(())
}
fn spec(path: &Path) -> Result<Request> {
    Request::parse(&fs::read(path).map_err(|e| format!("{}: {e}", path.display()))?)
}
/// An error of the submitted job itself: `invalid_job`, unless it already
/// has a code.
fn invalid(e: Error) -> Error {
    if e.downcast_ref::<Coded>().is_some() {
        e
    } else {
        coded("invalid_job", e.to_string())
    }
}
/// Stages and validates the job file `input`, read once: the parsed request,
/// the worker registration, the worker executable, the staging directory and
/// the file's JSON as submitted.
fn staged(
    root: &Path,
    input: &Path,
) -> Result<(Request, Value, Vec<u8>, tempfile::TempDir, Value)> {
    let raw = fs::read(input).map_err(|e| invalid(format!("{}: {e}", input.display()).into()))?;
    let submitted: Value = serde_json::from_slice(&raw)
        .map_err(|e| invalid(format!("{}: {e}", input.display()).into()))?;
    let mut s = Request::parse(&raw)?;
    let w = worker(root, s.worker())?;
    let exe = Path::new(w["executable"].as_str().ok_or("invalid executable")?);
    let bytes = fs::read(exe)?;
    if w["digest"] != digest(&bytes) {
        return Err(coded(
            "worker_changed",
            "worker changed since registration; register again explicitly",
        ));
    }
    // The node root must allow execution anyway (attempts run their staged
    // worker there); TMPDIR may be mounted noexec.
    let tmp = tempfile::Builder::new()
        .prefix(".staging-")
        .tempdir_in(root)?;
    let executable = tmp.path().join("worker");
    fs::write(&executable, &bytes)?;
    {
        use std::os::unix::fs::PermissionsExt;
        fs::set_permissions(&executable, fs::Permissions::from_mode(0o700))?;
    }
    if let Request::Job(ref mut job) = s {
        if !protocol_supported(&w["description"]["protocol"])
            || !w["description"]["profiles"]
                .as_array()
                .is_some_and(|a| a.iter().any(|v| v.as_str() == Some(&job.payload_schema)))
        {
            return Err(coded(
                "unsupported_profile",
                format!(
                    "worker {} does not support payload schema {}",
                    job.worker, job.payload_schema
                ),
            ));
        }
        stage_inputs(
            job,
            input
                .parent()
                .filter(|p| !p.as_os_str().is_empty())
                .unwrap_or(Path::new(".")),
            tmp.path(),
        )
        .map_err(|e| coded("invalid_job", format!("input: {e}")))?;
        write_atomic_json(&tmp.path().join("request.json"), job)?;
        // A signal during validation stops the validator too: it runs in its
        // own process group, which a terminal's SIGINT does not reach.
        install_stop_handlers();
        let (status, out, err) = bounded_command_until(
            &[
                executable.to_string_lossy().into_owned(),
                "validate".into(),
                tmp.path()
                    .join("request.json")
                    .to_string_lossy()
                    .into_owned(),
            ],
            vec![],
            Duration::from_secs(30),
            4 * 1024 * 1024,
            &|| SIGNALS.load(Ordering::Relaxed) > 0,
        )
        .map_err(|e| match e.kind() {
            std::io::ErrorKind::TimedOut => {
                coded("invalid_job", "worker validation took longer than 30 s")
            }
            _ if e.to_string().contains("exceeds configured cap") => coded(
                "invalid_job",
                "the resolved job exceeds the 4 MiB validation output; keep inline starts or points well below 4 MiB",
            ),
            _ => e.into(),
        })?;
        if !status.success() {
            return Err(coded(
                "invalid_job",
                format!(
                    "worker validation failed: {}",
                    String::from_utf8_lossy(&err)
                ),
            ));
        }
        let answer: Value = serde_json::from_slice(&out)?;
        let resolved: JobSpec = serde_json::from_value(answer["resolved"].clone())?;
        resolved.validate()?;
        let mut envelope = resolved.clone();
        envelope.payload = job.payload.clone();
        envelope.task_count = job.task_count;
        if envelope != *job || resolved.task_count.is_none() {
            return Err("worker changed shared envelope or omitted task count".into());
        }
        *job = resolved;
    }
    Ok((s, w, bytes, tmp, submitted))
}
/// True when neither the launcher (`job.lock`) nor the worker (`worker.lock`)
/// of an attempt is alive. Both hold their lock for their whole lifetime and
/// the native worker starts no processes of its own. Errors count as alive.
fn attempt_processes_gone(dir: &Path) -> bool {
    let locks = matches!(lock_is_free(&dir.join("job.lock")), Ok(true))
        && matches!(lock_is_free(&dir.join("worker.lock")), Ok(true));
    if !locks {
        return false;
    }
    // Nothing of an attempt survives a reboot: its processes and transient
    // unit ended with the boot that recorded them, and a recorded process
    // group ID may since belong to an unrelated process.
    let current = boot().ok();
    let earlier_boot = |v: &Value| current.is_some() && v["boot_id"].as_str() != current.as_deref();
    if let Ok(p) = read(&dir.join("worker-process.json")) {
        return earlier_boot(&p)
            || p["pgid"]
                .as_u64()
                .and_then(|n| u32::try_from(n).ok())
                .is_some_and(|pid| group_stopped(pid).unwrap_or(false));
    }
    read(&dir.join("job.json"))
        .is_ok_and(|s| terminal(&s["state"]) || never_started(&s) || earlier_boot(&s))
}
/// Without a recorded process group, a worker can exist only if the attempt
/// reached `running`, which is recorded before the worker is spawned. A
/// queued attempt (or a foreground one not yet launched) whose launcher is
/// gone therefore has no worker. Detached `submitted`/`starting` attempts may
/// still be started by their unit, so they do not count.
fn never_started(job: &Value) -> bool {
    job["state"] == "waiting"
        || (matches!(job["state"].as_str(), Some("submitted" | "starting"))
            && job["unit"].is_null())
}
/// True when an attempt's launcher died before admission: it never started a
/// worker, holds no lock, has no process record and no slot reservation. Such
/// an attempt did provably zero work and can be sealed with complete
/// (empty) accounting.
fn never_admitted(root: &Path, id: &str, dir: &Path) -> Result<bool> {
    if dir.join("worker-process.json").exists()
        || !never_started(&read(&dir.join("job.json"))?)
        || !matches!(lock_is_free(&dir.join("job.lock")), Ok(true))
        || !matches!(lock_is_free(&dir.join("worker.lock")), Ok(true))
    {
        return Ok(false);
    }
    let _g = lock(&root.join("slots.lock"))?;
    Ok(optional(&root.join("slots.json"))?[id].is_null())
}
fn capacity(root: &Path) -> Result<u64> {
    let path = root.join("node.json");
    if !path.exists() {
        return Err(coded(
            "node_not_initialized",
            "node init --capacity required",
        ));
    }
    read(&path)?["capacity"]
        .as_u64()
        .ok_or_else(|| "node.json has no valid capacity".into())
}
fn worker(root: &Path, id: &str) -> Result<Value> {
    let w = optional(&root.join("workers.json"))?[id].clone();
    if w.is_null() {
        return Err(coded(
            "unknown_worker",
            format!("register worker {id} first"),
        ));
    }
    Ok(w)
}
fn directory(root: &Path, id: &str) -> Result<PathBuf> {
    if id.len() != 32 || !id.bytes().all(|b| b.is_ascii_hexdigit()) {
        return Err(coded("unknown_job", format!("invalid job id {id:?}")));
    }
    let entry = optional(&root.join("requests.json"))?[id].clone();
    Ok(PathBuf::from(entry["directory"].as_str().ok_or_else(
        || coded("unknown_job", format!("no job {id} on this node")),
    )?))
}
fn check_systemd() -> Result<()> {
    let (s, out, _) = bounded_command(
        &[
            "systemctl".into(),
            "--user".into(),
            "show".into(),
            "--property=Version".into(),
        ],
        vec![],
        Duration::from_secs(10),
        65536,
    )?;
    if !s.success()
        || !String::from_utf8_lossy(&out)
            .lines()
            .any(|x| x.starts_with("Version=") && x.len() > 8)
    {
        return Err(coded(
            "systemd_unavailable",
            "systemd user manager unavailable; use foreground run",
        ));
    }
    Ok(())
}
fn prepare(
    root: &Path,
    input: &Path,
    dest: Option<PathBuf>,
    detached: bool,
) -> Result<(String, bool)> {
    if read(input).map_err(invalid)?["schema_version"] == command::SCHEMA {
        return command::prepare(root, input, dest, detached);
    }
    let (mut resolved, w, bytes, tmp, submitted) = staged(root, input)?;
    let node = capacity(root)?;
    if resolved.slots() as u64 > node {
        return Err(coded(
            "capacity_exceeded",
            format!(
                "the job requests {} CPU slots but the node capacity is {node}; it can never be admitted here",
                resolved.slots()
            ),
        ));
    }
    let executable = Path::new(
        w["executable"]
            .as_str()
            .ok_or("invalid worker registration")?,
    );
    let hash = digest(&bytes);
    let id = digest(resolved.request_key().as_bytes())[..32].to_owned();
    let identity = digest(&serde_json::to_vec(
        &json!({"spec":resolved,"worker_digest":hash}),
    )?);
    let _guard = lock(&root.join("registry.lock"))?;
    let mut requests = optional(&root.join("requests.json"))?;
    if !requests[&id].is_null() {
        if requests[&id]["identity"] != identity {
            return Err(coded(
                "request_key_conflict",
                format!(
                    "request_key conflict: {:?} already names job {id} with a different normalized spec or worker; use a new key",
                    resolved.request_key()
                ),
            ));
        }
        return Ok((id, false));
    }
    if detached {
        check_systemd()?;
    }
    let dir = dest.unwrap_or_else(|| root.join("jobs").join(&id));
    let dir = if dir.is_absolute() {
        dir
    } else {
        std::env::current_dir()?.join(dir)
    };
    if dir.exists() {
        return Err("output already exists; refusing overwrite".into());
    }
    let parent = dir.parent().ok_or("output has no parent")?;
    fs::create_dir_all(parent)?;
    fs::create_dir(&dir)?;
    // requests.json will point here; make the directory entry durable first.
    fs::File::open(parent)?.sync_all()?;
    let dir = fs::canonicalize(dir)?;
    if let Request::Job(ref mut job) = resolved {
        stage_inputs(job, tmp.path(), &dir)?;
    }
    write_atomic_json(&dir.join("submitted.json"), &submitted)?;
    write_atomic_json(&dir.join("resolved.json"), &resolved)?;
    fs::write(dir.join("worker"), bytes)?;
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        fs::set_permissions(dir.join("worker"), fs::Permissions::from_mode(0o700))?;
    }
    fs::File::open(dir.join("worker"))?.sync_all()?;
    let unit = if detached {
        Some(match resolved {
            Request::Legacy(_) => format!("fcmaes-{id}.service"),
            Request::Job(_) => format!("optimization-job-{id}.service"),
        })
    } else {
        None
    };
    write_atomic_json(
        &dir.join("provenance.json"),
        &json!({"worker_digest":hash,"registered_executable":executable,"identity":identity,"build":w["description"]["build"],"unit":unit,"boot_id":boot()?,"attempt_id":id}),
    )?;
    state_write(
        &dir.join("job.json"),
        &json!({"id":id,"state":"submitted","submitted_at":now(),"unit":unit,"boot_id":boot()?}),
    )?;
    requests[&id] = json!({"identity":identity,"directory":dir});
    write_atomic_json(&root.join("requests.json"), &requests)?;
    Ok((id, true))
}
fn submit(root: &Path, id: &str) -> Result<()> {
    let dir = directory(root, id)?;
    let mut state = read(&dir.join("job.json"))?;
    state["state"] = json!("starting");
    state_write(&dir.join("job.json"), &state)?;
    let unit = state["unit"].as_str().ok_or("missing unit")?;
    let exe = std::env::current_exe()?;
    let args = vec![
        "systemd-run".into(),
        "--user".into(),
        "--quiet".into(),
        format!("--unit={unit}"),
        "--property=KillMode=control-group".into(),
        "--property=Restart=no".into(),
        "--property=TimeoutStopSec=5s".into(),
        format!("--working-directory={}", dir.display()),
        exe.to_string_lossy().into_owned(),
        "--root".into(),
        root.to_string_lossy().into_owned(),
        "launch".into(),
        id.into(),
    ];
    match bounded_command(&args, vec![], Duration::from_secs(15), 65536) {
        Ok((s, _, _)) if s.success() => Ok(()),
        _ => Err(coded(
            "start_unknown",
            format!(
                "start acknowledgement unknown for {unit}; inspect recorded unit; repeating submit will NOT launch again"
            ),
        )),
    }
}
fn launch(root: &Path, id: &str) -> Result<()> {
    if is_command(&directory(root, id)?)? {
        execution::launch(root, id, command::Adapter::load)
    } else {
        execution::launch(root, id, optimization::Adapter::load)
    }
}
fn is_command(dir: &Path) -> Result<bool> {
    Ok(optional(&dir.join("job.json"))?["kind"] == "command")
}
fn get(root: &Path, id: &str) -> Result<Value> {
    let dir = directory(root, id)?;
    let mut v = read(&dir.join("job.json"))?;
    v["directory"] = json!(dir);
    if !is_command(&dir)? {
        let s = spec(&dir.join("resolved.json"))?;
        // A corrupt journal is an error here; `jobs list` reports it per job.
        for (k, value) in result::progress(&dir, &s)?
            .as_object()
            .ok_or("bad progress")?
        {
            v[k] = value.clone();
        }
    }
    if !terminal(&v["state"]) && v["boot_id"].as_str() != Some(&boot()?) {
        v["observed_state"] = json!("interrupted_after_reboot");
    }
    // A launcher holds job.lock for its whole lifetime, so a free lock in an
    // active state means it died (SIGKILL, closed terminal) without finishing.
    if matches!(v["state"].as_str(), Some("waiting" | "running"))
        && v["observed_state"].is_null()
        && matches!(lock_is_free(&dir.join("job.lock")), Ok(true))
    {
        v["observed_state"] = json!("launcher_lost");
        v["recovery"] = json!("run `jobs repair` after the worker has exited");
    }
    if matches!(
        v["state"].as_str(),
        Some("waiting" | "starting" | "running")
    ) && let Some(unit) = v["unit"].as_str()
    {
        let args = vec![
            "systemctl".into(),
            "--user".into(),
            "show".into(),
            unit.into(),
            "--property=ActiveState".into(),
        ];
        v["service_observation"] =
            match bounded_command(&args, vec![], Duration::from_secs(3), 4096) {
                Ok((s, out, _)) if s.success() => json!(String::from_utf8_lossy(&out).trim()),
                _ => json!("unknown; reservation retained"),
            };
    }
    if dir.join("cancel.request").exists() {
        v["cancel_requested"] = json!(true);
    }
    Ok(v)
}
fn repair(root: &Path, id: &str) -> Result<Value> {
    let dir = directory(root, id)?;
    if terminal(&read(&dir.join("job.json"))?["state"]) {
        return Err(coded(
            "already_terminal",
            "attempt already finalized; repair is for interrupted attempts",
        ));
    }
    // Decided before the reservation is touched below.
    let unadmitted = never_admitted(root, id, &dir)?;
    if !attempt_processes_gone(&dir) {
        // A held lock is a live launcher or worker: waiting helps.
        // Without one, liveness stays unknown (a process group
        // that still exists, or a detached unit that may yet
        // start); waiting alone may never settle it.
        if matches!(lock_is_free(&dir.join("worker.lock")), Ok(false)) {
            return Err(coded("attempt_active", "worker still owns this attempt"));
        }
        if matches!(lock_is_free(&dir.join("job.lock")), Ok(false)) {
            return Err(coded("attempt_active", "launcher still owns this attempt"));
        }
        return Err(coded(
            "liveness_unknown",
            "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",
        ));
    }
    let owner = fs::OpenOptions::new()
        .create(true)
        .truncate(false)
        .read(true)
        .write(true)
        .open(dir.join("job.lock"))?;
    fs2::FileExt::try_lock_exclusive(&owner)
        .map_err(|_| coded("attempt_active", "launcher still owns this attempt"))?;
    let worker = fs::OpenOptions::new()
        .create(true)
        .truncate(false)
        .read(true)
        .write(true)
        .open(dir.join("worker.lock"))?;
    fs2::FileExt::try_lock_exclusive(&worker)
        .map_err(|_| coded("attempt_active", "worker still owns this attempt"))?;
    let state = read(&dir.join("job.json"))?;
    if matches!(
        state["state"].as_str(),
        Some("completed" | "failed" | "cancelled" | "timed_out" | "interrupted")
    ) {
        return Err(coded(
            "already_terminal",
            "attempt already finalized; repair is for interrupted attempts",
        ));
    }
    // Holding both locks proves the launcher and worker are gone, so
    // this attempt's reservation can be released.
    {
        let _g = lock(&root.join("slots.lock"))?;
        let mut ledger = optional(&root.join("slots.json"))?;
        reconcile_ledger(root, &mut ledger)?;
        ledger.as_object_mut().ok_or("invalid ledger")?.remove(id);
        write_atomic_json(&root.join("slots.json"), &ledger)?;
    }
    let started = state["state"] == "running";
    if is_command(&dir)? {
        command::repair(&dir, started)?;
    } else {
        optimization::repair(&dir, unadmitted, started)?;
    }
    get(root, id)
}
fn main_result() -> Result<()> {
    // Usage errors are coded like every other error; help and version print
    // normally.
    let cli = match Cli::try_parse() {
        Ok(cli) => cli,
        Err(e)
            if matches!(
                e.kind(),
                clap::error::ErrorKind::DisplayHelp
                    | clap::error::ErrorKind::DisplayVersion
                    | clap::error::ErrorKind::DisplayHelpOnMissingArgumentOrSubcommand
            ) =>
        {
            e.exit()
        }
        Err(e) => return Err(coded("invalid_command", e.render().to_string())),
    };
    if matches!(
        &cli.command,
        Cmd::Remote {
            command: Remote::Serve
        }
    ) {
        return remote::serve();
    }
    let selected = cli
        .root
        .or_else(|| std::env::var_os("FCMAES_RUN_ROOT").map(PathBuf::from))
        .unwrap_or_else(|| {
            let legacy = std::env::current_exe()
                .ok()
                .is_some_and(|p| p.file_stem().is_some_and(|s| s == "fcmaes-run"));
            PathBuf::from(if legacy {
                ".fcmaes-jobs"
            } else {
                ".optimization-jobs"
            })
        });
    if let Cmd::Node {
        command: Node::Capabilities,
    } = &cli.command
    {
        return output(execution::capabilities(&selected)?);
    }
    fs::create_dir_all(&selected)?;
    let root = fs::canonicalize(&selected)?;
    match cli.command {
        Cmd::Remote { .. } => unreachable!(),
        Cmd::Fleet { command } => output(remote::fleet::run(&root, command)?),
        Cmd::Node {
            command: Node::Identity { init },
        } => output(remote::node::identity(&root, init)?),
        Cmd::Node {
            command:
                Node::Init {
                    capacity: c,
                    allow_commands,
                },
        } => {
            if c == 0 {
                return Err("capacity must be positive".into());
            }
            let _g = lock(&root.join("slots.lock"))?;
            if root.join("node.json").exists() {
                return Err("node already initialized; keep its capacity stable".into());
            }
            write_atomic_json(
                &root.join("node.json"),
                &json!({"capacity":c,"allow_commands":allow_commands,"node_id":remote::node::fresh_id()?}),
            )?;
            // The owner may mean a capacity beyond what this process can use
            // (another cgroup runs the jobs, say): a warning, not an error.
            let warnings = host::warnings(Some(c as u64), &host::host());
            output(json!({"capacity":c,"warnings":warnings}))
        }
        Cmd::Node {
            command: Node::Commands { enable, disable: _ },
        } => {
            capacity(&root)?;
            let _guard = lock(&root.join("slots.lock"))?;
            let mut node = read(&root.join("node.json"))?;
            node["allow_commands"] = json!(enable);
            write_atomic_json(&root.join("node.json"), &node)?;
            output(node)
        }
        Cmd::Files { command } => output(match command {
            Files::Put {
                source,
                sha256,
                bytes,
            } => files::put(&root, &source, bytes, &sha256)?,
            Files::Get {
                sha256,
                bytes,
                destination,
            } => files::get(&root, &sha256, bytes, &destination)?,
            Files::Cleanup => files::cleanup(&root)?,
        }),
        Cmd::Node {
            command: Node::Doctor,
        } => {
            let host = host::host();
            let capacity = capacity(&root).ok();
            output(
                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)?}),
            )
        }
        Cmd::Node {
            command: Node::Capabilities,
        } => output(execution::capabilities(&root)?),
        Cmd::Workers {
            command: Workers::Add { id, executable },
        } => {
            if !safe_name(&id) {
                return Err("invalid worker id".into());
            }
            let executable = fs::canonicalize(executable)?;
            let registered_hash = digest(&fs::read(&executable)?);
            let (status, out, _) = bounded_command(
                &[executable.to_string_lossy().into_owned(), "describe".into()],
                vec![],
                Duration::from_secs(10),
                MAX_DESCRIPTION,
            )
            .map_err(|e| {
                if e.to_string().contains("exceeds configured cap") {
                    format!("the worker's describe output exceeds {MAX_DESCRIPTION} bytes").into()
                } else {
                    Error::from(e)
                }
            })?;
            let description: Value = serde_json::from_slice(&out)?;
            let generic = protocol_supported(&description["protocol"])
                && description["profiles"]
                    .as_array()
                    .is_some_and(|p| !p.is_empty() && p.iter().all(Value::is_string));
            let compatible = id == "native"
                && ["protocol", "problems", "optimizers", "parallelism"]
                    .iter()
                    .all(|k| description[*k] == discovery()[*k]);
            if !status.success()
                || (!generic && !compatible)
                || registered_hash != digest(&fs::read(&executable)?)
            {
                return Err("worker capability profile mismatch or executable changed".into());
            }
            let _g = lock(&root.join("registry.lock"))?;
            let mut w = optional(&root.join("workers.json"))?;
            w[&id] = json!({"executable":executable,"digest":digest(&fs::read(&executable)?),"description":description});
            write_atomic_json(&root.join("workers.json"), &w)?;
            output(w)
        }
        Cmd::Workers {
            command: Workers::List,
        } => output(optional(&root.join("workers.json"))?),
        Cmd::Problems {
            command: Problems::List,
        } => {
            if std::env::current_exe()?
                .file_stem()
                .is_some_and(|name| name == "fcmaes-run")
            {
                output(discovery())
            } else {
                output(
                    json!({"legacy":discovery(),"registered":optional(&root.join("workers.json"))?}),
                )
            }
        }
        Cmd::Problems {
            command: Problems::Describe { id },
        } => {
            let registry = optional(&root.join("workers.json"))?;
            if !registry[&id].is_null() {
                output(registry[&id]["description"].clone())
            } else {
                let d = discovery();
                output(
                    d["problems"]
                        .as_array()
                        .unwrap()
                        .iter()
                        .find(|p| p["id"] == id)
                        .ok_or("unknown worker/problem")?
                        .clone(),
                )
            }
        }
        Cmd::Validate { spec: p }
            if read(&p).map_err(invalid)?["schema_version"] == command::SCHEMA =>
        {
            output(command::check(&root, &p)?)
        }
        Cmd::Validate { spec: p } => match spec(&p).map_err(invalid)? {
            Request::Legacy(s) => output(
                json!({"valid":true,"requested_evaluations":s.requested()?,"maximum_actual_evaluations":s.maximum_evaluations()?,"resolved":s}),
            ),
            Request::Job(_) => {
                let (s, _, _, _, _) = staged(&root, &p)?;
                output(json!({"valid":true,"resolved":s}))
            }
        },
        Cmd::Run {
            spec: p,
            output: dest,
        } => {
            let (id, new) = prepare(&root, &p, dest, false)?;
            if new {
                launch(&root, &id)?;
            }
            output(get(&root, &id)?)
        }
        Cmd::Submit { spec: p } => {
            let (id, new) = prepare(&root, &p, None, true)?;
            if new {
                submit(&root, &id)?;
            }
            output(get(&root, &id)?)
        }
        Cmd::Launch { id } => launch(&root, &id),
        Cmd::Result { path } if path.is_dir() && is_command(&path)? => {
            output(command::result(&path)?)
        }
        Cmd::Result { path } => output(read(&if path.is_dir() {
            path.join("run.json")
        } else {
            path
        })?),
        Cmd::Compare { paths } => {
            for path in &paths {
                if path.is_dir() && is_command(path)? {
                    return Err(coded(
                        "unsupported_job_kind",
                        "compare accepts optimization results; command results have no mathematical claims",
                    ));
                }
            }
            let runs = paths
                .iter()
                .map(|p| {
                    read(&if p.is_dir() {
                        p.join("run.json")
                    } else {
                        p.clone()
                    })
                })
                .collect::<Result<Vec<_>>>()?;
            output(result::compare(&runs)?)
        }
        Cmd::Jobs { command } => match command {
            Jobs::Collect {
                id,
                name,
                destination,
            } => output(command::collect(
                &directory(&root, &id)?,
                &name,
                &destination,
            )?),
            Jobs::Events { id } => {
                let dir = directory(&root, &id)?;
                output(json!(read_checked::<Value>(&dir.join("events.jsonl"), 1)?))
            }
            Jobs::List => {
                let requests = optional(&root.join("requests.json"))?;
                let mut jobs = vec![];
                for id in requests.as_object().ok_or("bad requests")?.keys() {
                    jobs.push(
                        get(&root, id).unwrap_or_else(|e| json!({"id":id,"error":e.to_string()})),
                    );
                }
                output(json!(jobs))
            }
            Jobs::Get { id } => output(get(&root, &id)?),
            Jobs::Execution { id } => output(execution::record(&directory(&root, &id)?)?),
            Jobs::Wait { id, timeout } => {
                if !timeout.is_finite() || timeout <= 0.0 {
                    return Err("positive finite timeout required".into());
                }
                let t = Instant::now();
                loop {
                    let v = get(&root, &id)?;
                    if matches!(
                        v["state"].as_str(),
                        Some("completed" | "failed" | "cancelled" | "timed_out" | "interrupted")
                    ) || !v["observed_state"].is_null()
                        || t.elapsed().as_secs_f64() >= timeout
                    {
                        return output(v);
                    }
                    thread::sleep(Duration::from_millis(250));
                }
            }
            Jobs::Cancel { id, now: immediate } => {
                let dir = directory(&root, &id)?;
                // Like a 409: a finished job has nothing to stop, and a late
                // request must not look as if it had stopped anything.
                let state = read(&dir.join("job.json"))?["state"].clone();
                if terminal(&state) {
                    return Err(coded(
                        "already_terminal",
                        format!(
                            "job {id} already ended as {}; nothing to cancel",
                            state.as_str().unwrap_or_default()
                        ),
                    ));
                }
                // Never downgrade: an immediate request stays immediate, also
                // when a graceful one races it (publish_stop serializes them).
                let mode = if immediate { "immediate" } else { "graceful" };
                publish_stop(&dir, json!({"mode":mode,"requested_at":now()}))?;
                output(get(&root, &id)?)
            }
            Jobs::Reconcile => {
                let _g = lock(&root.join("slots.lock"))?;
                let mut l = optional(&root.join("slots.json"))?;
                reconcile_ledger(&root, &mut l)?;
                write_atomic_json(&root.join("slots.json"), &l)?;
                output(l)
            }
            Jobs::Repair { id } => output(repair(&root, &id)?),
            Jobs::Progress { id, offset, limit } => {
                if !(1..=10000).contains(&limit) {
                    return Err(coded("invalid_command", "limit must be 1..10000"));
                }
                let dir = directory(&root, &id)?;
                if !is_command(&dir)? {
                    return Err(coded(
                        "unsupported_job_kind",
                        "progress files belong to command jobs; use jobs artifact for optimization jobs",
                    ));
                }
                output(command::progress(&dir, &id, offset, limit)?)
            }
            Jobs::Artifact {
                id,
                name,
                offset,
                limit,
            } => {
                let dir = directory(&root, &id)?;
                if is_command(&dir)? {
                    return Err(coded(
                        "unsupported_job_kind",
                        "use jobs collect for binary command outputs",
                    ));
                }
                let unknown = |why: &[String]| {
                    coded(
                        "unknown_artifact",
                        format!(
                            "job {id} has no artifact {name:?}{}",
                            if why.is_empty() {
                                String::new()
                            } else {
                                format!(" ({})", why.join("; "))
                            }
                        ),
                    )
                };
                // A sealed attempt serves what its manifest lists, checked
                // against the recorded digest; a running one its declarations.
                let sealed = dir.join("run.json").exists();
                let (file, format, sha256) = if sealed {
                    let run = read(&dir.join("run.json"))?;
                    let file = run["artifacts"][&name]
                        .as_str()
                        .ok_or_else(|| unknown(&[]))?;
                    let index = &run["runner"]["artifact_index"][&name];
                    // Manifests before artifact indexes list `results` only.
                    let format = index["format"]
                        .as_str()
                        .unwrap_or(if name == artifact::RESULTS {
                            "records"
                        } else {
                            "file"
                        });
                    (
                        file.to_string(),
                        format.to_string(),
                        index["sha256"].as_str().map(String::from),
                    )
                } else {
                    let (list, errors) = artifact::all_or_results(&dir);
                    let d = list
                        .into_iter()
                        .find(|d| d.name == name)
                        .ok_or_else(|| unknown(&errors))?;
                    (d.file, d.format, None)
                };
                let path = match fs::canonicalize(dir.join(&file)) {
                    Ok(path) => path,
                    Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
                        return Err(coded(
                            "unknown_artifact",
                            format!("artifact {name:?} of job {id} has no file yet"),
                        ));
                    }
                    Err(e) => return Err(e.into()),
                };
                if !path.starts_with(fs::canonicalize(&dir)?) || !path.is_file() {
                    return Err("artifact escapes job directory or is no file".into());
                }
                // A whole read checks the whole file, a torn final record
                // included (it was sealed too); pages check their records.
                let paged = offset.is_some() || limit.is_some();
                if let Some(sealed) = sha256
                    && !paged
                    && artifact::digest_file(&path)?.1 != sealed
                {
                    return Err(format!(
                        "artifact {name:?} changed after the job ended: its SHA-256 differs from the manifest"
                    )
                    .into());
                }
                let mut value = if paged {
                    if format != "records" {
                        return Err(coded(
                            "invalid_command",
                            format!(
                                "artifact {name:?} has format {format}; only records artifacts have pages"
                            ),
                        ));
                    }
                    artifact::page(&path, offset.unwrap_or(0), limit.unwrap_or(100))?
                } else {
                    artifact::content(&path, &format)?
                };
                value["name"] = json!(name);
                value["file"] = json!(file);
                value["final"] = json!(sealed);
                output(value)
            }
        },
    }
}
/// The `optimization-run` binary. An error is printed as
/// `{"error":{"code","message","retryable"}}` on standard error, with exit
/// status 2.
pub fn main() {
    if !cfg!(target_os = "linux") {
        eprintln!("Linux is required for process supervision");
        std::process::exit(2);
    }
    if let Err(e) = main_result() {
        let code = error_code(&e);
        eprintln!(
            "{}",
            json!({"error":{"code":code,"message":e.to_string(),"retryable":retryable(code)}})
        );
        std::process::exit(2);
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn stop_requests_only_escalate() {
        let dir = tempfile::tempdir().unwrap();
        let marker = |dir: &Path| read(&dir.join("cancel.request")).unwrap();
        let timeout = json!({"mode":"graceful","reason":"timed_out"});
        let graceful = json!({"mode":"graceful"});
        let immediate = json!({"mode":"immediate"});
        assert!(publish_stop(dir.path(), timeout.clone()).unwrap());
        assert!(!publish_stop(dir.path(), timeout.clone()).unwrap());
        // A cancellation replaces the launcher's timeout marker ...
        assert!(publish_stop(dir.path(), graceful.clone()).unwrap());
        assert!(!publish_stop(dir.path(), timeout).unwrap());
        assert!(publish_stop(dir.path(), immediate.clone()).unwrap());
        // ... and nothing replaces an immediate one.
        assert!(!publish_stop(dir.path(), graceful).unwrap());
        assert_eq!(marker(dir.path()), immediate);
        // An unreadable marker counts as the strongest request.
        fs::write(dir.path().join("cancel.request"), b"{").unwrap();
        assert!(!publish_stop(dir.path(), immediate).unwrap());
    }
}