Files
alzeo/tests/test_install_robust.py
T
Hasan BasbunarandClaude Opus 5.5 87ba62321c tests: a walled install reads no disk of the machine that runs it, and an uptime is not the machine's
GitHub's arm64 runner names a /mnt in its fstab that is not mounted, and has been up a few minutes: the cache's disk check
refused 18 installs of the suite there, and one test took the machine's uptime for the box's.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 16:38:53 +01:00

447 lines
22 KiB
Python

#!/usr/bin/env python3
"""What an install meets on a box that is not the reference one, each found on 2026-11-30 (the audit of v1.59.1): a disk
that fills, a company proxy, no network, a cache whose disk did not mount, another install or a Load under way, an
engine still loading, a clone a sudo left to root. The functions run as install.sh, lanes.sh and get.sh have them."""
import http.server
import json
import os
import pathlib
import re
import shutil
import subprocess
import sys
import tempfile
import threading
import time
import unittest
REPO = pathlib.Path(__file__).resolve().parents[1]
INSTALL = (REPO / "install.sh").read_text()
def function(name, text=INSTALL):
m = re.search(rf"(?m)^{name}\(\)\s*\{{.*\}}$", text) or re.search(rf"(?ms)^{name}\(\)\s*\{{.*?^\}}$", text)
assert m, name
return m.group(0) + "\n"
def bash(script, *args, env=None, path=None):
e = {k: v for k, v in os.environ.items() if not k.lower().endswith("_proxy")}
e.update(env or {})
if path:
e["PATH"] = f"{path}:{e['PATH']}"
return subprocess.run(["bash", "-c", script, "t", *map(str, args)], capture_output=True, text=True, env=e, timeout=60)
def lanes(script, *args, **kw):
return bash(f'set -euo pipefail; CONFIG_DIR="{kw.pop("config", "/nonexistent")}"; . "{REPO}/lanes.sh"\n' + script, *args, **kw)
class Tmp(unittest.TestCase):
def setUp(self):
self.d = pathlib.Path(tempfile.mkdtemp(prefix="install-robust-"))
self.addCleanup(shutil.rmtree, self.d, ignore_errors=True)
self.bin = self.d / "bin"
self.bin.mkdir()
def fake(self, name, body):
p = self.bin / name
p.write_text("#!/usr/bin/env bash\n" + body)
p.chmod(0o755)
class AFileIsReplacedWholeOrNotAtAll(Tmp):
def put(self):
(self.d / "new").write_text("the new proxy\n" * 9)
(self.d / "in-place").write_text("the proxy that runs\n")
return bash('die(){ echo "ERROR: $*" >&2; exit 1; }\n' + function("put_whole") + 'put_whole "$1" "$2"',
self.d / "new", self.d / "in-place", path=self.bin)
def test_it_is_put_in_place(self):
r = self.put()
self.assertEqual((r.returncode, (self.d / "in-place").read_text()), (0, "the new proxy\n" * 9), r.stderr)
self.assertEqual((self.d / "in-place").stat().st_mode & 0o777, 0o755)
def test_a_disk_that_fills_keeps_the_one_in_place(self):
# what install(1) does on a full disk: the destination emptied, part of it written, an error
self.fake("install", 'for d; do :; done; head -c 20 "$3" > "$d"; echo "install: No space left on device" >&2; exit 1\n')
r = self.put()
self.assertEqual(r.returncode, 1)
self.assertEqual((self.d / "in-place").read_text(), "the proxy that runs\n")
self.assertIn("is that disk full?", r.stderr)
self.assertEqual(sorted(p.name for p in self.d.iterdir()), ["bin", "in-place", "new"])
def test_the_files_the_box_runs_go_through_it(self):
for f in ("keepalive-proxy.py", "engine-secrets.sh", "engine-preflight.sh", "flash-ats-check.sh"):
self.assertIn(f'put_whole "$REPO_DIR/{f}" "$CONFIG_DIR/{f}"', INSTALL)
self.assertNotIn(f'install -m 755 "$REPO_DIR/{f}" "$CONFIG_DIR/{f}"', INSTALL)
self.assertIn('put_whole "$TMP_LAUNCH" "$CONFIG_DIR/launch-flash.sh"', INSTALL)
self.assertIn('os.replace(f"{cfg_dir}/opencode.json.new", f"{cfg_dir}/opencode.json")', INSTALL)
class AnImageNamedByItsDigestIsNotPulledAgain(Tmp):
def have(self, image, present):
self.fake("docker", f'[ "$1 $2" = "image inspect" ] && exit {0 if present else 1}; echo "docker $*" >&2; exit 9\n')
return bash(function("have_image") + 'have_image "$1"', image, path=self.bin)
def test_here(self):
r = self.have("lmsysorg/sglang@sha256:" + "a" * 64, True)
self.assertEqual((r.returncode, r.stdout.strip()), (0, "already here"))
def test_not_here_or_a_tag_that_moves(self):
self.assertNotEqual(self.have("lmsysorg/sglang@sha256:" + "a" * 64, False).returncode, 0)
self.assertNotEqual(self.have("lmsysorg/sglang:v0.5.22", True).returncode, 0)
def test_both_pulls_ask_it(self):
self.assertEqual(re.findall(r'(?m)^\s*(.*?)docker pull "\$PULL_TARGET"', INSTALL),
['have_image "$PULL_TARGET" || '] * 2)
class TheBoxsOwnAddressesNeverGoThroughAProxy(Tmp):
def test_the_variables(self):
show = 'echo "${no_proxy-unset}|${NO_PROXY-unset}"'
for env, want in (({}, "unset|unset"),
({"http_proxy": "http://p:1"}, "127.0.0.1,localhost|127.0.0.1,localhost"),
({"HTTP_PROXY": "http://p:1"}, "127.0.0.1,localhost|127.0.0.1,localhost"), # urllib reads it
({"HTTPS_PROXY": "http://p:1", "NO_PROXY": "corp.lan"}, "127.0.0.1,localhost|127.0.0.1,localhost,corp.lan"),
({"all_proxy": "http://p:1", "no_proxy": "*", "NO_PROXY": "*"}, "*|*"),
({"http_proxy": "http://p:1", "no_proxy": "127.0.0.1", "NO_PROXY": "127.0.0.1"}, "127.0.0.1|127.0.0.1")):
with self.subTest(env=env):
r = lanes(show, env=env)
self.assertEqual(r.stdout.strip(), want, r.stderr)
def test_a_probe_goes_to_the_box_and_the_key_nowhere_else(self):
seen = {"proxy": [], "engine": []}
def server(name):
class H(http.server.BaseHTTPRequestHandler):
def log_message(self, *a):
pass
def do_GET(self):
seen[name].append(self.headers.get("Authorization"))
self.send_response(200)
self.send_header("Content-Length", "0")
self.end_headers()
s = http.server.ThreadingHTTPServer(("127.0.0.1", 0), H)
threading.Thread(target=s.serve_forever, daemon=True).start()
self.addCleanup(s.server_close)
self.addCleanup(s.shutdown)
return s.server_address[1]
proxy, engine = server("proxy"), server("engine")
probe = f'curl -sf -m 5 -H "Authorization: Bearer fake" http://127.0.0.1:{engine}/health'
env = {"http_proxy": f"http://127.0.0.1:{proxy}"}
self.assertEqual(bash(probe, env=env).returncode, 0)
self.assertEqual(seen, {"proxy": ["Bearer fake"], "engine": []}, "the witness: without lanes.sh it goes to the proxy")
seen["proxy"].clear()
self.assertEqual(lanes(probe, env=env).returncode, 0)
self.assertEqual(seen, {"proxy": [], "engine": ["Bearer fake"]})
class ACacheWhoseDiskIsNotMounted(Tmp):
def disk(self, fstab, path, mounted=()):
(self.d / "fstab").write_text(fstab)
self.fake("mountpoint", "\n".join(f'[ "$3" = "{m}" ] && exit 0' for m in mounted) + "\nexit 1\n")
r = lanes('unmounted_disk_of "$1"', path, env={"QWEN38_FSTAB": str(self.d / "fstab")}, path=self.bin)
self.assertEqual(r.returncode, 0, r.stderr)
return r.stdout.strip()
FSTAB = ("# a comment\nUUID=1 / ext4 defaults 0 1\n/swap.img none swap sw 0 0\n"
"UUID=2 /mnt/ssd ext4 nofail 0 2\nUUID=3 /mnt/my\\040disk ext4 nofail 0 2\n")
def test_named(self):
self.assertEqual(self.disk(self.FSTAB, "/mnt/ssd/hf"), "/mnt/ssd")
self.assertEqual(self.disk(self.FSTAB, "/mnt/my disk/hf"), "/mnt/my disk")
def test_mounted_or_elsewhere(self):
self.assertEqual(self.disk(self.FSTAB, "/mnt/ssd/hf", ("/mnt/ssd",)), "")
self.assertEqual(self.disk(self.FSTAB, "/mnt/ssd2/hf"), "")
self.assertEqual(self.disk(self.FSTAB, self.d / "home/.cache/huggingface"), "")
self.assertEqual(self.disk("", "/mnt/ssd/hf"), "")
def test_through_a_link(self):
os.symlink("/mnt/ssd/hf", self.d / "huggingface")
self.assertEqual(self.disk(self.FSTAB, self.d / "huggingface"), "/mnt/ssd")
def test_the_install_asks_before_anything(self):
self.assertLess(INSTALL.index("unmounted_disk_of"), INSTALL.index('mkdir -p "$HF_CACHE"'))
class AnInstallBesideAnotherOrALoad(Tmp):
def beside(self):
r = lanes('runs_beside "$1"', self.d)
self.assertEqual(r.returncode, 0, r.stderr)
return r.stdout
def mark(self, pid, start):
(self.d / f"install-running.{pid}.json").write_text(json.dumps({"pid": pid, "start": start, "started": 1, "to": "v1"}))
@staticmethod
def start_of(pid):
s = pathlib.Path(f"/proc/{pid}/stat").read_text()
return s[s.rindex(")") + 2:].split()[19]
def sleeper(self, argv=("sleep", "60")):
p = subprocess.Popen(argv, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
self.addCleanup(p.wait)
self.addCleanup(p.kill)
time.sleep(0.2)
return p.pid
def test_another_install(self):
pid = self.sleeper()
self.mark(pid, self.start_of(pid))
self.assertIn(f"another install (pid {pid})", self.beside())
def test_a_mark_left_by_a_run_that_is_gone(self):
pid = self.sleeper()
self.mark(pid, "1") # the pid is another process's now
self.mark(2 ** 22 - 3, "1")
self.assertNotIn("another install", self.beside())
def test_its_own_mark_is_not_another(self):
r = lanes('run_mark "$1"; runs_beside "$1"; ls "$1"', self.d)
self.assertNotIn("another install", r.stdout)
self.assertIn("install-running.", r.stdout)
def test_a_load(self):
script = self.d / "switch-model.sh"
script.write_text("sleep 60; :\n")
pid = self.sleeper(("bash", str(script), "flash-local"))
self.assertIn(f"switch-model.sh flash-local (pid {pid})", self.beside())
def test_what_prepare_lane_becomes(self):
"""prepare-lane.sh's preparation is an exec of the lane's installer, whose command line no longer names it."""
(self.d / "install-image.sh").write_text("sleep 60; :\n")
script = self.d / "prepare-lane.sh"
script.write_text(f'exec bash "{self.d}/install-image.sh" --prepare image\n')
pid = self.sleeper(("bash", str(script), "image", "image"))
time.sleep(0.3)
self.assertIn(f"install-image.sh --prepare image (pid {pid})", self.beside())
def test_an_installer_that_prepares_nothing_is_not_a_load(self):
script = self.d / "install-image.sh"
script.write_text("sleep 60; :\n")
self.sleeper(("bash", str(script), "--units-only"))
self.assertNotIn("install-image.sh", self.beside())
def test_a_script_open_in_an_editor_is_not_one(self):
script = self.d / "switch-model.sh"
script.write_text("sleep 60; :\n")
self.sleeper(("tail", "-f", str(script)))
self.assertNotIn("switch-model.sh", self.beside())
pid = self.sleeper(("bash", "-x", str(script), "flash"))
self.assertIn(f"switch-model.sh flash (pid {pid})", self.beside())
def test_a_load_of_another_home_is_not_this_boxs(self):
"""The suite's own, beside an install it runs in another home."""
script = self.d / "prepare-lane.sh"
script.write_text("sleep 60; :\n")
p = subprocess.Popen(("bash", str(script), "flash"), env={**os.environ, "HOME": str(self.d)},
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
self.addCleanup(p.wait)
self.addCleanup(p.kill)
time.sleep(0.2)
self.assertNotIn(f"(pid {p.pid})", self.beside())
r = lanes('runs_beside "$1"', self.d, env={"HOME": str(self.d)})
self.assertIn(f"prepare-lane.sh flash (pid {p.pid})", r.stdout)
def test_a_command_that_only_names_it_is_not_one(self):
self.sleeper(("bash", "-c", "sleep 60; : switch-model.sh"))
self.assertNotIn("switch-model.sh", self.beside())
def test_the_install_refuses_and_says_what_runs(self):
block = INSTALL[INSTALL.index('if [ -z "$SECONDARY" ]; then\n BESIDE='):]
block = block[:block.index("\nfi\n") + 4]
r = bash('die(){ echo "ERROR: $*" >&2; exit 1; }\nSECONDARY=""; CONFIG_DIR=x\n'
"runs_beside(){ printf 'another install (pid 4)\\nswitch-model.sh flash (pid 5)\\n'; }\n" + block)
self.assertEqual(r.returncode, 1)
self.assertIn("busy with another install (pid 4), switch-model.sh flash (pid 5):", r.stderr)
r = bash('die(){ exit 1; }\nSECONDARY=""; CONFIG_DIR=x\nruns_beside(){ :; }\n' + block + "echo went on")
self.assertEqual(r.stdout.strip(), "went on")
class AnEngineThatLoadsIsWaitedFor(Tmp):
UP = 9_000_000 # seconds: the machine's own uptime is a runner's few minutes, whatever the box's
def loads(self, state, age_s):
at = "" if age_s is None else str(int((self.UP - age_s) * 1e6))
self.fake("awk", f"echo {self.UP * 1_000_000}\n")
self.fake("systemctl", f'case "$*" in *ActiveState*) echo {state} ;; *ActiveEnterTimestampMonotonic*) echo "{at}" ;; esac\n')
return bash("UNIT_NAME=x.service\n" + function("engine_loads") + "engine_loads", path=self.bin).returncode == 0
def test_when(self):
self.assertTrue(self.loads("active", 240))
self.assertFalse(self.loads("active", 1900))
self.assertFalse(self.loads("activating", 5)) # a relaunch, or its preflight waits: not loading
self.assertFalse(self.loads("inactive", 5))
self.assertFalse(self.loads("active", None))
def test_it_is_asked_only_of_an_engine_that_reads_what_this_run_has(self):
chain = INSTALL[INSTALL.index('ENGINE_KEEP=0; ENGINE_WHY=""'):]
order = [chain.index(x) for x in ('RESTART_ENGINE:-0', 'ENGINE_RUNNING_IT" != "yes"', 'ENGINE_FP_BEFORE"', '/health"', "elif engine_loads")]
self.assertEqual(order, sorted(order))
class SudosTimestampLastsAsLongAsTheRun(Tmp):
BLOCK = INSTALL[INSTALL.index('if [ "$NO_SERVICE" -eq 0 ] && [ -z "${SECONDARY:-}" ]; then\n # (a read that times out'):]
BLOCK = BLOCK[:BLOCK.index("\nfi\n") + 4]
def test_it_is_renewed_and_ends_with_the_run(self):
self.fake("sudo", f'echo "$*" >> "{self.d}/sudo.log"\n')
r = bash('set -euo pipefail; NO_SERVICE=0; SECONDARY=""; SUDO_KEEPER=""; forget_run_mark(){ :; }\n'
+ function("forget_sudo_keeper") + self.BLOCK + '/bin/sleep 1; echo "$SUDO_KEEPER"',
path=self.bin, env={"SUDO_KEEP_S": "0.1"})
self.assertNotIn("sleep", self.BLOCK.split("&\n")[0].split("\n")[-1], "a child that outlives the run")
self.assertEqual(r.returncode, 0, r.stderr)
n = (self.d / "sudo.log").read_text().splitlines()
self.assertGreater(len(n), 2)
self.assertEqual(set(n), {"-n -v"})
time.sleep(0.5)
self.assertEqual(len((self.d / "sudo.log").read_text().splitlines()), len(n), "it went on after the run")
def test_none_without_a_service_or_in_the_run_for_the_other_lane(self):
for var in ("NO_SERVICE=1; SECONDARY=", "NO_SERVICE=0; SECONDARY=flash"):
r = bash(f'set -euo pipefail; {var}; SUDO_KEEPER=""; forget_run_mark(){{ :; }}\n' + self.BLOCK + 'echo "[$SUDO_KEEPER]"')
self.assertEqual(r.stdout.strip(), "[]", r.stderr)
class AnInstallBesideALaneStartedByHand(Tmp):
"""The image lane is restarted to run new files (v1.40.6), but not under a run that says it starts and stops none."""
TEXT = (REPO / "install-image.sh").read_text()
BLOCK = TEXT[TEXT.index(' if [ "$SMOKE" -eq 0 ] && lane_serves_older "$UNIT" "${LANE_FILES[@]}"; then'):]
BLOCK = BLOCK[:BLOCK.index("\n fi\n") + 6]
def run_block(self, **env):
return bash('set -euo pipefail; SMOKE=0; UNIT=qwen38-image.service; LANE_FILES=(x)\nlane_serves_older(){ return 0; }\n'
'sudo(){ echo "SUDO $*"; }\n' + self.BLOCK, env=env)
def test_it_goes_on(self):
r = self.run_block(QWEN38_KEEPS_SERVING="1")
self.assertEqual(r.returncode, 0, r.stderr)
self.assertNotIn("SUDO", r.stdout)
self.assertIn("goes on serving", r.stdout)
def test_and_is_restarted_as_before_otherwise(self):
self.assertIn("SUDO systemctl restart qwen38-image.service", self.run_block().stdout)
def test_install_sh_says_it_to_the_lanes_installers(self):
self.assertIn('[ -z "$STARTS_NONE" ] || export QWEN38_KEEPS_SERVING=1', INSTALL)
class TheRecordOfATextLaneWhoseUnitsAreGone(Tmp):
LINE = next(ln for ln in INSTALL.splitlines() if ln.startswith('[ -n "$SECONDARY" ] || [ -f "$SGL_UNIT_PATH" ]'))
def run_line(self, unit, secondary=""):
(self.d / "text-lane").write_text("qwen38-sglang.service\n")
if unit:
(self.d / "u").write_text("x")
bash(f'set -euo pipefail; SECONDARY="{secondary}"; SGL_UNIT_PATH="{self.d}/u"; FLASH_UNIT_PATH="{self.d}/v"; CONFIG_DIR="{self.d}"\n{self.LINE}\n')
return (self.d / "text-lane").exists()
def test_goes_with_the_next_run(self):
self.assertFalse(self.run_line(unit=False))
self.assertTrue(self.run_line(unit=False, secondary="flash"))
self.assertTrue(self.run_line(unit=True))
def test_it_is_after_what_plan_prints(self):
self.assertLess(INSTALL.index('if [ "$PLAN_ONLY" -eq 1 ]; then'), INSTALL.index(self.LINE))
class TheUsersJsoncCounts(Tmp):
def test_in_what_restarts_the_agents_server(self):
(self.d / ".config/opencode").mkdir(parents=True)
out = []
for limit in (999000, 700000):
(self.d / ".config/opencode/opencode.jsonc").write_text(f'{{"limit": {limit}}}')
out.append(bash(f'set -euo pipefail; CONFIG_DIR="{self.d}/c"; HOME="{self.d}"\n' + function("oc_configs_sum") + "oc_configs_sum").stdout)
self.assertNotEqual(*out)
for script in ("switch-model.sh", "vllm-lane.sh"):
text = (REPO / script).read_text()
self.assertNotIn('"$HOME/.config/opencode/opencode.json" 2>/dev/null || true; } | sha256sum', text)
agent = (REPO / "dashboard/install-agent.sh").read_text()
self.assertIn('"$HOME/.config/opencode/opencode.json" "$HOME/.config/opencode/opencode.jsonc"; do', agent)
def test_one_that_names_no_provider_of_this_box_is_not_the_fits(self):
import importlib.util
spec = importlib.util.spec_from_file_location("fit_robust", REPO / "oc-fit-limits.py")
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
(self.d / ".config/opencode").mkdir(parents=True)
jsonc = self.d / ".config/opencode/opencode.jsonc"
saved = os.environ.get("HOME")
os.environ["HOME"] = str(self.d)
try:
for text, want in ((None, []), ("", []), ("{ broken", []), ('{"theme": "x"}', []),
('{// mine\n"provider": {"qwen38": {}}}', [jsonc]), ('{"provider": {"anthropic": {}}}', [])):
if text is not None:
jsonc.write_text(text)
got = mod.shadow_config()
self.assertEqual(got, want, text)
finally:
os.environ["HOME"] = saved
def test_the_fit_asks_the_engine_straight(self):
import importlib.util
seen = []
class H(http.server.BaseHTTPRequestHandler):
def log_message(self, *a):
pass
def do_GET(self):
seen.append(self.path)
self.send_response(200)
self.send_header("Content-Length", "2")
self.end_headers()
self.wfile.write(b"{}")
servers = [http.server.ThreadingHTTPServer(("127.0.0.1", 0), H) for _ in range(2)]
for s in servers:
threading.Thread(target=s.serve_forever, daemon=True).start()
self.addCleanup(s.server_close)
self.addCleanup(s.shutdown)
proxy, engine = (s.server_address[1] for s in servers)
spec = importlib.util.spec_from_file_location("fit_robust2", REPO / "oc-fit-limits.py")
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
(self.d / "api-key").write_text("k\n")
mod.CONFIG_DIR = self.d
saved = {k: os.environ.get(k) for k in ("http_proxy", "no_proxy", "NO_PROXY")}
os.environ["http_proxy"] = f"http://127.0.0.1:{proxy}"
os.environ.pop("no_proxy", None), os.environ.pop("NO_PROXY", None)
try:
mod.engine_info(f"http://127.0.0.1:{engine}")
finally:
for k, v in saved.items():
os.environ.pop(k, None) if v is None else os.environ.__setitem__(k, v)
self.assertEqual(seen, ["/server_info"], "through a proxy its path is the whole address")
class GetShSaysWhatGitSaid(Tmp):
def test_its_first_line_and_never_a_password(self):
text = (REPO / "get.sh").read_text()
block = text[text.index(" if ! SAID=$(git -C"):]
block = block[:block.index("\n fi\n") + 6]
for said, want in (("error: insufficient permission for adding an object to repository database .git/objects",
"git says: insufficient permission for adding an object to repository database .git/objects"),
("fatal: unable to access https://me:s3cret@github.com/x/y/: boom",
"git says: unable to access https://github.com/x/y/: boom"), ("", "")):
with self.subTest(said=said):
self.fake("git", f"echo '{said}' >&2; echo 'fatal: the second line' >&2; exit 1\n" if said else "exit 1\n")
r = bash("set -euo pipefail\nDIR=/x\n" + block, path=self.bin)
self.assertEqual(r.returncode, 1)
self.assertIn(want, r.stderr)
self.assertEqual("git says" in r.stderr, bool(said))
for leak in ("s3cret", "fatal", "second line"):
self.assertNotIn(leak, r.stderr)
class ThePreflightReadsNumbersInNoLocale(unittest.TestCase):
def test_its_locale(self):
text = (REPO / "engine-preflight.sh").read_text()
self.assertLess(text.index("export LC_ALL=C\n"), text.index("awk '"))
if __name__ == "__main__":
sys.exit(unittest.main(verbosity=1))