From 610046fe229c949751da3d019db69df0aede7abe Mon Sep 17 00:00:00 2001 From: Hasan Basbunar Date: Thu, 24 Sep 2026 14:14:43 +0200 Subject: [PATCH] wave 2 (engines): every lane runs alone, a timed-out image call holds the lane, crash loops and wedges read as they are - the two text units conflict with each other and with the image lane, and are ordered after them: a switch between any two lanes finishes the stop before the start (measured with throwaway units on the box's systemd 255) - the cockpit keeps the image lock after a read timeout until the lane's journal shows the request ended or the lane restarts (the runtime has no abort); the page shows it as still generating - the pixel budget reads width, height and size the way the lane does, and num_inference_steps is 1 to 100 - a unit in activating/auto-restart is failed with restarting set; install.sh stops waiting when NRestarts grows past its value after the restart (a manual restart does not zero it on systemd 255); the page offers Stop - wedged no longer holds a switch back, and reads degraded when it also loses health - the flash mid-boot stop warning says what it costs: the boot under way Co-Authored-By: Claude Opus 5.5 --- dashboard/DESIGN.md | 3 +- dashboard/cockpit.py | 91 +++++++++++++++++++--- dashboard/lifecycle.py | 16 +++- dashboard/static/app.js | 15 ++-- dashboard/tests/test_cockpit_collectors.py | 27 +++++++ dashboard/tests/test_image_routes.py | 79 +++++++++++++++++++ dashboard/tests/test_lifecycle.py | 27 ++++++- docs/image-lane.md | 13 ++++ install.sh | 13 ++++ qwen38-flash.service.template | 8 +- qwen38-sglang-1m.service.template | 8 +- qwen38-sglang.service.template | 8 +- tests/test_install_crash_loop.py | 70 +++++++++++++++++ tests/test_one_engine_units.py | 48 ++++++++++++ 14 files changed, 403 insertions(+), 23 deletions(-) create mode 100644 tests/test_install_crash_loop.py create mode 100644 tests/test_one_engine_units.py diff --git a/dashboard/DESIGN.md b/dashboard/DESIGN.md index 15a0a90d..05bb7fcd 100644 --- a/dashboard/DESIGN.md +++ b/dashboard/DESIGN.md @@ -147,7 +147,8 @@ so a cockpit restart facing a warm engine never records its uptime. Action gates live server-side in the same module: starting one engine while the other occupies the pool is refused with the reason (409), switch and update wait for transitional states to settle, and mid-boot flash stops are -allowed with a truthful warning (next boot rebuilds the PLE table). The UI +allowed with a truthful warning (the boot under way is lost, and every flash boot +writes its PLE table from scratch since v1.8). The UI renders the same rules: disabled buttons print their reason, the confirm modal carries the warnings, and the per-stage progress bar animates from stage pills plus elapsed-vs-learned-ETA. diff --git a/dashboard/cockpit.py b/dashboard/cockpit.py index dfeb7916..6acc293d 100644 --- a/dashboard/cockpit.py +++ b/dashboard/cockpit.py @@ -1123,7 +1123,7 @@ def collect_lifecycle(): for unit in lc.ENGINE_UNITS + ("qwen38-keepalive.service",): raw = run(["systemctl", "show", unit, "-p", "ActiveState,SubState,ActiveEnterTimestampMonotonic,StateChangeTimestampMonotonic," - "InvocationID,Result"]) + "InvocationID,Result,NRestarts"]) d = dict(ln.split("=", 1) for ln in raw.splitlines() if "=" in ln) active = d.get("ActiveState", "?") if unit not in lc.ENGINE_UNITS: @@ -1196,8 +1196,8 @@ def collect_lifecycle(): # degraded means "WAS serving, lost health", not "health probe has # not caught up yet": right after fired-up, stay warming-up unless # we had already reached ready in this activation. - if st["state"] == "degraded" and prev.get(unit) not in ("ready", - "degraded"): + # (wedged is only reachable from ready, so an engine that was wedged has served) + if st["state"] == "degraded" and prev.get(unit) not in ("ready", "degraded", "wedged"): st["state"] = "warming-up" if st["state"] == "ready" and not is_image: with STATE_LOCK: @@ -1330,6 +1330,9 @@ def collect_lifecycle(): # systemd's own word for how the last run ended: "timeout" is a # unit killed because it did not stop in time, not one that crashed "result": d.get("Result", ""), + # a crash loop reads failed between attempts; the page says so + "restarting": bool(st.get("restarting")), + "restarts": int(d.get("NRestarts") or 0) if str(d.get("NRestarts", "")).isdigit() else 0, "elapsed": round(elapsed, 1) if elapsed else None, "state_elapsed": round(state_elapsed, 1) if state_elapsed is not None else None, "eta": eta, "overdue": overdue, @@ -1750,6 +1753,9 @@ IMAGE_LOCK = threading.Lock() # failing the request, so a call may not ask for more pixels, all its images together, # than the largest call measured here: one 2752x1536 image, 44.8 GB at its peak. IMAGE_MAX_PIXELS = 2752 * 1536 +# How often a call this process gave up on is looked for in the lane's journal (M5 below). +IMAGE_END_POLL_S = 5.0 +IMAGE_END_MARKS = ("Pixel data generated", "Error executing request", "Failed to generate") IMAGE_UNIT_CACHE: dict = {} @@ -1969,6 +1975,55 @@ def _image_life() -> tuple: IMAGE_INTERRUPTED = ("the image lane was stopped or restarted while this image was being made, which is " "the only way this runtime can end a generation early (it has no abort); nothing was kept") +IMAGE_STILL_RUNNING = ("the image lane is still generating this request: it has no abort, so it goes on after " + "this page stopped waiting, and the next request is refused until it ends. Cancel " + "restarts the lane if it should not finish.") + + +def _image_axes(fields: dict): + """(width, height) the way the lane will read them, or the reason it would refuse: + build_sampling_params in its runtime takes an explicit width or height first, axis by + axis, then `size` (lower-cased, spaces dropped, WIDTHxHEIGHT, both positive), then the + pipeline's 1024 default (configs/sample/qwenimage21.py). The budget below read `size` + only when both axes were missing, and case-sensitively, so a width alone or "2048X2048" + reached the lane unbudgeted (found in review, 2026-09-24).""" + w, h = fields.get("width"), fields.get("height") + size = fields.get("size") + if size: + parts = str(size).lower().replace(" ", "").split("x") + try: + sw, sh = (int(parts[0]), int(parts[1])) if len(parts) == 2 else (0, 0) + except ValueError: + sw = sh = 0 + if sw <= 0 or sh <= 0: + return "size must be WIDTHxHEIGHT, two positive numbers (the lane refuses anything else)" + w = sw if w is None else w + h = sh if h is None else h + return (1024 if w is None else w), (1024 if h is None else h) + + +def _image_request_ended_since(invocation: str, since: float) -> bool: + """Whether this run of the lane has logged the end of a request since `since`: the same + lines image_progress() reads as one ending. A journal that cannot be read says no.""" + if not invocation: + return True + raw = run(["journalctl", f"_SYSTEMD_INVOCATION_ID={invocation}", "--since", f"@{int(since)}", + "--no-pager", "-o", "cat", "-g", "|".join(IMAGE_END_MARKS)], timeout=8.0) + return bool(raw.strip()) + + +def _release_image_lock_when_done(life0: tuple, since: float) -> None: + """The lock of a call that timed out here, given back when the lane is done with it: its + journal shows a request ending, or the lane is no longer the run the call went to (a + Cancel, a Stop, a crash), or another IMAGE_TIMEOUT went by with neither.""" + deadline = time.time() + IMAGE_TIMEOUT + try: + while time.time() < deadline: + if _image_life() != life0 or _image_request_ended_since(life0[1], since): + return + time.sleep(IMAGE_END_POLL_S) + finally: + IMAGE_LOCK.release() def image_call(payload: dict, editing: bool) -> tuple[int, dict]: @@ -1986,11 +2041,18 @@ def image_call(payload: dict, editing: bool) -> tuple[int, dict]: n = fields.get("n", 1) if isinstance(n, bool) or not isinstance(n, int) or not 1 <= n <= 10: return 400, {"error": "n is how many images the call makes, from 1 to 10"} - w, h = fields.get("width"), fields.get("height") - if not (w and h): - # generations default to 1024x1024 (the API's own default); a size string wins - m = re.fullmatch(r"(\d{2,5})x(\d{2,5})", str(fields.get("size") or "1024x1024")) - w, h = (int(m.group(1)), int(m.group(2))) if m else (1024, 1024) + steps = fields.get("num_inference_steps") + if steps is not None and (isinstance(steps, bool) or not isinstance(steps, int) or not 1 <= steps <= 100): + # the page offers 1 to 100, and a count past it is how a call outlives IMAGE_TIMEOUT + return 400, {"error": "num_inference_steps is a number from 1 to 100"} + axes = _image_axes(fields) + if isinstance(axes, str): + return 400, {"error": axes} + w, h = axes + for axis, v in (("width", w), ("height", h)): + if v < 32 or v % 32: + return 400, {"error": f"{axis} {v} is not a positive multiple of 32 " + f"(the engine answers a bare HTTP 500 otherwise)"} if n * w * h > IMAGE_MAX_PIXELS: return 400, {"error": f"{n} image{'s' if n > 1 else ''} of {w}x{h} in one call is " f"{n * w * h / 1e6:.1f} megapixels, and the largest call measured on this " @@ -2022,6 +2084,7 @@ def image_call(payload: dict, editing: bool) -> tuple[int, dict]: "to finish."} t0 = time.time() life0 = _image_life() + handed_over = [False] try: if editing: refs, why = _image_decoded_refs(payload) @@ -2052,12 +2115,22 @@ def image_call(payload: dict, editing: bool) -> tuple[int, dict]: except Exception as e: # noqa: BLE001 (isolated route) if _image_life() != life0: return 503, {"error": IMAGE_INTERRUPTED, "interrupted": True, "seconds": round(time.time() - t0, 2)} + if isinstance(e, TimeoutError): + # A read timeout: the request reached this same run and this process stopped + # waiting (a connect timeout is a URLError, and means it never got there). The + # lane has no abort and goes on. + # Releasing the lock here admitted a second generation beside it (found in review, + # 2026-09-24), so it is handed to a watcher that gives it back when the lane is done. + threading.Thread(target=_release_image_lock_when_done, args=(life0, t0), daemon=True).start() + handed_over[0] = True + return 504, {"error": IMAGE_STILL_RUNNING, "seconds": round(time.time() - t0, 2)} return 502, {"error": f"the image lane did not answer ({type(e).__name__}). " f"Switch to Qwen-Image 2.1 in the action bar and start it " f"(or ./switch-model.sh image)", "seconds": round(time.time() - t0, 2)} finally: - IMAGE_LOCK.release() + if not handed_over[0]: + IMAGE_LOCK.release() def _multipart(fields: dict, images: list) -> tuple[bytes, str]: diff --git a/dashboard/lifecycle.py b/dashboard/lifecycle.py index 102a0883..6ca58f3a 100644 --- a/dashboard/lifecycle.py +++ b/dashboard/lifecycle.py @@ -167,6 +167,11 @@ def derive_state(*, unit_active: str, unit_sub: str, container_running: bool, return {"state": "orphan", **flags} if unit_active == "failed": return {"state": "failed", **flags} + if unit_active == "activating" and unit_sub == "auto-restart": + # Between two attempts of Restart=always after a crash: RestartSec=15 never reaches + # systemd's start limit, so a unit dying at load never reads "failed" and was drawn + # as a boot in its first stage forever (found in review, 2026-09-24). + return {"state": "failed", "restarting": True, **flags} if unit_active == "deactivating": return {"state": "stopping", **flags} if unit_active in ("inactive", "dead", "?", ""): @@ -194,8 +199,9 @@ def derive_state(*, unit_active: str, unit_sub: str, container_running: bool, BUSY_STATES = {"starting", "loading-weights", "loading-draft", "allocating-kv", "capturing-graphs", "warming-up", "ready", "degraded", "stopping", "wedged", "orphan"} -# An orphan does not settle by waiting, so it does not hold a switch back either. -TRANSITIONAL = BUSY_STATES - {"ready", "degraded", "orphan"} +# An orphan or a wedge does not settle by waiting (autoheal is off by default), so neither +# holds a switch back, which only rewrites files; both stay busy for a second engine. +TRANSITIONAL = BUSY_STATES - {"ready", "degraded", "orphan", "wedged"} # Every unit that holds the GPU pool while it runs. The image lane is one of them: # 31 GB of weights, and two engines at once on 121.6 GB of unified memory is the # livelock this whole module exists to prevent. @@ -246,8 +252,10 @@ def warn_reasons(action: str, params: dict, states: dict, unit = params.get("unit", "") state = states.get(unit, "stopped") if unit == "qwen38-flash.service" and state in TRANSITIONAL: - warns.append("stopping the flash lane mid-boot marks the PLE " - "table dirty: the NEXT boot rebuilds it (~12 min)") + # Since v1.8 the launcher deletes the table before every boot and each boot + # writes it whole, so a stop marks nothing dirty; what it costs is this boot. + warns.append("this boot is thrown away: every flash boot writes its 47.7 GiB PLE " + "table from scratch, so the next start takes the full 12 to 15 min again") elif unit == IMAGE_UNIT and state == "ready": # the proxy on :30001 is a text door; nothing reaches this lane through it warns.append("an image being generated right now is lost, and the Image " diff --git a/dashboard/static/app.js b/dashboard/static/app.js index 20c72282..076f95c8 100644 --- a/dashboard/static/app.js +++ b/dashboard/static/app.js @@ -583,7 +583,7 @@ function rConfig(d){ const CARDS = new Map(); function servingEngine(){ const eng = (F.life && F.life.engines) || {}; - return Object.entries(eng).find(([n, e]) => !UNIT_DOWN.has(e.state)) || null; + return Object.entries(eng).find(([n, e]) => !UNIT_DOWN.has(e.state) || e.restarting) || null; } function enabledUnit(){ const e = Object.entries(F.units).find(([n, u]) => n !== 'qwen38-keepalive.service' && u.enabled === 'enabled'); @@ -669,9 +669,10 @@ function engineCard(name){ c = {root, chip, nameEl, enabled, since, btn, why, hist, extra, sig: ''}; btn.addEventListener('click', () => { const e = ((F.life || {}).engines || {})[name]; if (!e) return; - const on = !UNIT_DOWN.has(e.state); + // a crash loop is failed between attempts, yet only a stop ends it + const on = !UNIT_DOWN.has(e.state) || !!e.restarting; const warns = []; - if (on && TRANSITIONAL.has(e.state) && name.includes('flash')) warns.push('stopping the flash lane mid-boot marks the PLE table dirty: the NEXT boot rebuilds it (about 12 min)'); + if (on && TRANSITIONAL.has(e.state) && name.includes('flash')) warns.push('this boot is thrown away: every flash boot writes its 47.7 GiB PLE table from scratch, so the next start takes the full 12 to 15 min again'); if (on && e.state === 'ready') warns.push(name === IMAGE_UNIT ? 'an image being generated right now is lost, and the Image tab has nothing to talk to until this lane is back (' + readyIn(name) + ' after a start)' : 'clients on :30001 get "engine unavailable" until an engine is back (' + readyIn(name) + ' after a start)'); @@ -700,7 +701,7 @@ function rLifecycle(d){ const en = (units[name] || {}).enabled; c.enabled.textContent = en === 'enabled' ? 'starts at boot' : en === 'disabled' ? 'manual start only' : en || ''; c.since.textContent = e.state === 'ready' && e.elapsed ? 'up ' + fmtDur(e.elapsed) : ''; - const on = !UNIT_DOWN.has(e.state); + const on = !UNIT_DOWN.has(e.state) || !!e.restarting; const blocked = !on && (d.blocked || {})[`unit:start:${name}`]; c.btn.textContent = on ? (e.state === 'stopping' ? 'stopping…' : 'stop') : 'start'; c.btn.className = 'btn mini ' + (on ? 'danger' : 'low'); @@ -1203,7 +1204,9 @@ function banners(state, errors){ const eng = (F.life && F.life.engines) || {}; Object.entries(eng).forEach(([n, e]) => { if (e.state === 'wedged') add('err', `${LANE_NAME[n] || n} is wedged.`, 'It answers health checks but generates nothing. The autoheal belt restarts it after its grace period; the Logs tab has the scheduler forensics.'); - if (e.state === 'failed' && e.result === 'timeout') add('warn', `${LANE_NAME[n] || n} was killed while stopping.`, + if (e.state === 'failed' && e.restarting) add('err', `${LANE_NAME[n] || n} keeps crashing.`, + `It dies during startup and systemd relaunches it every 15 s (Restart=always${e.restarts ? `, ${e.restarts} relaunches so far` : ''}): the Logs tab has its journal. Stop it from the action bar to end the loop.`); + else if (e.state === 'failed' && e.result === 'timeout') add('warn', `${LANE_NAME[n] || n} was killed while stopping.`, 'It did not exit within its stop timeout, so systemd killed it and marks the unit failed. Nothing broke while it was serving: start it again from the action bar when you need it.'); else if (e.state === 'failed') add('err', `${LANE_NAME[n] || n} failed.`, 'systemd reports the unit failed. Read its journal in the Logs tab, then start it again from the action bar.'); if (e.state === 'degraded') add('warn', `${LANE_NAME[n] || n} stopped answering.`, 'It was serving; health probes retry every 2 s. If it stays here, the Logs tab tells why.'); @@ -2160,6 +2163,8 @@ async function imgRun(){ if (!r.ok){ const why = out.error || (out.refused ? JSON.stringify(out.refused).slice(0, 300) : 'HTTP ' + r.status); if (r.status === 409){ toast(why, 'warn', 7000); setChip('imgtime', 'lane busy', 'warn'); return; } + // 504: this page stopped waiting and the lane goes on (it has no abort); not a refusal + if (r.status === 504){ imgParkBar(); clear($('imgout')); $('imgout').append(el('p', 'note', why)); setChip('imgtime', 'still generating', 'warn'); return; } imgParkBar(); clear($('imgout')); $('imgout').append(el('p', 'note', 'Refused with HTTP ' + r.status + ': ' + why)); setChip('imgtime', r.status + ' refused', 'err'); return; diff --git a/dashboard/tests/test_cockpit_collectors.py b/dashboard/tests/test_cockpit_collectors.py index 171533df..a19376fe 100644 --- a/dashboard/tests/test_cockpit_collectors.py +++ b/dashboard/tests/test_cockpit_collectors.py @@ -477,6 +477,33 @@ class TheBootBarNeverGoesBack(Base): +class AWedgedEngineThatLosesHealthIsDegraded(Base): + """A wedge is only reachable from ready, so when that engine also stops answering it has + long been serving: "degraded". The check that keeps a fresh boot in warming-up did not + know the state, and drew a boot bar with an overdue warning over it (found in review, + 2026-09-24).""" + U = "qwen38-sglang.service" + + def test_it_reads_degraded_not_warming_up(self): + self.cp.BOOT_HEAD_READ.clear() + self.cp.BOOT_SEEN.clear() + fired = ("[2026-09-22 19:53:22] Load weight end. elapsed=118.38 s\n" + "[2026-09-22 19:58:40] The server is fired up and ready to roll!\n") + with self.cp.STATE_LOCK: + self.cp.STATE["engine_fast"] = {"data": {"healthy": False}} + with self.cp.LIFE_LOCK: + self.cp.LIFE["states"] = {self.U: "wedged"} + self.cp.UNHEALTHY_TICKS[self.U] = 5 + self.cp.LAST_PROGRESS["ts"] = None + self.box({f"systemctl show {self.U}": "ActiveState=active\nSubState=running\n" + "ActiveEnterTimestampMonotonic=1000\n", + "docker ps -q -f name=^qwen38-sglang$": "c0ffee\n", + "docker logs --tail 300 qwen38-sglang": fired, + "docker logs --since": fired}) + out = self.cp.collect_lifecycle() + self.assertEqual(out.get("data", out)["engines"][self.U]["state"], "degraded") + + class AStopTimeoutIsNotACrash(Base): """A unit systemd killed because it did not stop in time ends "failed" with Result=timeout: that is how a Stop during a generation looked on 2026-09-23, and the diff --git a/dashboard/tests/test_image_routes.py b/dashboard/tests/test_image_routes.py index aba0dfec..7be5a61e 100644 --- a/dashboard/tests/test_image_routes.py +++ b/dashboard/tests/test_image_routes.py @@ -315,6 +315,52 @@ class OneAtATime(Base): self.assertEqual(self.call({"prompt": "x", "width": 1000})[0], 400) self.assertFalse(self.ck.IMAGE_LOCK.locked()) + def _timeout_then(self, lives, ended): + """A call that times out here while the lane goes on, with the lane's invocation and + the journal's end marker driven by the test.""" + import socket + saved = (self.ck._image_life, self.ck._image_request_ended_since, self.ck.IMAGE_END_POLL_S) + self.addCleanup(lambda: (setattr(self.ck, "_image_life", saved[0]), + setattr(self.ck, "_image_request_ended_since", saved[1]), + setattr(self.ck, "IMAGE_END_POLL_S", saved[2]))) + + def slow(req, timeout=None): + raise socket.timeout("timed out") + self.ck.urllib.request.urlopen = slow + self.ck._image_life = lambda: lives[0] + self.ck._image_request_ended_since = lambda invocation, since: ended[0] + self.ck.IMAGE_END_POLL_S = 0.02 + + def _released(self): + import time + for _ in range(200): + if not self.ck.IMAGE_LOCK.locked(): + return True + time.sleep(0.01) + return False + + def test_a_request_that_timed_out_keeps_the_lane_busy_until_it_ends(self): + """The lane has no abort: a call this process gave up on after IMAGE_TIMEOUT is still + generating there, and releasing the lock then admitted a second generation beside it + (two at once held 90.5 GB and stopped the engine; found in review, 2026-09-24). The + lock now stays held until this invocation's journal shows a request end.""" + lives, ended = [("active", "run-1")], [False] + self._timeout_then(lives, ended) + code, out = self.call({"prompt": "x", "width": 512, "height": 512}) + self.assertEqual(code, 504, out) + self.assertIn("still generating", out["error"]) + self.assertNotIn("start it", out["error"], "it is serving: no advice to start it") + self.assertEqual(self.call({"prompt": "y", "width": 512, "height": 512})[0], 409) + ended[0] = True + self.assertTrue(self._released(), "released once the journal shows the end") + + def test_a_lane_that_restarts_while_the_lock_is_held_gives_it_back(self): + lives, ended = [("active", "run-1")], [False] + self._timeout_then(lives, ended) + self.assertEqual(self.call({"prompt": "x", "width": 512, "height": 512})[0], 504) + lives[0] = ("active", "run-2") # Cancel, a Stop and a Start, a crash + self.assertTrue(self._released(), "a new invocation is not generating the old request") + class ThePixelBudget(Base): """The images of one call run as one batch: ten 2048x2048 images took 42 s per step on @@ -348,6 +394,39 @@ class ThePixelBudget(Base): code, out = self.ask(size="2048x2048", n=2) self.assertEqual(code, 400, out) + def test_each_axis_is_read_the_way_the_lane_reads_it(self): + """build_sampling_params in the lane's runtime: an explicit width or height first, + axis by axis, then `size` lower-cased with its spaces dropped, then the pipeline's + 1024 default. The budget read `size` only when both axes were missing, and matched + it case-sensitively, so these reached the lane (found in review, 2026-09-24).""" + for fields in ({"width": 16384, "n": 4}, # height 1024: 67 MP + {"width": 16384, "size": "32x4096", "n": 10}, # 16384 x 4096: 671 MP + {"size": "2048X2048", "n": 4}, # 16.8 MP + {"size": "123456x123456"}, # 15 GP + {"height": 8192, "size": "4096x32"}): # 4096 x 8192 + with self.subTest(fields=fields): + self.spy.body = None + code, out = self.ask(**fields) + self.assertEqual(code, 400, out) + self.assertIsNone(self.spy.body, "a refused call reached the lane") + + def test_a_size_the_lane_would_refuse_or_500_on_is_refused_here(self): + for size in ("big", "512x", "0x512", "1000x1000", "1024x1000"): + with self.subTest(size=size): + self.spy.body = None + self.assertEqual(self.ask(size=size)[0], 400) + self.assertIsNone(self.spy.body) + self.assertEqual(self.ask(size=" 1024 X 768 ")[0], 200, "the lane reads this as 1024x768") + + def test_steps_are_a_number_from_1_to_100(self): + """The page offers 1 to 100 and the server capped nothing: one call with a huge + count outlived the 1800 s timeout and, with it, the lock.""" + for bad in (0, 101, -5, "30", 2.5, True): + with self.subTest(steps=bad): + self.assertEqual(self.ask(width=512, height=512, num_inference_steps=bad)[0], 400) + for good in (1, 100): + self.assertEqual(self.ask(width=512, height=512, num_inference_steps=good)[0], 200) + def test_the_count_is_a_number_from_1_to_10(self): for bad in (0, 11, -1, "3", 2.0, True, [2]): code, out = self.ask(width=512, height=512, n=bad) diff --git a/dashboard/tests/test_lifecycle.py b/dashboard/tests/test_lifecycle.py index fbccc0e9..faa51fe2 100644 --- a/dashboard/tests/test_lifecycle.py +++ b/dashboard/tests/test_lifecycle.py @@ -91,6 +91,17 @@ class DeriveState(unittest.TestCase): self.assertEqual(self.s(unit_active="failed", container_running=False)["state"], "failed") self.assertEqual(self.s(unit_active="deactivating")["state"], "stopping") + def test_a_unit_waiting_to_be_relaunched_after_a_crash_is_failed(self): + """Restart=always with RestartSec=15 never reaches systemd's start limit, so a unit + that dies at load sits in activating/auto-restart between attempts (read on the + reference box's systemd 255, 2026-09-24) and never in failed: the page drew a boot + in its first stage forever.""" + got = self.s(unit_active="activating", unit_sub="auto-restart", container_running=False) + self.assertEqual(got["state"], "failed") + self.assertTrue(got.get("restarting")) + self.assertNotEqual(self.s(unit_active="activating", unit_sub="start", container_running=False)["state"], + "failed", "an ordinary start is still a start") + def test_a_container_that_outlives_its_unit_is_an_orphan(self): """A stop past its timeout: systemd kills the docker client and marks the unit failed (app.js already tells that case apart), while the container, which the @@ -175,6 +186,17 @@ class BlockedReasons(unittest.TestCase): states), []) self.assertEqual(lc.blocked_reasons("switch", {"target": "stock"}, states), []) + def test_a_wedged_engine_does_not_hold_a_switch_back(self): + """A wedge does not settle by waiting (autoheal is off by default), and a switch only + rewrites files: "wait for it to settle" refused it for good (found in review, + 2026-09-24). It still counts as busy for starting a second engine.""" + states = {"qwen38-sglang.service": "wedged", "qwen38-flash.service": "stopped"} + self.assertEqual(lc.blocked_reasons("switch", {"target": "stock"}, states), []) + self.assertTrue(lc.blocked_reasons("unit", {"unit": "qwen38-flash.service", "verb": "start"}, states)) + self.assertEqual(lc.warn_reasons("unit", {"unit": "qwen38-flash.service", "verb": "stop"}, + {"qwen38-flash.service": "wedged"}), [], + "a wedged lane has booted: no mid-boot warning") + def test_stop_is_never_blocked(self): states = {"qwen38-flash.service": "loading-weights", "qwen38-sglang.service": "stopped"} @@ -187,7 +209,10 @@ class BlockedReasons(unittest.TestCase): w = lc.warn_reasons("unit", {"unit": "qwen38-flash.service", "verb": "stop"}, states) self.assertEqual(len(w), 1) - self.assertIn("rebuilds", w[0]) + # the launcher deletes the table before every boot (since v1.8): nothing is left + # dirty, and what a stop costs is the boot under way + self.assertIn("from scratch", w[0]) + self.assertNotIn("dirty", w[0]) class ThreeEngines(unittest.TestCase): diff --git a/docs/image-lane.md b/docs/image-lane.md index 53cb4f76..495d4207 100644 --- a/docs/image-lane.md +++ b/docs/image-lane.md @@ -253,6 +253,19 @@ empty body; the reason is only in the engine's own log (`Qwen-Image 2.1 height and width must be divisible by 32`). All seven aspect ratios Qwen publishes already are. +The cockpit reads the size of a call the way the lane does (`build_sampling_params`): an +explicit `width` or `height` first, axis by axis, then `size` lower-cased with its spaces +dropped, then 1024. It refuses a size the lane would refuse or 500 on, and budgets the pixels +on those same numbers. Until v1.18.7 it read `size` only when both axes were missing, and +case-sensitively, so a `width` alone or `"2048X2048"` went through unbudgeted. +`num_inference_steps` is 1 to 100, the range the page offers. + +**A call the cockpit stops waiting for keeps the lane busy.** After 30 minutes the cockpit +answers 504, "still generating": the runtime has no abort and goes on, so the next request +is refused until this run's journal shows the request ended, the lane restarts (Cancel), or +another 30 minutes pass. Until v1.18.7 the lock was given back at the timeout and a second +generation could start beside the first, the 90.5 GB case that stopped the engine. + **An output format must be sent, always.** Left out, `choose_output_image_ext` falls back to `jpg` when the background is not transparent. This model returns RGBA for *everything* it makes, PIL refuses to write RGBA as JPEG, and the request 500s. The plainest possible diff --git a/install.sh b/install.sh index 8029a55b..4069b496 100755 --- a/install.sh +++ b/install.sh @@ -1861,6 +1861,14 @@ fi SMOKE_MODEL="qwen3.8-27b" [ "$LANE" = "flash" ] && SMOKE_MODEL="qwen3.8-flash-next" [ "$ENGINE_KEEP" -eq 1 ] || sudo systemctl restart "$UNIT_NAME" +# A unit that dies at load never reads "failed" here: Restart=always relaunches it after +# RestartSec=15, which never reaches systemd's default limit of 5 starts in 10 s, so +# is-active says "activating" between attempts and the loop below waited its full 20 +# minutes with the journal unread. systemd counts the relaunches (NRestarts), and a manual +# restart does not zero the count (checked on the reference box's systemd 255), so the +# count now is the baseline and one more is a crash (found in review, 2026-09-24). +engine_restarts() { systemctl show -p NRestarts --value "$UNIT_NAME" 2>/dev/null | tr -dc '0-9'; } +ENGINE_RESTARTS0="$(engine_restarts)" # what the wait is made of: the flash lane rewrites its PLE table on every boot, and said # "first boot compiles kernels" through a 13-minute load that compiled nothing LOAD_WHY="first boot compiles kernels, be patient" @@ -2063,6 +2071,11 @@ except Exception as e: fi ST="$(systemctl is-active "$UNIT_NAME" || true)" [ "$ST" = "failed" ] && { journalctl -u "$UNIT_NAME" --no-pager | tail -25; die "Service failed during startup, logs above. Common cause: another process eating GPU/unified memory (this config needs the machine to itself)."; } + NOW_RESTARTS="$(engine_restarts)" + if [ -n "$NOW_RESTARTS" ] && [ -n "$ENGINE_RESTARTS0" ] && [ "$NOW_RESTARTS" -gt "$ENGINE_RESTARTS0" ]; then + journalctl -u "$UNIT_NAME" --no-pager | tail -25 + die "The engine died during startup and systemd is relaunching it (Restart=always, $((NOW_RESTARTS - ENGINE_RESTARTS0)) relaunch(es) so far): logs above. Stop the loop with: sudo systemctl stop $UNIT_NAME" + fi [ $((i % 15)) -eq 0 ] && echo " still loading... ($((i*8))s; $LOAD_WHY)" sleep 8 done diff --git a/qwen38-flash.service.template b/qwen38-flash.service.template index 7aa249e1..e94aa341 100644 --- a/qwen38-flash.service.template +++ b/qwen38-flash.service.template @@ -1,8 +1,14 @@ [Unit] Description=Qwen3.8-Flash-Next NVFP4 + NEXTN (SGLang, PLE table on NVMe, capped docker), OpenAI API :__PORT__ -After=network-online.target docker.service Wants=network-online.target Requires=docker.service +# One engine at a time on this box, said to systemd: starting this lane stops the others +# and starting another stops this one, the stop finishing before the start in both +# directions (Conflicts= alone orders nothing; measured with throwaway units on the +# reference box's systemd 255, 2026-09-24). Until v1.18.7 only the image lane said so, +# and two text lanes could run side by side, or both start at boot if both were enabled. +Conflicts=qwen38-sglang.service qwen38-image.service qwen38-llamacpp.service +After=network-online.target docker.service qwen38-sglang.service qwen38-image.service qwen38-llamacpp.service [Service] Type=simple diff --git a/qwen38-sglang-1m.service.template b/qwen38-sglang-1m.service.template index d67e345a..fe01ff3f 100644 --- a/qwen38-sglang-1m.service.template +++ b/qwen38-sglang-1m.service.template @@ -1,8 +1,14 @@ [Unit] Description=Qwen3.8-27B NVFP4 + DFlash2, 1M YaRN context (SGLang, capped docker), OpenAI+Anthropic API :__PORT__ -After=network-online.target docker.service Wants=network-online.target Requires=docker.service +# One engine at a time on this box, said to systemd: starting this lane stops the others +# and starting another stops this one, the stop finishing before the start in both +# directions (Conflicts= alone orders nothing; measured with throwaway units on the +# reference box's systemd 255, 2026-09-24). Until v1.18.7 only the image lane said so, +# and two text lanes could run side by side, or both start at boot if both were enabled. +Conflicts=qwen38-flash.service qwen38-image.service qwen38-llamacpp.service +After=network-online.target docker.service qwen38-flash.service qwen38-image.service qwen38-llamacpp.service [Service] Type=simple diff --git a/qwen38-sglang.service.template b/qwen38-sglang.service.template index 3f4cadc1..b10d92c6 100644 --- a/qwen38-sglang.service.template +++ b/qwen38-sglang.service.template @@ -1,8 +1,14 @@ [Unit] Description=Qwen3.8-27B NVFP4 + DFlash2 (SGLang, capped docker), OpenAI+Anthropic API :__PORT__ -After=network-online.target docker.service Wants=network-online.target Requires=docker.service +# One engine at a time on this box, said to systemd: starting this lane stops the others +# and starting another stops this one, the stop finishing before the start in both +# directions (Conflicts= alone orders nothing; measured with throwaway units on the +# reference box's systemd 255, 2026-09-24). Until v1.18.7 only the image lane said so, +# and two text lanes could run side by side, or both start at boot if both were enabled. +Conflicts=qwen38-flash.service qwen38-image.service qwen38-llamacpp.service +After=network-online.target docker.service qwen38-flash.service qwen38-image.service qwen38-llamacpp.service [Service] Type=simple diff --git a/tests/test_install_crash_loop.py b/tests/test_install_crash_loop.py new file mode 100644 index 00000000..e7fd4463 --- /dev/null +++ b/tests/test_install_crash_loop.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""install.sh names an engine that dies at load instead of waiting 20 minutes on it. + +Every engine unit has Restart=always and RestartSec=15, which never reaches systemd's +default limit (5 starts in 10 s), so between two attempts `systemctl is-active` says +"activating", never "failed", and the wait loop's only crash check could not fire: a +unit dying at load got "still loading... be patient" for 20 minutes, with its journal +unread (found in review, 2026-09-24). systemd counts the relaunches in NRestarts, and on +the reference box's systemd 255 a manual restart does not zero that count, so the loop +compares against the count right after the restart. + +These run the installer's own lines against a fake systemctl whose NRestarts the test +moves, and a fake journalctl. +""" +import pathlib +import subprocess +import tempfile +import unittest + +REPO = pathlib.Path(__file__).resolve().parents[1] +TEXT = (REPO / "install.sh").read_text() + + +def lines(start, end): + i = TEXT.index(start) + return TEXT[i:TEXT.index(end, i)] + + +FUNC = next(ln for ln in TEXT.splitlines() if ln.startswith("engine_restarts() {")) +BASE = next(ln for ln in TEXT.splitlines() if ln.startswith('ENGINE_RESTARTS0="$(engine_restarts)"')) +CHECK = lines(' NOW_RESTARTS="$(engine_restarts)"', "\n fi\n") + "\n fi\n" + + +def run(counts): + """counts: NRestarts answered by each successive `systemctl show` call.""" + t = pathlib.Path(tempfile.mkdtemp(prefix="crash-loop-")) + (t / "counts").write_text("\n".join(map(str, counts)) + "\n") + (t / "systemctl").write_text( + "#!/bin/sh\nf=\"$COUNTS\"; n=$(head -1 \"$f\"); tail -n +2 \"$f\" > \"$f.new\"; " + "[ -s \"$f.new\" ] && mv \"$f.new\" \"$f\"; echo \"$n\"\n") + (t / "journalctl").write_text("#!/bin/sh\necho 'the last lines of the dead engine'\n") + for n in ("systemctl", "journalctl"): + (t / n).chmod(0o755) + script = ("set -euo pipefail\ndie(){ echo \"DIE: $*\"; exit 1; }\nUNIT_NAME=qwen38-sglang.service\n" + + FUNC + "\n" + BASE + "\n" + CHECK + "echo STILL-WAITING\n") + r = subprocess.run(["bash", "-c", script], capture_output=True, text=True, timeout=30, + env={"PATH": f"{t}:/usr/bin:/bin", "COUNTS": str(t / "counts")}) + return r.returncode, r.stdout + r.stderr + + +class ACrashLoopIsNamed(unittest.TestCase): + def test_a_relaunch_after_the_restart_ends_the_wait_with_the_journal(self): + rc, out = run([2, 3]) # 2 before this boot, one more relaunch since + self.assertEqual(rc, 1, out) + self.assertIn("died during startup and systemd is relaunching it", out) + self.assertIn("1 relaunch(es)", out) + self.assertIn("the last lines of the dead engine", out) + + def test_an_old_count_from_before_the_restart_is_not_a_crash(self): + rc, out = run([2, 2]) # a manual restart did not zero it + self.assertEqual(rc, 0, out) + self.assertIn("STILL-WAITING", out) + + def test_it_sits_inside_the_wait_loop_after_the_restart(self): + self.assertLess(TEXT.index(BASE), TEXT.index('for i in $(seq 1 150); do')) + self.assertLess(TEXT.index('for i in $(seq 1 150); do'), TEXT.index(CHECK.strip().splitlines()[0])) + + +if __name__ == "__main__": + unittest.main(verbosity=2) diff --git a/tests/test_one_engine_units.py b/tests/test_one_engine_units.py new file mode 100644 index 00000000..d7d4e8ff --- /dev/null +++ b/tests/test_one_engine_units.py @@ -0,0 +1,48 @@ +#!/usr/bin/env python3 +"""Every lane's unit tells systemd that it runs alone, and in what order. + +Two engines on the unified pool is the livelock this box power-cycles out of. The image +unit said so with Conflicts= and no After=, and Conflicts= orders nothing: its start and +the text lane's stop ran side by side (5 to 60 s in the reference box's journal on +2026-09-23). The two text units said nothing at all to each other, so the 27B and the +flash lane could run together, or both start at boot if both were enabled. + +With Conflicts= and After= on every other lane, measured on the box's systemd 255 with +throwaway units (2026-09-24): each switch finished the stop before the start, in all four +directions tried, with no ordering-cycle warning, and a transaction asking for two lanes +at once started one of them only. +""" +import pathlib +import re +import unittest + +REPO = pathlib.Path(__file__).resolve().parents[1] +LANES = { + "qwen38-sglang.service": ("qwen38-sglang.service.template", "qwen38-sglang-1m.service.template"), + "qwen38-flash.service": ("qwen38-flash.service.template",), + "qwen38-image.service": ("qwen38-image.service.template",), +} +ALL = set(LANES) | {"qwen38-llamacpp.service"} + + +def unit_list(template, key): + unit = (REPO / template).read_text().split("[Service]")[0] + return {u for line in re.findall(rf"(?m)^{key}=(.*)$", unit) for u in line.split()} + + +class EveryLaneRunsAlone(unittest.TestCase): + def test_each_lane_conflicts_with_every_other_lane(self): + for lane, templates in LANES.items(): + for t in templates: + with self.subTest(template=t): + self.assertEqual(unit_list(t, "Conflicts"), ALL - {lane}) + + def test_each_lane_is_ordered_after_what_it_conflicts_with(self): + for templates in LANES.values(): + for t in templates: + with self.subTest(template=t): + self.assertEqual(unit_list(t, "Conflicts") - unit_list(t, "After"), set()) + + +if __name__ == "__main__": + unittest.main(verbosity=2)