okami.mom/strata

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

Niko1221Merge f-022-left: interrupted-move prompt (app + Terminal), deterministic disk test, engine-minimum test reads the tree version1f727f4b5

main
19.4 KiB400 linesraw
1"""Moving the models to another folder (strata models move): same drive, another drive, stop, a failed check, disk full, resume."""
2from __future__ import annotations
3
4import hashlib
5import json
6import os
7import shutil
8import tempfile
9import unittest
10from pathlib import Path
11from unittest import mock
12
13from strata_control import models_move as mm
14
15
16def sha(data: bytes) -> str:
17    return hashlib.sha256(data).hexdigest()
18
19
20class MoveCase(unittest.TestCase):
21    def setUp(self):
22        self.tmp = tempfile.TemporaryDirectory(prefix="strata-move-")
23        self.addCleanup(self.tmp.cleanup)
24        self.base = Path(self.tmp.name)
25        self.old = self.base / "old"
26        self.new = self.base / "new"
27        self.files = {
28            "models/gyro-s/a.gguf": b"A" * 300_000,
29            "models/gyro-s/b.gguf": b"B" * 200_000,
30            "packs/gyro-s/dense.bin": b"D" * 100_000,
31            "models/coder/c.gguf": b"C" * 150_000,
32            "mtp/rt/experts.bin": b"M" * 50_000,
33        }
34        for rel, data in self.files.items():
35            f = self.old / rel
36            f.parent.mkdir(parents=True, exist_ok=True)
37            f.write_bytes(data)
38        # a finished download carries the pinned checksum in its mark
39        (self.old / "models/gyro-s/a.gguf.done").write_text(f"done sha256 {sha(self.files['models/gyro-s/a.gguf'])}\n")
40        (self.old / "notes.txt").write_text("not a model file")        # Strata moves its own folders only
41        self.install = self.base / "install"
42        self.install.mkdir()
43        self.config = self.install / "strata-gyro-s.json"
44        self.config.write_text(json.dumps({"args": ["--native", str(self.old / "models/gyro-s/a.gguf"), "--pack", str(self.old / "packs/gyro-s")],
45                                           "mtp": str(self.old / "mtp/rt")}))
46        self.total = sum(len(v) for v in self.files.values())
47
48    def tree(self, root: Path) -> set[str]:
49        return {p.relative_to(root).as_posix() for p in root.rglob("*") if p.is_file() and p.name != mm.STATE_FILE}
50
51    def copy_mode(self):
52        """Another drive: the files are copied, whatever this machine's volumes are."""
53        return mock.patch.object(mm, "same_drive", return_value=False)
54
55    def break_after(self, n):
56        """A copy that works n times, then fails: a move cut off part way."""
57        real, calls = mm._copy_verified, [0]
58
59        def flaky(*args, **kw):
60            calls[0] += 1
61            if calls[0] > n:
62                raise mm.MoveError("io", "cut off")
63            return real(*args, **kw)
64        return mock.patch.object(mm, "_copy_verified", side_effect=flaky)
65
66    def cut_off(self, n=1):
67        with self.copy_mode(), self.break_after(n):
68            with self.assertRaises(mm.MoveError):
69                self.run_move()
70
71    def run_move(self, **kw):
72        events = []
73        summary = mm.move(self.old, self.new, on_progress=events.append, configs=[self.config], **kw)
74        return summary, events
75
76
77class PlanTests(MoveCase):
78    def test_plan_numbers_and_choices(self):
79        with self.copy_mode():
80            p = mm.plan(self.old, self.new, free=lambda _p: 10**9)
81        self.assertTrue(p["ok"])
82        self.assertGreaterEqual(p["models_bytes"], self.total)
83        self.assertGreater(p["needed_bytes"], p["models_bytes"])                    # the 5 % margin
84        self.assertTrue(p["choices"]["move"]["possible"])
85        self.assertEqual({m["name"] for m in p["models"]}, {"gyro-s", "coder", "mtp"})
86
87    def test_not_enough_room_switches_move_off(self):
88        with self.copy_mode():
89            p = mm.plan(self.old, self.new, free=lambda _p: 1000)
90        self.assertTrue(p["ok"])
91        self.assertFalse(p["choices"]["move"]["possible"])
92        self.assertIn("free", p["choices"]["move"]["reason"])
93        self.assertTrue(p["choices"]["keep"]["possible"] and p["choices"]["empty"]["possible"])
94
95    def test_same_drive_needs_no_room(self):
96        p = mm.plan(self.old, self.new, free=lambda _p: 0)
97        self.assertTrue(p["same_drive"])
98        self.assertTrue(p["choices"]["move"]["possible"])
99
100    def test_inside_and_same_are_refused(self):
101        self.assertEqual(mm.plan(self.old, self.old / "sub")["issue"]["code"], "inside")
102        self.assertEqual(mm.plan(self.old / "sub", self.old)["issue"]["code"], "inside")
103        self.assertEqual(mm.plan(self.old, self.old)["issue"]["code"], "same")
104
105    def test_a_folder_that_cannot_be_written_is_refused(self):
106        with mock.patch.object(mm, "_write_test", return_value="EPERM: operation not permitted, mkdir 'x'"):
107            p = mm.plan(self.old, self.new)
108        self.assertEqual(p["issue"]["code"], "not_writable")
109        self.assertIn("EPERM", p["issue"]["details"])
110
111    def test_nothing_is_changed_by_a_plan(self):
112        before = self.tree(self.old)
113        mm.plan(self.old, self.new)
114        self.assertEqual(self.tree(self.old), before)
115
116
117class MoveTests(MoveCase):
118    def check_whole(self):
119        self.assertEqual({k for k in self.tree(self.new) if not k.endswith(".done")}, set(self.files))
120        for rel, data in self.files.items():
121            self.assertEqual((self.new / rel).read_bytes(), data)
122        self.assertEqual(self.tree(self.old), {"notes.txt"})                       # only what is not Strata's own is left
123        cfg = json.loads(self.config.read_text())
124        self.assertEqual(Path(cfg["args"][1]), self.new / "models/gyro-s/a.gguf")
125        self.assertEqual(Path(cfg["mtp"]), self.new / "mtp/rt")
126        self.assertFalse((self.new / mm.STATE_FILE).exists())
127
128    def test_same_drive_is_a_rename(self):
129        with mock.patch.object(shutil, "copyfileobj", side_effect=AssertionError("copied")), mock.patch.object(mm, "_copy_verified", side_effect=AssertionError("copied")):
130            summary, _events = self.run_move()
131        self.assertTrue(summary["done"] and summary["same_drive"])
132        self.check_whole()
133
134    def test_another_drive_copies_checks_and_removes(self):
135        with self.copy_mode():
136            summary, events = self.run_move()
137        self.assertTrue(summary["done"] and not summary["same_drive"])
138        self.assertEqual(summary["files_moved"], len(self.files) + 1)               # + the .done mark
139        self.check_whole()
140        self.assertTrue(events and events[-1]["done"] <= self.total + 100)
141        self.assertEqual(events[0]["event"], "progress")
142
143    def test_stop_keeps_what_moved_and_removes_the_partial_copy(self):
144        calls = {"n": 0}
145
146        def stop():
147            calls["n"] += 1
148            return calls["n"] > 6                                                   # a few chunks into the second file or so
149        with self.copy_mode():
150            summary, _events = self.run_move(cancelled=stop)
151        self.assertTrue(summary["stopped"] and not summary["done"])
152        self.assertEqual([p for p in self.new.rglob("*.part")], [])
153        # every file is in exactly one place, nothing is lost
154        for rel, data in self.files.items():
155            places = [r for r in (self.old, self.new) if (r / rel).exists()]
156            self.assertEqual(len(places), 1, rel)
157            self.assertEqual((places[0] / rel).read_bytes(), data)
158        self.assertTrue(summary["remaining"])
159        # a model that moved whole now points at the new folder; one that did not stays where it is
160        cfg = json.loads(self.config.read_text())
161        for value in (cfg["args"][1], cfg["args"][3], cfg["mtp"]):
162            self.assertTrue(Path(value).exists(), value)
163
164    def test_stop_before_anything_leaves_the_old_folder_as_it_was(self):
165        with self.copy_mode():
166            summary, _ = self.run_move(cancelled=lambda: True)
167        self.assertTrue(summary["stopped"])
168        self.assertEqual(summary["files_moved"], 0)
169        self.assertEqual({k for k in self.tree(self.old) if not k.endswith(".done")}, set(self.files) | {"notes.txt"})
170        self.assertFalse((self.new / mm.STATE_FILE).exists())
171
172    def test_a_copy_that_does_not_match_is_never_trusted(self):
173        real = mm._sha256_of
174        calls = {"n": 0}
175
176        def lies(path, stop, tick=None):
177            calls["n"] += 1
178            return "0" * 64 if str(path).endswith(".part") and calls["n"] == 1 else real(path, stop, tick)
179        with self.copy_mode(), mock.patch.object(mm, "_sha256_of", side_effect=lies):
180            with self.assertRaises(mm.MoveError) as caught:
181                self.run_move()
182        self.assertEqual(caught.exception.code, "verify")
183        self.assertEqual(list(self.new.rglob("*.part")), [])
184        self.assertEqual({k for k in self.tree(self.old) if not k.endswith(".done")}, set(self.files) | {"notes.txt"})   # the original is untouched
185
186    def test_a_file_that_differs_from_its_pinned_checksum_is_not_moved(self):
187        (self.old / "models/gyro-s/a.gguf.done").write_text("done sha256 " + "1" * 64)
188        with self.copy_mode():
189            with self.assertRaises(mm.MoveError) as caught:
190                self.run_move()
191        self.assertEqual(caught.exception.code, "verify")
192        self.assertTrue((self.old / "models/gyro-s/a.gguf").exists())
193        self.assertFalse((self.new / "models/gyro-s/a.gguf").exists())
194
195    def test_disk_full_stops_at_once_and_loses_nothing(self):
196        real = mm._copy_verified
197        seen = {"n": 0}
198
199        def full(src, dst, size, stop, tick):
200            seen["n"] += 1
201            if seen["n"] == 3:
202                part = dst.with_name(dst.name + ".part")
203                part.parent.mkdir(parents=True, exist_ok=True)
204                part.write_bytes(b"half")
205                try:
206                    raise OSError(28, "No space left on device", str(dst))
207                except OSError as e:
208                    mm._quiet_remove(part)
209                    raise mm.MoveError("disk_full", "The drive ran out of space.", str(e)) from e
210            return real(src, dst, size, stop, tick)
211        with self.copy_mode(), mock.patch.object(mm, "_copy_verified", side_effect=full):
212            with self.assertRaises(mm.MoveError) as caught:
213                self.run_move()
214        self.assertEqual(caught.exception.code, "disk_full")
215        self.assertEqual(list(self.new.rglob("*.part")), [])
216        for rel, data in self.files.items():
217            places = [r for r in (self.old, self.new) if (r / rel).exists()]
218            self.assertEqual(len(places), 1, rel)
219        self.assertIn("remaining", caught.exception.summary)
220
221    def test_a_real_disk_full_error_is_named(self):
222        with mock.patch("builtins.open", side_effect=OSError(28, "No space left on device", "x")):
223            with self.assertRaises(mm.MoveError) as caught:
224                mm._copy_verified(self.old / "models/coder/c.gguf", self.new / "x.gguf", 1, lambda: False, lambda n: None)
225        self.assertEqual(caught.exception.code, "disk_full")
226
227    def test_a_crash_leaves_a_part_and_the_next_run_finishes(self):
228        stale = self.new / "models/gyro-s/a.gguf.part"
229        stale.parent.mkdir(parents=True)
230        stale.write_bytes(b"cut off")
231        # a file that was copied and renamed, but whose original was not removed yet
232        done = self.new / "models/coder/c.gguf"
233        done.parent.mkdir(parents=True)
234        done.write_bytes(self.files["models/coder/c.gguf"])
235        with self.copy_mode():
236            summary, _ = self.run_move()
237        self.assertTrue(summary["done"])
238        self.check_whole()
239
240    def test_an_interrupted_move_is_remembered(self):
241        self.cut_off(1)
242        st = mm.interrupted(self.old)                                               # the old folder is still the data folder: it holds the pointer
243        self.assertEqual(st["to"], str(self.new))
244        self.assertEqual(st["state"], "failed")
245        self.assertEqual(mm.interrupted(self.base / "elsewhere"), None)
246        mm._write_state(self.old, state="running", pid=os.getpid() + 7, token=None, **{"from": str(self.old), "to": str(self.new)})
247        self.assertEqual(mm.interrupted(self.old)["state"], "running")
248
249    def test_a_move_that_is_running_now_is_not_interrupted(self):
250        from strata_control import procs
251        mm._write_state(self.old, state="running", pid=os.getpid() + 7, token="t", **{"from": str(self.old), "to": str(self.new)})
252        with mock.patch.object(procs, "start_token", return_value="t"):
253            self.assertIsNone(mm.interrupted(self.old))
254        with mock.patch.object(procs, "start_token", return_value=None):
255            self.assertIsNotNone(mm.interrupted(self.old))
256
257    def test_nothing_moved_leaves_nothing_to_ask_about(self):
258        self.cut_off(0)
259        self.assertIsNone(mm.interrupted(self.old))
260        self.assertFalse((self.new / mm.STATE_FILE).exists())
261
262    def test_finish_resumes_the_move(self):
263        self.cut_off(1)
264        st = mm.interrupted(self.old)
265        with self.copy_mode():
266            summary = mm.move(Path(st["from"]), Path(st["to"]), configs=[self.config])
267        self.assertTrue(summary["done"])
268        self.check_whole()
269        self.assertIsNone(mm.interrupted(self.old))
270        self.assertFalse((self.old / mm.STATE_FILE).exists() or (self.new / mm.STATE_FILE).exists())
271
272    def test_leave_keeps_the_old_folder_complete(self):
273        self.cut_off(1)
274        (self.new / "models/stray.gguf.part").write_bytes(b"x")                      # not listed by the move, but a .part of ours is
275        (self.new / "models/gyro-s").mkdir(parents=True, exist_ok=True)
276        (self.new / "models/gyro-s/a.gguf.part").write_bytes(b"cut")
277        theirs = self.new / "models/own/mine.gguf"                                    # a file of the person's, not part of the move
278        theirs.parent.mkdir(parents=True)
279        theirs.write_bytes(b"mine")
280        st = mm.interrupted(self.old)
281        with self.copy_mode():
282            result = mm.leave(Path(st["from"]), Path(st["to"]), configs=[self.config])
283        self.assertGreaterEqual(result["restored"] + result["removed"], 1)
284        for rel, data in self.files.items():
285            self.assertEqual((self.old / rel).read_bytes(), data, rel)
286            self.assertFalse((self.new / rel).exists(), rel)
287        self.assertEqual(list(self.new.rglob("*.part")), [(self.new / "models/stray.gguf.part")])
288        self.assertTrue(theirs.exists())
289        self.assertIsNone(mm.interrupted(self.old))
290        self.assertFalse((self.new / mm.STATE_FILE).exists())
291        cfg = json.loads(self.config.read_text())
292        self.assertTrue(all(str(self.new) not in str(v) for v in cfg.values()))
293        self.assertIn(str(self.old / "models/gyro-s/a.gguf"), cfg["args"])
294
295    def test_leave_after_a_crash_removes_the_duplicate(self):
296        self.cut_off(1)
297        dup = self.new / "models/coder/c.gguf"                                       # copied and renamed, original not yet removed
298        dup.parent.mkdir(parents=True, exist_ok=True)
299        dup.write_bytes(self.files["models/coder/c.gguf"])
300        mm.leave(self.old, self.new)
301        self.assertFalse(dup.exists())
302        self.assertTrue((self.old / "models/coder/c.gguf").exists())
303
304    def test_configs_are_rewritten_only_for_files_that_are_there(self):
305        self.config.write_text(json.dumps({"args": ["--native", str(self.old / "models/gone.gguf")]}))
306        with self.copy_mode():
307            self.run_move()
308        self.assertEqual(json.loads(self.config.read_text())["args"][1], str(self.old / "models/gone.gguf"))
309
310    @unittest.skipUnless(os.environ.get("STRATA_TEST_OTHER_VOLUME"), "set STRATA_TEST_OTHER_VOLUME to a folder on another volume (e.g. a subst or USB drive)")
311    def test_a_real_second_volume(self):
312        other = Path(os.environ["STRATA_TEST_OTHER_VOLUME"]) / f"strata-move-{os.getpid()}"
313        self.addCleanup(shutil.rmtree, other, True)
314        self.new = other
315        summary, _ = self.run_move()
316        self.assertTrue(summary["done"])
317        self.check_whole()
318
319
320class CommandLineTests(MoveCase):
321    def test_json_plan_and_run(self):
322        from strata_cli import cli
323        import contextlib
324        import io
325        out = io.StringIO()
326        with contextlib.redirect_stdout(out), self.copy_mode():
327            code = cli.main(["models", "move", str(self.new), "--from", str(self.old), "--plan", "--output", "json"])
328        self.assertEqual(code, 0)
329        self.assertTrue(json.loads(out.getvalue())["plan"]["choices"]["move"]["possible"])
330        out = io.StringIO()
331        with contextlib.redirect_stdout(out), self.copy_mode():
332            code = cli.main(["models", "move", str(self.new), "--from", str(self.old), "--install-dir", str(self.install), "--output", "jsonl"])
333        self.assertEqual(code, 0, out.getvalue())
334        lines = [json.loads(line) for line in out.getvalue().splitlines() if line.startswith("{")]
335        self.assertEqual(lines[-1]["event"], "result")
336        self.assertTrue(lines[-1]["done"])
337        self.assertTrue((self.new / "models/coder/c.gguf").exists())
338
339    def run_cli(self, *argv):
340        from strata_cli import cli
341        from strata_control import discovery
342        import contextlib
343        import io
344        out = io.StringIO()
345        with contextlib.redirect_stdout(out), self.copy_mode(), mock.patch.object(discovery, "data_dir", return_value=(self.old, "settings")):
346            code = cli.main(["models", "move", *argv])
347        return code, out.getvalue()
348
349    def test_status_resume_and_leave(self):
350        code, text = self.run_cli("--status", "--output", "json")
351        self.assertEqual((code, json.loads(text)["interrupted"]), (0, None))
352        self.assertEqual(self.run_cli("--resume", "--output", "json")[0], 5)
353        self.cut_off(1)
354        code, text = self.run_cli("--status", "--output", "json")
355        self.assertEqual(json.loads(text)["interrupted"]["to"], str(self.new))
356        self.assertIn("--resume", self.run_cli("--status")[1])
357        code, text = self.run_cli("--leave", "--install-dir", str(self.install), "--output", "json")
358        self.assertEqual(code, 0, text)
359        self.assertTrue((self.old / "models/coder/c.gguf").exists())
360        self.cut_off(1)
361        code, text = self.run_cli("--resume", "--install-dir", str(self.install), "--output", "jsonl")
362        self.assertEqual(code, 0, text)
363        self.assertTrue([json.loads(l) for l in text.splitlines() if l.startswith("{")][-1]["done"])
364        self.assertTrue((self.new / "models/coder/c.gguf").exists())
365        self.assertFalse((self.old / "models/coder/c.gguf").exists())
366
367    def test_launch_says_it_in_one_line(self):
368        from strata_cli.launch import cmd
369        from strata_control import discovery
370        import contextlib
371        import io
372        self.cut_off(1)
373        with mock.patch.object(discovery, "data_dir", return_value=(self.old, "settings")):
374            out = io.StringIO()
375            with contextlib.redirect_stdout(out):
376                cmd._interrupted_move_notice()
377            self.assertEqual(len(out.getvalue().strip().splitlines()), 1)
378            self.assertIn("models move --resume", out.getvalue())
379            mm.leave(self.old, self.new)
380            out = io.StringIO()
381            with contextlib.redirect_stdout(out):
382                cmd._interrupted_move_notice()
383            self.assertEqual(out.getvalue(), "")
384
385    def test_the_cancel_file_stops_the_run(self):
386        from strata_cli import cli
387        import contextlib
388        import io
389        cancel = self.base / "cancel"
390        cancel.write_text("x")
391        out = io.StringIO()
392        with contextlib.redirect_stdout(out), self.copy_mode():
393            code = cli.main(["models", "move", str(self.new), "--from", str(self.old), "--cancel-file", str(cancel), "--output", "json"])
394        self.assertEqual(code, 6)
395        self.assertTrue(json.loads(out.getvalue().splitlines()[-1])["stopped"])
396        self.assertTrue((self.old / "models/coder/c.gguf").exists())
397
398
399if __name__ == "__main__":
400    unittest.main()