okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
76790f277
main
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 4python -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 23slot_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 31def __init__ (self ,engine ): 32self .engine = engine 33self .stdin = self 34self .sent :list [str ]= [] 35 36def write (self ,s ): 37self .sent .append (s ) 38cmd ,_ ,path = s .strip ().partition (" " ) 39script = self .engine .script 40if 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 43def play (): 44for line in script : 45if self .killed : 46return 47if isinstance (line ,float ): 48time .sleep (line ) 49else : 50self .engine .lines .put (line ) 51self .player = threading .Thread (target = play ,daemon = True ) 52self .player .start () 53return 54if cmd == "SAVE" : 55if self .engine .fail : 56self .engine .lines .put ("SERR invalid 0 no complete session to save\n" ) 57else : 58Path (path ).write_bytes (b"x" * 1234 ) 59self .engine .lines .put ("SAVED 62993 1234 401.5\n" ) 60elif cmd == "RESTORE" : 61if not Path (path ).exists ()or self .engine .fail : 62self .engine .lines .put ("SERR invalid 0 session file: saved with another model (model fingerprint differs)\n" ) 63else : 64self .engine .lines .put ("RESTORED 62993 1234 560.2\n" ) 65elif cmd == "DIE" : 66self .engine .lines .put (None ) 67 68def flush (self ): 69pass 70 71def poll (self ): 72return - 9 if self .killed else None 73 74killed = False 75 76def kill (self ): 77self .killed = True 78 79def wait (self ,timeout = None ): 80return - 9 81 82 83class FakeEngine (StrataEngine ): 84def __init__ (self ): 85super ().__init__ ("strata" , ["--max-context" ,"65536" ],lazy = True ) 86self .max_context = 65536 87self .unloaded ,self .ended = False ,False 88self .lines = queue .Queue () 89self .fail = False 90self .script = None 91self .proc = FakeProc (self ) 92 93 94class Slots (unittest .TestCase ): 95@classmethod 96def setUpClass (cls ): 97cls .dir = tempfile .TemporaryDirectory () 98tok = ByteTokenizer () 99cls .engine = FakeEngine () 100cls .svc = Service (cls .engine ,tok ,ChatTemplate (ROOT / "serve/chat_template.jinja" )) 101cls .svc .slot_save_path = cls .dir .name 102cls .httpd = serve (cls .svc ,port = 0 ) 103cls .base = f"http://127.0.0.1: { cls . httpd . server_address [ 1 ] } " 104 105@classmethod 106def tearDownClass (cls ): 107cls .httpd .shutdown () 108cls .httpd .server_close () 109cls .dir .cleanup () 110 111def setUp (self ): 112self .engine .fail = False 113self .engine .script = None 114self .engine .silence_s = 300.0 115self .fresh_engine () 116self .svc .slot_save_path = self .dir .name 117 118def fresh_engine (self ): 119self .engine .ended = False 120old = getattr (self .engine .proc ,"player" ,None ) 121if old is not None :# the previous scripted engine has finished... 122self .engine .proc .killed = True 123old .join (timeout = 5 ) 124while not self .engine .lines .empty ():# ...and left no line for the next exchange 125self .engine .lines .get_nowait () 126self .engine .proc = FakeProc (self .engine ) 127 128def post (self ,path ,body ,headers = None ): 129req = urllib .request .Request (self .base + path ,data = json .dumps (body ).encode (), 130headers = headers or {"Content-Type" :"application/json" }) 131try : 132with urllib .request .urlopen (req ,timeout = 30 )as r : 133return r .status ,json .loads (r .read ()) 134except urllib .error .HTTPError as e : 135with e : 136return e .code ,json .loads (e .read ()) 137 138def test_a_foreign_page_or_a_form_never_reaches_the_engine (self ): 139for action in ("save" ,"restore" ): 140for 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 )): 143s ,b = self .post (f"/slots/0?action= { action } " , {"filename" :"x.bin" },headers ) 144self .assertEqual (s ,code , (action ,headers ,b )) 145self .assertEqual (self .engine .proc .sent , []) 146self .assertFalse (Path (self .dir .name ,"x.bin" ).exists ()) 147 148def test_save_writes_into_the_slot_save_path (self ): 149s ,b = self .post ("/slots/0?action=save" , {"filename" :"a.bin" }) 150self .assertEqual (s ,200 ,b ) 151self .assertEqual (self .engine .proc .sent , [f"SAVE { Path ( self . dir . name , 'a.bin' ) } \n" ]) 152self .assertEqual ((b ["id_slot" ],b ["filename" ],b ["n_saved" ],b ["n_written" ]), (0 ,"a.bin" ,62993 ,1234 )) 153self .assertAlmostEqual (b ["timings" ]["save_ms" ],401.5 ) 154 155def test_restore_answers_like_llama_server (self ): 156self .post ("/slots/0?action=save" , {"filename" :"b.bin" }) 157s ,b = self .post ("/slots/0?action=restore" , {"filename" :"b.bin" }) 158self .assertEqual (s ,200 ,b ) 159self .assertEqual ((b ["id_slot" ],b ["filename" ],b ["n_restored" ],b ["n_read" ]), (0 ,"b.bin" ,62993 ,1234 )) 160self .assertAlmostEqual (b ["timings" ]["restore_ms" ],560.2 ) 161 162def test_refused_file_is_an_error_not_a_success (self ): 163self .post ("/slots/0?action=save" , {"filename" :"c.bin" }) 164self .engine .fail = True 165s ,b = self .post ("/slots/0?action=restore" , {"filename" :"c.bin" }) 166self .assertEqual (s ,400 ,b ) 167self .assertIn ("fingerprint" ,b ["error" ]["message" ]) 168 169def test_missing_file_is_not_found (self ): 170s ,b = self .post ("/slots/0?action=restore" , {"filename" :"never-saved.bin" }) 171self .assertEqual (s ,404 ,b ) 172self .assertEqual (self .engine .proc .sent , []) 173 174def test_filename_cannot_leave_the_directory (self ): 175for 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" ]): 180s ,b = self .post ("/slots/0?action=save" , {"filename" :bad }) 181self .assertEqual (s ,400 , (bad ,b )) 182self .assertEqual (self .engine .proc .sent , []) 183 184def test_ordinary_names_are_accepted (self ): 185for good in ("a.bin" ,"chat-2026-10-03.bin" ,"a.bin.tmp" ,"consul.bin" ,"nullable" ,"caf\u00e9.bin" , 186"\u4f1a\u8bdd.bin" ,"x" * 200 ): 187self .assertIsNone (slot_filename_problem (good ),good ) 188 189def test_relative_save_dir_becomes_absolute (self ): 190with tempfile .TemporaryDirectory ()as base : 191got = slot_save_dir ("sessions" ,base ) 192self .assertEqual (got ,os .path .join (base ,"sessions" )) 193self .assertTrue (os .path .isabs (got )and os .path .isdir (got )) 194if os .name != "nt" : 195self .assertEqual (os .stat (got ).st_mode & 0o777 ,0o700 ) 196self .assertEqual (slot_save_dir (got ,"/elsewhere" ),got )# an absolute path stays as it is 197cwd = os .getcwd () 198try : 199os .chdir (base ) 200self .assertEqual (os .path .realpath (slot_save_dir ("rel" )),os .path .realpath (os .path .join (base ,"rel" ))) 201finally : 202os .chdir (cwd ) 203for bad in ("" ," " ,None ,3 ,"a\nb" ): 204with self .assertRaises (ValueError ): 205slot_save_dir (bad ,base ) 206 207def test_engine_gets_an_absolute_path_on_one_line (self ): 208self .post ("/slots/0?action=save" , {"filename" :"abs.bin" }) 209line = self .engine .proc .sent [0 ] 210self .assertTrue (line .endswith ("\n" )and line .count ("\n" )== 1 ) 211self .assertTrue (os .path .isabs (line [len ("SAVE " ):- 1 ])) 212 213def 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.""" 215if os .name == "nt" : 216self .skipTest ("symlinks need privileges on Windows" ) 217target = Path (self .dir .name ,"real.bin" ) 218target .write_bytes (b"x" ) 219link = Path (self .dir .name ,"link.bin" ) 220link .symlink_to (target ) 221dangling = Path (self .dir .name ,"dangling.bin" ) 222dangling .symlink_to (Path (self .dir .name ,"nothing" )) 223self .engine .script = ["SERR invalid 0 session file: x: a symbolic link, not a file\n" ] 224for name in ("link.bin" ,"dangling.bin" ): 225s ,b = self .post ("/slots/0?action=restore" , {"filename" :name }) 226self .assertEqual (s ,400 ,b ) 227self .assertIn ("symbolic link" ,b ["error" ]["message" ]) 228 229def test_progress_lines_keep_a_long_save_alive (self ): 230self .engine .silence_s = 0.3 231self .engine .script = [0.2 ,"SESSION 268435456 1198691396\n" ,0.2 ,"SESSION 536870912 1198691396\n" ,0.2 , 232"SAVED 63000 1198691396 2000.0\n" ] 233t0 = time .monotonic () 234s ,b = self .post ("/slots/0?action=save" , {"filename" :"long.bin" }) 235self .assertEqual (s ,200 ,b ) 236self .assertGreater (time .monotonic ()- t0 ,0.5 )# the lines arrived during the wait, past its 0.3 s 237self .assertEqual (b ["n_written" ],1198691396 ) 238self .assertFalse (self .engine .ended ) 239 240def 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).""" 242self .engine .silence_s = 0.3 243self .engine .script = ["SESSION 0 56834\n" ,0.2 ,"SESSION 56834 56834\n" ,0.2 ,"SAVED 120 56834 410.0\n" ] 244s ,b = self .post ("/slots/0?action=save" , {"filename" :"small.bin" }) 245self .assertEqual (s ,200 ,b ) 246self .assertEqual (b ["n_written" ],56834 ) 247self .assertFalse (self .engine .ended ) 248 249def 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.""" 251self .engine .silence_s = 0.3 252self .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" ] 254t0 = time .monotonic () 255s ,b = self .post ("/slots/0?action=save" , {"filename" :"flush.bin" }) 256self .assertEqual (s ,200 ,b ) 257self .assertGreater (time .monotonic ()- t0 ,1.3 )# longer than the silence limit, twice 258self .assertFalse (self .engine .ended ) 259Path (self .dir .name ,"flush.bin" ).write_bytes (b"x" )# the scripted engine wrote nothing; restore needs a file 260self .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" ] 262s ,b = self .post ("/slots/0?action=restore" , {"filename" :"flush.bin" }) 263self .assertEqual (s ,200 ,b ) 264 265def 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.""" 267self .engine .silence_s = 0.3 268self .engine .script = ["SWAIT flush 1\n" ]# then nothing 269t0 = time .monotonic () 270s ,b = self .post ("/slots/0?action=save" , {"filename" :"stuck.bin" }) 271took = time .monotonic ()- t0 272self .assertEqual (s ,500 ,b ) 273self .assertGreater (took ,0.9 ) 274self .assertLess (took ,5 ) 275self .assertIn ("blocking step allowed 1 s" ,b ["error" ]["message" ]) 276self .assertTrue (self .engine .ended and self .engine .proc .killed ) 277 278def test_progress_ends_the_allowance (self ): 279"""B: after a SESSION line the ordinary silence limit applies again (the allowance was for one step).""" 280self .engine .silence_s = 0.3 281self .engine .script = ["SWAIT transfer 2\n" ,"SESSION 1 2\n" ,0.8 ,"SAVED 1 2 1.0\n" ] 282s ,b = self .post ("/slots/0?action=save" , {"filename" :"reset.bin" }) 283self .assertEqual (s ,500 ,b ) 284self .assertIn ("said nothing" ,b ["error" ]["message" ]) 285self .assertNotIn ("blocking step" ,b ["error" ]["message" ]) 286self .assertTrue (self .engine .ended ) 287 288def test_malformed_allowances_end_the_engine (self ): 289for 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" ]): 291with self .subTest (script = script ): 292self .fresh_engine () 293self .engine .script = script + [0.1 ,"SAVED 1 2 1.0\n" ] 294s ,b = self .post ("/slots/0?action=save" , {"filename" :"bad.bin" }) 295self .assertEqual (s ,500 ,b ) 296self .assertTrue (self .engine .ended and self .engine .proc .killed ) 297 298def test_a_silent_engine_is_ended_not_waited_for (self ): 299self .engine .silence_s = 0.3 300self .engine .script = []# the engine never answers 301t0 = time .monotonic () 302s ,b = self .post ("/slots/0?action=save" , {"filename" :"silent.bin" }) 303self .assertEqual (s ,500 ,b ) 304self .assertLess (time .monotonic ()- t0 ,5 ) 305self .assertIn ("said nothing" ,b ["error" ]["message" ]) 306self .assertTrue (self .engine .ended and self .engine .proc .killed ) 307self .assertTrue (self .svc .fifo .acquire (blocking = False ))# the FIFO was released 308self .svc .fifo .release () 309self .assertEqual (self .svc .status ["queued" ],0 ) 310self .assertFalse (self .svc .status ["busy" ]) 311 312def test_engine_death_is_a_server_error (self ): 313self .engine .script = [None ] 314s ,b = self .post ("/slots/0?action=save" , {"filename" :"dead.bin" }) 315self .assertEqual (s ,500 ,b ) 316 317def test_failed_restore_transfer_is_a_server_error (self ): 318Path (self .dir .name ,"t.bin" ).write_bytes (b"x" ) 319self .engine .script = ["SESSION 268435456 1198691396\n" , 320"FATAL restoring the session file failed after the device state was changed: copy\n" ] 321s ,b = self .post ("/slots/0?action=restore" , {"filename" :"t.bin" }) 322self .assertEqual (s ,500 ,b ) 323self .assertIn ("device state" ,b ["error" ]["message" ]) 324 325def test_malformed_or_mismatched_reply_is_a_server_error (self ): 326for script in (["RESTORED 1 2 3\n" ], ["SAVED x y z\n" ], ["SAVED 1 2\n" ], ["T 5\n" ]): 327self .engine .script = script 328self .engine .ended = False 329self .engine .proc = FakeProc (self .engine ) 330s ,b = self .post ("/slots/0?action=save" , {"filename" :"m.bin" }) 331self .assertEqual (s ,500 , (script ,b )) 332self .assertTrue (self .engine .ended ,script )# out of step: the engine is ended 333 334def 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.""" 336for 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" ]): 341self .engine .script = script 342self .engine .ended = False 343self .engine .proc = FakeProc (self .engine ) 344s ,b = self .post ("/slots/0?action=save" , {"filename" :"p.bin" }) 345self .assertEqual (s ,500 , (script ,b )) 346self .assertTrue (self .engine .ended and self .engine .proc .killed ,script ) 347json .dumps (b ,allow_nan = False )# standard JSON 348 349def test_log_lines_are_not_answers (self ): 350self .engine .script = ["INFO something\n" ,"SAVED 1 2 3.0\n" ] 351s ,b = self .post ("/slots/0?action=save" , {"filename" :"i.bin" }) 352self .assertEqual (s ,200 ,b ) 353self .assertFalse (self .engine .ended ) 354 355def test_typed_refusals_have_their_own_codes (self ): 356"""R5: the engine's category decides the status, never the words of the message.""" 357cases = [("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 )] 361for kind ,msg ,code in cases : 362self .engine .script = [f"SERR { kind } 0 { msg } \n" ] 363s ,b = self .post ("/slots/0?action=save" , {"filename" :"k.bin" }) 364self .assertEqual (s ,code , (kind ,msg ,b )) 365self .assertEqual (b ["error" ]["kind" ],kind ) 366self .assertEqual (b ["error" ]["message" ],msg ) 367self .assertNotIn ("published" ,b ["error" ]) 368self .assertFalse (self .engine .ended )# a refusal keeps the engine 369 370def 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.""" 372self .engine .script = ["SERR io 1 flushing the directory: Input/output error (the new file has already " 373"replaced the old one)\n" ] 374s ,b = self .post ("/slots/0?action=save" , {"filename" :"pub.bin" }) 375self .assertEqual (s ,500 ,b ) 376self .assertTrue (b ["error" ]["published" ]) 377self .assertIn ("replaced" ,b ["error" ]["message" ]) 378 379def test_disk_and_ram_refusals_have_their_own_codes (self ): 380self .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" ] 382self .assertEqual (self .post ("/slots/0?action=save" , {"filename" :"d.bin" })[0 ],507 ) 383Path (self .dir .name ,"r.bin" ).write_bytes (b"x" ) 384self .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" ] 386self .assertEqual (self .post ("/slots/0?action=restore" , {"filename" :"r.bin" })[0 ],503 ) 387 388def test_slot_work_counts_as_activity_and_shows_in_status (self ): 389seen = {} 390 391def during (): 392time .sleep (0.15 ) 393with self .svc .status_lock : 394seen .update (self .svc .status ) 395self .engine .script = [0.4 ,"SAVED 1 2 3.0\n" ] 396self .svc .last_request_at = 0 397t = threading .Thread (target = during ) 398t .start () 399s ,_ = self .post ("/slots/0?action=save" , {"filename" :"act.bin" }) 400t .join () 401self .assertEqual (s ,200 ) 402self .assertTrue (seen .get ("busy" )) 403self .assertEqual (seen .get ("phase" ),"saving the session" ) 404self .assertGreater (self .svc .last_request_at ,time .time ()- 5 ) 405self .assertFalse (self .svc .status ["busy" ]) 406self .assertEqual (self .svc .status ["queued" ],0 ) 407self .assertEqual (self .svc .unload (idle_for = 60 ),"busy" )# just active: the idle unload waits 408 409def test_only_slot_zero_and_known_actions (self ): 410self .assertEqual (self .post ("/slots/1?action=save" , {"filename" :"d.bin" })[0 ],400 ) 411self .assertEqual (self .post ("/slots/0?action=erase_all" , {"filename" :"d.bin" })[0 ],400 ) 412self .assertEqual (self .engine .proc .sent , []) 413 414def test_disabled_without_a_slot_save_path (self ): 415saved = self .svc .slot_save_path 416self .svc .slot_save_path = None 417try : 418s ,b = self .post ("/slots/0?action=save" , {"filename" :"e.bin" }) 419finally : 420self .svc .slot_save_path = saved 421self .assertEqual (s ,501 ,b ) 422 423def 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.""" 425self .engine .batch = 2 426try : 427s ,b = self .post ("/slots/0?action=save" , {"filename" :"p.bin" }) 428finally : 429self .engine .batch = 0 430self .assertEqual (s ,501 ,b ) 431self .assertIn ("parallel" ,b ["error" ]["message" ]) 432self .assertEqual (self .engine .proc .sent , []) 433 434def test_waits_for_a_running_request (self ): 435"""A save never interleaves with a generation: it takes the same FIFO.""" 436self .svc .fifo .acquire () 437out = {} 438t = threading .Thread (target = lambda :out .update (r = self .post ("/slots/0?action=save" , {"filename" :"f.bin" }))) 439t .start () 440t .join (0.5 ) 441self .assertTrue (t .is_alive ()) 442self .assertEqual (self .engine .proc .sent , []) 443self .svc .fifo .release () 444t .join (10 ) 445self .assertEqual (out ["r" ][0 ],200 ) 446 447 448if __name__ == "__main__" : 449unittest .main ()