Files
alzeo/tests/test_prepare_load_wait.py
T
Hasan Basbunar f40892d4bf 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 <target> --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 <vibe@mistral.ai>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 12:44:17 +01:00

223 lines
12 KiB
Python

#!/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 <target> --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 <target> --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()