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

- StrataEngine.close() (now also the unload and the restart): QUIT and EOF, then terminate, then kill, each with 20 s
  as the unload had (#333 went from QUIT straight to kill after 10 s; an engine unpinning tens of GB can need more).
  A process that outlives all three raises EngineStuck and stays owned.
- do_POST caught every RuntimeError as a 503 - EngineDied, GpuBusy and ModelBusy are RuntimeErrors too, and any other
  failure was turned into a vague 503. Only EngineStuck is caught now (also around POST /unload, and the idle-unload
  thread survives it); EngineDied keeps its own answer.
- test_lifecycle: terminate before kill, EngineStuck, an EngineDied on load answered as such.
This commit is contained in:
Niko1221 committed 2026-10-01 08:26:28 +02:00
1 parent 7f3a091895
commit bd9a1bc126
2 files changed
+55 -12

No files matched your search

+30 -10
View File
@@ -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):
+25 -2
View File
@@ -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)