Skip to main content

latexml_core/util/
logger.rs

1use std::{
2  cell::{Cell, RefCell},
3  fs::File,
4  sync::{
5    PoisonError, RwLock,
6    atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering},
7  },
8};
9
10use log::{Level, LevelFilter, Metadata, Record, SetLoggerError, max_level};
11
12// ANSI SGR escape sequences (drop-in replacement for the
13// unmaintained `ansi_term` crate; bytes match `ansi_term::Colour::*.paint(...)`).
14const ANSI_RESET: &str = "\x1b[0m";
15const ANSI_GREEN: &str = "\x1b[32m";
16const ANSI_YELLOW: &str = "\x1b[33m";
17const ANSI_RED: &str = "\x1b[31m";
18const ANSI_WHITE: &str = "\x1b[37m";
19
20fn paint(color: &str, text: &str) -> String { format!("{color}{text}{ANSI_RESET}") }
21
22/// Whether to emit ANSI color escapes on stderr. Colors are a convenience for
23/// an interactive terminal ONLY; when stderr is redirected to a file or pipe
24/// (the canvas/auto-upgrade path: `cortex_worker ... > log.txt 2>&1`) they are
25/// noise that breaks line-anchored error parsing — a naive `grep '^Error:'`
26/// matches `\x1b[31mError:` ZERO times and silently reports "0 errors" on a
27/// failed paper (the false-negative that masked real Rust-only regressions; see
28/// CLAUDE.md "canvas signal integrity"). So: colorize iff stderr is a TTY and
29/// `NO_COLOR` is unset. Cached once — stderr's terminal-ness can't change
30/// mid-process. Note the captured LOG_BUFFER (`.latexml.log`) is already
31/// ANSI-stripped independently; this makes the *redirected stderr* match it.
32fn stderr_use_color() -> bool {
33  use std::{io::IsTerminal, sync::OnceLock};
34  static USE_COLOR: OnceLock<bool> = OnceLock::new();
35  *USE_COLOR
36    .get_or_init(|| std::io::stderr().is_terminal() && std::env::var_os("NO_COLOR").is_none())
37}
38
39/// The STDERR verbosity gate, decoupled from the log-file floor.
40///
41/// Perl LaTeXML separates the two: the log file (`$LOG`) receives every message
42/// while it is open, but STDERR prints only when `$USE_STDERR && $VERBOSITY >= 0`
43/// (`Common/Error.pm` `_printline`). `--quiet` lowers THIS (to `Error`: Info and
44/// Warnings off the console) without lowering what the log keeps — so `(Loading …)`
45/// progress notes and `Info:` records still reach `.latexml.log`, which is what
46/// BookML's makefile dependency tracking reads (issue #763). `--verbose` raises it
47/// (to `Debug`). Unlike Perl, `Error`/`Fatal` reach STDERR at every verbosity
48/// (DG 2026-08-02, OXIDIZED_DESIGN_DIVERGENCES #1158).
49///
50/// Stored as the `LevelFilter` discriminant (`Off`=0 … `Trace`=5). Process-global
51/// like `max_level`: one shared stderr descriptor across `cortex_worker`'s pool.
52static STDERR_LEVEL: AtomicUsize = AtomicUsize::new(LevelFilter::Info as usize);
53
54/// Un-featured `Debug` records are admitted (`--verbose`). Without it a `Debug` record passes only when its target
55/// is a `--debug` feature: Perl guards its trace `Debug()` calls `if $LaTeXML::DEBUG{feature}` (`Common/Error.pm` L467).
56static DEBUG_ALL: AtomicBool = AtomicBool::new(false);
57
58/// Whether un-featured `Debug` records are logged (`--verbose`; see `DEBUG_ALL`).
59#[inline]
60pub fn debug_all() -> bool { DEBUG_ALL.load(Ordering::Relaxed) }
61
62/// The current STDERR verbosity (`STDERR_LEVEL`): `--quiet` `Error`, the default `Info`, `--verbose` `Debug`.
63pub fn stderr_level() -> LevelFilter {
64  match STDERR_LEVEL.load(Ordering::Relaxed) {
65    0 => LevelFilter::Off,
66    1 => LevelFilter::Error,
67    2 => LevelFilter::Warn,
68    3 => LevelFilter::Info,
69    4 => LevelFilter::Debug,
70    _ => LevelFilter::Trace,
71  }
72}
73
74/// Does the current STDERR verbosity admit a record of `level`? `Error`/`Fatal`
75/// are handled unconditionally by the caller (the project's deliberate
76/// always-emit-errors divergence); this governs the verbosity-gated levels.
77pub fn stderr_admits(level: Level) -> bool { level.to_level_filter() <= stderr_level() }
78
79/// Whether STDERR currently shows `Info`-level progress notes — Perl
80/// `$VERBOSITY >= 0`. The `Note!`/`NoteSTDERR!` macros gate their STDERR echo on
81/// this, decoupled from the log-file floor so `--quiet` silences the console note
82/// while the log keeps it (issue #763).
83pub fn stderr_shows_info() -> bool { stderr_admits(Level::Info) }
84
85struct LatexmlLogger;
86static LOGGER: LatexmlLogger = LatexmlLogger;
87
88thread_static! {
89  /// Thread-local log capture buffer. When enabled, log messages are
90  /// appended here (without ANSI colors) in addition to stderr.
91  static LOG_BUFFER: RefCell<Option<String>> = RefCell::new(None);
92}
93
94/// A file that receives a copy of every text appended to a bound [`LOG_BUFFER`]: the log of a
95/// conversion, kept on disk as it is written, for a process whose log buffer dies with it.
96/// `cortex_worker`'s harness children set it so the harness can return the partial log of a
97/// conversion the watchdog, an allocation failure or a signal ended. Process-global because those
98/// exits are taken from other threads than the converting one.
99static LOG_MIRROR: RwLock<Option<&'static File>> = RwLock::new(None);
100/// Whether [`LOG_MIRROR`] is set: the lock-free test every logged text takes first.
101static LOG_MIRROR_ON: AtomicBool = AtomicBool::new(false);
102/// Bytes written to [`LOG_MIRROR`] since it was last emptied.
103static LOG_MIRROR_BYTES: AtomicU64 = AtomicU64::new(0);
104/// The size at which the mirror file is emptied and restarted, so it keeps the most recent text
105/// of a runaway log within this bound.
106static LOG_MIRROR_CAP: AtomicU64 = AtomicU64::new(0);
107
108/// Mirror the captured log into `file` (opened for appending), emptying it whenever it would grow
109/// past `cap_bytes`; `None` stops mirroring.
110pub fn set_log_mirror(file: Option<&'static File>, cap_bytes: u64) {
111  LOG_MIRROR_CAP.store(cap_bytes, Ordering::Release);
112  LOG_MIRROR_BYTES.store(0, Ordering::Release);
113  *LOG_MIRROR.write().unwrap_or_else(PoisonError::into_inner) = file;
114  LOG_MIRROR_ON.store(file.is_some(), Ordering::Release);
115}
116
117/// The log mirror's file, if one is set.
118fn log_mirror() -> Option<&'static File> {
119  if !LOG_MIRROR_ON.load(Ordering::Acquire) {
120    return None;
121  }
122  *LOG_MIRROR.read().unwrap_or_else(PoisonError::into_inner)
123}
124
125/// Empty the log mirror (a new conversion begins).
126pub fn reset_log_mirror() {
127  if let Some(file) = log_mirror() {
128    truncate_file(file);
129    LOG_MIRROR_BYTES.store(0, Ordering::Release);
130  }
131}
132
133/// Copy `text` (just appended to a bound log buffer) to the log mirror, if one is set.
134fn mirror_log_text(text: &str) {
135  if text.is_empty() {
136    return;
137  }
138  let Some(file) = log_mirror() else {
139    return;
140  };
141  let len = text.len() as u64;
142  let cap = LOG_MIRROR_CAP.load(Ordering::Acquire);
143  if cap > 0 && LOG_MIRROR_BYTES.fetch_add(len, Ordering::AcqRel) + len > cap {
144    truncate_file(file);
145    LOG_MIRROR_BYTES.store(len, Ordering::Release);
146  }
147  write_file(file, text.as_bytes());
148}
149
150/// One `ftruncate(2)` to 0, a failure ignored: the mirror is best-effort and must never disturb
151/// the conversion.
152#[cfg(unix)]
153fn truncate_file(file: &File) { let _ = rustix::fs::ftruncate(file, 0); }
154#[cfg(not(unix))]
155fn truncate_file(_file: &File) {}
156
157/// `write(2)` until `bytes` are written, retried on EINTR, given up on any other error or a
158/// zero-length write.
159#[cfg(unix)]
160fn write_file(file: &File, mut bytes: &[u8]) {
161  while !bytes.is_empty() {
162    match rustix::io::write(file, bytes) {
163      Err(rustix::io::Errno::INTR) => continue,
164      Ok(0) | Err(_) => return,
165      Ok(n) => bytes = &bytes[n..],
166    }
167  }
168}
169#[cfg(not(unix))]
170fn write_file(_file: &File, _bytes: &[u8]) {}
171
172/// Does stderr currently sit at the start of a line?
173///
174/// A diagnostic record must begin on a fresh line so CorTeX's line-anchored
175/// parser (`^Error:`/`^Warning:`/`^Info:`) matches and the record never glues
176/// onto an in-flight progress note like `(Loading "foo.sty"… )`, which is
177/// written WITHOUT a trailing newline. That guarantee used to be bought with an
178/// unconditional leading `\n` on every record — which emits a BLANK line
179/// whenever stderr was already at line start, i.e. almost always.
180///
181/// Measured on the 131 MB witness: **1,440,571 of 3,142,509 captured stderr
182/// lines (45.8%) were blank**, matching the record count almost exactly. The
183/// `LOG_BUFFER` path never had this bug — it tests `ends_with('\n')` — so the
184/// on-disk `.latexml.log` and the captured stderr disagreed on line count.
185///
186/// Tracking line-start state reproduces the guarantee at half the bytes.
187///
188/// **Process-global, not per-thread, and mutated under the stderr lock.**
189/// stderr is one shared descriptor: `cortex_worker --pool-size N` runs N
190/// conversion threads in one process, and `logger::capture` exists precisely to
191/// run conversions on worker threads. A per-thread flag would let thread A skip
192/// its leading newline believing the cursor is at line start while thread B had
193/// left it mid-line — gluing a record onto B's output, where CorTeX's
194/// `^Error:`/`^Warning:` anchor then misses it entirely. That is a silent
195/// error-count loss, the exact failure this project's signal-integrity rule
196/// forbids (false negatives hide regressions). The unconditional leading `\n`
197/// was robust to that by construction, so the replacement has to be too:
198/// check-write-set happens as one critical section holding the stderr lock.
199static STDERR_AT_LINE_START: AtomicBool = AtomicBool::new(true);
200
201/// Whether stderr sits at the start of a line (`STDERR_AT_LINE_START`): read without the stderr lock by
202/// [`crate::watchdog::write_stderr_unlocked`], which must not wait on a stuck thread.
203pub fn stderr_at_line_start() -> bool { STDERR_AT_LINE_START.load(Ordering::Acquire) }
204
205/// Records where a write that bypassed the logger (`watchdog::write_stderr_unlocked`) left stderr's cursor.
206pub fn set_stderr_at_line_start(at_line_start: bool) {
207  STDERR_AT_LINE_START.store(at_line_start, Ordering::Release);
208}
209
210/// Perl `print STDERR _freshline(\*STDERR), $text`: a direct STDERR write at any verbosity, on a fresh line. One write
211/// under the (reentrant) stderr lock, so a capture buffer shared by a test's threads never splits a line.
212pub fn stderr_fresh_line(text: &str) {
213  let _stderr = std::io::stderr().lock();
214  let lead = if STDERR_AT_LINE_START.load(Ordering::Acquire) {
215    ""
216  } else {
217    "\n"
218  };
219  stderr_echo(&format!("{lead}{text}"));
220  STDERR_AT_LINE_START.store(text.ends_with('\n'), Ordering::Release);
221}
222
223/// Start capturing log output into the buffer (Perl: bind_log).
224pub fn bind_log() { *LOG_BUFFER.borrow_mut() = Some(String::new()); }
225
226/// Flush and return the captured log output, stopping capture (Perl: flush_log).
227pub fn flush_log() -> String { LOG_BUFFER.borrow_mut().take().unwrap_or_default() }
228
229/// The log captured so far, unflushed, for a panic hook: `None` when no log is bound or the panic holds the buffer.
230pub fn try_with_log_text<R>(f: impl FnOnce(&str) -> R) -> Option<R> {
231  LOG_BUFFER.try_borrow().ok()?.as_deref().map(f)
232}
233
234/// Append a progress note to the captured log (`.latexml.log`) only — the LOG
235/// half of Perl `Note`/`NoteLog` (`Common/Error.pm`: `print $LOG _freshline($LOG),
236/// strip_ansi($message), "\n" if $LOG`). ANSI is stripped and the note lands on
237/// its own fresh line with a single trailing newline, so CorTeX's line-anchored
238/// parser and the `.latexml.log` stay clean (mirrors the diagnostic-record
239/// freshline path below). No-op when no buffer is bound or output is suppressed —
240/// unlike a `log::info!` record it is NOT gated on the stderr verbosity, because
241/// the log is the verbose record (Perl writes it regardless of `$VERBOSITY`).
242pub fn note_to_log(msg: &str) {
243  if crate::common::error::is_log_output_suppressed() {
244    return;
245  }
246  crate::common::error::print_deferred_notes();
247  if let Ok(mut buf) = LOG_BUFFER.try_borrow_mut()
248    && let Some(ref mut log) = *buf
249  {
250    let clean = strip_ansi(msg);
251    let start = log.len();
252    if !log.is_empty() && !log.ends_with('\n') {
253      log.push('\n');
254    }
255    log.push_str(&clean);
256    if !log.ends_with('\n') {
257      log.push('\n');
258    }
259    mirror_log_text(&log[start..]);
260  }
261}
262
263/// Diagnostics captured from a worker thread by [`capture`], for the main thread
264/// to fold back in via [`replay_captured`]. Carries both the already-formatted
265/// log text AND the `REPORT` count deltas — `LOG_BUFFER` and `REPORT` are BOTH
266/// per-thread, so forwarding only the text would still leave
267/// `status_code` blind to a worker's failures.
268pub struct CapturedDiagnostics {
269  pub log:    String,
270  pub counts: crate::common::error::ReportCounts,
271}
272
273/// Run `f` on the CURRENT (worker) thread with diagnostic capture. Binds a fresh
274/// thread-local log buffer for the duration so any `Error!`/`Warn!`/`Info!` `f`
275/// emits (directly or deep inside a conversion helper) is recorded instead of
276/// lost, and snapshots the worker's `REPORT` counters afterward. The returned
277/// [`CapturedDiagnostics`] is replayed on the main thread by [`replay_captured`]
278/// after the worker is joined, so the messages reach the bound `cortex.log` and
279/// the failures register in `status_code`.
280///
281/// Assumes the worker thread has no pre-bound buffer (the spawned post-processing
282/// pool threads start clean); it does not save/restore a prior binding.
283///
284/// INVARIANTS (unenforced by types; guard the fleet's canonical signal):
285/// - one `capture` per thread lifetime — `bind_log()` CLOBBERS any pre-bound
286///   buffer, and `snapshot_report_counts` does not reset, so reusing capture
287///   on a pooled thread would drop earlier text and double-merge counts;
288/// - callers must `replay_captured` the result on the MAIN thread exactly
289///   once (a panicking worker never returns, losing its pre-panic capture —
290///   the real-time stderr echo retains it, and the caller's worker_panicked
291///   Error keeps status from reading clean).
292pub fn capture<R>(f: impl FnOnce() -> R) -> (R, CapturedDiagnostics) {
293  debug_assert!(
294    LOG_BUFFER
295      .try_borrow()
296      .map(|b| b.is_none())
297      .unwrap_or(false),
298    "logger::capture on a thread with a pre-bound buffer — pooled-thread reuse?"
299  );
300  bind_log();
301  let result = f();
302  let log = flush_log();
303  let counts = crate::common::error::snapshot_report_counts();
304  (result, CapturedDiagnostics { log, counts })
305}
306
307/// Fold worker-thread diagnostics (from [`capture`]) into the main thread: append
308/// the captured log text to the bound `LOG_BUFFER` and merge the count deltas
309/// into the main `REPORT`. Call on the MAIN thread, in a deterministic order
310/// (e.g. worker/job order), after the workers join. The worker already echoed
311/// each line to the shared stderr fd in real time, so this does NOT re-print to
312/// stderr — it only repairs the captured log + status tally.
313pub fn replay_captured(d: CapturedDiagnostics) {
314  debug_assert!(
315    LOG_BUFFER.try_borrow().is_ok(),
316    "replay_captured: LOG_BUFFER contended — captured text would be dropped"
317  );
318  // Not mirrored: a worker thread's own buffer already mirrored this text as it was written
319  // (a render worker *process*'s replayed log, `render_workers.rs`, is not in the mirror).
320  append_logged_text(&d.log);
321  crate::common::error::merge_report_counts(d.counts);
322}
323
324/// Append to the bound log text already logged once (a worker's captured log, a session's log), on a fresh line;
325/// not re-mirrored, as the mirror took it when it was first written.
326pub fn append_logged_text(text: &str) {
327  if !text.is_empty()
328    && let Ok(mut buf) = LOG_BUFFER.try_borrow_mut()
329    && let Some(ref mut log) = *buf
330  {
331    if !log.is_empty() && !log.ends_with('\n') {
332      log.push('\n');
333    }
334    log.push_str(text);
335  }
336}
337
338/// Strip ANSI escape sequences from a string for log file output.
339fn strip_ansi(s: &str) -> String {
340  // Match ESC[ ... m sequences
341  let mut result = String::with_capacity(s.len());
342  let mut in_escape = false;
343  for c in s.chars() {
344    if in_escape {
345      if c == 'm' {
346        in_escape = false;
347      }
348    } else if c == '\x1b' {
349      in_escape = true;
350    } else {
351      result.push(c);
352    }
353  }
354  result
355}
356
357/// Append a progress note to the capture buffer as INLINE flowing text — the
358/// faithful Perl LaTeXML / tex.web terminal-progress format. `note_begin`
359/// carries a leading '\n' so each stage opens on a fresh line; `note_end`
360/// (` )`) and `note_progress` (`[1][2]…`, `N formulae …`) append inline so a
361/// load's closing paren and the page markers stay on the SAME line as their
362/// opener, and nested closes chain (`… 0.00 sec) 0.05 sec)`). A leading '\n'
363/// is collapsed against an existing trailing '\n' (or buffer start) so we never
364/// emit a blank line. Replaces the old unconditional `push('\n')` per note,
365/// which put every `)` on its own line and doubled newlines into blank lines
366/// (the reported `.latexml.log` noise on corpora.latexml.rs).
367fn append_note(buf: &mut String, note: &str) {
368  if note.starts_with('\n') && (buf.is_empty() || buf.ends_with('\n')) {
369    buf.push_str(&note[1..]);
370  } else {
371    buf.push_str(note);
372  }
373}
374
375/// prints a single line to STDERR. Through `eprintln!`, as `stderr_echo`, so a test harness's
376/// output capture receives it.
377#[macro_export]
378macro_rules! println_stderr(
379    ($($arg:tt)*) => ({
380      ::std::eprintln!($($arg)*);
381    })
382);
383
384/// prints a to STDERR without a line break, through `eprint!` like `println_stderr!`.
385#[macro_export]
386macro_rules! print_stderr(
387    ($($arg:tt)*) => ({
388      ::std::eprint!($($arg)*);
389    })
390);
391
392/// The console echo of a log line: `eprint!`, the standard library's capture-aware stderr path.
393/// Under libtest (`cargo test`) a test thread's `eprint!` output is captured with the test and
394/// shown only when it fails; a direct `std::io::stderr()` write bypasses that capture, so every
395/// passing test's `Info:`/`Warning:`/`Error:` lines interleaved on the terminal. Threads spawned
396/// by a test (the conversion helpers' big-stack threads) inherit its capture. Outside a test
397/// harness this is the plain stderr write it replaced, apart from `eprint!`'s panic on a failed
398/// write (a closed pipe), which `println_stderr!` already had.
399fn stderr_echo(text: &str) {
400  ::std::eprint!("{text}");
401}
402
403impl log::Log for LatexmlLogger {
404  fn enabled(&self, metadata: &Metadata) -> bool {
405    metadata.level() <= max_level()
406      && (metadata.level() <= Level::Info
407        || debug_all()
408        || crate::common::error::debug_enabled(metadata.target()))
409  }
410
411  fn log(&self, record: &Record) {
412    if self.enabled(record.metadata()) {
413      let record_target = record.target();
414      let details = record.args();
415      if record_target == "note" {
416        let note = details.to_string();
417        // (a line inside a binding load not yet announced comes after its `(Loading …`, #945)
418        crate::common::error::print_deferred_notes();
419        // A note (e.g. `(Loading foo.sty… )`) is a live progress indicator — but when a capture
420        // buffer is active it must ALSO land there so it reaches the flushed `cortex.log` and
421        // CorTeX's `loaded_file` parser, which anchors on `^(Loading …`. `append_note` keeps it
422        // INLINE (Perl-faithful: `(Loading X… )` on one line, `[1][2]…` chained) while preserving
423        // the `^(Loading` anchor — every `note_begin` carries a leading '\n', so each load still
424        // opens at line start. The following `Info:/Warning:` record re-asserts its own line break
425        // (see the diagnostic-record path below), so the note can't glue onto its anchor.
426        if let Ok(mut buf) = LOG_BUFFER.try_borrow_mut()
427          && let Some(ref mut log) = *buf
428        {
429          let start = log.len();
430          append_note(log, &strip_ansi(&note));
431          mirror_log_text(&log[start..]);
432        }
433        // The LOG append above is the log-file record (Perl `$LOG` write, always).
434        // The STDERR echo is the live console indicator and is gated on the
435        // decoupled verbosity: `--quiet` silences the note here while the log
436        // still keeps it (issue #763; Perl `ProgressSpinup` gates STDERR on
437        // `$VERBOSITY >= 0`). Write and publish the cursor state under ONE stderr
438        // lock, so a concurrent diagnostic record cannot observe a stale flag.
439        if stderr_admits(record.level()) {
440          let _stderr = std::io::stderr().lock();
441          stderr_echo(&note);
442          // A note carries no trailing newline of its own unless its text ends
443          // in one (`note_begin` opens with a leading '\n'), so record where it
444          // left the cursor for the next diagnostic record.
445          STDERR_AT_LINE_START.store(note.ends_with('\n'), Ordering::Release);
446        }
447        return;
448      }
449      let category_object = if record_target.is_empty() {
450        "" // "unknown:unknown" ???
451      } else {
452        record_target
453      };
454      // Following the reporting syntax at: https://math.nist.gov/~BMiller/LaTeXML/manual/errorcodes/
455      // The severity word is the FULL Perl LaTeXML token (Info/Warning/Error/Fatal) — consumers
456      // (CorTeX's log parser, the --server LSP) key on it, so it must match Perl exactly. In
457      // particular WARN must serialize as `Warning` (not the abbreviated `Warn`): CorTeX maps an
458      // unrecognized severity to Info, so `Warn:` silently misfiled every warning (see
459      // LaTeXML/lib/LaTeXML/Common/Error.pm: `"Warning:" . $category . …`).
460      let severity = if category_object.starts_with("Fatal:") {
461        ""
462      } else {
463        match record.level() {
464          Level::Info => "Info",
465          Level::Warn => "Warning",
466          Level::Error => "Error",
467          Level::Debug => "Debug",
468          Level::Trace => "Trace",
469        }
470      };
471
472      // Tally every printed diagnostic record that was NOT emitted by a
473      // counting macro (those count at raise time, even under output
474      // suppression — the MAX_ERRORS cap depends on that). This is the
475      // lossless half of the tally contract: any `Warning:`/`Error:` line
476      // this backend prints from a raw `log::warn!`/`log::error!` call now
477      // registers in `REPORT`, so the final "Conversion complete: N
478      // warnings" agrees with what a reader greps from the log. Witness:
479      // the 131 MB witness logged 12,105 `Warning:` lines (12,103 of them
480      // the math parser's raw `log_math_warn!`) and reported "2 warnings".
481      {
482        use crate::common::error::{LogStatus, note_status_from_logger};
483        let status = if category_object.starts_with("Fatal:") {
484          Some(LogStatus::Fatal)
485        } else {
486          match record.level() {
487            Level::Warn => Some(LogStatus::Warning),
488            Level::Error => Some(LogStatus::Error),
489            Level::Info => Some(LogStatus::Info),
490            Level::Debug => Some(LogStatus::Debug),
491            // No Trace counter exists; Trace records stay uncounted.
492            Level::Trace => None,
493          }
494        };
495        if let Some(status) = status {
496          note_status_from_logger(status);
497        }
498      }
499      let message = if severity.is_empty() {
500        s!("{} ", category_object)
501      } else {
502        s!("{}:{} ", severity, category_object)
503      };
504      let painted_message = match record.level() {
505        Level::Info => message,
506        Level::Warn => paint(ANSI_YELLOW, &message),
507        Level::Error => paint(ANSI_RED, &message),
508        Level::Debug => paint(ANSI_GREEN, &message),
509        _ => paint(ANSI_WHITE, &message),
510      } + &details.to_string();
511
512      if !hold_record(record.level(), &painted_message) {
513        write_record(record.level(), painted_message);
514      }
515    }
516  }
517
518  fn flush(&self) {}
519}
520
521/// Write one formatted diagnostic record: the log-file buffer (always) and the
522/// STDERR echo (gated). The tail of [`LatexmlLogger::log`], shared with
523/// [`DiagnosticsHold::commit`], which writes records it held back.
524fn write_record(level: Level, painted_message: String) {
525  crate::common::error::print_deferred_notes();
526  // Capture to log buffer if active (strip ANSI for clean log text).
527  // A diagnostic record (Info/Warning/Error/Fatal) must start on a fresh
528  // line so CorTeX's line-anchored parser (^Error:/^Warning:/^Info:)
529  // matches and the record never glues onto an in-flight progress note
530  // (notes no longer force a trailing newline — see append_note).
531  if let Ok(mut buf) = LOG_BUFFER.try_borrow_mut()
532    && let Some(ref mut log) = *buf
533  {
534    let start = log.len();
535    if !log.is_empty() && !log.ends_with('\n') {
536      log.push('\n');
537    }
538    log.push_str(&strip_ansi(&painted_message));
539    // Exactly one trailing newline — a multi-detail message (e.g.
540    // `Info:…loaded …\n\tat …\n\tIn …`) already ends with '\n', so an
541    // unconditional push would double it into a blank line before the next
542    // `(Loading …` note.
543    if !log.ends_with('\n') {
544      log.push('\n');
545    }
546    mirror_log_text(&log[start..]);
547  }
548
549  // Use `\n` (not `\r`) to guarantee each log line starts on a fresh
550  // line in both TTY and file output. The previous `\r` prefix made
551  // log lines visually overlay any in-flight progress indicator like
552  // `(Loading "foo.sty" definitions... )` — convenient in a terminal
553  // but produced `(...)<CR>Error:...` byte sequences in log files,
554  // breaking line-anchored counts in canvas harnesses
555  // (`grep -cE '^...Error:'` silently returned 0 even when errors
556  // were present). Trade-off: progress indicators in a TTY no longer
557  // get overwritten, but they were not really self-erasing anyway
558  // (they always emitted ` )` to close their parens), so the visual
559  // change is small.
560  // Colorize for an interactive terminal only; when stderr is redirected
561  // to a file/pipe, emit the ANSI-stripped text so on-disk logs stay
562  // grep-clean (matches the captured `.latexml.log` buffer above).
563  // Break onto a fresh line ONLY when a note left the cursor mid-line —
564  // an unconditional leading '\n' was 45.8% of the witness's log (see
565  // STDERR_AT_LINE_START). One critical section: read the flag, write, and
566  // republish it while holding the stderr lock, so the "record starts at
567  // line start" guarantee survives concurrent loggers.
568  //
569  // The LOG_BUFFER append above is the log-file record (Perl `$LOG`, always,
570  // subject only to the Info floor). The STDERR echo is gated on the decoupled
571  // console verbosity so `--quiet` reduces the console without touching the log
572  // (issue #763) — EXCEPT `Error`/`Fatal`, which always reach STDERR (the
573  // project's deliberate always-emit-errors divergence, since cortex aggregates
574  // success rates from `Error:`/`Fatal:` lines; Perl prints nothing below
575  // `$VERBOSITY` 0, `_printline`; OXIDIZED_DESIGN_DIVERGENCES #1158). `Error` is
576  // the lowest `Level` value and Fatal records are emitted at `Level::Error`, so
577  // `<= Error` captures both.
578  // A `Debug` record that got here is wanted (`--verbose` or its feature); it prints at Perl's `$VERBOSITY >= 0`.
579  let to_stderr = level <= Level::Error || stderr_admits(level.min(Level::Info));
580  if to_stderr {
581    let text = if stderr_use_color() {
582      painted_message
583    } else {
584      strip_ansi(&painted_message)
585    };
586    stderr_fresh_line(&format!("{text}\n"));
587  }
588}
589
590thread_static! {
591  /// Diagnostic records held back by an active [`DiagnosticsHold`], in order.
592  static HELD: RefCell<Option<Vec<(Level, String)>>> = RefCell::new(None);
593}
594
595thread_static! {
596  /// The control sequences an active [`DiagnosticsHold`]'s scope stubbed as undefined
597  /// ([`crate::state::generate_error_stub`]): the stub stands in for the error, so it goes with it.
598  static HELD_STUBS: RefCell<Option<Vec<crate::token::Token>>> = RefCell::new(None);
599}
600
601/// Record that `token` was just stubbed as undefined, when a [`DiagnosticsHold`] is active.
602pub fn note_held_stub(token: crate::token::Token) {
603  if let Ok(mut stubs) = HELD_STUBS.try_borrow_mut()
604    && let Some(stubs) = stubs.as_mut()
605  {
606    stubs.push(token);
607  }
608}
609
610/// Hold a formatted record when a [`DiagnosticsHold`] is active on this
611/// thread; `false` means "write it now".
612fn hold_record(level: Level, painted_message: &str) -> bool {
613  match HELD.try_borrow_mut() {
614    Ok(mut held) => match held.as_mut() {
615      Some(records) => {
616        records.push((level, painted_message.to_string()));
617        true
618      },
619      None => false,
620    },
621    // Never lose a record to a contended cell: write it.
622    Err(_) => false,
623  }
624}
625
626/// A speculative scope's diagnostics, held until the caller decides whether
627/// the scope's RESULT is kept. For work the engine runs on its own initiative
628/// in a state the document never produces — the `\maketitle` deposit replays
629/// a class's dropped title body with the title fields emptied — so that its
630/// diagnostics are the document's exactly when its output is:
631///
632/// * [`commit`](Self::commit) writes the held records, in order, as if never
633///   held (the counts were taken at raise time and stand);
634/// * [`discard`](Self::discard) drops them AND restores the report counts —
635///   and the runaway guards beside them — to the snapshot, so the log and the
636///   status agree that nothing was raised (the whole-diagnostic rule of
637///   `set_ignore_diagnostics`). Only diagnostics are rolled back, with the
638///   error stubs that stand in for them (an undefined control sequence's
639///   `<ltx:ERROR/>` definition, installed globally: kept, it would turn the
640///   document's own later use of that command into an uncounted error). The
641///   scope's other side effects (a global assignment it made) stay.
642///
643/// Holds nest (a commit writes into the enclosing hold). Dropping an
644/// unresolved hold commits it, so a panic or an early return cannot lose a
645/// diagnostic. Progress notes (`(Loading …)`) are never held.
646#[must_use = "resolve the hold with commit() or discard()"]
647pub struct DiagnosticsHold {
648  outer:       Option<Vec<(Level, String)>>,
649  outer_stubs: Option<Vec<crate::token::Token>>,
650  // (the scope runs without the enclosing stashed Fatal, `stomach::stash_fatal`, and drops its own with a discard)
651  outer_stash: Option<crate::common::error::Error>,
652  snapshot:    crate::common::error::DiagnosticGates,
653  resolved:    bool,
654}
655
656impl DiagnosticsHold {
657  /// Start holding this thread's diagnostic records.
658  pub fn begin() -> Self {
659    let snapshot = crate::common::error::save_diagnostic_gates();
660    let outer = HELD.borrow_mut().replace(Vec::new());
661    let outer_stubs = HELD_STUBS.borrow_mut().replace(Vec::new());
662    DiagnosticsHold {
663      outer,
664      outer_stubs,
665      outer_stash: crate::stomach::set_aside_stashed_fatal(),
666      snapshot,
667      resolved: false,
668    }
669  }
670
671  /// Errors (a Fatal counts as one) raised since [`begin`](Self::begin), those dropped after a Fatal too.
672  pub fn errors_raised(&self) -> usize {
673    let now = crate::common::error::REPORT.borrow();
674    let then = &self.snapshot.report;
675    let muted = crate::common::error::muted_errors().saturating_sub(self.snapshot.muted_errors);
676    now.error.saturating_sub(then.error) + usize::from(now.fatal && !then.fatal) + muted
677  }
678
679  /// Whether a Fatal was raised since [`begin`](Self::begin): counted (the report's flag set) or held as a record — what
680  /// [`defer`](Self::defer) never sets aside, and a caller taking back its work must not [`discard`](Self::discard).
681  pub fn fatal_raised(&self) -> bool {
682    let fatal_now = {
683      let now = crate::common::error::REPORT.borrow();
684      now.fatal && !self.snapshot.report.fatal
685    };
686    fatal_now
687      || HELD.borrow().as_ref().is_some_and(|records| {
688        records
689          .iter()
690          .any(|(_, m)| strip_ansi(m).starts_with("Fatal:"))
691      })
692  }
693
694  /// Warnings raised since [`begin`](Self::begin) (a suppressed one counted too).
695  pub fn warnings_raised(&self) -> usize {
696    let now = crate::common::error::REPORT.borrow();
697    now.warning.saturating_sub(self.snapshot.report.warning)
698  }
699
700  /// The errors held since [`begin`](Self::begin), in order: each record's first line, without its colors.
701  pub fn held_errors(&self) -> Vec<String> {
702    HELD.borrow().as_ref().map_or_else(Vec::new, |records| {
703      records
704        .iter()
705        .map(|(_, message)| strip_ansi(message))
706        .filter(|message| message.starts_with("Error:"))
707        .map(|message| message.lines().next().unwrap_or("").to_string())
708        .collect()
709    })
710  }
711
712  fn take_held(&mut self) -> Vec<(Level, String)> {
713    self.resolved = true;
714    let mut held = HELD.borrow_mut();
715    let records = held.take().unwrap_or_default();
716    *held = self.outer.take();
717    records
718  }
719
720  /// The scope's stubs; the enclosing hold's list is current again.
721  fn take_stubs(&mut self) -> Vec<crate::token::Token> {
722    let mut stubs = HELD_STUBS.borrow_mut();
723    let own = stubs.take().unwrap_or_default();
724    *stubs = self.outer_stubs.take();
725    own
726  }
727
728  /// The scope raised no diagnostic since [`begin`](Self::begin): nothing held, nothing counted (a suppressed
729  /// Warning is counted without a record), no Error dropped after a Fatal.
730  pub fn is_empty(&self) -> bool {
731    let report = crate::common::error::REPORT.borrow();
732    let then = &self.snapshot.report;
733    HELD.borrow().as_ref().is_none_or(Vec::is_empty)
734      && (
735        report.debug,
736        report.info,
737        report.warning,
738        report.error,
739        report.fatal,
740      ) == (then.debug, then.info, then.warning, then.error, then.fatal)
741      && crate::common::error::muted_errors() == self.snapshot.muted_errors
742  }
743
744  /// The scope raised nothing but Debug messages (counted, never written): [`is_empty`](Self::is_empty) but for those.
745  /// A held tag whose typesetting only traced itself holds nothing to defer (latexml_engine tags_refnums.rs
746  /// `\lx@tag@intags@held`).
747  /// (An Error dropped after a Fatal is not counted here, unlike [`is_empty`](Self::is_empty): it left nothing to
748  /// defer.)
749  pub fn is_empty_but_debug(&self) -> bool {
750    let report = crate::common::error::REPORT.borrow();
751    let then = &self.snapshot.report;
752    HELD.borrow().as_ref().is_none_or(Vec::is_empty)
753      && (report.info, report.warning, report.error, report.fatal)
754        == (then.info, then.warning, then.error, then.fatal)
755  }
756
757  /// Keep the scope's diagnostics: write the held records.
758  pub fn commit(mut self) { self.commit_records(); }
759
760  /// Set the scope's diagnostics aside until their use ([`DeferredDiagnostics`]): records and counts are taken back as
761  /// [`discard`](Self::discard) takes them — the error stubs too, so a later use of the command raises its own error
762  /// — and kept to be replayed ([`replay_shown_deferred`]). A Fatal is never deferred: it is committed (`None`).
763  pub fn defer(mut self) -> Option<DeferredDiagnostics> {
764    let (counts, missing, undefined) = {
765      let now = crate::common::error::REPORT.borrow();
766      let then = &self.snapshot.report;
767      let held_fatal = HELD.borrow().as_ref().is_some_and(|records| {
768        records
769          .iter()
770          .any(|(_, m)| strip_ansi(m).starts_with("Fatal:"))
771      });
772      if (now.fatal && !then.fatal) || held_fatal {
773        drop(now);
774        self.commit_records();
775        return None;
776      }
777      // The undefined names the scope's errors recorded (not every `Error:undefined:` does: `\csname` and keyval
778      // errors count no name), for replay to record exactly those.
779      let undefined: Vec<(String, usize)> = now
780        .undefined
781        .0
782        .iter()
783        .filter_map(|(key, &n)| {
784          let added = n.saturating_sub(then.undefined.get_sym(*key).copied().unwrap_or(0));
785          (added > 0).then(|| (crate::common::arena::to_string(*key), added))
786        })
787        .collect();
788      let missing: Vec<_> = now
789        .missing
790        .0
791        .iter()
792        .filter_map(|(key, &n)| {
793          let added = n.saturating_sub(then.missing.get_sym(*key).copied().unwrap_or(0));
794          (added > 0).then_some((*key, added))
795        })
796        .collect();
797      // Errors (and the undefined names they report) are counted per replayed record; the rest by count, as a
798      // suppressed Warning or Info leaves no record.
799      let counts = crate::common::error::ReportCounts {
800        debug:   now.debug.saturating_sub(then.debug),
801        info:    now.info.saturating_sub(then.info),
802        warning: now.warning.saturating_sub(then.warning),
803        error:   0,
804        fatal:   false,
805      };
806      (counts, missing, undefined)
807    };
808    for stub in self.take_stubs() {
809      crate::state::remove_error_stub(&stub);
810    }
811    let records = self.take_held();
812    crate::stomach::restore_stashed_fatal(self.outer_stash.take(), false);
813    crate::common::error::restore_diagnostic_gates(self.snapshot.clone());
814    Some(DeferredDiagnostics {
815      records,
816      counts,
817      missing,
818      undefined,
819    })
820  }
821
822  fn commit_records(&mut self) {
823    // An enclosing hold now answers for the scope's stubs.
824    for stub in self.take_stubs() {
825      note_held_stub(stub);
826    }
827    crate::stomach::restore_stashed_fatal(self.outer_stash.take(), true);
828    for (level, message) in self.take_held() {
829      if !hold_record(level, &message) {
830        write_record(level, message);
831      }
832    }
833  }
834
835  /// Drop the scope's diagnostics, records and counts alike — with the
836  /// runaway gates beside the counts ([`DiagnosticGates`]). Returns how many
837  /// records were dropped.
838  ///
839  /// [`DiagnosticGates`]: crate::common::error::DiagnosticGates
840  pub fn discard(mut self) -> usize {
841    for stub in self.take_stubs() {
842      crate::state::remove_error_stub(&stub);
843    }
844    let dropped = self.take_held().len();
845    crate::stomach::restore_stashed_fatal(self.outer_stash.take(), false);
846    crate::common::error::restore_diagnostic_gates(self.snapshot.clone());
847    dropped
848  }
849}
850
851impl Drop for DiagnosticsHold {
852  fn drop(&mut self) {
853    if !self.resolved {
854      self.commit_records();
855    }
856  }
857}
858
859/// Diagnostics a [`DiagnosticsHold`] set aside ([`DiagnosticsHold::defer`]) for work done ahead of its use: written and
860/// counted only when replayed. An `\autoref` name is built at its target but typeset — and its errors
861/// raised, in TeX — only where an `\autoref` prints it (ruling 7e; [`replay_shown_deferred`]; witness
862/// biblatex-gost-examples, hyperref's Russian `\cyr…` names under TU).
863pub struct DeferredDiagnostics {
864  records:   Vec<(Level, String)>,
865  counts:    crate::common::error::ReportCounts,
866  missing:   Vec<(crate::common::arena::SymStr, usize)>,
867  undefined: Vec<(String, usize)>,
868}
869
870impl DeferredDiagnostics {
871  /// Write the records as if raised now, through the accounting of a live diagnostic: an Error is dropped once the
872  /// error cap or a resource Fatal has latched, counted, and checked against the cap (after any Fatal only counted:
873  /// `note_error_cap` returns early on the mute); an undefined command is
874  /// reported once per document (`undefined` names already replayed, as its error stub makes it in LaTeXML). The
875  /// records keep the target's location.
876  fn replay(mut self, undefined_seen: &mut rustc_hash::FxHashSet<String>) {
877    use crate::common::error::{
878      LogStatus, note_error_cap, note_status, resource_fatal_latched, too_many_errors_latched,
879    };
880    for (level, message) in self.records {
881      let plain = strip_ansi(&message);
882      let key = plain.split_whitespace().next().unwrap_or("");
883      let mut parts = key.splitn(3, ':');
884      let (_, category, object) = (
885        parts.next(),
886        parts.next().unwrap_or(""),
887        parts.next().unwrap_or(""),
888      );
889      if level == Level::Error {
890        // Not the after-Fatal mute: a held record was raised before any Fatal (one after it never reaches a hold,
891        // `error::emit_record`; a Fatal in the hold commits it, `defer`), and the replay comes after the build.
892        if too_many_errors_latched() || resource_fatal_latched() {
893          continue;
894        }
895        if category == "undefined" && !undefined_seen.insert(object.to_string()) {
896          continue;
897        }
898      }
899      if !hold_record(level, &message) {
900        write_record(level, message);
901      }
902      if level == Level::Error {
903        note_status(LogStatus::Error, None);
904        // As the live raise recorded it: only a name the scope's errors put on the undefined list.
905        if category == "undefined"
906          && let Some((_, n)) = self
907            .undefined
908            .iter_mut()
909            .find(|(name, n)| name == object && *n > 0)
910        {
911          *n -= 1;
912          note_status(LogStatus::Undefined, Some(object));
913        }
914        note_error_cap(&format!("{category}:{object}"));
915      }
916    }
917    crate::common::error::merge_report_counts(self.counts);
918    let mut report = crate::common::error::REPORT.borrow_mut();
919    for (key, n) in self.missing {
920      *report.missing.0.entry(key).or_default() += n;
921    }
922  }
923}
924
925thread_static! {
926  /// The job's deferred diagnostics by id, until replayed or dropped.
927  static DEFERRED: RefCell<Vec<Option<DeferredDiagnostics>>> = RefCell::new(Vec::new());
928}
929/// Label → (role of the held tag, deferred id) its target answers for.
930type HeldByLabel = rustc_hash::FxHashMap<String, Vec<(String, usize)>>;
931thread_static! {
932  /// The deferred diagnostics each label's target answers for.
933  static DEFERRED_AT_LABEL: RefCell<Option<HeldByLabel>> = RefCell::new(None);
934}
935thread_static! {
936  /// Every reference to a label, with the `show` that prints its target's tags.
937  static LABEL_USES: RefCell<Vec<(String, String)>> = RefCell::new(Vec::new());
938}
939
940/// Keep deferred diagnostics; their id.
941pub fn keep_deferred(deferred: DeferredDiagnostics) -> usize {
942  let mut kept = DEFERRED.borrow_mut();
943  kept.push(Some(deferred));
944  kept.len() - 1
945}
946
947/// Whether any deferred diagnostics are kept: a held tag may wait in the document (sect11.rs `settle_held_tags`).
948pub fn deferred_kept() -> bool { !DEFERRED.borrow().is_empty() }
949
950/// The target of `label` answers for deferred diagnostics `id`, raised by its (or its ancestor's) tag of `role`.
951pub fn defer_to_label(label: &str, role: &str, id: usize) {
952  DEFERRED_AT_LABEL
953    .borrow_mut()
954    .get_or_insert_with(Default::default)
955    .entry(label.to_string())
956    .or_default()
957    .push((role.to_string(), id));
958}
959
960/// A reference to `label` prints its target's tags as `show` names them.
961pub fn note_label_use(label: &str, show: &str) {
962  LABEL_USES
963    .borrow_mut()
964    .push((label.to_string(), show.to_string()));
965}
966
967/// Replay the deferred diagnostics of every tag a reference prints — a held tag of role R answering for a label,
968/// referenced with a `show` naming R (a word of it: CrossRef's show words, `autoref`, `typerefnum`…; a looser split
969/// than CrossRef's, so it can only replay more) — once each; the rest are dropped unraised, as TeX never typesets them.
970/// Run once the document is built (forward references included); empties the job's registries.
971pub fn replay_shown_deferred() {
972  let uses = std::mem::take(&mut *LABEL_USES.borrow_mut());
973  let at_label = DEFERRED_AT_LABEL.borrow_mut().take().unwrap_or_default();
974  let mut deferred = std::mem::take(&mut *DEFERRED.borrow_mut());
975  // A command the document already reported undefined (a later live use, once the deferral had taken its stub back)
976  // is not reported again: once per document.
977  let mut undefined_seen: rustc_hash::FxHashSet<String> = crate::common::error::REPORT
978    .borrow()
979    .undefined
980    .0
981    .keys()
982    .map(|key| crate::common::arena::to_string(*key))
983    .collect();
984  for (label, show) in &uses {
985    let Some(held) = at_label.get(label) else {
986      continue;
987    };
988    for (role, id) in held {
989      let shown = show
990        .split(|c: char| !c.is_ascii_alphanumeric())
991        .any(|word| word.eq_ignore_ascii_case(role));
992      if shown && let Some(diagnostics) = deferred.get_mut(*id).and_then(Option::take) {
993        diagnostics.replay(&mut undefined_seen);
994      }
995    }
996  }
997}
998
999/// Free the log capture buffer, the held records and the deferred diagnostics, for a thread about to exit
1000/// (`crate::shrink_thread_engine`): they are leaked per-thread statics.
1001pub(crate) fn shrink() {
1002  LOG_BUFFER.borrow_mut().take();
1003  HELD.borrow_mut().take();
1004  HELD_STUBS.borrow_mut().take();
1005  *DEFERRED.borrow_mut() = Vec::new();
1006  DEFERRED_AT_LABEL.borrow_mut().take();
1007  *LABEL_USES.borrow_mut() = Vec::new();
1008}
1009
1010/// Forget the job's deferred diagnostics (each conversion's `initialize_report`), the empty held tags it was waiting
1011/// on too: a persistent worker's next paper starts at none.
1012pub fn reset_deferred_diagnostics() {
1013  DEFERRED.borrow_mut().clear();
1014  DEFERRED_AT_LABEL.borrow_mut().take();
1015  LABEL_USES.borrow_mut().clear();
1016  EMPTY_HELD_TAGS.set(0);
1017}
1018
1019thread_local! {
1020  /// How many empty held tags are kept in the document, waiting for their target to settle them
1021  /// ([`note_empty_held_tag`]).
1022  static EMPTY_HELD_TAGS: Cell<usize> = const { Cell::new(0) };
1023}
1024
1025/// A held tag (`\lx@tag@intags@held`, latexml_engine tags_refnums.rs) that typeset nothing but holds diagnostics
1026/// (`_deferred`) is kept, empty, until its target closes, which ties them to its labels (latex_constructs sect11.rs
1027/// `tie_held_tags`) and then removes it ([`take_empty_held_tag`]); one no target closed over (a caption's tags folded
1028/// into a minipage panel) is settled once the document is built (sect11.rs `settle_held_tags`, tied to its
1029/// owner's labels only: an unlabelled owner drops it with its diagnostics). A form that errs
1030/// gives no content, and its errors are raised where a reference prints its role (cleveref_sty.rs
1031/// `\lx@cref@docformat`; 2008.12750, 2604.24399).
1032pub fn note_empty_held_tag() { EMPTY_HELD_TAGS.set(EMPTY_HELD_TAGS.get() + 1); }
1033
1034/// Whether an empty held tag is waiting for its target to settle it ([`note_empty_held_tag`]).
1035pub fn empty_held_tags_pending() -> bool { EMPTY_HELD_TAGS.get() > 0 }
1036
1037/// One empty held tag ([`note_empty_held_tag`]) was removed.
1038pub fn take_empty_held_tag() { EMPTY_HELD_TAGS.set(EMPTY_HELD_TAGS.get().saturating_sub(1)); }
1039
1040/// The document is built: every empty held tag is settled ([`note_empty_held_tag`]).
1041pub fn settled_empty_held_tags() { EMPTY_HELD_TAGS.set(0); }
1042
1043/// initialize the logger at a given STDERR verbosity `level`
1044///
1045/// `level` is the **console** verbosity (`--quiet` ⇒ `Error`, default ⇒ `Info`,
1046/// `--verbose` ⇒ `Debug`, which also admits un-featured `Debug` records; a `--debug`
1047/// feature raises only the `max_level` floor, [`crate::common::error::enable_debug_feature`]). Perl decouples this from the log-file floor:
1048/// the `.latexml.log` keeps a minimum of `Info` regardless of `--quiet`, while
1049/// STDERR follows `level` (`Common/Error.pm` `_printline`; issue #763). So the
1050/// global `log` `max_level` is set to the MORE verbose of `level` and `Info` (the
1051/// floor), admitting to `LatexmlLogger::log` everything the log needs; the STDERR
1052/// echo is then gated separately on the `STDERR_LEVEL` atomic.
1053///
1054/// Returns the underlying `SetLoggerError` if another `log` global logger
1055/// is already installed (e.g. an embedder set up `tracing-log` first).
1056/// Callers can decide whether to ignore that — the in-process `bind_log` /
1057/// `flush_log` buffers are independent of the `log` crate sink and keep
1058/// working either way.
1059pub fn init(level: LevelFilter) -> Result<(), SetLoggerError> {
1060  // Global config (STDERR gate + log-file floor) is set unconditionally — it must
1061  // reflect the requested verbosity even if the logger was already installed (a
1062  // second `init` in-process returns `Err` from `set_logger`, which callers `.ok()`).
1063  STDERR_LEVEL.store(level as usize, Ordering::Relaxed);
1064  DEBUG_ALL.store(level >= LevelFilter::Debug, Ordering::Relaxed);
1065  let floor = if crate::common::error::any_debug_feature_enabled() {
1066    LevelFilter::Debug
1067  } else {
1068    LevelFilter::Info
1069  };
1070  log::set_max_level(level.max(floor));
1071  log::set_logger(&LOGGER)
1072}
1073
1074#[cfg(test)]
1075mod tests {
1076  use super::*;
1077
1078  /// A conversion's deferred diagnostics die with it: a persistent worker (cortex_worker) re-initializes the report
1079  /// per paper (`initialize_report`), so a paper that stopped before `finish_document` cannot replay its held errors
1080  /// into the next paper's log and status (60o review, ruling 7e). Each registry is guarded on its own: a stale
1081  /// use, a stale tie and a stale deferred set each meet a next paper reusing id 0 and `LABEL:a`.
1082  #[test]
1083  fn deferred_diagnostics_die_with_the_conversion() {
1084    use crate::common::error::{LogStatus, get_status, initialize_report};
1085    let held = || DeferredDiagnostics {
1086      records:   vec![(
1087        Level::Error,
1088        "Error:undefined:\\stale left by an earlier paper".to_string(),
1089      )],
1090      counts:    crate::common::error::ReportCounts::default(),
1091      missing:   Vec::new(),
1092      undefined: vec![("\\stale".to_string(), 1)],
1093    };
1094    // A stale use: the next paper ties its own held tag to `LABEL:a` but never references it.
1095    initialize_report();
1096    let id = keep_deferred(held());
1097    defer_to_label("LABEL:a", "autoref", id);
1098    note_label_use("LABEL:a", "autoref");
1099    initialize_report();
1100    let id = keep_deferred(held());
1101    defer_to_label("LABEL:a", "autoref", id);
1102    replay_shown_deferred();
1103    assert_eq!(get_status(LogStatus::Error), 0, "stale use");
1104    // A stale tie: the next paper references `LABEL:a`, whose target holds nothing.
1105    initialize_report();
1106    let id = keep_deferred(held());
1107    defer_to_label("LABEL:a", "autoref", id);
1108    initialize_report();
1109    keep_deferred(held());
1110    note_label_use("LABEL:a", "autoref");
1111    replay_shown_deferred();
1112    assert_eq!(get_status(LogStatus::Error), 0, "stale tie");
1113    // A stale deferred set: the next paper ties and references id 0 without holding anything.
1114    initialize_report();
1115    keep_deferred(held());
1116    initialize_report();
1117    defer_to_label("LABEL:a", "autoref", 0);
1118    note_label_use("LABEL:a", "autoref");
1119    replay_shown_deferred();
1120    assert_eq!(get_status(LogStatus::Error), 0, "stale deferred set");
1121  }
1122
1123  /// A hold tells a Fatal raised in its scope (`fatal_raised`), which a caller taking its work back commits rather
1124  /// than discards — Fatal stays Fatal (review rev94a r5, the writer's re-part take-back); an Error alone is no Fatal.
1125  #[test]
1126  fn a_hold_tells_a_fatal_raised_in_it() {
1127    use crate::common::error::{LogStatus, get_status, initialize_report, note_status_from_logger};
1128    initialize_report();
1129    let hold = DiagnosticsHold::begin();
1130    note_status_from_logger(LogStatus::Error);
1131    assert!(!hold.fatal_raised(), "an Error is no Fatal");
1132    note_status_from_logger(LogStatus::Fatal);
1133    assert!(hold.fatal_raised());
1134    hold.commit();
1135    assert_eq!(
1136      get_status(LogStatus::Fatal),
1137      1,
1138      "committed, the Fatal stays"
1139    );
1140    let hold = DiagnosticsHold::begin();
1141    assert!(
1142      !hold.fatal_raised(),
1143      "one raised before the hold is not its own"
1144    );
1145    hold.discard();
1146    initialize_report();
1147  }
1148
1149  #[test]
1150  fn append_note_inline_and_no_blank_lines() {
1151    // note_begin opens a fresh line; note_end / note_progress stay inline.
1152    let mut b = String::new();
1153    append_note(&mut b, "\n(Loading keyval.sty..."); // note_begin (buffer empty: no leading blank)
1154    append_note(&mut b, " )"); // note_end inline
1155    assert_eq!(b, "(Loading keyval.sty... )");
1156    append_note(&mut b, "\n(Loading graphics.sty..."); // mid-line: keep the break
1157    append_note(&mut b, " )");
1158    assert_eq!(b, "(Loading keyval.sty... )\n(Loading graphics.sty... )");
1159    // page markers chain inline
1160    append_note(&mut b, "\n410 formulae ...");
1161    append_note(&mut b, "[1]");
1162    append_note(&mut b, "[2]");
1163    assert!(b.ends_with("410 formulae ...[1][2]"));
1164    // a leading '\n' note after a buffer already at line-start collapses (no blank line)
1165    let mut c = String::from("Info:foo\n");
1166    append_note(&mut c, "\n(Building...");
1167    assert_eq!(c, "Info:foo\n(Building...");
1168  }
1169
1170  /// The lossless-tally contract (user directive 2026-08-02): every printed
1171  /// diagnostic record counts exactly once, whether it came from a counting
1172  /// macro (raise-time count, logger skips) or a raw `log::warn!`-family call
1173  /// (logger counts). Defect this pins: the 131 MB witness logged 12,105
1174  /// `Warning:` lines — 12,103 from the math parser's raw `log_math_warn!` —
1175  /// and the final verdict said "2 warnings".
1176  ///
1177  /// One test, not several: the global logger and the thread-local `REPORT`
1178  /// are both process/thread state, and cargo runs sibling `#[test]`s on
1179  /// separate threads — but a SINGLE test body sees one thread and one
1180  /// deterministic sequence.
1181  #[test]
1182  fn raw_log_records_count_and_macro_records_do_not_double_count() {
1183    use crate::common::error::{
1184      LogStatus, get_status, initialize_report, macro_diag_guard, note_status,
1185      note_status_from_logger,
1186    };
1187    // Another test may have installed the logger already; counting rides
1188    // note_status_from_logger either way, so drive it exactly as
1189    // `LatexmlLogger::log` does rather than through the global sink.
1190    initialize_report();
1191
1192    // Raw record: the logger's tally path counts it.
1193    note_status_from_logger(LogStatus::Warning);
1194    assert_eq!(get_status(LogStatus::Warning), 1, "raw warning must count");
1195
1196    // Macro-emitted record: raise-time count happens under the guard, and
1197    // the logger's observation of the same record must be a no-op.
1198    {
1199      let _g = macro_diag_guard();
1200      note_status(LogStatus::Warning, None); // what the macro does
1201      note_status_from_logger(LogStatus::Warning); // what the logger then sees
1202    }
1203    assert_eq!(
1204      get_status(LogStatus::Warning),
1205      2,
1206      "a macro warning counts once, not twice"
1207    );
1208
1209    // Nested guards (Error! escalating into Fatal!) keep the marker set.
1210    {
1211      let _outer = macro_diag_guard();
1212      {
1213        let _inner = macro_diag_guard();
1214      }
1215      note_status_from_logger(LogStatus::Error);
1216    }
1217    assert_eq!(
1218      get_status(LogStatus::Error),
1219      0,
1220      "the logger stays muted for the whole macro emission, even after a \
1221       nested guard drops"
1222    );
1223
1224    // Raw error and a raw Fatal-target record (log_fatal's shape when some
1225    // future caller bypasses it): the error counts, the fatal latches.
1226    note_status_from_logger(LogStatus::Error);
1227    note_status_from_logger(LogStatus::Fatal);
1228    assert_eq!(get_status(LogStatus::Error), 1);
1229    assert_eq!(get_status(LogStatus::Fatal), 1, "raw fatal latches sticky");
1230    initialize_report();
1231  }
1232
1233  /// Suppression semantics (user decision 2026-08-03): Debug/Info/Warning
1234  /// records are muted under suppression, but Error and Fatal EMIT
1235  /// UNCONDITIONALLY — cortex-class frameworks aggregate success rates from
1236  /// `Error:`/`Fatal:` lines, and a suppressed error would vanish from that
1237  /// measurement while still counting locally. Counts accrue either way.
1238  #[test]
1239  fn suppression_never_mutes_error_or_fatal() {
1240    use crate::common::error::{
1241      LogStatus, emit_record, get_status, initialize_report, set_suppress_log_output,
1242    };
1243    initialize_report();
1244    let _ = log::set_logger(&LOGGER); // ok if another test installed it
1245    log::set_max_level(LevelFilter::Warn);
1246    let prev = set_suppress_log_output(true);
1247
1248    bind_log();
1249    emit_record(LogStatus::Warning, "quiet:warn", "muted warning");
1250    emit_record(LogStatus::Error, "loud:error", "unmutable error");
1251    emit_record(LogStatus::Fatal, "Fatal:loud:fatal", "unmutable fatal");
1252    let captured = flush_log();
1253
1254    set_suppress_log_output(prev);
1255    assert!(
1256      !captured.contains("muted warning"),
1257      "suppression must mute Warning records, captured:\n{captured}"
1258    );
1259    assert!(
1260      captured.contains("Error:loud:error unmutable error"),
1261      "Error must emit under suppression, captured:\n{captured}"
1262    );
1263    // (Fatal targets carry their own trailing space, so the formatter's
1264    // separator makes it two — match the pieces, not the join.)
1265    assert!(
1266      captured.contains("Fatal:loud:fatal") && captured.contains("unmutable fatal"),
1267      "Fatal must emit under suppression, captured:\n{captured}"
1268    );
1269    // Counts accrue regardless of emission.
1270    assert_eq!(get_status(LogStatus::Warning), 1);
1271    assert_eq!(get_status(LogStatus::Error), 1);
1272    assert_eq!(get_status(LogStatus::Fatal), 1);
1273    initialize_report();
1274  }
1275
1276  #[test]
1277  fn strip_ansi_removes_color_codes() {
1278    // ESC [ ... m should vanish; other content preserved.
1279    let red = "\x1b[31mhello\x1b[0m";
1280    assert_eq!(strip_ansi(red), "hello");
1281  }
1282
1283  #[test]
1284  fn strip_ansi_noop_on_plain() {
1285    assert_eq!(strip_ansi("plain text"), "plain text");
1286    assert_eq!(strip_ansi(""), "");
1287  }
1288
1289  #[test]
1290  fn strip_ansi_multiple_sequences() {
1291    let s = "\x1b[31merror:\x1b[0m \x1b[33mwarning\x1b[0m";
1292    assert_eq!(strip_ansi(s), "error: warning");
1293  }
1294
1295  #[test]
1296  fn strip_ansi_preserves_unicode() {
1297    let s = "\x1b[31mαβγ\x1b[0m";
1298    assert_eq!(strip_ansi(s), "αβγ");
1299  }
1300
1301  #[test]
1302  fn strip_ansi_handles_incomplete_escape() {
1303    // Unterminated ESC[ sequence — we should not hang.
1304    // Current impl: scan until 'm' is found. If never found, consumes
1305    // the rest of the input. Document that behavior.
1306    let s = "\x1b[1;31m hello";
1307    // The scan consumes characters until 'm' is found → the 'm' in the
1308    // escape closes, then " hello" remains.
1309    assert_eq!(strip_ansi(s), " hello");
1310  }
1311
1312  #[test]
1313  fn bind_log_and_flush_log_roundtrip() {
1314    // Before bind_log, flush_log returns empty.
1315    // After bind_log, the buffer is active but empty until a log
1316    // message arrives. Since we can't easily exercise the Log impl
1317    // without initializing a global logger, just verify the
1318    // capture-buffer lifecycle primitives.
1319    let before = flush_log();
1320    assert!(before.is_empty(), "no active buffer → empty flush");
1321
1322    bind_log();
1323    let after = flush_log();
1324    assert!(
1325      after.is_empty(),
1326      "empty buffer is still empty after bind/flush with no log traffic"
1327    );
1328  }
1329}