Skip to main content

latexml/
post.rs

1//! Post-processing pipeline API.
2//!
3//! Provides a public interface to the LaTeXML post-processing pipeline
4//! (Scan → Bibliography → CrossRef → Graphics → Split → MathML → XSLT → HTML5 fixups).
5//! Used by both the `latexml_oxide` binary and the `cortex_worker` binary.
6
7use std::sync::LazyLock;
8
9use latexml_core::{
10  Info, Warn,
11  common::error::{emit_error, emit_fatal, note_progress},
12  s,
13  telemetry::{self, Phase},
14};
15use latexml_post::{
16  document::{PostDocument, PostDocumentOptions},
17  object_db::ObjectDB,
18  processor::Processor,
19};
20
21// Process-once cached env var (see WISDOM #56 — getenv hot-path race).
22static POST_AUDIT: LazyLock<bool> = LazyLock::new(|| std::env::var("LATEXML_POST_AUDIT").is_ok());
23
24/// Start an audit timer when `LATEXML_POST_AUDIT` is set. Module-level (not a
25/// closure) so [`render_spilled_page`] — shared by the serial driver and the
26/// parallel render worker — can use the identical instrumentation.
27fn audit_start(name: &str) -> Option<(String, std::time::Instant)> {
28  if *POST_AUDIT {
29    Some((name.to_string(), std::time::Instant::now()))
30  } else {
31    None
32  }
33}
34
35/// Report an audit timer started by [`audit_start`] (no-op when audit is off).
36fn audit_end(started: Option<(String, std::time::Instant)>) {
37  if let Some((name, t0)) = started {
38    let ms = t0.elapsed().as_millis();
39    Info!("audit", "phase", s!("{} took {}ms", name, ms));
40  }
41}
42
43/// Options for the post-processing pipeline.
44pub struct PostOptions<'a> {
45  pub pmml:                      bool,
46  pub cmml:                      bool,
47  pub keep_xmath:                bool,
48  pub stylesheet:                Option<&'a str>,
49  pub destination:               Option<&'a str>,
50  /// Base directory of the original LaTeX source (`--sourcedirectory`; Perl
51  /// Config.pm L147, passed to Post as `sourceDirectory` in LaTeXML.pm L429).
52  /// Used to locate graphics/resources the post-phase copies. When `None`,
53  /// the caller defaults it to the source file's own directory.
54  pub source_directory:          Option<&'a str>,
55  /// Root directory of the generated site (`--sitedirectory`; Perl Config.pm
56  /// L146, passed to Post as `siteDirectory` in LaTeXML.pm L430). Establishes
57  /// the base against which cross-document/resource URLs are made relative.
58  /// When `None`, Post defaults it to the destination's directory (Perl
59  /// Config.pm L466-469; `document.rs` mirrors that fallback).
60  pub site_directory:            Option<&'a str>,
61  /// Extra resource search paths (the `--path` flag): directories searched
62  /// for `--css`/`--javascript` files (and other post resources) to copy into
63  /// the destination, in addition to the document's own paths, the current
64  /// directory, and the binary's embedded resource table.
65  pub search_paths:              &'a [String],
66  /// Link and copy the bundled CSS/JS resources (Perl `defaultresources`, Config.pm:120; `--nodefaultresources`
67  /// clears it). The XSLT step receives its negation as `no_resources`, as LaTeXML.pm:584 hands `noresources`; a
68  /// remote stylesheet a binding requires (`https://…`) is linked either way (OD #1249).
69  pub default_resources:         bool,
70  pub css_files:                 &'a [String],
71  pub js_files:                  &'a [String],
72  pub noinvisibletimes:          bool,
73  /// Remap styled alphanumerics to Unicode Plane-1 (Perl `--plane1`, default on).
74  pub plane1:                    bool,
75  /// Remap only the poorly-supported variants, to their simpler form
76  /// (Perl `--hackplane1`); implies `plane1`.
77  pub hackplane1:                bool,
78  pub mathtex:                   bool,
79  /// Add a UnicodeMath annotation to the parallel markup (Perl `--unicodemath`,
80  /// Config.pm L113); with no MathML format requested, UnicodeMath is the only one.
81  pub unicodemath:               bool,
82  /// Cross-reference URL style (Perl `--urlstyle`; `CrossRef::generateURL`).
83  /// Defaults to [`UrlStyle::File`](latexml_post::crossref::UrlStyle::File) at
84  /// every non-CLI construction site (the binary threads the parsed `--urlstyle`
85  /// value here).
86  pub url_style:                 latexml_post::crossref::UrlStyle,
87  /// The navigation TOC style, `context` or `normal` (Perl `--navigationtoc`, lowercased and checked by the
88  /// caller; `none` is `None`, Config.pm L472-480).
89  pub navigationtoc:             Option<&'a str>,
90  /// Serialize the pages as HTML (Perl `is_html`, Config.pm L436: the format is `html*`), else as XML. `None`: a
91  /// caller naming only a built-in sheet, whose name says it (`LaTeXML-html5.xsl`).
92  pub is_html:                   Option<bool>,
93  pub schemadocs:                bool,
94  pub split:                     bool,
95  pub split_xpath:               Option<String>,
96  pub split_naming:              Option<&'a str>,
97  pub xslt_parameters:           &'a [String],
98  /// If > 0, try the vector-SVG converters (mutool → pdftocairo) for PDF
99  /// graphics smaller than this many KB (vector-preservation path). Fall
100  /// back to the raster ImageMagick `convert`/`gs` → PNG path on failure
101  /// or timeout. Tracks upstream brucemiller/LaTeXML#902.
102  pub graphics_svg_threshold_kb: u32,
103  /// Convert `\includegraphics` figures to web images (Perl `graphicimages!`
104  /// → `dographics`, default on). When `false` (`--nographicimages`) the
105  /// Graphics post-phase is skipped entirely: the output keeps the raw
106  /// `<ltx:graphics>` references untouched — useful for faster runs or hosts
107  /// without the image tools.
108  pub graphicimages:             bool,
109  /// Timestamp string embedded in the generated page (Perl `--timestamp`,
110  /// XSLT `TIMESTAMP` param). `None` → no timestamp emitted (the deterministic
111  /// default; Perl instead defaults to the current time). Perl's
112  /// `--timestamp=0` "omit" case is normalized to `None` by the caller.
113  pub timestamp:                 Option<&'a str>,
114  /// Favicon resource for the generated site (Perl `--icon`, XSLT `ICON`
115  /// param): emitted as a `<link rel="icon">` and copied to the destination.
116  pub icon:                      Option<&'a str>,
117  /// Output extraction mode (Perl `LaTeXML::Util::Pack::whatsout`).
118  /// `Document` (default) → serialize the full post-processed
119  /// document; `Fragment` → embeddable HTML snippet via
120  /// `latexml_post::extract::get_embeddable`; `Math` → math subtree
121  /// via `get_math`. Applied to each `PostDocument` in the final
122  /// serialization loop.
123  pub whatsout:                  latexml_post::extract::Whatsout,
124  /// Keep the destination's cache (Perl's document cache, `LaTeXML-oxide.cache`) in memory, writing no file (Perl's
125  /// `nocache`, `Post.pm` L678): the cortex worker, whose every paper gets a fresh directory that is packed.
126  pub nocache:                   bool,
127}
128
129impl Default for PostOptions<'_> {
130  fn default() -> Self {
131    Self {
132      pmml:                      false,
133      cmml:                      false,
134      keep_xmath:                false,
135      stylesheet:                None,
136      destination:               None,
137      source_directory:          None,
138      site_directory:            None,
139      search_paths:              &[],
140      default_resources:         true,
141      css_files:                 &[],
142      js_files:                  &[],
143      noinvisibletimes:          false,
144      plane1:                    true,
145      hackplane1:                false,
146      mathtex:                   false,
147      unicodemath:               false,
148      url_style:                 latexml_post::crossref::UrlStyle::File,
149      navigationtoc:             None,
150      is_html:                   None,
151      schemadocs:                false,
152      split:                     false,
153      split_xpath:               None,
154      split_naming:              None,
155      xslt_parameters:           &[],
156      graphics_svg_threshold_kb: 0,
157      graphicimages:             true,
158      timestamp:                 None,
159      icon:                      None,
160      whatsout:                  latexml_post::extract::Whatsout::Document,
161      nocache:                   false,
162    }
163  }
164}
165
166thread_local! {
167  /// One-shot CLI flag: release dead core TeX engine state on this thread right
168  /// after `MakeBibliography` finishes (before `parallel_render` sizes the
169  /// worker fleet and before render phases). Armed only by the one-shot
170  /// `latexml_oxide` binary so persistent workers (`cortex_worker`, LSP, library
171  /// API) never tear down their thread-local engine/arena.
172  static RELEASE_CORE_AFTER_BIB: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
173}
174
175/// RAII guard returned by [`arm_core_release_after_bib`] that clears the flag on
176/// drop even if post-processing returns early before `MakeBibliography`.
177pub struct CoreReleaseAfterBibGuard;
178
179impl Drop for CoreReleaseAfterBibGuard {
180  fn drop(&mut self) { RELEASE_CORE_AFTER_BIB.with(|f| f.set(false)); }
181}
182
183/// Arm one-shot teardown of dead core TeX engine state (`STATE`, `STOMACH`,
184/// `GULLET`, `StringInterner`, and per-conversion caches) on the current thread
185/// right after `MakeBibliography` completes in `run_post_processing_*`.
186///
187/// Only call this from a one-shot CLI process whose thread will not re-enter
188/// the TeX engine afterward (see [`latexml_core::release_core_state_for_post`]).
189pub fn arm_core_release_after_bib() -> CoreReleaseAfterBibGuard {
190  RELEASE_CORE_AFTER_BIB.with(|f| f.set(true));
191  CoreReleaseAfterBibGuard
192}
193
194/// The requested math formats as the post chain's one math processor: a primary with
195/// its parallel secondaries (Perl `LaTeXML.pm` L504-556, order per OXIDIZED_DESIGN
196/// #1093), shared by the in-process renderer and the page-render workers.
197#[derive(Clone, Copy)]
198pub(crate) struct MathFormats {
199  pub pmml:            bool,
200  pub cmml:            bool,
201  pub unicodemath:     bool,
202  pub keep_xmath:      bool,
203  pub invisible_times: bool,
204  pub plane1:          bool,
205  pub hackplane1:      bool,
206  pub mathtex:         bool,
207  pub intent_literal:  bool,
208}
209
210impl MathFormats {
211  pub(crate) fn processor(self) -> Option<Box<dyn Processor>> {
212    use latexml_post::{math_processor::MathProcessor, mathml::MathML, unicode_math::UnicodeMath};
213    let content = || {
214      MathML::new_content()
215        .with_keep_xmath(self.keep_xmath)
216        .with_invisible_times(self.invisible_times)
217        .with_plane1(self.plane1, self.hackplane1)
218    };
219    let unicode = || UnicodeMath::new().with_keep_xmath(self.keep_xmath);
220    let unicode_secondary = || -> Option<Box<dyn MathProcessor>> {
221      self
222        .unicodemath
223        .then(|| Box::new(unicode().secondary()) as _)
224    };
225    if self.pmml {
226      let mut secondaries: Vec<Box<dyn MathProcessor>> = Vec::new();
227      if self.cmml {
228        secondaries.push(Box::new(content().secondary()));
229      }
230      secondaries.extend(unicode_secondary());
231      Some(Box::new(
232        MathML::new_presentation()
233          .with_keep_xmath(self.keep_xmath)
234          .with_invisible_times(self.invisible_times)
235          .with_plane1(self.plane1, self.hackplane1)
236          .with_mathtex(self.mathtex)
237          .with_intent_literal(self.intent_literal)
238          .with_secondaries(secondaries),
239      ))
240    } else if self.cmml {
241      Some(Box::new(
242        content().with_secondaries(unicode_secondary().into_iter().collect()),
243      ))
244    } else if self.unicodemath {
245      Some(Box::new(unicode()))
246    } else {
247      None
248    }
249  }
250}
251
252/// The built-in XSLT stylesheet for an output format (Perl `Config.pm` L543-551), as the
253/// `embed:///` name served from the binary, never a copy on disk (#806). Returns `None` for a
254/// format with no default (e.g. `xml`), so a caller keeps `--stylesheet` / no post.
255///
256/// SINGLE SOURCE OF TRUTH shared by the CLI (`bin/latexml_oxide.rs` picks
257/// `effective_stylesheet` when `--stylesheet` is unset) and the library
258/// (`crate::api::convert_to_html`), so the two can never disagree on which
259/// sheet an `html5`/`xhtml`/`epub` job gets.
260pub fn default_stylesheet(format: Option<&str>) -> Option<&'static str> {
261  match format {
262    // Config.pm L436: `html` is html5.
263    Some("html5") | Some("html") => Some("embed:///LaTeXML-html5.xsl"),
264    Some("xhtml") => Some("embed:///LaTeXML-xhtml.xsl"),
265    Some("epub") | Some("epub3") => Some("embed:///LaTeXML-epub3.xsl"),
266    _ => None,
267  }
268}
269
270/// Split one `--xsltparameter` into `(name, value)`: Perl's `name:value` (LaTeXML.pm L575
271/// `/^\s*(\w+)\s*:\s*(.*)$/`, bin/latexmlpost L354) first, else our `name=value`; `None` when
272/// it is neither (#803).
273pub fn parse_xslt_parameter(param: &str) -> Option<(String, String)> {
274  let trimmed = param.trim_start();
275  let name_len = trimmed
276    .find(|c: char| !(c.is_alphanumeric() || c == '_'))
277    .unwrap_or(trimmed.len());
278  if name_len > 0
279    && let Some(value) = trimmed[name_len..].trim_start().strip_prefix(':')
280  {
281    return Some((
282      trimmed[..name_len].to_string(),
283      value.trim_start().to_string(),
284    ));
285  }
286  match param.split_once('=') {
287    Some((name, value)) if !name.is_empty() => Some((name.to_string(), value.to_string())),
288    _ => None,
289  }
290}
291
292/// Emit a post-processing error: capture it into the active log buffer (so it
293/// reaches `cortex.log`) AND bump the Error counter so `Status:conversion`
294/// reflects post-phase failures (Perl `LaTeXML.pm` L633: `max(core, post)`).
295///
296/// Deliberately NOT the `Error!` macro: that expands to a too-many-errors
297/// `Fatal!(…)` → `return Err(error::Error)`, which only typechecks inside the
298/// digester's `Result<_, error::Error>` functions. The post-processing entry
299/// points return `String`/`Result<_, ()>`, so we log+count directly with no
300/// control-flow side effect.
301fn post_error(object: &str, message: &str) { emit_error("post", object, message); }
302
303/// Result of [`run_post_processing_logged`]: the serialized HTML plus the
304/// post-phase log text and status code, mirroring Perl `LaTeXML.pm`'s
305/// `convert_post`, which flushes the log AFTER post and folds the post status
306/// into the final `max(core, post)` verdict (L631-634).
307pub struct PostOutcome {
308  /// Serialized post-processed output (same value as [`run_post_processing`]).
309  pub html:        String,
310  /// Log text captured during the post phase only — Graphics/MathML/XSLT
311  /// `Info!`/`Warn!`/`post_error` lines. Append to the core conversion log.
312  pub log:         String,
313  /// Status code read from the shared REPORT counter AFTER post. Because the
314  /// counter is NOT reset between core and post, this is already the combined
315  /// core+post code; callers still `max()` it with the core code as a
316  /// belt-and-suspenders guard for paths that force a fatal outside REPORT
317  /// (e.g. a `catch_unwind`-trapped panic).
318  pub status_code: usize,
319  /// The pages written, in the order the post pipeline produced them — Split's (the root, then each page
320  /// before its children), the order Perl's `@docs` reaches `Manifest::Epub::process` in for the EPUB spine.
321  pub pages:       Vec<String>,
322}
323
324/// Run post-processing while capturing its log into a fresh thread-local
325/// LOG_BUFFER. `Converter::convert()` already flushed the *core* log into its
326/// own response, leaving the buffer unbound — so without re-binding here every
327/// post-phase `Info!`/`Warn!`/`post_error` (incl. a silent EPS→PNG failure)
328/// reaches stderr only and never the persisted `--log`/`cortex.log`. Perl's
329/// single `flush_log()` after `convert_post` sweeps up the post log for ALL
330/// consumers; this is the Rust equivalent, shared by the `latexml_oxide` and
331/// `cortex_worker` binaries so their logs reach parity. See SYNC_STATUS task 5.
332pub fn run_post_processing_logged(xml: &str, opts: &PostOptions) -> PostOutcome {
333  run_post_processing_impl_logged(PostInput::Xml(xml), opts)
334}
335
336/// File-input variant of [`run_post_processing_logged`]: parses the XML from
337/// disk via libxml2's streaming reader rather than from an in-memory `String`.
338/// Used for already-converted `.xml` inputs, where slurping the file would keep
339/// a whole extra copy of a multi-hundred-MB document resident alongside the DOM.
340pub fn run_post_processing_from_file_logged(path: &str, opts: &PostOptions) -> PostOutcome {
341  run_post_processing_impl_logged(PostInput::File(path), opts)
342}
343
344fn run_post_processing_impl_logged(input: PostInput, opts: &PostOptions) -> PostOutcome {
345  latexml_core::util::logger::bind_log();
346  // An XML input has no core session to log what the front end held for it (`warn_at_session_start`).
347  latexml_core::common::error::log_session_warnings();
348  let mut pages = Vec::new();
349  let html = run_post_processing_impl(input, opts, &mut pages);
350  let log = latexml_core::util::logger::flush_log();
351  let status_code = latexml_core::common::error::get_status_code();
352  PostOutcome { html, log, status_code, pages }
353}
354
355/// Where the post-pipeline reads its already-converted LaTeXML XML from.
356#[derive(Clone, Copy)]
357enum PostInput<'a> {
358  /// XML already resident in memory (the TeX→XML conversion result). The common
359  /// path — the 2.8M-doc arXiv fleet and every TeX conversion feed this.
360  Xml(&'a str),
361  /// A path to an XML file, parsed via libxml2's streaming file reader
362  /// (`xmlReadIO`). Avoids vivifying a very large document as a Rust `String`
363  /// on top of the ~11× DOM it becomes.
364  File(&'a str),
365}
366
367/// Run the post-processing pipeline on in-memory XML output.
368///
369/// Executes: Split → Scan → MakeBibliography → CrossRef → Graphics → MathML → XSLT → HTML5 fixups.
370pub fn run_post_processing(xml: &str, opts: &PostOptions) -> String {
371  run_post_processing_impl(PostInput::Xml(xml), opts, &mut Vec::new())
372}
373
374/// File-input variant of [`run_post_processing`].
375pub fn run_post_processing_from_file(path: &str, opts: &PostOptions) -> String {
376  run_post_processing_impl(PostInput::File(path), opts, &mut Vec::new())
377}
378
379/// The in-memory parse ceiling: libxml2's `xmlReadMemory` takes the buffer
380/// length as a C `int`, so a handoff string of `i32::MAX` bytes or more
381/// CANNOT be parsed from memory — it fails with "Document too large for
382/// i32". First witness to cross it: the 131 MB book's 2.68 GB core XML,
383/// single-invocation `.tex → .htm` (laptop UAT 2026-07-31; the streamed
384/// assembly exists only as serialized text, so post must re-parse it).
385/// Above the ceiling the handoff spills to a temp file beside the
386/// destination and takes the `PostInput::File` arm — the streaming-reader
387/// path that already parses this very document in the two-invocation flow.
388///
389/// Env-overridable for tests only (`LATEXML_POST_MEM_PARSE_LIMIT`): a real
390/// 2-GiB-plus fixture is not something CI can allocate, so the guard test
391/// drives the spill path with a tiny limit instead.
392fn post_mem_parse_limit() -> usize {
393  std::env::var("LATEXML_POST_MEM_PARSE_LIMIT")
394    .ok()
395    .and_then(|v| v.parse::<usize>().ok())
396    .unwrap_or(i32::MAX as usize)
397}
398
399/// The size at which a *split* run prefers the streaming split front-end
400/// (`latexml_post::stream_split`) over the whole-DOM parse. Default 0: every
401/// split run streams, since its pages are byte-identical to the whole-DOM
402/// split's (guard: `118_streaming_split_parity`) while its peak is one content
403/// subtree, not the whole DOM (Nasser's 2,400-problem book, 337 MB of HTML in
404/// 9,713 pages, with the split run's core watermark: 3.8 → 1.35 GB peak RSS).
405/// Calibration/test override: `LATEXML_POST_STREAM_THRESHOLD` (bytes).
406fn stream_split_threshold() -> u64 {
407  std::env::var("LATEXML_POST_STREAM_THRESHOLD")
408    .ok()
409    .and_then(|v| v.parse::<u64>().ok())
410    .unwrap_or(0)
411}
412
413/// Below this size a failed streaming split falls back to the whole-DOM path,
414/// the pre-default behaviour (a 614 MB core XML parsed to ~16 GB of DOM);
415/// above it the fallback is the OOM the streaming front-end exists to avoid
416/// (a 2.68 GB core XML OOM'd a 31 GB host), so the failure stays an Error.
417const STREAM_SPLIT_DOM_FALLBACK_LIMIT: u64 = 1 << 30;
418
419/// Gate for the streaming split on an input of `len` bytes:
420/// `LATEXML_POST_STREAM_SPLIT=1` forces it on (any size), `=0` disables it,
421/// unset engages it at or above [`stream_split_threshold`] (by default every
422/// split run).
423fn stream_split_gate(len: u64) -> bool {
424  match std::env::var("LATEXML_POST_STREAM_SPLIT").as_deref() {
425    Ok("0") => false,
426    Ok(_) => true,
427    Err(_) => len >= stream_split_threshold(),
428  }
429}
430
431/// Will a run with `opts` over an input of `len` bytes take the streaming split
432/// front-end? The front-end's own preconditions (a destination, a union it can
433/// evaluate) and the gate. An in-memory handoff that answers yes is staged to a
434/// file first: the streaming reader parses only files.
435fn takes_streaming_split(opts: &PostOptions, len: u64) -> bool {
436  opts.split
437    && opts.destination.is_some()
438    && opts
439      .split_xpath
440      .as_deref()
441      .is_some_and(latexml_post::stream_split::supports_union)
442    && stream_split_gate(len)
443}
444
445/// Test override: `LATEXML_POST_SPILL_PAGE=1` stages an unsplit page on disk as
446/// a split one is, so the parity guard can compare the two paths.
447fn spill_every_page() -> bool {
448  std::env::var_os("LATEXML_POST_SPILL_PAGE").is_some_and(|v| v == "1")
449}
450
451/// `--splitnaming` → `SplitNaming`, shared by the DOM and streaming split
452/// front-ends so the two cannot disagree.
453fn resolve_split_naming(split_naming: Option<&str>) -> latexml_post::split::SplitNaming {
454  use latexml_post::split::SplitNaming;
455  match split_naming {
456    Some("id") | None => SplitNaming::Id,
457    Some("idrelative") => SplitNaming::IdRelative,
458    Some("label") => SplitNaming::Label,
459    Some("labelrelative") => SplitNaming::LabelRelative,
460    Some(other) => {
461      Warn!(
462        "post",
463        "split",
464        format!("Unknown splitnaming '{other}', using 'id'")
465      );
466      SplitNaming::Id
467    },
468  }
469}
470
471/// Perl's `labelids` for Scan: `--splitnaming=label` or `labelrelative` also takes fragment ids from labels
472/// (`LaTeXML.pm` L462, `latexmlpost` L422). The same two values `resolve_split_naming` accepts, so an
473/// unknown value names pages and fragments by id alike.
474fn label_ids(split_naming: Option<&str>) -> bool {
475  matches!(split_naming, Some("label" | "labelrelative"))
476}
477
478/// The destination's directory for the staged handoff and the page spill: "."
479/// for a bare file name (`--dest=index.html`), whose empty parent would
480/// otherwise send them to the system temp dir (often a RAM-backed tmpfs).
481fn staging_dir_of(destination: Option<&str>) -> Option<std::path::PathBuf> {
482  let parent = std::path::Path::new(destination?).parent()?;
483  Some(if parent.as_os_str().is_empty() {
484    std::path::PathBuf::from(".")
485  } else {
486    parent.to_path_buf()
487  })
488}
489
490/// Destination directory for a page pathname (empty parent → ".", mirroring
491/// `PostDocument`'s internal derivation).
492fn destination_directory_of(destination: &str) -> Option<String> {
493  std::path::Path::new(destination).parent().map(|p| {
494    let s = p.to_string_lossy();
495    if s.is_empty() {
496      ".".to_string()
497    } else {
498      s.into_owned()
499    }
500  })
501}
502
503/// The two placeholder probes recorded per page WHILE it is parsed, so the
504/// ObjectDB-baton sweeps (MakeIndex, MakeBibliography) re-read only the
505/// handful of pages that actually carry work.
506fn page_placeholder_probes(d: &PostDocument) -> (bool, bool) {
507  (
508    !d.findnodes(latexml_post::make_index::PLACEHOLDERS)
509      .is_empty(),
510    !d.findnodes("//ltx:bibliography").is_empty(),
511  )
512}
513
514/// Everything the shared pipeline tail (MakeIndex → sweeps → page-major
515/// render) needs from a front-end: spilled pages plus the scanned ObjectDB.
516/// Produced by BOTH front-ends — the streaming split and the whole-DOM
517/// parse+Split+Scan.
518struct PostFront {
519  spilled_pages:  Vec<SpilledPage>,
520  db:             ObjectDB,
521  intent_literal: bool,
522}
523
524/// Attempt the streaming split front-end (`latexml_post::stream_split`).
525///
526/// `Ok(None)` = not applicable (the union matched no pages, or the stream
527/// could not be split faithfully — already reported) → the caller falls back
528/// to the whole-DOM pipeline. `Err(())` = a hard failure after pages were in
529/// flight (I/O, resource ceiling), already reported via `post_error`; the
530/// caller bails out. With `dom_fallback` (an input below
531/// [`STREAM_SPLIT_DOM_FALLBACK_LIMIT`]) a failed stream is `Ok(None)` instead,
532/// reported at Info.
533fn try_streaming_front(
534  path: &str,
535  split_xpath: &str,
536  split_naming: Option<&str>,
537  page_opts: &PostDocumentOptions,
538  spill_dir: &std::path::Path,
539  dom_fallback: bool,
540  mut graphics: Option<&mut latexml_post::graphics::Graphics>,
541) -> Result<Option<PostFront>, ()> {
542  let naming = resolve_split_naming(split_naming);
543  telemetry::phase_enter(Phase::Split);
544  let outcome = latexml_post::stream_split::stream_split(
545    path,
546    split_xpath,
547    naming,
548    // The run's `--dest`, as `run_post_processing_inner` set it on the page options.
549    page_opts.destination.as_deref(),
550    spill_dir,
551    dom_fallback,
552  );
553  telemetry::phase_exit();
554  let outcome = match outcome {
555    Ok(Some(o)) => o,
556    Ok(None) => return Ok(None),
557    // A file the whole-DOM path parses comfortably: give it that path, as
558    // before every split run streamed.
559    Err(e) if dom_fallback => {
560      Info!(
561        "post",
562        "stream-split",
563        s!("streaming split failed ({e}); splitting the whole document instead")
564      );
565      return Ok(None);
566    },
567    Err(e) => {
568      // Fail toward flagging: the whole-DOM fallback may well OOM on an input
569      // this large, but a loud failure beats a silently wrong result — and
570      // beats the whole-DOM fallback, whose parse of a threshold-sized file
571      // is a guaranteed OOM on commodity RAM (witnessed: a mid-stream error
572      // fell back into a 2.68 GB whole-DOM parse that grew past a 26 GB
573      // ceiling with zero pages to show). The unions this front-end cannot
574      // evaluate never reach here — the caller gates on `supports_union`.
575      post_error("split", &format!("streaming split failed: {e}"));
576      return Err(());
577    },
578  };
579  // The engagement marker the parity/threshold tests assert on.
580  Info!(
581    "post",
582    "stream-split",
583    s!(
584      "streaming split engaged for '{}': {} pages",
585      path,
586      outcome.pages.len()
587    )
588  );
589  note_progress(&format!("Split into {} documents", outcome.pages.len()));
590  let intent_literal = outcome
591    .latexml_pis
592    .iter()
593    .any(|pi| pi.contains("package=\"ar5iv"));
594
595  // Pre-order Scan sweep over the spilled pages — the streaming equivalent of
596  // `run_phase(docs, Scan)` + the driver's spill loop, ONE page resident at a
597  // time. The order is semantic, not cosmetic: SITE_ROOT is taken from the
598  // first page scanned (the root page), an ancestor must be in the DB before
599  // its descendants (Scan files a page under its Split parent's entry, the
600  // page's `parent_id`, and lists it among that entry's `children`), and each
601  // parent's `children` list follows scan order — all three feed CrossRef's
602  // navigation.
603  telemetry::phase_enter(Phase::PostScan);
604  let mut scanner =
605    latexml_post::scan::Scan::new(ObjectDB::new()).with_label_ids(label_ids(split_naming));
606  let mut spilled: Vec<SpilledPage> = Vec::with_capacity(outcome.pages.len());
607  for page in &outcome.pages {
608    if let Err(e) = latexml_core::stomach::check_timeout_now() {
609      // FATAL, not Error: a scan stopped partway means the delivered site
610      // would be silently truncated (user decision 2026-08-02 — a resource
611      // stop that truncates the deliverable carries fatal severity).
612      Info!(
613        "post",
614        "stopped",
615        s!(
616          "Scan stopped after {} of {} pages",
617          spilled.len(),
618          outcome.pages.len()
619        )
620      );
621      e.log_fatal();
622      telemetry::phase_exit();
623      return Err(());
624    }
625    let path_str = page.path.to_string_lossy().into_owned();
626    let page_doc = match PostDocument::new_from_file(&path_str, page_opts.clone()) {
627      Ok(mut d) => {
628        d.destination = Some(page.destination.clone());
629        d.destination_directory = destination_directory_of(&page.destination);
630        d.parent_id = page.parent_id.clone();
631        d
632      },
633      Err(e) => {
634        post_error("post", &format!("cannot read a streamed page: {e}"));
635        telemetry::phase_exit();
636        return Err(());
637      },
638    };
639    // Scan's only page mutation: a root without an id gets
640    // `xml:id="Document"`. Detect it so the spill is refreshed (pass B
641    // re-parses pages from disk and must see what Scan registered).
642    let root_unnamed = page_doc
643      .get_document_element()
644      .and_then(|r| latexml_post::document::get_xml_id(&r))
645      .is_none();
646    let nodes = scanner.to_process(&page_doc);
647    let has_scan_nodes = !nodes.is_empty();
648    let processed = if !has_scan_nodes {
649      vec![page_doc]
650    } else {
651      match scanner.process(page_doc, nodes) {
652        Ok(p) => p,
653        Err(e) => {
654          post_error("Scan", &format!("Scan failed: {e}"));
655          telemetry::phase_exit();
656          return Err(());
657        },
658      }
659    };
660    let scan_placeholders = if has_scan_nodes {
661      scanner.last_page_placeholders()
662    } else {
663      (false, false)
664    };
665    for d in processed {
666      if root_unnamed && let Err(e) = std::fs::write(&page.path, d.to_xml_string()) {
667        post_error("post", &format!("cannot refresh a disk-staged page: {e}"));
668        telemetry::phase_exit();
669        return Err(());
670      }
671      #[cfg(debug_assertions)]
672      debug_assert_eq!(
673        scan_placeholders,
674        page_placeholder_probes(&d),
675        "Scan placeholder tracking diverged from XPath probe on {}",
676        page.destination
677      );
678      if let Some(graphics) = graphics.as_deref_mut()
679        && outcome.pages.len() > 1
680      {
681        graphics.plan_names(&d);
682      }
683      let (needs_index, needs_bib) = scan_placeholders;
684      spilled.push(SpilledPage {
685        needs_index,
686        needs_bib,
687        path: page.path.clone(),
688        destination: Some(page.destination.clone()),
689        destination_directory: destination_directory_of(&page.destination),
690        resident: None,
691      });
692      // The page's DOM drops here — one resident at a time.
693    }
694    if !spilled.is_empty() && spilled.len().is_multiple_of(crate::heap_trim::SAMPLE_PAGES) {
695      crate::heap_trim::sample();
696    }
697  }
698  telemetry::phase_exit();
699  Ok(Some(PostFront {
700    spilled_pages: spilled,
701    db: scanner.db,
702    intent_literal,
703  }))
704}
705
706/// A core handoff staged on disk for the streaming file parser, removed when
707/// dropped and on the exits that skip destructors.
708pub struct StagedHandoff {
709  path:   String,
710  _guard: latexml_core::watchdog::RemoveOnExit,
711}
712
713impl Drop for StagedHandoff {
714  fn drop(&mut self) { let _ = std::fs::remove_file(&self.path); }
715}
716
717impl StagedHandoff {
718  /// The handoff's path beside the destination ("." for a bare file name), else in the system temp dir.
719  fn at(destination: Option<&str>) -> StagedHandoff {
720    let dir = staging_dir_of(destination).unwrap_or_else(std::env::temp_dir);
721    let path = dir.join(format!("latexml-post-handoff-{}.xml", std::process::id()));
722    StagedHandoff {
723      _guard: latexml_core::watchdog::remove_on_exit(&path),
724      path:   path.to_string_lossy().into_owned(),
725    }
726  }
727
728  pub fn path(&self) -> &str { &self.path }
729}
730
731/// The reserved handoff, kept only when the core serialized into it (`ConversionResponse::handoff_file`). An
732/// unused one is dropped here, removing a file an earlier attempt wrote: a fused eager attempt's salvage, when the
733/// `--streaming` rerun on the same path ends without a document.
734pub fn used_core_handoff(
735  reserved: Option<StagedHandoff>,
736  serialized_to: Option<&str>,
737) -> Option<StagedHandoff> {
738  reserved.filter(|staged| serialized_to == Some(staged.path()))
739}
740
741/// The handoff file a split run's core result is serialized into (`Config::handoff_file`), reserved before the
742/// conversion: when the run would take the streaming split, which parses only files, the document-sized `String`
743/// would exist only to be staged (2 GiB on Nasser's whole book, issue 777). `None` when it would not.
744pub fn reserve_core_handoff(
745  split: bool,
746  destination: Option<&str>,
747  split_xpath: Option<&str>,
748) -> Option<StagedHandoff> {
749  let streams = split
750    && destination.is_some()
751    && split_xpath.is_some_and(latexml_post::stream_split::supports_union)
752    && std::env::var("LATEXML_POST_STREAM_SPLIT").as_deref() != Ok("0");
753  streams.then(|| StagedHandoff::at(destination))
754}
755
756/// The staging Info: operationally worth a line (a temp file the size of the core XML just appeared beside the
757/// destination), and the guard tests' engagement proof — without it a silently-failing spill would fall back to the
758/// memory parse and the tests would pass vacuously.
759fn note_staged(len: u64, path: &str, how: &str) {
760  let why = if len >= post_mem_parse_limit() as u64 {
761    "oversized handoff"
762  } else {
763    "streaming-split handoff"
764  };
765  latexml_core::Info!(
766    "post",
767    "spill",
768    format!("{why} ({len} bytes) staged to {path}{how}")
769  );
770}
771
772/// Should an in-memory handoff be staged to a file: past the in-memory parse
773/// ceiling (`post_mem_parse_limit`), or bound for the streaming split, which
774/// parses only files. An empty handoff stays in memory: it is post-processed
775/// against a bare `<document/>` (Perl LaTeXML.pm L330-336).
776fn handoff_needs_file(xml: &str, opts: &PostOptions) -> bool {
777  xml.len() >= post_mem_parse_limit()
778    || (!xml.trim().is_empty() && takes_streaming_split(opts, xml.len() as u64))
779}
780
781/// Write the handoff to a temp file beside the destination when there is one
782/// (writing to the destination directory is always allowed), else the system
783/// temp dir. `None` = the write failed (reported at Info): parse from memory.
784fn stage_handoff(xml: &str, opts: &PostOptions) -> Option<StagedHandoff> {
785  let staged = StagedHandoff::at(opts.destination);
786  // The destination's directory may not exist yet: the writer creates it, so
787  // create it here, where the handoff and the page spill go first.
788  let dir = std::path::Path::new(&staged.path).parent();
789  if let Err(e) = dir
790    .map_or(Ok(()), std::fs::create_dir_all)
791    .and_then(|()| std::fs::write(&staged.path, xml))
792  {
793    // (the drop removes a partial file)
794    latexml_core::Info!(
795      "post",
796      "spill",
797      format!("could not stage the core handoff to disk ({e}); parsing from memory")
798    );
799    return None;
800  }
801  note_staged(xml.len() as u64, &staged.path, "");
802  Some(staged)
803}
804
805/// [`run_post_processing_logged`] taking the core result by value: a handoff
806/// staged to disk (see `handoff_needs_file`) is dropped before post runs, so
807/// the core XML is not resident beside the post pipeline — on Nasser's
808/// 2,400-problem book a few hundred MB of the single-invocation peak.
809pub fn run_post_processing_owned_logged(xml: String, opts: &PostOptions) -> PostOutcome {
810  // Bound first: the staging Info belongs to the post log.
811  latexml_core::util::logger::bind_log();
812  latexml_core::common::error::log_session_warnings();
813  latexml_core::common::arena::take_overflow_interns();
814  let staged = if handoff_needs_file(&xml, opts) {
815    stage_handoff(&xml, opts)
816  } else {
817    None
818  };
819  let mut pages = Vec::new();
820  // Straight to the inner pipeline: a handoff whose staging failed must not
821  // be staged a second time.
822  let html = match staged {
823    Some(staged) => {
824      drop(xml);
825      let path = staged.path.clone();
826      run_post_processing_inner(PostInput::File(&path), opts, &mut pages, Some(staged))
827    },
828    None => run_post_processing_inner(PostInput::Xml(&xml), opts, &mut pages, None),
829  };
830  let log = latexml_core::util::logger::flush_log();
831  let status_code = latexml_core::common::error::get_status_code();
832  PostOutcome { html, log, status_code, pages }
833}
834
835/// [`run_post_processing_owned_logged`] for a core result the conversion serialized into `staged`
836/// ([`reserve_core_handoff`]), so no `String` of it ever existed. A file the gate keeps in memory (a test's
837/// `LATEXML_POST_STREAM_THRESHOLD` above its size) is read back and post-processed as that `String` would be.
838pub fn run_post_processing_staged_logged(staged: StagedHandoff, opts: &PostOptions) -> PostOutcome {
839  latexml_core::util::logger::bind_log();
840  latexml_core::common::error::log_session_warnings();
841  latexml_core::common::arena::take_overflow_interns();
842  let len = std::fs::metadata(&staged.path).map_or(0, |m| m.len());
843  let mut pages = Vec::new();
844  let html = if len >= post_mem_parse_limit() as u64 || takes_streaming_split(opts, len) {
845    note_staged(len, &staged.path, " by the core serializer");
846    let path = staged.path.clone();
847    run_post_processing_inner(PostInput::File(&path), opts, &mut pages, Some(staged))
848  } else {
849    match std::fs::read_to_string(&staged.path) {
850      Ok(xml) => {
851        drop(staged);
852        run_post_processing_inner(PostInput::Xml(&xml), opts, &mut pages, None)
853      },
854      // (unreadable: the file parser reports it as the failure it is)
855      Err(_) => {
856        let path = staged.path.clone();
857        run_post_processing_inner(PostInput::File(&path), opts, &mut pages, Some(staged))
858      },
859    }
860  };
861  let log = latexml_core::util::logger::flush_log();
862  let status_code = latexml_core::common::error::get_status_code();
863  PostOutcome { html, log, status_code, pages }
864}
865
866/// `written` collects the pages written, in the pipeline's order (see [`PostOutcome::pages`]).
867fn run_post_processing_impl(
868  input: PostInput,
869  opts: &PostOptions,
870  written: &mut Vec<String>,
871) -> String {
872  // A conversion entry point: the arena's overflow count starts at zero, as in `Converter::convert`.
873  latexml_core::common::arena::take_overflow_interns();
874  // An in-memory handoff past the parse ceiling, or bound for the streaming
875  // split, parses from a staged file (dropped, and so removed, once the front-end has read it); a staging
876  // failure falls through to the memory parse, whose own error reporting then
877  // names the real problem.
878  let staged = match input {
879    PostInput::Xml(xml) if handoff_needs_file(xml, opts) => stage_handoff(xml, opts),
880    _ => None,
881  };
882  let path = staged.as_ref().map(|staged| staged.path.clone());
883  let input = match path.as_deref() {
884    Some(path) => PostInput::File(path),
885    None => input,
886  };
887  run_post_processing_inner(input, opts, written, staged)
888}
889
890/// `staged`: the handoff file `input` reads, removed once a front-end has
891/// read it (the page spill then holds the document).
892fn run_post_processing_inner(
893  input: PostInput,
894  opts: &PostOptions,
895  written: &mut Vec<String>,
896  staged: Option<StagedHandoff>,
897) -> String {
898  let PostOptions {
899    pmml,
900    cmml,
901    keep_xmath,
902    stylesheet,
903    destination,
904    source_directory,
905    site_directory,
906    search_paths,
907    default_resources,
908    css_files,
909    js_files,
910    noinvisibletimes,
911    plane1,
912    hackplane1,
913    mathtex,
914    unicodemath,
915    url_style,
916    navigationtoc,
917    is_html,
918    schemadocs,
919    split,
920    ref split_xpath,
921    split_naming,
922    xslt_parameters,
923    graphics_svg_threshold_kb,
924    graphicimages,
925    timestamp,
926    icon,
927    whatsout,
928    nocache,
929  } = *opts;
930  // Perl `Common/Config.pm` L395-397: the destination and the source and site directories are canonical before post
931  // reads them, so the root's spelling is its split pages' (`./out/index.html` is `out/index.html`, issue 1006).
932  let canonical = |path: Option<&str>| path.map(latexml_core::util::pathname::canonical);
933  let (destination, source_directory, site_directory) = (
934    canonical(destination),
935    canonical(source_directory),
936    canonical(site_directory),
937  );
938  let (destination, source_directory, site_directory) = (
939    destination.as_deref(),
940    source_directory.as_deref(),
941    site_directory.as_deref(),
942  );
943
944  // Perl's document cache, shared by the document and every page of it (`Post.pm` L687-690), closed (its side files
945  // checkpointed away) when post ends, before anything is packed.
946  let run_cache = latexml_post::document::DocCache::new(nocache);
947  let _close_cache = CloseCache(run_cache.clone());
948  let mut doc_opts = PostDocumentOptions {
949    nocache,
950    cache: Some(run_cache.clone()),
951    ..Default::default()
952  };
953  if let Some(dest) = destination {
954    doc_opts.destination = Some(dest.to_string());
955  }
956  if let Some(src_dir) = source_directory {
957    doc_opts.source_directory = Some(src_dir.to_string());
958    let mut sp = doc_opts.searchpaths.take().unwrap_or_default();
959    sp.push(src_dir.to_string());
960    doc_opts.searchpaths = Some(sp);
961  }
962  // --sitedirectory (Perl LaTeXML.pm L430 `siteDirectory`): the site root for
963  // relativizing cross-document/resource URLs. When unset, `PostDocument::new`
964  // falls back to the destination's directory (document.rs, Perl Config.pm L466).
965  if let Some(site_dir) = site_directory {
966    doc_opts.site_directory = Some(site_dir.to_string());
967    // Perl `Post.pm` L698-706 (`Post::Document::new_internal`): the destination must lie within the site directory,
968    // as written (Perl) or with both sides resolved. A relative destination is completed from the working directory,
969    // which the OS reports resolved (macOS `/var` is `/private/var`), so a site directory named through a link fails
970    // the lexical test alone (KNOWN_PERL_ERRORS #1334); a destination named inside the site through a link that
971    // leads out passes it, and is written at its lexical path (batchfix995).
972    if let Some(dest) = destination {
973      let dest_dir = std::path::Path::new(dest)
974        .parent()
975        .map(|dir| dir.to_string_lossy().into_owned())
976        .filter(|dir| !dir.is_empty())
977        .unwrap_or_else(|| ".".to_string());
978      use latexml_core::util::pathname::{is_contained, resolved};
979      let inside = is_contained(&dest_dir, site_dir).is_some()
980        || is_contained(&resolved(&dest_dir), &resolved(site_dir)).is_some();
981      if !inside {
982        emit_fatal(
983          "unexpected",
984          &dest_dir,
985          &format!(
986            "The destination directory ({dest_dir}) must be within the siteDirectory ({site_dir})"
987          ),
988        );
989        return String::new();
990      }
991    }
992  }
993  // `raw_xml` holds the in-memory serialization — `Some` only for `Xml` input.
994  // `File` input streams from disk and never holds it, so `raw_xml` is `None`
995  // and the three raw-string features (empty-doc substitution, SVG extraction,
996  // ar5iv sniff) plus the on-failure echo are re-derived from the parsed doc.
997  //
998  // Perl LaTeXML.pm L330-336: an empty core result (e.g. after a Fatal) is still
999  // post-processed against a bare <document/> root ("important for utility
1000  // features such as packing .zip archives"). Mirror that for empty in-memory
1001  // input; a File is never empty (an empty file simply errors on parse below).
1002  let raw_xml: Option<&str> = match input {
1003    PostInput::Xml(xml) if xml.trim().is_empty() => Some("<document/>"),
1004    PostInput::Xml(xml) => Some(xml),
1005    PostInput::File(_) => None,
1006  };
1007  // Best-effort output when a phase bails: echo the original XML for in-memory
1008  // input; for File input the source is on disk (and a failure here is itself
1009  // the case we are hardening against), so return empty and rely on the logged
1010  // Error + status code.
1011  let fallback = || raw_xml.map(str::to_string).unwrap_or_default();
1012
1013  // Pass B re-parses each spilled page and must see the SAME searchpaths and
1014  // site directory as this parse does.
1015  let page_opts = doc_opts.clone();
1016
1017  // The per-page spill directory, created up front: BOTH front-ends (the
1018  // streaming split and the whole-DOM parse) write their pages into it.
1019  // Beside the destination when there is one — the same volume the output
1020  // lands on (and NOT the system temp dir, which can be a RAM-backed tmpfs:
1021  // a 40k-page document spills the whole core XML's worth of pages here).
1022  let mut spill_builder = tempfile::Builder::new();
1023  spill_builder.prefix(".latexml-post-pages-");
1024  let page_spill = match staging_dir_of(destination).filter(|p| p.is_dir()) {
1025    Some(dest_dir) => spill_builder.tempdir_in(dest_dir),
1026    None => spill_builder.tempdir(),
1027  };
1028  let page_spill = match page_spill {
1029    Ok(dir) => dir,
1030    Err(e) => {
1031      post_error(
1032        "post",
1033        &format!("cannot create the page staging directory: {e}"),
1034      );
1035      return fallback();
1036    },
1037  };
1038  // A watchdog or allocation-failure exit skips the `TempDir`'s drop.
1039  let _spill_on_exit = latexml_core::watchdog::remove_on_exit(page_spill.path());
1040
1041  // ---- Front-end selection --------------------------------------------------
1042  //
1043  // For a *file* input that will be split and is past the streaming threshold
1044  // (or force-enabled), the streaming split front-end produces the spilled
1045  // pages + scanned ObjectDB without ever parsing the whole document — the
1046  // whole-DOM parse of a 2.68 GB core XML needs ~30+ GB and OOM'd a 31 GB
1047  // host before Split ran (laptop UAT 2026-07-31). Everything downstream of
1048  // this block is shared between the two front-ends.
1049  // Phase 5: Graphics (Perl `graphicimages!` → `dographics`, default on).
1050  // `--nographicimages` skips the phase wholesale, leaving the raw
1051  // `<ltx:graphics>` references in the output untouched. Made here: the pages of a split name their images as they
1052  // are spilled (`Graphics::plan_names`, issue 995).
1053  let mut graphics_proc = graphicimages.then(|| {
1054    latexml_post::graphics::Graphics::new(None, true)
1055      .with_svg_threshold_kb(graphics_svg_threshold_kb)
1056      .with_doc_cache(run_cache.clone())
1057  });
1058  let file_len = |path: &str| std::fs::metadata(path).map(|m| m.len()).ok();
1059  let streamed: Option<PostFront> = if let PostInput::File(path) = input
1060    && let Some(len) = file_len(path)
1061    && takes_streaming_split(opts, len)
1062    && let Some(xpath) = split_xpath.as_deref()
1063  {
1064    match try_streaming_front(
1065      path,
1066      xpath,
1067      split_naming,
1068      &page_opts,
1069      page_spill.path(),
1070      len < STREAM_SPLIT_DOM_FALLBACK_LIMIT,
1071      graphics_proc.as_mut(),
1072    ) {
1073      Ok(front) => front,
1074      Err(()) => return fallback(),
1075    }
1076  } else {
1077    None
1078  };
1079
1080  let front = if let Some(front) = streamed {
1081    // The pages are spilled: the staged handoff is read no more.
1082    drop(staged);
1083    front
1084  } else {
1085    // ==== Whole-DOM front-end (the pre-existing pipeline, indentation kept) ====
1086    telemetry::phase_enter(Phase::PostXmlParse);
1087    let t_parse = audit_start("PostDocument parse");
1088    let parsed = match input {
1089      // `raw_xml` is `Some` for `Xml` input (the two arms above), so the default
1090      // is dead — kept only to avoid an `unwrap`.
1091      PostInput::Xml(_) => {
1092        PostDocument::new_from_string(raw_xml.unwrap_or("<document/>"), doc_opts)
1093      },
1094      PostInput::File(path) => PostDocument::new_from_file(path, doc_opts),
1095    };
1096    let doc = match parsed {
1097      Ok(d) => d,
1098      Err(e) => {
1099        post_error("parse", &format!("failed to parse XML: {e}"));
1100        telemetry::phase_exit();
1101        return fallback();
1102      },
1103    };
1104    audit_end(t_parse);
1105    telemetry::phase_exit();
1106    drop(staged);
1107
1108    // ar5iv sniff: the ar5iv package emits literal-intent MathML. In-memory input
1109    // checks the raw string; file input checks the parsed doc's `<?latexml
1110    // package="ar5iv"?>` PI. Computed here — before Split moves `doc` into `docs`.
1111    let intent_literal = match raw_xml {
1112      Some(xml) => xml.contains("package=\"ar5iv"),
1113      None => doc
1114        .processing_instructions()
1115        .iter()
1116        .any(|pi| pi.contains("package=\"ar5iv")),
1117    };
1118
1119    // Perl-faithful pipeline order (latexmlpost L223-242):
1120    //   Split → Scan → MakeBibliography → CrossRef → Graphics → ...
1121    // Split runs FIRST so each downstream pass sees the per-page
1122    // destination. With the previous order (Scan before Split), every
1123    // entry's `location` was the root document and CrossRef built every
1124    // ref as a within-page anchor — the user-visible TOC links pointed
1125    // at `#Ch1` instead of `Ch1.html`.
1126    //
1127    // Phase 1: Split (only attributes time when --split is on)
1128    let mut docs: Vec<PostDocument> = if split {
1129      telemetry::phase_enter(Phase::Split);
1130      let result = if let Some(xpath) = split_xpath {
1131        let naming = resolve_split_naming(split_naming);
1132        let mut splitter = latexml_post::split::Split::new(xpath, naming, false);
1133        let split_nodes = splitter.to_process(&doc);
1134        match splitter.process(doc, split_nodes) {
1135          Ok(docs) => {
1136            if docs.len() > 1 {
1137              note_progress(&format!("Split into {} documents", docs.len()));
1138            }
1139            Ok(docs)
1140          },
1141          Err(e) => {
1142            post_error("split", &format!("Split failed: {e}"));
1143            Err(())
1144          },
1145        }
1146      } else {
1147        Ok(vec![doc])
1148      };
1149      telemetry::phase_exit();
1150      match result {
1151        Ok(ds) => ds,
1152        Err(()) => return fallback(),
1153      }
1154    } else {
1155      vec![doc]
1156    };
1157
1158    // Helper: run one processor across every doc in a Vec, mirroring
1159    // Perl Post.pm:50-65's `foreach $proc { @newdocs = ... }` loop.
1160    // Each processor's per-doc `process` may return multiple docs (only
1161    // Split actually does, and we've already run Split above), so the
1162    // inner result is flattened back into `docs`.
1163    fn run_phase<P: Processor + ?Sized>(
1164      docs: Vec<PostDocument>,
1165      proc: &mut P,
1166      label: &'static str,
1167    ) -> Result<Vec<PostDocument>, ()> {
1168      let mut out: Vec<PostDocument> = Vec::with_capacity(docs.len());
1169      for d in docs {
1170        // Cooperative memory check per document, so a phase that grows across
1171        // many documents degrades gracefully instead of being hard-killed.
1172        //
1173        // MEASURED LIMIT, so nobody reads more into this than it delivers: on the
1174        // 614 MB witness at `--max-memory 6000` the ceiling is breached BEFORE
1175        // this loop is reached — the one-time parse + split DOM alone exceeds it,
1176        // so the run still ends at the hard watchdog (exit 137, zero pages). No
1177        // cooperative check inside the phases can catch that; bounding it is
1178        // task #147 (streaming the split parse). What this DOES cover is the
1179        // document whose growth happens across the phase itself.
1180        if let Err(e) = latexml_core::stomach::check_timeout_now() {
1181          // FATAL, not Error — see the render-loop stop below.
1182          Info!("post", "stopped", s!("{label} stopped mid-phase"));
1183          e.log_fatal();
1184          return Err(());
1185        }
1186        let nodes = proc.to_process(&d);
1187        if nodes.is_empty() {
1188          out.push(d);
1189          continue;
1190        }
1191        match proc.process(d, nodes) {
1192          Ok(processed) => out.extend(processed),
1193          Err(e) => {
1194            post_error(label, &format!("{label} failed: {e}"));
1195            return Err(());
1196          },
1197        }
1198      }
1199      Ok(out)
1200    }
1201
1202    // Phase 2: Scan — runs on EACH sub-document so its entries register
1203    // the per-page `location` and `pageid`. Single shared ObjectDB so
1204    // the later CrossRef pass can resolve cross-doc refs.
1205    let mut scanner =
1206      latexml_post::scan::Scan::new(ObjectDB::new()).with_label_ids(label_ids(split_naming));
1207    telemetry::phase_enter(Phase::PostScan);
1208    let t_scan = audit_start("Scan");
1209    docs = match run_phase(docs, &mut scanner, "Scan") {
1210      Ok(d) => d,
1211      Err(()) => {
1212        telemetry::phase_exit();
1213        return fallback();
1214      },
1215    };
1216    audit_end(t_scan);
1217    telemetry::phase_exit();
1218
1219    // ---- Pass A / Pass B boundary -------------------------------------------
1220    //
1221    // Scan is the ONLY phase that needs global knowledge: it visits every page
1222    // and produces strings in the ObjectDB. Everything after it is page-local.
1223    // The driver used to be phase-major (`for each phase { for each page }`),
1224    // which keeps every page alive at every boundary — and a live page is not
1225    // cheap: each is its own `xmlDoc` with its own dictionary, id table and
1226    // lazily-built caches, measured at ~1.6 MB of per-document overhead. Across
1227    // the 40,201 pages of a 614 MB core XML that alone grew RSS from 16 GB to
1228    // 80 GB *during Scan*, wrote zero pages, and was killed by the ceiling.
1229    //
1230    // So: spill each scanned page to disk (into the shared `page_spill` dir
1231    // created before front-end selection), free it, and render page-by-page
1232    // below. Peak becomes the one-time split DOM plus ONE page. Spilling (rather
1233    // than re-deriving pages from the source) keeps Scan's per-page
1234    // `location`/`pageid` registration byte-identical — those semantics were
1235    // themselves the fix for empty cross-document TOCs, so they are the wrong
1236    // thing to restructure here.
1237    //
1238    // (path, destination, destination_directory) — the metadata that does NOT
1239    // survive an XML round-trip and must be restored in pass B.
1240    // Plus a flag per page: does it carry an index/glossary/bibliography
1241    // placeholder? Recorded HERE, while the page is already parsed, so the two
1242    // baton sweeps below visit only the handful of pages that have work instead
1243    // of re-parsing every page twice (~80 k redundant parses on a 40 k-page
1244    // document).
1245    //
1246    // One unsplit page stays resident instead, as in Perl (LaTeXML.pm L445): see
1247    // `SpilledPage::resident` for why that is the reparse's DOM.
1248    let keep_resident =
1249      !split && docs.len() == 1 && docs.iter().all(parsed_cleanly) && !spill_every_page();
1250    let mut spilled_pages = Vec::with_capacity(docs.len());
1251    for (i, d) in docs.drain(..).enumerate() {
1252      let path = page_spill.path().join(format!("page-{i:07}.xml"));
1253      if !keep_resident && let Err(e) = std::fs::write(&path, d.to_xml_string()) {
1254        post_error("post", &format!("cannot stage page {i} to disk: {e}"));
1255        return fallback();
1256      }
1257      if let Some(graphics) = graphics_proc.as_mut()
1258        && !keep_resident
1259      {
1260        graphics.plan_names(&d);
1261      }
1262      let (needs_index, needs_bib) = page_placeholder_probes(&d);
1263      let destination = d.get_destination().map(String::from);
1264      let destination_directory = d.get_destination_directory().map(String::from);
1265      let resident = keep_resident.then(|| as_reparsed(d, &path, &page_opts));
1266      spilled_pages.push(SpilledPage {
1267        needs_index,
1268        needs_bib,
1269        path,
1270        destination,
1271        destination_directory,
1272        resident,
1273      });
1274      // `d` (unless resident) drops here: one page's worth of DOM and caches
1275      // released before the next is touched.
1276    }
1277    PostFront {
1278      spilled_pages,
1279      db: scanner.db,
1280      intent_literal,
1281    }
1282  }; // ==== end of the whole-DOM front-end ====
1283  let PostFront {
1284    mut spilled_pages,
1285    db,
1286    intent_literal,
1287  } = front;
1288
1289  // Phase 2b: MakeIndex (Perl LaTeXML.pm L466-470)
1290  //   Runs BEFORE MakeBibliography in Perl. Populates `<ltx:indexlist>`
1291  //   inside `<ltx:index>` placeholders and `<ltx:glossarylist>` inside
1292  //   `<ltx:glossary>` placeholders, using the `GLOSSARY:*` / `INDEX:*`
1293  //   entries Scan registered in the ObjectDB. Without this pass, glossary
1294  //   sections render empty in HTML (witness: tests/structure/glossary.tex).
1295  let mut indexer = latexml_post::make_index::MakeIndex::new(db, false, false);
1296
1297  // Phase 3: MakeBibliography
1298  //
1299  // A raw `.bib` is converted by a recursive BibTeX session (Perl
1300  // `MakeBibliography.pm::convertBibliography`), which needs this crate's
1301  // model loader — so `latexml_post` declares the hook and we fill it in here,
1302  // on the thread that is about to run the pipeline.
1303  crate::bib_session::install();
1304
1305  // The output file extension CrossRef strips for `--urlstyle` (Perl
1306  // `extension => $$opts{extension}`, LaTeXML.pm L479; derived in Config.pm
1307  // L408-420 from the destination's extension, else the format). Without it the
1308  // `server`/`negotiated` styles would strip the wrong suffix (the `xml` default)
1309  // and leave an html site's links untouched.
1310  let is_html_out = is_html.unwrap_or_else(|| stylesheet.is_some_and(|s| s.contains("html")));
1311  let out_extension = destination
1312    .and_then(|d| std::path::Path::new(d).extension().and_then(|e| e.to_str()))
1313    .map(str::to_string)
1314    .unwrap_or_else(|| {
1315      if is_html_out {
1316        "html".to_string()
1317      } else {
1318        "xml".to_string()
1319      }
1320    });
1321
1322  // Phase 4: CrossRef — built only once the bibliography sweep has handed the
1323  // ObjectDB baton on (see `sweep_pages`), so nothing holds two owners of it.
1324  let build_crossref = |db| {
1325    let mut crossref = latexml_post::crossref::CrossRef::new(db, url_style, true);
1326    crossref.set_extension(&out_extension);
1327    if let Some(navtoc) = navigationtoc {
1328      crossref.set_navigation_toc(navtoc);
1329    }
1330    crossref
1331  };
1332
1333  // Phase 3: SVG + MathML + XSLT
1334  let post = latexml_post::Post::new();
1335  let mut processors: Vec<Box<dyn Processor>> = Vec::new();
1336  // SVG first, on the live page DOM — Perl's chain order (`LaTeXML.pm`
1337  // L493-581: Graphics → SVG → MathML → XSLT; SVG for the HTML output and the
1338  // html-family sheets, where Perl's `$$opts{svg}` is on for every sheet but html4's,
1339  // Config.pm L560). The Graphics page-phase has already resolved every
1340  // picture-nested `<ltx:graphics>` by the time this runs, so
1341  // `SVG::convert_foreign` wraps the resolved node and the XSLT renders it
1342  // (#1291's Graphics→SVG order comes for free).
1343  let svg = is_html_out || stylesheet.is_some_and(|s| s.contains("html"));
1344  if svg {
1345    processors.push(Box::new(latexml_post::svg::SVG::new()));
1346  }
1347
1348  // `intent_literal` was computed up-front (before Split consumed `doc`).
1349  let math_formats = MathFormats {
1350    pmml,
1351    cmml,
1352    unicodemath,
1353    keep_xmath,
1354    invisible_times: !noinvisibletimes,
1355    plane1,
1356    hackplane1,
1357    mathtex,
1358    intent_literal,
1359  };
1360  if let Some(math) = math_formats.processor() {
1361    processors.push(math);
1362  }
1363  // Clones of the fully-resolved XSLT inputs for the parallel-render worker
1364  // manifest — `XSLT::new` consumes the real map/vec below, and by the time
1365  // the pass-B driver decides between serial and parallel they are gone.
1366  let mut manifest_xslt_params: Vec<(String, String)> = Vec::new();
1367  let mut manifest_searchpaths: Vec<String> = Vec::new();
1368  if let Some(xsl_path) = stylesheet {
1369    let mut searchpaths = vec![".".to_string()];
1370    if let Ok(exe) = std::env::current_exe()
1371      && let Some(project_root) = exe
1372        .parent()
1373        .and_then(|p| p.parent())
1374        .and_then(|p| p.parent())
1375    {
1376      searchpaths.insert(0, project_root.display().to_string());
1377    }
1378    // Prepend the user's `--path` directories so `--css`/`--javascript`
1379    // resources are found there (and take priority over `.`/project root)
1380    // when copy_param_resources searches for them.
1381    for p in search_paths.iter().rev() {
1382      searchpaths.insert(0, p.clone());
1383    }
1384    let mut xslt_params = rustc_hash::FxHashMap::default();
1385
1386    // When `--schemadocs` is on, auto-prepend the rustdoc-styled
1387    // theme assets so callers don't need to repeat them on every
1388    // invocation. Idempotent: skipped if the user has already
1389    // listed the same basename via `--css` / `--javascript`.
1390    let prepend = |list: &[String], extra: &str| -> Vec<String> {
1391      if list
1392        .iter()
1393        .any(|p| std::path::Path::new(p).file_name().and_then(|s| s.to_str()) == Some(extra))
1394      {
1395        list.to_vec()
1396      } else {
1397        let mut out = Vec::with_capacity(list.len() + 1);
1398        out.push(extra.to_string());
1399        out.extend_from_slice(list);
1400        out
1401      }
1402    };
1403    let css_effective: Vec<String> = if schemadocs {
1404      prepend(css_files, latexml_post::schema_docs::THEME_CSS_BASENAME)
1405    } else {
1406      css_files.to_vec()
1407    };
1408    let js_effective: Vec<String> = if schemadocs {
1409      prepend(js_files, latexml_post::schema_docs::THEME_JS_BASENAME)
1410    } else {
1411      js_files.to_vec()
1412    };
1413    if !css_effective.is_empty() {
1414      xslt_params.insert(
1415        "CSS".to_string(),
1416        format!("\"{}\"", css_effective.join("|")),
1417      );
1418    }
1419    if !js_effective.is_empty() {
1420      xslt_params.insert(
1421        "JAVASCRIPT".to_string(),
1422        format!("\"{}\"", js_effective.join("|")),
1423      );
1424    }
1425    if let Some(ts) = timestamp {
1426      xslt_params.insert("TIMESTAMP".to_string(), format!("\"{}\"", ts));
1427    }
1428    if let Some(icon) = icon {
1429      xslt_params.insert("ICON".to_string(), format!("\"{}\"", icon));
1430    }
1431    // Perl `LaTeXML.pm:562` unconditionally seeds `LATEXML_VERSION => '$LaTeXML::VERSION'`,
1432    // which drives `LaTeXML-common.xsl`'s `LaTeXML_identifier` generator stamp
1433    // (`<!--Generated by LaTeXML oxide (version X) ...-->`) and BookML's `utils.xsl`
1434    // `b:version-leq($LATEXML_VERSION,…)`. We expose OUR own crate `X.Y.Z` (#320). Inserted
1435    // BEFORE the user-override loop so `--xsltparameter LATEXML_VERSION=…` still wins (this
1436    // is how Perl's test suite pins `version TEST` for version-independent goldens).
1437    xslt_params.insert(
1438      "LATEXML_VERSION".to_string(),
1439      format!("\"{}\"", crate::core_interface::LATEXML_VERSION),
1440    );
1441    for param in xslt_parameters {
1442      match parse_xslt_parameter(param) {
1443        Some((key, value)) => {
1444          xslt_params.insert(key, format!("\"{}\"", value));
1445        },
1446        None => post_error(
1447          "xsltparameter",
1448          &format!("xsltparameter not in recognized format: 'name:value' got: '{param}'"),
1449        ),
1450      }
1451    }
1452    manifest_xslt_params = xslt_params
1453      .iter()
1454      .map(|(k, v)| (k.clone(), v.clone()))
1455      .collect();
1456    manifest_searchpaths = searchpaths.clone();
1457    match latexml_post::xslt::XSLT::new(
1458      xsl_path,
1459      xslt_params,
1460      !default_resources,
1461      None,
1462      searchpaths,
1463    ) {
1464      Ok(xslt) => processors.push(Box::new(xslt)),
1465      Err(e) => post_error("xslt", &format!("XSLT error: {e}")),
1466    }
1467  }
1468
1469  // process_chain attributes per-processor inside latexml_post::Post::
1470  // process_chain (MathmlPres / MathmlCont / Xslt). No outer phase wrap
1471  // needed; the inner per-processor guards cover their own time.
1472  //
1473  // Perl-faithful: pass ALL split docs to ProcessChain at once. Perl's
1474  // `Post::ProcessChain_internal` (Post.pm L41-67) seeds `@docs = ($doc)`
1475  // and lets each processor return a (possibly multi-element) list which
1476  // becomes the input to the next processor. We've already produced the
1477  // post-Split list above; ProcessChain just needs to fan MathML/XSLT
1478  // across it.
1479  // ---- Pass B: render one page at a time, then FREE it --------------------
1480  //
1481  // Document-major, not phase-major: each page goes through MakeIndex ->
1482  // MakeBibliography -> CrossRef -> Graphics -> MathML -> XSLT -> write, and
1483  // is dropped before the next is parsed. Every one of these phases is
1484  // page-local; only Scan (pass A, above) needed the whole document, and it
1485  // left its results in the ObjectDB as strings. Peak is therefore ONE page
1486  // plus the index, whatever the page count.
1487  //
1488  // Failure semantics change deliberately: pages that finish are already on
1489  // disk, so a later failure leaves a partial site rather than nothing. That
1490  // matches how a resource Fatal already keeps partial core output.
1491  // (The per-page pipeline itself lives in `render_spilled_page`, shared with
1492  // the process-parallel worker in `crate::render_workers`.)
1493
1494  // The ObjectDB is a BATON: MakeIndex, MakeBibliography and CrossRef each take
1495  // it by value in turn, so they cannot be alive simultaneously. Each therefore
1496  // gets its own sweep over the spilled pages — still ONE page resident at a
1497  // time. A page is only re-spilled when its phase actually had work
1498  // (`to_process` non-empty), which for index/bibliography placeholders is a
1499  // handful of pages out of tens of thousands, so the sweeps cost a parse each
1500  // and almost no writes.
1501  fn sweep_pages(
1502    pages: &mut [SpilledPage],
1503    opts: &PostDocumentOptions,
1504    proc: &mut dyn Processor,
1505    label: &'static str,
1506    selector: fn(&SpilledPage) -> bool,
1507  ) -> Result<(), ()> {
1508    for page_meta in pages.iter_mut().filter(|p| selector(p)) {
1509      let (path, dest, dest_dir) = (
1510        &page_meta.path,
1511        &page_meta.destination,
1512        &page_meta.destination_directory,
1513      );
1514      let path_str = path.to_string_lossy().into_owned();
1515      let resident = page_meta.resident.is_some();
1516      let mut page = match page_meta.resident.take() {
1517        Some(d) => d,
1518        None => PostDocument::new_from_file(&path_str, opts.clone()).map_err(|e| {
1519          post_error("post", &format!("cannot re-read a disk-staged page: {e}"));
1520        })?,
1521      };
1522      page.destination = dest.clone();
1523      page.destination_directory = dest_dir.clone();
1524      let nodes = proc.to_process(&page);
1525      if nodes.is_empty() {
1526        // untouched: the spill on disk (or the resident DOM) is still current
1527        if resident {
1528          page_meta.resident = Some(as_reparsed(page, path, opts));
1529        }
1530        continue;
1531      }
1532      let processed = proc.process(page, nodes).map_err(|e| {
1533        post_error(label, &format!("{label} failed: {e}"));
1534      })?;
1535      // A phase may split one page into several (an index page beside its
1536      // host); the extras are written by their own destination in pass B, so
1537      // re-spill each under the original path only for the first and append
1538      // the rest as additional spills is NOT needed here: MakeIndex and
1539      // MakeBibliography fill placeholders in place and return the same page.
1540      // (Both return `vec![doc]` today; an empty result would leave a resident
1541      // page with nothing to render, so it is an error, never a silent skip.)
1542      let Some(d) = processed.into_iter().next() else {
1543        post_error(label, &format!("{label} returned no page"));
1544        return Err(());
1545      };
1546      let xml = d.to_xml_string();
1547      drop(d);
1548      if resident {
1549        // A changed page is re-parsed, in memory: the processors' edits reach
1550        // pass B in the reparse's normal form (merged text nodes, rescoped
1551        // namespaces), as from disk.
1552        let reparsed =
1553          PostDocument::new_from_string(&xml, PostDocument::file_options(&path_str, opts.clone()))
1554            .map_err(|e| {
1555              post_error("post", &format!("cannot re-read a staged page: {e}"));
1556            })?;
1557        page_meta.resident = Some(reparsed);
1558      } else if let Err(e) = std::fs::write(path, xml) {
1559        post_error("post", &format!("cannot re-stage a page to disk: {e}"));
1560        return Err(());
1561      }
1562    }
1563    Ok(())
1564  }
1565
1566  if sweep_pages(
1567    &mut spilled_pages,
1568    &page_opts,
1569    &mut indexer,
1570    "MakeIndex",
1571    |p| p.needs_index,
1572  )
1573  .is_err()
1574  {
1575    return fallback();
1576  }
1577  let mut bibmaker = latexml_post::make_bibliography::MakeBibliography::new(indexer.db, false);
1578  telemetry::phase_enter(Phase::Bibliography);
1579  let t_bib = audit_start("MakeBibliography");
1580  let bib_result = sweep_pages(
1581    &mut spilled_pages,
1582    &page_opts,
1583    &mut bibmaker,
1584    "MakeBibliography",
1585    |p| p.needs_bib,
1586  );
1587  audit_end(t_bib);
1588  telemetry::phase_exit();
1589  if bib_result.is_err() {
1590    return fallback();
1591  }
1592  // MakeBibliography (the last post-phase that can read `STATE`, `VFS_KEY`, or
1593  // run a recursive `.bib` session) is finished. On large/split one-shot CLI
1594  // runs, release dead core TeX engine state + arena + malloc trim BEFORE
1595  // `parallel_render` sizes the worker fleet and before `CrossRef`/`MathML`/`XSLT`.
1596  if RELEASE_CORE_AFTER_BIB.with(|f| f.replace(false)) {
1597    crate::core_interface::release_core_state_for_post();
1598  }
1599  // ---- Parallel pass B: process-level page-range workers (design §6) ------
1600  //
1601  // Sized by `render_workers::render_jobs` (`LATEXML_RENDER_JOBS`, else
1602  // automatic in the `latexml_oxide` binary, else 1 = the serial path below),
1603  // and only past a minimum page count — below it the db save +
1604  // child spawn overhead beats the win. The ObjectDB is COMPLETE here (Scan,
1605  // MakeIndex and MakeBibliography have all run), so it is saved once as a
1606  // SQLite file and each worker attaches it readonly; the workers run the
1607  // identical `render_spilled_page` pipeline over contiguous page ranges and
1608  // the parent folds their diagnostics deterministically, in chunk order.
1609  // Every page's images are named before any page is rendered, in page order (as the pages were spilled, then those
1610  // MakeIndex and MakeBibliography rewrote), and stored in the resource cache (Perl's document cache,
1611  // `LaTeXML-oxide.cache`): the serial render and every render worker look the names up, so they are the same whichever
1612  // process renders a page, and CrossRef's copies of other pages' titles into a page's navigation meet the names of
1613  // the pages they come from (issue 995). One unsplit page names its images as it renders, as Perl does.
1614  if let Some(gfx) = graphics_proc.as_mut() {
1615    plan_rewritten_pages(&spilled_pages, &page_opts, gfx);
1616  }
1617  // The pages an abandoned fleet may have written: a page's Fatal in the serial render removes them
1618  // too, and a stop removes those it did not rewrite.
1619  let mut fleet_pages: Vec<String> = Vec::new();
1620  let render_jobs = crate::render_workers::render_jobs();
1621  if render_jobs > 1 && spilled_pages.len() >= crate::render_workers::MIN_PAGES_FOR_PARALLEL {
1622    let page_jobs: Vec<crate::render_workers::PageJob> = spilled_pages
1623      .iter()
1624      .map(|p| crate::render_workers::PageJob {
1625        path:                  p.path.clone(),
1626        destination:           p.destination.clone(),
1627        destination_directory: p.destination_directory.clone(),
1628      })
1629      .collect();
1630    let manifest = crate::render_workers::RenderManifest {
1631      // Filled in by `parallel_render` once the db is saved.
1632      dbfile: std::path::PathBuf::new(),
1633      navigation_toc: navigationtoc.map(String::from),
1634      url_style: url_style.as_cli().to_string(),
1635      out_extension: out_extension.clone(),
1636      graphicimages,
1637      graphics_svg_threshold_kb,
1638      pmml,
1639      cmml,
1640      keep_xmath,
1641      invisible_times: !noinvisibletimes,
1642      plane1,
1643      hackplane1,
1644      mathtex,
1645      unicodemath,
1646      intent_literal,
1647      stylesheet: stylesheet.map(String::from),
1648      xslt_params: manifest_xslt_params,
1649      default_resources,
1650      searchpaths: manifest_searchpaths,
1651      svg,
1652      is_html_out,
1653      schemadocs,
1654      whatsout: whatsout.as_cli().to_string(),
1655      page_opts: (&page_opts).into(),
1656      pages: Vec::new(),
1657      // Filled in by `parallel_render` once the fleet is sized.
1658      max_rss_kb: 0,
1659      post_values: latexml_core::PostStateValues::capture(),
1660      resource_names: graphics_proc
1661        .as_ref()
1662        .map(latexml_post::graphics::Graphics::planned_names)
1663        .unwrap_or_default(),
1664      log_level: latexml_core::util::logger::stderr_level().to_string(),
1665      confinement: latexml_core::util::pathname::confinement_snapshot(),
1666    };
1667    // The names are stored: the workers open the cache file themselves, so this process holds no handle across.
1668    run_cache.close_files();
1669    let t_pages = audit_start("render_pages");
1670    let outcome = crate::render_workers::parallel_render(
1671      manifest,
1672      page_jobs,
1673      render_jobs,
1674      page_spill.path(),
1675      &bibmaker.db,
1676    );
1677    audit_end(t_pages);
1678    if let Some(result) = outcome.as_ref().filter(|r| r.abandoned) {
1679      fleet_pages.clone_from(&result.written);
1680    } else if let Some(result) = outcome {
1681      Info!(
1682        "post",
1683        "parallel-render",
1684        s!(
1685          "parallel render finished: {} of {} page(s) written",
1686          result.pages_rendered,
1687          spilled_pages.len()
1688        )
1689      );
1690      drop(page_spill);
1691      // A worker's post Fatal leaves no output, as the serial render's does (#782).
1692      if result.discarded {
1693        return String::new();
1694      }
1695      *written = result.written;
1696      return result.main_output.unwrap_or_else(fallback);
1697    }
1698    // Setup failed, or a worker failed to spawn or died without its report
1699    // (already reported): fall through to the serial render — the workers keep
1700    // the spilled pages on disk.
1701  }
1702
1703  let crossref = build_crossref(bibmaker.db);
1704  let ctx = PageRenderCtx {
1705    page_opts: page_opts.clone(),
1706    is_html_out,
1707    schemadocs,
1708    whatsout,
1709    remove_spilled: true,
1710  };
1711  let mut procs = PageProcessors {
1712    crossref,
1713    graphics: graphics_proc,
1714    post,
1715    processors,
1716  };
1717
1718  let mut main_output: Option<String> = None;
1719  let t_pages = audit_start("render_pages");
1720  let mut pages_rendered = 0usize;
1721  let mut made_dirs = latexml_post::writer::MadeDirs::default();
1722  for SpilledPage {
1723    path,
1724    destination: dest,
1725    destination_directory: dest_dir,
1726    resident,
1727    ..
1728  } in spilled_pages
1729  {
1730    // The cooperative memory guard, at the one seam post has: a page boundary.
1731    //
1732    // Nothing in latexml_post or this driver consulted it — `check_timeout`
1733    // appeared ZERO times across both — so an oversized post run was killed by
1734    // the hard watchdog at 100% of the ceiling (exit 137, `Fatal:oom:rss …
1735    // exceeded the … ceiling`) with nothing on disk, where the design promise
1736    // is a named Fatal at 75% plus whatever finished. Measured on the 131 MB
1737    // witness at `--max-memory 48000`: post died at 48,002 MiB having written
1738    // ZERO pages. Same shape as the Build phase before it got a guard.
1739    //
1740    // Stopping HERE is cheap and honest: pages already rendered are already
1741    // written, so the run ends with a real, if partial, site.
1742    let stop = latexml_core::stomach::check_timeout_now();
1743    #[cfg(feature = "test-utils")]
1744    let stop = stop.and_then(|()| serial_stop_hook(pages_rendered));
1745    if let Err(e) = stop {
1746      // FATAL, not Error (user decision 2026-08-02): a render stopped at
1747      // page N of M is a TRUNCATED deliverable — the same severity class as
1748      // the core's cheap-partial handoff. The pages already written stay on
1749      // disk (a real, if partial, site), the verdict says failed, and the
1750      // combined status the framework reads is 3. Witness that motivated
1751      // it: the joint 131 MB run stopped at 56,088 of 115,519 pages with
1752      // Error-class severity and process exit 0.
1753      Info!(
1754        "post",
1755        "stopped",
1756        s!("render stopped after {pages_rendered} page(s); partial site preserved")
1757      );
1758      e.log_fatal();
1759      remove_fleet_pages_not_rewritten(&fleet_pages, written);
1760      break;
1761    }
1762    // Hand freed page memory back to the OS, exactly as core pass 1 does
1763    // (core_interface.rs, same rationale): every page cycles a full DOM +
1764    // XSLT result through GLIBC's heap (libxml2/libxslt allocate via libc,
1765    // not the Rust allocator), and glibc keeps freed mid-heap pages mapped —
1766    // the render loop's measured ~152 KB/page RSS growth on the 131 MB
1767    // witness is dominated by exactly this class, and it is what pushed the
1768    // single-invocation run over the memory fuse at page 56,088 of 115,519.
1769    // A trim walks the heap: it runs when RSS grew by a step, not per page count (`heap_trim`).
1770    if pages_rendered > 0 && pages_rendered.is_multiple_of(crate::heap_trim::SAMPLE_PAGES) {
1771      crate::heap_trim::sample();
1772    }
1773    // Retention triage probe (`LATEXML_POST_MEMDIAG=1`): splits the render
1774    // loop's RSS growth into live-C (libxml2/libxslt allocations still
1775    // reachable), free-but-mapped C, and "everything else" (Rust/mimalloc +
1776    // mmap). One run with this told the ~144 KB/page term apart from the
1777    // three candidates the first fixes addressed.
1778    #[cfg(target_os = "linux")]
1779    if pages_rendered > 0
1780      && pages_rendered.is_multiple_of(1024)
1781      && std::env::var("LATEXML_POST_MEMDIAG").is_ok()
1782    {
1783      let (c_live_mb, c_free_mb) = crate::heap_trim::c_heap_mb();
1784      let rss_mb = latexml_core::watchdog::process_rss_kb().unwrap_or(0) / 1024;
1785      eprintln!(
1786        "memdiag: pages={pages_rendered} RSS={rss_mb}MB C-live={c_live_mb}MB C-free={c_free_mb}MB"
1787      );
1788    }
1789    let rendered = match resident {
1790      Some(mut page) => {
1791        page.destination = dest;
1792        page.destination_directory = dest_dir;
1793        render_page(page, &mut procs, &ctx)
1794      },
1795      None => render_spilled_page(&path, &mut procs, &ctx, dest, dest_dir),
1796    };
1797    let outputs = match rendered {
1798      Ok(o) => o,
1799      Err(PageFailure::Fatal) => {
1800        remove_pages(written);
1801        remove_pages(&fleet_pages);
1802        written.clear();
1803        return String::new();
1804      },
1805      Err(PageFailure::Error) => {
1806        remove_fleet_pages_not_rewritten(&fleet_pages, written);
1807        return fallback();
1808      },
1809    };
1810    for (dest, output) in outputs {
1811      if let Some(path) = dest.as_deref() {
1812        let _ = made_dirs.ensure_parent(path);
1813        pages_rendered += 1;
1814        if let Err(e) = std::fs::write(path, &output) {
1815          post_error("write", &format!("failed to write page {path}: {e}"));
1816        }
1817        written.push(path.to_string());
1818      }
1819      if main_output.is_none() {
1820        main_output = Some(output);
1821      }
1822    }
1823  }
1824  audit_end(t_pages);
1825  drop(page_spill);
1826
1827  main_output.unwrap_or_else(fallback)
1828}
1829
1830/// The per-page processor set for pass B — everything [`render_spilled_page`]
1831/// mutates. Bundled so the serial driver and the process-parallel worker
1832/// ([`crate::render_workers`]) share ONE pipeline implementation and cannot
1833/// drift.
1834pub(crate) struct PageProcessors {
1835  pub(crate) crossref:   latexml_post::crossref::CrossRef,
1836  pub(crate) graphics:   Option<latexml_post::graphics::Graphics>,
1837  pub(crate) post:       latexml_post::Post,
1838  pub(crate) processors: Vec<Box<dyn Processor>>,
1839}
1840
1841/// The read-only per-run context for pass B page rendering, shared by every
1842/// page of one conversion (serial driver or one parallel worker).
1843pub(crate) struct PageRenderCtx {
1844  /// Clone-source for each page's `PostDocument` parse — carries the same
1845  /// searchpaths/site-directory the pass-A parse used.
1846  pub(crate) page_opts:      PostDocumentOptions,
1847  pub(crate) is_html_out:    bool,
1848  pub(crate) schemadocs:     bool,
1849  pub(crate) whatsout:       latexml_post::extract::Whatsout,
1850  /// Delete each spilled page once parsed. A render worker keeps its pages:
1851  /// should one fail, the serial render redoes the document from them.
1852  pub(crate) remove_spilled: bool,
1853}
1854
1855/// Run one page-local phase (CrossRef / Graphics) over one page, mirroring
1856/// `run_phase` for a single document. Failures are reported via [`post_error`].
1857fn run_page_phase(
1858  doc: PostDocument,
1859  proc: &mut dyn Processor,
1860  label: &'static str,
1861) -> Result<Vec<PostDocument>, ()> {
1862  let nodes = proc.to_process(&doc);
1863  if nodes.is_empty() {
1864    return Ok(vec![doc]);
1865  }
1866  proc.process(doc, nodes).map_err(|e| {
1867    post_error(label, &format!("{label} failed: {e}"));
1868  })
1869}
1870
1871/// The pass-B per-page pipeline: parse one spilled page (deleting the spill
1872/// file as soon as it is parsed), run CrossRef → Graphics → MathML/XSLT, and
1873/// return the finalized `(destination, output)` pairs for the caller to write.
1874/// Exactly the body the serial render loop ran in place before the
1875/// process-parallel split — phase order, telemetry and audit calls included —
1876/// so the serial path stays byte-identical (guard:
1877/// `118_streaming_split_parity`). `Err(())` means the failure was already
1878/// reported via [`post_error`] (or a phase's own diagnostics).
1879pub(crate) fn render_spilled_page(
1880  path: &std::path::Path,
1881  procs: &mut PageProcessors,
1882  ctx: &PageRenderCtx,
1883  destination: Option<String>,
1884  destination_directory: Option<String>,
1885) -> Result<Vec<(Option<String>, String)>, PageFailure> {
1886  let path_str = path.to_string_lossy().into_owned();
1887  let page = match PostDocument::new_from_file(&path_str, ctx.page_opts.clone()) {
1888    Ok(mut d) => {
1889      d.destination = destination;
1890      d.destination_directory = destination_directory;
1891      d
1892    },
1893    Err(e) => {
1894      post_error("post", &format!("cannot re-read a disk-staged page: {e}"));
1895      return Err(PageFailure::Error);
1896    },
1897  };
1898  // Free the spill as soon as it is parsed: for a 40k-page document the
1899  // spill area is the size of the core XML, and it need not outlive its page.
1900  if ctx.remove_spilled {
1901    let _ = std::fs::remove_file(path);
1902  }
1903  render_page(page, procs, ctx)
1904}
1905
1906/// [`render_spilled_page`]'s pipeline after the parse: CrossRef → Graphics →
1907/// MathML/XSLT on one page, returning its `(destination, output)` pairs.
1908fn render_page(
1909  page: PostDocument,
1910  procs: &mut PageProcessors,
1911  ctx: &PageRenderCtx,
1912) -> Result<Vec<(Option<String>, String)>, PageFailure> {
1913  // CrossRef resolves this page's references out of the completed ObjectDB,
1914  // and its navigation/TOC work reads the DB rather than sibling pages — so
1915  // it is page-local once pass A has finished.
1916  telemetry::phase_enter(Phase::Crossref);
1917  let t_xref = audit_start("CrossRef");
1918  let xref = run_page_phase(page, &mut procs.crossref, "CrossRef");
1919  audit_end(t_xref);
1920  telemetry::phase_exit();
1921  let mut staged = xref.map_err(|()| PageFailure::Error)?;
1922  if let Some(gfx) = procs.graphics.as_mut() {
1923    telemetry::phase_enter(Phase::Graphics);
1924    let t_gfx = audit_start("Graphics");
1925    let mut next = Vec::with_capacity(staged.len());
1926    let mut failed = false;
1927    for d in staged.drain(..) {
1928      match run_page_phase(d, gfx, "Graphics") {
1929        Ok(out) => next.extend(out),
1930        Err(()) => {
1931          failed = true;
1932          break;
1933        },
1934      }
1935    }
1936    audit_end(t_gfx);
1937    telemetry::phase_exit();
1938    if failed {
1939      return Err(PageFailure::Error);
1940    }
1941    staged = next;
1942  }
1943
1944  let rendered = match procs.post.process_chain(staged, &mut procs.processors) {
1945    Ok(r) => r,
1946    Err(e) => {
1947      emit_fatal("post", "convert", &format!("Post-processing failed: {e}"));
1948      return Err(PageFailure::Fatal);
1949    },
1950  };
1951
1952  let mut outputs = Vec::with_capacity(rendered.len());
1953  for doc in rendered {
1954    let dest = doc.get_destination().map(String::from);
1955    let output = latexml_post::extract::serialize_whatsout(&doc, ctx.whatsout);
1956    let output = if ctx.is_html_out {
1957      finalize_html5(output)
1958    } else {
1959      output
1960    };
1961    let output = if ctx.schemadocs && ctx.is_html_out {
1962      latexml_post::schema_docs::process_page(&output)
1963    } else {
1964      output
1965    };
1966    outputs.push((dest, output));
1967    // `doc` drops here — the whole point.
1968  }
1969  Ok(outputs)
1970}
1971
1972/// Remove the pages a render wrote before a Fatal: Perl runs each processor over every page
1973/// before its writer, so a die in ProcessChain leaves none (LaTeXML.pm L605-614, #782).
1974pub(crate) fn remove_pages<S: AsRef<str>>(pages: &[S]) {
1975  for page in pages {
1976    let _ = std::fs::remove_file(page.as_ref());
1977  }
1978}
1979
1980/// A serial render that stops after an abandoned fleet removes the fleet's pages it did not
1981/// rewrite: Info's count and `PostOutcome::pages` name only `written`, and a worker killed mid-write
1982/// may have left an empty page. The site is then the contiguous partial one a serial-only run leaves.
1983fn remove_fleet_pages_not_rewritten(fleet_pages: &[String], written: &[String]) {
1984  if fleet_pages.is_empty() {
1985    return;
1986  }
1987  let rewritten: std::collections::HashSet<&str> = written.iter().map(String::as_str).collect();
1988  for page in fleet_pages
1989    .iter()
1990    .filter(|p| !rewritten.contains(p.as_str()))
1991  {
1992    let _ = std::fs::remove_file(page);
1993  }
1994}
1995
1996/// Test hook `LATEXML_RENDER_TEST_SERIAL_STOP=<n>` (guard: cluster_xslt_split): the serial render
1997/// stops before its page `n + 1`, as the memory fuse or the timeout would.
1998#[cfg(feature = "test-utils")]
1999fn serial_stop_hook(pages_rendered: usize) -> latexml_core::common::error::Result<()> {
2000  let at = std::env::var("LATEXML_RENDER_TEST_SERIAL_STOP").ok();
2001  if at.and_then(|n| n.parse().ok()) == Some(pages_rendered) {
2002    latexml_core::fatal!(Timeout, Convert, "Conversion timed out!");
2003  }
2004  Ok(())
2005}
2006
2007/// Why a page did not render (already reported). `Fatal`: a MathML/XSLT step failed, which stops
2008/// post-processing with no output, as a die in Perl's ProcessChain does (LaTeXML.pm L605-614, #782).
2009#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2010pub(crate) enum PageFailure {
2011  Error,
2012  Fatal,
2013}
2014
2015/// One page spilled between the post pipeline's two passes: where its XML
2016/// lives, the metadata that does NOT survive an XML round-trip, and whether it
2017/// carries the placeholders the two ObjectDB-baton sweeps look for (recorded in
2018/// pass A, while the page is already parsed).
2019struct SpilledPage {
2020  path:                  std::path::PathBuf,
2021  destination:           Option<String>,
2022  destination_directory: Option<String>,
2023  needs_index:           bool,
2024  needs_bib:             bool,
2025  /// The page itself, never written to `path`: the one page of an unsplit, cleanly parsed document. Its DOM is
2026  /// what re-parsing `path` would give (a clean parse reparses to the same tree, and Scan only adds the root's
2027  /// `xml:id`), and [`as_reparsed`] gives it the wrapper state of a fresh parse.
2028  resident:              Option<PostDocument>,
2029}
2030
2031/// Closes the run's cache when post ends, whichever way it returns.
2032struct CloseCache(latexml_post::document::DocCache);
2033
2034impl Drop for CloseCache {
2035  fn drop(&mut self) { self.0.close(); }
2036}
2037
2038/// Name the images MakeIndex and MakeBibliography may have added to the pages they rewrote (the pages were planned
2039/// when spilled), then store the names of every planned page ([`Graphics::commit_names`]). A page that cannot be
2040/// re-read is reported by its render.
2041///
2042/// [`Graphics::commit_names`]: latexml_post::graphics::Graphics::commit_names
2043fn plan_rewritten_pages(
2044  pages: &[SpilledPage],
2045  opts: &PostDocumentOptions,
2046  graphics: &mut latexml_post::graphics::Graphics,
2047) {
2048  if !graphics.planned() {
2049    return;
2050  }
2051  for page_meta in pages.iter().filter(|p| p.needs_index || p.needs_bib) {
2052    let Ok(mut page) = PostDocument::new_from_file(&page_meta.path.to_string_lossy(), opts.clone())
2053    else {
2054      continue;
2055    };
2056    page.destination.clone_from(&page_meta.destination);
2057    page
2058      .destination_directory
2059      .clone_from(&page_meta.destination_directory);
2060    graphics.plan_names(&page);
2061  }
2062  graphics.commit_names();
2063}
2064
2065/// Whether libxml2 parsed `doc` without errors: a recovered tree (say, adjacent text nodes around a dropped
2066/// invalid character) can differ from its reparse, so such a page goes to disk.
2067fn parsed_cleanly(doc: &PostDocument) -> bool {
2068  let xml = doc.get_document();
2069  xml.is_well_formed() && xml.is_ns_valid()
2070}
2071
2072/// `doc` as [`PostDocument::new_from_file`] would return it from `path`: the same DOM, with fresh ids,
2073/// namespaces, memos, node wrappers and `source` options.
2074fn as_reparsed(
2075  doc: PostDocument,
2076  path: &std::path::Path,
2077  opts: &PostDocumentOptions,
2078) -> PostDocument {
2079  let xml = doc.into_document();
2080  xml.trim_node_cache();
2081  let path_str = path.to_string_lossy();
2082  let page = PostDocument::new(xml, PostDocument::file_options(&path_str, opts.clone()));
2083  #[cfg(debug_assertions)]
2084  assert_matches_reparse(&page, &path_str, opts);
2085  page
2086}
2087
2088/// Test-profile check that a resident page is what its disk spill would reparse to: Scan sets the root's
2089/// `xml:id` with a raw `set_attribute` (scan.rs), so a page that skipped the refresh keeps a stale id cache
2090/// and `source`. Every post fixture runs it; release builds pay nothing.
2091#[cfg(debug_assertions)]
2092fn assert_matches_reparse(page: &PostDocument, path: &str, opts: &PostDocumentOptions) {
2093  let reparsed = PostDocument::new_from_string(
2094    &page.to_xml_string(),
2095    PostDocument::file_options(path, opts.clone()),
2096  )
2097  .expect("a resident page reparses");
2098  let root_id_resolves = |d: &PostDocument| {
2099    let root = d.get_document().get_root_element()?;
2100    let id = latexml_post::document::get_xml_id(&root)?;
2101    Some(
2102      d.find_node_by_id(&id)
2103        .map(|n| n.node_ptr() == root.node_ptr()),
2104    )
2105  };
2106  let ns_decls = |d: &PostDocument| {
2107    let root = d.get_document().get_root_element();
2108    let decls = root
2109      .map(|r| r.get_namespace_declarations())
2110      .unwrap_or_default();
2111    decls
2112      .iter()
2113      .map(|ns| (ns.get_prefix(), ns.get_href()))
2114      .collect::<Vec<_>>()
2115  };
2116  assert_eq!(
2117    page.to_xml_string(),
2118    reparsed.to_xml_string(),
2119    "resident page: XML"
2120  );
2121  assert_eq!(
2122    root_id_resolves(page),
2123    root_id_resolves(&reparsed),
2124    "resident page: root xml:id"
2125  );
2126  assert_eq!(
2127    page.get_source(),
2128    reparsed.get_source(),
2129    "resident page: source"
2130  );
2131  assert_eq!(
2132    page.source_directory, reparsed.source_directory,
2133    "resident page: source_directory"
2134  );
2135  assert_eq!(
2136    page.processing_instructions(),
2137    reparsed.processing_instructions(),
2138    "resident page: PIs"
2139  );
2140  assert_eq!(
2141    page.searchpaths, reparsed.searchpaths,
2142    "resident page: searchpaths"
2143  );
2144  assert_eq!(
2145    ns_decls(page),
2146    ns_decls(&reparsed),
2147    "resident page: namespace declarations"
2148  );
2149  assert_eq!(
2150    page.namespaces, reparsed.namespaces,
2151    "resident page: namespaces"
2152  );
2153  assert_eq!(
2154    page.namespace_uris, reparsed.namespace_uris,
2155    "resident page: namespace_uris"
2156  );
2157}
2158
2159/// Apply HTML5 cleanup (XML prolog strip, void-element fixes) to one rendered
2160/// page. Pulled out of `run_post_processing` so it can run on every split
2161/// sub-document, not just the first.
2162///
2163/// Pictures need no string-level work here any more: `latexml_post::svg::SVG`
2164/// converts every `<ltx:picture>` on the live page DOM before MathML/XSLT
2165/// (Perl's chain order, `LaTeXML.pm` Graphics → SVG → MathML → XSLT), so the
2166/// XSLT's `as-svg` branch renders the `<svg:svg>` itself. The former
2167/// regex-built fragment table and post-XSLT placeholder splice truncated an
2168/// outer picture at its first nested `</picture>` and dropped every
2169/// `<block>`/`<p>`/`<inline-block>` child (pagelayout ×3, ticket ×2,
2170/// vocaltract, bookcover-example2, latex-refsheet/header-graph lost all
2171/// picture text at post; batch 56bz).
2172fn finalize_html5(mut output: String) -> String {
2173  use std::{borrow::Cow, sync::LazyLock};
2174  // Cached at first call — regex compile is the slow part of `Regex::new`,
2175  // and finalize_html5 runs on every (sub-)document in the post-pipeline.
2176  static XML_PROLOG_RE: LazyLock<regex::Regex> =
2177    LazyLock::new(|| regex::Regex::new(r"^<\?xml[^?]*\?>\s*").unwrap());
2178  static NON_VOID_SELF_CLOSE_RE: LazyLock<regex::Regex> = LazyLock::new(|| {
2179    regex::Regex::new(
2180      r"<(span|div|p|a|td|th|tr|section|article|figure|figcaption|pre|code|em|strong|b|i|u|sub|sup|small|cite)(\s[^>]*)?/>",
2181    ).unwrap()
2182  });
2183  static VOID_CLOSE_RE: LazyLock<regex::Regex> = LazyLock::new(|| {
2184    regex::Regex::new(r"</(br|img|hr|input|meta|link|col|area|base|source|track|wbr|embed|param)>")
2185      .unwrap()
2186  });
2187  static VOID_SELF_CLOSE_RE: LazyLock<regex::Regex> = LazyLock::new(|| {
2188    regex::Regex::new(
2189      r"<(br|img|hr|input|meta|link|col|area|base|source|track|wbr|embed|param)(\s[^>]*?)\s*/>",
2190    )
2191    .unwrap()
2192  });
2193
2194  let _gp_html5 = telemetry::phase(Phase::Html5Fixups);
2195  // Strip <?xml version...?> prolog: HTML5 must NOT have an XML declaration.
2196  // libxml2's to_string() includes it by default; we strip it here.
2197  let prolog_end = if output.starts_with("<?xml") {
2198    XML_PROLOG_RE.find(&output).map_or(0, |m| m.end())
2199  } else {
2200    0
2201  };
2202  let mut s: Cow<'_, str> = Cow::Borrowed(&output[prolog_end..]);
2203  if s.contains("/>")
2204    && let Cow::Owned(replaced) = NON_VOID_SELF_CLOSE_RE.replace_all(&s, "<$1$2></$1>")
2205  {
2206    s = Cow::Owned(replaced);
2207  }
2208  if s.contains("</")
2209    && let Cow::Owned(replaced) = VOID_CLOSE_RE.replace_all(&s, "")
2210  {
2211    s = Cow::Owned(replaced);
2212  }
2213  if s.contains("/>")
2214    && let Cow::Owned(replaced) = VOID_SELF_CLOSE_RE.replace_all(&s, "<$1$2>")
2215  {
2216    s = Cow::Owned(replaced);
2217  }
2218  match s {
2219    Cow::Owned(final_str) => final_str,
2220    Cow::Borrowed(_) => {
2221      if prolog_end > 0 {
2222        output.drain(..prolog_end);
2223      }
2224      output
2225    },
2226  }
2227}
2228
2229#[cfg(test)]
2230mod tests {
2231  use super::*;
2232
2233  #[test]
2234  fn finalize_html5_preserves_clean_html_and_fixes_xml_artifacts() {
2235    let clean = "<!DOCTYPE html><html><body><p>Hello</p><br></body></html>";
2236    assert_eq!(finalize_html5(clean.to_string()), clean);
2237
2238    let with_prolog = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE html><p>ok</p>";
2239    assert_eq!(
2240      finalize_html5(with_prolog.to_string()),
2241      "<!DOCTYPE html><p>ok</p>"
2242    );
2243
2244    let with_fixes =
2245      "<?xml version=\"1.0\"?> <span class=\"x\"/><div/><br></br><img src=\"a.png\" />";
2246    assert_eq!(
2247      finalize_html5(with_fixes.to_string()),
2248      "<span class=\"x\"></span><div></div><br><img src=\"a.png\">"
2249    );
2250  }
2251
2252  /// An unused reservation removes the file an earlier attempt wrote; a used one keeps it for post.
2253  #[test]
2254  fn an_unused_core_handoff_is_removed() {
2255    let dir = tempfile::tempdir().expect("tempdir");
2256    let dest = dir.path().join("index.html");
2257    let dest = dest.to_str();
2258    let staged = StagedHandoff::at(dest);
2259    let path = staged.path().to_string();
2260    std::fs::write(&path, "<document/>\n").expect("written");
2261    let kept = used_core_handoff(Some(staged), Some(&path));
2262    assert_eq!(kept.as_ref().map(StagedHandoff::path), Some(path.as_str()));
2263    assert!(
2264      std::path::Path::new(&path).exists(),
2265      "a used handoff stays for post"
2266    );
2267    assert!(used_core_handoff(kept, None).is_none());
2268    assert!(
2269      !std::path::Path::new(&path).exists(),
2270      "an unused handoff is removed"
2271    );
2272  }
2273}