From f40892d4bf2d77862c5ee5a86dcec28db1e1f2d7 Mon Sep 17 00:00:00 2001 From: Hasan Basbunar Date: Thu, 19 Nov 2026 12:37:36 +0100 Subject: [PATCH] no-download updates: a Load of an update that waits runs the switch's steps after the fetch The Load's prepare fetched the new revision with `switch-model.sh --fetch`, which stops right after the download, so on the serving lane's short path (prepare, apply_pending, restart, no switch) the new checkpoint's config.json was never YaRN-patched for a 1M unit (which does not load on an unpatched config), never restored for a native one, Arete's fp8 KV cache was never declared, and the chat template was never regenerated from the new revision (sixth review of v1.52.0, 2026-11-19, GLM 5.3, defect 1, verified in the code and on the box: the 27B serves the 1M window). The switch's steps 2, 2a and 2b are now one function, lanes.sh's `patch_served_checkpoint`, which the switch calls with the unit in place and prepare-lane.sh, when an update waits for this Load and this Load loads its target, with the unit that waits and the cache it mounts: the 27B and the flash serve their new revision with those steps done, on the short path as on the other. The patches are idempotent, so a journey that runs both changes nothing twice. tests/test_prepare_load_wait.py runs the prepare on a fabricated cache and fails on the code before (config unpatched, no template); test_switch_native_restore and test_arete_target read the function where it now lives. Generated by Mistral Vibe. Co-Authored-By: Mistral Vibe Co-Authored-By: Claude Opus 5.5 --- lanes.sh | 43 ++++++ prepare-lane.sh | 25 +++- switch-model.sh | 37 +---- tests/lane-templates-check.py | 10 +- tests/test_arete_target.py | 22 +-- tests/test_lane_templates_check.py | 10 +- tests/test_prepare_load_wait.py | 222 ++++++++++++++++++++++++++++ tests/test_switch_native_restore.py | 40 +++-- 8 files changed, 345 insertions(+), 64 deletions(-) create mode 100644 tests/test_prepare_load_wait.py diff --git a/lanes.sh b/lanes.sh index 6bb2011a..f29b15b0 100644 --- a/lanes.sh +++ b/lanes.sh @@ -376,6 +376,49 @@ unit_pending_clear(){ # $1 where a unit goes: it is in place, nothing waits for rm -f "${CONFIG_DIR:-$HOME/.config/qwen38}/pending/$(basename "$1")" "${CONFIG_DIR:-$HOME/.config/qwen38}/pending/$(basename "$1").needs" \ "${CONFIG_DIR:-$HOME/.config/qwen38}/pending/$(basename "$1").base" } + +# The switch's steps 2, 2a and 2b after its fetch, as one function the switch and a Load's prepare +# both call, so a checkpoint the Load fetched is patched the same way whichever of the two runs +# them: switch-model.sh calls it with the unit in place, prepare-lane.sh with the unit that waits +# (the one the Load will put in place), each with the cache that unit mounts. The patches are +# idempotent (patch-yarn.py, patch-kv.py and patch-template.py all say so), so a run of both on +# the same checkpoint, as a Load toward another target than the one that served does, changes +# nothing twice. +# $1 the lane (27b|flash), $2 the switch target (arete says so), $3 the unit or launcher that +# will serve the checkpoint (read for the 1M window flag), $4 the cache it mounts, +# $5 the checkpoint's repo, $6 its revision. +patch_served_checkpoint(){ # 27b|flash, target, unit, hf cache, repo, revision + local lane="$1" choice="$2" unit="$3" hf="$4" repo="$5" rev="$6" out + # 2) 1M YaRN patch on the target's cached config.json (27B pair only, and only + # if its unit uses it; flash serves its native window) + if [ "$lane" = "27b" ] && grep -q -- '--context-length 1010000' "$unit"; then + python3 "$(_lanes_dir)/patch-yarn.py" "$hf" "$repo" "$rev" || die "YaRN patch failed" + elif [ "$lane" = "27b" ]; then + # A native unit crashes at load on a YaRN-patched config, and a target this box served + # while it was in 1m keeps its patch in the cache after the box went back to native + # (install.sh restores the target it installs, not the others). So the target's config + # is restored here, idempotently; the restore refuses, before the unit is touched, when + # a patched config lost its backup (found in review, 2026-09-24). + echo "unit does not use the 1M context flag: restoring the target's native config if it carries YaRN" + python3 "$(_lanes_dir)/patch-yarn.py" --restore "$hf" "$repo" "$rev" \ + || die "the target's config carries the 1M YaRN patch and could not be restored (the unit was NOT rewritten yet)" + fi + # 2a) Arete's checkpoint declares no KV cache, and served so it gets a bf16 one and about half + # the pool: the lane's fp8 declaration goes into its config, as install.sh writes it, and its + # unit stays stock's, with no --kv-cache-dtype (patch-kv.py says why). After the window's + # configs: a YaRN restore puts back a config saved before the declaration. + if [ "$choice" = arete ]; then + python3 "$(_lanes_dir)/patch-kv.py" "$hf" "$repo" "$rev" \ + || die "the fp8 KV cache declaration failed for $repo (the unit was NOT rewritten yet)" + fi + # 2b) regenerate the patched chat template FROM the target's own snapshot. + # One template file per engine; the served template always follows the served + # model. Read at service startup only, so writing it now is safe. + out="${CONFIG_DIR:-$HOME/.config/qwen38}/chat-template-sglang.jinja" + [ "$lane" = "flash" ] && out="${CONFIG_DIR:-$HOME/.config/qwen38}/chat-template-flashnext.jinja" + python3 "$(_lanes_dir)/patch-template.py" "$hf" "$out" "$rev" "$repo" \ + || die "template patch failed for $repo (the unit was NOT rewritten yet)" +} lane_serves_older(){ # $1 unit, $2... its files: true when it serves and one of them is newer than its start local unit="$1" started f; shift [ "$(systemctl show -p ActiveState --value "$unit" 2>/dev/null)" = active ] || return 1 diff --git a/prepare-lane.sh b/prepare-lane.sh index 49791395..0c72714d 100755 --- a/prepare-lane.sh +++ b/prepare-lane.sh @@ -135,13 +135,21 @@ prepare_flash(){ "$hf|$(ckpt_room_gb flash "$hf" "$model" "$rev")|its checkpoint and its caches" \ "${ple:-$hf}|$table_need|its PLE table, 47.7 GiB written at every boot" pull_image "$img" flash 49 # its peak, as install.sh counts it (DOCKER_NEED_GB) - # The fetch goes into the cache the unit that waits mounts ($hf, read above from it when an + # The fetch goes into the cache the launcher that waits mounts ($hf, read above from it when an # update waits): the switch reads the one the invocation in place mounts when no HF_CACHE is # passed, and a cache moved by a re-run of install with HF_CACHE= would then get the download - # while the waiting unit kept reading the other one, and the Load would loop (sixth review of - # v1.52.0, 2026-11-19, GLM 5.3: the image, video and image-h3 switches already read the waiting - # unit's cache, the two text lanes did not). + # while the waiting launcher kept reading the other one, and the Load would loop (sixth review + # of v1.52.0, 2026-11-19, GLM 5.3: the image, video and image-h3 switches already read the + # waiting unit's cache, the two text lanes did not). HF_CACHE="$hf" bash "$HERE/switch-model.sh" "$target" --fetch + # An update waits for this Load and this Load loads its target: the switch's steps after the + # fetch run here too, against the launcher that waits (the switch reads the one in place, not + # yet put): the new revision's chat template regenerated from its own snapshot (sixth review + # of v1.52.0, 2026-11-19, GLM 5.3: the --fetch stopped right after the download, and the lane + # restarted on the template of the revision before). + if [ -n "$pend" ]; then + patch_served_checkpoint flash "$target" "$launch" "$hf" "$model" "$rev" + fi # The PLE table its launcher writes at every boot, 47.7 GiB in PLE_DIR, needs its room there, # counted after the checkpoint when the two share a disk (install.sh asks for both at once). if [ -n "$ple" ] && ! ls "$ple"/ple_table_*.bin >/dev/null 2>&1; then @@ -241,6 +249,15 @@ prepare_27b(){ # v1.52.0, 2026-11-19, GLM 5.3: the image, video and image-h3 switches already read the waiting # unit's cache, the two text lanes did not). HF_CACHE="$hf" bash "$HERE/switch-model.sh" "$target" --fetch + # An update waits for this Load and this Load loads its target: the switch's steps after the + # fetch run here too, against the unit that waits (the switch reads the one in place, not yet + # put): the new revision's config patched for the window that unit serves (YaRN in 1M, its + # restore in native), Arete's fp8 KV cache declaration, the chat template regenerated from its + # own snapshot (sixth review of v1.52.0, 2026-11-19, GLM 5.3: the --fetch stopped right after + # the download, and a 1M lane restarted on an unpatched config, which does not load). + if [ -n "$pend" ]; then + patch_served_checkpoint 27b "$target" "$unit" "$hf" "$trepo" "$trev" + fi printf '\n\033[1;32m── Done: the 27B lane is prepared; its Load switches to it and starts it\033[0m\n' } diff --git a/switch-model.sh b/switch-model.sh index d255d0ae..03ee292f 100755 --- a/switch-model.sh +++ b/switch-model.sh @@ -1665,36 +1665,13 @@ docker run --rm --init --network host --user "$(id -u):$(id -g)" \ || die "download failed ($(dl_free_gb) GiB left under $HF_CACHE; if that is near 0 the disk filled up, otherwise re-run to resume: HuggingFace throttles unauthenticated downloads, set HF_TOKEN= if it stalls)" fetched "$TARGET_REPO @ ${TARGET_REV:0:12}" -# 2) 1M YaRN patch on the target's cached config.json (27B pair only, and only -# if its unit uses it; flash serves its native window) -if [ "$TARGET_LANE" = "27b" ] && grep -q -- '--context-length 1010000' "$TARGET_UNIT"; then - python3 "$REPO_DIR/patch-yarn.py" "$HF_CACHE" "$TARGET_REPO" "$TARGET_REV" || die "YaRN patch failed" -elif [ "$TARGET_LANE" = "27b" ]; then - # A native unit crashes at load on a YaRN-patched config, and a target this box served - # while it was in 1m keeps its patch in the cache after the box went back to native - # (install.sh restores the target it installs, not the others). So the target's config - # is restored here, idempotently; the restore refuses, before the unit is touched, when - # a patched config lost its backup (found in review, 2026-09-24). - echo "unit does not use the 1M context flag: restoring the target's native config if it carries YaRN" - python3 "$REPO_DIR/patch-yarn.py" --restore "$HF_CACHE" "$TARGET_REPO" "$TARGET_REV" \ - || die "the target's config carries the 1M YaRN patch and could not be restored (the switch was NOT applied to the unit yet)" -fi -# 2a) Arete's checkpoint declares no KV cache, and served so it gets a bf16 one and about half -# the pool: the lane's fp8 declaration goes into its config, as install.sh writes it, and its -# unit stays stock's, with no --kv-cache-dtype (patch-kv.py says why). After the window's -# configs: a YaRN restore puts back a config saved before the declaration. -if [ "$CHOICE" = arete ]; then - python3 "$REPO_DIR/patch-kv.py" "$HF_CACHE" "$TARGET_REPO" "$TARGET_REV" \ - || die "the fp8 KV cache declaration failed for $TARGET_REPO (the switch was NOT applied to the unit yet)" -fi - -# 2b) regenerate the patched chat template FROM the target's own snapshot. -# One template file per engine; the served template always follows the served -# model. Read at service startup only, so writing it now is safe. -TEMPLATE_OUT="$CONFIG_DIR/chat-template-sglang.jinja" -[ "$TARGET_LANE" = "flash" ] && TEMPLATE_OUT="$CONFIG_DIR/chat-template-flashnext.jinja" -python3 "$REPO_DIR/patch-template.py" "$HF_CACHE" "$TEMPLATE_OUT" "$TARGET_REV" "$TARGET_REPO" \ - || die "template patch failed for $TARGET_REPO (the switch was NOT applied to the unit yet)" +# 2, 2a, 2b) the fetched checkpoint's own files, patched for what will serve them: one function +# lanes.sh holds, which a Load's prepare (prepare-lane.sh) calls too when an update waits for +# it, against the unit that waits, with the cache that unit mounts (sixth review of v1.52.0, +# 2026-11-19, GLM 5.3: the Load's --fetch stopped right after the download, and a lane serving +# its target with an update waiting restarted on a config the switch's steps never patched, +# which does not load in 1M). +patch_served_checkpoint "$TARGET_LANE" "$CHOICE" "$TARGET_UNIT" "$HF_CACHE" "$TARGET_REPO" "$TARGET_REV" # 3) point the target unit at the exact checkpoint. For the 27B pair, rewrite # ONLY --model-path/--revision (the draft's own revision flag has a diff --git a/tests/lane-templates-check.py b/tests/lane-templates-check.py index 62210e8d..dd8d8364 100644 --- a/tests/lane-templates-check.py +++ b/tests/lane-templates-check.py @@ -120,12 +120,14 @@ def lane_specs(repo_dir=REPO): targets = re.findall(r'^\s+([a-z0-9-]+)\)\s+MODEL_REPO="\$([A-Z0-9_]+)_REPO"', install, re.M) if not targets: raise SystemExit("install.sh no longer maps its targets the way this check reads them") - # the five fixes there: install.sh and switch-model.sh run patch-template.py with no --patches and no - # environment of their own, or this check would render a template they do not write (code review) - for script in ("install.sh", "switch-model.sh"): + # the five fixes there: install.sh, and lanes.sh where the switch's and the Load's patcher call now + # lives (patch_served_checkpoint), run patch-template.py with no --patches and no environment of + # their own, or this check would render a template they do not write (code review) + for script, call in (("install.sh", 'python3 "$REPO_DIR/patch-template.py"'), + ("lanes.sh", 'python3 "$(_lanes_dir)/patch-template.py"')): calls = [ln.strip() for ln in re.sub(r"\\\n", " ", (repo_dir / script).read_text()).splitlines() if "patch-template.py" in re.sub(r"(^|\s)#.*$", "", ln)] - if not calls or any("--patches" in c or not c.startswith('python3 "$REPO_DIR/patch-template.py"') for c in calls): + if not calls or any("--patches" in c or not c.startswith(call) for c in calls): raise SystemExit(f"{script} runs patch-template.py otherwise than with its five fixes: {calls}") specs = [(t, *pin(install, p), {}) for t, p in targets] installers = sorted(f.name for f in repo_dir.glob("install-*.sh") if "vlane_put_unit" in f.read_text()) diff --git a/tests/test_arete_target.py b/tests/test_arete_target.py index 6002b659..51295f24 100644 --- a/tests/test_arete_target.py +++ b/tests/test_arete_target.py @@ -20,9 +20,13 @@ REPO = pathlib.Path(__file__).resolve().parents[1] SWITCH = (REPO / "switch-model.sh").read_text() INSTALL = (REPO / "install.sh").read_text() RUN = (REPO / "run.sh").read_text() +LANES = (REPO / "lanes.sh").read_text() PINS = dict(re.findall(r'^([A-Z0-9_]+_(?:REPO|REV))="([^"$]+)"', INSTALL, re.M)) ARETE = (PINS["ARETE_REPO"], PINS["ARETE_REV"]) TARGETS_27B = {"stock": "STOCK", "uncensored": "UNC", "fp8": "FP8", "uncensored-fp8": "UNCFP8", "arete": "ARETE"} +# the switch's steps 2, 2a and 2b after the fetch, as one function lanes.sh holds and the switch +# calls with the unit in place (prepare-lane.sh calls it with the unit that waits) +FN = LANES[LANES.index("patch_served_checkpoint(){"):LANES.index("\n}\n", LANES.index("patch_served_checkpoint(){")) + 3] def block(text, start, end_after): @@ -32,8 +36,8 @@ def block(text, start, end_after): def stubs(d, kv_rc=0): - """patch-yarn.py and patch-kv.py in d, each line of the shared log: the script, then its arguments.""" - for name, rc in (("patch-yarn.py", 0), ("patch-kv.py", kv_rc)): + """patch-yarn.py, patch-kv.py and patch-template.py in d, each line of the shared log: the script, then its arguments.""" + for name, rc in (("patch-yarn.py", 0), ("patch-kv.py", kv_rc), ("patch-template.py", 0)): (d / name).write_text( "import os, sys\n" "open(os.path.join(os.path.dirname(sys.argv[0]), 'calls'), 'a').write(" @@ -49,18 +53,15 @@ def bash(script, d): class TheSwitch(unittest.TestCase): - # step 2, the window's configs, and step 2a, the declaration, as switch-model.sh runs them - LINES = block(SWITCH, """if [ "$TARGET_LANE" = "27b" ] && grep -q -- '--context-length 1010000' "$TARGET_UNIT"; then""", - 'if [ "$CHOICE" = arete ]; then') - + # steps 2, 2a and 2b after the fetch, as lanes.sh's patch_served_checkpoint runs them for the switch def switch(self, choice, window, kv_rc=0): d = pathlib.Path(tempfile.mkdtemp(prefix="arete-switch-")) self.addCleanup(shutil.rmtree, d, True) stubs(d, kv_rc) (d / "unit").write_text(f"ExecStart=... --context-length {window} ...\n") repo, rev = PINS[TARGETS_27B[choice] + "_REPO"], PINS[TARGETS_27B[choice] + "_REV"] - script = (f'REPO_DIR="{d}"; HF_CACHE=/hf; CHOICE={choice}; TARGET_LANE=27b; TARGET_REPO={repo}; ' - f'TARGET_REV={rev}; TARGET_UNIT="{d}/unit"\n' + self.LINES + "echo REACHED\n") + script = (f'_lanes_dir(){{ echo "{d}"; }}\nCONFIG_DIR="{d}"\n' + FN + + f'patch_served_checkpoint 27b {choice} "{d}/unit" /hf {repo} {rev}\necho REACHED\n') return bash(script, d) def test_arete_gets_the_declaration_after_the_window_in_both_modes(self): @@ -68,7 +69,8 @@ class TheSwitch(unittest.TestCase): for window, yarn in ((1010000, f"patch-yarn.py /hf {repo} {rev}"), (262144, f"patch-yarn.py --restore /hf {repo} {rev}")): with self.subTest(window=window): out, calls = self.switch("arete", window) - self.assertEqual(calls, [yarn, f"patch-kv.py /hf {repo} {rev}"], out) + self.assertEqual(calls[:2], [yarn, f"patch-kv.py /hf {repo} {rev}"], out) + self.assertIn("patch-template.py /hf", calls[2], out) self.assertIn("REACHED", out) def test_no_other_target_has_its_config_declared(self): @@ -77,7 +79,7 @@ class TheSwitch(unittest.TestCase): with self.subTest(choice=choice, window=window): out, calls = self.switch(choice, window) self.assertEqual([c for c in calls if c.startswith("patch-kv.py")], [], out) - self.assertEqual(len(calls), 1, out) + self.assertEqual(len(calls), 2, out) # the window's config, then the template self.assertIn("REACHED", out) def test_a_declaration_that_fails_stops_the_switch_before_the_unit(self): diff --git a/tests/test_lane_templates_check.py b/tests/test_lane_templates_check.py index d07dd48d..3cb71c3b 100644 --- a/tests/test_lane_templates_check.py +++ b/tests/test_lane_templates_check.py @@ -47,7 +47,7 @@ class TheLanesItKnows(unittest.TestCase): def copy(self): d = pathlib.Path(tempfile.mkdtemp(prefix="ltc-")) self.addCleanup(shutil.rmtree, d, True) - for f in [REPO / "install.sh", REPO / "switch-model.sh", *REPO.glob("install-*.sh")]: + for f in [REPO / "install.sh", REPO / "switch-model.sh", REPO / "lanes.sh", *REPO.glob("install-*.sh")]: shutil.copy(f, d / f.name) return d @@ -118,14 +118,14 @@ class TheLanesItKnows(unittest.TestCase): def test_the_27b_and_flash_patcher_calls_are_read_too(self): # the check gives their targets the five fixes: a call of install.sh or switch-model.sh with fixes # of its own would pass it unseen, as the first push of this release did (code review, 2026-10-24) - for script in ("install.sh", "switch-model.sh"): + for script, call in (("install.sh", 'python3 "$REPO_DIR/patch-template.py"'), + ("lanes.sh", 'python3 "$(_lanes_dir)/patch-template.py"')): with self.subTest(script=script): d = self.copy() f = d / script text = f.read_text() - self.assertIn('python3 "$REPO_DIR/patch-template.py"', text) - f.write_text(text.replace('python3 "$REPO_DIR/patch-template.py"', - 'python3 "$REPO_DIR/patch-template.py" --patches=system-reminder', 1)) + self.assertIn(call, text) + f.write_text(text.replace(call, call + " --patches=system-reminder", 1)) with self.assertRaisesRegex(SystemExit, f"{script} runs patch-template.py otherwise"): ltc.lane_specs(d) diff --git a/tests/test_prepare_load_wait.py b/tests/test_prepare_load_wait.py new file mode 100644 index 00000000..ad3cdbff --- /dev/null +++ b/tests/test_prepare_load_wait.py @@ -0,0 +1,222 @@ +#!/usr/bin/env python3 +"""The Load of an update that waits (decision 1408), as prepare-lane.sh runs it for the two text +lanes, on a fabricated cache. + +Sixth review of v1.52.0 (2026-11-19, GLM 5.3), two defects of the Load's prepare: +1. its `switch-model.sh --fetch` stopped right after the download, so the switch's steps + after the fetch never ran on the Load's short path (the lane serves the target the update + waits for: prepare, apply_pending, restart, no switch): the new revision's config.json was + never YaRN-patched for a 1M unit (which does not load), never restored for a native one, + Arete's fp8 KV cache was never declared, and the chat template was never regenerated from the + new revision. prepare-lane.sh now runs those steps itself, against the unit that waits, when + an update waits for this Load and this Load loads its target (lanes.sh's patch_served_checkpoint, + the same function the switch calls with the unit in place). +2. that fetch went into the cache of the unit in place (the switch reads it from the invocation + when no HF_CACHE is passed), while prepare read the waiting unit's: with an HF_CACHE moved by + a re-run of install, the Load downloaded into the old cache and looped. The fetch now passes + the waiting unit's cache. + +The prepare runs as written in a HOME of the test's own, against a docker that records its calls +and knows the pin image is there, a df with room, and a switch-model.sh stub that records its +argv and the HF_CACHE it was given; the patch scripts are the repo's own, run on a fabricated +cache that holds the new revision's snapshot, as if the fetch had just brought it. +""" +import importlib.util +import json +import pathlib +import re +import subprocess +import tempfile +import unittest + +REPO = pathlib.Path(__file__).resolve().parents[1] +_INSTALL = (REPO / "install.sh").read_text() +PINS = dict(re.findall(r'^([A-Z0-9_]+(?:_REPO|_REV))="([^"$]+)"', _INSTALL, re.M)) +PINS["IMAGE"] = re.search(r'^IMAGE="\$\{IMAGE:-([^}]+)\}"', _INSTALL, re.M).group(1) +_spec = importlib.util.spec_from_file_location("patch_template_under_test", REPO / "patch-template.py") +PT = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(PT) +# a chat template carrying every anchor patch-template.py looks for, as the checkpoints' own do +TEMPLATE = "\n".join((PT.EFFORT_ANCHOR, PT.LEAN_ANCHOR, PT.MSG_ANCHOR, PT.SYSTEM_ANCHOR, + PT.TOOL_REF_ANCHOR, PT.TOOL_REF_RAISE)) + "\n" + +NATIVE = {"text_config": {"max_position_embeddings": 262144, "rope_scaling": {"type": "linear"}}} +YARNED = {"text_config": {"max_position_embeddings": 1010000, + "rope_scaling": {"type": "yarn", "factor": 4.0, "original_max_position_embeddings": 262144}}} + + +class Box: + """prepare-lane.sh 27b|flash, with a waiting unit (or launcher) in $CONFIG_DIR/pending and a + fabricated cache holding the new revision's snapshot in the cache that unit mounts.""" + + def __init__(self, lane, target, window="1m", model=None, pending=True, quant=None): + self.t = t = pathlib.Path(tempfile.mkdtemp(prefix=f"prepare-wait-{lane}-")) + self.d = d = t / "repo" + d.mkdir() + for f in ("lanes.sh", "install.sh", "flash-ats-check.sh", "boxmem.py", "patch-yarn.py", + "patch-kv.py", "patch-template.py"): + (d / f).write_text((REPO / f).read_text()) + self.units = t / "units" + self.units.mkdir() + (d / "prepare-lane.sh").write_text( + (REPO / "prepare-lane.sh").read_text().replace("/etc/systemd/system/", f"{self.units}/")) + # the switch the Load's prepare calls: a stub recording its argv and the HF_CACHE it got + (d / "switch-model.sh").write_text( + f'#!/bin/bash\necho "switch-model.sh $*" >> "{t}/calls"\necho "${{HF_CACHE:-}}" >> "{t}/hfenv"\n') + (d / "switch-model.sh").chmod(0o755) + self.bin = t / "bin" + self.bin.mkdir() + (self.bin / "docker").write_text( + f'#!/bin/bash\necho "docker $*" >> "{t}/calls"\ncase "$1" in\n' + f' info) echo "{t}/docker-root" ;;\n' + ' image) exit 0 ;; # the pin image is there\n' + 'esac\nexit 0\n') + (self.bin / "df").write_text('#!/bin/sh\necho Avail; echo 900G\n') + (self.bin / "nvidia-smi").write_text('#!/bin/sh\necho ATS\n') + for n in ("docker", "df", "nvidia-smi"): + (self.bin / n).chmod(0o755) + (t / "meminfo").write_text("MemTotal: 127533104 kB\nMemAvailable: 121000000 kB\n") + self.home = t / "home" + self.cfg = self.home / ".config" / "qwen38" + self.cfg.mkdir(parents=True) + self.hf_inplace = t / "hf-inplace" + self.hf_wait = t / "hf-wait" + self.hf_inplace.mkdir() + self.hf_wait.mkdir() + img = PINS["IMAGE"] + repo = model or PINS[{"27b": "STOCK_REPO", "flash": "FLASH_REPO"}[lane]] + rev = PINS[{"27b": "STOCK_REV", "flash": "FLASH_REV"}[lane]] if model is None else PINS["ARETE_REV"] + if model is not None: + repo = PINS["ARETE_REPO"] + window_line = " --context-length 1010000 \\\\\n" if window == "1m" else "" + unit_text = ( + "[Service]\nExecStart=/usr/bin/docker run --rm --name qwen38 --gpus all \\\n" + f" -v {{hf}}:/root/.cache/huggingface \\\\\n" + f" {img} \\\\\n python3 -m sglang.launch_server \\\\\n" + f" --model-path {repo} --revision {rev} \\\\\n{window_line} --port 30000\n") + # the unit in place mounts the old cache and serves the target, the waiting one the new cache + (self.units / "qwen38-sglang.service").write_text(unit_text.replace("{hf}", str(self.hf_inplace))) + (self.cfg / "launch-flash.sh").write_text( + "exec /usr/bin/docker run --rm --name qwen38-flash --gpus all \\\n" + f" -v {self.hf_inplace}:/root/.cache/huggingface \\\n -e HF_HUB_OFFLINE=1 \\\n" + f" {img} \\\n python3 -m sglang.launch_server \\\n --model-path {PINS['FLASH_REPO']} " + f"--revision {PINS['FLASH_REV']}\\n") + if pending: + (self.cfg / "pending").mkdir() + if lane == "27b": + (self.cfg / "pending" / "qwen38-sglang.service").write_text( + unit_text.replace("{hf}", str(self.hf_wait))) + (self.cfg / "pending" / "qwen38-sglang.service.needs").write_text("checkpoint gone\n") + else: + (self.cfg / "pending" / "launch-flash.sh").write_text( + "exec /usr/bin/docker run --rm --name qwen38-flash --gpus all \\\n" + f" -v {self.hf_wait}:/root/.cache/huggingface \\\n -e HF_HUB_OFFLINE=1 \\\n" + f" {img} \\\n python3 -m sglang.launch_server \\\n --model-path {PINS['FLASH_REPO']} " + f"--revision {PINS['FLASH_REV']}\\n") + (self.cfg / "pending" / "qwen38-flash.service.needs").write_text("checkpoint gone\n") + # the fabricated cache: the new revision's snapshot, as if the fetch had just brought it + self.repo, self.rev = repo, rev + snap = self.hf_wait / "hub" / ("models--" + repo.replace("/", "--")) / "snapshots" / rev + snap.mkdir(parents=True) + cfg = dict(NATIVE) + if quant == "arete": + cfg = {"text_config": NATIVE["text_config"], + "quantization_config": {"quant_method": "modelopt", "quant_algo": "FP8"}} + (snap / "hf_quant_config.json").write_text(json.dumps({"quantization": {"format": "float8"}})) + if quant == "yarned": + cfg = dict(YARNED) + (snap / "config.json.pre-yarn").write_text(json.dumps(NATIVE)) + (snap / "config.json").write_text(json.dumps(cfg)) + (snap / "chat_template.jinja").write_text(TEMPLATE) + self.snap = snap + + def run(self, *args): + env = {"PATH": f"{self.bin}:/usr/bin:/bin", "HOME": str(self.home), "QWEN38_MEMINFO": str(self.t / "meminfo")} + r = subprocess.run(["bash", str(self.d / "prepare-lane.sh"), *args], capture_output=True, + text=True, timeout=60, env=env) + calls = (self.t / "calls").read_text().splitlines() if (self.t / "calls").exists() else [] + hfenv = (self.t / "hfenv").read_text().splitlines() if (self.t / "hfenv").exists() else [] + return r.returncode, r.stdout + r.stderr, calls, hfenv + + def config(self): + return json.loads((self.snap / "config.json").read_text()) + + +class TheLoadsFetchGoesIntoTheWaitingUnitsCache(unittest.TestCase): + """Defect 2: prepare-lane.sh's `switch-model.sh --fetch` passes the cache the unit + that waits mounts, so a cache moved by a re-run of install with HF_CACHE= gets the download + and the Load does not loop (the switch would read the one in place).""" + + def test_27b(self): + b = Box("27b", "stock") + rc, out, calls, hfenv = b.run("27b", "stock") + self.assertEqual(rc, 0, out) + self.assertIn("switch-model.sh stock --fetch", calls) + self.assertEqual(hfenv, [str(b.hf_wait)], out) + + def test_flash(self): + b = Box("flash", "flash") + rc, out, calls, hfenv = b.run("flash", "flash") + self.assertEqual(rc, 0, out) + self.assertIn("switch-model.sh flash --fetch", calls) + self.assertEqual(hfenv, [str(b.hf_wait)], out) + + +class TheLoadPatchesTheWaitingUnitsCheckpoint(unittest.TestCase): + """Defect 1: when an update waits for this Load and this Load loads its target, the switch's + steps after the fetch run in the prepare too, against the unit that waits: the new revision's + config.json patched for the window that unit serves, Arete's KV declaration, the chat template + regenerated from its own snapshot.""" + + def test_a_1m_wait_patches_the_new_revisions_config_and_template(self): + b = Box("27b", "stock", window="1m") + rc, out, calls, _ = b.run("27b", "stock") + self.assertEqual(rc, 0, out) + cfg = b.config() + tc = cfg.get("text_config", cfg) + self.assertEqual(tc["max_position_embeddings"], 1010000, out) + self.assertEqual(tc.get("rope_parameters", {}).get("rope_type"), "yarn", out) + tpl = b.cfg / "chat-template-sglang.jinja" + self.assertTrue(tpl.is_file(), out) + self.assertIn("'max', 'high'", tpl.read_text(), "the template is the patched one, from the new revision") + + def test_a_native_wait_restores_the_new_revisions_config(self): + b = Box("27b", "stock", window="native", quant="yarned") + rc, out, _, _ = b.run("27b", "stock") + self.assertEqual(rc, 0, out) + tc = b.config().get("text_config", {}) + self.assertEqual(tc.get("max_position_embeddings"), 262144, out) + self.assertFalse((b.snap / "config.json.pre-yarn").exists(), "the restore consumed its backup") + + def test_an_arete_wait_gets_the_fp8_kv_declaration(self): + b = Box("27b", "arete", window="1m", model=PINS["ARETE_REPO"], quant="arete") + rc, out, _, _ = b.run("27b", "arete") + self.assertEqual(rc, 0, out) + cfg = b.config() + self.assertEqual(cfg["quantization_config"].get("kv_cache_scheme"), + {"dynamic": False, "num_bits": 8, "type": "float"}, out) + hfq = json.loads((b.snap / "hf_quant_config.json").read_text()) + self.assertEqual(hfq["quantization"].get("kv_cache_quant_algo"), "FP8", out) + + def test_a_flash_wait_regenerates_its_own_template(self): + b = Box("flash", "flash") + rc, out, _, _ = b.run("flash", "flash") + self.assertEqual(rc, 0, out) + tpl = b.cfg / "chat-template-flashnext.jinja" + self.assertTrue(tpl.is_file(), out) + self.assertIn("'max', 'high'", tpl.read_text()) + self.assertFalse((b.cfg / "chat-template-sglang.jinja").exists(), out) + + def test_without_a_wait_the_prepare_patches_nothing(self): + # no update waits: the switch step of the journey runs the steps, against the unit in place + b = Box("27b", "stock", window="1m", pending=False) + rc, out, _, hfenv = b.run("27b", "stock") + self.assertEqual(rc, 0, out) + self.assertEqual(hfenv, [str(b.hf_inplace)], out) # no wait: the cache of the unit in place + tc = b.config().get("text_config", {}) + self.assertEqual(tc.get("max_position_embeddings"), 262144, out) + self.assertFalse((b.cfg / "chat-template-sglang.jinja").exists(), out) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_switch_native_restore.py b/tests/test_switch_native_restore.py index 33ede8b6..17b7b2ee 100644 --- a/tests/test_switch_native_restore.py +++ b/tests/test_switch_native_restore.py @@ -6,7 +6,10 @@ A native server crashes at load on a YaRN-patched config.json (measured 2026-09- the box goes back to native, since install.sh restores the target it installs and not the others. switch-model.sh skipped the patch in native mode and restored nothing, so a switch to such a target queued an engine that could not start (found in review, 2026-09-24). -The switch's own lines run here with patch-yarn.py replaced by a stub that records calls. +The switch's steps after the fetch now live in lanes.sh's patch_served_checkpoint, called by +the switch with the unit in place and by prepare-lane.sh with the unit that waits; the +function runs here with patch-yarn.py and patch-template.py replaced by stubs that record +calls. """ import pathlib import subprocess @@ -14,41 +17,56 @@ import tempfile import unittest REPO = pathlib.Path(__file__).resolve().parents[1] -TEXT = (REPO / "switch-model.sh").read_text() -START = TEXT.index('if [ "$TARGET_LANE" = "27b" ] && grep -q -- \'--context-length 1010000\' "$TARGET_UNIT"; then') -BLOCK = TEXT[START:TEXT.index("\nfi\n", START) + 4] +LANES = (REPO / "lanes.sh").read_text() +FN = LANES[LANES.index("patch_served_checkpoint(){"):LANES.index("\n}\n", LANES.index("patch_served_checkpoint(){")) + 3] -def run(context_length, restore_rc=0): +def run(lane, choice, context_length, restore_rc=0): d = pathlib.Path(tempfile.mkdtemp(prefix="sw-restore-")) (d / "unit").write_text(f"ExecStart=... --context-length {context_length} ...\n") (d / "patch-yarn.py").write_text( "import sys\nopen(sys.argv[0] + '.log', 'a').write(' '.join(sys.argv[1:]) + '\\n')\n" f"sys.exit({restore_rc} if '--restore' in sys.argv else 0)\n") + (d / "patch-template.py").write_text( + "import sys\nopen(sys.argv[0] + '.log', 'a').write(' '.join(sys.argv[1:]) + '\\n')\n") script = ('set -euo pipefail\ndie(){ echo "DIE: $*"; exit 1; }\n' - f'REPO_DIR="{d}"; HF_CACHE=/hf; TARGET_LANE=27b; TARGET_REPO=org/uncensored; ' - f'TARGET_REV=abc; TARGET_UNIT="{d}/unit"\n' + BLOCK + "echo REACHED\n") + f'_lanes_dir(){{ echo "{d}"; }}\nCONFIG_DIR="{d}"\n' + FN + + f'patch_served_checkpoint {lane} {choice} "{d}/unit" /hf org/uncensored abc\necho REACHED\n') r = subprocess.run(["bash", "-c", script], capture_output=True, text=True, timeout=30) log = d / "patch-yarn.py.log" - return r.stdout + r.stderr, log.read_text() if log.exists() else "" + tlog = d / "patch-template.py.log" + return (r.stdout + r.stderr, + log.read_text() if log.exists() else "", + tlog.read_text() if tlog.exists() else "") class ANativeSwitchRestores(unittest.TestCase): def test_the_target_is_restored_on_a_native_unit(self): - out, calls = run(262144) + out, calls, _ = run("27b", "stock", 262144) self.assertIn("--restore /hf org/uncensored abc", calls, out) self.assertIn("REACHED", out) def test_a_restore_that_fails_stops_the_switch_before_the_unit(self): - out, _ = run(262144, restore_rc=1) + out, _, _ = run("27b", "stock", 262144, restore_rc=1) self.assertIn("DIE:", out) self.assertNotIn("REACHED", out) def test_a_1m_unit_still_gets_the_patch(self): - out, calls = run(1010000) + out, calls, _ = run("27b", "stock", 1010000) self.assertIn("/hf org/uncensored abc", calls) self.assertNotIn("--restore", calls) + def test_the_template_is_regenerated_from_the_targets_snapshot(self): + out, _, tpl = run("27b", "stock", 1010000) + self.assertIn("/hf", tpl, out) + self.assertIn("abc org/uncensored", tpl) + self.assertIn("chat-template-sglang.jinja", tpl) + + def test_the_flash_lane_gets_no_yarn_call_and_its_own_template(self): + out, calls, tpl = run("flash", "flash", 262144) + self.assertEqual(calls, "", out) + self.assertIn("chat-template-flashnext.jinja", tpl, out) + if __name__ == "__main__": unittest.main(verbosity=2)