okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
538acd098
main
1"""Elastic encoder failures reach clients, can be retried, and do not prevent recovery.""" 2import json 3from pathlib import Path 4import sys 5import tempfile 6import unittest 7import urllib .error 8import urllib .request 9 10from serve .frontend import ChatTemplate 11from serve .server import ByteTokenizer ,Service ,Vision ,serve 12from serve .test_vision_elastic import ElasticVision 13from serve .test_vram import VramEngine 14 15 16class EncoderFailureHTTP (unittest .TestCase ): 17def setUp (self ): 18tmp = tempfile .TemporaryDirectory () 19self .addCleanup (tmp .cleanup ) 20tok = ByteTokenizer () 21self .engine = VramEngine (tok ) 22self .engine .loaded = True 23self .engine .elastic = False # as on a layer split: the cache cannot make room 24self .vision = ElasticVision (tmp .name ) 25self .svc = Service (self .engine ,tok ,ChatTemplate (Path (__file__ ).parent / 'chat_template.jinja' ), 26vision = self .vision ) 27httpd = serve (self .svc ,port = 0 ) 28self .addCleanup (httpd .server_close ) 29self .addCleanup (httpd .shutdown ) 30self .addCleanup (self .drop_embeddings ) 31self .base = f'http://127.0.0.1: { httpd . server_address [ 1 ] } ' 32self .attempts = 0 33self .original_restart = self .vision .restart 34 35def drop_embeddings (self ): 36path = getattr (getattr (self .svc ,'embeddings' ,None ),'path' ,None ) 37if path is not None : 38path .unlink (missing_ok = True ) 39 40def post (self ,path ,body ): 41req = urllib .request .Request (self .base + path ,json .dumps (body ).encode (), 42 {'Content-Type' :'application/json' }) 43return urllib .request .urlopen (req ,timeout = 10 ) 44 45@staticmethod 46def chat_picture (): 47return {'model' :'m' ,'max_tokens' :8 ,'messages' : [{'role' :'user' ,'content' : [ 48 {'type' :'image_url' ,'image_url' : {'url' :'data:image/png;base64,eA==' }}]}]} 49 50def fail_with (self ,error_type ): 51def fail (): 52self .attempts += 1 53raise error_type ('synthetic encoder startup failure' ) 54self .vision .restart = fail 55 56def assert_503 (self ,path ,body ): 57with self .assertRaises (urllib .error .HTTPError )as got : 58self .post (path ,body ) 59with got .exception as response : 60self .assertEqual (response .code ,503 ) 61payload = json .load (response ) 62self .assertIn ('synthetic encoder startup failure' ,payload ['error' ]['message' ]) 63 64def test_start_failure_and_retry_on_all_three_apis (self ): 65cases = [ 66 ('/v1/chat/completions' ,self .chat_picture ()), 67 ('/v1/messages' , {'model' :'m' ,'max_tokens' :8 ,'messages' : [{'role' :'user' ,'content' : [ 68 {'type' :'image' ,'source' : {'type' :'base64' ,'media_type' :'image/png' ,'data' :'eA==' }}]}]}), 69 ('/v1/responses' , {'model' :'m' ,'max_output_tokens' :8 ,'input' : [{'role' :'user' ,'content' : [ 70 {'type' :'input_image' ,'image_url' :'data:image/png;base64,eA==' }]}]}), 71 ] 72for error_type in (RuntimeError ,OSError ): 73self .fail_with (error_type ) 74for path ,body in cases : 75for stream in (False ,True ): 76for retry in range (2 ): 77with self .subTest (error = error_type .__name__ ,path = path ,stream = stream ,retry = retry ): 78before = self .attempts 79self .assert_503 (path , {** body ,'stream' :stream }) 80self .assertEqual (self .attempts ,before + 1 ) 81 82def test_text_requests_and_image_recovery_after_a_failed_start (self ): 83self .fail_with (RuntimeError ) 84text = {'model' :'m' ,'max_tokens' :8 ,'messages' : [{'role' :'user' ,'content' :'hi' }]} 85with self .post ('/v1/chat/completions' ,text )as response : 86self .assertEqual (response .status ,200 ) 87response .read () 88self .assertEqual (self .attempts ,0 ) 89self .assert_503 ('/v1/chat/completions' ,self .chat_picture ()) 90self .assertEqual (self .attempts ,1 ) 91self .vision .restart = self .original_restart 92with self .post ('/v1/chat/completions' ,self .chat_picture ())as response : 93self .assertEqual (response .status ,200 ) 94response .read () 95self .assertEqual (self .vision .starts ,1 ) 96with self .post ('/v1/chat/completions' ,text )as response : 97self .assertEqual (response .status ,200 ) 98response .read () 99self .assertEqual (self .vision .starts ,1 ) 100 101@ unittest . skipUnless ( sys . platform . startswith ( 'linux' ), 'child reaping is checked through /proc' ) 102def test_real_encoder_failure_retries_and_reaps_each_child (self ): 103with tempfile .TemporaryDirectory ()as directory : 104started = Path (directory )/ 'started-pids' 105executable = Path (directory )/ 'encoder-exits' 106executable .write_text ( 107'#!' + sys .executable + '\nimport os\n' 108'with open(' + repr (str (started ))+ ', "a") as output:\n' 109' output.write(str(os.getpid()) + "\\n")\n' 110'raise SystemExit(71)\n' ) 111executable .chmod (0o700 ) 112vision = Vision ({'exe' :str (executable ),'mmproj' :'unused' ,'model' :'unused' , 113'elastic' :True },lazy = True ) 114self .addCleanup (vision .unload ) 115self .svc .vision = vision 116cases = [ 117 ('/v1/chat/completions' ,self .chat_picture ()), 118 ('/v1/messages' , {'model' :'m' ,'max_tokens' :8 ,'messages' : [{'role' :'user' ,'content' : [ 119 {'type' :'image' ,'source' : {'type' :'base64' ,'media_type' :'image/png' ,'data' :'eA==' }}]}]}), 120 ('/v1/responses' , {'model' :'m' ,'max_output_tokens' :8 ,'input' : [{'role' :'user' ,'content' : [ 121 {'type' :'input_image' ,'image_url' :'data:image/png;base64,eA==' }]}]}), 122 ] 123for path ,body in cases : 124for stream in (False ,True ): 125for retry in range (2 ): 126with self .subTest (path = path ,stream = stream ,retry = retry ): 127previous = started .read_text ().splitlines ()if started .exists ()else [] 128with self .assertRaises (urllib .error .HTTPError )as got : 129self .post (path , {** body ,'stream' :stream }) 130with got .exception as response : 131self .assertEqual (response .code ,503 ) 132self .assertIn ('the image encoder failed to start' ,json .load (response )['error' ]['message' ]) 133children = started .read_text ().splitlines () 134self .assertEqual (len (children ),len (previous )+ 1 ) 135self .assertFalse (vision .alive ()) 136self .assertFalse (Path ('/proc' ,children [- 1 ]).exists ()) 137 138 139if __name__ == '__main__' : 140unittest .main ()