Files
alzeo/tests/test_engine_inputs.py
T
Hasan BasbunarandClaude Opus 5.5 dbf649932b v1.21.0: an engine restart no longer ends a session, and no engine starts on memory still held
Issue #26 reported a 27B engine dying about once a day with "CUDA error:
operation not permitted", systemd starting it again 17 s later, and the
fear that the restart lands in the window sglang#40948 blames for a DGX
Spark frozen 9.5 h. Measured on the reference box: a crashed engine's
memory is back 2 to 5 s after it dies, about 15 s before the restart.

engine-preflight.sh runs before every engine (27B, flash, image, video)
and refuses a start while what is left of an engine holds GPU memory,
while the driver holds more than 16 GiB that no process accounts for,
or while nvidia-smi does not answer; systemd tries again every 15 s.

The proxy (v6.28) holds a request while its engine comes back, through
a restart's stop half too, up to 1200 s: a streamed one gets its 200
and the keepalives at once. On a 503, opencode gave up after 151 s and
Claude Code after 325 s; both wait on a held stream (900 s measured).
An engine's mid-stream cut is passed on as a cut: the error event sent
in its place made Claude Code retry without a stream, give up on it
after about 330 s, and end with no answer.

The cockpit restarts an SGLang server left without its scheduler, once
it has been so for 2 min (COCKPIT_ZOMBIE_RESTART), tells one crash of a
serving lane from a boot that keeps dying, and says why a start waits
or was refused.

Tested end to end on the reference box: the flash lane's server sent
SIGQUIT under the real opencode and Claude Code, twice. The runs found
four faults the unit tests could not (a zombie probe docker refused, a
watched boot read as a boot again, a restart that ended the waits, the
cut's error event), each fixed with a test that fails without the fix.
After 632 to 1,068 s held, both clients got their whole answers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 23:20:35 +02:00

314 lines
16 KiB
Python

#!/usr/bin/env python3
"""install.sh restarts the engine only when it has to.
It restarted it on every run, so an update that changed nothing the engine reads still
cost a full boot: 8 min on the 27B, 12 on flash (reference box, 2026-09-23). The engine
is now kept when it started after every file it reads was last written, the run changed
none of them by content, and it answers. These pin engine-inputs.py (what the engine
reads, found from its unit) and the installer's own decision lines, run as written,
against fake systemctl, docker, python3 and curl."""
import os
import pathlib
import subprocess
import sys
import tempfile
import time
import unittest
REPO = pathlib.Path(__file__).resolve().parents[1]
TOOL = REPO / "engine-inputs.py"
DIGEST = "lmsysorg/sglang@sha256:" + "a" * 64
FAKE_DOCKER = """#!/bin/sh
# docker image inspect --format {{.Id}} REF | docker inspect --format {{.Image}} NAME
if [ "$1" = image ]; then v=$(grep -F "$5=" "$FAKE_IMAGES" | head -1 | cut -d= -f2-); else v=$(grep -F "container:$4=" "$FAKE_IMAGES" | head -1 | cut -d= -f2-); fi
[ -n "$v" ] || exit 1
echo "$v"
"""
# systemd prints the epoch only when asked for it (--timestamp=unix, systemd >= 248), and a
# local date otherwise: a fake that always printed the epoch let the flag go unnoticed
# (found in review, 2026-09-24)
FAKE_SYSTEMCTL = """#!/bin/sh
echo "ActiveState=$FAKE_ACTIVE"
case " $* " in
*" --timestamp=unix "*) echo "ExecMainStartTimestamp=@$FAKE_STARTED" ;;
*) echo "ExecMainStartTimestamp=$(date -d "@$FAKE_STARTED" '+%a %Y-%m-%d %H:%M:%S %Z')" ;;
esac
"""
class Box:
"""A config dir, an HF cache and a unit, the way the installer lays them out."""
def __init__(self, flash=False):
self.t = pathlib.Path(tempfile.mkdtemp(prefix="engine-in-"))
self.cfg = self.t / "cfg"
self.cfg.mkdir()
self.hf = self.t / "hf"
(self.cfg / "api-key").write_text("k\n")
snap = self.hf / "hub" / "models--org--model" / "snapshots" / "rev1"
snap.mkdir(parents=True)
(snap / "config.json").write_text('{"rope_scaling": null}\n')
self.config_json = snap / "config.json"
self.unit = self.t / ("qwen38-flash.service" if flash else "qwen38-sglang.service")
if flash:
(self.cfg / "chat-template-flashnext.jinja").write_text("{{ x }}\n")
(self.cfg / "token-map-65536.pt").write_bytes(b"\x00\x01")
(self.cfg / "launch-flash.sh").write_text(
f"docker run --name qwen38-flash -v {self.cfg}:/out {DIGEST} "
f"--chat-template /out/chat-template-flashnext.jinja "
f"--speculative-token-map /out/token-map-65536.pt --api-key $(cat {self.cfg}/api-key)\n")
self.unit.write_text(f"[Service]\nExecStart=/bin/bash {self.cfg}/launch-flash.sh\n")
self.template = self.cfg / "chat-template-flashnext.jinja"
else:
(self.cfg / "chat-template-sglang.jinja").write_text("{{ x }}\n")
self.unit.write_text(
f"[Service]\nExecStart=/bin/bash -c 'exec docker run --name qwen38-sglang -v {self.cfg}:/out "
f"{DIGEST} --chat-template /out/chat-template-sglang.jinja "
f"--api-key \"$(cat {self.cfg}/api-key)\"'\n")
self.template = self.cfg / "chat-template-sglang.jinja"
self.bin = self.t / "bin"
self.bin.mkdir()
for name, body in (("docker", FAKE_DOCKER), ("systemctl", FAKE_SYSTEMCTL)):
(self.bin / name).write_text(body)
(self.bin / name).chmod(0o755)
self.images = self.t / "images"
container = "qwen38-flash" if flash else "qwen38-sglang"
self.images.write_text(f"{DIGEST}=sha256:img1\ncontainer:{container}=sha256:img1\n")
self.active, self.started = "active", int(time.time()) + 5
def run(self, mode, ckpt="org/model@rev1"):
env = {"PATH": f"{self.bin}:/usr/bin:/bin", "FAKE_IMAGES": str(self.images),
"FAKE_ACTIVE": self.active, "FAKE_STARTED": str(self.started)}
r = subprocess.run([sys.executable, str(TOOL), mode, str(self.unit), str(self.cfg), str(self.hf),
ckpt], capture_output=True, text=True, env=env, timeout=30)
assert r.returncode == 0, r.stderr
return r.stdout.strip()
class WhatTheEngineReads(unittest.TestCase):
def test_the_27b_unit_names_its_template_key_checkpoint_and_image(self):
box = Box()
out = subprocess.run([sys.executable, "-c",
"import importlib.util,sys; s=importlib.util.spec_from_file_location('e', sys.argv[1]);"
"m=importlib.util.module_from_spec(s); s.loader.exec_module(m);"
"f,i,c=m.inputs(*sys.argv[2:5], ['org/model@rev1']); print(f); print(i); print(c)",
str(TOOL), str(box.unit), str(box.cfg), str(box.hf)], capture_output=True, text=True)
files = out.stdout.splitlines()[0]
for p in (box.unit, box.template, box.cfg / "api-key", box.config_json):
self.assertIn(str(p), files)
self.assertIn(DIGEST, out.stdout.splitlines()[1])
self.assertIn("qwen38-sglang", out.stdout.splitlines()[2])
def test_the_guard_the_unit_runs_first_is_no_input(self):
"""Every engine unit runs engine-preflight.sh before it starts the engine, which never
reads it: a new guard, or one rewritten after the start, must not restart a healthy
engine. Both lookups found it, the scripts the unit runs and the config files it names."""
for flash in (False, True):
with self.subTest(flash=flash):
box = Box(flash=flash)
guard = box.cfg / "engine-preflight.sh"
guard.write_text("#!/usr/bin/env bash\necho guard one\n")
box.unit.write_text(box.unit.read_text().replace(
"[Service]\n", f"[Service]\nExecStartPre=/bin/bash {guard} {box.unit.name}\n"))
fp = box.run("fingerprint")
guard.write_text("#!/usr/bin/env bash\necho guard two\n")
self.assertEqual(box.run("fingerprint"), fp)
later = time.time() + 600
os.utime(guard, (later, later))
self.assertTrue(box.run("running").startswith("yes"), box.run("running"))
def test_the_flash_unit_brings_in_its_launcher_and_what_it_names(self):
box = Box(flash=True)
fp = box.run("fingerprint")
(box.cfg / "token-map-65536.pt").write_bytes(b"\x00\x02")
self.assertNotEqual(box.run("fingerprint"), fp, "the token map named by the launcher is an input")
fp = box.run("fingerprint")
(box.cfg / "launch-flash.sh").write_text((box.cfg / "launch-flash.sh").read_text() + "# a flag\n")
self.assertNotEqual(box.run("fingerprint"), fp, "the launcher itself is an input")
class RefsAndMovingTags(unittest.TestCase):
"""Two documented settings kept a stale engine under "nothing it reads changed" (found in
review, 2026-09-24): a revision given as a branch (MODEL_REV=main), whose snapshot is
named by the commit its ref holds, so neither snapshots/main/config.json (it never
exists) nor the ref counted; and an image given by a tag that moves, which neither of
the image patterns matched."""
def test_a_branch_revision_reads_the_config_of_the_commit_it_names(self):
box = Box()
refs = box.hf / "hub" / "models--org--model" / "refs"
refs.mkdir()
(refs / "main").write_text("rev1")
fp = box.run("fingerprint", "org/model@main")
box.config_json.write_text('{"rope_scaling": {"type": "yarn"}}\n') # a YaRN patch
self.assertNotEqual(box.run("fingerprint", "org/model@main"), fp)
def test_a_branch_that_moves_is_a_change(self):
box = Box()
refs = box.hf / "hub" / "models--org--model" / "refs"
refs.mkdir()
(refs / "main").write_text("rev1")
fp = box.run("fingerprint", "org/model@main")
snap2 = box.hf / "hub" / "models--org--model" / "snapshots" / "rev2"
snap2.mkdir()
(snap2 / "config.json").write_text('{"rope_scaling": null, "new": 1}\n')
(refs / "main").write_text("rev2") # a download moved main
self.assertNotEqual(box.run("fingerprint", "org/model@main"), fp)
def test_an_image_named_by_a_tag_that_moves_is_a_change(self):
box = Box()
box.unit.write_text("[Service]\nExecStart=/bin/bash -c 'exec docker run --name qwen38-sglang "
f"-v {box.cfg}:/out \\\n lmsysorg/sglang:v0.5.19 \\\n python3 -m sglang.launch_server "
"--chat-template /out/chat-template-sglang.jinja'\n")
box.images.write_text("lmsysorg/sglang:v0.5.19=sha256:img1\ncontainer:qwen38-sglang=sha256:img1\n")
fp = box.run("fingerprint")
self.assertEqual(box.run("running"), "yes")
box.images.write_text("lmsysorg/sglang:v0.5.19=sha256:img2\ncontainer:qwen38-sglang=sha256:img1\n")
self.assertNotEqual(box.run("fingerprint"), fp, "a pull that moved the tag is a change")
self.assertIn("another image", box.run("running"))
class TheFingerprintIsByContent(unittest.TestCase):
def test_a_changed_template_changes_it(self):
box = Box()
fp = box.run("fingerprint")
box.template.write_text("{{ y }}\n")
self.assertNotEqual(box.run("fingerprint"), fp)
def test_a_file_rewritten_identically_does_not(self):
box = Box()
fp = box.run("fingerprint")
box.template.write_text(box.template.read_text())
os.utime(box.config_json, None)
self.assertEqual(box.run("fingerprint"), fp)
def test_a_yarn_patch_in_the_checkpoint_changes_it(self):
box = Box()
fp = box.run("fingerprint")
box.config_json.write_text('{"rope_scaling": {"type": "yarn", "factor": 4.0}}\n')
self.assertNotEqual(box.run("fingerprint"), fp)
def test_an_image_that_moved_under_its_name_changes_it(self):
box = Box()
fp = box.run("fingerprint")
box.images.write_text(box.images.read_text().replace(f"{DIGEST}=sha256:img1", f"{DIGEST}=sha256:img2"))
self.assertNotEqual(box.run("fingerprint"), fp)
class TheRunningVerdict(unittest.TestCase):
def test_an_engine_started_after_everything_it_reads_has_it(self):
self.assertEqual(Box().run("running"), "yes")
def test_a_file_written_after_the_start_is_not_in_the_running_engine(self):
box = Box()
box.started = int(time.time()) - 100
self.assertRegex(box.run("running"), r"^no: .* changed after qwen38-sglang.service started$")
def test_a_file_written_in_the_second_the_engine_started_is_in_it(self):
# The installer writes the unit, then restarts the engine in the same second, and
# systemd gives the start in whole seconds: compared with the file's fraction, the
# run after every first install restarted an engine that had everything (the
# reference box, 2026-09-30).
box = Box()
t = int(time.time()) - 100
for f in (box.unit, box.template, box.cfg / "api-key", box.config_json):
os.utime(f, (t + 0.9, t + 0.9))
box.started = t
self.assertEqual(box.run("running"), "yes")
def test_a_file_written_the_second_after_the_start_is_not(self):
box = Box()
t = int(time.time()) - 100
for f in (box.unit, box.template, box.cfg / "api-key", box.config_json):
os.utime(f, (t, t))
os.utime(box.template, (t + 1.1, t + 1.1))
box.started = t
self.assertRegex(box.run("running"),
r"^no: .*chat-template-sglang\.jinja changed after qwen38-sglang\.service started$")
def test_a_stopped_engine_has_nothing(self):
box = Box()
box.active = "inactive"
self.assertEqual(box.run("running"), "no: qwen38-sglang.service is inactive")
def test_a_container_on_another_image_does_not_run_this_one(self):
box = Box()
box.images.write_text(box.images.read_text().replace("container:qwen38-sglang=sha256:img1",
"container:qwen38-sglang=sha256:old"))
self.assertIn("runs another image", box.run("running"))
class TheInstallerDecides(unittest.TestCase):
"""Step 9's own lines, with engine-inputs.py and curl stubbed by their answers."""
def decide(self, running="yes", fp_before="F1", fp_after="F1", health=True, restart=None):
text = (REPO / "install.sh").read_text()
start = text.index("# Kept only when the running engine started after every file it reads")
end = text.index('[ "$ENGINE_KEEP" -eq 1 ] || sudo systemctl restart "$UNIT_NAME"')
t = pathlib.Path(tempfile.mkdtemp(prefix="engine-decide-"))
(t / "python3").write_text(f'#!/bin/sh\necho "{fp_after}"\n')
(t / "curl").write_text(f"#!/bin/sh\nexit {0 if health else 22}\n")
for n in ("python3", "curl"):
(t / n).chmod(0o755)
script = ("set -euo pipefail\nstep(){ echo \"STEP $*\"; }\n"
f'ENGINE_RUNNING_IT="{running}"; ENGINE_FP_BEFORE="{fp_before}"; LANE=27b; PORT=30000\n'
'REPO_DIR=/r; ENGINE_UNIT_PATH=/u; CONFIG_DIR=/c; HF_CACHE=/h; ENGINE_CKPTS=(a@b); OTHER_UNIT=""\n'
+ (f"RESTART_ENGINE={restart}\n" if restart else "")
+ text[start:end] + 'echo "KEEP=$ENGINE_KEEP"\n')
r = subprocess.run(["bash", "-c", script], capture_output=True, text=True, timeout=30,
env={"PATH": f"{t}:/usr/bin:/bin"})
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
return r.stdout
def test_nothing_changed_keeps_the_engine(self):
out = self.decide()
self.assertIn("KEEP=1", out)
self.assertIn("STEP 9/10 Keeping the running engine", out)
self.assertNotIn("why:", out)
def test_a_run_that_changed_an_input_restarts_it(self):
out = self.decide(fp_after="F2")
self.assertIn("KEEP=0", out)
self.assertIn("why: this run changed what it reads", out)
def test_an_engine_that_predates_an_input_restarts_it(self):
out = self.decide(running="no: /c/chat-template-sglang.jinja changed after qwen38-sglang.service started")
self.assertIn("KEEP=0", out)
self.assertIn("why: /c/chat-template-sglang.jinja changed after", out)
def test_an_engine_that_does_not_answer_restarts_it(self):
self.assertIn("why: it does not answer /health", self.decide(health=False))
def test_restart_engine_1_always_restarts(self):
out = self.decide(restart="1")
self.assertIn("KEEP=0", out)
self.assertIn("why: RESTART_ENGINE=1", out)
def test_what_the_engine_reads_is_rewritten_only_when_it_changes(self):
# A rewrite, even an identical one, dates the file after the engine's start, and
# the next run restarted it: on the reference box every second run did, until the
# unit and the flash launcher were compared first (the template, in patch-template.py).
text = (REPO / "install.sh").read_text()
self.assertIn('cmp -s "$TMP_UNIT" "/etc/systemd/system/$UNIT_NAME" || sudo install -m 644 "$TMP_UNIT"', text)
# the launcher is installed in the branch where the comparison found a difference,
# and only there (it also says which of the two happened, since 2026-09-30)
self.assertRegex(text, r'if cmp -s "\$TMP_LAUNCH" "\$CONFIG_DIR/launch-flash\.sh"; then\n'
r'\s*echo "launch script unchanged[^\n]*\n\s*else\n'
r'\s*install -m 755 "\$TMP_LAUNCH" "\$CONFIG_DIR/launch-flash\.sh"\n')
self.assertEqual(text.count('install -m 755 "$TMP_LAUNCH"'), 1, "no other path writes the launcher")
def test_the_restart_itself_is_the_one_the_decision_guards(self):
self.assertIn('[ "$ENGINE_KEEP" -eq 1 ] || sudo systemctl restart "$UNIT_NAME"',
(REPO / "install.sh").read_text())
def test_a_first_install_just_starts_it(self):
out = self.decide(running="no: not installed yet", fp_before="")
self.assertIn("KEEP=0", out)
self.assertNotIn("why:", out)
self.assertIn("STEP 9/10 Starting", out)
if __name__ == "__main__":
unittest.main(verbosity=2)