zc2 0.0.50

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
//! The agent's hosting tick (every `watchdog::TICK_SECS`): keep the host
//! runner started when it is enabled, installed and reachable, stopped when
//! the owner turns it off, and yielding when the watchdog says so.

use crate::agent::host_runner::{plan_start, HostRunner, HostRunnerCfg, RunnerApi};
use crate::agent::hosting::{self, Hosting};
use crate::agent::runners::{catalogue, CatalogueEntry, Hardware, Isolation, RunnerKind};
use crate::agent::watchdog::{self, Action, MacSignals};
use std::collections::{HashMap, HashSet};
use std::net::IpAddr;
use std::path::{Path, PathBuf};

/// What one tick knows.
#[derive(Debug, Clone, PartialEq)]
pub struct Inputs {
    pub enabled: bool,
    pub installed: bool,
    /// An address to advertise exists.
    pub advertise: bool,
    /// Nothing else listens on the runner port (an older runner without
    /// `/status`, or another program): starting would only fail and retry.
    pub port_free: bool,
    /// The runner's reservation fits the owner's budget.
    pub fits: bool,
    /// The signed-in owner's public id is known (the runner is tagged with it).
    pub owner_known: bool,
    /// The running runner was started under another owner id.
    pub owner_changed: bool,
    /// The runner crashed recently; wait before starting it again.
    pub backoff: bool,
    pub alive: bool,
    /// `GET /status`; `None` when the runner did not answer.
    pub running_jobs: Option<Vec<String>>,
    pub draining: bool,
    pub action: Action,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Do {
    Start,
    Stop,
    Drain(bool),
    WrapUp(Vec<String>),
}

/// The tick's decision, and the reason the host runner is not serving (the
/// deployments view's `blocked_reason`). A runner is never stopped unless
/// it is known to run no job: with jobs it is drained and they are wrapped
/// up; with jobs unknown it is only drained.
pub fn step(i: &Inputs) -> (Vec<Do>, Option<&'static str>) {
    // Stop only a runner known to be idle; drain first, so even a runner
    // the agent cannot signal (adopted, no pid) stops taking jobs.
    let stand_down = |wrap: bool| match &i.running_jobs {
        None => vec![Do::Drain(true)],
        Some(j) if j.is_empty() => vec![Do::Drain(true), Do::Stop],
        Some(j) if wrap => vec![Do::Drain(true), Do::WrapUp(j.clone())],
        Some(_) => vec![Do::Drain(true)],
    };
    let yield_now = |reason, wrap| {
        if i.alive {
            (stand_down(wrap), Some(reason))
        } else {
            (vec![], Some(reason))
        }
    };
    if !i.enabled {
        return yield_now("disabled", true);
    }
    if !i.installed {
        return yield_now("not-installed", true);
    }
    if !i.fits {
        // Over budget: no new jobs, nothing cut short, nothing killed.
        return if i.alive {
            (vec![Do::Drain(true)], Some("budget"))
        } else {
            (vec![], Some("budget"))
        };
    }
    if !i.alive {
        return if !i.advertise {
            (vec![], Some("unreachable"))
        } else if !i.port_free {
            (vec![], Some("port-busy"))
        } else if !i.owner_known {
            (vec![], Some("signed-out"))
        } else if i.backoff {
            (vec![], Some("restarting"))
        } else {
            (vec![Do::Start], None)
        };
    }
    if i.owner_changed {
        // Re-tag it: restart once idle; never cut a job short for this.
        return (stand_down(false), Some("restarting"));
    }
    match &i.action {
        Action::None if i.draining => (vec![Do::Drain(false)], None),
        Action::None => (vec![], None),
        Action::StopAccepting => (vec![Do::Drain(true)], Some("yielding")),
        Action::WrapUp(j) => (
            vec![Do::Drain(true), Do::WrapUp(j.clone())],
            Some("yielding"),
        ),
    }
}

/// Restart delay for a runner that keeps exiting: 30 s, doubling to 10 min;
/// a runner that lived [`Backoff::HEALTHY`] resets it.
#[derive(Debug, Default, Clone)]
pub struct Backoff {
    delay: std::time::Duration,
}

impl Backoff {
    pub const HEALTHY: std::time::Duration = std::time::Duration::from_secs(600);
    const FIRST: std::time::Duration = std::time::Duration::from_secs(30);
    const MAX: std::time::Duration = std::time::Duration::from_secs(600);

    /// The wait before the next start, after a runner exited having lived `lived`.
    pub fn after_exit(&mut self, lived: std::time::Duration) -> std::time::Duration {
        self.delay = if lived >= Self::HEALTHY {
            std::time::Duration::ZERO
        } else if self.delay.is_zero() {
            Self::FIRST
        } else {
            (self.delay * 2).min(Self::MAX)
        };
        self.delay
    }
}

/// The address the runner advertises: `ZAKURO_RUNNER_ADVERTISE_IP` (a host
/// reached through another tunnel than the mesh), else the mesh address.
pub fn advertise_ip(override_ip: Option<String>, mesh_ip: Option<String>) -> Option<IpAddr> {
    match override_ip.filter(|v| !v.trim().is_empty()) {
        Some(v) => v.trim().parse().ok(),
        None => mesh_ip?.parse().ok(),
    }
}

/// `KEY=value` lines (`deploy-mac.sh`'s `runner.env`); quotes stripped,
/// comments and blanks skipped.
pub fn parse_env_file(s: &str) -> HashMap<String, String> {
    s.lines()
        .map(str::trim)
        .filter(|l| !l.is_empty() && !l.starts_with('#'))
        .filter_map(|l| l.split_once('='))
        .map(|(k, v)| {
            let v = v.trim();
            let v = v
                .strip_prefix('\'')
                .and_then(|v| v.strip_suffix('\''))
                .or_else(|| v.strip_prefix('"').and_then(|v| v.strip_suffix('"')))
                .unwrap_or(v);
            (k.trim().to_string(), v.to_string())
        })
        .collect()
}

/// The host runner config from an existing `deploy-mac.sh` install at
/// `root` (`$ZAKURO_RUNNER_ROOT`, default `~/atelier`). `None` when there is
/// no `runner.env` there.
pub fn load_cfg(root: &Path, backend: &str) -> Option<HostRunnerCfg> {
    let env = parse_env_file(&std::fs::read_to_string(root.join("runner.env")).ok()?);
    let get = |k: &str| env.get(k).cloned().filter(|v| !v.is_empty());
    Some(HostRunnerCfg {
        backend: backend.to_string(),
        port: get("FORGE_RUNNER_PORT")
            .and_then(|p| p.parse().ok())
            .unwrap_or(8102),
        root: root.to_path_buf(),
        broker: get("FORGE_ATELIER_ZC_BROKER")?,
        key_file: PathBuf::from(get("FORGE_ATELIER_ZC_WORKER_KEY_FILE")?),
        name: get("FORGE_ATELIER_ZC_NAME")?,
        price_per_hour: get("FORGE_ATELIER_PRICE_PER_HOUR").unwrap_or_else(|| "0.9".into()),
        gpu_model: get("FORGE_ATELIER_ZC_GPU_MODEL").unwrap_or_else(|| "Apple".into()),
        gpu_mem_gb: get("FORGE_ATELIER_ZC_GPU_VRAM_GB")
            .and_then(|v| v.parse().ok())
            .unwrap_or(8),
        owner: None,
        token: get("FORGE_RUNNER_TOKEN").map(crate::agent::host_runner::Secret::new),
    })
}

pub fn default_root() -> PathBuf {
    std::env::var_os("ZAKURO_RUNNER_ROOT")
        .map(PathBuf::from)
        .unwrap_or_else(|| {
            PathBuf::from(std::env::var_os("HOME").unwrap_or_default()).join("atelier")
        })
}

/// What the API handlers read about hosting: written at the end of each
/// tick under its own short lock, so a slow tick (network calls, a stop)
/// never holds up `/v2/deployments` or `/v2/images`.
#[derive(Debug, Clone, Default)]
pub struct HostingStatus {
    /// Filled on first use (`Hardware::detect`); tests set it.
    pub catalogue: Option<Vec<CatalogueEntry>>,
    /// The runner install root; `None` = [`default_root`]. Tests point it
    /// at a temp dir so nothing touches the owner's real install.
    pub root: Option<PathBuf>,
    /// Why the host runner does not serve now (`blocked_reason`).
    pub reason: Option<&'static str>,
    /// Up and taking jobs.
    pub serving: bool,
    /// The runner's base URL, for live "which jobs run?" checks.
    pub runner_base: Option<String>,
    /// The runner's bearer (`FORGE_RUNNER_TOKEN`), for those checks.
    pub runner_token: Option<crate::agent::host_runner::Secret>,
    /// The last tick's answer; `None` = unknown.
    pub running_jobs: Option<Vec<String>>,
    pub last_job_seen: Option<std::time::SystemTime>,
}

impl HostingStatus {
    pub fn root(&self) -> PathBuf {
        self.root.clone().unwrap_or_else(default_root)
    }

    pub fn catalogue(&mut self) -> Vec<CatalogueEntry> {
        self.catalogue
            .get_or_insert_with(|| catalogue(&Hardware::detect()))
            .clone()
    }

    /// Apple Silicon (the host runner kind exists): GPU memory is RAM.
    pub fn unified(&mut self) -> bool {
        self.catalogue()
            .iter()
            .any(|e| e.supported && e.isolation == Isolation::Host)
    }

    /// The image store over this status: "which jobs run?" is asked of the
    /// runner at every check, falling back to the last tick's answer.
    pub fn image_store(&self, h: &Hosting) -> crate::agent::images::HostStore {
        let base = self.runner_base.clone();
        let token = self.runner_token.clone();
        let last = self.running_jobs.clone();
        crate::agent::images::HostStore {
            root: self.root(),
            enabled_backends: if h.budget.gpu {
                h.workloads.atelier.clone()
            } else {
                vec![]
            },
            jobs: Box::new(move || match &base {
                Some(b) => RunnerApi {
                    base: b.clone(),
                    token: token.clone(),
                }
                .running(),
                None => last.clone(),
            }),
            last_job_seen: self.last_job_seen,
        }
    }
}

/// The hourly cleanup a tick asks for; the caller runs it outside every lock.
pub struct GcPlan {
    pub store: crate::agent::images::HostStore,
    pub ttl: std::time::Duration,
}

/// The host runner's live state, owned by `Core` and only touched by the tick.
#[derive(Default)]
pub struct HostingRuntime {
    pub runner: HostRunner,
    pub draining: bool,
    /// Jobs a wrap-up was already asked for (asked once each).
    wrapped: HashSet<String>,
    last_gc: Option<std::time::Instant>,
    last_job_seen: Option<std::time::SystemTime>,
    /// When the owned runner was started, and under which owner id.
    started: Option<(std::time::Instant, Option<String>)>,
    backoff: Backoff,
    next_start: Option<std::time::Instant>,
    /// An adopted runner already stopped once in this agent's life: if it
    /// comes back (launchd KeepAlive), it is drained, not killed again.
    stopped_adopted: bool,
}

/// Log files grow in append mode; cut one past this size before a start.
const MAX_LOG_BYTES: u64 = 50 << 20;

impl HostingRuntime {
    /// One tick. `status` is the snapshot the API reads (catalogue, root);
    /// the tick fills in the rest. Returns the cleanup to run, when one is due.
    pub fn tick(
        &mut self,
        state_dir: &Path,
        owner: Option<String>,
        status: &std::sync::Mutex<HostingStatus>,
    ) -> Option<GcPlan> {
        let (cat, root) = {
            let mut st = status.lock().unwrap_or_else(|p| p.into_inner());
            (st.catalogue(), st.root())
        };
        let entry = cat
            .iter()
            .find(|e| e.kind == RunnerKind::AtelierPeft && e.isolation == Isolation::Host)
            .cloned()?; // no host runner kind on this machine
        let h = match hosting::load_or_default(state_dir, &cat) {
            Ok(h) => h,
            Err(e) => {
                eprintln!("  [HOSTING] {e}");
                return None;
            }
        };
        let cfg = load_cfg(&root, "peft").map(|mut c| {
            c.owner = owner.clone();
            // A runner registering with this node's own broker must present
            // the key that broker now requires (it starts with
            // ZAKURO_REQUIRE_WORKER_KEY=1), not the one deploy-mac.sh wrote.
            if crate::worker_key::is_loopback(&c.broker) {
                if let Some(dir) = crate::credentials::dir() {
                    match crate::worker_key::file_for_local_client(
                        std::env::var(crate::worker_key::ENV).ok(),
                        &dir,
                    ) {
                        Ok(p) => c.key_file = p,
                        Err(e) => eprintln!("  [HOSTING] worker key for the host runner: {e}"),
                    }
                }
            }
            c
        });
        let addr = advertise_ip(
            std::env::var("ZAKURO_RUNNER_ADVERTISE_IP").ok(),
            crate::vpn::local_mesh().map(|m| m.ip),
        );
        let base = addr
            .zip(cfg.as_ref())
            .map(|(a, c)| crate::agent::host_runner::base_url(a, c.port));
        let token = cfg.as_ref().and_then(|c| c.token.clone());
        let api = base.clone().map(|b| RunnerApi {
            base: b,
            token: token.clone(),
        });

        // A crashed owned runner sets the restart backoff.
        let was_owned = self.runner.owned();
        let child_alive = self.runner.alive();
        if was_owned && !child_alive {
            if let Some((at, _)) = self.started.take() {
                let wait = self.backoff.after_exit(at.elapsed());
                self.next_start = Some(std::time::Instant::now() + wait);
                eprintln!(
                    "  [HOSTING] host runner exited; next start in {}s",
                    wait.as_secs()
                );
            }
        }
        // A runner that answers is alive even when this agent did not start
        // it (an agent restart leaves it running, so training survives an
        // update): it is adopted, never started a second time on its port.
        let st = api.as_ref().and_then(RunnerApi::status);
        if let Some(s) = &st {
            self.runner.adopt(s.pid);
        }
        let running_jobs = st.map(|s| s.jobs);
        let alive = child_alive || running_jobs.is_some();
        let jobs = running_jobs.clone().unwrap_or_default();
        if !jobs.is_empty() {
            self.last_job_seen = Some(std::time::SystemTime::now());
        }
        self.wrapped.retain(|j| jobs.contains(j));
        let fits = h
            .budget()
            .and_then(|b| {
                let total = b.total(&crate::sandbox::HostResources::detect())?;
                let r = entry.reservation;
                Ok(r.cpu_millis <= total.cpu_millis
                    && r.memory_bytes + r.vram_bytes <= total.memory_bytes
                    && r.disk_bytes <= b.disk_bytes)
            })
            .unwrap_or(false);
        let signals = MacSignals {
            runner_pid: self.runner.pid(),
        };
        let port_free = alive
            || addr.zip(cfg.as_ref()).is_none_or(|(a, c)| {
                std::net::TcpStream::connect_timeout(
                    &std::net::SocketAddr::new(a, c.port),
                    std::time::Duration::from_millis(300),
                )
                .is_err()
            });
        let inputs = Inputs {
            enabled: enabled(&h),
            installed: cfg.as_ref().is_some_and(HostRunnerCfg::installed),
            advertise: addr.is_some(),
            port_free,
            fits,
            owner_known: owner.is_some(),
            // Only a runner this agent started carries a tag it knows.
            owner_changed: self.runner.owned()
                && self.started.as_ref().is_some_and(|(_, o)| *o != owner),
            backoff: self
                .next_start
                .is_some_and(|t| std::time::Instant::now() < t),
            alive,
            running_jobs: running_jobs.clone(),
            draining: self.draining,
            action: watchdog::decide(&signals, &h, entry.reservation.memory_bytes, &jobs),
        };
        // Something runs on the runner port but did not say which jobs: the
        // cleanup cannot know what is in use, so it waits for a tick that can.
        let jobs_unknown = running_jobs.is_none() && (alive || !port_free);
        let (todo, reason) = step(&inputs);
        for d in todo {
            match d {
                Do::Start => {
                    let (Some(cfg), Some(addr)) = (cfg.as_ref(), addr) else {
                        continue;
                    };
                    let Ok((argv, env)) = plan_start(Some(addr), cfg) else {
                        continue;
                    };
                    let _ =
                        crate::agent::supervisor::truncate_if_large(&cfg.log_path(), MAX_LOG_BYTES);
                    match self.runner.start(
                        &argv,
                        &env,
                        &cfg.root.join("zak-forge"),
                        &cfg.log_path(),
                    ) {
                        Ok(()) => {
                            self.draining = false;
                            self.started = Some((std::time::Instant::now(), owner.clone()));
                            eprintln!("  [HOSTING] host runner started on {addr}:{}", cfg.port);
                        }
                        Err(e) => {
                            let wait = self.backoff.after_exit(std::time::Duration::ZERO);
                            self.next_start = Some(std::time::Instant::now() + wait);
                            eprintln!("  [HOSTING] host runner did not start: {e}");
                        }
                    }
                }
                Do::Stop => {
                    if self.runner.owned() || !self.stopped_adopted {
                        self.stopped_adopted |= !self.runner.owned();
                        self.runner.stop();
                        self.started = None;
                        self.draining = false;
                    }
                }
                Do::Drain(on) => {
                    if self.draining != on && api.as_ref().is_some_and(|a| a.drain(on)) {
                        self.draining = on;
                    }
                }
                Do::WrapUp(ids) => {
                    for id in ids {
                        if !self.wrapped.contains(&id)
                            && api.as_ref().is_some_and(|a| a.wrap_up(&id))
                        {
                            eprintln!("  [HOSTING] wrap-up asked for job {id}");
                            self.wrapped.insert(id);
                        }
                    }
                }
            }
        }
        {
            let mut st = status.lock().unwrap_or_else(|p| p.into_inner());
            st.reason = reason;
            st.serving = reason.is_none() && alive && !self.draining;
            st.runner_base = if alive { base } else { None };
            st.runner_token = token;
            st.running_jobs = if jobs_unknown { None } else { Some(jobs) };
            st.last_job_seen = self.last_job_seen;
        }
        let due = self
            .last_gc
            .is_none_or(|t| t.elapsed() >= crate::agent::images::GC_EVERY);
        if !due || jobs_unknown {
            return None;
        }
        self.last_gc = Some(std::time::Instant::now());
        let ttl = match h.idle_ttl() {
            Ok(t) => t,
            Err(e) => {
                eprintln!("  [HOSTING] cleanup skipped: {e}");
                return None;
            }
        };
        let store = status
            .lock()
            .unwrap_or_else(|p| p.into_inner())
            .image_store(&h);
        Some(GcPlan { store, ttl })
    }
}

fn enabled(h: &Hosting) -> bool {
    h.budget.gpu && h.workloads.atelier.iter().any(|a| a == "peft")
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::agent::watchdog::Action;
    use std::time::Duration;

    fn base() -> Inputs {
        Inputs {
            enabled: true,
            installed: true,
            advertise: true,
            port_free: true,
            fits: true,
            owner_known: true,
            owner_changed: false,
            backoff: false,
            alive: false,
            running_jobs: Some(vec![]),
            draining: false,
            action: Action::None,
        }
    }

    fn j1() -> Option<Vec<String>> {
        Some(vec!["j1".into()])
    }

    #[test]
    fn starts_when_enabled_installed_and_reachable() {
        assert_eq!(step(&base()), (vec![Do::Start], None));
    }

    #[test]
    fn never_starts_without_an_address() {
        let i = Inputs {
            advertise: false,
            ..base()
        };
        assert_eq!(step(&i), (vec![], Some("unreachable")));
    }

    #[test]
    fn busy_port_is_reported_not_retried() {
        let i = Inputs {
            port_free: false,
            ..base()
        };
        assert_eq!(step(&i), (vec![], Some("port-busy")));
    }

    #[test]
    fn not_installed_is_reported() {
        let i = Inputs {
            installed: false,
            ..base()
        };
        assert_eq!(step(&i), (vec![], Some("not-installed")));
    }

    #[test]
    fn disabled_idle_runner_is_drained_then_stopped() {
        // Drain first: an adopted runner the agent cannot signal still stops
        // taking jobs.
        let i = Inputs {
            enabled: false,
            alive: true,
            ..base()
        };
        assert_eq!(
            step(&i),
            (vec![Do::Drain(true), Do::Stop], Some("disabled"))
        );
    }

    #[test]
    fn disabled_busy_runner_drains_and_wraps_up_never_killed() {
        let i = Inputs {
            enabled: false,
            alive: true,
            running_jobs: j1(),
            ..base()
        };
        assert_eq!(
            step(&i),
            (
                vec![Do::Drain(true), Do::WrapUp(vec!["j1".into()])],
                Some("disabled")
            )
        );
    }

    #[test]
    fn unknown_jobs_are_never_stopped_only_drained() {
        let i = Inputs {
            enabled: false,
            alive: true,
            running_jobs: None,
            ..base()
        };
        assert_eq!(step(&i), (vec![Do::Drain(true)], Some("disabled")));
    }

    #[test]
    fn over_budget_runner_drains_without_wrap_up_or_kill() {
        let i = Inputs {
            fits: false,
            alive: true,
            running_jobs: j1(),
            ..base()
        };
        assert_eq!(step(&i), (vec![Do::Drain(true)], Some("budget")));
    }

    #[test]
    fn over_budget_runner_is_not_started() {
        let i = Inputs {
            fits: false,
            ..base()
        };
        assert_eq!(step(&i), (vec![], Some("budget")));
    }

    #[test]
    fn no_start_before_the_owner_is_known() {
        let i = Inputs {
            owner_known: false,
            ..base()
        };
        assert_eq!(step(&i), (vec![], Some("signed-out")));
    }

    #[test]
    fn owner_change_restarts_an_idle_runner_only() {
        let i = Inputs {
            alive: true,
            owner_changed: true,
            ..base()
        };
        assert_eq!(
            step(&i),
            (vec![Do::Drain(true), Do::Stop], Some("restarting"))
        );
        let busy = Inputs {
            alive: true,
            owner_changed: true,
            running_jobs: j1(),
            ..base()
        };
        assert_eq!(step(&busy), (vec![Do::Drain(true)], Some("restarting")));
    }

    #[test]
    fn crashing_runner_waits_for_its_backoff() {
        let i = Inputs {
            backoff: true,
            ..base()
        };
        assert_eq!(step(&i), (vec![], Some("restarting")));
    }

    #[test]
    fn watchdog_stop_accepting_drains_and_says_yielding() {
        let i = Inputs {
            alive: true,
            action: Action::StopAccepting,
            ..base()
        };
        assert_eq!(step(&i), (vec![Do::Drain(true)], Some("yielding")));
    }

    #[test]
    fn watchdog_wrap_up_drains_and_wraps() {
        let i = Inputs {
            alive: true,
            action: Action::WrapUp(vec!["j1".into()]),
            ..base()
        };
        assert_eq!(
            step(&i),
            (
                vec![Do::Drain(true), Do::WrapUp(vec!["j1".into()])],
                Some("yielding")
            )
        );
    }

    #[test]
    fn calm_again_undrains() {
        let i = Inputs {
            alive: true,
            draining: true,
            ..base()
        };
        assert_eq!(step(&i), (vec![Do::Drain(false)], None));
    }

    #[test]
    fn backoff_doubles_and_caps() {
        let mut b = Backoff::default();
        let quick = Duration::from_secs(5);
        assert_eq!(b.after_exit(quick).as_secs(), 30);
        assert_eq!(b.after_exit(quick).as_secs(), 60);
        for _ in 0..10 {
            b.after_exit(quick);
        }
        assert_eq!(b.after_exit(quick).as_secs(), 600);
        // A runner that lived long enough resets it.
        assert_eq!(b.after_exit(Duration::from_secs(3600)).as_secs(), 0);
    }

    #[test]
    fn advertise_ip_override_wins() {
        let ip = advertise_ip(Some("10.5.5.3".into()), Some("10.13.13.7".into()));
        assert_eq!(ip.unwrap().to_string(), "10.5.5.3");
        let ip = advertise_ip(None, Some("10.13.13.7".into()));
        assert_eq!(ip.unwrap().to_string(), "10.13.13.7");
        assert!(advertise_ip(Some("nope".into()), None).is_none());
        assert!(advertise_ip(None, None).is_none());
    }

    #[test]
    fn runner_env_file_is_parsed() {
        let s = "FORGE_ATELIER_ZC_NAME=atelier-m5\nFORGE_ATELIER_ZC_GPU_MODEL='Apple M5'\n# c\n\nX=\"y\"\n";
        let m = parse_env_file(s);
        assert_eq!(m.get("FORGE_ATELIER_ZC_NAME").unwrap(), "atelier-m5");
        assert_eq!(m.get("FORGE_ATELIER_ZC_GPU_MODEL").unwrap(), "Apple M5");
        assert_eq!(m.get("X").unwrap(), "y");
    }
}