Skip to main content

latexml/
api.rs

1//! Stable, high-level conversion API for using `latexml` as a **library**.
2//!
3//! Downstream Rust crates depend on `latexml` and call one function — no
4//! binary, no manual [`Config`] or
5//! binding-dispatch wiring:
6//!
7//! ```no_run
8//! let xml = latexml::api::convert_to_xml(r"\documentclass{article}\begin{document}Hi\end{document}")?;
9//! let html = latexml::api::convert_to_html(r"\documentclass{article}\begin{document}Hi\end{document}")?;
10//! # Ok::<(), String>(())
11//! ```
12//!
13//! ## What these encapsulate
14//! The engine is a **thread-local singleton**, so each call runs on an engine
15//! worker thread with a large (256 MiB) stack — matching the `latexml_oxide`
16//! binary — so deeply nested math can't overflow the 8 MiB default stack.
17//!
18//! **A call blocks** its thread until the result is back; an async caller wraps it
19//! in its runtime's blocking pool (`tokio::task::spawn_blocking`), not on an
20//! executor thread.
21//!
22//! **Workers are pooled.** A call takes an idle worker or starts one, so calls made
23//! from several threads at once convert in parallel, one worker each. After each
24//! call the worker's engine is reset
25//! ([`reset_thread_engine`](latexml_core::reset_thread_engine)): no definition,
26//! counter or cache of one call reaches the next. The pool is bounded: at most one
27//! idle worker per available core stays parked (a worker finishing beyond that
28//! exits), and idle workers exit after a few seconds without a call, all but the
29//! newest: one worker stays parked, so a caller converting now and then reuses it
30//! instead of starting a worker per call. A parked worker holds one reset engine
31//! (~39 MB of heap) and the stack pages its deepest conversion touched. A worker
32//! that exits first empties its engine
33//! ([`shrink_thread_engine`](latexml_core::shrink_thread_engine)): the engine's
34//! per-thread roots do **not** run destructors at thread exit, so an exiting
35//! worker would otherwise leave its engine behind. A call that panics returns
36//! `Err`, and its worker exits. A child forked while no call is in flight starts
37//! with an empty pool (one forked mid-call may inherit a held pool or dump-cache
38//! lock). The
39//! standard package + contrib binding-dispatch chain is wired for you.
40//!
41//! Like the `latexml_oxide` binary, these calls interpret a `.sty`/`.cls` that has no binding raw
42//! (Perl LaTeXML's `--includestyles`) and use the arXiv profile's runaway limits; a caller wanting
43//! Perl LaTeXML's binding-only default drives a [`Converter`] with its
44//! own [`Config`] (`include_styles: Some(false)`; OXIDIZED_DESIGN_DIVERGENCES #1080).
45//!
46//! ## Requirements at runtime
47//! Same host dependencies as the binary: a **TeX distribution** on `PATH` for
48//! packages/classes/fonts, and (only for figure-bearing HTML) the graphics
49//! tools. XML/XSLT/RelaxNG assets are embedded.
50//!
51//! For finer control (preloads, search paths, encoding, whatsin/out, split,
52//! …), drive [`crate::converter::Converter`] and [`crate::post`] directly; this
53//! module is the batteries-included entrypoint.
54
55use std::{
56  panic::{self, AssertUnwindSafe},
57  rc::Rc,
58  sync::{Mutex, MutexGuard, PoisonError, mpsc},
59  time::Duration,
60};
61
62use latexml_core::common::{Config, OutputFormat};
63
64use crate::{
65  converter::{ConversionResponse, Converter},
66  post,
67};
68
69/// Build the standard library `Config`: quiet, LaTeX mode, with the package +
70/// contrib binding-dispatch chain a normal conversion uses.
71fn library_config(format: OutputFormat) -> Config {
72  Config {
73    // Quiet by default: a library caller doesn't want progress notes on stderr.
74    // The per-conversion log is still captured internally and returned in the
75    // error path. Callers wanting logs can use `Converter` directly.
76    verbosity: -1,
77    format,
78    bindings_dispatch: Some(Rc::new(latexml_package::dispatch)),
79    extra_bindings_dispatch: Some(Rc::new(latexml_contrib::dispatch)),
80    // The CLI's defaults: raw `.sty`/`.cls` loading and ar5iv.sty's runaway limits (OD #1080).
81    include_styles: Some(true),
82    if_limit: Some(latexml_core::common::RUNAWAY_IF_LIMIT),
83    absorb_limit: Some(latexml_core::common::RUNAWAY_ABSORB_LIMIT),
84    ..Config::default()
85  }
86}
87
88/// A job for a worker thread. It returns whether the worker may take another, and the delivery of its result, which
89/// the worker makes once it is back on the idle list (a sequential caller's next call then finds it there).
90type Job = Box<dyn FnOnce() -> (bool, Box<dyn FnOnce()>) + Send>;
91
92/// How long an idle worker waits for a job before it exits (the newest parked one waits again instead). A new worker
93/// costs ~0.3 ms (`init_thread_engine`, release) against at least ~60 ms for the smallest conversion, while a parked
94/// one holds ~39 MB of reset engine plus the stack its deepest conversion touched: a caller converting every few
95/// seconds keeps its workers, an idle host gives back all but one. Tests use a shorter wait.
96const IDLE_TIMEOUT: Duration = if cfg!(test) {
97  Duration::from_millis(300)
98} else {
99  Duration::from_secs(5)
100};
101
102/// The idle workers of this process, each with its id and the channel it waits on for a job.
103struct Idle {
104  /// The process the workers belong to: a forked child (another process id) has none of its parent's threads, so it
105  /// starts an empty pool.
106  pid:     u32,
107  next_id: u64,
108  workers: Vec<(u64, mpsc::Sender<Job>)>,
109}
110
111/// The pool. A call takes the newest idle worker (the last listed) or spawns one, so calls made in parallel run in
112/// parallel; at most [`max_idle`] workers stay parked, each but the newest for at most [`IDLE_TIMEOUT`].
113static IDLE_WORKERS: Mutex<Idle> = Mutex::new(Idle {
114  pid:     0,
115  next_id: 0,
116  workers: Vec::new(),
117});
118
119/// This process's idle workers.
120fn idle_workers() -> MutexGuard<'static, Idle> {
121  let mut idle = IDLE_WORKERS.lock().unwrap_or_else(PoisonError::into_inner);
122  let pid = std::process::id();
123  if idle.pid != pid {
124    idle.pid = pid;
125    idle.workers = Vec::new();
126  }
127  idle
128}
129
130/// The most idle workers kept: one per core this process may use. A worker finishing while that many are parked
131/// exits instead.
132fn max_idle() -> usize {
133  #[cfg(test)]
134  if let n @ 1.. = MAX_IDLE_FOR_TESTS.load(std::sync::atomic::Ordering::Relaxed) {
135    return n;
136  }
137  // Read once: on Linux `available_parallelism` reads the cgroup files, and this runs under the pool lock.
138  static CORES: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
139  *CORES.get_or_init(|| std::thread::available_parallelism().map_or(1, std::num::NonZeroUsize::get))
140}
141
142/// A lower cap for the cap's test, which would otherwise start a worker (~38 MB) per core and two more.
143#[cfg(test)]
144static MAX_IDLE_FOR_TESTS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
145
146/// Run `job` on a 256 MiB-stack engine worker thread (as `latexml_oxide::main` converts), then reset the
147/// thread-local engine, and return `job`'s result. Workers are reused: the engine's per-thread roots are leaked
148/// statics that a thread exit does not free (`latexml_core::reset_thread_engine`), so a thread per call grew a
149/// long-lived host by ~36 MB per call; a parked worker keeps one reset engine. A worker that exits — the pool is
150/// full, it idled past [`IDLE_TIMEOUT`] below a newer parked worker, its job panicked (the call returns `Err`), or its
151/// reset could not give its symbol constants back (`reset_thread_engine` returns `false`) — first empties its engine
152/// ([`latexml_core::shrink_thread_engine`]), so it leaves only the roots' boxes behind.
153fn on_worker<T: Send + 'static>(
154  job: impl FnOnce() -> Result<T, String> + Send + 'static,
155) -> Result<T, String> {
156  let (result_tx, result_rx) = mpsc::channel();
157  let mut job: Option<Job> = Some(Box::new(move || {
158    let outcome = panic::catch_unwind(AssertUnwindSafe(|| {
159      // The CLI's pushback cap (ar5iv.sty's `pushbacklimit`), on the thread whose gullet converts; per job, as the
160      // reset gives the next job a fresh gullet.
161      if std::env::var_os("LATEXML_NO_DEFAULT_PUSHBACK_LIMIT").is_none() {
162        latexml_core::gullet::set_pushback_limit(Some(5_000_000));
163      }
164      job()
165    }));
166    // A panicked job's worker exits (`retire` clears what the reset would).
167    let reset = match outcome {
168      Ok(_) => panic::catch_unwind(|| {
169        reset_crates();
170        latexml_core::reset_thread_engine()
171      }),
172      Err(_) => Ok(false),
173    };
174    let reusable = outcome.is_ok() && matches!(reset, Ok(true));
175    let result = match (outcome, reset) {
176      (Ok(result), Ok(_)) => result,
177      (Err(payload), _) | (Ok(_), Err(payload)) => Err(format!(
178        "latexml worker thread panicked: {}",
179        panic_message(payload.as_ref())
180      )),
181    };
182    let deliver: Box<dyn FnOnce()> = Box::new(move || {
183      let _ = result_tx.send(result);
184    });
185    (reusable, deliver)
186  }));
187  loop {
188    let idle = idle_workers().workers.pop();
189    match idle {
190      // A worker that exited left its sender behind: the job comes back, try the next.
191      Some((_, worker)) => match worker.send(job.take().expect("the job is sent once")) {
192        Ok(()) => break,
193        Err(mpsc::SendError(back)) => job = Some(back),
194      },
195      None => {
196        spawn_worker(job.take().expect("the job is sent once"))?;
197        break;
198      },
199    }
200  }
201  result_rx
202    .recv()
203    .unwrap_or_else(|_| Err("latexml worker thread exited without a result".to_string()))
204}
205
206/// The engine, package and contrib crates' per-conversion state (cleared at a session's start too,
207/// `Converter::initialize_session`): it holds symbols, so it goes before the arena does.
208fn reset_crates() {
209  latexml_engine::reset_conversion_state();
210  latexml_package::reset_conversion_state();
211  latexml_contrib::reset_conversion_state();
212}
213
214/// Empty a worker's engine before it exits. A panic here is caught (the default hook has printed it) and the worker
215/// exits anyway, leaving what was not emptied.
216fn retire() {
217  let _ = panic::catch_unwind(|| {
218    reset_crates();
219    latexml_core::shrink_thread_engine();
220  });
221}
222
223/// Start a worker on `first`. It builds its engine roots before any job ([`latexml_core::init_thread_engine`], which
224/// makes its resets reusable), then runs jobs, parking on the idle list after each while they allow it and the list
225/// has room.
226fn spawn_worker(first: Job) -> Result<(), String> {
227  let (job_tx, job_rx) = mpsc::channel::<Job>();
228  std::thread::Builder::new()
229    .name("latexml-api".to_string())
230    .stack_size(256 * 1024 * 1024)
231    .spawn(move || {
232      latexml_core::init_thread_engine();
233      let mut next = Some(first);
234      let mut id = None;
235      while let Some(job) = next.take() {
236        let (reusable, deliver) = job();
237        let parked = reusable && {
238          let mut idle = idle_workers();
239          let room = idle.workers.len() < max_idle();
240          if room {
241            let worker = *id.get_or_insert_with(|| {
242              idle.next_id += 1;
243              idle.next_id
244            });
245            idle.workers.push((worker, job_tx.clone()));
246          }
247          room
248        };
249        if !parked {
250          retire();
251        }
252        deliver();
253        if parked {
254          next = next_job(id.expect("a parked worker has an id"), &job_rx);
255        }
256      }
257    })
258    .map(drop)
259    .map_err(|e| format!("failed to spawn latexml worker thread: {e}"))
260}
261
262/// A parked worker's next job, or `None` once it has idled past [`IDLE_TIMEOUT`] and left the idle list (its engine
263/// emptied). The newest parked worker (the list's last, which a caller takes first) does not leave: it waits again,
264/// so a caller converting less often than the timeout keeps one worker instead of starting one per call. A caller
265/// that popped the worker just before it timed out has its job on the way: the worker takes it.
266fn next_job(worker: u64, jobs: &mpsc::Receiver<Job>) -> Option<Job> {
267  loop {
268    if let Ok(job) = jobs.recv_timeout(IDLE_TIMEOUT) {
269      return Some(job);
270    }
271    let mut idle = idle_workers();
272    let newest = idle.workers.len().checked_sub(1);
273    match idle
274      .workers
275      .iter()
276      .position(|(listed, _)| *listed == worker)
277    {
278      Some(at) if Some(at) == newest => {},
279      Some(at) => {
280        idle.workers.remove(at);
281        drop(idle);
282        retire();
283        return None;
284      },
285      None => {
286        drop(idle);
287        return jobs.recv().ok();
288      },
289    }
290  }
291}
292
293/// A panic payload's message, as the default hook prints it.
294fn panic_message(payload: &(dyn std::any::Any + Send)) -> &str {
295  payload
296    .downcast_ref::<&str>()
297    .copied()
298    .or_else(|| payload.downcast_ref::<String>().map(String::as_str))
299    .unwrap_or("unknown panic")
300}
301
302/// Extract the converted XML from a [`ConversionResponse`], preserving the
303/// captured conversion log in the `Err` message when conversion failed.
304fn core_result_xml(response: ConversionResponse, prefix: &str) -> Result<String, String> {
305  response.result.ok_or_else(|| {
306    if response.log.is_empty() {
307      prefix.to_string()
308    } else {
309      format!("{prefix}:\n{}", response.log)
310    }
311  })
312}
313
314/// Convert a TeX/LaTeX source string to LaTeXML **XML** (the intermediate
315/// representation, before any HTML post-processing).
316///
317/// Returns the serialized XML on success, or the captured conversion log on
318/// failure (a fatal error, or an engine that could not initialize). Runs on a
319/// pooled engine worker (see the [module docs](self)); safe to call from several
320/// threads at once.
321pub fn convert_to_xml(tex: &str) -> Result<String, String> {
322  let tex = tex.to_string();
323  on_worker(move || xml_job(&tex))
324}
325
326/// The conversion [`convert_to_xml`] runs on its worker.
327fn xml_job(tex: &str) -> Result<String, String> {
328  let opts = library_config(OutputFormat::XML);
329  let mut converter = Converter::from_config(opts.clone());
330  converter.note_main_source(&format!("literal:{tex}"));
331  converter
332    .prepare_session(&opts)
333    .map_err(|e| format!("could not prepare session: {e}"))?;
334  let response = converter.convert(format!("literal:{tex}"));
335  core_result_xml(response, "conversion failed")
336}
337
338/// Convert a TeX/LaTeX source string all the way to a standalone **HTML5**
339/// document (LaTeXML XML + the HTML post-processing pipeline, with
340/// Presentation MathML).
341///
342/// Figures are left as raw `<ltx:graphics>` references — image conversion
343/// writes files next to a destination, and this string-returning API has none;
344/// use [`crate::post`] with a `destination` when you need converted images.
345///
346/// The page links the bundled CSS/JS, and with no destination those files are
347/// copied into the working directory; [`convert_to_html_with`] and
348/// [`HtmlOptions`] choose otherwise.
349///
350/// Runs on a pooled engine worker (see the [module docs](self)); safe to call
351/// from several threads at once.
352pub fn convert_to_html(tex: &str) -> Result<String, String> {
353  convert_to_html_with(tex, &HtmlOptions::default())
354}
355
356/// The settings [`convert_to_html_with`] takes. [`Default`] is what
357/// [`convert_to_html`] does. Start from [`HtmlOptions::default()`] and use its
358/// builder methods so future options remain backwards-compatible:
359///
360/// ```no_run
361/// use latexml::api::{HtmlOptions, convert_to_html_with};
362/// let options = HtmlOptions::default().with_default_resources(false);
363/// let html = convert_to_html_with(r"\documentclass{article}\begin{document}Hi\end{document}", &options)?;
364/// # Ok::<(), String>(())
365/// ```
366#[derive(Clone, Debug)]
367#[non_exhaustive]
368pub struct HtmlOptions {
369  /// Link and copy the bundled CSS/JS (`true`, Perl `defaultresources`). With no
370  /// destination the files land in the working directory; `false` is the
371  /// `--nodefaultresources` equivalent: no links to them, nothing written (a remote
372  /// `https://…` stylesheet a binding requires stays linked, OD #1249).
373  pub default_resources: bool,
374}
375
376impl Default for HtmlOptions {
377  fn default() -> Self { HtmlOptions { default_resources: true } }
378}
379
380impl HtmlOptions {
381  /// Set whether to link and copy the bundled CSS/JS resources (`--defaultresources` /
382  /// `--nodefaultresources`).
383  pub fn with_default_resources(mut self, default_resources: bool) -> Self {
384    self.default_resources = default_resources;
385    self
386  }
387}
388
389/// [`convert_to_html`] with the given [`HtmlOptions`], on a pooled engine worker
390/// as [`convert_to_html`].
391pub fn convert_to_html_with(tex: &str, options: &HtmlOptions) -> Result<String, String> {
392  let tex = tex.to_string();
393  let options = options.clone();
394  on_worker(move || html_job(&tex, &options))
395}
396
397/// The conversion [`convert_to_html_with`] runs on its worker.
398fn html_job(tex: &str, options: &HtmlOptions) -> Result<String, String> {
399  let opts = library_config(OutputFormat::HTML5);
400  let mut converter = Converter::from_config(opts.clone());
401  converter.note_main_source(&format!("literal:{tex}"));
402  converter
403    .prepare_session(&opts)
404    .map_err(|e| format!("could not prepare session: {e}"))?;
405  let xml = core_result_xml(
406    converter.convert(format!("literal:{tex}")),
407    "conversion failed before post-processing",
408  )?;
409
410  let post_opts = html_post_options(options.default_resources);
411  post_result(post::run_post_processing_logged(&xml, &post_opts))
412}
413
414/// The post-processing [`convert_to_html_with`] runs: the CLI's `html5` defaults, no destination.
415fn html_post_options(default_resources: bool) -> post::PostOptions<'static> {
416  post::PostOptions {
417    pmml: true,
418    // Same per-format sheet the CLI uses (shared source of truth).
419    stylesheet: post::default_stylesheet(Some("html5")),
420    is_html: Some(true),
421    default_resources,
422    // No destination to write images to; keep the raw graphics references.
423    graphicimages: false,
424    ..post::PostOptions::default()
425  }
426}
427
428/// The HTML, or post's log when post-processing died (`Fatal:post:convert`, #782) and left no
429/// document, the CLI's test. The status also counts core's: a core Fatal's rescued document is
430/// post-processed and returned, as in Perl's convert (LaTeXML.pm L277-337).
431fn post_result(post: post::PostOutcome) -> Result<String, String> {
432  if post.html.is_empty() && post.status_code >= 3 {
433    Err(format!("post-processing failed:\n{}", post.log))
434  } else {
435    Ok(post.html)
436  }
437}
438
439#[cfg(test)]
440mod tests {
441  use std::{
442    cell::RefCell,
443    sync::{Arc, Barrier},
444    time::Instant,
445  };
446
447  use super::*;
448
449  const DOC: &str = r"\documentclass{article}\begin{document}Hello \(x^2\)\end{document}";
450
451  /// The process's resident set, where it measures only this test: under nextest (one process per test). Under
452  /// `cargo test` the binary's other converting tests run alongside and grow the same resident set, so the bound is
453  /// skipped there (visibly); the thread-identity asserts still tell a reused worker from a worker per call.
454  fn rss_kb_if_alone(test: &str) -> Option<u64> {
455    if std::env::var_os("NEXTEST_EXECUTION_MODE").is_some_and(|mode| mode == "process-per-test") {
456      latexml_core::watchdog::process_rss_kb()
457    } else {
458      eprintln!("SKIP {test}: RSS bound checked only under nextest (one process per test)");
459      None
460    }
461  }
462
463  /// The pool to this test alone: the tests that call through it run one at a time under `cargo test` (one process),
464  /// so none takes, parks or kills another's worker. (nextest runs each test in its own process.)
465  fn pool_to_myself() -> MutexGuard<'static, ()> {
466    static POOL_TESTS: Mutex<()> = Mutex::new(());
467    POOL_TESTS.lock().unwrap_or_else(PoisonError::into_inner)
468  }
469
470  #[test]
471  fn xml_conversion_returns_content() {
472    let _pool = pool_to_myself();
473    let xml = convert_to_xml(DOC).expect("convert_to_xml");
474    assert!(
475      xml.contains("Hello"),
476      "XML should contain the body text: {xml}"
477    );
478    assert!(
479      xml.contains("<?xml") || xml.contains("<document"),
480      "looks like XML"
481    );
482  }
483
484  /// #782: a post Fatal (here a sheet that terminates) is an `Err` carrying the log, not `Ok("")`.
485  #[test]
486  fn a_post_fatal_is_an_err() {
487    let _pool = pool_to_myself();
488    let _ = latexml_core::util::logger::init(log::LevelFilter::Warn);
489    let dir = tempfile::tempdir().expect("tempdir");
490    let xsl = dir.path().join("terminate.xsl");
491    std::fs::write(
492      &xsl,
493      "<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">\
494       <xsl:template match=\"/\"><xsl:message terminate=\"yes\">STOP</xsl:message></xsl:template>\
495       </xsl:stylesheet>",
496    )
497    .unwrap();
498    let xsl = xsl.to_string_lossy().into_owned();
499    let xml = "<?xml version=\"1.0\"?><document xmlns=\"http://dlmf.nist.gov/LaTeXML\"><para><p>Hi</p></para></document>";
500    let result = on_worker(move || {
501      post_result(post::run_post_processing_logged(xml, &post::PostOptions {
502        stylesheet: Some(&xsl),
503        ..html_post_options(false)
504      }))
505    });
506    let log = result.expect_err("a post Fatal is an Err");
507    assert_eq!(log.matches("Fatal:post:convert").count(), 1, "{log}");
508  }
509
510  /// A core Fatal that keeps its partial document (too many errors) is still post-processed and
511  /// returned, as Perl's convert and the CLI do (LaTeXML.pm L277-337); the Fatal is in the core log.
512  #[test]
513  fn a_core_fatal_keeps_its_rescued_document() {
514    let _pool = pool_to_myself();
515    let tex = format!(
516      "\\documentclass{{article}}\\begin{{document}}Kept text.\n\n{}\\end{{document}}",
517      (0..101u8)
518        .map(|i| format!(
519          "\\nosuch{}{} ",
520          (b'a' + i / 26) as char,
521          (b'a' + i % 26) as char
522        ))
523        .collect::<String>()
524    );
525    let (core_log, result) = on_worker(move || {
526      let opts = library_config(OutputFormat::HTML5);
527      let mut converter = Converter::from_config(opts.clone());
528      converter.prepare_session(&opts).expect("session");
529      let response = converter.convert(format!("literal:{tex}"));
530      let xml = response.result.expect("the rescued document");
531      let post = post_result(post::run_post_processing_logged(
532        &xml,
533        &html_post_options(false),
534      ));
535      Ok(((response.status_code, response.log), post))
536    })
537    .expect("worker thread");
538    assert_eq!(core_log.0, 3, "{}", core_log.1);
539    assert!(
540      core_log.1.contains("101 errors; 1 fatal error;"),
541      "{}",
542      core_log.1
543    );
544    let html = result.expect("a core Fatal's rescued document is Ok");
545    assert!(html.contains("Kept text."), "{html}");
546  }
547
548  #[test]
549  fn html_conversion_returns_page() {
550    let _pool = pool_to_myself();
551    let html = convert_to_html_with(DOC, &HtmlOptions::default().with_default_resources(false))
552      .expect("convert_to_html_with");
553    assert!(html.contains("Hello"), "HTML should contain the body text");
554    assert!(
555      html.contains("<math") || html.contains("ltx_Math"),
556      "math rendered"
557    );
558  }
559
560  /// Converts its documents in turn on one engine thread, as a pooled worker does (built by `init_thread_engine`,
561  /// reset after each job), and returns each HTML.
562  fn in_turn(docs: Vec<String>) -> Vec<String> {
563    std::thread::Builder::new()
564      .stack_size(256 * 1024 * 1024)
565      .spawn(move || {
566        latexml_core::init_thread_engine();
567        docs
568          .iter()
569          .map(|tex| {
570            latexml_core::gullet::set_pushback_limit(Some(5_000_000));
571            let html = html_job(tex, &HtmlOptions::default().with_default_resources(false));
572            assert!(
573              latexml_core::reset_thread_engine(),
574              "the reset gave the constants their symbols"
575            );
576            html.expect("an HTML page")
577          })
578          .collect()
579      })
580      .expect("an engine thread")
581      .join()
582      .unwrap_or_else(|payload| panic::resume_unwind(payload))
583  }
584
585  /// A document that defines a macro, a counter, a theorem style and a label, then one that reads the same names: on
586  /// a reused worker, the second converts as alone on a fresh thread (no definition, counter, label or id bleeds), and
587  /// so does the first after it. The reset rebuilds the arena; the token constants keep their symbols (STABLE1 r3).
588  #[test]
589  fn a_reused_worker_converts_as_a_fresh_one() {
590    let _pool = pool_to_myself();
591    let a = r"\documentclass{article}\newtheorem{thm}{Theorem}\newcounter{cnt}\setcounter{cnt}{41}
592\newcommand\foo{Defined in A}\def\aonly{A's macro}
593\begin{document}\section{First}\label{s:x}\foo, \aonly, \stepcounter{cnt}\thecnt.
594\begin{thm}A theorem.\end{thm} \(\frac{a}{b}+\sqrt{x}\) \footnote{A's note.} See \ref{s:x}.
595\begin{tabular}{cc}1&2\\3&4\end{tabular}\end{document}"
596      .to_string();
597    let b = r"\documentclass{article}\newtheorem{thm}{Proposition}\newcounter{cnt}
598\providecommand\foo{Provided in B}
599\begin{document}\section{Second}\foo; \ifdefined\aonly A's macro bled\else no A macro\fi; \thecnt; \ref{s:x}.
600\begin{thm}B's claim.\end{thm} \[x^2\over y\] \begin{tabular}{c}5\end{tabular}\end{document}"
601      .to_string();
602    let b_alone = in_turn(vec![b.clone()]).remove(0);
603    let a_alone = in_turn(vec![a.clone()]).remove(0);
604    assert!(
605      b_alone.contains("Provided in B")
606        && b_alone.contains("no A macro")
607        && b_alone.contains("Proposition"),
608      "{b_alone}"
609    );
610    let runs = in_turn(vec![a.clone(), b.clone(), a.clone(), b.clone()]);
611    assert_eq!(runs[0], a_alone);
612    assert_eq!(runs[1], b_alone);
613    assert_eq!(runs[2], a_alone);
614    assert_eq!(runs[3], b_alone);
615    // Through the pool: B right after A on the same worker (another test of this binary may take the idle worker in
616    // between, so up to five tries; the worker is back on the idle list before A's result is delivered).
617    let page = |tex: String| {
618      on_worker(move || {
619        let html = html_job(&tex, &HtmlOptions::default().with_default_resources(false))?;
620        Ok((html, std::thread::current().id()))
621      })
622      .expect("an HTML page")
623    };
624    let same_worker = (0..5).any(|_| {
625      let (html_a, thread_a) = page(a.clone());
626      let (html_b, thread_b) = page(b.clone());
627      assert_eq!(html_a, a_alone);
628      assert_eq!(html_b, b_alone);
629      thread_a == thread_b
630    });
631    assert!(same_worker, "B never ran on A's worker");
632  }
633
634  /// The API reuses its workers: sequential calls run on a pooled thread, not a thread each, so a long-lived host does
635  /// not grow per call (a thread per call left ~36 MB of engine on each exited thread, 13.7 MB of it
636  /// resident: RSS measured over 300 calls). Other tests of this binary may hold a worker at the same time,
637  /// hence a bound on the threads, not one thread.
638  #[test]
639  fn sequential_calls_reuse_their_workers() {
640    let _pool = pool_to_myself();
641    const CALLS: usize = 60;
642    let mut threads = std::collections::HashSet::new();
643    let mut rss_after_warm_up = None;
644    for call in 0..CALLS {
645      let (xml, thread) =
646        on_worker(|| Ok((xml_job(DOC)?, std::thread::current().id()))).expect("a conversion");
647      assert!(xml.contains("Hello"), "{xml}");
648      threads.insert(thread);
649      if call == 9 {
650        rss_after_warm_up = rss_kb_if_alone("sequential_calls_reuse_their_workers");
651      }
652    }
653    assert!(
654      threads.len() <= 8,
655      "{} worker threads for {CALLS} calls",
656      threads.len()
657    );
658    // Where the platform reports a resident set: 50 more calls stay within 256 MiB of it (a thread per call: ~680 MiB).
659    if let (Some(before), Some(after)) =
660      (rss_after_warm_up, latexml_core::watchdog::process_rss_kb())
661    {
662      assert!(
663        after.saturating_sub(before) < 256 * 1024,
664        "RSS grew {} KiB over {} calls",
665        after.saturating_sub(before),
666        CALLS - 10
667      );
668    }
669  }
670
671  /// A job that panics ends its worker: the next call runs on another thread.
672  #[test]
673  fn a_panicked_worker_is_not_reused() {
674    let _pool = pool_to_myself();
675    let (tx, rx) = mpsc::channel();
676    let err = on_worker::<()>(move || {
677      tx.send(std::thread::current().id()).unwrap();
678      panic!("boom")
679    })
680    .expect_err("a panic is an Err");
681    assert!(
682      err.contains("latexml worker thread panicked: boom"),
683      "{err}"
684    );
685    let panicked = rx.recv().unwrap();
686    let next = on_worker(|| Ok(std::thread::current().id())).expect("a worker");
687    assert_ne!(next, panicked);
688  }
689
690  thread_local! {
691    /// A test's mark on the worker that ran its job: dropped when the worker's thread exits.
692    static WORKER_MARK: RefCell<Option<Arc<()>>> = const { RefCell::new(None) };
693  }
694
695  /// Waits up to `seconds` for `done`, polling.
696  fn eventually(seconds: u64, done: impl Fn() -> bool) -> bool {
697    let deadline = Instant::now() + Duration::from_secs(seconds);
698    while Instant::now() < deadline {
699      if done() {
700        return true;
701      }
702      std::thread::sleep(Duration::from_millis(20));
703    }
704    done()
705  }
706
707  /// Two workers parked at once: the one below idles past `IDLE_TIMEOUT` and exits (the mark it holds is dropped with
708  /// its thread), and the newest stays parked, so eviction never empties the idle list.
709  #[test]
710  fn an_idle_worker_exits_after_the_timeout() {
711    let _pool = pool_to_myself();
712    let mark = Arc::new(());
713    let both_in = Arc::new(Barrier::new(2));
714    let callers: Vec<_> = (0..2)
715      .map(|_| {
716        let (held, both_in) = (mark.clone(), both_in.clone());
717        std::thread::spawn(move || {
718          on_worker(move || {
719            WORKER_MARK.with(|m| *m.borrow_mut() = Some(held));
720            both_in.wait();
721            Ok(())
722          })
723          .expect("a worker")
724        })
725      })
726      .collect();
727    callers
728      .into_iter()
729      .for_each(|c| c.join().expect("a caller"));
730    assert_eq!(
731      Arc::strong_count(&mark),
732      3,
733      "both parked workers hold the mark"
734    );
735    assert!(
736      eventually(60, || Arc::strong_count(&mark) <= 2),
737      "both workers are still alive after {IDLE_TIMEOUT:?} idle"
738    );
739    std::thread::sleep(IDLE_TIMEOUT * 3);
740    assert_eq!(
741      Arc::strong_count(&mark),
742      2,
743      "the newest parked worker stays"
744    );
745    assert_eq!(idle_workers().workers.len(), 1, "one worker stays parked");
746  }
747
748  /// A caller converting less often than every `IDLE_TIMEOUT` keeps one worker: the newest parked worker does not
749  /// evict, so 20 calls, each after an idle wait past the timeout, run on one thread: no worker starts or retires, so
750  /// none leaves heap behind. When every idle worker evicted, each such call started a worker and each
751  /// retired one left ~0.37 MB of heap behind (release), without bound for a long-running host. The thread identity is
752  /// the check: an RSS bound here (+2-3 MiB kept vs +19 MiB per call) failed under a loaded full-suite run (+18 MiB).
753  #[test]
754  fn a_sporadic_caller_keeps_one_worker() {
755    let _pool = pool_to_myself();
756    let call =
757      || on_worker(|| Ok((xml_job(DOC)?, std::thread::current().id()))).expect("a conversion");
758    let (_, warm) = call();
759    // A worker an earlier test parked below this one evicts meanwhile.
760    std::thread::sleep(IDLE_TIMEOUT * 2);
761    let mut threads = std::collections::HashSet::new();
762    for _ in 0..20 {
763      std::thread::sleep(IDLE_TIMEOUT + Duration::from_millis(100));
764      let (xml, thread) = call();
765      assert!(xml.contains("Hello"), "{xml}");
766      threads.insert(thread);
767    }
768    assert_eq!(
769      threads,
770      std::collections::HashSet::from([warm]),
771      "20 sporadic calls ran on {} threads",
772      threads.len()
773    );
774  }
775
776  /// `max_idle() + 2` calls at once run on as many workers; afterwards at most `max_idle()` stay parked, and the
777  /// others have exited. The cap lowered to 2 for this binary (another test may park a worker too, never past it).
778  #[test]
779  fn the_idle_workers_are_capped() {
780    let _pool = pool_to_myself();
781    let cap = 2;
782    MAX_IDLE_FOR_TESTS.store(cap, std::sync::atomic::Ordering::Relaxed);
783    // The cap goes back to the core count however this test ends.
784    struct RestoreCap;
785    impl Drop for RestoreCap {
786      fn drop(&mut self) { MAX_IDLE_FOR_TESTS.store(0, std::sync::atomic::Ordering::Relaxed); }
787    }
788    let _restore = RestoreCap;
789    let calls = cap + 2;
790    let mark = Arc::new(());
791    let all_in = Arc::new(Barrier::new(calls));
792    let callers: Vec<_> = (0..calls)
793      .map(|_| {
794        let (held, all_in) = (mark.clone(), all_in.clone());
795        std::thread::spawn(move || {
796          on_worker(move || {
797            WORKER_MARK.with(|m| *m.borrow_mut() = Some(held));
798            all_in.wait();
799            Ok(std::thread::current().id())
800          })
801          .expect("a worker")
802        })
803      })
804      .collect();
805    let workers: std::collections::HashSet<_> = callers
806      .into_iter()
807      .map(|c| c.join().expect("a caller"))
808      .collect();
809    assert_eq!(workers.len(), calls, "the calls ran in parallel");
810    assert!(
811      idle_workers().workers.len() <= cap,
812      "more than {cap} idle workers"
813    );
814    // The parked workers may time out meanwhile, which only lowers the count.
815    assert!(
816      eventually(5, || Arc::strong_count(&mark) - 1 <= cap),
817      "{} workers alive, cap {cap}",
818      Arc::strong_count(&mark) - 1
819    );
820  }
821
822  /// A worker whose job panics (after a conversion) empties its engine before it exits: 50 panicking calls leave the
823  /// host's resident set within 128 MiB of where it was. Without the shrink each exited worker left its reset engine
824  /// (36.5 MB of heap, ~13.7 MB of it resident: ~600 MiB over 45 calls). Where the platform reports RSS.
825  #[test]
826  fn panicking_calls_do_not_grow_the_host() {
827    let _pool = pool_to_myself();
828    let panic_once = || {
829      let err = on_worker::<()>(|| {
830        assert!(xml_job(DOC)?.contains("Hello"));
831        panic!("a panicking job")
832      })
833      .expect_err("a panic is an Err");
834      assert!(err.contains("a panicking job"), "{err}");
835    };
836    (0..5).for_each(|_| panic_once());
837    let before = rss_kb_if_alone("panicking_calls_do_not_grow_the_host");
838    (5..50).for_each(|_| panic_once());
839    if let (Some(before), Some(after)) = (before, latexml_core::watchdog::process_rss_kb()) {
840      assert!(
841        after.saturating_sub(before) < 128 * 1024,
842        "RSS grew {} KiB over 45 panicking calls",
843        after.saturating_sub(before)
844      );
845    }
846  }
847
848  #[test]
849  fn worker_panic_returns_err_instead_of_crashing_caller() {
850    let _pool = pool_to_myself();
851    let err =
852      on_worker::<()>(|| panic!("boom in worker")).expect_err("worker panic should surface as Err");
853    assert!(
854      err.contains("latexml worker thread panicked: boom in worker"),
855      "unexpected panic error: {err}"
856    );
857  }
858
859  #[test]
860  fn core_failure_preserves_conversion_log() {
861    let response = ConversionResponse {
862      result:       None,
863      log:          "Fatal:foo:bar detailed diagnostic".to_string(),
864      status:       "Fatal".to_string(),
865      status_code:  3,
866      handoff_file: None,
867    };
868    let err = core_result_xml(response, "conversion failed before post-processing")
869      .expect_err("missing XML is an Err");
870    assert!(
871      err.contains("conversion failed before post-processing"),
872      "{err}"
873    );
874    assert!(err.contains("Fatal:foo:bar detailed diagnostic"), "{err}");
875  }
876}