1use 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
42pub(crate) const MIN_PAGES_FOR_PARALLEL: usize = 64;
45
46pub(crate) const AUTO_JOBS_MAX: usize = 8;
49
50static AUTO_JOBS: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
54
55pub fn enable_auto_jobs() { AUTO_JOBS.store(true, std::sync::atomic::Ordering::Relaxed); }
57
58pub(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#[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#[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#[derive(Serialize, Deserialize, Clone, Default)]
136pub struct RenderManifest {
137 pub dbfile: PathBuf,
139 pub navigation_toc: Option<String>,
140 pub url_style: String,
143 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 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 pub xslt_params: Vec<(String, String)>,
161 pub default_resources: bool,
162 pub searchpaths: Vec<String>,
165 pub svg: bool,
167 pub is_html_out: bool,
169 pub schemadocs: bool,
170 pub whatsout: String,
173 pub page_opts: PageOpts,
174 pub pages: Vec<PageJob>,
175 #[serde(default)]
178 pub max_rss_kb: u64,
179 #[serde(default)]
182 pub post_values: latexml_core::PostStateValues,
183 #[serde(default)]
187 pub resource_names: Vec<(String, String, String, Option<String>)>,
188 #[serde(default)]
191 pub log_level: String,
192 #[serde(default)]
195 pub confinement: Option<latexml_core::util::pathname::ConfinementSnapshot>,
196}
197
198pub(crate) struct ParallelResult {
201 pub(crate) main_output: Option<String>,
204 pub(crate) pages_rendered: usize,
206 pub(crate) discarded: bool,
209 pub(crate) written: Vec<String>,
212 pub(crate) abandoned: bool,
215}
216
217fn 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
232fn 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
252struct ChildReport {
255 log: String,
256 counts: Option<ReportCounts>,
257 status: Option<usize>,
258 pages: usize,
259 discard: bool,
261 written: Vec<String>,
263 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
320enum Pending {
322 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
334type 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
351struct WorkerFailure {
353 why: String,
354 by_signal: bool,
356}
357
358fn 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
382fn 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
397fn 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#[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
441fn worker_estimate_bytes(db_bytes: u64) -> u64 {
446 db_bytes.saturating_mul(6).saturating_add(64 << 20)
447}
448
449fn 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
477fn 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
495pub(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 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 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 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 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 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 let kill_guard = latexml_core::watchdog::kill_pid_on_exit(pid, false);
642 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 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 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 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 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 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 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 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 note_status(LogStatus::Fatal, None);
788 },
789 Some(_) => {},
790 }
791 },
792 }
793 }
794
795 if discard {
800 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
822fn 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
848fn stderr_share(log: &str) -> String {
852 stderr_share_at(log, latexml_core::util::logger::stderr_admits)
853}
854
855fn 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 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
890fn print_setup_failure(why: &str) -> i32 {
894 eprintln!("Status:setup-failed:{}", why.replace('\n', " "));
895 1
896}
897
898pub 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 #[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 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#[cfg(feature = "test-utils")]
981fn test_fault() -> Option<String> { std::env::var("LATEXML_RENDER_WORKER_TEST_ABORT").ok() }
982
983fn 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 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 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 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 Err(crate::post::PageFailure::Error) => break,
1113 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 #[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 #[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 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 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 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 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 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 Ok((
1313 report("Status:written:S1\nStatus:pages:1\nStatus:conversion:0\n"),
1314 status,
1315 )),
1316 Ok((report("Info:post:x partial\n"), status)),
1318 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}