okami.mom/strata

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

Niko1221Merge f-ds-out ac306afb2 into f-own-intaff3a132f

main
14.6 KiB273 linesraw
1"""#4891 ("Qwen breaks each time Strata is updated"): a saved run config names folders of one version of Strata's own components (the Control bundle that
2ran setup: cwd, --expert-profile; an engine package: the picture reader, library folders).  The update keeps the new Control and
3the one before it, so the SECOND update after setup removes the folder the config names; the model then showed as "not installed" and a start failed.
4
5The updates here are real (`updater.run_update(control=True)` unpacks and prunes Control folders; `prune_engines` removes the
6older engine packages); the starts are real `runtime.start` calls with a fake engine, the way the app (with --die-with-pid) and the Terminal start.
7"""
8from __future__ import annotations
9
10import json
11import os
12import shutil
13import sys
14import unittest
15from pathlib import Path
16
17sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
18from strata_control import cfg_paths, doctor, engine_component as ec, profiles, runtime, updater  # noqa: E402
19from tests.terminal.test_updater import PLATFORM, UpdaterCase  # noqa: E402
20
21WINDOWS = os.name == "nt"
22FAKE_ENGINE = ("#!" + sys.executable + "\nimport sys\n"
23               "print('READY 4096 stop', flush=True)\n"
24               "for line in sys.stdin:\n"
25               "    if line.strip() == 'QUIT': break\n"
26               "    if line.startswith(('GEN ', 'BGEN ')):\n"
27               "        print('T 97', flush=True)\n"
28               "        print('DONE 1 1 1.0 1.0 length 0 0 0', flush=True)\n")
29
30
31class StaleConfigPaths(UpdaterCase):
32    # (UpdaterCase's own tests are not repeated)
33    def setUp(self):
34        super().setUp()
35        self.control = self.components / "control"
36        self.engine_root = self.components / "engine"
37        self.sequence = 0
38        # Control 0.1.44 is what ran setup: its data/ holds the shipped expert profile
39        self.install_control("0.1.44")
40        (self.control / "active.json").write_text(json.dumps({"version": "0.1.44", "folder": "0.1.44", "sha256": "0" * 64}))
41        # the engine package that setup (or an earlier update) wrote into the config
42        self.engine_kind = f"{PLATFORM}-cuda-cuda13"
43        (self.root / "packs" / "iq3_s").mkdir(parents=True)
44        self.old_engine = self.make_engine_folder(self.engine_root, "0.1.44")
45        self.tokenizer = str(self.root / "tokenizer")
46        self.mine = self.root / "mine" / "my-profile.bin"   # a path the person typed themselves
47        self.configs = {}
48
49    # ------------------------------------------------------------------ the world
50
51    def install_control(self, version):
52        folder = self.control / version
53        (folder / "data").mkdir(parents=True)
54        (folder / "strata.py").write_text(f"print('strata {version} (python stub)')\n")
55        (folder / "data" / "expert-profile.bin").write_bytes(b"profile-" + version.encode())
56        return folder
57
58    def make_engine_folder(self, root, version, script_name=None):
59        folder = root / f"{version}-{self.engine_kind}"
60        folder.mkdir(parents=True)
61        name = script_name or ("engine.cmd" if WINDOWS else "engine.py")
62        script = folder / "engine.py"
63        script.write_text(FAKE_ENGINE, encoding="utf-8")
64        script.chmod(0o700)
65        if WINDOWS:
66            (folder / "engine.cmd").write_bytes(f'@echo off\r\n"{sys.executable}" "%~dp0engine.py" %*\r\n'.encode())
67        (folder / "strata-vision").write_bytes(b"reader " + version.encode())
68        return folder
69
70    def engine_exe(self, folder):
71        return folder / ("engine.cmd" if WINDOWS else "engine.py")
72
73    def publish_control(self, version):
74        bundle = self.root / f"bundle-{version}"
75        (bundle / "strata_control").mkdir(parents=True)
76        (bundle / "data").mkdir()
77        (bundle / "data" / "expert-profile.bin").write_bytes(b"profile-" + version.encode())
78        (bundle / "strata.py").write_text(f"print('strata {version} (python stub)')\n")
79        (bundle / "strata_control" / "__init__.py").write_text("")
80        from feed_tool import build_feed, pack_control
81        shutil.rmtree(self.release, ignore_errors=True)
82        (self.release / "control").mkdir(parents=True)
83        pack_control(bundle, self.release / "control", version=version, platform=PLATFORM)
84        self.sequence += 1
85        build_feed(self.release, key=self.key, sequence=self.sequence, control_dir=self.release / "control")
86
87    def update_to(self, version):
88        self.publish_control(version)
89        out = updater.run_update(self.ctx(), engine=False, control=True)
90        self.assertEqual(out["results"][0]["status"], "updated", out)
91
92    def two_updates(self):
93        """Setup ran on Control 0.1.44.  Two updates later (0.1.45, then 0.1.46) Control keeps 0.1.46 and 0.1.45, and the engine package
94        is replaced the way its update does it."""
95        self.update_to("0.1.45")
96        self.assertTrue((self.control / "0.1.44").is_dir(), "one update keeps the folder before it")
97        self.update_to("0.1.46")
98        self.assertFalse((self.control / "0.1.44").exists(), "the second update removes the folder setup wrote into the config")
99        new_engine = self.make_engine_folder(self.engine_root, "0.1.46")
100        updater.prune_engines(self.components, {new_engine.name})
101        self.assertFalse(self.old_engine.exists())
102        return new_engine, None
103
104    def qwen_config(self, name, vision=False, **extra):
105        cfg = {"exe": str(self.engine_exe(self.old_engine)), "backend": "cuda", "tokenizer": self.tokenizer,
106               "cwd": str(self.control / "0.1.44"), "model_name": "fake", "host": "127.0.0.1", "port": 0,
107               "lib_dirs": [str(self.old_engine)],
108               "args": ["--pack", str(self.root / "packs" / "iq3_s"),
109                        "--expert-profile", str(self.control / "0.1.44" / "data" / "expert-profile.bin"),
110                        "--expert-profile-save", str(self.control / "0.1.44" / "data" / "learned.bin"),
111                        "--mtp", "2", "--lookup-file", str(self.mine)]}
112        if vision:                                            # (a real start would run the picture reader: only the read-side tests ask for it)
113            cfg["vision"] = {"exe": str(self.old_engine / "strata-vision")}
114        cfg.update(extra)
115        path = self.root / "run" / f"{name}.json"
116        path.parent.mkdir(exist_ok=True)
117        path.write_text(json.dumps(cfg, indent=2), encoding="utf-8")
118        profiles.create(name, str(path))
119        self.configs[name] = path
120        return path
121
122    def deepseek_config(self, name):
123        """A DeepSeek config of Strata 0.2.13: its engine in engine-dsv41/, its cwd in the Control that ran setup."""
124        old_ds = self.root / "data" / "engine-dsv41" / f"0.1.49-{self.engine_kind}"
125        exe = old_ds / "strata-dsv41"
126        cfg = {"exe": str(exe), "arch": "deepseek41", "backend": "cuda", "tokenizer": self.tokenizer, "cwd": str(self.control / "0.1.44"),
127               "model_name": "deepseek", "host": "127.0.0.1", "port": 0, "lib_dirs": [str(old_ds)],
128               "args": ["--pack", str(self.root / "packs" / "ds"), "--max-context", "8192"]}
129        path = self.root / "run" / f"{name}.json"
130        path.parent.mkdir(exist_ok=True)
131        path.write_text(json.dumps(cfg, indent=2), encoding="utf-8")
132        profiles.create(name, str(path))
133        self.configs[name] = path
134        return path
135
136    def cfg_of(self, path):
137        return json.loads(Path(path).read_text(encoding="utf-8"))
138
139    def without_output_path(self, path):
140        """The config's text without the one path the engine WRITES (--expert-profile-save), which is deliberately not looked for."""
141        return Path(path).read_text(encoding="utf-8").replace(json.dumps(str(self.control / "0.1.44" / "data" / "learned.bin"))[1:-1], "")
142
143    def host_log_lines(self, name, word="config:"):
144        _, _, log_path = runtime._paths(name)
145        return [l for l in log_path.read_text(encoding="utf-8").splitlines() if word in l] if log_path.exists() else []
146
147    def stop(self, name):
148        try:
149            if runtime._read_state(name) is not None:
150                runtime.stop(name, timeout=12)
151        except Exception:                                     # noqa: BLE001
152            pass
153
154    # ------------------------------------------------------------------ what an update does
155
156    def test_the_folders_the_config_names_are_gone_after_two_updates_and_the_model_looks_missing(self):
157        path = self.qwen_config("qwen", vision=True)
158        self.two_updates()
159        cfg = self.cfg_of(path)
160        self.assertFalse(Path(cfg["cwd"]).exists())
161        self.assertFalse(Path(cfg["args"][cfg["args"].index("--expert-profile") + 1]).exists())
162        report = doctor.inspect(path)
163        stale = [c for c in report["components"] if c["status"] != "ok" and c["name"] in ("expert-profile", "vision/exe", "engine")]
164        self.assertEqual(stale, [], "the doctor (and so the model list) must follow the current folders: " + json.dumps(stale))
165
166    def test_reading_the_config_follows_the_current_version_in_memory_and_writes_nothing(self):
167        path = self.qwen_config("qwen", vision=True)
168        new_engine, _ = self.two_updates()
169        before = path.read_bytes()
170        cfg = profiles.read_run_config(path)
171        active = self.control / "0.1.46"
172        self.assertEqual(Path(cfg["cwd"]), active)
173        self.assertEqual(Path(cfg["args"][cfg["args"].index("--expert-profile") + 1]), active / "data" / "expert-profile.bin")
174        self.assertEqual(Path(cfg["vision"]["exe"]), new_engine / "strata-vision")
175        self.assertEqual([Path(d) for d in cfg["lib_dirs"]], [new_engine])
176        self.assertEqual(Path(cfg["exe"]), self.engine_exe(new_engine))
177        self.assertEqual(path.read_bytes(), before)
178
179    def test_the_paths_the_person_typed_and_the_data_are_left_alone(self):
180        path = self.qwen_config("qwen")
181        self.two_updates()
182        cfg = profiles.read_run_config(path)
183        args = cfg["args"]
184        self.assertEqual(args[args.index("--pack") + 1], str(self.root / "packs" / "iq3_s"))
185        self.assertEqual(args[args.index("--lookup-file") + 1], str(self.mine))      # (typed, outside Strata's folders, does not exist: not touched)
186        self.assertEqual(args[args.index("--mtp") + 1], "2")
187        self.assertEqual(args[args.index("--expert-profile-save") + 1], str(self.control / "0.1.44" / "data" / "learned.bin"),
188                         "a path the engine writes is not a file to look for")
189        self.assertEqual(cfg["tokenizer"], self.tokenizer)
190        self.assertEqual(cfg["model_name"], "fake")
191
192    def test_a_folder_that_still_exists_is_not_replaced_by_a_newer_one(self):
193        path = self.qwen_config("qwen")
194        self.update_to("0.1.45")                              # 0.1.44 is still there (the version before the newest)
195        before = path.read_bytes()
196        cfg = profiles.read_run_config(path)
197        self.assertEqual(cfg["cwd"], str(self.control / "0.1.44"))
198        self.assertEqual(cfg_paths.repair([path]), ([], []))
199        self.assertEqual(path.read_bytes(), before)
200
201    # ------------------------------------------------------------------ starts
202
203    def test_a_terminal_start_rewrites_the_config_once_and_says_so_in_one_line(self):
204        path = self.qwen_config("term")
205        new_engine, _ = self.two_updates()
206        self.addCleanup(self.stop, "term")
207        started = runtime.start("term", wait=60)
208        self.assertTrue(started["ok"], started)
209        cfg = self.cfg_of(path)
210        self.assertEqual(cfg["cwd"], str(self.control / "0.1.46"))
211        self.assertEqual(cfg["exe"], str(self.engine_exe(new_engine)))
212        self.assertNotIn("0.1.44", self.without_output_path(path))
213        self.assertEqual(len(self.host_log_lines("term")), 1, self.host_log_lines("term"))
214        self.assertIn("earlier Strata version", self.host_log_lines("term")[0])
215        runtime.stop("term", timeout=12)
216        again = runtime.start("term", wait=60)
217        self.assertTrue(again["ok"], again)
218        self.assertEqual(len(self.host_log_lines("term")), 1, "nothing is rewritten the second time")
219
220    def test_an_app_start_with_die_with_pid_does_the_same(self):
221        path = self.qwen_config("app-1")
222        self.two_updates()
223        self.addCleanup(self.stop, "app-1")
224        started = runtime.start("app-1", wait=60, die_with_pid=os.getpid())
225        self.assertTrue(started["ok"], started)
226        self.assertEqual(self.cfg_of(path)["cwd"], str(self.control / "0.1.46"))
227
228    def test_a_start_planned_on_the_old_file_is_not_refused_because_strata_rewrote_it(self):
229        import hashlib
230        path = self.qwen_config("app-2")
231        self.two_updates()
232        self.addCleanup(self.stop, "app-2")
233        planned = hashlib.sha256(path.read_bytes()).hexdigest()
234        started = runtime.start("app-2", wait=60, expected_source_sha256=planned)
235        self.assertTrue(started["ok"], started)
236
237    def test_every_saved_profile_is_repaired_by_one_start(self):
238        a, b = self.qwen_config("one"), self.qwen_config("two")
239        self.two_updates()
240        self.addCleanup(self.stop, "one")
241        self.assertTrue(runtime.start("one", wait=60)["ok"])
242        self.assertNotIn("0.1.44", self.without_output_path(b), "the Models page reads the other profiles' configs too")
243
244    def test_a_deepseek_config_is_left_exactly_as_it_was(self):
245        """This Strata runs no DeepSeek model (strata_control/retired.py): neither the repair nor a start writes its config, which may still
246        serve the Strata it came from; the start says why it stops."""
247        path = self.deepseek_config("ds")
248        self.two_updates()
249        before = Path(path).read_bytes()
250        self.assertEqual(cfg_paths.repair([path]), ([], []))
251        with self.assertRaises(profiles.ProfileError) as caught:
252            runtime.start("ds", wait=1, die_with_pid=os.getpid())
253        self.assertIn("is a DeepSeek model. This version of Strata no longer runs DeepSeek models, so it was not started.", str(caught.exception))
254        self.assertEqual(Path(path).read_bytes(), before)
255
256    # ------------------------------------------------------------------ a file that is nowhere
257
258    def test_a_file_the_new_version_no_longer_has_stops_the_start_with_its_name(self):
259        path = self.qwen_config("lost")
260        self.two_updates()
261        (self.control / "0.1.46" / "data" / "expert-profile.bin").unlink()
262        (self.control / "0.1.45" / "data" / "expert-profile.bin").unlink()
263        with self.assertRaises(profiles.ProfileError) as caught:
264            runtime.start("lost", wait=5)
265        text = str(caught.exception)
266        self.assertIn("expert-profile.bin", text)
267        self.assertIn("removed by an update", text)
268        self.assertIn("run setup again", text)
269        self.assertIn("0.1.44", path.read_text(encoding="utf-8"), "nothing is guessed: the file is left as it was")
270
271
272if __name__ == "__main__":
273    unittest.main()