tak-cli 0.0.14

Pre-v1 command-line benchmarking and performance tracking
Documentation
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
//! Progress for a benchmark run, on stderr.
//!
//! A long comparison — ten minutes of cold installs — is otherwise silent
//! until it finishes. On a terminal this draws one bar that redraws in place.
//! Anywhere else (CI logs) it prints a plain line at most every tenth of the
//! way or every 30 seconds, since a carriage-return animation turns into
//! thousands of lines in a log.
//!
//! The time remaining is estimated per subject: each subject's average sample
//! so far, prepare included, times the samples it still has to take. One
//! average over everything would be badly wrong exactly when it matters —
//! when a 20-second cold install shares a run with a 300ms one.
//!
//! A subject's one-time `setup` is shown while it runs but is not a sample:
//! it counts toward elapsed time and nothing else, so a minute-long clone
//! does not make every later sample look a minute long.

use crate::measure::Observer;
use std::io::{IsTerminal, Write};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, PoisonError};
use std::thread::JoinHandle;
use std::time::{Duration, Instant};

/// How often a non-terminal prints, at most, when no tenth has been crossed.
const LOG_EVERY: Duration = Duration::from_secs(30);

/// How often the ticker wakes. A terminal bar redraws its elapsed time this
/// often while a sample runs; a log checks whether LOG_EVERY has passed.
const TICK: Duration = Duration::from_secs(1);

/// The progress reporter. Samples can run for minutes — a cold install, or a
/// prepare step that re-downloads everything — so a ticker thread keeps the
/// output alive between them rather than only when one finishes.
pub struct Bar {
    state: Arc<Mutex<State>>,
    stop: Arc<AtomicBool>,
    ticker: Option<JoinHandle<()>>,
}

impl Bar {
    pub fn new(label: &str, names: Vec<String>) -> Self {
        let state = Arc::new(Mutex::new(State::new(label, names)));
        let stop = Arc::new(AtomicBool::new(false));
        let ticker = {
            let (state, stop) = (Arc::clone(&state), Arc::clone(&stop));
            std::thread::spawn(move || {
                while !stop.load(Ordering::Relaxed) {
                    std::thread::park_timeout(TICK);
                    if !stop.load(Ordering::Relaxed) {
                        lock(&state).tick();
                    }
                }
            })
        };
        Bar {
            state,
            stop,
            ticker: Some(ticker),
        }
    }

    /// Stop the ticker and clear the bar so results print on a clean line.
    /// Call once the run is over, whatever its outcome.
    pub fn finish(&mut self) {
        self.stop.store(true, Ordering::Relaxed);
        if let Some(t) = self.ticker.take() {
            t.thread().unpark();
            t.join().ok();
        }
        lock(&self.state).clear();
    }
}

impl Drop for Bar {
    fn drop(&mut self) {
        self.finish();
    }
}

/// A panic elsewhere must not also take the progress output down with it.
fn lock(state: &Mutex<State>) -> std::sync::MutexGuard<'_, State> {
    state.lock().unwrap_or_else(PoisonError::into_inner)
}

impl Observer for Bar {
    fn planned(&mut self, remaining: &[u64]) {
        lock(&self.state).planned(remaining);
    }
    fn setting_up(&mut self, subject: usize) {
        lock(&self.state).setting_up(subject);
    }
    fn started(&mut self, subject: usize) {
        lock(&self.state).started(subject);
    }
    fn finished(&mut self, subject: usize, elapsed: Duration) {
        lock(&self.state).finished(subject, elapsed);
    }
    fn dropped(&mut self, subject: usize) {
        lock(&self.state).dropped(subject);
    }
}

struct State {
    label: String,
    names: Vec<String>,
    remaining: Vec<u64>,
    /// Per subject: total time and count of finished samples.
    spent: Vec<(Duration, u32)>,
    done: u64,
    current: Option<usize>,
    /// Whether `current` is running its setup rather than a sample.
    in_setup: bool,
    started: Instant,
    tty: bool,
    last_log: Instant,
    last_tenth: u64,
    drawn: bool,
}

impl State {
    fn new(label: &str, names: Vec<String>) -> Self {
        let n = names.len();
        let now = Instant::now();
        State {
            label: label.to_string(),
            names,
            remaining: vec![0; n],
            spent: vec![(Duration::ZERO, 0); n],
            done: 0,
            current: None,
            in_setup: false,
            started: now,
            tty: std::io::stderr().is_terminal(),
            last_log: now,
            last_tenth: 0,
            drawn: false,
        }
    }

    fn total(&self) -> u64 {
        self.done + self.remaining.iter().sum::<u64>()
    }

    /// Estimated time left, or `None` until anything has been timed.
    fn eta(&self) -> Option<Duration> {
        let (all, n) = self
            .spent
            .iter()
            .fold((Duration::ZERO, 0u32), |(t, c), &(d, k)| (t + d, c + k));
        if n == 0 {
            return None;
        }
        // A subject not yet timed is guessed at the average of those that
        // were, which is replaced by its own the moment it has one.
        let fallback = all / n;
        let secs: f64 = self
            .remaining
            .iter()
            .zip(&self.spent)
            .map(|(&left, &(d, k))| {
                let each = if k == 0 { fallback } else { d / k };
                each.as_secs_f64() * left as f64
            })
            .sum();
        Some(Duration::from_secs_f64(secs))
    }

    fn line(&self, width: usize) -> String {
        let total = self.total().max(1);
        let pct = self.done * 100 / total;
        let eta = if self.remaining.iter().all(|&r| r == 0) && self.done > 0 {
            "done".to_string()
        } else {
            self.eta()
                .map_or_else(|| "estimating".to_string(), |d| format!("~{} left", fmt(d)))
        };
        let who = match self.current {
            Some(i) if self.in_setup => format!("setup {}", self.names[i]),
            Some(i) => self.names[i].clone(),
            None => String::new(),
        };
        let tail = format!(
            " {}/{} {pct:>3}%  {} elapsed, {eta}  {who}",
            self.done,
            total,
            fmt(self.started.elapsed())
        );
        if !self.tty {
            return format!("  {}:{tail}", self.label);
        }
        // Whatever width is left for the bar itself, within reason.
        let room = width.saturating_sub(self.label.len() + tail.len() + 6);
        let cells = room.clamp(10, 30);
        let filled = (cells as u64 * self.done / total) as usize;
        let line = format!(
            "  {} [{}{}]{tail}",
            self.label,
            "#".repeat(filled),
            "-".repeat(cells - filled)
        );
        line.chars().take(width.saturating_sub(1)).collect()
    }

    fn draw(&mut self, force: bool) {
        if self.tty {
            let width = std::env::var("COLUMNS")
                .ok()
                .and_then(|c| c.parse().ok())
                .unwrap_or(80);
            eprint!("\r\x1b[2K{}", self.line(width));
            std::io::stderr().flush().ok();
            self.drawn = true;
            return;
        }
        let tenth = self.done * 10 / self.total().max(1);
        if force || tenth > self.last_tenth || self.last_log.elapsed() >= LOG_EVERY {
            eprintln!("{}", self.line(usize::MAX));
            self.last_tenth = tenth;
            self.last_log = Instant::now();
        }
    }

    /// Called by the ticker between events: redraw a terminal bar so its
    /// elapsed time keeps moving, and give a log its periodic line even while
    /// one long sample is still running.
    fn tick(&mut self) {
        if self.total() == 0 {
            return;
        }
        if self.tty {
            if self.drawn {
                self.draw(false);
            }
        } else if self.last_log.elapsed() >= LOG_EVERY {
            self.draw(true);
        }
    }

    fn clear(&mut self) {
        if self.tty && self.drawn {
            eprint!("\r\x1b[2K");
            std::io::stderr().flush().ok();
            self.drawn = false;
        }
    }
}

impl Observer for State {
    fn planned(&mut self, remaining: &[u64]) {
        self.remaining = remaining.to_vec();
        self.draw(false);
    }

    fn setting_up(&mut self, subject: usize) {
        self.current = Some(subject);
        self.in_setup = true;
        // Forced in a log too: a setup can take minutes, and the line saying
        // which one is running is the only sign the run has not hung.
        self.draw(true);
    }

    fn started(&mut self, subject: usize) {
        self.current = Some(subject);
        self.in_setup = false;
        if self.tty {
            self.draw(false);
        }
    }

    fn finished(&mut self, subject: usize, elapsed: Duration) {
        self.remaining[subject] = self.remaining[subject].saturating_sub(1);
        let (d, k) = &mut self.spent[subject];
        *d += elapsed;
        *k += 1;
        self.done += 1;
        self.current = None;
        let last = self.remaining.iter().all(|&r| r == 0);
        self.draw(last);
    }

    fn dropped(&mut self, subject: usize) {
        self.remaining[subject] = 0;
        self.current = None;
        self.in_setup = false;
        self.draw(false);
    }
}

/// `850ms`, `42s`, `3m05s`, `1h02m`.
pub fn fmt(d: Duration) -> String {
    let s = d.as_secs();
    match s {
        0 => format!("{}ms", d.as_millis()),
        1..60 => format!("{s}s"),
        60..3600 => format!("{}m{:02}s", s / 60, s % 60),
        _ => format!("{}h{:02}m", s / 3600, (s % 3600) / 60),
    }
}

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

    fn bar(names: &[&str]) -> State {
        let mut b = State::new("b", names.iter().map(|s| s.to_string()).collect());
        b.tty = false;
        b.last_log = Instant::now();
        b
    }

    #[test]
    fn durations_read_naturally() {
        assert_eq!(fmt(Duration::from_millis(850)), "850ms");
        assert_eq!(fmt(Duration::from_secs(42)), "42s");
        assert_eq!(fmt(Duration::from_secs(185)), "3m05s");
        assert_eq!(fmt(Duration::from_secs(3720)), "1h02m");
    }

    /// The estimate prices each subject's remaining samples at its own speed,
    /// so a slow subject's backlog is not averaged away by a fast one.
    #[test]
    fn the_estimate_is_per_subject() {
        let mut b = bar(&["fast", "slow"]);
        b.planned(&[11, 6]);
        b.finished(0, Duration::from_millis(100));
        b.finished(1, Duration::from_secs(20));
        // 10 x 100ms + 5 x 20s
        let eta = b.eta().unwrap().as_secs_f64();
        assert!((eta - 101.0).abs() < 0.01, "{eta}");
    }

    #[test]
    fn an_untimed_subject_is_guessed_at_the_average() {
        let mut b = bar(&["a", "b"]);
        b.planned(&[2, 3]);
        assert_eq!(b.eta(), None, "nothing timed yet");
        b.finished(0, Duration::from_secs(2));
        // 1 x 2s for a, 3 x 2s for b until b has a time of its own
        assert_eq!(b.eta(), Some(Duration::from_secs(8)));
    }

    #[test]
    fn a_dropped_subject_leaves_the_estimate() {
        let mut b = bar(&["a", "b"]);
        b.planned(&[2, 5]);
        b.finished(0, Duration::from_secs(1));
        b.finished(1, Duration::from_secs(10));
        b.dropped(1);
        assert_eq!(b.eta(), Some(Duration::from_secs(1)));
        assert_eq!(b.total(), 3);
    }

    #[test]
    fn the_bar_fits_the_terminal() {
        let mut b = bar(&["aube"]);
        b.tty = true;
        b.planned(&[40]);
        for _ in 0..10 {
            b.finished(0, Duration::from_millis(250));
        }
        let line = b.line(80);
        assert!(line.chars().count() < 80, "{line}");
        assert!(line.contains("10/40") && line.contains("25%"), "{line}");
        assert!(line.contains("~7s left"), "{line}");
    }

    /// A log gets a line every LOG_EVERY even when no sample has finished —
    /// the case of one very long prepare step or sample.
    #[test]
    fn a_log_hears_from_a_long_sample_before_it_finishes() {
        let mut b = bar(&["slow"]);
        b.planned(&[5]);
        b.started(0);
        let before = b.last_log;
        b.tick();
        assert_eq!(b.last_log, before, "too soon to log again");
        b.last_log = Instant::now() - LOG_EVERY;
        b.tick();
        assert!(b.last_log > before, "the ticker logged mid-sample");
    }

    /// A setup is named while it runs but is not a sample: it neither
    /// advances the count nor enters the estimate.
    #[test]
    fn setup_is_shown_but_not_counted() {
        let mut b = bar(&["aube", "pnpm"]);
        b.planned(&[2, 2]);
        b.setting_up(1);
        assert!(
            b.line(usize::MAX).ends_with("setup pnpm"),
            "{}",
            b.line(usize::MAX)
        );
        assert_eq!((b.done, b.eta()), (0, None));
        b.started(0);
        assert!(
            b.line(usize::MAX).ends_with(" aube"),
            "{}",
            b.line(usize::MAX)
        );
        b.finished(0, Duration::from_secs(1));
        assert_eq!(b.eta(), Some(Duration::from_secs(3)));
    }

    /// The ticker thread starts and stops cleanly, and finishing twice (the
    /// explicit call, then Drop) is harmless.
    #[test]
    fn the_ticker_stops_when_finished() {
        let mut b = Bar::new("b", vec!["a".into()]);
        b.planned(&[1]);
        b.finished(0, Duration::from_millis(1));
        b.finish();
        assert!(b.ticker.is_none());
    }
}