Run frontier MoE models on hardware you already own — pure C, zero deps, experts streamed from disk. Tiny engine, immense model. 🐦
C
fix(stop): scope shutdowns to the requested port
Blake6707d1a26c82
diff --git a/c/coli b/c/coliindex dc608ab7..ae10a461 100755--- a/c/coli+++ b/c/coli@@ -1302,6 +1302,34 @@ def cmd_chat(a):def serve_pidfile(port): return os.path.join(tempfile.gettempdir(), f"coli-serve-{port}.pid")+def _serve_cmdline_matches_port(raw, port):+ argv=[part.decode("utf-8","replace") for part in raw.split(b"\0") if part]+ try: coli_i=next(i for i,arg in enumerate(argv) if os.path.basename(arg)=="coli")+ except StopIteration: return False+ if coli_i+1>=len(argv) or argv[coli_i+1]!="serve":+ return False+ configured=8000+ for i,arg in enumerate(argv[coli_i+2:], start=coli_i+2):+ if arg=="--port" and i+1<len(argv):+ try: configured=int(argv[i+1])+ except ValueError: return False+ elif arg.startswith("--port="):+ try: configured=int(arg.split("=",1)[1])+ except ValueError: return False+ return configured==port++def _serve_environ_matches_port(raw, port):+ env={}+ for entry in raw.split(b"\0"):+ if b"=" in entry:+ key,value=entry.split(b"=",1); env[key]=value+ return env.get(b"SERVE")==b"1" and env.get(b"COLI_SERVE_PORT")==str(port).encode()++def _serve_engine_env(a, arch):+ env=env_for_engine(a,arch)+ env["COLI_SERVE_PORT"]=str(a.port)+ return env+def cmd_serve(a):arch=model_arch(a.model)engine=engine_for(a.model)@@ -1322,7 +1350,7 @@ def cmd_serve(a):"glm-5.2-colibri")try:openai_server.serve(a.model,a.host,a.port,model_id,a.api_key,- a.cap,ngen_for(a,interactive=True),engine,env_for_engine(a,arch),a.cors_origin,+ a.cap,ngen_for(a,interactive=True),engine,_serve_engine_env(a,arch),a.cors_origin,a.max_queue,a.queue_timeout,a.kv_slots,allowed_hosts=a.allowed_host)finally:try: os.unlink(serve_pidfile(a.port))@@ -1334,36 +1362,38 @@ def cmd_stop(a):not `glm`: every `pkill -x glm` in history silently killed nothing (that ishow two 17+5 GB ghost engines OOM'd this box on 2026-07-16). This finds thereal processes: the pidfile first, then /proc by cmdline/environ — only- processes that are demonstrably ours (SERVE=1 + our SNAP, or `coli serve`- in the command line)."""+ the requested port's tagged engine and matching `coli serve` wrapper."""banner("stop")- targets=[] # (pid, descrizione)+ targets={} # pid -> descrizionepf=serve_pidfile(a.port)try:- pid=int(open(pf).read().split()[0])- os.kill(pid,0); targets.append((pid,f"coli serve (pidfile, port {a.port})"))+ with open(pf) as f: pid=int(f.read().split()[0])+ os.kill(pid,0); targets[pid]=f"coli serve (pidfile, port {a.port})"except (OSError,ValueError,IndexError): pass- for pd in os.listdir("/proc"):+ 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(): continuepid=int(pd)try:- cmd=open(f"/proc/{pd}/cmdline","rb").read().replace(b"\0",b" ").decode("utf-8","replace")- if "coli" in cmd and " serve" in cmd and pid!=os.getpid():- if not any(p==pid for p,_ in targets): targets.append((pid,"coli serve (cmdline)"))- comm=open(f"/proc/{pd}/comm").read().strip()+ 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()if comm in ("colibri","glm","exe","olmoe","inkling","kimi_k3","deepseek_v4"):- env=open(f"/proc/{pd}/environ","rb").read().replace(b"\0",b"\n").decode("utf-8","replace")- if "SERVE=1" in env: targets.append((pid,f"engine `{comm}` (SERVE=1)"))+ 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})")except (OSError,PermissionError): continueif not targets:print(f" nothing running — no serve on port {a.port}, no SERVE engines"); return- for pid,desc in targets: print(f" {'would stop' if a.dry_run else 'stopping'} {pid}: {desc}")+ for pid,desc in targets.items(): print(f" {'would stop' if a.dry_run else 'stopping'} {pid}: {desc}")if a.dry_run: return- for pid,_ in targets:+ for pid in targets:try: os.kill(pid, signal.SIGTERM)except OSError: passtime.sleep(2.0)- for pid,_ in targets:+ for pid in targets:try: os.kill(pid, signal.SIGKILL); print(f" {pid}: forced (SIGKILL)")except OSError: pass # gia' morto: benetry: os.unlink(pf)diff --git a/c/tests/test_stop_scope.py b/c/tests/test_stop_scope.pynew file mode 100644index 00000000..e5c74c46--- /dev/null+++ b/c/tests/test_stop_scope.py@@ -0,0 +1,101 @@+import contextlib+import importlib.machinery+import importlib.util+import io+import os+import subprocess+import sys+import tempfile+import time+import types+import unittest+from pathlib import Path+from unittest import mock+++C_DIR = Path(__file__).resolve().parents[1]+loader = importlib.machinery.SourceFileLoader("coli_stop_scope", str(C_DIR / "coli"))+spec = importlib.util.spec_from_loader(loader.name, loader)+coli = importlib.util.module_from_spec(spec)+loader.exec_module(coli)+++class StopScopeTests(unittest.TestCase):+ def cmdline(self, *args):+ return b"\0".join(arg.encode() for arg in args) + b"\0"++ def test_explicit_port_does_not_match_another_server(self):+ raw = self.cmdline("python3", "/opt/colibri/coli", "serve",+ "--model", "/models/a", "--port", "9000")+ self.assertTrue(coli._serve_cmdline_matches_port(raw, 9000))+ self.assertFalse(coli._serve_cmdline_matches_port(raw, 8000))++ def test_equals_port_syntax(self):+ raw = self.cmdline("/opt/colibri/coli", "serve", "--port=9000")+ self.assertTrue(coli._serve_cmdline_matches_port(raw, 9000))++ def test_serve_as_an_argument_is_not_a_server(self):+ raw = self.cmdline("python3", "/opt/colibri/coli", "chat",+ "--prompt", "serve", "--port", "9000")+ self.assertFalse(coli._serve_cmdline_matches_port(raw, 9000))++ def test_default_port_matches_only_8000(self):+ raw = self.cmdline("python3", "/opt/colibri/coli", "serve",+ "--model", "/models/a")+ self.assertTrue(coli._serve_cmdline_matches_port(raw, 8000))+ self.assertFalse(coli._serve_cmdline_matches_port(raw, 9000))++ def test_engine_tag_is_port_specific(self):+ raw = b"SNAP=/models/a\0SERVE=1\0COLI_SERVE_PORT=9000\0"+ self.assertTrue(coli._serve_environ_matches_port(raw, 9000))+ self.assertFalse(coli._serve_environ_matches_port(raw, 8000))++ def test_serve_tags_the_engine_environment(self):+ args = types.SimpleNamespace(port=9123)+ with mock.patch.object(coli, "env_for_engine", return_value={"X": "1"}):+ env = coli._serve_engine_env(args, "glm")+ self.assertEqual(env, {"X": "1", "COLI_SERVE_PORT": "9123"})++ def test_stop_handles_platform_without_proc(self):+ args = types.SimpleNamespace(port=9123, dry_run=True)+ with mock.patch.object(coli, "banner"), \+ mock.patch.object(coli, "serve_pidfile", return_value="/not/a/pidfile"), \+ mock.patch.object(coli.os, "listdir", side_effect=OSError):+ coli.cmd_stop(args)++ @unittest.skipUnless(sys.platform.startswith("linux") and Path("/proc").is_dir(),+ "process discovery uses Linux /proc")+ def test_stop_kills_only_the_requested_server(self):+ with tempfile.TemporaryDirectory() as tmp:+ script = Path(tmp) / "coli"+ script.write_text("import time\ntime.sleep(60)\n", encoding="utf-8")+ own = subprocess.Popen([sys.executable, str(script), "serve",+ "--port", "9123"])+ other = subprocess.Popen([sys.executable, str(script), "serve",+ "--port", "9124"])+ try:+ for _ in range(50):+ try:+ if b"serve" in Path(f"/proc/{own.pid}/cmdline").read_bytes():+ break+ except OSError:+ pass+ time.sleep(0.02)+ args = types.SimpleNamespace(port=9123, dry_run=False)+ with mock.patch.object(coli, "banner"), \+ mock.patch.object(coli, "serve_pidfile",+ return_value=os.path.join(tmp, "missing.pid")), \+ mock.patch.object(coli.time, "sleep"), \+ contextlib.redirect_stdout(io.StringIO()):+ coli.cmd_stop(args)+ own.wait(timeout=5)+ self.assertIsNone(other.poll(), "stop killed a server on another port")+ finally:+ for process in (own, other):+ if process.poll() is None:+ process.terminate()+ process.wait(timeout=5)+++if __name__ == "__main__":+ unittest.main()