Skip to content

Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.

C++

#333 follow-up: the unload keeps its terminate/kill fallback; EngineStuck instead of a catch-all RuntimeError

Niko1221bd9a1bc12673
diff --git a/serve/server.py b/serve/server.py
index 32ef06487..e86e27a6b 100644
--- a/serve/server.py
+++ b/serve/server.py
@@ -104,6 +104,11 @@ class ModelBusy(RuntimeError):
"""Explicit model controls must not interrupt active or queued requests."""
+class EngineStuck(RuntimeError):
+ """The engine process did not end after QUIT, terminate and kill: the server keeps it (and says so) rather than
+ reporting its GPU and RAM as given back."""
+
+
class GpuBusy(RuntimeError):
"""The model is unloaded and the GPU has less free VRAM than min_free_vram_mib: something else (a game, another
model server) is using it, so the engine is not started into the little that is left."""
@@ -437,20 +442,28 @@ class StrataEngine:
break
def close(self):
+ """End the engine process: QUIT first (the engine frees its memory itself - unpinning tens of GB can take
+ a while), then terminate, then kill, each given 20 s. Raises EngineStuck when it still runs after all three."""
if self.proc is None:
return
try:
if self.proc.poll() is None:
- self.proc.stdin.write("QUIT\n")
- self.proc.stdin.flush()
- self.proc.stdin.close() # Windows' detached stdin reader must see EOF before shutdown
- self.proc.wait(timeout=10)
- except (OSError, ValueError, subprocess.TimeoutExpired):
+ try:
+ self.proc.stdin.write("QUIT\n")
+ self.proc.stdin.flush()
+ self.proc.stdin.close() # Windows' detached stdin reader must see EOF before shutdown
+ self.proc.wait(timeout=20)
+ except (OSError, ValueError, subprocess.TimeoutExpired):
+ self.proc.terminate()
+ self.proc.wait(timeout=20)
+ except subprocess.TimeoutExpired:
self.proc.kill()
try:
- self.proc.wait(timeout=5)
+ self.proc.wait(timeout=20)
except subprocess.TimeoutExpired:
- raise RuntimeError("Strata is still releasing GPU/RAM; retry unloading after it exits") from None
+ raise EngineStuck("Strata is still releasing GPU/RAM; retry unloading after it exits") from None
+ except OSError:
+ pass
finally:
if self.proc.poll() is not None:
if self.pump is not None:
@@ -823,7 +836,10 @@ class Service:
def loop():
while True:
time.sleep(max(1.0, min(30.0, self.idle_unload_s / 4)))
- self.unload(idle_for=self.idle_unload_s)
+ try:
+ self.unload(idle_for=self.idle_unload_s)
+ except EngineStuck as e: # tried again at the next turn; the thread keeps running
+ print(f"[strata] idle unload: {e}", flush=True)
threading.Thread(target=loop, daemon=True).start()
def set_shared(self, defaults) -> dict:
@@ -1701,7 +1717,11 @@ def make_handler(svc: Service):
self._settings()
return
if path == "/unload": # give the GPU back now (between requests)
- r = svc.unload()
+ try:
+ r = svc.unload()
+ except EngineStuck as e:
+ self._json(503, {"error": {"type": "server_error", "message": str(e)}})
+ return
self._json(409 if r == "busy" else 200, {"status": r})
return
if path == "/load": # load now, e.g. ahead of a request
@@ -1757,7 +1777,7 @@ def make_handler(svc: Service):
self._json(503, {"error": {"type": "server_error", "message": str(e)}})
except EngineDied as e: # before the answer started (not streamed)
self._json(503, {"error": {"type": "server_error", "message": f"{e}; the next request restarts it"}})
- except RuntimeError as e:
+ except EngineStuck as e: # an unload or restart that could not end the engine
self._json(503, {"error": {"type": "server_error", "message": str(e)}})
def _props(self):
diff --git a/serve/test_lifecycle.py b/serve/test_lifecycle.py
index 6e54fd8fa..1d9f58c46 100644
--- a/serve/test_lifecycle.py
+++ b/serve/test_lifecycle.py
@@ -10,7 +10,7 @@ from pathlib import Path
from unittest import mock
from serve.frontend import ChatTemplate
-from serve.server import ByteTokenizer, MockEngine, Service, StrataEngine, serve
+from serve.server import ByteTokenizer, EngineDied, EngineStuck, MockEngine, Service, StrataEngine, serve
class ResidentEngine(StrataEngine):
@@ -63,11 +63,25 @@ class Lifecycle(unittest.TestCase):
proc.poll.return_value = None
proc.wait.side_effect = subprocess.TimeoutExpired("engine", 2)
engine.proc = proc
- with self.assertRaisesRegex(RuntimeError, "still releasing"):
+ with self.assertRaisesRegex(EngineStuck, "still releasing"):
engine.close()
self.assertIs(engine.proc, proc)
+ proc.terminate.assert_called_once()
proc.kill.assert_called_once()
+ def test_close_terminates_before_it_kills(self):
+ # an engine that does not end on QUIT is terminated first (as the unload always did); kill is the last resort
+ engine = StrataEngine("missing-executable", [], lazy=True)
+ proc = mock.Mock()
+ proc.stdin, proc.stdout = io.StringIO(), io.StringIO()
+ proc.poll.side_effect = [None, 0]
+ proc.wait.side_effect = [subprocess.TimeoutExpired("engine", 20), 0]
+ engine.proc = proc
+ engine.close()
+ proc.terminate.assert_called_once()
+ proc.kill.assert_not_called()
+ self.assertIsNone(engine.proc)
+
def test_native_lazy_constructor_does_not_start_a_process(self):
engine = StrataEngine("missing-executable", ["--max-context", "16384"], lazy=True)
self.assertFalse(engine.alive())
@@ -127,6 +141,15 @@ class Lifecycle(unittest.TestCase):
self.assertTrue(self.engine.loaded)
self.assertEqual(self.request("/v1/unload", {}, {"Authorization": "Bearer local-secret"})[0], 200)
+ def test_an_engine_that_died_on_load_is_reported_as_such(self):
+ # EngineDied is a RuntimeError: it keeps its own answer ("the next request restarts it")
+ def died():
+ raise EngineDied("the engine ended while it started")
+ self.engine.restart = died
+ code, body = self.request("/v1/chat/completions", {"messages": [{"role": "user", "content": "Hello"}]})
+ self.assertEqual(code, 503)
+ self.assertIn("the next request restarts it", body["error"]["message"])
+
def test_explicit_load_and_model_matching(self):
self.assertEqual(self.request("/v1/load", {"model": "other-model"})[0], 404)
self.assertEqual(self.engine.starts, 0)