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++

serve: time out the untimed reads of the engine's READY line and the image encoder's pipe (#1317)

Niko122102be84a09cce
diff --git a/serve/server.py b/serve/server.py
index fd90e3cd4..5d06c2de9 100644
--- a/serve/server.py
+++ b/serve/server.py
@@ -214,6 +214,14 @@ SESSION_WAIT_MAX_S = 3600
PP_CHUNK_MAX = 32768
PP_FLOOR_TOK_S = 50.0
PP_SLACK = 3.0
+# Reads that had no timeout (#1317). A blocking read of the image encoder's pipe or of the engine's READY line that
+# never returned held the request turn for good: the engine then sat idle in its command loop, so no watchdog could
+# fire and every later request queued behind it (the "lost step" class of #481). Generous on purpose: a cold model
+# load, a slow disk or a slow CPU encode is not a hang. Only a process that says nothing at all for this long is
+# ended; the next request starts it again.
+VISION_READY_S = 300.0
+VISION_ENCODE_S = 300.0
+ENGINE_READY_S = 900.0
# ------------------------------------------------------------------------------------------------ engines
@@ -611,7 +619,23 @@ class StrataEngine:
stdout=subprocess.PIPE, stderr=self.log, text=True, encoding="utf-8", bufsize=1, env=env)
contain(self.proc) # ends with the server, however it ends (Windows)
self.max_context = 0
- for line in self.proc.stdout:
+ # the READY read has a timeout (#1317): the lines come from a thread, up to READY, so the rest of the stream
+ # stays for _pump (one reader at a time)
+ ready_q: queue.Queue = queue.Queue()
+ threading.Thread(target=self._ready_pump, args=(self.proc, ready_q), daemon=True).start()
+ ready_deadline = time.monotonic() + ENGINE_READY_S
+ timed_out = False
+ while True:
+ left = ready_deadline - time.monotonic()
+ if left <= 0:
+ timed_out = True
+ break
+ try:
+ line = ready_q.get(timeout=left)
+ except queue.Empty:
+ continue
+ if line is None:
+ break
if line.startswith("INFO "):
for kv in line.split()[1:]:
k, _, v = kv.partition("=")
@@ -623,6 +647,11 @@ class StrataEngine:
break
loading.set()
if self.max_context <= 0:
+ if timed_out: # still loading, or hung: end it, so the turn is not held for good
+ try:
+ self.proc.kill()
+ except OSError:
+ pass
try: # its pipes and our handle on its log (the log stays)
self.proc.wait(timeout=5)
self.proc.stdin.close()
@@ -631,7 +660,9 @@ class StrataEngine:
self.log.close()
except (OSError, subprocess.TimeoutExpired):
pass
- raise RuntimeError("the engine exited before it was ready" + (f" (see {log})" if log else "") +
+ why = (f"the engine did not report READY within {ENGINE_READY_S:.0f} s" if timed_out else
+ "the engine exited before it was ready")
+ raise RuntimeError(why + (f" (see {log})" if log else "") +
start_failure_hint(log, log_start) + start_log_tail(log, log_start))
self.known_ctx = self.max_context # survives a failed restart: requests keep their limit and restart it
# (from PR #41, midhatn) a locally built engine can sit next to another release's BUILD.json: engines that
@@ -759,6 +790,22 @@ class StrataEngine:
RESTART_RETRY_S = 15.0 # between the tries of restart(): a dying engine's VRAM may take a while to come back
+ @staticmethod
+ def _ready_pump(proc, out: queue.Queue) -> None:
+ """The engine's first lines up to READY, for a read that can time out; None when its output closed first."""
+ done = False
+ try:
+ for line in proc.stdout:
+ out.put(line)
+ if line.startswith("READY"):
+ done = True
+ return
+ except (OSError, ValueError): # the pipe closed under us (the engine was killed)
+ pass
+ finally:
+ if not done:
+ out.put(None)
+
def restart(self, tries: int = 3):
"""Start the engine again (the same command) after it died; the new process has its own line queue.
close() ends and waits for the old process first (EngineStuck when it cannot be ended). A start that still
@@ -1689,7 +1736,11 @@ class Vision:
stderr=log or subprocess.DEVNULL, text=True, encoding="utf-8", bufsize=1, env=env,
cwd=self.dir)
contain(self.proc)
- line = self.proc.stdout.readline()
+ try:
+ line = self._readline(VISION_READY_S, "the vision encoder did not start")
+ except RuntimeError as e: # silent for VISION_READY_S: it was ended, and it is not left half-started
+ self.proc, self.stopped = None, True
+ raise RuntimeError(str(e)) from None
if not line.startswith("READY"):
proc, self.proc = self.proc, None
self.stopped = True
@@ -1701,6 +1752,28 @@ class Vision:
raise RuntimeError("the vision encoder did not start: " + line.strip())
self.stopped = False
+ def _readline(self, timeout: float, what: str) -> str:
+ """One line from the encoder, waiting at most `timeout` s (#1317). On a timeout the encoder is killed, so the
+ next request starts a fresh one, and the read raises RuntimeError instead of holding the request turn."""
+ proc = self.proc
+ got: queue.Queue = queue.Queue()
+
+ def read():
+ try:
+ got.put(proc.stdout.readline())
+ except (OSError, ValueError): # killed under the read
+ got.put("")
+
+ threading.Thread(target=read, daemon=True).start()
+ try:
+ return got.get(timeout=timeout)
+ except queue.Empty:
+ try:
+ proc.kill()
+ except OSError:
+ pass
+ raise RuntimeError(f"{what}: it said nothing for {timeout:.0f} s") from None
+
def alive(self) -> bool:
return self.proc is not None and not self.stopped and self.proc.poll() is None
@@ -1827,7 +1900,11 @@ class Vision:
try:
self.proc.stdin.write(f"ENC {img.name} {out.name}\n") # relative to the encoder's cwd (#480)
self.proc.stdin.flush()
- line = self.proc.stdout.readline().strip()
+ try:
+ line = self._readline(VISION_ENCODE_S, "the image could not be read").strip()
+ except RuntimeError as e: # silent for VISION_ENCODE_S: the encoder was ended (#1317)
+ self.stopped = True # alive() is False, so the next request starts it again
+ raise ValueError(str(e)) from None
finally: # #352: also when the encoder's pipe is gone
img.unlink(missing_ok=True)
if not line.startswith("OK"):
diff --git a/serve/test_server.py b/serve/test_server.py
index fe374614a..a6f9f1155 100644
--- a/serve/test_server.py
+++ b/serve/test_server.py
@@ -4709,5 +4709,89 @@ class ClaudeCodeBillingStamp(unittest.TestCase):
self.assertEqual(ids[1][:len(first) - 8], first[:len(first) - 8]) # all but the generation header
+class UntimedReads(unittest.TestCase):
+ """#1317: a read of the engine's READY line or of the image encoder's pipe that never returns held the request
+ turn for good. Each now has a timeout; a process that stays silent is ended and the read raises."""
+
+ def test_engine_that_never_says_ready_is_ended(self):
+ import serve.server as server
+ fake = "import time\nprint('INFO engine=0.0.0', flush=True)\ntime.sleep(600)\n"
+ with tempfile.TemporaryDirectory() as d:
+ script = Path(d) / "fake_strata.py"
+ script.write_text(fake, encoding="utf-8")
+ real = server.subprocess.Popen
+ procs = []
+
+ def popen(cmd, **kw):
+ procs.append(real([sys.executable, str(script), *cmd[1:]], **kw))
+ return procs[-1]
+ with mock.patch.object(server.subprocess, "Popen", popen), \
+ mock.patch.object(server, "ENGINE_READY_S", 1.0), \
+ mock.patch.object(server, "narrate_start", lambda *a, **k: None):
+ t0 = time.monotonic()
+ with self.assertRaises(RuntimeError) as cm:
+ StrataEngine("strata", [])
+ self.assertLess(time.monotonic() - t0, 30)
+ self.assertIn("did not report READY within 1 s", str(cm.exception))
+ procs[0].wait(10) # killed, not left running
+ self.assertIsNotNone(procs[0].poll())
+
+ class Silent:
+ """A pipe whose readline blocks until the test lets go (or the encoder is killed)."""
+ def __init__(self):
+ self.release = threading.Event()
+ self.killed = False
+
+ def readline(self):
+ self.release.wait(30)
+ return ""
+
+ def kill(self):
+ self.killed = True
+ self.release.set()
+
+ def test_vision_encode_read_times_out(self):
+ import serve.server as server
+ silent = self.Silent()
+ v = server.Vision.__new__(server.Vision)
+ v.dir, v.lock, v.cache = Path(tempfile.mkdtemp(prefix="strata-vision-test-")), threading.Lock(), {}
+ v.stopped = False
+ v.proc = SimpleNamespace(stdin=io.StringIO(), stdout=silent, kill=silent.kill, poll=lambda: 1 if silent.killed else None)
+ try:
+ with mock.patch.object(server, "VISION_ENCODE_S", 0.3), \
+ mock.patch.object(server.Vision, "load", return_value=b""), mock.patch.object(server.Vision, "normalize", return_value=b"png"):
+ with self.assertRaises(ValueError) as cm:
+ v.encode("x")
+ self.assertIn("said nothing for", str(cm.exception))
+ self.assertTrue(silent.killed) # ended: the next request starts a fresh one
+ self.assertFalse(v.alive())
+ self.assertEqual(list(v.dir.glob("*.img")), []) # the temporary image is removed
+ finally:
+ shutil_rmtree(v.dir)
+
+ def test_vision_ready_read_times_out(self):
+ import serve.server as server
+ silent = self.Silent()
+ proc = SimpleNamespace(stdin=io.StringIO(), stdout=silent, kill=silent.kill, poll=lambda: None)
+ v = server.Vision.__new__(server.Vision)
+ v.spawn = (["strata-vision"], None, None)
+ v.dir = Path(tempfile.mkdtemp(prefix="strata-vision-test-"))
+ try:
+ with mock.patch.object(server, "popen", lambda *a, **k: proc), mock.patch.object(server, "contain"), mock.patch.object(server, "VISION_READY_S", 0.3):
+ with self.assertRaises(RuntimeError) as cm:
+ v._start()
+ self.assertIn("did not start", str(cm.exception))
+ self.assertTrue(silent.killed)
+ self.assertFalse(v.alive())
+ finally:
+ shutil_rmtree(v.dir)
+
+ def test_a_vision_answer_in_time_is_unchanged(self):
+ import serve.server as server
+ v = server.Vision.__new__(server.Vision)
+ v.proc = SimpleNamespace(stdout=SimpleNamespace(readline=lambda: "OK 7 1 1 1\n"))
+ self.assertEqual(v._readline(5.0, "x"), "OK 7 1 1 1\n")
+
+
if __name__ == "__main__":
unittest.main()