serve: restart a dead engine for real - wait for the old process, retry the start, keep the last known context

Seen in long agent sessions (Claude Code, many turns at ~20K tokens): when the engine was ended mid-request (the
60 s watchdog), restart() started the new engine while the old process still held its VRAM. The new one ran out
of memory and exited before READY, `max_context` stayed 0, and from then on every request failed with
"400 ... exceeds the context (0)" until the server was restarted by hand.

- restart() ends the old process first (close(); kill and wait if it is stuck), so its GPU memory is free;
- a start that exits before READY is tried again, 3 times, RESTART_RETRY_S (15 s) apart; `starting` is set
  meanwhile, so a request gets the 503 "starting" of #344;
- `known_ctx` keeps the last context the engine reported: after a restart that failed for good, a request is
  checked against it and reaches run(), which starts the engine again, instead of a 400 about context 0.

Two tests in RestartWindow (both fail without this change): a start that fails once is retried and the engine
comes up; a request after a failed restart gets 200, not a 400. `python -m unittest serve.test_server`: 120 OK.
This commit is contained in:
JeanP00l authored and Niko1221 committed 2026-10-03 18:07:54 +02:00
1 parent 09817da397
commit 67f4dc72bf
2 files changed
+105 -13

No files matched your search

+50 -13
View File
@@ -361,6 +361,7 @@ class StrataEngine:
pass
raise RuntimeError("the engine exited before it was ready" + (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
# report their own version (INFO engine=, 0.1.8+) win, the manifest stays the fallback for older ones
if self.info.get("engine"):
@@ -420,15 +421,44 @@ class StrataEngine:
self.close()
self.unloaded = True
def restart(self):
"""Start the engine again (the same command) after it died; the new process has its own line queue."""
self.close()
RESTART_RETRY_S = 15.0 # between the tries of restart(): a dying engine's VRAM may take a while to come back
def restart(self, tries: int = 3):
"""Start the engine again (the same command) after it died; the new process has its own line queue.
The old process is ended first (close(): QUIT, terminate, kill) - its GPU memory is freed only when it is
gone, and a new engine started next to it runs out of VRAM and exits before it is ready - and a failed start
is retried."""
try:
self.close()
except EngineStuck:
try:
self.proc.kill()
self.proc.wait(timeout=120)
except (subprocess.TimeoutExpired, OSError):
pass
info = dict(self.info)
# #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 = True
self.__init__(*self.spawn)
self.starting = True # prepare() answers 503 "starting" meanwhile (#344)
try:
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
# (0)". __init__ clears `ended` itself once READY (before its pump thread can set it again).
self.ended = True
try:
self.__init__(*self.spawn)
break
except RuntimeError:
try:
self.proc.wait(timeout=60)
except (subprocess.TimeoutExpired, OSError):
pass
if i == tries - 1:
raise
print(f"[strata] the engine did not start (try {i + 1} of {tries}); again in "
f"{self.RESTART_RETRY_S:g} s", flush=True)
time.sleep(self.RESTART_RETRY_S)
finally:
self.starting = False
self.info = {**info, **self.info}
def _parse_done(self, line):
@@ -1374,18 +1404,25 @@ 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)
ctx = self.engine.max_context
if ctx <= 0:
if getattr(self.engine, "starting", False): # #344: (re)starting, not a prompt that is too long
raise EngineStarting("the engine is starting (a minute or two); try again shortly")
# a failed restart leaves max_context 0: check against the last known context, so the request reaches
# run() - which starts the engine again - instead of failing with "exceeds the context (0)" forever
ctx = getattr(self.engine, "known_ctx", 0)
if ctx <= 0:
raise EngineStarting("the engine is starting (a minute or two); try again shortly")
room = ctx - CTX_SLACK - len(ids)
if max_new is None or max_new <= 0 or (self.fit_max_tokens and room < 1):
if room < 1:
raise ValueError(f"prompt ({len(ids)} tokens) leaves no room to answer in the context "
f"({self.engine.max_context}); requests are never truncated")
f"({ctx}); requests are never truncated")
max_new = room
elif max_new > room:
if not self.fit_max_tokens:
raise ValueError(f"prompt ({len(ids)} tokens) + max tokens ({max_new}) exceeds the context "
f"({self.engine.max_context}); requests are never truncated. Send a smaller "
f"({ctx}); requests are never truncated. Send a smaller "
f"max_tokens (at most {max(0, room)} here), or add \"fit_max_tokens\": true to the "
"model's strata-<model>.json to shorten it to the room left (#545)")
max_new = max(1, room) # --fit-max-tokens: a shorter completion beats a 400
+55
View File
@@ -1955,6 +1955,13 @@ for line in sys.stdin:
break
'''
FAKE_STRATA_FAIL_ONCE = '''import pathlib, sys, time
fail = pathlib.Path(sys.argv[sys.argv.index("--fail") + 1])
if fail.exists(): # this start fails before READY (as one next to a dying engine did)
fail.unlink()
sys.exit(1)
''' + FAKE_STRATA.split("\n", 1)[1]
class RestartWindow(unittest.TestCase):
"""#344: while the engine restarts it is not alive (a request waits for the restart instead of reading
@@ -2006,6 +2013,54 @@ class RestartWindow(unittest.TestCase):
gate.touch()
eng.unload()
def test_restart_retries_a_start_that_fails(self):
"""A dead engine's VRAM is freed only when its process is gone, so a new engine started at once can exit
before READY; restart() tries again (3 times) instead of leaving the server with max_context 0."""
from unittest import mock
import serve.server as server
with tempfile.TemporaryDirectory() as d:
script, gate, fail = Path(d) / "fake_strata.py", Path(d) / "ready", Path(d) / "fail_once"
script.write_text(FAKE_STRATA_FAIL_ONCE, 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)), \
mock.patch.object(StrataEngine, "RESTART_RETRY_S", 0.0):
gate.touch()
eng = StrataEngine("strata", ["--gate", str(gate), "--fail", str(fail)])
try:
self.assertEqual(eng.max_context, 4096)
self.assertEqual(eng.known_ctx, 4096)
fail.touch() # the next start exits before READY, the one after works
eng.proc.kill()
eng.proc.wait(10)
eng.restart()
self.assertFalse(fail.exists(), "the failing start never ran")
self.assertTrue(eng.alive())
self.assertEqual(eng.max_context, 4096)
self.assertFalse(eng.starting)
finally:
gate.touch()
eng.unload()
def test_failed_restart_keeps_the_known_context(self):
"""After a restart that failed, max_context is 0 but the engine is not starting: a request is checked against
the last known context and reaches run() (which starts the engine again), not a 400 about context 0."""
tok = ByteTokenizer()
eng = MockEngine(tok, "</think>\n\nok", max_context=0)
eng.known_ctx, eng.starting = 4096, False
svc = Service(eng, tok, ChatTemplate(ROOT / "serve/chat_template.jinja"))
httpd = serve(svc, port=0)
base = f"http://127.0.0.1:{httpd.server_address[1]}"
try:
req = urllib.request.Request(base + "/v1/chat/completions",
data=json.dumps({"model": "m", "max_tokens": 16,
"messages": [{"role": "user", "content": "hi"}]}).encode(),
headers={"Content-Type": "application/json"})
with urllib.request.urlopen(req, timeout=30) as r:
self.assertEqual(r.status, 200)
finally:
httpd.shutdown()
def test_context_zero_is_503(self):
tok = ByteTokenizer()
svc = Service(MockEngine(tok, "</think>\n\nok", max_context=0), tok,