Files
alzeo/tests/test_install_robust.py
T
Hasan BasbunarandClaude Opus 5.5 344af51ce8 install: a full disk, a company proxy, no network, an unmounted cache, a Load under way and a slow download are met as they are
Found on 2026-11-30 by the audit of this version (update-risks). A file the box runs is replaced whole or not at all (a
full disk left the proxy cut short, the API gone at its next start); the box's own addresses never go through http_proxy
(the key went there in clear, and its page was taken for the engine's answer); an image named by its digest and already
here is not pulled; a cache on a disk fstab mounts and is not mounted is refused instead of downloaded again under the
mount point; an install beside another one or a Load is refused; an engine still loading is waited for, not started over;
sudo's timestamp lasts as long as the run; get.sh says what git said; the preflight reads numbers in no locale.

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

296 lines
14 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"(?ms)^{name}\(\)\s*\{{.*?^\}}$", text) or re.search(rf"(?m)^{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"),
({"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_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):
def loads(self, state, age_s):
up = float(pathlib.Path("/proc/uptime").read_text().split()[0])
at = "" if age_s is None else str(int((up - age_s) * 1e6))
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 ( while sleep 60'):]
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')
self.fake("sleep", 'exec /bin/sleep 0.1\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)
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 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))