okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
4d482e627
main
1"""P0 (round 0213): streamed output must be delivered only to the request that owns it. 2 3#2892 (unbatched replicas cross DONE ownership) and #4451 (--batch: one client's stream reaches another connection). 4 5The fake engine is the one of test_parallel.py with a canary reply: the reply to a prompt is the prompt's own canary 6(two capital letters and 4 digits) repeated, so a token that reaches the wrong request is visible as a foreign canary. Every 7test forces a LEGAL schedule with events or a hooked lock (the way serve/test_replica_lifetime.py of PR #2886 does), 8so a failure does not depend on winning a scheduler race. 9""" 10import re 11import sys 12import tempfile 13import threading 14import time 15import unittest 16from pathlib import Path 17from unittest import mock 18 19from serve .replicas import ReplicaEngine 20from serve .server import StrataEngine 21from serve .test_parallel import FAKE_BATCH 22 23CANARY_REPEAT = 60 24CANARY_RE = re .compile (rb"[A-Z]{2}\d{4}" ) 25 26# the fake's `continued` (the whole reply, how much of it the prompt ends with) with a canary reply: the last canary 27# of the prompt, repeated. STEP is shortened so the many repetitions stay fast. 28CANARY_PATCH = ''' 29import re as _re 30_orig_continued = continued 31def continued(ids): 32pb = bytes(int(x) & 255 for x in ids) 33found = _re.findall(rb"[A-Z]{2}\\d{4}", pb) 34if found: 35R = list((found[-1] + b" ") * %d) + [257] 36ints = [int(x) for x in ids] 37return R, max(k for k in range(len(R)) if k == 0 or ints[-k:] == R[:k]) 38return _orig_continued(ids) 39def reply(ids): 40R, k = continued(ids) 41return R[k:] 42''' % CANARY_REPEAT 43 44 45def canary_script (step = 0.004 ): 46text = FAKE_BATCH .replace ("STEP = 0.02" ,f"STEP = { step } " ) 47# SLOWPREFILL in a prompt: its read takes a while (a cancel can land inside it). DEAFSTOP: the engine reads the 48# whole prompt whatever STOP says and then goes on as if it had not come (a drain that does not get its line in time). 49old = " given = None\n for q in range(CH, len(ids) - 1, CH):\n time.sleep(STEP / 2)\n" 50assert old in text 51text = text .replace (old ," given = None\n pbm = bytes(int(x) & 255 for x in ids)\n" 52" slow, deaf = b\"SLOWPREFILL\" in pbm, b\"DEAFSTOP\" in pbm\n" 53" quiet = b\"SILENTREAD\" in pbm\n" 54" for q in range(CH, len(ids) - 1, CH):\n" 55" time.sleep(STEP / 2 + (0.02 if slow or deaf else 0))\n" 56" if quiet and q > CH:\n" 57" continue # SILENTREAD: after its first PP line the read says nothing\n" ,1 ) 58old = " if stop.is_set():\n break\n if active and (q // CH) % 4 == 0:" 59assert old in text 60text = text .replace (old ," if stop.is_set() and not deaf:\n break\n" 61" if active and (q // CH) % 4 == 0:" ,1 ) 62old = " if given:\n if log:\n log.write(f\"YIELD" 63assert old in text 64text = text .replace (old ," if deaf:\n stop.clear()\n" + old ,1 ) 65text = text .replace ("while True:\n try:\n line = lines.get(timeout=STEP if active else None)" , 66CANARY_PATCH + "while True:\n try:\n line = lines.get(timeout=STEP if active else None)" ,1 ) 67assert CANARY_PATCH in text 68# VRAM and SAVE / RESTORE answer on the control lines, in the engine's own words 69old = ' if line:\n print("ERR unknown " + line[:20], flush=True)\n continue\n' 70assert old in text 71text = text .replace (old ,' if line.startswith("VRAM"):\n print("VRAM vram_free_mib=100 expert_slots=1", flush=True)\n continue\n' 72' if line.startswith(("SAVE ", "RESTORE ")):\n' 73' print("SAVED 1 1 1.0" if line.startswith("SAVE") else "RESTORED 1 1 1.0", flush=True)\n' 74' continue\n' + old ,1 ) 75return text 76 77 78def prompt_ids (canary :str ,filler :int = 0 )-> list [int ]: 79return list (f"say { canary } " .encode ())+ [ord ("x" )]* filler + list (f" { canary } please" .encode ()) 80 81 82def expected_reply (canary :str )-> list [int ]: 83return list ((canary .encode ()+ b" " )* CANARY_REPEAT )+ [257 ] 84 85 86def text_of (tokens )-> bytes : 87return bytes (t for t in tokens if 0 <= t < 256 ) 88 89 90def foreign (tokens ,own :str )-> list [bytes ]: 91"""The canaries in a token stream that are not `own`.""" 92return [c for c in CANARY_RE .findall (text_of (tokens ))if c != own .encode ()] 93 94 95class FakeEngines : 96"""Real StrataEngine objects (the reader/pump, the generate paths) over the canary fake process.""" 97 98def make_engines (self ,n ,batch = 0 ,step = 0.004 ): 99import serve .server as server 100self .tmp = tempfile .TemporaryDirectory () 101script = Path (self .tmp .name )/ "fake_strata.py" 102script .write_text (canary_script (step ),encoding = "utf-8" ) 103real = server .subprocess .Popen 104# kept for the whole test: restart() starts the fake again 105self .popen_patch = mock .patch .object (server .subprocess ,"Popen" , 106lambda cmd ,** kw :real ([sys .executable ,str (script ),* cmd [1 :]],** kw )) 107self .popen_patch .start () 108engines = [] 109for i in range (n ): 110extra = (["--batch" ,str (batch )]if batch else []) 111engines .append (StrataEngine ("strata" ,extra )) 112for e in engines : 113e .silence_s = 20 114return engines 115 116def cleanup_engines (self ): 117for e in getattr (self ,"engines" , []): 118try : 119e .unload () 120except Exception :# noqa: BLE001 121pass 122if getattr (self ,"popen_patch" ,None ): 123self .popen_patch .stop () 124if getattr (self ,"tmp" ,None ): 125self .tmp .cleanup () 126 127 128class HookLock : 129"""A run lock that calls a hook right after it is released: the successor is then free to take the replica at the 130exact moment the real race needs (before the previous request's child generator has been finalized).""" 131 132def __init__ (self ): 133self ._lock = threading .Lock () 134self .after_release = None 135 136def acquire (self ,* a ,** k ): 137return self ._lock .acquire (* a ,** k ) 138 139def release (self ): 140self ._lock .release () 141hook ,self .after_release = self .after_release ,None 142if hook is not None : 143hook () 144 145def locked (self ): 146return self ._lock .locked () 147 148 149def collect (gen ,into :list )-> None : 150for t in gen : 151if t is not None : 152into .append (t ) 153 154 155class ReplicaOwnership (FakeEngines ,unittest .TestCase ): 156"""#2892: an unbatched replica takes one request at a time under its run lock. The lock must cover the previous 157request's whole native exchange (STOP, DONE), and the DONE statistics must belong to the request that read them.""" 158 159def setUp (self ): 160self .engines = self .make_engines (2 ) 161self .rep = ReplicaEngine (self .engines ) 162self .rep .heal = lambda :None 163self .engines [1 ].ended = True # only replica 0 is alive: every request goes to it 164self .lock = HookLock () 165self .rep .run_locks [0 ]= self .lock 166 167def tearDown (self ): 168self .cleanup_engines () 169 170def wait_reading (self ,engine ,timeout = 5.0 ): 171"""True once some thread waits on the engine's line queue (the successor sent its GEN and reads).""" 172end = time .monotonic ()+ timeout 173while time .monotonic ()< end : 174if engine .lines .not_empty ._waiters : 175return True 176time .sleep (0.001 ) 177return False 178 179def run_handoff (self ,a_can ,b_can ,hold_s ): 180"""A reads two tokens and its consumer closes it; B takes the replica the moment the lock is free and reads 181for `hold_s` seconds before A's child is finalized (so A's tokens are already in the line queue).""" 182a_got ,b_got = [], [] 183threads = [] 184 185def successor (): 186def run (): 187collect (self .rep .generate (prompt_ids (b_can ),500 , {},threading .Event ()),b_got ) 188t = threading .Thread (target = run ,daemon = True ) 189threads .append (t ) 190t .start () 191self .wait_reading (self .engines [0 ]) 192time .sleep (hold_s ) 193self .lock .after_release = successor 194gen_a = self .rep .generate (prompt_ids (a_can ),500 , {},threading .Event ()) 195for t in gen_a : 196if t is not None : 197a_got .append (t ) 198if len (a_got )>= 2 : 199break 200gen_a .close ()# what Service does on a stop token, a stop string or a disconnect 201del gen_a 202threads [0 ].join (30 ) 203self .assertFalse (threads [0 ].is_alive ()) 204return a_got ,b_got 205 206def test_a_successor_never_reads_the_predecessors_done (self ): 207"""#2892: B is the next request on the replica and A's DONE is still unread.""" 208a_can ,b_can = "QA0001" ,"QB0002" 209a_got ,b_got = self .run_handoff (a_can ,b_can ,0 ) 210self .assertEqual (foreign (a_got ,a_can ), []) 211self .assertEqual (foreign (b_got ,b_can ), [],"B received A's tokens" ) 212self .assertEqual (b_got ,expected_reply (b_can ),"B's own reply is complete and exactly its own" ) 213 214def test_a_successor_never_reads_the_predecessors_tokens (self ): 215"""#2892: A's remaining tokens are already queued when B reads.""" 216a_can ,b_can = "QA0011" ,"QB0012" 217a_got ,b_got = self .run_handoff (a_can ,b_can ,0.08 ) 218self .assertEqual (foreign (b_got ,b_can ), [],"B received A's tokens" ) 219self .assertEqual (b_got ,expected_reply (b_can ),"B's own reply is complete and exactly its own" ) 220 221def test_many_forced_handoffs_never_cross (self ): 222"""The forced schedule above, 30 times with different hold times and different cut-off points.""" 223import random 224rnd = random .Random (2892 ) 225bad = [] 226for i in range (30 ): 227a_can ,b_can = f"QA { i :04d } " ,f"QB { i :04d } " 228self .lock .after_release = None 229cut = rnd .choice ((1 ,2 ,3 ,10 ,40 )) 230hold = rnd .choice ((0 ,0.002 ,0.01 ,0.05 )) 231a_got ,b_got = [], [] 232threads = [] 233 234def successor (b_can = b_can ,b_got = b_got ,hold = hold ,threads = threads ): 235t = threading .Thread (target = lambda :collect ( 236self .rep .generate (prompt_ids (b_can ),500 , {},threading .Event ()),b_got ),daemon = True ) 237threads .append (t ) 238t .start () 239self .wait_reading (self .engines [0 ]) 240time .sleep (hold ) 241self .lock .after_release = successor 242gen_a = self .rep .generate (prompt_ids (a_can ),500 , {},threading .Event ()) 243for t in gen_a : 244if t is not None : 245a_got .append (t ) 246if len (a_got )>= cut : 247break 248gen_a .close () 249del gen_a 250threads [0 ].join (30 ) 251if foreign (b_got ,b_can )or b_got != expected_reply (b_can ): 252bad .append ((i ,cut ,hold ,len (b_got ),foreign (b_got ,b_can )[:2 ])) 253self .assertEqual (bad , [],f" { len ( bad ) } of 30 handoffs crossed" ) 254 255def test_unforced_back_to_back_requests_never_cross (self ): 256"""No hook: B waits for the replica's lock while A is cut off at a random token; 60 repetitions.""" 257import random 258rnd = random .Random (4451 ) 259self .rep .run_locks [0 ]= threading .Lock () 260bad = [] 261for i in range (60 ): 262a_can ,b_can = f"QA { i :04d } " ,f"QB { i :04d } " 263cut = rnd .choice ((1 ,2 ,3 ,5 ,20 ,100 )) 264a_got ,b_got = [], [] 265go = threading .Event () 266tb = threading .Thread (target = lambda : (go .wait (),collect ( 267self .rep .generate (prompt_ids (b_can ),500 , {},threading .Event ()),b_got )),daemon = True ) 268tb .start () 269gen_a = self .rep .generate (prompt_ids (a_can ),500 , {},threading .Event ()) 270for t in gen_a : 271if t is not None : 272a_got .append (t ) 273if len (a_got )>= cut : 274break 275go .set () 276gen_a .close () 277del gen_a 278tb .join (30 ) 279if foreign (b_got ,b_can )or b_got != expected_reply (b_can ): 280bad .append ((i ,cut ,len (b_got ),foreign (b_got ,b_can )[:2 ])) 281self .assertEqual (bad , [],f" { len ( bad ) } of 60 crossed" ) 282 283def test_the_figures_of_a_request_are_its_own (self ): 284"""A runs to its max_tokens; before A's caller reads its DONE figures, B runs to completion on the replica.""" 285a_can ,b_can = "QA0003" ,"QB0004" 286done = [] 287 288def successor (): 289def run (): 290collect (self .rep .generate (prompt_ids (b_can ,40 ),25 , {},threading .Event ()), []) 291t = threading .Thread (target = run ,daemon = True ) 292t .start () 293t .join (30 ) 294done .append (t ) 295self .lock .after_release = successor 296got = [] 297collect (self .rep .generate (prompt_ids (a_can ),10 , {},threading .Event ()),got ) 298self .assertTrue (done ,"the successor ran" ) 299last = self .rep .last 300self .assertEqual (last .get ("generated" ),10 ,last ) 301self .assertEqual (last .get ("prompt_tokens" ),len (prompt_ids (a_can )),last ) 302 303def test_an_undrainable_replica_is_not_handed_to_the_next_request (self ): 304"""The child cannot be drained (the engine never answers STOP): the replica is ended, not reused.""" 305from serve .server import EngineSilent 306a_can = "QA0005" 307engine = self .engines [0 ] 308engine .silence_s = 1.0 309gen_a = self .rep .generate (prompt_ids (a_can ),500 , {},threading .Event ()) 310got = [] 311for t in gen_a : 312if t is not None : 313got .append (t ) 314if len (got )>= 2 : 315break 316engine .can_stop = True 317# the engine stops answering: its process is frozen 318import os 319import signal 320if hasattr (signal ,"SIGSTOP" ): 321os .kill (engine .proc .pid ,signal .SIGSTOP ) 322else : 323self .skipTest ("needs SIGSTOP to freeze the fake engine" ) 324try : 325try : 326gen_a .close () 327except EngineSilent : 328pass 329finally : 330if engine .proc .poll ()is None : 331os .kill (engine .proc .pid ,signal .SIGCONT ) 332self .assertFalse (engine .alive (),"the replica that could not be drained is out of the routing" ) 333self .assertFalse (self .lock .locked (),"and its run lock is free" ) 334self .assertEqual (self .rep .route (prompt_ids ("QA0006" )),- 1 ) 335 336 337class Client (threading .Thread ): 338"""One streaming client of a --batch engine: its own canary, its own cancel Event. `pause_after`/`resume`: the 339consumer stops reading after that many tokens until `resume` is set (a slow reader).""" 340 341def __init__ (self ,engine ,canary ,filler = 0 ,max_new = 500 ,pause_after = None ,resume = None ,extra = "" ,leave_after_beats = None ): 342super ().__init__ (daemon = True ) 343self .leave_after_beats = leave_after_beats # close the stream (as Service does) at this PP heartbeat 344self .engine ,self .canary = engine ,canary 345self .ids = prompt_ids (canary + extra ,filler ) 346self .max_new ,self .pause_after ,self .resume = max_new ,pause_after ,resume 347self .cancel = threading .Event () 348self .tokens ,self .error ,self .paused = [],None ,threading .Event () 349 350def run (self ): 351beats = 0 352gen = self .engine .generate (self .ids ,self .max_new , {},self .cancel ) 353try : 354for t in gen : 355if t is None : 356beats += 1 357if self .leave_after_beats is not None and beats >= self .leave_after_beats : 358gen .close ()# the consumer leaves: GeneratorExit inside the engine's request 359return 360continue 361self .tokens .append (t ) 362if self .pause_after is not None and len (self .tokens )== self .pause_after : 363self .paused .set () 364self .resume .wait (30 ) 365except BaseException as e :# noqa: BLE001 366self .error = e 367 368def foreign (self ): 369return foreign (self .tokens ,self .canary ) 370 371def complete (self ): 372return self .tokens == expected_reply (self .canary ) 373 374 375def wait_until (cond ,timeout = 10.0 ): 376end = time .monotonic ()+ timeout 377while time .monotonic ()< end : 378if cond (): 379return True 380time .sleep (0.005 ) 381return False 382 383 384class BatchOwnership (FakeEngines ,unittest .TestCase ): 385"""#4451: a --batch engine. Every frame a request reads must be its own, whatever happened to the requests before 386it on the same slot, the same control lines or the same engine process.""" 387 388def setUp (self ): 389self .engines = self .make_engines (1 ,batch = 4 ) 390self .engine = self .engines [0 ] 391# 0.3 s instead of 300 s for the wait that ends an interrupted exchange (a wrapper that works on every version) 392orig = self .engine ._drain_control 393self .engine ._drain_control = lambda until ,timeout = None ,born = None ,lines_q = None :orig ( 394until ,timeout = 0.3 if timeout is None else timeout ,born = born , 395** ({}if lines_q is None else {"lines_q" :lines_q })) 396self .engine .QUARANTINE_S = 8.0 397 398def tearDown (self ): 399self .cleanup_engines () 400 401def start_busy (self ,n = 1 ,tag = "Y" ): 402"""Long requests that hold batch slots, so that the next requests are admitted into slots too.""" 403bg = [Client (self .engine ,f" { chr ( ord ( tag ) + i ) } B { 9990 - i :04d } " ,max_new = 500 )for i in range (n )] 404for c in bg : 405c .start () 406time .sleep (0.05 ) 407wait_until (lambda :all (len (c .tokens )>= 3 for c in bg )) 408return bg 409 410def finish (self ,clients ,timeout = 60 ): 411for c in clients : 412c .join (timeout ) 413self .assertFalse (c .is_alive ()) 414 415def test_interleaved_clients_get_their_own_replies (self ): 416cs = [Client (self .engine ,f" { chr ( ord ( 'A' ) + i ) } { chr ( ord ( 'K' ) + i ) } { i :04d } " )for i in range (4 )] 417for c in cs : 418c .start () 419time .sleep (0.02 ) 420self .finish (cs ) 421for c in cs : 422self .assertIsNone (c .error ) 423self .assertEqual (c .foreign (), []) 424self .assertTrue (c .complete (),c .canary ) 425 426def test_a_cancel_in_the_middle_of_the_prompt_read_then_reuse (self ): 427"""The first of several interleaved clients is cancelled while its prompt is being read; the next requests 428reuse the slot and the control lines and must read only their own frames.""" 429import random 430rnd = random .Random (4451 ) 431bg = self .start_busy (n = 2 ) 432bad = [] 433for i in range (12 ): 434a = Client (self .engine ,f"KA { i :04d } " ,filler = 700 ,extra = " SLOWPREFILL" ) 435a .start () 436time .sleep (rnd .choice ((0.03 ,0.08 ,0.15 ,0.3 ))) 437a .cancel .set () 438followers = [Client (self .engine ,f" { chr ( ord ( 'M' ) + j ) } { chr ( ord ( 'Q' ) + j ) } { i :02d } { j :02d } " ,max_new = 60 ) 439for j in range (2 )] 440for f in followers : 441f .start () 442self .finish ([a ]+ followers ) 443for f in followers : 444if f .error or f .foreign ()or f .tokens != expected_reply (f .canary )[:60 ]: 445bad .append ((i ,f .canary ,repr (f .error ),f .foreign ()[:2 ],len (f .tokens ))) 446self .assertEqual (a .foreign (), []) 447for c in bg : 448c .cancel .set () 449self .finish (bg ) 450for c in bg : 451self .assertEqual (c .foreign (), [],"a background request received a foreign frame" ) 452self .assertEqual (bad , []) 453 454def test_a_drain_that_times_out_does_not_leak_into_the_next_request (self ): 455"""A leaves (its stream is closed, as Service does) in the middle of its prompt read; the engine says nothing for 456longer than the drain limit (SILENTREAD, DEAFSTOP: ~1 s of silence, then its DONE and BADM). The control lines stay 457with A's exchange until they come; the request after it gets its own frames only.""" 458bg = self .start_busy (n = 1 ) 459a = Client (self .engine ,"KA0001" ,filler = 1300 ,extra = " DEAFSTOP SILENTREAD" ,leave_after_beats = 1 ) 460a .start () 461time .sleep (0.6 )# past the 0.3 s drain: A's request has left, its engine exchange has not ended 462# (B's prompt is not under half of A's: a much shorter waiting request would make A give way, BYIELD, at once) 463b = Client (self .engine ,"LB0002" ,filler = 900 ,max_new = 80 ) 464b .start () 465self .finish ([a ,b ]) 466for c in bg : 467c .cancel .set () 468self .finish (bg ) 469self .assertIsNone (b .error ) 470self .assertEqual (b .foreign (), [],"B received A's frames" ) 471self .assertEqual (b .tokens ,expected_reply ("LB0002" )[:80 ],"B's reply is its own, in full" ) 472self .assertEqual (bg [0 ].foreign (), []) 473self .assertTrue (self .engine .alive ()) 474 475def test_an_engine_that_keeps_talking_after_a_stop_is_not_given_up_on (self ): 476"""The limits count silence, never a read or a decode that still produces lines: the engine takes ~1.8 s to end A's 477exchange (DEAFSTOP, a PP line every chunk) with the drain at 0.3 s and the quarantine at 0.4 s. A limit counted 478from the start would have ended the engine at ~0.7 s, with the other requests in it.""" 479self .engine .QUARANTINE_S = 0.4 480gen_before = self .engine .gen 481bg = self .start_busy (n = 1 ) 482a = Client (self .engine ,"KA0001" ,filler = 2600 ,extra = " DEAFSTOP" ,leave_after_beats = 1 ) 483a .start () 484time .sleep (0.1 ) 485b = Client (self .engine ,"LB0002" ,filler = 1500 ,max_new = 80 )# (not under half of A's prompt: no BYIELD) 486b .start () 487self .finish ([a ,b ],timeout = 60 ) 488self .assertEqual (self .engine .gen ,gen_before ,"the engine was ended although it kept talking" ) 489self .assertTrue (self .engine .alive ()) 490self .assertIsNone (b .error ) 491self .assertEqual (b .tokens ,expected_reply ("LB0002" )[:80 ]) 492self .assertEqual (bg [0 ].foreign (), []) 493self .assertIsNone (bg [0 ].error ,"a request running in another slot was ended with the engine" ) 494bg [0 ].cancel .set () 495self .finish (bg ) 496 497def test_an_engine_that_goes_silent_after_a_stop_is_ended (self ): 498"""The other side of the limit: no line at all for DRAIN_TIMEOUT_S + QUARANTINE_S after the stop (here 0.3 + 0.4 s, 499the read is silent for ~1.8 s) is a wedged engine: it is ended and the next request starts it again.""" 500self .engine .QUARANTINE_S = 0.4 501a = Client (self .engine ,"KA0001" ,filler = 2600 ,extra = " DEAFSTOP SILENTREAD" ,leave_after_beats = 1 ) 502a .start () 503self .assertTrue (wait_until (lambda :not self .engine .alive (),8.0 ),"a silent engine was not ended" ) 504self .finish ([a ]) 505 506def test_the_engine_ending_during_a_drain_then_a_restart (self ): 507"""A is interrupted mid-prompt; the engine dies while A drains; after the restart the new requests (same slot 508numbers) must never be read by a request of the old process.""" 509old = self .start_busy (n = 2 ) 510slow = [Client (self .engine ,f" { chr ( ord ( 'S' ) + i ) } { chr ( ord ( 'T' ) + i ) } { i :04d } " ,pause_after = 3 , 511resume = threading .Event ())for i in range (2 )] 512for c in slow : 513c .start () 514time .sleep (0.05 ) 515self .assertTrue (wait_until (lambda :all (c .paused .is_set ()for c in slow ))) 516a = Client (self .engine ,"KA0001" ,filler = 700 ,extra = " SLOWPREFILL" ) 517a .start () 518time .sleep (0.1 ) 519a .cancel .set () 520self .engine .proc .kill ()# the engine ends while A's exchange is being drained 521self .engine .proc .wait () 522self .finish ([a ]+ old ) 523self .engine .restart () 524self .assertTrue (self .engine .alive ()) 525new = self .start_busy (n = 2 ,tag = "D" )# the new process: the same slot numbers again 526for c in slow : 527c .resume .set () 528# they read on: the old process's queued frames, then its end - never the new process's frames 529time .sleep (1.0 ) 530for c in slow : 531self .assertEqual (c .foreign (), [],f" { c . canary } (old process) read a frame of the new one" ) 532for c in new : 533c .cancel .set () 534self .finish (new ) 535self .finish (slow ) 536for c in slow : 537self .assertIsInstance (c .error ,Exception ,"a request of the dead engine ends with an error" ) 538for c in new : 539self .assertEqual (c .foreign (), [],"a request of the new process received a foreign frame" ) 540self .assertTrue (len (c .tokens )>= 3 ) 541 542def test_long_generations_are_never_cut_by_the_drain_limits (self ): 543"""The drain and quarantine limits (here 0.3 s and 0.4 s, far below a reply's ~1.7 s) apply after a STOP or BSTOP 544only: replies that are still streaming complete.""" 545self .engine .QUARANTINE_S = 0.4 546cs = [Client (self .engine ,f" { chr ( ord ( 'A' ) + i ) } { chr ( ord ( 'K' ) + i ) } { i :04d } " )for i in range (4 )] 547for c in cs : 548c .start () 549time .sleep (0.05 ) 550self .finish (cs ) 551for c in cs : 552self .assertIsNone (c .error ) 553self .assertTrue (c .complete (),c .canary ) 554 555def test_vram_and_session_file_take_the_control_lines_like_a_request (self ): 556"""VRAM and SAVE read the control lines for their answer. Run beside a request that holds them (its solo read 557or an admission), they took that request's T / PP / DONE lines and it lost its reply.""" 558for what in ("vram" ,"save" ,"restore" ): 559a = Client (self .engine ,"KA0001" ) 560a .start () 561self .assertTrue (wait_until (lambda :len (a .tokens )>= 3 )) 562answers = [] 563 564def call (what = what ): 565try : 566if what == "vram" : 567answers .append (self .engine .vram (None )) 568else : 569answers .append (self .engine .session_file (what ,"/tmp/x" )) 570except BaseException as e :# noqa: BLE001 571answers .append (e ) 572t = threading .Thread (target = call ,daemon = True ) 573t .start () 574self .finish ([a ]) 575t .join (30 ) 576self .assertFalse (t .is_alive (),what ) 577self .assertIsNone (a .error ,what ) 578self .assertTrue (a .complete (),f" { what } : the request lost lines to the VRAM / session call " 579f"( { len ( a . tokens ) } of { len ( expected_reply ( 'KA0001' )) } tokens)" ) 580self .assertIsInstance (answers [0 ],dict ,answers ) 581self .assertEqual (answers [0 ].get ("vram_free_mib" )if what == "vram" else answers [0 ].get ("tokens" ), 582100 if what == "vram" else 1 ) 583 584def test_a_slot_is_not_handed_on_before_the_engine_confirms (self ): 585"""A consumer leaves a slot's stream; its BDONE has not come. Whatever frames still arrive for that slot are 586not the next request's.""" 587bg = self .start_busy (n = 1 ) 588a = Client (self .engine ,"KA0001" ,max_new = 500 ) 589a .start () 590self .assertTrue (wait_until (lambda :len (a .tokens )>= 5 )) 591a .cancel .set ()# BSTOP: A's slot ends at its next window 592followers = [Client (self .engine ,f" { chr ( ord ( 'M' ) + j ) } { chr ( ord ( 'Q' ) + j ) } { j :04d } " ,max_new = 60 )for j in range (3 )] 593for f in followers : 594f .start () 595self .finish ([a ]+ followers ) 596for f in followers : 597self .assertEqual (f .foreign (), []) 598self .assertEqual (f .tokens ,expected_reply (f .canary )[:60 ]) 599bg [0 ].cancel .set () 600self .finish (bg ) 601 602 603if __name__ == "__main__" : 604unittest .main ()