code wiki / (root) / nx_fd_hygiene.nx

nx_fd_hygiene.nx source

↩ module page · 23 lines · 1308 B

1// nx_fd_hygiene.nx -- fd-leak hygiene primitive (2026-07-17). A long-lived supervisor/launcher that forks+execs 2// daemons must not leak INHERITED file descriptors into them: a leaked LISTEN socket keeps its port held, so a 3// redeployed daemon can no longer rebind it. That is exactly what took the mgmt control plane down for ~10 min on 4// 2026-07-17 -- nx_hostctl had inherited mgmt's :18098 listen socket at startup and propagated it to every daemon 5// it forked (children inherit the supervisor's fd table), so a rebuilt mgmt hit EADDRINUSE. 6// 7// nx_fd_scrub_inherited() closes every fd >= 3, preserving stdio (0,1,2). Called ONCE at a supervisor's entry it 8// fixes the whole process tree by construction: a clean supervisor fd table yields clean children. Closing an 9// already-closed fd is a harmless EBADF no-op, so the scrub is safe to run unconditionally. Returns the count of 10// fds that were actually open (closed). license_tier: ORIGINAL 11import "nx_syscalls.nx" 12 13const NX_FD_SCRUB_MAX: i64 = 1024 // POSIX default soft RLIMIT_NOFILE; covers every fd a supervisor could hold 14 15func nx_fd_scrub_inherited() -> i64 { 16 var fd: i64 = 3 17 var closed: i64 = 0 18 while fd < NX_FD_SCRUB_MAX { 19 if sys_close(fd) == 0 { closed = closed + 1 } 20 fd = fd + 1 21 } 22 return closed 23}