Skip to main content

latexml/
render_workers.rs

1//! Process-parallel page rendering for pass B of the post pipeline
2//! (`docs/archive/STREAMING_POST_DESIGN_2026-07-06.md` §6).
3//!
4//! In-process page threads are blocked twice (`ObjectDB` is `!Send`;
5//! libxslt serializes every transform behind a process-wide lock), so the
6//! chosen shape is **process-level page-range workers**: the parent saves the
7//! completed ObjectDB as a SQLite file, partitions the spilled pages into
8//! contiguous chunks, and re-invokes its own binary once per chunk with
9//! `LATEXML_RENDER_WORKER=<manifest.json>`. Each child attaches the db
10//! readonly (WAL — N readers share one page cache via mmap), runs the SAME
11//! per-page pipeline as the serial driver
12//! (`crate::post::render_spilled_page`), and reports its diagnostic tally
13//! as trailing `Status:` lines on stderr. The parent folds child logs and
14//! counts deterministically, in chunk order, into its own `LOG_BUFFER` /
15//! `REPORT` — so the combined verdict and the persisted `--log` stay lossless
16//! (canvas signal-integrity rule: a child that dies without a status line is
17//! never taken for success).
18//!
19//! Env knob: `LATEXML_RENDER_JOBS` (usize; `1` = the serial path). Unset, the
20//! `latexml_oxide` binary renders a split of `MIN_PAGES_FOR_PARALLEL` pages
21//! or more on min(available cores, `AUTO_JOBS_MAX`) workers; every other
22//! embedder (the library, `cortex_worker`) stays serial. The pages are
23//! byte-identical either way (the parent names every page's images before the render and
24//! the workers look the names up, issue 995); a worker that fails to spawn, cannot set up, or
25//! dies without its status report sends the whole document back to the serial
26//! render at once, stopping the rest of the fleet (an Info; a Warning for a
27//! worker killed by a signal, a crash).
28
29use std::path::{Path, PathBuf};
30
31use latexml_core::{
32  Info, Warn,
33  common::error::{
34    LogStatus, ReportCounts, emit_error, get_status_code, note_status, snapshot_report_counts,
35  },
36  s,
37  util::logger::{CapturedDiagnostics, replay_captured},
38};
39use latexml_post::object_db::{DbAttachOptions, ObjectDB};
40use serde::{Deserialize, Serialize};
41
42/// Fewer spilled pages than this and the db save + child spawn overhead beats
43/// the parallel win — the serial path is taken regardless of the jobs knob.
44pub(crate) const MIN_PAGES_FOR_PARALLEL: usize = 64;
45
46/// The automatic fleet's ceiling: on Nasser's 2,400-problem book (9,713 pages)
47/// 8 workers took the two-invocation run from 115 s to 79 s.
48pub(crate) const AUTO_JOBS_MAX: usize = 8;
49
50/// Set by a binary that serves the worker mode (`LATEXML_RENDER_WORKER`, see
51/// [`worker_main`]): only it may spawn itself as a worker, so only it renders
52/// in parallel without being asked.
53static AUTO_JOBS: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
54
55/// Let an unset `LATEXML_RENDER_JOBS` pick the fleet size (`render_jobs`).
56pub fn enable_auto_jobs() { AUTO_JOBS.store(true, std::sync::atomic::Ordering::Relaxed); }
57
58/// How many page-render worker processes pass B may spawn: an explicit
59/// `LATEXML_RENDER_JOBS` wins (an unparsable or zero value is 1 = serial);
60/// unset, min(available cores, `AUTO_JOBS_MAX`) where [`enable_auto_jobs`]
61/// was called, else 1. Read once per conversion, so no hot-path caching is
62/// needed.
63pub(crate) fn render_jobs() -> usize {
64  match std::env::var("LATEXML_RENDER_JOBS") {
65    Ok(v) => v.parse::<usize>().ok().filter(|&n| n >= 1).unwrap_or(1),
66    Err(_) if AUTO_JOBS.load(std::sync::atomic::Ordering::Relaxed) => {
67      std::thread::available_parallelism()
68        .map_or(1, std::num::NonZeroUsize::get)
69        .min(AUTO_JOBS_MAX)
70    },
71    Err(_) => 1,
72  }
73}
74
75/// The serializable subset of `PostDocumentOptions` a worker needs to
76/// reconstruct the page parse — ALL of its fields, since even `destination`
77/// (later overridden per page) feeds the site-directory fallback inside
78/// `PostDocument::new`.
79#[derive(Serialize, Deserialize, Clone, Default)]
80pub struct PageOpts {
81  pub destination:           Option<String>,
82  pub destination_directory: Option<String>,
83  pub site_directory:        Option<String>,
84  pub source:                Option<String>,
85  pub source_directory:      Option<String>,
86  pub searchpaths:           Option<Vec<String>>,
87  pub validate:              bool,
88  pub nocache:               bool,
89}
90
91impl From<&latexml_post::document::PostDocumentOptions> for PageOpts {
92  fn from(o: &latexml_post::document::PostDocumentOptions) -> Self {
93    PageOpts {
94      destination:           o.destination.clone(),
95      destination_directory: o.destination_directory.clone(),
96      site_directory:        o.site_directory.clone(),
97      source:                o.source.clone(),
98      source_directory:      o.source_directory.clone(),
99      searchpaths:           o.searchpaths.clone(),
100      validate:              o.validate,
101      nocache:               o.nocache,
102    }
103  }
104}
105
106impl From<PageOpts> for latexml_post::document::PostDocumentOptions {
107  fn from(o: PageOpts) -> Self {
108    latexml_post::document::PostDocumentOptions {
109      destination:           o.destination,
110      destination_directory: o.destination_directory,
111      site_directory:        o.site_directory,
112      source:                o.source,
113      source_directory:      o.source_directory,
114      searchpaths:           o.searchpaths,
115      validate:              o.validate,
116      nocache:               o.nocache,
117      cache:                 None,
118    }
119  }
120}
121
122/// One spilled page for a worker to render: the spill path plus the metadata
123/// that does not survive the XML round-trip (mirrors `post::SpilledPage`
124/// minus the parent-only placeholder flags).
125#[derive(Serialize, Deserialize, Clone)]
126pub struct PageJob {
127  pub path:                  PathBuf,
128  pub destination:           Option<String>,
129  pub destination_directory: Option<String>,
130}
131
132/// Everything a page-render worker needs to rebuild the pass-B processor set
133/// exactly as the parent would have, plus its page range. Written as
134/// `render-manifest-{i}.json` beside the saved `LaTeXML-render.db`.
135#[derive(Serialize, Deserialize, Clone, Default)]
136pub struct RenderManifest {
137  /// The saved ObjectDB (SQLite, attached readonly by each worker).
138  pub dbfile:                    PathBuf,
139  pub navigation_toc:            Option<String>,
140  /// Cross-reference URL style as its canonical CLI tag (`UrlStyle::as_cli` /
141  /// `from_cli` round-trip), serialized across the worker manifest.
142  pub url_style:                 String,
143  /// Output file extension CrossRef strips for `--urlstyle` (Perl `extension`).
144  pub out_extension:             String,
145  pub graphicimages:             bool,
146  pub graphics_svg_threshold_kb: u32,
147  pub pmml:                      bool,
148  pub cmml:                      bool,
149  pub keep_xmath:                bool,
150  /// Already-inverted from the CLI's `noinvisibletimes`.
151  pub invisible_times:           bool,
152  pub plane1:                    bool,
153  pub hackplane1:                bool,
154  pub mathtex:                   bool,
155  pub unicodemath:               bool,
156  pub intent_literal:            bool,
157  pub stylesheet:                Option<String>,
158  /// The fully-resolved XSLT parameter map (CSS/JS/LATEXML_VERSION/user
159  /// overrides), captured after the parent computed it.
160  pub xslt_params:               Vec<(String, String)>,
161  pub default_resources:         bool,
162  /// The resolved stylesheet/resource search paths the parent's `XSLT::new`
163  /// received.
164  pub searchpaths:               Vec<String>,
165  /// Run the SVG processor before MathML (the parent's `svg`).
166  pub svg:                       bool,
167  /// Serialize the pages as HTML (Perl `is_html`).
168  pub is_html_out:               bool,
169  pub schemadocs:                bool,
170  /// [`latexml_post::extract::Whatsout`] as its canonical CLI tag
171  /// (`as_cli`/`from_cli` round-trip).
172  pub whatsout:                  String,
173  pub page_opts:                 PageOpts,
174  pub pages:                     Vec<PageJob>,
175  /// This worker's share of the run's memory budget, in KiB (0 = none): its
176  /// watchdog's ceiling, so the fleet stays within `--max-memory`.
177  #[serde(default)]
178  pub max_rss_kb:                u64,
179  /// The parent's STATE values the render reads: a worker is a fresh process, whose STATE
180  /// holds none (MathML's `<mpadded>` widths read `NOMINAL_FONT_SIZE`).
181  #[serde(default)]
182  pub post_values:               latexml_core::PostStateValues,
183  /// The names the parent gave every page's images before the render (`Graphics::plan_names`): (destination
184  /// directory, key, destination, vector render). A worker looks them up, so a page's names never depend on which
185  /// worker renders it (issue 995).
186  #[serde(default)]
187  pub resource_names:            Vec<(String, String, String, Option<String>)>,
188  /// The parent's stderr verbosity (`LevelFilter` name: `ERROR` under `--quiet`, `DEBUG` under `--verbose`). The
189  /// worker logs at it, never below `Info`, so its folded log is the serial render's.
190  #[serde(default)]
191  pub log_level:                 String,
192  /// The parent's read confinement (OXIDIZED_DESIGN_DIVERGENCES #1183): a worker is a fresh process, confined to the
193  /// same roots before it reads anything, so a parallel render refuses what the serial one does.
194  #[serde(default)]
195  pub confinement:               Option<latexml_core::util::pathname::ConfinementSnapshot>,
196}
197
198/// The parent-side result of a parallel render in which workers were actually
199/// spawned (successfully or not — failures are already folded as diagnostics).
200pub(crate) struct ParallelResult {
201  /// The first page's finalized output, read back from its destination file —
202  /// the same content the serial driver would have returned as `main_output`.
203  pub(crate) main_output:    Option<String>,
204  /// Total pages written, summed from the workers' `Status:pages:` lines.
205  pub(crate) pages_rendered: usize,
206  /// A worker's MathML/XSLT step died (`Status:discard:1`): the pages written are removed and
207  /// the render leaves no output (#782).
208  pub(crate) discarded:      bool,
209  /// The pages the workers wrote, folded in chunk order — the serial render's page order. For an
210  /// abandoned fleet, every page it may have written ([`pages_the_fleet_may_have_written`]).
211  pub(crate) written:        Vec<String>,
212  /// A worker failed, so nothing was folded and the document renders serially. A page's Fatal
213  /// there removes `written` too (#782); a fuse or timeout stop keeps only the pages it rewrote.
214  pub(crate) abandoned:      bool,
215}
216
217/// Remove the per-run handoff artifacts (db + WAL sidecars + manifests).
218/// Best-effort: they live in the page-spill tempdir, which is removed wholesale
219/// when the parent drops it, so a failure here only delays the cleanup.
220fn cleanup_handoff(dbfile: &Path, manifests: &[PathBuf]) {
221  let _ = std::fs::remove_file(dbfile);
222  for suffix in ["-wal", "-shm"] {
223    let mut side = dbfile.as_os_str().to_owned();
224    side.push(suffix);
225    let _ = std::fs::remove_file(PathBuf::from(side));
226  }
227  for m in manifests {
228    let _ = std::fs::remove_file(m);
229  }
230}
231
232/// Strip ANSI `ESC[...m` color sequences (same logic as the logger's private
233/// helper). Child stderr is a pipe, so the TTY-gated logger should emit none —
234/// this is belt-and-suspenders for the log fold (signal-integrity rule).
235fn strip_ansi(s: &str) -> String {
236  let mut result = String::with_capacity(s.len());
237  let mut in_escape = false;
238  for c in s.chars() {
239    if in_escape {
240      if c == 'm' {
241        in_escape = false;
242      }
243    } else if c == '\u{1b}' {
244      in_escape = true;
245    } else {
246      result.push(c);
247    }
248  }
249  result
250}
251
252/// A worker's stderr, parsed: the trailing `Status:` lines are consumed into
253/// structured fields and everything else is the log text to forward + fold.
254struct ChildReport {
255  log:          String,
256  counts:       Option<ReportCounts>,
257  status:       Option<usize>,
258  pages:        usize,
259  /// `Status:discard:1`: a MathML/XSLT step died, so no page of the run is kept (#782).
260  discard:      bool,
261  /// `Status:written:<path>`: the pages this worker wrote, the only ones a discard removes.
262  written:      Vec<String>,
263  /// `Status:setup-failed:<why>`: the worker rendered nothing (`print_setup_failure`).
264  setup_failed: Option<String>,
265}
266
267fn parse_child_report(stderr_text: &str) -> ChildReport {
268  let mut log = String::new();
269  let mut counts = None;
270  let mut status = None;
271  let mut pages = 0usize;
272  let mut discard = false;
273  let mut written = Vec::new();
274  let mut setup_failed = None;
275  for line in stderr_text.lines() {
276    if let Some(rest) = line.strip_prefix("Status:counts:") {
277      let mut it = rest.split(',').map(|v| v.trim().parse::<usize>().ok());
278      let (d, i, w, e, f) = (
279        it.next().flatten(),
280        it.next().flatten(),
281        it.next().flatten(),
282        it.next().flatten(),
283        it.next().flatten(),
284      );
285      if let (Some(debug), Some(info), Some(warning), Some(error), Some(fatal)) = (d, i, w, e, f) {
286        counts = Some(ReportCounts {
287          debug,
288          info,
289          warning,
290          error,
291          fatal: fatal > 0,
292        });
293      }
294    } else if let Some(rest) = line.strip_prefix("Status:conversion:") {
295      status = rest.trim().parse::<usize>().ok();
296    } else if let Some(rest) = line.strip_prefix("Status:pages:") {
297      pages = rest.trim().parse::<usize>().unwrap_or(0);
298    } else if let Some(rest) = line.strip_prefix("Status:discard:") {
299      discard = rest.trim() == "1";
300    } else if let Some(path) = line.strip_prefix("Status:written:") {
301      written.push(path.to_string());
302    } else if let Some(why) = line.strip_prefix("Status:setup-failed:") {
303      setup_failed = Some(why.to_string());
304    } else {
305      log.push_str(line);
306      log.push('\n');
307    }
308  }
309  ChildReport {
310    log,
311    counts,
312    status,
313    pages,
314    discard,
315    written,
316    setup_failed,
317  }
318}
319
320/// One spawned (or spawn-failed) worker awaiting its fold.
321enum Pending {
322  /// The drain thread owns the child and returns its full `Output`; the pid
323  /// is kept so a parent-side timeout can kill the fleet. Only read on Unix
324  /// (`libc::kill` in the breach path below); the equivalent Windows fleet-kill
325  /// (OpenProcess + TerminateProcess) is not wired yet, so the pid is dead on
326  /// non-unix — scope the `dead_code` allow there rather than workspace-wide.
327  Spawned(
328    std::thread::JoinHandle<std::io::Result<std::process::Output>>,
329    #[cfg_attr(not(unix), allow(dead_code))] u32,
330  ),
331  Failed(String),
332}
333
334/// A joined worker: its parsed report and exit status, or why it could not be waited for.
335type Joined = Result<(ChildReport, std::process::ExitStatus), String>;
336
337fn join_worker(p: Pending) -> Joined {
338  match p {
339    Pending::Failed(e) => Err(e),
340    Pending::Spawned(handle, _) => match handle.join() {
341      Err(_) => Err("drain thread panicked".to_string()),
342      Ok(Err(e)) => Err(format!("wait failed: {e}")),
343      Ok(Ok(output)) => {
344        let stderr_text = strip_ansi(&String::from_utf8_lossy(&output.stderr));
345        Ok((parse_child_report(&stderr_text), output.status))
346      },
347    },
348  }
349}
350
351/// Why a worker sends the document to the serial render.
352struct WorkerFailure {
353  why:       String,
354  /// Ended by a signal (no exit code): a crash, not one of the worker's own exits.
355  by_signal: bool,
356}
357
358/// The failure of a joined worker that did not render its range, `None` for one that reported. A death names its
359/// signal and ends with the worker's last stderr lines (its `Fatal:oom:rss`, a panic), which are not folded.
360fn worker_failure(r: &Joined) -> Option<WorkerFailure> {
361  let (why, by_signal) = match r {
362    Err(e) => (e.clone(), false),
363    Ok((report, _)) if let Some(why) = &report.setup_failed => {
364      (format!("setup failed: {why}"), false)
365    },
366    Ok((report, status)) if report.status.is_none() => {
367      let by_signal = status.code().is_none();
368      let why = format!(
369        "{} without a Status:conversion line",
370        describe_death(status)
371      );
372      match stderr_tail(&report.log) {
373        Some(tail) => (format!("{why}; its stderr ended: {tail}"), by_signal),
374        None => (why, by_signal),
375      }
376    },
377    Ok(_) => return None,
378  };
379  Some(WorkerFailure { why, by_signal })
380}
381
382/// The last three non-blank lines of a failed worker's stderr, on one line (each cut at 300 bytes), so a line the
383/// worker began with `Fatal:` stays inside the parent's message.
384fn stderr_tail(log: &str) -> Option<String> {
385  let mut lines: Vec<&str> = log
386    .lines()
387    .map(str::trim)
388    .filter(|l| !l.is_empty())
389    .rev()
390    .take(3)
391    .map(|l| &l[..l.floor_char_boundary(300)])
392    .collect();
393  lines.reverse();
394  (!lines.is_empty()).then(|| lines.join(" | "))
395}
396
397/// How a worker ended: `exited (code 137)`, or `killed by SIGSEGV (signal 11)`.
398fn describe_death(status: &std::process::ExitStatus) -> String {
399  match status.code() {
400    Some(code) => format!("exited (code {code})"),
401    None => format!("killed by {}", describe_signal(status)),
402  }
403}
404
405/// The signal by name and number (`SIGSEGV (signal 11)`), and whether it dumped core.
406#[cfg(unix)]
407fn describe_signal(status: &std::process::ExitStatus) -> String {
408  use std::os::unix::process::ExitStatusExt;
409  let Some(n) = status.signal() else {
410    return "a signal".to_string();
411  };
412  let name = match n {
413    libc::SIGSEGV => "SIGSEGV",
414    libc::SIGBUS => "SIGBUS",
415    libc::SIGABRT => "SIGABRT",
416    libc::SIGILL => "SIGILL",
417    libc::SIGFPE => "SIGFPE",
418    libc::SIGKILL => "SIGKILL",
419    libc::SIGTERM => "SIGTERM",
420    libc::SIGINT => "SIGINT",
421    libc::SIGHUP => "SIGHUP",
422    libc::SIGQUIT => "SIGQUIT",
423    libc::SIGPIPE => "SIGPIPE",
424    libc::SIGTRAP => "SIGTRAP",
425    libc::SIGSYS => "SIGSYS",
426    libc::SIGXCPU => "SIGXCPU",
427    libc::SIGXFSZ => "SIGXFSZ",
428    _ => return format!("signal {n}"),
429  };
430  let core = if status.core_dumped() {
431    ", core dumped"
432  } else {
433    ""
434  };
435  format!("{name} (signal {n}{core})")
436}
437
438#[cfg(not(unix))]
439fn describe_signal(_: &std::process::ExitStatus) -> String { "a signal".to_string() }
440
441/// A worker's expected peak resident set: it decodes the whole db at attach, and its pages add
442/// little. Measured VmHWM, Nasser's book: 95 MB on the 600-problem part (11 MB db), 260 MB on the
443/// 2,400-problem part (45 MB db), i.e. ~42 MB + 4.85 x db; this adds a quarter's margin. The old
444/// `max(3 x db, 256 MB)` sized k2400 workers below their start, and one died (exit 137).
445fn worker_estimate_bytes(db_bytes: u64) -> u64 {
446  db_bytes.saturating_mul(6).saturating_add(64 << 20)
447}
448
449/// Pure fleet-sizing calculation for [`parallel_render`].
450///
451/// `soft_cap` is the cooperative RSS fuse (`stomach::resolve_rss_cap`, already
452/// 3/4 of `--max-memory` via `soft_cap_from_ceiling`) — it must NOT be scaled
453/// by 3/4 a second time. Returns `(jobs, affordable, budget, per_worker, max_rss_kb)`.
454fn compute_fleet_budget(
455  available_mem: Option<u64>,
456  soft_cap: Option<u64>,
457  parent_rss_bytes: u64,
458  db_bytes: u64,
459  requested_jobs: usize,
460  total_pages: usize,
461) -> (usize, usize, u64, u64, u64) {
462  let per_worker = worker_estimate_bytes(db_bytes);
463  let mut budget = available_mem.unwrap_or(u64::MAX);
464  if let Some(fuse) = soft_cap {
465    budget = budget.min(fuse.saturating_sub(parent_rss_bytes));
466  }
467  let affordable = (budget / per_worker) as usize;
468  let jobs = requested_jobs.min(total_pages).min(affordable);
469  let max_rss_kb = if budget != u64::MAX && jobs >= 2 {
470    budget / jobs as u64 / 1024
471  } else {
472    0
473  };
474  (jobs, affordable, budget, per_worker, max_rss_kb)
475}
476
477/// The pages an abandoned fleet may have written, for the serial render to remove if it ends in a
478/// Fatal (#782): a worker that reported (or could not set up) names its pages, and one that died
479/// before its `Status:written:` lines may have written any page of its range. The serial render
480/// rewrites them; one that stops (the fuse, the timeout, a page's Error) removes those it did not.
481fn pages_the_fleet_may_have_written(joined: &[Joined], ranges: &[Vec<String>]) -> Vec<String> {
482  joined
483    .iter()
484    .zip(ranges)
485    .flat_map(|(r, range)| match r {
486      Ok((report, _)) if report.status.is_some() || report.setup_failed.is_some() => {
487        report.written.clone()
488      },
489      Err(e) if e.starts_with("worker spawn failed") => Vec::new(),
490      _ => range.clone(),
491    })
492    .collect()
493}
494
495/// Spawn `jobs` page-range workers over `pages` and fold their results.
496///
497/// Returns `None` when setup failed or the fleet was declined, and an `abandoned` result when a
498/// worker failed to spawn, could not set up, or died without its status report (an Info, a Warning
499/// when a signal killed it) — the caller falls
500/// back to the serial render, which is still fully correct since the workers
501/// keep the spilled pages. Only a timeout breach folds the killed workers as an
502/// Error + FATAL status (fail toward flagging, never silent success).
503pub(crate) fn parallel_render(
504  mut manifest: RenderManifest,
505  pages: Vec<PageJob>,
506  jobs: usize,
507  spill_dir: &Path,
508  db: &ObjectDB,
509) -> Option<ParallelResult> {
510  let total_pages = pages.len();
511  let exe = match std::env::current_exe() {
512    Ok(e) => e,
513    Err(e) => {
514      Info!(
515        "post",
516        "parallel-render",
517        s!("parallel render disabled (current_exe: {})", e)
518      );
519      return None;
520    },
521  };
522  let dbfile = spill_dir.join("LaTeXML-render.db");
523  if let Err(e) = db.save_as(&dbfile) {
524    Info!(
525      "post",
526      "parallel-render",
527      s!("parallel render disabled (db save: {})", e)
528    );
529    return None;
530  }
531  manifest.dbfile = dbfile.clone();
532
533  // Clamp the fleet to ACTUAL headroom (witness OOM 2026-08-03: a joint run
534  // carries ~15 GB of core residual into post, and 8 workers each
535  // eager-loading a 1.82M-object db blew a 30 GB cgroup at spawn — the
536  // post-only measurement survived only because its parent was fresh). Free
537  // what the allocators will give back first, then estimate each worker at
538  // 64 MiB + 6x the on-disk db (`worker_estimate_bytes`), and size the
539  // fleet from the smaller of MemAvailable and the
540  // distance to this run's own memory fuse. Degrade to fewer workers — or
541  // decline to engage — rather than let the kernel choose a victim.
542  crate::heap_trim::release_free_heap();
543  let db_bytes = std::fs::metadata(&dbfile).map(|m| m.len()).unwrap_or(0);
544  let parent_rss_bytes = latexml_core::watchdog::process_rss_kb()
545    .unwrap_or(0)
546    .saturating_mul(1024);
547  let (jobs, affordable, budget, per_worker, max_rss_kb) = compute_fleet_budget(
548    latexml_core::watchdog::available_memory_bytes(),
549    latexml_core::stomach::resolve_rss_cap(),
550    parent_rss_bytes,
551    db_bytes,
552    jobs,
553    total_pages,
554  );
555  // Each worker's watchdog holds it to its share, so parent + fleet stay
556  // under the fuse; one that outgrows it dies and the document renders serially.
557  manifest.max_rss_kb = max_rss_kb;
558  if jobs < 2 {
559    Info!(
560      "post",
561      "parallel-render",
562      s!(
563        "parallel render declined: headroom {} MB affords {} worker(s) at ~{} MB each — staying serial",
564        budget / (1024 * 1024),
565        affordable,
566        per_worker / (1024 * 1024)
567      )
568    );
569    cleanup_handoff(&dbfile, &[]);
570    return None;
571  }
572
573  // Contiguous chunks preserve page order: worker 0 owns the first pages, so
574  // the fold below (and the first page's main-output read) is deterministic.
575  let chunk_size = total_pages.div_ceil(jobs);
576  let first_destination = pages.first().and_then(|p| p.destination.clone());
577  let mut manifest_paths: Vec<PathBuf> = Vec::with_capacity(jobs);
578  let mut ranges: Vec<Vec<String>> = Vec::with_capacity(jobs);
579  for (i, chunk) in pages.chunks(chunk_size).enumerate() {
580    ranges.push(chunk.iter().filter_map(|p| p.destination.clone()).collect());
581    let mut m = manifest.clone();
582    m.pages = chunk.to_vec();
583    let mpath = spill_dir.join(format!("render-manifest-{i}.json"));
584    let write_result = serde_json::to_string(&m)
585      .map_err(|e| e.to_string())
586      .and_then(|json| std::fs::write(&mpath, json).map_err(|e| e.to_string()));
587    if let Err(e) = write_result {
588      Info!(
589        "post",
590        "parallel-render",
591        s!("parallel render disabled (manifest write: {})", e)
592      );
593      cleanup_handoff(&dbfile, &manifest_paths);
594      return None;
595    }
596    manifest_paths.push(mpath);
597  }
598
599  // Parent-side deadline check before committing to the spawn (the workers
600  // carry no deadline of their own; the parent polls between waits below and
601  // kills the fleet on a breach).
602  if let Err(e) = latexml_core::stomach::check_timeout_now() {
603    e.log_fatal();
604    cleanup_handoff(&dbfile, &manifest_paths);
605    return Some(ParallelResult {
606      main_output:    None,
607      pages_rendered: 0,
608      discarded:      false,
609      written:        Vec::new(),
610      abandoned:      false,
611    });
612  }
613
614  // The engagement marker (also what the parity test asserts on — without it
615  // a silently-ignored jobs knob would let the test pass vacuously serial).
616  Info!(
617    "post",
618    "parallel-render",
619    s!(
620      "parallel page render engaged: {} worker(s) over {} pages",
621      manifest_paths.len(),
622      total_pages
623    )
624  );
625
626  let mut pending: Vec<Pending> = Vec::with_capacity(manifest_paths.len());
627  for mpath in &manifest_paths {
628    let spawned = std::process::Command::new(&exe)
629      .env("LATEXML_RENDER_WORKER", mpath)
630      .stdin(std::process::Stdio::null())
631      .stdout(std::process::Stdio::piped())
632      .stderr(std::process::Stdio::piped())
633      .spawn();
634    match spawned {
635      Ok(child) => {
636        let pid = child.id();
637        // Register with the watchdog so timeout/OOM exits never orphan the
638        // worker pool across Unix and Windows. Moved into the drain closure so
639        // each worker's PID unregisters immediately when `wait_with_output`
640        // reaps it (never outliving an early-finishing worker).
641        let kill_guard = latexml_core::watchdog::kill_pid_on_exit(pid, false);
642        // Each child gets a drain thread calling `wait_with_output` — piped
643        // stderr MUST be consumed while the parent polls, or a chatty child
644        // blocks on a full pipe and the poll below never sees it exit.
645        let handle = std::thread::Builder::new()
646          .name(format!("render-worker-drain-{pid}"))
647          .spawn(move || {
648            let _kill_guard = kill_guard;
649            child.wait_with_output()
650          });
651        match handle {
652          Ok(h) => pending.push(Pending::Spawned(h, pid)),
653          Err(e) => {
654            // `child` and `kill_guard` were moved into the closure and dropped
655            // on spawn failure, unregistering the PID; kill it explicitly so we
656            // never leak a live worker.
657            latexml_core::watchdog::kill_pid(pid, false);
658            pending.push(Pending::Failed(format!("drain thread spawn failed: {e}")));
659          },
660        }
661      },
662      Err(e) => pending.push(Pending::Failed(format!("worker spawn failed: {e}"))),
663    }
664  }
665
666  // Poll (rather than block) so the parent's cooperative timeout keeps
667  // running between waits, and join each worker as it ends: the first one
668  // that fails sends the document to the serial render at once, and a breach
669  // ends the run, so either way the rest of the fleet is killed rather than
670  // waited for (Nasser k2400: a worker's death was acted on only after its
671  // seven siblings finished).
672  let mut slots: Vec<Option<Pending>> = pending.into_iter().map(Some).collect();
673  let mut joined: Vec<Option<Joined>> = slots.iter().map(|_| None).collect();
674  let failed: Option<(usize, WorkerFailure)> = loop {
675    for (slot, out) in slots.iter_mut().zip(joined.iter_mut()) {
676      if slot
677        .as_ref()
678        .is_some_and(|p| !matches!(p, Pending::Spawned(h, _) if !h.is_finished()))
679      {
680        *out = slot.take().map(join_worker);
681      }
682    }
683    let failure = joined
684      .iter()
685      .enumerate()
686      .find_map(|(i, r)| r.as_ref().and_then(worker_failure).map(|f| (i, f)));
687    if failure.is_some() || slots.iter().all(Option::is_none) {
688      break failure;
689    }
690    if let Err(e) = latexml_core::stomach::check_timeout_now() {
691      e.log_fatal();
692      break None;
693    }
694    std::thread::sleep(std::time::Duration::from_millis(100));
695  };
696  for slot in slots.iter().flatten() {
697    if let Pending::Spawned(h, pid) = slot
698      && !h.is_finished()
699    {
700      latexml_core::watchdog::kill_pid(*pid, false);
701    }
702  }
703  for (slot, out) in slots.into_iter().zip(joined.iter_mut()) {
704    if let Some(p) = slot {
705      *out = Some(join_worker(p));
706    }
707  }
708
709  // Every worker is joined before any child log is folded: one that could not
710  // run, or died without its status report (a crash, its memory share
711  // exceeded, a broken pipe), sends the whole range to the serial render, so
712  // nothing is counted twice. A worker's own diagnostics, Fatal included, are
713  // the document's and fold as they are. After a timeout breach the killed
714  // workers fold as failures (the Fatal is already logged).
715  let mut joined: Vec<Joined> = joined
716    .into_iter()
717    .map(|r| r.unwrap_or_else(|| Err("not joined".to_string())))
718    .collect();
719  if let Some((i, failure)) = failed {
720    let message = s!(
721      "parallel render abandoned (worker {}: {}) — rendering serially",
722      i,
723      failure.why
724    );
725    // A worker killed by a signal crashed (or the kernel's OOM killer took
726    // it): the serial render recovers the pages, but the crash is counted. Its
727    // own watchdog's memory exit and a setup failure are expected outcomes.
728    if failure.by_signal {
729      Warn!("post", "parallel-render", message);
730    } else {
731      Info!("post", "parallel-render", message);
732    }
733    cleanup_handoff(&dbfile, &manifest_paths);
734    return Some(ParallelResult {
735      main_output:    None,
736      pages_rendered: 0,
737      discarded:      false,
738      written:        pages_the_fleet_may_have_written(&joined, &ranges),
739      abandoned:      true,
740    });
741  }
742
743  // Fold IN CHUNK ORDER (deterministic log/tally, mirroring the graphics
744  // worker fold): forward each child's stderr, replay its log + counts into
745  // the parent LOG_BUFFER/REPORT, and flag anything that did not report.
746  let mut pages_rendered = 0usize;
747  let mut discard = false;
748  let mut written: Vec<String> = Vec::new();
749  for (i, r) in joined.drain(..).enumerate() {
750    match r {
751      Err(e) => {
752        emit_error("post", "render_worker", &format!("worker {i}: {e}"));
753        note_status(LogStatus::Fatal, None);
754      },
755      Ok((report, exit_status)) => {
756        if !report.log.is_empty() {
757          // The child's stderr was piped, so nothing reached the live
758          // stderr yet — forward it now, then fold the same text + counts
759          // into the captured log and the REPORT tally.
760          eprint!("{}", stderr_share(&report.log));
761        }
762        replay_captured(CapturedDiagnostics {
763          log:    report.log,
764          counts: report.counts.unwrap_or_default(),
765        });
766        pages_rendered += report.pages;
767        discard |= report.discard;
768        written.extend(report.written);
769        match report.status {
770          None => {
771            // No status line = the child died before its final report (or
772            // never got that far). Fail toward flagging: this chunk's pages
773            // cannot be assumed rendered.
774            emit_error(
775              "post",
776              "render_worker",
777              &format!(
778                "worker {i} {} without a Status:conversion line",
779                describe_death(&exit_status)
780              ),
781            );
782            note_status(LogStatus::Fatal, None);
783          },
784          Some(s) if s >= 3 && !report.counts.is_some_and(|c| c.fatal) => {
785            // The child declared fatal but its counts line didn't carry the
786            // flag (or was missing) — max-fold the declared status anyway.
787            note_status(LogStatus::Fatal, None);
788          },
789          Some(_) => {},
790        }
791      },
792    }
793  }
794
795  // The serial driver returns the first page's finalized output as
796  // `main_output`; here that page is already on disk (written by worker 0),
797  // so read it back. A missing/unreadable file leaves `None` and the caller's
798  // fallback applies — the diagnostics above already flagged the failure.
799  if discard {
800    // Only this run's pages: a stale page of an earlier run in the destination stays.
801    crate::post::remove_pages(&written);
802    cleanup_handoff(&dbfile, &manifest_paths);
803    return Some(ParallelResult {
804      main_output:    None,
805      pages_rendered: 0,
806      discarded:      true,
807      written:        Vec::new(),
808      abandoned:      false,
809    });
810  }
811  let main_output = first_destination.and_then(|d| std::fs::read_to_string(&d).ok());
812  cleanup_handoff(&dbfile, &manifest_paths);
813  Some(ParallelResult {
814    main_output,
815    pages_rendered,
816    discarded: false,
817    written,
818    abandoned: false,
819  })
820}
821
822/// Print the worker's canonical trailing status report (the LAST lines on
823/// stderr): `Status:pages:`, `Status:written:` per page, then `Status:counts:`, then
824/// `Status:conversion:` — the parent parses them positionally-independently by prefix. Returns
825/// the process exit code (0 below fatal, 1 at fatal).
826fn print_status_report(written: &[String], discard: bool) -> i32 {
827  let c = snapshot_report_counts();
828  let status = get_status_code();
829  eprintln!("Status:pages:{}", written.len());
830  for path in written {
831    eprintln!("Status:written:{path}");
832  }
833  if discard {
834    eprintln!("Status:discard:1");
835  }
836  eprintln!(
837    "Status:counts:{},{},{},{},{}",
838    c.debug,
839    c.info,
840    c.warning,
841    c.error,
842    usize::from(c.fatal)
843  );
844  eprintln!("Status:conversion:{status}");
845  if status < 3 { 0 } else { 1 }
846}
847
848/// The lines of a worker's log the parent's stderr shows: its records at the parent's verbosity (`--quiet` hides
849/// `Info` and `Warning`, only `--verbose` shows `Debug`), each with its continuation lines; `Error`/`Fatal` always,
850/// as the logger prints them (OXIDIZED_DESIGN_DIVERGENCES #1158).
851fn stderr_share(log: &str) -> String {
852  stderr_share_at(log, latexml_core::util::logger::stderr_admits)
853}
854
855/// [`stderr_share`] at the verbosity `admits`. A line that opens no record is either a progress note (an `Info`)
856/// or an unindented continuation of a multi-line message, which the log cannot tell apart: it is shown when either
857/// would be, so a shown record keeps every line (a note after it may show under `--quiet`).
858fn stderr_share_at(log: &str, admits: impl Fn(log::Level) -> bool) -> String {
859  use log::Level;
860  let mut shown = String::with_capacity(log.len());
861  let mut admitted = true;
862  let mut record_admitted = false;
863  for line in log.split_inclusive('\n') {
864    let level = [
865      ("Error:", Level::Error),
866      ("Fatal:", Level::Error),
867      ("Warning:", Level::Warn),
868      ("Info:", Level::Info),
869      ("Debug:", Level::Debug),
870      ("Trace:", Level::Trace),
871    ]
872    .into_iter()
873    .find_map(|(head, level)| line.starts_with(head).then_some(level));
874    match level {
875      Some(level) => {
876        admitted = level == Level::Error || admits(level);
877        record_admitted = admitted;
878      },
879      // An indented line (`\tat …`, a blank line) goes with the line before it.
880      None if line.starts_with(char::is_whitespace) => {},
881      None => admitted = record_admitted || admits(Level::Info),
882    }
883    if admitted {
884      shown.push_str(line);
885    }
886  }
887  shown
888}
889
890/// A worker that could not set up (its manifest or db unreadable) has rendered
891/// nothing and its failure is not the document's: no status report, so the
892/// parent renders serially, and this line names why (an Info there).
893fn print_setup_failure(why: &str) -> i32 {
894  eprintln!("Status:setup-failed:{}", why.replace('\n', " "));
895  1
896}
897
898/// Entry point of the hidden worker mode (`LATEXML_RENDER_WORKER=<manifest>`),
899/// dispatched from the binary's `main` before any CLI handling. Renders the
900/// manifest's page range and ends its stderr with the status report, or with
901/// the setup-failure line when it could not start, so the parent never
902/// mistakes a broken worker for a clean one.
903pub fn worker_main(manifest_path: &str) -> i32 {
904  latexml_core::util::logger::init(log::LevelFilter::Info).ok();
905  let manifest: RenderManifest = match std::fs::read_to_string(manifest_path)
906    .map_err(|e| e.to_string())
907    .and_then(|s| serde_json::from_str(&s).map_err(|e| e.to_string()))
908  {
909    Ok(m) => m,
910    Err(e) => {
911      return print_setup_failure(&format!(
912        "cannot read the render manifest {manifest_path}: {e}"
913      ));
914    },
915  };
916  // Mirror `api.rs::on_worker`: a 256 MiB-stack thread for deeply nested
917  // math, and an explicit engine reset before the thread exits (the
918  // per-thread roots do not Drop on a bare thread exit).
919  #[cfg(feature = "test-utils")]
920  let first_worker = manifest_path.ends_with("render-manifest-0.json");
921  std::thread::Builder::new()
922    .stack_size(256 * 1024 * 1024)
923    .spawn(move || {
924      #[cfg(feature = "test-utils")]
925      match test_fault().as_deref() {
926        None | Some("attach" | "unreported" | "rss") => {},
927        Some("signal") if first_worker => {
928          latexml_core::watchdog::kill_pid(std::process::id(), false)
929        },
930        Some("signal") => std::thread::sleep(std::time::Duration::from_secs(600)),
931        Some(_) => latexml_core::watchdog::exit_now(70),
932      }
933      // Hold this worker to its share of the run's memory budget, and align
934      // `heap_trim::step_kb()` with that ceiling instead of the 4.5 GB default.
935      // The share is the worker's HARD (watchdog) ceiling, where the parent's cap
936      // is the soft 3/4 fuse: a `check_timeout` added to the page loop must not
937      // read it as the cooperative fuse.
938      if manifest.max_rss_kb > 0 {
939        latexml_core::stomach::set_memory_cap(Some(manifest.max_rss_kb.saturating_mul(1024)));
940      }
941      manifest.post_values.restore();
942      let _confined = manifest
943        .confinement
944        .clone()
945        .map(latexml_core::util::pathname::resume);
946      let level = manifest.log_level.parse().unwrap_or(log::LevelFilter::Info);
947      latexml_core::util::logger::init(level.max(log::LevelFilter::Info)).ok();
948      let watchdog_kb = manifest.max_rss_kb;
949      #[cfg(feature = "test-utils")]
950      let watchdog_kb = if test_fault().as_deref() == Some("rss") {
951        1
952      } else {
953        watchdog_kb
954      };
955      let _watchdog = (watchdog_kb > 0)
956        .then(|| latexml_core::watchdog::Watchdog::with_limits(0, watchdog_kb, None));
957      let code = match render_manifest_pages(manifest) {
958        #[cfg(feature = "test-utils")]
959        Ok(_) if test_fault().as_deref() == Some("unreported") => {
960          latexml_core::watchdog::exit_now(70)
961        },
962        Ok((written, discard)) => print_status_report(&written, discard),
963        Err(why) => print_setup_failure(&why),
964      };
965      latexml_core::reset_thread_engine();
966      code
967    })
968    .expect("spawn render worker thread")
969    .join()
970    .expect("render worker thread panicked")
971}
972
973/// Test hook `LATEXML_RENDER_WORKER_TEST_ABORT` (guard: 120_midscale_streaming):
974/// `attach` fails the worker's db attach; `signal` SIGKILLs worker 0 (a crash)
975/// and holds its siblings for ten minutes, unless the parent stops them;
976/// `unreported` renders the range and exits before the status report, as a
977/// worker killed late would; `rss` holds the worker's watchdog to 1 KB, so it
978/// exits 137 at its first poll, while the render attaches; any other value
979/// exits the worker before it renders.
980#[cfg(feature = "test-utils")]
981fn test_fault() -> Option<String> { std::env::var("LATEXML_RENDER_WORKER_TEST_ABORT").ok() }
982
983/// Rebuild the pass-B processor set from the manifest — the EXACT construction
984/// the parent's `run_post_processing_inner` performs (same MathML
985/// primary/secondary parallel model, same XSLT wiring, same error paths) —
986/// then render every page in the manifest's range through the shared
987/// [`crate::post::render_spilled_page`]. Returns the pages written, and whether a Fatal discards them;
988/// `Err` = the worker could not set up (see `print_setup_failure`).
989fn render_manifest_pages(m: RenderManifest) -> Result<(Vec<String>, bool), String> {
990  use latexml_post::{
991    crossref::{CrossRef, UrlStyle},
992    processor::Processor,
993  };
994  #[cfg(feature = "test-utils")]
995  let m = RenderManifest {
996    dbfile: if test_fault().as_deref() == Some("attach") {
997      m.dbfile.with_extension("missing")
998    } else {
999      m.dbfile
1000    },
1001    ..m
1002  };
1003  let db = match ObjectDB::attach(&m.dbfile, DbAttachOptions {
1004    readonly: true,
1005    clean:    false,
1006  }) {
1007    Ok(db) => db,
1008    Err(e) => {
1009      return Err(format!(
1010        "cannot attach the render db {}: {e}",
1011        m.dbfile.display()
1012      ));
1013    },
1014  };
1015  let url_style = UrlStyle::from_cli(&m.url_style).unwrap_or(UrlStyle::File);
1016  let mut crossref = CrossRef::new(db, url_style, true);
1017  crossref.set_extension(&m.out_extension);
1018  if let Some(navtoc) = m.navigation_toc.as_deref() {
1019    crossref.set_navigation_toc(navtoc);
1020  }
1021  // The worker's own handle on the destination's cache (Perl's document cache), shared by its pages and Graphics.
1022  let mut page_opts: latexml_post::document::PostDocumentOptions = m.page_opts.clone().into();
1023  let cache = latexml_post::document::DocCache::new(page_opts.nocache);
1024  page_opts.cache = Some(cache.clone());
1025  let graphics = m.graphicimages.then(|| {
1026    latexml_post::graphics::Graphics::new(None, true)
1027      .with_svg_threshold_kb(m.graphics_svg_threshold_kb)
1028      .with_planned_names(m.resource_names.clone())
1029      .with_doc_cache(cache.clone())
1030  });
1031  let post = latexml_post::Post::new();
1032  let mut processors: Vec<Box<dyn Processor>> = Vec::new();
1033  // Same chain as the in-process renderer (`post.rs`): SVG on the live page
1034  // DOM before MathML/XSLT for the HTML formats (Perl `LaTeXML.pm` order).
1035  if m.svg {
1036    processors.push(Box::new(latexml_post::svg::SVG::new()));
1037  }
1038  let math_formats = crate::post::MathFormats {
1039    pmml:            m.pmml,
1040    cmml:            m.cmml,
1041    unicodemath:     m.unicodemath,
1042    keep_xmath:      m.keep_xmath,
1043    invisible_times: m.invisible_times,
1044    plane1:          m.plane1,
1045    hackplane1:      m.hackplane1,
1046    mathtex:         m.mathtex,
1047    intent_literal:  m.intent_literal,
1048  };
1049  if let Some(math) = math_formats.processor() {
1050    processors.push(math);
1051  }
1052  if let Some(xsl_path) = m.stylesheet.as_deref() {
1053    let params: rustc_hash::FxHashMap<String, String> = m.xslt_params.iter().cloned().collect();
1054    match latexml_post::xslt::XSLT::new(
1055      xsl_path,
1056      params,
1057      !m.default_resources,
1058      None,
1059      m.searchpaths.clone(),
1060    ) {
1061      Ok(xslt) => processors.push(Box::new(xslt)),
1062      Err(e) => emit_error("post", "xslt", &format!("XSLT error: {e}")),
1063    }
1064  }
1065  let ctx = crate::post::PageRenderCtx {
1066    page_opts,
1067    is_html_out: m.is_html_out,
1068    schemadocs: m.schemadocs,
1069    whatsout: latexml_post::extract::Whatsout::from_cli(&m.whatsout).unwrap_or_default(),
1070    remove_spilled: false,
1071  };
1072  let mut procs = crate::post::PageProcessors {
1073    crossref,
1074    graphics,
1075    post,
1076    processors,
1077  };
1078  let mut written: Vec<String> = Vec::new();
1079  let mut made_dirs = latexml_post::writer::MadeDirs::default();
1080  for job in &m.pages {
1081    // Same OS give-back cadence as the serial render loop: each page cycles a
1082    // DOM + XSLT result through the C heap, and a chunk can be tens of
1083    // thousands of pages.
1084    if !written.is_empty() && written.len().is_multiple_of(crate::heap_trim::SAMPLE_PAGES) {
1085      crate::heap_trim::sample();
1086    }
1087    match crate::post::render_spilled_page(
1088      &job.path,
1089      &mut procs,
1090      &ctx,
1091      job.destination.clone(),
1092      job.destination_directory.clone(),
1093    ) {
1094      Ok(outputs) => {
1095        for (dest, output) in outputs {
1096          if let Some(path) = dest.as_deref() {
1097            let _ = made_dirs.ensure_parent(path);
1098            written.push(path.to_string());
1099            if let Err(e) = std::fs::write(path, &output) {
1100              emit_error(
1101                "post",
1102                "write",
1103                &format!("failed to write page {path}: {e}"),
1104              );
1105            }
1106          }
1107        }
1108      },
1109      // Already reported inside the pipeline; mirror the serial driver's
1110      // abort-on-page-failure (the parent flags the shortfall through the
1111      // folded error + the fatal-bearing status this worker will report).
1112      Err(crate::post::PageFailure::Error) => break,
1113      // The parent removes every page of the run (#782).
1114      Err(crate::post::PageFailure::Fatal) => return Ok((written, true)),
1115    }
1116  }
1117  Ok((written, false))
1118}
1119
1120#[cfg(test)]
1121mod tests {
1122  use super::*;
1123
1124  /// At the `Warn` level a Warning keeps its unindented continuation lines (a multi-line message); the notes after an
1125  /// Info record stay hidden. The default verbosity shows every line; `--quiet` (`Error`) only the Error and the
1126  /// Fatal, each with its continuation lines, and so does a console that admits nothing (OD #1158).
1127  #[test]
1128  fn stderr_share_keeps_a_records_continuation_lines() {
1129    let log = "note before\nInfo:a:x one\nMathML[Presentation] S1.html processing\nWarning:b:y first line\nsecond \
1130               line\n\tat loc\nInfo:c:z two\n\tIn here\npost-processing\nError:d:w bad\nits second line\n\tat \
1131               loc2\nWarning:e:v late\nFatal:f:u end\n\tat loc3\n";
1132    let errors = "Error:d:w bad\nits second line\n\tat loc2\nFatal:f:u end\n\tat loc3\n";
1133    assert_eq!(
1134      stderr_share_at(log, |level| level <= log::Level::Warn),
1135      "Warning:b:y first line\nsecond line\n\tat loc\nError:d:w bad\nits second line\n\tat loc2\nWarning:e:v \
1136       late\nFatal:f:u end\n\tat loc3\n"
1137    );
1138    assert_eq!(stderr_share_at(log, |level| level <= log::Level::Info), log);
1139    assert_eq!(
1140      stderr_share_at(log, |level| level <= log::Level::Error),
1141      errors
1142    );
1143    assert_eq!(stderr_share_at(log, |_| false), errors);
1144  }
1145
1146  #[test]
1147  fn child_report_parses_status_lines_and_keeps_log() {
1148    let stderr_text = "Warning:post:x something odd\nInfo:post:y fine\nStatus:pages:41\nStatus:written:/d/S1.html\nStatus:discard:1\nStatus:counts:0,2,1,3,1\nStatus:conversion:3\n";
1149    let r = parse_child_report(stderr_text);
1150    assert_eq!(r.pages, 41);
1151    assert_eq!(r.written, vec!["/d/S1.html"]);
1152    assert!(r.discard);
1153    assert_eq!(r.status, Some(3));
1154    let c = r.counts.expect("counts parsed");
1155    assert_eq!((c.debug, c.info, c.warning, c.error), (0, 2, 1, 3));
1156    assert!(c.fatal);
1157    assert!(r.log.contains("something odd"));
1158    assert!(
1159      !r.log.contains("Status:"),
1160      "status lines must not leak into the folded log"
1161    );
1162  }
1163
1164  /// The parent's STATE values reach the worker's STATE through the manifest's JSON: the raised error cap
1165  /// (tikz's 1000) as the nominal font size (the a0poster guard in cluster_cli).
1166  #[test]
1167  fn manifest_carries_the_parents_state_values() {
1168    let manifest = RenderManifest {
1169      post_values: latexml_core::PostStateValues {
1170        nominal_font_size: Some(24.88),
1171        max_errors:        Some(1000),
1172      },
1173      ..RenderManifest::default()
1174    };
1175    let json = serde_json::to_string(&manifest).unwrap();
1176    let read: RenderManifest = serde_json::from_str(&json).unwrap();
1177    read.post_values.restore();
1178    assert_eq!(
1179      latexml_core::state::try_lookup_int("MAX_ERRORS"),
1180      Some(1000)
1181    );
1182    assert_eq!(
1183      latexml_core::state::lookup_float("NOMINAL_FONT_SIZE").map(|f| f.0),
1184      Some(24.88)
1185    );
1186  }
1187
1188  #[test]
1189  fn child_report_parses_a_setup_failure() {
1190    let r =
1191      parse_child_report("Status:setup-failed:cannot attach the render db /d/LaTeXML-render.db\n");
1192    assert_eq!(
1193      r.setup_failed.as_deref(),
1194      Some("cannot attach the render db /d/LaTeXML-render.db")
1195    );
1196    assert_eq!(r.status, None);
1197    assert!(r.log.is_empty());
1198  }
1199
1200  #[test]
1201  fn child_report_without_status_is_flagged_as_none() {
1202    let r = parse_child_report("Error:post:z boom\n");
1203    assert_eq!(r.status, None);
1204    assert!(r.counts.is_none());
1205    assert_eq!(r.pages, 0);
1206  }
1207
1208  #[test]
1209  fn ansi_is_stripped_from_child_stderr() {
1210    assert_eq!(strip_ansi("\u{1b}[31mError:\u{1b}[0m x"), "Error: x");
1211  }
1212
1213  #[test]
1214  fn render_jobs_defaults_to_serial() {
1215    // NOTE: does not set the env var (process-global); only checks the parse
1216    // fallback contract via the default branch.
1217    assert!(render_jobs() >= 1);
1218  }
1219
1220  #[test]
1221  fn fleet_budget_uses_soft_cap_without_double_discount() {
1222    const MIB: u64 = 1024 * 1024;
1223    // `--max-memory=8192` → soft_cap = 6,144 MiB (3/4 of 8 GiB).
1224    // With 4,300 MiB parent RSS and 80 MiB db (per_worker = 64 + 6 x 80 = 544 MiB):
1225    // remaining fuse headroom is 1,844 MiB → 3 workers affordable.
1226    // (With the old double 3/4 bug, fuse dropped to 4,608 MiB → 308 MiB → 0 workers.)
1227    let soft_cap = latexml_core::stomach::soft_cap_from_ceiling(8192);
1228    assert_eq!(soft_cap, 6144 * MIB);
1229    let (jobs, affordable, budget, per_worker, max_rss_kb) = compute_fleet_budget(
1230      Some(16_000 * MIB),
1231      Some(soft_cap),
1232      4300 * MIB,
1233      80 * MIB,
1234      8,
1235      1000,
1236    );
1237    assert_eq!(budget, 1844 * MIB);
1238    assert_eq!(per_worker, 544 * MIB);
1239    assert_eq!(affordable, 3);
1240    assert_eq!(jobs, 3);
1241    assert_eq!(max_rss_kb, (1844 * MIB) / 3 / 1024);
1242  }
1243
1244  #[test]
1245  fn fleet_shares_cover_the_measured_worker_peak() {
1246    const MIB: u64 = 1024 * 1024;
1247    // Nasser k2400 under `--max-memory=4900`: a 45 MB db, the parent at ~860 MB when the fleet
1248    // spawns, a worker's measured VmHWM 260 MB. Every share must hold that peak.
1249    let (jobs, _, _, per_worker, max_rss_kb) = compute_fleet_budget(
1250      Some(16_000 * MIB),
1251      Some(latexml_core::stomach::soft_cap_from_ceiling(4900)),
1252      860 * MIB,
1253      45 * MIB,
1254      8,
1255      9713,
1256    );
1257    assert_eq!(per_worker, 334 * MIB);
1258    assert_eq!(jobs, 8);
1259    assert!(max_rss_kb * 1024 >= 260 * MIB, "share {max_rss_kb} KiB");
1260  }
1261
1262  #[cfg(unix)]
1263  #[test]
1264  fn only_a_signal_death_is_a_crash() {
1265    use std::os::unix::process::ExitStatusExt;
1266    let report = || parse_child_report("Info:post:x partial\n");
1267    let killed = worker_failure(&Ok((report(), std::process::ExitStatus::from_raw(9)))).unwrap();
1268    assert!(killed.by_signal);
1269    assert_eq!(
1270      killed.why,
1271      "killed by SIGKILL (signal 9) without a Status:conversion line; its stderr ended: Info:post:x partial"
1272    );
1273    // A crash names its signal and the core dump (wait status 11 | 0x80).
1274    let crashed = worker_failure(&Ok((
1275      parse_child_report(""),
1276      std::process::ExitStatus::from_raw(11 | 0x80),
1277    )))
1278    .unwrap();
1279    assert!(crashed.by_signal);
1280    assert_eq!(
1281      crashed.why,
1282      "killed by SIGSEGV (signal 11, core dumped) without a Status:conversion line"
1283    );
1284    // The worker's own memory exit is not a crash; its last three stderr lines end the message, on one line.
1285    let capped = worker_failure(&Ok((
1286      parse_child_report(
1287        "Info:post:a one\nInfo:post:b two\n\nWarning:post:c three\nFatal:oom:rss latexml-oxide: resident \
1288         memory 900MB exceeded the 800MB ceiling\nStatus:pages:0\n",
1289      ),
1290      std::process::ExitStatus::from_raw(137 << 8),
1291    )))
1292    .unwrap();
1293    assert!(
1294      !capped.by_signal,
1295      "the worker's own memory exit is not a crash"
1296    );
1297    assert_eq!(
1298      capped.why,
1299      "exited (code 137) without a Status:conversion line; its stderr ended: Info:post:b two | Warning:post:c \
1300       three | Fatal:oom:rss latexml-oxide: resident memory 900MB exceeded the 800MB ceiling"
1301    );
1302    let done = parse_child_report("Status:pages:1\nStatus:conversion:0\n");
1303    assert!(worker_failure(&Ok((done, std::process::ExitStatus::from_raw(0)))).is_none());
1304  }
1305
1306  #[test]
1307  fn an_abandoned_fleet_names_every_page_it_may_have_written() {
1308    let report = |text: &str| parse_child_report(text);
1309    let status = std::process::ExitStatus::default();
1310    let joined: Vec<Joined> = vec![
1311      // Reported: only the pages it names (not S3, a stale page of an earlier run).
1312      Ok((
1313        report("Status:written:S1\nStatus:pages:1\nStatus:conversion:0\n"),
1314        status,
1315      )),
1316      // Died before its report: any page of its range.
1317      Ok((report("Info:post:x partial\n"), status)),
1318      // Could not set up: none.
1319      Ok((report("Status:setup-failed:no db\n"), status)),
1320      Err("worker spawn failed: EAGAIN".to_string()),
1321      Err("wait failed: EINTR".to_string()),
1322    ];
1323    let range = |names: &[&str]| names.iter().map(|n| n.to_string()).collect::<Vec<_>>();
1324    let ranges = vec![
1325      range(&["S1", "S3"]),
1326      range(&["S4", "S5"]),
1327      range(&["S6"]),
1328      range(&["S7"]),
1329      range(&["S8"]),
1330    ];
1331    assert_eq!(pages_the_fleet_may_have_written(&joined, &ranges), vec![
1332      "S1", "S4", "S5", "S8"
1333    ]);
1334  }
1335}