latexml/streaming_restart.rs
1//! Eager → `--streaming` restart policy shared by the CLI and `cortex_worker`
2//! (batches 56dw/56dz): when to stream up front (`resolve_streaming`, the
3//! source-size projection), where an eligible eager run stops to rerun
4//! (`restart_watermark`, nine tenths of the memory fuse), whether a finished
5//! eager attempt asks for the rerun (`restart_budget`), and the memory release
6//! the rerun needs first (`release_before_rerun`).
7
8use std::{fs::File, io::Read, path::Path};
9
10use latexml_core::stomach::{self, RestartSignal};
11
12/// The box budget a mid-run eager→streaming transition (`digest_adaptive`)
13/// hands to pass 1: the same yardstick `resolve_streaming` uses — the resolved
14/// RSS cap when one is set, else this machine's default ceiling — over the
15/// per-box footprint. Never `None`: the transition happens BECAUSE memory is
16/// under pressure, so the budget must be finite.
17pub fn transition_budget() -> usize {
18 const BYTES_PER_BOX: u64 = 2416; // stomach::BYTES_PER_LIGHT_BOX's basis
19 // `resolve_streaming` sizes against the RAW ceiling (`--max-memory=N`);
20 // what is resolvable here is the fuse `apply_memory_ceiling` derived from it
21 // (`soft_cap_from_ceiling` = 3/4 of N), so invert that to the same yardstick.
22 // With no cap at all (`--max-memory=0`) both use this machine's default
23 // ceiling. (`cortex_worker`, whose fuse IS its `--max-rss-mb`, and an
24 // embedder that sets only `LATEXML_RSS_CAP_BYTES` get a yardstick 4/3 of it;
25 // a slightly larger budget.)
26 let yardstick_mib = stomach::resolve_rss_cap()
27 .map(|fuse| fuse.saturating_mul(4) / 3 / (1024 * 1024))
28 .unwrap_or_else(latexml_core::watchdog::default_ceiling_mib);
29 ((yardstick_mib.saturating_mul(1024 * 1024) / 8 / BYTES_PER_BOX) as usize).max(1)
30}
31
32/// The RSS at which an eligible eager run stops to rerun under `--streaming`:
33/// nine tenths of the cooperative fuse in force for this thread. The stop
34/// exists for clean reporting (an Info instead of a Fatal, no salvage of a
35/// partial document) more than for time: sweep #104 put it at two thirds and
36/// five documents whose eager peak sat between the watermark and the fuse paid
37/// a needless rerun (+330 s of sweep wall, no verdict changed), while the
38/// witnesses that fuse anyway saved little (pgf-PeriodicTable's manual is
39/// bounded by its ~380 s streaming rerun, not by where the eager attempt
40/// stops). `None` when memory limiting is disabled (`--max-memory=0`): the
41/// single knob governs every ceiling.
42pub fn restart_watermark() -> Option<u64> { stomach::resolve_rss_cap().map(|cap| cap * 9 / 10) }
43
44/// After an eager attempt on this thread: the fragment budget to rerun under
45/// when digestion stopped for memory — at the watermark or at the fuse. Takes
46/// the signal, so a later paper on the same thread starts clean. `None` = keep
47/// the eager result.
48pub fn restart_budget(max_memory_mib: u64, source: &str) -> Option<usize> {
49 stomach::take_streaming_restart_signal()?;
50 resolve_streaming(Some(true), max_memory_mib, source)
51}
52
53/// Give the fused attempt's memory back before the rerun's first fuse check:
54/// its boxes still sit in the stomach's lists and its freed pages in mimalloc's
55/// heap, so the rerun read the OLD peak and fused again (807 MB against an
56/// 805 MB cap half a second in). Returns the resident size after the release
57/// and the fuse, both in MB; the caller reruns only when the first is below
58/// the second.
59pub fn release_before_rerun() -> (u64, u64) {
60 stomach::drop_pending_box_lists();
61 stomach::clear_token_stack();
62 crate::heap_trim::collect_rust_heap();
63 let rss_mb = latexml_core::watchdog::process_rss_kb().unwrap_or(0) / 1024;
64 let cap_mb = stomach::resolve_rss_cap().unwrap_or(0) / (1024 * 1024);
65 (rss_mb, cap_mb)
66}
67
68/// Test seam: pretend digestion stopped for memory on this thread.
69pub fn note_restart_signal(signal: RestartSignal) {
70 stomach::note_streaming_restart_signal(signal);
71}
72
73/// Streaming activation (user policy 2026-07-29: flag + auto-when-doomed).
74///
75/// Forced by `--streaming`; otherwise auto-enabled only when the PROJECTED
76/// peak of the eager path exceeds the memory ceiling — measured ~1.84 GB of
77/// peak RSS per MB of math-heavy source on the 131 MB witness
78/// (`docs/archive/STREAMING_CORE_DESIGN_2026-07-29.md` §1), i.e. only for
79/// documents that today would die at the ceiling with certainty. An explicit
80/// `--streaming=false` (or `LATEXML_STREAMING=false`) suppresses BOTH, and the
81/// eager run's switch to streaming at the spill watermark too — the
82/// escape hatch for a caller who would rather have the eager path's Fatal
83/// than a fragmented conversion, and the only way to A/B the two paths on a
84/// document large enough for auto to fire. The returned
85/// budget is the pass-1 fragment yield threshold in BOXES: an eighth of the
86/// ceiling at the measured ~2.4 KB per retained box. The bite must leave REAL
87/// headroom under the RSS fuse (75% of the ceiling): a fragment's live cost
88/// is boxes + the DOM built from them (~1.4×), yields only fire at legal
89/// seams (a large alignment digests un-yieldingly past any knob), and
90/// per-run bookkeeping (FragmentIndex, spine) creeps monotonically — on the
91/// 131 MB witness at a 48 GB ceiling, a quarter-bite steadied at ~33 GB and
92/// the ~5 GB creep then walked it into the 37.7 GB fuse.
93pub fn resolve_streaming(
94 requested: Option<bool>,
95 max_memory_mib: u64,
96 source: &str,
97) -> Option<usize> {
98 // Peak RSS per source byte, an UPPER envelope over the corpus (batch 56ew): the
99 // NLCT manuals (datatool-user 1.71 MB → 5.5 GB, glossaries-user, glossaries-
100 // extra-manual: `\createexample*` retains ~2.3 MB per block) run at ~3200 B/B,
101 // source2e's kernel `.dtx` prose at ~1500. At 1900 the three manuals projected
102 // "fits" (3.2 GB < the 4.6 GB fuse), ran eager to the restart watermark (~46 s,
103 // 37% of their wall) and re-digested everything under `--streaming`; at 3200
104 // exactly those three cross the fuse and stream from the start (memoir/memman
105 // 1.44 MB lands on the line and stays eager; every other manual is ≤ 1.05 MB).
106 const PEAK_BYTES_PER_SOURCE_BYTE: u64 = 3200;
107 const BYTES_PER_BOX: u64 = 2416; // stomach::BYTES_PER_LIGHT_BOX's basis
108 // `--max-memory=0` disables the death ceiling, but the machine is still
109 // finite and such a document may still need to spill. Judge — and size
110 // fragments — against the ceiling we WOULD have derived. Without this the
111 // arithmetic degenerated: `projected > 0` always fired, and
112 // `0 / 8 / 2416 -> max(1)` gave a ONE-BOX budget, i.e. a yield after every
113 // box.
114 let yardstick_mib = if max_memory_mib == 0 {
115 latexml_core::watchdog::default_ceiling_mib()
116 } else {
117 max_memory_mib
118 };
119 // Compare against the cooperative FUSE, not the ceiling: death happens at
120 // 75% of the ceiling, so comparing against the ceiling left a band
121 // (0.75-1.0x) that was judged "fits", took the eager path, and was then
122 // killed by the fuse — 8.1-10.8 MB of source on a 16 GB laptop.
123 let fuse_mib = stomach::soft_cap_from_ceiling(yardstick_mib) / (1024 * 1024);
124 let auto = || {
125 let projected_mib =
126 projected_source_bytes(source).saturating_mul(PEAK_BYTES_PER_SOURCE_BYTE) / (1024 * 1024);
127 (projected_mib > fuse_mib).then_some(())
128 };
129 match requested {
130 // Explicit opt-out: never stream, not even when projected to die.
131 Some(false) => return None,
132 Some(true) => {},
133 None if auto().is_none() => return None,
134 None => {},
135 }
136 // The eighth is MEASURED, not guessed, and shrinking it buys nothing: on the
137 // 19.8 MB witness at an 8192 MiB ceiling, divisors 8/16/32 peak at
138 // 4747/4719/4714 MB with an invariant ramp (3788/3784/3787 MB at fragment 2)
139 // and byte-identical output. Peak there is a STARTUP TRANSIENT that this knob
140 // does not size — see task #158.
141 let budget_boxes = (yardstick_mib.saturating_mul(1024 * 1024) / 8 / BYTES_PER_BOX) as usize;
142 Some(budget_boxes.max(1))
143}
144
145/// The byte size the memory projection must reason from: the DOCUMENT, not the
146/// main file.
147///
148/// A 2 KB `index.tex` that `\input`s a thousand chapters is a half-gigabyte
149/// document, but `metadata(main).len()` projects it at 2 KB — "fits easily" —
150/// and the eager path then dies on it. When the main file actually names an
151/// inclusion command, sum the source tree (`.tex`/`.ltx`/`.bbl`) instead.
152///
153/// Gated on the command being present so a SELF-CONTAINED paper sitting in a
154/// directory of unused alternates (a common arXiv bundle shape) still projects
155/// as itself and keeps the eager path.
156///
157/// Known limitation: an inclusion assembled by macro expansion
158/// (`\myinput{ch1}`) names no literal command and is not detected; such a
159/// document needs an explicit `--streaming`.
160pub fn projected_source_bytes(source: &str) -> u64 {
161 /// Enough of the main file to see its inclusion commands without reading a
162 /// 131 MB self-contained source in full (whose own size already dominates).
163 const SCAN_BYTES: u64 = 4 * 1024 * 1024;
164 /// Backstop against a pathological tree (a home directory as source dir).
165 const WALK_ENTRIES: usize = 50_000;
166 const INCLUSION_COMMANDS: [&str; 8] = [
167 "\\input",
168 "\\include",
169 "\\import",
170 "\\subimport",
171 "\\subfile",
172 "\\includeonly",
173 "\\DocInput",
174 "\\DocInclude",
175 ];
176
177 let own = std::fs::metadata(source).map(|m| m.len()).unwrap_or(0);
178 let Some(dir) = source_dir(source) else {
179 return own;
180 };
181 let mut head = Vec::new();
182 if File::open(source)
183 .map(|f| f.take(SCAN_BYTES).read_to_end(&mut head))
184 .is_err()
185 {
186 return own;
187 }
188 let head = String::from_utf8_lossy(&head);
189 if !INCLUSION_COMMANDS.iter().any(|cmd| head.contains(cmd)) {
190 return own;
191 }
192 // doc.sty's `\DocInput{x}` / `\DocInclude{x}` pull `x.dtx` from the SOURCE tree
193 // (`texmf-dist/source/…`), which the directory walk below never sees: source2e.tex
194 // is a 15 KB driver over 57 `.dtx` = 3.5 MB, source3.tex 2 KB over 65 = 4.0 MB
195 // (batch 56ew). Resolve each named file through kpathsea and count it; a
196 // same-directory `.dtx` is also counted by the walk (extension list below).
197 // source3.tex keeps its `\DocInclude`s in `\input{source3body}`: follow one
198 // level of `\input`/`\include` from the head as well (same directory, else
199 // kpathsea; bounded), so a two-file driver projects like a one-file one.
200 let mut total = doc_input_dtx_bytes(&head);
201 for sub in included_heads(&head, dir).iter().take(32) {
202 total = total.saturating_add(doc_input_dtx_bytes(sub));
203 }
204 let mut seen = 0usize;
205 let mut stack = vec![dir.to_path_buf()];
206 while let Some(d) = stack.pop() {
207 let Ok(entries) = std::fs::read_dir(&d) else {
208 continue;
209 };
210 for entry in entries.flatten() {
211 seen += 1;
212 if seen > WALK_ENTRIES {
213 return total.max(own);
214 }
215 match entry.file_type() {
216 Ok(t) if t.is_dir() => stack.push(entry.path()),
217 Ok(t) if t.is_file() => {
218 let path = entry.path();
219 if matches!(
220 path.extension().and_then(|e| e.to_str()),
221 Some("tex" | "ltx" | "bbl" | "dtx")
222 ) {
223 total = total.saturating_add(entry.metadata().map(|m| m.len()).unwrap_or(0));
224 }
225 },
226 _ => {},
227 }
228 }
229 }
230 total.max(own)
231}
232
233/// The directory a source file lives in. A bare file name's parent is the EMPTY
234/// path, which `read_dir` cannot read: the projection then skipped the
235/// example-file walk, the document ran eager, and under an address-space cap
236/// libxml2 died at build start (roadmap stream C, 2026-09-25: datatool-user run
237/// as `datatool-user.tex`). It is the current directory.
238fn source_dir(source: &str) -> Option<&Path> {
239 match Path::new(source).parent() {
240 Some(d) if d.as_os_str().is_empty() => Some(Path::new(".")),
241 other => other,
242 }
243}
244
245/// The heads (first `SCAN_BYTES`) of the files `\input{…}` / `\include{…}` in `head`
246/// name, one level deep: resolved in `dir` first (with and without `.tex`), else through
247/// kpathsea. Macro-assembled names are skipped.
248fn included_heads(head: &str, dir: &Path) -> Vec<String> {
249 const SCAN_BYTES: u64 = 4 * 1024 * 1024;
250 let mut out = Vec::new();
251 for cmd in ["\\input{", "\\include{"] {
252 for (idx, _) in head.match_indices(cmd) {
253 let rest = &head[idx + cmd.len()..];
254 let Some(end) = rest.find('}') else {
255 continue;
256 };
257 let name = rest[..end].trim();
258 if name.is_empty() || name.contains('\\') || name.contains('#') {
259 continue;
260 }
261 let candidates = [dir.join(name), dir.join(format!("{name}.tex"))];
262 let path = candidates
263 .iter()
264 .find(|p| latexml_core::util::pathname::read_allowed(&p.to_string_lossy()) && p.is_file())
265 .map(|p| p.to_string_lossy().into_owned())
266 .or_else(|| {
267 let with_ext = format!("{name}.tex");
268 latexml_core::util::pathname::kpsewhich(&[with_ext.as_str(), name])
269 });
270 let Some(path) = path else {
271 continue;
272 };
273 let mut buf = Vec::new();
274 if File::open(&path)
275 .map(|f| f.take(SCAN_BYTES).read_to_end(&mut buf))
276 .is_ok()
277 {
278 out.push(String::from_utf8_lossy(&buf).into_owned());
279 }
280 }
281 }
282 out
283}
284
285/// Bytes of every `.dtx` a `\DocInput{…}` / `\DocInclude{…}` in `head` names, resolved
286/// through kpathsea (`kpsewhich`), so a doc.sty driver projects as its documented
287/// sources rather than as its own few kilobytes. A name already carrying an
288/// extension is tried as given first. Unresolvable names count as zero.
289fn doc_input_dtx_bytes(head: &str) -> u64 {
290 let mut total = 0u64;
291 for cmd in ["\\DocInput{", "\\DocInclude{"] {
292 for (idx, _) in head.match_indices(cmd) {
293 let rest = &head[idx + cmd.len()..];
294 let Some(end) = rest.find('}') else {
295 continue;
296 };
297 let name = rest[..end].trim();
298 if name.is_empty() || name.contains('\\') || name.contains('#') {
299 continue; // a macro-assembled name: not statically resolvable
300 }
301 let with_ext = if Path::new(name).extension().is_some() {
302 name.to_string()
303 } else {
304 format!("{name}.dtx")
305 };
306 if let Some(found) = latexml_core::util::pathname::kpsewhich(&[with_ext.as_str(), name]) {
307 total = total.saturating_add(std::fs::metadata(&found).map(|m| m.len()).unwrap_or(0));
308 }
309 }
310 }
311 total
312}
313
314#[cfg(test)]
315mod tests {
316 use super::{projected_source_bytes, source_dir};
317
318 /// A bare file name lives in the current directory, not in the empty path.
319 #[test]
320 fn bare_source_name_is_in_the_current_directory() {
321 assert_eq!(source_dir("x.tex"), Some(std::path::Path::new(".")));
322 assert_eq!(source_dir("d/x.tex"), Some(std::path::Path::new("d")));
323 }
324
325 /// Batch 56ew: a doc.sty driver projects as the `.dtx` it documents, not as its
326 /// own few kilobytes — otherwise the eager attempt overruns the memory fuse and
327 /// the whole conversion re-digests under `--streaming` (source2e: 15 KB driver,
328 /// 3.5 MB of `.dtx`, 170 s → 85 s once streamed from the start). A same-directory
329 /// `.dtx` is found by the walk; a kpathsea-resolvable one by name.
330 #[test]
331 fn docinput_driver_projects_its_dtx_volume() {
332 let dir = std::env::temp_dir().join(format!("pk56ew-{}", std::process::id()));
333 std::fs::create_dir_all(&dir).unwrap();
334 let driver = dir.join("driver.tex");
335 std::fs::write(
336 &driver,
337 "\\documentclass{ltxdoc}\n\\begin{document}\n\\DocInput{zz-probe-56ew.dtx}\n\\end{document}\n",
338 )
339 .unwrap();
340 std::fs::write(dir.join("zz-probe-56ew.dtx"), vec![b'%'; 200_000]).unwrap();
341 let projected = projected_source_bytes(driver.to_str().unwrap());
342 let _ = std::fs::remove_dir_all(&dir);
343 assert!(
344 projected >= 200_000,
345 "the .dtx volume must be counted (projected {projected} bytes)"
346 );
347 }
348
349 /// source3.tex shape: the driver only `\input`s a body file that holds the
350 /// `\DocInclude`s — one level of inclusion is followed.
351 #[test]
352 fn docinclude_behind_an_input_is_followed_one_level() {
353 let dir = std::env::temp_dir().join(format!("pk56ew-body-{}", std::process::id()));
354 std::fs::create_dir_all(&dir).unwrap();
355 let driver = dir.join("driver.tex");
356 std::fs::write(
357 &driver,
358 "\\documentclass{ltxdoc}\\begin{document}\\input{body}\\end{document}\n",
359 )
360 .unwrap();
361 std::fs::write(dir.join("body.tex"), "\\DocInclude{zz-probe-56ew-body}\n").unwrap();
362 std::fs::write(dir.join("zz-probe-56ew-body.dtx"), vec![b'%'; 300_000]).unwrap();
363 let projected = projected_source_bytes(driver.to_str().unwrap());
364 let _ = std::fs::remove_dir_all(&dir);
365 assert!(
366 projected >= 300_000,
367 "the .dtx behind \\input{{body}} must be counted (got {projected})"
368 );
369 }
370
371 /// Control: a self-contained file with no inclusion command projects as itself.
372 #[test]
373 fn self_contained_source_projects_as_itself() {
374 let dir = std::env::temp_dir().join(format!("pk56ew-solo-{}", std::process::id()));
375 std::fs::create_dir_all(&dir).unwrap();
376 let main = dir.join("solo.tex");
377 std::fs::write(
378 &main,
379 "\\documentclass{article}\\begin{document}x\\end{document}\n",
380 )
381 .unwrap();
382 std::fs::write(dir.join("unused.dtx"), vec![b'%'; 100_000]).unwrap();
383 let projected = projected_source_bytes(main.to_str().unwrap());
384 let _ = std::fs::remove_dir_all(&dir);
385 assert!(
386 projected < 1_000,
387 "no inclusion command: own size only (got {projected})"
388 );
389 }
390}