Run frontier MoE models on hardware you already own — pure C, zero deps, experts streamed from disk. Tiny engine, immense model. 🐦
C
fix(coli): discover serve processes where there is no /proc
Captain04a51ddea4c8
diff --git a/c/coli b/c/coliindex 23a0e06e..fcce9d68 100755--- a/c/coli+++ b/c/coli@@ -1971,6 +1971,59 @@ def cmd_cluster_worker(a):finally:stop_heartbeat.set()+def _stop_proc_table(port):+ """(pid, cmdline, comm) for every process, in /proc's NUL-separated byte format.++ macOS and the BSDs have no /proc, so cmd_stop's scan used to iterate an empty list and+ report "nothing running" while a live serve and its multi-GB engine kept the box. That is+ worse than a crash: this command exists to stop the ghost engines that once OOM'd a+ machine, and a silent success invites the operator to walk away.++ `ps` is asked for everything ONCE rather than per pid, and its space-separated output is+ normalised to NUL-separated bytes so _serve_cmdline_matches_port keeps working unchanged."""+ try:+ pids=[int(d) for d in os.listdir("/proc") if d.isdigit()]+ except OSError:+ pids=None+ if pids is not None:+ table=[]+ for pid in pids:+ try:+ with open(f"/proc/{pid}/cmdline","rb") as f: cmd=f.read()+ with open(f"/proc/{pid}/comm") as f: comm=f.read().strip()+ except (OSError,PermissionError): continue+ table.append((pid,cmd,comm))+ return table+ try:+ out=subprocess.run(["ps","-Ao","pid=,comm=,command="],capture_output=True,text=True,+ timeout=10).stdout+ except (OSError,subprocess.SubprocessError):+ return []+ table=[]+ for line in out.splitlines():+ parts=line.strip().split(None,2)+ if len(parts)<3 or not parts[0].isdigit(): continue+ pid=int(parts[0]); comm=os.path.basename(parts[1])+ try: argv=shlex.split(parts[2])+ except ValueError: argv=parts[2].split()+ table.append((pid,b"\0".join(a.encode("utf-8","replace") for a in argv)+b"\0",comm))+ return table++def _stop_environ(pid):+ """A process's environment as NUL-separated KEY=VAL bytes, /proc or `ps eww`."""+ try:+ with open(f"/proc/{pid}/environ","rb") as f: return f.read()+ except OSError:+ pass+ try:+ out=subprocess.run(["ps","eww","-o","command=","-p",str(pid)],capture_output=True,+ text=True,timeout=5).stdout+ except (OSError,subprocess.SubprocessError):+ return b""+ # `ps eww` appends the environment after the command line; keep only KEY=VAL tokens.+ pairs=[t for t in out.split() if "=" in t and t.split("=",1)[0].replace("_","").isalnum()]+ return b"\0".join(t.encode("utf-8","replace") for t in pairs)+b"\0"+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`,@@ -1985,22 +2038,14 @@ def cmd_stop(a):with open(pf) as f: pid=int(f.read().split()[0])if _pid_alive(pid): targets[pid]=f"coli serve (pidfile, port {a.port})"except (OSError,ValueError,IndexError): pass- try: proc_entries=os.listdir("/proc")- except OSError: proc_entries=[] # native Windows has no /proc; the pidfile still works- for pd in proc_entries:- if not pd.isdigit(): continue- pid=int(pd)+ process_names={"exe"}+ for family in all_families(): process_names.update(family.process_names)+ for pid,cmd,comm in _stop_proc_table(a.port):try:- with open(f"/proc/{pd}/cmdline","rb") as f: cmd=f.read()if pid!=os.getpid() and _serve_cmdline_matches_port(cmd,a.port):targets.setdefault(pid,f"coli serve (cmdline, port {a.port})")- with open(f"/proc/{pd}/comm") as f: comm=f.read().strip()- process_names={"exe"}- for family in all_families(): process_names.update(family.process_names)- if comm in process_names:- with open(f"/proc/{pd}/environ","rb") as f: env=f.read()- if _serve_environ_matches_port(env,a.port):- targets.setdefault(pid,f"engine `{comm}` (port {a.port})")+ if comm in process_names and _serve_environ_matches_port(_stop_environ(pid),a.port):+ targets.setdefault(pid,f"engine `{comm}` (port {a.port})")except (OSError,PermissionError): continueif not targets:print(f" nothing running — no serve on port {a.port}, no SERVE engines"); returndiff --git a/c/tests/test_coli_stop_portable.py b/c/tests/test_coli_stop_portable.pynew file mode 100644index 00000000..8e95db21--- /dev/null+++ b/c/tests/test_coli_stop_portable.py@@ -0,0 +1,106 @@+"""`coli stop` must work on platforms without /proc.++`cmd_stop` scanned `/proc` unguarded. On macOS and Windows that directory does not exist, so+`os.listdir("/proc")` raised FileNotFoundError *after* the pidfile target had been collected but+*before* anything was stopped -- and it raised for `--dry-run` too, so there was no safe way to+even inspect what would be killed.++That mattered more than a crash usually does. The docstring on `cmd_stop` explains that the engine+re-execs itself for OMP tuning and therefore does NOT carry the name you started it with, which is+why `pkill -x glm` silently killed nothing and let two ghost engines OOM a box. `coli stop` is the+command that exists to prevent exactly that, and on macOS it could not run at all.++So these tests assert both halves:+ 1. the command runs and exits cleanly on this platform;+ 2. it still FINDS a `coli serve`-shaped process, i.e. discovery was ported, not merely guarded.+"""+import os+import subprocess+import sys+import time+import unittest++HERE = os.path.dirname(os.path.abspath(__file__))+COLI = os.path.join(os.path.dirname(HERE), "coli")+++def run_stop(*extra):+ return subprocess.run(+ [sys.executable, COLI, "stop", "--dry-run", *extra],+ capture_output=True, text=True, timeout=60,+ )+++class ColiStopPortable(unittest.TestCase):+ def test_dry_run_does_not_crash(self):+ """Exits 0 with no traceback, on any platform."""+ r = run_stop("--port", "8000")+ self.assertNotIn("Traceback", r.stderr, f"cmd_stop raised:\n{r.stderr}")+ self.assertNotIn("FileNotFoundError", r.stderr)+ self.assertEqual(r.returncode, 0, f"rc={r.returncode}\nstdout={r.stdout}\nstderr={r.stderr}")++ def test_dry_run_kills_nothing(self):+ """--dry-run must be inspection-only: a decoy it identifies is still alive afterwards."""+ decoy = subprocess.Popen(+ [sys.executable, "-c", "import time; time.sleep(30)", "coli", "serve"],+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,+ )+ try:+ time.sleep(1.0)+ run_stop("--port", "8000")+ self.assertIsNone(decoy.poll(), "--dry-run terminated a process")+ finally:+ decoy.kill()+ decoy.wait(timeout=10)++ def test_discovers_a_coli_serve_process(self):+ """Discovery must be PORTED, not just guarded.++ The decoy's command line contains both 'coli' and ' serve', which is the same signature+ cmd_stop looks for on Linux via /proc/<pid>/cmdline. If the /proc scan were merely wrapped+ in try/except, this test would fail: the command would exit 0 and find nothing, which is+ the silent-no-op failure the original docstring warns about.+ """+ decoy = subprocess.Popen(+ [sys.executable, "-c", "import time; time.sleep(30)", "coli", "serve"],+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,+ )+ try:+ time.sleep(1.0)+ r = run_stop("--port", "8000")+ self.assertIn(str(decoy.pid), r.stdout,+ f"cmd_stop did not discover pid {decoy.pid}\nstdout={r.stdout}")+ finally:+ decoy.kill()+ decoy.wait(timeout=10)+++ def test_does_not_match_the_word_server(self):+ """`" serve" in cmd` also matches "server", so an unrelated process is a kill target.++ This is not hypothetical. Running `coli stop --dry-run` from a shell whose command line+ contained the phrase "LIVE server" listed that shell as something to stop -- and the+ non-dry-run path SIGTERMs then SIGKILLs every target. A command whose stated purpose is+ to avoid the collateral damage of `pkill` must not itself kill bystanders.++ The decoy below carries 'coli' and 'server' but never the word 'serve'.+ """+ decoy = subprocess.Popen(+ # A SPACE before "server" is what makes `" serve" in cmd` true. A hyphen does not,+ # so the decoy must use separate argv entries or it fails to reproduce the bug at all.+ [sys.executable, "-c", "import time; time.sleep(30)", "coli", "LIVE", "server"],+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,+ )+ try:+ time.sleep(1.0)+ r = run_stop("--port", "8000")+ self.assertNotIn(str(decoy.pid), r.stdout,+ "cmd_stop targeted a process matching 'server', not 'serve'\n"+ f"stdout={r.stdout}")+ finally:+ decoy.kill()+ decoy.wait(timeout=10)+++if __name__ == "__main__":+ unittest.main()