legume_numeric/matrix/progress.rs
1//! Workspace-wide progress-bar style and the single [`MULTI_PROGRESS`] that
2//! every bar registers with.
3//!
4//! This lives in `legume_numeric::matrix` — the lowest common dependency of `data-beans`,
5//! `data_beans::alg`, `data_beans::aux`, and the binaries — so the whole
6//! workspace shares ONE style definition and ONE `MultiProgress`. That single
7//! `MultiProgress` is what lets `indicatif_log_bridge` (installed by
8//! `data_beans::aux::logging::init_logger`) interleave `log` output cleanly
9//! above the bars. Duplicating the bar/`MultiProgress` in another crate (as
10//! `graph-embedding-util` once did) silently spawns a second, *unbridged*
11//! `MultiProgress` whose bars corrupt the log output — so every crate must
12//! draw through this module. `data_beans::aux::logging` re-exports these names
13//! for backward compatibility.
14//!
15//! Off a terminal (an MCP server's child, a batch job's log) indicatif draws
16//! nothing, so each bar made here is also said in a line on stderr every
17//! [`EVERY`] while it moves, and once as it ends: see [`PREFIX`] for the
18//! line's shape, which `legume-mcp` reads back into a job's progress.
19
20use indicatif::{MultiProgress, ProgressBar, ProgressStyle, WeakProgressBar};
21use std::io::IsTerminal;
22use std::sync::atomic::{AtomicU64, Ordering};
23use std::sync::{LazyLock, Mutex};
24use std::time::Duration;
25
26/// The single global `MultiProgress` every workspace progress bar registers
27/// with, so `log` output routed through `indicatif_log_bridge` interleaves
28/// cleanly above the bars instead of corrupting them.
29pub static MULTI_PROGRESS: LazyLock<MultiProgress> = LazyLock::new(MultiProgress::new);
30
31/// Standard bounded-bar template: `[elapsed] bar pos/len (eta) msg`. The
32/// trailing `{msg}` is empty unless a caller sets one (e.g.
33/// `new_progress_bar(n).with_message("blocks")`).
34const BAR_TEMPLATE: &str = "[{elapsed_precise}] {bar:40.cyan/blue} {pos}/{len} ({eta}) {msg}";
35
36/// Tick frames shared by every [`new_spinner`].
37const SPINNER_TICKS: &str = "⠁⠂⠄⡀⢀⠠⠐⠈ ";
38
39/// Repaint cadence for both bars and spinners. Without a steady tick a bar
40/// only repaints when [`ProgressBar::inc`] fires, so work with a heavy-tailed
41/// per-item cost (one huge gene among thousands of small ones) leaves a frozen
42/// elapsed time on screen for minutes and reads as a hang.
43const STEADY_TICK: Duration = Duration::from_millis(200);
44
45/// Create a progress bar registered with the shared [`MULTI_PROGRESS`] and
46/// styled with the standard template. Attach a trailing label with
47/// [`ProgressBar::with_message`], e.g. `new_progress_bar(n).with_message("blocks")`.
48/// Repaints on the shared `STEADY_TICK` cadence.
49#[must_use]
50pub fn new_progress_bar(len: u64) -> ProgressBar {
51 let prog_bar = MULTI_PROGRESS.add(ProgressBar::new(len));
52 prog_bar.set_style(
53 ProgressStyle::with_template(BAR_TEMPLATE)
54 .unwrap()
55 .progress_chars("##-"),
56 );
57 prog_bar.enable_steady_tick(STEADY_TICK);
58 lines::watch(&prog_bar);
59 prog_bar
60}
61
62/// Create a spinner registered with the shared [`MULTI_PROGRESS`] for
63/// unbounded / streaming work (no known total). `template` is an indicatif
64/// spinner template (e.g. `"{spinner} streamed {pos} fragments ({per_sec})"`);
65/// the shared tick frames and the shared `STEADY_TICK` cadence are applied so
66/// the spinner animates and stays visually consistent across crates.
67#[must_use]
68pub fn new_spinner(template: &str) -> ProgressBar {
69 let prog_bar = MULTI_PROGRESS.add(ProgressBar::new_spinner());
70 prog_bar.set_style(
71 ProgressStyle::with_template(template)
72 .unwrap()
73 .tick_chars(SPINNER_TICKS),
74 );
75 prog_bar.enable_steady_tick(STEADY_TICK);
76 lines::watch(&prog_bar);
77 prog_bar
78}
79
80/// What starts each progress line said off a terminal. The rest of the line
81/// is one JSON object:
82///
83/// ```text
84/// legume-progress {"id":3,"label":"blocks","pos":12,"len":40,"elapsed_s":31,"eta_s":72,"done":false}
85/// ```
86///
87/// `id` numbers the bars of one process (several may run at once), `label`
88/// is the bar's message (may be empty), `len` and `eta_s` are `null` for a
89/// spinner, and `done` is true on a bar's last line.
90pub const PREFIX: &str = "legume-progress ";
91
92/// How often a bar off a terminal says where it stands, while it moves;
93/// `LEGUME_PROGRESS_EVERY` (seconds; 0 for never) sets it otherwise.
94pub const EVERY: Duration = Duration::from_secs(15);
95
96/// A bar as its line says it.
97#[derive(Clone, Debug, PartialEq)]
98struct Said {
99 id: u64,
100 label: String,
101 pos: u64,
102 len: Option<u64>,
103 elapsed_s: u64,
104 eta_s: Option<u64>,
105 done: bool,
106}
107
108impl Said {
109 fn of(id: u64, bar: &ProgressBar, done: bool) -> Self {
110 let len = bar.length();
111 Self {
112 id,
113 label: bar.message(),
114 pos: bar.position(),
115 len,
116 elapsed_s: bar.elapsed().as_secs(),
117 eta_s: len.map(|_| bar.eta().as_secs()),
118 done,
119 }
120 }
121
122 /// The line, [`PREFIX`] first.
123 fn line(&self) -> String {
124 let opt = |v: Option<u64>| v.map_or("null".to_string(), |v| v.to_string());
125 format!(
126 "{PREFIX}{{\"id\":{},\"label\":{},\"pos\":{},\"len\":{},\"elapsed_s\":{},\"eta_s\":{},\"done\":{}}}",
127 self.id,
128 json_string(&self.label),
129 self.pos,
130 opt(self.len),
131 self.elapsed_s,
132 opt(self.eta_s),
133 self.done
134 )
135 }
136}
137
138/// `s` as a JSON string.
139fn json_string(s: &str) -> String {
140 let mut out = String::with_capacity(s.len() + 2);
141 out.push('"');
142 for c in s.chars() {
143 match c {
144 '"' => out.push_str("\\\""),
145 '\\' => out.push_str("\\\\"),
146 c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
147 c => out.push(c),
148 }
149 }
150 out.push('"');
151 out
152}
153
154/// The bars said in lines off a terminal, and the thread that says them.
155mod lines {
156 use super::*;
157
158 /// A bar watched: its number, a handle that lets it go, and what its
159 /// last line said (none yet).
160 struct Watched {
161 id: u64,
162 bar: WeakProgressBar,
163 said: Option<Said>,
164 }
165
166 static WATCHED: Mutex<Vec<Watched>> = Mutex::new(Vec::new());
167 static NEXT: AtomicU64 = AtomicU64::new(1);
168
169 /// How often to say the bars, none when stderr is a terminal (the bars
170 /// are drawn) or lines are turned off.
171 fn every() -> Option<Duration> {
172 static EVERY_SET: LazyLock<Option<Duration>> = LazyLock::new(|| {
173 let every = match std::env::var("LEGUME_PROGRESS_EVERY") {
174 Ok(s) => s.trim().parse::<f64>().ok().map(Duration::from_secs_f64),
175 Err(_) => Some(EVERY),
176 };
177 every.filter(|d| !d.is_zero() && !std::io::stderr().is_terminal())
178 });
179 *EVERY_SET
180 }
181
182 /// Say `bar` in lines from now on, when they are said at all.
183 pub(super) fn watch(bar: &ProgressBar) {
184 let Some(every) = every() else { return };
185 static THREAD: std::sync::Once = std::sync::Once::new();
186 THREAD.call_once(|| {
187 let spawned = std::thread::Builder::new()
188 .name("progress-lines".into())
189 .spawn(move || loop {
190 std::thread::sleep(every);
191 say();
192 });
193 if let Err(e) = spawned {
194 log::warn!("progress lines: {e}");
195 }
196 });
197 let id = NEXT.fetch_add(1, Ordering::Relaxed);
198 let mut watched = WATCHED.lock().unwrap_or_else(|e| e.into_inner());
199 watched.push(Watched {
200 id,
201 bar: bar.downgrade(),
202 said: None,
203 });
204 }
205
206 /// The lines due now: each bar that moved since its last (or, every
207 /// fourth time, that did not: it is still there), and a last line for
208 /// each that ended; those that ended are no longer watched.
209 pub(super) fn say() {
210 static ROUND: AtomicU64 = AtomicU64::new(0);
211 let round = ROUND.fetch_add(1, Ordering::Relaxed);
212 let mut watched = WATCHED.lock().unwrap_or_else(|e| e.into_inner());
213 watched.retain_mut(|w| {
214 let (now, keep) = match w.bar.upgrade() {
215 Some(bar) if bar.is_finished() => (Said::of(w.id, &bar, true), false),
216 Some(bar) => (Said::of(w.id, &bar, false), true),
217 // Let go unfinished (a parallel iterator's bar, dropped as it
218 // ends): last said as it last stood.
219 None => match w.said.take() {
220 Some(last) => (Said { done: true, ..last }, false),
221 None => return false,
222 },
223 };
224 let moved = w.said.as_ref().is_none_or(|s| {
225 (s.pos, s.len, &s.label, s.done) != (now.pos, now.len, &now.label, now.done)
226 });
227 if moved || !keep || round % 4 == 3 {
228 eprintln!("{}", now.line());
229 }
230 w.said = Some(now);
231 keep
232 });
233 }
234}
235
236#[cfg(test)]
237mod tests {
238 use super::*;
239
240 /// A bar's line is the prefix and one JSON object, its label escaped.
241 #[test]
242 fn a_line_is_the_prefix_and_json() {
243 let said = Said {
244 id: 3,
245 label: "a \"b\"\\c".into(),
246 pos: 12,
247 len: Some(40),
248 elapsed_s: 31,
249 eta_s: Some(72),
250 done: false,
251 };
252 assert_eq!(
253 said.line(),
254 r#"legume-progress {"id":3,"label":"a \"b\"\\c","pos":12,"len":40,"elapsed_s":31,"eta_s":72,"done":false}"#
255 );
256 let spinner = Said {
257 len: None,
258 eta_s: None,
259 done: true,
260 label: String::new(),
261 ..said
262 };
263 assert!(spinner
264 .line()
265 .ends_with(r#""len":null,"elapsed_s":31,"eta_s":null,"done":true}"#));
266 }
267}