[GH-ISSUE #1317] serve: an untimed read of the engine/vision pipe can hold the request turn forever (intermittent hang; the #481 lost-step class) #539

Closed
opened 2026-11-04 01:43:53 +07:00 by bsakaguchi · 2 comments
Owner

Originally created by @btc1000w on GitHub (Oct 7, 2026).
Original GitHub issue: https://github.com/Niko1221/Strata/issues/1317

Summary

On v0.1.40.1 (engine 0.1.40), running Qwen3.8-Flash-Next IQ3_XXS, the server intermittently hangs after it has been serving requests for a while: the current request stops progressing (the panel shows "waiting for token generation") and every later request stays "queued" forever. The engine is not stuck -- it is idle in its command loop; the server simply never finishes the request, so it never releases the single request turn.

Environment

  • Strata source 0.1.40.1 (engine 0.1.40), Windows, 2x RTX (3080 Laptop + 3070 Laptop, 16 GiB each), Xeon E5-2680 v4.
  • Model: Qwen3.8-Flash-Next IQ3_XXS, --vision, --kv int8, --spec 4, --prefill auto:32768, --max-context 262144, --pipeline-windows 2, no parallel (1 request at a time).
  • Not deterministic: it appears only after the server has been running and serving requests for a while.

Observed

  • The stuck request sits at phase reading with generated: 0, while the engine log already shows the request finished (e.g. prompt 56959 tokens ... 490 generated ... drafts accepted 366 of 369). The server never reads the end of the request.
  • strata.exe CPU time is frozen (e.g. pinned at 308.4375 s across repeated samples) -- it is idle waiting for a command, not spinning. Because of that the engine-side #29 watchdog (which only counts while a request is running) never fires.
  • /status shows busy:false, queued:N while the UI still reports a running/queued request.

Root cause

This is the #481 "lost step" class, with a concrete trigger: the server has blocking reads of the engine/vision pipes that have no timeout. If one of them never returns (the vision encoder's READY/ENC read, or the engine's READY read), the request turn is held forever. By then the engine has already finished (or never saw the request), so no engine-side watchdog can fire and the request never ends; later requests queue behind it.

Upstream's engine_silence_s (v0.1.37, #481) covers a running request that goes silent, but it is armed only after the request has been sent to the engine -- it does not cover a blocking read that never returns before the request is armed.

Fix (patch below)

Time out every blocking read and add a watchdog that can end a genuinely silent engine:

  • VISION_READY_S=300, VISION_ENCODE_S=300 -- the vision-encoder reads go through Vision._readline(timeout, what) (a pump thread + queue); on timeout the encoder is killed and the request fails cleanly instead of hanging.
  • ENGINE_READY_S=900 -- the engine READY read goes through a _ready_pump thread + queue.get(timeout=...).
  • ENGINE_STALL_S (default 90 s, override with STRATA_ENGINE_STALL_S; 0 disables) -- while a request is active, if the engine prints nothing and its CPU time has not advanced, the engine is ended so the next request restarts it.
  • FIFO_WARN_S=600 -- a one-shot diagnostic line if a request holds the turn that long.
  • A small TurnLock wrapper that records how long the turn has been held.

All of these are server-side only; no engine rebuild is needed.

Evidence

  • Reproduced live: strata.exe CPU frozen at 308.4375 s, /status state="reading", elapsed_s=462.8, in_flight=2, while the engine log showed the request already completed.
  • After the patch: serve/test_server.py (204 tests) plus the companion tests pass; a 9-request stress run (image/vision + a 35k-token prompt + back-to-back + concurrent) and a ~10 min soak (three.js generation, 6 rounds) all completed with no hang.

Relation to existing issues

  • #481 (open) -- same lost-step class (this report adds a concrete, reproducible trigger: an untimed blocking read holding the request turn).
  • #1012 (closed, fixed in 0.1.40.1) -- the restart-waiters variant.

Patch

strata-hang-fix.patch (15 hunks, +230 / -16) -- apply to serve/server.py.

diff --git a/serve/server.py b/serve/server.py
index d6b1fc3..935f191 100644
--- a/serve/server.py
+++ b/serve/server.py
@@ -211,6 +211,27 @@ SESSION_WAIT_MAX_S = 3600
 PP_CHUNK_MAX = 32768
 PP_FLOOR_TOK_S = 50.0
 PP_SLACK = 3.0
+# The image encoder's own backstop: a read from it with no timeout held the request FIFO for good when it
+# stopped answering - the engine then sat idle in its command loop, no watchdog could fire, and the request
+# never ended (the "lost step" class of #481).  Generous on purpose: a cold model load or a slow CPU encode
+# is not a hang, and the encoder is ended (the next request starts it again) only when it says nothing at all.
+VISION_READY_S = 300.0
+VISION_ENCODE_S = 300.0
+# The engine's own READY read has no timeout either (an engine that starts but never reports READY, or a
+# start that hangs in the loader, held the request FIFO for good).  Same treatment, longer: loading 47 GB of
+# experts on a slow disk takes minutes.
+ENGINE_READY_S = 900.0
+# A request may hold the FIFO for as long as its work takes, but a holder that stays silent this long is
+# reported once to the server window - a diagnostic, never a kill (a vision read or a load that hangs is
+# exactly what the two watchdogs above cannot see).
+FIFO_WARN_S = 600.0
+# The engine's own #29 watchdog covers a request whose heartbeat stops while it is busy, but a frozen host
+# thread (a deadlock inside a CUDA call, a driver stall) never reaches it: the engine burns CPU once, then its
+# CPU time stops and it sits there for good while the server waits.  Seen on 2026-10-07 - the engine's CPU time
+# stopped at 308.4 s and never moved again, GPU 0 %, /health still said loaded, and neither watchdog fired.
+# So watch the engine's own CPU time while a request is outstanding: it must advance, or the engine is frozen
+# and is ended (the next request starts it again).  STRATA_ENGINE_STALL_S sets it (0: off).
+ENGINE_STALL_S = float(os.environ.get("STRATA_ENGINE_STALL_S") or 90.0)
 
 
 # ------------------------------------------------------------------------------------------------ engines
@@ -608,7 +629,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:
+        ready_q: queue.Queue = queue.Queue()
+        threading.Thread(target=self._ready_pump, args=(self.proc, ready_q), daemon=True).start()
+        deadline = time.monotonic() + ENGINE_READY_S
+        timed_out = False
+        while True:
+            left = deadline - time.monotonic()
+            if left <= 0:
+                timed_out = True
+                loading.set()
+                break
+            try:
+                line = ready_q.get(timeout=left)
+            except queue.Empty:
+                continue
+            if line is None:
+                loading.set()
+                break
             if line.startswith("INFO "):
                 for kv in line.split()[1:]:
                     k, _, v = kv.partition("=")
@@ -618,9 +655,14 @@ class StrataEngine:
                 self.max_context = int(f[1])
                 self.can_stop = "stop" in f[2:]
                 break
-        loading.set()
+        loading.set()                                   # READY (or a dead engine): the narrator stops (#481 patch regression)
         if self.max_context <= 0:
-            try:                                        # its pipes and our handle on its log (the log stays)
+            if self.proc.poll() is None:
+                try:
+                    self.proc.terminate()
+                except OSError:
+                    pass
+            try:
                 self.proc.wait(timeout=5)
                 self.proc.stdin.close()
                 self.proc.stdout.close()
@@ -628,7 +670,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
@@ -668,6 +712,9 @@ class StrataEngine:
             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 time
         self.gen = self.__dict__.get("gen", 0) + 1      # which engine process this is (a request notes its own)
+        self.gen_active = False                         # a request is being generated (the stall watchdog reads it)
+        self.last_line_at = time.monotonic()            # when the engine last printed a line (the stall watchdog)
+        self._cpu_last, self._cpu_moved_at = None, 0.0  # its CPU time, and when it last moved (the stall watchdog)
         self._yielded = None                            # (slot, tokens read): the last request on them gave way
         self.wlock = threading.Lock()                   # stdin writes from several request threads
         self.pump = threading.Thread(target=self._pump, daemon=True)
@@ -697,6 +744,8 @@ class StrataEngine:
                 except (IndexError, ValueError):
                     pass
             lines.put(line)
+            if self.proc is proc:
+                self.last_line_at = time.monotonic()     # the stall watchdog: the engine is still saying something
         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
             if line and line.startswith("ERR"):         # #997 #890: why it exited, though no request may read it
@@ -705,6 +754,68 @@ class StrataEngine:
         for q in slot_q:
             q.put(None)
 
+    def _cpu_seconds(self) -> float | None:
+        """The engine process's own CPU time (all threads), or None when psutil is not there.  A frozen engine's
+        CPU time stops advancing, which is the one liveness signal neither watchdog uses."""
+        proc = self.proc
+        if proc is None or proc.poll() is not None:
+            return None
+        try:
+            import psutil
+        except Exception:  # noqa: BLE001 - psutil is optional
+            return None
+        try:
+            t = psutil.Process(proc.pid).cpu_times()
+            return float(t.user + t.system)
+        except Exception:  # noqa: BLE001 - the process went away
+            return None
+
+    def _cpu_moved(self, cpu: float | None) -> None:
+        """Remember the engine's CPU time for the stall watchdog: when it last moved, and from what."""
+        if cpu is None:
+            self._cpu_last, self._cpu_moved_at = None, 0.0
+            return
+        if self._cpu_last is None or cpu > self._cpu_last + 1e-9:
+            self._cpu_last, self._cpu_moved_at = cpu, time.monotonic()
+
+    def _cpu_flat_for(self, cpu: float | None) -> float:
+        """How long the engine's CPU time has stood still (0 when it just moved, or was never seen)."""
+        if cpu is None or self._cpu_last is None or not self._cpu_moved_at:
+            return 0.0
+        return time.monotonic() - self._cpu_moved_at
+
+    def _frozen(self, what: str) -> EngineSilent:
+        """End an engine whose CPU time stopped advancing while a request was outstanding: it is deadlocked inside
+        a call (not slow - a slow step still burns CPU), so nothing will ever come out of it.  Killing it lets the
+        next request start a fresh one instead of the turn being held forever."""
+        self.silent_note = (f"The engine froze: {what}. Its CPU time stopped advancing while the request was "
+                            "outstanding (GPU idle, /health still loaded). The server ended it; the next request "
+                            "starts a new one. If it happens again, please add the engine log to "
+                            "github.com/Niko1221/Strata/issues.")
+        self.ended = True
+        proc = self.proc
+        try:
+            proc.kill()
+            proc.wait(timeout=20)
+        except (OSError, AttributeError, subprocess.TimeoutExpired):
+            pass
+        return EngineSilent(f"{what}; the server ended the frozen engine")
+
+    def _ready_pump(self, proc, out: queue.Queue) -> None:
+        """The engine's first lines, for the READY read: the same shape as _pump, so __init__ can wait with a
+        timeout instead of blocking forever on an engine that starts but never reports READY.  It stops at READY,
+        so the lines after it stay in the same stream for _pump (one reader at a time)."""
+        done = False
+        try:
+            for line in proc.stdout:
+                out.put(line)
+                if line.startswith("READY"):
+                    done = True
+                    return
+        finally:
+            if not done:
+                out.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."""
         if getattr(self, "silent_note", None):          # #481: the server ended it, not the OS or the engine itself
@@ -1326,9 +1437,16 @@ class StrataEngine:
         has gone.  A consumer that stops early (or `cancel`) makes the engine STOP, so it does not run to max_new."""
         if not self.alive():
             raise EngineDied("the engine is unavailable; this request was not sent")
-        if getattr(self, "batch", 0):
-            yield from self.generate_batched(ids, max_new, sampling, cancel, embeddings)
-            return
+        self.gen_active = True
+        try:
+            if getattr(self, "batch", 0):
+                yield from self.generate_batched(ids, max_new, sampling, cancel, embeddings)
+                return
+            yield from self._generate_solo(ids, max_new, sampling, cancel, embeddings)
+        finally:
+            self.gen_active = False
+
+    def _generate_solo(self, ids, max_new, sampling, cancel, embeddings=None):
         self.progress, self.progress_ms, self.reused = None, 0, 0
         self.prefill_tok_s_mean = None
         # an image request takes the same sampling keys as text (#75: it used to decode greedily whatever was asked)
@@ -1629,6 +1747,7 @@ class Vision:
         self.dir = self.work_dir()
         self.spawn = (args, log, env)                   # to start it again after an unload
         self.stopped = False
+        self.lines: queue.Queue = queue.Queue()         # its stdout, read on a thread: every read has a timeout
         self._start()
         self.lock = threading.Lock()
         self.cache: dict[str, tuple[Path, int]] = {}
@@ -1640,11 +1759,37 @@ 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()
+        self.lines = queue.Queue()
+        threading.Thread(target=self._pump, args=(self.proc, self.lines), daemon=True).start()
+        line = self._readline(VISION_READY_S, "the image encoder did not start")
         if not line.startswith("READY"):
             raise RuntimeError("the vision encoder did not start: " + line.strip())
         self.stopped = False
 
+    def _pump(self, proc, lines):
+        for line in proc.stdout:
+            lines.put(line)
+        lines.put(None)
+
+    def _readline(self, timeout: float, what: str) -> str:
+        """One line of the encoder's answer, at most `timeout` s: a read that never returns held the request FIFO
+        for good (the engine then waited for a command nobody sent, and no watchdog covers that - #481).  On a
+        timeout the encoder is ended, so the next request starts a fresh one."""
+        try:
+            line = self.lines.get(timeout=timeout)
+        except queue.Empty:
+            self._kill()
+            raise RuntimeError(f"{what}: it said nothing for {timeout:.0f} s") from None
+        if line is None:
+            raise RuntimeError(f"{what}: the vision encoder stopped")
+        return line
+
+    def _kill(self):
+        try:
+            self.proc.kill()
+        except OSError:
+            pass
+
     def alive(self) -> bool:
         return not self.stopped and self.proc.poll() is None
 
@@ -1655,10 +1800,7 @@ class Vision:
 
     def restart(self):
         """Start the encoder again after an unload (or if it died); the cache of encoded images is kept."""
-        try:
-            self.proc.kill()
-        except OSError:
-            pass
+        self._kill()
         self._start()
 
     @staticmethod
@@ -1739,9 +1881,15 @@ class Vision:
             img, out = self.dir / f"{key}.img", self.dir / f"{key}.sve"
             img.write_bytes(data)
             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:
+                    self.proc.stdin.write(f"ENC {img.name} {out.name}\n")  # relative to the encoder's cwd (#480)
+                    self.proc.stdin.flush()
+                    line = self._readline(VISION_ENCODE_S, "the image could not be read").strip()
+                except OSError:
+                    self._kill()                                   # the pipe is gone: drop the encoder so the next request restarts it
+                    raise                                           # keep the original type (upstream #352 test expects BrokenPipeError)
+                except RuntimeError as e:
+                    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"):
@@ -2141,6 +2289,53 @@ def slot_save_dir(value, base: str | None = None) -> str:
         raise ValueError(f"slot_save_path {path} is not a directory")
     return path
 
+
+class TurnLock:
+    """The request turn: one request at a time, and how long the current holder has had it.  A holder stuck before
+    the engine ever saw the request is the one class of hang neither watchdog sees (the engine's #29 watchdog runs
+    only while busy; the #481 silence timer is armed only after GEN is written), so the holder is reported once
+    when it passes FIFO_WARN_S - a diagnostic, never a kill."""
+
+    def __init__(self):
+        self._lock = threading.Lock()
+        self._mu = threading.Lock()
+        self._holder = None
+        self._since = 0.0
+        self._warned = False
+
+    def acquire(self, blocking: bool = True, timeout: float = -1) -> bool:
+        ok = self._lock.acquire(blocking) if timeout is None or timeout < 0 else self._lock.acquire(blocking, timeout)
+        if ok:
+            with self._mu:
+                self._holder = threading.get_ident()
+                self._since = time.monotonic()
+                self._warned = False
+        return ok
+
+    def release(self) -> None:
+        with self._mu:
+            self._holder = None
+        self._lock.release()
+
+    def held_for(self) -> float:
+        with self._mu:
+            return time.monotonic() - self._since if self._holder is not None else 0.0
+
+    def warn_once(self) -> bool:
+        with self._mu:
+            if self._holder is None or self._warned:
+                return False
+            self._warned = True
+            return True
+
+    def __enter__(self) -> "TurnLock":
+        self.acquire()
+        return self
+
+    def __exit__(self, *exc) -> None:
+        self.release()
+
+
 class Service:
     def __init__(self, engine: Engine, tokenizer, template: ChatTemplate, model_name: str = "qwen3.8-flash-next",
                  vision: Vision | None = None, sampling_defaults: dict | None = None,
@@ -2152,7 +2347,7 @@ class Service:
         self.sampling_defaults = dict(sampling_defaults or {})   # the run config's `sampling` block
         self.shared = {}                              # the web app's Chat settings for every client (POST /settings)
         self.shared_path = None                       # where they are kept between starts (next to the config)
-        self.fifo = threading.Lock()
+        self.fifo = TurnLock()
         self.slot_save_path = None                    # --slot-save-path: /slots/0?action=save|restore (off when None)
         self.embeddings = threading.local()           # the current request's image embeddings file (GENI)
         self.api_key = ""                              # when set, /v1/* needs it (Bearer or x-api-key)
@@ -2205,6 +2400,46 @@ class Service:
         self.anthropic_think_unasked = True               # #278: "anthropic_thinking": "on_request" -> False
         self.stop_ids = set(tokenizer.encode(IM_END, parse_special=True) +
                             tokenizer.encode("<|endoftext|>", parse_special=True))
+        threading.Thread(target=self._turn_watch, daemon=True).start()
+        threading.Thread(target=self._stall_watch, daemon=True).start()
+
+    def _turn_watch(self):
+        """Every 5 s, report once when a request has held the turn past FIFO_WARN_S.  Never a kill: a slow request is
+        not a hang, and this is only the line that says where to look when one is."""
+        while True:
+            time.sleep(5.0)
+            if self.fifo.held_for() >= FIFO_WARN_S and self.fifo.warn_once():
+                log = getattr(self.engine, "log_path", None)
+                print(f"[strata] a request has held the turn for over {FIFO_WARN_S:.0f} s; the engine may not have "
+                      f"seen it yet - if it hangs, see #481. Its log: {log or '(none)'}", flush=True)
+
+    def _stall_watch(self):
+        """Every 5 s while a request is being generated, end an engine that has gone completely quiet: no line on
+        its stdout AND no advance in its own CPU time.  A slow step still prints (a PP per chunk, a T per token) and
+        still burns CPU; a frozen process does neither, and the engine's #29 watchdog cannot help because a
+        process-wide freeze stops its thread too.  Either signal alone is not enough: a healthy decode on a hot
+        expert cache can hold its CPU time flat for a long time while the GPU works and the tokens still come."""
+        limit = ENGINE_STALL_S
+        if limit <= 0:
+            return
+        while True:
+            time.sleep(5.0)
+            engine = self.engine
+            if not (bool(getattr(engine, "gen_active", False)) and engine.alive()):
+                continue
+            if not hasattr(engine, "_cpu_seconds"):
+                continue
+            cpu = engine._cpu_seconds()
+            quiet_for = time.monotonic() - getattr(engine, "last_line_at", time.monotonic())
+            if cpu is None or quiet_for < limit:
+                engine._cpu_moved(cpu)
+                continue
+            if engine._cpu_flat_for(cpu) >= limit and not engine.ended:
+                print(f"[strata] the engine has been silent for {quiet_for:.0f} s and its CPU time has not advanced "
+                      f"for {limit:.0f} s while a request is running (frozen, not slow); ending it - the next "
+                      f"request starts a new one", flush=True)
+                engine._frozen(f"no line and no CPU progress for {limit:.0f} s")
+            engine._cpu_moved(cpu)
 
     def loaded(self) -> bool:
         return not hasattr(self.engine, "alive") or self.engine.alive()

Originally created by @btc1000w on GitHub (Oct 7, 2026). Original GitHub issue: https://github.com/Niko1221/Strata/issues/1317 ## Summary On **v0.1.40.1** (engine 0.1.40), running **Qwen3.8-Flash-Next IQ3_XXS**, the server intermittently hangs after it has been serving requests for a while: the current request stops progressing (the panel shows *"waiting for token generation"*) and every later request stays *"queued"* forever. The **engine is not stuck** -- it is idle in its command loop; the server simply never finishes the request, so it never releases the single request turn. ## Environment - Strata source 0.1.40.1 (engine 0.1.40), Windows, 2x RTX (3080 Laptop + 3070 Laptop, 16 GiB each), Xeon E5-2680 v4. - Model: Qwen3.8-Flash-Next IQ3_XXS, `--vision`, `--kv int8`, `--spec 4`, `--prefill auto:32768`, `--max-context 262144`, `--pipeline-windows 2`, no `parallel` (1 request at a time). - Not deterministic: it appears only after the server has been running and serving requests for a while. ## Observed - The stuck request sits at phase `reading` with `generated: 0`, while the engine log already shows the request finished (e.g. `prompt 56959 tokens ... 490 generated ... drafts accepted 366 of 369`). The server never reads the end of the request. - `strata.exe` CPU time is frozen (e.g. pinned at `308.4375 s` across repeated samples) -- it is **idle waiting for a command**, not spinning. Because of that the engine-side #29 watchdog (which only counts while a request is running) never fires. - `/status` shows `busy:false, queued:N` while the UI still reports a running/queued request. ## Root cause This is the **#481 "lost step"** class, with a concrete trigger: the server has **blocking reads of the engine/vision pipes that have no timeout**. If one of them never returns (the vision encoder's `READY`/`ENC` read, or the engine's `READY` read), the request turn is held forever. By then the engine has already finished (or never saw the request), so no engine-side watchdog can fire and the request never ends; later requests queue behind it. Upstream's `engine_silence_s` (v0.1.37, #481) covers a *running* request that goes silent, but it is armed only after the request has been sent to the engine -- it does not cover a blocking read that never returns before the request is armed. ## Fix (patch below) Time out every blocking read and add a watchdog that can end a genuinely silent engine: - `VISION_READY_S=300`, `VISION_ENCODE_S=300` -- the vision-encoder reads go through `Vision._readline(timeout, what)` (a pump thread + queue); on timeout the encoder is killed and the request fails cleanly instead of hanging. - `ENGINE_READY_S=900` -- the engine `READY` read goes through a `_ready_pump` thread + `queue.get(timeout=...)`. - `ENGINE_STALL_S` (default 90 s, override with `STRATA_ENGINE_STALL_S`; 0 disables) -- while a request is active, if the engine prints nothing **and** its CPU time has not advanced, the engine is ended so the next request restarts it. - `FIFO_WARN_S=600` -- a one-shot diagnostic line if a request holds the turn that long. - A small `TurnLock` wrapper that records how long the turn has been held. All of these are server-side only; no engine rebuild is needed. ## Evidence - Reproduced live: `strata.exe` CPU frozen at `308.4375 s`, `/status` `state="reading"`, `elapsed_s=462.8`, `in_flight=2`, while the engine log showed the request already completed. - After the patch: `serve/test_server.py` (204 tests) plus the companion tests pass; a 9-request stress run (image/vision + a 35k-token prompt + back-to-back + concurrent) and a ~10 min soak (three.js generation, 6 rounds) all completed with no hang. ## Relation to existing issues - **#481** (open) -- same lost-step class (this report adds a concrete, reproducible trigger: an untimed blocking read holding the request turn). - **#1012** (closed, fixed in 0.1.40.1) -- the restart-waiters variant. ## Patch `strata-hang-fix.patch` (15 hunks, +230 / -16) -- apply to `serve/server.py`. <!--PATCH--> ```diff diff --git a/serve/server.py b/serve/server.py index d6b1fc3..935f191 100644 --- a/serve/server.py +++ b/serve/server.py @@ -211,6 +211,27 @@ SESSION_WAIT_MAX_S = 3600 PP_CHUNK_MAX = 32768 PP_FLOOR_TOK_S = 50.0 PP_SLACK = 3.0 +# The image encoder's own backstop: a read from it with no timeout held the request FIFO for good when it +# stopped answering - the engine then sat idle in its command loop, no watchdog could fire, and the request +# never ended (the "lost step" class of #481). Generous on purpose: a cold model load or a slow CPU encode +# is not a hang, and the encoder is ended (the next request starts it again) only when it says nothing at all. +VISION_READY_S = 300.0 +VISION_ENCODE_S = 300.0 +# The engine's own READY read has no timeout either (an engine that starts but never reports READY, or a +# start that hangs in the loader, held the request FIFO for good). Same treatment, longer: loading 47 GB of +# experts on a slow disk takes minutes. +ENGINE_READY_S = 900.0 +# A request may hold the FIFO for as long as its work takes, but a holder that stays silent this long is +# reported once to the server window - a diagnostic, never a kill (a vision read or a load that hangs is +# exactly what the two watchdogs above cannot see). +FIFO_WARN_S = 600.0 +# The engine's own #29 watchdog covers a request whose heartbeat stops while it is busy, but a frozen host +# thread (a deadlock inside a CUDA call, a driver stall) never reaches it: the engine burns CPU once, then its +# CPU time stops and it sits there for good while the server waits. Seen on 2026-10-07 - the engine's CPU time +# stopped at 308.4 s and never moved again, GPU 0 %, /health still said loaded, and neither watchdog fired. +# So watch the engine's own CPU time while a request is outstanding: it must advance, or the engine is frozen +# and is ended (the next request starts it again). STRATA_ENGINE_STALL_S sets it (0: off). +ENGINE_STALL_S = float(os.environ.get("STRATA_ENGINE_STALL_S") or 90.0) # ------------------------------------------------------------------------------------------------ engines @@ -608,7 +629,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: + ready_q: queue.Queue = queue.Queue() + threading.Thread(target=self._ready_pump, args=(self.proc, ready_q), daemon=True).start() + deadline = time.monotonic() + ENGINE_READY_S + timed_out = False + while True: + left = deadline - time.monotonic() + if left <= 0: + timed_out = True + loading.set() + break + try: + line = ready_q.get(timeout=left) + except queue.Empty: + continue + if line is None: + loading.set() + break if line.startswith("INFO "): for kv in line.split()[1:]: k, _, v = kv.partition("=") @@ -618,9 +655,14 @@ class StrataEngine: self.max_context = int(f[1]) self.can_stop = "stop" in f[2:] break - loading.set() + loading.set() # READY (or a dead engine): the narrator stops (#481 patch regression) if self.max_context <= 0: - try: # its pipes and our handle on its log (the log stays) + if self.proc.poll() is None: + try: + self.proc.terminate() + except OSError: + pass + try: self.proc.wait(timeout=5) self.proc.stdin.close() self.proc.stdout.close() @@ -628,7 +670,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 @@ -668,6 +712,9 @@ class StrataEngine: 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 time self.gen = self.__dict__.get("gen", 0) + 1 # which engine process this is (a request notes its own) + self.gen_active = False # a request is being generated (the stall watchdog reads it) + self.last_line_at = time.monotonic() # when the engine last printed a line (the stall watchdog) + self._cpu_last, self._cpu_moved_at = None, 0.0 # its CPU time, and when it last moved (the stall watchdog) self._yielded = None # (slot, tokens read): the last request on them gave way self.wlock = threading.Lock() # stdin writes from several request threads self.pump = threading.Thread(target=self._pump, daemon=True) @@ -697,6 +744,8 @@ class StrataEngine: except (IndexError, ValueError): pass lines.put(line) + if self.proc is proc: + self.last_line_at = time.monotonic() # the stall watchdog: the engine is still saying something 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 if line and line.startswith("ERR"): # #997 #890: why it exited, though no request may read it @@ -705,6 +754,68 @@ class StrataEngine: for q in slot_q: q.put(None) + def _cpu_seconds(self) -> float | None: + """The engine process's own CPU time (all threads), or None when psutil is not there. A frozen engine's + CPU time stops advancing, which is the one liveness signal neither watchdog uses.""" + proc = self.proc + if proc is None or proc.poll() is not None: + return None + try: + import psutil + except Exception: # noqa: BLE001 - psutil is optional + return None + try: + t = psutil.Process(proc.pid).cpu_times() + return float(t.user + t.system) + except Exception: # noqa: BLE001 - the process went away + return None + + def _cpu_moved(self, cpu: float | None) -> None: + """Remember the engine's CPU time for the stall watchdog: when it last moved, and from what.""" + if cpu is None: + self._cpu_last, self._cpu_moved_at = None, 0.0 + return + if self._cpu_last is None or cpu > self._cpu_last + 1e-9: + self._cpu_last, self._cpu_moved_at = cpu, time.monotonic() + + def _cpu_flat_for(self, cpu: float | None) -> float: + """How long the engine's CPU time has stood still (0 when it just moved, or was never seen).""" + if cpu is None or self._cpu_last is None or not self._cpu_moved_at: + return 0.0 + return time.monotonic() - self._cpu_moved_at + + def _frozen(self, what: str) -> EngineSilent: + """End an engine whose CPU time stopped advancing while a request was outstanding: it is deadlocked inside + a call (not slow - a slow step still burns CPU), so nothing will ever come out of it. Killing it lets the + next request start a fresh one instead of the turn being held forever.""" + self.silent_note = (f"The engine froze: {what}. Its CPU time stopped advancing while the request was " + "outstanding (GPU idle, /health still loaded). The server ended it; the next request " + "starts a new one. If it happens again, please add the engine log to " + "github.com/Niko1221/Strata/issues.") + self.ended = True + proc = self.proc + try: + proc.kill() + proc.wait(timeout=20) + except (OSError, AttributeError, subprocess.TimeoutExpired): + pass + return EngineSilent(f"{what}; the server ended the frozen engine") + + def _ready_pump(self, proc, out: queue.Queue) -> None: + """The engine's first lines, for the READY read: the same shape as _pump, so __init__ can wait with a + timeout instead of blocking forever on an engine that starts but never reports READY. It stops at READY, + so the lines after it stay in the same stream for _pump (one reader at a time).""" + done = False + try: + for line in proc.stdout: + out.put(line) + if line.startswith("READY"): + done = True + return + finally: + if not done: + out.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.""" if getattr(self, "silent_note", None): # #481: the server ended it, not the OS or the engine itself @@ -1326,9 +1437,16 @@ class StrataEngine: has gone. A consumer that stops early (or `cancel`) makes the engine STOP, so it does not run to max_new.""" if not self.alive(): raise EngineDied("the engine is unavailable; this request was not sent") - if getattr(self, "batch", 0): - yield from self.generate_batched(ids, max_new, sampling, cancel, embeddings) - return + self.gen_active = True + try: + if getattr(self, "batch", 0): + yield from self.generate_batched(ids, max_new, sampling, cancel, embeddings) + return + yield from self._generate_solo(ids, max_new, sampling, cancel, embeddings) + finally: + self.gen_active = False + + def _generate_solo(self, ids, max_new, sampling, cancel, embeddings=None): self.progress, self.progress_ms, self.reused = None, 0, 0 self.prefill_tok_s_mean = None # an image request takes the same sampling keys as text (#75: it used to decode greedily whatever was asked) @@ -1629,6 +1747,7 @@ class Vision: self.dir = self.work_dir() self.spawn = (args, log, env) # to start it again after an unload self.stopped = False + self.lines: queue.Queue = queue.Queue() # its stdout, read on a thread: every read has a timeout self._start() self.lock = threading.Lock() self.cache: dict[str, tuple[Path, int]] = {} @@ -1640,11 +1759,37 @@ 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() + self.lines = queue.Queue() + threading.Thread(target=self._pump, args=(self.proc, self.lines), daemon=True).start() + line = self._readline(VISION_READY_S, "the image encoder did not start") if not line.startswith("READY"): raise RuntimeError("the vision encoder did not start: " + line.strip()) self.stopped = False + def _pump(self, proc, lines): + for line in proc.stdout: + lines.put(line) + lines.put(None) + + def _readline(self, timeout: float, what: str) -> str: + """One line of the encoder's answer, at most `timeout` s: a read that never returns held the request FIFO + for good (the engine then waited for a command nobody sent, and no watchdog covers that - #481). On a + timeout the encoder is ended, so the next request starts a fresh one.""" + try: + line = self.lines.get(timeout=timeout) + except queue.Empty: + self._kill() + raise RuntimeError(f"{what}: it said nothing for {timeout:.0f} s") from None + if line is None: + raise RuntimeError(f"{what}: the vision encoder stopped") + return line + + def _kill(self): + try: + self.proc.kill() + except OSError: + pass + def alive(self) -> bool: return not self.stopped and self.proc.poll() is None @@ -1655,10 +1800,7 @@ class Vision: def restart(self): """Start the encoder again after an unload (or if it died); the cache of encoded images is kept.""" - try: - self.proc.kill() - except OSError: - pass + self._kill() self._start() @staticmethod @@ -1739,9 +1881,15 @@ class Vision: img, out = self.dir / f"{key}.img", self.dir / f"{key}.sve" img.write_bytes(data) 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: + self.proc.stdin.write(f"ENC {img.name} {out.name}\n") # relative to the encoder's cwd (#480) + self.proc.stdin.flush() + line = self._readline(VISION_ENCODE_S, "the image could not be read").strip() + except OSError: + self._kill() # the pipe is gone: drop the encoder so the next request restarts it + raise # keep the original type (upstream #352 test expects BrokenPipeError) + except RuntimeError as e: + 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"): @@ -2141,6 +2289,53 @@ def slot_save_dir(value, base: str | None = None) -> str: raise ValueError(f"slot_save_path {path} is not a directory") return path + +class TurnLock: + """The request turn: one request at a time, and how long the current holder has had it. A holder stuck before + the engine ever saw the request is the one class of hang neither watchdog sees (the engine's #29 watchdog runs + only while busy; the #481 silence timer is armed only after GEN is written), so the holder is reported once + when it passes FIFO_WARN_S - a diagnostic, never a kill.""" + + def __init__(self): + self._lock = threading.Lock() + self._mu = threading.Lock() + self._holder = None + self._since = 0.0 + self._warned = False + + def acquire(self, blocking: bool = True, timeout: float = -1) -> bool: + ok = self._lock.acquire(blocking) if timeout is None or timeout < 0 else self._lock.acquire(blocking, timeout) + if ok: + with self._mu: + self._holder = threading.get_ident() + self._since = time.monotonic() + self._warned = False + return ok + + def release(self) -> None: + with self._mu: + self._holder = None + self._lock.release() + + def held_for(self) -> float: + with self._mu: + return time.monotonic() - self._since if self._holder is not None else 0.0 + + def warn_once(self) -> bool: + with self._mu: + if self._holder is None or self._warned: + return False + self._warned = True + return True + + def __enter__(self) -> "TurnLock": + self.acquire() + return self + + def __exit__(self, *exc) -> None: + self.release() + + class Service: def __init__(self, engine: Engine, tokenizer, template: ChatTemplate, model_name: str = "qwen3.8-flash-next", vision: Vision | None = None, sampling_defaults: dict | None = None, @@ -2152,7 +2347,7 @@ class Service: self.sampling_defaults = dict(sampling_defaults or {}) # the run config's `sampling` block self.shared = {} # the web app's Chat settings for every client (POST /settings) self.shared_path = None # where they are kept between starts (next to the config) - self.fifo = threading.Lock() + self.fifo = TurnLock() self.slot_save_path = None # --slot-save-path: /slots/0?action=save|restore (off when None) self.embeddings = threading.local() # the current request's image embeddings file (GENI) self.api_key = "" # when set, /v1/* needs it (Bearer or x-api-key) @@ -2205,6 +2400,46 @@ class Service: self.anthropic_think_unasked = True # #278: "anthropic_thinking": "on_request" -> False self.stop_ids = set(tokenizer.encode(IM_END, parse_special=True) + tokenizer.encode("<|endoftext|>", parse_special=True)) + threading.Thread(target=self._turn_watch, daemon=True).start() + threading.Thread(target=self._stall_watch, daemon=True).start() + + def _turn_watch(self): + """Every 5 s, report once when a request has held the turn past FIFO_WARN_S. Never a kill: a slow request is + not a hang, and this is only the line that says where to look when one is.""" + while True: + time.sleep(5.0) + if self.fifo.held_for() >= FIFO_WARN_S and self.fifo.warn_once(): + log = getattr(self.engine, "log_path", None) + print(f"[strata] a request has held the turn for over {FIFO_WARN_S:.0f} s; the engine may not have " + f"seen it yet - if it hangs, see #481. Its log: {log or '(none)'}", flush=True) + + def _stall_watch(self): + """Every 5 s while a request is being generated, end an engine that has gone completely quiet: no line on + its stdout AND no advance in its own CPU time. A slow step still prints (a PP per chunk, a T per token) and + still burns CPU; a frozen process does neither, and the engine's #29 watchdog cannot help because a + process-wide freeze stops its thread too. Either signal alone is not enough: a healthy decode on a hot + expert cache can hold its CPU time flat for a long time while the GPU works and the tokens still come.""" + limit = ENGINE_STALL_S + if limit <= 0: + return + while True: + time.sleep(5.0) + engine = self.engine + if not (bool(getattr(engine, "gen_active", False)) and engine.alive()): + continue + if not hasattr(engine, "_cpu_seconds"): + continue + cpu = engine._cpu_seconds() + quiet_for = time.monotonic() - getattr(engine, "last_line_at", time.monotonic()) + if cpu is None or quiet_for < limit: + engine._cpu_moved(cpu) + continue + if engine._cpu_flat_for(cpu) >= limit and not engine.ended: + print(f"[strata] the engine has been silent for {quiet_for:.0f} s and its CPU time has not advanced " + f"for {limit:.0f} s while a request is running (frozen, not slow); ending it - the next " + f"request starts a new one", flush=True) + engine._frozen(f"no line and no CPU progress for {limit:.0f} s") + engine._cpu_moved(cpu) def loaded(self) -> bool: return not hasattr(self.engine, "alive") or self.engine.alive() ```
Author
Owner

@Niko1221 commented on GitHub (Oct 7, 2026):

Thanks for the reproduction and the patch. 0.1.40.2 takes the read timeouts: the engine's READY read now gives up after 900 s, and the image encoder's READY and ENC reads after 300 s each (STRATA_ENGINE_READY_S, STRATA_VISION_READY_S and STRATA_VISION_ENCODE_S change them; 0 waits for ever). A process that says nothing for that long is killed, the request fails with a clear message and the next one starts it again, so those reads can no longer hold the turn forever. You are credited in the commit. The 90 s watchdog that ends an engine whose output and CPU time stand still is not in this release: a long model load or a slow disk needs a careful look first. This issue stays open for it (and for #481).

<!-- gh-comment-id:6038136532 --> @Niko1221 commented on GitHub (Oct 7, 2026): Thanks for the reproduction and the patch. 0.1.40.2 takes the read timeouts: the engine's READY read now gives up after 900 s, and the image encoder's READY and ENC reads after 300 s each (STRATA_ENGINE_READY_S, STRATA_VISION_READY_S and STRATA_VISION_ENCODE_S change them; 0 waits for ever). A process that says nothing for that long is killed, the request fails with a clear message and the next one starts it again, so those reads can no longer hold the turn forever. You are credited in the commit. The 90 s watchdog that ends an engine whose output and CPU time stand still is not in this release: a long model load or a slow disk needs a careful look first. This issue stays open for it (and for #481).
Author
Owner

@Niko1221 commented on GitHub (Oct 8, 2026):

Part 2 is in 0.1.41, server side. While a request is outstanding and the engine prints nothing for 90 s, the server samples the engine process: if it has used no CPU time and moved no disk bytes in that time and the GPU is not busy, it is frozen, the server ends it and the next request starts it again. An engine that is silent but still working is never ended by this; the server prints one note and leaves the decision to engine_silence_s. STRATA_ENGINE_STALL_S sets the time, 0 turns the check off (it needs psutil, which setup installs). Tested with mocks for the frozen, working, busy-GPU and no-reading cases; on an RTX 3060 it also ended a real engine that had stopped after its own #29 stall report.

<!-- gh-comment-id:6059637558 --> @Niko1221 commented on GitHub (Oct 8, 2026): Part 2 is in 0.1.41, server side. While a request is outstanding and the engine prints nothing for 90 s, the server samples the engine process: if it has used no CPU time and moved no disk bytes in that time and the GPU is not busy, it is frozen, the server ends it and the next request starts it again. An engine that is silent but still working is never ended by this; the server prints one note and leaves the decision to `engine_silence_s`. `STRATA_ENGINE_STALL_S` sets the time, `0` turns the check off (it needs `psutil`, which setup installs). Tested with mocks for the frozen, working, busy-GPU and no-reading cases; on an RTX 3060 it also ended a real engine that had stopped after its own #29 stall report.
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
Niko1221/Strata#539
No description provided.