devsandbox 0.11.1

Manage devcontainer-style sandboxes on docker, podman, or Apple container — many throwaway instances per repo from one TOML config.
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
//! Placement (docs/architecture/daemon/fleet.md, *Placement*; fleet plan
//! decision 11: it runs in the daemon): which machine a new instance goes
//! on. [`place`] is pure over a [`Spec`] and the [`Candidate`]s the daemon
//! fills from its snapshots ([`Candidate::local`], [`Candidate::from_machine`],
//! [`Candidate::from_routed`]).
//!
//! Soft caps never refuse: a machine over one scores below every machine
//! that isn't, and when all are over the best is still used with an
//! `over cap: …` warning. New work never goes to a machine that is
//! unreachable or has no container runtime (a driver, its capacity's
//! `runtime: false`); a pin is refused only then (or when the machine is
//! unknown). A required GPU goes only where one is usable and lent
//! ([`gpu_check`]); an optional one scores [`GPU`] there.

use std::cmp::Ordering;
use std::fmt;

use serde_json::Value;

use crate::config::GpuNeed;
use crate::serve::capacity::{Capacity, over_caps, over_note};
use crate::serve::snapshots::{LinkState, Machine, Routed};

/// A machine as placement names it: this host, or a registered machine.
/// Orders this host first, then machines by name (the tie-break).
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum MachineRef {
    Local,
    Machine(String),
}

impl fmt::Display for MachineRef {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            MachineRef::Local => f.write_str("this host"),
            MachineRef::Machine(name) => f.write_str(name),
        }
    }
}

/// What is being placed.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Spec {
    pub sandbox: String,
    /// The resolved sandbox's config hash (`SandboxRow::config_hash`);
    /// `None` when unknown (no image locality then).
    pub config_hash: Option<String>,
    /// Its build dockerfile's hash (`SandboxRow::build_hash`); `None` is
    /// not compared.
    pub build_hash: Option<String>,
    /// The repo's identity (its `origin` URL for now); what a candidate's
    /// `has_repo` is about.
    pub repo: Option<String>,
    /// Who asked: gets [`REQUESTER`]'s bias.
    pub requester: MachineRef,
    /// `--machine m` or a qualified name: wins over the score.
    pub pinned: Option<MachineRef>,
    /// The sandbox's GPU need, its services' included ([`super::placed::gpu_need`]).
    pub gpu: Option<GpuNeed>,
}

/// One machine new work could go on.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Candidate {
    pub machine: MachineRef,
    pub reachable: bool,
    /// `None` before a report came: every headroom item counts as neutral.
    pub capacity: Option<Capacity>,
    /// An instance of the spec's sandbox runs there at the spec's hashes
    /// ([`has_image`]).
    pub has_image: bool,
    /// The spec's repo is already there (cloned or cached).
    pub has_repo: bool,
}

impl Candidate {
    /// This host: reachable by definition. `roots` are its
    /// roots' `instances.snapshot` params, for [`has_image`]; `has_repo` is
    /// the caller's (no snapshot says which repos are here).
    pub fn local<'a>(spec: &Spec, capacity: Option<Capacity>, roots: impl IntoIterator<Item = &'a Value>) -> Candidate {
        Candidate {
            machine: MachineRef::Local,
            reachable: true,
            capacity,
            has_image: has_image(spec, roots),
            has_repo: false,
        }
    }

    /// A machine (any kind), from what the daemon keeps of it: its link
    /// state ([`reachable`]), its pushed rows for [`has_image`] and its
    /// capacity report. `has_repo` is the caller's.
    pub fn from_machine(spec: &Spec, m: &Machine) -> Candidate {
        Candidate {
            machine: MachineRef::Machine(m.name.clone()),
            reachable: reachable(m.state),
            capacity: m.capacity(),
            has_image: has_image(spec, m.rows.values().map(|v| v.as_ref())),
            has_repo: false,
        }
    }

    /// A routed machine (no link of its own here, fleet plan decision 60):
    /// reachable while a path to it starts with a link up here, its
    /// capacity as the control plane's view reports it. No rows of its own are
    /// watched, so no image locality.
    pub fn from_routed(r: &Routed) -> Candidate {
        Candidate {
            machine: MachineRef::Machine(r.name.clone()),
            reachable: reachable(r.state),
            capacity: r.capacity.clone(),
            has_image: false,
            has_repo: false,
        }
    }
}

/// Whether new work can reach a machine: while its held link is up,
/// whatever its kind (the code moves over it before the run does).
pub fn reachable(state: LinkState) -> bool {
    state == LinkState::Connected
}

/// Whether some root's snapshot in `roots` (`instances.snapshot` params)
/// shows the spec's image built: a sandbox row of that name at the spec's
/// `config_hash` (and `build_hash`, when the spec has one) with a ready,
/// non-drifted instance of it from the same root. Image tags are per config
/// root (`run::image::sandbox_image`), so the instance's root must match.
pub fn has_image<'a>(spec: &Spec, roots: impl IntoIterator<Item = &'a Value>) -> bool {
    let Some(config_hash) = spec.config_hash.as_deref().filter(|h| !h.is_empty()) else { return false };
    let str_of = |v: &Value, k: &str| v.get(k).and_then(Value::as_str).map(str::to_owned);
    roots.into_iter().any(|snap| {
        let rows = |k: &str| snap.get(k).and_then(Value::as_array).into_iter().flatten();
        rows("sandboxes").any(|s| {
            let matches = str_of(s, "name").as_deref() == Some(&spec.sandbox)
                && str_of(s, "config_hash").as_deref() == Some(config_hash)
                && spec.build_hash.as_ref().is_none_or(|b| str_of(s, "build_hash").as_ref() == Some(b));
            let root = str_of(s, "root").or_else(|| str_of(snap, "dir"));
            matches
                && root.is_some()
                && rows("instances").any(|i| {
                    str_of(i, "sandbox").as_deref() == Some(&spec.sandbox)
                        && str_of(i, "root") == root
                        && i.get("drift").and_then(Value::as_bool) == Some(false)
                        && i.get("phase").is_none_or(Value::is_null)
                })
        })
    })
}

/// Where it goes and why.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Placement {
    pub machine: MachineRef,
    /// For the verb's output: `over cap: mem 18G/16G`, ….
    pub warnings: Vec<String>,
    pub score: i64,
    /// The score's parts, as text (`mem 60% free`, `image built`, …).
    pub reasons: Vec<String>,
}

/// Why nothing was placed.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum NoPlace {
    /// The pinned machine isn't a candidate.
    UnknownPin(MachineRef),
    PinUnreachable(MachineRef),
    PinNoRuntime(MachineRef),
    /// A required GPU pinned to a machine that can't give one: why
    /// ([`gpu_check`]).
    PinNoGpu(MachineRef, &'static str),
    /// No candidate takes new work: each with why.
    NoCandidate(Vec<(MachineRef, &'static str)>),
}

impl fmt::Display for NoPlace {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            NoPlace::UnknownPin(m) => write!(f, "no machine `{m}`"),
            NoPlace::PinUnreachable(m) => write!(f, "{m} is unreachable"),
            NoPlace::PinNoRuntime(m) => write!(f, "{m} has no container runtime"),
            NoPlace::PinNoGpu(m, why) => write!(f, "{m} can't take a required GPU ({why})"),
            NoPlace::NoCandidate(skipped) if skipped.is_empty() => f.write_str("no machine to place on"),
            NoPlace::NoCandidate(skipped) => {
                let why: Vec<String> = skipped.iter().map(|(m, why)| format!("{m}: {why}")).collect();
                write!(f, "no machine takes new work ({})", why.join(", "))
            }
        }
    }
}

impl std::error::Error for NoPlace {}

/// Per-item headroom in points, `0..=100`; unknown is [`NEUTRAL`].
pub const NEUTRAL: i64 = 50;
/// Weights of the headroom items.
pub const W_MEM: i64 = 3;
pub const W_DISK: i64 = 2;
pub const W_SLOTS: i64 = 2;
pub const W_CPU: i64 = 1;
/// Subtracted per exceeded cap: more than any in-cap machine can score
/// (headroom 800 + locality 450 + GPU 400 + bias 50), so over-cap always
/// ranks last.
pub const OVER: i64 = 2000;
/// Locality.
pub const IMAGE: i64 = 300;
pub const REPO: i64 = 150;
/// The requester's own host.
pub const REQUESTER: i64 = 50;
/// An optional GPU it can use there: above [`IMAGE`], since a missing
/// image costs one build and a missing GPU the whole run's speed; below
/// the headroom span (800), so a full GPU host still loses to an idle one.
pub const GPU: i64 = 400;

/// Pick the machine for `spec` among `candidates`. A pin wins (refused only
/// unknown, unreachable, without a runtime or, for a required GPU, without
/// one it gives; warned over cap); otherwise the highest [`score`] among
/// reachable candidates with a runtime (and a GPU, when required), ties to
/// the lowest [`MachineRef`].
pub fn place(spec: &Spec, candidates: &[Candidate]) -> Result<Placement, NoPlace> {
    if let Some(pin) = &spec.pinned {
        let c = candidates.iter().find(|c| &c.machine == pin).ok_or_else(|| NoPlace::UnknownPin(pin.clone()))?;
        if !c.reachable {
            return Err(NoPlace::PinUnreachable(pin.clone()));
        }
        if !has_runtime(c) {
            return Err(NoPlace::PinNoRuntime(pin.clone()));
        }
        if spec.gpu == Some(GpuNeed::Required)
            && let Err(why) = gpu_check(spec, c)
        {
            return Err(NoPlace::PinNoGpu(pin.clone(), why));
        }
        return Ok(scored(spec, c));
    }
    let mut skipped = Vec::new();
    let mut best: Option<Placement> = None;
    for c in candidates {
        if !c.reachable {
            skipped.push((c.machine.clone(), "unreachable"));
            continue;
        }
        if !has_runtime(c) {
            skipped.push((c.machine.clone(), "no container runtime"));
            continue;
        }
        if spec.gpu == Some(GpuNeed::Required)
            && let Err(why) = gpu_check(spec, c)
        {
            skipped.push((c.machine.clone(), why));
            continue;
        }
        let p = scored(spec, c);
        let better = best.as_ref().is_none_or(|b| match p.score.cmp(&b.score) {
            Ordering::Greater => true,
            Ordering::Equal => p.machine < b.machine,
            Ordering::Less => false,
        });
        if better {
            best = Some(p);
        }
    }
    best.ok_or(NoPlace::NoCandidate(skipped))
}

/// Whether `c` can run containers: its report says so, or there's none
/// yet (unknown is assumed to).
fn has_runtime(c: &Candidate) -> bool {
    c.capacity.as_ref().is_none_or(|cap| cap.runtime)
}

/// Whether `c` gives `spec`'s work a GPU (decision 6 of the gpus plan):
/// its report has a usable one (no report: none) and it lends it
/// (`GpuReport::lent`), or it is the requester, whose own run is under no
/// worker policy. Else why not.
pub fn gpu_check(spec: &Spec, c: &Candidate) -> Result<(), &'static str> {
    let Some(gpu) = c.capacity.as_ref().and_then(|cap| cap.gpu.as_ref()) else { return Err("no GPU") };
    if gpu.lent || c.machine == spec.requester { Ok(()) } else { Err("GPU not lent") }
}

fn scored(spec: &Spec, c: &Candidate) -> Placement {
    let (score, reasons) = score(spec, c);
    let warnings = c.capacity.as_ref().and_then(over_note).into_iter().map(|n| format!("{}: {n}", c.machine)).collect();
    Placement { machine: c.machine.clone(), warnings, score, reasons }
}

/// `c`'s score for `spec` and its parts: headroom (mem·3 + disk·2 +
/// slots·2 + cpu·1, each `0..=100`, unknown [`NEUTRAL`]), minus [`OVER`]
/// per exceeded cap, plus [`IMAGE`] / [`REPO`] locality, [`GPU`] for an
/// optional GPU it gives ([`gpu_check`]) and the [`REQUESTER`] bias.
pub fn score(spec: &Spec, c: &Candidate) -> (i64, Vec<String>) {
    let mut reasons = Vec::new();
    let mut total = 0;
    let h = headroom(c.capacity.as_ref());
    for (name, w, pts) in [("mem", W_MEM, h.mem), ("disk", W_DISK, h.disk), ("slots", W_SLOTS, h.slots), ("cpu", W_CPU, h.cpu)] {
        match pts {
            Some(p) => {
                total += w * p;
                reasons.push(format!("{name} {p}% free"));
            }
            None => total += w * NEUTRAL,
        }
    }
    if let Some(cap) = &c.capacity {
        let over = over_caps(cap);
        total -= OVER * over.len() as i64;
        if let Some(note) = over_note(cap) {
            reasons.push(note);
        }
    } else {
        reasons.push("no capacity report".into());
    }
    if c.has_image {
        total += IMAGE;
        reasons.push("image built".into());
    }
    if c.has_repo {
        total += REPO;
        reasons.push("repo there".into());
    }
    if spec.gpu == Some(GpuNeed::Optional) && gpu_check(spec, c).is_ok() {
        total += GPU;
        reasons.push("GPU".into());
    }
    if c.machine == spec.requester {
        total += REQUESTER;
        reasons.push("requester's host".into());
    }
    (total, reasons)
}

/// Each headroom item in points, `None` unknown.
#[derive(Debug, Default, PartialEq, Eq)]
struct Headroom {
    mem: Option<i64>,
    disk: Option<i64>,
    slots: Option<i64>,
    cpu: Option<i64>,
}

/// Memory: available over total, and over the `mem` cap's room when set,
/// the smaller. Disk the same with free / total / `disk`. Slots: room left
/// under the `instances` cap (unknown without one). Cpu: `running` per cpu
/// (the `cpus` cap lowers the count), `0` at one instance per cpu.
fn headroom(c: Option<&Capacity>) -> Headroom {
    let Some(c) = c else { return Headroom::default() };
    let caps = c.caps.clone().unwrap_or_default();
    let pct = |num: u64, den: u64| (den > 0).then(|| (num.min(den) as u128 * 100 / den as u128) as i64);
    let room = |used: Option<u64>, cap: Option<u64>| pct(cap?.saturating_sub(used?), cap?);
    let min = |a: Option<i64>, b: Option<i64>| match (a, b) {
        (Some(a), Some(b)) => Some(a.min(b)),
        (a, b) => a.or(b),
    };
    let used = |total: Option<u64>, free: Option<u64>| Some(total?.saturating_sub(free?));
    let running = c.running as u64;
    let cpus = match (c.cpus, caps.cpus) {
        (Some(n), Some(cap)) => Some(n.min(cap)),
        (n, cap) => n.or(cap),
    };
    Headroom {
        mem: min(c.mem_total.zip(c.mem_available).and_then(|(t, a)| pct(a, t)), room(used(c.mem_total, c.mem_available), caps.mem)),
        disk: min(c.disk_total.zip(c.disk_free).and_then(|(t, f)| pct(f, t)), room(used(c.disk_total, c.disk_free), caps.disk)),
        slots: room(Some(running), caps.instances),
        cpu: cpus.and_then(|n| pct(n.saturating_sub(running), n)),
    }
}

#[cfg(test)]
mod tests {
    use std::collections::BTreeMap;
    use std::path::PathBuf;
    use std::sync::Arc;

    use serde_json::json;

    use super::*;
    use crate::serve::capacity::{Caps, GpuReport};
    use crate::serve::machines::MachineKind;

    const G: u64 = 1 << 30;

    fn m(name: &str) -> MachineRef {
        MachineRef::Machine(name.into())
    }

    fn spec() -> Spec {
        Spec {
            sandbox: "web".into(),
            config_hash: Some("c1".into()),
            build_hash: None,
            repo: None,
            requester: MachineRef::Local,
            pinned: None,
            gpu: None,
        }
    }

    /// `c` with a usable GPU, `lent` or not.
    fn gpu(c: Capacity, lent: bool) -> Capacity {
        Capacity { gpu: Some(GpuReport { count: Some(1), lent }), ..c }
    }

    /// 8 cpus, 32G with `avail` free, 500G disk with `free_disk` free.
    fn cap(avail: u64, free_disk: u64, running: usize) -> Capacity {
        Capacity {
            runtime: true,
            cpus: Some(8),
            mem_total: Some(32 * G),
            mem_available: Some(avail * G),
            disk_free: Some(free_disk * G),
            disk_total: Some(500 * G),
            running,
            caps: None,
            gpu: None,
        }
    }

    fn cand(machine: MachineRef, capacity: Option<Capacity>) -> Candidate {
        Candidate { machine, reachable: true, capacity, has_image: false, has_repo: false }
    }

    fn over_mem(c: Capacity) -> Capacity {
        Capacity { caps: Some(Caps { mem: Some(16 * G), ..Caps::default() }), ..c }
    }

    #[test]
    fn the_rules() {
        struct Case {
            name: &'static str,
            spec: Spec,
            candidates: Vec<Candidate>,
            want: Result<MachineRef, NoPlace>,
            warnings: &'static [&'static str],
        }
        let local = || cand(MachineRef::Local, Some(cap(16, 250, 2)));
        let roomy = || cand(m("big"), Some(cap(28, 450, 0)));
        let pinned = |p: MachineRef| Spec { pinned: Some(p), ..spec() };
        let required = || Spec { gpu: Some(GpuNeed::Required), ..spec() };
        let optional = || Spec { gpu: Some(GpuNeed::Optional), ..spec() };
        let cases = vec![
            Case { name: "more headroom wins", spec: spec(), candidates: vec![local(), roomy()], want: Ok(m("big")), warnings: &[] },
            Case {
                name: "the requester's bias breaks a near tie",
                spec: spec(),
                candidates: vec![cand(MachineRef::Local, Some(cap(16, 250, 2))), cand(m("a"), Some(cap(16, 250, 2)))],
                want: Ok(MachineRef::Local),
                warnings: &[],
            },
            Case {
                name: "a remote requester's own host",
                spec: Spec { requester: m("b"), ..spec() },
                candidates: vec![local(), cand(m("b"), Some(cap(16, 250, 2)))],
                want: Ok(m("b")),
                warnings: &[],
            },
            Case {
                name: "an exact tie goes to the lowest name",
                spec: Spec { requester: m("nobody"), ..spec() },
                candidates: vec![cand(m("b"), Some(cap(16, 250, 2))), cand(m("a"), Some(cap(16, 250, 2)))],
                want: Ok(m("a")),
                warnings: &[],
            },
            Case {
                name: "this host sorts before any machine in a tie",
                spec: Spec { requester: m("nobody"), ..spec() },
                candidates: vec![cand(m("a"), None), cand(MachineRef::Local, None)],
                want: Ok(MachineRef::Local),
                warnings: &[],
            },
            Case {
                name: "an image built beats more headroom",
                spec: spec(),
                candidates: vec![roomy(), Candidate { has_image: true, ..local() }],
                want: Ok(MachineRef::Local),
                warnings: &[],
            },
            Case {
                name: "a repo there tips a close call",
                spec: Spec { requester: m("nobody"), ..spec() },
                candidates: vec![cand(m("a"), Some(cap(20, 250, 1))), Candidate { has_repo: true, ..cand(m("b"), Some(cap(16, 250, 2))) }],
                want: Ok(m("b")),
                warnings: &[],
            },
            Case {
                name: "over a cap ranks below in-cap, even with its image",
                spec: spec(),
                candidates: vec![Candidate { has_image: true, ..cand(MachineRef::Local, Some(over_mem(cap(4, 250, 2)))) }, cand(m("small"), Some(cap(2, 10, 7)))],
                want: Ok(m("small")),
                warnings: &[],
            },
            Case {
                name: "all over cap: the best, warned",
                spec: spec(),
                candidates: vec![cand(MachineRef::Local, Some(over_mem(cap(14, 250, 2)))), cand(m("a"), Some(over_mem(cap(4, 250, 2))))],
                want: Ok(MachineRef::Local),
                warnings: &["this host: over cap: mem 18G/16G"],
            },
            Case {
                name: "unknown capacity is neutral, not zero",
                spec: Spec { requester: m("nobody"), ..spec() },
                candidates: vec![cand(m("a"), Some(cap(4, 40, 6))), cand(m("b"), None)],
                want: Ok(m("b")),
                warnings: &[],
            },
            Case {
                name: "unknown capacity loses to plenty",
                spec: Spec { requester: m("nobody"), ..spec() },
                candidates: vec![cand(m("a"), Some(cap(28, 450, 0))), cand(m("b"), None)],
                want: Ok(m("a")),
                warnings: &[],
            },
            Case {
                name: "an unreachable machine takes no new work",
                spec: spec(),
                candidates: vec![
                    Candidate { reachable: false, ..cand(m("gone"), Some(cap(30, 490, 0))) },
                    local(),
                ],
                want: Ok(MachineRef::Local),
                warnings: &[],
            },
            Case {
                name: "nothing takes new work",
                spec: spec(),
                candidates: vec![Candidate { reachable: false, ..roomy() }, Candidate { reachable: false, ..local() }],
                want: Err(NoPlace::NoCandidate(vec![(m("big"), "unreachable"), (MachineRef::Local, "unreachable")])),
                warnings: &[],
            },
            Case {
                name: "no candidates",
                spec: spec(),
                candidates: vec![],
                want: Err(NoPlace::NoCandidate(vec![])),
                warnings: &[],
            },
            Case { name: "a pin wins over the score", spec: pinned(MachineRef::Local), candidates: vec![roomy(), local()], want: Ok(MachineRef::Local), warnings: &[] },
            Case {
                name: "a pin over cap is warned",
                spec: pinned(m("a")),
                candidates: vec![local(), cand(m("a"), Some(over_mem(cap(4, 250, 2))))],
                want: Ok(m("a")),
                warnings: &["a: over cap: mem 28G/16G"],
            },
            Case {
                name: "a pin on an unreachable machine is refused",
                spec: pinned(m("big")),
                candidates: vec![local(), Candidate { reachable: false, ..roomy() }],
                want: Err(NoPlace::PinUnreachable(m("big"))),
                warnings: &[],
            },
            Case {
                name: "a host without a runtime takes no new work, even as the requester with all the room",
                spec: Spec { requester: m("laptop"), ..spec() },
                candidates: vec![
                    Candidate { has_image: true, ..cand(m("laptop"), Some(Capacity { runtime: false, ..cap(30, 490, 0) })) },
                    cand(m("juchu"), Some(cap(4, 40, 6))),
                ],
                want: Ok(m("juchu")),
                warnings: &[],
            },
            Case {
                name: "only drivers: nothing takes new work",
                spec: spec(),
                candidates: vec![cand(MachineRef::Local, Some(Capacity { runtime: false, ..Capacity::default() })), Candidate { reachable: false, ..roomy() }],
                want: Err(NoPlace::NoCandidate(vec![(MachineRef::Local, "no container runtime"), (m("big"), "unreachable")])),
                warnings: &[],
            },
            Case {
                name: "a pin on a host without a runtime is refused",
                spec: pinned(m("laptop")),
                candidates: vec![local(), cand(m("laptop"), Some(Capacity { runtime: false, ..Capacity::default() }))],
                want: Err(NoPlace::PinNoRuntime(m("laptop"))),
                warnings: &[],
            },
            Case { name: "a pin on an unknown machine is refused", spec: pinned(m("nope")), candidates: vec![local()], want: Err(NoPlace::UnknownPin(m("nope"))), warnings: &[] },
            Case {
                name: "a required GPU goes only where one is lent, however roomy the rest",
                spec: required(),
                candidates: vec![
                    roomy(),
                    cand(m("kept"), Some(gpu(cap(30, 490, 0), false))),
                    cand(m("silent"), None),
                    cand(m("gpu"), Some(gpu(cap(2, 10, 7), true))),
                ],
                want: Ok(m("gpu")),
                warnings: &[],
            },
            Case {
                name: "the requester needs only the GPU, not lending it",
                spec: required(),
                candidates: vec![cand(MachineRef::Local, Some(gpu(cap(2, 10, 7), false))), roomy()],
                want: Ok(MachineRef::Local),
                warnings: &[],
            },
            Case {
                name: "a remote requester's unlent GPU is its own",
                spec: Spec { requester: m("lap"), ..required() },
                candidates: vec![cand(MachineRef::Local, Some(gpu(cap(30, 490, 0), false))), cand(m("lap"), Some(gpu(cap(2, 10, 7), false)))],
                want: Ok(m("lap")),
                warnings: &[],
            },
            Case {
                name: "no GPU anywhere: nothing takes it, each with why",
                spec: Spec { requester: m("nobody"), ..required() },
                candidates: vec![
                    cand(MachineRef::Local, Some(gpu(cap(16, 250, 2), false))),
                    roomy(),
                    cand(m("silent"), None),
                    Candidate { reachable: false, ..cand(m("gone"), Some(gpu(cap(16, 250, 2), true))) },
                ],
                want: Err(NoPlace::NoCandidate(vec![
                    (MachineRef::Local, "GPU not lent"),
                    (m("big"), "no GPU"),
                    (m("silent"), "no GPU"),
                    (m("gone"), "unreachable"),
                ])),
                warnings: &[],
            },
            Case {
                name: "a required GPU pinned where none is: refused",
                spec: Spec { pinned: Some(m("big")), ..required() },
                candidates: vec![local(), roomy()],
                want: Err(NoPlace::PinNoGpu(m("big"), "no GPU")),
                warnings: &[],
            },
            Case {
                name: "a required GPU pinned where it isn't lent: refused",
                spec: Spec { pinned: Some(m("a")), ..required() },
                candidates: vec![local(), cand(m("a"), Some(gpu(cap(16, 250, 2), false)))],
                want: Err(NoPlace::PinNoGpu(m("a"), "GPU not lent")),
                warnings: &[],
            },
            Case {
                name: "a required GPU pinned where it's lent",
                spec: Spec { pinned: Some(m("a")), ..required() },
                candidates: vec![local(), cand(m("a"), Some(gpu(cap(16, 250, 2), true)))],
                want: Ok(m("a")),
                warnings: &[],
            },
            Case {
                name: "an optional GPU prefers a lent one over a built image",
                spec: optional(),
                candidates: vec![Candidate { has_image: true, ..local() }, cand(m("gpu"), Some(gpu(cap(16, 250, 2), true)))],
                want: Ok(m("gpu")),
                warnings: &[],
            },
            Case {
                name: "an optional GPU not lent earns nothing",
                spec: optional(),
                candidates: vec![roomy(), cand(m("kept"), Some(gpu(cap(16, 250, 2), false)))],
                want: Ok(m("big")),
                warnings: &[],
            },
            Case {
                name: "an optional GPU never filters",
                spec: optional(),
                candidates: vec![local()],
                want: Ok(MachineRef::Local),
                warnings: &[],
            },
        ];
        for case in cases {
            let got = place(&case.spec, &case.candidates);
            match (&got, &case.want) {
                (Ok(p), Ok(want)) => {
                    assert_eq!(&p.machine, want, "{}: {p:?}", case.name);
                    assert_eq!(p.warnings, case.warnings, "{}", case.name);
                }
                (got, want) => assert_eq!(got.as_ref().map(|p| &p.machine), want.as_ref(), "{}", case.name),
            }
        }
    }

    #[test]
    fn the_score_and_its_reasons() {
        // 16/32G free (50), 250/500G (50), no instances cap (neutral 50),
        // 2 running of 8 cpus (75): 150 + 100 + 100 + 75.
        let c = cand(MachineRef::Local, Some(cap(16, 250, 2)));
        let (s, reasons) = score(&spec(), &c);
        assert_eq!(s, 425 + REQUESTER);
        assert_eq!(reasons, ["mem 50% free", "disk 50% free", "cpu 75% free", "requester's host"]);
        // Caps narrow the room: mem cap 20G with 16G used is 20%; 2 of 4
        // instances is 50%; a 4-cpu cap with 2 running is 50%.
        let capped = Capacity { caps: Some(Caps { cpus: Some(4), mem: Some(20 * G), disk: None, instances: Some(4) }), ..cap(16, 250, 2) };
        let (s, reasons) = score(&Spec { requester: m("x"), ..spec() }, &Candidate { has_image: true, has_repo: true, ..cand(m("a"), Some(capped)) });
        assert_eq!(s, 3 * 20 + 2 * 50 + 2 * 50 + 50 + IMAGE + REPO);
        assert_eq!(reasons, ["mem 20% free", "disk 50% free", "slots 50% free", "cpu 50% free", "image built", "repo there"]);
        let (s, reasons) = score(&Spec { requester: m("x"), ..spec() }, &cand(m("a"), None));
        assert_eq!(s, (W_MEM + W_DISK + W_SLOTS + W_CPU) * NEUTRAL);
        assert_eq!(reasons, ["no capacity report"]);
        // Over: one penalty per exceeded cap, with the note.
        let over = Capacity { caps: Some(Caps { instances: Some(1), mem: Some(8 * G), ..Caps::default() }), ..cap(16, 250, 2) };
        let (s, reasons) = score(&Spec { requester: m("x"), ..spec() }, &cand(m("a"), Some(over)));
        assert_eq!(s, 2 * 50 + 75 - 2 * OVER, "mem and slots at 0");
        assert!(reasons.contains(&"over cap: mem 16G/8G, instances 2/1".to_string()), "{reasons:?}");
        // An optional GPU there: the bonus; the requester's needn't be lent.
        let opt = Spec { gpu: Some(GpuNeed::Optional), ..spec() };
        let (s, reasons) = score(&Spec { requester: m("x"), ..opt.clone() }, &cand(m("a"), Some(gpu(cap(16, 250, 2), true))));
        assert_eq!((s, reasons.last().map(String::as_str)), (425 + GPU, Some("GPU")));
        let (s, _) = score(&opt, &cand(MachineRef::Local, Some(gpu(cap(16, 250, 2), false))));
        assert_eq!(s, 425 + GPU + REQUESTER);
        // A required one filters instead: no bonus.
        let (s, _) = score(&Spec { gpu: Some(GpuNeed::Required), ..spec() }, &cand(MachineRef::Local, Some(gpu(cap(16, 250, 2), true))));
        assert_eq!(s, 425 + REQUESTER);
    }

    #[test]
    fn reachable_while_the_link_is_up() {
        use LinkState::*;
        for (state, want) in [(Idle, false), (Connecting, false), (Connected, true), (Unreachable, false)] {
            assert_eq!(reachable(state), want, "{state:?}");
        }
    }

    fn root_snapshot(drift: bool, phase: Value) -> Value {
        json!({
            "dir": "/r",
            "sandboxes": [{"name": "web", "config_hash": "c1", "build_hash": "b1", "root": "/r"}, {"name": "api", "config_hash": "c9", "build_hash": "", "root": "/r"}],
            "instances": [
                {"name": "web-1", "sandbox": "web", "root": "/r", "drift": drift, "phase": phase},
                {"name": "other", "sandbox": "web", "root": "/elsewhere", "drift": false},
            ],
        })
    }

    #[test]
    fn has_image_wants_a_ready_matching_instance_from_the_same_root() {
        let ok = root_snapshot(false, Value::Null);
        assert!(has_image(&spec(), [&ok]));
        assert!(has_image(&Spec { build_hash: Some("b1".into()), ..spec() }, [&ok]));
        assert!(!has_image(&Spec { build_hash: Some("b2".into()), ..spec() }, [&ok]), "build hash differs");
        assert!(!has_image(&Spec { config_hash: Some("c2".into()), ..spec() }, [&ok]), "config hash differs");
        assert!(!has_image(&Spec { config_hash: None, ..spec() }, [&ok]), "unknown hash");
        assert!(!has_image(&Spec { sandbox: "api".into(), config_hash: Some("c9".into()), ..spec() }, [&ok]), "no instance of it");
        assert!(!has_image(&spec(), [&root_snapshot(true, Value::Null)]), "drifted");
        assert!(!has_image(&spec(), [&root_snapshot(false, json!({"in_flight": {"step": "build"}}))]), "not ready");
        assert!(!has_image(&spec(), []));
        // Only another root's instance: its image is another root's tag.
        let mut moved = ok.clone();
        moved["instances"][0]["root"] = json!("/x");
        assert!(!has_image(&spec(), [&moved]));
        // No `root` on the sandbox row: the snapshot's `dir`.
        let mut bare = ok.clone();
        bare["sandboxes"][0].as_object_mut().unwrap().remove("root");
        assert!(has_image(&spec(), [&bare]));
    }

    #[test]
    fn candidates_from_the_daemons_state() {
        let ok = root_snapshot(false, Value::Null);
        let local = Candidate::local(&spec(), Some(cap(16, 250, 2)), [&ok]);
        assert_eq!((local.machine, local.reachable, local.has_image), (MachineRef::Local, true, true));

        let mut snap = ok.clone();
        snap["capacity"] = serde_json::to_value(cap(8, 100, 1)).unwrap();
        let w = Machine {
            name: "w".into(),
            kind: MachineKind::Ssh,
            roots: vec![PathBuf::from("/r")],
            state: LinkState::Connected,
            rows: BTreeMap::from([(PathBuf::from("/r"), Arc::new(snap))]),
            ..Machine::default()
        };
        let c = Candidate::from_machine(&spec(), &w);
        assert_eq!((c.machine.clone(), c.reachable, c.has_image, c.has_repo), (m("w"), true, true, false));
        assert_eq!(c.capacity.as_ref().map(|c| c.running), Some(1));
        // Its link down: unreachable.
        let bare = Machine { name: "s".into(), state: LinkState::Idle, ..Machine::default() };
        let c = Candidate::from_machine(&spec(), &bare);
        assert_eq!((c.reachable, c.capacity, c.has_image), (false, None, false));
        // An inbound one: the same rules.
        let inbound = Machine { kind: MachineKind::Inbound, ..w.clone() };
        let c = Candidate::from_machine(&spec(), &inbound);
        assert_eq!((c.reachable, c.has_image), (true, true));
        // Connected without a report: neutral.
        let fresh = Machine { name: "f".into(), state: LinkState::Connected, ..Machine::default() };
        let c = Candidate::from_machine(&spec(), &fresh);
        assert_eq!((c.reachable, c.capacity), (true, None));
        let down = Machine { state: LinkState::Idle, ..w };
        assert!(!Candidate::from_machine(&spec(), &down).reachable);
    }

    #[test]
    fn no_place_says_why() {
        assert_eq!(NoPlace::UnknownPin(m("x")).to_string(), "no machine `x`");
        assert_eq!(NoPlace::PinUnreachable(m("x")).to_string(), "x is unreachable");
        assert_eq!(NoPlace::PinNoRuntime(m("x")).to_string(), "x has no container runtime");
        assert_eq!(NoPlace::PinNoGpu(m("x"), "GPU not lent").to_string(), "x can't take a required GPU (GPU not lent)");
        assert_eq!(NoPlace::NoCandidate(vec![]).to_string(), "no machine to place on");
        assert_eq!(
            NoPlace::NoCandidate(vec![(m("a"), "unreachable"), (MachineRef::Local, "unreachable")]).to_string(),
            "no machine takes new work (a: unreachable, this host: unreachable)"
        );
    }
}