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. Dropon theWatchdoghandle cancels the watchdog thread, so RAII usage (let _wd = Watchdog::new(secs)) is sufficient.- We exit (
exit_now) rather thanpanic!because panic may unwind or be caught by a surroundingcatch_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 niceErr(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§
- Kill
OnExit - Holds a child registered with
kill_registered_children; dropping it kills, reaps and unregisters the child. - Kill
PidOn Exit - Keeps a child PID registered with
kill_registered_children; dropping it unregisters the PID (the owner is responsible for normal waiting/reaping). - Remove
OnExit - 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
layoutthat 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, orNoneif 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
Nonewhen 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;
Nonewithout one (the LSP server’s in-process path, the tests, an embedder), where the caller readsInstant::now. - deadline_
passed - Whether
deadline, set whentime_off_the_clockreadoff_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 ofstd::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:exitruns the libraries’ destructors under that thread (libxml2’s.fini_arraycallsxmlCleanupParser, 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 unbufferedwrite(2)), a pre-exit hook’s file. Only a partial line still in stdout’s line buffer is lost. - kill_
on_ exit - Registers
childto 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_groupis true). Portable across Unix and Windows, with zerounsafe(usesrustix::processon Unix andtaskkill /T /Fon Windows). - kill_
pid_ on_ exit - Registers
pidto be killed by exits that skip destructors (watchdog timeout/OOM, allocation failure), for as long as the returned guard lives. Setkill_group = truewhen 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 onlyboundends 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).
Noneotherwise, or when no peak is measurable. - process_
peak_ rss_ kb - Kernel-tracked PEAK resident set of this process in KiB (
VmHWM), orNoneif it can’t be determined. Unlikeprocess_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
Noneif it can’t be determined. Linux readsVmRSSfrom/proc/self/status; macOS asks libproc (proc_pidinfo/PROC_PIDTASKINFO) — without it the whole--max-memoryceiling silently did not exist on macOS, and the115_streaming_cliFatal-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
pathfor removal byremove_registered_pathswhile 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
SIGTERMto a Unix child’s process group (no-op on non-Unix). Safe wrapper overrustix::process::kill_process_group. - time_
off_ the_ clock - The time
off_the_clocksetup has taken in this process so far, the running one’s included. - total_
memory_ bytes - Total physical RAM on this machine in bytes, or
Noneif it cannot be determined. - try_
kill_ registered_ children kill_registered_childrenfor an allocation-failure or panic hook: it gives up rather than wait for the lock.- try_
remove_ registered_ paths remove_registered_paths(aftertry_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
argsto standard error in onewrite(2), formatted into a stack buffer (cut at 1 KiB). Unlikeeprintln!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: aFatal:timeout:wallclockglued onto(Processing definitions …l3backend-pdftex.def... )escaped every^Fatal:count.