zc2 0.0.45

P2P compute broker with credit-based 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
//! Lending capacity to the hub (zc#472). Opt-in slice of this machine (RAM,
//! GPU memory, disk) for the hub's own workloads, as distinct from what the
//! node sells on the marketplace.
//!
//! Contract: zak-marketplace `docs/specs/2026-10-13-hub-allocated-resources-design.md` §b.
//!
//!   zc hub allocate --enable [--vram 8G] [--ram 16G] [--disk 50G] [--purpose inference,warmup]
//!   zc hub allocate --disable
//!   zc hub allocate                 (prints the setting)
//!
//! Persisted as `[hub_allocation]` in `<state_dir>/config.toml`; the other
//! sections of that file are kept (parsed and written back as TOML tables).

pub mod claim;

use std::path::{Path, PathBuf};

use serde::{Deserialize, Deserializer, Serialize};
use serde_json::{json, Value};

pub const PURPOSES: [&str; 2] = ["inference", "warmup"];

fn whole_gb<'de, D: Deserializer<'de>>(d: D) -> Result<u64, D::Error> {
    let v = f64::deserialize(d)?;
    Ok(if v.is_finite() && v > 0.0 {
        v.floor() as u64
    } else {
        0
    })
}

fn default_purpose() -> Vec<String> {
    vec!["inference".to_string()]
}

/// The `[hub_allocation]` section. Sizes are whole gigabytes.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct HubAllocation {
    pub enabled: bool,
    #[serde(default, deserialize_with = "whole_gb")]
    pub vram_gb: u64,
    #[serde(default, deserialize_with = "whole_gb")]
    pub ram_gb: u64,
    #[serde(default, deserialize_with = "whole_gb")]
    pub disk_gb: u64,
    #[serde(default = "default_purpose")]
    pub purpose: Vec<String>,
}

impl HubAllocation {
    /// The `hub_allocation` value of the register payload.
    pub fn to_payload(&self) -> Value {
        json!({
            "enabled": self.enabled,
            "vram_gb": self.vram_gb,
            "ram_gb": self.ram_gb,
            "disk_gb": self.disk_gb,
            "purpose": self.purpose,
        })
    }
}

/// What this node can actually lend, whole GB. Sized from what workers can
/// serve (the VM/cgroup memory limit, the writable disk, CUDA VRAM), not from
/// the host totals: a Mac's unified memory is not VRAM, and Docker Desktop's VM
/// holds less RAM than the Mac.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Machine {
    pub vram_gb: u64,
    pub ram_gb: u64,
    pub disk_gb: u64,
}

const GIB: u64 = 1 << 30;

/// VRAM of CUDA devices only. Other vendors (Apple unified memory) count 0.
fn cuda_vram_bytes(gpus: &[crate::bench_node::fingerprint::GpuId]) -> u64 {
    gpus.iter()
        .filter(|g| g.vendor.eq_ignore_ascii_case("nvidia"))
        .map(|g| g.vram_bytes)
        .sum()
}

/// Smallest known (non-zero) limit, in bytes; 0 when none is known.
fn tightest(limits: &[u64]) -> u64 {
    limits.iter().copied().filter(|&l| l > 0).min().unwrap_or(0)
}

/// Linux cgroup memory limit in bytes (v2 then v1); 0 when unlimited or absent.
fn cgroup_memory_limit_bytes() -> u64 {
    for path in [
        "/sys/fs/cgroup/memory.max",
        "/sys/fs/cgroup/memory/memory.limit_in_bytes",
    ] {
        if let Ok(t) = std::fs::read_to_string(path) {
            // "max" (v2) or a near-u64::MAX sentinel (v1) means unlimited.
            if let Ok(v) = t.trim().parse::<u64>() {
                if v < (1u64 << 60) {
                    return v;
                }
            }
        }
    }
    0
}

/// Memory of the Docker daemon's VM/host (`docker info`), bounded by the probe
/// timeout so a hung daemon cannot stall `zc hub allocate`. 0 when unknown.
fn docker_memory_bytes() -> u64 {
    use crate::broker::deploy::runtime::{run_bounded, CliOutcome, PROBE_TIMEOUT};
    let (outcome, out) = run_bounded(
        std::process::Command::new("docker").args(["info", "--format", "{{.MemTotal}}"]),
        PROBE_TIMEOUT,
    );
    match outcome {
        CliOutcome::Exited { success: true, .. } => out.trim().parse().unwrap_or(0),
        _ => 0,
    }
}

impl Machine {
    pub fn detect() -> Machine {
        let vram = crate::bench_node::run::enumerate_with_timeout(
            &std::sync::atomic::AtomicBool::new(false),
        )
        .map(|g| cuda_vram_bytes(&g))
        .unwrap_or(0);
        let host_ram = (crate::spaces::schedule::memory_gb() * GIB as f64) as u64;
        let ram = match tightest(&[cgroup_memory_limit_bytes(), docker_memory_bytes()]) {
            0 => host_ram,
            limit if host_ram > 0 => limit.min(host_ram),
            limit => limit,
        };
        Machine {
            vram_gb: vram / GIB,
            ram_gb: ram / GIB,
            disk_gb: disk_usable_gb(),
        }
    }

    /// A quarter of what the node can lend, rounded down to a whole GB.
    pub fn quarter(&self) -> (u64, u64, u64) {
        (self.vram_gb / 4, self.ram_gb / 4, self.disk_gb / 4)
    }
}

/// Writable size (used + available, i.e. without the filesystem's reserved
/// blocks) of the filesystem holding the state directory, whole GB (0 unknown).
fn disk_usable_gb() -> u64 {
    let dir = crate::credentials::dir().unwrap_or_else(|| PathBuf::from("."));
    let target = if dir.exists() {
        dir
    } else {
        PathBuf::from("/")
    };
    std::process::Command::new("df")
        .arg("-Pk")
        .arg(target)
        .output()
        .ok()
        .and_then(|o| parse_df_usable_gb(&String::from_utf8_lossy(&o.stdout)))
        .unwrap_or(0)
}

/// Used + available of the first data row of `df -Pk` output, in whole GB.
fn parse_df_usable_gb(out: &str) -> Option<u64> {
    let row = out.lines().nth(1)?;
    let mut f = row.split_whitespace().skip(2);
    let used: u64 = f.next()?.parse().ok()?;
    let avail: u64 = f.next()?.parse().ok()?;
    Some((used + avail) / 1024 / 1024)
}

// ---- config.toml ----------------------------------------------------------

pub fn config_path(dir: &Path) -> PathBuf {
    dir.join("config.toml")
}

fn read_table(dir: &Path) -> toml::value::Table {
    std::fs::read_to_string(config_path(dir))
        .ok()
        .and_then(|t| t.parse::<toml::Value>().ok())
        .and_then(|v| match v {
            toml::Value::Table(t) => Some(t),
            _ => None,
        })
        .unwrap_or_default()
}

/// The saved section, `None` when the file or section is missing or invalid.
pub fn load(dir: &Path) -> Option<HubAllocation> {
    read_table(dir)
        .get("hub_allocation")?
        .clone()
        .try_into()
        .ok()
}

/// Write the section, keeping every other section of `config.toml`.
pub fn save(dir: &Path, a: &HubAllocation) -> Result<(), String> {
    let mut table = read_table(dir);
    let v = toml::Value::try_from(a).map_err(|e| e.to_string())?;
    table.insert("hub_allocation".to_string(), v);
    std::fs::create_dir_all(dir).map_err(|e| e.to_string())?;
    let text = toml::to_string_pretty(&toml::Value::Table(table)).map_err(|e| e.to_string())?;
    let tmp = dir.join("config.toml.tmp");
    std::fs::write(&tmp, text).map_err(|e| e.to_string())?;
    std::fs::rename(&tmp, config_path(dir)).map_err(|e| e.to_string())
}

// ---- CLI -------------------------------------------------------------------

#[derive(Debug, Clone, PartialEq)]
pub enum Cmd {
    Show,
    Disable,
    Enable {
        vram_gb: Option<u64>,
        ram_gb: Option<u64>,
        disk_gb: Option<u64>,
        purpose: Option<Vec<String>>,
    },
}

/// `8G`, `8GB`, `8g`, or a bare `8` -> whole GB. Fractions and other units
/// are refused: the hub records whole gigabytes.
pub fn parse_gb(s: &str) -> Result<u64, String> {
    let t = s.trim().to_ascii_lowercase();
    let t = t
        .strip_suffix("gb")
        .or_else(|| t.strip_suffix('g'))
        .unwrap_or(&t);
    t.trim()
        .parse::<u64>()
        .map_err(|_| format!("'{s}' is not a size in whole GB (e.g. 8G)"))
}

pub fn parse_purpose(s: &str) -> Result<Vec<String>, String> {
    let mut out: Vec<String> = Vec::new();
    for p in s.split(',').map(|p| p.trim().to_ascii_lowercase()) {
        if !PURPOSES.contains(&p.as_str()) {
            return Err(format!(
                "unknown purpose '{p}' (choose from {})",
                PURPOSES.join(", ")
            ));
        }
        if !out.contains(&p) {
            out.push(p);
        }
    }
    Ok(out)
}

/// Parse what follows `zc hub allocate`.
pub fn parse_args(args: &[String]) -> Result<Cmd, String> {
    let (mut enable, mut disable) = (false, false);
    let (mut vram, mut ram, mut disk, mut purpose) = (None, None, None, None);
    let mut it = args.iter();
    while let Some(a) = it.next() {
        let (flag, inline) = match a.split_once('=') {
            Some((f, v)) => (f, Some(v.to_string())),
            None => (a.as_str(), None),
        };
        let mut value = |name: &str| -> Result<String, String> {
            inline
                .clone()
                .or_else(|| it.next().cloned())
                .ok_or_else(|| format!("{name} needs a value"))
        };
        match flag {
            "--enable" => enable = true,
            "--disable" => disable = true,
            "--vram" => vram = Some(parse_gb(&value("--vram")?)?),
            "--ram" => ram = Some(parse_gb(&value("--ram")?)?),
            "--disk" => disk = Some(parse_gb(&value("--disk")?)?),
            "--purpose" => purpose = Some(parse_purpose(&value("--purpose")?)?),
            other => return Err(format!("unknown argument '{other}'")),
        }
    }
    let sized = vram.is_some() || ram.is_some() || disk.is_some() || purpose.is_some();
    match (enable, disable) {
        (true, true) => Err("--enable and --disable are mutually exclusive".to_string()),
        (false, true) if sized => Err("--disable takes no size or purpose flags".to_string()),
        (false, true) => Ok(Cmd::Disable),
        (true, false) => Ok(Cmd::Enable {
            vram_gb: vram,
            ram_gb: ram,
            disk_gb: disk,
            purpose,
        }),
        (false, false) if sized => Err("size and purpose flags need --enable".to_string()),
        (false, false) => Ok(Cmd::Show),
    }
}

/// Refuse a slice larger than what the node can lend. VRAM is always checked (a machine
/// with no GPU lends none); RAM and disk are skipped when the machine total
/// could not be measured (0).
pub fn validate(a: &HubAllocation, m: &Machine) -> Result<(), String> {
    if a.vram_gb > m.vram_gb {
        return Err(format!(
            "--vram {}G is more than this node can lend: GPU memory (CUDA VRAM) is {}G",
            a.vram_gb, m.vram_gb
        ));
    }
    if m.ram_gb > 0 && a.ram_gb > m.ram_gb {
        return Err(format!(
            "--ram {}G is more than this node can lend: usable memory is {}G",
            a.ram_gb, m.ram_gb
        ));
    }
    if m.disk_gb > 0 && a.disk_gb > m.disk_gb {
        return Err(format!(
            "--disk {}G is more than this node can lend: usable disk is {}G",
            a.disk_gb, m.disk_gb
        ));
    }
    if a.purpose.is_empty() {
        return Err("purpose must name at least one of inference, warmup".to_string());
    }
    Ok(())
}

/// The section `--enable` produces: given flags win, then the saved section,
/// then a quarter of what the node can lend (first enable only). Purpose defaults to
/// `inference`.
pub fn enabled_from(
    existing: Option<&HubAllocation>,
    cmd: &Cmd,
    m: &Machine,
) -> Result<HubAllocation, String> {
    let Cmd::Enable {
        vram_gb,
        ram_gb,
        disk_gb,
        purpose,
    } = cmd
    else {
        return Err("not an --enable command".to_string());
    };
    let (qv, qr, qd) = m.quarter();
    let a = HubAllocation {
        enabled: true,
        vram_gb: vram_gb.or(existing.map(|e| e.vram_gb)).unwrap_or(qv),
        ram_gb: ram_gb.or(existing.map(|e| e.ram_gb)).unwrap_or(qr),
        disk_gb: disk_gb.or(existing.map(|e| e.disk_gb)).unwrap_or(qd),
        purpose: purpose
            .clone()
            .or_else(|| existing.map(|e| e.purpose.clone()))
            .unwrap_or_else(default_purpose),
    };
    validate(&a, m)?;
    Ok(a)
}

pub fn describe(a: Option<&HubAllocation>) -> String {
    match a {
        None => "Hub allocation: not set (lend capacity with `zc hub allocate --enable`)".into(),
        Some(a) if !a.enabled => "Hub allocation: disabled".into(),
        Some(a) => format!(
            "Hub allocation: enabled\n  vram: {}G\n  ram:  {}G\n  disk: {}G\n  purpose: {}",
            a.vram_gb,
            a.ram_gb,
            a.disk_gb,
            a.purpose.join(", ")
        ),
    }
}

/// Run a parsed command against `dir`. Returns the text to print.
pub fn execute(dir: &Path, cmd: &Cmd, m: &Machine) -> Result<String, String> {
    let existing = load(dir);
    match cmd {
        Cmd::Show => Ok(describe(existing.as_ref())),
        Cmd::Disable => match existing {
            None => Ok(describe(None)),
            Some(mut a) => {
                a.enabled = false;
                save(dir, &a)?;
                Ok("Hub allocation disabled. The hub is told on the next broker sync.".into())
            }
        },
        Cmd::Enable { .. } => {
            let a = enabled_from(existing.as_ref(), cmd, m)?;
            save(dir, &a)?;
            Ok(format!(
                "{}\nThe hub is told on the next broker sync; restart the broker if it is not running.",
                describe(Some(&a))
            ))
        }
    }
}

/// `zc hub allocate ...`. Returns the exit code.
pub fn run_cli(args: &[String]) -> i32 {
    if args.first().map(String::as_str) != Some("allocate") {
        eprintln!("usage: zc hub allocate [--enable [--vram 8G] [--ram 16G] [--disk 50G] [--purpose inference,warmup] | --disable]");
        return 2;
    }
    let cmd = match parse_args(&args[1..]) {
        Ok(c) => c,
        Err(e) => {
            eprintln!("Error: {e}");
            return 2;
        }
    };
    let Some(dir) = crate::credentials::dir() else {
        eprintln!("Error: no state directory (set HOME or ZAKURO_HOME)");
        return 1;
    };
    let machine = if matches!(cmd, Cmd::Enable { .. }) {
        Machine::detect()
    } else {
        Machine {
            vram_gb: 0,
            ram_gb: 0,
            disk_gb: 0,
        }
    };
    match execute(&dir, &cmd, &machine) {
        Ok(t) => {
            println!("{t}");
            0
        }
        Err(e) => {
            eprintln!("Error: {e}");
            1
        }
    }
}

// ---- register response -----------------------------------------------------

/// Apply the `hub_allocation` object a register response may carry (a change
/// made from the Hub). The Hub owns `enabled` and `purpose`; sizes are the
/// machine's call and are only taken when there is no local section yet.
/// Returns the new section when it differs from `local`.
pub fn merge_from_hub(
    local: Option<&HubAllocation>,
    remote: &Value,
    m: &Machine,
) -> Option<HubAllocation> {
    let obj = remote.as_object()?;
    let enabled = obj.get("enabled").and_then(Value::as_bool);
    let purpose = obj
        .get("purpose")
        .and_then(Value::as_array)
        .map(|a| {
            a.iter()
                .filter_map(Value::as_str)
                .filter(|p| PURPOSES.contains(p))
                .map(String::from)
                .collect::<Vec<_>>()
        })
        .filter(|p| !p.is_empty());
    let next = match local {
        Some(l) => HubAllocation {
            enabled: enabled.unwrap_or(l.enabled),
            purpose: purpose.unwrap_or_else(|| l.purpose.clone()),
            ..l.clone()
        },
        None => {
            let enabled = enabled?;
            let (qv, qr, qd) = m.quarter();
            let gb = |k: &str, d: u64| {
                obj.get(k)
                    .and_then(Value::as_f64)
                    .map(|v| v.max(0.0).floor() as u64)
                    .unwrap_or(d)
            };
            HubAllocation {
                enabled,
                vram_gb: gb("vram_gb", qv),
                ram_gb: gb("ram_gb", qr),
                disk_gb: gb("disk_gb", qd),
                purpose: purpose.unwrap_or_else(default_purpose),
            }
        }
    };
    if Some(&next) == local || validate(&next, m).is_err() {
        return None;
    }
    Some(next)
}

/// Called by `node_sync::register_node` with the response body.
pub fn apply_register_response(dir: &Path, body: &str) {
    let Ok(v) = serde_json::from_str::<Value>(body) else {
        return;
    };
    let Some(remote) = v.get("hub_allocation") else {
        return;
    };
    let local = load(dir);
    let machine = Machine::detect();
    if let Some(next) = merge_from_hub(local.as_ref(), remote, &machine) {
        match save(dir, &next) {
            Ok(()) => println!(
                "  [HUB_ALLOC] hub changed the opt-in: {}",
                if next.enabled { "enabled" } else { "disabled" }
            ),
            Err(e) => eprintln!("  [HUB_ALLOC] could not save the hub's change: {e}"),
        }
    }
}

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

    fn argv(a: &[&str]) -> Vec<String> {
        a.iter().map(|s| s.to_string()).collect()
    }
    fn machine() -> Machine {
        Machine {
            vram_gb: 24,
            ram_gb: 64,
            disk_gb: 1000,
        }
    }
    fn tmp() -> PathBuf {
        let d = std::env::temp_dir().join(format!(
            "zc-huballoc-{}-{}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        std::fs::create_dir_all(&d).unwrap();
        d
    }

    #[test]
    fn parses_sizes() {
        assert_eq!(parse_gb("8G"), Ok(8));
        assert_eq!(parse_gb("16gb"), Ok(16));
        assert_eq!(parse_gb("50"), Ok(50));
        assert!(parse_gb("1.5G").is_err());
        assert!(parse_gb("8T").is_err());
    }

    #[test]
    fn parses_commands() {
        assert_eq!(parse_args(&[]), Ok(Cmd::Show));
        assert_eq!(parse_args(&argv(&["--disable"])), Ok(Cmd::Disable));
        assert_eq!(
            parse_args(&argv(&[
                "--enable",
                "--vram",
                "8G",
                "--ram=16G",
                "--purpose",
                "inference,warmup"
            ])),
            Ok(Cmd::Enable {
                vram_gb: Some(8),
                ram_gb: Some(16),
                disk_gb: None,
                purpose: Some(argv(&["inference", "warmup"])),
            })
        );
        assert!(parse_args(&argv(&["--enable", "--disable"])).is_err());
        assert!(parse_args(&argv(&["--vram", "8G"])).is_err());
        assert!(parse_args(&argv(&["--disable", "--ram", "1G"])).is_err());
        assert!(parse_args(&argv(&["--enable", "--purpose", "batch"])).is_err());
        assert!(parse_args(&argv(&["--enable", "--vram"])).is_err());
        assert!(parse_args(&argv(&["--bogus"])).is_err());
    }

    #[test]
    fn first_enable_defaults_to_a_quarter_rounded_down() {
        let m = Machine {
            vram_gb: 10,
            ram_gb: 66,
            disk_gb: 999,
        };
        let cmd = parse_args(&argv(&["--enable"])).unwrap();
        let a = enabled_from(None, &cmd, &m).unwrap();
        assert_eq!((a.vram_gb, a.ram_gb, a.disk_gb), (2, 16, 249));
        assert_eq!(a.purpose, vec!["inference"]);
        assert!(a.enabled);
    }

    #[test]
    fn re_enable_keeps_saved_sizes_unless_overridden() {
        let saved = HubAllocation {
            enabled: false,
            vram_gb: 8,
            ram_gb: 16,
            disk_gb: 50,
            purpose: argv(&["warmup"]),
        };
        let cmd = parse_args(&argv(&["--enable", "--ram", "32G"])).unwrap();
        let a = enabled_from(Some(&saved), &cmd, &machine()).unwrap();
        assert_eq!((a.vram_gb, a.ram_gb, a.disk_gb), (8, 32, 50));
        assert_eq!(a.purpose, vec!["warmup"]);
    }

    #[test]
    fn refuses_a_slice_larger_than_the_machine() {
        for flags in [
            ["--enable", "--vram", "48G"],
            ["--enable", "--ram", "128G"],
            ["--enable", "--disk", "2000G"],
        ] {
            let cmd = parse_args(&argv(&flags)).unwrap();
            assert!(enabled_from(None, &cmd, &machine()).is_err(), "{flags:?}");
        }
    }

    #[test]
    fn config_round_trips_and_keeps_other_sections() {
        let d = tmp();
        std::fs::write(config_path(&d), "[broker]\nport = 7000\n").unwrap();
        assert_eq!(load(&d), None);
        let a = HubAllocation {
            enabled: true,
            vram_gb: 8,
            ram_gb: 16,
            disk_gb: 50,
            purpose: argv(&["inference", "warmup"]),
        };
        save(&d, &a).unwrap();
        assert_eq!(load(&d), Some(a));
        let text = std::fs::read_to_string(config_path(&d)).unwrap();
        assert!(
            text.contains("[broker]") && text.contains("[hub_allocation]"),
            "{text}"
        );
        let _ = std::fs::remove_dir_all(d);
    }

    #[test]
    fn execute_enable_show_disable() {
        let d = tmp();
        let m = machine();
        let out = execute(
            &d,
            &parse_args(&argv(&["--enable", "--vram", "8G"])).unwrap(),
            &m,
        )
        .unwrap();
        assert!(out.contains("enabled") && out.contains("8G"), "{out}");
        assert!(load(&d).unwrap().enabled);
        execute(&d, &Cmd::Disable, &m).unwrap();
        let a = load(&d).unwrap();
        assert!(!a.enabled);
        assert_eq!(a.vram_gb, 8, "disable keeps the sizes");
        assert!(execute(&d, &Cmd::Show, &m).unwrap().contains("disabled"));
        let _ = std::fs::remove_dir_all(d);
    }

    #[test]
    fn deserializes_decimal_sizes_by_rounding_down() {
        let a: HubAllocation =
            serde_json::from_str(r#"{"enabled":true,"vram_gb":8.9,"ram_gb":16}"#).unwrap();
        assert_eq!((a.vram_gb, a.ram_gb, a.disk_gb), (8, 16, 0));
        assert_eq!(a.purpose, vec!["inference"]);
    }

    #[test]
    fn hub_change_flips_enabled_but_not_sizes() {
        let local = HubAllocation {
            enabled: true,
            vram_gb: 8,
            ram_gb: 16,
            disk_gb: 50,
            purpose: argv(&["inference"]),
        };
        let remote = json!({"enabled": false, "vram_gb": 20, "purpose": ["inference","warmup"]});
        let n = merge_from_hub(Some(&local), &remote, &machine()).unwrap();
        assert!(!n.enabled);
        assert_eq!(n.vram_gb, 8);
        assert_eq!(n.purpose, argv(&["inference", "warmup"]));
        assert_eq!(
            merge_from_hub(Some(&local), &json!({"enabled": true}), &machine()),
            None
        );
    }

    #[test]
    fn hub_enable_without_local_section_uses_a_quarter() {
        let n = merge_from_hub(None, &json!({"enabled": true}), &machine()).unwrap();
        assert_eq!((n.vram_gb, n.ram_gb, n.disk_gb), (6, 16, 250));
        assert_eq!(merge_from_hub(None, &json!({}), &machine()), None);
    }

    #[test]
    fn df_output_is_parsed() {
        let out =
            "Filesystem 1024-blocks Used Available Capacity Mounted on\n/dev/x 976490576 1 2 3% /\n";
        assert_eq!(parse_df_usable_gb(out), Some(0));
        let out = "Filesystem 1024-blocks Used Available Capacity Mounted on\n/dev/x 976490576 400000000 570000000 41% /\n";
        // 970000000 KiB: the reserved blocks (6490576) are not lendable.
        assert_eq!(parse_df_usable_gb(out), Some(925));
    }

    fn gpu(vendor: &str, gib: u64) -> crate::bench_node::fingerprint::GpuId {
        crate::bench_node::fingerprint::GpuId {
            vendor: vendor.into(),
            model: "m".into(),
            uuid: "u".into(),
            vram_bytes: gib * GIB,
        }
    }

    #[test]
    fn apple_unified_memory_is_not_vram() {
        assert_eq!(cuda_vram_bytes(&[gpu("apple", 16)]), 0);
        assert_eq!(
            cuda_vram_bytes(&[gpu("apple", 16), gpu("nvidia", 24), gpu("nvidia", 8)]),
            32 * GIB
        );
        assert_eq!(cuda_vram_bytes(&[]), 0);
    }

    #[test]
    fn tightest_limit_ignores_unknowns() {
        assert_eq!(tightest(&[0, 0]), 0);
        assert_eq!(tightest(&[0, 3 * GIB]), 3 * GIB);
        assert_eq!(tightest(&[8 * GIB, 3 * GIB]), 3 * GIB);
    }

    #[test]
    fn no_gpu_node_defaults_vram_zero_and_refuses_explicit_vram() {
        let m = Machine {
            vram_gb: 0,
            ram_gb: 3,
            disk_gb: 170,
        };
        let cmd = Cmd::Enable {
            vram_gb: None,
            ram_gb: None,
            disk_gb: None,
            purpose: None,
        };
        let a = enabled_from(None, &cmd, &m).unwrap();
        assert_eq!((a.vram_gb, a.ram_gb, a.disk_gb), (0, 0, 42));
        let big = Cmd::Enable {
            vram_gb: Some(2),
            ram_gb: Some(4),
            disk_gb: Some(231),
            purpose: None,
        };
        let e = enabled_from(None, &big, &m).unwrap_err();
        assert!(e.contains("--vram"), "{e}");
        let e = enabled_from(
            None,
            &Cmd::Enable {
                vram_gb: None,
                ram_gb: Some(4),
                disk_gb: None,
                purpose: None,
            },
            &m,
        )
        .unwrap_err();
        assert!(e.contains("--ram"), "{e}");
        let e = enabled_from(
            None,
            &Cmd::Enable {
                vram_gb: None,
                ram_gb: None,
                disk_gb: Some(231),
                purpose: None,
            },
            &m,
        )
        .unwrap_err();
        assert!(e.contains("--disk"), "{e}");
    }
}