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 restart keeps the admission state, so waiting requests no longer hang or fail with ValueError (#1012)
Niko122157a69eb48f4e
diff --git a/serve/server.py b/serve/server.pyindex 4522ab399..334528b62 100644--- a/serve/server.py+++ b/serve/server.py@@ -657,12 +657,17 @@ class StrataEngine:self.slot_held: list[list[int]] = [[] for _ in range(self.batch)]self.slot_used = [0.0] * self.batchself.slot_live: list[dict | None] = [None] * self.batch # /metrics: the request in each slot- self.slot_cv = threading.Condition()- self.waiting = 0 # requests waiting for the control lines (ctl)- self.wait_lens: list[list[int]] = [] # ... their prompt lengths (a long read gives way to short ones)- self.ctl_epoch = 0 # how often the control lines were taken+ # #1012: the admission state belongs to the server, not to one engine process. restart() runs this again+ # while requests still wait on it (they hold these very objects), so it is made once and kept: new ones+ # would leave the waiters on a lock and a condition nobody notifies, with their counts missing from the+ # new lists.+ if "slot_cv" not in self.__dict__:+ self.slot_cv = threading.Condition()+ self.waiting = 0 # requests waiting for the control lines (ctl)+ self.wait_lens: list[list[int]] = [] # ... their prompt lengths (a long read gives way to short ones)+ self.ctl_epoch = 0 # how often the control lines were taken+ self.ctl = threading.Lock() # one admission or solo request on the control lines at a timeself._yielded = None # (slot, tokens read): the last request on them gave way- self.ctl = threading.Lock() # one admission or solo request on the control lines at a timeself.wlock = threading.Lock() # stdin writes from several request threadsself.pump = threading.Thread(target=self._pump, daemon=True)self.pump.start()@@ -750,10 +755,10 @@ class StrataEngine:close() ends and waits for the old process first (EngineStuck when it cannot be ended). A start that stillexits before READY - a dead engine's VRAM can take a while to come back, notably on ROCm - is retried(PR #637)."""- self.close()info = dict(self.info)self.starting = True # prepare() answers 503 "starting" meanwhile (#344)try:+ self.close()for i in range(tries):# #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@@ -774,6 +779,8 @@ class StrataEngine:time.sleep(self.RESTART_RETRY_S)finally:self.starting = False+ with self.slot_cv: # #1012: wake the requests that waited through it: they go on with the+ self.slot_cv.notify_all() # new engine, or (it did not start) end with a clean EngineDiedself.info = {**info, **self.info}def _parse_done(self, line):@@ -963,16 +970,20 @@ class StrataEngine:"""A slot whose consumer left (a stop token, a stop string, a disconnect): BSTOP it and free it once the enginesays BDONE (in the background). `stream`: the prompt and every token of it so far - with the tokens still tocome before BDONE, all but the last are what the slot holds then (the next turn of its conversation)."""+ if slot >= len(self.slot_q): # the engine restarted with fewer slots: this one is gone+ returntry:self._send(f"BSTOP {slot}")except EngineDied:pass+ q, busy, held = self.slot_q[slot], self.slot_busy, self.slot_held # this process's: restart() replaces them+def wait():end = time.monotonic() + 600.0tail = list(stream or [])while time.monotonic() < end:try:- line = self.slot_q[slot].get(timeout=5.0)+ line = q.get(timeout=5.0)except queue.Empty:continueif line is None:@@ -985,9 +996,9 @@ class StrataEngine:tail = []if line.startswith("BDONE "):break- self.slot_held[slot] = tail[:-1] if stream and tail else []+ held[slot] = tail[:-1] if stream and tail else []with self.slot_cv:- self.slot_busy[slot] = False+ busy[slot] = Falseself.slot_cv.notify_all()threading.Thread(target=wait, daemon=True).start()@@ -1003,10 +1014,18 @@ class StrataEngine:beat = time.monotonic()try:while True:+ if not self.alive() and not getattr(self, "starting", False):+ # #1012: the engine is gone and nobody is starting it again: this request was not sent, so it+ # ends now (a clean 503) instead of waiting for control lines nothing will answer on. While a+ # restart is under way it keeps waiting and goes on with the new engine.+ raise EngineDied("the engine stopped while this request waited; it was not sent")with self.slot_cv:turn = after_epoch is None or self.ctl_epoch > after_epoch or self.waiting <= 1if turn and self.ctl.acquire(timeout=0.5):- break+ if self.alive():+ break+ self.ctl.release() # it died (or is being restarted) while this one was getting+ turn = False # the lines: not the engine this request was meant forif not turn:with self.slot_cv:self.slot_cv.wait(timeout=0.5)@@ -1017,8 +1036,9 @@ class StrataEngine:yield Nonefinally:with self.slot_cv:- self.waiting -= 1- self.wait_lens.remove(entry)+ self.waiting = max(0, self.waiting - 1)+ if entry in self.wait_lens:+ self.wait_lens.remove(entry)with self.slot_cv:self.ctl_epoch += 1self.slot_cv.notify_all()@@ -3137,6 +3157,10 @@ class Service:Path(emb).unlink(missing_ok=True)for ev in cut(parser.finish(finish)):yield "event", ev+ if parser.rescued or parser.refused:+ self.totals["tool_calls_from_reasoning"] = self.totals.get("tool_calls_from_reasoning", 0) + parser.rescued+ print(f"[strata] tool calls inside the thinking: {parser.rescued} read as calls, {parser.refused} kept as "+ f"reasoning (quoted, or the turn did not end on a stop)", flush=True)if stops is not None and stops.hit is None and stops.held:yield "event", Event("content", stops.flush()) # the held tail was not a stop string after alldone = {"finish": finish, "completion_tokens": n, "reused": (timings or {}).get("cache_n", 0),@@ -3157,10 +3181,6 @@ def prompt_tokens_seen(prompt_tokens: int, last: dict) -> int:return prompt_tokensreturn min(prompt_tokens, int(last.get("reused") or 0) + int(read))- if parser.rescued or parser.refused:- self.totals["tool_calls_from_reasoning"] = self.totals.get("tool_calls_from_reasoning", 0) + parser.rescued- print(f"[strata] tool calls inside the thinking: {parser.rescued} read as calls, {parser.refused} kept as "- f"reasoning (quoted, or the turn did not end on a stop)", flush=True)def request_timings(prompt_tokens: int, generated: int, last: dict) -> dict | None:"""One request's `timings` in llama.cpp's names (what its clients show as speed), from the engine's own clockdiff --git a/serve/test_restart_waiters.py b/serve/test_restart_waiters.pynew file mode 100644index 000000000..df5fa5387--- /dev/null+++ b/serve/test_restart_waiters.py@@ -0,0 +1,151 @@+"""#1012 (the old #792): requests waiting for the engine's control lines when the engine is restarted.++restart() runs StrataEngine.__init__ again; it used to make a new condition variable, lock, wait counter and wait+list while the waiters still held the old ones: they hung for good, or failed with `list.remove(x): x not in+list`. The admission state is now kept across a restart. A waiter either goes on with the new engine or ends+with a clean 503; never a hang, never a ValueError. The fake engine of test_parallel runs behind the real+StrataEngine and Service.++ python -m unittest serve.test_restart_waiters -v+"""+import json+import subprocess+import sys+import threading+import time+import unittest+import urllib.error+import urllib.request+from pathlib import Path+from unittest import mock++from serve import test_parallel++REAL_POPEN = subprocess.Popen++class RestartWaiters(unittest.TestCase):+ # the fake-engine helpers of test_parallel (its module, not its class, is imported: no duplicate tests)+ chat = test_parallel.ParallelService.chat+ _start, tearDown = test_parallel.ParallelService.start, test_parallel.ParallelService.tearDown++ def start(self, slots, fit=None):+ """The fake engine, and it stays the engine for the restarts that follow (Popen is patched for the test)."""+ import serve.server as server+ real = REAL_POPEN+ self._start(slots, fit=fit)+ script = Path(self.tmp.name) / "fake_strata.py"+ patch = mock.patch.object(server.subprocess, "Popen",+ lambda cmd, **kw: real([sys.executable, str(script), *cmd[1:]], **kw))+ patch.start()+ self.addCleanup(patch.stop)++ def post(self, text, out, i):+ try:+ out[i] = ("ok", self.chat(text)["choices"][0]["message"]["content"])+ except urllib.error.HTTPError as e:+ out[i] = ("http", e.code, json.loads(e.read().decode())["error"]["message"])+ except Exception as e: # noqa: BLE001 - reported by the assertions+ out[i] = ("exc", repr(e))++ def waiters(self, n):+ """n requests that wait for the control lines: the test holds them (as a prompt read would)."""+ assert self.engine.ctl.acquire(timeout=5)+ out, threads = {}, []+ for i in range(n):+ th = threading.Thread(target=self.post, args=(f"question {i}", out, i))+ th.start()+ threads.append(th)+ deadline = time.time() + 20+ while self.engine.waiting < n and time.time() < deadline:+ time.sleep(0.02)+ self.assertEqual(self.engine.waiting, n)+ return out, threads++ def joined(self, threads):+ for th in threads:+ th.join(60)+ self.assertFalse([th for th in threads if th.is_alive()], "a waiter hung")++ def clean(self):+ e = self.engine+ self.assertEqual((e.waiting, e.wait_lens), (0, []))+ self.assertFalse(e.ctl.locked())++ def kill(self):+ self.engine.proc.kill()+ self.engine.proc.wait(timeout=10)++ def go_on(self, slots):+ self.start(slots)+ e = self.engine+ cv, ctl, old_proc = e.slot_cv, e.ctl, e.proc+ out, threads = self.waiters(3)+ self.kill()+ restarter = threading.Thread(target=e.restart) # what ensure_loaded does for the next request+ restarter.start()+ time.sleep(0.2)+ e.ctl.release() # the request that held the lines is gone+ restarter.join(120)+ self.joined(threads)+ self.assertEqual(out, {i: ("ok", "ok, done.") for i in range(3)})+ self.assertIsNot(e.proc, old_proc)+ self.assertIs(e.slot_cv, cv) # the same condition variable and lock+ self.assertIs(e.ctl, ctl)+ self.clean()++ def test_waiters_go_on_with_the_new_engine_2_slots(self):+ self.go_on(2)++ def test_waiters_go_on_with_the_new_engine_4_slots(self):+ self.go_on(4)++ def stays_down(self, slots):+ self.start(slots)+ out, threads = self.waiters(3)+ self.kill()+ self.engine.ctl.release()+ self.joined(threads)+ for i in range(3):+ self.assertEqual(out[i][:2], ("http", 503), out[i])+ self.assertNotIn("list.remove", out[i][2])+ self.assertIn("engine", out[i][2])+ self.clean()+ # the next request starts the engine again and is served+ self.assertEqual(self.chat("after")["choices"][0]["message"]["content"], "ok, done.")+ self.clean()++ def test_waiters_get_a_clean_503_when_the_engine_stays_down_2_slots(self):+ self.stays_down(2)++ def test_waiters_get_a_clean_503_when_the_engine_stays_down_4_slots(self):+ self.stays_down(4)++ def test_a_restart_that_fails_wakes_the_waiters(self):+ self.start(2)+ e = self.engine+ out, threads = self.waiters(2)+ self.kill()++ def refuse(*a, **k): # as __init__ when the new engine exits before READY+ e.proc = REAL_POPEN([sys.executable, "-c", "pass"], stdin=subprocess.PIPE, stdout=subprocess.PIPE,+ text=True)+ raise RuntimeError("the engine exited before it was ready")+ e.__init__ = refuse+ try:+ with self.assertRaises(RuntimeError):+ e.restart(tries=1)+ finally:+ del e.__init__+ e.ctl.release()+ self.joined(threads)+ self.assertEqual([out[i][:2] for i in range(2)], [("http", 503)] * 2, out)+ self.clean()++ def test_solo_engine_is_unchanged(self):+ self.start(4, fit=0) # the engine turns batching off+ self.kill()+ self.assertEqual(self.chat("hi")["choices"][0]["message"]["content"], "ok, done.")+++if __name__ == "__main__":+ unittest.main()