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++
serve: a restarting engine is not alive until READY; context 0 is a 503 "starting" (#344)
Niko122140eaa123d4d0
diff --git a/serve/server.py b/serve/server.pyindex af6665701..5134c91b3 100644--- a/serve/server.py+++ b/serve/server.py@@ -99,6 +99,11 @@ class EngineDied(RuntimeError):"""The engine process ended in the middle of a request (issue #27: on Linux, the out-of-memory killer)."""+class EngineStarting(RuntimeError):+ """The engine is (re)starting and has not said READY yet (#344): no context size to plan a request with - a 503,+ not a 400 about the prompt."""++class GpuBusy(RuntimeError):"""The model is unloaded and the GPU has less free VRAM than min_free_vram_mib: something else (a game, anothermodel server) is using it, so the engine is not started into the little that is left."""@@ -206,15 +211,18 @@ class StrataEngine:# report their own version (INFO engine=, 0.1.8+) win, the manifest stays the fallback for older onesif self.info.get("engine"):self.info["version"] = str(self.info["engine"])+ self.ended = False # READY: alive from here (restart() set it True, #344)# the engine's stdout on a thread, so a request can wait with a timeout (heartbeats, cancel checks)self.lines: queue.Queue = queue.Queue()threading.Thread(target=self._pump, daemon=True).start()def _pump(self):- for line in self.proc.stdout:- self.lines.put(line)- self.ended = True # its output closed: it is gone, even before the OS says so- self.lines.put(None)+ proc, lines = self.proc, self.lines # this process's: a restart replaces both (#344)+ for line in proc.stdout:+ lines.put(line)+ if self.proc is proc: # a killed engine's pump must not mark its successor dead+ self.ended = True # its output closed: it is gone, even before the OS says so+ lines.put(None)def death_note(self) -> str:"""Why the engine most likely ended, from the end of its log: its own watchdog (issue #29), else RAM."""@@ -274,7 +282,10 @@ class StrataEngine:except OSError:passinfo = dict(self.info)- self.ended = False+ # #344: not alive until READY - __init__ sets max_context to 0 and blocks until the engine says READY, and a+ # request that saw alive() in that window skipped load() and failed with "context (0)". __init__ clears+ # `ended` itself once READY (before its pump thread can set it again).+ self.ended = Trueself.__init__(*self.spawn)self.info = {**info, **self.info}@@ -953,6 +964,8 @@ class Service:for path, _ in encoded:f.write(path.read_bytes())self.embeddings.path = combined+ if self.engine.max_context <= 0: # #344: (re)starting, not a prompt that is too long+ raise EngineStarting("the engine is starting (a minute or two); try again shortly")room = self.engine.max_context - CTX_SLACK - len(ids)if max_new is None or max_new <= 0 or (self.fit_max_tokens and room < 1):if room < 1:@@ -1637,7 +1650,7 @@ def make_handler(svc: Service):self._json(404, {"error": {"message": "not found"}})except ValueError as e:self._json(400, {"error": {"type": "invalid_request_error", "message": str(e)}})- except GpuBusy as e:+ except (GpuBusy, EngineStarting) as e: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"}})diff --git a/serve/test_server.py b/serve/test_server.pyindex d84ebff40..087ca44a6 100644--- a/serve/test_server.py+++ b/serve/test_server.py@@ -1380,5 +1380,93 @@ class StatusHandover(unittest.TestCase):self.assertFalse(svc.status["busy"])self.assertNotIn("tail", svc.status)++FAKE_STRATA = '''import pathlib, sys, time+gate = pathlib.Path(sys.argv[sys.argv.index("--gate") + 1])+print("INFO engine=0.0.0", flush=True)+while not gate.exists(): # the test says when the engine is "ready"+ time.sleep(0.01)+print("READY 4096 stop", flush=True)+for line in sys.stdin:+ if line.startswith("QUIT"):+ break+'''+++class RestartWindow(unittest.TestCase):+ """#344: while the engine restarts it is not alive (a request waits for the restart instead of reading+ max_context 0), and a request that still meets max_context 0 gets a 503 "starting", not a 400 about its prompt."""++ def test_not_alive_until_ready(self):+ from unittest import mock+ import serve.server as server+ with tempfile.TemporaryDirectory() as d:+ script, gate = Path(d) / "fake_strata.py", Path(d) / "ready"+ script.write_text(FAKE_STRATA, encoding="utf-8")+ real = server.subprocess.Popen+ with mock.patch.object(server.subprocess, "Popen",+ lambda cmd, **kw: real([sys.executable, str(script), *cmd[1:]], **kw)):+ gate.touch()+ eng = StrataEngine("strata", ["--gate", str(gate)])+ try:+ self.assertEqual(eng.max_context, 4096)+ self.assertTrue(eng.alive())+ gate.unlink()+ old = eng.proc+ old.kill()+ old.wait(10)+ deadline = time.time() + 10+ while not getattr(eng, "ended", False) and time.time() < deadline:+ time.sleep(0.01) # the server has noticed: its output closed+ self.assertFalse(eng.alive())+ t = threading.Thread(target=eng.restart)+ t.start()+ deadline = time.time() + 10+ while eng.proc is old and time.time() < deadline:+ time.sleep(0.005)+ self.assertIsNot(eng.proc, old, "restart never started the engine")+ time.sleep(0.2) # the new engine is up, but has not said READY+ self.assertEqual(eng.max_context, 0)+ self.assertFalse(eng.alive(), "alive before READY: a request would plan with context 0")+ gate.touch()+ t.join(10)+ self.assertFalse(t.is_alive())+ self.assertTrue(eng.alive())+ self.assertEqual(eng.max_context, 4096)+ # restart() of a running engine kills it first: that engine's output thread ends after the new+ # one is up, and must not mark it dead (it did: every request after restarted it again)+ eng.restart()+ time.sleep(0.5)+ self.assertTrue(eng.alive())+ self.assertEqual(eng.max_context, 4096)+ finally:+ gate.touch()+ eng.unload()++ def test_context_zero_is_503(self):+ tok = ByteTokenizer()+ svc = Service(MockEngine(tok, "</think>\n\nok", max_context=0), tok,+ ChatTemplate(ROOT / "serve/chat_template.jinja"))+ httpd = serve(svc, port=0)+ base = f"http://127.0.0.1:{httpd.server_address[1]}"+ try:+ for path, body in (("/v1/chat/completions", {"model": "m", "messages": [{"role": "user", "content": "hi"}],+ "max_tokens": 16}),+ ("/v1/messages", {"model": "m", "max_tokens": 16,+ "messages": [{"role": "user", "content": "hi"}]})):+ req = urllib.request.Request(base + path, data=json.dumps(body).encode(),+ headers={"Content-Type": "application/json"})+ with self.assertRaises(urllib.error.HTTPError) as cm:+ urllib.request.urlopen(req, timeout=30)+ with cm.exception as e:+ self.assertEqual(e.code, 503, path)+ text = e.read().decode()+ self.assertIn("starting", text)+ self.assertNotIn("leaves no room", text)+ finally:+ httpd.shutdown()+ httpd.server_close()++if __name__ == "__main__":unittest.main()