okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
ef6c18a14
main
1"""#1012 (the old #792): requests waiting for the engine's control lines when the engine is restarted. 2 3restart() runs StrataEngine.__init__ again; it used to make a new condition variable, lock, wait counter and wait 4list while the waiters still held the old ones: they hung for good, or failed with `list.remove(x): x not in 5list`. The admission state is now kept across a restart. A waiter either goes on with the new engine or ends 6with a clean 503; never a hang, never a ValueError. The fake engine of test_parallel runs behind the real 7StrataEngine and Service. 8 9python -m unittest serve.test_restart_waiters -v 10""" 11import json 12import subprocess 13import sys 14import threading 15import time 16import unittest 17import urllib .error 18import urllib .request 19from pathlib import Path 20from unittest import mock 21 22from serve import test_parallel 23 24REAL_POPEN = subprocess .Popen 25 26class RestartWaiters (unittest .TestCase ): 27# the fake-engine helpers of test_parallel (its module, not its class, is imported: no duplicate tests) 28chat = test_parallel .ParallelService .chat 29_start ,tearDown = test_parallel .ParallelService .start ,test_parallel .ParallelService .tearDown 30 31def start (self ,slots ,fit = None ): 32"""The fake engine, and it stays the engine for the restarts that follow (Popen is patched for the test).""" 33import serve .server as server 34real = REAL_POPEN 35self ._start (slots ,fit = fit ) 36script = Path (self .tmp .name )/ "fake_strata.py" 37patch = mock .patch .object (server .subprocess ,"Popen" , 38lambda cmd ,** kw :real ([sys .executable ,str (script ),* cmd [1 :]],** kw )) 39patch .start () 40self .addCleanup (patch .stop ) 41 42def post (self ,text ,out ,i ): 43try : 44out [i ]= ("ok" ,self .chat (text )["choices" ][0 ]["message" ]["content" ]) 45except urllib .error .HTTPError as e : 46out [i ]= ("http" ,e .code ,json .loads (e .read ().decode ())["error" ]["message" ]) 47except Exception as e :# noqa: BLE001 - reported by the assertions 48out [i ]= ("exc" ,repr (e )) 49 50def waiters (self ,n ): 51"""n requests that wait for the control lines: the test holds them (as a prompt read would).""" 52assert self .engine .ctl .acquire (timeout = 5 ) 53out ,threads = {}, [] 54for i in range (n ): 55th = threading .Thread (target = self .post ,args = (f"question { i } " ,out ,i )) 56th .start () 57threads .append (th ) 58deadline = time .time ()+ 20 59while self .engine .waiting < n and time .time ()< deadline : 60time .sleep (0.02 ) 61self .assertEqual (self .engine .waiting ,n ) 62return out ,threads 63 64def joined (self ,threads ): 65for th in threads : 66th .join (60 ) 67self .assertFalse ([th for th in threads if th .is_alive ()],"a waiter hung" ) 68 69def clean (self ): 70e = self .engine 71self .assertEqual ((e .waiting ,e .wait_lens ), (0 , [])) 72self .assertFalse (e .ctl .locked ()) 73 74def kill (self ): 75self .engine .proc .kill () 76self .engine .proc .wait (timeout = 10 ) 77 78def go_on (self ,slots ): 79self .start (slots ) 80e = self .engine 81cv ,ctl ,old_proc = e .slot_cv ,e .ctl ,e .proc 82out ,threads = self .waiters (3 ) 83self .kill () 84restarter = threading .Thread (target = e .restart )# what ensure_loaded does for the next request 85restarter .start () 86time .sleep (0.2 ) 87e .ctl .release ()# the request that held the lines is gone 88restarter .join (120 ) 89self .joined (threads ) 90self .assertEqual (out , {i : ("ok" ,"ok, done." )for i in range (3 )}) 91self .assertIsNot (e .proc ,old_proc ) 92self .assertIs (e .slot_cv ,cv )# the same condition variable and lock 93self .assertIs (e .ctl ,ctl ) 94self .clean () 95 96def test_waiters_go_on_with_the_new_engine_2_slots (self ): 97self .go_on (2 ) 98 99def test_waiters_go_on_with_the_new_engine_4_slots (self ): 100self .go_on (4 ) 101 102def stays_down (self ,slots ): 103self .start (slots ) 104out ,threads = self .waiters (3 ) 105self .kill () 106self .engine .ctl .release () 107self .joined (threads ) 108for i in range (3 ): 109self .assertEqual (out [i ][:2 ], ("http" ,503 ),out [i ]) 110self .assertNotIn ("list.remove" ,out [i ][2 ]) 111self .assertIn ("engine" ,out [i ][2 ]) 112self .clean () 113# the next request starts the engine again and is served 114self .assertEqual (self .chat ("after" )["choices" ][0 ]["message" ]["content" ],"ok, done." ) 115self .clean () 116 117def test_waiters_get_a_clean_503_when_the_engine_stays_down_2_slots (self ): 118self .stays_down (2 ) 119 120def test_waiters_get_a_clean_503_when_the_engine_stays_down_4_slots (self ): 121self .stays_down (4 ) 122 123def test_a_restart_that_fails_wakes_the_waiters (self ): 124self .start (2 ) 125e = self .engine 126out ,threads = self .waiters (2 ) 127self .kill () 128 129def refuse (* a ,** k ):# as __init__ when the new engine exits before READY 130e .proc = REAL_POPEN ([sys .executable ,"-c" ,"pass" ],stdin = subprocess .PIPE ,stdout = subprocess .PIPE , 131text = True ) 132raise RuntimeError ("the engine exited before it was ready" ) 133e .__init__ = refuse 134try : 135with self .assertRaises (RuntimeError ): 136e .restart (tries = 1 ) 137finally : 138del e .__init__ 139e .ctl .release () 140self .joined (threads ) 141self .assertEqual ([out [i ][:2 ]for i in range (2 )], [("http" ,503 )]* 2 ,out ) 142self .clean () 143 144def killed_mid_read (self ,slots ,others ): 145"""A long prompt is being read (alone, or with `others` short requests arriving meanwhile: it gives way and is 146admitted into a slot) when the engine dies: every request ends at once with a 503. It used to wait out the 147300 s drain for an end line that had been read already.""" 148self .start (slots ) 149out ,threads = {}, [] 150threads .append (threading .Thread (target = self .post ,args = ("LONGREPLY " + "word " * 740 ,out ,"long" ))) 151threads [0 ].start () 152time .sleep (0.25 ) 153for i in range (others ): 154th = threading .Thread (target = self .post ,args = (f"short { i } " ,out ,i )) 155th .start () 156threads .append (th ) 157time .sleep (0.05 ) 158time .sleep (0.1 ) 159t0 = time .time () 160self .kill () 161self .joined (threads ) 162self .assertLess (time .time ()- t0 ,20 ) 163self .assertTrue (all (v [0 ]== "ok" or v [:2 ]== ("http" ,503 )for v in out .values ()),out ) 164self .assertEqual (out ["long" ][:2 ], ("http" ,503 ),out ) 165self .clean () 166self .assertEqual (self .chat ("after" )["choices" ][0 ]["message" ]["content" ],"ok, done." ) 167 168def test_killed_while_reading_alone (self ): 169self .killed_mid_read (2 ,0 ) 170 171def test_killed_while_reading_with_others_arriving (self ): 172self .killed_mid_read (2 ,2 ) 173 174def test_an_old_request_meets_a_restart_in_progress (self ): 175"""A request that learns its engine died while restart() has already taken the process (self.proc is None): 176its death note and its sends answer with EngineDied, not AttributeError (the client got no reply at all).""" 177from serve .server import EngineDied 178self .start (2 ) 179self .kill () 180self .engine .close ()# what restart() does first 181self .assertIsNone (self .engine .proc ) 182self .assertTrue (self .engine .death_note ())# a sentence, no AttributeError 183self .assertFalse (self .engine .alive ()) 184with self .assertRaises (EngineDied ): 185self .engine ._send ("STOP" ) 186 187def refused (self ,slots ): 188"""#1059: the engine refuses a request up front (ERR, then idle). The server answered after a 300 s drain of 189a DONE that never comes, and held the control lines meanwhile.""" 190self .start (slots ) 191out = {} 192t0 = time .time () 193self .post ("REFUSEME please" ,out ,0 ) 194self .assertLess (time .time ()- t0 ,20 ) 195self .assertEqual (out [0 ][0 ],"http" ,out ) 196self .assertIn ("refused" ,out [0 ][2 ]) 197self .clean () 198self .assertEqual (self .chat ("after" )["choices" ][0 ]["message" ]["content" ],"ok, done." ) 199 200def test_an_engine_err_answers_at_once_solo_loop (self ): 201self .refused (2 ) 202 203def test_an_engine_err_answers_at_once_not_batched (self ): 204self .refused (0 ) 205 206def test_solo_engine_is_unchanged (self ): 207self .start (4 ,fit = 0 )# the engine turns batching off 208self .kill () 209self .assertEqual (self .chat ("hi" )["choices" ][0 ]["message" ]["content" ],"ok, done." ) 210 211 212if __name__ == "__main__" : 213unittest .main ()