latexml/heap_trim.rs
1//! Handing freed heap memory back to the OS on long runs.
2//!
3//! libxml2/libxslt allocate on glibc's heap, and glibc keeps freed mid-heap pages mapped: a book-scale core
4//! pass or split render cycles a DOM per fragment or page through it, so RSS creeps into the memory fuse
5//! unless the free pages are trimmed (the 131 MB witness: core RSS 22→36 GB, post +152 KB/page). A trim
6//! walks the whole heap and madvises EVERY free chunk again, so a trim per fixed page count costs
7//! pages × heap: 203 K madvise calls at 8,094 pages on Nasser's document (#777 FAQ, 130 of 194 min in sys
8//! under WSL 1). [`sample`] trims only when the resident set grew by [`step_kb`] since the last trim, which
9//! bounds the trims by the run's memory growth instead of its length.
10
11use std::cell::Cell;
12
13/// The page cadence of [`sample`] in the render loops: one `/proc/self/status` read per this many pages.
14pub const SAMPLE_PAGES: usize = 64;
15
16/// Release the free pages of both heaps: glibc's (`malloc_trim`) and mimalloc's ([`collect_rust_heap`]).
17pub fn release_free_heap() {
18 #[cfg(target_os = "linux")]
19 // SAFETY: `malloc_trim(0)` only advises glibc to release unused heap pages; no Rust refs are affected.
20 unsafe {
21 libc::malloc_trim(0);
22 }
23 collect_rust_heap();
24}
25
26/// Purge mimalloc's free pages (skipped under `dhat-heap`).
27pub fn collect_rust_heap() {
28 #[cfg(not(feature = "dhat-heap"))]
29 // SAFETY: `mi_collect(true)` only purges unused mimalloc pages; live allocations remain valid.
30 unsafe {
31 libmimalloc_sys::mi_collect(true);
32 }
33}
34
35/// glibc's heap in MB, (live, freed but retained): `mallinfo2`'s `uordblks` and `fordblks`, all arenas. libxml2
36/// and libxslt allocate there, Rust through mimalloc; diagnostic only.
37#[cfg(target_os = "linux")]
38pub fn c_heap_mb() -> (usize, usize) {
39 // SAFETY: `mallinfo2` is a read-only glibc allocator stat query with no pointer inputs.
40 let mi = unsafe { libc::mallinfo2() };
41 (mi.uordblks / (1024 * 1024), mi.fordblks / (1024 * 1024))
42}
43
44thread_local! {
45 /// RSS (KiB) right after the last trim, lowered when the resident set falls below it.
46 static TRIMMED_AT_KB: Cell<u64> = const { Cell::new(0) };
47 /// Samples taken without an RSS reading, for the fallback cadence.
48 static BLIND_SAMPLES: Cell<usize> = const { Cell::new(0) };
49}
50
51/// Without an RSS reading, [`sample`] trims every this many samples: every 512 pages in the render loops,
52/// their cadence before the RSS gate (every 32,768 fragments in streaming core, which trimmed every 4,096).
53const BLIND_TRIM_SAMPLES: usize = 512 / SAMPLE_PAGES;
54
55/// The resident growth that warrants a trim: 1/64 of the soft memory fuse (`resolve_rss_cap`, 3/4 of
56/// `--max-memory`), within 32-256 MB: 96 MB under `--max-memory=8192`, the 32 MB floor below a ceiling of
57/// ~2.7 GB, ~67 MB at the 4.5 GB default fuse, 256 MB with none. Per sample this replaces up to
58/// step/page-cost of retained free pages (~650 pages at the 152 KB/page growth) with one
59/// `/proc/self/status` read. A render-worker child (`render_workers::worker_main`) installs its
60/// `manifest.max_rss_kb` share via `stomach::set_memory_cap`, so it steps by its own share (or by
61/// the default fuse / `LATEXML_RSS_CAP_BYTES` when uncapped).
62pub fn step_kb() -> u64 {
63 const MIB: u64 = 1024;
64 let cap_kb = latexml_core::stomach::resolve_rss_cap().map_or(u64::MAX, |cap| cap / 1024);
65 (cap_kb / 64).clamp(32 * MIB, 256 * MIB)
66}
67
68/// Sample the resident set and trim when it grew by [`step_kb`] since the last trim. Returns whether it
69/// trimmed. Callers sample at a page or fragment cadence; the first sample of a thread trims.
70pub fn sample() -> bool {
71 let Some(rss_kb) = latexml_core::watchdog::process_rss_kb() else {
72 // No RSS reading (an unsupported OS): nothing to gate on, so trim at a fixed cadence (`mi_collect`
73 // works on every OS).
74 let blind = BLIND_SAMPLES.get() + 1;
75 BLIND_SAMPLES.set(blind);
76 if blind.is_multiple_of(BLIND_TRIM_SAMPLES) {
77 release_free_heap();
78 return true;
79 }
80 return false;
81 };
82 let trimmed_at = TRIMMED_AT_KB.get();
83 if rss_kb < trimmed_at {
84 TRIMMED_AT_KB.set(rss_kb);
85 return false;
86 }
87 if rss_kb - trimmed_at < step_kb() {
88 return false;
89 }
90 release_free_heap();
91 TRIMMED_AT_KB.set(latexml_core::watchdog::process_rss_kb().unwrap_or(rss_kb));
92 true
93}