zc2 0.0.51

P2P compute broker with yen-denominated billing, WAL, and broker mesh support
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
//! Runs the whole suite once: measure, score, sign, persist, submit.
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{mpsc, Arc};
use std::time::{Duration, Instant};

use super::budget::Budget;
use super::fingerprint::{GpuId, HardwareFingerprint};
use super::gpu::{self, GpuOutcome};
use super::report::{sign, BenchReport, SignedReport};
use super::schedule::LastRun;
use super::submit::SubmitError;
use super::{cpu, disk, net, score, SUITE};
use crate::broker::node_identity::NodeKey;

/// Share of the total budget each probe may use.
const CPU_SHARE: f64 = 0.45;
const GPU_SHARE: f64 = 0.35;
const DISK_SHARE: f64 = 0.10;
const NET_SHARE: f64 = 0.10;
/// The GPU probe's CUDA calls cannot be interrupted, so it gets this much on
/// top of its slice before the runner gives up on it.
/// The watchdog never fires sooner than this after the start.
// Tests run many debug-build probes in parallel; a tight floor makes them flaky.
const WATCHDOG_FLOOR: Duration = Duration::from_secs(if cfg!(test) { 120 } else { 5 });
const GPU_GRACE: Duration = Duration::from_secs(10);

/// Where a saved report stands with the hub.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum SubmitState {
    /// Measured, not delivered: a running broker sends it.
    Pending,
    Done,
    /// The hub refused the report with this 4xx status. Not sent again; the
    /// scheduler re-measures later (see `schedule::decide`).
    Rejected(u16),
    /// The owner said no (CLI prompt, `--json`, non-TTY). Never sent
    /// automatically, and it still counts as measured for this hardware.
    Declined,
}

pub struct RunOpts {
    /// What `last.json` says before the submit hook has run.
    pub save_as: SubmitState,
    pub budget: Duration,
    pub no_gpu: bool,
    /// The zc state dir (`~/.zakuro`); `bench/` under it holds scratch + last.json.
    pub state_dir: PathBuf,
    pub hub_url: Option<String>,
    pub peers: Vec<String>,
}

/// Delivers a signed report to the hub.
pub type SubmitHook<'a> = &'a mut dyn FnMut(&SignedReport) -> Result<(), SubmitError>;

pub struct RunCtx<'a> {
    pub key: &'a NodeKey,
    pub cancel: Arc<AtomicBool>,
    /// One call per probe, as it starts.
    pub progress: &'a dyn Fn(&str),
    /// Sends the signed report to the hub; never called for a cancelled run.
    /// `None` measures and saves only (the CLI asks before it submits).
    pub submit: Option<SubmitHook<'a>>,
}

#[derive(Debug)]
pub enum RunOutcome {
    /// Cancelled (a request arrived, or the 2x watchdog fired): nothing saved or sent.
    Cancelled,
    /// Another benchmark (the CLI or the broker's scheduler) holds `bench/run.lock`.
    AlreadyRunning,
    Completed {
        signed: SignedReport,
        report: Box<BenchReport>,
        /// `None` when the submit hook accepted it.
        submit_error: Option<SubmitError>,
    },
}

fn bench_dir(state_dir: &Path) -> PathBuf {
    state_dir.join("bench")
}

fn last_path(state_dir: &Path) -> PathBuf {
    bench_dir(state_dir).join("last.json")
}

/// `bench/last.json`: the signed form plus whether the hub has it.
pub fn save_last(state_dir: &Path, s: &SignedReport, state: SubmitState) -> std::io::Result<()> {
    std::fs::create_dir_all(bench_dir(state_dir))?;
    let body = serde_json::json!({
        "report_json": s.report_json,
        "signature": s.signature,
        "submitted": state == SubmitState::Done,
        "declined": state == SubmitState::Declined,
        "rejected": match state { SubmitState::Rejected(c) => Some(c), _ => None },
        "rejected_at": match state { SubmitState::Rejected(_) => Some(crate::broker::node_identity::now_secs()), _ => None },
    });
    let tmp = bench_dir(state_dir).join("last.json.tmp");
    std::fs::write(&tmp, body.to_string())?;
    std::fs::rename(tmp, last_path(state_dir))
}

pub fn load_last(state_dir: &Path) -> Option<(SignedReport, SubmitState)> {
    let v: serde_json::Value =
        serde_json::from_slice(&std::fs::read(last_path(state_dir)).ok()?).ok()?;
    Some((
        SignedReport {
            report_json: v.get("report_json")?.as_str()?.to_string(),
            signature: v.get("signature")?.as_str()?.to_string(),
        },
        match (
            v.get("submitted").and_then(|b| b.as_bool()) == Some(true),
            v.get("declined").and_then(|b| b.as_bool()) == Some(true),
            v.get("rejected").and_then(|c| c.as_u64()),
        ) {
            (true, _, _) => SubmitState::Done,
            (_, true, _) => SubmitState::Declined,
            (_, _, Some(c)) => SubmitState::Rejected(c as u16),
            _ => SubmitState::Pending,
        },
    ))
}

/// The report a broker should still deliver: saved as pending, and not one
/// the hub already refused. Declined and delivered reports are never returned.
pub fn pending_submission(state_dir: &Path, rejected: Option<&str>) -> Option<SignedReport> {
    match load_last(state_dir)? {
        (s, SubmitState::Pending) if rejected != Some(s.signature.as_str()) => Some(s),
        _ => None,
    }
}
/// What the scheduler compares against the current hardware.
pub fn last_run(state_dir: &Path) -> Option<LastRun> {
    let (s, state) = load_last(state_dir)?;
    let rejected = match state {
        SubmitState::Rejected(code) => {
            let at = std::fs::read(last_path(state_dir))
                .ok()
                .and_then(|b| serde_json::from_slice::<serde_json::Value>(&b).ok())
                .and_then(|v| v.get("rejected_at")?.as_u64())
                .unwrap_or(0);
            let since = crate::broker::node_identity::now_secs().saturating_sub(at);
            Some((code, Duration::from_secs(since)))
        }
        _ => None,
    };
    let r: serde_json::Value = serde_json::from_str(&s.report_json).ok()?;
    let age = chrono::DateTime::parse_from_rfc3339(r.get("measured_at")?.as_str()?)
        .ok()
        .and_then(|t| {
            (chrono::Utc::now() - t.with_timezone(&chrono::Utc))
                .to_std()
                .ok()
        })
        .unwrap_or(Duration::ZERO);
    Some(LastRun {
        age,
        suite: r.get("suite")?.as_str()?.to_string(),
        fingerprint_sha256: r.get("fingerprint_sha256")?.as_str()?.to_string(),
        submitted: state == SubmitState::Done,
        partial: r.get("partial").and_then(|p| p.as_bool()) == Some(true),
        rejected,
        busy_streak: load_busy_streak(state_dir),
    })
}

fn busy_streak_path(state_dir: &Path) -> PathBuf {
    bench_dir(state_dir).join("busy_streak")
}

/// Consecutive partial-because-busy runs recorded by the last completed run.
pub fn load_busy_streak(state_dir: &Path) -> u32 {
    std::fs::read_to_string(busy_streak_path(state_dir))
        .ok()
        .and_then(|s| s.trim().parse().ok())
        .unwrap_or(0)
}

/// The streak after a run: one more if it was partial with a busy GPU among
/// the reasons, otherwise back to zero (a complete run resets it).
fn next_busy_streak(prev: u32, partial: bool, skipped: &[String]) -> u32 {
    if partial && skipped.iter().any(|s| gpu::cuda::is_busy_note(s)) {
        prev.saturating_add(1)
    } else {
        0
    }
}

/// A stage budget: `share` of the total, never more than what the run has left.
fn stage(total: Duration, share: f64, overall: &Budget, cancel: &Arc<AtomicBool>) -> Budget {
    Budget::new(
        total.mul_f64(share).min(overall.remaining()),
        cancel.clone(),
    )
}

/// Runs `gpu::probe` on its own thread; gives up after `b`'s time + `GPU_GRACE`,
/// or as soon as the run is cancelled.
fn gpu_with_timeout(b: &Budget, cancel: &AtomicBool) -> GpuOutcome {
    let (tx, rx) = mpsc::channel();
    let bb = b.clone();
    std::thread::spawn(move || {
        let _ = tx.send(gpu::probe(&bb));
    });
    let give_up = Instant::now() + b.remaining() + GPU_GRACE;
    loop {
        match rx.recv_timeout(Duration::from_millis(100)) {
            Ok(o) => return o,
            Err(mpsc::RecvTimeoutError::Disconnected) => {
                return GpuOutcome {
                    gpus: vec![],
                    skipped: Some("gpu: probe thread died".into()),
                }
            }
            Err(mpsc::RecvTimeoutError::Timeout) => {
                if cancel.load(Ordering::SeqCst) || Instant::now() >= give_up {
                    return GpuOutcome {
                        gpus: vec![],
                        skipped: Some("gpu: probe timed out".into()),
                    };
                }
            }
        }
    }
}

/// Runs GPU enumeration on at most ONE thread at a time. A hung CUDA call
/// cannot be interrupted, so every timed-out enumerate used to leak a thread
/// (one per scheduler retry). While one is still hung, callers get the last
/// good result straight away instead of another thread.
pub(super) struct Prober {
    busy: Arc<AtomicBool>,
    cache: Arc<std::sync::Mutex<Option<Vec<GpuId>>>>,
}

impl Prober {
    pub(super) fn new() -> Self {
        Prober {
            busy: Arc::new(AtomicBool::new(false)),
            cache: Arc::new(std::sync::Mutex::new(None)),
        }
    }

    fn cached(&self) -> Option<Vec<GpuId>> {
        self.cache.lock().ok().and_then(|c| c.clone())
    }

    /// The probe's result within `grace`; `None` if it timed out (or the run
    /// was cancelled). If an earlier probe is still hung, the previous result
    /// (or `None` if there never was one) without spawning anything.
    pub(super) fn enumerate(
        &self,
        probe: impl FnOnce() -> Vec<GpuId> + Send + 'static,
        cancel: &AtomicBool,
        grace: Duration,
    ) -> Option<Vec<GpuId>> {
        if self.busy.swap(true, Ordering::SeqCst) {
            return self.cached();
        }
        let (tx, rx) = mpsc::channel();
        let (busy, cache) = (self.busy.clone(), self.cache.clone());
        std::thread::spawn(move || {
            // Clears `busy` even if the probe panics, so enumeration is not
            // dead for the rest of the process.
            struct Clear(Arc<AtomicBool>);
            impl Drop for Clear {
                fn drop(&mut self) {
                    self.0.store(false, Ordering::SeqCst);
                }
            }
            let clear = Clear(busy);
            let ids = probe();
            if let Ok(mut c) = cache.lock() {
                *c = Some(ids.clone());
            }
            // Idle BEFORE the send, not when the thread exits: a caller woken
            // by the send could otherwise probe again, find `busy` still set
            // and get the cached result instead of a fresh probe.
            drop(clear);
            let _ = tx.send(ids);
        });
        let give_up = Instant::now() + grace;
        loop {
            match rx.recv_timeout(Duration::from_millis(100).min(grace)) {
                Ok(ids) => return Some(ids),
                Err(mpsc::RecvTimeoutError::Timeout)
                    if !cancel.load(Ordering::SeqCst) && Instant::now() < give_up => {}
                Err(_) => return None,
            }
        }
    }
}

/// `gpu::enumerate` calls into the driver, which cannot be interrupted: bound it.
pub(crate) fn enumerate_with_timeout(cancel: &AtomicBool) -> Option<Vec<GpuId>> {
    static PROBER: std::sync::OnceLock<Prober> = std::sync::OnceLock::new();
    PROBER
        .get_or_init(Prober::new)
        .enumerate(gpu::enumerate, cancel, GPU_GRACE)
}

/// The GPUs to fingerprint: what enumeration found, or, when it timed out,
/// what the previous run saw (an empty list would flip the fingerprint).
fn fingerprint_gpus(enumerated: Option<Vec<GpuId>>, previous: Option<Vec<GpuId>>) -> Vec<GpuId> {
    enumerated.or(previous).unwrap_or_default()
}

/// A lock file holding its owner's pid. Used where there is no `flock`: a
/// lock whose pid is no longer alive (the owner crashed) is taken over.
#[cfg(any(not(unix), test))]
struct PidLock {
    path: PathBuf,
}

/// A lock file with no readable pid is a crash between create and write, or
/// junk: stale once it is this old.
#[cfg(any(not(unix), test))]
const UNREADABLE_LOCK_STALE_AFTER: Duration = Duration::from_secs(60);

/// Whether the lock file's `contents` (a pid, written by its owner) and `age`
/// say nobody holds it any more.
#[cfg(any(not(unix), test))]
fn lock_is_stale(contents: &str, age: Duration, alive: impl Fn(u32) -> bool) -> bool {
    match contents.trim().parse::<u32>() {
        Ok(pid) => !alive(pid),
        Err(_) => age >= UNREADABLE_LOCK_STALE_AFTER,
    }
}

#[cfg(any(not(unix), test))]
impl PidLock {
    /// `None` when a live process holds `path` (or it cannot be created).
    /// A stale file is renamed away before the retry, so only one of several
    /// racing takers can retire it, and the exclusive create picks one winner.
    /// (Between reading the pid and the rename a new owner could in theory
    /// replace the file; that window is microseconds and needs a crash first.)
    fn acquire(path: &Path, alive: impl Fn(u32) -> bool) -> Option<PidLock> {
        use std::io::Write;
        for _ in 0..2 {
            match std::fs::OpenOptions::new()
                .write(true)
                .create_new(true)
                .open(path)
            {
                Ok(mut f) => {
                    let _ = write!(f, "{}", std::process::id());
                    return Some(PidLock { path: path.into() });
                }
                Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
                    let contents = std::fs::read_to_string(path).unwrap_or_default();
                    let age = std::fs::metadata(path)
                        .and_then(|m| m.modified())
                        .ok()
                        .and_then(|t| t.elapsed().ok())
                        .unwrap_or_default();
                    if !lock_is_stale(&contents, age, &alive) {
                        return None;
                    }
                    // Rename to a name only we know, and take over only if
                    // that worked: of two racing takers just one rename of the
                    // stale file succeeds, and neither can delete the other's
                    // freshly created lock.
                    let grave = path.with_extension(format!("stale-{}", std::process::id()));
                    if std::fs::rename(path, &grave).is_err() {
                        continue;
                    }
                    let _ = std::fs::remove_file(&grave);
                }
                Err(_) => return None,
            }
        }
        None
    }
}

#[cfg(any(not(unix), test))]
impl Drop for PidLock {
    fn drop(&mut self) {
        let _ = std::fs::remove_file(&self.path);
    }
}

/// Is a process with this pid running?
#[cfg(any(not(unix), test))]
fn pid_alive(pid: u32) -> bool {
    #[cfg(unix)]
    {
        // SAFETY: signal 0 only checks that the process exists.
        let rc = unsafe { libc::kill(pid as libc::pid_t, 0) };
        rc == 0 || std::io::Error::last_os_error().raw_os_error() == Some(libc::EPERM)
    }
    #[cfg(windows)]
    {
        std::process::Command::new("tasklist")
            .args(["/FI", &format!("PID eq {pid}"), "/NH"])
            .output()
            .map(|o| String::from_utf8_lossy(&o.stdout).contains(&pid.to_string()))
            .unwrap_or(true)
    }
    #[cfg(not(any(unix, windows)))]
    {
        let _ = pid;
        true
    }
}

/// Holds `bench/run.lock` for the life of a run. On unix an advisory `flock`,
/// which the OS drops if the process dies; elsewhere a pid file that a later
/// run takes over once its pid is dead.
pub struct RunLock {
    #[cfg(unix)]
    _file: std::fs::File,
    #[cfg(not(unix))]
    _lock: PidLock,
}

#[cfg(unix)]
impl Drop for RunLock {
    fn drop(&mut self) {
        use std::os::unix::io::AsRawFd;
        // Release now, even if a forked child still shares the descriptor.
        // SAFETY: unlock on a descriptor this struct owns.
        unsafe { libc::flock(self._file.as_raw_fd(), libc::LOCK_UN) };
    }
}

impl RunLock {
    /// `None` when another run holds the lock (or the lock cannot be created).
    pub fn acquire(dir: &Path) -> Option<RunLock> {
        std::fs::create_dir_all(dir).ok()?;
        let path = dir.join("run.lock");
        #[cfg(unix)]
        {
            use std::os::unix::io::AsRawFd;
            let file = std::fs::OpenOptions::new()
                .create(true)
                .truncate(false)
                .write(true)
                .open(&path)
                .ok()?;
            // SAFETY: flock on a descriptor this function owns.
            let rc = unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) };
            (rc == 0).then_some(RunLock { _file: file })
        }
        #[cfg(not(unix))]
        {
            PidLock::acquire(&path, pid_alive).map(|_lock| RunLock { _lock })
        }
    }
}

/// True when a GPU the machine has was not fully measured: enumeration timed
/// out (`None`), a listed GPU is missing from the measurements, or a measured
/// one lacks fp32, fp16 or copy bandwidth. `--no-gpu` and
/// `ZAKURO_BENCH_GPU=0` skip on purpose and are not partial.
fn gpu_partial(
    no_gpu: bool,
    enumerated: Option<&[GpuId]>,
    measured: &[super::report::GpuMetrics],
) -> bool {
    if no_gpu {
        return false;
    }
    let Some(ids) = enumerated else { return true };
    ids.iter()
        .any(|id| !measured.iter().any(|m| m.uuid == id.uuid))
        || measured
            .iter()
            .any(|m| !(m.tflops_f32 > 0.0 && m.tflops_f16 > 0.0 && m.mem_bw_gbps > 0.0))
}

pub fn run(opts: &RunOpts, ctx: &mut RunCtx) -> RunOutcome {
    // One benchmark per state dir at a time: two would measure each other.
    let Some(_lock) = RunLock::acquire(&bench_dir(&opts.state_dir)) else {
        return RunOutcome::AlreadyRunning;
    };
    // A killed run leaves its scratch file behind; clear the old ones.
    disk::sweep_stale_scratch(
        &bench_dir(&opts.state_dir),
        std::time::SystemTime::now(),
        disk::STALE_SCRATCH_AFTER,
    );
    let started = Instant::now();
    let cancel = ctx.cancel.clone();
    let overall = Budget::new(opts.budget, cancel.clone());

    // Backstop for anything the budget cannot interrupt.
    let done = Arc::new(AtomicBool::new(false));
    {
        let (done, cancel) = (done.clone(), cancel.clone());
        // Each probe runs at least one round whatever its slice, so a tiny
        // budget still needs a few seconds of real time.
        let limit = Instant::now() + (opts.budget * 2).max(WATCHDOG_FLOOR);
        std::thread::spawn(move || {
            while !done.load(Ordering::SeqCst) {
                if Instant::now() >= limit {
                    cancel.store(true, Ordering::SeqCst);
                    return;
                }
                std::thread::sleep(Duration::from_millis(50));
            }
        });
    }
    let outcome = measure_and_send(opts, ctx, &overall, started);
    done.store(true, Ordering::SeqCst);
    outcome
}

fn measure_and_send(
    opts: &RunOpts,
    ctx: &mut RunCtx,
    overall: &Budget,
    started: Instant,
) -> RunOutcome {
    let cancel = &ctx.cancel;
    let mut skipped: Vec<String> = vec![];
    let mut partial = false;

    (ctx.progress)("cpu + memory");
    let cpu = match cpu::probe(&stage(opts.budget, CPU_SHARE, overall, cancel)) {
        Ok(p) => {
            // A panicked worker or a memory test that could not run: the
            // figures are lower bounds, so say so.
            partial |= !p.notes.is_empty();
            skipped.extend(p.notes);
            Some(p.metrics)
        }
        Err(e) => {
            partial = true;
            skipped.push(format!("cpu: {e}"));
            None
        }
    };
    if cancel.load(Ordering::SeqCst) {
        return RunOutcome::Cancelled;
    }

    (ctx.progress)("gpu");
    let gpu_out = if opts.no_gpu {
        GpuOutcome {
            gpus: vec![],
            skipped: Some("gpu: disabled by --no-gpu".into()),
        }
    } else {
        gpu_with_timeout(&stage(opts.budget, GPU_SHARE, overall, cancel), cancel)
    };
    skipped.extend(gpu_out.skipped.clone());
    if cancel.load(Ordering::SeqCst) {
        return RunOutcome::Cancelled;
    }

    (ctx.progress)("disk");
    let disk = match std::fs::create_dir_all(bench_dir(&opts.state_dir))
        .map_err(|e| e.to_string())
        .and_then(|_| {
            disk::probe(
                &bench_dir(&opts.state_dir),
                &stage(opts.budget, DISK_SHARE, overall, cancel),
            )
        }) {
        Ok(m) => Some(m),
        Err(e) => {
            partial = true;
            skipped.push(format!("disk: {e}"));
            None
        }
    };
    if cancel.load(Ordering::SeqCst) {
        return RunOutcome::Cancelled;
    }

    (ctx.progress)("network");
    let net = net::probe(
        opts.hub_url.as_deref(),
        &opts.peers,
        &stage(opts.budget, NET_SHARE, overall, cancel),
    );
    if net.hub_rtt_ms.is_none() && opts.hub_url.is_some() {
        skipped.push("net: hub unreachable".into());
    }
    if cancel.load(Ordering::SeqCst) {
        return RunOutcome::Cancelled;
    }

    // The fingerprint names the hardware present, from the same source the
    // idle scheduler compares against (`gpu::enumerate`), not what the probe
    // managed to time: a timed-out, failed or disabled GPU probe must not make
    // this machine look like different hardware.
    let enumerated = enumerate_with_timeout(cancel);
    partial |= gpu_partial(opts.no_gpu, enumerated.as_deref(), &gpu_out.gpus);
    let fingerprint = HardwareFingerprint::detect(fingerprint_gpus(
        enumerated,
        load_last(&opts.state_dir)
            .and_then(|(s, _)| serde_json::from_str::<BenchReport>(&s.report_json).ok())
            .map(|r| r.fingerprint.gpus),
    ));
    // Informational only: a busy host does not make the run partial.
    skipped.extend(super::fingerprint::busy_host_note(
        super::fingerprint::load_average_1m(),
        fingerprint.logical_cores,
    ));
    let cpu_units = cpu.as_ref().map(score::cpu_units).unwrap_or(0.0);
    let gpu_units = score::gpu_units(&gpu_out.gpus);
    let build = crate::build_id::current();
    let report = BenchReport {
        suite: SUITE.into(),
        zc_version: build.version.clone(),
        zc_git: build.git.clone(),
        node_pubkey: ctx.key.public_b64(),
        fingerprint_sha256: fingerprint.sha256(),
        fingerprint,
        measured_at: chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
        duration_ms: started.elapsed().as_millis() as u64,
        partial: partial || overall.expired(),
        cpu,
        disk,
        net: Some(net),
        gpus: gpu_out.gpus,
        skipped,
        cpu_units,
        gpu_units,
        numa_mem: super::fingerprint::numa_memory(),
    };
    let signed = sign(&report, ctx.key);
    // Only the scheduler's automatic runs (saved as Pending) drive the
    // back-off; a manual `zc bench node` neither extends nor resets it.
    if opts.save_as == SubmitState::Pending {
        let streak = next_busy_streak(
            load_busy_streak(&opts.state_dir),
            report.partial,
            &report.skipped,
        );
        if let Err(e) = std::fs::write(busy_streak_path(&opts.state_dir), streak.to_string()) {
            eprintln!("  [BENCH] could not save busy_streak: {e}");
        }
    }
    // Persist first: a failed submit is retried from this file, not re-measured.
    if let Err(e) = save_last(&opts.state_dir, &signed, opts.save_as) {
        eprintln!("  [BENCH] could not save last.json: {e}");
    }
    let submit_error = match ctx.submit.as_mut().map(|submit| submit(&signed)) {
        Some(Ok(())) => {
            let _ = save_last(&opts.state_dir, &signed, SubmitState::Done);
            None
        }
        Some(Err(e)) => Some(e),
        None => None,
    };
    RunOutcome::Completed {
        signed,
        report: Box::new(report),
        submit_error,
    }
}

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

    fn opts(dir: &Path, budget: Duration) -> RunOpts {
        RunOpts {
            save_as: SubmitState::Pending,
            budget,
            no_gpu: true,
            state_dir: dir.to_path_buf(),
            hub_url: None,
            peers: vec![],
        }
    }

    fn tmp(name: &str) -> PathBuf {
        let d = std::env::temp_dir().join(format!("zc-bench-run-{name}-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&d);
        std::fs::create_dir_all(&d).unwrap();
        d
    }

    #[test]
    fn cancelled_run_is_not_submitted() {
        let dir = tmp("cancel");
        let key = NodeKey::generate();
        let cancel = Arc::new(AtomicBool::new(false));
        let c2 = cancel.clone();
        std::thread::spawn(move || {
            std::thread::sleep(Duration::from_millis(200));
            c2.store(true, Ordering::SeqCst);
        });
        let mut calls = 0;
        let mut submit = |_: &SignedReport| {
            calls += 1;
            Ok(())
        };
        // The first progress call stalls past the 200 ms mark, so the cancel
        // lands before the CPU probe starts, whatever the machine's speed.
        let progress = |_: &str| std::thread::sleep(Duration::from_millis(400));
        let out = run(
            &opts(&dir, Duration::from_secs(60)),
            &mut RunCtx {
                key: &key,
                cancel,
                progress: &progress,
                submit: Some(&mut submit),
            },
        );
        assert!(matches!(out, RunOutcome::Cancelled));
        assert_eq!(calls, 0);
        assert!(!dir.join("bench/last.json").exists());
    }

    #[test]
    fn a_completed_run_saves_last_json_before_submitting() {
        let dir = tmp("save");
        let key = NodeKey::generate();
        let mut seen_file = None;
        let d2 = dir.clone();
        let mut submit = |s: &SignedReport| {
            let (saved, state) = load_last(&d2).expect("last.json exists at submit time");
            seen_file = Some((saved == *s, state));
            Ok(())
        };
        let out = run(
            &opts(&dir, Duration::from_secs(5)),
            &mut RunCtx {
                key: &key,
                cancel: Arc::new(AtomicBool::new(false)),
                progress: &|_| {},
                submit: Some(&mut submit),
            },
        );
        assert!(matches!(
            out,
            RunOutcome::Completed {
                submit_error: None,
                ..
            }
        ));
        assert_eq!(seen_file, Some((true, SubmitState::Pending)));
        // An accepted submit flips the flag.
        assert_eq!(load_last(&dir).unwrap().1, SubmitState::Done);
        assert_eq!(last_run(&dir).unwrap().suite, SUITE);
    }

    #[test]
    fn a_failed_submit_leaves_last_json_unsubmitted() {
        let dir = tmp("retry");
        let key = NodeKey::generate();
        let mut submit = |_: &SignedReport| Err(SubmitError::Retryable("down".into()));
        let out = run(
            &opts(&dir, Duration::from_secs(5)),
            &mut RunCtx {
                key: &key,
                cancel: Arc::new(AtomicBool::new(false)),
                progress: &|_| {},
                submit: Some(&mut submit),
            },
        );
        assert!(matches!(
            out,
            RunOutcome::Completed {
                submit_error: Some(SubmitError::Retryable(_)),
                ..
            }
        ));
        assert_eq!(load_last(&dir).unwrap().1, SubmitState::Pending);
    }

    #[test]
    fn report_fills_skipped_reasons_and_partial() {
        let dir = tmp("partial");
        let key = NodeKey::generate();
        let mut submit = |_: &SignedReport| Ok(());
        let out = run(
            &opts(&dir, Duration::ZERO),
            &mut RunCtx {
                key: &key,
                cancel: Arc::new(AtomicBool::new(false)),
                progress: &|_| {},
                submit: Some(&mut submit),
            },
        );
        let RunOutcome::Completed { report, .. } = out else {
            panic!("expected a completed run")
        };
        assert!(report.partial);
        assert!(report.skipped.iter().any(|s| s.starts_with("gpu:")));
    }

    #[test]
    fn a_run_with_the_gpu_probe_off_is_rerun_only_if_it_was_partial() {
        use crate::bench_node::schedule::{decide, Decision, IDLE_BEFORE_RUN};
        let dir = tmp("norerun");
        let key = NodeKey::generate();
        // `no_gpu` stands in for any GPU probe that timed out or failed.
        run(
            &opts(&dir, Duration::from_secs(5)),
            &mut RunCtx {
                key: &key,
                cancel: Arc::new(AtomicBool::new(false)),
                progress: &|_| {},
                submit: None,
            },
        );
        let last = last_run(&dir).unwrap();
        let current = HardwareFingerprint::detect(gpu::enumerate()).sha256();
        assert_eq!(last.fingerprint_sha256, current);
        // `--no-gpu` is on purpose, not partial; the 5 s budget may still
        // have cut the disk probe short, and then the 6 h re-run rule applies.
        for tick in 1..=5u64 {
            let idle = IDLE_BEFORE_RUN * tick as u32 * 2;
            let d = decide(Some(&last), &current, SUITE, idle, 0, true);
            if last.partial {
                assert!(matches!(d, Decision::Wait(_)), "tick {tick}: {d:?}");
            } else {
                assert_eq!(d, Decision::Never, "tick {tick}");
            }
        }
    }

    #[test]
    fn declined_and_delivered_reports_are_never_pending() {
        let dir = tmp("declined");
        let s = SignedReport {
            report_json: "{}".into(),
            signature: "sig".into(),
        };
        save_last(&dir, &s, SubmitState::Declined).unwrap();
        assert_eq!(pending_submission(&dir, None), None);
        assert_eq!(load_last(&dir).unwrap().1, SubmitState::Declined);
        save_last(&dir, &s, SubmitState::Done).unwrap();
        assert_eq!(pending_submission(&dir, None), None);
        save_last(&dir, &s, SubmitState::Pending).unwrap();
        assert_eq!(pending_submission(&dir, None), Some(s.clone()));
        assert_eq!(
            pending_submission(&dir, Some("sig")),
            None,
            "refused by the hub"
        );
    }

    #[test]
    fn an_enumerate_timeout_keeps_the_previous_runs_gpus() {
        let gpu = |u: &str| GpuId {
            vendor: "nvidia".into(),
            model: "m".into(),
            uuid: u.into(),
            vram_bytes: 1,
        };
        let prev = Some(vec![gpu("a")]);
        assert_eq!(fingerprint_gpus(None, prev.clone()), vec![gpu("a")]);
        assert_eq!(fingerprint_gpus(Some(vec![gpu("b")]), prev), vec![gpu("b")]);
        assert_eq!(fingerprint_gpus(Some(vec![]), Some(vec![gpu("a")])), vec![]);
        assert!(fingerprint_gpus(None, None).is_empty());
        let fp = |g| HardwareFingerprint::detect(g).sha256();
        assert_eq!(
            fp(fingerprint_gpus(None, Some(vec![gpu("a")]))),
            fp(vec![gpu("a")])
        );
    }

    fn gpu_id(u: &str) -> GpuId {
        GpuId {
            vendor: "nvidia".into(),
            model: "m".into(),
            uuid: u.into(),
            vram_bytes: 1,
        }
    }
    fn gpu_m(u: &str, f32: f64, f16: f64, bw: f64) -> super::super::report::GpuMetrics {
        super::super::report::GpuMetrics {
            vendor: "nvidia".into(),
            model: "m".into(),
            uuid: u.into(),
            tflops_f32: f32,
            tflops_f16: f16,
            mem_bw_gbps: bw,
            vram_bytes: 1,
        }
    }

    #[test]
    fn a_gpu_that_was_not_fully_measured_makes_the_report_partial() {
        let full = [gpu_m("a", 1.0, 2.0, 3.0)];
        let ids = [gpu_id("a")];
        assert!(!gpu_partial(false, Some(&ids), &full));
        // Listed but not measured (timeout, cuInit failure, busy, expired slice).
        assert!(gpu_partial(false, Some(&ids), &[]));
        assert!(gpu_partial(false, Some(&[gpu_id("a"), gpu_id("b")]), &full));
        // Enumeration itself timed out.
        assert!(gpu_partial(false, None, &[]));
        // Measured, but fp16 or copy bandwidth is missing.
        assert!(gpu_partial(false, Some(&ids), &[gpu_m("a", 1.0, 0.0, 3.0)]));
        assert!(gpu_partial(false, Some(&ids), &[gpu_m("a", 1.0, 2.0, 0.0)]));
        // Skipped on purpose, or no GPU at all: complete.
        assert!(!gpu_partial(true, Some(&ids), &[]));
        assert!(!gpu_partial(false, Some(&[]), &[]));
    }

    #[test]
    fn a_partial_last_run_is_read_back_as_partial() {
        let dir = tmp("partial-last");
        let key = NodeKey::generate();
        let mut o = opts(&dir, Duration::ZERO);
        o.save_as = SubmitState::Declined;
        run(
            &o,
            &mut RunCtx {
                key: &key,
                cancel: Arc::new(AtomicBool::new(false)),
                progress: &|_| {},
                submit: None,
            },
        );
        assert!(last_run(&dir).unwrap().partial, "zero budget is partial");
    }

    #[test]
    fn a_refused_report_is_remembered_with_its_status_and_time() {
        let dir = tmp("rejected");
        let key = NodeKey::generate();
        let mut submit = |_: &SignedReport| Err(SubmitError::Rejected(400, "stale".into()));
        let RunOutcome::Completed { signed, .. } = run(
            &opts(&dir, Duration::from_secs(5)),
            &mut RunCtx {
                key: &key,
                cancel: Arc::new(AtomicBool::new(false)),
                progress: &|_| {},
                submit: Some(&mut submit),
            },
        ) else {
            panic!("expected a completed run")
        };
        save_last(&dir, &signed, SubmitState::Rejected(400)).unwrap();
        assert_eq!(load_last(&dir).unwrap().1, SubmitState::Rejected(400));
        assert_eq!(pending_submission(&dir, None), None, "not re-sent");
        let (code, since) = last_run(&dir).unwrap().rejected.unwrap();
        assert_eq!(code, 400);
        assert!(since < Duration::from_secs(5));
        // The next accepted save clears it.
        save_last(&dir, &signed, SubmitState::Done).unwrap();
        assert!(last_run(&dir).unwrap().rejected.is_none());
    }

    #[test]
    fn a_404_from_the_hub_leaves_the_report_pending_and_is_not_remeasured() {
        use crate::bench_node::schedule::{decide, Decision, IDLE_BEFORE_RUN};
        let dir = tmp("hub-404");
        let key = NodeKey::generate();
        let url = crate::bench_node::submit::tests::stub(vec!["404 Not Found"]);
        let mut submit =
            |s: &SignedReport| crate::bench_node::submit::post(&url, "k", s).map(|_| ());
        let RunOutcome::Completed {
            signed,
            submit_error,
            ..
        } = run(
            &opts(&dir, Duration::from_secs(5)),
            &mut RunCtx {
                key: &key,
                cancel: Arc::new(AtomicBool::new(false)),
                progress: &|_| {},
                submit: Some(&mut submit),
            },
        )
        else {
            panic!("expected a completed run")
        };
        assert!(matches!(submit_error, Some(SubmitError::Retryable(_))));
        // The scheduler resends this from last.json...
        assert_eq!(pending_submission(&dir, None), Some(signed));
        // ...and does not start a new measurement, however idle the node is.
        let last = last_run(&dir).unwrap();
        assert!(last.rejected.is_none());
        // (A partial run waits out its own 6 h re-measure window; a complete
        // one is Never. Either way, not RunNow.)
        assert_ne!(
            decide(
                Some(&last),
                &last.fingerprint_sha256,
                &last.suite,
                IDLE_BEFORE_RUN * 10,
                0,
                true
            ),
            Decision::RunNow
        );
    }

    #[test]
    fn a_second_run_in_the_same_state_dir_is_refused_not_interleaved() {
        let dir = tmp("lock");
        let first = RunLock::acquire(&bench_dir(&dir)).expect("first lock");
        assert!(RunLock::acquire(&bench_dir(&dir)).is_none(), "held");
        let key = NodeKey::generate();
        let out = run(
            &opts(&dir, Duration::from_secs(5)),
            &mut RunCtx {
                key: &key,
                cancel: Arc::new(AtomicBool::new(false)),
                progress: &|_| {},
                submit: None,
            },
        );
        assert!(matches!(out, RunOutcome::AlreadyRunning));
        assert!(!dir.join("bench/last.json").exists());
        drop(first);
        // A parallel test's fork can briefly inherit the descriptor (and so the
        // flock) before it execs; give that a moment to clear.
        let deadline = Instant::now() + Duration::from_secs(5);
        let mut again = RunLock::acquire(&bench_dir(&dir));
        while again.is_none() && Instant::now() < deadline {
            std::thread::sleep(Duration::from_millis(20));
            again = RunLock::acquire(&bench_dir(&dir));
        }
        assert!(again.is_some(), "released on drop");
    }

    #[test]
    fn a_lock_is_stale_when_its_pid_is_dead_or_it_is_junk_and_old() {
        let old = Duration::from_secs(120);
        let fresh = Duration::from_secs(1);
        assert!(lock_is_stale("4242", fresh, |_| false));
        assert!(!lock_is_stale("4242\n", fresh, |p| p == 4242));
        // Junk or empty: possibly an owner mid-write, so only old ones go.
        assert!(!lock_is_stale("", fresh, |_| false));
        assert!(lock_is_stale("", old, |_| false));
        assert!(lock_is_stale("xyz", old, |_| true));
    }

    #[test]
    fn the_pid_lock_records_its_pid_and_takes_over_a_dead_owners_file() {
        let dir = tmp("pidlock");
        let path = dir.join("run.lock");
        let mine = std::process::id().to_string();
        let first = PidLock::acquire(&path, |_| true).expect("first");
        assert_eq!(std::fs::read_to_string(&path).unwrap(), mine);
        // The owner is alive: refused.
        assert!(PidLock::acquire(&path, |_| true).is_none());
        // The owner is dead (crash): taken over, now holding OUR pid.
        std::fs::write(&path, "999999999").unwrap();
        let second = PidLock::acquire(&path, |p| p != 999_999_999).expect("takeover");
        assert_eq!(std::fs::read_to_string(&path).unwrap(), mine);
        drop(second);
        assert!(!path.exists(), "released on drop");
        std::mem::forget(first); // its file is gone already
    }

    #[test]
    fn the_real_pid_check_sees_this_process_and_not_a_dead_one() {
        assert!(pid_alive(std::process::id()));
        // Pids are bounded well below this on every unix we ship for.
        assert!(!pid_alive(i32::MAX as u32));
    }

    fn id(uuid: &str) -> GpuId {
        GpuId {
            vendor: "nvidia".into(),
            model: "m".into(),
            uuid: uuid.into(),
            vram_bytes: 1,
        }
    }

    #[test]
    fn a_hung_prober_is_never_joined_by_a_second_thread() {
        use std::sync::atomic::AtomicUsize;
        let p = Prober::new();
        let spawned = Arc::new(AtomicUsize::new(0));
        let cancel = AtomicBool::new(false);
        let grace = Duration::from_millis(150);
        // 1. A healthy probe answers and is remembered.
        let s = spawned.clone();
        let ids = p.enumerate(
            move || {
                s.fetch_add(1, Ordering::SeqCst);
                vec![id("GPU-1")]
            },
            &cancel,
            grace,
        );
        assert_eq!(ids, Some(vec![id("GPU-1")]));
        // 2. The next one hangs: the caller times out.
        let (release, hold) = mpsc::channel::<()>();
        let s = spawned.clone();
        let t = Instant::now();
        let hung = p.enumerate(
            move || {
                s.fetch_add(1, Ordering::SeqCst);
                let _ = hold.recv();
                vec![id("GPU-2")]
            },
            &cancel,
            grace,
        );
        assert_eq!(hung, None);
        assert!(t.elapsed() >= grace);
        // 3. While it is still hung: the cached result, at once, no new thread.
        let s = spawned.clone();
        let t = Instant::now();
        let again = p.enumerate(
            move || {
                s.fetch_add(1, Ordering::SeqCst);
                vec![id("GPU-3")]
            },
            &cancel,
            Duration::from_secs(5),
        );
        assert_eq!(again, Some(vec![id("GPU-1")]));
        assert!(t.elapsed() < Duration::from_secs(1));
        assert_eq!(spawned.load(Ordering::SeqCst), 2, "no third thread");
        // 4. Once the hung call returns, probing works again.
        release.send(()).unwrap();
        let deadline = Instant::now() + Duration::from_secs(5);
        while p.busy.load(Ordering::SeqCst) && Instant::now() < deadline {
            std::thread::sleep(Duration::from_millis(10));
        }
        let ids = p.enumerate(|| vec![id("GPU-4")], &cancel, Duration::from_secs(5));
        assert_eq!(ids, Some(vec![id("GPU-4")]));
    }

    #[test]
    fn a_panicking_probe_does_not_kill_later_enumeration() {
        let p = Prober::new();
        let cancel = AtomicBool::new(false);
        let grace = Duration::from_secs(5);
        assert_eq!(
            p.enumerate(|| panic!("driver exploded"), &cancel, grace),
            None
        );
        let deadline = Instant::now() + Duration::from_secs(5);
        while p.busy.load(Ordering::SeqCst) && Instant::now() < deadline {
            std::thread::sleep(Duration::from_millis(10));
        }
        assert_eq!(
            p.enumerate(|| vec![id("GPU-9")], &cancel, grace),
            Some(vec![id("GPU-9")])
        );
    }

    #[test]
    fn the_busy_streak_grows_while_busy_and_resets_on_a_complete_run() {
        let busy = vec!["gpu: RTX busy (20.0 GiB used by other processes)".to_string()];
        let other = vec!["gpu: probe timed out".to_string()];
        assert_eq!(next_busy_streak(0, true, &busy), 1);
        assert_eq!(next_busy_streak(1, true, &busy), 2);
        assert_eq!(next_busy_streak(2, true, &other), 0);
        assert_eq!(next_busy_streak(5, false, &[]), 0);
        // Busy note but a complete run cannot happen; still: not partial resets.
        assert_eq!(next_busy_streak(5, false, &busy), 0);
        let dir = tmp("streak");
        assert_eq!(load_busy_streak(&dir), 0);
        std::fs::create_dir_all(dir.join("bench")).unwrap();
        std::fs::write(dir.join("bench/busy_streak"), "3").unwrap();
        assert_eq!(load_busy_streak(&dir), 3);
    }

    #[test]
    fn a_manual_run_does_not_touch_the_busy_streak() {
        let dir = tmp("manualstreak");
        std::fs::create_dir_all(dir.join("bench")).unwrap();
        std::fs::write(dir.join("bench/busy_streak"), "2").unwrap();
        let key = NodeKey::generate();
        let go = |save_as| {
            let mut o = opts(&dir, Duration::from_secs(5));
            o.save_as = save_as;
            let _ = run(
                &o,
                &mut RunCtx {
                    key: &key,
                    cancel: Arc::new(AtomicBool::new(false)),
                    progress: &|_| {},
                    submit: None,
                },
            );
        };
        go(SubmitState::Declined);
        assert_eq!(load_busy_streak(&dir), 2, "manual run changed the streak");
        // A scheduled run that is not busy-partial resets it.
        go(SubmitState::Pending);
        assert_eq!(load_busy_streak(&dir), 0);
    }

    #[test]
    fn a_run_clears_stale_scratch_files_at_start() {
        let dir = tmp("sweepstart");
        let bench = dir.join("bench");
        std::fs::create_dir_all(&bench).unwrap();
        let stale = bench.join("bench-424242.tmp");
        std::fs::write(&stale, b"x").unwrap();
        let f = std::fs::File::options().write(true).open(&stale).unwrap();
        f.set_modified(std::time::SystemTime::now() - Duration::from_secs(2 * 3600))
            .unwrap();
        drop(f);
        let key = NodeKey::generate();
        let _ = run(
            &opts(&dir, Duration::from_secs(5)),
            &mut RunCtx {
                key: &key,
                cancel: Arc::new(AtomicBool::new(false)),
                progress: &|_| {},
                submit: None,
            },
        );
        assert!(!stale.exists(), "stale scratch file survived the run");
    }
}