okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
326e39118
main
1"""Model discovery, on-demand loading and safe unloading over the actual HTTP API.""" 2import json 3import io 4import os 5import subprocess 6import time 7import unittest 8import urllib .error 9import urllib .request 10from pathlib import Path 11from unittest import mock 12 13from serve .frontend import ChatTemplate 14from serve .server import ByteTokenizer ,EngineDied ,EngineStuck ,MockEngine ,Service ,StrataEngine ,serve 15 16 17class ResidentEngine (StrataEngine ): 18def __init__ (self ,tok ): 19self .reply = MockEngine (tok ,"Hello." ,max_context = 4096 ) 20self .max_context ,self .info ,self .last = 4096 , {}, {} 21self .loaded ,self .starts ,self .closes = False ,0 ,0 22self .unloaded = True 23self .progress = None 24 25def alive (self ): 26return self .loaded 27 28def exit_code (self ): 29return None 30 31def restart (self ): 32self .loaded = True 33self .starts += 1 34self .unloaded = False 35 36def close (self ): 37self .loaded = False 38self .closes += 1 39 40def unload (self ): 41self .close () 42self .unloaded = True 43 44def generate (self ,* args ,** kwargs ): 45yield from self .reply .generate (* args ,** kwargs ) 46 47 48class Lifecycle (unittest .TestCase ): 49def test_close_cleans_up_after_a_broken_stdin_pipe (self ): 50for running in (False ,True ): 51with self .subTest (running = running ): 52engine = StrataEngine ("missing-executable" , [],lazy = True ) 53read_fd ,write_fd = os .pipe () 54stdin = os .fdopen (write_fd ,"w" ) 55self .addCleanup (stdin .close ) 56os .close (read_fd )# the engine's end of the pipe is already gone 57stdin .write ("pending" )# buffered: flush() and close() will hit the broken pipe 58proc = mock .Mock (stdin = stdin ,stdout = io .StringIO ()) 59self .addCleanup (proc .stdout .close ) 60proc .poll .side_effect = [None if running else 0 ,0 ] 61engine .proc ,engine .pump ,engine .log = proc ,mock .Mock (),io .StringIO () 62self .addCleanup (engine .log .close ) 63engine .ended ,engine .progress ,engine .last = False , (1 ,2 ), {"generated" :1 } 64 65engine .close () 66 67self .assertTrue (stdin .closed ) 68self .assertTrue (proc .stdout .closed ) 69self .assertTrue (engine .log .closed ) 70engine .pump .join .assert_called_once_with (timeout = 2 ) 71self .assertIsNone (engine .proc ) 72self .assertTrue (engine .ended ) 73self .assertIsNone (engine .progress ) 74self .assertEqual (engine .last , {}) 75if running : 76proc .terminate .assert_called_once () 77proc .wait .assert_called_once_with (timeout = 5 ) 78else : 79proc .terminate .assert_not_called () 80proc .wait .assert_not_called () 81proc .kill .assert_not_called () 82engine .close ()# repeated cleanup is harmless 83 84def test_close_sends_eof_before_waiting_for_windows_reader (self ): 85engine = StrataEngine ("missing-executable" , [],lazy = True ) 86proc = mock .Mock () 87proc .stdin ,proc .stdout = io .StringIO (),io .StringIO () 88proc .poll .side_effect = [None ,0 ] 89proc .wait .side_effect = lambda ** kwargs :self .assertTrue (proc .stdin .closed ) 90engine .proc = proc 91engine .close () 92self .assertIsNone (engine .proc ) 93proc .kill .assert_not_called () 94 95def test_close_does_not_forget_a_process_still_exiting (self ): 96engine = StrataEngine ("missing-executable" , [],lazy = True ) 97proc = mock .Mock () 98proc .stdin ,proc .stdout = io .StringIO (),io .StringIO () 99proc .poll .return_value = None 100proc .wait .side_effect = subprocess .TimeoutExpired ("engine" ,2 ) 101engine .proc = proc 102with self .assertRaisesRegex (EngineStuck ,"still releasing" ): 103engine .close () 104self .assertIs (engine .proc ,proc ) 105proc .terminate .assert_called_once () 106proc .kill .assert_called_once () 107 108def test_close_terminates_before_it_kills (self ): 109# an engine that does not end on QUIT is terminated first (as the unload always did); kill is the last resort 110engine = StrataEngine ("missing-executable" , [],lazy = True ) 111proc = mock .Mock () 112proc .stdin ,proc .stdout = io .StringIO (),io .StringIO () 113proc .poll .side_effect = [None ,0 ] 114proc .wait .side_effect = [subprocess .TimeoutExpired ("engine" ,20 ),0 ] 115engine .proc = proc 116engine .close () 117proc .terminate .assert_called_once () 118proc .kill .assert_not_called () 119self .assertIsNone (engine .proc ) 120 121def test_native_lazy_constructor_does_not_start_a_process (self ): 122engine = StrataEngine ("missing-executable" , ["--max-context" ,"16384" ],lazy = True ) 123self .assertFalse (engine .alive ()) 124self .assertEqual (engine .max_context ,16384 ) 125self .assertIsNone (engine .exit_code ()) 126engine .close () 127 128def setUp (self ): 129tok = ByteTokenizer () 130self .engine = ResidentEngine (tok ) 131self .svc = Service (self .engine ,tok ,ChatTemplate (Path (__file__ ).parent / "chat_template.jinja" )) 132self .httpd = serve (self .svc ,port = 0 ) 133self .base = f"http://127.0.0.1: { self . httpd . server_address [ 1 ] } " 134 135def tearDown (self ): 136self .httpd .shutdown () 137self .httpd .server_close () 138 139def request (self ,path ,body = None ,headers = None ): 140req = urllib .request .Request (self .base + path ,data = json .dumps (body ).encode ()if body is not None else None , 141headers = {"Content-Type" :"application/json" ,** (headers or {})}) 142try : 143response = urllib .request .urlopen (req ,timeout = 10 ) 144except urllib .error .HTTPError as error : 145response = error 146with response : 147data = response .read ().decode () 148return response .status ,data if "event-stream" in response .headers .get ("Content-Type" ,"" )else json .loads (data ) 149 150def test_discover_chat_unload_and_stream_reload (self ): 151self .assertEqual (self .request ("/api/health" )[1 ]["service" ],"strata" ) 152self .assertFalse (self .request ("/v1/status" )[1 ]["loaded" ]) 153self .assertEqual (self .request ("/v1/models" )[1 ]["data" ][0 ]["status" ]["value" ],"unloaded" ) 154self .assertTrue (self .request ("/props" )[1 ]["models_autoload" ]) 155self .assertEqual (self .engine .starts ,0 ) 156chat = {"messages" : [{"role" :"user" ,"content" :"Hello" }],"max_tokens" :32 ,"reasoning_effort" :"none" } 157for _ in range (2 ): 158code ,answer = self .request ("/v1/chat/completions" ,chat ) 159self .assertEqual (code ,200 ) 160self .assertEqual (answer ["choices" ][0 ]["message" ]["content" ],"Hello." ) 161self .assertEqual (self .engine .starts ,1 ) 162self .assertFalse (self .request ("/v1/unload" , {})[1 ]["loaded" ]) 163code ,stream = self .request ("/v1/chat/completions" , {** chat ,"stream" :True }) 164self .assertEqual (code ,200 ) 165self .assertIn ("data: [DONE]" ,stream ) 166self .assertEqual (self .engine .starts ,2 ) 167 168def test_busy_auth_and_foreign_origin_cannot_unload (self ): 169self .engine .loaded = True 170with self .svc .fifo : 171self .assertEqual (self .request ("/v1/unload" , {})[0 ],409 ) 172self .svc .api_key = "local-secret" 173self .assertEqual (self .request ("/v1/unload" , {})[0 ],401 ) 174self .assertEqual (self .request ("/v1/unload" , {}, {"Authorization" :"Bearer local-secret" , 175"Origin" :"https://other.example" })[0 ],403 ) 176self .assertEqual (self .engine .closes ,0 ) 177self .assertTrue (self .engine .loaded ) 178self .assertEqual (self .request ("/v1/unload" , {}, {"Authorization" :"Bearer local-secret" })[0 ],200 ) 179 180def test_an_engine_that_died_on_load_is_reported_as_such (self ): 181# EngineDied is a RuntimeError: it keeps its own answer ("the next request restarts it") 182def died (): 183raise EngineDied ("the engine ended while it started" ) 184self .engine .restart = died 185code ,body = self .request ("/v1/chat/completions" , {"messages" : [{"role" :"user" ,"content" :"Hello" }]}) 186self .assertEqual (code ,503 ) 187self .assertIn ("the next request restarts it" ,body ["error" ]["message" ]) 188 189def test_explicit_load_and_model_matching (self ): 190self .assertEqual (self .request ("/v1/load" , {"model" :"other-model" })[0 ],404 ) 191self .assertEqual (self .engine .starts ,0 ) 192before = time .time () 193code ,status = self .request ("/v1/load" , {"model" :self .svc .model }) 194self .assertEqual (code ,200 ) 195self .assertTrue (status ["loaded" ]) 196self .assertEqual (self .engine .starts ,1 ) 197self .assertGreaterEqual (self .svc .last_request_at ,before ) 198self .svc .status ["queued" ]= 1 199self .assertEqual (self .request ("/v1/load" , {})[0 ],409 ) 200self .assertEqual (self .request ("/v1/unload" , {})[0 ],409 ) 201self .assertEqual (self .engine .closes ,0 ) 202self .assertEqual (self .request ("/v1/load" , {}, {"Content-Type" :"text/plain" })[0 ],415 ) 203 204 205if __name__ == "__main__" : 206unittest .main ()