okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
b111d1e83
main
1"""#465 (part 2): the parallel slots when a long prompt gives way, a window fails, a slot leaks or a conversation returns. 2 3The same fake engine and helpers as serve/test_parallel.py (FakeEngineCase); split out because the whole file took 4about two minutes in one piece.""" 5import json 6import sys 7import threading 8import time 9import unittest 10import urllib .error 11import urllib .request 12from pathlib import Path 13from unittest import mock 14from serve import test_parallel as tp 15 16 17class ParallelServiceYield (tp .FakeEngineCase ): 18"""Requests that give way to each other, and what happens to a slot when the engine misbehaves.""" 19 20def test_a_long_prompt_gives_way_to_a_short_one (self ): 21"""#656: a long solo prompt read gives way at a chunk boundary; the short request is answered first, then the 22long one goes on (in the slot its part waited in) and is answered too.""" 23self .start (2 ) 24long_q ,short_q = "long " * 600 ,"short" 25res = self .race (long_q ,short_q ) 26self .assertEqual (res [long_q ][0 ],"ok, done." ) 27self .assertEqual (res [short_q ][0 ],"ok, done." ) 28# the long read takes ~1 s (3,000 tokens, 32 a chunk, 10 ms a chunk): the short one did not wait for it 29self .assertLess (res [short_q ][1 ],res [long_q ][1 ]- 0.5 ,res ) 30log = self .log .read_text ().splitlines () 31self .assertTrue (any (x .startswith ("YIELD " )for x in log ),log ) 32with self .svc .status_lock : 33self .assertEqual (len (self .svc .history ),2 ) 34self .assertFalse (any (self .engine .slot_busy )) 35 36def test_the_way_is_asked_between_far_apart_progress_lines (self ): 37"""#656 when the PP lines come far apart (the pipelined groups' read in pieces of one chunk: one PP per piece, 38at its end): the BYIELD goes out while the engine is quiet, so the read gives way at the first boundary after 39the short request came. Asked only at a PP line, it reached the engine after that boundary's check and the 40read gave way one piece later.""" 41self .start (2 ,more = ["--pp-every" ,"80" ])# a boundary every 80 chunks (~0.8 s): one in this read 42long_q ,short_q = "long " * 600 ,"short" 43res = self .race (long_q ,short_q ) 44self .assertEqual (res [long_q ][0 ],"ok, done." ) 45self .assertEqual (res [short_q ][0 ],"ok, done." ) 46yields = [x for x in self .log .read_text ().splitlines ()if x .startswith ("YIELD " )] 47self .assertEqual ([int (x .split ()[2 ])for x in yields ], [80 * 32 ],yields ) 48 49def test_three_requests_long_long_short_do_not_deadlock (self ): 50"""ENGINE_REVIEW finding 1 (0.1.41 check): two long prompts fill both slots, a short one arrives a moment later 51and wants one of them (the yield path). The reviewer's repro: long, long, short at 0.25 s steps. Every 52request must be answered; none may wait on the control lock that the yielding read holds.""" 53self .start (2 ) 54texts = ["long " * 600 ,"lung " * 600 ,"short" ] 55res ,errors = {}, [] 56 57def go (t ): 58t0 = time .time () 59try : 60r = self .chat (t ,max_tokens = 64 ) 61res [t ]= (r ["choices" ][0 ]["message" ]["content" ],time .time ()- t0 ) 62except Exception as e :# noqa: BLE001 - a timeout is the failure this test looks for 63errors .append ((t [:6 ],repr (e ))) 64threads = [] 65for t in texts : 66th = threading .Thread (target = go ,args = (t ,)) 67th .start () 68threads .append (th ) 69time .sleep (0.25 ) 70for th in threads : 71th .join (45 ) 72self .assertFalse (any (th .is_alive ()for th in threads ),"a request never finished (deadlock)" ) 73self .assertEqual (errors , []) 74self .assertEqual (sorted (r [0 ]for r in res .values ()), ["ok, done." ]* 3 ) 75self .assertFalse (any (self .engine .slot_busy )) 76with self .svc .status_lock : 77self .assertEqual (len (self .svc .history ),3 ) 78 79def test_an_admission_gives_way_too (self ): 80"""The same while another request decodes in a slot: the long one is being admitted, a short one waits.""" 81self .start (3 ) 82bg = threading .Thread (target = lambda :self .chat ("background" ,max_tokens = 60 )) 83bg .start () 84time .sleep (0.05 ) 85long_q ,short_q = "long " * 600 ,"short" 86res = self .race (long_q ,short_q ) 87bg .join (30 ) 88self .assertEqual (res [long_q ][0 ],"ok, done." ) 89self .assertLess (res [short_q ][1 ],res [long_q ][1 ]- 0.5 ,res ) 90log = self .log .read_text ().splitlines () 91self .assertTrue (any (x .startswith ("YIELD " )for x in log ),log ) 92self .assertFalse (any (self .engine .slot_busy )) 93 94def test_an_admission_is_asked_between_far_apart_progress_lines (self ): 95"""As above for a read admitted beside a decoding slot (BGEN, `ask()`): with one PP line per 80 chunks the 96short request's BYIELD still reaches the first boundary.""" 97self .start (3 ,more = ["--pp-every" ,"80" ]) 98bg = threading .Thread (target = lambda :self .chat ("LONGREPLY background" ,max_tokens = 60 )) 99bg .start () 100time .sleep (0.05 ) 101long_q ,short_q = "long " * 600 ,"short" 102res = self .race (long_q ,short_q ) 103bg .join (30 ) 104self .assertEqual (res [long_q ][0 ],"ok, done." ) 105self .assertEqual (res [short_q ][0 ],"ok, done." ) 106log = self .log .read_text ().splitlines () 107admitted = [x .split ()for x in log if x .startswith ("BGEN " )and int (x .split ()[2 ])> 2600 ] 108self .assertTrue (admitted ,log )# the long read was an admission 109yields = [x .split ()[1 :]for x in log if x .startswith ("YIELD " )] 110self .assertEqual (yields [:1 ], [[admitted [0 ][1 ],str (80 * 32 )]],log ) 111self .assertFalse (any (self .engine .slot_busy )) 112 113def test_no_way_given_to_a_long_one (self ): 114"""Two prompts of about the same length: no BYIELD (it only goes to a much shorter one).""" 115self .start (2 ) 116res = self .race ("long " * 600 ,"lung " * 600 ) 117self .assertEqual (sorted (r [0 ]for r in res .values ()), ["ok, done." ]* 2 ) 118self .assertFalse (any (x .startswith ("YIELD " )for x in self .log .read_text ().splitlines ())) 119 120def test_no_way_given_to_a_long_one_between_far_apart_progress_lines (self ): 121"""The ask between PP lines keeps the rule: a waiting request about as long gets no BYIELD there either.""" 122self .start (2 ,more = ["--pp-every" ,"80" ]) 123res = self .race ("long " * 600 ,"lung " * 600 ) 124self .assertEqual (sorted (r [0 ]for r in res .values ()), ["ok, done." ]* 2 ) 125self .assertFalse (any (x .startswith ("YIELD " )for x in self .log .read_text ().splitlines ())) 126 127def test_left_alone_it_goes_back_to_the_solo_path (self ): 128"""A request decoding in a slot whose neighbour finished goes back to the solo path (MTP drafts), continued 129from its slot - only with an engine that keeps the slots' conversations (INFO slot_cache=1).""" 130self .start (2 ,slot_cache = True ) 131res = {} 132long = threading .Thread (target = lambda :res .setdefault ("long" ,self .chat ("LONGREPLY please" ,max_tokens = 200 ))) 133long .start () 134time .sleep (0.05 ) 135short = self .chat ("short" ,max_tokens = 200 ) 136long .join (30 ) 137self .assertEqual (short ["choices" ][0 ]["message" ]["content" ],"ok, done." ) 138self .assertEqual (res ["long" ]["choices" ][0 ]["message" ]["content" ],"ok, " + "la " * 15 + "done." ) 139kinds = [x .split ()[0 ]for x in self .log .read_text ().splitlines ()] 140# solo, then both in slots, then the long one alone again: a GEN after the BGENs 141self .assertIn ("BGEN" ,kinds ) 142self .assertEqual (kinds [- 1 ],"GEN" ,kinds ) 143self .assertFalse (any (self .engine .slot_busy )) 144with self .svc .status_lock : 145self .assertEqual (len (self .svc .history ),2 ) 146 147def test_next_turn_goes_back_to_its_slot (self ): 148self .start (2 ) 149a = "conversation A, first turn" 150r1 = {} 151th = threading .Thread (target = lambda :r1 .setdefault ("x" ,self .chat ("blocker LONGREPLY" ,max_tokens = 200 ))) 152th .start () 153time .sleep (0.05 ) 154first = self .chat (a ) 155th .join (30 ) 156deadline = time .time ()+ 10 # a slot left at its stop token is freed at its BDONE 157while not [h for h in self .engine .slot_held if h ]and time .time ()< deadline : 158time .sleep (0.02 ) 159held = [h for h in self .engine .slot_held if h ] 160self .assertTrue (held ,"a finished slot request keeps what its slot holds" ) 161# the held tokens are the prompt and every token fed: all of the reply but its last token 162reply = list (b"ok, done." )+ [257 ] 163mine = [h for h in held if h [- len (reply )+ 1 :]== reply [:- 1 ]and bytes (x for x in h if x < 256 ).find (b"conversation A" )>= 0 ] 164self .assertEqual (len (mine ),1 ,held ) 165slot = self .engine .slot_held .index (mine [0 ]) 166self .assertEqual (self .engine .pick_slot (mine [0 ]+ [10 ,11 ]),slot ) 167self .assertEqual (first ["choices" ][0 ]["message" ]["content" ],"ok, done." ) 168 169def test_a_failed_window_names_its_error (self ): 170# #997 #890: a batch window fails while every request reads its own slot's lines, so no request reads the 171# engine's ERR line before it exits; the server's note on the death gives it instead of a guess 172self .start (2 ,fail = True ) 173errors = [] 174 175def go (t ): 176try : 177self .chat (t ) 178except urllib .error .HTTPError as e : 179errors .append (e .code ) 180 181threads = [threading .Thread (target = go ,args = (t ,))for t in ("first question LONGREPLY" ,"second question" )] 182for th in threads : 183th .start () 184time .sleep (0.05 ) 185for th in threads : 186th .join (30 ) 187self .assertEqual (len (errors ),2 ,errors ) 188note = self .engine .death_note () 189self .assertIn ("exited (code 1)" ,note ) 190self .assertIn ("verify batch: layer 34 never rang (graph finished)" ,note ) 191 192def test_nonfinite_in_batch_mode (self ): 193"""#879 in --batch mode: DONE ... nonfinite on the solo path or at an admission (nothing emitted yet) sends the 194request again once; BDONE ... nonfinite in a slot ends the reply that had started, as "length".""" 195self .start (2 ) 196self .assertEqual (self .chat ("NFSOLO alone" )["choices" ][0 ]["message" ]["content" ],"ok, done." ) 197gens = [x for x in self .log .read_text ().splitlines ()if x .startswith ("GEN" )] 198self .assertEqual (len (gens ),2 ,gens )# sent again once 199res = self .race ("first question LONGREPLY" ,"NFADMIT second" ) 200self .assertEqual (res ["NFADMIT second" ][0 ],"ok, done." ) 201self .assertEqual (res ["first question LONGREPLY" ][0 ],"ok, " + "la " * 15 + "done." ) 202self .assertTrue (any (x .startswith ("BGEN" )for x in self .log .read_text ().splitlines ())) 203out = {} 204 205def go (t ): 206body = {"messages" : [{"role" :"user" ,"content" :t }],"max_tokens" :64 ,"reasoning_effort" :"none" } 207req = urllib .request .Request (self .base + "/v1/chat/completions" ,data = json .dumps (body ).encode (), 208headers = {"Content-Type" :"application/json" }) 209with urllib .request .urlopen (req ,timeout = 60 )as r : 210out [t ]= json .loads (r .read ().decode ())["choices" ][0 ] 211a = threading .Thread (target = go ,args = ("third question LONGREPLY" ,)) 212a .start () 213time .sleep (0.15 ) 214go ("NFSLOT fourth" ) 215a .join (30 ) 216c = out ["NFSLOT fourth" ] 217self .assertEqual ((c ["message" ]["content" ],c ["finish_reason" ]), ("ok" ,"length" )) 218self .assertEqual (out ["third question LONGREPLY" ]["message" ]["content" ],"ok, " + "la " * 15 + "done." ) 219# the engine dropped that slot's state: the server does not route the conversation's next turn to it 220self .assertFalse ([h for h in self .engine .slot_held if bytes (t & 255 for t in h ).find (b"NFSLOT" )>= 0 ]) 221with self .svc .status_lock : 222self .assertEqual (self .svc .live_reqs , {}) 223 224def test_a_continued_request_reports_its_own_prompt_reuse (self ): 225"""A request STOPped on the solo path and continued in a slot (or back on the solo path) is sent again as its 226prompt + what it generated, and the engine holds all of that: the usage must still split the request's OWN 227prompt (input_tokens + cache_read_input_tokens = the prompt, input_tokens >= 1). input_tokens 0 makes Claude 228Code count the prompt twice (message_start's input_tokens + cache_read_input_tokens): "Prompt is too long" 229at half the context.""" 230self .start (2 ,slot_cache = True ,reuse = True ) 231res = {} 232long = threading .Thread (target = lambda :res .setdefault ("long" ,self .message ("LONGREPLY please" ,200 ))) 233long .start () 234time .sleep (0.05 ) 235self .message ("short" ,200 ) 236long .join (30 ) 237kinds = [x .split ()[0 ]for x in self .log .read_text ().splitlines ()] 238self .assertIn ("BGEN" ,kinds )# it was continued: the case under test 239u = res ["long" ]["usage" ] 240prompt = self .svc .history [[h ["output_tokens" ]for h in self .svc .history ].index ( 241max (h ["output_tokens" ]for h in self .svc .history ))]["prompt_total" ] 242self .assertGreaterEqual (u ["input_tokens" ],1 ,u ) 243self .assertEqual (u ["input_tokens" ]+ u ["cache_creation_input_tokens" ]+ u ["cache_read_input_tokens" ],prompt ,u ) 244self .assertEqual (u ["cache_read_input_tokens" ],3 ,u )# the first read's reuse, not the continuation's 245 246def test_a_slot_request_ended_by_its_stop_token_reports_the_slot_leg (self ): 247"""#1869: the consumer leaves at the stop token, before the BDONE: the request kept the admission's one token and 248its few ms. Its figures are the slot leg's now (finish=stop was the broken case, finish=length read the BDONE).""" 249import serve .server as server 250self .start (2 ,slot_cache = True ,reuse = True ,more = ("--readfield" ,)) 251res = {} 252with mock .patch .object (server ,"EOS_IDS" , {257 }):# the fake engine's stop token 253a = threading .Thread (target = lambda :res .setdefault ("a" ,self .chat ("List three primes please" ,200 ))) 254b = threading .Thread (target = lambda :res .setdefault ("b" ,self .chat ("Name two rivers in Germany" ,200 ))) 255a .start ();b .start ();a .join (30 );b .join (30 ) 256self .assertEqual (len (self .svc .history ),2 ) 257for h in self .svc .history : 258self .assertEqual (h ["engine_generated" ],h ["output_tokens" ],h ) 259self .assertGreaterEqual (h ["decode_ms" ],1.0 ,h ) 260for r in res .values (): 261t = r ["timings" ] 262self .assertEqual (t ["prompt_n" ]+ t ["cache_n" ],r ["usage" ]["prompt_tokens" ],t ) 263self .assertEqual (t ["predicted_n" ],10 ,t ) 264self .assertFalse (any (self .engine .slot_busy ))# the slots are free (no BDONE left for a wait) 265 266def test_a_request_moved_between_solo_and_slot_keeps_its_totals (self ): 267"""#1869/#1870: a request that read its prompt and decoded on the solo path, was STOPped when another arrived and 268went on in a slot (its admission copies the held prefix: prompt_read 1, one token) reports the prompt it read and 269the decode time and tokens of ALL its legs, not the last one's.""" 270self .start (2 ,slot_cache = True ,reuse = True ,more = ("--readfield" ,)) 271res = {} 272long = threading .Thread (target = lambda :res .setdefault ("long" ,self .chat ("LONGREPLY please" ,max_tokens = 200 ))) 273long .start () 274time .sleep (0.25 )# a few solo tokens first 275self .chat ("short" ,max_tokens = 200 ) 276long .join (30 ) 277kinds = [x .split ()[0 ]for x in self .log .read_text ().splitlines ()] 278self .assertEqual (kinds [:2 ], ["GEN" ,"BGEN" ],kinds )# solo, then continued in a slot: the case under test 279n = res ["long" ]["usage" ]["completion_tokens" ] 280row = max (self .svc .history ,key = lambda h :h ["output_tokens" ]) 281self .assertEqual (row ["engine_generated" ],n ,row ) 282self .assertGreater (row ["decode_ms" ],20.0 * 3 ,row )# the solo leg's STEP-long tokens are in it 283self .assertGreater (row ["prompt_read" ],1 ,row )# the first read, not the copy leg's 1 284t = res ["long" ]["timings" ] 285self .assertEqual (t ["prompt_n" ]+ t ["cache_n" ],res ["long" ]["usage" ]["prompt_tokens" ],t ) 286self .assertEqual (t ["cache_n" ],3 ,t )# the first read's reuse only 287self .assertGreater (t ["predicted_ms" ],60.0 ,t ) 288 289def test_a_leaked_busy_slot_does_not_hang_the_next_request (self ): 290"""#1603: a slot whose busy flag has no owner (no request holds it, no BDONE wait is running) kept every later 291request waiting for a slot nothing would free: running 0, queued 0, and the frozen-engine check never looked. 292The waiting request is now counted (admitting), the slot is given back after ORPHAN_SLOT_S, and it is 293answered.""" 294self .start (2 ) 295e = self .engine 296e .ORPHAN_SLOT_S = 0.4 297with e .slot_cv : 298e .slot_busy [0 ]= e .slot_busy [1 ]= True # the leak: busy, claimed by nobody, nothing ending them 299# the solo path needs a quiet engine; a busy flag sends the request to the slot path, which waits 300res ,errs = {}, [] 301def go (): 302try : 303res ["r" ]= self .chat ("after the leak" ,max_tokens = 16 ) 304except Exception as ex :# noqa: BLE001 305errs .append (ex ) 306t = threading .Thread (target = go ) 307t0 = time .time () 308t .start () 309seen = [] 310while t .is_alive ()and time .time ()- t0 < 20 : 311live = self .get ("/metrics" )["live" ] 312seen .append ((live .get ("running" ),live .get ("queued" ),live .get ("admitting" ))) 313time .sleep (0.05 ) 314t .join (5 ) 315self .assertEqual (errs , []) 316self .assertFalse (t .is_alive (),"the request hung on a slot nobody owns" ) 317self .assertEqual (res ["r" ]["choices" ][0 ]["message" ]["content" ],"ok, done." ) 318# while it waited it was visible: running as a request, and counted as waiting for a slot - never 0 / 0 / 0 319self .assertTrue (any (r == 1 and a == 1 for r ,q ,a in seen ),seen ) 320first = next (i for i ,x in enumerate (seen )if sum (v or 0 for v in x )) 321self .assertTrue (all (sum (v or 0 for v in x )for x in seen [first :- 1 ]),seen )# never invisible once it arrived 322self .assertEqual (e .admitting ,0 ) 323self .assertEqual (e .slot_claims ,set ()) 324 325def test_an_owned_busy_slot_is_never_taken (self ): 326"""The leak check frees only slots with no owner: a slot a request holds stays busy however long it waits.""" 327self .start (2 ) 328e = self .engine 329e .ORPHAN_SLOT_S = 0.0 330with e .slot_cv : 331e .slot_busy [0 ]= True 332e .slot_claims .add (0 ) 333e .slot_busy [1 ]= True 334e .slot_releasing .add (1 ) 335self .assertEqual (e ._reap_orphan_slots (), []) 336self .assertEqual (e .slot_busy , [True ,True ]) 337e .slot_claims .discard (0 ) 338self .assertEqual (e ._reap_orphan_slots (), [0 ]) 339self .assertEqual (e .slot_busy , [False ,True ]) 340 341def test_a_parallel_request_does_not_wait_for_the_fifo_on_a_loaded_engine (self ): 342"""#1603: parallel requests used to take the FIFO (held by an image encode, /v1/vram, load) just to find the 343engine loaded; between 'queued' and 'running' they were neither. Loaded: no fifo. Unloaded: they wait for it 344and are counted as queued the whole time.""" 345self .start (2 ) 346self .assertEqual (self .chat ("warm" )["choices" ][0 ]["message" ]["content" ],"ok, done." ) 347self .svc .fifo .acquire () 348try : 349r = self .chat ("with the fifo held" )# would block here before 350self .assertEqual (r ["choices" ][0 ]["message" ]["content" ],"ok, done." ) 351finally : 352self .svc .fifo .release () 353import serve .server as server 354script ,real = Path (self .tmp .name )/ "fake_strata.py" ,server .subprocess .Popen 355patch = mock .patch .object (server .subprocess ,"Popen" ,# the reload starts the fake again 356lambda cmd ,** kw :real ([sys .executable ,str (script ),* cmd [1 :]],** kw )) 357patch .start () 358self .addCleanup (patch .stop ) 359self .engine .unload () 360self .svc .fifo .acquire () 361res = {} 362t = threading .Thread (target = lambda :res .setdefault ("r" ,self .chat ("reloads" ,max_tokens = 16 ))) 363t .start () 364try : 365deadline = time .time ()+ 10 366live = {} 367while time .time ()< deadline : 368live = self .get ("/metrics" )["live" ] 369if live .get ("queued" ): 370break 371time .sleep (0.05 ) 372self .assertEqual (live .get ("queued" ),1 ,live )# waiting for the fifo: queued, not nothing 373self .assertEqual (live .get ("running" ),0 ,live ) 374finally : 375self .svc .fifo .release () 376t .join (60 ) 377self .assertEqual (res ["r" ]["choices" ][0 ]["message" ]["content" ],"ok, done." ) 378self .assertEqual (self .get ("/metrics" )["live" ]["queued" ],0 ) 379 380 381 382 383if __name__ == "__main__" : 384unittest .main ()