Run frontier MoE models on hardware you already own — pure C, zero deps, experts streamed from disk. Tiny engine, immense model. 🐦
C
fix(windows): make coli stop actually find the serve, and stop orphaning engines
JustVugg35349e1e01cd
diff --git a/c/coli b/c/coliindex 2ce41bd1..cafa4ae2 100755--- a/c/coli+++ b/c/coli@@ -1370,6 +1370,36 @@ def cmd_serve(a):try: os.unlink(serve_pidfile(a.port))except OSError: pass+def _pid_alive(pid):+ """Is `pid` a live process?++ `os.kill(pid, 0)` is the POSIX idiom, but on Windows os.kill() has no signal+ semantics: for a pid this process did not spawn it raises+ OSError [WinError 87] "The parameter is incorrect" instead of reporting+ liveness. cmd_stop caught that as "not running", so `coli stop` printed+ "nothing running" while the port was still LISTENING and ~5 GB of engines+ were resident (#1049, reported with a reproduction on Windows 11 native).+ On win32 ask the OS directly instead."""+ if sys.platform != "win32":+ try: os.kill(pid, 0); return True+ except OSError: return False+ import ctypes+ from ctypes import wintypes+ PROCESS_QUERY_LIMITED_INFORMATION, STILL_ACTIVE = 0x1000, 259+ k32 = ctypes.WinDLL("kernel32", use_last_error=True)+ k32.OpenProcess.restype = wintypes.HANDLE+ handle = k32.OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, False, pid)+ if not handle: return False+ try:+ code = wintypes.DWORD()+ if not k32.GetExitCodeProcess(handle, ctypes.byref(code)): return False+ # STILL_ACTIVE is also a legal exit code; a process that exited with 259+ # reads as alive here. SIGTERM on a dead pid is harmless, so the failure+ # mode is a redundant kill, never a missed one.+ return code.value == STILL_ACTIVE+ finally:+ k32.CloseHandle(handle)+def cmd_stop(a):"""Shut down a running `coli serve` AND its engine — one command, no pkill.The engine re-execs itself for OMP tuning, so its process is named `exe`,@@ -1382,7 +1412,7 @@ def cmd_stop(a):pf=serve_pidfile(a.port)try:with open(pf) as f: pid=int(f.read().split()[0])- os.kill(pid,0); targets[pid]=f"coli serve (pidfile, port {a.port})"+ if _pid_alive(pid): targets[pid]=f"coli serve (pidfile, port {a.port})"except (OSError,ValueError,IndexError): passtry: proc_entries=os.listdir("/proc")except OSError: proc_entries=[] # native Windows has no /proc; the pidfile still works@@ -1408,7 +1438,11 @@ def cmd_stop(a):except OSError: passtime.sleep(2.0)for pid in targets:- try: os.kill(pid, signal.SIGKILL); print(f" {pid}: forced (SIGKILL)")+ # signal.SIGKILL does not exist on win32 and AttributeError is not OSError,+ # so the bare `except OSError` let it escape and abort the command AFTER+ # the SIGTERMs above (#1049). Line 752 in this file already uses the+ # getattr form; os.kill(SIGTERM) is TerminateProcess on Windows anyway.+ try: os.kill(pid, getattr(signal, "SIGKILL", signal.SIGTERM)); print(f" {pid}: forced")except OSError: pass # gia' morto: benetry: os.unlink(pf)except OSError: passdiff --git a/c/openai_server.py b/c/openai_server.pyindex d2fbce69..ea2c5548 100644--- a/c/openai_server.py+++ b/c/openai_server.py@@ -1685,6 +1685,87 @@ def tune_child_env(env, arch):return env+def _win_kill_on_close_job(pid):+ """Tie an engine process to this server's lifetime, on Windows.++ The engine re-execs itself for OMP tuning, and the re-exec's parent exits+ immediately -- so the surviving engine is orphaned at birth. It is not a+ descendant of anything the launcher can walk to, and it is not the pid the+ server recorded, so neither the pidfile nor a parent-child scan can reach+ it. #1049 measured the consequence on Windows 11: 2,617 MB still resident+ after a shutdown that reported success, accumulating one ghost per+ serve/stop cycle. (Same failure that OOM'd a box on 2026-07-16 with two+ 17+5 GB ghosts, where `pkill -x glm` matched nothing because the re-exec+ renames itself.)++ A Job Object with KILL_ON_JOB_CLOSE fixes it at the OS level rather than by+ guessing pids: job membership is INHERITED by child processes, so the+ re-exec stays inside the job, and when the last handle closes -- normal+ exit, TerminateProcess, or a crash of this server -- Windows terminates+ everything in it. Returns the handle, which the caller must keep alive for+ as long as the engine should live; returns None on any failure, which+ simply restores today's behaviour.+ """+ if sys.platform != "win32" or not pid:+ return None+ try:+ import ctypes+ from ctypes import wintypes++ class IO_COUNTERS(ctypes.Structure):+ _fields_ = [("ReadOperationCount", ctypes.c_ulonglong),+ ("WriteOperationCount", ctypes.c_ulonglong),+ ("OtherOperationCount", ctypes.c_ulonglong),+ ("ReadTransferCount", ctypes.c_ulonglong),+ ("WriteTransferCount", ctypes.c_ulonglong),+ ("OtherTransferCount", ctypes.c_ulonglong)]++ class JOBOBJECT_BASIC_LIMIT_INFORMATION(ctypes.Structure):+ _fields_ = [("PerProcessUserTimeLimit", ctypes.c_longlong),+ ("PerJobUserTimeLimit", ctypes.c_longlong),+ ("LimitFlags", wintypes.DWORD),+ ("MinimumWorkingSetSize", ctypes.c_size_t),+ ("MaximumWorkingSetSize", ctypes.c_size_t),+ ("ActiveProcessLimit", wintypes.DWORD),+ ("Affinity", ctypes.POINTER(ctypes.c_ulong)),+ ("PriorityClass", wintypes.DWORD),+ ("SchedulingClass", wintypes.DWORD)]++ class JOBOBJECT_EXTENDED_LIMIT_INFORMATION(ctypes.Structure):+ _fields_ = [("BasicLimitInformation", JOBOBJECT_BASIC_LIMIT_INFORMATION),+ ("IoInfo", IO_COUNTERS),+ ("ProcessMemoryLimit", ctypes.c_size_t),+ ("JobMemoryLimit", ctypes.c_size_t),+ ("PeakProcessMemoryUsed", ctypes.c_size_t),+ ("PeakJobMemoryUsed", ctypes.c_size_t)]++ JobObjectExtendedLimitInformation = 9+ JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE = 0x00002000+ PROCESS_SET_QUOTA, PROCESS_TERMINATE = 0x0100, 0x0001++ k32 = ctypes.WinDLL("kernel32", use_last_error=True)+ k32.CreateJobObjectW.restype = wintypes.HANDLE+ k32.OpenProcess.restype = wintypes.HANDLE+ job = k32.CreateJobObjectW(None, None)+ if not job:+ return None+ info = JOBOBJECT_EXTENDED_LIMIT_INFORMATION()+ info.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE+ if not k32.SetInformationJobObject(job, JobObjectExtendedLimitInformation,+ ctypes.byref(info), ctypes.sizeof(info)):+ k32.CloseHandle(job); return None+ handle = k32.OpenProcess(PROCESS_SET_QUOTA | PROCESS_TERMINATE, False, pid)+ if not handle:+ k32.CloseHandle(job); return None+ ok = k32.AssignProcessToJobObject(job, handle)+ k32.CloseHandle(handle)+ if not ok:+ k32.CloseHandle(job); return None+ return job+ except Exception:+ return None # never let process bookkeeping break starting the engine++class Engine:# cap=None = "not explicitly set": a glm-arch model's engine resolves the# 0 sentinel (8 historically, 1 on Metal+darwin+fast SSD -- colibri.c@@ -1701,6 +1782,14 @@ class Engine:[str(executable), str(cap_for_arch(arch, cap))], env=child_env,stdin=subprocess.PIPE, stdout=subprocess.PIPE, bufsize=0,)+ # Keep the job handle on the instance: KILL_ON_JOB_CLOSE fires when the+ # LAST handle closes, so this reference is what ties the engine (and the+ # OMP re-exec that orphans itself) to the server's lifetime (#1049).+ # Guarded so the non-Windows path never touches .pid -- the test suite+ # drives this class with a fake process object that has none.+ self._win_job = None+ if sys.platform == "win32":+ self._win_job = _win_kill_on_close_job(getattr(self.process, "pid", None))self.write_lock = threading.Lock()self.pending_lock = threading.Lock()self.pending = {}diff --git a/c/tests/test_stop_liveness.py b/c/tests/test_stop_liveness.pynew file mode 100644index 00000000..6b80313a--- /dev/null+++ b/c/tests/test_stop_liveness.py@@ -0,0 +1,79 @@+"""#1049: `coli stop` must actually find a live serve, on every platform.++The bug these cover: `os.kill(pid, 0)` is the POSIX liveness idiom, but on+Windows os.kill() has no signal semantics and raises OSError [WinError 87] for+a pid the caller did not spawn. cmd_stop swallowed that as "not running", so+`coli stop` reported "nothing running" while the port was still LISTENING and+~5 GB of engines were resident.+"""+import importlib.machinery, importlib.util, os, subprocess, sys, unittest++HERE = os.path.dirname(os.path.abspath(__file__))+COLI = os.path.join(os.path.dirname(HERE), "coli")+++def load_coli():+ loader = importlib.machinery.SourceFileLoader("coli_mod", COLI)+ spec = importlib.util.spec_from_loader("coli_mod", loader)+ mod = importlib.util.module_from_spec(spec)+ loader.exec_module(mod)+ return mod+++class StopLivenessTest(unittest.TestCase):+ def setUp(self):+ self.coli = load_coli()++ def test_probe_exists(self):+ """cmd_stop must not use the raw POSIX idiom for liveness."""+ self.assertTrue(hasattr(self.coli, "_pid_alive"))+ src = open(COLI, encoding="utf-8").read()+ stop = src[src.index("def cmd_stop("):]+ stop = stop[:stop.index("\ndef ")]+ self.assertNotIn("os.kill(pid,0)", stop)+ self.assertIn("_pid_alive(pid)", stop)++ def test_self_is_alive(self):+ self.assertTrue(self.coli._pid_alive(os.getpid()))++ def test_reaped_child_is_not_alive(self):+ """A process we started and waited on must read as dead."""+ p = subprocess.Popen([sys.executable, "-c", "pass"])+ p.wait()+ self.assertFalse(self.coli._pid_alive(p.pid))++ def test_sigkill_lookup_is_guarded(self):+ """signal.SIGKILL is absent on win32 and AttributeError is not OSError."""+ src = open(COLI, encoding="utf-8").read()+ stop = src[src.index("def cmd_stop("):]+ stop = stop[:stop.index("\ndef ")]+ # the *call* must not name it directly; the explanatory comment may.+ self.assertNotIn("os.kill(pid, signal.SIGKILL)", stop)+ self.assertIn('getattr(signal, "SIGKILL"', stop)+++class OrphanJobTest(unittest.TestCase):+ """The engine re-execs for OMP tuning and orphans itself; a Job Object with+ KILL_ON_JOB_CLOSE is what ties it to the server's lifetime on Windows."""++ def test_engine_takes_a_job_handle(self):+ src = open(os.path.join(os.path.dirname(HERE), "openai_server.py"),+ encoding="utf-8").read()+ self.assertIn("_win_kill_on_close_job", src)+ self.assertIn("JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE", src)+ self.assertIn("_win_kill_on_close_job(getattr(self.process,", src)+ # the non-Windows path must not even read .pid: the suite drives Engine+ # with a fake process object that has none.+ self.assertIn('if sys.platform == "win32":', src)++ def test_helper_is_a_noop_off_windows(self):+ sys.path.insert(0, os.path.dirname(HERE))+ try:+ import openai_server+ self.assertIsNone(openai_server._win_kill_on_close_job(os.getpid()))+ finally:+ sys.path.pop(0)+++if __name__ == "__main__":+ unittest.main()