zc2 0.0.47

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
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
//! The interactive run.
//!
//! Same measurements as every other view โ€” this module owns no arithmetic โ€”
//! but it takes the terminal for the duration: a full-screen layout that
//! reflows to the window, and keys to drive it while the run is going.
//!
//! It deliberately gives the terminal back before the report is printed. A
//! full-screen app that exits leaves nothing behind, and the thing people
//! actually keep from a benchmark is the summary they paste into a pull
//! request. So: alternate screen while running, ordinary scrollback after.

use std::io;
use std::sync::atomic::Ordering;
use std::time::{Duration, Instant};

use crossterm::event::{self, Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers};
use ratatui::layout::{Constraint, Layout, Rect};
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, Borders, Cell, Gauge, Paragraph, Row, Sparkline, Table, Tabs};
use ratatui::{DefaultTerminal, Frame};

use super::layout::{bar, fmt_ms, fmt_tick, fmt_us, grouped, short_duration};
use super::metrics::{Buckets, Ledger, Placement, RateRing, MAX_BUCKET_ROWS, MIN_RATE_SAMPLES};
use super::{BenchConfig, Shared};

/// Which detail the bottom panel is showing.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Pane {
    Placement,
    Workers,
    Failures,
}

impl Pane {
    const ALL: [Pane; 3] = [Pane::Placement, Pane::Workers, Pane::Failures];
    fn title(&self) -> &'static str {
        match self {
            Pane::Placement => "placement",
            Pane::Workers => "workers",
            Pane::Failures => "failures",
        }
    }
    fn next(self) -> Pane {
        match self {
            Pane::Placement => Pane::Workers,
            Pane::Workers => Pane::Failures,
            Pane::Failures => Pane::Placement,
        }
    }
}

/// Why the loop ended.
pub(crate) enum Exit {
    /// Every request was sent.
    Finished,
    /// The person asked it to stop.
    Quit,
}

struct App<'a> {
    config: &'a BenchConfig,
    shared: &'a Shared,
    start: Instant,
    total: u64,
    workers: u64,
    pane: Pane,
    /// Freezes the numbers on screen without stopping the run, so a spike can
    /// be read instead of chased.
    paused: bool,
    scroll: usize,
    frozen: Option<Snapshot>,
}

/// Everything one frame draws, read once so the panels cannot disagree.
struct Snapshot {
    done: u64,
    ok: u64,
    failed: u64,
    elapsed: Duration,
    samples: Vec<u64>,
    ledger: Ledger,
    rates: RateRing,
    failures: Vec<(String, u64)>,
}

impl App<'_> {
    fn read(&self) -> Snapshot {
        Snapshot {
            done: self.shared.completed.load(Ordering::Relaxed),
            ok: self.shared.successful.load(Ordering::Relaxed),
            failed: self.shared.failed.load(Ordering::Relaxed),
            elapsed: self.start.elapsed(),
            samples: self
                .shared
                .latencies
                .lock()
                .map(|l| l.clone())
                .unwrap_or_default(),
            ledger: self
                .shared
                .ledger
                .lock()
                .map(|l| l.clone())
                .unwrap_or_default(),
            rates: self
                .shared
                .rates
                .lock()
                .map(|r| r.clone())
                .unwrap_or_default(),
            failures: {
                let mut v: Vec<(String, u64)> = self
                    .shared
                    .failure_reasons
                    .lock()
                    .map(|f| f.iter().map(|(r, c)| (r.clone(), *c)).collect())
                    .unwrap_or_default();
                v.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
                v
            },
        }
    }
}

/// Past this the layout stops widening. Every panel in it has a natural size
/// โ€” a bar, a column, a table of eight fields โ€” so a 250-column window spread
/// the same content over twice the space and left half the screen blank
/// between the figures and the words naming them.
const MAX_WIDTH: u16 = 180;
/// How tall the rate sparkline is drawn. It showed one second of data
/// stretched over forty rows on a tall window.
const SPARK_ROWS: u16 = 6;
/// The most the two distributions may take, however much room there is.
const MAX_DIST_HEIGHT: u16 = 18;
/// The most the detail panel may take. Past this the spare rows are left
/// blank rather than spent stretching four table rows down a tall window.
const MAX_PANEL_HEIGHT: u16 = 18;

const GREY: Color = Color::Indexed(245);
const FREE: Color = Color::Indexed(41);
const BILLED: Color = Color::Indexed(178);
const ACCENT: Color = Color::Indexed(80);

fn label<T: Into<String>>(s: T) -> Span<'static> {
    Span::styled(s.into(), Style::default().fg(GREY))
}

/// Run the interactive view until the run finishes or the person stops it.
pub(crate) fn run(
    config: &BenchConfig,
    shared: &Shared,
    start: Instant,
    total: u64,
    workers: u64,
) -> io::Result<Exit> {
    let mut terminal = ratatui::init();
    let mut app = App {
        config,
        shared,
        start,
        total,
        workers,
        pane: Pane::Placement,
        paused: false,
        scroll: 0,
        frozen: None,
    };
    let outcome = event_loop(&mut terminal, &mut app);
    ratatui::restore();
    outcome
}

fn event_loop(terminal: &mut DefaultTerminal, app: &mut App) -> io::Result<Exit> {
    loop {
        let done = app.shared.completed.load(Ordering::Relaxed);
        if done >= app.total || app.shared.stop.load(Ordering::Relaxed) {
            // One last frame so the finished numbers are on screen, however
            // briefly, rather than the frame from 100 ms before the end.
            let snap = app.read();
            if let Ok(mut r) = app.shared.rates.lock() {
                r.sample(snap.done, snap.elapsed);
            }
            terminal.draw(|f| draw(f, app, &snap))?;
            return Ok(Exit::Finished);
        }

        let snap = match (&app.frozen, app.paused) {
            (Some(s), true) => Snapshot {
                done: s.done,
                ok: s.ok,
                failed: s.failed,
                elapsed: s.elapsed,
                samples: s.samples.clone(),
                ledger: s.ledger.clone(),
                rates: s.rates.clone(),
                failures: s.failures.clone(),
            },
            _ => {
                let s = app.read();
                if let Ok(mut r) = app.shared.rates.lock() {
                    r.sample(s.done, s.elapsed);
                }
                s
            }
        };
        terminal.draw(|f| draw(f, app, &snap))?;

        if event::poll(Duration::from_millis(100))? {
            if let Event::Key(key) = event::read()? {
                if key.kind != KeyEventKind::Release && handle_key(app, key) {
                    return Ok(Exit::Quit);
                }
            }
        }
    }
}

/// Returns true when the person asked to stop.
fn handle_key(app: &mut App, key: KeyEvent) -> bool {
    let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
    match key.code {
        KeyCode::Char('q') | KeyCode::Esc => return true,
        KeyCode::Char('c') if ctrl => return true,
        KeyCode::Char('p') | KeyCode::Char(' ') => {
            app.paused = !app.paused;
            app.frozen = match app.paused {
                true => Some(app.read()),
                false => None,
            };
        }
        KeyCode::Tab | KeyCode::Right => {
            app.pane = app.pane.next();
            app.scroll = 0;
        }
        KeyCode::BackTab | KeyCode::Left => {
            app.pane = app.pane.next().next();
            app.scroll = 0;
        }
        KeyCode::Char('1') => app.pane = Pane::Placement,
        KeyCode::Char('2') => app.pane = Pane::Workers,
        KeyCode::Char('3') => app.pane = Pane::Failures,
        KeyCode::Down | KeyCode::Char('j') => app.scroll = app.scroll.saturating_add(1),
        KeyCode::Up | KeyCode::Char('k') => app.scroll = app.scroll.saturating_sub(1),
        _ => {}
    }
    false
}

fn draw(f: &mut Frame, app: &App, snap: &Snapshot) {
    // Panels stack when the window is short: the distributions are the first
    // thing to go, because progress and placement answer the two questions
    // that cannot wait. The keys line is last to go and never goes โ€” a
    // full-screen view whose only exit is undocumented is a trap, and at 24
    // rows the fixed heights below added up to 25 and squeezed it away.
    const HEADER: u16 = 3;
    const PROGRESS: u16 = 4;
    const KEYS: u16 = 1;
    const DIST_MIN: u16 = 9;

    // On a large window every panel would otherwise take its share of the
    // slack and hold it empty: an eleven-row histogram floating at the top of
    // a fifty-row panel, and a sparkline stretched over forty rows of one
    // second's data. Bands are sized to what they hold; the spare rows go to
    // the node table, which is the one panel with more to show, and the spare
    // columns are simply left.
    let area = Rect {
        width: f.area().width.min(MAX_WIDTH),
        ..f.area()
    };
    let lat_rows = Buckets::of(&snap.samples, MAX_BUCKET_ROWS)
        .interesting()
        .count() as u16;
    let thr_rows = match snap.rates.per_second().len() < MIN_RATE_SAMPLES {
        true => 0,
        false => Buckets::linear(snap.rates.per_second(), 6)
            .interesting()
            .count() as u16,
    };
    let dist_h = (2 + lat_rows.max(SPARK_ROWS + thr_rows)).clamp(DIST_MIN, MAX_DIST_HEIGHT);
    // The detail panel: borders, the tab strip, the split bar and a blank
    // line, a header row, then one row per thing it has to show.
    let panel_rows = match app.pane {
        Pane::Placement => snap.ledger.rows().len() as u16 + 4,
        Pane::Workers => snap.ledger.worker_names().len() as u16 + 2,
        Pane::Failures => snap.failures.len().max(1) as u16 + 2,
    };
    let panel_h = (2 + panel_rows).clamp(6, MAX_PANEL_HEIGHT);
    let height = area.height;
    let tall = height >= HEADER + PROGRESS + DIST_MIN + 6 + KEYS;
    let areas = match tall {
        true => Layout::vertical([
            Constraint::Length(HEADER),
            Constraint::Length(PROGRESS),
            Constraint::Length(dist_h),
            Constraint::Length(panel_h),
            // Whatever is left over stays empty rather than stretching a
            // four-row table down a fifty-row window.
            Constraint::Min(0),
            Constraint::Length(KEYS),
        ])
        .split(area),
        false => Layout::vertical([
            Constraint::Length(HEADER),
            Constraint::Length(PROGRESS),
            Constraint::Length(0),
            Constraint::Min(3),
            Constraint::Length(0),
            Constraint::Length(KEYS),
        ])
        .split(area),
    };

    header(f, app, areas[0]);
    progress(f, app, snap, areas[1]);
    if tall {
        let halves = Layout::horizontal([Constraint::Percentage(52), Constraint::Percentage(48)])
            .split(areas[2]);
        latency(f, snap, halves[0]);
        throughput(f, snap, halves[1]);
    }
    match app.pane {
        Pane::Placement => placement(f, app, snap, areas[3]),
        Pane::Workers => workers(f, app, snap, areas[3]),
        Pane::Failures => failures(f, app, snap, areas[3]),
    }
    footer(f, app, areas[5]);
}

fn header(f: &mut Frame, app: &App, area: Rect) {
    let broker = app
        .config
        .broker_url
        .trim_start_matches("http://")
        .trim_start_matches("https://")
        .trim_end_matches('/');
    let line = Line::from(vec![
        Span::styled(
            app.config.workload.name(),
            Style::default().fg(BILLED).add_modifier(Modifier::BOLD),
        ),
        label(" ยท "),
        Span::styled(
            app.config.strategy.as_str(),
            Style::default().fg(BILLED).add_modifier(Modifier::BOLD),
        ),
        label(" ยท "),
        Span::raw(format!("{} concurrent", app.config.concurrency)),
        label(" ยท "),
        Span::raw(grouped(app.total)),
        label(" requests"),
        label("     broker "),
        Span::styled(broker, Style::default().fg(ACCENT)),
        label("     "),
        Span::raw(format!("{} workers", app.workers)),
    ]);
    f.render_widget(
        Paragraph::new(line).block(
            Block::default()
                .borders(Borders::ALL)
                .border_style(Style::default().fg(GREY))
                .title(Span::styled(
                    " zc bench ",
                    Style::default().add_modifier(Modifier::BOLD),
                )),
        ),
        area,
    );
}

fn progress(f: &mut Frame, app: &App, snap: &Snapshot, area: Rect) {
    let rows = Layout::vertical([Constraint::Length(1), Constraint::Length(1)])
        .margin(1)
        .split(area);
    let ratio = (snap.done as f64 / app.total.max(1) as f64).clamp(0.0, 1.0);
    let eta = super::layout::eta(snap.done, app.total, snap.elapsed)
        .map(|d| format!(" ยท eta {}", short_duration(d)))
        .unwrap_or_default();
    f.render_widget(
        Block::default()
            .borders(Borders::ALL)
            .border_style(Style::default().fg(GREY))
            .title(Line::from(vec![
                label(" "),
                Span::raw(format!("{} / {}", grouped(snap.done), grouped(app.total))),
                label(format!("   {}{}  ", short_duration(snap.elapsed), eta)),
            ])),
        area,
    );
    f.render_widget(
        Gauge::default()
            .gauge_style(Style::default().fg(ACCENT))
            .ratio(ratio)
            .label(format!("{:.1}%", ratio * 100.0)),
        rows[0],
    );

    let now = snap.rates.now(5, snap.done, snap.elapsed);
    let mean = snap.done as f64 / snap.elapsed.as_secs_f64().max(0.001);
    let (p50, p99) = super::metrics::percentiles_us(&snap.samples);
    f.render_widget(
        Paragraph::new(Line::from(vec![
            Span::styled(grouped(snap.ok), Style::default().fg(FREE)),
            label(" ok ยท "),
            Span::styled(
                grouped(snap.failed),
                Style::default().fg(match snap.failed {
                    0 => GREY,
                    _ => Color::Indexed(203),
                }),
            ),
            label(" failed        "),
            Span::styled(
                format!("{now:.1}"),
                Style::default().fg(BILLED).add_modifier(Modifier::BOLD),
            ),
            label(" req/s now ยท "),
            Span::raw(format!("{mean:.1}")),
            label(" avg ยท "),
            Span::raw(snap.rates.peak().to_string()),
            label(" peak        "),
            Span::raw(fmt_us(p50)),
            label(" p50 ยท "),
            Span::raw(fmt_us(p99)),
            label(" p99"),
        ])),
        rows[1],
    );
}

fn latency(f: &mut Frame, snap: &Snapshot, area: Rect) {
    let b = Buckets::of(
        &snap.samples,
        MAX_BUCKET_ROWS.min(area.height.saturating_sub(2) as usize),
    );
    let rows: Vec<usize> = b.interesting().collect();
    let peak = b.peak();
    let total = b.total().max(1);
    let label_w = rows
        .iter()
        .map(|i| b.label(*i, &fmt_tick).chars().count())
        .max()
        .unwrap_or(7);
    let bar_w = (area.width as usize).saturating_sub(label_w + 16).min(56);
    let lines: Vec<Line> = rows
        .iter()
        .map(|i| {
            let n = b.counts[*i];
            Line::from(vec![
                label(format!("{:>w$} ", b.label(*i, &fmt_tick), w = label_w)),
                Span::styled(bar(n, peak, bar_w), Style::default().fg(ACCENT)),
                Span::raw(format!("{:>8}", grouped(n))),
                label(format!(
                    "{:>5}",
                    format!("{:.0}%", n as f64 / total as f64 * 100.0)
                )),
            ])
        })
        .collect();
    f.render_widget(
        Paragraph::new(lines).block(
            Block::default()
                .borders(Borders::ALL)
                .border_style(Style::default().fg(GREY))
                .title(Span::styled(
                    " latency ",
                    Style::default().add_modifier(Modifier::BOLD),
                )),
        ),
        area,
    );
}

fn throughput(f: &mut Frame, snap: &Snapshot, area: Rect) {
    let block = Block::default()
        .borders(Borders::ALL)
        .border_style(Style::default().fg(GREY))
        .title(Span::styled(
            " throughput  req/s ",
            Style::default().add_modifier(Modifier::BOLD),
        ));
    let inner = block.inner(area);
    f.render_widget(block, area);
    let per_second = snap.rates.per_second();
    if per_second.is_empty() {
        f.render_widget(Paragraph::new(label("measuringโ€ฆ")), inner);
        return;
    }
    let split = Layout::vertical([Constraint::Length(SPARK_ROWS), Constraint::Min(1)]).split(inner);
    let width = split[0].width as usize;
    let data: Vec<u64> = per_second.iter().rev().take(width).rev().copied().collect();
    f.render_widget(
        Sparkline::default()
            .data(&data)
            .style(Style::default().fg(FREE)),
        split[0],
    );

    // Under the shape, the distribution of those per-second rates: the
    // question a single number cannot answer is whether it held.
    let b = Buckets::linear(per_second, 6);
    let rows: Vec<usize> = match per_second.len() < MIN_RATE_SAMPLES {
        true => Vec::new(),
        false => b.interesting().collect(),
    };
    let peak = b.peak();
    let total = b.total().max(1);
    let lines: Vec<Line> = match rows.is_empty() {
        true => vec![Line::from(label(
            "a distribution needs a few seconds of samples",
        ))],
        false => rows
            .iter()
            .map(|i| {
                let n = b.counts[*i];
                Line::from(vec![
                    label(format!("{:>10} ", b.label(*i, &|v| format!("{v} req/s")))),
                    Span::styled(
                        bar(
                            n,
                            peak,
                            (split[1].width as usize).saturating_sub(22).min(20),
                        ),
                        Style::default().fg(FREE),
                    ),
                    Span::raw(format!("{n:>5}")),
                    label(
                        format!("{:>5}", format!("{:.0}%", n as f64 / total as f64 * 100.0)).leak(),
                    ),
                ])
            })
            .collect(),
    };
    f.render_widget(Paragraph::new(lines), split[1]);
}

/// The bottom panel's frame. It carries no title: the tab strip inside it
/// names what is showing, and a title as well would say it twice.
fn panel() -> Block<'static> {
    Block::default()
        .borders(Borders::ALL)
        .border_style(Style::default().fg(GREY))
}

fn tabs(app: &App) -> Tabs<'static> {
    Tabs::new(Pane::ALL.iter().map(|p| p.title()).collect::<Vec<_>>())
        .select(Pane::ALL.iter().position(|p| *p == app.pane).unwrap_or(0))
        .style(Style::default().fg(GREY))
        .highlight_style(Style::default().fg(ACCENT).add_modifier(Modifier::BOLD))
        .divider(" ")
}

fn placement(f: &mut Frame, app: &App, snap: &Snapshot, area: Rect) {
    let block = panel();
    let inner = block.inner(area);
    f.render_widget(block, area);
    let split = Layout::vertical([
        Constraint::Length(1),
        Constraint::Length(2),
        Constraint::Min(1),
    ])
    .split(inner);
    f.render_widget(tabs(app), split[0]);

    let (free_n, _) = snap.ledger.totals(Placement::Free);
    let (billed_n, billed) = snap.ledger.totals(Placement::Billed);
    let placed = snap.ledger.placed().max(1);
    let bar_w = (split[1].width as usize).saturating_sub(48).clamp(8, 40);
    let (free_run, billed_run) = super::layout::split_bar(free_n, billed_n, bar_w);
    f.render_widget(
        Paragraph::new(Line::from(vec![
            Span::styled(free_run, Style::default().fg(FREE)),
            Span::styled(billed_run, Style::default().fg(BILLED)),
            label("   free "),
            Span::styled(
                format!("{:.0}%", free_n as f64 / placed as f64 * 100.0),
                Style::default().fg(FREE).add_modifier(Modifier::BOLD),
            ),
            label(" of the work ยท billed "),
            Span::styled(
                format!("{:.0}%", billed_n as f64 / placed as f64 * 100.0),
                Style::default().fg(BILLED).add_modifier(Modifier::BOLD),
            ),
            label("  "),
            Span::styled(format!("ยฅ{billed:.4}"), Style::default().fg(BILLED)),
        ])),
        split[1],
    );

    let rows: Vec<Row> = snap
        .ledger
        .rows()
        .into_iter()
        .skip(app.scroll)
        .map(|(class, node, stat)| {
            let tint = match class {
                Placement::Free => FREE,
                Placement::Billed => BILLED,
            };
            let expected = match stat.expectation.avg_expected_ms() {
                Some(ms) => match stat.expectation.is_miscalibrated() {
                    true => format!("{} โš ", fmt_ms(ms)),
                    false => fmt_ms(ms),
                },
                None => "โ€”".to_string(),
            };
            Row::new(vec![
                Cell::from(class.as_str()).style(Style::default().fg(tint)),
                Cell::from(node).style(Style::default().fg(ACCENT)),
                Cell::from(stat.price()).style(Style::default().fg(
                    match stat.priced_but_unbilled() {
                        true => BILLED,
                        false => GREY,
                    },
                )),
                Cell::from(stat.via()).style(Style::default().fg(GREY)),
                Cell::from(grouped(stat.requests)),
                Cell::from(format!(
                    "{:.1}%",
                    stat.requests as f64 / placed as f64 * 100.0
                ))
                .style(Style::default().fg(GREY)),
                Cell::from(fmt_us(stat.p50_us())),
                Cell::from(expected).style(Style::default().fg(GREY)),
                Cell::from(match class {
                    Placement::Free => "free".to_string(),
                    Placement::Billed => format!("ยฅ{:.4}", stat.charged),
                })
                .style(Style::default().fg(tint)),
                Cell::from(""),
            ])
        })
        .collect();
    let widths = [
        Constraint::Length(8),
        Constraint::Length(24),
        Constraint::Length(11),
        Constraint::Length(7),
        Constraint::Length(9),
        Constraint::Length(8),
        Constraint::Length(10),
        Constraint::Length(13),
        Constraint::Length(13),
        // Absorbs the slack, so a wide window spreads empty space at the end
        // rather than between the node and everything said about it.
        Constraint::Fill(1),
    ];
    let table = Table::new(rows, widths).header(
        Row::new(vec![
            "",
            "node",
            "via",
            "req",
            "share",
            "p50",
            "router said",
            "spend",
        ])
        .style(Style::default().fg(GREY)),
    );
    f.render_widget(table, split[2]);
}

fn workers(f: &mut Frame, app: &App, snap: &Snapshot, area: Rect) {
    let block = panel();
    let inner = block.inner(area);
    f.render_widget(block, area);
    let split = Layout::vertical([Constraint::Length(1), Constraint::Min(1)]).split(inner);
    f.render_widget(tabs(app), split[0]);

    let mut all: Vec<(String, String, u64)> = Vec::new();
    for (_, node, stat) in snap.ledger.rows() {
        for (w, n) in &stat.workers {
            all.push((node.clone(), super::layout::worker_leaf(w), *n));
        }
    }
    all.sort_by(|a, b| b.2.cmp(&a.2).then_with(|| a.0.cmp(&b.0)));
    let busiest = all.first().map(|w| w.2).unwrap_or(0);
    let rows: Vec<Row> = all
        .into_iter()
        .skip(app.scroll)
        .map(|(node, leaf, n)| {
            Row::new(vec![
                Cell::from(node).style(Style::default().fg(ACCENT)),
                Cell::from(leaf).style(Style::default().fg(GREY)),
                Cell::from(bar(n, busiest, 32)).style(Style::default().fg(ACCENT)),
                Cell::from(grouped(n)),
                Cell::from(""),
            ])
        })
        .collect();
    f.render_widget(
        Table::new(
            rows,
            [
                Constraint::Length(24),
                Constraint::Length(10),
                Constraint::Length(34),
                Constraint::Length(9),
                Constraint::Fill(1),
            ],
        )
        .header(Row::new(vec!["node", "worker", "", "req", ""]).style(Style::default().fg(GREY))),
        split[1],
    );
}

fn failures(f: &mut Frame, app: &App, snap: &Snapshot, area: Rect) {
    let block = panel();
    let inner = block.inner(area);
    f.render_widget(block, area);
    let split = Layout::vertical([Constraint::Length(1), Constraint::Min(1)]).split(inner);
    f.render_widget(tabs(app), split[0]);

    let lines: Vec<Line> = match snap.failures.is_empty() {
        true => vec![Line::from(Span::styled(
            "nothing has failed",
            Style::default().fg(FREE),
        ))],
        false => snap
            .failures
            .iter()
            .skip(app.scroll)
            .map(|(reason, n)| {
                Line::from(vec![
                    Span::styled(
                        format!("{:>7}ร— ", grouped(*n)),
                        Style::default().fg(Color::Indexed(203)),
                    ),
                    label(reason.as_str()),
                ])
            })
            .collect(),
    };
    f.render_widget(Paragraph::new(lines), split[1]);
}

fn footer(f: &mut Frame, app: &App, area: Rect) {
    let paused = match app.paused {
        true => Span::styled(
            "  PAUSED (run continues) ",
            Style::default()
                .fg(Color::Black)
                .bg(BILLED)
                .add_modifier(Modifier::BOLD),
        ),
        false => Span::raw(""),
    };
    f.render_widget(
        Paragraph::new(Line::from(vec![
            Span::styled(" q", Style::default().add_modifier(Modifier::BOLD)),
            label(" stop & report  "),
            Span::styled("p", Style::default().add_modifier(Modifier::BOLD)),
            label(" pause  "),
            Span::styled("tab", Style::default().add_modifier(Modifier::BOLD)),
            label(" pane  "),
            Span::styled("โ†‘โ†“", Style::default().add_modifier(Modifier::BOLD)),
            label(" scroll  "),
            paused,
        ])),
        area,
    );
}

/// Whether an interactive run is possible and wanted.
///
/// It needs a real terminal on both ends โ€” keys come from stdin, the drawing
/// goes to stdout โ€” and it is off wherever another view has claimed the
/// output: `--json`, `--no-progress`, `--compare`, or a pipe.
pub(crate) fn wanted(config: &BenchConfig) -> bool {
    use std::io::IsTerminal;
    if config.no_tui || config.json || config.no_progress || config.silent {
        return false;
    }
    std::io::stdout().is_terminal() && std::io::stdin().is_terminal()
}

// ---------------------------------------------------------------------------
// the comparison
// ---------------------------------------------------------------------------

/// Draw a strategy comparison while it runs.
///
/// The benchmarks happen on another thread; this one owns the terminal and
/// reads what they publish. Returns when every strategy has been run, or the
/// person has ended it.
pub(crate) fn run_compare(
    base: &BenchConfig,
    progress: &std::sync::Arc<super::compare::Progress>,
) -> io::Result<()> {
    let mut terminal = ratatui::init();
    let outcome = compare_loop(&mut terminal, base, progress);
    ratatui::restore();
    outcome
}

fn compare_loop(
    terminal: &mut DefaultTerminal,
    base: &BenchConfig,
    progress: &std::sync::Arc<super::compare::Progress>,
) -> io::Result<()> {
    loop {
        terminal.draw(|f| draw_compare(f, base, progress))?;
        if progress.is_over() {
            // One last frame with the finished table on it, then hand the
            // terminal back so the summary can print into the scrollback.
            terminal.draw(|f| draw_compare(f, base, progress))?;
            return Ok(());
        }
        if event::poll(Duration::from_millis(100))? {
            if let Event::Key(key) = event::read()? {
                if key.kind == KeyEventKind::Release {
                    continue;
                }
                let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
                match key.code {
                    // Stop after the strategy in flight: a half-measured row
                    // in the table is worse than a row that is not there.
                    KeyCode::Char('q') | KeyCode::Esc => progress.ask_to_stop(),
                    KeyCode::Char('x') | KeyCode::Char('Q') => progress.abandon(),
                    KeyCode::Char('c') if ctrl => progress.abandon(),
                    _ => {}
                }
            }
        }
    }
}

fn draw_compare(
    f: &mut Frame,
    base: &BenchConfig,
    progress: &std::sync::Arc<super::compare::Progress>,
) {
    use super::compare::{free_share, verdicts, STRATEGIES};

    let area = Rect {
        width: f.area().width.min(MAX_WIDTH),
        ..f.area()
    };
    let areas = Layout::vertical([
        Constraint::Length(3),
        Constraint::Length(4),
        Constraint::Length(STRATEGIES.len() as u16 + 4),
        Constraint::Length(3),
        Constraint::Min(0),
        Constraint::Length(1),
    ])
    .split(area);

    // What is being compared.
    f.render_widget(
        Paragraph::new(Line::from(vec![
            Span::styled(
                base.workload.name(),
                Style::default().fg(BILLED).add_modifier(Modifier::BOLD),
            ),
            label(format!("  ยท  {} concurrent  ยท  ", base.concurrency)),
            Span::raw(grouped(base.requests)),
            label(" requests each     broker "),
            Span::styled(
                base.broker_url
                    .trim_start_matches("http://")
                    .trim_start_matches("https://")
                    .trim_end_matches('/')
                    .to_string(),
                Style::default().fg(ACCENT),
            ),
        ]))
        .block(
            Block::default()
                .borders(Borders::ALL)
                .border_style(Style::default().fg(GREY))
                .title(Span::styled(
                    " zc bench --compare ",
                    Style::default().add_modifier(Modifier::BOLD),
                )),
        ),
        areas[0],
    );

    // The strategy in flight.
    let running = progress.running();
    let nth = progress.started().max(1).min(STRATEGIES.len());
    let title = match &running {
        Some((s, _, _)) => format!(" {} of {} ยท {} ", nth, STRATEGIES.len(), s.as_str()),
        None => match progress.is_over() {
            true => " done ".to_string(),
            false => format!(" {} of {} ยท starting ", nth, STRATEGIES.len()),
        },
    };
    let block = Block::default()
        .borders(Borders::ALL)
        .border_style(Style::default().fg(GREY))
        .title(Span::styled(
            title,
            Style::default().add_modifier(Modifier::BOLD),
        ));
    let inner = block.inner(areas[1]);
    f.render_widget(block, areas[1]);
    let rows = Layout::vertical([Constraint::Length(1), Constraint::Length(1)]).split(inner);
    if let Some((_, shared, started)) = &running {
        let done = shared.completed.load(Ordering::Relaxed);
        let ok = shared.successful.load(Ordering::Relaxed);
        let failed = shared.failed.load(Ordering::Relaxed);
        let elapsed = started.elapsed();
        let ratio = (done as f64 / base.requests.max(1) as f64).clamp(0.0, 1.0);
        f.render_widget(
            Gauge::default()
                .gauge_style(Style::default().fg(ACCENT))
                .ratio(ratio)
                .label(format!("{} / {}", grouped(done), grouped(base.requests))),
            rows[0],
        );
        let samples = shared
            .latencies
            .lock()
            .map(|l| l.clone())
            .unwrap_or_default();
        let (p50, _) = super::metrics::percentiles_us(&samples);
        f.render_widget(
            Paragraph::new(Line::from(vec![
                Span::styled(grouped(ok), Style::default().fg(FREE)),
                label(" ok ยท "),
                Span::styled(
                    grouped(failed),
                    Style::default().fg(match failed {
                        0 => GREY,
                        _ => Color::Indexed(203),
                    }),
                ),
                label(" failed     "),
                Span::styled(
                    format!("{:.1}", done as f64 / elapsed.as_secs_f64().max(0.001)),
                    Style::default().fg(BILLED).add_modifier(Modifier::BOLD),
                ),
                label(" req/s     "),
                Span::raw(fmt_us(p50)),
                label(" p50"),
            ])),
            rows[1],
        );
    } else {
        f.render_widget(
            Paragraph::new(label(match progress.is_over() {
                true => "every strategy measured",
                false => "startingโ€ฆ",
            })),
            rows[0],
        );
    }

    // The table, filling in.
    let done = progress.finished();
    let v = verdicts(&done);
    let block = Block::default()
        .borders(Borders::ALL)
        .border_style(Style::default().fg(GREY))
        .title(Span::styled(
            " strategies ",
            Style::default().add_modifier(Modifier::BOLD),
        ));
    let inner = block.inner(areas[2]);
    f.render_widget(block, areas[2]);

    let running_name = running.as_ref().map(|(s, _, _)| s.as_str());
    let rows: Vec<Row> = STRATEGIES
        .iter()
        .map(|s| {
            let finished = done.iter().position(|(d, _)| d == s);
            match finished {
                Some(i) => {
                    let r = &done[i].1;
                    let share = free_share(r);
                    let (free_run, billed_run) = super::layout::split_bar(
                        (share * 100.0).round() as u64,
                        ((1.0 - share) * 100.0).round() as u64,
                        14,
                    );
                    let mark = match (Some(i) == v.fastest, Some(i) == v.cheapest) {
                        (true, true) => "fastest, cheapest",
                        (true, false) => "fastest",
                        (false, true) => "cheapest",
                        _ => "",
                    };
                    Row::new(vec![
                        Cell::from("โœ“").style(Style::default().fg(FREE)),
                        Cell::from(s.as_str()),
                        Cell::from(format!("{:.1}", r.rps)),
                        Cell::from(fmt_us(super::metrics::percentile_us(&r.latencies_us, 50.0))),
                        Cell::from(fmt_us(super::metrics::percentile_us(&r.latencies_us, 99.0))),
                        Cell::from(Line::from(vec![
                            Span::styled(free_run, Style::default().fg(FREE)),
                            Span::styled(billed_run, Style::default().fg(BILLED)),
                            Span::raw(format!(" {:.0}%", share * 100.0)),
                        ])),
                        Cell::from(format!("{:.4}", r.total_charged)),
                        Cell::from(mark).style(Style::default().fg(BILLED)),
                    ])
                }
                None if running_name == Some(s.as_str()) => Row::new(vec![
                    Cell::from("โ–ถ").style(Style::default().fg(ACCENT)),
                    Cell::from(s.as_str()).style(Style::default().add_modifier(Modifier::BOLD)),
                    Cell::from("running").style(Style::default().fg(GREY)),
                ]),
                None => Row::new(vec![
                    Cell::from("ยท").style(Style::default().fg(GREY)),
                    Cell::from(s.as_str()).style(Style::default().fg(GREY)),
                    Cell::from(match progress.asked_to_stop() {
                        true => "skipped",
                        false => "queued",
                    })
                    .style(Style::default().fg(GREY)),
                ]),
            }
        })
        .collect();
    f.render_widget(
        Table::new(
            rows,
            [
                Constraint::Length(2),
                Constraint::Length(20),
                Constraint::Length(9),
                Constraint::Length(10),
                Constraint::Length(10),
                Constraint::Length(20),
                Constraint::Length(9),
                Constraint::Length(18),
                Constraint::Fill(1),
            ],
        )
        .header(
            Row::new(vec![
                "",
                "strategy",
                "req/s",
                "p50",
                "p99",
                "free / billed",
                "spend",
                "",
            ])
            .style(Style::default().fg(GREY)),
        ),
        inner,
    );

    // The recommendation, as soon as there is one to make. Each verdict
    // stands on its own: "most free" is absent when every strategy placed
    // its work the same way, and that must not take fastest and cheapest
    // down with it.
    let mut parts: Vec<Span> = Vec::new();
    for (name, idx, extra) in [
        ("fastest", v.fastest, None),
        ("cheapest", v.cheapest, None),
        (
            "most free",
            v.freest,
            v.freest
                .map(|i| format!("  ({:.0}% of the work)", free_share(&done[i].1) * 100.0)),
        ),
    ] {
        let Some(i) = idx else { continue };
        if !parts.is_empty() {
            parts.push(label("     "));
        }
        parts.push(label(format!("{name} ")));
        parts.push(Span::styled(
            done[i].0.as_str(),
            Style::default().fg(ACCENT),
        ));
        if let Some(e) = extra {
            parts.push(label(e));
        }
    }
    let verdict = match (parts.is_empty(), done.len()) {
        (false, _) => Line::from(parts),
        (true, 0) => Line::from(label("nothing measured yet")),
        // No winner is a result. Saying so, with the spread, beats naming one
        // from a gap that is inside the noise.
        (true, n) => Line::from(label(format!(
            "no clear winner โ€” all {n} within {:.1}% of each other on speed",
            v.rps_spread * 100.0
        ))),
    };
    f.render_widget(
        Paragraph::new(verdict).block(
            Block::default()
                .borders(Borders::ALL)
                .border_style(Style::default().fg(GREY)),
        ),
        areas[3],
    );

    f.render_widget(
        Paragraph::new(Line::from(vec![
            Span::styled(" q", Style::default().add_modifier(Modifier::BOLD)),
            label(" stop after this strategy  "),
            Span::styled("x", Style::default().add_modifier(Modifier::BOLD)),
            label(" abandon it and report"),
        ])),
        areas[5],
    );
}