okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
4d482e627
main
1"""Smaller serve-side robustness fixes of round 0213 (each test fails on the base a3a10b90a): 2 3#3443 ConvCacheLog.poll without a lock, #4792 a failed engine start when another thread closed the process, 4#4738 lost wake-ups of the control-line queue, #5044 a byte that is not UTF-8 on the engine's stdout. 5The fake engine and helpers are those of test_stream_ownership.py. 6""" 7import sys 8import tempfile 9import threading 10import unittest 11from pathlib import Path 12from unittest import mock 13 14from serve .server import StrataEngine 15from serve .test_stream_ownership import FakeEngines ,canary_script ,collect ,expected_reply ,prompt_ids 16 17 18class ConvCachePoll (unittest .TestCase ): 19"""ConvCacheLog.poll ran outside any lock: a second poll that moved `pos` between the first one's size check and 20its read left a negative read length (ValueError). Found by HWSTALL while triaging #3443.""" 21PARK = ("strata serve: conversation cache: parked 5000 tokens in 12.0 ms; parked=1 bytes=104857600 evictions=0 " 22"snapshot_bytes=104857600 reused_kv_bytes=0\n" ) 23 24def test_a_poll_that_overlaps_another_one_does_not_raise (self ): 25import os 26from serve .server import ConvCacheLog 27with tempfile .TemporaryDirectory ()as d : 28log = Path (d )/ "strata.log" 29log .write_text (self .PARK ,encoding = "utf-8" ) 30c = ConvCacheLog () 31c .poll (str (log ),0 ) 32with open (log ,"a" ,encoding = "utf-8" )as f : 33f .write (self .PARK ) 34first_sized ,first_may_go = threading .Event (),threading .Event () 35real_size = os .path .getsize 36calls = [] 37 38def slow_first (path ): 39size = real_size (path ) 40if not calls and path == str (log ): 41calls .append (1 ) 42first_sized .set () 43first_may_go .wait (2.0 )# the first poll has its size; a second poll runs meanwhile 44return size 45errors = [] 46 47def first (): 48try : 49c .poll (str (log ),0 ) 50except BaseException as e :# noqa: BLE001 51errors .append (e ) 52with mock .patch ("serve.server.os.path.getsize" ,slow_first ): 53t = threading .Thread (target = first ,daemon = True ) 54t .start () 55self .assertTrue (first_sized .wait (5 )) 56with open (log ,"a" ,encoding = "utf-8" )as f : 57f .write (self .PARK * 2 ) 58second = threading .Thread (target = lambda :c .poll (str (log ),0 ),daemon = True ) 59second .start () 60second .join (0.5 )# (with the lock it waits for the first one) 61first_may_go .set () 62t .join (5 ) 63second .join (5 ) 64self .assertEqual (errors , []) 65self .assertEqual (c .poll (str (log ),0 )["parks" ],4 ,"every parked line counted once" ) 66 67 68class FailedStart (unittest .TestCase ): 69"""#4792 (PR by a community author; the fix is written in our tree): a start that ends before READY must not crash 70when another thread closed the process (set self.proc to None) while the failed start cleaned up.""" 71 72def test_close_from_another_thread_during_a_failed_start (self ): 73import serve .server as server 74holder = {} 75 76class Pipe : 77def close (self ): 78pass 79 80def __iter__ (self ): 81return iter (())# the engine's output ends: no READY 82 83class Proc : 84returncode = 1 85stdin ,stdout = Pipe (),Pipe () 86pid = 0 87 88def wait (self ,timeout = None ): 89holder ["engine" ].proc = None # restart()'s close() on another thread 90return 1 91 92def poll (self ): 93return 1 94 95def kill (self ): 96pass 97 98engine = StrataEngine .__new__ (StrataEngine ) 99holder ["engine" ]= engine 100with mock .patch .object (server ,"popen" ,lambda * a ,** k :Proc ()), \ 101mock .patch .object (server ,"end_leftover_engines" ,lambda exe :None ), \ 102mock .patch .object (server ,"transient_start_failure" ,lambda * a ,** k :False ): 103with self .assertRaises (server .EngineDied ): 104engine .__init__ ("strata" , [],retry_args = None ) 105 106 107class ControlNotify (unittest .TestCase ): 108"""#4738 (the PR's approach, written in our tree): a request that waits for the control lines must not miss a 109notification sent between its check of the turn and its wait, and a waiter that leaves tells the others.""" 110 111class Cond (threading .Condition ): 112def __init__ (self ): 113super ().__init__ () 114self .exits ,self .after_check ,self .waits ,self .notifications = 0 ,None , [],0 115 116def __exit__ (self ,* args ): 117result = super ().__exit__ (* args ) 118self .exits += 1 119if self .exits == 2 and self .after_check is not None :# registered (1), turn read (2): now the producer 120hook ,self .after_check = self .after_check ,None 121hook () 122return result 123 124def wait (self ,timeout = None ): 125self .waits .append (timeout ) 126return True # (never blocks: the test is the schedule) 127 128def notify_all (self ): 129self .notifications += 1 130return super ().notify_all () 131 132def engine (self ): 133e = StrataEngine .__new__ (StrataEngine ) 134e .slot_cv ,e .waiting ,e .admitting = self .Cond (),1 ,0 # one other request is waiting 135e .wait_lens ,e .arrivals ,e .ctl_epoch ,e .ctl = [],__import__ ("collections" ).deque (maxlen = 64 ),0 ,threading .Lock () 136e .proc ,e .ended ,e .starting = mock .Mock (** {"poll.return_value" :None }),False ,False 137return e 138 139def test_a_notification_between_the_check_and_the_wait_is_not_lost (self ): 140e = self .engine () 141 142def producer ():# another request took the lines and gave them back 143with e .slot_cv : 144e .ctl_epoch += 1 145e .slot_cv .notify_all () 146e .slot_cv .after_check = producer 147gen = e ._take_control (threading .Event (),10 ,after_epoch = 0 ) 148with self .assertRaises (StopIteration )as done : 149for _ in range (5 ): 150next (gen ) 151self .assertTrue (done .exception .value ) 152self .assertEqual (e .slot_cv .waits , [],"it waited although its turn had come in the meantime" ) 153 154def test_a_waiter_that_leaves_notifies_the_others (self ): 155e = self .engine () 156e .ctl .acquire ()# the lines are taken: this one cannot have them 157cancel = threading .Event () 158cancel .set () 159gen = e ._take_control (cancel ,10 ) 160with self .assertRaises (StopIteration )as done : 161for _ in range (3 ): 162next (gen ) 163self .assertFalse (done .exception .value ) 164self .assertGreaterEqual (e .slot_cv .notifications ,1 ) 165self .assertEqual (e .waiting ,1 ) 166 167 168class StalledClient (unittest .TestCase ): 169"""#4271: a streaming client that stops reading, without closing its connection, must not hold the engine's turn 170for ever: the write that makes no progress ends the request as a disconnect and the next request is served.""" 171 172def test_a_client_that_stops_reading_gives_the_turn_back (self ): 173import json 174import socket 175import time 176import urllib .request 177import serve .server as server 178from serve .frontend import ChatTemplate 179from serve .server import ByteTokenizer ,MockEngine ,Service ,serve 180tok = ByteTokenizer () 181engine = MockEngine (tok ," " .join (str (i )for i in range (80000 )),max_context = 2_000_000 )# (not one repeated token) 182svc = Service (engine ,tok ,ChatTemplate (Path (server .__file__ ).parent / "chat_template.jinja" )) 183httpd = serve (svc ,port = 0 ) 184port = httpd .server_address [1 ] 185stuck = socket .socket () 186try : 187with mock .patch .object (server ,"STREAM_WRITE_TIMEOUT_S" ,0.5 ,create = True ): 188stuck .setsockopt (socket .SOL_SOCKET ,socket .SO_RCVBUF ,4096 ) 189stuck .connect (("127.0.0.1" ,port )) 190body = json .dumps ({"messages" : [{"role" :"user" ,"content" :"go" }],"stream" :True , 191"max_tokens" :400000 ,"reasoning_effort" :"none" }).encode () 192stuck .sendall (b"POST /v1/chat/completions HTTP/1.1\r\nHost: 127.0.0.1\r\nContent-Type: application/json\r\n" 193b"Content-Length: " + str (len (body )).encode ()+ b"\r\n\r\n" + body ) 194# ... and it never reads. Wait until the server is writing into a full buffer, then until it lets go. 195end = time .monotonic ()+ 3 196while time .monotonic ()< end and not svc .fifo .locked (): 197time .sleep (0.01 ) 198self .assertTrue (svc .fifo .locked (),"the stuck client's request holds the engine's turn" ) 199end = time .monotonic ()+ 20 200while time .monotonic ()< end and svc .fifo .locked (): 201time .sleep (0.05 ) 202self .assertFalse (svc .fifo .locked (),"the turn is still held by a client that does not read" ) 203finally : 204stuck .close () 205httpd .shutdown () 206httpd .server_close () 207 208 209def test_a_client_that_reads_but_waits_for_a_slow_engine_is_not_cut_off (self ): 210"""The write limit is for a write that makes no progress (the client stopped reading), not for a client that is 211idle while the engine thinks: 0.3 s between tokens, a 0.1 s write limit, the whole reply arrives.""" 212import http .client 213import json 214import serve .server as server 215from serve .frontend import ChatTemplate 216from serve .server import ByteTokenizer ,MockEngine ,Service ,serve 217tok = ByteTokenizer () 218svc = Service (MockEngine (tok ,"abcdef" ,delay_s = 0.3 ),tok , 219ChatTemplate (Path (server .__file__ ).parent / "chat_template.jinja" )) 220httpd = serve (svc ,port = 0 ) 221try : 222with mock .patch .object (server ,"STREAM_WRITE_TIMEOUT_S" ,0.1 ,create = True ): 223conn = http .client .HTTPConnection ("127.0.0.1" ,httpd .server_address [1 ],timeout = 30 ) 224conn .request ("POST" ,"/v1/chat/completions" ,json .dumps ( 225 {"messages" : [{"role" :"user" ,"content" :"go" }],"stream" :True ,"max_tokens" :50 , 226"reasoning_effort" :"none" }), {"Content-Type" :"application/json" }) 227body = conn .getresponse ().read ().decode () 228conn .close () 229text = "" .join (json .loads (l [5 :])["choices" ][0 ]["delta" ].get ("content" )or "" 230for l in body .splitlines ()if l .startswith ("data:" )and "[DONE]" not in l 231and json .loads (l [5 :]).get ("choices" )) 232self .assertEqual (text ,"abcdef" ) 233self .assertIn ("data: [DONE]" ,body ) 234finally : 235httpd .shutdown () 236httpd .server_close () 237 238 239class BlockedConsole (unittest .TestCase ): 240"""#4479 / #2481: a console that stops taking output must not hold the thread that prints.""" 241 242def pipe (self ): 243import os 244r ,w = os .pipe () 245self .addCleanup (lambda : [os .close (x )for x in (r ,)if True ]) 246return r ,os .fdopen (w ,"w" ,encoding = "utf-8" ,buffering = 1 ) 247 248def test_a_print_to_a_full_pipe_blocks_without_the_wrapper (self ): 249"""The control: this is the dependency the request lifecycle had on the console.""" 250r ,w = self .pipe () 251done = threading .Event () 252 253def spam (): 254for i in range (20000 ): 255w .write (f"[strata] progress line { i } " + "x" * 40 + "\n" ) 256w .flush () 257done .set () 258threading .Thread (target = spam ,daemon = True ).start () 259self .assertFalse (done .wait (1.0 ),"a pipe nobody reads must block a plain print" ) 260 261def test_the_wrapper_never_blocks_and_keeps_the_newest_lines (self ): 262import os 263from serve .nonblocking_out import NonBlockingOut 264r ,w = self .pipe () 265out = NonBlockingOut (w ,max_bytes = 64 * 1024 ,max_chunks = 500 ) 266done = threading .Event () 267 268def spam (): 269for i in range (20000 ): 270f"[strata] progress line { i } " + "x" * 40 ,file = out ,flush = True ) 271done .set () 272threading .Thread (target = spam ,daemon = True ).start () 273self .assertTrue (done .wait (5.0 ),"printing into a console nobody reads must not block" ) 274self .assertGreater (out .dropped_chunks ,0 ) 275self .assertLessEqual (len (out ._q ),500 ) 276# the console wakes up: everything that was kept arrives, in order, ending with the newest line 277data = b"" 278end = __import__ ("time" ).monotonic ()+ 10 279while __import__ ("time" ).monotonic ()< end and b"progress line 19999" not in data : 280data += os .read (r ,65536 ) 281text = data .decode () 282self .assertIn ("progress line 19999 " ,text ) 283seen = [int (l .split ()[3 ])for l in text .splitlines ()if l .startswith ("[strata] progress line" )] 284self .assertEqual (seen ,sorted (seen ),"order is kept" ) 285out .close (1.0 ) 286 287def test_the_console_is_restored_and_drained (self ): 288import io 289from serve .nonblocking_out import NonBlockingOut 290real = io .StringIO () 291out = NonBlockingOut (real ) 292out .write ("hello\n" ) 293out .write ("world\n" ) 294self .assertTrue (out .drain (2.0 )) 295self .assertEqual (real .getvalue (),"hello\nworld\n" ) 296out .close () 297self .assertEqual (out .write ("late\n" ),5 )# a late write after close is not an error 298 299 300class EngineOutputDecoding (FakeEngines ,unittest .TestCase ): 301"""#5044: a byte that is not UTF-8 on the engine's stdout (Windows can print one) must not end the reader.""" 302 303def tearDown (self ): 304self .cleanup_engines () 305 306def test_a_non_utf8_byte_before_ready_and_in_a_reply (self ): 307import serve .server as server 308self .tmp = tempfile .TemporaryDirectory () 309text = canary_script () 310bad = 'sys.stdout.buffer.write(b"INFO note=\\x8e\\n"); sys.stdout.flush()\nprint("READY 4096 stop", flush=True)' 311self .assertIn ('print("READY 4096 stop", flush=True)' ,text ) 312text = text .replace ('print("READY 4096 stop", flush=True)' ,bad ,1 ) 313script = Path (self .tmp .name )/ "fake_strata.py" 314script .write_text (text ,encoding = "utf-8" ) 315real = server .subprocess .Popen 316self .popen_patch = mock .patch .object (server .subprocess ,"Popen" , 317lambda cmd ,** kw :real ([sys .executable ,str (script ),* cmd [1 :]],** kw )) 318self .popen_patch .start () 319engine = StrataEngine ("strata" , []) 320self .engines = [engine ] 321self .assertTrue (engine .alive ()) 322got = [] 323collect (engine .generate (prompt_ids ("KA0001" ),500 , {},threading .Event ()),got ) 324self .assertEqual (got ,expected_reply ("KA0001" )) 325 326 327if __name__ == "__main__" : 328unittest .main ()