Skip to main content

Module watchdog

Module watchdog 

Source
Expand description

Wall-clock watchdog that forcibly aborts the process after a deadline.

The existing stomach::check_timeout() is a cooperative mechanism — it only fires when the digestion loop polls it. That leaves tight native loops (Marpa precompute / parse, libxml2 post-processing, FFI calls into libxslt, …) completely unguarded: a 60-second timeout can easily turn into 10 minutes if control never returns to the digestion loop.

This module provides a main-level Watchdog that spawns a dedicated thread at construction, wakes after the specified number of seconds, and — if the watchdog has not yet been cancelled — prints a message and exits the process (EXIT_TIMEOUT). The process dies within timeout + poll_interval, regardless of what the main thread is doing, plus the time one-time setup spent off_the_clock (the format build): only its own bound ends that setup. --timeout 0 arms no time guard: no deadline, and no bound on the setup (a non-zero --max-memory still starts the watchdog thread for its memory guard).

§Design notes

  • Uses Arc<AtomicBool> for cancellation. Polling every 100 ms keeps the cancellation latency low without burning CPU.
  • Drop on the Watchdog handle cancels the watchdog thread, so RAII usage (let _wd = Watchdog::new(secs)) is sufficient.
  • We exit (exit_now) rather than panic! because panic may unwind or be caught by a surrounding catch_unwind, which would defeat the safety guarantee.
  • The existing cooperative stomach::check_timeout() path is retained: on most conversions it fires before the hard abort, giving callers a nice Err(Fatal) with proper error propagation. The watchdog is a safety net for the pathological cases where cooperative polling doesn’t happen. While it runs it also keeps the coarse clock that check reads (coarse_now_ns).

§Resource limits

Watchdog::with_limits guards both a wall-clock deadline and a resident-memory ceiling — the two defenses any executable that converts arbitrary input needs. It is the shared guard reused by both cortex_worker (in-process, one paper per process) and the latexml_oxide --server LSP (run inside each forked body child, which self-terminates on breach so the parent reaps it via pipe EOF). The exit codes are distinct so a supervising parent can tell them apart: 124 = wall-clock timeout, 137 = memory ceiling.

§Portability

The wall-clock guard is portable (std::thread + Instant).

Portable: total_memory_bytes and available_disk_bytes answer on Linux, macOS and Windows — sysconf(_SC_PHYS_PAGES)/statvfs are POSIX, and Windows uses GlobalMemoryStatusEx/GetDiskFreeSpaceExW. They back the machine-derived default ceiling (default_ceiling_mib) and the spill-headroom check, so those behave identically on every supported OS.

Enforcement, also portable: process_rss_kb — the half that actually checks live usage against the ceiling — answers on all three: Linux samples /proc/self/status, macOS asks libproc (proc_pidinfo), and Windows uses GetProcessMemoryInfo. So the memory ceiling is both computed and checked on every supported OS; other targets fall back to None (time guard only).

Structs§

KillOnExit
Holds a child registered with kill_registered_children; dropping it kills, reaps and unregisters the child.
KillPidOnExit
Keeps a child PID registered with kill_registered_children; dropping it unregisters the PID (the owner is responsible for normal waiting/reaping).
RemoveOnExit
Keeps a path registered with remove_registered_paths; unregisters it when dropped.
Watchdog

Constants§

EXIT_OOM
Exit code used when the memory ceiling is exceeded (128 + SIGKILL).
EXIT_TIMEOUT
Exit code used when the wall-clock deadline is exceeded (standard timeout).
FALLBACK_CEILING_MIB
Ceiling used when the machine’s RAM cannot be probed — the historical flat default, kept so an unprobeable platform behaves exactly as before rather than losing its guard entirely.
MAX_DEFAULT_CEILING_MIB
Upper bound on the machine-derived default ceiling (64 GiB in MiB).
MIN_DEFAULT_CEILING_MIB
Floor for the machine-derived default, so a small container still gets a workable budget rather than a ceiling no conversion can fit under.

Functions§

alloc_failed
Ends the process for an allocation of layout that failed: through the registered hook, or where none is (a test binary, an embedder) through std’s default (handle_alloc_error: one line, then abort). Allocates nothing. Never inlined: every allocation failure passes this frame (the global allocator’s and libxml2’s XPath one), so the hooks’ line names it as the debugger breakpoint.
available_disk_bytes
Free space in bytes on the filesystem holding path, or None if it cannot be determined. Used to check headroom before spilling intermediates to disk.
available_memory_bytes
RAM available for new allocations right now, in bytes, or None when the platform offers no honest answer.
children_cpu_time_us
The user and system CPU time of this process’s waited-for children (RUSAGE_CHILDREN), in microseconds; (0, 0) when it cannot be read.
claim_normal_end
Claims the process’s end for the normal path before a single-run binary hands on its result: a breach after it stands down, where its pre-exit hook would overwrite the written result with its placeholder (cortex_worker --standalone --output). When a breach claimed first, parks (park_if_exiting) until its exit.
coarse_now_ns
The coarse clock’s last reading, at most one poll old, while a watchdog runs; None without one (the LSP server’s in-process path, the tests, an embedder), where the caller reads Instant::now.
deadline_passed
Whether deadline, set when time_off_the_clock read off_at_set, has passed once the setup since is taken off the clock: the one test of both the watchdog and the cooperative deadline.
default_ceiling_mib
The default per-conversion memory ceiling in MiB, derived from the machine as it is right now.
enter_alloc_failure_hook
The first call of a binary’s allocation-failure hook. The hook then runs alone and without allocating: it writes its line (write_stderr_unlocked), sweeps the run’s trees (try_remove_registered_paths) and ends the process (exit_now).
exit_now
Ends the process now with code: _exit, without the atexit handlers, destructors and stream flushes of std::process::exit, any of which can allocate or wait on a lock held by a thread that will never release it. Every exit taken while another thread may still run goes through it: exit runs the libraries’ destructors under that thread (libxml2’s .fini_array calls xmlCleanupParser, freeing the catalog, encoding aliases, dict mutexes and global-state key a running render reads: a render worker’s SIGSEGV with ip == fault address in freed heap, on Nasser’s 2,400-problem slice under concurrent load, issue #777, not reproduced). What must land is written first, unbuffered: the stderr line (write_stderr_unlocked), the log mirror (an unbuffered write(2)), a pre-exit hook’s file. Only a partial line still in stdout’s line buffer is lost.
kill_on_exit
Registers child to be killed by the exits that skip destructors, for as long as the returned guard lives.
kill_pid
Best-effort immediate termination of a child PID (or its Unix process group when kill_group is true). Portable across Unix and Windows, with zero unsafe (uses rustix::process on Unix and taskkill /T /F on Windows).
kill_pid_on_exit
Registers pid to be killed by exits that skip destructors (watchdog timeout/OOM, allocation failure), for as long as the returned guard lives. Set kill_group = true when the child is a Unix process-group leader.
kill_registered_children
Kills every registered child (the exiting process does not wait for them; they are reparented and reaped).
memory_fatal_seen
Did a memory-budget Fatal fire since the last reset_memory_fatal?
note_memory_fatal
Record that a memory-budget Fatal fired, so the end-of-run report knows memory was actually the problem.
off_the_clock
Runs work, one-time setup that is not the conversion’s (what: the format build for the host’s TeX tree), off every deadline: the watchdog’s and the cooperative one (stomach::set_timeout) move back by the time it takes, and while it runs only bound ends it, a watchdog’s breach (exit 124). Calls nest: the outermost one’s time and bound count. Without a watchdog (--timeout 0) nothing bounds it.
park_if_exiting
Parks the calling thread once the watchdog has begun to exit, until that exit ends the process. Called before every exit and result hand-off a timed-out run could race (the binaries’ final exits, cortex_worker’s results). Bounded: if the exit has not come within a minute (a pre-exit hook that blocked, or a sweep slower than that, which it then cuts short) the thread exits itself, with the claimed code, through exit_now: the watchdog thread still runs.
peak_memory_report
The end-of-run memory report — emitted ONLY when a memory-budget Fatal fired during the run (user directive 2026-08-03: alert when needed, stay quiet on clean runs). None otherwise, or when no peak is measurable.
process_peak_rss_kb
Kernel-tracked PEAK resident set of this process in KiB (VmHWM), or None if it can’t be determined. Unlike process_rss_kb’s point-in-time sample, this is the true high-water mark over the whole process lifetime — no sampling cadence can miss a spike — which makes it the honest basis for the end-of-run “this document needed N” report (peak_memory_report).
process_rss_kb
Current resident set size of this process in KiB, or None if it can’t be determined. Linux reads VmRSS from /proc/self/status; macOS asks libproc (proc_pidinfo/PROC_PIDTASKINFO) — without it the whole --max-memory ceiling silently did not exist on macOS, and the 115_streaming_cli Fatal-contract guard caught exactly that on macOS CI (an over-budget run exited 0). Cheap enough to poll a few times a second.
remove_on_exit
Registers path for removal by remove_registered_paths while the returned guard lives.
remove_registered_paths
Removes every registered path, directories with their contents: for the exits that skip destructors.
reset_memory_fatal
Forget a memory-budget Fatal: the CLI restarts a fused EAGER conversion under --streaming, and the end-of-run report must describe the attempt that produced the output.
set_alloc_failure_hook
Registers the binary’s allocation-failure hook, first thing in main; a second registration is ignored.
set_pre_exit_hook
setup_past_bound
The running setup and its bound, once it has run past that bound (what the watchdog’s breach line names).
signal_group_term
Best-effort graceful SIGTERM to a Unix child’s process group (no-op on non-Unix). Safe wrapper over rustix::process::kill_process_group.
time_off_the_clock
The time off_the_clock setup has taken in this process so far, the running one’s included.
total_memory_bytes
Total physical RAM on this machine in bytes, or None if it cannot be determined.
try_kill_registered_children
kill_registered_children for an allocation-failure or panic hook: it gives up rather than wait for the lock.
try_remove_registered_paths
remove_registered_paths (after try_kill_registered_children) for an allocation-failure hook, which may have 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 takes every job’s trees, and the other threads must not hand on results built over them.
write_stderr_unlocked
Writes args to standard error in one write(2), formatted into a stack buffer (cut at 1 KiB). Unlike eprintln! it neither allocates nor takes the standard library’s stderr lock. That makes it safe in an allocation-failure hook, and for the watchdog when a stuck thread holds that lock. It opens a fresh line when a progress note left stderr mid-line, as the logger’s records do: a Fatal:timeout:wallclock glued onto (Processing definitions …l3backend-pdftex.def... ) escaped every ^Fatal: count.