Skip to main content

latexml_core/
watchdog.rs

1//! Wall-clock watchdog that forcibly aborts the process after a deadline.
2//!
3//! The existing `stomach::check_timeout()` is a cooperative mechanism — it only
4//! fires when the digestion loop polls it. That leaves tight native loops
5//! (Marpa precompute / parse, libxml2 post-processing, FFI calls into libxslt,
6//! ...) completely unguarded: a 60-second timeout can easily turn into 10
7//! minutes if control never returns to the digestion loop.
8//!
9//! This module provides a main-level `Watchdog` that spawns a dedicated thread
10//! at construction, wakes after the specified number of seconds, and — if the
11//! watchdog has not yet been cancelled — prints a message and exits the process
12//! ([`EXIT_TIMEOUT`]). The process dies within `timeout + poll_interval`,
13//! regardless of what the main thread is doing, plus the time one-time setup
14//! spent [`off_the_clock`] (the format build): only its own bound ends that setup.
15//! `--timeout 0` arms no time guard: no deadline, and no bound on the setup (a non-zero `--max-memory` still starts
16//! the watchdog thread for its memory guard).
17//!
18//! # Design notes
19//!
20//! - Uses `Arc<AtomicBool>` for cancellation. Polling every 100 ms keeps the cancellation latency
21//!   low without burning CPU.
22//! - `Drop` on the `Watchdog` handle cancels the watchdog thread, so RAII usage (`let _wd =
23//!   Watchdog::new(secs)`) is sufficient.
24//! - We exit ([`exit_now`]) rather than `panic!` because panic may unwind or be caught by a
25//!   surrounding `catch_unwind`, which would defeat the safety guarantee.
26//! - The existing cooperative `stomach::check_timeout()` path is retained: on most conversions it
27//!   fires before the hard abort, giving callers a nice `Err(Fatal)` with proper error propagation.
28//!   The watchdog is a safety net for the pathological cases where cooperative polling doesn't
29//!   happen. While it runs it also keeps the coarse clock that check reads ([`coarse_now_ns`]).
30//!
31//! # Resource limits
32//!
33//! [`Watchdog::with_limits`] guards
34//! **both** a wall-clock deadline and a
35//! resident-memory ceiling — the two defenses any executable that converts
36//! arbitrary input needs. It is the shared guard reused by both
37//! `cortex_worker` (in-process, one paper per process) and the
38//! `latexml_oxide --server` LSP (run inside each forked body child, which
39//! self-terminates on breach so the parent reaps it via pipe EOF). The exit
40//! codes are distinct so a supervising parent can tell them apart:
41//! `124` = wall-clock timeout, `137` = memory ceiling.
42//!
43//! # Portability
44//!
45//! The wall-clock guard is portable (`std::thread` + `Instant`).
46//!
47//! **Portable:** [`total_memory_bytes`] and [`available_disk_bytes`] answer on
48//! Linux, macOS and Windows — `sysconf(_SC_PHYS_PAGES)`/`statvfs` are POSIX, and
49//! Windows uses `GlobalMemoryStatusEx`/`GetDiskFreeSpaceExW`. They back the
50//! machine-derived default ceiling ([`default_ceiling_mib`]) and the
51//! spill-headroom check, so those behave identically on every supported OS.
52//!
53//! **Enforcement, also portable:** [`process_rss_kb`] — the half that actually
54//! checks live usage against the ceiling — answers on all three: Linux samples
55//! `/proc/self/status`, macOS asks libproc (`proc_pidinfo`), and Windows uses
56//! `GetProcessMemoryInfo`. So the memory ceiling is both computed *and* checked
57//! on every supported OS; other targets fall back to `None` (time guard only).
58
59use std::{
60  sync::{
61    Arc,
62    atomic::{AtomicBool, AtomicI32, AtomicU64, AtomicUsize, Ordering},
63  },
64  thread,
65  time::{Duration, Instant},
66};
67
68/// Current resident set size of this process in KiB, or `None` if it can't be
69/// determined. Linux reads `VmRSS` from `/proc/self/status`; macOS asks
70/// libproc (`proc_pidinfo`/`PROC_PIDTASKINFO`) — without it the whole
71/// `--max-memory` ceiling silently did not exist on macOS, and the
72/// `115_streaming_cli` Fatal-contract guard caught exactly that on macOS CI
73/// (an over-budget run exited 0). Cheap enough to poll a few times a second.
74#[cfg(target_os = "linux")]
75pub fn process_rss_kb() -> Option<u64> {
76  let status = std::fs::read_to_string("/proc/self/status").ok()?;
77  for line in status.lines() {
78    if let Some(rest) = line.strip_prefix("VmRSS:") {
79      return rest.split_whitespace().next()?.parse::<u64>().ok();
80    }
81  }
82  None
83}
84
85/// macOS: libproc task info; `pti_resident_size` is in BYTES.
86#[cfg(target_os = "macos")]
87pub fn process_rss_kb() -> Option<u64> {
88  let mut info: libc::proc_taskinfo = unsafe { std::mem::zeroed() };
89  let size = size_of::<libc::proc_taskinfo>() as libc::c_int;
90  // SAFETY: proc_pidinfo fills at most `size` bytes of the zeroed struct we
91  // own; a short or negative return is handled below.
92  let got = unsafe {
93    libc::proc_pidinfo(
94      std::process::id() as libc::c_int,
95      libc::PROC_PIDTASKINFO,
96      0,
97      (&raw mut info).cast::<libc::c_void>(),
98      size,
99    )
100  };
101  (got == size).then(|| info.pti_resident_size / 1024)
102}
103
104/// Windows: `GetProcessMemoryInfo`'s `WorkingSetSize` is this process's resident
105/// set — the RSS analog the cooperative ceiling needs. Without it the whole
106/// `--max-memory` ceiling silently did not exist on Windows (exactly as it did
107/// not on macOS before the libproc arm), and the `115_streaming_cli`
108/// Fatal-contract guard caught it: an over-budget run exited 0. `windows-sys` is
109/// already linked, and the `K32`-prefixed forwarder lives in kernel32, so this
110/// adds no new DLL import to the self-contained release binary.
111#[cfg(windows)]
112pub fn process_rss_kb() -> Option<u64> {
113  use windows_sys::Win32::System::{
114    ProcessStatus::{K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS},
115    Threading::GetCurrentProcess,
116  };
117  let mut counters: PROCESS_MEMORY_COUNTERS = unsafe { std::mem::zeroed() };
118  counters.cb = size_of::<PROCESS_MEMORY_COUNTERS>() as u32;
119  // SAFETY: `counters` is a correctly sized, zeroed struct with `cb` set, as the
120  // API requires; `GetCurrentProcess` returns a pseudo-handle needing no close.
121  if unsafe { K32GetProcessMemoryInfo(GetCurrentProcess(), &mut counters, counters.cb) } != 0 {
122    return Some(counters.WorkingSetSize as u64 / 1024);
123  }
124  None
125}
126
127/// Other platforms: unknown — the cooperative memory ceiling stays inactive.
128#[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
129pub fn process_rss_kb() -> Option<u64> { None }
130
131/// Kernel-tracked PEAK resident set of this process in KiB (`VmHWM`), or `None`
132/// if it can't be determined. Unlike [`process_rss_kb`]'s point-in-time sample,
133/// this is the true high-water mark over the whole process lifetime — no
134/// sampling cadence can miss a spike — which makes it the honest basis for the
135/// end-of-run "this document needed N" report ([`peak_memory_report`]).
136#[cfg(target_os = "linux")]
137pub fn process_peak_rss_kb() -> Option<u64> {
138  let status = std::fs::read_to_string("/proc/self/status").ok()?;
139  for line in status.lines() {
140    if let Some(rest) = line.strip_prefix("VmHWM:") {
141      return rest.split_whitespace().next()?.parse::<u64>().ok();
142    }
143  }
144  None
145}
146
147/// macOS: `getrusage(RUSAGE_SELF)`; `ru_maxrss` is in BYTES on Darwin.
148#[cfg(target_os = "macos")]
149pub fn process_peak_rss_kb() -> Option<u64> {
150  rusage(libc::RUSAGE_SELF).map(|usage| usage.ru_maxrss as u64 / 1024)
151}
152
153/// `getrusage(who)`, `None` when it fails. The one call site of `getrusage(2)`, which neither `std` nor `rustix`
154/// wraps (issue #937).
155#[cfg(unix)]
156fn rusage(who: libc::c_int) -> Option<libc::rusage> {
157  // SAFETY: a zeroed `rusage` is a valid value; getrusage writes only into the struct we own, read after success.
158  unsafe {
159    let mut usage: libc::rusage = std::mem::zeroed();
160    (libc::getrusage(who, &mut usage) == 0).then_some(usage)
161  }
162}
163
164/// The user and system CPU time of this process's waited-for children (`RUSAGE_CHILDREN`), in microseconds;
165/// `(0, 0)` when it cannot be read.
166#[cfg(unix)]
167pub fn children_cpu_time_us() -> (u64, u64) {
168  rusage(libc::RUSAGE_CHILDREN).map_or((0, 0), |ru| {
169    let user = (ru.ru_utime.tv_sec as u64) * 1_000_000 + (ru.ru_utime.tv_usec as u64);
170    let sys = (ru.ru_stime.tv_sec as u64) * 1_000_000 + (ru.ru_stime.tv_usec as u64);
171    (user, sys)
172  })
173}
174
175/// Other platforms: no children's CPU time.
176#[cfg(not(unix))]
177pub fn children_cpu_time_us() -> (u64, u64) { (0, 0) }
178
179/// Windows: `PeakWorkingSetSize` from the same `GetProcessMemoryInfo` call that
180/// backs [`process_rss_kb`].
181#[cfg(windows)]
182pub fn process_peak_rss_kb() -> Option<u64> {
183  use windows_sys::Win32::System::{
184    ProcessStatus::{K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS},
185    Threading::GetCurrentProcess,
186  };
187  let mut counters: PROCESS_MEMORY_COUNTERS = unsafe { std::mem::zeroed() };
188  counters.cb = size_of::<PROCESS_MEMORY_COUNTERS>() as u32;
189  // SAFETY: `counters` is a correctly sized, zeroed struct with `cb` set, as the
190  // API requires; `GetCurrentProcess` returns a pseudo-handle needing no close.
191  if unsafe { K32GetProcessMemoryInfo(GetCurrentProcess(), &mut counters, counters.cb) } != 0 {
192    return Some(counters.PeakWorkingSetSize as u64 / 1024);
193  }
194  None
195}
196
197/// Other platforms: no peak available — the report line is simply omitted.
198#[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
199pub fn process_peak_rss_kb() -> Option<u64> { None }
200
201/// Latched by the cooperative memory fuse when it raises its
202/// `Timeout:MemoryBudget` Fatal (`stomach::check_timeout`), read at end of run
203/// by [`peak_memory_report`]. An `AtomicBool` static, not a thread-local: the
204/// fuse fires on the conversion thread while the binary's end-of-run reporting
205/// runs on the main thread.
206static MEMORY_FATAL_SEEN: AtomicBool = AtomicBool::new(false);
207
208/// Record that a memory-budget Fatal fired, so the end-of-run report knows
209/// memory was actually the problem.
210pub fn note_memory_fatal() { MEMORY_FATAL_SEEN.store(true, Ordering::Relaxed); }
211
212/// Did a memory-budget Fatal fire since the last `reset_memory_fatal`?
213pub fn memory_fatal_seen() -> bool { MEMORY_FATAL_SEEN.load(Ordering::Relaxed) }
214
215/// Forget a memory-budget Fatal: the CLI restarts a fused EAGER conversion
216/// under `--streaming`, and the end-of-run report must describe the attempt
217/// that produced the output.
218pub fn reset_memory_fatal() { MEMORY_FATAL_SEEN.store(false, Ordering::Relaxed); }
219
220/// The end-of-run memory report — emitted ONLY when a memory-budget Fatal
221/// fired during the run (user directive 2026-08-03: alert when needed, stay
222/// quiet on clean runs). `None` otherwise, or when no peak is measurable.
223///
224/// It reports the kernel-tracked peak and says the document needs MORE — never
225/// a specific sufficient figure, because none is knowable from a truncated
226/// run: the fuse clamped the peak at 75% of the ceiling, and the streaming
227/// spill watermark itself derives from the ceiling, so the true requirement
228/// can only be found by rerunning higher. A document's need scales with macro
229/// expansion and math density, not source bytes (the 131 MB math-dense
230/// witness needs ~23 GB resident just to stream through core), so this
231/// measured figure is the only honest lower bound there is.
232pub fn peak_memory_report() -> Option<String> {
233  if !MEMORY_FATAL_SEEN.load(Ordering::Relaxed) {
234    return None;
235  }
236  let peak_kb = process_peak_rss_kb()?;
237  Some(format!(
238    "peak memory {} MB was not enough: this document needs a higher --max-memory ceiling \
239     (0 disables the limit) and enough free RAM",
240    peak_kb / 1024,
241  ))
242}
243
244/// Total physical RAM on this machine in bytes, or `None` if it cannot be
245/// determined.
246///
247/// Portable by construction: `sysconf(_SC_PHYS_PAGES) * sysconf(_SC_PAGE_SIZE)`
248/// is POSIX and answers on both Linux and macOS, and Windows has
249/// `GlobalMemoryStatusEx`. No new dependency — `libc` and `windows-sys` are
250/// already in the tree.
251///
252/// Deliberately NOT `/proc/meminfo`: that would repeat the Linux-only mistake
253/// this module already carries in [`process_rss_kb`], which returns `None`
254/// everywhere else and so silently deactivates the memory ceiling on
255/// macOS/Windows.
256pub fn total_memory_bytes() -> Option<u64> {
257  #[cfg(unix)]
258  {
259    // SAFETY: `sysconf` is a pure query with no pointer arguments; a negative
260    // return means "unavailable", which we map to `None` rather than trusting.
261    let pages = unsafe { libc::sysconf(libc::_SC_PHYS_PAGES) };
262    // `sysconf(_SC_PAGESIZE)` itself: latexml_core enables rustix's `use-libc-auxv`, so `page_size` reads the libc
263    // auxiliary vector and cannot fail (the raw backend would read `/proc/self/auxv` before Linux 6.4 and panic
264    // without it).
265    let page_size = rustix::param::page_size();
266    if pages > 0 {
267      return (pages as u64).checked_mul(page_size as u64);
268    }
269    None
270  }
271  #[cfg(windows)]
272  {
273    // `MEMORYSTATUSEX` is what windows-sys calls this, mirroring the Win32
274    // header. This arm originally said `GLOBAL_MEMORY_STATUS_EX` — a spelling
275    // from a different generation of the bindings — while Cargo.toml pinned
276    // `windows-sys = "0.61"`, so it never matched the version it declared and
277    // has NEVER compiled. It survived because CI builds Linux and macOS only:
278    // the first Windows compile of this file was the 0.7.5-rc4 RELEASE
279    // workflow, on a tag, days after the code landed. See task #164.
280    use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX};
281    let mut status: MEMORYSTATUSEX = unsafe { std::mem::zeroed() };
282    status.dwLength = size_of::<MEMORYSTATUSEX>() as u32;
283    // SAFETY: `status` is a correctly sized, zeroed struct with `dwLength` set,
284    // exactly as the API requires.
285    if unsafe { GlobalMemoryStatusEx(&mut status) } != 0 {
286      return Some(status.ullTotalPhys);
287    }
288    None
289  }
290  #[cfg(not(any(unix, windows)))]
291  {
292    None
293  }
294}
295
296/// The default per-conversion memory ceiling in MiB, derived from the machine
297/// **as it is right now**.
298///
299/// `min(64 GiB, 90 % of AVAILABLE RAM at startup)`, never above the
300/// cgroup-capped total, floored at [`MIN_DEFAULT_CEILING_MIB`]. When
301/// availability cannot be probed the rule falls back to half of the
302/// (cgroup-capped) total, and to [`FALLBACK_CEILING_MIB`] when nothing can be
303/// probed at all. One sentence for users: *a conversion may use most of the
304/// RAM that is actually free when it starts, never more than 64 GiB.*
305///
306/// History of the rule (each step measured, none guessed):
307/// - flat 6144 MiB — absurd on a 256 GB host, over-generous on a laptop;
308/// - 90 % of TOTAL RAM — laptop-hostile: blind to what the session already
309///   uses, it let one conversion push a busy 16 GB machine deep into swap;
310/// - half of TOTAL RAM — laptop-safe but wasteful the other way: on the 31 GB
311///   witness laptop it derives ~15.5 GiB while the machine sits idle with
312///   ~28 GB free, and the 131 MB witness (24.2 GB core peak) then dies at a
313///   fuse it did not need to meet (user directive 2026-08-01: "we can
314///   comfortably use up to 24 GB here");
315/// - 90 % of AVAILABLE — self-adjusting: on that idle laptop it derives
316///   ~25 GiB, and on the same laptop with a browser session holding 6 GB it
317///   derives roughly what the half-of-total rule chose. `MemAvailable` is the
318///   kernel's own estimate of what is reclaimable without swapping, so "the
319///   session starts swapping long before the guard fires" — the failure that
320///   killed the 90 %-of-total rule — cannot recur by construction.
321///
322/// The **64 GiB cap** is not about this machine but about the *others*: in a
323/// parallel fleet the aggregate is `N_processes x ceiling`, so an uncapped
324/// fraction-of-RAM rule on a big host would let a busy fleet OOM it. The
325/// `cortex_worker` fleet overrides this with its own per-child ceiling anyway;
326/// the cap keeps the single-process default from being reckless.
327///
328/// Startup-derived, deliberately: the figure is resolved once and becomes the
329/// run's `--max-memory`, so a neighbours' later allocations cannot move a
330/// running conversion's fuse mid-flight.
331pub fn default_ceiling_mib() -> u64 {
332  derive_ceiling_mib(available_memory_bytes(), effective_memory_bytes())
333}
334
335/// The pure arithmetic behind [`default_ceiling_mib`], split out so the rule
336/// is unit-testable without controlling the test host's actual memory state.
337fn derive_ceiling_mib(available: Option<u64>, effective_total: Option<u64>) -> u64 {
338  const MIB: u64 = 1024 * 1024;
339  let candidate = match (available, effective_total) {
340    // Headroom rule: 90 % of what is free right now, never above what the
341    // process may use at all (the cgroup-capped total).
342    (Some(avail), Some(total)) => (avail / MIB * 9 / 10).min(total / MIB),
343    (Some(avail), None) => avail / MIB * 9 / 10,
344    // Availability unknown (exotic platform): the conservative half-of-total
345    // rule this default previously shipped.
346    (None, Some(total)) => total / MIB / 2,
347    (None, None) => return FALLBACK_CEILING_MIB,
348  };
349  candidate.clamp(MIN_DEFAULT_CEILING_MIB, MAX_DEFAULT_CEILING_MIB)
350}
351
352/// RAM available for new allocations right now, in bytes, or `None` when the
353/// platform offers no honest answer.
354///
355/// "Available" here means the OS's own estimate of what a new consumer can
356/// take **without pushing the machine into swap** — not merely "free", which
357/// undercounts by excluding reclaimable caches:
358/// - Linux: `MemAvailable` from `/proc/meminfo`, the kernel's purpose-built
359///   estimate (free + reclaimable page cache − watermarks). This is the one
360///   legitimate use of `/proc/meminfo` in this module — availability has no
361///   `sysconf` spelling — and it degrades safely: `None` on any other Unix,
362///   which the ceiling rule answers with the half-of-total fallback.
363/// - Windows: `GlobalMemoryStatusEx`'s `ullAvailPhys`, the direct analog.
364/// - macOS: `host_statistics64` free + inactive pages — inactive is macOS's
365///   reclaimable class, the moral equivalent of Linux's page cache share.
366pub fn available_memory_bytes() -> Option<u64> {
367  #[cfg(target_os = "linux")]
368  {
369    let meminfo = std::fs::read_to_string("/proc/meminfo").ok()?;
370    for line in meminfo.lines() {
371      if let Some(rest) = line.strip_prefix("MemAvailable:") {
372        let kb = rest.split_whitespace().next()?.parse::<u64>().ok()?;
373        return kb.checked_mul(1024);
374      }
375    }
376    None
377  }
378  #[cfg(target_os = "macos")]
379  {
380    let mut stats: libc::vm_statistics64 = unsafe { std::mem::zeroed() };
381    let mut count = (size_of::<libc::vm_statistics64>() / size_of::<libc::integer_t>())
382      as libc::mach_msg_type_number_t;
383    // SAFETY: `stats` is a correctly sized, zeroed struct and `count` names
384    // its capacity in `integer_t` units, exactly as the API requires;
385    // `mach_host_self` returns a send right that need not be deallocated for
386    // a one-shot query in a short-lived process. (`mach2`, not libc's deprecated
387    // `mach_host_self`: libc points Mach APIs to that crate.)
388    let kr = unsafe {
389      libc::host_statistics64(
390        mach2::mach_init::mach_host_self(),
391        libc::HOST_VM_INFO64,
392        (&raw mut stats).cast::<libc::integer_t>(),
393        &mut count,
394      )
395    };
396    if kr != libc::KERN_SUCCESS {
397      return None;
398    }
399    let page_size = rustix::param::page_size();
400    (stats.free_count as u64 + stats.inactive_count as u64).checked_mul(page_size as u64)
401  }
402  #[cfg(windows)]
403  {
404    use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX};
405    let mut status: MEMORYSTATUSEX = unsafe { std::mem::zeroed() };
406    status.dwLength = size_of::<MEMORYSTATUSEX>() as u32;
407    // SAFETY: `status` is a correctly sized, zeroed struct with `dwLength`
408    // set, exactly as the API requires.
409    if unsafe { GlobalMemoryStatusEx(&mut status) } != 0 {
410      return Some(status.ullAvailPhys);
411    }
412    None
413  }
414  #[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
415  {
416    None
417  }
418}
419
420/// Memory this PROCESS may actually use: physical RAM, capped by the cgroup
421/// limit when one is in force.
422///
423/// `total_memory_bytes` reports the HOST's RAM (`sysconf(_SC_PHYS_PAGES)`),
424/// which is blind to containers — so `docker run -m 4g` on a 258 GB host chose
425/// a 64 GiB ceiling and a 48 GiB cooperative fuse, neither of which the process
426/// could ever reach. The kernel killed it at 4 GB instead: exit 137, no output,
427/// no `Fatal:` line — exactly the failure the graceful guard exists to replace.
428/// The cortex fleet is only accidentally safe here, because it pins every child
429/// with `--max-rss-mb`; a plain containerized CLI user is not.
430fn effective_memory_bytes() -> Option<u64> {
431  let physical = total_memory_bytes();
432  match (physical, cgroup_limit_bytes()) {
433    (Some(p), Some(c)) => Some(p.min(c)),
434    (p, None) => p,
435    (None, c) => c,
436  }
437}
438
439/// The cgroup memory limit, v2 then v1, or `None` when unlimited/unreadable.
440///
441/// Both spell "unlimited" in their own way: v2 writes the literal `max`, v1
442/// writes a huge sentinel (`u64::MAX` rounded down to a page multiple), so a
443/// value at or above the host's RAM is treated as no limit rather than as a
444/// bound worth honouring.
445fn cgroup_limit_bytes() -> Option<u64> {
446  let v2 = std::fs::read_to_string("/sys/fs/cgroup/memory.max").ok();
447  let v1 = || std::fs::read_to_string("/sys/fs/cgroup/memory/memory.limit_in_bytes").ok();
448  let raw = v2.or_else(v1)?;
449  interpret_cgroup_limit(&raw, total_memory_bytes())
450}
451
452/// Decide what a cgroup limit file MEANS. Split out from the file read so the
453/// rules are testable without a container: the reachable spellings of
454/// "unlimited" are what make this subtle.
455fn interpret_cgroup_limit(raw: &str, physical: Option<u64>) -> Option<u64> {
456  let text = raw.trim();
457  // cgroup v2 spells unlimited literally.
458  if text == "max" {
459    return None;
460  }
461  let limit = text.parse::<u64>().ok()?;
462  // cgroup v1 spells it as a huge sentinel, and a "limit" at or above the
463  // host's RAM bounds nothing — treat both as no limit rather than as a
464  // ceiling worth honouring.
465  if limit == 0 || physical.is_some_and(|phys| limit >= phys) {
466    return None;
467  }
468  Some(limit)
469}
470
471/// Floor for the machine-derived default, so a small container still gets a
472/// workable budget rather than a ceiling no conversion can fit under.
473pub const MIN_DEFAULT_CEILING_MIB: u64 = 2048;
474
475/// Upper bound on the machine-derived default ceiling (64 GiB in MiB).
476pub const MAX_DEFAULT_CEILING_MIB: u64 = 64 * 1024;
477
478/// Ceiling used when the machine's RAM cannot be probed — the historical flat
479/// default, kept so an unprobeable platform behaves exactly as before rather
480/// than losing its guard entirely.
481pub const FALLBACK_CEILING_MIB: u64 = 6144;
482
483/// Free space in bytes on the filesystem holding `path`, or `None` if it cannot
484/// be determined. Used to check headroom before spilling intermediates to disk.
485pub fn available_disk_bytes(path: &std::path::Path) -> Option<u64> {
486  #[cfg(unix)]
487  {
488    // (a path holding a NUL is an `Err`, as `CString::new` refused it)
489    let stat = rustix::fs::statvfs(path).ok()?;
490    // `f_bavail` is blocks available to unprivileged users — the honest figure,
491    // as `f_bfree` includes the root-reserved slice we cannot use.
492    stat.f_bavail.checked_mul(stat.f_frsize)
493  }
494  #[cfg(windows)]
495  {
496    use std::os::windows::ffi::OsStrExt;
497
498    use windows_sys::Win32::Storage::FileSystem::GetDiskFreeSpaceExW;
499    let mut wide: Vec<u16> = path.as_os_str().encode_wide().collect();
500    wide.push(0);
501    let mut free_to_caller: u64 = 0;
502    // SAFETY: `wide` is NUL-terminated and outlives the call; the two unused
503    // out-parameters are passed as null, which the API permits.
504    let ok = unsafe {
505      GetDiskFreeSpaceExW(
506        wide.as_ptr(),
507        &mut free_to_caller,
508        std::ptr::null_mut(),
509        std::ptr::null_mut(),
510      )
511    };
512    (ok != 0).then_some(free_to_caller)
513  }
514  #[cfg(not(any(unix, windows)))]
515  {
516    let _ = path;
517    None
518  }
519}
520
521/// Exit code used when the wall-clock deadline is exceeded (standard `timeout`).
522pub const EXIT_TIMEOUT: i32 = 124;
523/// Exit code used when the memory ceiling is exceeded (128 + SIGKILL).
524pub const EXIT_OOM: i32 = 137;
525
526/// Handle to a watchdog thread. Cancels on drop.
527///
528/// `Watchdog::new(0)` is a no-op — produces a handle that does nothing. This
529/// lets call-sites set a watchdog conditionally without special-casing the
530/// "no timeout" branch.
531/// Optional hook to run from the watchdog thread immediately before its
532/// exit, called with the exit code it is about to take ([`EXIT_TIMEOUT`] or
533/// [`EXIT_OOM`]). Used by `cortex_worker --standalone` to write a
534/// structured `Status:conversion:3` placeholder to `--output` so the
535/// exit produces a usable failure artifact instead of a missing
536/// file, and by a `cortex_worker` harness child to record the cause of its
537/// exit for the harness. Set once at startup via `set_pre_exit_hook`; the hook is
538/// invoked exactly once. Zero overhead on the happy path — only the
539/// watchdog firing reads it. The process then ends through [`exit_now`], which flushes
540/// nothing: the hook writes, finishes and closes what it leaves before it returns.
541type PreExitHook = Box<dyn FnOnce(i32) + Send + 'static>;
542
543static PRE_EXIT_HOOK: std::sync::OnceLock<std::sync::Mutex<Option<PreExitHook>>> =
544  std::sync::OnceLock::new();
545
546pub fn set_pre_exit_hook(hook: PreExitHook) {
547  let cell = PRE_EXIT_HOOK.get_or_init(|| std::sync::Mutex::new(None));
548  if let Ok(mut guard) = cell.lock() {
549    *guard = Some(hook);
550  }
551}
552
553fn run_pre_exit_hook(code: i32) {
554  if let Some(cell) = PRE_EXIT_HOOK.get()
555    && let Ok(mut guard) = cell.lock()
556    && let Some(hook) = guard.take()
557  {
558    hook(code);
559  }
560}
561
562/// Paths a run created that an exit skipping destructors would leave behind — an unpacked archive (a `TempDir`), the
563/// destination, the post page-spill directory: the watchdog's `exit(124)`/`exit(EXIT_OOM)` and the binaries'
564/// allocation-failure hooks call [`remove_registered_paths`] first. On the normal path a path's owner removes it, and
565/// its [`RemoveOnExit`] guard unregisters it. (A `panic = "abort"` build of `cortex_worker` still leaves them on a
566/// panic; `latexml_oxide`'s panic hook removes them.)
567static REMOVE_ON_EXIT: std::sync::Mutex<Vec<(u64, std::path::PathBuf)>> =
568  std::sync::Mutex::new(Vec::new());
569static NEXT_REMOVE_ON_EXIT: AtomicU64 = AtomicU64::new(0);
570
571/// Keeps a path registered with [`remove_registered_paths`]; unregisters it when dropped.
572#[must_use = "the path is unregistered when this guard is dropped"]
573pub struct RemoveOnExit(u64);
574
575impl Drop for RemoveOnExit {
576  fn drop(&mut self) { registry().retain(|(id, _)| *id != self.0); }
577}
578
579/// The registry, its lock poison-tolerant: no critical section can leave it inconsistent.
580fn registry() -> std::sync::MutexGuard<'static, Vec<(u64, std::path::PathBuf)>> {
581  REMOVE_ON_EXIT
582    .lock()
583    .unwrap_or_else(std::sync::PoisonError::into_inner)
584}
585
586/// Registers `path` for removal by [`remove_registered_paths`] while the returned guard lives.
587pub fn remove_on_exit(path: &std::path::Path) -> RemoveOnExit {
588  let id = NEXT_REMOVE_ON_EXIT.fetch_add(1, Ordering::Relaxed);
589  registry().push((id, path.to_path_buf()));
590  RemoveOnExit(id)
591}
592
593/// Child processes a run started that an exit skipping destructors would orphan: a document's `texlua` spinning in
594/// `while true do end` outlived a `Fatal:timeout:wallclock` at 100 % CPU (OXIDIZED_DESIGN_DIVERGENCES #1081). The exits
595/// kill them ([`kill_registered_children`]); on the normal path the [`KillOnExit`] guard ends and reaps its child.
596static KILL_ON_EXIT: std::sync::Mutex<Vec<(u64, std::process::Child)>> =
597  std::sync::Mutex::new(Vec::new());
598
599/// Holds a child registered with [`kill_registered_children`]; dropping it kills, reaps and unregisters the child.
600#[must_use = "the child is killed when this guard is dropped"]
601pub struct KillOnExit(u64);
602
603/// Registers `child` to be killed by the exits that skip destructors, for as long as the returned guard lives.
604pub fn kill_on_exit(child: std::process::Child) -> KillOnExit {
605  let id = NEXT_REMOVE_ON_EXIT.fetch_add(1, Ordering::Relaxed);
606  children().push((id, child));
607  KillOnExit(id)
608}
609
610impl KillOnExit {
611  /// Ends the child and says how it ended: its own exit status when it exits within `grace` (a child whose pipe
612  /// closed is ending), `None` when it is still running then (the guard's drop kills it) or is already gone.
613  pub fn finish(self, grace: Duration) -> Option<std::process::ExitStatus> {
614    let deadline = Instant::now() + grace;
615    loop {
616      let status = {
617        let mut children = children();
618        let (_, child) = children.iter_mut().find(|(id, _)| *id == self.0)?;
619        child.try_wait().ok().flatten()
620      };
621      if status.is_some() || Instant::now() >= deadline {
622        return status;
623      }
624      thread::sleep(Duration::from_millis(5));
625    }
626  }
627}
628
629impl Drop for KillOnExit {
630  fn drop(&mut self) {
631    let child = {
632      let mut children = children();
633      let index = children.iter().position(|(id, _)| *id == self.0);
634      index.map(|index| children.swap_remove(index).1)
635    };
636    if let Some(mut child) = child {
637      let _ = child.kill();
638      let _ = child.wait();
639    }
640  }
641}
642
643fn children() -> std::sync::MutexGuard<'static, Vec<(u64, std::process::Child)>> {
644  KILL_ON_EXIT
645    .lock()
646    .unwrap_or_else(std::sync::PoisonError::into_inner)
647}
648
649/// Child PIDs registered by callers that must retain ownership of `Child` (for
650/// piped `wait_with_output`, e.g. parallel page-render workers, graphics
651/// converters, Rhai `Command::output`). `kill_group = true` signals the child's
652/// process group on Unix (`setsid`-detached converters like `graphics.rs`).
653static KILL_PIDS_ON_EXIT: std::sync::Mutex<Vec<(u64, u32, bool)>> =
654  std::sync::Mutex::new(Vec::new());
655
656/// Keeps a child PID registered with [`kill_registered_children`]; dropping it
657/// unregisters the PID (the owner is responsible for normal waiting/reaping).
658#[must_use = "the child PID is unregistered when this guard is dropped"]
659pub struct KillPidOnExit(u64);
660
661impl Drop for KillPidOnExit {
662  fn drop(&mut self) {
663    let mut pids = kill_pids();
664    if let Some(index) = pids.iter().position(|(id, ..)| *id == self.0) {
665      pids.swap_remove(index);
666    }
667  }
668}
669
670fn kill_pids() -> std::sync::MutexGuard<'static, Vec<(u64, u32, bool)>> {
671  KILL_PIDS_ON_EXIT
672    .lock()
673    .unwrap_or_else(std::sync::PoisonError::into_inner)
674}
675
676/// Registers `pid` to be killed by exits that skip destructors (watchdog
677/// timeout/OOM, allocation failure), for as long as the returned guard lives.
678/// Set `kill_group = true` when the child is a Unix process-group leader.
679pub fn kill_pid_on_exit(pid: u32, kill_group: bool) -> KillPidOnExit {
680  let id = NEXT_REMOVE_ON_EXIT.fetch_add(1, Ordering::Relaxed);
681  kill_pids().push((id, pid, kill_group));
682  KillPidOnExit(id)
683}
684
685/// Best-effort graceful `SIGTERM` to a Unix child's process group (no-op on
686/// non-Unix). Safe wrapper over `rustix::process::kill_process_group`.
687pub fn signal_group_term(pid: u32) {
688  #[cfg(unix)]
689  {
690    use rustix::process::{Pid, Signal, kill_process_group};
691    if let Some(pid) = i32::try_from(pid).ok().and_then(Pid::from_raw) {
692      let _ = kill_process_group(pid, Signal::TERM);
693    }
694  }
695  #[cfg(not(unix))]
696  {
697    let _ = pid;
698  }
699}
700
701/// Best-effort immediate termination of a child PID (or its Unix process group
702/// when `kill_group` is true). Portable across Unix and Windows, with zero
703/// `unsafe` (uses `rustix::process` on Unix and `taskkill /T /F` on Windows).
704pub fn kill_pid(pid: u32, kill_group: bool) {
705  if pid == 0 {
706    return;
707  }
708  #[cfg(unix)]
709  {
710    use rustix::process::{Pid, Signal, kill_process, kill_process_group};
711    if let Some(pid) = i32::try_from(pid).ok().and_then(Pid::from_raw) {
712      if kill_group {
713        let _ = kill_process_group(pid, Signal::KILL);
714      }
715      let _ = kill_process(pid, Signal::KILL);
716    }
717  }
718  #[cfg(windows)]
719  {
720    let _ = kill_group;
721    let _ = std::process::Command::new("taskkill")
722      .args(["/PID", &pid.to_string(), "/T", "/F"])
723      .stdin(std::process::Stdio::null())
724      .stdout(std::process::Stdio::null())
725      .stderr(std::process::Stdio::null())
726      .output();
727  }
728  #[cfg(not(any(unix, windows)))]
729  {
730    let _ = (pid, kill_group);
731  }
732}
733
734/// Kills every registered child (the exiting process does not wait for them; they are reparented and reaped).
735pub fn kill_registered_children() {
736  for (_, child) in children().iter_mut() {
737    let _ = child.kill();
738  }
739  for &(_, pid, kill_group) in kill_pids().iter() {
740    kill_pid(pid, kill_group);
741  }
742}
743
744/// [`kill_registered_children`] for an allocation-failure or panic hook: it gives up rather than wait for the lock.
745pub fn try_kill_registered_children() {
746  if let Ok(mut children) = KILL_ON_EXIT.try_lock() {
747    for (_, child) in children.iter_mut() {
748      let _ = child.kill();
749    }
750  }
751  if let Ok(pids) = KILL_PIDS_ON_EXIT.try_lock() {
752    for &(_, pid, kill_group) in pids.iter() {
753      kill_pid(pid, kill_group);
754    }
755  }
756}
757
758/// Removes every registered path, directories with their contents: for the exits that skip destructors.
759pub fn remove_registered_paths() { remove_paths(std::mem::take(&mut *registry())); }
760
761/// [`remove_registered_paths`] (after [`try_kill_registered_children`]) for an allocation-failure hook, which may have
762/// interrupted the registry's holder: it gives up rather than wait for the lock. It claims the exit first, as the watchdog does: in a worker pool the sweep
763/// takes every job's trees, and the other threads must not hand on results built over them.
764pub fn try_remove_registered_paths() {
765  let _ = claim_exit(EXIT_OOM);
766  try_kill_registered_children();
767  let paths = match REMOVE_ON_EXIT.try_lock() {
768    Ok(mut paths) => std::mem::take(&mut *paths),
769    Err(_) => return,
770  };
771  remove_paths(paths);
772}
773
774fn remove_paths(paths: Vec<(u64, std::path::PathBuf)>) {
775  for (_, path) in paths {
776    let _ = if path.is_dir() {
777      std::fs::remove_dir_all(&path)
778    } else {
779      std::fs::remove_file(&path)
780    };
781  }
782}
783
784/// Set by the first allocation failure that reaches a binary's allocation-failure hook.
785static ALLOC_FAILURE: AtomicBool = AtomicBool::new(false);
786
787/// The binary's allocation-failure hook, which ends the process. Stable Rust has no `set_alloc_error_hook`, so the
788/// binaries' global allocator (`latexml::alloc_hook::HookedAlloc`) calls it through [`alloc_failed`].
789static ALLOC_FAILURE_HOOK: std::sync::OnceLock<fn(std::alloc::Layout) -> !> =
790  std::sync::OnceLock::new();
791
792/// Registers the binary's allocation-failure hook, first thing in `main`; a second registration is ignored.
793pub fn set_alloc_failure_hook(hook: fn(std::alloc::Layout) -> !) {
794  let _ = ALLOC_FAILURE_HOOK.set(hook);
795}
796
797/// Ends the process for an allocation of `layout` that failed: through the registered hook, or where none is (a test
798/// binary, an embedder) through std's default (`handle_alloc_error`: one line, then abort). Allocates nothing. Never
799/// inlined: every allocation failure passes this frame (the global allocator's and libxml2's XPath one), so the hooks'
800/// line names it as the debugger breakpoint.
801#[cold]
802#[inline(never)]
803pub fn alloc_failed(layout: std::alloc::Layout) -> ! {
804  match ALLOC_FAILURE_HOOK.get() {
805    Some(hook) => hook(layout),
806    None => std::alloc::handle_alloc_error(layout),
807  }
808}
809
810std::thread_local! {
811  /// Whether this thread is inside the allocation-failure hook (const-initialized, no destructor:
812  /// reading it allocates nothing).
813  static IN_ALLOC_FAILURE_HOOK: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
814}
815
816/// The first call of a binary's allocation-failure hook. The hook then runs alone and without
817/// allocating: it writes its line ([`write_stderr_unlocked`]), sweeps the run's trees
818/// ([`try_remove_registered_paths`]) and ends the process ([`exit_now`]).
819///
820/// When memory is spent, anything the hook allocates fails as well and calls the hook again, on the
821/// same thread. Run again, it would allocate again: a fleet child printed 6,048 nested
822/// `Fatal:oom:alloc_failed` lines in a millisecond (each re-entry failing at reading
823/// `RUST_BACKTRACE`, 1 byte). Or it would wait forever. The old hook formatted a backtrace while
824/// holding the standard library's backtrace lock and the stderr lock. Symbolizing the backtrace
825/// allocated, the re-entered hook waited on the backtrace lock, and the watchdog's own
826/// `Fatal:timeout` waited on stderr. The child stayed parked until the harness killed it as
827/// unresponsive and re-leased its paper (run 351, 2026-10-14; 1804.07640 among the papers). So a
828/// re-entry on the same thread ends the process at once. An allocation failure on another thread
829/// meanwhile waits for the first thread's exit, and exits itself if that has not come in ten seconds.
830pub fn enter_alloc_failure_hook() {
831  if IN_ALLOC_FAILURE_HOOK
832    .try_with(|inside| inside.replace(true))
833    .unwrap_or(true)
834  {
835    exit_now(EXIT_OOM);
836  }
837  if ALLOC_FAILURE.swap(true, Ordering::AcqRel) {
838    for _ in 0..10 {
839      thread::sleep(Duration::from_secs(1));
840    }
841    exit_now(EXIT_OOM);
842  }
843}
844
845/// Ends the process now with `code`: `_exit`, without the atexit handlers, destructors and stream
846/// flushes of [`std::process::exit`], any of which can allocate or wait on a lock held by a thread
847/// that will never release it. Every exit taken while another thread may still run goes through it:
848/// `exit` runs the libraries' destructors under that thread (libxml2's `.fini_array` calls
849/// `xmlCleanupParser`, freeing the catalog, encoding aliases, dict mutexes and global-state key a
850/// running render reads: a render worker's SIGSEGV with ip == fault address in freed heap, on Nasser's
851/// 2,400-problem slice under concurrent load, issue #777, not reproduced). What
852/// must land is written first, unbuffered: the stderr line ([`write_stderr_unlocked`]), the log
853/// mirror (an unbuffered `write(2)`), a pre-exit hook's file. Only a partial line still in stdout's
854/// line buffer is lost.
855pub fn exit_now(code: i32) -> ! {
856  #[cfg(unix)]
857  // SAFETY: `_exit` takes no pointers and does not return.
858  unsafe {
859    libc::_exit(code)
860  }
861  #[cfg(not(unix))]
862  std::process::exit(code)
863}
864
865/// Writes `args` to standard error in one `write(2)`, formatted into a stack buffer (cut at 1 KiB).
866/// Unlike `eprintln!` it neither allocates nor takes the standard library's stderr lock. That makes
867/// it safe in an allocation-failure hook, and for the watchdog when a stuck thread holds that lock.
868/// It opens a fresh line when a progress note left stderr mid-line, as the logger's records do: a
869/// `Fatal:timeout:wallclock` glued onto `(Processing definitions …l3backend-pdftex.def... )` escaped
870/// every `^Fatal:` count.
871pub fn write_stderr_unlocked(args: std::fmt::Arguments) {
872  struct StackLine {
873    bytes: [u8; 1024],
874    len:   usize,
875  }
876  impl std::fmt::Write for StackLine {
877    fn write_str(&mut self, text: &str) -> std::fmt::Result {
878      let take = text.len().min(self.bytes.len() - self.len);
879      self.bytes[self.len..self.len + take].copy_from_slice(&text.as_bytes()[..take]);
880      self.len += take;
881      Ok(())
882    }
883  }
884  let mut line = StackLine { bytes: [0; 1024], len: 0 };
885  if !crate::util::logger::stderr_at_line_start() {
886    line.bytes[0] = b'\n';
887    line.len = 1;
888  }
889  let _ = std::fmt::write(&mut line, args);
890  if line.len > 0 {
891    crate::util::logger::set_stderr_at_line_start(line.bytes[line.len - 1] == b'\n');
892  }
893  #[cfg(unix)]
894  let _ = rustix::io::write(rustix::stdio::stderr(), &line.bytes[..line.len]);
895  #[cfg(not(unix))]
896  {
897    use std::io::Write;
898    let _ = std::io::stderr().write_all(&line.bytes[..line.len]);
899  }
900}
901
902/// The exit code claimed when the watchdog (or an allocation-failure hook) begins to exit, 0 while none is. Its sweep
903/// deletes the run's trees while the other threads still run, and one finishing in that window must neither exit first
904/// with its own code (the first `exit` wins) nor hand on output built over the deleted trees: [`park_if_exiting`] holds
905/// it until the claimed exit ends the process. [`NORMAL_END`] while the normal path hands on its result.
906static EXITING: AtomicI32 = AtomicI32::new(0);
907
908/// [`EXITING`] once the normal path has claimed the process's end ([`claim_normal_end`]).
909const NORMAL_END: i32 = -1;
910
911/// Claims the exit with `code` (the first claim stands); false once the normal path claimed the end.
912fn claim_exit(code: i32) -> bool {
913  match EXITING.compare_exchange(0, code, Ordering::AcqRel, Ordering::Acquire) {
914    Ok(_) => true,
915    Err(held) => held != NORMAL_END,
916  }
917}
918
919/// Claims the process's end for the normal path before a single-run binary hands on its result: a breach after it
920/// stands down, where its pre-exit hook would overwrite the written result with its placeholder (cortex_worker
921/// `--standalone --output`). When a breach claimed first, parks ([`park_if_exiting`]) until its exit.
922pub fn claim_normal_end() {
923  if EXITING
924    .compare_exchange(0, NORMAL_END, Ordering::AcqRel, Ordering::Acquire)
925    .is_err()
926  {
927    park_if_exiting();
928  }
929}
930
931/// Parks the calling thread once the watchdog has begun to exit, until that exit ends the process. Called before every
932/// exit and result hand-off a timed-out run could race (the binaries' final exits, cortex_worker's results). Bounded: if
933/// the exit has not come within a minute (a pre-exit hook that blocked, or a sweep slower than that, which it then cuts
934/// short) the thread exits itself, with the claimed code, through [`exit_now`]: the watchdog thread still runs.
935pub fn park_if_exiting() {
936  let code = EXITING.load(Ordering::Acquire);
937  if code > 0 {
938    let deadline = Instant::now() + Duration::from_secs(60);
939    while let Some(left) = deadline.checked_duration_since(Instant::now()) {
940      thread::park_timeout(left);
941    }
942    exit_now(code);
943  }
944}
945
946/// The memory breach's line. The fleet classifies on its `Fatal:oom:rss` prefix; the advice names the flag that set
947/// the ceiling (`cortex_worker` has no `--max-memory`, row R CORTEXRSS), or none.
948fn oom_rss_message(rss_kb: u64, max_rss_kb: u64, memory_knob: Option<&str>) -> String {
949  let advice = match memory_knob {
950    Some(knob) => format!(": rerun with a higher {knob} on a machine with enough free RAM"),
951    None => String::new(),
952  };
953  format!(
954    "Fatal:oom:rss latexml-oxide: resident memory {}MB exceeded the {}MB ceiling — exiting process. This document \
955     needs a larger ceiling{advice}.",
956    rss_kb / 1024,
957    max_rss_kb / 1024
958  )
959}
960
961/// Setup kept off every deadline ([`off_the_clock`]), read without a lock (`stomach::check_timeout` is on the hot path):
962/// the time the finished setups took, and the running one's start (nanoseconds from [`epoch`], plus one; 0: none).
963static SETUP_DONE_NS: AtomicU64 = AtomicU64::new(0);
964static SETUP_SINCE_NS: AtomicU64 = AtomicU64::new(0);
965
966/// The running setup's nesting depth, what it is and its bound (the outermost call's): taken by the setup's calls and
967/// the watchdog's poll, never by a deadline check.
968static SETUP_RUNNING: std::sync::Mutex<(u32, &str, Duration)> =
969  std::sync::Mutex::new((0, "", Duration::ZERO));
970
971fn setup_running() -> std::sync::MutexGuard<'static, (u32, &'static str, Duration)> {
972  SETUP_RUNNING
973    .lock()
974    .unwrap_or_else(std::sync::PoisonError::into_inner)
975}
976
977fn epoch() -> Instant {
978  static EPOCH: std::sync::OnceLock<Instant> = std::sync::OnceLock::new();
979  *EPOCH.get_or_init(Instant::now)
980}
981
982pub(crate) fn nanos_since_epoch(at: Instant) -> u64 {
983  u64::try_from(at.saturating_duration_since(epoch()).as_nanos()).unwrap_or(u64::MAX)
984}
985
986/// The coarse clock running watchdogs keep for `stomach::check_timeout`, which reads it on its hot path instead of
987/// `Instant::now` (a vDSO call): nanoseconds from [`epoch`], published at each poll while [`ACTIVE_WATCHDOGS`] > 0.
988static WATCHDOG_NOW_NS: AtomicU64 = AtomicU64::new(0);
989static ACTIVE_WATCHDOGS: AtomicUsize = AtomicUsize::new(0);
990/// The cooperative deadline last set (`stomach::set_timeout`) and the time off the clock then: the watchdog publishes
991/// the clock as it passes (moved by setup since, as `stomach` reads it) and gives the cooperative check a poll before
992/// it breaches the same deadline. Taken by `set_timeout` and the poll, never by a check.
993static COOPERATIVE_DEADLINE: std::sync::Mutex<Option<(Instant, Duration)>> =
994  std::sync::Mutex::new(None);
995
996/// The coarse clock's last reading, at most one poll old, while a watchdog runs; `None` without one (the LSP
997/// server's in-process path, the tests, an embedder), where the caller reads `Instant::now`.
998pub fn coarse_now_ns() -> Option<u64> {
999  (ACTIVE_WATCHDOGS.load(Ordering::Acquire) > 0).then(|| WATCHDOG_NOW_NS.load(Ordering::Relaxed))
1000}
1001
1002/// Records the cooperative deadline, set when [`time_off_the_clock`] read `off_at_set`, for the watchdog's poll; `None`
1003/// clears it.
1004pub(crate) fn note_cooperative_deadline(deadline: Option<(Instant, Duration)>) {
1005  *COOPERATIVE_DEADLINE
1006    .lock()
1007    .unwrap_or_else(std::sync::PoisonError::into_inner) = deadline;
1008}
1009
1010/// The cooperative deadline as the check reads it now, moved by the setup since it was set ([`deadline_ns_lower_bound`]).
1011fn cooperative_deadline_ns() -> Option<u64> {
1012  let deadline = *COOPERATIVE_DEADLINE
1013    .lock()
1014    .unwrap_or_else(std::sync::PoisonError::into_inner);
1015  deadline.map(|(at, off_at_set)| deadline_ns_lower_bound(at, off_at_set))
1016}
1017
1018/// Publishes the clock; returns the coarse clock's reading after it.
1019fn publish_now() -> u64 {
1020  let now = nanos_since_epoch(Instant::now());
1021  WATCHDOG_NOW_NS.fetch_max(now, Ordering::Relaxed).max(now)
1022}
1023
1024/// One running watchdog's share of the coarse clock: it publishes before it counts (a reader that sees the count
1025/// sees a reading), and stops counting on its return. (No watchdog runs across a `fork`: the LSP server's parent
1026/// arms none, its body child its own.)
1027struct CoarseClock;
1028
1029impl CoarseClock {
1030  fn keep() -> Self {
1031    publish_now();
1032    ACTIVE_WATCHDOGS.fetch_add(1, Ordering::Release);
1033    CoarseClock
1034  }
1035}
1036
1037impl Drop for CoarseClock {
1038  fn drop(&mut self) { ACTIVE_WATCHDOGS.fetch_sub(1, Ordering::Release); }
1039}
1040
1041/// Sleeps one poll, publishing the clock on the way as the (moved) cooperative deadline `cooperative_ns` passes.
1042fn sleep_one_poll(poll_interval: Duration, cooperative_ns: Option<u64>) {
1043  let wake = Instant::now() + poll_interval;
1044  if let Some(ns) = cooperative_ns {
1045    let at = epoch() + Duration::from_nanos(ns);
1046    let now = Instant::now();
1047    if now < at && at < wake {
1048      thread::sleep(at - now);
1049      publish_now();
1050    }
1051  }
1052  thread::sleep(wake.saturating_duration_since(Instant::now()));
1053}
1054
1055/// Runs `work`, one-time setup that is not the conversion's (`what`: the format build for the host's TeX tree), off
1056/// every deadline: the watchdog's and the cooperative one (`stomach::set_timeout`) move back by the time it takes,
1057/// and while it runs only `bound` ends it, a watchdog's breach (exit 124). Calls nest: the outermost one's time and
1058/// bound count. Without a watchdog (`--timeout 0`) nothing bounds it.
1059pub fn off_the_clock<T>(what: &'static str, bound: Duration, work: impl FnOnce() -> T) -> T {
1060  let _running = OffTheClock::enter(what, bound);
1061  work()
1062}
1063
1064/// One [`off_the_clock`] call's share of the running setup; its drop ends the setup when it is the outermost, a
1065/// panic's unwinding included.
1066struct OffTheClock;
1067
1068impl OffTheClock {
1069  fn enter(what: &'static str, bound: Duration) -> Self {
1070    let mut running = setup_running();
1071    if running.0 == 0 {
1072      *running = (0, what, bound);
1073      SETUP_SINCE_NS.store(nanos_since_epoch(Instant::now()) + 1, Ordering::Release);
1074    }
1075    running.0 += 1;
1076    OffTheClock
1077  }
1078}
1079
1080impl Drop for OffTheClock {
1081  fn drop(&mut self) {
1082    let mut running = setup_running();
1083    running.0 -= 1;
1084    if running.0 == 0 {
1085      let since = SETUP_SINCE_NS.load(Ordering::Acquire).saturating_sub(1);
1086      let took = nanos_since_epoch(Instant::now()).saturating_sub(since);
1087      // Added before the start is cleared: a reader that sees no running setup sees its time (one between may count
1088      // it twice, a later deadline, never an early one).
1089      SETUP_DONE_NS.fetch_add(took, Ordering::AcqRel);
1090      SETUP_SINCE_NS.store(0, Ordering::Release);
1091    }
1092  }
1093}
1094
1095/// The time [`off_the_clock`] setup has taken in this process so far, the running one's included.
1096pub fn time_off_the_clock() -> Duration {
1097  let since = SETUP_SINCE_NS.load(Ordering::Acquire);
1098  let done = SETUP_DONE_NS.load(Ordering::Acquire);
1099  let running = since.checked_sub(1).map_or(0, |since| {
1100    nanos_since_epoch(Instant::now()).saturating_sub(since)
1101  });
1102  Duration::from_nanos(done.saturating_add(running))
1103}
1104
1105/// Whether `deadline`, set when [`time_off_the_clock`] read `off_at_set`, has passed once the setup since is taken off
1106/// the clock: the one test of both the watchdog and the cooperative deadline.
1107pub fn deadline_passed(deadline: Instant, off_at_set: Duration) -> bool {
1108  let now = Instant::now();
1109  // The setup only defers a deadline: before it, no atomic is read.
1110  now > deadline && now > deadline + time_off_the_clock().saturating_sub(off_at_set)
1111}
1112
1113/// The earliest the coarse clock can show `deadline` (as [`deadline_passed`] reads it) passed: moved by the setup so
1114/// far, which only grows.
1115pub(crate) fn deadline_ns_lower_bound(deadline: Instant, off_at_set: Duration) -> u64 {
1116  let moved = time_off_the_clock().saturating_sub(off_at_set);
1117  nanos_since_epoch(deadline).saturating_add(u64::try_from(moved.as_nanos()).unwrap_or(u64::MAX))
1118}
1119
1120/// The running setup and its bound, once it has run past that bound (what the watchdog's breach line names).
1121pub fn setup_past_bound() -> Option<(&'static str, Duration)> {
1122  let (depth, what, bound) = *setup_running();
1123  let since = SETUP_SINCE_NS.load(Ordering::Acquire).checked_sub(1)?;
1124  let ran = Duration::from_nanos(nanos_since_epoch(Instant::now()).saturating_sub(since));
1125  (depth > 0 && ran >= bound).then_some((what, bound))
1126}
1127
1128pub struct Watchdog {
1129  cancelled: Arc<AtomicBool>,
1130}
1131
1132impl Watchdog {
1133  /// Create a wall-clock-only watchdog. `timeout_secs = 0` disables it.
1134  /// Equivalent to [`Watchdog::with_limits(timeout_secs, 0, None)`].
1135  pub fn new(timeout_secs: u64) -> Self { Self::with_limits(timeout_secs, 0, None) }
1136
1137  /// Create a watchdog guarding a wall-clock deadline **and** a resident-memory
1138  /// ceiling. `timeout_secs = 0` disables the time guard; `max_rss_kb = 0`
1139  /// disables the memory guard. With both `0` this is a no-op handle. `memory_knob` is the flag that set the
1140  /// ceiling (`--max-memory`, `cortex_worker`'s `--max-rss-mb`), for the breach's Fatal to name; `None` names none.
1141  ///
1142  /// The thread polls `cancelled`, the deadline, and RSS every `poll_interval`.
1143  /// On a time breach it exits [`EXIT_TIMEOUT`]; on a memory breach,
1144  /// [`EXIT_OOM`]. The memory guard is inactive where [`process_rss_kb`]
1145  /// returns `None` (non-Linux); see the module portability note.
1146  pub fn with_limits(
1147    timeout_secs: u64,
1148    max_rss_kb: u64,
1149    memory_knob: Option<&'static str>,
1150  ) -> Self {
1151    let cancelled = Arc::new(AtomicBool::new(false));
1152    if timeout_secs > 0 || max_rss_kb > 0 {
1153      let c = cancelled.clone();
1154      thread::Builder::new()
1155        .name("latexml-watchdog".to_string())
1156        .spawn(move || Self::run(c, timeout_secs, max_rss_kb, memory_knob))
1157        .expect("watchdog thread spawn failed");
1158    }
1159    Self { cancelled }
1160  }
1161
1162  fn run(
1163    cancelled: Arc<AtomicBool>,
1164    timeout_secs: u64,
1165    max_rss_kb: u64,
1166    memory_knob: Option<&'static str>,
1167  ) {
1168    let deadline = (timeout_secs > 0).then(|| {
1169      (
1170        Instant::now() + Duration::from_secs(timeout_secs),
1171        time_off_the_clock(),
1172      )
1173    });
1174    let poll_interval = Duration::from_millis(100);
1175    let poll_ns = u64::try_from(poll_interval.as_nanos()).unwrap_or(u64::MAX);
1176    let _clock = CoarseClock::keep();
1177    let mut cooperative_was_past = false;
1178    loop {
1179      let now_ns = publish_now();
1180      if cancelled.load(Ordering::Relaxed) {
1181        return; // cancelled: graceful exit.
1182      }
1183      // The cooperative check gets a full poll on the published clock before a breach of a deadline it shares
1184      // (cortex_worker, the LSP child): no breach while it is passing, by the next poll, and was not at the last one.
1185      let cooperative_ns = cooperative_deadline_ns();
1186      let cooperative_grace = cooperative_ns
1187        .is_some_and(|ns| !cooperative_was_past && ns <= now_ns.saturating_add(poll_ns));
1188      cooperative_was_past = cooperative_ns.is_some_and(|ns| now_ns > ns);
1189      let breach = deadline.and_then(|(deadline, off_at_set)| match setup_past_bound() {
1190        Some((what, bound)) => Some(format!(
1191          "{what} ran past its own bound of {}s (kept off the {timeout_secs}s timeout)",
1192          bound.as_secs()
1193        )),
1194        None => (deadline_passed(deadline, off_at_set) && !cooperative_grace)
1195          .then(|| format!("main-level wall-clock timeout after {timeout_secs}s")),
1196      });
1197      if let Some(breach) = breach {
1198        // Claimed first: a normal end claimed before it (the result being written) stands the breach down.
1199        if cancelled.load(Ordering::Relaxed) || !claim_exit(EXIT_TIMEOUT) {
1200          return;
1201        }
1202        // Unlocked: a thread stuck while holding the stderr lock must not hold up the exit.
1203        write_stderr_unlocked(format_args!(
1204          "Fatal:timeout:wallclock latexml-oxide: {breach} — exiting process\n"
1205        ));
1206        // Run the optional pre-exit hook (e.g. cortex_worker writing a
1207        // structured Status:conversion:3 placeholder to its --output path)
1208        // BEFORE exiting. The hook is invoked at most once per process.
1209        run_pre_exit_hook(EXIT_TIMEOUT);
1210        kill_registered_children();
1211        remove_registered_paths();
1212        // Exit 124 (the standard timeout code), not `abort()`: the worker thread is presumed wedged
1213        // and won't observe a cancel, and a SIGABRT reads to the harness as a crash ("Aborted (core
1214        // dumped)"; witnesses 2602.11915, 2604.11500, 2604.13944, hep-ph9205242, q-alg9604005,
1215        // q-alg9605003, q-alg9605028, the 7 "Aborted" rows of the 2026-05-13 588-paper sweep).
1216        // Through `exit_now`, as that thread still runs: `exit`'s library destructors would free
1217        // libxml2's globals under it (issue #777's render-worker SIGSEGV, not reproduced).
1218        exit_now(EXIT_TIMEOUT);
1219      }
1220      if max_rss_kb > 0
1221        && let Some(rss) = process_rss_kb()
1222        && rss > max_rss_kb
1223      {
1224        if cancelled.load(Ordering::Relaxed) || !claim_exit(EXIT_OOM) {
1225          return;
1226        }
1227        write_stderr_unlocked(format_args!(
1228          "{}\n",
1229          oom_rss_message(rss, max_rss_kb, memory_knob)
1230        ));
1231        run_pre_exit_hook(EXIT_OOM);
1232        kill_registered_children();
1233        remove_registered_paths();
1234        exit_now(EXIT_OOM);
1235      }
1236      sleep_one_poll(poll_interval, cooperative_ns);
1237    }
1238  }
1239
1240  /// Explicitly cancel the watchdog. Idempotent.
1241  pub fn cancel(&self) { self.cancelled.store(true, Ordering::Relaxed); }
1242}
1243
1244impl Drop for Watchdog {
1245  fn drop(&mut self) { self.cancel(); }
1246}
1247
1248#[cfg(test)]
1249mod tests {
1250  use super::*;
1251
1252  /// The memory breach names the flag that set the ceiling, or none: `cortex_worker` has no `--max-memory`.
1253  #[test]
1254  fn the_oom_fatal_names_the_knob_that_set_it() {
1255    let head = "Fatal:oom:rss latexml-oxide: resident memory 5400MB exceeded the 5376MB ceiling — exiting process. \
1256                This document needs a larger ceiling";
1257    let (rss, ceiling) = (5400 * 1024, 5376 * 1024);
1258    assert_eq!(
1259      oom_rss_message(rss, ceiling, Some("--max-rss-mb")),
1260      format!("{head}: rerun with a higher --max-rss-mb on a machine with enough free RAM.")
1261    );
1262    assert_eq!(
1263      oom_rss_message(rss, ceiling, Some("--max-memory")),
1264      format!("{head}: rerun with a higher --max-memory on a machine with enough free RAM.")
1265    );
1266    assert_eq!(oom_rss_message(rss, ceiling, None), format!("{head}."));
1267  }
1268
1269  /// A breach ends the process through `_exit`, as its pre-exit work leaves it: no exit handler runs under the threads
1270  /// still converting (libxml2's `.fini_array` `xmlCleanupParser` freed the globals a render worker read: its SIGSEGV).
1271  /// The child plants two markers only `exit` would act on: a thread-local destructor of the breaching thread (glibc's
1272  /// exit handlers) and a line left in stdout's buffer (`std::process::exit`'s flush). Run here, it is the child.
1273  #[test]
1274  fn a_breach_ends_the_process_without_exit_handlers() {
1275    const CHILD: &str = "LATEXML_WATCHDOG_BREACH_CHILD";
1276    struct Marker;
1277    impl Drop for Marker {
1278      fn drop(&mut self) { write_stderr_unlocked(format_args!("exit-handler-ran\n")); }
1279    }
1280    std::thread_local!(static MARKER: Marker = const { Marker });
1281    if let Ok(breach) = std::env::var(CHILD) {
1282      MARKER.with(|_| {});
1283      use std::io::Write;
1284      let _ = std::io::stdout().write_all(b"buffered-stdout");
1285      let cancelled = Arc::new(AtomicBool::new(false));
1286      match breach.as_str() {
1287        "timeout" => Watchdog::run(cancelled, 1, 0, None),
1288        _ => Watchdog::run(cancelled, 0, 1, Some("--max-memory")),
1289      }
1290      unreachable!("the breach exits");
1291    }
1292    let mut breaches = vec![("timeout", EXIT_TIMEOUT, "Fatal:timeout:wallclock")];
1293    if process_rss_kb().is_some() {
1294      breaches.push(("rss", EXIT_OOM, "Fatal:oom:rss"));
1295    }
1296    for (breach, code, line) in breaches {
1297      let out = std::process::Command::new(std::env::current_exe().unwrap())
1298        .args([
1299          "watchdog::tests::a_breach_ends_the_process_without_exit_handlers",
1300          "--exact",
1301          "--nocapture",
1302          "--test-threads=1",
1303        ])
1304        .env(CHILD, breach)
1305        .output()
1306        .unwrap();
1307      let (stdout, stderr) = (
1308        String::from_utf8_lossy(&out.stdout),
1309        String::from_utf8_lossy(&out.stderr),
1310      );
1311      assert_eq!(out.status.code(), Some(code), "{breach}: {stderr}");
1312      assert!(
1313        stderr.contains(line),
1314        "{breach}: the breach's line: {stderr}"
1315      );
1316      // `exit_now` is `_exit` on Unix only; elsewhere it is `std::process::exit`, which runs the thread-local
1317      // destructors and flushes stdout by design (the hazard it avoids, libxml2's `.fini_array` under a running
1318      // render thread, is ELF's). On Windows the breach's code and line are what this guard holds.
1319      if cfg!(unix) {
1320        assert!(
1321          !stderr.contains("exit-handler-ran"),
1322          "{breach}: the thread's destructor ran: exit, not _exit"
1323        );
1324        assert!(
1325          !stdout.contains("buffered-stdout"),
1326          "{breach}: stdout was flushed: std::process::exit, not _exit"
1327        );
1328      }
1329    }
1330  }
1331
1332  /// A breach after the normal path claimed the end (cortex_worker's result written to `--output`) stands down: no
1333  /// Fatal line, no pre-exit hook (its placeholder would overwrite the result), no exit. Run here, it is the child.
1334  #[test]
1335  fn a_breach_after_the_normal_end_stands_down() {
1336    const CHILD: &str = "LATEXML_WATCHDOG_NORMAL_END_CHILD";
1337    if std::env::var_os(CHILD).is_some() {
1338      set_pre_exit_hook(Box::new(|_| {
1339        write_stderr_unlocked(format_args!("hook-ran\n"))
1340      }));
1341      claim_normal_end();
1342      Watchdog::run(Arc::new(AtomicBool::new(false)), 1, 0, None);
1343      write_stderr_unlocked(format_args!("stood-down\n"));
1344      park_if_exiting();
1345      exit_now(0);
1346    }
1347    let out = std::process::Command::new(std::env::current_exe().unwrap())
1348      .args([
1349        "watchdog::tests::a_breach_after_the_normal_end_stands_down",
1350        "--exact",
1351        "--nocapture",
1352        "--test-threads=1",
1353      ])
1354      .env(CHILD, "1")
1355      .output()
1356      .unwrap();
1357    let stderr = String::from_utf8_lossy(&out.stderr);
1358    assert_eq!(out.status.code(), Some(0), "{stderr}");
1359    assert!(stderr.contains("stood-down"), "{stderr}");
1360    assert!(!stderr.contains("Fatal:"), "{stderr}");
1361    assert!(!stderr.contains("hook-ran"), "the hook ran: {stderr}");
1362  }
1363
1364  /// Setup run [`off_the_clock`] moves a breach back by its time, not off: the watchdog armed before a 2 s setup ends the
1365  /// process at its 1 s deadline plus the setup's 2 s; and a setup past its own bound ends it then, saying so (exit
1366  /// 124 both). Run here, it is the child.
1367  #[test]
1368  fn a_setup_moves_the_breach_back_and_runs_under_its_own_bound() {
1369    const CHILD: &str = "LATEXML_WATCHDOG_SETUP_CHILD";
1370    if let Ok(mode) = std::env::var(CHILD) {
1371      let _watchdog = Watchdog::new(1);
1372      let (bound, setup) = match mode.as_str() {
1373        "moved" => (60, 2),
1374        _ => (2, 20),
1375      };
1376      off_the_clock("the test setup", Duration::from_secs(bound), || {
1377        thread::sleep(Duration::from_secs(setup))
1378      });
1379      thread::sleep(Duration::from_secs(10));
1380      exit_now(0);
1381    }
1382    for (mode, line, at_least, below) in [
1383      ("moved", "main-level wall-clock timeout after 1s", 3, 12),
1384      (
1385        "bound",
1386        "the test setup ran past its own bound of 2s",
1387        2,
1388        15,
1389      ),
1390    ] {
1391      let started = Instant::now();
1392      let out = std::process::Command::new(std::env::current_exe().unwrap())
1393        .args([
1394          "watchdog::tests::a_setup_moves_the_breach_back_and_runs_under_its_own_bound",
1395          "--exact",
1396          "--nocapture",
1397          "--test-threads=1",
1398        ])
1399        .env(CHILD, mode)
1400        .output()
1401        .unwrap();
1402      let took = started.elapsed();
1403      let stderr = String::from_utf8_lossy(&out.stderr);
1404      assert_eq!(out.status.code(), Some(EXIT_TIMEOUT), "{mode}: {stderr}");
1405      assert!(stderr.contains(line), "{mode}: {stderr}");
1406      assert!(
1407        took >= Duration::from_secs(at_least) && took < Duration::from_secs(below),
1408        "{mode}: the breach came after {took:?}"
1409      );
1410    }
1411  }
1412
1413  /// The cooperative check reads the deadline on the coarse clock a running watchdog keeps, not on a call count: a
1414  /// caller polling at 20 Hz (some 20 calls, far below a 1024-call gate) stops within a poll or two of its deadline.
1415  /// With the watchdog on the same deadline (cortex_worker, the LSP child), the watchdog gives the check a full poll
1416  /// before its breach: a hot loop raises the graceful Fatal, also after a setup run off the clock (a format build)
1417  /// has moved both deadlines, where the poll that first published the moved deadline was the one that breached it.
1418  /// Each "step" there spins 200 µs, a digestion step's work between checks. Run here, it is the child; the children
1419  /// run one at a time, so two spinning ones never starve each other's watchdog on a small CI runner.
1420  #[test]
1421  fn the_cooperative_check_fires_on_the_watchdog_clock() {
1422    const CHILD: &str = "LATEXML_WATCHDOG_COARSE_CHILD";
1423    const SETUP_MS: u64 = 300;
1424    if let Ok(mode) = std::env::var(CHILD) {
1425      crate::common::error::initialize_report();
1426      let _watchdog = Watchdog::new(if mode == "slow" { 60 } else { 1 });
1427      let started = Instant::now();
1428      crate::stomach::set_timeout(1);
1429      if mode == "setup" {
1430        off_the_clock("the test setup", Duration::from_secs(60), || {
1431          thread::sleep(Duration::from_millis(SETUP_MS))
1432        });
1433      }
1434      let stop = loop {
1435        match mode.as_str() {
1436          "slow" => thread::sleep(Duration::from_millis(50)),
1437          "setup" => {
1438            let step = Instant::now();
1439            while step.elapsed() < Duration::from_micros(200) {
1440              std::hint::spin_loop();
1441            }
1442          },
1443          _ => {},
1444        }
1445        if let Err(stop) = crate::stomach::check_timeout() {
1446          break stop;
1447        }
1448      };
1449      claim_normal_end();
1450      write_stderr_unlocked(format_args!(
1451        "stopped after {}ms: {stop:?}\n",
1452        started.elapsed().as_millis()
1453      ));
1454      exit_now(0);
1455    }
1456    for (mode, from) in [("slow", 1000), ("hot", 1000), ("setup", 1000 + SETUP_MS)] {
1457      let out = std::process::Command::new(std::env::current_exe().unwrap())
1458        .args([
1459          "watchdog::tests::the_cooperative_check_fires_on_the_watchdog_clock",
1460          "--exact",
1461          "--nocapture",
1462          "--test-threads=1",
1463        ])
1464        .env(CHILD, mode)
1465        .stdout(std::process::Stdio::null())
1466        .stderr(std::process::Stdio::piped())
1467        .output()
1468        .unwrap();
1469      let stderr = String::from_utf8_lossy(&out.stderr);
1470      assert_eq!(out.status.code(), Some(0), "{mode}: {stderr}");
1471      assert!(stderr.contains("Conversion timed out"), "{mode}: {stderr}");
1472      let ms: u128 = stderr
1473        .split("stopped after ")
1474        .nth(1)
1475        .and_then(|rest| rest.split("ms").next())
1476        .and_then(|ms| ms.parse().ok())
1477        .unwrap_or_else(|| panic!("{mode}: {stderr}"));
1478      let from = u128::from(from);
1479      assert!(
1480        (from..from + 500).contains(&ms),
1481        "{mode}: stopped after {ms}ms"
1482      );
1483    }
1484  }
1485
1486  /// The cooperative deadline (`stomach::set_timeout`), set before a setup (cortex_worker, the LSP server), moves back
1487  /// by it too; nested calls count their time once; a panic ends the setup.
1488  #[test]
1489  fn a_setup_moves_the_cooperative_deadline_once_and_ends_on_a_panic() {
1490    crate::stomach::set_timeout(1);
1491    off_the_clock("the test setup", Duration::from_secs(60), || {
1492      thread::sleep(Duration::from_secs(2))
1493    });
1494    assert!(
1495      !crate::stomach::conversion_deadline_passed(),
1496      "the setup counted towards the deadline"
1497    );
1498    thread::sleep(Duration::from_millis(1200));
1499    assert!(
1500      crate::stomach::conversion_deadline_passed(),
1501      "the deadline was dropped, not moved"
1502    );
1503    crate::stomach::set_timeout(0);
1504
1505    let (before, started) = (time_off_the_clock(), Instant::now());
1506    off_the_clock("outer", Duration::from_secs(60), || {
1507      thread::sleep(Duration::from_millis(200));
1508      off_the_clock("inner", Duration::from_secs(1), || {
1509        thread::sleep(Duration::from_millis(200))
1510      });
1511      assert_ne!(
1512        SETUP_SINCE_NS.load(Ordering::Acquire),
1513        0,
1514        "the inner call ended the outer one"
1515      );
1516      assert_eq!(*setup_running(), (1, "outer", Duration::from_secs(60)));
1517      thread::sleep(Duration::from_millis(200));
1518    });
1519    let (took, wall) = (time_off_the_clock() - before, started.elapsed());
1520    assert!(
1521      took >= Duration::from_millis(600) && took <= wall,
1522      "{took:?} off the clock in {wall:?}"
1523    );
1524
1525    let panicked = std::panic::catch_unwind(|| {
1526      off_the_clock("panicking", Duration::from_secs(60), || {
1527        panic!("the setup panicked")
1528      })
1529    });
1530    assert!(panicked.is_err());
1531    assert_eq!(
1532      SETUP_SINCE_NS.load(Ordering::Acquire),
1533      0,
1534      "the panic left the setup running"
1535    );
1536    assert_eq!(setup_running().0, 0);
1537  }
1538
1539  /// A registered path is removed by the sweep an exit runs; one whose guard was dropped (its owner removed it, or
1540  /// keeps it) is not.
1541  #[test]
1542  fn registered_paths_are_removed_before_an_exit() {
1543    let base = std::env::temp_dir().join(format!("lx-remove-on-exit-{}", std::process::id()));
1544    let (kept, swept) = (base.join("kept"), base.join("swept"));
1545    std::fs::create_dir_all(&kept).unwrap();
1546    std::fs::create_dir_all(swept.join("inner")).unwrap();
1547    std::fs::write(swept.join("inner").join("file.tex"), "x").unwrap();
1548    drop(remove_on_exit(&kept));
1549    let guard = remove_on_exit(&swept);
1550    remove_registered_paths();
1551    assert!(kept.is_dir(), "an unregistered path stays");
1552    assert!(
1553      !swept.exists(),
1554      "a registered path is removed with its contents"
1555    );
1556    drop(guard);
1557    std::fs::remove_dir_all(&base).unwrap();
1558  }
1559
1560  /// The cgroup limit decides the ceiling in a container, so each way of
1561  /// spelling "unlimited" has to be recognised — otherwise a sentinel is
1562  /// mistaken for a 8 EiB budget, or `max` for a parse failure.
1563  #[test]
1564  fn cgroup_limit_recognises_every_unlimited_spelling() {
1565    const PHYS: Option<u64> = Some(258 * 1024 * 1024 * 1024);
1566
1567    // cgroup v2: the literal word.
1568    assert_eq!(interpret_cgroup_limit("max\n", PHYS), None);
1569    // cgroup v1: a huge sentinel (u64::MAX rounded to a page multiple).
1570    assert_eq!(interpret_cgroup_limit("9223372036854771712", PHYS), None);
1571    // A limit at or above physical RAM bounds nothing (258 GiB exactly, and
1572    // above).
1573    assert_eq!(interpret_cgroup_limit("277025390592", PHYS), None);
1574    assert_eq!(interpret_cgroup_limit("281474976710656", PHYS), None);
1575    // Garbage is not a limit.
1576    assert_eq!(interpret_cgroup_limit("", PHYS), None);
1577    assert_eq!(interpret_cgroup_limit("nonsense", PHYS), None);
1578    assert_eq!(interpret_cgroup_limit("0", PHYS), None);
1579
1580    // A REAL limit is honoured — this is the `docker run -m 4g` case that was
1581    // being ignored, leaving the process to be OOM-killed at 4 GB while its
1582    // cooperative fuse sat at 48 GiB.
1583    let four_gib = 4 * 1024 * 1024 * 1024;
1584    assert_eq!(
1585      interpret_cgroup_limit(&four_gib.to_string(), PHYS),
1586      Some(four_gib)
1587    );
1588    // …and trailing whitespace from the sysfs read must not defeat it.
1589    assert_eq!(
1590      interpret_cgroup_limit(&format!("{four_gib}\n"), PHYS),
1591      Some(four_gib)
1592    );
1593  }
1594
1595  #[test]
1596  fn watchdog_zero_timeout_is_noop() {
1597    // timeout_secs=0 should NOT spawn a thread and NOT abort.
1598    let w = Watchdog::new(0);
1599    assert!(
1600      !w.cancelled.load(Ordering::Relaxed),
1601      "initial cancelled state is false"
1602    );
1603    // Dropping is safe — there's no live thread to interact with.
1604    drop(w);
1605  }
1606
1607  #[test]
1608  fn watchdog_cancel_is_idempotent() {
1609    let w = Watchdog::new(60);
1610    w.cancel();
1611    assert!(w.cancelled.load(Ordering::Relaxed));
1612    // Calling again is a no-op.
1613    w.cancel();
1614    assert!(w.cancelled.load(Ordering::Relaxed));
1615  }
1616
1617  #[test]
1618  fn watchdog_drop_cancels() {
1619    let cancelled_ref = {
1620      let w = Watchdog::new(60);
1621      // Grab a reference to the atomic so we can inspect post-drop.
1622      w.cancelled.clone()
1623    }; // w dropped here
1624    assert!(
1625      cancelled_ref.load(Ordering::Relaxed),
1626      "drop should set cancelled=true"
1627    );
1628  }
1629
1630  #[test]
1631  fn watchdog_explicit_cancel_before_drop() {
1632    // Pre-drop cancellation is also reflected on the clone.
1633    let w = Watchdog::new(60);
1634    let cancelled_ref = w.cancelled.clone();
1635    w.cancel();
1636    assert!(cancelled_ref.load(Ordering::Relaxed));
1637    // Explicit drop after cancel remains idempotent.
1638    drop(w);
1639    assert!(cancelled_ref.load(Ordering::Relaxed));
1640  }
1641
1642  #[test]
1643  fn watchdog_long_timeout_doesnt_fire_quickly() {
1644    // 60-second timeout shouldn't fire during a 50 ms sleep.
1645    let _w = Watchdog::new(60);
1646    thread::sleep(Duration::from_millis(50));
1647    // If the watchdog had fired, we'd be dead. We made it here → fine.
1648  }
1649
1650  /// The ceiling is derived from the machine, so the machine must be probeable
1651  /// on every platform we ship. A `None` here means the default silently falls
1652  /// back to a flat number and the ceiling stops tracking the host — the exact
1653  /// failure `process_rss_kb` already has on non-Linux.
1654  #[test]
1655  #[cfg(any(unix, windows))]
1656  fn total_memory_is_probeable_and_plausible() {
1657    let total = total_memory_bytes().expect("physical RAM must be probeable on unix/windows");
1658    // No real machine we support has under 256 MiB, and none has over 100 TiB;
1659    // a value outside that says the units are wrong, not that the host is odd.
1660    assert!(
1661      total > 256 * 1024 * 1024,
1662      "implausibly small total RAM ({total} bytes) — check the unit conversion"
1663    );
1664    assert!(
1665      total < 100 * 1024 * 1024 * 1024 * 1024,
1666      "implausibly large total RAM ({total} bytes) — check the unit conversion"
1667    );
1668  }
1669
1670  /// The live probes compose sanely: never zero (a zero ceiling would mean
1671  /// "no limit" downstream, `resolve_rss_cap`), never above the fleet cap,
1672  /// never above what the process may use at all. The exact fraction is
1673  /// asserted on the pure function below, not here — the live machine's
1674  /// availability moves between the probe and any re-probe.
1675  #[test]
1676  fn default_ceiling_respects_both_halves_of_the_rule() {
1677    let ceiling = default_ceiling_mib();
1678    assert!(
1679      ceiling > 0,
1680      "a derived ceiling of 0 would read as 'unlimited'"
1681    );
1682    assert!(
1683      ceiling <= MAX_DEFAULT_CEILING_MIB,
1684      "derived {ceiling} MiB exceeds the {MAX_DEFAULT_CEILING_MIB} MiB cap; on a \
1685       large host an uncapped fraction-of-RAM default would let a parallel fleet \
1686       (N_processes x ceiling) OOM the machine"
1687    );
1688    if let Some(total) = total_memory_bytes() {
1689      assert!(
1690        ceiling <= (total / (1024 * 1024)).max(MIN_DEFAULT_CEILING_MIB),
1691        "the ceiling ({ceiling} MiB) cannot exceed physical RAM"
1692      );
1693    }
1694    if total_memory_bytes().is_none() && available_memory_bytes().is_none() {
1695      assert_eq!(ceiling, FALLBACK_CEILING_MIB);
1696    }
1697  }
1698
1699  /// The headroom rule, case by case (user directive 2026-08-01: default to
1700  /// actual machine headroom — the 26000-vs-32000 hand-tuning episode on the
1701  /// 131 MB witness showed how sharp the manual edge is).
1702  #[test]
1703  fn ceiling_rule_is_ninety_percent_of_available_with_fallbacks() {
1704    const GIB: u64 = 1024 * 1024 * 1024;
1705    // Idle 31 GB laptop, ~28 GB available: 90 % of available, NOT half of
1706    // total — the difference is the witness converting by default or dying.
1707    assert_eq!(derive_ceiling_mib(Some(28 * GIB), Some(31 * GIB)), 25804);
1708    // Busy 16 GB laptop with ~9 GB available: the rule self-adjusts to
1709    // roughly what half-of-total used to choose.
1710    assert_eq!(derive_ceiling_mib(Some(9 * GIB), Some(16 * GIB)), 8294);
1711    // Availability above the cgroup-capped total (host-wide MemAvailable seen
1712    // from inside a small container): the total binds.
1713    assert_eq!(derive_ceiling_mib(Some(28 * GIB), Some(4 * GIB)), 4 * 1024);
1714    // No availability probe: the conservative half-of-total fallback.
1715    assert_eq!(derive_ceiling_mib(None, Some(16 * GIB)), 8 * 1024);
1716    // Huge host: the 64 GiB fleet cap binds.
1717    assert_eq!(
1718      derive_ceiling_mib(Some(200 * GIB), Some(256 * GIB)),
1719      MAX_DEFAULT_CEILING_MIB
1720    );
1721    // Tiny container: the floor binds rather than deriving an unusable sliver.
1722    assert_eq!(
1723      derive_ceiling_mib(Some(GIB), Some(2 * GIB)),
1724      MIN_DEFAULT_CEILING_MIB
1725    );
1726    // Nothing probeable: the historical flat default.
1727    assert_eq!(derive_ceiling_mib(None, None), FALLBACK_CEILING_MIB);
1728  }
1729
1730  /// The availability probe answers on every CI platform (Linux, macOS,
1731  /// Windows) and the figure is plausible: nonzero, and no more than total.
1732  #[test]
1733  fn available_memory_probe_is_plausible() {
1734    let Some(avail) = available_memory_bytes() else {
1735      panic!("availability probe must answer on Linux/macOS/Windows CI");
1736    };
1737    assert!(avail > 0, "zero available RAM on a running machine");
1738    if let Some(total) = total_memory_bytes() {
1739      assert!(
1740        avail <= total,
1741        "available ({avail}) cannot exceed total ({total})"
1742      );
1743    }
1744  }
1745
1746  /// Free-disk probing backs the spill-headroom check; if it cannot answer we
1747  /// would have to spill blind.
1748  #[test]
1749  #[cfg(any(unix, windows))]
1750  fn available_disk_is_probeable() {
1751    let free = available_disk_bytes(std::path::Path::new("."))
1752      .expect("free space must be probeable on unix/windows");
1753    assert!(
1754      free > 0,
1755      "reported zero free space on the working directory"
1756    );
1757  }
1758}