Files
alzeo/dashboard/tests/test_embed_cockpit.py
T
Hasan BasbunarandClaude Opus 5.5 c773ac2643 qwen4-35b: the box is its own, no lane beside it (decision 1725)
Hasan, 2026-12-04: a Qwen4 lane on a machine dedicated to it, with all the context it can hold. Its Load stops every lane
beside first, the embeddings lane too (the OCR and Clipstral lanes already, for want of room), and none of them starts
while it serves or is the boot lane: the embeddings lane's unit's head refuses it now as the OCR and Clipstral lanes'
do, and the cockpit says so before the click. Tests red on the old code (the head, the plan), green now.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 16:59:16 +01:00

711 lines
45 KiB
Python

#!/usr/bin/env python3
"""The cockpit follows the embeddings lane on its own facts (v1.60).
Perplexity's pplx-embed-v1-0.6b served by this repo's own server on the CPU, on a port of its own (30028 by default, its
unit's --port) and on 127.0.0.1 alone, with no key: a lane beside every lane, like the speech lane, that never touches
the GPU and stops nothing. Its card appears once its unit is installed, ready when it runs (its server answers /health itself:
no boot to parse, no belt to feed), its Load prepares it (its image, the model) then enables and starts it without
touching the lane that serves, and the page's Load journey says exactly that. The module is imported with its
environment pointed at a throwaway box; the unit is the one its installer renders (--stage, no sudo).
"""
import importlib.util
import json
import os
import re
import shutil
import subprocess
import sys
import tempfile
import unittest
from pathlib import Path
HERE = Path(__file__).resolve()
DASH = HERE.parents[1]
REPO = HERE.parents[2]
sys.path.insert(0, str(HERE.parent))
import pagejs # noqa: E402
U = "qwen38-embed.service"
INSTALLER = (REPO / "install-embeddings.sh").read_text()
IMAGE = re.search(r'^EMBED_IMAGE="([^"]+)"', INSTALLER, re.M).group(1)
MODEL = re.search(r'^EMBED_MODEL="([^"]+)"', INSTALLER, re.M).group(1)
REV = re.search(r'^EMBED_REV="([0-9a-f]{40})"', INSTALLER, re.M).group(1)
SUDOERS = (DASH / "sudoers-cockpit.template").read_text()
ENV_BEFORE = {}
def setUpModule():
ENV_BEFORE.update(os.environ)
def tearDownModule():
for name in set(os.environ) - set(ENV_BEFORE):
del os.environ[name]
os.environ.update(ENV_BEFORE)
class Base(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.box = Path(tempfile.mkdtemp(prefix="cockpit-embed-"))
cls.systemd = cls.box / "systemd"
cls.systemd.mkdir()
cls.hf = cls.box / "hf"
os.environ.update(COCKPIT_DRY_RUN="1", COCKPIT_SYSTEMD_DIR=str(cls.systemd), COCKPIT_CONFIG_DIR=str(cls.box),
COCKPIT_REPO_DIR=str(REPO), COCKPIT_PORT="0", COCKPIT_AGENT_PORT="0", COCKPIT_AUTOHEAL="0",
COCKPIT_ENGINE="http://127.0.0.1:1", COCKPIT_PROXY="http://127.0.0.1:1")
(cls.box / "api-key").write_text("test-key\n")
sys.path.insert(0, str(DASH))
spec = importlib.util.spec_from_file_location("cockpit_embed_under_test", DASH / "cockpit.py")
cls.ck = importlib.util.module_from_spec(spec)
spec.loader.exec_module(cls.ck)
# its unit as its installer renders it for this box (--stage: no sudo, no download)
cls.unit = cls.systemd / U
staged = cls.box / "staged-unit"
subprocess.run(["bash", str(REPO / "install-embeddings.sh"), "--stage", str(staged)],
check=True, capture_output=True, text=True,
env=dict(os.environ, HF_CACHE=str(cls.hf), HOME=os.environ["HOME"]))
cls.unit_text = staged.read_text()
cls.real_run = cls.ck.run
@classmethod
def tearDownClass(cls):
shutil.rmtree(cls.box, ignore_errors=True)
def setUp(self):
self.ck.run = self.real_run
self.ck.UNIT_TARGET_CACHE.clear()
def install_unit(self):
self.unit.write_text(self.unit_text)
def preflight_files(self):
"""The files the unit's own preflight checks before its server starts, as its installer renders it."""
m = re.search(r'snap="([^"]+)"; for f in ([^;]+); do', self.unit_text)
return [Path(m.group(1)) / f for f in m.group(2).split()]
def whole_model(self, but=()):
"""The model whole in the cache its unit mounts: every file its preflight checks (the safetensors
and the tokenizer), those named in `but` left out."""
for f in self.preflight_files():
if f.name in but:
continue
f.parent.mkdir(parents=True, exist_ok=True)
f.write_bytes(b"x")
def show(self, active, sub="running"):
"""run() as collect_lifecycle sees it: systemd's answer for the embed unit alone."""
return lambda argv, **kw: (f"ActiveState={active}\nSubState={sub}\n"
if argv[:3] == ["systemctl", "show", U] else "")
class ItsUnit(Base):
def test_the_unit_its_installer_renders_holds_the_lane_s_promise(self):
t = self.unit_text
self.assertIn("--host 127.0.0.1", t)
self.assertNotIn("api-key", t) # no key: loopback alone, and the proxy before it
self.assertNotIn("\nConflicts=", t) # beside every lane, like the speech lane
self.assertIn("--memory 5632m --memory-swap 5632m", t) # the cgroup cap, equal swap: no spill to the box
self.assertIn("--cpuset-cpus 0-4,10-14", t) # the A725 cores, never the X925
self.assertIn("-e HF_HUB_OFFLINE=1", t) # it reads the cache, never the network
# its model's own folder of the cache, read-only, and nothing else of it: its root holds the account's token
folder = f"hub/models--{MODEL.replace('/', '--')}"
self.assertIn(f"--mount type=bind,source={self.hf}/{folder},target=/root/.cache/huggingface/{folder},readonly", t)
self.assertIn(f"--model-id /root/.cache/huggingface/hub/models--{MODEL.replace('/', '--')}/snapshots/{REV} "
f"--revision {REV}", t)
self.assertIn(f"{IMAGE}", t)
def test_its_card_names_the_repository_its_unit_serves(self):
self.install_unit()
self.addCleanup(self.unit.unlink)
self.assertEqual(self.ck.unit_target(U), {"model": MODEL, "target": "embeddings"})
def test_it_is_a_prepare_target_a_unit_the_page_may_drive_and_a_container_it_lists(self):
ck = self.ck
self.assertEqual(ck.target_lane("embeddings"), "embeddings")
self.assertIn("embeddings", ck.ACTIONS["prepare"]["params"]["target"])
self.assertNotIn("embeddings", ck.ACTIONS["switch"]["params"]["target"], "no switch ever drives it")
self.assertEqual(ck.ACTIONS["prepare"]["argv"]({"target": "embeddings"})[-1], "embeddings")
self.assertIn(U, ck.SERVING_UNITS)
self.assertIn(U, ck.JOURNAL_UNITS)
self.assertIn("qwen38-embed", ck.CONTAINERS)
self.assertEqual(ck.UNIT2CONT[U], "qwen38-embed")
self.assertIn("journal-embed.txt", (DASH / "cockpit.py").read_text(), "its journal is in the bundle")
for verb in ("start", "stop", "restart", "enable", "disable"):
self.assertIn(f"/usr/bin/systemctl {verb} {U}", SUDOERS, verb)
def test_the_unit_s_path_is_the_one_the_cockpit_reads(self):
self.assertEqual(self.ck.EMBED_UNIT_PATH, self.unit)
def test_its_boot_is_given_and_taken_back_and_no_other_lane_s(self):
"""Its Load enables it at boot, and nothing the cockpit offered took that back: no disable for this unit,
Stop stopping it until the next boot only, where the speech lane's card has its boot both ways (code
review of v1.60.0). The server takes enable and disable for the lanes beside alone: an engine lane takes
the boot by its switch, and gives it by the next switch."""
import time
ck = self.ck
for verb in ("enable", "disable"):
code, out = ck.start_action("unit", {"verb": verb, "unit": U})
self.assertEqual(code, 202, out)
self.assertEqual(out["argv"], ["sudo", "-n", "/usr/bin/systemctl", verb, U])
for _ in range(200):
if ck.JOB_LOCK.acquire(blocking=False):
ck.JOB_LOCK.release()
break
time.sleep(0.05)
for unit in ("qwen38-sglang.service", "qwen38-flash.service", "opencode-web.service"):
code, out = ck.start_action("unit", {"verb": "disable", "unit": unit})
self.assertEqual((code, out), (400, {"error": "invalid verb"}), unit)
class ItsBootOnItsCard(unittest.TestCase):
"""The card says whether the lane starts with the box and offers the other choice, as the speech lane's card
does: its Load enables it at boot, and the page had no way to take that back (code review of v1.60.0)."""
def card(self, enabled):
return pagejs.run(self, HELPERS + r"""
const units = JSON.parse(JSON.stringify(UNITS.units));
units['qwen38-embed.service'] = {active: 'active', enabled: '%s'};
feed({config: CONFIG, units: {units}, lanes_ready: {embeddings: true},
lifecycle: life({'qwen38-sglang.service': eng('ready'),
'qwen38-embed.service': eng('ready', {target: 'embeddings', kind: 'embed'})})});
const root = LCARDS.get('qwen38-embed.service').root;
const shown = [...root.querySelectorAll('button')].filter(b => !b.hidden && !b.closest('[hidden]')).map(b => b.textContent);
const boot = [...root.querySelectorAll('button')].find(b => /with the box/.test(b.textContent));
let sheet = null;
if (boot && !boot.hidden){
boot.click();
sheet = {title: txt('sh-title'), lede: txt('sh-lede'), cmd: txt('sh-cmd'), go: txt('sh-go'), cls: $('sh-go').className};
$('sh-cancel').click();
}
const others = [...LCARDS.entries()].filter(([u]) => !BESIDE_UNITS.has(u))
.flatMap(([, c]) => [...c.root.querySelectorAll('button')].filter(b => /with the box/.test(b.textContent)));
report({shown, sheet, others: others.length});
""" % enabled)
def test_enabled_it_offers_to_leave_the_boot(self):
r = self.card("enabled")
self.assertIn("Do not start with the box", r["shown"], r)
self.assertEqual(r["sheet"]["cmd"], "sudo -n /usr/bin/systemctl disable qwen38-embed.service")
self.assertIn("after the next boot", r["sheet"]["lede"])
self.assertNotIn("danger", r["sheet"]["cls"], "taking it out of the boot stops nothing")
self.assertEqual(r["others"], 0, "the lanes of the GPU's turn take the boot by their switch")
def test_disabled_it_offers_to_start_with_the_box(self):
r = self.card("disabled")
self.assertIn("Start with the box", r["shown"], r)
self.assertEqual(r["sheet"]["cmd"], "sudo -n /usr/bin/systemctl enable qwen38-embed.service")
self.assertIn("from the next boot", r["sheet"]["lede"])
class ItsState(Base):
def test_no_unit_no_card(self):
self.ck.run = self.show("active")
d = self.ck.collect_lifecycle()
d = d.get("data", d)
self.assertNotIn(U, d["engines"], "a lane not installed wears no card")
def test_ready_once_tei_answers_and_failed_when_systemd_says_so(self):
"""The state read ready as soon as the unit was active, which it is from the docker run on, while its server
loads the model and the proxy answers 503 (about 10 s on ORT, 30 on candle); and every other state read
stopped, its preflight's 78 included, which leaves the unit failed (code review of v1.60.0). It is
its own /health that says ready, asked on the port the lane's unit names (here a stand-in, on a port
of its own: an EMBED_PORT the installer took), and systemd's word the rest, as for any lane."""
import http.server
import threading
class Health(http.server.BaseHTTPRequestHandler):
ok = False
def log_message(self, *a):
pass
def do_GET(self):
self.send_response(200 if self.path == "/health" and Health.ok else 503)
self.send_header("Content-Length", "0")
self.end_headers()
tei = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Health)
threading.Thread(target=tei.serve_forever, daemon=True).start()
self.addCleanup(tei.server_close)
self.addCleanup(tei.shutdown)
self.unit.write_text(self.unit_text.replace("--port 30028", f"--port {tei.server_port}"))
self.addCleanup(self.unit.unlink, missing_ok=True)
cases = (("active", "running", True, "ready", False), ("active", "running", False, "starting", False),
("activating", "start-pre", False, "starting", False), ("failed", "failed", False, "failed", False),
("activating", "auto-restart", False, "failed", True), ("deactivating", "stop", False, "stopping", False),
("inactive", "dead", False, "stopped", False))
for active, sub, answers, state, restarting in cases:
with self.subTest(active=active, sub=sub, answers=answers):
Health.ok = answers
self.ck.run = self.show(active, sub)
d = self.ck.collect_lifecycle()
d = d.get("data", d)
self.assertEqual(d["engines"][U]["state"], state)
self.assertIs(d["engines"][U]["restarting"], restarting)
def test_failed_it_says_why_its_head_refused_it(self):
"""Its card said "The unit failed: read its journal, then start it again" of a start its unit's head had refused with
the reason and the way out: the collector asks the journal of that run, as for an engine lane."""
self.install_unit()
self.addCleanup(self.unit.unlink, missing_ok=True)
line = ("preflight: qwen38-embed.service lacks room: the box had 9 GiB of memory available and this lane starts with 11 GiB at least "
"(its cap, and the 3 GiB under which generations are stopped): stop the lane that serves or load one that leaves the box "
"more, then start this one again")
asked = []
def run(argv, **kw):
if argv[:3] == ["systemctl", "show", U]:
return f"ActiveState={self.active}\nSubState={self.active}\nInvocationID=abc\n"
if argv[0] == "journalctl" and U in argv and "_SYSTEMD_INVOCATION_ID=abc" in argv:
asked.append(argv)
return line + "\n"
return ""
self.ck.run = run
for self.active, room in (("failed", line.split(" lacks room: ")[1]), ("inactive", None)):
asked.clear()
d = self.ck.collect_lifecycle()
e = d.get("data", d)["engines"][U]
self.assertEqual((e["room"], e["lacks"], bool(asked)), (room, None, room is not None), self.active)
def test_it_wears_none_of_the_text_belts_and_blocks_no_lane(self):
ck = self.ck
self.assertNotIn(U, ck.lc.ENGINE_UNITS, "no SGLang belt: its server answers /health itself")
self.assertNotIn(U, ck.lc.TEXT_UNITS)
# beside every lane: its start is not held by a lane that serves, and it holds no start back
self.assertFalse(ck.lc.blocked_reasons("unit", {"unit": U, "verb": "start"}, {"qwen38-sglang.service": "ready"}))
self.assertFalse(ck.lc.blocked_reasons("unit", {"unit": "qwen38-sglang.service", "verb": "start"}, {U: "ready"}))
class ItsPreparation(Base):
def setUp(self):
super().setUp()
self.install_unit()
shutil.rmtree(self.hf, ignore_errors=True) # the box starts with no model, whatever an earlier test fetched
self.image_here = lambda argv, **kw: (
"sha256:abc\n" if argv[:3] == ["docker", "image", "inspect"] and argv[-1] == IMAGE else "")
def test_prepared_once_the_image_is_here_and_the_model_whole(self):
self.whole_model()
self.ck.run = self.image_here
self.assertTrue(self.ck.lane_prepared("embeddings"))
self.assertIn("embeddings", self.ck.collect_lanes_ready())
def test_the_image_gone_or_the_model_gone_holds_it_back(self):
self.ck.run = self.image_here
self.assertFalse(self.ck.lane_prepared("embeddings"), "the model is not in the cache yet")
self.whole_model()
self.ck.run = lambda argv, **kw: ""
self.assertFalse(self.ck.lane_prepared("embeddings"), "its image is not pulled yet")
def test_a_snapshot_short_of_a_file_its_preflight_checks_is_not_prepared(self):
"""The safetensors there and the tokenizer not (a cache another tool filled at the
pinned revision, a lane fetched before a pin was added at the same revision): its unit's preflight
stops the start at 78, "Load the lane from the cockpit", and the Load read the lane as prepared off
the safetensors alone, so it skipped the fetch and started it into the same 78 (code review of
v1.60.0). Each file the preflight checks holds the Load's preparation back until it is there."""
self.ck.run = self.image_here
self.assertEqual(len(self.preflight_files()), 2, self.preflight_files())
for gone in ("tokenizer.json", "model.safetensors"):
with self.subTest(gone=gone):
shutil.rmtree(self.hf, ignore_errors=True)
self.whole_model(but=(gone,))
self.assertFalse(self.ck.lane_prepared("embeddings"), f"{gone} is not in the snapshot")
shutil.rmtree(self.hf, ignore_errors=True)
self.whole_model()
self.assertTrue(self.ck.lane_prepared("embeddings"))
HELPERS = r"""
const wrap = o => Object.fromEntries(Object.entries(o).map(([k, v]) => [k, {data: v, ts: Date.now() / 1000}]));
const feed = o => apply(wrap(o));
const txt = id => ($(id) ? $(id).textContent : null);
const CONFIG = {version: '1.1.2', dry_run: false, usable_frac: 0.92, periods: {}};
const UNITS = {units: {'qwen38-sglang.service': {active: 'active', enabled: 'enabled'},
'qwen38-embed.service': {active: 'inactive', enabled: 'disabled'},
'qwen38-keepalive.service': {active: 'active', enabled: 'enabled'}}};
const life = (engines, extra) => Object.assign({engines, events: [], blocked: {}}, extra || {});
const eng = (state, extra) => Object.assign({state, target: 'stock', elapsed: 600}, extra || {});
"""
class ItsLoadStopsNothing(unittest.TestCase):
"""The lane's Load (its card's Load, the page's journey): prepare what it lacks, enable it at
boot, start it. No switch drives it and no unit stops: the lane that serves serves throughout,
which is the point of a lane on the CPU beside every lane (decisions 1323 and 1494)."""
def journey(self, ready, pending=None):
return pagejs.run(self, HELPERS + r"""
feed({config: CONFIG, units: UNITS, lifecycle: life({'qwen38-sglang.service': eng('ready')}),
lanes_ready: {embeddings: %s}%s});
askJourney('embeddings');
const steps = [...$('sh-journey').children].map(li => li.textContent);
report({steps, open: !$('scrim').hidden, serving: txt('serving-sub'), warns: $('sh-warns').hidden ? '' : txt('sh-warns')});
""" % ("true" if ready else "false",
", pending: {'qwen38-embed.service': %s}" % (pending and repr(pending) or "undefined")))
def test_its_first_load_downloads_enables_and_starts_and_stops_nothing(self):
r = self.journey(False)
self.assertTrue(r["open"], r)
self.assertEqual(len(r["steps"]), 3, r["steps"])
self.assertIn("Download", r["steps"][0])
self.assertIn("Enable", r["steps"][1])
self.assertIn("Start", r["steps"][2])
for step in r["steps"]:
self.assertNotIn("Stop", step, step)
self.assertNotIn("switch-model", step, step)
# the image it runs on is the 27B lane's, which is no step on that lane
self.assertNotIn("qwen38-sglang", step, step)
def test_its_load_window_warns_of_nothing_it_does_not_do(self):
# the Load window warned "Agent clients on :30001 lose their engine until a text lane answers again"
# over this Load, which stops nothing: its warnings are those of a Load that takes the GPU's turn
# from the lane that serves (code review of v1.60.0, the lane taken for one of the GPU's turn)
r = self.journey(False)
self.assertTrue(r["open"], r)
self.assertEqual(r["warns"], "", r)
def warned(self, target, avail, engines, boot=None, owed=None):
"""A Load's window, MemAvailable, the lanes that run and the boot lane given: its warnings and its steps. engines: each
unit's state, or its state and the target its unit serves."""
return pagejs.run(self, HELPERS + r"""
const a = %s, units = JSON.parse(JSON.stringify(UNITS.units)), engines = {};
if (a.boot) for (const u of Object.keys(units)) units[u].enabled = 'disabled';
for (const [u, x] of Object.entries(a.engines)){
const [s, target] = Array.isArray(x) ? x : [x, null];
engines[u] = eng(s, Object.assign(BESIDE_UNITS.has(u) ? {kind: 'embed'} : {}, target ? {target} : {}));
units[u] = {active: s === 'ready' ? 'active' : 'inactive', enabled: a.boot === u ? 'enabled' : 'disabled'};
}
feed({config: CONFIG, units: {units}, lifecycle: life(engines), update: a.owed ? {stale_engines: {[a.owed]: 'Its unit changed'}} : {},
lanes_ready: {embeddings: true, clipstral: true, '27b': true, flash: true, kolibri: true, 'nemotron-super': true},
machine: {mem: {MemTotal: 121.6 * GIB, MemAvailable: a.avail * GIB, Cached: 2 * GIB, SwapTotal: 0, SwapFree: 0}, disks: {}, net: {}}});
askJourney(a.target);
report({warns: $('sh-warns').hidden ? [] : [...$('sh-warns').children].map(p => p.textContent), open: !$('scrim').hidden,
steps: [...$('sh-journey').children].map(li => li.textContent)});
""" % json.dumps({"target": target, "avail": avail, "engines": engines, "boot": boot, "owed": owed}))
def test_its_load_says_before_the_click_that_its_start_would_be_refused(self):
for target, unit, room in (("embeddings", "qwen38-embed.service", 9), ("clipstral", "qwen38-clipstral.service", 12)):
beside = {"qwen38-sglang.service": "ready", unit: "stopped"}
r = self.warned(target, room - 0.03, beside)
self.assertTrue(r["open"], r)
self.assertEqual(len(r["warns"]), 1, r)
# the reading is cut, not rounded: 10.97 read "has 11.0 GiB ... starts with 11 GiB at least" (review of v1.60.0)
self.assertIn(f"The box has {room - 0.1:.1f} GiB of memory available and this lane starts with {room} GiB at least", r["warns"][0])
self.assertEqual(self.warned(target, room + 0.2, beside)["warns"], [])
def test_a_restart_its_memory_would_not_come_back_from_is_said(self):
runs = {"qwen38-sglang.service": "ready", "qwen38-embed.service": "ready"}
r = self.warned("embeddings", 7.9, runs, boot="qwen38-embed.service", owed="qwen38-embed.service")
self.assertEqual(len(r["warns"]), 1, r)
self.assertIn("The box would have 8.9 GiB of memory available once it stops", r["warns"][0])
self.assertEqual(self.warned("embeddings", 8.1, runs, boot="qwen38-embed.service", owed="qwen38-embed.service")["warns"], [])
def test_beside_a_lane_that_leaves_the_box_little(self):
"""What MemAvailable says while such a lane rests is not what its long prompts leave: the flash lane's 16.6 GiB let both
lanes start, with 1 left under its prompts (review of v1.60.0)."""
clip, embed = "qwen38-clipstral.service", "qwen38-embed.service"
for unit, target, name, little in (("qwen38-flash.service", "flash", "Qwen3.8 Flash-Next", "6.9"),
("qwen38-nemotron-super.service", "nemotron-super", "Nemotron 3.5 Super VL", "9.1"),
("qwen38-kolibri.service", "kolibri", "Kolibri-1", "10.9")):
r = self.warned("clipstral", 40, {unit: ["ready", target], clip: "stopped"}, boot=unit)
self.assertEqual(len(r["warns"]), 1, (unit, r))
self.assertIn(f"leaves the box as little as {little} GiB, and this lane holds 5: its start would be refused.", r["warns"][0])
self.assertIn(name, r["warns"][0])
# and while the box boots it, but for the flash lane, which sizes itself by what is left
r = self.warned("clipstral", 110, {unit: ["stopped", target], clip: "stopped"}, boot=unit)
self.assertEqual(len(r["warns"]), 0 if "flash" in unit else 1, (unit, r))
for unit, target in (("qwen38-flash.service", "flash"), ("qwen38-nemotron-super.service", "nemotron-super"), ("qwen38-kolibri.service", "kolibri"),
("qwen38-sglang.service", "stock")):
# the embeddings lane holds 1 GiB of its own, and its model's file is pages the kernel may take back
self.assertEqual(self.warned("embeddings", 40, {unit: ["ready", target], embed: "stopped"}, boot=unit)["warns"], [], unit)
for unit, target in (("qwen38-kolibri.service", "kolibri-nvfp4"), ("qwen38-sglang.service", "stock")):
self.assertEqual(self.warned("clipstral", 40, {unit: ["ready", target], clip: "stopped"}, boot=unit)["warns"], [], unit)
def test_a_lane_loaded_while_they_run_is_told_what_they_keep(self):
both = {"qwen38-sglang.service": "stopped", "qwen38-embed.service": "ready", "qwen38-clipstral.service": "ready"}
r = self.warned("stock", 108, both)
self.assertEqual(len(r["warns"]), 1, r)
self.assertIn("run beside every lane and keep their memory: a lane loaded now gets a smaller KV cache, or leaves the box less.", r["warns"][0])
self.assertIn("Stop them first to give it everything.", r["warns"][0])
one = dict(both, **{"qwen38-clipstral.service": "stopped"})
r = self.warned("stock", 112, one)
self.assertIn("pplx-embed v1 0.6B runs beside every lane and keeps its memory", r["warns"][0])
self.assertEqual(self.warned("stock", 116, dict(one, **{"qwen38-embed.service": "stopped"}))["warns"], [])
# beside a lane that leaves the box little by itself, the way is to stop them
r = self.warned("flash", 108, {"qwen38-flash.service": "stopped", **both})
self.assertIn("This one leaves the box as little as 6.9 GiB by itself: stop them first.", r["warns"][0])
self.assertFalse([s for s in r["steps"] if "Stop Mistral" in s], "the flash lane sizes itself by what is left")
def test_a_lane_with_a_fixed_share_and_little_left_stops_the_clipstral_lane_first(self):
runs = {"qwen38-embed.service": "ready", "qwen38-clipstral.service": "ready"}
for unit, target, stops in (("qwen38-nemotron-super.service", "nemotron-super", True), ("qwen38-kolibri.service", "kolibri", True),
("qwen38-kolibri.service", "kolibri-nvfp4", False), ("qwen38-sglang.service", "stock", False)):
r = self.warned(target, 108, {unit: ["stopped", target], **runs})
at = [i for i, s in enumerate(r["steps"]) if "systemctl stop qwen38-clipstral.service" in s]
self.assertEqual(bool(at), stops, (target, r["steps"]))
if stops:
self.assertIn(f"systemctl start {unit}", r["steps"][at[0] + 1])
self.assertIn("pplx-embed v1 0.6B runs beside every lane and keeps its memory", r["warns"][0])
self.assertFalse([s for s in r["steps"] if "systemctl stop qwen38-embed.service" in s], r["steps"])
self.assertFalse([s for s in self.warned("nemotron-super", 112, {"qwen38-nemotron-super.service": ["stopped", "nemotron-super"],
"qwen38-clipstral.service": "stopped"})["steps"] if "clipstral" in s])
def test_the_qwen4_lane_takes_the_box_alone(self):
# decision 1725 (Hasan): its Load stops every lane beside first, the embeddings lane too, and no lane beside starts while it
# serves or is the boot lane, which their units' heads refuse
runs = {"qwen38-embed.service": "ready", "qwen38-clipstral.service": "ready"}
r = self.warned("qwen4-35b", 108, {"qwen38-qwen4-35b.service": ["stopped", "qwen4-35b"], **runs})
start = [i for i, s in enumerate(r["steps"]) if "systemctl start qwen38-qwen4-35b.service" in s]
for b in ("qwen38-embed.service", "qwen38-clipstral.service"):
stop = [i for i, s in enumerate(r["steps"]) if f"systemctl stop {b}" in s]
self.assertTrue(stop and start and stop[0] < start[0], (b, r["steps"]))
self.assertEqual(r["warns"], [], "every lane beside stops first: nothing is left to keep its memory")
for target, unit in (("embeddings", "qwen38-embed.service"), ("clipstral", "qwen38-clipstral.service")):
for state in ("ready", "stopped"):
w = self.warned(target, 40, {"qwen38-qwen4-35b.service": [state, "qwen4-35b"], unit: "stopped"},
boot="qwen38-qwen4-35b.service")["warns"]
self.assertEqual(len(w), 1, (target, state, w))
self.assertIn("Qwen4 35B-A3B takes the box alone, its KV cache holding its whole window: this lane does not start "
"beside it, nor while it is the boot lane.", w[0])
# beside another lane the embeddings lane starts as before
self.assertEqual(self.warned("embeddings", 40, {"qwen38-sglang.service": ["ready", "stock"], "qwen38-embed.service": "stopped"},
boot="qwen38-sglang.service")["warns"], [])
def test_what_the_window_says_of_those_lanes_is_what_their_pages_give(self):
for page, said in (("flash-lane.md", "(MemAvailable sampled throughout, floor 6.9 GiB)"),
("nemotron-super-lane.md", "| MemAvailable, lowest seen | 9.1 GiB "), ("kolibri-lane.md", "| MemAvailable, lowest seen | 10.9 GiB |"),
("qwen4-35b-lane.md", "MemAvailable, lowest seen: 13.5 GiB")):
self.assertIn(said, (REPO / "docs" / page).read_text(), page)
js = (REPO / "dashboard" / "static" / "js" / "base.js").read_text()
self.assertIn("({[UFLASH]: 6.9, [NEMOTRON_SUPER_UNIT]: 9.1, [QWEN4_35B_UNIT]: 13.5})[unit] || (unit === KOLIBRI_UNIT && target === 'kolibri' ? 10.9 : 0)", js)
def test_a_start_the_box_had_too_little_memory_for_says_that(self):
"""Its card and its bay read "cannot start: a file is missing", the word of another refusal (review of v1.60.0). And a lane
beside whose model is missing is said whichever lane serves: that banner waited until none did."""
why = "the box had 9 GiB of memory available and this lane starts with 11 GiB at least"
r = pagejs.run(self, HELPERS + r"""
const units = JSON.parse(JSON.stringify(UNITS.units)), seen = {};
for (const k of ['room', 'lacks']){
feed({config: CONFIG, units: {units}, lifecycle: life({'qwen38-sglang.service': eng('ready'), 'qwen38-embed.service': eng('failed', {kind: 'embed', [k]: %s})})});
showView('lanes');
seen[k] = {label: stateLabel(engines()['qwen38-embed.service']), card: LCARDS.get('qwen38-embed.service').why.textContent, banners: txt('banners')};
}
report(seen);
""" % json.dumps(why))
self.assertEqual(r["room"]["label"], "not started: too little memory")
self.assertEqual(r["room"]["card"], why[0].upper() + why[1:] + ".")
self.assertNotIn("pplx-embed", r["room"]["banners"])
self.assertEqual(r["lacks"]["label"], "cannot start: a file is missing")
self.assertIn("pplx-embed v1 0.6B cannot start: a file it reads is missing.", r["lacks"]["banners"])
def test_prepared_its_load_enables_and_starts_only(self):
r = self.journey(True)
self.assertEqual(len(r["steps"]), 2, r["steps"])
self.assertIn("Enable", r["steps"][0])
self.assertIn("Start", r["steps"][1])
def test_an_update_that_waited_goes_in_place_before_it_starts(self):
r = self.journey(True, pending=["its new image"])
self.assertEqual(len(r["steps"]), 4, r["steps"])
self.assertIn("Download", r["steps"][0])
self.assertIn("Put in place", r["steps"][1])
self.assertIn("Enable", r["steps"][2])
self.assertIn("Start", r["steps"][3])
class ItsLoadAppliesWhatWaitsOnTheLaneThatRuns(unittest.TestCase):
"""The lane's Load of an update while it runs: its preparation, apply_pending, then a start, which systemd
answers with success on an active unit and which applies nothing, so the lane went on serving the unit it
started with; a wait the cockpit marks stale (the unit in place changed since) was prepared and posed anyway,
where every other lane's Load leaves it; and a lane running up to date, enabled at boot, was enabled and
started again (code review of v1.60.0). The Load restarts a lane that runs when an update waits for it or one
left it owed, starts one that does not, enables one the boot does not start, and has nothing to do else."""
def journey(self, running, enabled, pending=None, owed=False):
return pagejs.run(self, HELPERS + r"""
const a = %s;
const units = JSON.parse(JSON.stringify(UNITS.units));
units['qwen38-embed.service'] = {active: a.running ? 'active' : 'inactive', enabled: a.enabled ? 'enabled' : 'disabled'};
const engines = {'qwen38-sglang.service': eng('ready'),
'qwen38-embed.service': eng(a.running ? 'ready' : 'stopped', {target: 'embeddings', kind: 'embed'})};
feed({config: CONFIG, units: {units}, lifecycle: life(engines), lanes_ready: {embeddings: true},
pending: a.pending ? {'qwen38-embed.service': a.pending} : {},
update: a.owed ? {stale_engines: {'qwen38-embed.service': 'Its unit changed (what it runs and how)'}} : {}});
askJourney('embeddings');
report({steps: [...$('sh-journey').children].map(li => li.textContent), open: !$('scrim').hidden, toast: txt('toasts')});
""" % json.dumps({"running": running, "enabled": enabled, "pending": pending, "owed": owed}))
def kinds(self, r):
return [next((w for w in ("Download", "Put in place", "Enable", "Restart", "Start") if w in s), s) for s in r["steps"]]
def test_an_update_that_waits_for_the_lane_that_runs_restarts_it(self):
r = self.journey(running=True, enabled=True, pending=["image lmsysorg/sglang@sha256:" + "c" * 64])
self.assertEqual(self.kinds(r), ["Download", "Put in place", "Restart"], r["steps"])
self.assertIn("systemctl restart qwen38-embed.service", r["steps"][-1])
r = self.journey(running=True, enabled=False, pending=["image x"])
self.assertEqual(self.kinds(r), ["Download", "Put in place", "Enable", "Restart"], r["steps"])
def test_an_update_an_install_left_owed_restarts_it(self):
r = self.journey(running=True, enabled=True, owed=True)
self.assertEqual(self.kinds(r), ["Restart"], r["steps"])
def test_a_lane_that_runs_up_to_date_has_nothing_to_load(self):
r = self.journey(running=True, enabled=True)
self.assertEqual(r["steps"], [])
self.assertFalse(r["open"], r)
self.assertIn("is already serving", r["toast"])
def test_a_stale_wait_is_neither_downloaded_nor_posed(self):
stale = ["stale: the unit in place changed since this update waited (a switch); it is dropped, ./install.sh writes it again"]
r = self.journey(running=False, enabled=False, pending=stale)
self.assertEqual(self.kinds(r), ["Enable", "Start"], r["steps"])
class ItsLoadWaitsOnlyAfterAStop(unittest.TestCase):
"""The Load runs its steps one after the other, and after a step that stops a lane it waits for that lane to
read down, since a start of another one is refused until then. It waited after every step of a unit whose verb
was not "start": the enable of the lane's Load, on a lane already running, held the next step for its whole
90 s, the lane never going down (code review of v1.60.0)."""
def test_the_step_after_its_enable_runs_at_once(self):
r = pagejs.run(self, HELPERS + r"""
let jobs = 0;
__fetch = async url => url === '/api/csrf' ? __response(200, {token: 't'})
: url === '/api/action' ? __response(202, {job: 'j' + (++jobs)})
: new Promise(() => {});
const units = JSON.parse(JSON.stringify(UNITS.units));
feed({config: CONFIG, units: {units}, lanes_ready: {embeddings: true},
update: {stale_engines: {'qwen38-embed.service': 'Its unit changed (what it runs and how)'}},
lifecycle: life({'qwen38-sglang.service': eng('ready'),
'qwen38-embed.service': eng('ready', {target: 'embeddings', kind: 'embed'})})});
askJourney('embeddings');
const steps = [...$('sh-journey').children].map(li => li.textContent);
$('sh-go').click(); await __settle(); await __advance(1000);
feed({job: {current: null, recent: [{id: 'j1', action: 'unit', status: 'done', rc: 0, elapsed: 1}]}});
await __advance(2000); await __settle(); await __advance(2000);
report({steps, verbs: __fetches.filter(f => f.url === '/api/action').map(f => JSON.parse(f.init.body).params.verb)});
""")
self.assertEqual(len(r["steps"]), 2, r["steps"])
self.assertIn("Enable", r["steps"][0])
self.assertEqual(len(r["verbs"]), 2, f"the step after the enable waited for the lane to stop: {r}")
self.assertEqual(r["verbs"][0], "enable")
class ItIsNeverTheLaneThatServes(unittest.TestCase):
"""The lane runs beside whichever lane serves, on the CPU: it is no lane of the GPU's turn. Its card and its
state are in the lifecycle like any lane's, and the page took it for the lane that serves when no lane of the
GPU did, and for the boot lane when none of them was enabled: a Load of the 27B stopped it first, the text
actions read a text engine ready on a closed :30000, the cards of the GPU lanes hid their Start, and the spine
named it as what serves (code review of v1.60.0)."""
BOX = r"""
const units = JSON.parse(JSON.stringify(UNITS.units));
units['qwen38-sglang.service'] = {active: 'inactive', enabled: 'disabled'};
units['qwen38-embed.service'] = {active: 'active', enabled: 'enabled'};
"""
def test_with_no_lane_of_the_gpu_serving_nothing_serves_and_nothing_boots(self):
r = pagejs.run(self, HELPERS + self.BOX + r"""
feed({config: CONFIG, units: {units}, lanes_ready: {embeddings: true},
lifecycle: life({'qwen38-sglang.service': eng('stopped'),
'qwen38-embed.service': eng('ready', {target: 'embeddings', kind: 'embed'})})});
const start27 = LCARDS.get('qwen38-sglang.service').start;
const seen = {serving: servingEngine(), boot: bootUnit(), text: textReady(), why: noEngineWhy(),
start27: start27.hidden ? null : start27.textContent, name: txt('serving-name')};
askJourney('stock');
report(Object.assign(seen, {steps: [...$('sh-journey').children].map(li => li.textContent)}));
""")
self.assertIsNone(r["serving"], r)
self.assertIsNone(r["boot"], r)
self.assertFalse(r["text"], r)
self.assertIn("No text engine is serving", r["why"])
self.assertEqual(r["start27"], "Start Qwen3.8 27B as installed")
self.assertEqual(r["name"], "Nothing is serving")
self.assertTrue(r["steps"], r)
for step in r["steps"]:
self.assertNotIn("pplx-embed", step, "the Load of the 27B stops nothing beside it")
self.assertIn("systemctl start qwen38-sglang.service", r["steps"][-1])
def test_its_journal_is_its_own_while_another_lane_serves(self):
"""The card's Journal opens the lane's own source: while it ran, it opened the 27B's container log, the source of
every lane the page's list did not name (found on 2026-12-01, before the lane was released)."""
r = pagejs.run(self, HELPERS + self.BOX + r"""
const seen = {};
for (const [u, target] of [['qwen38-embed.service', 'embeddings'], ['qwen38-clipstral.service', 'clipstral']])
for (const state of ['ready', 'stopped']){
units[u] = {active: state === 'ready' ? 'active' : 'inactive', enabled: 'enabled'};
feed({config: CONFIG, units: {units}, lanes_ready: {embeddings: true, clipstral: true},
lifecycle: life({'qwen38-sglang.service': eng('ready'), [u]: eng(state, {target, kind: 'embed'})})});
showView('lanes'); LCARDS.get(u).logs.click();
seen[`${target} ${state}`] = $('log-src').value;
}
report(seen);
""")
self.assertEqual(r, {"embeddings ready": "qwen38-embed", "embeddings stopped": "qwen38-embed.service",
"clipstral ready": "qwen38-clipstral", "clipstral stopped": "qwen38-clipstral.service"})
def test_its_card_is_one_that_serves_while_it_runs(self):
"""Each of the two lanes beside, with a lane of the GPU serving and with none: its card read "Load" beside "Stop" and its
bay "Load this lane" while it served, since the one seat the page knew was the GPU's (found on 2026-12-01)."""
r = pagejs.run(self, HELPERS + r"""
const out = {}, units = JSON.parse(JSON.stringify(UNITS.units));
const see = (u, t, state, gpu, more) => {
units['qwen38-sglang.service'].active = gpu === 'ready' ? 'active' : 'inactive';
units[u] = {active: state === 'ready' ? 'active' : 'inactive', enabled: 'enabled'};
feed(Object.assign({config: CONFIG, units: {units}, lanes_ready: {embeddings: true, clipstral: true}, update: {}, pending: {},
lifecycle: life({'qwen38-sglang.service': eng(gpu), [u]: eng(state, {target: t, kind: 'embed'})})}, more || {}));
const c = LCARDS.get(u), b = BAYS.get(u);
return {title: c.h.textContent, load: c.load.hidden ? null : c.load.textContent, start: c.start.hidden ? null : c.start.textContent,
stop: c.stop.hidden ? null : c.stop.textContent, act: b.act.textContent, seated: b.root.classList.contains('seated'),
gpu: BAYS.get('qwen38-sglang.service').act.textContent};
};
for (const [u, t] of [['qwen38-embed.service', 'embeddings'], ['qwen38-clipstral.service', 'clipstral']])
out[t] = {serves: see(u, t, 'ready', 'ready'), alone: see(u, t, 'ready', 'stopped'), starts: see(u, t, 'loading', 'ready'), stopped: see(u, t, 'stopped', 'ready'),
failed: see(u, t, 'failed', 'ready'), owed: see(u, t, 'ready', 'ready', {update: {stale_engines: {[u]: 'its unit changed'}}})};
showView('now'); see('qwen38-embed.service', 'embeddings', 'ready', 'ready'); BAYS.get('qwen38-embed.service').root.click();
out.click = {view: document.querySelector('.view.active').id, sheet: !$('scrim').hidden};
report(out);
""")
for t in ("embeddings", "clipstral"):
for state in ("serves", "alone"):
with self.subTest(lane=t, state=state):
x = r[t][state]
self.assertTrue(x["title"].endswith(", serving"), x)
self.assertEqual((x["load"], x["start"], x["act"], x["seated"]), (None, None, "Details", True), x)
self.assertTrue(x["stop"].startswith("Stop "), x)
self.assertEqual((r[t]["starts"]["load"], r[t]["starts"]["seated"], r[t]["starts"]["act"]), (None, False, "Details"), r[t])
self.assertTrue(r[t]["stopped"]["load"].startswith("Load "), r[t])
self.assertEqual((r[t]["stopped"]["act"], r[t]["stopped"]["stop"], r[t]["stopped"]["seated"]), ("Load this lane", None, False), r[t])
self.assertTrue(r[t]["failed"]["load"].startswith("Load "), r[t])
self.assertRegex(r[t]["owed"]["load"], "^Restart .* to apply the update$")
self.assertEqual((r[t]["serves"]["gpu"], r[t]["alone"]["gpu"]), ("Open the agent", "Load this lane"), "the GPU's lane keeps its own")
self.assertEqual(r["click"], {"view": "view-lanes", "sheet": False})
def test_its_own_start_is_offered_while_a_lane_of_the_gpu_serves(self):
r = pagejs.run(self, HELPERS + r"""
const units = JSON.parse(JSON.stringify(UNITS.units));
feed({config: CONFIG, units: {units}, lanes_ready: {embeddings: true},
lifecycle: life({'qwen38-sglang.service': eng('ready'),
'qwen38-embed.service': eng('stopped', {target: 'embeddings', kind: 'embed'})})});
const c = LCARDS.get('qwen38-embed.service');
report({start: c.start.hidden ? null : c.start.textContent, serving: (servingEngine() || [])[0]});
""")
self.assertEqual(r["serving"], "qwen38-sglang.service")
self.assertEqual(r["start"], "Start pplx-embed v1 0.6B as installed")
def test_a_lane_that_cannot_start_is_said_while_it_alone_runs_beside(self):
# the banner of a lane of the GPU that cannot start is said while no other lane of the GPU is up,
# whose Load is the way out it names: the lane beside every lane is none of them
r = pagejs.run(self, HELPERS + self.BOX + r"""
feed({config: CONFIG, units: {units},
lifecycle: life({'qwen38-flash.service': eng('failed', {target: 'flash', cannot: 'its GPU is not in ATS mode'}),
'qwen38-embed.service': eng('ready', {target: 'embeddings', kind: 'embed'})})});
report(txt('banners'));
""")
self.assertIn("Qwen3.8 Flash-Next cannot start on this box.", r)
if __name__ == "__main__":
unittest.main()