zc2 0.0.46

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
//! `zc bench node` and `zc price recommend|auto`.
use std::io::{BufRead, IsTerminal, Write};
use std::sync::atomic::AtomicBool;
use std::sync::Arc;
use std::time::Duration;

use super::report::BenchReport;
use super::run::{self, RunCtx, RunOpts, RunOutcome};
use super::submit::{self, SubmitError};
use crate::broker::node_identity::NodeKey;

#[derive(Debug, Default, PartialEq)]
pub struct NodeArgs {
    pub json: bool,
    pub quick: bool,
    pub submit: bool,
    pub no_gpu: bool,
}

pub const NODE_USAGE: &str = "Usage: zc bench node [--json] [--quick] [--submit] [--no-gpu]
  --json     print the signed report and the parsed report; no submit unless --submit
  --quick    20 s budget instead of 60 s
  --submit   send the report to the hub without asking
  --no-gpu   skip the GPU probe";

pub fn parse_node_args(args: &[String]) -> Result<NodeArgs, String> {
    let mut a = NodeArgs::default();
    for arg in args {
        match arg.as_str() {
            "--json" => a.json = true,
            "--quick" => a.quick = true,
            "--submit" => a.submit = true,
            "--no-gpu" => a.no_gpu = true,
            other => return Err(format!("unknown option '{other}' for `zc bench node`")),
        }
    }
    Ok(a)
}

/// Hub address and key, from `~/.zakuro/credentials` or the environment.
fn hub_credentials() -> Option<(String, String)> {
    crate::credentials::load_into_env();
    let key = std::env::var("ZAKURO_API_KEY")
        .ok()
        .filter(|k| !k.is_empty())?;
    Some((crate::credentials::default_api_url(), key))
}

/// `zc bench node [flags]`; returns the process exit code.
pub fn run(args: &[String]) -> i32 {
    if args.iter().any(|a| a == "-h" || a == "--help") {
        println!("{NODE_USAGE}");
        return 0;
    }
    let a = match parse_node_args(args) {
        Ok(a) => a,
        Err(e) => {
            eprintln!("Error: {e}\n{NODE_USAGE}");
            return 2;
        }
    };
    let Some(state_dir) = crate::credentials::dir() else {
        eprintln!("Error: no HOME or ZAKURO_HOME for the benchmark's scratch files");
        return 1;
    };
    let creds = hub_credentials();
    let key = NodeKey::load_or_create();
    // Saved as declined until the owner agrees, so a running broker cannot
    // send it while the prompt is open (or after a "no").
    let opts = RunOpts {
        save_as: run::SubmitState::Declined,
        budget: Duration::from_secs(if a.quick { 20 } else { 60 }),
        no_gpu: a.no_gpu,
        state_dir: state_dir.clone(),
        hub_url: creds.as_ref().map(|c| c.0.clone()),
        peers: vec![],
    };
    let progress = |probe: &str| eprintln!("  measuring {probe}...");
    let outcome = run::run(
        &opts,
        &mut RunCtx {
            key: &key,
            cancel: Arc::new(AtomicBool::new(false)),
            progress: &progress,
            submit: None,
        },
    );
    let (signed, report) = match outcome {
        RunOutcome::Cancelled => {
            eprintln!("The benchmark was cancelled before it finished; nothing was saved.");
            return 1;
        }
        RunOutcome::AlreadyRunning => {
            eprintln!("A benchmark is already running on this node; wait for it to finish.");
            return 1;
        }
        RunOutcome::Completed { signed, report, .. } => (signed, report),
    };

    if a.json {
        let out = serde_json::json!({ "signed": signed, "report": *report });
        println!("{}", serde_json::to_string_pretty(&out).unwrap_or_default());
    } else {
        print!("{}", render(&report));
    }

    let send = if a.submit {
        true
    } else if a.json || !std::io::stdin().is_terminal() {
        false
    } else {
        confirm("Submit to the hub? [Y/n] ")
    };
    if !send {
        return 0;
    }
    let Some((api_url, api_key)) = creds else {
        eprintln!("Not submitted: this Mac is not signed in (run `zc login`).");
        return 1;
    };
    match submit::post(&api_url, &api_key, &signed) {
        Ok(_) => {
            let _ = run::save_last(&state_dir, &signed, run::SubmitState::Done);
            eprintln!("Submitted to the hub.");
            0
        }
        Err(e) => {
            eprintln!("Not submitted: {e}");
            match e {
                SubmitError::Retryable(_) => {
                    // The owner agreed: hand it to a running broker to retry.
                    let _ = run::save_last(&state_dir, &signed, run::SubmitState::Pending);
                    eprintln!("The report is saved; a running broker will retry it.");
                }
                // Refused: a running broker re-measures later instead of
                // treating this hardware as done.
                SubmitError::Rejected(code, _) => {
                    let _ = run::save_last(&state_dir, &signed, run::SubmitState::Rejected(code));
                }
            }
            1
        }
    }
}

fn confirm(prompt: &str) -> bool {
    eprint!("{prompt}");
    let _ = std::io::stderr().flush();
    let mut line = String::new();
    if std::io::stdin().lock().read_line(&mut line).is_err() {
        return false;
    }
    !matches!(line.trim().to_lowercase().as_str(), "n" | "no")
}

fn opt(v: Option<f64>, unit: &str) -> String {
    v.map(|v| format!("{v:.1} {unit}"))
        .unwrap_or_else(|| "n/a".into())
}

/// The human-readable result table.
pub fn render(r: &BenchReport) -> String {
    let mut out = String::new();
    if let Some(c) = &r.cpu {
        out += &format!(
            "CPU      {:.1} GFLOPS f32 ยท {:.1} f64 ยท {:.1} single-thread\n",
            c.gflops_f32, c.gflops_f64, c.gflops_f32_1t
        );
        out += &format!("Memory   {:.1} GB/s\n", c.mem_bw_gbps);
        if !r.numa_mem.is_empty() {
            let per: Vec<String> = r
                .numa_mem
                .iter()
                .map(|n| format!("node{} {:.1} GB", n.node, n.mem_bytes as f64 / 1e9))
                .collect();
            out += &format!("NUMA     {}\n", per.join(" ยท "));
        }
    } else {
        out += "CPU      not measured\n";
    }
    for g in &r.gpus {
        out += &format!(
            "GPU      {} ยท {:.2} TFLOPS fp32 ยท {:.2} fp16 ยท {:.1} GB/s\n",
            g.model, g.tflops_f32, g.tflops_f16, g.mem_bw_gbps
        );
    }
    if r.gpus.is_empty() {
        out += "GPU      none measured\n";
    }
    match &r.disk {
        Some(d) => {
            out += &format!(
                "Disk     {:.0} MB/s write ยท {:.0} MB/s read\n",
                d.write_mbps, d.read_mbps
            )
        }
        None => out += "Disk     not measured\n",
    }
    match &r.net {
        Some(n) => {
            out += &format!(
                "Network  hub {} ยท peers {} ยท {}\n",
                opt(n.hub_rtt_ms, "ms"),
                opt(n.peer_rtt_ms_p50, "ms"),
                opt(n.mbps, "Mbit/s")
            )
        }
        None => out += "Network  not measured\n",
    }
    out += &format!("Units    {:.2} CPU", r.cpu_units);
    if let Some(g) = r.gpu_units {
        out += &format!(" ยท {g:.2} GPU");
    }
    out += "\n";
    if r.partial {
        out += "(partial run: the time budget ran out)\n";
    }
    for s in &r.skipped {
        out += &format!("skipped: {s}\n");
    }
    out
}

/// What `zc price recommend` prints for a recommendation and the current price.
pub fn render_recommendation(rec: &serde_json::Value, current: Option<PriceView>) -> String {
    let f = |k: &str| rec.get(k).and_then(|v| v.as_f64());
    let n = |k: &str| {
        f(k).map(|v| format!("{v:.2}"))
            .unwrap_or_else(|| "n/a".into())
    };
    let class = rec
        .get("class")
        .and_then(|v| v.as_str())
        .unwrap_or("cpu")
        .to_uppercase();
    let basis = rec
        .get("basis")
        .and_then(|v| v.as_str())
        .unwrap_or("unknown");
    let samples = rec.get("sample_size").and_then(|v| v.as_u64()).unwrap_or(0);
    let unit = rec
        .get("unit")
        .and_then(|v| v.as_str())
        .unwrap_or("yen/hour");
    let mut out = format!(
        "Recommended (basis: {basis}, {samples} nodes) for {} {class} units, {unit}\n",
        n("units")
    );
    out += &format!(
        "  floor {} ยท p25 {} ยท median {} ยท p75 {} ยท ceiling {}\n",
        n("floor"),
        n("p25"),
        n("median"),
        n("p75"),
        n("ceiling")
    );
    match current {
        Some(v) => {
            let price = if v.lo == v.hi {
                format!("{:.2}", v.lo)
            } else {
                format!("{:.2}\u{2013}{:.2}", v.lo, v.hi)
            };
            let suffix = if v.synced { " (last synced)" } else { "" };
            let verdict = match (f("floor"), f("ceiling")) {
                (Some(lo), Some(_)) if v.hi < lo => Some("below band"),
                (Some(_), Some(hi)) if v.lo > hi => Some("above band"),
                (Some(lo), Some(hi)) if v.lo >= lo && v.hi <= hi => Some("within band"),
                (Some(_), Some(_)) => Some("straddles band"),
                _ => None,
            };
            match verdict {
                Some(t) => out += &format!("  your price {price}{suffix} \u{2014} {t}\n"),
                None => out += &format!("  your price {price}{suffix}\n"),
            }
        }
        None => out += "  your price unknown (the hub has not reported one for this node)\n",
    }
    if let Some(flags) = rec.get("flags").and_then(|v| v.as_array()) {
        let names: Vec<&str> = flags.iter().filter_map(|f| f.as_str()).collect();
        if !names.is_empty() {
            out += &format!("  flags: {}\n", names.join(", "));
        }
    }
    out
}

/// This node's price as shown by `zc price recommend`: one price or a range.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct PriceView {
    pub lo: f64,
    pub hi: f64,
    /// Read from the local broker's workers (what the hub last synced to them)
    /// rather than from the hub's own answer.
    pub synced: bool,
}

/// The node's price as the hub reports it in the recommendation response, if
/// that response carries one.
pub fn hub_price(rec: &serde_json::Value) -> Option<PriceView> {
    ["effective_price", "current_price"]
        .iter()
        .find_map(|k| rec.get(*k)?.as_f64())
        .filter(|p| p.is_finite() && *p > 0.0)
        .map(|p| PriceView {
            lo: p,
            hi: p,
            synced: false,
        })
}

/// The prices this node's workers are billed at (what the hub applied;
/// `worker.pricing.price_per_hour`), from a `GET /workers?node=<own fp>` body,
/// as min-max. `None` when no worker has a positive price. `BrokerPrice`
/// (`GET /price`) only feeds adverts, so it is deliberately not used.
pub fn worker_price_view(workers: &serde_json::Value) -> Option<PriceView> {
    let prices: Vec<f64> = workers
        .get("workers")?
        .as_array()?
        .iter()
        .filter_map(|w| w.get("price_per_hour")?.as_f64())
        .filter(|p| p.is_finite() && *p > 0.0)
        .collect();
    let lo = prices.iter().copied().fold(f64::INFINITY, f64::min);
    let hi = prices.iter().copied().fold(0.0, f64::max);
    (!prices.is_empty()).then_some(PriceView {
        lo,
        hi,
        synced: true,
    })
}

/// This node's own workers only (`?node=`; the unfiltered list includes mesh
/// peers' workers), from the local broker. Best effort.
fn local_price() -> Option<PriceView> {
    let base = std::env::var("ZAKURO_BROKER")
        .ok()
        .filter(|b| b.starts_with("http"))
        .unwrap_or_else(|| "http://127.0.0.1:9000".into());
    let fp = NodeKey::load_or_create().fingerprint();
    let resp = ureq::get(&format!("{}/workers?node={fp}", base.trim_end_matches('/')))
        .config()
        .timeout_global(Some(Duration::from_secs(2)))
        .http_status_as_error(false)
        .build()
        .call()
        .ok()?;
    let v: serde_json::Value =
        serde_json::from_str(&resp.into_body().read_to_string().ok()?).ok()?;
    worker_price_view(&v)
}

fn signed_in() -> Result<(String, String, String), i32> {
    let Some((url, key)) = hub_credentials() else {
        eprintln!("Error: this Mac is not signed in: run `zc login`");
        return Err(1);
    };
    Ok((url, key, NodeKey::load_or_create().public_b64()))
}

/// `zc price recommend`.
pub fn price_recommend() -> i32 {
    let (url, key, pubkey) = match signed_in() {
        Ok(c) => c,
        Err(code) => return code,
    };
    match submit::recommendation(&url, &key, &pubkey) {
        Ok(rec) => {
            print!(
                "{}",
                render_recommendation(&rec, hub_price(&rec).or_else(local_price))
            );
            0
        }
        Err(e) => {
            eprintln!("Error: {e}");
            1
        }
    }
}

/// What `zc price auto` prints once the hub has the mode: the band, and who
/// applies the median.
pub fn render_auto_confirmation(rec: Option<&serde_json::Value>) -> String {
    let mut out = String::from("price mode: auto. The hub now prices this node at the median");
    let band = rec.and_then(|r| {
        let f = |k: &str| r.get(k).and_then(|v| v.as_f64());
        Some((f("floor")?, f("median")?, f("ceiling")?))
    });
    match band {
        Some((lo, mid, hi)) => {
            out += &format!(" (currently {mid:.2} yen/hour; band {lo:.2} to {hi:.2}).\n")
        }
        None => out += " of the recommendation band (no recommendation available yet).\n",
    }
    out
}

/// `zc price auto`. The hub applies the median for auto nodes; nothing runs
/// on the broker.
pub fn price_auto() -> i32 {
    let (url, key, pubkey) = match signed_in() {
        Ok(c) => c,
        Err(code) => return code,
    };
    match submit::put_price_mode(&url, &key, &pubkey, "auto") {
        Ok(()) => {
            let rec = submit::recommendation(&url, &key, &pubkey).ok();
            print!("{}", render_auto_confirmation(rec.as_ref()));
            0
        }
        Err(e) => {
            eprintln!("Error: {e}");
            1
        }
    }
}

/// After `zc price <n>`: this node is back on a fixed price. Best effort.
pub fn price_fixed() {
    if let Ok((url, key, pubkey)) = signed_in() {
        if let Err(e) = submit::put_price_mode(&url, &key, &pubkey, "fixed") {
            eprintln!("note: could not set price mode to fixed on the hub: {e}");
        }
    }
}

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

    fn args(v: &[&str]) -> Vec<String> {
        v.iter().map(|s| s.to_string()).collect()
    }

    #[test]
    fn price_auto_tells_the_owner_the_hub_applies_the_median() {
        let rec = serde_json::json!({"floor": 2.1, "median": 3.4, "ceiling": 5.0});
        let t = render_auto_confirmation(Some(&rec));
        assert!(
            t.contains("The hub now prices this node at the median"),
            "{t}"
        );
        assert!(
            t.contains("3.40") && t.contains("2.10") && t.contains("5.00"),
            "{t}"
        );
        assert!(!t.contains("15 minutes"));
        assert!(render_auto_confirmation(None).contains("no recommendation"));
    }

    #[test]
    fn node_flags_parse() {
        assert_eq!(parse_node_args(&[]), Ok(NodeArgs::default()));
        let a = parse_node_args(&args(&["--json", "--quick", "--submit", "--no-gpu"])).unwrap();
        assert!(a.json && a.quick && a.submit && a.no_gpu);
        assert!(parse_node_args(&args(&["--bogus"])).is_err());
    }

    #[test]
    fn recommendation_reads_like_the_spec_example() {
        let rec = serde_json::json!({
            "class": "cpu", "units": 8.12, "basis": "mesh", "unit": "yen/hour",
            "floor": 2.10, "p25": 2.80, "median": 3.40, "p75": 4.10, "ceiling": 5.00,
            "sample_size": 7, "flags": [], "price_mode": "fixed"
        });
        assert_eq!(
            render_recommendation(&rec, one(3.60)),
            "Recommended (basis: mesh, 7 nodes) for 8.12 CPU units, yen/hour\n  \
             floor 2.10 ยท p25 2.80 ยท median 3.40 ยท p75 4.10 ยท ceiling 5.00\n  \
             your price 3.60 โ€” within band\n"
        );
        assert!(render_recommendation(&rec, one(9.0)).contains("above band"));
        assert!(render_recommendation(&rec, one(1.0)).contains("below band"));
        assert!(render_recommendation(&rec, None).contains("unknown"));
    }

    fn one(p: f64) -> Option<PriceView> {
        Some(PriceView {
            lo: p,
            hi: p,
            synced: false,
        })
    }

    #[test]
    fn your_price_prefers_the_hub_then_the_synced_worker_range() {
        let rec = serde_json::json!({"floor": 2.0, "ceiling": 5.0, "effective_price": 3.0});
        assert_eq!(hub_price(&rec), one(3.0));
        assert_eq!(hub_price(&serde_json::json!({"floor": 2.0})), None);
        let body = serde_json::json!({
            "price_per_hour": 3.6,
            "workers": [{"price_per_hour": 2.0}, {"price_per_hour": 4.0}]
        });
        let v = worker_price_view(&body).unwrap();
        assert_eq!((v.lo, v.hi, v.synced), (2.0, 4.0, true));
        let t = render_recommendation(&rec, Some(v));
        assert!(
            t.contains("your price 2.00\u{2013}4.00 (last synced) \u{2014} within band"),
            "{t}"
        );
        assert!(
            render_recommendation(&rec, one(3.0)).contains("your price 3.00 \u{2014} within band")
        );
        // No workers, unpriced workers, wrong shape: unknown, never BrokerPrice.
        assert_eq!(worker_price_view(&serde_json::json!({"workers": []})), None);
        assert_eq!(
            worker_price_view(&serde_json::json!({"workers": [{"price_per_hour": 0.0}, {}]})),
            None
        );
        assert_eq!(
            worker_price_view(&serde_json::json!({"price_per_hour": 3.6})),
            None
        );
        let t = render_recommendation(&rec, None);
        assert!(
            t.contains("your price unknown") && !t.contains("3.60"),
            "{t}"
        );
        let wide = PriceView {
            lo: 1.0,
            hi: 4.0,
            synced: true,
        };
        assert!(render_recommendation(&rec, Some(wide)).contains("straddles band"));
    }

    #[test]
    fn table_names_every_measurement() {
        use crate::bench_node::report::*;
        let key = NodeKey::generate();
        let fp = crate::bench_node::fingerprint::HardwareFingerprint::detect(vec![]);
        let r = BenchReport {
            suite: crate::bench_node::SUITE.into(),
            zc_version: "0".into(),
            zc_git: None,
            node_pubkey: key.public_b64(),
            fingerprint_sha256: fp.sha256(),
            fingerprint: fp,
            measured_at: "2026-10-03T00:00:00Z".into(),
            duration_ms: 1,
            partial: true,
            cpu: Some(CpuMetrics {
                gflops_f32: 800.0,
                gflops_f64: 400.0,
                gflops_f32_1t: 60.0,
                mem_bw_gbps: 40.0,
            }),
            disk: Some(DiskMetrics {
                write_mbps: 1500.0,
                read_mbps: 2500.0,
            }),
            net: Some(NetMetrics {
                hub_rtt_ms: Some(12.0),
                peer_rtt_ms_p50: None,
                mbps: None,
            }),
            gpus: vec![GpuMetrics {
                vendor: "nvidia".into(),
                model: "RTX".into(),
                uuid: "u".into(),
                tflops_f32: 20.0,
                tflops_f16: 40.0,
                mem_bw_gbps: 500.0,
                vram_bytes: 1,
            }],
            skipped: vec!["net: x".into()],
            cpu_units: 8.0,
            gpu_units: Some(1.5),
            numa_mem: vec![],
        };
        let t = render(&r);
        for needle in [
            "800.0 GFLOPS f32",
            "400.0 f64",
            "60.0 single-thread",
            "40.0 GB/s",
            "RTX",
            "20.00 TFLOPS fp32",
            "40.00 fp16",
            "500.0 GB/s",
            "1500 MB/s write",
            "2500 MB/s read",
            "hub 12.0 ms",
            "8.00 CPU ยท 1.50 GPU",
            "partial run",
            "skipped: net: x",
        ] {
            assert!(t.contains(needle), "missing {needle:?} in:\n{t}");
        }
    }
}