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: #1317 part 2 quick watchdog for a frozen engine (90 s silent, no CPU or disk work; STRATA_ENGINE_STALL_S); #1344 several API keys (comma list or config list)

Niko1221d7932123e10d
diff --git a/serve/server.py b/serve/server.py
index d3b31c90a..1ec6179ea 100644
--- a/serve/server.py
+++ b/serve/server.py
@@ -230,6 +230,22 @@ def _timeout_env(name: str, default: float) -> float | None:
return None if v <= 0 else v
+# #1317 part 2: the quick watchdog for a FROZEN engine. engine_silence_s (above) is generous on purpose: a slow PC reads a
+# prompt chunk for minutes without a line. But an engine that prints nothing for ENGINE_STALL_S and also uses no CPU time and
+# moves no bytes of I/O in that time is not slow, it is idle or frozen (a deadlock in a CUDA call, a driver stall, a lost
+# step), and waiting longer cannot help: it is ended, and the next request starts it again. An engine that is silent but
+# still working is never ended by this, only reported once (the recommendation: engine_silence_s, or this variable).
+# STRATA_ENGINE_STALL_S overrides it (0 = off). Needs psutil (setup installs it); without it nothing is ended.
+ENGINE_STALL_S = _timeout_env("STRATA_ENGINE_STALL_S", 90.0)
+STALL_CPU_EPS_S = 0.5 # CPU seconds the engine may use in the whole stall window and still count as frozen
+STALL_IO_EPS_B = 1 << 20 # bytes read or written in that window
+
+
+def engine_frozen(base: tuple[float, int], now: tuple[float, int]) -> bool:
+ """#1317: True when two (cpu seconds, io bytes) samples of the engine show no work between them."""
+ return (now[0] - base[0]) <= STALL_CPU_EPS_S and (now[1] - base[1]) <= STALL_IO_EPS_B
+
+
VISION_READY_S = _timeout_env("STRATA_VISION_READY_S", 300.0)
VISION_ENCODE_S = _timeout_env("STRATA_VISION_ENCODE_S", 300.0)
ENGINE_READY_S = _timeout_env("STRATA_ENGINE_READY_S", 900.0)
@@ -1446,6 +1462,8 @@ class StrataEngine:
allow = silence + min(len(ids), PP_CHUNK_MAX) / PP_FLOOR_TOK_S if silence > 0 else 0.0
heard, read_to = time.monotonic(), 0
beat = heard
+ stall_s = ENGINE_STALL_S or 0.0
+ stall_state: dict = {}
try:
while True:
wait = 10.0
@@ -1460,6 +1478,12 @@ class StrataEngine:
except queue.Empty:
if cancel.is_set():
return
+ if stall_s > 0:
+ try:
+ self._stall_check(heard, stall_state, stall_s)
+ except EngineSilent:
+ done = True # as above: nothing is listening
+ raise
if allow > 0 and time.monotonic() - heard >= allow:
continue # enforce the expired deadline before another heartbeat
if time.monotonic() - beat >= 10.0:
@@ -1471,6 +1495,8 @@ class StrataEngine:
raise EngineDied(f"the engine stopped unexpectedly (exit code {self.exit_code()})")
heard = time.monotonic() # any line is output: T, PP, RESUME, INFO ...
beat = heard
+ if stall_state:
+ stall_state.clear()
if line.startswith("T "):
allow = silence
if cancel.is_set():
@@ -1530,6 +1556,39 @@ class StrataEngine:
if not self.can_stop:
heard = time.monotonic()
+ def _activity(self) -> tuple[float, int] | None:
+ """#1317: (CPU seconds, I/O bytes) the engine process has used so far, or None when they cannot be read."""
+ try:
+ import psutil
+ pr = psutil.Process(self.proc.pid)
+ t = pr.cpu_times()
+ io = pr.io_counters()
+ return (t.user + t.system, io.read_bytes + io.write_bytes)
+ except Exception: # noqa: BLE001 - psutil missing, the process gone, no permission: no reading
+ return None
+
+ def _stall_check(self, heard: float, state: dict, stall_s: float) -> None:
+ """#1317: called while the engine is silent. Takes a baseline soon after the last line, and at stall_s of silence
+ compares: no CPU and no I/O in all that time -> the engine is ended (EngineSilent); work going on -> one warning."""
+ age = time.monotonic() - heard
+ if state.get("base") is None:
+ state["base"] = self._activity()
+ return
+ if age < state.get("next", stall_s) or state["base"] is None:
+ return
+ now = self._activity()
+ if now is not None and engine_frozen(state["base"], now):
+ raise self._silent(f"the engine said nothing for {age:.0f} s and used no CPU or disk in that time (frozen; "
+ "STRATA_ENGINE_STALL_S sets this, 0 = off)")
+ if now is not None: # working: look again after another window from here, and say so once
+ state["base"], state["next"] = now, age + stall_s
+ if not state.get("warned"):
+ state["warned"] = True
+ print(f"[strata] the engine has said nothing for {age:.0f} s but is still working; it is not ended (the "
+ "limit is engine_silence_s). If it is stuck, \"engine_silence_s\" can be set lower.", flush=True)
+ else:
+ state["next"] = float("inf") # no reading (psutil missing): nothing to decide on
+
def _silent(self, what: str) -> EngineSilent:
"""#481: end an engine that lost step with the server (its main thread waits for a command the server never
sends), so the next request starts it again: killed now, its GPU and RAM go back with the process."""
@@ -5148,27 +5207,47 @@ def host_allowed(host, names, any_host=False) -> bool:
or _name_in(name, names))
-def api_key_of(value) -> str:
+def key_list(value) -> list[str]:
+ """#1344: the keys a server accepts. --api-key / STRATA_API_KEY / "api_key" take llama.cpp's form, several keys
+ separated by commas ("k1,k2"; spaces around each are dropped), or a list in the config ("api_key": ["k1", "k2"],
+ the way to give a key that contains a comma). A list is taken as it is."""
+ if value is None or value == "":
+ return []
+ if isinstance(value, (list, tuple)):
+ return [str(k) for k in value if str(k)]
+ return [k.strip() for k in str(value).split(",") if k.strip()]
+
+
+def api_key_of(value):
"""The key as a client can send it (#725). An HTTP header loses the spaces and line ends around its value, so a
key kept with them (a config file or an environment file with CRLF line ends, a quoted " key ") matched no
request: every client got 401 with the right key. A value that is only such characters raises ValueError, it
- never means "no key" (#213)."""
+ never means "no key" (#213). #1344: a config list of keys returns the list (each key stripped, none empty); a
+ string stays a string (its commas separate keys, see key_list)."""
+ if isinstance(value, (list, tuple)):
+ keys = [str(k).strip() for k in value]
+ if not keys or any(not k for k in keys):
+ raise ValueError("an API key was given but it is empty")
+ return keys
key = "" if value is None else str(value)
- if key and not key.strip():
+ if key and not key_list(key):
raise ValueError("an API key was given but it is empty")
return key.strip()
-def key_matches(given: str, key: str) -> bool:
+def key_matches(given: str, key) -> bool:
"""given: a header's value as http.server read it, each byte one character. A key with characters outside ASCII
arrives as UTF-8 from most clients and as Latin-1 from some; the right key passes in both forms (#725: the
- bytes were re-encoded before, so a UTF-8 key never matched). Constant-time (#213)."""
+ bytes were re-encoded before, so a UTF-8 key never matched). Constant-time (#213). #1344: `key` may name several
+ keys (see key_list); the given one must match any, and every key is compared whatever the outcome."""
raw = given.encode("latin-1", "replace")
- ok = hmac.compare_digest(raw, key.encode())
- try:
- ok |= hmac.compare_digest(raw, key.encode("latin-1"))
- except UnicodeEncodeError:
- pass
+ ok = False
+ for k in key_list(key):
+ ok |= hmac.compare_digest(raw, k.encode())
+ try:
+ ok |= hmac.compare_digest(raw, k.encode("latin-1"))
+ except UnicodeEncodeError:
+ pass
return ok
@@ -5346,7 +5425,8 @@ def main() -> int:
help="clamp max_tokens to the remaining context instead of rejecting the request "
"(default: reject with 400, like llama.cpp; also \"fit_max_tokens\": true in the config)")
ap.add_argument("--api-key", default=os.environ.get("STRATA_API_KEY", ""),
- help="require this key on /v1/* (Authorization: Bearer ... or x-api-key); also $STRATA_API_KEY")
+ help="require this key on /v1/* (Authorization: Bearer ... or x-api-key); also $STRATA_API_KEY. "
+ "Several keys: separate them with commas (key1,key2), as llama.cpp does")
ap.add_argument("--mcp-config", help="a JSON file with MCP servers in Claude Desktop's format ({\"mcpServers\": "
"{...}}); the web app's chat can use their tools (also \"mcp_servers\" in "
"the config)")
diff --git a/serve/test_server.py b/serve/test_server.py
index a6f9f1155..a7f976ecb 100644
--- a/serve/test_server.py
+++ b/serve/test_server.py
@@ -922,6 +922,25 @@ class ApiKeyForms(unittest.TestCase):
self.assertTrue(key_matches(as_read("ключ", "utf-8"), "ключ"))
self.assertFalse(key_matches(as_read("ключ", "utf-8"), "ключx"))
+ def test_several_keys_1344(self):
+ # llama.cpp's form: "k1,k2" is two keys, not one key with a comma; a config list is taken as it is
+ self.assertEqual(api_key_of("sk-aaa,sk-bbb"), "sk-aaa,sk-bbb")
+ self.assertEqual(api_key_of(["sk-aaa", " sk-bbb "]), ["sk-aaa", "sk-bbb"])
+ self.assertEqual(api_key_of(["a,b"]), ["a,b"]) # a key with a comma: as a list
+ for bad in (",", " , ", [], [""], ["a", " "]):
+ with self.assertRaises(ValueError):
+ api_key_of(bad)
+ two = "sk-aaa,sk-bbb"
+ self.assertTrue(key_matches("sk-aaa", two))
+ self.assertTrue(key_matches("sk-bbb", two))
+ self.assertTrue(key_matches("sk-bbb", "sk-aaa, sk-bbb"))
+ self.assertFalse(key_matches(two, two)) # the joined text is no key
+ self.assertFalse(key_matches("sk-ccc", two))
+ self.assertFalse(key_matches("", two))
+ self.assertTrue(key_matches("a,b", ["a,b", "c"]))
+ self.assertFalse(key_matches("a", ["a,b", "c"]))
+ self.assertTrue(key_matches("single", "single"))
+
def test_a_utf8_key_over_http(self):
tok = ByteTokenizer()
svc = Service(MockEngine(tok, "ok", max_context=CTX), tok, ChatTemplate(ROOT / "serve/chat_template.jinja"))
@@ -3913,6 +3932,49 @@ class SilentEngine(unittest.TestCase):
engine.proc.kill.assert_called_once()
self.assertFalse(engine.alive())
+ def test_frozen_engine_is_ended_by_the_stall_watchdog(self):
+ # #1317 part 2: silent AND no CPU / disk work for the stall window -> ended, long before engine_silence_s
+ from serve import server
+ from serve.server import EngineSilent
+ engine = self.bare(300.0)
+ engine.lines.put("T 5")
+ engine._activity = lambda: (12.0, 4096) # the same reading every time: no work
+ with mock.patch.object(server, "ENGINE_STALL_S", 1.0):
+ gen = engine.generate([1], 10, {}, threading.Event())
+ self.assertEqual(next(gen), 5)
+ t0 = time.monotonic()
+ with self.assertRaises(EngineSilent) as cm:
+ next(gen)
+ self.assertLess(time.monotonic() - t0, 10)
+ self.assertIn("frozen", str(cm.exception))
+ engine.proc.kill.assert_called_once()
+
+ def test_a_working_silent_engine_is_not_ended_by_the_stall_watchdog(self):
+ from serve import server
+ engine = self.bare(300.0)
+ ticks = iter(range(10 ** 6))
+ engine._activity = lambda: (float(next(ticks)), 0) # CPU time advances: it is working
+ self.later(engine, 3.0, "T 7", "DONE 1 1 1 1 length")
+ with mock.patch.object(server, "ENGINE_STALL_S", 1.0):
+ self.assertEqual(list(engine.generate([1], 10, {}, threading.Event())), [7])
+ engine.proc.kill.assert_not_called()
+
+ def test_no_reading_means_no_kill_and_zero_is_off(self):
+ from serve import server
+ for stall, act in ((1.0, lambda: None), (0, lambda: (1.0, 1))):
+ engine = self.bare(300.0)
+ engine._activity = act
+ self.later(engine, 2.5, "T 7", "DONE 1 1 1 1 length")
+ with mock.patch.object(server, "ENGINE_STALL_S", stall):
+ self.assertEqual(list(engine.generate([1], 10, {}, threading.Event())), [7])
+ engine.proc.kill.assert_not_called()
+
+ def test_engine_frozen_samples(self):
+ from serve.server import engine_frozen
+ self.assertTrue(engine_frozen((10.0, 100), (10.2, 100)))
+ self.assertFalse(engine_frozen((10.0, 100), (13.0, 100)))
+ self.assertFalse(engine_frozen((10.0, 100), (10.0, 100 + (8 << 20))))
+
def test_zero_waits_as_before(self):
engine = self.bare(0)
self.later(engine, 0.5, "T 5", "DONE 1 1 1 1 length")
diff --git a/setup.py b/setup.py
index 12e87fe11..224629d6d 100644
--- a/setup.py
+++ b/setup.py
@@ -4547,7 +4547,7 @@ def main() -> int:
help="with two or more GPUs: leave out --remote-expert-opt, which setup adds there (#578)")
ap.add_argument("--host", help="where the server listens: 127.0.0.1 = this PC only (default), 0.0.0.0 = also other "
"devices on your network (issue #26; set --api-key too)")
- ap.add_argument("--api-key", help="require this key from clients (recommended with --host 0.0.0.0)")
+ ap.add_argument("--api-key", help="require this key from clients (recommended with --host 0.0.0.0); several keys: key1,key2")
ap.add_argument("--no-browser", dest="browser", action="store_false", default=None,
help="do not open the chat page in the browser when the model is ready (for a harness or an app "
"that uses the API; remembered for this model, also in run-<model>.bat/.sh)")