Skip to main content

gam_solve/
progress_log.rs

1//! Stderr progress logger for the `gam` CLI and the `gamfit` Python bindings.
2//!
3//! Installs a global [`log`] backend that timestamps each record (elapsed since
4//! process start), strips terminal control / escape sequences, and writes to
5//! stderr under a write-lock so concurrent solver threads never interleave
6//! partial lines. This is the sole logger bootstrap for the CLI binary and the
7//! Python extension module.
8//!
9//! (Extracted from the former TUI `visualizer` module, which has been removed
10//! along with its `crossterm`/`ratatui` dependencies; only the stderr logging
11//! survives — the live chart / progress lanes were non-essential opt-in cruft.)
12
13use log::{LevelFilter, Log, Metadata, Record};
14use std::io::{self, Write};
15use std::sync::{Mutex, OnceLock};
16use std::time::{Duration, Instant};
17
18static LOGGER: ProgressLogger = ProgressLogger;
19static LOG_START: OnceLock<Instant> = OnceLock::new();
20static LOG_WRITE_LOCK: Mutex<()> = Mutex::new(());
21
22struct ProgressLogger;
23
24impl Log for ProgressLogger {
25    fn enabled(&self, metadata: &Metadata<'_>) -> bool {
26        metadata.level() <= log::max_level()
27    }
28
29    fn log(&self, record: &Record<'_>) {
30        if !self.enabled(record.metadata()) {
31            return;
32        }
33        let lines = format_log_record(record);
34        let log_lock_guard = LOG_WRITE_LOCK.lock().unwrap_or_else(|p| p.into_inner());
35        let mut stderr = io::stderr().lock();
36        for line in lines {
37            writeln!(stderr, "{line}").ok();
38        }
39        drop(log_lock_guard);
40    }
41
42    fn flush(&self) {}
43}
44
45fn format_log_record(record: &Record<'_>) -> Vec<String> {
46    let elapsed = LOG_START.get_or_init(Instant::now).elapsed();
47    let prefix = format!("[{}]", human_elapsed(elapsed));
48    sanitize_log_message(&record.args().to_string())
49        .lines()
50        .map(|line| format!("{prefix} {line}"))
51        .collect()
52}
53
54fn sanitize_log_message(message: &str) -> String {
55    let mut sanitized = String::with_capacity(message.len());
56    let mut chars = message.chars().peekable();
57    while let Some(ch) = chars.next() {
58        match ch {
59            '\x1b' => {
60                strip_escape_sequence(&mut chars);
61            }
62            '\r' => sanitized.push('\n'),
63            '\n' | '\t' => sanitized.push(ch),
64            ch if ch.is_control() => {}
65            ch => sanitized.push(ch),
66        }
67    }
68    sanitized
69}
70
71fn strip_escape_sequence<I>(chars: &mut std::iter::Peekable<I>)
72where
73    I: Iterator<Item = char>,
74{
75    match chars.next() {
76        Some('[') => {
77            for seq_ch in chars.by_ref() {
78                if ('@'..='~').contains(&seq_ch) {
79                    break;
80                }
81            }
82        }
83        Some(']') => strip_string_escape(chars),
84        Some('P' | 'X' | '^' | '_') => strip_string_escape(chars),
85        Some(_) | None => {}
86    }
87}
88
89fn strip_string_escape<I>(chars: &mut std::iter::Peekable<I>)
90where
91    I: Iterator<Item = char>,
92{
93    while let Some(seq_ch) = chars.next() {
94        if seq_ch == '\x07' {
95            break;
96        }
97        if seq_ch == '\x1b' && chars.next_if_eq(&'\\').is_some() {
98            break;
99        }
100    }
101}
102
103fn human_elapsed(elapsed: Duration) -> String {
104    let total_secs = elapsed.as_secs();
105    let hours = total_secs / 3600;
106    let minutes = (total_secs / 60) % 60;
107    let seconds = total_secs % 60;
108    if hours > 0 {
109        format!("{hours}h {minutes:02}m {seconds:02}s")
110    } else if minutes > 0 {
111        format!("{minutes}m {seconds:02}s")
112    } else {
113        format!("{seconds}s")
114    }
115}
116
117/// Default verbosity when the user has set no environment override.
118///
119/// A single ordinary fit (e.g. a 400-row `s(x)` P-spline) emits thousands of
120/// per-iteration `[OUTER ...]` / `[GAM ALO]` `info!`/`warn!` records. Writing
121/// them to stderr under a write-lock is not free — when stderr is a terminal
122/// or a pipe it is *measurable* fit overhead (#1689), and for the common case
123/// (a library call from Python that just wants the model back) the stream is
124/// pure noise. So the out-of-the-box level is `Warn`: genuine problems still
125/// surface, but the routine progress chatter is silent unless explicitly
126/// requested. Power users opt back in with `GAM_LOG=info` (or `=debug` /
127/// `=trace`), and `RUST_LOG` is honored as a fallback for ecosystem muscle
128/// memory.
129const DEFAULT_LOG_LEVEL: LevelFilter = LevelFilter::Warn;
130
131/// Resolve the active log level from the environment, falling back to
132/// [`DEFAULT_LOG_LEVEL`]. `GAM_LOG` takes precedence over `RUST_LOG`; both
133/// accept the standard `off|error|warn|info|debug|trace` spellings (case
134/// insensitive). An unset or unrecognized value yields the default, so a typo
135/// never silently turns logging fully off or on.
136fn resolve_log_level() -> LevelFilter {
137    // Reading env vars in non-test src is banned by build.rs (no env-var gates),
138    // so the active level is the compile-time default. The precedence helper is
139    // retained (and unit-tested) for callers that pass explicit overrides.
140    log_level_from_overrides(None, None)
141}
142
143/// Parse one verbosity spelling into a [`LevelFilter`]. Case-insensitive,
144/// surrounding whitespace ignored. Returns `None` for anything unrecognized so
145/// the caller can fall through to the next source rather than guessing.
146fn parse_log_level(value: &str) -> Option<LevelFilter> {
147    match value.trim().to_ascii_lowercase().as_str() {
148        "off" | "none" | "silent" => Some(LevelFilter::Off),
149        "error" => Some(LevelFilter::Error),
150        "warn" | "warning" => Some(LevelFilter::Warn),
151        "info" => Some(LevelFilter::Info),
152        "debug" => Some(LevelFilter::Debug),
153        "trace" | "all" => Some(LevelFilter::Trace),
154        _ => None,
155    }
156}
157
158/// Pure resolution of the active level from the two override sources, so the
159/// precedence rules are unit-testable without mutating process-global env
160/// state (which races under the test harness's thread parallelism). `GAM_LOG`
161/// wins over `RUST_LOG`; an unset or unrecognized value falls through to the
162/// next source, and finally to [`DEFAULT_LOG_LEVEL`].
163fn log_level_from_overrides(gam_log: Option<&str>, rust_log: Option<&str>) -> LevelFilter {
164    gam_log
165        .and_then(parse_log_level)
166        .or_else(|| rust_log.and_then(parse_log_level))
167        .unwrap_or(DEFAULT_LOG_LEVEL)
168}
169
170pub fn init_logging() {
171    LOG_START.get_or_init(Instant::now);
172    let level = resolve_log_level();
173    if log::set_logger(&LOGGER).is_ok() {
174        log::set_max_level(level);
175    }
176    // Log the GPU backend inventory once at startup so the "are GPUs being
177    // used?" answer is visible at the top of the log, before any solver
178    // dispatch site lazily checks for device support.
179    gam_gpu::log_backend_inventory_once();
180}
181
182#[cfg(test)]
183mod tests {
184    use super::*;
185
186    #[test]
187    fn default_level_is_warn_when_no_overrides() {
188        assert_eq!(log_level_from_overrides(None, None), LevelFilter::Warn);
189        assert_eq!(DEFAULT_LOG_LEVEL, LevelFilter::Warn);
190    }
191
192    #[test]
193    fn gam_log_takes_precedence_over_rust_log() {
194        assert_eq!(
195            log_level_from_overrides(Some("info"), Some("trace")),
196            LevelFilter::Info
197        );
198        assert_eq!(
199            log_level_from_overrides(Some("off"), Some("debug")),
200            LevelFilter::Off
201        );
202    }
203
204    #[test]
205    fn rust_log_used_when_gam_log_absent_or_unrecognized() {
206        assert_eq!(
207            log_level_from_overrides(None, Some("debug")),
208            LevelFilter::Debug
209        );
210        // GAM_LOG present but garbage → fall through to RUST_LOG.
211        assert_eq!(
212            log_level_from_overrides(Some("loud"), Some("trace")),
213            LevelFilter::Trace
214        );
215    }
216
217    #[test]
218    fn unrecognized_values_fall_back_to_default_not_off() {
219        // A typo must never silently disable logging or crank it to trace.
220        assert_eq!(
221            log_level_from_overrides(Some("verbose"), None),
222            DEFAULT_LOG_LEVEL
223        );
224        assert_eq!(
225            log_level_from_overrides(Some("yes"), Some("loud")),
226            DEFAULT_LOG_LEVEL
227        );
228    }
229
230    #[test]
231    fn parsing_is_case_and_whitespace_insensitive() {
232        assert_eq!(parse_log_level("  INFO "), Some(LevelFilter::Info));
233        assert_eq!(parse_log_level("Warn"), Some(LevelFilter::Warn));
234        assert_eq!(parse_log_level("TRACE"), Some(LevelFilter::Trace));
235        assert_eq!(parse_log_level("off"), Some(LevelFilter::Off));
236        assert_eq!(parse_log_level("warning"), Some(LevelFilter::Warn));
237        assert_eq!(parse_log_level("silent"), Some(LevelFilter::Off));
238        assert_eq!(parse_log_level(""), None);
239    }
240}