okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
b111d1e83
main
1"""#1527: the READY-read timeout (#1317) ends the engine, and the request that was loading it must end too - 2a 503 with the reason, not a connection that never answers (or a misleading 400).""" 3import os 4from pathlib import Path 5import sys 6import tempfile 7import threading 8import time 9import unittest 10import json 11import urllib .request 12from unittest import mock 13sys .path .insert (0 ,str (Path (__file__ ).resolve ().parents [1 ])) 14import serve .server as server # noqa: E402 15from serve .server import StrataEngine ,Service ,ChatTemplate ,ByteTokenizer ,serve # noqa: E402 16 17# never prints READY: the READY read times out and the process is killed 18SILENT = r''' 19import time 20time.sleep(3600) 21''' 22 23# first run answers READY + one request; after --hang is touched a restart stays silent forever 24HANG_ON_RESTART = r''' 25import sys, time 26from pathlib import Path 27hang = Path(sys.argv[sys.argv.index('--hang') + 1]) 28if hang.exists(): 29time.sleep(3600) 30print('READY 4096 stop', flush=True) 31for line in sys.stdin: 32if line.startswith('QUIT'): 33break 34if line.startswith(('GEN', 'BGEN')): 35print('T 90\nDONE 1 1 0 1 stop', flush=True) 36''' 37 38 39@ unittest . skipIf ( os . name == "nt" , "the .cmd wrapper keeps the pipe open after the kill (only the wrapper dies), so the " 40"close of its stdout waits for the sleeping child; a real engine is one process" ) 41class ReadyTimeout (unittest .TestCase ): 42def setUp (self ): 43self .tmp = tempfile .TemporaryDirectory ();self .addCleanup (self .tmp .cleanup ) 44self .root = Path (self .tmp .name ) 45self ._patchers = [mock .patch .object (server ,'ENGINE_READY_S' ,0.5 ), 46mock .patch .object (StrataEngine ,'RESTART_RETRY_S' ,0.0 )] 47for p in self ._patchers : 48p .start ();self .addCleanup (p .stop ) 49 50def make_script (self ,name ,code ): 51py = self .root / (name + '.py' ) 52if os .name == 'nt' : 53py .write_text (code );script = self .root / (name + '.cmd' ) 54script .write_text (f'@" { sys . executable } " " { py } " %*\r\n' ) 55else : 56script = py ;py .write_text ('#!' + sys .executable + '\n' + code );py .chmod (0o700 ) 57return str (script ) 58 59def service (self ,script ,extra_args = ()): 60eng = StrataEngine (script ,list (extra_args ),lazy = True ) 61self .addCleanup (eng .close ) 62return Service (eng ,ByteTokenizer (),ChatTemplate (Path (__file__ ).parent / 'chat_template.jinja' )) 63 64def post (self ,base ): 65body = {'messages' : [{'role' :'user' ,'content' :'hi' }],'max_tokens' :8 } 66req = urllib .request .Request (base + '/v1/chat/completions' ,data = json .dumps (body ).encode (), 67headers = {'Content-Type' :'application/json' }) 68with urllib .request .urlopen (req ,timeout = 30 )as r : 69return r .status ,r .read () 70 71def assert503 (self ,base ): 72t0 = time .monotonic () 73try : 74self .post (base ) 75self .fail ('a request on an engine that never reports READY must not succeed' ) 76except urllib .error .HTTPError as e : 77self .assertEqual (e .code ,503 ) 78body = e .read ().decode () 79self .assertIn ('did not report READY' ,body ) 80self .assertIn ('next request restarts it' ,body ) 81self .assertLess (time .monotonic ()- t0 ,60 ) 82 83def test_ready_timeout_on_lazy_load_answers_the_request (self ): 84# lazy start: restart()'s own bookkeeping must not crash on the missing slot_cv either (#1527) 85svc = self .service (self .make_script ('silent' ,SILENT )) 86httpd = serve (svc ,port = 0 ) 87self .addCleanup (httpd .shutdown );self .addCleanup (httpd .server_close ) 88base = f'http://127.0.0.1: { httpd . server_address [ 1 ] } ' 89self .assert503 (base ) 90self .assertFalse (svc .engine .starting ) 91 92def test_ready_timeout_on_restart_answers_the_request (self ): 93# the reporter's case: the engine had answered once, then a restart hangs on the READY read 94hang = self .root / 'hang' 95svc = self .service (self .make_script ('hang_on_restart' ,HANG_ON_RESTART ), ('--hang' ,str (hang ))) 96httpd = serve (svc ,port = 0 ) 97self .addCleanup (httpd .shutdown );self .addCleanup (httpd .server_close ) 98base = f'http://127.0.0.1: { httpd . server_address [ 1 ] } ' 99status ,_ = self .post (base )# first request: the engine works 100self .assertEqual (status ,200 ) 101svc .engine .proc .kill ();svc .engine .proc .wait (10 )# it dies between requests 102hang .touch ()# and its restart never reports READY 103self .assert503 (base ) 104self .assertFalse (svc .engine .starting ) 105 106 107class SpawnFailure (unittest .TestCase ): 108"""The engine program cannot be started at all (missing, not executable, or blocked by Windows - #735): the 109request that was loading it gets a 503 with the reason, not a dropped connection.""" 110BODIES = {'/v1/chat/completions' : {'messages' : [{'role' :'user' ,'content' :'hi' }],'max_tokens' :8 }, 111'/v1/messages' : {'model' :'strata' ,'max_tokens' :8 ,'messages' : [{'role' :'user' ,'content' :'hi' }]}, 112'/v1/responses' : {'input' :'hi' ,'max_output_tokens' :8 }} 113 114def test_missing_engine_answers_503_and_leaves_nothing_running (self ): 115tmp = tempfile .TemporaryDirectory ();self .addCleanup (tmp .cleanup ) 116root = Path (tmp .name ) 117eng = StrataEngine (str (root / 'no-such-engine' ), [],log = str (root / 'engine.log' ),lazy = True ) 118svc = Service (eng ,ByteTokenizer (),ChatTemplate (Path (__file__ ).parent / 'chat_template.jinja' )) 119httpd = serve (svc ,port = 0 ) 120self .addCleanup (httpd .shutdown );self .addCleanup (httpd .server_close ) 121base = f'http://127.0.0.1: { httpd . server_address [ 1 ] } ' 122before = set (threading .enumerate ()) 123cases = list (self .BODIES .items ())+ [('/v1/chat/completions' , 124 {** self .BODIES ['/v1/chat/completions' ],'stream' :True })] 125for path ,body in cases : 126with self .subTest (path = path ,stream = body .get ('stream' ,False )): 127req = urllib .request .Request (base + path ,data = json .dumps (body ).encode (), 128headers = {'Content-Type' :'application/json' }) 129with self .assertRaises (urllib .error .HTTPError )as cm : 130urllib .request .urlopen (req ,timeout = 30 ) 131self .assertEqual (cm .exception .code ,503 ) 132self .assertIn ('the engine could not be started' ,cm .exception .read ().decode ()) 133self .assertTrue (eng .log .closed )# our handle on the engine log is given back 134# the start narrator ("still starting ... please wait") ends with the failed start 135deadline = time .monotonic ()+ 5 136while (narrators := [t for t in set (threading .enumerate ())- before if '(narrate_start)' in t .name ]) \ 137and time .monotonic ()< deadline : 138time .sleep (0.1 ) 139self .assertEqual (narrators , []) 140 141 142if __name__ == '__main__' : 143unittest .main ()