Skip to content

Run frontier MoE models on hardware you already own β€” pure C, zero deps, experts streamed from disk. Tiny engine, immense model. 🐦

C

serve: give the engine its graceful exit β€” stdin drain, SIGBREAK, group isolation

Taras Zubar49e72cd94e1c
diff --git a/c/coli b/c/coli
index bdc1072e..d7959e7d 100755
--- a/c/coli
+++ b/c/coli
@@ -2252,9 +2252,21 @@ def cmd_stop(a):
print(f" nothing running β€” no serve on port {a.port}, no SERVE engines"); return
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:
+ # Graceful first: only the launcher's Engine.close drains the engine
+ # (stdin EOF -> atexit -> HEAT_FILE save). SIGTERM the launchers and
+ # give them the drain window to exit on their own; engine pids left
+ # behind (orphaned, no launcher) get the old treatment after.
+ launchers = [pid for pid, d in targets.items() if d.startswith("coli serve")]
+ strays = [pid for pid, d in targets.items() if not d.startswith("coli serve")]
+ deadline = time.time() + 30.0
+ for pid in launchers:
try: os.kill(pid, signal.SIGTERM)
except OSError: pass
+ while time.time() < deadline and any(_pid_alive(p) for p in launchers):
+ time.sleep(0.25)
+ for pid in strays:
+ try: os.kill(pid, signal.SIGTERM) # normally already gone with the launcher
+ except OSError: pass
time.sleep(2.0)
for pid in targets:
# signal.SIGKILL does not exist on win32 and AttributeError is not OSError,
diff --git a/c/openai_server.py b/c/openai_server.py
index 42fe3635..f38e0fb6 100644
--- a/c/openai_server.py
+++ b/c/openai_server.py
@@ -2483,6 +2483,11 @@ GENERIC_JSON_GBNF = (
DEFAULT_CHAT_STOP_SEQUENCES = ("<|user|>", "<|observation|>")
+# Seconds to wait for the engine to exit on its own after stdin EOF (its
+# atexit teardown writes HEAT_FILE). EOF is only observed between turns,
+# so an in-flight generation delays exit; override for impatient scripts.
+_ENGINE_DRAIN_S = float(os.environ.get("COLI_ENGINE_DRAIN_S", "30"))
+
def parse_stop_sequences(body):
value = body.get("stop")
@@ -2979,9 +2984,15 @@ class Engine:
resolved_cap = cap_for_arch(arch, cap, child_env)
child_env.pop("COLI_PROFILE_CAP", None)
child_env.pop("COLI_PLAN_CAP", None)
+ # Own process group on Windows: a CTRL_BREAK sent to the serve
+ # process group (the graceful stop, handled as SIGBREAK above) must
+ # not reach the engine β€” the C runtime's default would kill it
+ # before its stdin-EOF teardown (atexit -> HEAT_FILE save) can run.
+ spawn_flags = subprocess.CREATE_NEW_PROCESS_GROUP if sys.platform == "win32" else 0
self.process = subprocess.Popen(
[str(executable), str(resolved_cap)], env=child_env,
stdin=subprocess.PIPE, stdout=subprocess.PIPE, bufsize=0,
+ creationflags=spawn_flags,
)
# 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
@@ -3370,21 +3381,33 @@ class Engine:
self.closed = True
self._fail_pending(RuntimeError("colibri engine is shutting down"))
if self.process.poll() is None:
- self.process.terminate()
+ # Graceful drain first: the engine's serve loop reads requests
+ # from stdin, and EOF there is the one portable path to its
+ # atexit teardown (qt_shutdown -> HEAT_FILE save). EOF only
+ # lands between turns, so the drain wait must be generous;
+ # anything else falls through to the hard-stop ladder below.
+ try:
+ self.process.stdin.close()
+ except (OSError, ValueError, AttributeError):
+ pass
try:
- self.process.wait(timeout=5)
+ self.process.wait(timeout=_ENGINE_DRAIN_S)
except subprocess.TimeoutExpired:
- # A large resident cache (e.g. 111 GB at --memory-gb 126) can
- # take longer than the grace period to unmap and free on
- # SIGTERM. SIGKILL cannot be caught, so the process is already
- # on its way out; a second timeout only means the reap has not
- # landed yet. Teardown is best-effort: never raise from here, or
- # a completed measurement is lost to a shutdown that succeeded.
- self.process.kill()
+ self.process.terminate()
try:
self.process.wait(timeout=5)
except subprocess.TimeoutExpired:
- pass
+ # A large resident cache (e.g. 111 GB at --memory-gb 126) can
+ # take longer than the grace period to unmap and free on
+ # SIGTERM. SIGKILL cannot be caught, so the process is already
+ # on its way out; a second timeout only means the reap has not
+ # landed yet. Teardown is best-effort: never raise from here, or
+ # a completed measurement is lost to a shutdown that succeeded.
+ self.process.kill()
+ try:
+ self.process.wait(timeout=5)
+ except subprocess.TimeoutExpired:
+ pass
if self.dispatcher is not threading.current_thread():
self.dispatcher.join(timeout=5)
@@ -4887,6 +4910,16 @@ def serve(model, host="127.0.0.1", port=8000, model_id=None, api_key=None,
server.engine = runtime
print(f"OpenAI-compatible API listening on http://{host}:{port}/v1", file=sys.stderr)
signal.signal(signal.SIGTERM, lambda *_: threading.Thread(target=server.shutdown, daemon=True).start())
+ # On Windows SIGTERM is never delivered (os.kill is TerminateProcess);
+ # CTRL_BREAK β€” the one console signal a controller CAN target at this
+ # process group β€” arrives as SIGBREAK. Without this handler it kills
+ # the serve loop outright, skipping the finally that drains the
+ # engine (stdin EOF -> atexit -> HEAT_FILE save). The engine child
+ # runs in its own process group (see Engine.__init__) and does not
+ # receive this event.
+ if hasattr(signal, "SIGBREAK"):
+ signal.signal(signal.SIGBREAK,
+ lambda *_: threading.Thread(target=server.shutdown, daemon=True).start())
try:
server.serve_forever()
except KeyboardInterrupt:
diff --git a/c/tests/test_engine_close_drain.py b/c/tests/test_engine_close_drain.py
new file mode 100644
index 00000000..b4502276
--- /dev/null
+++ b/c/tests/test_engine_close_drain.py
@@ -0,0 +1,75 @@
+"""Engine.close drain contract: stdin EOF is the engine's graceful exit.
+
+``Engine.close`` must give the engine its one portable graceful path β€” the
+serve loop reads requests from stdin, so closing that pipe lets the process
+run its ``atexit`` teardown (``qt_shutdown`` writes HEAT_FILE) and exit 0.
+Only a process that outlives the drain window falls through to the existing
+terminate/kill ladder.
+
+The tests drive ``close()`` against real subprocesses of ``python -c``:
+one that blocks on ``stdin.read()`` (the well-behaved engine) and one that
+ignores EOF and sleeps (the hung engine). No model, GPU, or engine build is
+involved β€” the contract under test is the *shutdown handshake*.
+"""
+
+import os
+import subprocess
+import sys
+import threading
+import time
+import unittest
+
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+import openai_server # noqa: E402
+
+EOF_ENGINE = "import sys\nsys.stdin.read()\n" # blocks until EOF, exits 0
+HANG_ENGINE = "import time\ntime.sleep(120)\n" # ignores stdin entirely
+
+
+def bare_engine(code):
+ """An Engine with only what close() touches, around a real subprocess."""
+ engine = object.__new__(openai_server.Engine)
+ engine.closed = False
+ engine.pending_lock = threading.Lock()
+ engine._fail_pending = lambda *args, **kwargs: None
+ engine.dispatcher = threading.current_thread() # skip the join branch
+ engine.process = subprocess.Popen(
+ [sys.executable, "-c", code], stdin=subprocess.PIPE)
+ return engine
+
+
+class EngineCloseDrain(unittest.TestCase):
+ def tearDown(self):
+ saved = openai_server._ENGINE_DRAIN_S
+ self.addCleanup(lambda: setattr(openai_server, "_ENGINE_DRAIN_S", saved))
+
+ def test_eof_exit_is_graceful(self):
+ openai_server._ENGINE_DRAIN_S = 10.0
+ engine = bare_engine(EOF_ENGINE)
+ self.addCleanup(engine.process.kill)
+ engine.process.stdin.write(b"x") # a buffered request byte, like a turn
+ engine.process.stdin.flush()
+ started = time.perf_counter()
+ engine.close()
+ elapsed = time.perf_counter() - started
+ self.assertEqual(engine.process.returncode, 0,
+ "engine should exit 0 on stdin EOF, not by signal")
+ self.assertLess(elapsed, openai_server._ENGINE_DRAIN_S,
+ "graceful exit must not consume the drain window")
+
+ def test_hung_engine_falls_back_to_hard_stop(self):
+ openai_server._ENGINE_DRAIN_S = 0.5
+ engine = bare_engine(HANG_ENGINE)
+ self.addCleanup(engine.process.kill)
+ started = time.perf_counter()
+ engine.close()
+ elapsed = time.perf_counter() - started
+ self.assertIsNotNone(engine.process.returncode,
+ "fallback ladder must still stop the process")
+ self.assertNotEqual(engine.process.returncode, 0,
+ "a killed engine must not look like a clean exit")
+ self.assertLess(elapsed, 20, "fallback should be prompt")
+
+
+if __name__ == "__main__":
+ unittest.main()