okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge main (87dfca0e7) into f-own-int: the 0.2.14 app branch, fixtures and CI fixes, the Qwen4-readiness tools, the shape-engine build scriptsffb3d9b31

main
16.0 KiB292 linesraw
1"""docker/entrypoint.sh: environment variables become `strata launch` flags, the key never appears on a command line, an engine
2that does not fit the card ends the start with a plain message, a started server is kept up, and SIGTERM runs `launch --stop`.
3
4Runs the real script in a temporary tree with a stub for the `strata` command (POSIX sh needed: skipped on Windows).
5
6    python -m unittest tools.test_docker_entrypoint
7"""
8from __future__ import annotations
9
10import os
11import sys
12import shutil
13import signal
14import subprocess
15import tempfile
16import time
17import unittest
18from pathlib import Path
19
20ROOT = Path(__file__).resolve().parents[1]
21SH = shutil.which("sh")
22
23STUB = r"""#!/bin/sh
24# records every call; answers the few read-only queries the entrypoint makes
25echo "$*" >> "$STUB_LOG"
26case "$1 $2" in
27  "components engine") if [ "${STUB_ENGINE:-ok}" = ok ]; then echo "{\"usable\": true, \"backend\": \"${STUB_BACKEND:-}\"}"; else echo '{"usable": false}'; echo "no engine for this card" >&2; fi; exit 0 ;;
28esac
29case "$*" in
30  *"--list-presets --output json"*) if [ -n "${STUB_PRESET:-}" ]; then echo '{"presets": [{"name": "docker"}]}'; fi; exit 0 ;;
31  *"--list-presets"*) if [ -n "${STUB_PRESET:-}" ]; then echo "docker   iq3_xxs   32K   fit to card   ${STUB_TUNED:-not tuned}"; fi; exit 0 ;;
32  *"launch --status"*) echo '{"running": [{"name": "docker", "state": "ready"}]}'; exit 0 ;;
33  *"--show-key"*) echo "KEY-FROM-PRESET-0123456789"; exit 0 ;;
34  *"launch --stop"*) echo "stopped" >> "$STUB_LOG"; exit 0 ;;
35  *"launch --no-tui"*) echo "key-env=${STRATA_LAUNCH_KEY:-}" >> "$STUB_LOG"; [ -n "${STUB_FAIL:-}" ] && exit 6; exit 0 ;;
36esac
37exit 0
38"""
39
40
41@unittest.skipUnless(sys.platform.startswith("linux") and SH is not None, "the container entry point runs in a Linux image (POSIX sh with GNU tools)")
42class Entrypoint(unittest.TestCase):
43    def setUp(self):
44        self.tmp = Path(tempfile.mkdtemp())
45        self.addCleanup(shutil.rmtree, self.tmp, ignore_errors=True)
46        (self.tmp / "opt" / "terminal" / "bin").mkdir(parents=True)
47        stub = self.tmp / "opt" / "terminal" / "bin" / "strata"
48        stub.write_text(STUB, encoding="utf-8")
49        stub.chmod(0o755)
50        self.log = self.tmp / "calls.log"
51        text = (ROOT / "docker" / "entrypoint.sh").read_text(encoding="utf-8")
52        text = (text.replace("/opt/strata", str(self.tmp / "opt")).replace("/data", str(self.tmp / "data"))
53                .replace("/run/strata-phase", str(self.tmp / "phase")).replace("mkdir -p ", "mkdir -p " + str(self.tmp / "run") + " ", 1))
54        self.script = self.tmp / "entry.sh"
55        self.script.write_text(text, encoding="utf-8")
56
57    def env(self, **extra):
58        env = {k: v for k, v in os.environ.items() if k not in ("MODEL", "API_KEY", "CONTEXT", "VISION", "TUNE", "PORT", "GPU", "GPUS")}
59        env.update(STUB_LOG=str(self.log), STRATA_CPUINFO=str(self.tmp / "cpuinfo"), **extra)
60        (self.tmp / "cpuinfo").write_text("flags : fpu avx2 sse4_2\n")
61        return env
62
63    def start(self, **extra) -> subprocess.Popen:
64        return subprocess.Popen([SH, str(self.script)], env=self.env(**extra), stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
65
66    def wait_for(self, text: str, timeout: float = 20.0) -> str:
67        end = time.time() + timeout
68        while time.time() < end:
69            if self.log.exists() and text in self.log.read_text():
70                return self.log.read_text()
71            time.sleep(0.1)
72        self.fail(f"{text!r} not seen in {self.log.read_text() if self.log.exists() else '(no log)'}")
73
74    def stop(self, p: subprocess.Popen) -> tuple[int, str, str]:
75        p.send_signal(signal.SIGTERM)
76        out, err = p.communicate(timeout=30)
77        return p.returncode, out, err
78
79    def launch_line(self, log: str) -> str:
80        return next(line for line in log.splitlines() if line.startswith("launch --no-tui"))
81
82    def test_settings_become_flags_and_sigterm_stops_cleanly(self):
83        (self.tmp / "models").mkdir()
84        (self.tmp / "models" / "m-00001-of-00002.gguf").write_text("x")
85        p = self.start(MODEL="IQ3_XXS", CONTEXT="64k", PARALLEL="2", VISION="yes", TUNE="quick", GPUS="0,1", PORT="8123", PRESET="office",
86                       API_KEY="a-long-enough-key-123456", MODEL_PATH=str(self.tmp / "models"), STRATA_SET="prefill=65536 STRATA_PIN_BY_NEED=1")
87        log = self.wait_for("--show-key")
88        line = self.launch_line(log)
89        for want in ("--access lan", "--port 8123", "--model IQ3_XXS", "--model-path " + str(self.tmp / "models"), "--context 64k", "--parallel 2",
90                     "--vision on", "--gpu 0,1", "--tune quick", "--set prefill=65536", "--set STRATA_PIN_BY_NEED=1",
91                     "--save-preset office", "--api-key-env STRATA_LAUNCH_KEY"):
92            self.assertIn(want, line)
93        self.assertNotIn("a-long-enough-key", line)                      # the key is passed by environment, never on a command line
94        self.assertIn("key-env=a-long-enough-key-123456", log)
95        code, out, err = self.stop(p)
96        self.assertEqual(code, 0, err)
97        self.assertIn("launch --stop --preset office", self.log.read_text())
98        self.assertIn("stopped", self.log.read_text())
99
100    def test_saved_preset_is_reused_and_a_tuned_one_is_not_tuned_again(self):
101        p = self.start(STUB_PRESET="1", STUB_TUNED="tuned 2026-10-17", TUNE="quick", MODEL="Q2_0")
102        line = self.launch_line(self.wait_for("--show-key"))
103        self.assertIn("--preset docker", line)
104        self.assertIn("--model Q2_0", line)
105        self.assertNotIn("--tune", line)
106        self.stop(p)
107
108    def test_untuned_preset_is_tuned_and_retune_forces_it(self):
109        p = self.start(STUB_PRESET="1", TUNE="quick")
110        self.assertIn("--tune quick", self.launch_line(self.wait_for("--show-key")))
111        self.stop(p)
112        self.log.unlink()
113        p = self.start(STUB_PRESET="1", STUB_TUNED="tuned x", TUNE="quick", RETUNE="1")
114        self.assertIn("--tune quick", self.launch_line(self.wait_for("--show-key")))
115        self.assertIn("--retune", self.launch_line(self.wait_for("--show-key")))      # #4779: the launcher needs the flag itself
116        self.stop(p)
117
118    def test_no_settings_asks_for_the_recommended_model_and_warns(self):
119        p = self.start()
120        log = self.wait_for("--show-key")
121        self.assertIn("--save-preset docker", self.launch_line(log))
122        self.assertNotIn("--model ", self.launch_line(log))
123        code, out, err = self.stop(p)
124        self.assertIn("No MODEL was set", err)
125        self.assertIn("made one", err)                                   # no API_KEY given: told how to show the generated key
126
127    def test_wrong_engine_for_this_card_ends_the_start_with_a_plain_message(self):
128        r = subprocess.run([SH, str(self.script)], env=self.env(STUB_ENGINE="none"), capture_output=True, text=True, timeout=30)
129        self.assertEqual(r.returncode, 3)
130        self.assertIn("does not match this computer's graphics card", r.stderr)
131        self.assertIn("docs/DOCKER.md", r.stderr)
132        self.assertNotIn("launch --no-tui", self.log.read_text())
133
134    def test_failed_launch_ends_the_container_with_its_code(self):
135        r = subprocess.run([SH, str(self.script)], env=self.env(STUB_FAIL="1", MODEL="Q2_0"), capture_output=True, text=True, timeout=30)
136        self.assertEqual(r.returncode, 6)
137        self.assertIn("stopped with code 6", r.stderr)
138
139    def test_bad_vision_value_is_a_plain_error(self):
140        r = subprocess.run([SH, str(self.script)], env=self.env(VISION="maybe"), capture_output=True, text=True, timeout=30)
141        self.assertEqual(r.returncode, 2)
142        self.assertIn("VISION=maybe is not one of", r.stderr)
143
144    def test_short_key_and_old_variables_warn(self):
145        p = self.start(API_KEY="short", HOST="0.0.0.0", MODEL="Q2_0")
146        self.wait_for("--show-key")
147        code, out, err = self.stop(p)
148        self.assertIn("API_KEY is short", err)
149        self.assertIn("HOST is from the older image", err)
150
151    def test_a_changed_card_drops_the_saved_run_settings_of_the_old_card(self):
152        install = self.tmp / "data" / "install"
153        install.mkdir(parents=True)
154        (install / "strata-q2_0.json").write_text('{"gpu": 3, "args": []}')
155        (install / "strata-iq3_s.json").write_text('{"gpu": 1, "args": []}')
156        p = self.start(MODEL="Q2_0", GPU="1")
157        line = self.launch_line(self.wait_for("--show-key"))
158        self.assertIn("--gpu 1", line)
159        code, out, err = self.stop(p)
160        self.assertIn("making them again", out)
161        self.assertFalse((install / "strata-q2_0.json").exists())          # card 3 -> 1: made again from the files
162        self.assertTrue((install / "strata-iq3_s.json").exists())          # already card 1: kept
163
164    def test_all_cards_leaves_the_saved_run_settings_alone(self):
165        install = self.tmp / "data" / "install"
166        install.mkdir(parents=True)
167        (install / "strata-q2_0.json").write_text('{"gpu": 3, "args": []}')
168        p = self.start(MODEL="Q2_0", GPUS="all")
169        self.wait_for("--show-key")
170        self.stop(p)
171        self.assertTrue((install / "strata-q2_0.json").exists())
172
173    def test_a_volume_of_the_older_image_is_moved_not_downloaded_again(self):
174        data = self.tmp / "data"
175        (data / "models" / "Qwen3.8-Flash-Next-IQ3_XXS").mkdir(parents=True)
176        shard = data / "models" / "Qwen3.8-Flash-Next-IQ3_XXS" / "a-00001-of-00002.gguf"
177        shard.write_text("weights")
178        (data / "models" / "Qwen3.8-Flash-Next-IQ3_XXS" / "a-00001-of-00002.gguf.done").write_text("x")
179        (data / "packs" / "qwen3.8-flash-next-iq3_xxs").mkdir(parents=True)
180        (data / "packs" / "qwen3.8-flash-next-iq3_xxs" / "experts.bin").write_text("pack")
181        (data / "mtp" / "rt").mkdir(parents=True)
182        (data / "mtp" / "rt" / "experts.bin").write_text("mtp")
183        ino = shard.stat().st_ino
184        p = self.start(MODEL="IQ3_XXS")
185        self.wait_for("--show-key")
186        code, out, err = self.stop(p)
187        new = data / "Strata-data"
188        moved = new / "models" / "Qwen3.8-Flash-Next-IQ3_XXS" / "a-00001-of-00002.gguf"
189        self.assertEqual(moved.read_text(), "weights")
190        self.assertEqual(moved.stat().st_ino, ino)                          # renamed, not copied
191        self.assertTrue((moved.parent / "a-00001-of-00002.gguf.done").exists())
192        self.assertTrue((new / "packs" / "qwen3.8-flash-next-iq3_xxs" / "experts.bin").exists())
193        self.assertTrue((new / "mtp" / "rt" / "experts.bin").exists())
194        self.assertFalse((data / "models").exists())
195        self.assertIn("moved them into", out)
196
197    def test_a_file_already_in_the_new_place_is_never_overwritten(self):
198        data = self.tmp / "data"
199        (data / "models" / "t").mkdir(parents=True)
200        (data / "models" / "t" / "f.gguf").write_text("old")
201        (data / "Strata-data" / "models" / "t").mkdir(parents=True)
202        (data / "Strata-data" / "models" / "t" / "f.gguf").write_text("new")
203        # the older copy stays where it is, so the guard for model files left in the older place (#3421) would stop the start
204        # ("Nothing was downloaded."); ALLOW_DOWNLOAD=1 goes on with a warning, which is what this test is about
205        p = self.start(MODEL="IQ3_XXS", ALLOW_DOWNLOAD="1")
206        self.wait_for("--show-key")
207        self.stop(p)
208        self.assertEqual((data / "Strata-data" / "models" / "t" / "f.gguf").read_text(), "new")   # never overwritten
209        self.assertEqual((data / "models" / "t" / "f.gguf").read_text(), "old")
210
211    def test_older_model_files_that_were_not_moved_stop_the_start_unless_downloading_is_allowed(self):
212        data = self.tmp / "data"
213        (data / "models" / "t").mkdir(parents=True)
214        (data / "models" / "t" / "f.gguf").write_text("old")
215        (data / "Strata-data" / "models" / "t").mkdir(parents=True)
216        (data / "Strata-data" / "models" / "t" / "f.gguf").write_text("new")
217        p = self.start(MODEL="IQ3_XXS")
218        out, err = p.communicate(timeout=30)
219        code = p.returncode
220        self.assertEqual(code, 2, err)
221        self.assertIn("Nothing was downloaded.", out + err)
222        self.assertNotIn("launch --no-tui", self.log.read_text() if self.log.exists() else "")
223
224    def test_run_settings_that_name_another_images_engine_folder_are_made_again(self):
225        install = self.tmp / "data" / "install"
226        install.mkdir(parents=True)
227        here = self.tmp / "opt" / "components" / "engine" / "0.1.46-cuda12"
228        here.mkdir(parents=True)
229        (here / "strata-vision").write_text("x")
230        gone = self.tmp / "opt" / "components" / "engine" / "0.1.46-cuda13"
231        (install / "strata-a.json").write_text('{"exe": "component:strata-engine", "vision": {"exe": "%s/strata-vision"}}' % gone)
232        (install / "strata-b.json").write_text('{"exe": "component:strata-engine", "vision": {"exe": "%s/strata-vision"}}' % here)
233        (install / "strata-c.json").write_text('{"exe": "component:strata-engine", "args": []}')
234        (install / "strata-bad.json").write_text("not json")
235        p = self.start(MODEL="IQ3_XXS")
236        self.wait_for("--show-key")
237        code, out, err = self.stop(p)
238        self.assertFalse((install / "strata-a.json").exists())
239        self.assertTrue((install / "strata-b.json").exists())
240        self.assertTrue((install / "strata-c.json").exists())
241        self.assertTrue((install / "strata-bad.json").exists())
242        self.assertIn("strata-a.json", out)
243        self.assertIn("does not have", out)
244
245    def test_nvidia_card_without_gpu_access_ends_before_any_work(self):
246        dev = self.tmp / "dev"
247        dev.mkdir()
248        r = subprocess.run([SH, str(self.script)], env=self.env(STUB_BACKEND="cuda", STRATA_DEV_DIR=str(dev), MODEL="Q2_0"),
249                           capture_output=True, text=True, timeout=30)
250        self.assertEqual(r.returncode, 3)
251        self.assertIn("--gpus all", r.stderr)
252        self.assertNotIn("launch --no-tui", self.log.read_text())
253        (dev / "nvidia0").write_text("")                                  # with the device files the start goes on
254        p = self.start(STUB_BACKEND="cuda", STRATA_DEV_DIR=str(dev), MODEL="Q2_0")
255        self.wait_for("launch --no-tui")
256        self.stop(p)
257
258    def test_model_path_that_is_not_there_or_empty_ends_the_start_in_plain_words(self):
259        missing = self.tmp / "nothing-mounted"
260        r = subprocess.run([SH, str(self.script)], env=self.env(MODEL="IQ3_XXS", MODEL_PATH=str(missing)), capture_output=True, text=True, timeout=30)
261        self.assertEqual(r.returncode, 2)
262        self.assertIn("is not in the container", r.stderr)
263        self.assertIn("-v /srv/gguf/IQ3_XXS:", r.stderr)
264        empty = self.tmp / "empty"
265        (empty / "IQ3_XXS").mkdir(parents=True)
266        r = subprocess.run([SH, str(self.script)], env=self.env(MODEL="IQ3_XXS", MODEL_PATH=str(empty)), capture_output=True, text=True, timeout=30)
267        self.assertEqual(r.returncode, 2)
268        self.assertIn("holds no .gguf files", r.stderr)
269        (empty / "IQ3_XXS" / "a-00001-of-00002.gguf").write_text("x")
270        r = subprocess.run([SH, str(self.script)], env=self.env(MODEL="IQ3_XXS", MODEL_PATH=str(empty)), capture_output=True, text=True, timeout=30)
271        self.assertEqual(r.returncode, 2)
272        self.assertIn("Set MODEL_PATH=" + str(empty / "IQ3_XXS"), r.stderr)
273        self.assertNotIn("launch --no-tui", self.log.read_text() if self.log.exists() else "")
274
275    def test_own_files_without_a_model_name_do_not_say_recommended_model(self):
276        (self.tmp / "g").mkdir()
277        (self.tmp / "g" / "m-00001-of-00001.gguf").write_text("x")
278        p = self.start(MODEL_PATH=str(self.tmp / "g"))
279        self.wait_for("--show-key")
280        code, out, err = self.stop(p)
281        self.assertIn("Starting Strata: the model files in " + str(self.tmp / "g"), out)
282
283    def test_other_commands_run_instead_of_the_server(self):
284        r = subprocess.run([SH, str(self.script), "strata", "launch", "--plan", "--model", "q2_0"], env=self.env(), capture_output=True,
285                           text=True, timeout=30)
286        self.assertEqual(r.returncode, 0)
287        self.assertIn("launch --plan --model q2_0", self.log.read_text())
288        self.assertNotIn("--no-tui", self.log.read_text())
289
290
291if __name__ == "__main__":
292    unittest.main()