sqlload 0.61.0

SQL data loading tooling.
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
//! What `load` writes as it runs, rendered from its load events: a line per table as it finishes, `--events` as JSON lines, the summary it ends with, and on a terminal the block it redraws in place while tables load: how many are done, each running table and what it is doing, what waits, and the rate limits in use.

use std::collections::BTreeMap;
use std::io::{IsTerminal, Write};
use std::sync::PoisonError;
use std::time::Duration;

use tokio::sync::mpsc::UnboundedReceiver;

use crate::command::_helpers::logging::LIVE_BLOCK;
use crate::command::_helpers::output::{paint, print_lines};
use crate::command::constants::PLAN_TREE_HINT;
use crate::load_events::main::event_line::event_line;
use crate::load_events::main::phase_summary::phase_summary;
use crate::load_events::main::progress_view::progress_view;
use crate::load_events::models::{EventKind, LoadEvent, ProgressView, StepView};
use crate::loader::constants::{
    BOLD, CYAN, DICT_HINT_MILLISECONDS, DICT_HINT_ROWS, DIM, INVERSE, RED, RESET, YELLOW,
};
use crate::loader::models::ProjectPlan;
use crate::number_text::main::memory_text::memory_text;
use crate::number_text::main::thousands::thousands;
use crate::python_sources::models::TransformTime;

/// The width of a tally line's verb column: `loaded` or `failed` and two spaces.
const VERB_COLUMN: usize = 8;

/// The width of a summary branch's label column.
const SUMMARY_LABEL: usize = 13;

/// How often the live block redraws.
const LIVE_REDRAW: std::time::Duration = std::time::Duration::from_millis(100);

/// The most redraws a second the live block's draw target allows.
const LIVE_HZ: u8 = 10;

/// The width the live block assumes when the terminal's is unknown.
const MAX_LIVE_WIDTH: usize = 112;

/// How many tables a summary names before `+N more`.
const NAMED_TABLES: usize = 3;

/// Spinner frames, one per redraw.
const SPINNER: [char; 10] = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];

/// How many queued tables the block names before `…`.
const QUEUED_NAMED: usize = 3;

/// The width of a running table's name column.
const NAME_COLUMN: usize = 28;

/// The widest the block draws, however wide the terminal.
const MAX_WIDTH: usize = 112;

/// How long a step before the plan runs before its spinner shows, so fast runs stay clean.
const SPINNER_DELAY: Duration = Duration::from_millis(300);

/// How often a step before the plan that is still running prints a `RUNNING` row.
const RUNNING_EVERY: Duration = Duration::from_secs(30);

/// How long after a wait a connection's rate limit still shows as in use.
const RATE_RECENT: Duration = Duration::from_millis(1500);

/// The columns of the live block's bar line besides the badge, the bar and its counts: a space before the bar, two spaces before the counts, and one short of the edge so the line never wraps.
const BAR_LINE_GAPS: usize = 3 + 1;

/// Where a load's lines go: printed as they come (`print`), or kept to return with the rest.
#[derive(Debug)]
pub(crate) struct LoadOutput {
    /// The width of the table-name column: the widest selected table's name and two spaces.
    pub(crate) name_width: usize,
    /// The width of the rows column: the widest row count the plan expects, with separators, and at least 5.
    pub(crate) rows_width: usize,
    pub(crate) print: bool,
    pub(crate) no_color: bool,
    /// Where `--events` writes each event as a JSON line, if anywhere.
    pub(crate) events: Option<EventsTarget>,
    /// The block drawn on stderr while tables load, when it is drawn.
    pub(crate) live: Option<LiveState>,
}

/// Where `--events` writes: stderr, or the `--events-file`.
#[derive(Debug)]
pub(crate) enum EventsTarget {
    Stderr,
    File(std::fs::File),
}

impl EventsTarget {
    /// Write `line` and a newline, and flush it.
    fn write_line(&mut self, line: &str) {
        let _ = match self {
            Self::Stderr => {
                let mut stderr = std::io::stderr().lock();
                writeln!(stderr, "{line}").and_then(|()| stderr.flush())
            }
            Self::File(file) => writeln!(file, "{line}").and_then(|()| file.flush()),
        };
    }
}

/// What the events said happened, for the summary.
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub(crate) struct Tally {
    pub(crate) loaded: usize,
    pub(crate) failed: usize,
    pub(crate) not_started: Vec<String>,
    pub(crate) rows: u64,
    /// The table that took longest to load, and how long.
    pub(crate) slowest: Option<(String, u64)>,
    /// The most memory the whole process held at once, in bytes, as the run's end reported it.
    pub(crate) peak_memory_bytes: Option<u64>,
}

impl Tally {
    /// `event` counted in.
    pub(crate) fn add(&mut self, event: &LoadEvent) {
        let table = event.table.clone().unwrap_or_default();
        match &event.kind {
            EventKind::TableDone {
                rows, elapsed_ms, ..
            } => {
                self.loaded += 1;
                self.rows += rows;
                if self
                    .slowest
                    .as_ref()
                    .is_none_or(|(_, slowest)| elapsed_ms > slowest)
                {
                    self.slowest = Some((table, *elapsed_ms));
                }
            }
            EventKind::TableFailed { .. } => self.failed += 1,
            EventKind::TableNotStarted { .. } => self.not_started.push(table),
            EventKind::RunFinished {
                peak_memory_bytes, ..
            } => self.peak_memory_bytes = *peak_memory_bytes,
            _ => {}
        }
    }
}

/// A table loading now.
#[derive(Debug, Clone, PartialEq, Eq)]
struct Running {
    table: String,
    strategy: String,
    rows: u64,
    /// What it is doing: `batch 3`, `committing`, or empty before its first progress.
    doing: String,
    committing: bool,
    /// Under `load --follow`, the rows of the batches written so far, which the rows of the one being written add to, and how many.
    written: (u64, u64),
}

/// What the block shows, as the events left it.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub(crate) struct LiveState {
    /// The tables to load, in the order they may start.
    waiting: Vec<String>,
    total: usize,
    done: usize,
    /// Rows of the tables that finished.
    finished_rows: u64,
    running: Vec<Running>,
    fail_fast: bool,
    /// The table whose failure stopped new tables starting under `--fail-fast`.
    stopped_after: Option<String>,
    /// Each connection with a `rate_limit`: its limit and when a request last waited, as time since the load started.
    rates: BTreeMap<String, (String, Option<Duration>)>,
    /// `load --follow`: the tables stream until it stops.
    follow: bool,
}

impl LiveState {
    /// The state before any event: `tables` to load, in plan order, and whether the load stops starting tables at the first failure.
    pub(crate) fn new(tables: Vec<String>, fail_fast: bool) -> Self {
        Self {
            total: tables.len(),
            waiting: tables,
            fail_fast,
            ..Self::default()
        }
    }

    /// The state of `load --follow`, whose tables stream until it stops.
    pub(crate) fn following(self) -> Self {
        Self {
            follow: true,
            ..self
        }
    }

    /// `event`, which happened `at` into the load, taken in.
    pub(crate) fn apply(&mut self, event: &LoadEvent, at: Duration) {
        let table = event.table.clone().unwrap_or_default();
        match &event.kind {
            EventKind::TableStarted { strategy } => {
                self.waiting.retain(|waiting| *waiting != table);
                self.running.push(Running {
                    table,
                    strategy: strategy.clone(),
                    rows: 0,
                    doing: String::new(),
                    committing: false,
                    written: (0, 0),
                });
            }
            EventKind::TableProgress { unit, count, rows } => {
                if let Some(running) = self.running_mut(&table) {
                    running.rows = running.written.0 + rows;
                    running.doing = format!("{unit} {count}");
                }
            }
            EventKind::TableCommitting { rows } => {
                if let Some(running) = self.running_mut(&table) {
                    running.rows = running.written.0 + rows;
                    running.doing = "committing".to_owned();
                    running.committing = true;
                }
            }
            EventKind::TableBatchWritten { rows, .. } => {
                if let Some(running) = self.running_mut(&table) {
                    running.written = (running.written.0 + rows, running.written.1 + 1);
                    running.rows = running.written.0;
                    running.doing = match running.written.1 {
                        1 => "1 batch written".to_owned(),
                        batches => format!("{batches} batches written"),
                    };
                    running.committing = false;
                }
            }
            EventKind::RateLimited {
                connection, rate, ..
            } => {
                self.rates
                    .insert(connection.clone(), (rate.clone(), Some(at)));
            }
            EventKind::TableDone { rows, .. } => {
                self.running.retain(|running| running.table != table);
                self.done += 1;
                self.finished_rows += rows;
            }
            EventKind::TableFailed { .. } => {
                self.running.retain(|running| running.table != table);
                if self.fail_fast && self.stopped_after.is_none() {
                    self.stopped_after = Some(table);
                }
            }
            EventKind::TableNotStarted { .. } => {
                self.waiting.retain(|waiting| *waiting != table);
            }
            EventKind::RunStarted { .. }
            | EventKind::RunFinished { .. }
            | EventKind::Connected { .. }
            | EventKind::Discovered { .. } => {}
        }
    }

    /// The running table named `table`.
    fn running_mut(&mut self, table: &str) -> Option<&mut Running> {
        self.running
            .iter_mut()
            .find(|running| running.table == table)
    }
}

/// The tally lines `event` prints: `loaded` with its rows, time and new position (after the `created` and `altered` lines of a table that made its columns as it loaded), or `failed` with why. Names are padded to `name_width` and row counts to `rows_width`, so lines printed one at a time still line up.
pub(crate) fn event_lines(
    event: &LoadEvent,
    (name_width, rows_width): (usize, usize),
) -> Vec<String> {
    let name = event.table.as_deref().unwrap_or_default();
    let (verb, detail) = match &event.kind {
        EventKind::TableDone {
            rows,
            elapsed_ms,
            position,
            changes,
            transforms,
            names,
            warnings,
            peak_memory_bytes,
        } => {
            let word = match rows {
                1 => "row",
                _ => "rows",
            };
            let seconds = format!("{:.1}s", *elapsed_ms as f64 / 1000.0);
            let note: Vec<String> = position
                .iter()
                .cloned()
                .chain(peak_memory_bytes.map(peak_note))
                .collect();
            let detail = format!(
                "{}{}",
                format!(
                    "{:>rows_width$} {word:<5}{seconds:<6}{}",
                    thousands(*rows),
                    note.join("  ")
                )
                .trim_end(),
                names
                    .iter()
                    .map(|line| format!("\nnames  {line}"))
                    .chain(warnings.iter().map(|line| format!("\n⚠ {line}")))
                    .collect::<String>()
                    + &transform_lines(transforms)
            );
            let mut lines: Vec<String> = changes
                .iter()
                .map(|change| change_tally_line(change, name_width))
                .collect();
            lines.push(tally_line(("loaded", name), &detail, name_width));
            return lines;
        }
        EventKind::TableBatchWritten { rows, behind_secs } => {
            let word = match rows {
                1 => "row",
                _ => "rows",
            };
            let behind = behind_secs
                .map(|secs| format!("{secs}s behind"))
                .unwrap_or_default();
            (
                "written",
                format!("{:>rows_width$} {word:<5}{behind}", thousands(*rows))
                    .trim_end()
                    .to_owned(),
            )
        }
        EventKind::TableFailed {
            reason,
            peak_memory_bytes,
            ..
        } => (
            "failed",
            match peak_memory_bytes {
                Some(bytes) => format!("{reason}\n{}", peak_note(*bytes)),
                None => reason.clone(),
            },
        ),
        _ => return Vec::new(),
    };
    vec![tally_line((verb, name), &detail, name_width)]
}

/// A table's peak memory under `--memory-per-table`, as its tally line notes it: `peak memory 85 MiB`.
fn peak_note(bytes: u64) -> String {
    format!("peak memory {}", memory_text(bytes))
}

/// A line per file or range a `transform` ran on, with its time, each after a line break; then, when it returned dicts for a large one and took a while, one hint naming the slowest such that Arrow or a DataFrame is faster.
fn transform_lines(times: &[TransformTime]) -> String {
    let seconds = |time: &TransformTime| time.milliseconds as f64 / 1000.0;
    let mut lines: String = times
        .iter()
        .map(|time| format!("\ntransform  {}  {:.2}s", time.file, seconds(time)))
        .collect();
    let slow = times
        .iter()
        .filter(|time| {
            time.dicts && time.rows >= DICT_HINT_ROWS && time.milliseconds >= DICT_HINT_MILLISECONDS
        })
        .max_by_key(|time| time.milliseconds);
    if let Some(time) = slow {
        lines.push_str(&format!(
            "\nhint: the transform returned dicts for {} ({} rows, {:.1}s); a pyarrow Table or a DataFrame transforms faster",
            time.file,
            thousands(time.rows),
            seconds(time)
        ));
    }
    lines
}

/// `verb  name  detail` in the tally's columns, a detail's further lines under its first; a verb longer than `loaded` (`created`, `altered`), or a name wider than the column (a child table made as its parent loads), keeps two spaces after it.
fn tally_line((verb, name): (&str, &str), detail: &str, name_width: usize) -> String {
    let verb_width = VERB_COLUMN.max(verb.len() + 2);
    let name_width = name_width.max(name.len() + 2);
    let continued = format!("\n{:width$}", "", width = verb_width + name_width);
    format!(
        "{verb:<verb_width$}{name:<name_width$}{}",
        detail.replace('\n', &continued)
    )
    .trim_end()
    .to_owned()
}

/// A `created` or `altered` line `apply` reported, in the tally's columns.
pub(crate) fn change_tally_line(line: &str, name_width: usize) -> String {
    let mut parts = line.splitn(2, char::is_whitespace);
    let verb = parts.next().unwrap_or_default();
    let rest = parts.next().unwrap_or_default().trim_start();
    let (name, detail) = rest.split_once("  ").unwrap_or((rest, ""));
    tally_line((verb, name), detail.trim_start(), name_width)
}

/// What `load` prints of its plan before it starts: the closing line, pointing a complete plan to `sqlload plan`, and the Errors and Warnings sections when there are any; the Objects, Loads and Skipped trees and the `Plan ready` line are `plan`'s (and Objects `apply`'s), and the `created` and `altered` lines follow.
pub(crate) fn start_lines(plan_lines: Vec<String>) -> Vec<String> {
    let dropped = ["Plan ready", "Objects (", "Loads (", "Skipped ("];
    let mut kept: Vec<String> = Vec::new();
    for section in plan_lines.split(String::is_empty) {
        let first = section.first().map_or("", String::as_str);
        if section.is_empty() || dropped.iter().any(|heading| first.starts_with(heading)) {
            continue;
        }
        kept.extend(section.iter().cloned());
        kept.push(String::new());
    }
    kept.pop();
    if let Some(closing) = kept.last_mut()
        && closing.starts_with('✓')
    {
        closing.push_str(&format!("   {PLAN_TREE_HINT}"));
    }
    kept
}

/// Write each event from `receiver` as it comes: to `--events`, and as its tally line, printed or kept; until every sender is gone. The live block, when drawn, redraws about ten times a second under the printed lines, and is cleared at the end. Returns the kept lines and the tally.
pub(crate) async fn write_events(
    mut output: LoadOutput,
    mut receiver: UnboundedReceiver<LoadEvent>,
) -> (Vec<String>, Tally) {
    let mut kept: Vec<String> = Vec::new();
    let mut tally = Tally::default();
    let started = std::time::Instant::now();
    let block = output.live.as_ref().map(|_| live_bar());
    if let Some(bar) = &block {
        *LIVE_BLOCK.lock().unwrap_or_else(PoisonError::into_inner) = Some(bar.clone());
    }
    let width = console::Term::stderr()
        .size_checked()
        .map_or(MAX_LIVE_WIDTH, |(_, columns)| usize::from(columns));
    let mut ticks = tokio::time::interval(LIVE_REDRAW);
    let mut frame: usize = 0;
    let coloured = !output.no_color && std::env::var_os("NO_COLOR").is_none();
    loop {
        let event = tokio::select! {
            event = receiver.recv() => event,
            _ = ticks.tick(), if block.is_some() => {
                frame += 1;
                if let (Some(bar), Some(state)) = (&block, &output.live) {
                    bar.set_message(live_lines(state, (started.elapsed(), frame), (width, coloured)).join("\n"));
                }
                continue;
            }
        };
        let Some(event) = event else {
            break;
        };
        if let Some(events) = output.events.as_mut() {
            events.write_line(&event_line(&event));
        }
        tally.add(&event);
        if let Some(state) = output.live.as_mut() {
            state.apply(&event, started.elapsed());
        }
        let lines = event_lines(&event, (output.name_width, output.rows_width));
        match (output.print, &block) {
            (true, _) if lines.is_empty() => {}
            (true, Some(bar)) => bar.suspend(|| print_lines(lines, output.no_color)),
            (true, None) => print_lines(lines, output.no_color),
            (false, _) => kept.extend(lines),
        }
    }
    if let Some(bar) = block {
        *LIVE_BLOCK.lock().unwrap_or_else(PoisonError::into_inner) = None;
        bar.finish_and_clear();
    }
    (kept, tally)
}

/// Run `write`, which writes to stderr, with the live block, when one is drawn, lifted off the screen for it and redrawn under what it wrote.
pub(crate) fn above_live_block<T>(write: impl FnOnce() -> T) -> T {
    let drawn = LIVE_BLOCK
        .lock()
        .unwrap_or_else(PoisonError::into_inner)
        .clone();
    match drawn {
        Some(bar) => bar.suspend(write),
        None => write(),
    }
}

/// The live block's one bar on stderr: a message of several lines, redrawn in place.
fn live_bar() -> indicatif::ProgressBar {
    let bar = indicatif::ProgressBar::with_draw_target(
        None,
        indicatif::ProgressDrawTarget::stderr_with_hz(LIVE_HZ),
    );
    if let Ok(style) = indicatif::ProgressStyle::with_template("{msg}") {
        bar.set_style(style);
    }
    bar
}

/// The line a load ends with, and the branches under it: what never started, the slowest table, the run's peak memory, and after failures whether running it again helps and what it would do.
pub(crate) fn summary_lines(tally: &Tally, elapsed_ms: u64, exit_code: u8) -> Vec<String> {
    let mut clauses: Vec<String> = Vec::new();
    clauses.extend((tally.loaded > 0).then(|| format!("{} loaded", tally.loaded)));
    clauses.extend((tally.failed > 0).then(|| format!("{} failed", tally.failed)));
    clauses.extend(
        (!tally.not_started.is_empty()).then(|| format!("{} not started", tally.not_started.len())),
    );
    clauses.extend((tally.loaded > 0).then(|| match tally.rows {
        1 => "1 row".to_owned(),
        rows => format!("{} rows", thousands(rows)),
    }));
    clauses.push(format!("{:.1}s", elapsed_ms as f64 / 1000.0));
    let failures = tally.failed > 0 || !tally.not_started.is_empty();
    let mut branches: Vec<(&str, String)> = Vec::new();
    if !tally.not_started.is_empty() {
        let named: Vec<&str> = tally
            .not_started
            .iter()
            .take(NAMED_TABLES)
            .map(String::as_str)
            .collect();
        let more = match tally.not_started.len().saturating_sub(NAMED_TABLES) {
            0 => String::new(),
            more => format!(", +{more} more"),
        };
        branches.push((
            "not started",
            format!("{}{more} (--fail-fast)", named.join(", ")),
        ));
    }
    if let Some((table, elapsed_ms)) = &tally.slowest {
        branches.push((
            "slowest",
            format!("{table} {:.1}s", *elapsed_ms as f64 / 1000.0),
        ));
    }
    if let Some(bytes) = tally.peak_memory_bytes {
        branches.push(("peak memory", memory_text(bytes)));
    }
    if failures && exit_code == crate::command::constants::RETRYABLE_EXIT {
        branches.push((
            "retry",
            format!("every failure is retryable, so exit {exit_code}: run the same command again"),
        ));
    }
    if failures {
        let unchanged = match tally.failed + tally.not_started.len() {
            1 => "the 1 unchanged table loads".to_owned(),
            count => format!("the {count} unchanged tables load"),
        };
        branches.push((
            "next",
            match tally.loaded {
                0 => unchanged,
                1 => format!("{unchanged}; the 1 that committed carries on from its position"),
                count => {
                    format!("{unchanged}; the {count} that committed carry on from their positions")
                }
            },
        ));
    }
    let mut lines = vec![match tally.failed {
        0 => format!("✓ Completed  {}", clauses.join(", ")),
        _ => format!("✗ Completed with failures  {}", clauses.join(", ")),
    }];
    for (index, (label, text)) in branches.iter().enumerate() {
        let branch = match index + 1 == branches.len() {
            true => "└── ",
            false => "├── ",
        };
        lines.push(format!("{branch}{label:<SUMMARY_LABEL$}{text}"));
    }
    lines
}

/// `work`, a plan of a project with `sources` sources, with its progress on stderr, watched by a thread of its own (planning may hold up the async runtime): when `prints`, the phase line of each connection and discovery that failed or was slow as it ends (with `verbose`, every one), then the `Connected` and `Discovered` summary lines (not with `verbose`), and a `RUNNING` row for a step every [`running_every`] it runs, which logs that are no terminal show too; when `draws`, a spinner for the step running once it has run [`SPINNER_DELAY`] (or `Planning` and how many sources are done between steps), cleared before anything else prints.
pub(crate) async fn planning<T>(
    work: impl std::future::Future<Output = T>,
    sources: usize,
    (draws, prints, no_color): (bool, bool, bool),
    verbose: bool,
) -> T {
    let done = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
    let watcher = {
        let done = done.clone();
        std::thread::spawn(move || {
            watch_steps(&done, sources, (draws, prints, no_color), verbose);
        })
    };
    let output = work.await;
    done.store(true, std::sync::atomic::Ordering::Relaxed);
    let _ = watcher.join();
    output
}

/// What [`planning`] shows, until `done`: its phase lines (every one with `verbose`, else those of failed and slow steps, then the summary lines) and `RUNNING` rows (when `prints`), and its spinner (when `draws`), which it clears at the end.
fn watch_steps(
    done: &std::sync::atomic::AtomicBool,
    sources: usize,
    (draws, prints, no_color): (bool, bool, bool),
    verbose: bool,
) {
    let started = std::time::Instant::now();
    let every = running_every();
    let coloured =
        !no_color && std::env::var_os("NO_COLOR").is_none() && std::io::stderr().is_terminal();
    let mut bar: Option<indicatif::ProgressBar> = None;
    let mut reported: (u64, u128) = (0, 0);
    loop {
        let finished = done.load(std::sync::atomic::Ordering::Relaxed);
        let ProgressView { mut lines, step } = progress_view(verbose);
        let row;
        (reported, row) = running_row(step.as_ref(), every, reported);
        lines.extend(row);
        if finished && !verbose {
            let summary = phase_summary();
            if !summary.is_empty() {
                lines.extend(summary);
                lines.push(String::new());
            }
        }
        if prints && !lines.is_empty() {
            let write = || {
                let mut stderr = std::io::stderr().lock();
                for line in lines {
                    let line = match coloured {
                        true => paint(line),
                        false => line,
                    };
                    let _ = writeln!(stderr, "{line}");
                }
                let _ = stderr.flush();
            };
            match &bar {
                Some(bar) => bar.suspend(write),
                None => write(),
            }
        }
        if finished {
            break;
        }
        let shown = spinner_message(
            step.as_ref(),
            started.elapsed(),
            (ProjectPlan::planned_sources(), sources),
        );
        if let Some(message) = shown.filter(|_| draws) {
            bar.get_or_insert_with(|| spinner(no_color))
                .set_message(message);
        }
        if let Some(bar) = &bar {
            bar.tick();
        }
        std::thread::sleep(LIVE_REDRAW);
    }
    if let Some(bar) = bar {
        bar.finish_and_clear();
    }
}

/// The `RUNNING` row due for `step`, if any: one each time it has run another `every`. `reported` is the step the rows so far were for and how many; returned as it stands after this row, so each prints once.
pub(crate) fn running_row(
    step: Option<&StepView>,
    every: Duration,
    reported: (u64, u128),
) -> ((u64, u128), Option<String>) {
    let Some(step) = step else {
        return (reported, None);
    };
    let before = match step.id == reported.0 {
        true => reported.1,
        false => 0,
    };
    let due = step.elapsed.as_millis() / every.as_millis().max(1);
    let row = (due > before).then(|| {
        format!(
            "  {}  {}  RUNNING {:.1}s",
            step.subject,
            step.doing,
            step.elapsed.as_secs_f64()
        )
    });
    ((step.id, due.max(before)), row)
}

/// What the spinner says, `waited` into the plan, with `planned` of `sources` sources checked: the step running once it has run [`SPINNER_DELAY`], else, between steps once the plan has, how many sources are done; `None` before then, so fast runs draw nothing.
pub(crate) fn spinner_message(
    step: Option<&StepView>,
    waited: Duration,
    (planned, sources): (usize, usize),
) -> Option<String> {
    match step {
        Some(step) => (step.elapsed >= SPINNER_DELAY).then(|| {
            format!(
                "{}  {}… {}s",
                step.subject,
                step.doing,
                step.elapsed.as_secs()
            )
        }),
        None => (waited >= SPINNER_DELAY)
            .then(|| format!("Planning  checking sources, {planned} of {sources} done")),
    }
}

/// The spinner [`planning`] draws on stderr.
fn spinner(no_color: bool) -> indicatif::ProgressBar {
    let bar = indicatif::ProgressBar::with_draw_target(
        None,
        indicatif::ProgressDrawTarget::stderr_with_hz(LIVE_HZ),
    );
    let template = match no_color {
        true => "{spinner} {msg}",
        false => "{spinner:.cyan} {msg:.dim}",
    };
    if let Ok(style) = indicatif::ProgressStyle::with_template(template) {
        bar.set_style(style.tick_chars("⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏ "));
    }
    bar
}

/// How often a step still running prints a `RUNNING` row: [`RUNNING_EVERY`], or the milliseconds `SQLLOAD_RUNNING_EVERY_MS` names, which tests shorten it to.
fn running_every() -> Duration {
    let set = std::env::var_os("SQLLOAD_RUNNING_EVERY_MS")
        .map(|millis| millis.to_string_lossy().parse::<u64>());
    match set {
        Some(Ok(millis)) => Duration::from_millis(millis),
        _ => RUNNING_EVERY,
    }
}

/// The block's lines, after a blank one that parts it from the finished tables' lines, for `state`, `elapsed` into the load, at redraw `frame`, for a terminal `width` columns wide; `coloured` as the mock has it: cyan for what runs, red only for a failure, yellow for waits and fail-fast, dim for notes.
pub(crate) fn live_lines(
    state: &LiveState,
    (elapsed, frame): (Duration, usize),
    (width, coloured): (usize, bool),
) -> Vec<String> {
    let paint = |code: &str, text: String| match coloured && !text.is_empty() {
        true => format!("{code}{text}{RESET}"),
        false => text,
    };
    let width = width.min(MAX_WIDTH);
    let spinner = paint(CYAN, SPINNER[frame % SPINNER.len()].to_string());
    let rows = state.finished_rows
        + state
            .running
            .iter()
            .map(|running| running.rows)
            .sum::<u64>();
    let seconds = elapsed.as_secs();
    let counts = format!(
        "{}/{} tables · {:>5} rows · {:02}:{:02}",
        state.done,
        state.total,
        thousands(rows),
        seconds / 60,
        seconds % 60
    );
    let badge = match state.follow {
        true => " FOLLOWING ",
        false => " LOADING ",
    };
    let bar_width = width
        .saturating_sub(badge.len() + BAR_LINE_GAPS + counts.chars().count())
        .max(10);
    let filled = match state.total {
        0 => bar_width,
        total => bar_width * state.done / total,
    };
    let mut lines = vec![
        String::new(),
        format!(
            "{} {}{}  {counts}",
            paint(&format!("{BOLD}{INVERSE}{CYAN}"), badge.to_owned()),
            paint(
                match state.stopped_after {
                    Some(_) => RED,
                    None => CYAN,
                },
                "━".repeat(filled)
            ),
            paint(DIM, "━".repeat(bar_width - filled)),
        ),
        String::new(),
    ];
    for running in &state.running {
        lines.push(format!(
            "  {spinner} {:<NAME_COLUMN$} {:<8} {:>6} {}",
            running.table,
            running.strategy,
            thousands(running.rows),
            paint(
                match running.committing {
                    true => CYAN,
                    false => DIM,
                },
                running.doing.clone()
            )
        ));
    }
    if let Some(failed) = &state.stopped_after {
        lines.push(paint(
            YELLOW,
            format!(
                "  ⊘ fail-fast: {} will not start after {failed} failed; running tables finish",
                match state.waiting.len() {
                    1 => "1 table".to_owned(),
                    count => format!("{count} tables"),
                }
            ),
        ));
    } else if !state.waiting.is_empty() {
        let named: Vec<&str> = state
            .waiting
            .iter()
            .take(QUEUED_NAMED)
            .map(String::as_str)
            .collect();
        let more = match state.waiting.len() > QUEUED_NAMED {
            true => ", …",
            false => "",
        };
        lines.push(paint(
            DIM,
            format!(
                "  · {} queued: {}{more}",
                state.waiting.len(),
                named.join(", ")
            ),
        ));
    }
    lines.push(String::new());
    if !state.rates.is_empty() {
        let meters: Vec<String> = state
            .rates
            .iter()
            .map(|(connection, (rate, waited))| {
                let busy = waited.is_some_and(|at| elapsed.saturating_sub(at) < RATE_RECENT);
                match busy {
                    true => format!(
                        "{connection} {}",
                        paint(YELLOW, format!("▮▮▮▮▮▮▮▮ at {rate}"))
                    ),
                    false => format!(
                        "{connection} {}",
                        paint(DIM, format!("▯▯▯▯▯▯▯▯ under {rate}"))
                    ),
                }
            })
            .collect();
        lines.push(format!(
            "  {}{}",
            paint(DIM, "rate  ".to_owned()),
            meters.join("   ")
        ));
    }
    lines.push(paint(
        DIM,
        match state.follow {
            true => "  ctrl-c writes what it read and stops · a second ctrl-c stops at once",
            false => "  ctrl-c finishes running tables and stops · a second ctrl-c stops at once",
        }
        .to_owned(),
    ));
    lines
}