zc2 0.0.42

P2P compute broker with credit-based billing, WAL, and broker mesh support
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
//! The live view: one block, repainted in place while the run goes on.
//!
//! Four bands, always in the same order — how far, what shape, where it ran,
//! what the keys do. They never move, so between repaints the eye lands in
//! the same place instead of re-reading the screen.
//!
//! Every band sizes itself to the terminal and drops its least important
//! column rather than wrapping. A wrapped line turns each repaint into
//! confetti, because the cursor-up count no longer matches what was drawn.

use std::time::Duration;

use colored::Colorize;

use super::layout::{
    bar, eta, fmt_tick, fmt_us, grouped, pad, short_duration, short_worker, spark, split_bar,
    trim_lines, visible_width, Muted,
};
use super::metrics::{
    percentile_us, percentiles_us, Buckets, Ledger, Placement, RateRing, MAX_BUCKET_ROWS,
    MIN_RATE_SAMPLES,
};

/// Below this the two distributions sit side by side; above it they stack.
const TWO_COLUMN_MIN: usize = 104;

/// The widest the block ever lays itself out.
///
/// Every panel in it has a natural size — a bar caps at 28 or 40 cells, a
/// column at what it holds — so on a very wide terminal the block stops
/// growing at about this point while the progress line, which right-aligns
/// its rate against the full width, kept going: the rates ended up eighty
/// columns adrift of a block that was only a hundred wide.
const MAX_VIEW_WIDTH: usize = 118;

/// Everything the live block draws, gathered so the renderer takes one
/// argument instead of eleven.
#[derive(Clone, Copy)]
pub(crate) struct LiveView<'a> {
    pub(crate) spin: char,
    pub(crate) done: u64,
    pub(crate) total: u64,
    pub(crate) ok: u64,
    pub(crate) failed: u64,
    pub(crate) elapsed: Duration,
    pub(crate) samples: &'a [u64],
    pub(crate) ledger: &'a Ledger,
    pub(crate) rates: &'a RateRing,
    pub(crate) width: usize,
}

impl LiveView<'_> {
    pub(crate) fn render(&self) -> String {
        // Lay out for the widest the block is ever worth, not for the window.
        if self.width > MAX_VIEW_WIDTH {
            return LiveView {
                width: MAX_VIEW_WIDTH,
                ..*self
            }
            .render();
        }
        let mut out = String::new();
        self.progress(&mut out);
        self.distributions(&mut out);
        self.placement(&mut out);
        self.keys(&mut out);
        trim_lines(&out)
    }

    // -- band 1: how far, how fast, how much longer -------------------------

    fn progress(&self, out: &mut String) {
        let w = self.width;
        let pct = self.done as f64 / self.total.max(1) as f64;
        let counter = format!("{} / {}", grouped(self.done), grouped(self.total));
        let long_when = match eta(self.done, self.total, self.elapsed) {
            Some(left) => format!(
                "{} · eta {}",
                short_duration(self.elapsed),
                short_duration(left)
            ),
            None => short_duration(self.elapsed),
        };
        // Lay the line out with no bar, measure what that costs, and give the
        // bar exactly what is left. Hand-counting the format string drifts the
        // moment the format changes; measuring cannot.
        let line = |b: &str, when: &str| {
            format!(
                "  {}  {}{}  {}   {}",
                self.spin.to_string().cyan(),
                pad(&counter, 20, false),
                b,
                pad(&format!("{:.1}%", pct * 100.0), 6, true),
                when.muted(),
            )
        };
        let when = match w.saturating_sub(visible_width(&line("", &long_when))) >= 8 {
            true => long_when,
            false => short_duration(self.elapsed),
        };
        let bar_w = w.saturating_sub(visible_width(&line("", &when))).min(34);
        // A run that has done something shows something: rounding 0.8% of a
        // 34-cell bar to zero draws a bar that has not started.
        let filled = match (pct * bar_w as f64).round() as usize {
            0 if pct > 0.0 => 1,
            n => n,
        };
        let progress = format!(
            "{}{}",
            "█".repeat(filled.min(bar_w)).cyan(),
            "·".repeat(bar_w.saturating_sub(filled)).muted()
        );
        out.push_str(&line(&progress, &when));
        out.push('\n');

        // Outcomes and rate, with the least important figures dropped first.
        let (p50, _) = percentiles_us(self.samples);
        let outcome = format!(
            "     {} · {}",
            pad(
                &format!("{} {}", grouped(self.ok).green(), "ok".muted()),
                10,
                false
            ),
            match self.failed {
                0 => format!("{} {}", "0".muted(), "failed".muted()),
                n => format!("{} {}", grouped(n).red(), "failed".muted()),
            },
        );
        let now = self.rates.now(5, self.done, self.elapsed);
        let mean = self.done as f64 / self.elapsed.as_secs_f64().max(0.001);
        let now_s = format!("{now:.1}");
        let mean_s = format!("{mean:.1}");
        let peak_s = self.rates.peak().to_string();
        let tails = [
            format!(
                "{} {}  ·  {} {}  ·  {} {}  ·  {} {}",
                now_s.clone().yellow().bold(),
                "req/s now".muted(),
                mean_s,
                "avg".muted(),
                peak_s,
                "peak".muted(),
                fmt_us(p50),
                "p50".muted(),
            ),
            format!(
                "{} {}  ·  {} {}",
                format!("{now:.1}").yellow().bold(),
                "req/s".muted(),
                fmt_us(p50),
                "p50".muted(),
            ),
            format!(
                "{} {}",
                format!("{now:.1}").yellow().bold(),
                "req/s".muted()
            ),
        ];
        let tail = tails
            .iter()
            .find(|t| visible_width(&outcome) + 4 + visible_width(t) <= w)
            .cloned()
            .unwrap_or_default();
        let gap = w
            .saturating_sub(visible_width(&outcome) + visible_width(&tail))
            .max(2);
        out.push_str(&format!("{outcome}{}{tail}\n", " ".repeat(gap)));

        // The rate over time. One line, and the only thing on the screen that
        // can show a collapse while it is happening.
        let series = self.rates.as_f64();
        if !series.is_empty() {
            let room = w.saturating_sub(24);
            let shown: Vec<f64> = series.iter().rev().take(room).rev().copied().collect();
            out.push_str(&format!(
                "     {}{}  {}\n",
                pad(&"rate".muted(), 8, false),
                spark(&shown).green(),
                format!("last {}s", shown.len()).muted(),
            ));
        }
        out.push('\n');
    }

    // -- band 2: the two distributions --------------------------------------

    fn distributions(&self, out: &mut String) {
        let lat = Buckets::of(self.samples, MAX_BUCKET_ROWS);
        let thr = Buckets::linear(self.rates.per_second(), 7);
        let lat_rows: Vec<usize> = lat.interesting().collect();
        let lat_label_w = lat_rows
            .iter()
            .map(|i| visible_width(&lat.label(*i, &fmt_tick)))
            .max()
            .unwrap_or(8);

        let thr_fmt = |v: u64| format!("{v} req/s");
        let thr_rows: Vec<usize> = match self.rates.per_second().len() < MIN_RATE_SAMPLES {
            true => Vec::new(),
            false => thr.interesting().collect(),
        };
        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 + 8 + 5;
        let right_fixed = thr_label_w + 1 + 6 + 5;
        let gutter = 6;
        let room = self.width.saturating_sub(left_fixed + right_fixed + gutter) as f64;
        let two_col = self.width >= TWO_COLUMN_MIN && !thr_rows.is_empty() && room >= 22.0;

        let (lat_bar, thr_bar) = match two_col {
            true => {
                let l = ((room * 0.58) as usize).min(28);
                (l, (room as usize - l).min(20))
            }
            false => (self.width.saturating_sub(left_fixed).min(34), 0),
        };

        // Header
        let mut head = format!(
            "  {}{}{}{}",
            pad(&"latency".bold().to_string(), lat_label_w + 1, false),
            " ".repeat(lat_bar),
            pad(&"n".muted(), 8, true),
            pad(&"%".muted(), 5, true),
        );
        if two_col {
            head.push_str(&format!(
                "   {}  {}{}{}",
                "│".muted(),
                pad(
                    &"throughput".bold().to_string(),
                    thr_label_w + 1 + thr_bar,
                    false
                ),
                pad(&"secs".muted(), 6, true),
                pad(&"%".muted(), 5, true),
            ));
        }
        out.push_str(&head);
        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);

        // The right column carries the percentile summary under its bars, so
        // the two columns end at roughly the same depth.
        let (p50, p99) = percentiles_us(self.samples);
        let extras = [
            format!(
                "{} {}   {} {}   {} {}",
                "p50".muted(),
                fmt_us(p50),
                "p90".muted(),
                fmt_us(percentile_us(self.samples, 90.0)),
                "p99".muted(),
                fmt_us(p99),
            ),
            format!(
                "{} {}   {} {}",
                "min".muted(),
                fmt_us(self.samples.iter().copied().min().unwrap_or(0)),
                "max".muted(),
                fmt_us(self.samples.iter().copied().max().unwrap_or(0)),
            ),
        ];

        for (row, i) in lat_rows.iter().enumerate() {
            let n = lat.counts[*i];
            // Latency that landed where a local worker lands is cyan; the
            // slower modes, which on a mixed run are the peers, are yellow.
            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), 8, true),
                pad(
                    &match n {
                        0 => String::new(),
                        _ => format!("{:.0}%", n as f64 / lat_total as f64 * 100.0),
                    }
                    .muted()
                    .to_string(),
                    5,
                    true
                ),
            );
            if two_col {
                line.push_str(&format!("   {}  ", "│".muted()));
                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(), 6, true),
                        pad(
                            &format!("{:.0}%", tn as f64 / thr_total as f64 * 100.0)
                                .muted()
                                .to_string(),
                            5,
                            true
                        ),
                    ));
                } else if let Some(extra) = row
                    .checked_sub(thr_rows.len() + 1)
                    .and_then(|k| extras.get(k))
                {
                    // One blank row between the last throughput bucket and
                    // the percentile summary, so they do not read as one
                    // table.
                    line.push_str(extra);
                }
            }
            out.push_str(&line);
            out.push('\n');
        }
        if !two_col {
            for e in &extras {
                out.push_str(&format!("  {e}\n"));
            }
        }
        out.push('\n');
    }

    // -- band 3: where it ran, and what it cost -----------------------------

    fn placement(&self, out: &mut String) {
        let w = self.width;
        if self.ledger.is_empty() {
            out.push_str(&format!("  {}\n\n", "nothing has been routed yet".muted()));
            return;
        }
        let (free_n, _) = self.ledger.totals(Placement::Free);
        let (billed_n, billed_zkcr) = self.ledger.totals(Placement::Billed);
        let placed = self.ledger.placed().max(1);

        // The headline: one bar, solid for what was free and shaded for what
        // was billed. This is the question `zc bench` exists to answer that
        // no HTTP benchmark has to.
        let free_pct = format!("{:.0}%", free_n as f64 / placed as f64 * 100.0);
        let billed_pct = format!("{:.0}%", billed_n as f64 / placed as f64 * 100.0);
        let spend = format!("{billed_zkcr:.4}");
        let summaries = [
            format!(
                "{} {} {}   ·   {} {}  {} {}",
                "free".muted(),
                free_pct.clone().green().bold(),
                "of the work".muted(),
                "billed".muted(),
                billed_pct.clone().yellow().bold(),
                spend.clone().yellow(),
                "zkcr".muted(),
            ),
            format!(
                "{} {}  ·  {} {}  {}",
                "free".muted(),
                free_pct.clone().green().bold(),
                "billed".muted(),
                billed_pct.clone().yellow().bold(),
                spend.clone().yellow(),
            ),
            format!(
                "{} {} {} {}",
                free_pct.green().bold(),
                "free".muted(),
                billed_pct.yellow().bold(),
                spend.yellow(),
            ),
        ];
        let label = pad(&"placement".bold().to_string(), 11, false);
        // Pick the longest summary that leaves room for a readable bar, and
        // only then give the bar what is left.
        let (summary, bar_w) = summaries
            .iter()
            .map(|s| {
                let room = w.saturating_sub(2 + 11 + 4 + visible_width(s)).min(40);
                (s, room)
            })
            .find(|(_, room)| *room >= 12)
            .unwrap_or_else(|| {
                let last = summaries.last().unwrap();
                (
                    last,
                    w.saturating_sub(2 + 11 + 4 + visible_width(last)).min(40),
                )
            });
        if bar_w >= 8 {
            let (free, billed) = split_bar(free_n, billed_n, bar_w);
            out.push_str(&format!(
                "  {}{}{}    {}\n\n",
                label,
                free.green(),
                billed.yellow(),
                summary
            ));
        } else {
            out.push_str(&format!("  {}{}\n\n", label, summary));
        }

        // The per-node table. Columns drop right to left as the terminal
        // narrows; the node, its share and its cost are the last to go.
        let cols = Columns::for_width(w);
        out.push_str(&cols.header());
        out.push('\n');
        let mut last_class = None;
        for (class, node, stat) in self.ledger.rows().into_iter().take(8) {
            let shown_class = match Some(class) == last_class {
                true => String::new(),
                false => class.as_str().to_string(),
            };
            last_class = Some(class);
            out.push_str(&cols.row(
                &shown_class,
                class,
                &node,
                &stat.via(),
                stat.workers.len(),
                stat.requests,
                stat.requests as f64 / placed as f64 * 100.0,
                stat.p50_us(),
                stat.expectation.avg_expected_ms(),
                stat.expectation.is_miscalibrated(),
                stat.charged_zkcr,
            ));
            out.push('\n');
        }

        // What it will cost if it keeps going like this. A run that is 2%
        // through and has spent 4 credits is worth knowing about at minute
        // one, not minute forty.
        if billed_n > 0 && self.done > 0 && self.done < self.total {
            let projected = billed_zkcr / self.done as f64 * self.total as f64;
            out.push_str(&format!(
                "  {}{} {} {}\n",
                " ".repeat(11),
                format!("{billed_n} of {} billed", grouped(self.done)).muted(),
                "· projected total".muted(),
                format!("{projected:.4} zkcr").yellow().bold(),
            ));
        }
        out.push('\n');
    }

    fn keys(&self, out: &mut String) {
        let full = format!(
            "  {} {}    ·    {} {}",
            "ctrl-c".white(),
            "stop & report".muted(),
            "--json".white(),
            "machine output".muted(),
        );
        let short = format!("  {} {}", "ctrl-c".white(), "stop & report".muted());
        out.push_str(match visible_width(&full) <= self.width {
            true => &full,
            false => &short,
        });
        out.push('\n');
    }
}

/// The per-node table's columns, chosen for the terminal in front of us.
struct Columns {
    class: usize,
    node: usize,
    via: usize,
    req: usize,
    share: usize,
    p50: usize,
    router: usize,
    spend: usize,
}

impl Columns {
    /// Widths for `w` columns. Each variant is a whole layout rather than a
    /// column shaved off the last: a table that merely gets tighter as the
    /// window narrows becomes unreadable before it becomes narrow enough.
    fn for_width(w: usize) -> Columns {
        match w {
            0..=71 => Columns {
                class: 9,
                node: 18,
                via: 0,
                req: 8,
                share: 0,
                p50: 0,
                router: 0,
                spend: 13,
            },
            72..=93 => Columns {
                class: 9,
                node: 22,
                via: 0,
                req: 8,
                share: 7,
                p50: 10,
                router: 0,
                spend: 13,
            },
            94..=113 => Columns {
                class: 10,
                node: 26,
                via: 0,
                req: 8,
                share: 8,
                p50: 11,
                router: 16,
                spend: 14,
            },
            _ => Columns {
                class: 10,
                node: 26,
                via: 9,
                req: 8,
                share: 8,
                p50: 11,
                router: 16,
                spend: 14,
            },
        }
    }

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

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

    fn header(&self) -> String {
        format!(
            "  {}{}{}{}{}{}{}{}",
            " ".repeat(self.class),
            pad(&"node".muted(), self.node, false),
            Self::left(self.via, "via".muted()),
            Self::cell(self.req, "req".muted()),
            Self::cell(self.share, "share".muted()),
            Self::cell(self.p50, "p50".muted()),
            Self::cell(self.router, "router said".muted()),
            Self::cell(self.spend, "spend".muted()),
        )
    }

    #[allow(clippy::too_many_arguments)]
    fn row(
        &self,
        shown_class: &str,
        class: Placement,
        node: &str,
        via: &str,
        workers: usize,
        req: u64,
        share: f64,
        p50_us: u64,
        expected_ms: Option<f64>,
        miscalibrated: bool,
        spend: f64,
    ) -> String {
        let tint = match class {
            Placement::Free => colored::Color::Green,
            Placement::Billed => colored::Color::Yellow,
        };
        let name = match workers {
            0 | 1 => short_worker(node),
            n => format!("{} · {n} workers", short_worker(node)),
        };
        let router = match expected_ms {
            Some(ms) => {
                let t = super::layout::fmt_ms(ms);
                match miscalibrated {
                    true => format!("{} {}", t, "⚠".red()),
                    false => t,
                }
            }
            None => "—".muted(),
        };
        format!(
            "  {}{}{}{}{}{}{}{}",
            pad(
                &shown_class.color(tint).bold().to_string(),
                self.class,
                false
            ),
            pad(&name.cyan().to_string(), self.node, false),
            Self::left(self.via, via.muted()),
            Self::cell(self.req, grouped(req)),
            Self::cell(self.share, format!("{share:.1}%").muted()),
            Self::cell(self.p50, fmt_us(p50_us)),
            Self::cell(self.router, router),
            Self::cell(
                self.spend,
                match class {
                    Placement::Free => "free".green().to_string(),
                    Placement::Billed => format!("{spend:.4} zkcr").yellow().to_string(),
                }
            ),
        )
    }
}