okami.mom/strata

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

Niko1221test_slots: compare the relative save dir through realpath (8.3 temp dir names on Windows)76790f277

main
21.5 KiB449 linesraw
1"""serve/test_slots.py - llama-server compatible /slots/0?action=save|restore over the engine's SAVE/RESTORE lines
2(mock engine: no GPU, no pack).
3
4    python -m unittest serve.test_slots -v
5"""
6from __future__ import annotations
7
8import json
9import os
10import queue
11import sys
12import tempfile
13import threading
14import time
15import unittest
16import urllib.error
17import urllib.request
18from pathlib import Path
19
20sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
21from serve.frontend import ChatTemplate  # noqa: E402
22from serve.server import (ByteTokenizer, Service, StrataEngine, serve, slot_filename_problem,  # noqa: E402
23                          slot_save_dir)
24
25ROOT = Path(__file__).resolve().parents[1]
26
27
28class FakeProc:
29    """Stands in for the engine process: answers SAVE / RESTORE lines like `strata --serve` does."""
30
31    def __init__(self, engine):
32        self.engine = engine
33        self.stdin = self
34        self.sent: list[str] = []
35
36    def write(self, s):
37        self.sent.append(s)
38        cmd, _, path = s.strip().partition(" ")
39        script = self.engine.script
40        if script is not None:                      # a scripted answer: a list of lines, None = the process ends
41            # played by its own thread, like the real engine's output: write() returns at once, so the server's
42            # wait (and its deadline) is already running when a delayed line arrives
43            def play():
44                for line in script:
45                    if self.killed:
46                        return
47                    if isinstance(line, float):
48                        time.sleep(line)
49                    else:
50                        self.engine.lines.put(line)
51            self.player = threading.Thread(target=play, daemon=True)
52            self.player.start()
53            return
54        if cmd == "SAVE":
55            if self.engine.fail:
56                self.engine.lines.put("SERR invalid 0 no complete session to save\n")
57            else:
58                Path(path).write_bytes(b"x" * 1234)
59                self.engine.lines.put("SAVED 62993 1234 401.5\n")
60        elif cmd == "RESTORE":
61            if not Path(path).exists() or self.engine.fail:
62                self.engine.lines.put("SERR invalid 0 session file: saved with another model (model fingerprint differs)\n")
63            else:
64                self.engine.lines.put("RESTORED 62993 1234 560.2\n")
65        elif cmd == "DIE":
66            self.engine.lines.put(None)
67
68    def flush(self):
69        pass
70
71    def poll(self):
72        return -9 if self.killed else None
73
74    killed = False
75
76    def kill(self):
77        self.killed = True
78
79    def wait(self, timeout=None):
80        return -9
81
82
83class FakeEngine(StrataEngine):
84    def __init__(self):
85        super().__init__("strata", ["--max-context", "65536"], lazy=True)
86        self.max_context = 65536
87        self.unloaded, self.ended = False, False
88        self.lines = queue.Queue()
89        self.fail = False
90        self.script = None
91        self.proc = FakeProc(self)
92
93
94class Slots(unittest.TestCase):
95    @classmethod
96    def setUpClass(cls):
97        cls.dir = tempfile.TemporaryDirectory()
98        tok = ByteTokenizer()
99        cls.engine = FakeEngine()
100        cls.svc = Service(cls.engine, tok, ChatTemplate(ROOT / "serve/chat_template.jinja"))
101        cls.svc.slot_save_path = cls.dir.name
102        cls.httpd = serve(cls.svc, port=0)
103        cls.base = f"http://127.0.0.1:{cls.httpd.server_address[1]}"
104
105    @classmethod
106    def tearDownClass(cls):
107        cls.httpd.shutdown()
108        cls.httpd.server_close()
109        cls.dir.cleanup()
110
111    def setUp(self):
112        self.engine.fail = False
113        self.engine.script = None
114        self.engine.silence_s = 300.0
115        self.fresh_engine()
116        self.svc.slot_save_path = self.dir.name
117
118    def fresh_engine(self):
119        self.engine.ended = False
120        old = getattr(self.engine.proc, "player", None)
121        if old is not None:                          # the previous scripted engine has finished...
122            self.engine.proc.killed = True
123            old.join(timeout=5)
124        while not self.engine.lines.empty():         # ...and left no line for the next exchange
125            self.engine.lines.get_nowait()
126        self.engine.proc = FakeProc(self.engine)
127
128    def post(self, path, body, headers=None):
129        req = urllib.request.Request(self.base + path, data=json.dumps(body).encode(),
130                                     headers=headers or {"Content-Type": "application/json"})
131        try:
132            with urllib.request.urlopen(req, timeout=30) as r:
133                return r.status, json.loads(r.read())
134        except urllib.error.HTTPError as e:
135            with e:
136                return e.code, json.loads(e.read())
137
138    def test_a_foreign_page_or_a_form_never_reaches_the_engine(self):
139        for action in ("save", "restore"):
140            for headers, code in (({"Content-Type": "application/json", "Origin": "http://evil.example.com"}, 403),
141                                  ({"Content-Type": "text/plain"}, 415),
142                                  ({"Content-Type": "application/x-www-form-urlencoded"}, 415)):
143                s, b = self.post(f"/slots/0?action={action}", {"filename": "x.bin"}, headers)
144                self.assertEqual(s, code, (action, headers, b))
145        self.assertEqual(self.engine.proc.sent, [])
146        self.assertFalse(Path(self.dir.name, "x.bin").exists())
147
148    def test_save_writes_into_the_slot_save_path(self):
149        s, b = self.post("/slots/0?action=save", {"filename": "a.bin"})
150        self.assertEqual(s, 200, b)
151        self.assertEqual(self.engine.proc.sent, [f"SAVE {Path(self.dir.name, 'a.bin')}\n"])
152        self.assertEqual((b["id_slot"], b["filename"], b["n_saved"], b["n_written"]), (0, "a.bin", 62993, 1234))
153        self.assertAlmostEqual(b["timings"]["save_ms"], 401.5)
154
155    def test_restore_answers_like_llama_server(self):
156        self.post("/slots/0?action=save", {"filename": "b.bin"})
157        s, b = self.post("/slots/0?action=restore", {"filename": "b.bin"})
158        self.assertEqual(s, 200, b)
159        self.assertEqual((b["id_slot"], b["filename"], b["n_restored"], b["n_read"]), (0, "b.bin", 62993, 1234))
160        self.assertAlmostEqual(b["timings"]["restore_ms"], 560.2)
161
162    def test_refused_file_is_an_error_not_a_success(self):
163        self.post("/slots/0?action=save", {"filename": "c.bin"})
164        self.engine.fail = True
165        s, b = self.post("/slots/0?action=restore", {"filename": "c.bin"})
166        self.assertEqual(s, 400, b)
167        self.assertIn("fingerprint", b["error"]["message"])
168
169    def test_missing_file_is_not_found(self):
170        s, b = self.post("/slots/0?action=restore", {"filename": "never-saved.bin"})
171        self.assertEqual(s, 404, b)
172        self.assertEqual(self.engine.proc.sent, [])
173
174    def test_filename_cannot_leave_the_directory(self):
175        for bad in ("../x.bin", "/etc/passwd", "a/b.bin", "", ".", "..", "x\ny.bin",
176                    # Windows: another drive, a stream, devices with and without an extension, names Windows trims
177                    "D:escape.bin", "C:\\x.bin", "a.bin:stream", "NUL", "nul.txt", "CON.bin", "com1.x", "LPT9",
178                    "a.bin.", "a.bin ", ".hidden", ".a.bin.0123456789abcdef.tmp", "x\x7fy", "a*b", "a?b", 'a"b',
179                    "a<b", "a>b", "a|b", "x" * 201, None, 5, ["a"]):
180            s, b = self.post("/slots/0?action=save", {"filename": bad})
181            self.assertEqual(s, 400, (bad, b))
182        self.assertEqual(self.engine.proc.sent, [])
183
184    def test_ordinary_names_are_accepted(self):
185        for good in ("a.bin", "chat-2026-10-03.bin", "a.bin.tmp", "consul.bin", "nullable", "caf\u00e9.bin",
186                     "\u4f1a\u8bdd.bin", "x" * 200):
187            self.assertIsNone(slot_filename_problem(good), good)
188
189    def test_relative_save_dir_becomes_absolute(self):
190        with tempfile.TemporaryDirectory() as base:
191            got = slot_save_dir("sessions", base)
192            self.assertEqual(got, os.path.join(base, "sessions"))
193            self.assertTrue(os.path.isabs(got) and os.path.isdir(got))
194            if os.name != "nt":
195                self.assertEqual(os.stat(got).st_mode & 0o777, 0o700)
196            self.assertEqual(slot_save_dir(got, "/elsewhere"), got)     # an absolute path stays as it is
197            cwd = os.getcwd()
198            try:
199                os.chdir(base)
200                self.assertEqual(os.path.realpath(slot_save_dir("rel")), os.path.realpath(os.path.join(base, "rel")))
201            finally:
202                os.chdir(cwd)
203            for bad in ("", "  ", None, 3, "a\nb"):
204                with self.assertRaises(ValueError):
205                    slot_save_dir(bad, base)
206
207    def test_engine_gets_an_absolute_path_on_one_line(self):
208        self.post("/slots/0?action=save", {"filename": "abs.bin"})
209        line = self.engine.proc.sent[0]
210        self.assertTrue(line.endswith("\n") and line.count("\n") == 1)
211        self.assertTrue(os.path.isabs(line[len("SAVE "):-1]))
212
213    def test_restore_of_a_link_reaches_the_engine_which_decides(self):
214        """The server only checks the name exists (lstat); the engine opens it without following a link."""
215        if os.name == "nt":
216            self.skipTest("symlinks need privileges on Windows")
217        target = Path(self.dir.name, "real.bin")
218        target.write_bytes(b"x")
219        link = Path(self.dir.name, "link.bin")
220        link.symlink_to(target)
221        dangling = Path(self.dir.name, "dangling.bin")
222        dangling.symlink_to(Path(self.dir.name, "nothing"))
223        self.engine.script = ["SERR invalid 0 session file: x: a symbolic link, not a file\n"]
224        for name in ("link.bin", "dangling.bin"):
225            s, b = self.post("/slots/0?action=restore", {"filename": name})
226            self.assertEqual(s, 400, b)
227            self.assertIn("symbolic link", b["error"]["message"])
228
229    def test_progress_lines_keep_a_long_save_alive(self):
230        self.engine.silence_s = 0.3
231        self.engine.script = [0.2, "SESSION 268435456 1198691396\n", 0.2, "SESSION 536870912 1198691396\n", 0.2,
232                              "SAVED 63000 1198691396 2000.0\n"]
233        t0 = time.monotonic()
234        s, b = self.post("/slots/0?action=save", {"filename": "long.bin"})
235        self.assertEqual(s, 200, b)
236        self.assertGreater(time.monotonic() - t0, 0.5)       # the lines arrived during the wait, past its 0.3 s
237        self.assertEqual(b["n_written"], 1198691396)
238        self.assertFalse(self.engine.ended)
239
240    def test_a_small_save_reports_its_only_partial_block(self):
241        """B: a file below one 16 MiB block still reports (the start, then its last partial block)."""
242        self.engine.silence_s = 0.3
243        self.engine.script = ["SESSION 0 56834\n", 0.2, "SESSION 56834 56834\n", 0.2, "SAVED 120 56834 410.0\n"]
244        s, b = self.post("/slots/0?action=save", {"filename": "small.bin"})
245        self.assertEqual(s, 200, b)
246        self.assertEqual(b["n_written"], 56834)
247        self.assertFalse(self.engine.ended)
248
249    def test_a_blocking_step_gets_its_announced_allowance(self):
250        """B: SWAIT gives one non-streaming step (a flush, the device transfer) its own bounded wait."""
251        self.engine.silence_s = 0.3
252        self.engine.script = ["SESSION 1198691396 1198691396\n", "SWAIT flush 1\n", 0.7, "SWAIT publish 1\n", 0.7,
253                              "SAVED 63000 1198691396 2000.0\n"]
254        t0 = time.monotonic()
255        s, b = self.post("/slots/0?action=save", {"filename": "flush.bin"})
256        self.assertEqual(s, 200, b)
257        self.assertGreater(time.monotonic() - t0, 1.3)       # longer than the silence limit, twice
258        self.assertFalse(self.engine.ended)
259        Path(self.dir.name, "flush.bin").write_bytes(b"x")    # the scripted engine wrote nothing; restore needs a file
260        self.engine.script = ["SESSION 16777216 1198691396\n", 0.2, "SWAIT validate 1\n", 0.7, "SWAIT transfer 1\n", 0.7,
261                              "RESTORED 63000 1198691396 900.0\n"]
262        s, b = self.post("/slots/0?action=restore", {"filename": "flush.bin"})
263        self.assertEqual(s, 200, b)
264
265    def test_a_blocking_step_that_never_ends_is_ended(self):
266        """B: the allowance is a bound, not a heartbeat: a step that outlives it ends the engine."""
267        self.engine.silence_s = 0.3
268        self.engine.script = ["SWAIT flush 1\n"]               # then nothing
269        t0 = time.monotonic()
270        s, b = self.post("/slots/0?action=save", {"filename": "stuck.bin"})
271        took = time.monotonic() - t0
272        self.assertEqual(s, 500, b)
273        self.assertGreater(took, 0.9)
274        self.assertLess(took, 5)
275        self.assertIn("blocking step allowed 1 s", b["error"]["message"])
276        self.assertTrue(self.engine.ended and self.engine.proc.killed)
277
278    def test_progress_ends_the_allowance(self):
279        """B: after a SESSION line the ordinary silence limit applies again (the allowance was for one step)."""
280        self.engine.silence_s = 0.3
281        self.engine.script = ["SWAIT transfer 2\n", "SESSION 1 2\n", 0.8, "SAVED 1 2 1.0\n"]
282        s, b = self.post("/slots/0?action=save", {"filename": "reset.bin"})
283        self.assertEqual(s, 500, b)
284        self.assertIn("said nothing", b["error"]["message"])
285        self.assertNotIn("blocking step", b["error"]["message"])
286        self.assertTrue(self.engine.ended)
287
288    def test_malformed_allowances_end_the_engine(self):
289        for script in (["SWAIT flush 0\n"], ["SWAIT flush 3601\n"], ["SWAIT 5\n"], ["SWAIT flush x\n"],
290                       ["SWAIT flush -1\n"], ["SWAIT fl:sh 5\n"], ["SWAIT flush 5 extra\n"]):
291            with self.subTest(script=script):
292                self.fresh_engine()
293                self.engine.script = script + [0.1, "SAVED 1 2 1.0\n"]
294                s, b = self.post("/slots/0?action=save", {"filename": "bad.bin"})
295                self.assertEqual(s, 500, b)
296                self.assertTrue(self.engine.ended and self.engine.proc.killed)
297
298    def test_a_silent_engine_is_ended_not_waited_for(self):
299        self.engine.silence_s = 0.3
300        self.engine.script = []                      # the engine never answers
301        t0 = time.monotonic()
302        s, b = self.post("/slots/0?action=save", {"filename": "silent.bin"})
303        self.assertEqual(s, 500, b)
304        self.assertLess(time.monotonic() - t0, 5)
305        self.assertIn("said nothing", b["error"]["message"])
306        self.assertTrue(self.engine.ended and self.engine.proc.killed)
307        self.assertTrue(self.svc.fifo.acquire(blocking=False))   # the FIFO was released
308        self.svc.fifo.release()
309        self.assertEqual(self.svc.status["queued"], 0)
310        self.assertFalse(self.svc.status["busy"])
311
312    def test_engine_death_is_a_server_error(self):
313        self.engine.script = [None]
314        s, b = self.post("/slots/0?action=save", {"filename": "dead.bin"})
315        self.assertEqual(s, 500, b)
316
317    def test_failed_restore_transfer_is_a_server_error(self):
318        Path(self.dir.name, "t.bin").write_bytes(b"x")
319        self.engine.script = ["SESSION 268435456 1198691396\n",
320                              "FATAL restoring the session file failed after the device state was changed: copy\n"]
321        s, b = self.post("/slots/0?action=restore", {"filename": "t.bin"})
322        self.assertEqual(s, 500, b)
323        self.assertIn("device state", b["error"]["message"])
324
325    def test_malformed_or_mismatched_reply_is_a_server_error(self):
326        for script in (["RESTORED 1 2 3\n"], ["SAVED x y z\n"], ["SAVED 1 2\n"], ["T 5\n"]):
327            self.engine.script = script
328            self.engine.ended = False
329            self.engine.proc = FakeProc(self.engine)
330            s, b = self.post("/slots/0?action=save", {"filename": "m.bin"})
331            self.assertEqual(s, 500, (script, b))
332            self.assertTrue(self.engine.ended, script)           # out of step: the engine is ended
333
334    def test_out_of_protocol_lines_end_the_engine(self):
335        """R4: a line this exchange does not allow is not a heartbeat, and an answer must hold valid numbers."""
336        for script in (["SESSION nonsense\n"], ["SESSION 5\n"], ["SESSION -1 10\n"], ["SESSION 11 10\n"],
337                       ["SESSION 8 10\n", "SESSION 4 10\n"],      # progress going back
338                       ["SAVED -1 -2 nan\n"], ["SAVED 1 2 nan\n"], ["SAVED 1 2 inf\n"], ["SAVED 1 2 -5\n"],
339                       ["SAVED +1 2 3\n"], ["ERR bare refusal\n"], ["SERR weird 0 x\n"], ["SERR io 2 x\n"],
340                       ["SERR io\n"], ["garbage\n"]):
341            self.engine.script = script
342            self.engine.ended = False
343            self.engine.proc = FakeProc(self.engine)
344            s, b = self.post("/slots/0?action=save", {"filename": "p.bin"})
345            self.assertEqual(s, 500, (script, b))
346            self.assertTrue(self.engine.ended and self.engine.proc.killed, script)
347            json.dumps(b, allow_nan=False)                        # standard JSON
348
349    def test_log_lines_are_not_answers(self):
350        self.engine.script = ["INFO something\n", "SAVED 1 2 3.0\n"]
351        s, b = self.post("/slots/0?action=save", {"filename": "i.bin"})
352        self.assertEqual(s, 200, b)
353        self.assertFalse(self.engine.ended)
354
355    def test_typed_refusals_have_their_own_codes(self):
356        """R5: the engine's category decides the status, never the words of the message."""
357        cases = [("storage", "No space left on device", 507), ("storage", "espace insuffisant", 507),
358                 ("memory", "out of memory for the write buffer", 503), ("invalid", "not enough disk space", 400),
359                 ("invalid", "saved with another model", 400), ("io", "Permission denied", 500),
360                 ("io", "RAM", 500)]
361        for kind, msg, code in cases:
362            self.engine.script = [f"SERR {kind} 0 {msg}\n"]
363            s, b = self.post("/slots/0?action=save", {"filename": "k.bin"})
364            self.assertEqual(s, code, (kind, msg, b))
365            self.assertEqual(b["error"]["kind"], kind)
366            self.assertEqual(b["error"]["message"], msg)
367            self.assertNotIn("published", b["error"])
368            self.assertFalse(self.engine.ended)                   # a refusal keeps the engine
369
370    def test_published_failure_is_reported(self):
371        """R3: the folder flush failed after the rename - the new file replaced the old one; the answer says so."""
372        self.engine.script = ["SERR io 1 flushing the directory: Input/output error (the new file has already "
373                              "replaced the old one)\n"]
374        s, b = self.post("/slots/0?action=save", {"filename": "pub.bin"})
375        self.assertEqual(s, 500, b)
376        self.assertTrue(b["error"]["published"])
377        self.assertIn("replaced", b["error"]["message"])
378
379    def test_disk_and_ram_refusals_have_their_own_codes(self):
380        self.engine.script = ["SERR storage 0 session file: not enough disk space (1143 MiB plus a reserve of 4096 "
381                              "MiB needed, 10 MiB free)\n"]
382        self.assertEqual(self.post("/slots/0?action=save", {"filename": "d.bin"})[0], 507)
383        Path(self.dir.name, "r.bin").write_bytes(b"x")
384        self.engine.script = ["SERR memory 0 session file: not enough RAM to read it (1143 MiB plus a floor of 2560 "
385                              "MiB needed, 900 MiB available)\n"]
386        self.assertEqual(self.post("/slots/0?action=restore", {"filename": "r.bin"})[0], 503)
387
388    def test_slot_work_counts_as_activity_and_shows_in_status(self):
389        seen = {}
390
391        def during():
392            time.sleep(0.15)
393            with self.svc.status_lock:
394                seen.update(self.svc.status)
395        self.engine.script = [0.4, "SAVED 1 2 3.0\n"]
396        self.svc.last_request_at = 0
397        t = threading.Thread(target=during)
398        t.start()
399        s, _ = self.post("/slots/0?action=save", {"filename": "act.bin"})
400        t.join()
401        self.assertEqual(s, 200)
402        self.assertTrue(seen.get("busy"))
403        self.assertEqual(seen.get("phase"), "saving the session")
404        self.assertGreater(self.svc.last_request_at, time.time() - 5)
405        self.assertFalse(self.svc.status["busy"])
406        self.assertEqual(self.svc.status["queued"], 0)
407        self.assertEqual(self.svc.unload(idle_for=60), "busy")        # just active: the idle unload waits
408
409    def test_only_slot_zero_and_known_actions(self):
410        self.assertEqual(self.post("/slots/1?action=save", {"filename": "d.bin"})[0], 400)
411        self.assertEqual(self.post("/slots/0?action=erase_all", {"filename": "d.bin"})[0], 400)
412        self.assertEqual(self.engine.proc.sent, [])
413
414    def test_disabled_without_a_slot_save_path(self):
415        saved = self.svc.slot_save_path
416        self.svc.slot_save_path = None
417        try:
418            s, b = self.post("/slots/0?action=save", {"filename": "e.bin"})
419        finally:
420            self.svc.slot_save_path = saved
421        self.assertEqual(s, 501, b)
422
423    def test_refused_with_parallel_requests(self):
424        """#465: batch slots do not hold the FIFO, so a session file is refused before anything reaches the engine."""
425        self.engine.batch = 2
426        try:
427            s, b = self.post("/slots/0?action=save", {"filename": "p.bin"})
428        finally:
429            self.engine.batch = 0
430        self.assertEqual(s, 501, b)
431        self.assertIn("parallel", b["error"]["message"])
432        self.assertEqual(self.engine.proc.sent, [])
433
434    def test_waits_for_a_running_request(self):
435        """A save never interleaves with a generation: it takes the same FIFO."""
436        self.svc.fifo.acquire()
437        out = {}
438        t = threading.Thread(target=lambda: out.update(r=self.post("/slots/0?action=save", {"filename": "f.bin"})))
439        t.start()
440        t.join(0.5)
441        self.assertTrue(t.is_alive())
442        self.assertEqual(self.engine.proc.sent, [])
443        self.svc.fifo.release()
444        t.join(10)
445        self.assertEqual(out["r"][0], 200)
446
447
448if __name__ == "__main__":
449    unittest.main()