zc2 0.0.48

P2P compute broker with yen-denominated billing, WAL, and broker mesh support
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
//! The finished run, rendered.
//!
//! This is the part that outlives the run: it stays in the scrollback, gets
//! pasted into a pull request, and is the only record anyone will read a week
//! later. So it states its own conditions — which broker, which build, when,
//! and whether it finished — and it ends by reading its own numbers back,
//! because a benchmark that leaves the reader to spot a 9× routing error has
//! not finished its job.

use colored::Colorize;

use super::layout::{
    bar, fit, fmt_ms, fmt_tick, fmt_us, grouped, pad, precise_duration, short_duration, split_bar,
    trim_lines, visible_width, worker_leaf, wrap_visible, Muted,
};
use super::metrics::{
    percentile_us, rate_spread, Buckets, Placement, MAX_BUCKET_ROWS, MIN_RATE_SAMPLES,
};
use super::{BenchResults, StopReason};

/// How the run ended, in words.
fn ending(results: &BenchResults) -> Option<String> {
    match results.stopped {
        Some(StopReason::Interrupt) => Some("stopped by ctrl-c".to_string()),
        Some(StopReason::Failing) => Some("stopped: too many failures".to_string()),
        None => None,
    }
}

pub(crate) fn render(results: &BenchResults, width: usize) -> String {
    let mut out = String::new();
    let rule = width.saturating_sub(4).min(116);
    out.push('\n');

    // -- what this is ------------------------------------------------------
    out.push_str(&format!("  {}\n", "═".repeat(rule).muted()));

    // The conditions the run happened under. On a narrow terminal these go
    // on their own lines rather than being cut: a report that does not say
    // which broker it measured is not worth keeping.
    let ident = format!(
        "{} · {} · c={}",
        results.config.workload.name(),
        results.config.strategy.as_str(),
        results.config.concurrency
    );
    let version = format!("zc {}", env!("CARGO_PKG_VERSION"));
    let meta = format!(
        "{}   {}   {}",
        results.broker_label(),
        version,
        results.started_at
    );
    out.push_str(&fit(
        width,
        &[
            format!(
                "  {}{}{}",
                pad(&"zc bench".bold().to_string(), 11, false),
                pad(&ident, 32, false),
                meta.muted()
            ),
            format!(
                "  {}{}\n  {}{}",
                pad(&"zc bench".bold().to_string(), 11, false),
                ident,
                " ".repeat(11),
                meta.muted()
            ),
            format!("  {}\n  {}\n  {}", "zc bench".bold(), ident, meta.muted()),
        ],
    ));
    out.push('\n');

    let ending_text = ending(results);
    let outcome = format!(
        "{}{} · {}",
        pad(
            &format!("{:.1} req/s", results.rps)
                .yellow()
                .bold()
                .to_string(),
            16,
            false
        ),
        format!("{} ok", grouped(results.successful)).green(),
        match results.failed {
            0 => "0 failed".muted(),
            n => format!("{n} failed").red().to_string(),
        },
    );
    let did = format!(
        "{}{}",
        pad(&grouped(results.completed).bold().to_string(), 11, false),
        format!(
            "of {} requests   in {}",
            grouped(results.total_requests),
            precise_duration(results.duration)
        )
        .muted(),
    );
    let stopped_note = match &ending_text {
        Some(e) => format!("   {}", e.yellow()),
        None => String::new(),
    };
    out.push_str(&fit(
        width,
        &[
            format!("  {did}{stopped_note}   {outcome}"),
            format!("  {did}{stopped_note}\n  {}{outcome}", " ".repeat(11)),
            format!(
                "  {did}\n  {}{}\n  {}{outcome}",
                " ".repeat(11),
                ending_text.clone().unwrap_or_default().yellow(),
                " ".repeat(11)
            ),
        ],
    ));
    out.push('\n');
    out.push_str(&format!("  {}\n\n", "═".repeat(rule).muted()));

    // -- the four summaries -------------------------------------------------
    summaries(results, width, &mut out);

    // -- the two distributions ----------------------------------------------
    distributions(results, width, &mut out);

    // -- where it ran --------------------------------------------------------
    where_it_ran(results, width, &mut out);

    // -- what the numbers say ------------------------------------------------
    notes(results, width, &mut out);

    trim_lines(&out)
}

fn summaries(results: &BenchResults, width: usize, out: &mut String) {
    let lat = &results.latencies_us;
    let (free_n, _) = results.ledger.totals(Placement::Free);
    let (billed_n, billed) = results.ledger.totals(Placement::Billed);
    let placed = results.ledger.placed().max(1);
    let rates = &results.rates_per_second;
    let dip = match rates.len() {
        0..=2 => 0,
        _ => rates[1..].iter().copied().min().unwrap_or(0),
    };

    let blocks: [(&str, Vec<(String, String)>); 4] = [
        (
            "latency  ms",
            vec![
                ("min".into(), fmt_us(lat.iter().copied().min().unwrap_or(0))),
                ("p50".into(), fmt_us(percentile_us(lat, 50.0))),
                ("p90".into(), fmt_us(percentile_us(lat, 90.0))),
                ("p99".into(), fmt_us(percentile_us(lat, 99.0))),
                ("max".into(), fmt_us(lat.iter().copied().max().unwrap_or(0))),
            ],
        ),
        ("throughput  req/s", {
            let spread = rate_spread(rates);
            let dash = "—".to_string();
            vec![
                ("mean".into(), format!("{:.1}", results.rps)),
                (
                    "peak".into(),
                    match rates.iter().copied().max() {
                        Some(v) => v.to_string(),
                        None => dash.clone(),
                    },
                ),
                (
                    "dip".into(),
                    match (rates.len() >= 3, dip) {
                        (true, d) => d.to_string(),
                        (false, _) => dash.clone(),
                    },
                ),
                (
                    "stdev".into(),
                    match spread {
                        Some((_, sd, _)) => format!("{sd:.1}"),
                        None => dash.clone(),
                    },
                ),
                (
                    "cv".into(),
                    match spread {
                        Some((_, _, cv)) => format!("{cv:.0}%"),
                        None => dash,
                    },
                ),
            ]
        }),
        (
            "placement",
            vec![
                (
                    "free".into(),
                    format!(
                        "{}  ·  {:.0}%",
                        grouped(free_n),
                        free_n as f64 / placed as f64 * 100.0
                    ),
                ),
                ("".into(), "cost nothing".green().to_string()),
                (
                    "billed".into(),
                    format!(
                        "{}  ·  {:.0}%",
                        grouped(billed_n),
                        billed_n as f64 / placed as f64 * 100.0
                    ),
                ),
                (
                    "".into(),
                    match billed_n {
                        0 => "—".muted(),
                        _ => format!("¥{billed:.4}").yellow().to_string(),
                    },
                ),
                ("".into(), String::new()),
            ],
        ),
        (
            "spend  ¥",
            vec![
                ("spent".into(), format!("{:.4}", results.total_charged)),
                ("per req".into(), format!("{:.6}", results.avg_charge())),
                (
                    "billed".into(),
                    format!("{} of {}", grouped(billed_n), grouped(results.completed)),
                ),
                ("".into(), String::new()),
                ("".into(), String::new()),
            ],
        ),
    ];

    // Four across on a wide terminal, two on a normal one, one when there is
    // no other choice.
    let per_row = match width {
        0..=59 => 1,
        60..=111 => 2,
        _ => 4,
    };
    let col_w = 28;
    for chunk in blocks.chunks(per_row) {
        let mut head = String::from("  ");
        for (title, _) in chunk {
            head.push_str(&pad(&title.bold().to_string(), col_w, false));
        }
        out.push_str(head.trim_end());
        out.push('\n');
        for i in 0..5 {
            let mut line = String::from("  ");
            for (_, rows) in chunk {
                let (k, v) = &rows[i];
                line.push_str(&pad(&k.muted(), 9, false));
                line.push_str(&pad(v, col_w - 9, false));
            }
            let line = line.trim_end().to_string();
            if !line.is_empty() {
                out.push_str(&line);
            }
            out.push('\n');
        }
        out.push('\n');
    }
}

fn distributions(results: &BenchResults, width: usize, out: &mut String) {
    let lat = Buckets::of(&results.latencies_us, MAX_BUCKET_ROWS);
    let thr = Buckets::linear(&results.rates_per_second, 7);
    let lat_rows: Vec<usize> = lat.interesting().collect();
    let thr_rows: Vec<usize> = match results.rates_per_second.len() < MIN_RATE_SAMPLES {
        true => Vec::new(),
        false => thr.interesting().collect(),
    };
    let thr_fmt = |v: u64| format!("{v} req/s");
    let lat_label_w = lat_rows
        .iter()
        .map(|i| visible_width(&lat.label(*i, &fmt_tick)))
        .max()
        .unwrap_or(8);
    let thr_label_w = thr_rows
        .iter()
        .map(|i| visible_width(&thr.label(*i, &thr_fmt)))
        .max()
        .unwrap_or(0);

    let left_fixed = 2 + lat_label_w + 1 + 7 + 5;
    let right_fixed = thr_label_w + 1 + 5 + 5;
    let two_col = width >= 104 && !thr_rows.is_empty();
    let lat_bar = match two_col {
        true => (width.saturating_sub(left_fixed + right_fixed + 5) * 58 / 100).min(26),
        false => width.saturating_sub(left_fixed).min(30),
    };
    let thr_bar = match two_col {
        true => width
            .saturating_sub(left_fixed + right_fixed + 5 + lat_bar)
            .min(22),
        false => 0,
    };

    let mut head = format!(
        "  {}",
        pad(
            &"latency distribution".bold().to_string(),
            2 + lat_label_w + lat_bar + 12 + 5,
            false
        )
    );
    if two_col {
        head.push_str(&format!(
            "{}   {}",
            "throughput distribution".bold(),
            format!("{} per-second samples", results.rates_per_second.len()).muted()
        ));
    }
    out.push_str(head.trim_end());
    out.push('\n');

    let lat_peak = lat.peak();
    let thr_peak = thr.peak();
    let lat_total = lat.total().max(1);
    let thr_total = thr.total().max(1);
    for (row, i) in lat_rows.iter().enumerate() {
        let n = lat.counts[*i];
        let mut line = format!(
            "  {}{}{}{}",
            pad(&lat.label(*i, &fmt_tick).muted(), lat_label_w + 1, false),
            bar(n, lat_peak, lat_bar).cyan(),
            pad(&grouped(n), 7, true),
            pad(
                &format!("{:.0}%", n as f64 / lat_total as f64 * 100.0)
                    .muted()
                    .to_string(),
                5,
                true
            ),
        );
        if two_col {
            line.push_str("     ");
            if let Some(j) = thr_rows.get(row) {
                let tn = thr.counts[*j];
                line.push_str(&format!(
                    "{}{}{}{}",
                    pad(&thr.label(*j, &thr_fmt).muted(), thr_label_w + 1, false),
                    bar(tn, thr_peak, thr_bar).green(),
                    pad(&tn.to_string(), 5, true),
                    pad(
                        &format!("{:.0}%", tn as f64 / thr_total as f64 * 100.0)
                            .muted()
                            .to_string(),
                        5,
                        true
                    ),
                ));
            }
        }
        out.push_str(line.trim_end());
        out.push('\n');
    }
    if !two_col && !thr_rows.is_empty() {
        out.push_str(&format!("\n  {}\n", "throughput distribution".bold()));
        for j in &thr_rows {
            let tn = thr.counts[*j];
            out.push_str(
                format!(
                    "  {}{}{}{}",
                    pad(&thr.label(*j, &thr_fmt).muted(), thr_label_w + 1, false),
                    bar(tn, thr_peak, lat_bar).green(),
                    pad(&tn.to_string(), 7, true),
                    pad(
                        &format!("{:.0}%", tn as f64 / thr_total as f64 * 100.0)
                            .muted()
                            .to_string(),
                        5,
                        true
                    ),
                )
                .trim_end(),
            );
            out.push('\n');
        }
    }
    out.push('\n');
}

/// The per-node table's columns, chosen for the terminal in front of us.
/// Each variant is a whole layout rather than the last one shaved down: a
/// table that merely gets tighter becomes unreadable before it becomes narrow
/// enough to fit.
struct Cols {
    class: usize,
    node: usize,
    price: usize,
    via: usize,
    bar: usize,
    req: usize,
    share: usize,
    p50: usize,
    spend: usize,
}

impl Cols {
    fn for_width(width: usize, name_w: usize) -> Cols {
        let mut c = match width {
            0..=79 => Cols {
                class: 9,
                node: name_w + 2,
                price: 0,
                via: 0,
                bar: 0,
                req: 8,
                share: 0,
                p50: 0,
                spend: 13,
            },
            80..=103 => Cols {
                class: 9,
                node: name_w + 2,
                price: 11,
                via: 0,
                bar: 0,
                req: 8,
                share: 7,
                p50: 10,
                spend: 13,
            },
            _ => Cols {
                class: 10,
                node: name_w + 2,
                price: 11,
                via: 10,
                bar: 0,
                req: 8,
                share: 7,
                p50: 11,
                spend: 14,
            },
        };
        let fixed = 2 + c.class + c.node + c.price + c.via + c.req + c.share + c.p50 + c.spend;
        c.bar = width.saturating_sub(fixed).min(30);
        c
    }

    fn cell(width: usize, text: String) -> String {
        match width {
            0 => String::new(),
            w => pad(&text, w, true),
        }
    }

    fn indent(&self) -> usize {
        self.class + self.node + self.price + self.via
    }
}

fn where_it_ran(results: &BenchResults, width: usize, out: &mut String) {
    if results.ledger.is_empty() {
        return;
    }
    out.push_str(&format!("  {}\n", "where it ran".bold()));
    let rows = results.ledger.rows();
    let placed = results.ledger.placed().max(1);
    let busiest = rows.iter().map(|(_, _, s)| s.requests).max().unwrap_or(0);
    let name_w = rows
        .iter()
        .map(|(_, n, _)| visible_width(n))
        .max()
        .unwrap_or(0)
        .clamp(8, 20);
    let c = Cols::for_width(width, name_w);

    out.push_str(
        format!(
            "  {}{}{}{}{}{}{}{}{}",
            " ".repeat(c.class),
            pad(&"node".muted(), c.node, false),
            match c.price {
                0 => String::new(),
                w => pad(&"price".muted(), w, false),
            },
            match c.via {
                0 => String::new(),
                w => pad(&"via".muted(), w, false),
            },
            " ".repeat(c.bar),
            Cols::cell(c.req, "req".muted()),
            Cols::cell(c.share, "share".muted()),
            Cols::cell(c.p50, "p50".muted()),
            Cols::cell(c.spend, "spend".muted()),
        )
        .trim_end(),
    );
    out.push('\n');

    for (class, node, stat) in &rows {
        let tint = match class {
            Placement::Free => colored::Color::Green,
            Placement::Billed => colored::Color::Yellow,
        };
        let drawn = bar(stat.requests, busiest, c.bar);
        out.push_str(
            format!(
                "  {}{}{}{}{}{}{}{}{}",
                pad(
                    &class.as_str().color(tint).bold().to_string(),
                    c.class,
                    false
                ),
                pad(&node.cyan().to_string(), c.node, false),
                match c.price {
                    0 => String::new(),
                    w => pad(
                        &match stat.priced_but_unbilled() {
                            true => stat.price().yellow().to_string(),
                            false => stat.price().muted(),
                        },
                        w,
                        false
                    ),
                },
                match c.via {
                    0 => String::new(),
                    w => pad(&stat.via().muted(), w, false),
                },
                drawn.color(tint),
                Cols::cell(c.req, grouped(stat.requests)),
                Cols::cell(
                    c.share,
                    format!("{:.0}%", stat.requests as f64 / placed as f64 * 100.0)
                        .muted()
                        .to_string()
                ),
                Cols::cell(c.p50, fmt_us(stat.p50_us())),
                Cols::cell(
                    c.spend,
                    match class {
                        Placement::Free => "free".green().to_string(),
                        Placement::Billed => format!("¥{:.4}", stat.charged).yellow().to_string(),
                    }
                ),
            )
            .trim_end(),
        );
        out.push('\n');

        // The workers behind that node, compactly: useful when one of them is
        // doing nothing while its siblings are busy.
        let mut detail: Vec<String> = Vec::new();
        if stat.workers.len() > 1 {
            let mut mine: Vec<(&String, &u64)> = stat.workers.iter().collect();
            mine.sort_by(|a, b| b.1.cmp(a.1).then_with(|| a.0.cmp(b.0)));
            let shown: Vec<String> = mine
                .iter()
                .take(8)
                .map(|(w, n)| format!("{} {}", worker_leaf(w), n))
                .collect();
            let more = match mine.len() > 8 {
                true => format!(" · … {} more", mine.len() - 8),
                false => String::new(),
            };
            detail.push(format!(
                "{} workers · {}{}",
                stat.workers.len(),
                shown.join(" · "),
                more
            ));
        }
        if let Some(expected) = stat.expectation.avg_expected_ms() {
            detail.push(format!(
                "router expected {} · delivered {}",
                fmt_ms(expected),
                fmt_ms(stat.expectation.avg_delivered_ms())
            ));
        }
        for d in detail {
            let indent = 2 + c.indent();
            for line in wrap_visible(&d, width.saturating_sub(indent).max(20), 0) {
                out.push_str(&format!("{}{}\n", " ".repeat(indent), line.muted()));
            }
        }
    }

    // The split, once more, as one bar — it is the line people screenshot.
    let (free_n, _) = results.ledger.totals(Placement::Free);
    let (billed_n, billed) = results.ledger.totals(Placement::Billed);
    let summary = format!(
        "{} {} {}   ·   {} {}",
        "free".muted(),
        format!("{:.0}%", free_n as f64 / placed as f64 * 100.0)
            .green()
            .bold(),
        "of the work".muted(),
        "billed".muted(),
        match billed_n {
            0 => "0%".muted(),
            _ => format!("¥{billed:.4}").yellow().bold().to_string(),
        },
    );
    let bar_w = width
        .saturating_sub(2 + 10 + 4 + visible_width(&summary))
        .min(30);
    out.push('\n');
    if bar_w >= 8 {
        let (free, billed) = split_bar(free_n, billed_n, bar_w);
        out.push_str(&format!(
            "  {}{}{}    {}\n\n",
            pad(&"split".bold().to_string(), 10, false),
            free.green(),
            billed.yellow(),
            summary
        ));
    } else {
        out.push_str(&format!(
            "  {}{}\n\n",
            pad(&"split".bold().to_string(), 10, false),
            summary
        ));
    }
}

/// What the numbers say, in sentences.
///
/// Everything here is derived from figures already on the screen — the notes
/// add reading, not data. A run that surfaces a 9× routing error and leaves
/// it as a dim line at the bottom has technically reported it and practically
/// buried it.
fn notes(results: &BenchResults, width: usize, out: &mut String) {
    // Each note is a marker and a sentence. The marker sits in its own
    // column and the sentence wraps under itself, so a long note stays a
    // note rather than becoming a wall.
    let mut notes: Vec<(String, String)> = Vec::new();

    for (node, exp) in results.ledger.miscalibrated() {
        if let (Some(e), Some(ratio)) = (exp.avg_expected_ms(), exp.ratio()) {
            let (factor, direction) = match ratio < 1.0 {
                true => (1.0 / ratio, "pessimistic"),
                false => (ratio, "optimistic"),
            };
            notes.push((
                "⚠".red().bold().to_string(),
                format!(
                    "{} expected {} of {} and got {} — {} {}. Routing is choosing on that estimate; {} shows each worker's posterior.",
                    results.config.strategy.as_str(),
                    fmt_ms(e).red(),
                    node.cyan(),
                    fmt_ms(exp.avg_delivered_ms()).green(),
                    format!("{factor:.1}×").red(),
                    direction,
                    "zc ls".cyan(),
                ),
            ));
        }
    }

    let (free_n, _) = results.ledger.totals(Placement::Free);
    let (_, billed) = results.ledger.totals(Placement::Billed);
    let placed = results.ledger.placed();

    // Nodes that advertise a price and charged nothing. Whether that is right
    // depends on whose machines they are, which this tool cannot know — so it
    // reports the fact and names the two readings rather than picking one.
    let unbilled: Vec<String> = results
        .ledger
        .rows()
        .into_iter()
        .filter(|(_, _, s)| s.priced_but_unbilled())
        .map(|(_, node, s)| format!("{node} at {}", s.price()))
        .collect();

    if placed > 0 && billed == 0.0 {
        match unbilled.is_empty() {
            // Nothing was billed and nothing advertised a price: free, with
            // nothing to explain.
            true => notes.push((
                "○".green().bold().to_string(),
                "Nothing was billed, and no worker asked to be paid.".to_string(),
            )),
            false => {
                notes.push((
                    "⚠".yellow().bold().to_string(),
                    format!(
                        "Nothing was billed, but {} advertised a price: {}.",
                        match unbilled.len() {
                            1 => "one node".to_string(),
                            n => format!("{n} nodes"),
                        },
                        unbilled.join(", ").yellow(),
                    ),
                ));
                notes.push((
                    " ".to_string(),
                    "Free is correct on hardware you own. On anyone else's it is zc#297, \
                     and the owner of that machine was not paid."
                        .muted(),
                ));
            }
        }
    } else if billed > 0.0 {
        notes.push((
            "○".yellow().bold().to_string(),
            format!(
                "{} {} {}",
                format!("¥{billed:.4}").yellow(),
                "was charged for work sent across the network.",
                format!(
                    "{:.0}% of the work cost nothing.",
                    free_n as f64 / placed.max(1) as f64 * 100.0
                )
                .muted()
            ),
        ));
    }

    // A run that named a node made a promise about placement. Say whether it
    // was kept: the table below already shows the nodes, but "is this one row
    // or five" is the whole question a pinned run was asked, and counting
    // rows is not the reader's job.
    if let Some(pin) = results.config.effective_pin() {
        let touched = results.ledger.nodes_touched();
        match touched.len() {
            0 => {}
            1 => notes.push((
                "○".green().bold().to_string(),
                format!(
                    "All {} placed requests ran on {}, as pinned.",
                    grouped(placed),
                    touched[0].0.clone().green(),
                ),
            )),
            n => {
                notes.push((
                    "⚠".red().bold().to_string(),
                    format!(
                        "Pinned to {} but the work ran on {} nodes: {}.",
                        pin.cyan(),
                        n.to_string().red(),
                        touched
                            .iter()
                            .map(|(node, reqs)| format!("{node} ×{reqs}"))
                            .collect::<Vec<_>>()
                            .join(", ")
                            .yellow(),
                    ),
                ));
                notes.push((
                    " ".to_string(),
                    format!(
                        "This broker's build spreads a pinned job across the mesh, so the run \
                         measures the mesh rather than the node. {} names each broker's build.",
                        "zc brokers".cyan()
                    )
                    .muted(),
                ));
            }
        }
    }

    if let Some((reason, count)) = results.ranked_failure_reasons().first() {
        notes.push((
            "⚠".red().bold().to_string(),
            format!("{} {}", format!("{count}×").red(), reason.muted()),
        ));
    }

    if results.completed < results.total_requests && results.rps > 0.0 {
        let full = std::time::Duration::from_secs_f64(results.total_requests as f64 / results.rps);
        notes.push((
            "○".muted_bold(),
            format!(
                "{} {}",
                format!(
                    "{} of {} requested. At {:.1} req/s the whole run needs {}; try",
                    grouped(results.completed),
                    grouped(results.total_requests),
                    results.rps,
                    short_duration(full),
                )
                .muted(),
                format!(
                    "{} for a shorter sample.",
                    format!("-n {}", suggest_n(results.rps)).cyan()
                )
                .muted(),
            ),
        ));
    }

    if notes.is_empty() {
        return;
    }
    out.push_str(&format!("  {}\n", "notes".bold()));
    const MARKER: usize = 5;
    for (marker, body) in notes {
        let room = width.saturating_sub(2 + MARKER).max(30);
        for (i, line) in wrap_visible(&body, room, 0).into_iter().enumerate() {
            match i {
                0 => out.push_str(&format!("  {}{}\n", pad(&marker, MARKER, false), line)),
                _ => out.push_str(&format!("  {}{}\n", " ".repeat(MARKER), line)),
            }
        }
    }
    out.push('\n');
}

/// A request count that would finish in about two minutes at this rate,
/// rounded to something a person would actually type.
pub(crate) fn suggest_n(rps: f64) -> u64 {
    let raw = (rps * 120.0).max(100.0);
    let mag = 10f64.powf(raw.log10().floor());
    ((raw / mag).round() * mag) as u64
}

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

    #[test]
    fn a_suggested_sample_is_a_number_a_person_would_type() {
        assert_eq!(suggest_n(37.6), 5000);
        assert_eq!(suggest_n(0.1), 100);
        assert_eq!(suggest_n(800.0), 100000);
    }
}