Files
alzeo/tests/vector_lanes.py
T

468 lines
30 KiB
Python

"""The two CPU embedding lanes' installers have one shape (install-clipstral.sh, install-embeddings.sh): what holds of one holds
of the other, and is tested here for both (test_clipstral_lane.py and test_embed_lane.py give it their lane as L).
This repo's own server on the CPU, in the 27B lane's image, beside every lane: no Conflicts=, no key, 127.0.0.1 alone, no
GPU, a container that writes nothing and has no rights but to read, capped by its cgroup and pinned to the A725 cores.
--stage runs the installer as written, in a throwaway home, with no sudo and no docker."""
import hashlib
import os
import pathlib
import re
import shutil
import subprocess
import tempfile
import time
REPO = pathlib.Path(__file__).resolve().parents[1]
PREFLIGHT = r'snap="([^"]+)"; for f in ([^;]+); do \[ -f "\$snap/\$f" \]'
class Lane:
def __init__(self, installer, unit, prefix, folder, key, title, port, code):
self.installer, self.unit, self.prefix, self.folder = REPO / installer, unit, prefix, folder
self.key, self.title, self.port, self.code = key, title, port, code
self.text, self.template = self.installer.read_text(), (REPO / f"{unit}.template").read_text()
self.pins = {k: v.strip('"') for k, v in (ln.split("=", 1) for ln in self.text.splitlines() if re.match(rf"^{prefix}_[A-Z_]+=", ln))}
self.model, self.rev, self.image = self.pin("MODEL"), self.pin("REV"), self.pin("IMAGE")
self.code_id = hashlib.sha256(b"".join((REPO / f).read_bytes() for f in code)).hexdigest()[:12]
self.repo_dir = "models--" + self.model.replace("/", "--")
def pin(self, name):
return self.pins[f"{self.prefix}_{name}"]
CLIPSTRAL = Lane("install-clipstral.sh", "qwen38-clipstral.service", "CLIPSTRAL", "clipstral", "clipstral", "Mistral Multimodal Embed 1B", 30030,
("clipstral-server.py", "clipstral_model.py", "vectors_server.py", "cpu_layers.py"))
EMBED = Lane("install-embeddings.sh", "qwen38-embed.service", "EMBED", "embed", "embeddings", "pplx-embed v1 0.6B", 30028,
("pplx-server.py", "pplx_model.py", "vectors_server.py", "cpu_layers.py"))
def command(unit):
"""The ExecStart command as systemd runs it: the lines a backslash ends joined."""
i = unit.index("exec /usr/bin/docker run")
return unit[i:unit.index("'\n", unit.index("--port", i))].replace("\\\n", " ")
class Staged:
def setUp(self):
self.t = pathlib.Path(tempfile.mkdtemp(prefix="vector-lane-stage-"))
self.addCleanup(shutil.rmtree, self.t, True)
self.home, self.units, self.hf, self.out = self.t / "home", self.t / "units", self.t / "hf", self.t / "stage.service"
self.cfg = self.home / ".config" / "qwen38"
self.cfg.mkdir(parents=True)
self.units.mkdir()
def stage(self, **env):
r = subprocess.run(["bash", str(self.L.installer), "--stage", str(self.out)], capture_output=True, text=True, timeout=120,
env={"PATH": "/usr/bin:/bin", "HOME": str(self.home), "LANES_UNIT_DIR": str(self.units),
"HF_CACHE": str(self.hf), **env})
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
return self.out.read_text()
class UnitTests(Staged):
def test_it_runs_this_repos_server_on_the_27b_lanes_image_and_the_pinned_model(self):
unit = self.stage()
cmd = command(unit)
self.assertEqual(self.L.image, re.search(r'^IMAGE="\$\{IMAGE:-([^}]+)\}"', (REPO / "install.sh").read_text(), re.M).group(1),
"the 27B lane's image, by its digest")
self.assertIn(f"--entrypoint python3 {self.L.image} ", re.sub(r"\s+", " ", cmd))
self.assertIn(f"-I -B /{self.L.folder}/{self.L.code[0]}", cmd)
self.assertIn(f"--model-id /root/.cache/huggingface/hub/models--{self.L.model.replace('/', '--')}/snapshots/{self.L.rev} --revision {self.L.rev}", cmd)
self.assertRegex(self.L.rev, r"^[0-9a-f]{40}$")
self.assertIn(f"--threads {self.L.pin('THREADS')} --products {self.L.pin('PRODUCTS')}", cmd)
self.assertNotIn("__", re.sub(r"__pycache__", "", unit))
def test_the_code_it_runs_is_the_copy_named_by_its_content(self):
self.assertIn(f"--mount type=bind,source={self.cfg}/{self.L.folder}/{self.L.code_id},target=/{self.L.folder},readonly", command(self.stage()))
# a bind by --mount: a source that is not there fails the start, where -v makes a root-owned folder in its place
self.assertNotIn(f":/{self.L.folder}", self.L.template)
def test_no_key_loopback_only_and_no_gpu(self):
(self.cfg / "api-key").write_text("secret-of-the-box\n")
unit = self.stage()
cmd = command(unit)
self.assertNotIn("secret-of-the-box", unit)
self.assertNotIn("api-key", cmd)
self.assertIn(f"--host 127.0.0.1 --port {self.L.port}", cmd)
self.assertNotIn("--gpus", cmd)
self.assertIn("-e CUDA_VISIBLE_DEVICES= ", cmd)
self.assertNotIn("0.0.0.0", unit)
def test_its_container_writes_nothing_and_reads_what_it_is_given(self):
cmd = re.sub(r"\s+", " ", command(self.stage()))
for flag in ("--rm", "--read-only", "--cap-drop ALL", "--cap-add DAC_OVERRIDE", "--security-opt no-new-privileges", "--no-healthcheck",
"--tmpfs /tmp:size=64m", "-e HF_HUB_OFFLINE=1",
f"--mount type=bind,source={self.hf}/hub/{self.L.repo_dir},target=/root/.cache/huggingface/hub/{self.L.repo_dir},readonly"):
self.assertIn(flag, cmd, flag)
self.assertEqual(re.findall(r"--cap-add (\S+)", cmd), ["DAC_OVERRIDE"], "one right given back")
# the model's folder alone: the root of the cache holds the account's token (review of v1.60.0)
self.assertEqual(re.findall(r"-v \S+", cmd), [])
self.assertEqual(re.findall(r"source=([^,]+),", cmd), [f"{self.hf}/hub/{self.L.repo_dir}", f"{self.cfg}/{self.L.folder}/{self.L.code_id}"])
def test_capped_by_its_cgroup_and_pinned_to_the_small_cores(self):
cmd = command(self.stage())
self.assertIn(f"--memory {self.L.pin('MEMORY')} --memory-swap {self.L.pin('MEMORY')}", cmd)
self.assertRegex(self.L.pin("MEMORY"), r"^\d+m$")
self.assertIn(f"--cpuset-cpus {self.L.pin('CPUS')}", cmd)
both = {re.search(r"^[A-Z]+_CPUS=(\S+)$", (REPO / f).read_text(), re.M).group(1) for f in ("install-embeddings.sh", "install-clipstral.sh")}
self.assertEqual(both, {self.L.pin("CPUS")}, "the two lanes' cores are the same")
cores = sum(int(b) - int(a) + 1 for a, b in re.findall(r"(\d+)-(\d+)", self.L.pin("CPUS")))
self.assertEqual(self.L.pin("THREADS"), str(cores), "a thread a core")
def test_it_runs_beside_every_lane(self):
unit = self.stage()
self.assertNotIn("Conflicts=", "\n".join(ln for ln in unit.splitlines() if not ln.startswith("#")))
self.assertIn("Requires=docker.service", unit)
self.assertIn("After=network-online.target docker.service", unit)
self.assertIn("Restart=on-failure", unit)
self.assertIn("RestartPreventExitStatus=78", unit)
def test_the_port_its_override_and_the_one_the_unit_in_place_says(self):
self.assertIn("--port 30130", command(self.stage(**{self.L.prefix + "_PORT": "30130"})))
(self.units / self.L.unit).write_text("ExecStart=/usr/bin/docker run x --host 127.0.0.1 --port 30131\n")
self.assertIn("--port 30131", command(self.stage()))
r = subprocess.run(["bash", str(self.L.installer), "--stage", str(self.out)], capture_output=True, text=True, timeout=60,
env={"PATH": "/usr/bin:/bin", "HOME": str(self.home), "LANES_UNIT_DIR": str(self.units), self.L.prefix + "_PORT": "x"})
self.assertNotEqual(r.returncode, 0)
self.assertIn(f"{self.L.prefix}_PORT takes a number", r.stdout + r.stderr)
def test_its_preflight_checks_every_file_its_server_reads_and_leaves_it_failed(self):
unit = self.stage()
m = re.search(PREFLIGHT, unit)
self.assertEqual(m.group(1), f"{self.hf}/hub/models--{self.L.model.replace('/', '--')}/snapshots/{self.L.rev}")
fetched = [self.L.pin(k).split("=", 1)[0] for k in ("FILE", "TOKENIZER")]
self.assertEqual(m.group(2).split(), fetched)
code = "".join((REPO / f).read_text() for f in self.L.code)
for f in ('"tokenizer.json"', '"model.safetensors"'):
self.assertIn(f, code)
head = re.search(r"ExecStart=/bin/bash -c '(.*?)exec /usr/bin/docker run ", unit, re.S).group(1).replace("\\\n", " ")
self.assertEqual([ln for ln in unit.splitlines() if ln.startswith("ExecStartPre=") and "exit 78" in ln], [],
"the check is a start step, whose 78 systemd starts again every 10 s")
# it waits 90 s for a disk mounted late, then a second for its word to reach the journal, then 78; with every file there the server
# runs at once
head = head.replace("/proc/meminfo", str(self.meminfo(64)))
for have, rc, waits in (((), 78, 31), (fetched[:1], 78, 31), (fetched, 0, 0)):
shutil.rmtree(self.hf, True)
snap = pathlib.Path(m.group(1))
snap.mkdir(parents=True)
for f in have:
(snap / f).write_text("x")
r = subprocess.run(["bash", "-c", "sleep(){ echo waited; }; " + head + " exit 0"], capture_output=True, text=True)
self.assertEqual((r.returncode, r.stdout.count("waited")), (rc, waits), (have, r.stderr))
if rc:
self.assertIn(f"preflight: {self.L.unit} lacks its model: ", r.stderr)
self.assertIn(f"./{self.L.installer.name} --fetch", r.stderr)
def meminfo(self, gib, line="MemAvailable: {} kB"):
f = self.t / "meminfo"
f.write_text("MemTotal: 127535932 kB\nMemFree: 1048576 kB\n" + line.format(int(gib * 1048576)) + "\nBuffers: 524288 kB\n")
return f
def systemctl(self, up=(), boot=(), n=0):
"""A systemctl for the unit's head: the units that run and those enabled at boot, and how many times it was started again."""
return (f"systemctl(){{ case \"$*\" in \"show -p NRestarts --value {self.L.unit}\") echo {n} ;; "
+ "".join(f"\"-q is-active {u}\") return 0 ;; " for u in up) + "".join(f"\"-q is-enabled {u}\") return 0 ;; " for u in boot)
+ "*) return 3 ;; esac; }; ")
def test_it_starts_with_the_memory_it_takes_or_says_so(self):
"""Beside a lane that leaves the box 9 GiB at its lowest, nothing held its start back: its cap bounds its growth, not
what its start takes, and a GB10 whose memory runs out freezes whole (found by the proof of v1.60.0)."""
unit, room = self.stage(), int(self.L.pin("ROOM_GIB"))
snap = pathlib.Path(re.search(PREFLIGHT, unit).group(1))
snap.mkdir(parents=True)
for f in re.search(PREFLIGHT, unit).group(2).split():
(snap / f).write_text("x")
head = re.search(r"ExecStart=/bin/bash -c '(.*?)exec /usr/bin/docker run ", unit, re.S).group(1).replace("\\\n", " ")
self.assertNotIn("${", head, "systemd would read it as a variable of its own")
self.assertNotIn("%", head, "systemd would read it as a specifier")
head = head.replace("/proc/meminfo", str(self.t / "meminfo"))
# systemd starts it again after a death with a smaller question: what the lane holds, and the 3 GiB. Asked the first start's,
# a lane that died on its cap beside a busy one stayed down; asked nothing, it took its part of a box that runs out
again = int(self.L.pin("AGAIN_GIB"))
for gib, rc in ((again, 0), (again - 0.1, 78)):
self.meminfo(gib)
r = subprocess.run(["bash", "-c", self.systemctl(n=2, up=("qwen38-flash.service",)) + "sleep(){ :; }; " + head + " exit 0"],
capture_output=True, text=True)
self.assertEqual(r.returncode, rc, (gib, r.stderr))
self.assertIn(f"this lane starts with {again} GiB at least", r.stderr)
waits = self.systemctl() + "sleep(){ echo waited; }; "
for gib, rc in ((room + 0.1, 0), (room, 0), (room - 0.1, 78), (1, 78)):
self.meminfo(gib)
r = subprocess.run(["bash", "-c", waits + head + " exit 0"], capture_output=True, text=True)
self.assertEqual((r.returncode, r.stdout.count("waited")), (rc, 11 if rc else 0), (gib, r.stderr))
if rc:
self.assertIn(f"preflight: {self.L.unit} lacks room: the box had {int(gib)} GiB of memory available and this lane starts "
f"with {room} GiB at least", r.stderr)
# what a lane that stops hands back comes within the wait
self.meminfo(1)
back = f"sleep(){{ echo waited; printf 'MemTotal: 1 kB\\nMemAvailable: {(room + 20) * 1048576} kB\\n' > {self.t}/meminfo; }}; "
r = subprocess.run(["bash", "-c", self.systemctl() + back + head + " exit 0"], capture_output=True, text=True)
self.assertEqual((r.returncode, r.stdout.count("waited")), (0, 1), r.stderr)
# a reading that does not come holds nothing back
self.meminfo(1, line="MemElsewhere: {} kB")
r = subprocess.run(["bash", "-c", waits + head + " exit 0"], capture_output=True, text=True)
self.assertEqual((r.returncode, r.stdout.count("waited")), (0, 0), r.stderr)
def test_the_room_it_asks_is_its_cap_and_the_floor(self):
room = self.L.pin("ROOM_GIB")
self.assertEqual(int(room), -(-int(self.L.pin("MEMORY").rstrip("m")) // 1024) + 3)
for f, var in (("dashboard/cockpit.py", "COCKPIT_MEM_FLOOR_GIB"), ("keepalive-proxy.py", "PROXY_MEM_FLOOR_GIB")):
self.assertRegex((REPO / f).read_text(), rf'"{var}", "3\.0"', f)
said = (REPO / "dashboard/static/js/base.js").read_text().split("BESIDE_ROOM_GIB = ")[1].split(";")[0]
self.assertIn(f"[{self.L.prefix}_UNIT]: {room}", said)
holds = {"EMBED": 1, "CLIPSTRAL": 5}[self.L.prefix]
self.assertEqual(int(self.L.pin("AGAIN_GIB")), -(-holds // 1) + 3)
self.assertIn("BESIDE_HOLDS_GIB = {[EMBED_UNIT]: 1, [CLIPSTRAL_UNIT]: 5}", (REPO / "dashboard/static/js/base.js").read_text())
page = {"EMBED": "embed-lane.md", "CLIPSTRAL": "clipstral-lane.md"}[self.L.prefix]
self.assertIn(f"{room} GiB of memory available", " ".join((REPO / "docs" / page).read_text().split()))
def test_what_it_lacks_is_named_to_an_update_and_to_the_cockpit(self):
"""lanes.sh's unit_needs: the image, the snapshot, each file its preflight checks, and the folder of its code."""
bin_ = self.t / "bin"
bin_.mkdir()
(bin_ / "docker").write_text("#!/bin/sh\nexit 0\n")
(bin_ / "docker").chmod(0o755)
self.stage()
def needs():
r = subprocess.run(["bash", "-c", f'. "{REPO}/lanes.sh"; unit_needs "{self.out}"'], capture_output=True, text=True,
env={"PATH": f"{bin_}:/usr/bin:/bin", "HOME": str(self.home), "LANES_UNIT_DIR": str(self.units)})
self.assertEqual(r.returncode, 0, r.stderr)
return r.stdout.split("\n")[:-1]
code = f"{self.cfg}/{self.L.folder}/{self.L.code_id}"
self.assertIn(f"path {code}", needs())
self.assertTrue(any(self.L.model.split("/")[1] in x for x in needs()), needs())
snap = self.hf / "hub" / f"models--{self.L.model.replace('/', '--')}" / "snapshots" / self.L.rev
snap.mkdir(parents=True)
(snap / "model.safetensors").write_text("x")
os.makedirs(code)
self.assertEqual(needs(), [f"path {snap}/tokenizer.json"])
(snap / "tokenizer.json").write_text("x")
self.assertEqual(needs(), [])
def test_the_cache_it_fetches_into_is_the_one_the_text_lanes_mount(self):
(self.units / "qwen38-sglang.service").write_text(
"ExecStart=/bin/bash -c 'exec /usr/bin/docker run --rm --name qwen38-sglang -v /mnt/disk/hf:/root/.cache/huggingface:ro x'\n")
r = subprocess.run(["bash", str(self.L.installer), "--stage", str(self.out)], capture_output=True, text=True, timeout=60,
env={"PATH": "/usr/bin:/bin", "HOME": str(self.home), "LANES_UNIT_DIR": str(self.units)})
self.assertEqual(r.returncode, 0, r.stderr)
self.assertIn(f"source=/mnt/disk/hf/hub/{self.L.repo_dir},", command(self.out.read_text()))
# where its readers find the cache in it (its own unit first, at the next run)
r = subprocess.run(["bash", "-c", f'. "{REPO}/lanes.sh"; unit_hf_cache "{self.out}"'], capture_output=True, text=True)
self.assertEqual(r.stdout.strip(), "/mnt/disk/hf")
class CodeTests:
"""Each release's code is a folder of its own, so that a unit waiting for its Load leaves the one in place whole."""
def run_fn(self, cfg, installed):
body = self.L.text[self.L.text.index("CODE_FILES=("):self.L.text.index("missing_gb(){")]
script = f'set -euo pipefail\nHERE="{REPO}"; CONFIG_DIR="{cfg}"; INSTALLED="{installed}"; UNIT={self.L.unit}\n{body}\nput_code; drop_old_code\n'
r = subprocess.run(["bash", "-c", script], capture_output=True, text=True, timeout=30)
self.assertEqual(r.returncode, 0, r.stderr)
def test_it_is_copied_and_only_what_no_unit_names_goes(self):
t = pathlib.Path(tempfile.mkdtemp(prefix="vector-lane-code-"))
self.addCleanup(shutil.rmtree, t, True)
cfg, installed = t / "cfg", t / self.L.unit
for name in ("inplace00000", "waiting00000", "nobody000000"):
(cfg / self.L.folder / name).mkdir(parents=True)
(cfg / self.L.folder / name / self.L.code[0]).write_text("x")
(cfg / "pending").mkdir()
installed.write_text(f"--mount type=bind,source={cfg}/{self.L.folder}/inplace00000,target=/{self.L.folder},readonly\n")
(cfg / "pending" / self.L.unit).write_text(f"--mount type=bind,source={cfg}/{self.L.folder}/waiting00000,target=/{self.L.folder},readonly\n")
self.run_fn(cfg, installed)
self.assertEqual(sorted(p.name for p in (cfg / self.L.folder).iterdir()), sorted([self.L.code_id, "inplace00000", "waiting00000"]))
for f in self.L.code:
self.assertEqual((cfg / self.L.folder / self.L.code_id / f).read_bytes(), (REPO / f).read_bytes())
self.assertEqual((cfg / self.L.folder / self.L.code_id / f).stat().st_mode & 0o777, 0o644)
# a second run moves nothing
was = (cfg / self.L.folder / self.L.code_id / self.L.code[0]).stat().st_mtime_ns
self.run_fn(cfg, installed)
self.assertEqual((cfg / self.L.folder / self.L.code_id / self.L.code[0]).stat().st_mtime_ns, was)
def test_a_box_with_no_folder_yet(self):
t = pathlib.Path(tempfile.mkdtemp(prefix="vector-lane-code-"))
self.addCleanup(shutil.rmtree, t, True)
self.run_fn(t / "cfg", t / "absent")
self.assertEqual([p.name for p in (t / "cfg" / self.L.folder).iterdir()], [self.L.code_id])
def test_the_folder_its_code_names_itself_by_is_the_one_python_reads(self):
server = (REPO / self.L.code[0]).read_text()
self.assertIn("sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))", server) # python -I leaves it out
self.assertIn("import " + self.L.code[1].removesuffix(".py"), server)
def test_the_installers_and_the_scripts_hold_to_shellcheck(self):
r = subprocess.run(["shellcheck", "-S", "warning", str(self.L.installer), str(REPO / "lanes.sh")], capture_output=True, text=True)
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
class FirstLoadTests:
"""--prepare is what the cockpit's first Load runs: the image, then the model, the room of each checked before its
first byte, and nothing of either asked when it is here."""
def prepare(self, free_gib, image_here=False):
d = pathlib.Path(tempfile.mkdtemp(prefix="vector-lane-prepare-"))
self.addCleanup(shutil.rmtree, d, True)
for f in ("docker-root", "home", "bin"):
(d / f).mkdir()
b, log = d / "bin", d / "log"
log.write_text("")
(b / "df").write_text(f"#!/bin/sh\necho Avail\necho {free_gib}G\n")
(b / "getent").write_text("#!/bin/sh\nexit 2\n")
(b / "id").write_text("#!/bin/sh\ncase $1 in -u) echo 1000 ;; -G) echo 1000 ;; -un|-gn) echo user ;; -nG) echo user ;; *) exit 1 ;; esac\n")
(b / "docker").write_text(f'#!/bin/sh\n[ "$1" = info ] && {{ echo "{d}/docker-root"; exit 0; }}\n'
f'[ "$1 $2" = "image inspect" ] && exit {0 if image_here else 1}\n'
f'[ "$1" = pull ] && {{ echo "pull $2" >> "{log}"; exit 0; }}\nexit 0\n')
(b / "python3").write_text(f'#!/bin/sh\n[ "$1 $2" = "-I {REPO}/gguf-fetch.py" ] && {{ echo "fetch $*" >> "{log}"; exit 0; }}\n'
'exec /usr/bin/python3 "$@"\n')
for f in b.iterdir():
f.chmod(0o755)
r = subprocess.run(["bash", str(self.L.installer), "--prepare"], capture_output=True, text=True, timeout=60,
env={"PATH": f"{b}:/usr/bin:/bin", "HOME": str(d / "home"), "LANES_UNIT_DIR": str(d / "units")})
return r.returncode, r.stdout + r.stderr, log.read_text().splitlines()
def test_the_image_then_the_model_by_their_pins(self):
rc, out, log = self.prepare(free_gib=100)
self.assertEqual(rc, 0, out)
self.assertEqual(log[0], f"pull {self.L.image}")
self.assertTrue(log[1].startswith(f"fetch -I {REPO}/gguf-fetch.py "), log)
for part in (self.L.model, self.L.rev, self.L.pin("FILE"), self.L.pin("TOKENIZER")):
self.assertIn(f" {part}", log[1] + " ")
self.assertEqual(len(log), 2)
def test_the_image_already_here_is_not_pulled_nor_its_room_asked(self):
rc, out, log = self.prepare(free_gib=8, image_here=True)
self.assertEqual(rc, 0, out)
self.assertEqual([x.split()[0] for x in log], ["fetch"])
def test_a_disk_too_full_is_refused_before_the_first_byte(self):
rc, out, log = self.prepare(free_gib=20)
self.assertNotEqual(rc, 0)
self.assertIn("nothing was pulled", out)
rc, out, log2 = self.prepare(free_gib=1, image_here=True)
self.assertNotEqual(rc, 0)
self.assertIn("nothing was downloaded", out)
self.assertEqual((log, log2), ([], []))
def test_a_64_gb_box_refuses_it(self):
self.assertIn(f'lane_fits {self.L.key} || die "The {self.L.title} lane needs a 128 GB DGX Spark', self.L.text)
class ProofRunTests:
"""The proof at the end of a full run asks the engine that runs. A lane that ran before the run was left running as it was:
a unit this run put in place (an image, a port, a flag moved), its code or a model file it fetched was not what answered,
and the proof passed on the old container (code review of v1.60.0). A lane that serves files older than the ones installed
now restarts first; one that serves them already is left as it is. The run is the installer as written, against stand-ins
for docker, systemd, sudo and curl that write down what they are asked."""
def full_run(self, started, active=True):
d = pathlib.Path(tempfile.mkdtemp(prefix="vector-lane-proof-"))
self.addCleanup(shutil.rmtree, d, True)
for f in ("docker-root", "home", "units", "bin"):
(d / f).mkdir()
log, checks, unit = d / "systemctl.log", d / "checks.log", self.L.unit
fakes = {
"df": "#!/bin/sh\necho Avail\necho 999G\n",
"getent": "#!/bin/sh\nexit 2\n",
"uname": "#!/bin/sh\necho aarch64\n",
"id": "#!/bin/sh\ncase $1 in -u) echo 1000 ;; -G) echo 1000 ;; -un|-gn) echo user ;; -nG) echo user ;; *) exit 1 ;; esac\n",
# the image is here, every other docker call answers nothing
"docker": f'#!/bin/sh\n[ "$1" = info ] && {{ echo "{d}/docker-root"; exit 0; }}\nexit 0\n',
# the model's fetch and the check of the vectors are their own tests' subject: stand-ins that answer 0
"python3": f'#!/bin/sh\n[ "$1 $2" = "-I {REPO}/gguf-fetch.py" ] && exit 0\n'
f'[ "$1 $2" = "-I {REPO}/vectors-check.py" ] && {{ echo "$*" >> "{checks}"; exit 0; }}\nexec /usr/bin/python3 "$@"\n',
"sudo": '#!/bin/sh\nexec "$@"\n',
"journalctl": "#!/bin/sh\nexit 0\n",
"curl": "#!/bin/sh\nexit 0\n",
# the lane, active or not since `started` (seconds since the epoch), as systemd says it
"systemctl": f'#!/bin/sh\necho "$*" >> "{log}"\ncase "$*" in\n'
f' "is-active --quiet {unit}") exit {0 if active else 3} ;;\n'
f' "is-active {unit}") echo active ;;\n'
f' "show -p ActiveState --value {unit}") echo active ;;\n'
f' "show -p ExecMainStartTimestamp --value --timestamp=unix {unit}") echo "@{started}" ;;\n'
f' "show -p NRestarts --value {unit}") echo 0 ;;\nesac\nexit 0\n',
}
for name, text in fakes.items():
(d / "bin" / name).write_text(text)
(d / "bin" / name).chmod(0o755)
r = subprocess.run(["bash", str(self.L.installer)], capture_output=True, text=True, timeout=120,
env={"PATH": f"{d}/bin:/usr/bin:/bin", "HOME": str(d / "home"), "LANES_UNIT_DIR": str(d / "units")})
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
verbs = [a.split()[0] for a in log.read_text().splitlines() if a.split()[0] in ("start", "stop", "restart")]
self.assertEqual(checks.read_text().split()[:3], ["-I", f"{REPO}/vectors-check.py", f"http://127.0.0.1:{self.L.port}"])
return verbs
def test_a_lane_that_ran_before_the_run_restarts_on_what_it_installed(self):
self.assertEqual(self.full_run(started=1000), ["restart"], "left running, as it was found")
def test_a_lane_that_serves_what_is_installed_is_left_as_it_is(self):
self.assertEqual(self.full_run(started=int(time.time()) + 100000), [])
def test_a_lane_that_did_not_run_is_stopped_after_its_proof(self):
self.assertEqual(self.full_run(started=1000, active=False), ["start", "stop"])
class BegunTests:
"""install.sh tells a lane a first Load began (its image here, its model's folder in the cache its unit mounts) from one never
loaded, by side_gguf_begun: begun, a run updates it (--no-smoke) and its summary says it is up to date; not begun, its units
only and "its first Load ... fetches its weights". The probe looked for a snapshot path followed by a slash (a GGUF file's),
and these units name their snapshot as a folder: a box whose lane was loaded and served read as never loaded at every
update (review of v1.60.0)."""
def test_a_loaded_lane_is_begun_and_one_never_loaded_is_not(self):
for loaded in (True, False):
t = pathlib.Path(tempfile.mkdtemp(prefix="vector-lane-begun-"))
self.addCleanup(shutil.rmtree, t, True)
home, hf, bin_ = t / "home", t / "hf", t / "bin"
(home / ".config" / "qwen38").mkdir(parents=True)
bin_.mkdir()
(bin_ / "docker").write_text("#!/bin/bash\nexit 0\n") # the image is here
(bin_ / "docker").chmod(0o755)
unit = t / self.L.unit
r = subprocess.run(["bash", str(self.L.installer), "--stage", str(unit)], capture_output=True, text=True, timeout=60,
env={"PATH": "/usr/bin:/bin", "HOME": str(home), "HF_CACHE": str(hf), "LANES_UNIT_DIR": str(t)})
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
if loaded:
(hf / "hub" / self.L.repo_dir / "snapshots" / self.L.rev).mkdir(parents=True)
sh = (REPO / "install.sh").read_text()
start = sh.index("side_gguf_begun(){")
fn = sh[start:sh.index("\n}\n", start) + 3]
r = subprocess.run(["bash", "-c", f'. "{REPO}/lanes.sh"\n{fn}side_gguf_begun "{unit}"'], capture_output=True, text=True,
timeout=60, env={"PATH": f"{bin_}:/usr/bin:/bin", "HOME": str(home)})
self.assertEqual(r.returncode == 0, loaded, r.stdout + r.stderr)
class PortTests:
"""EMBED_PORT=30128 ./install.sh wrote the unit and left the lane that ran on 30028: the proxy, which reads the unit, asked
30128 for good, the cockpit showed it starting, and its Load said it was already serving (review of v1.60.0)."""
def moved(self, was, now, active, restarts=True):
with tempfile.TemporaryDirectory() as t:
for name, body in (("systemctl", f'[ "$1" = is-active ] && exit {0 if active else 3}; exit 1'),
("sudo", f'echo "sudo $*"; exit {0 if restarts else 1}')):
f = pathlib.Path(t) / name
f.write_text("#!/bin/sh\n" + body + "\n")
f.chmod(0o755)
r = subprocess.run(["bash", "-euc", f'. "{REPO}/lanes.sh"; beside_port_moved {self.L.unit} "{was}" "{now}"; echo end'],
env={"PATH": f"{t}:/usr/bin:/bin", "HOME": t}, capture_output=True, text=True)
self.assertTrue(r.stdout.endswith("end\n"), r.stderr)
return r.stdout[:-4]
def test_a_lane_that_runs_starts_again_there(self):
was, now, unit = str(self.L.port), str(self.L.port + 100), self.L.unit
self.assertEqual(self.moved(was, now, True), f"sudo systemctl restart {unit}\nits port moved from {was} to {now}: restarted there\n")
self.assertIn(f"NOTE: {unit} still answers on port {was}, and its unit names {now} now: sudo systemctl restart {unit}",
self.moved(was, now, True, restarts=False))
for a, b, active in ((was, was, True), ("", now, True), (was, now, False)):
self.assertEqual(self.moved(a, b, active), "", (a, b, active))
def test_its_installer_does_it_and_its_uninstall_drops_what_waited(self):
text = self.L.text
body = text[text.index("install_service(){"):text.index("\n}\n", text.index("install_service(){"))]
self.assertLess(body.index('was="$(installed_flag --port)"'), body.index("unit_put"))
self.assertGreater(body.index('[ "$put" = pending ] || beside_port_moved "$UNIT" "$was" "$PORT"'), body.index("unit_put"))
gone = text[text.index('if [ "$ACTION" = uninstall ]; then'):]
self.assertIn('unit_pending_clear "$INSTALLED"', gone[:gone.index("\nfi\n")])