diff --git a/engine-preflight.sh b/engine-preflight.sh index 7656ac06..5400be41 100755 --- a/engine-preflight.sh +++ b/engine-preflight.sh @@ -55,7 +55,7 @@ gpu_holders() { # SGLang's lanes, and the Kolibri lane's vLLM: its engine core is VLLM::EngineCore (the # kernel keeps 15 characters of it) and its API server a python3 running vllm serve. if [ ! -d "$PROC/$pid" ] || [[ "$comm" == sglang* ]] || [[ "$cmd" == *sglang* ]] \ - || [[ "$comm" == VLLM::* ]] || [[ "$cmd" == *vllm\ serve* ]] || [[ "$cmd" == *vllm/* ]]; then + || [[ "$comm" == VLLM::* ]] || [[ "$cmd" == *vllm\ serve* ]]; then eng=$((eng + mib)); rem+="$pid ${comm:-gone} $mib MiB; " else oth+="$pid ${comm:-$name} $mib MiB; " diff --git a/install-kolibri.sh b/install-kolibri.sh index 28db26f4..aabadbac 100755 --- a/install-kolibri.sh +++ b/install-kolibri.sh @@ -143,6 +143,44 @@ if [ "$ACTION" = uninstall ]; then rm -f "$CONFIG_DIR/lane-before-$SIDE" fi done + # opencode and pi: the kolibri provider goes, and a default that named it follows the text + # lane this box had before Kolibri (oc-point-default.py with no target: no name changes). + # Left as they were, opencode offered and defaulted to a model nothing served, and its + # small-model calls sent Kolibri's level "none" to the Qwen template, which refuses it + # (found in review, 2026-10-14). + OC_BACK="$KOL_BEFORE" + for _ in 1 2 3; do + case "$OC_BACK" in + qwen38-image.service|qwen38-video.service) + SIDE="${OC_BACK#qwen38-}"; OC_BACK="$(cat "$CONFIG_DIR/lane-before-${SIDE%.service}" 2>/dev/null || true)" ;; + *) break ;; + esac + done + case "$OC_BACK" in + qwen38-flash.service) OC_LANE=flash ;; + qwen38-sglang.service) OC_LANE=27b ;; + *) OC_LANE=27b; [ -f /etc/systemd/system/qwen38-sglang.service ] || OC_LANE=flash ;; + esac + OC_SUM_BEFORE="$({ cat "$CONFIG_DIR/opencode.json" "$HOME/.config/opencode/opencode.json" 2>/dev/null || true; } | sha256sum)" + for OC_JSON in "$CONFIG_DIR/opencode.json" "$HOME/.config/opencode/opencode.json"; do + [ -f "$OC_JSON" ] || continue + WAS_DEFAULT=0 + grep -qsE '"model"[[:space:]]*:[[:space:]]*"kolibri/' "$OC_JSON" && WAS_DEFAULT=1 + python3 "$HERE/oc-merge-limits.py" "$OC_JSON" --remove-provider kolibri \ + || echo "NOTE: could not take the kolibri provider out of $OC_JSON; remove it by hand" + if [ "$WAS_DEFAULT" -eq 1 ]; then + python3 "$HERE/oc-point-default.py" "$OC_JSON" "$OC_LANE" "" "" \ + || echo "NOTE: could not point $OC_JSON at the $OC_LANE lane; set its \"model\" field yourself" + fi + done + if [ -d "$CONFIG_DIR/pi" ] || [ -d "$CONFIG_DIR/omp" ]; then + python3 "$HERE/pi-gen.py" --config "$CONFIG_DIR/opencode.json" --out "$CONFIG_DIR" \ + || echo "NOTE: could not regenerate the pi/omp artifacts; run ./pi-gen.py by hand" + fi + if [ "$OC_SUM_BEFORE" != "$({ cat "$CONFIG_DIR/opencode.json" "$HOME/.config/opencode/opencode.json" 2>/dev/null || true; } | sha256sum)" ] \ + && systemctl is-active --quiet opencode-web.service 2>/dev/null; then + sudo systemctl restart opencode-web.service && echo "opencode-web.service restarted so it reads the change" + fi rm -f "$CONFIG_DIR/lane-before-kolibri" docker rm -f "$CONTAINER" >/dev/null 2>&1 || true for img in $(docker images --format '{{.Repository}}:{{.Tag}}' 'qwen38-kolibri' 2>/dev/null); do @@ -150,6 +188,7 @@ if [ "$ACTION" = uninstall ]; then done # vLLM writes its compile cache as root inside the container: what the user cannot remove, sudo does rm -rf "$CONFIG_DIR/kolibri-cache" 2>/dev/null || sudo rm -rf --one-file-system "$CONFIG_DIR/kolibri-cache" + rm -rf "$CONFIG_DIR/vllm-auth" echo "the base image $KOLIBRI_BASE_IMAGE stays (docker rmi it yourself if nothing else uses it)" for R in "$KOLIBRI_FP8_REPO" "$KOLIBRI_NVFP4_REPO"; do D="$HF_CACHE/hub/models--${R//\//--}" @@ -164,7 +203,8 @@ command -v nvidia-smi >/dev/null || die "nvidia-smi not found: this needs the NV command -v docker >/dev/null || die "docker is required (stock on DGX OS)." docker info >/dev/null 2>&1 || die "docker does not answer for $(id -un). Is it running, and is $(id -un) in the docker group?" [ -s "$CONFIG_DIR/api-key" ] || die "no API key at $CONFIG_DIR/api-key. Run ./install.sh first: this lane serves behind the proxy with that key." -[ -f "$HERE/engine-preflight.sh" ] && [ -f "$HERE/engine-secrets.sh" ] || die "engine-preflight.sh or engine-secrets.sh is missing next to this script: run it from the repository." +[ -f "$HERE/engine-preflight.sh" ] && [ -f "$HERE/engine-secrets.sh" ] && [ -f "$HERE/vllm_engine_auth.py" ] \ + || die "engine-preflight.sh, engine-secrets.sh or vllm_engine_auth.py is missing next to this script: run it from the repository." # Measured where each part lands: the weights go to HF_CACHE, the image to Docker's own # disk. What the cache already holds of this checkpoint comes off its share, by bytes. existing(){ local p="$1"; while [ ! -e "$p" ]; do p="$(dirname "$p")"; done; printf '%s\n' "$p"; } @@ -176,7 +216,9 @@ IMAGE_NEED="$IMAGE_GB" docker image inspect "$LOCAL_IMAGE" >/dev/null 2>&1 && IMAGE_NEED=0 docker image inspect "$KOLIBRI_BASE_IMAGE" >/dev/null 2>&1 && IMAGE_NEED=0 FREE_W="$(free_gb "$HF_CACHE")"; FREE_D="$(free_gb "$DOCKER_ROOT")" -if [ "$(stat -c %d "$(existing "$HF_CACHE")")" = "$(stat -c %d "$(existing "$DOCKER_ROOT")")" ]; then +# -L: a cache moved to another disk behind a symlink (~/.cache/huggingface on an SSD) is on +# that disk; the link's own device is the home directory's, which skipped Docker's check. +if [ "$(stat -L -c %d "$(existing "$HF_CACHE")")" = "$(stat -L -c %d "$(existing "$DOCKER_ROOT")")" ]; then WANT=$((WEIGHTS_NEED + IMAGE_NEED)) [ "${FREE_W:-0}" -ge "$WANT" ] \ || die "${FREE_W:-?} GB free on the disk of $HF_CACHE and $DOCKER_ROOT, this needs about $WANT GB ($WEIGHTS_NEED for the checkpoint, $IMAGE_NEED for the image). Free some space, or ./install.sh --no-kolibri to leave this lane out." @@ -215,10 +257,6 @@ DEOF rm -rf "$BUILD" echo "built from $KOLIBRI_BASE_IMAGE and the plugin's wheel" fi -# Images of this lane built from older pins: the unit no longer names them. -for img in $(docker images --format '{{.Repository}}:{{.Tag}}' 'qwen38-kolibri' 2>/dev/null); do - [ "$img" = "$LOCAL_IMAGE" ] || { docker rmi "$img" >/dev/null 2>&1 && echo "removed the older build $img"; } -done step "3/5 Checkpoint ($MODEL @ ${MODEL_REV:0:12}, resumable)" mkdir -p "$HF_CACHE" @@ -253,6 +291,11 @@ cmp -s "$HERE/engine-preflight.sh" "$CONFIG_DIR/engine-preflight.sh" \ || install -m 755 "$HERE/engine-preflight.sh" "$CONFIG_DIR/engine-preflight.sh" cmp -s "$HERE/engine-secrets.sh" "$CONFIG_DIR/engine-secrets.sh" \ || install -m 755 "$HERE/engine-secrets.sh" "$CONFIG_DIR/engine-secrets.sh" +# The middleware that asks the key on every route of the engine (see vllm_engine_auth.py), +# in a directory of its own: the unit mounts that one, read-only, on the module path. +mkdir -p "$CONFIG_DIR/vllm-auth" +cmp -s "$HERE/vllm_engine_auth.py" "$CONFIG_DIR/vllm-auth/vllm_engine_auth.py" \ + || install -m 644 "$HERE/vllm_engine_auth.py" "$CONFIG_DIR/vllm-auth/vllm_engine_auth.py" RENDER="$(mktemp)"; trap 'rm -f "$RENDER"' EXIT sed -e "s|__USER__|$(id -un)|g" -e "s|__GROUP__|$(id -gn)|g" -e "s|__HOME__|$HOME|g" \ -e "s|__IMAGE__|$LOCAL_IMAGE|g" -e "s|__MODEL__|$MODEL|g" -e "s|__REV__|$MODEL_REV|g" \ @@ -269,6 +312,11 @@ else echo "NOTE: Kolibri is serving the unit it started with; it serves this one after: sudo systemctl restart $UNIT" fi fi +# Images of this lane built from older pins, once the unit names this one: removed before +# the checkpoint came, a failed download left the unit naming an image that was gone. +for img in $(docker images --format '{{.Repository}}:{{.Tag}}' 'qwen38-kolibri' 2>/dev/null); do + [ "$img" = "$LOCAL_IMAGE" ] || { docker rmi "$img" >/dev/null 2>&1 && echo "removed the older build $img"; } +done # Installed, not switched to: the lane this box serves stays the lane it serves. echo "installed as a lane of its own. Switch to it like any lane:" echo " the cockpit: Load on Kolibri-1 in the Lanes view" @@ -326,7 +374,11 @@ if "READY" not in text: raise SystemExit(f"reply: {text[:200]!r}") print(f" reply: {text[:40]!r}") PY -CODE="$(ask '{"model":"kolibri-1","messages":[{"role":"user","content":"What is the weather in Berlin? Use celsius."}],"max_tokens":2048,"tools":[{"type":"function","function":{"name":"get_weather","description":"Get the current weather for a city.","parameters":{"type":"object","properties":{"city":{"type":"string"},"unit":{"type":"string","enum":["celsius","fahrenheit"]}},"required":["city"]}}}]}')" +# At effort none: at high (the template's default), the kolibri1 reasoning parser cuts the +# reasoning at a the model writes inside it, and the call is missed, on 1.9 to +# 3.5 % of the replies to an English weather request like this one (Quantinine, both +# checkpoints); at none they measured every call parsed. A first install must not fail by chance. +CODE="$(ask '{"model":"kolibri-1","messages":[{"role":"user","content":"What is the weather in Berlin? Use celsius."}],"max_tokens":2048,"chat_template_kwargs":{"reasoning_effort":"none"},"tools":[{"type":"function","function":{"name":"get_weather","description":"Get the current weather for a city.","parameters":{"type":"object","properties":{"city":{"type":"string"},"unit":{"type":"string","enum":["celsius","fahrenheit"]}},"required":["city"]}}}]}')" [ "$CODE" = 200 ] || { echo "HTTP ${CODE:-000}: $(head -c 300 "$OUT")"; die "the tool-call request failed (HTTP ${CODE:-000})."; } python3 - "$OUT" <<'PY' || die "the lane did not return a parsed tool call (the kolibri1 parsers are not in effect?)." import json, sys @@ -338,10 +390,18 @@ args = json.loads(calls[0]["function"]["arguments"]) print(f" tool call: get_weather({args})") PY # The key must not be in the lane's journal (vLLM masks api_key in its argument log line). -if sudo journalctl -u "$UNIT" --since "$SINCE" --no-pager 2>/dev/null | grep -q -F -f <(head -1 "$CONFIG_DIR/api-key"); then - die "the API key appears in the lane's journal: rotate it, and report this." +# Read whole first, then searched: piped into grep -q under pipefail, a journal long enough +# to fill the pipe died of SIGPIPE at the first match, and the check read "not found". +JOURNAL_COPY="$(mktemp)" +# shellcheck disable=SC2024 # the copy is this user's own temporary file, written by this shell +if ! sudo journalctl -u "$UNIT" --since "$SINCE" --no-pager > "$JOURNAL_COPY" 2>/dev/null; then + rm -f "$JOURNAL_COPY"; die "the lane's journal could not be read to check the key is not in it." fi -echo " the key is in none of the lane's journal lines" +if grep -q -F -f <(head -1 "$CONFIG_DIR/api-key") "$JOURNAL_COPY"; then + rm -f "$JOURNAL_COPY"; die "the API key appears in the lane's journal: rotate it, and report this." +fi +echo " the key is in none of the lane's $(wc -l < "$JOURNAL_COPY") journal lines" +rm -f "$JOURNAL_COPY" # the trap stops the lane and brings the serving lane back, whichever way this ends step "Done: the Kolibri lane is installed and proved it serves on $ENGINE_BIND:$PORT" diff --git a/install.sh b/install.sh index 3e68318e..1d6c6843 100755 --- a/install.sh +++ b/install.sh @@ -601,6 +601,7 @@ done KEEP_MODEL_VERBATIM=0 SGL_UNIT_PATH="/etc/systemd/system/qwen38-sglang.service" FLASH_UNIT_PATH="/etc/systemd/system/qwen38-flash.service" +KOLIBRI_UNIT_PATH="/etc/systemd/system/qwen38-kolibri.service" for _p in "$SGL_UNIT_PATH" "$FLASH_UNIT_PATH"; do if [ -f "$_p" ] && [ ! -r "$_p" ]; then echo "NOTE: an installed unit ($_p) exists but is not readable (pre-v1.2.3 installs used mode 600)," @@ -1770,11 +1771,11 @@ OC_27B=0; OC_FLASH=0; OC_KOLIBRI=0 { [ "$LANE" = "flash" ] || [ -f "$FLASH_UNIT_PATH" ]; } && OC_FLASH=1 # The Kolibri lane is installed at the end of a run (install-kolibri.sh): its provider comes # with the first run that finds its unit, or with the first switch to it. -[ -f /etc/systemd/system/qwen38-kolibri.service ] && OC_KOLIBRI=1 +[ -f "$KOLIBRI_UNIT_PATH" ] && OC_KOLIBRI=1 OC_KOLIBRI_CTX=""; OC_KOLIBRI_OUT=""; OC_KOLIBRI_NAME="" if [ "$OC_KOLIBRI" -eq 1 ]; then OC_KOLIBRI_TARGET=kolibri - grep -qs -- "Quantinine/Kolibri-1-NVFP4A16-FP8 --revision" /etc/systemd/system/qwen38-kolibri.service && OC_KOLIBRI_TARGET=kolibri-nvfp4 + grep -qs -- "Quantinine/Kolibri-1-NVFP4A16-FP8 --revision" "$KOLIBRI_UNIT_PATH" && OC_KOLIBRI_TARGET=kolibri-nvfp4 OC_KOLIBRI_PAIR="$("$REPO_DIR/oc-limits.sh" "$OC_KOLIBRI_TARGET")" \ || die "oc-limits.sh refused $OC_KOLIBRI_TARGET (repo bug: please open an issue)" OC_KOLIBRI_CTX="${OC_KOLIBRI_PAIR%% *}"; OC_KOLIBRI_OUT="$(echo "$OC_KOLIBRI_PAIR" | cut -d' ' -f2)" @@ -1804,6 +1805,14 @@ PY || die "oc-limits.sh --preserve failed for $OC_FIT_CTX (repo bug: please open an issue)" fi fi +# The Kolibri lane serving at boot: opencode's default is Kolibri (OC_POINT_* below), and the +# compaction block, global, goes with the default's window, as a switch to it sizes it. Sized +# from the Qwen lane, a 27B in 1M mode kept 132,000 verbatim against Kolibri's threshold of +# 153,000, and opencode compacted again every step or two (found in review, 2026-10-14). +if [ "$KOLIBRI_BOOT" -eq 1 ] && [ "$OC_KOLIBRI" -eq 1 ] && [ -n "$OC_KOLIBRI_CTX" ]; then + OC_KEEP="$("$REPO_DIR/oc-limits.sh" --preserve "$OC_KOLIBRI_CTX")" \ + || die "oc-limits.sh --preserve failed for $OC_KOLIBRI_CTX (repo bug: please open an issue)" +fi # The other engine's limits, for when both providers are present: the 27B block # keeps its context-mode limits, flash always serves its native window. A flash install # runs in native mode, so the 27B's own mode comes from its unit: taken from this run, a @@ -2691,7 +2700,7 @@ except Exception as e: IMAGE_FRESH=0; VIDEO_FRESH=0; KOLIBRI_FRESH=0 [ -f /etc/systemd/system/qwen38-image.service ] || IMAGE_FRESH=1 [ -f /etc/systemd/system/qwen38-video.service ] || VIDEO_FRESH=1 - [ -f /etc/systemd/system/qwen38-kolibri.service ] || KOLIBRI_FRESH=1 + [ -f "$KOLIBRI_UNIT_PATH" ] || KOLIBRI_FRESH=1 IMAGE_STATE=off; VIDEO_STATE=off; KOLIBRI_STATE=off if [ "$WANT_IMAGE" -eq 1 ]; then step "Qwen-Image 2.1 lane (text-to-image, editing, native RGBA)" @@ -2829,7 +2838,7 @@ except Exception as e: fi lane_line "Images " "$IMAGE_STATE" image image "40 GB" /etc/systemd/system/qwen38-image.service lane_line "Videos " "$VIDEO_STATE" video video "144 GB" /etc/systemd/system/qwen38-video.service - lane_line "Kolibri-1 " "$KOLIBRI_STATE" kolibri kolibri "102 GB" /etc/systemd/system/qwen38-kolibri.service + lane_line "Kolibri-1 " "$KOLIBRI_STATE" kolibri kolibri "102 GB" "$KOLIBRI_UNIT_PATH" [ "$LANE" = "27b" ] && echo " Benchmark : ./bench.sh" exit 0 fi diff --git a/oc-merge-limits.py b/oc-merge-limits.py index 83d0389d..0c5c3018 100755 --- a/oc-merge-limits.py +++ b/oc-merge-limits.py @@ -7,6 +7,7 @@ Usage: oc-merge-limits.py oc-merge-limits.py --autoupdate notify oc-merge-limits.py --add-providers oc-merge-limits.py --remove-providers + oc-merge-limits.py --remove-provider Only the "limit" object of the named provider/model is rewritten, in place, by targeted text substitution: comments, ordering and the user's other @@ -592,6 +593,54 @@ def add_providers(path: str, source: str) -> int: return 0 +def remove_provider(path: str, pid: str) -> int: + """Take one provider of this box out of an opencode.json, with "model" and "small_model" + when they name it: a lane removed on its own (install-kolibri.sh --uninstall) left opencode + offering, and defaulting to, a model nothing serves any more. The rest of the file stays as + it is, by the same targeted edit as everything here; the file itself is never removed.""" + if pid not in OURS: + print(f"{pid!r} is not one of this box's providers ({', '.join(OURS)}): refused") + return 2 + opened = _open(path) + if opened is None: + return 1 + text, doc = opened + if not isinstance(doc.get("provider"), dict) or pid not in doc["provider"]: + print(f"no provider {pid!r} in {path}: unchanged") + return 0 + cur = copy.deepcopy(doc) + del cur["provider"][pid] + steps = [(["provider", pid], copy.deepcopy(cur))] + for k in ("model", "small_model"): + if isinstance(cur.get(k), str) and cur[k].split("/", 1)[0] == pid: + del cur[k] + steps.append(([k], copy.deepcopy(cur))) + new_text = text + for where, want in steps: + try: + cand = remove_member(new_text, where) + ok = load(cand) == want + except ValueError: + ok = False + if not ok: + print(f"{path}: refused, could not take {where[-1]!r} out by an edit that leaves the rest " + f"as it is; remove the {pid} provider by hand") + return 1 + new_text = cand + saved, bad = commit(path, new_text, cur) + if bad: + print(f"{path}: refused, {bad}; unchanged.") + return 1 + try: + ok = _reread(path) == cur + except ValueError: + ok = False + if not _landed(path, saved, "" if ok else "it reads back differently", "the removal"): + return 1 + print(f"removed the {pid} provider from {path} (backup {saved})") + return 0 + + def remove_providers(path: str, key_file: str) -> int: """Take out of an opencode.json the providers that read this box's API key file. @@ -664,6 +713,8 @@ def main(argv: list[str]) -> int: return add_providers(argv[1], argv[3]) if len(argv) == 4 and argv[2] == "--remove-providers": return remove_providers(argv[1], argv[3]) + if len(argv) == 4 and argv[2] == "--remove-provider": + return remove_provider(argv[1], argv[3]) if len(argv) == 6 and argv[4] == "--add-variant": return add_variant(argv[1], argv[2], argv[3], argv[5]) keep_lower = argv[6:] == ["--keep-lower"] diff --git a/qwen38-kolibri.service.template b/qwen38-kolibri.service.template index ccc2c238..cb497f00 100644 --- a/qwen38-kolibri.service.template +++ b/qwen38-kolibri.service.template @@ -26,19 +26,25 @@ ExecStartPre=/bin/bash __HOME__/.config/qwen38/engine-secrets.sh # generation_config.json, which vLLM applies to any request that does not set them. # VLLM_NO_USAGE_STATS and DO_NOT_TRACK: vLLM reports anonymous usage to its authors by # default; a box that serves its owner's data sends nothing anywhere. +# vllm_engine_auth.RequireKey: vLLM checks the key only under /v1, /v2, /inference and +# /cohere, and /invocations (which runs chat and completions), /tokenize and /detokenize +# answered without it; the middleware asks it everywhere but /health and /metrics, as the +# SGLang lanes do. Its directory alone is mounted, read-only, and it reads the key file. ExecStart=/bin/bash -c 'exec /usr/bin/docker run --rm --name qwen38-kolibri --gpus all \ --memory 100g --memory-swap 100g --shm-size 16g --network host --ipc=host \ -e HF_HUB_OFFLINE=1 -e VLLM_NO_USAGE_STATS=1 -e DO_NOT_TRACK=1 \ + -e PYTHONPATH=/opt/qwen38-auth -e QWEN38_KEY_FILE=/out/api-key \ -v __HOME__/.config/qwen38/kolibri-cache:/root/.cache/vllm \ -v __HF_CACHE__:/root/.cache/huggingface \ -v __HOME__/.config/qwen38:/out \ + -v __HOME__/.config/qwen38/vllm-auth:/opt/qwen38-auth:ro \ __IMAGE__ \ __MODEL__ --revision __REV__ \ --served-model-name kolibri-1 \ --max-model-len 262144 --kv-cache-dtype fp8 \ --gpu-memory-utilization __GMU__ --max-num-seqs 16 \ --reasoning-parser kolibri1 --tool-call-parser kolibri1 --enable-auto-tool-choice \ - --config /out/engine-secrets.yaml \ + --config /out/engine-secrets.yaml --middleware vllm_engine_auth.RequireKey \ --host __ENGINE_BIND__ --port __PORT__' ExecStop=-/usr/bin/docker stop -t 20 qwen38-kolibri Restart=always diff --git a/switch-model.sh b/switch-model.sh index 1869d800..845a2b10 100755 --- a/switch-model.sh +++ b/switch-model.sh @@ -142,6 +142,7 @@ if [ "$CHOICE" = "kolibri" ] || [ "$CHOICE" = "kolibri-nvfp4" ]; then -v "$KOL_HF":/hf "$KOL_IMAGE" - <<'PYKOL' || die "the Kolibri checkpoint could not be verified or fetched (re-run to resume; set HF_TOKEN if it stalls)" import contextlib import importlib.util +import json import os import time from huggingface_hub import constants, snapshot_download @@ -159,9 +160,24 @@ def reporting(*args, **kwargs): return contextlib.nullcontext() +def complete(path): + """Every shard the index names is in the snapshot (a file appears there only once its + blob is whole), as install.sh's ckpt_cached reads it: huggingface_hub's own offline + check sees a missing file only when it cached the repo's tree, which a download made + with another tool or an older hub never wrote, and vLLM then dies at every start.""" + try: + with open(os.path.join(path, "model.safetensors.index.json")) as f: + shards = set(json.load(f)["weight_map"].values()) + except (OSError, ValueError, KeyError, TypeError, AttributeError): + shards = {"model.safetensors"} + return bool(shards) and all(os.path.exists(os.path.join(path, s)) for s in shards) + + repo, rev = os.environ["KOL_MODEL"], os.environ["KOL_REV"] try: path = snapshot_download(repo, revision=rev, local_files_only=True) + if not complete(path): + raise FileNotFoundError(f"a shard the index of {repo} names is missing") except Exception: # Refused before the first byte rather than stopped by a full disk halfway. What the # cache already holds of the repo comes off the need: a fetch that stopped resumes. @@ -251,11 +267,18 @@ PYKOL KOL_SRC="$(mktemp)" if [ -n "$KOL_PAIR" ] && python3 "$REPO_DIR/oc-kolibri.py" "http://127.0.0.1:${KOL_PORT:-30001}/v1" "$CONFIG_DIR/api-key" \ "${KOL_PAIR%% *}" "$(echo "$KOL_PAIR" | cut -d' ' -f2)" "${KOL_NAME:-Kolibri-1 (local, 262K)}" > "$KOL_SRC"; then + # The compaction block is global: sized from Kolibri's window as every text switch sizes + # it from its own. Left as the Qwen lane wrote it (132,000 on a 27B in 1M mode), opencode + # kept almost all of a session verbatim against Kolibri's threshold and compacted again + # every step or two (found in review, 2026-10-14). pi's keepRecentTokens follows (pi-gen). + KOL_KEEP="$("$REPO_DIR/oc-limits.sh" --preserve "${KOL_PAIR%% *}")" || KOL_KEEP="" for OC_JSON in "$CONFIG_DIR/opencode.json" "$HOME/.config/opencode/opencode.json"; do [ -f "$OC_JSON" ] || continue python3 "$REPO_DIR/oc-merge-limits.py" "$OC_JSON" --add-providers "$KOL_SRC" >/dev/null || true python3 "$REPO_DIR/oc-point-default.py" "$OC_JSON" kolibri "$CHOICE" 262144 \ || echo "NOTE: could not update $OC_JSON (hand-edited?); set its \"model\" field yourself" + [ -n "$KOL_KEEP" ] && { python3 "$REPO_DIR/oc-merge-limits.py" "$OC_JSON" --compaction "$KOL_KEEP" \ + || echo "NOTE: could not update the compaction block in $OC_JSON; check it by hand ($KOL_KEEP)"; } done fi rm -f "$KOL_SRC" diff --git a/tests/test_engine_preflight.py b/tests/test_engine_preflight.py index 079695b5..75222e30 100644 --- a/tests/test_engine_preflight.py +++ b/tests/test_engine_preflight.py @@ -48,9 +48,10 @@ Percpu: 20000 kB class Box: - """A fake /proc with five processes: 101 an SGLang scheduler, 102 SGLang's launcher + """A fake /proc with six processes: 101 an SGLang scheduler, 102 SGLang's launcher (a python3 whose command line names sglang), 103 somebody's own training script, 104 - vLLM's engine core (the Kolibri lane), 105 vLLM's API server.""" + vLLM's engine core (the Kolibri lane), 105 vLLM's API server, 106 somebody's own script + in a directory named vllm.""" def __init__(self): self.t = pathlib.Path(tempfile.mkdtemp(prefix="preflight-")) @@ -59,7 +60,8 @@ class Box: ("102", "python3", "python3\0-m\0sglang.launch_server"), ("103", "python3", "python3\0train.py"), ("104", "VLLM::EngineCor", "VLLM::EngineCore"), - ("105", "python3", "/usr/bin/python3\0/usr/local/bin/vllm\0serve\0Aleph-Alpha/Kolibri-1")): + ("105", "python3", "/usr/bin/python3\0/usr/local/bin/vllm\0serve\0Aleph-Alpha/Kolibri-1"), + ("106", "python3", "python3\0/home/u/vllm/benchmarks/bench.py")): (self.proc / pid).mkdir(parents=True) (self.proc / pid / "comm").write_text(comm + "\n") (self.proc / pid / "cmdline").write_text(cmd + "\0") @@ -136,6 +138,14 @@ class WhatBlocksAStart(unittest.TestCase): self.assertEqual(rc, 0, out) self.assertIn("other programs hold GPU memory: 103 python3 16578 MiB", out) + def test_a_path_with_vllm_in_it_is_not_an_engine(self): + """Any command line holding "vllm/" was a remnant, so a script of one's own in a vllm + checkout held every lane's start (found in review, 2026-10-14).""" + self.box.smi('echo "106, python3, 3000"') + rc, out, _ = self.box.run() + self.assertEqual(rc, 0, out) + self.assertIn("other programs hold GPU memory: 106 python3 3000 MiB", out) + def test_a_small_remnant_is_below_the_line(self): """The tokenizer of an engine being torn down holds 196 MiB for a few seconds.""" self.box.smi('echo "101, sglang::scheduler, 196"') diff --git a/tests/test_install_oc_artifact.py b/tests/test_install_oc_artifact.py index 2e588ef9..17b3de2b 100644 --- a/tests/test_install_oc_artifact.py +++ b/tests/test_install_oc_artifact.py @@ -20,7 +20,7 @@ INSTALL = REPO / "install.sh" def block() -> str: text = INSTALL.read_text() - start = text.index("OC_27B=0; OC_FLASH=0\n") + start = text.index("OC_27B=0; OC_FLASH=0; OC_KOLIBRI=0\n") end = text.index("\nPYEOF\n", start) + len("\nPYEOF\n") return text[start:end] @@ -31,8 +31,11 @@ PINS = "\n".join(line for line in INSTALL.read_text().splitlines() def generate(lane, mode, unit_ctx=None, flash_unit=False, model="RadixArk/Qwen3.8-27B-NVFP4", - pair=None, names=False, flash_running=None): + pair=None, names=False, flash_running=None, kolibri_unit=False, kolibri_boot=False, doc=False): t = pathlib.Path(tempfile.mkdtemp(prefix="oc-art-")) + kolibri = t / "qwen38-kolibri.service" + if kolibri_unit: + kolibri.write_text("ExecStart=... Aleph-Alpha/Kolibri-1 --revision 258cae8f ...\n") if flash_running: (t / "launch-flash.sh").write_text( "docker run img python3 -m sglang.launch_server --model-path RadixArk/Qwen3.8-Flash-Next-NVFP4 " @@ -46,13 +49,17 @@ def generate(lane, mode, unit_ctx=None, flash_unit=False, model="RadixArk/Qwen3. ctx, out = pair or (("205000", "32000") if lane == "flash" else ("700000", "200000")) script = ("set -euo pipefail\ndie(){ echo \"DIE: $*\"; exit 1; }\n" + PINS + "\n" f'LANE={lane}; CONTEXT_MODE={mode}; SGL_UNIT_PATH="{sgl}"; FLASH_UNIT_PATH="{flash}"\n' + f'KOLIBRI_UNIT_PATH="{kolibri}"; KOLIBRI_BOOT={1 if kolibri_boot else 0}\n' f'MODEL_CHOICE={"flash" if lane == "flash" else "stock"}\n' f'REPO_DIR="{REPO}"; CONFIG_DIR="{t}"; OC_PORT=30001; OC_CTX={ctx}; OC_OUT={out}\n' 'OC_LABEL=local; OPENCODE_PIN=1\n' + block()) r = subprocess.run(["bash", "-c", script], capture_output=True, text=True, timeout=60, env={"PATH": "/usr/bin:/bin", "HOME": str(t)}) assert r.returncode == 0, r.stdout + r.stderr - doc = json.loads((t / "opencode.json").read_text()) + doc_ = json.loads((t / "opencode.json").read_text()) + if doc: + return doc_ + doc = doc_ if names: return {p: b["models"][next(iter(b["models"]))]["name"] for p, b in doc["provider"].items()} return {p: b["models"][next(iter(b["models"]))]["limit"] for p, b in doc["provider"].items()} @@ -116,5 +123,28 @@ class TheLaneNotInstalledKeepsItsCheckpointsName(unittest.TestCase): names = generate("flash", "native", unit_ctx=262144, model="Qwen/Qwen3.8-27B-FP8", names=True) self.assertEqual(names["qwen38"], "Qwen3.8-27B FP8 official + DFlash2 (local, 262K)") + +class ABoxBootingKolibri(unittest.TestCase): + """Kolibri serving at boot: opencode's default is Kolibri, and the compaction block, global, + is sized from its window (38,000 kept of its 153,000 threshold), not from the 27B's (132,000 + on a 1M 27B, and opencode compacted again every step or two: found in review, 2026-10-14).""" + + def test_the_default_and_the_compaction_are_kolibris(self): + d = generate("27b", "1m", unit_ctx=1010000, flash_unit=True, pair=("551000", "160000"), + kolibri_unit=True, kolibri_boot=True, doc=True) + self.assertEqual(d["model"], "kolibri/kolibri-1") + self.assertIn("kolibri", d["provider"]) + self.assertEqual(d["compaction"]["preserve_recent_tokens"], 38000) + + def test_with_kolibri_installed_but_not_at_boot_the_27b_keeps_its_own(self): + d = generate("27b", "1m", unit_ctx=1010000, pair=("551000", "160000"), kolibri_unit=True, doc=True) + self.assertEqual(d["model"], "qwen38/qwen3.8-27b") + self.assertIn("kolibri", d["provider"], "the installed lane is offered") + self.assertEqual(d["compaction"]["preserve_recent_tokens"], 132000) + + def test_without_its_unit_there_is_no_kolibri_provider(self): + d = generate("27b", "1m", unit_ctx=1010000, pair=("551000", "160000"), doc=True) + self.assertNotIn("kolibri", d["provider"]) + if __name__ == "__main__": unittest.main(verbosity=2) diff --git a/tests/test_kolibri_switch_checkpoint.py b/tests/test_kolibri_switch_checkpoint.py new file mode 100644 index 00000000..da7f462f --- /dev/null +++ b/tests/test_kolibri_switch_checkpoint.py @@ -0,0 +1,83 @@ +#!/usr/bin/env python3 +"""./switch-model.sh kolibri: a snapshot missing a shard is fetched, not taken as cached. + +The switch first asks huggingface_hub for the snapshot offline. huggingface_hub 1.30 (the +lane image's) sees a missing file there only when it cached the repo's tree listing, which +a download made with another tool or an older hub never wrote: the NVFP4 checkpoint on the +reference box has no tree cache. A switch would then enable a unit whose vLLM, offline, +dies at every start. The script's own Python runs here, whole, against a fake hub. +""" +import json +import os +import pathlib +import subprocess +import sys +import tempfile +import unittest + +REPO = pathlib.Path(__file__).resolve().parents[1] +TEXT = (REPO / "switch-model.sh").read_text() +_at = TEXT.index("<<'PYKOL'") +SCRIPT = TEXT[TEXT.index("\n", _at) + 1:TEXT.index("\nPYKOL\n", _at)] + +FAKE_HUB = ''' +import json, os, pathlib + + +class constants: + HF_HUB_CACHE = os.path.join(os.environ["HF_HOME"], "hub") + + +def snapshot_download(repo, revision=None, local_files_only=False, **kw): + with open(os.environ["FAKE_LOG"], "a") as f: + f.write(f"{repo} {revision} local={local_files_only}\\n") + snap = pathlib.Path(os.environ["SNAP"]) + if not local_files_only: # the online path completes the snapshot + index = snap / "model.safetensors.index.json" + names = json.loads(index.read_text())["weight_map"].values() if index.exists() else ["model.safetensors"] + for name in names: + (snap / name).write_text("w") + return str(snap) +''' + + +class ACheckpointIsCachedOnlyWhenWhole(unittest.TestCase): + def run_switch(self, files, index=None): + d = pathlib.Path(tempfile.mkdtemp(prefix="kol-ckpt-")) + (d / "huggingface_hub").mkdir() + (d / "huggingface_hub" / "__init__.py").write_text(FAKE_HUB) + snap = d / "hub" / "models--Quantinine--Kolibri-1-NVFP4A16-FP8" / "snapshots" / ("4" * 40) + snap.mkdir(parents=True) + if index is not None: + (snap / "model.safetensors.index.json").write_text(json.dumps({"weight_map": index})) + for name in files: + (snap / name).write_text("w") + log = d / "calls.log" + env = dict(os.environ, PYTHONPATH=str(d), HF_HOME=str(d), FAKE_LOG=str(log), SNAP=str(snap), + KOL_MODEL="Quantinine/Kolibri-1-NVFP4A16-FP8", KOL_REV="4" * 40, + KOL_NEED_GB="46", KOL_FREE_GB="1000") + r = subprocess.run([sys.executable, "-c", SCRIPT], capture_output=True, text=True, env=env, timeout=60) + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + return log.read_text().splitlines(), r.stdout + + def test_a_snapshot_missing_a_shard_is_fetched(self): + index = {"a.weight": "model-00001-of-00002.safetensors", "b.weight": "model-00002-of-00002.safetensors"} + calls, out = self.run_switch(["model-00001-of-00002.safetensors"], index) + self.assertEqual([c.split()[-1] for c in calls], ["local=True", "local=False"], calls) + self.assertIn("not complete in the cache, fetching the rest", out) + + def test_a_whole_snapshot_needs_no_network(self): + index = {"a.weight": "model-00001-of-00002.safetensors", "b.weight": "model-00002-of-00002.safetensors"} + calls, out = self.run_switch(["model-00001-of-00002.safetensors", "model-00002-of-00002.safetensors"], index) + self.assertEqual([c.split()[-1] for c in calls], ["local=True"], calls) + self.assertNotIn("fetching", out) + + def test_a_single_file_checkpoint_is_read_the_same_way(self): + calls, _ = self.run_switch([]) + self.assertEqual([c.split()[-1] for c in calls], ["local=True", "local=False"]) + calls, _ = self.run_switch(["model.safetensors"]) + self.assertEqual([c.split()[-1] for c in calls], ["local=True"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_kolibri_uninstall_chain.py b/tests/test_kolibri_uninstall_chain.py index 16d8092b..42ae4ad1 100644 --- a/tests/test_kolibri_uninstall_chain.py +++ b/tests/test_kolibri_uninstall_chain.py @@ -12,6 +12,7 @@ a box that had been serving the flash lane. The script's own uninstall block runs here, whole, against a fake unit path and a fake config directory; sudo, systemctl and docker are stubs that write down every call. """ +import json import os import pathlib import subprocess @@ -26,10 +27,16 @@ BLOCK = TEXT[START:END] class TheUninstallKeepsTheChain(unittest.TestCase): - def run_block(self, files, kolibri_at_boot=False): + def run_block(self, files, kolibri_at_boot=False, opencode=None): d = pathlib.Path(tempfile.mkdtemp(prefix="kol-uninstall-")) + self.home = d / "home" cfg = d / "cfg" cfg.mkdir() + (self.home / ".config" / "opencode").mkdir(parents=True) + if opencode is not None: + (cfg / "opencode.json").write_text(json.dumps(opencode, indent=2)) + (self.home / ".config" / "opencode" / "opencode.json").write_text(json.dumps(opencode, indent=2)) + self.cfg = cfg for name, value in files.items(): (cfg / name).write_text(value + "\n") bin_ = d / "bin" @@ -49,6 +56,7 @@ class TheUninstallKeepsTheChain(unittest.TestCase): script = "\n".join([ "set -euo pipefail", "step(){ :; }", + f'HERE="{REPO}"', "ACTION=uninstall", "UNIT=qwen38-kolibri.service", f'INSTALLED="{unit}"', @@ -60,7 +68,7 @@ class TheUninstallKeepsTheChain(unittest.TestCase): "KOLIBRI_NVFP4_REPO=Quantinine/Kolibri-1-NVFP4A16-FP8", BLOCK, ]) - env = dict(os.environ, PATH=f"{bin_}:/usr/bin:/bin") + env = dict(os.environ, PATH=f"{bin_}:/usr/bin:/bin", HOME=str(self.home)) r = subprocess.run(["bash", "-c", script], capture_output=True, text=True, env=env, timeout=30) self.assertEqual(r.returncode, 0, r.stdout + r.stderr) return {p.name: p.read_text().strip() for p in cfg.iterdir() if p.name.startswith("lane-before-")} @@ -93,6 +101,36 @@ class TheUninstallKeepsTheChain(unittest.TestCase): self.assertEqual(left, {"lane-before-image": "qwen38-flash.service", "lane-before-video": "qwen38-image.service"}) + def test_opencode_loses_the_provider_and_its_default_follows_the_lane_before(self): + # left as they were, opencode offered and defaulted to a model nothing served, and its + # small-model calls sent "none" to the Qwen template, which refuses it + conf = {"$schema": "https://opencode.ai/config.json", "model": "kolibri/kolibri-1", + "small_model": "kolibri/kolibri-1", + "provider": {p: {"options": {"baseURL": "http://127.0.0.1:30001/v1", + "apiKey": "{file:/k/api-key}"}, + "models": {m: {"name": m}}} + for p, m in (("qwen38", "qwen3.8-27b"), ("flashnext", "qwen3.8-flash-next"), + ("kolibri", "kolibri-1"))}} + self.run_block({"lane-before-kolibri": "qwen38-flash.service"}, opencode=conf) + for path in (self.cfg / "opencode.json", self.home / ".config/opencode/opencode.json"): + left = json.loads(path.read_text()) + self.assertNotIn("kolibri", left["provider"], path) + self.assertEqual((left["model"], left["small_model"]), + ("flashnext/qwen3.8-flash-next",) * 2, path) + self.assertEqual(left["provider"]["flashnext"]["models"]["qwen3.8-flash-next"]["name"], + "qwen3.8-flash-next", "no name changed") + + def test_a_default_that_was_not_kolibri_is_left_where_it_was(self): + conf = {"model": "qwen38/qwen3.8-27b", + "provider": {p: {"options": {"baseURL": "http://127.0.0.1:30001/v1", + "apiKey": "{file:/k/api-key}"}, + "models": {m: {"name": m}}} + for p, m in (("qwen38", "qwen3.8-27b"), ("kolibri", "kolibri-1"))}} + self.run_block({"lane-before-kolibri": "qwen38-flash.service"}, opencode=conf) + left = json.loads((self.cfg / "opencode.json").read_text()) + self.assertEqual(left["model"], "qwen38/qwen3.8-27b") + self.assertNotIn("kolibri", left["provider"]) + def test_kolibri_at_boot_still_gives_the_boot_back_to_its_own_lane(self): # the handover reads Kolibri's link before anything else touches it d_files = {"lane-before-kolibri": "qwen38-flash.service", diff --git a/tests/test_oc_merge_limits.py b/tests/test_oc_merge_limits.py index 64cc5b84..4e7e2f8f 100644 --- a/tests/test_oc_merge_limits.py +++ b/tests/test_oc_merge_limits.py @@ -256,6 +256,29 @@ def main() -> None: rc, out = remove(p) assert rc == 0 and doc_of(p) == {"provider": {"x": {}}, "y": 1}, open(p).read() + # 9. --remove-provider: one lane of this box removed on its own (install-kolibri.sh + # --uninstall). Its provider goes, with "model" and "small_model" when they name it; + # the other providers, the user's comments and the file itself stay. + def remove_one(path, pid): + r = subprocess.run([sys.executable, SCRIPT, path, "--remove-provider", pid], + capture_output=True, text=True) + return r.returncode, (r.stdout + r.stderr).strip() + + body = ('{\n // mine\n "model": "kolibri/kolibri-1",\n "small_model": "qwen38/qwen3.8-27b",\n' + ' "provider": {\n "qwen38": ' + json.dumps(box()) + ',\n' + ' "kolibri": ' + json.dumps(box()) + '\n }\n}\n') + p = write(tmp, body) + want = doc_of(p) + del want["provider"]["kolibri"], want["model"] + rc, out = remove_one(p, "kolibri") + assert rc == 0 and "removed the kolibri provider" in out, out + assert doc_of(p) == want, doc_of(p) + assert "// mine" in open(p).read(), "a comment was dropped" + rc, out = remove_one(p, "kolibri") + assert rc == 0 and "unchanged" in out, out + rc, out = remove_one(p, "anthropic") # only this box's own providers + assert rc == 2 and "refused" in out and doc_of(p) == want, out + print("test_oc_merge_limits: OK") diff --git a/tests/test_vllm_engine_auth.py b/tests/test_vllm_engine_auth.py new file mode 100644 index 00000000..54fc400a --- /dev/null +++ b/tests/test_vllm_engine_auth.py @@ -0,0 +1,133 @@ +#!/usr/bin/env python3 +"""vllm_engine_auth.RequireKey: the key on every route of the Kolibri lane's engine. + +vLLM 0.29 checks --api-key only under /v1, /v2, /inference and /cohere: /invocations +(SageMaker's router, registered on every server, which runs chat and completions), +/tokenize and /detokenize answered anyone who reached the port. The middleware refuses +everything but /health and /metrics without the key, as the SGLang lanes do; the unit +loads it and the installer puts it where the unit mounts it. +""" +import asyncio +import importlib.util +import pathlib +import re +import tempfile +import unittest +import unittest.mock + +REPO = pathlib.Path(__file__).resolve().parents[1] +_spec = importlib.util.spec_from_file_location("vllm_engine_auth", REPO / "vllm_engine_auth.py") +auth = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(auth) +KEY = "sk-test-0123456789abcdef" + + +class Fake: + """An ASGI app that records being reached, and a send() that records the reply.""" + def __init__(self): + self.reached, self.sent = [], [] + + async def app(self, scope, receive, send): + self.reached.append(scope["path"]) + + async def send(self, msg): + self.sent.append(msg) + + +class TheEngineAsksTheKeyEverywhere(unittest.TestCase): + def setUp(self): + d = pathlib.Path(tempfile.mkdtemp(prefix="vllm-auth-")) + self.keyfile = d / "api-key" + self.keyfile.write_text(KEY + "\n") + self.env = unittest.mock.patch.dict("os.environ", {"QWEN38_KEY_FILE": str(self.keyfile)}) + self.env.start() + self.addCleanup(self.env.stop) + + def call(self, path, auth_header=None, kind="http", method="POST", root=""): + fake = Fake() + mw = auth.RequireKey(fake.app) + headers = [(b"content-type", b"application/json")] + if auth_header is not None: + headers.append((b"authorization", auth_header.encode())) + scope = {"type": kind, "path": path, "root_path": root, "method": method, "headers": headers} + asyncio.run(mw(scope, None, fake.send)) + status = next((m["status"] for m in fake.sent if m["type"] == "http.response.start"), None) + return fake, status + + def test_invocations_without_the_key_is_refused(self): + fake, status = self.call("/invocations") + self.assertEqual(status, 401) + self.assertEqual(fake.reached, [], "the engine never saw it") + + def test_every_unguarded_vllm_route_is_refused_without_the_key(self): + for path in ("/invocations", "/tokenize", "/detokenize", "/scale_elastic_ep", "/ping", + "/version", "/load", "/v1/chat/completions", "/v1/models", "/start_profile"): + with self.subTest(path=path): + fake, status = self.call(path) + self.assertEqual((status, fake.reached), (401, [])) + + def test_the_key_opens_them(self): + for path in ("/invocations", "/tokenize", "/v1/chat/completions", "/version"): + with self.subTest(path=path): + fake, status = self.call(path, f"Bearer {KEY}") + self.assertEqual((status, fake.reached), (None, [path])) + + def test_a_wrong_key_or_another_scheme_is_refused(self): + for header in (f"Bearer {KEY}x", "Bearer ", f"Basic {KEY}", KEY, f"bearer{KEY}"): + with self.subTest(header=header): + fake, status = self.call("/invocations", header) + self.assertEqual((status, fake.reached), (401, [])) + + def test_the_scheme_is_case_blind_as_in_vllm(self): + fake, status = self.call("/invocations", f"bearer {KEY}") + self.assertEqual(fake.reached, ["/invocations"]) + + def test_health_and_metrics_stay_open(self): + # the cockpit reads both without the key, on every lane + for path in ("/health", "/metrics", "/metrics/"): + with self.subTest(path=path): + fake, status = self.call(path, method="GET") + self.assertEqual((status, fake.reached), (None, [path])) + + def test_a_root_path_is_taken_off_first(self): + fake, status = self.call("/engine/health", root="/engine", method="GET") + self.assertEqual(fake.reached, ["/engine/health"]) + fake, status = self.call("/engine/invocations", root="/engine") + self.assertEqual(status, 401) + + def test_preflight_and_lifespan_pass(self): + fake, status = self.call("/invocations", method="OPTIONS") + self.assertEqual(fake.reached, ["/invocations"]) + fake = Fake() + asyncio.run(auth.RequireKey(fake.app)({"type": "lifespan", "path": ""}, None, fake.send)) + self.assertEqual(fake.reached, [""]) + + def test_a_websocket_without_the_key_is_closed(self): + fake, _ = self.call("/v1/realtime", kind="websocket") + self.assertEqual(fake.reached, []) + self.assertEqual(fake.sent, [{"type": "websocket.close", "code": 1008}]) + + def test_an_empty_key_file_keeps_the_engine_down(self): + self.keyfile.write_text("\n") + with self.assertRaises(RuntimeError): + auth.RequireKey(Fake().app) + + +class TheLaneLoadsIt(unittest.TestCase): + def test_the_unit_loads_the_middleware_from_its_own_mount(self): + unit = (REPO / "qwen38-kolibri.service.template").read_text() + self.assertIn("--middleware vllm_engine_auth.RequireKey", unit) + mount = re.search(r"-v (\S+):(/opt/qwen38-auth):ro", unit) + self.assertIsNotNone(mount, "the module's directory, read-only, and nothing else of the config") + self.assertIn("-e PYTHONPATH=/opt/qwen38-auth", unit) + self.assertIn("-e QWEN38_KEY_FILE=/out/api-key", unit) + self.assertIn("-v __HOME__/.config/qwen38:/out", unit, "where the key file is") + + def test_the_installer_puts_it_there(self): + inst = (REPO / "install-kolibri.sh").read_text() + self.assertIn('"$HERE/vllm_engine_auth.py"', inst) + self.assertIn("$CONFIG_DIR/vllm-auth/vllm_engine_auth.py", inst) + + +if __name__ == "__main__": + unittest.main() diff --git a/vllm_engine_auth.py b/vllm_engine_auth.py new file mode 100644 index 00000000..551098e2 --- /dev/null +++ b/vllm_engine_auth.py @@ -0,0 +1,64 @@ +"""The box's key on every route of a vLLM lane's engine, as the SGLang lanes have it. + +vLLM checks --api-key only on the paths under /v1, /v2, /inference and /cohere (its +AuthenticationMiddleware's GUARDED_PREFIX). /invocations, the SageMaker router that every +vLLM 0.29 server registers and that runs chat and completions, answered without the key, +and so did /tokenize, /detokenize and the elastic-EP routes (read in vLLM 0.29.0's source, +2026-10-14). On a box whose engine listens beyond loopback (ENGINE_BIND), anyone on the +network could generate on it. The SGLang lanes refuse everything but /health and /metrics +without the key: loaded with `--middleware vllm_engine_auth.RequireKey`, this makes the +vLLM lane refuse the same. + +The key is read once, at start, from the file the unit mounts (QWEN38_KEY_FILE; the +engine is restarted to take a new key, as --config's is). It is compared the way vLLM +compares it, sha256 digests in constant time. Pure ASGI, like vLLM's own middleware: a +streamed answer and a client's disconnect pass through untouched. +""" +import hashlib +import json +import os +import secrets + +# What the cockpit and the installers read without the key, on every lane. +OPEN = ("/health", "/metrics") + + +def _key_digest(path): + with open(path, encoding="utf-8") as f: + key = f.readline().strip() + if not key: + raise RuntimeError(f"{path} holds no key: an engine nobody can authenticate to stays down") + return hashlib.sha256(key.encode("utf-8")).digest() + + +class RequireKey: + def __init__(self, app): + self.app = app + self.digest = _key_digest(os.environ.get("QWEN38_KEY_FILE", "/out/api-key")) + + def authorized(self, scope): + for name, value in scope.get("headers") or (): + if name.lower() == b"authorization": + scheme, _, param = value.decode("latin-1").partition(" ") + return scheme.lower() == "bearer" and secrets.compare_digest( + hashlib.sha256(param.encode("utf-8")).digest(), self.digest) + return False + + async def __call__(self, scope, receive, send): + if scope["type"] not in ("http", "websocket") or scope.get("method") == "OPTIONS": + await self.app(scope, receive, send) + return + root, path = scope.get("root_path", ""), scope["path"] + if root and path.startswith(root): + path = path[len(root):] + if path in OPEN or path.startswith("/metrics/") or self.authorized(scope): + await self.app(scope, receive, send) + return + if scope["type"] == "websocket": + await send({"type": "websocket.close", "code": 1008}) + return + body = json.dumps({"error": "Unauthorized"}).encode() + await send({"type": "http.response.start", "status": 401, + "headers": [(b"content-type", b"application/json"), + (b"content-length", str(len(body)).encode())]}) + await send({"type": "http.response.body", "body": body})