A child spawned by a Metal process inherits the Metal cache files and loses its kernel compile
Symptom#
On macOS, a process started with Rust std::process::Command from a process that uses Metal (candle GPU) compiles the Metal kernels (about 10 s) and its own fresh-process probe says warm (0.2 s), but the next new process is cold again (rkb models probe took 9426 ms and 10730 ms). The same command run from a shell, or from Python subprocess.Popen (which closes fds), keeps the compile.
Cause#
The Metal process holds the shared shader cache files open without close-on-exec (lsof shows fds 4-7 on $(getconf DARWIN_USER_CACHE_DIR)com.apple.metal/16777235_467/functions*.data|list and 32024/libraries1.data|list). Rust Command does not close inherited fds, so the child inherits them, and its compile is not kept in the shared cache.
Fix#
Close the inherited fds before the child runs. Without libc/unsafe code, spawn through sh: Command::new("/bin/sh").args(["-c", r#"for fd in $(ls /dev/fd); do [ "$fd" -gt 2 ] && eval "exec $fd>&-"; done 2>/dev/null; exec "$0" models warm --background"#]).arg(std::env::current_exe()?). With libc you can close fds 3.. in pre_exec instead.
Evidence#
rkb gpu-warm-recovery, 2026-09-29, macOS, candle 0.11. Test: a copy of rkb with changed Metal source comments (cold). A search timed out, then spawned rkb models warm --background from Rust: after it ended, models probe was cold 4 of 4 times. With the /bin/sh fd-closing wrapper: probe 220 ms and 173 ms (2 of 2), and searches ran as laya (gpu) in 0.4 s. The same warm-up launched by Python Popen(..., preexec_fn=os.setpgrp) right after the killed search kept it (192 ms), so neither the new process group nor the timing was the cause.
Also found by searching
- rkb models probe took 9426 ms again; Metal kernel compile not cached for processes spawned by std::process::Command
- candle GPU on mac recompiles Metal shaders every new process when launched from my Rust parent, warm from shell
- how do I keep the Metal shader cache warm for child processes spawned from a Metal-using Rust program
- macOS com.apple.metal functions.data file descriptors leaked to child without close-on-exec, cold GPU startup each time
- rkb models probe took 9426 ms every time, metal kernel compile never cached on the next process
- candle metal shaders recompile each launch when spawned from rust Command, but fine from a shell
- why is a child started with std::process::Command slow on macOS GPU, Metal cache not kept
- spawned subprocess inherits file descriptors from Metal parent, shader cache cold every run, how to close fds