From 344af51ce8c3ca32e4d2f2f3f4c758d7c35848d7 Mon Sep 17 00:00:00 2001 From: Hasan Basbunar Date: Mon, 30 Nov 2026 08:29:00 +0100 Subject: [PATCH] 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 --- engine-preflight.sh | 2 + get.sh | 7 +- install.sh | 78 ++++++-- lanes.sh | 66 +++++++ tests/test_engine_inputs.py | 4 +- tests/test_engine_key_file.py | 2 +- tests/test_engine_preflight.py | 5 +- tests/test_flash_ats_check.py | 2 +- tests/test_image_lane_removal.py | 2 +- tests/test_install_every_lane.py | 2 +- tests/test_install_restarts.py | 2 +- tests/test_install_robust.py | 295 ++++++++++++++++++++++++++++++ tests/test_update_no_boot_lane.py | 2 +- 13 files changed, 441 insertions(+), 28 deletions(-) create mode 100644 tests/test_install_robust.py diff --git a/engine-preflight.sh b/engine-preflight.sh index bf4bf105..13548329 100755 --- a/engine-preflight.sh +++ b/engine-preflight.sh @@ -27,6 +27,8 @@ # # usage: engine-preflight.sh set -u +# a decimal comma from awk (mawk under fr_FR) read as a string past every bound below, and a start was refused +export LC_ALL=C LANE="${1:-engine}" WAIT_S="${QWEN38_PREFLIGHT_WAIT_S:-60}" HELD_MIB_MAX="${QWEN38_PREFLIGHT_HELD_MIB:-2048}" diff --git a/get.sh b/get.sh index 6c21ef03..0c6f6463 100755 --- a/get.sh +++ b/get.sh @@ -153,8 +153,11 @@ main() { # a raw "fatal:") told the operator nothing, and the sources of tag below were never # reached anyway (review, 2026-11-20). Nothing has been written at this point: not the # clone, not a branch, not the channel file. - if ! git -C "$DIR" fetch -q origin main 2>/dev/null; then - echo "ERROR: cannot reach GitHub (no network, or GitHub is down): the fetch of main failed." >&2 + if ! SAID=$(git -C "$DIR" fetch -q origin main 2>&1); then + echo "ERROR: cannot reach GitHub (no network, or GitHub is down), or this clone is not yours to update: the fetch of main failed." >&2 + # git's own words: a clone a sudo git left to root read as a network down (2026-11-30). Never a password in an address. + SAID=$(printf '%s\n' "$SAID" | LC_ALL=C sed -nE -e 's#(://)[^/@[:space:]]*@#\1#g' -e 's#^(fatal|error): ##' -e '/./{p;q}') + [ -z "$SAID" ] || echo " git says: $SAID" >&2 echo " Nothing was touched: the clone, its branches and the channel file are as they were." >&2 echo " try again once online." >&2 exit 1 diff --git a/install.sh b/install.sh index 5a6eaae0..39b8ac74 100755 --- a/install.sh +++ b/install.sh @@ -18,6 +18,19 @@ trap 'printf "\n\033[1;31mInstall failed at line %s (command: %s).\033[0m\nRe-ru # exited through the ERR trap, losing the message that names the problem # (tests/test_install_preflight.py pins that failure mode on the port checks). die() { printf '\n\033[1;31mERROR:\033[0m %s\n' "$*" >&2; exit 1; } +# $2 replaced by $1 whole, or not at all: install(1) empties the file first, and a disk that filled left the proxy cut +# short, the box's API gone at its next start (2026-11-30). +put_whole(){ + install -m 755 "$1" "$2.new" && mv -f "$2.new" "$2" && return 0 + rm -f "$2.new"; die "could not write $2 (is that disk full?): the one in place is kept" +} +# An image named by its digest is its content: one already here asks nothing of the network, nor of Docker Hub's rate +# limit, which an update offline, or of several boxes behind one address, died on (2026-11-30). +have_image(){ + case "$1" in *@sha256:*) docker image inspect "$1" >/dev/null 2>&1 && echo "already here" ;; *) return 1 ;; esac +} +SUDO_KEEPER="" +forget_sudo_keeper(){ [ -z "$SUDO_KEEPER" ] || kill "$SUDO_KEEPER" 2>/dev/null || true; return 0; } # One spelling of the home, without a trailing slash: a home given as "/home/nvidia/" in /etc/passwd # (on a second ASUS Ascent GX10) put a "//" in every path built on it, while systemd hands the cockpit the @@ -2180,13 +2193,20 @@ step "1/10 Preflight checks" # `bash -c` line, in a docker `-v src:dst`, and in systemd's own syntax, where % is a # specifier. A space, a colon, a quote, a $ or a % in one was accepted and broke the # unit it went into, seen only when that failed to start (found in review, 2026-09-24). -for _p in "HOME=$HOME" "HF_CACHE=$HF_CACHE" "PLE_DIR=$PLE_DIR"; do +# the clone too, for the cockpit's unit, which runs from it (2026-11-30) +_paths=("HOME=$HOME" "HF_CACHE=$HF_CACHE" "PLE_DIR=$PLE_DIR"); [ "$NO_COCKPIT" -eq 1 ] || _paths+=("REPO_DIR=$REPO_DIR") +for _p in "${_paths[@]}"; do case "${_p#*=}" in /*) case "${_p#*=}" in *[!A-Za-z0-9._/+@-]*) die "${_p%%=*}=${_p#*=}: the units this installs cannot carry that path. Use an absolute path of letters, digits and . _ / + @ - only." ;; esac ;; *) die "${_p%%=*}=${_p#*=}: an absolute path is needed (the units carry it as it is)." ;; esac done -unset _p +unset _p _paths +for _p in "$HF_CACHE" "$PLE_DIR"; do + _m="$(unmounted_disk_of "$_p")" + [ -z "$_m" ] || die "$_p is on $_m, which /etc/fstab mounts and is not mounted now: its weights would be downloaded again onto the system disk. Mount it (sudo mount $_m), then run this again." +done +unset _p _m command -v nvidia-smi >/dev/null || die "nvidia-smi not found. Is the NVIDIA driver stack installed? (stock on DGX OS)" # nvidia-smi says what is wrong when it cannot reach the driver, and exits non-zero: # inside a bare $(...) under set -e that ended the install with only "Install failed at @@ -2215,6 +2235,10 @@ docker_grant bash "$REPO_DIR/${BASH_SOURCE[0]##*/}" "$@" # this run, said to the cockpit while it lasts (lanes.sh, run_mark); the run it starts for the other # text lane is part of it [ -n "$SECONDARY" ] || run_mark "$CONFIG_DIR"; trap forget_run_mark EXIT +if [ -z "$SECONDARY" ]; then + BESIDE="$(runs_beside "$CONFIG_DIR")" + [ -z "$BESIDE" ] || die "this box is busy with $(printf '%s' "$BESIDE" | paste -sd ',' | sed 's/,/, /g'): an install now would cut it or meet it half way. Run this again once it is done (the cockpit's Now view says when)." +fi # A GPU outside its ATS addressing mode cannot start the flash lane (issue #54), and a flash install # fetches its image and its checkpoint (223 GB in all). A new flash install stops here, before the # first byte. A run for a box whose flash lane is installed gives it its units only, which say why at @@ -2460,6 +2484,13 @@ if [ "$NO_SERVICE" -eq 0 ] && ! sudo -n true 2>/dev/null; then echo "sudo is needed from step 8 on (systemd units); it asks for your password now, before the downloads." sudo -v || die "sudo could not be used here: run 'sudo -v' in this terminal, then re-run ./install.sh" fi +# Its timestamp (15 min on a stock box) is kept for as long as this run lasts: a lane's download is longer, and the prompt +# that came after it, with nobody there any more, ended the install (2026-11-30). +if [ "$NO_SERVICE" -eq 0 ] && [ -z "$SECONDARY" ]; then + ( while sleep 60; do kill -0 "$$" && sudo -n -v || exit 0; done ) /dev/null 2>&1 & + SUDO_KEEPER=$! + trap 'forget_run_mark; forget_sudo_keeper' EXIT +fi echo "OK (aarch64, ${TOTAL_GIB} GiB of memory: a ${MEM_CLASS} GB box, ${FREE_DISK_GB} GiB free)" # What the image and video lanes build or run with, which DGX OS lacks: Python's headers, which # their first Load builds xatlas against, and ffmpeg, which the video pipeline refuses to start @@ -2517,11 +2548,11 @@ if [ "$UNITS_ONLY" -eq 1 ]; then PULLED_IMAGE="$PULL_TARGET" elif [ "$LANE" = "flash" ]; then step "2/10 Pulling the official SGLang Flash-Next image (~16 GB to download, 35 GB on disk, one-time, resumable)" - docker pull "$PULL_TARGET" || die "docker pull failed. Causes: no internet, Docker Hub rate limit (retry in a few minutes or 'docker login'), or the pinned image was removed upstream, its dated tag (lmsysorg/sglang:nightly-cu134-20261011-53295c6) with it: update this repo, or open an issue on GitHub if it is up to date" + have_image "$PULL_TARGET" || docker pull "$PULL_TARGET" || die "docker pull failed. Causes: no internet, Docker Hub rate limit (retry in a few minutes or 'docker login'), or the pinned image was removed upstream, its dated tag (lmsysorg/sglang:nightly-cu134-20261011-53295c6) with it: update this repo, or open an issue on GitHub if it is up to date" PULLED_IMAGE="$PULL_TARGET" else step "2/10 Pulling the SGLang image (~15 GB to download, 34 GB on disk, one-time, resumable)" - docker pull "$PULL_TARGET" || die "docker pull failed. Causes: no internet, Docker Hub rate limit (retry in a few minutes or 'docker login'), or the pinned digest was removed upstream: try IMAGE=lmsysorg/sglang:v0.5.22 ./install.sh, the moving tag of the same release" + have_image "$PULL_TARGET" || docker pull "$PULL_TARGET" || die "docker pull failed. Causes: no internet, Docker Hub rate limit (retry in a few minutes or 'docker login'), or the pinned digest was removed upstream: try IMAGE=lmsysorg/sglang:v0.5.22 ./install.sh, the moving tag of the same release" PULLED_IMAGE="$PULL_TARGET" fi # pin_tag, the local tag a digest pull needs to survive a docker image prune: in lanes.sh @@ -2680,17 +2711,17 @@ KEY="$(cat "$CONFIG_DIR/api-key")" # used by the step-9 smoke test # before every start (the units, the flash launcher, run.sh): as --api-key "$(cat ...)" it # was in the argv of the docker client and of the server (found in review, 2026-09-24). cmp -s "$REPO_DIR/engine-secrets.sh" "$CONFIG_DIR/engine-secrets.sh" \ - || install -m 755 "$REPO_DIR/engine-secrets.sh" "$CONFIG_DIR/engine-secrets.sh" + || put_whole "$REPO_DIR/engine-secrets.sh" "$CONFIG_DIR/engine-secrets.sh" bash "$CONFIG_DIR/engine-secrets.sh" || die "could not write the engine's key file from $CONFIG_DIR/api-key (see above)" # Every engine unit runs this before it starts (the last engine's GPU memory has to be back, # see engine-preflight.sh), so it is in place before any unit that names it can start. cmp -s "$REPO_DIR/engine-preflight.sh" "$CONFIG_DIR/engine-preflight.sh" \ - || install -m 755 "$REPO_DIR/engine-preflight.sh" "$CONFIG_DIR/engine-preflight.sh" + || put_whole "$REPO_DIR/engine-preflight.sh" "$CONFIG_DIR/engine-preflight.sh" # The flash launcher asks it before every start (a GB10 outside its ATS addressing mode cannot # serve the lane's N-gram table from a file, issue #54); every box gets it, as a flash lane # installed on demand starts from its first Load. cmp -s "$REPO_DIR/flash-ats-check.sh" "$CONFIG_DIR/flash-ats-check.sh" \ - || install -m 755 "$REPO_DIR/flash-ats-check.sh" "$CONFIG_DIR/flash-ats-check.sh" + || put_whole "$REPO_DIR/flash-ats-check.sh" "$CONFIG_DIR/flash-ats-check.sh" # One patched template per engine file name: the served template always follows # the served model (the five fixes: reasoning_effort normalization, lean, the # refusal's wording, mid-conversation system messages as blocks, @@ -3699,8 +3730,10 @@ try: except OSError: same = False if not same: - with open(f"{cfg_dir}/opencode.json", "w") as f: + # whole or not at all: a disk that filled left half a config, opencode and the Agent tab down with it + with open(f"{cfg_dir}/opencode.json.new", "w") as f: f.write(text) + os.replace(f"{cfg_dir}/opencode.json.new", f"{cfg_dir}/opencode.json") print(f"{'kept' if same else 'wrote'} {cfg_dir}/opencode.json (default {default}, " f"providers: {', '.join(providers) or 'none'})") PYEOF @@ -4224,7 +4257,7 @@ render_tpl() { # $1 template file; substituted result on stdout # a mktemp and its rm left the rendered file in /tmp (2026-10-03). Subshells reset the trap. RENDERED=() forget_rendered(){ local f; for f in "${RENDERED[@]}"; do if [ -f "$f" ]; then rm -f -- "$f"; fi; done; return 0; } -trap 'forget_rendered; forget_run_mark' EXIT +trap 'forget_rendered; forget_run_mark; forget_sudo_keeper' EXIT if [ "$LANE" = "flash" ]; then mkdir -p "$PLE_DIR" # The docker-run command lives in a plain launch script, not in ExecStart: @@ -4254,7 +4287,7 @@ if [ "$LANE" = "flash" ]; then || cp "$TMP_LAUNCH" "$CONFIG_DIR/pending/qwen38-flash.service" echo "its new launch script waits for its Load, the one in place kept: it lacks $(unit_pending_says qwen38-flash.service) (decision 1408)" else - install -m 755 "$TMP_LAUNCH" "$CONFIG_DIR/launch-flash.sh" + put_whole "$TMP_LAUNCH" "$CONFIG_DIR/launch-flash.sh" # the new launcher is in place and reads what the box has: a wait of an earlier run (rendered against # another launcher) is cleared here, as the unchanged branch above and unit_put's unit_pending_clear do # (fifth review of v1.52.0, 2026-11-19, GLM 5.3: it stayed, and the Load then prepared for a launcher @@ -4389,7 +4422,7 @@ FLASH_PROMPT_CEILING="${FLASH_PROMPT_CEILING_TOKENS:-250000}" # at native context) and agent CLIs abort a silent stream (~140-180 s for # opencode). It also aborts zombie generations when the client disconnects. cmp -s "$REPO_DIR/keepalive-proxy.py" "$CONFIG_DIR/keepalive-proxy.py" \ - || { install -m 755 "$REPO_DIR/keepalive-proxy.py" "$CONFIG_DIR/keepalive-proxy.py"; KA_CHANGED=1; } + || { put_whole "$REPO_DIR/keepalive-proxy.py" "$CONFIG_DIR/keepalive-proxy.py"; KA_CHANGED=1; } TMP_KA="$(mktemp)"; RENDERED+=("$TMP_KA") sed -e "s|__HOME__|$HOME|g" \ -e "s|__USER__|$(id -un)|g" \ @@ -4600,6 +4633,7 @@ else esac else step "Done: the text lane is up to date; $ENDS" + [ "$WAITS_LOAD" -eq 0 ] || echo " its update waits for its next Load, which downloads what it needs: $WAITS_WHAT" if [ "$STARTS_NONE" = beside ] && systemctl is-enabled --quiet "$UNIT_NAME" 2>/dev/null; then echo " text lane : installed as $UNIT_NAME, enabled at boot as before, not started" else @@ -4640,6 +4674,14 @@ if [ "$NO_START" -eq 1 ]; then exit 0 fi +# The engine loads: its unit runs since less than 30 min, and the engine does not answer yet. +engine_loads(){ + local at now + [ "$(systemctl show -p ActiveState --value "$UNIT_NAME" 2>/dev/null)" = active ] || return 1 + at="$(systemctl show -p ActiveEnterTimestampMonotonic --value "$UNIT_NAME" 2>/dev/null | tr -dc 0-9)" + now="$(awk '{printf "%.0f", $1 * 1000000}' /proc/uptime)" + [ -n "$at" ] && [ "$at" -gt 0 ] && [ $((now - at)) -lt 1800000000 ] +} # Kept only when the running engine started after every file it reads was last written, # this run changed none of them by content (engine-inputs.py), and it answers. ENGINE_KEEP=0; ENGINE_WHY="" @@ -4649,10 +4691,14 @@ elif [ "$ENGINE_RUNNING_IT" != "yes" ]; then ENGINE_WHY="${ENGINE_RUNNING_IT#no: }" elif [ -z "$ENGINE_FP_BEFORE" ] || [ "$(python3 "$REPO_DIR/engine-inputs.py" fingerprint "$ENGINE_UNIT_PATH" "$CONFIG_DIR" "$HF_CACHE" "${ENGINE_CKPTS[@]}" 2>/dev/null || true)" != "$ENGINE_FP_BEFORE" ]; then ENGINE_WHY="this run changed what it reads" -elif ! curl -sf -m 5 "http://127.0.0.1:$PORT/health" >/dev/null 2>&1; then - ENGINE_WHY="it does not answer /health" -else +elif curl -sf -m 5 "http://127.0.0.1:$PORT/health" >/dev/null 2>&1; then ENGINE_KEEP=1 +elif engine_loads; then + # started over, it would begin again: 3.5 to 15 min (2026-11-30) + ENGINE_KEEP=1 + echo "$UNIT_NAME is still loading, with what this run has: waited for, not started over" +else + ENGINE_WHY="it does not answer /health" fi if [ "$ENGINE_KEEP" -eq 1 ]; then step "9/10 Keeping the running engine: nothing it reads changed since it started (RESTART_ENGINE=1 restarts it)" @@ -4692,7 +4738,7 @@ prove_text_lane(){ r0="$(systemctl show -p NRestarts --value "$unit" 2>/dev/null | tr -dc '0-9')" sudo systemctl start "$unit" || { echo "NOTE: $unit did not start (journalctl -u $unit -n 50)"; return 1; } for n in $(seq 1 150); do - if curl -s -m 2 "http://127.0.0.1:$PORT/health" >/dev/null 2>&1; then + if curl -sf -m 2 "http://127.0.0.1:$PORT/health" >/dev/null 2>&1; then raw="$(curl -s -m 300 "http://127.0.0.1:$PORT/v1/chat/completions" \ -H @<(printf 'Authorization: Bearer %s\n' "$KEY") -H 'Content-Type: application/json' \ -d '{"model":"'"$model"'","messages":[{"role":"user","content":"Reply with exactly: READY"}],"max_tokens":600}')" \ @@ -4731,7 +4777,7 @@ except Exception as e: LOAD_WHY="first boot compiles kernels, be patient" [ "$LANE" = "flash" ] && LOAD_WHY="every boot writes the 47.7 GiB PLE table, be patient" for i in $(seq 1 150); do - if curl -s -m 2 "http://127.0.0.1:$PORT/health" >/dev/null 2>&1; then + if curl -sf -m 2 "http://127.0.0.1:$PORT/health" >/dev/null 2>&1; then echo "health OK, running a real generation smoke test..." # curl on its own, so its failure is named: in the pipe it came out through the ERR trap # as "Install failed at line N", and the pointer to the journal below never showed. A diff --git a/lanes.sh b/lanes.sh index 45e4622f..b2cfe8ce 100644 --- a/lanes.sh +++ b/lanes.sh @@ -12,6 +12,16 @@ # one record there is no chain to follow, and no loop to close. LANES_UNIT_DIR="${LANES_UNIT_DIR:-/etc/systemd/system}" +# Through a company proxy (http_proxy, and no no_proxy), curl sent each local probe there, the box's key in its +# Authorization header, and took the proxy's page for the engine's answer (found 2026-11-30): this box's own addresses +# never go through one, for every script that sources this one. +if [ -n "${http_proxy:-}${https_proxy:-}${HTTPS_PROXY:-}${all_proxy:-}${ALL_PROXY:-}" ]; then + for _v in no_proxy NO_PROXY; do + case ",${!_v:-}," in *,127.0.0.1,*|",*,") ;; *) export "$_v=127.0.0.1,localhost${!_v:+,${!_v}}" ;; esac + done + unset _v +fi + # The box's memory class and the lanes that fit it, from boxmem.py beside this file: 128, or 64 for # the 64 GB DGX Spark NVIDIA's partners ship from 2026-10-23, which gets only the lanes that fit it. _lanes_dir(){ case "${BASH_SOURCE[0]}" in */*) echo "${BASH_SOURCE[0]%/*}" ;; *) echo . ;; esac; } @@ -1091,6 +1101,62 @@ PY return 0 } forget_run_mark(){ [ -z "$RUN_MARK" ] || rm -f -- "$RUN_MARK"; return 0; } +# runs_beside CONFIG_DIR: what runs on this box now that an install would cut or meet half way, one a line: another install +# (its mark, run_mark), a Load or a Download of this account (switch-model.sh, prepare-lane.sh), which the cockpit's restart +# at the end of an install stops with the cockpit's other jobs. +runs_beside(){ + python3 -I - "$1" "$$" <<'PY' 2>/dev/null || true +import json, os, re, sys +def stat_of(pid): # the fields of /proc//stat after the name in parentheses: the 4th is the parent, the 22nd the start + with open(f"/proc/{pid}/stat") as f: + s = f.read() + return s[s.rindex(")") + 2:].split() +mine, pid = set(), int(sys.argv[2]) +while pid > 1: # this run and what started it: a Load that runs the installer is not beside it + mine.add(pid) + try: + pid = int(stat_of(pid)[1]) + except (OSError, ValueError, IndexError): + break +for name in sorted(os.listdir(sys.argv[1]) if os.path.isdir(sys.argv[1]) else []): + m = re.fullmatch(r"install-running\.(\d+)\.json", name) + if not m or int(m.group(1)) in mine: + continue + try: + with open(os.path.join(sys.argv[1], name)) as f: + started = str(json.load(f)["start"]) + if stat_of(int(m.group(1)))[19] == started: + print(f"another install (pid {m.group(1)})") + except (OSError, ValueError, KeyError, TypeError, IndexError): + pass +for d in os.listdir("/proc"): + if not d.isdigit() or int(d) in mine: + continue + try: + if os.stat(f"/proc/{d}").st_uid != os.getuid(): + continue + with open(f"/proc/{d}/cmdline", "rb") as f: + argv = [a.decode(errors="replace") for a in f.read().split(b"\0")[:-1]] + except OSError: + continue + for i, a in enumerate(argv[:2]): + if os.path.basename(a) in ("switch-model.sh", "prepare-lane.sh"): + print(f"{' '.join([os.path.basename(a), *argv[i + 1:i + 3]])} (pid {d})") + break +PY +} +# The mount point /etc/fstab has over $1 that is not mounted now; nothing when there is none. A cache on a disk that did not +# mount is an empty folder of the system disk, and an update fetched every weight again under the mount point (2026-11-30). +unmounted_disk_of(){ + local p m + p="$(realpath -m -- "$1")" + while read -r _ m _; do + case "$m" in /|none|swap|"") continue ;; esac + m="$(printf '%b' "${m//\\/\\0}")" # fstab writes a space \040 + case "$p/" in "${m%/}"/*) mountpoint -q -- "$m" || { echo "$m"; return 0; } ;; esac + done < <(grep -vE '^[[:space:]]*(#|$)' "${QWEN38_FSTAB:-/etc/fstab}" 2>/dev/null) + return 0 +} # A diffusion lane's own sockets (v1.40.6): torch's TCPStore listens on every interface whatever its rendezvous # address (port 30005), and gloo's and NCCL's bootstrap took the box's LAN address until the unit pinned it to lo diff --git a/tests/test_engine_inputs.py b/tests/test_engine_inputs.py index 07fced5c..9f378105 100644 --- a/tests/test_engine_inputs.py +++ b/tests/test_engine_inputs.py @@ -513,8 +513,8 @@ class TheInstallerDecides(unittest.TestCase): # pending/, the launcher the engine reads untouched) self.assertRegex(text, r'if cmp -s "\$TMP_LAUNCH" "\$CONFIG_DIR/launch-flash\.sh"; then\n' r'\s*echo "launch script unchanged[^\n]*\n(?:[^\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" "$CONFIG_DIR/launch-flash.sh"'), 1, + r'\s*put_whole "\$TMP_LAUNCH" "\$CONFIG_DIR/launch-flash\.sh"\n') + self.assertEqual(text.count('put_whole "$TMP_LAUNCH" "$CONFIG_DIR/launch-flash.sh"'), 1, "no other path writes the launcher") def test_the_restart_itself_is_the_one_the_decision_guards(self): diff --git a/tests/test_engine_key_file.py b/tests/test_engine_key_file.py index ed237dc9..fe0e2bde 100644 --- a/tests/test_engine_key_file.py +++ b/tests/test_engine_key_file.py @@ -43,7 +43,7 @@ class TheKeyFile(unittest.TestCase): self.assertLess(flash.index("/bin/bash __HOME__/.config/qwen38/engine-secrets.sh"), flash.index("exec /usr/bin/docker run")) install = (REPO / "install.sh").read_text() - self.assertIn('install -m 755 "$REPO_DIR/engine-secrets.sh" "$CONFIG_DIR/engine-secrets.sh"', install) + self.assertIn('put_whole "$REPO_DIR/engine-secrets.sh" "$CONFIG_DIR/engine-secrets.sh"', install) self.assertIn('bash "$CONFIG_DIR/engine-secrets.sh"', install) def test_the_helper_writes_a_private_yaml_once(self): diff --git a/tests/test_engine_preflight.py b/tests/test_engine_preflight.py index 3e76575d..9f9eae84 100644 --- a/tests/test_engine_preflight.py +++ b/tests/test_engine_preflight.py @@ -336,7 +336,8 @@ class WhereItRuns(unittest.TestCase): ("vllm-lane.sh", "$HERE")): with self.subTest(inst=inst): text = (REPO / inst).read_text() - self.assertIn(f'install -m 755 "{src}/engine-preflight.sh" "$CONFIG_DIR/engine-preflight.sh"', text) + put = "put_whole" if inst == "install.sh" else "install -m 755" + self.assertIn(f'{put} "{src}/engine-preflight.sh" "$CONFIG_DIR/engine-preflight.sh"', text) # written only when it changed, so an unchanged run rewrites nothing self.assertIn(f'cmp -s "{src}/engine-preflight.sh" "$CONFIG_DIR/engine-preflight.sh"', text) for inst in ("install-image.sh", "install-video.sh"): @@ -348,7 +349,7 @@ class WhereItRuns(unittest.TestCase): text = (REPO / inst).read_text() self.assertLess(text.index(" vlane_service_files "), text.index('"$HERE/$UNIT.template"'), inst) install = (REPO / "install.sh").read_text() - self.assertLess(install.index('install -m 755 "$REPO_DIR/engine-preflight.sh"'), + self.assertLess(install.index('put_whole "$REPO_DIR/engine-preflight.sh"'), install.index("qwen38-sglang.service.template")) def test_it_is_a_bash_script_that_says_what_it_does_on_one_line(self): diff --git a/tests/test_flash_ats_check.py b/tests/test_flash_ats_check.py index 1f616797..a5101cfa 100644 --- a/tests/test_flash_ats_check.py +++ b/tests/test_flash_ats_check.py @@ -177,7 +177,7 @@ class TheInstaller(Box): def test_every_box_gets_the_check_as_it_gets_the_engine_preflight(self): self.assertIn('cmp -s "$REPO_DIR/flash-ats-check.sh" "$CONFIG_DIR/flash-ats-check.sh"', self.TEXT) - self.assertIn('install -m 755 "$REPO_DIR/flash-ats-check.sh" "$CONFIG_DIR/flash-ats-check.sh"', self.TEXT) + self.assertIn('put_whole "$REPO_DIR/flash-ats-check.sh" "$CONFIG_DIR/flash-ats-check.sh"', self.TEXT) def test_a_flash_install_asks_before_its_first_download(self): line = 'if [ "$LANE" = "flash" ] && ATS_CANNOT="$(flash_cannot_start)"; then' diff --git a/tests/test_image_lane_removal.py b/tests/test_image_lane_removal.py index 14201ba6..ed2c0498 100644 --- a/tests/test_image_lane_removal.py +++ b/tests/test_image_lane_removal.py @@ -58,7 +58,7 @@ class BothPathsRemoveOnlyTheLane(unittest.TestCase): lambda d: {"IMAGE_LANE_DIR": d, "PRIV": "0", "PRIV_DONE": "0"}), ("install-image.sh --uninstall", lambda: removal(INSTALL_IMAGE, 'if [ -d "$LANE_DIR" ]; then'), lambda d: {"LANE_DIR": d, "VENV": f"{d}/venv", "SRC": f"{d}/sglang", "WHEEL_NOTE": f"{d}/sglang-wheel", - "SOURCE_NOTE": f"{d}/sglang-source"}), + "SOURCE_NOTE": f"{d}/sglang-source", "RUNTIME_NOTE": f"{d}/runtime-changed"}), ) def test_a_shared_directory_keeps_everything_else(self): diff --git a/tests/test_install_every_lane.py b/tests/test_install_every_lane.py index e18966bb..f99e2769 100644 --- a/tests/test_install_every_lane.py +++ b/tests/test_install_every_lane.py @@ -645,7 +645,7 @@ class ItLeavesWhatIsSharedToItsParent(unittest.TestCase): self.assertIn(guarded, TEXT) ka = TEXT.index('KEEPALIVE_UNIT="qwen38-keepalive.service"\n') gate = TEXT.index('if [ -z "$SECONDARY" ]; then\n', ka) - self.assertLess(gate, TEXT.index('install -m 755 "$REPO_DIR/keepalive-proxy.py"', ka)) + self.assertLess(gate, TEXT.index('put_whole "$REPO_DIR/keepalive-proxy.py"', ka)) self.assertLess(gate, TEXT.index('sudo systemctl enable "$KEEPALIVE_UNIT"', ka)) def test_it_ends_before_enabling_or_starting_anything(self): diff --git a/tests/test_install_restarts.py b/tests/test_install_restarts.py index 986dec90..056d0a06 100644 --- a/tests/test_install_restarts.py +++ b/tests/test_install_restarts.py @@ -84,7 +84,7 @@ class EachRestartHasAReason(unittest.TestCase): guard = INSTALL[INSTALL.rfind("if ", 0, m.start()):m.start()] self.assertIn("stale_since \"$KEEPALIVE_UNIT\"", guard, INSTALL[m.start() - 200:m.start()]) self.assertIn('"$KA_CHANGED" -eq 1', guard) - for write in ('install -m 755 "$REPO_DIR/keepalive-proxy.py" "$CONFIG_DIR/keepalive-proxy.py"; KA_CHANGED=1', + for write in ('put_whole "$REPO_DIR/keepalive-proxy.py" "$CONFIG_DIR/keepalive-proxy.py"; KA_CHANGED=1', 'sudo install -m 644 "$TMP_KA" "/etc/systemd/system/$KEEPALIVE_UNIT"; KA_CHANGED=1'): self.assertIn(write, INSTALL) diff --git a/tests/test_install_robust.py b/tests/test_install_robust.py new file mode 100644 index 00000000..6d7bf278 --- /dev/null +++ b/tests/test_install_robust.py @@ -0,0 +1,295 @@ +#!/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)) diff --git a/tests/test_update_no_boot_lane.py b/tests/test_update_no_boot_lane.py index 4884195a..d77205af 100644 --- a/tests/test_update_no_boot_lane.py +++ b/tests/test_update_no_boot_lane.py @@ -273,7 +273,7 @@ class NoLaneAtBoot(unittest.TestCase): def test_the_lane_named_is_fetched_now_and_not_started(self): u = Update(prepared=(), args=("--with-27b",)) self.beside(u) - self.assertIn("docker pull", " ".join(u.downloads)) + self.assertNotIn("docker pull", " ".join(u.downloads), "this docker has the image, named by its digest") self.assertTrue([c for c in u.calls if c.startswith("docker run") and STOCK[0] in c], "its checkpoint was not fetched") u = Update(args=("--with-image",)) self.beside(u)