okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
ddbfa1d5c
main
1"""#465: "parallel": N - several requests decode together in the engine's batch slots (--batch N). 2 3A fake engine (a Python script speaking the engine's GEN / BGEN / BT / BDONE / BADM / BSTOP lines) runs behind the 4real StrataEngine and Service, so the server's side is tested without a GPU: requests up to N run at once, more 5wait for a slot, /metrics shows the slots, each request's history row is its own, and a conversation's next turn 6goes back to the slot that holds it.""" 7import json 8import sys 9import tempfile 10import threading 11import time 12import unittest 13import urllib .error 14import urllib .request 15from pathlib import Path 16from unittest import mock 17 18from serve .frontend import ChatTemplate 19from serve import server 20from serve .server import ByteTokenizer ,Service ,StrataEngine ,engine_args ,parallel_args ,serve 21from strata_cli import bench 22from strata_cli .client import Endpoint 23 24# The fake engine: one token every STEP seconds per active slot (a "window" serves every active slot at once); 25# GEN (solo) streams T lines; BGEN reads the prompt (one T line, DONE), answers BADM and continues in the slot. 26# Every reply is the bytes of "ok, done." then <|im_end|> (ByteTokenizer: 257). 27FAKE_BATCH = r'''import queue, sys, threading, time 28args = sys.argv[1:] 29slots = int(args[args.index("--batch") + 1]) if "--batch" in args else 0 30fit = int(args[args.index("--fit") + 1]) if "--fit" in args else slots 31fail = "--fail-window" in args 32groups = int(args[args.index("--says-groups") + 1]) if "--says-groups" in args else 0 # INFO batch_groups=G (--batch-groups auto) # #997: the first window over two slots fails 33STEP = 0.02 34CH = 32 35BDONE_MS = " 0.0" if "--zero-bdone-ms" in args else " 1.0" 36lines, stop = queue.Queue(), threading.Event() 37def reader(): 38for l in sys.stdin: 39l = l.strip() 40if l == "STOP": 41stop.set() 42else: 43lines.put(l) 44lines.put(None) 45threading.Thread(target=reader, daemon=True).start() 46print("INFO engine=0.1.39" + (f" batch_slots={fit}" if fit >= 2 else "") + 47(" slot_cache=1" if "--slotcache" in args else "") + (f" batch_groups={groups}" if groups > 1 else ""), flush=True) 48if "--fake-stage-plan" in args: 49print("strata serve: layer split: layers 0-11 (CUDA0), 12-23 (CUDA1), 24-35 (CUDA2), " 50"36-47 (CUDA3), one hand-off per window", file=sys.stderr, flush=True) 51print("READY 4096 stop", flush=True) 52LONG = list(b"LONGREPLY") 53def continued(ids): # (the whole reply, how much of it the prompt already ends with: a request continued) 54ids = [int(x) for x in ids] 55long_one = any(ids[i:i + len(LONG)] == LONG for i in range(len(ids))) or \ 56b"Cancellation benchmark:" in bytes(int(x) & 255 for x in ids) 57R = list(b"ok, " + b"la " * 15 + b"done." if long_one else b"ok, done.") + [257] 58return R, max(k for k in range(len(R)) if k == 0 or ids[-k:] == R[:k]) 59def reply(ids): # the rest of the reply after what the prompt already ends with 60R, k = continued(ids) 61return R[k:] 62active = {} # slot -> [tokens left, max_new, produced] 63stopped = set() # BSTOPped slots: they end "cancel" 64# #879: a prompt with NFSOLO / NFADMIT ends its first GEN / BGEN with DONE ... nonfinite (nothing emitted); one with 65# NFSLOT ends its slot with BDONE ... nonfinite after its second token 66fired, nf_slots = set(), set() 67def window(): # one batch window: every active slot one token 68if fail and len(active) >= 2: # as the engine: the reason on stdout, then exit code 1 69print("ERR verify batch: layer 34 never rang (graph finished)", flush=True) 70sys.exit(1) 71processed = len(active) 72for b in sorted(active): 73left, max_new, produced = active[b] 74if b in nf_slots and produced >= 2: 75nf_slots.discard(b) 76print(f"BDONE {b} {produced} nonfinite{BDONE_MS}", flush=True) 77del active[b] 78continue 79t = left.pop(0) if left else 257 80produced += 1 81print(f"BT {b} {t}", flush=True) 82if t == 257 or produced >= max_new: 83fin = 'stop' if t == 257 else 'cancel' if b in stopped else 'length' 84stopped.discard(b) 85print(f"BDONE {b} {produced} {fin}{BDONE_MS}", flush=True) 86del active[b] 87else: 88active[b] = [left, max_new, produced] 89if "--fake-batch-sample" in args and processed and not active: 90print(f"BSTAT 1 {processed} {processed} 20", flush=True) 91if "--fake-stage-sample" in args and processed and not active: 92print("PSTAT 4 20000 16000 14000 12000 10000", flush=True) 93log = open(args[args.index("--log") + 1], "a") if "--log" in args else None 94PPK = int(args[args.index("--pp-every") + 1]) if "--pp-every" in args else 1 95READF = "--readfield" in args # DONE's 15th field: the prompt tokens the engine read (a continued prompt: the 1 it copies) 96REUSE = "--reuse" in args # DONE's reused field as the engine gives it: a continued prompt is all held but its last 97def reused(ids): # token (the request's own output included), a fresh one the first 3 tokens 98return 0 if not REUSE else len(ids) - 1 if continued(ids)[1] else 3 99while True: 100try: 101line = lines.get(timeout=STEP if active else None) 102except queue.Empty: 103line = "" 104if line is None or line == "QUIT": 105break 106if line.startswith("BYIELD "): 107continue # too late: the read it was for has ended 108if line.startswith("BSTOP "): 109b = int(line.split()[1]) 110if b in active: 111active[b][1] = 0 112stopped.add(b) 113continue 114if line.startswith(("GEN ", "BGEN ")): 115f = line.split() 116slot = int(f[1]) if f[0] == "BGEN" else None 117max_new = int(f[2] if f[0] == "BGEN" else f[1]) 118ids = f[-1].split(",") 119if bytes(int(x) & 255 for x in ids).find(b"REFUSEME") >= 0: # #1059: refused up front, then idle (no DONE) 120print("ERR refused: images are not enabled", flush=True) 121continue 122# #1994: the engine's own view of its slots differs: BUSYSLOT is refused once, BUSYALL always 123pbx = bytes(int(x) & 255 for x in ids) 124if slot is not None and (b"BUSYALL" in pbx or (b"BUSYSLOT" in pbx and "busyslot" not in fired)): 125fired.add("busyslot") 126print(f"ERR BGEN: no such free slot (--batch {slots}) or a bad max_new", flush=True) 127if log: 128log.write(f"REFUSED {slot}\n"); log.flush() 129continue 130if log: 131log.write(f"{f[0]} {slot} {len(ids)} {max(len(active), 0)}\n"); log.flush() 132pb = bytes(int(x) & 255 for x in ids) 133mark = b"NFSOLO" if f[0] == "GEN" else b"NFADMIT" 134if mark in pb and mark not in fired: 135fired.add(mark) 136print(f"DONE 0 {len(ids)} 5.0 0.0 nonfinite 0 0 0", flush=True) 137if slot is not None: 138print(f"BADM {slot} 0", flush=True) 139continue 140if slot is not None and b"NFSLOT" in pb: 141nf_slots.add(slot) 142toks = reply(ids) 143stop.clear() 144# the prompt read: CH tokens a chunk, a PP line each; a BYIELD <s> gives way at a chunk boundary 145given = None 146for q in range(CH, len(ids) - 1, CH): 147time.sleep(STEP / 2) 148if (q // CH) % PPK: # --pp-every K: a PP line and a boundary every K chunks (the pipelined groups' pieces) 149continue 150print(f"PP {q} {len(ids)} 1 1", flush=True) 151held = [] 152while True: 153try: 154l2 = lines.get_nowait() 155except queue.Empty: 156break 157if l2 and l2.startswith("BYIELD "): 158ys = int(l2.split()[1]) 159if len(ids) - 1 - q > CH and (slot is None or ys == slot) and given is None: 160given = (ys, q) 161elif l2 == "STOP": 162stop.set() 163else: 164held.append(l2) 165for l2 in held: 166lines.put(l2) 167if given: 168break 169if stop.is_set(): 170break 171if active and (q // CH) % 4 == 0: # the slots decode between the prompt's chunks (as the engine) 172window() 173if given: 174if log: 175log.write(f"YIELD {given[0]} {given[1]}\n"); log.flush() 176print(f"YIELDED {given[0]} {given[1]}", flush=True) 177print(f"DONE 0 {len(ids)} 5.0 0.0 cancel 0 0 {reused(ids)}", flush=True) 178if slot is not None: 179print(f"BADM {slot} 0", flush=True) 180continue 181n = 1 if slot is not None else max_new 182out = 0 183for t in toks[:n]: 184if stop.is_set(): 185break 186print(f"T {t}", flush=True) 187out += 1 188time.sleep(STEP) 189fin = "stop" if out and toks[out - 1] == 257 else ("cancel" if stop.is_set() else "length") 190print(f"DONE {out} {len(ids)} 5.0 {out * STEP * 1000:.1f} {fin} 0 0 {reused(ids)}" + 191(f" 0 0 0 0 0.0 {len(ids) - reused(ids)}" if READF else ""), flush=True) 192if slot is not None: 193cont = fin == "length" and max_new > 1 194if cont: 195active[slot] = [toks[1:], max_new, 1] 196print(f"BADM {slot} {1 if cont else 0}", flush=True) 197continue 198if line: 199print("ERR unknown " + line[:20], flush=True) 200continue 201window() 202''' 203 204 205class ParallelArgs (unittest .TestCase ): 206def test_parallel_config_key (self ): 207self .assertEqual (parallel_args ({"parallel" :4 }, []), ["--batch" ,"4" ]) 208self .assertEqual (parallel_args ({"parallel" :1 }, []), []) 209self .assertEqual (parallel_args ({}, []), []) 210self .assertEqual (parallel_args ({"parallel" :2 }, ["--batch" ,"3" ]), [])# the args' own value wins 211self .assertEqual (parallel_args ({"parallel" :"4" }, []), [])# said and ignored 212self .assertEqual (parallel_args ({"parallel" :True }, []), []) 213self .assertEqual (parallel_args ({"parallel" :12 }, []), ["--batch" ,"12" ])# the engine warns and caps 214def test_parallel_above_the_window_says_so_unless_batch_mtp (self ): 215import contextlib ,io ,os 216def said (args ,env ): 217buf = io .StringIO () 218old = os .environ .get ("STRATA_BATCH_MTP" ) 219if env is None : 220os .environ .pop ("STRATA_BATCH_MTP" ,None ) 221else : 222os .environ ["STRATA_BATCH_MTP" ]= env 223try : 224with contextlib .redirect_stdout (buf ): 225r = parallel_args ({"parallel" :12 },args ) 226finally : 227if old is None : 228os .environ .pop ("STRATA_BATCH_MTP" ,None ) 229else : 230os .environ ["STRATA_BATCH_MTP" ]= old 231self .assertEqual (r , ["--batch" ,"12" ]) 232return "at most" in buf .getvalue () 233self .assertTrue (said ([],None ))# 0.1.39: the window holds 8 rows 234self .assertTrue (said ([],"0" )) 235self .assertFalse (said (["--batch-mtp" ],None ))# --batch-mtp waves more through the window 236self .assertFalse (said ([],"1" )) 237 238args = engine_args ({"args" : ["--pack" ,"p" ],"parallel" :2 }) 239self .assertEqual (args [- 2 :], ["--batch" ,"2" ]) 240 241 242class DFlash2ChosenWithRequests (unittest .TestCase ): 243"""Owner 2026-11-03: the person's own choice wins. DFlash2 chosen by name + a number of requests = `--draft dflash2 --draft-fallback none --batch N` (the engine runs a 244drafter per request); DFlash2 alone = one request; Auto and the MTP are as they were. Nothing is started: the arguments the server builds.""" 245 246BASE = ["--pack" ,"/d/packs/x" ,"--native" ,"/m/x.gguf" ,"--mtp" ,"/d/mtp/rt" ,"--spec" ,"4" ,"--spec-min-p" ,"0.5" ,"--batch-mtp" ] 247 248def build (self ,** cfg ): 249import contextlib 250import io 251from strata_control import drafting 252shaped = {"model_name" :"qwen3.8-flash-next-gyro-gyro-s" ,"args" :list (self .BASE ),** cfg } 253patches = (mock .patch .object (drafting ,"detect_hardware" ,return_value = ("cuda" , ["sm_120" ])),mock .patch .object (drafting ,"pack_ready" ,return_value = True ), 254mock .patch .object (drafting ,"vocab_path" ,return_value = Path ("/d/draft_vocab.bin" )),mock .patch .object (drafting ,"mtp_ready" ,return_value = True ), 255mock .patch ("serve.server.drafting_vram_mib" ,return_value = None ),contextlib .redirect_stdout (io .StringIO ())) 256with contextlib .ExitStack ()as stack : 257for patch in patches : 258stack .enter_context (patch ) 259args = engine_args (shaped ,None ) 260return args ,drafting .take_note () 261 262def value (self ,args ,flag ): 263return args [args .index (flag )+ 1 ]if flag in args else None 264 265def test_dflash2_by_name_with_a_number_of_requests_runs_dflash2_with_that_many (self ): 266for n in (2 ,4 ,8 ): 267args ,note = self .build (drafting = "dflash2" ,parallel = n ) 268self .assertEqual ((self .value (args ,"--draft" ),self .value (args ,"--draft-fallback" ),self .value (args ,"--batch" )), ("dflash2" ,"none" ,str (n )),n ) 269self .assertNotIn ("--mtp" ,args ) 270self .assertNotIn ("--batch-mtp" ,args ) 271self .assertEqual (note ,"" ,"no 'isn't available in this mode' line where DFlash2 now runs" ) 272 273def test_the_number_in_the_saved_arguments_is_the_same_word (self ): 274args ,note = self .build (drafting = "dflash2" ,args = [* self .BASE ,"--batch" ,"4" ]) 275self .assertEqual ((self .value (args ,"--draft" ),self .value (args ,"--batch" ),args .count ("--batch" )), ("dflash2" ,"4" ,1 )) 276self .assertEqual (note ,"" ) 277 278def test_dflash2_by_name_without_a_number_is_one_request (self ): 279for extra in ({}, {"parallel" :1 }): 280args ,note = self .build (drafting = "dflash2" ,** extra ) 281self .assertEqual (self .value (args ,"--draft" ),"dflash2" ,extra ) 282self .assertNotIn ("--batch" ,args ) 283self .assertEqual (note ,"" ) 284 285def test_auto_with_several_requests_keeps_the_mtp (self ): 286args ,note = self .build (parallel = 4 ) 287self .assertNotIn ("--draft" ,args ) 288self .assertEqual ((self .value (args ,"--mtp" ),self .value (args ,"--batch" )), ("/d/mtp/rt" ,"4" )) 289self .assertEqual (note ,"DFlash2 isn't available in this mode" ) 290args ,note = self .build (drafting = "auto" ,parallel = 4 ) 291self .assertNotIn ("--draft" ,args ) 292 293def test_the_mtp_by_name_is_unchanged (self ): 294args ,note = self .build (drafting = "mtp" ,parallel = 4 ) 295self .assertNotIn ("--draft" ,args ) 296self .assertEqual ((self .value (args ,"--mtp" ),self .value (args ,"--batch" ),note ), ("/d/mtp/rt" ,"4" ,"" )) 297 298def test_a_layer_split_runs_it_too (self ): 299args ,note = self .build (drafting = "dflash2" ,parallel = 4 ,gpu = [0 ,1 ]) 300self .assertEqual ((self .value (args ,"--draft" ),self .value (args ,"--batch" ),"--layer-split" in args ,note ), ("dflash2" ,"4" ,True ,"" )) 301args ,note = self .build (parallel = 4 ,gpu = [0 ,1 ]) 302self .assertNotIn ("--draft" ,args )# Auto: still the MTP for several requests 303 304def test_the_all_cards_split_engine_run_config_keeps_its_dflash2_flags_and_the_persons_lanes (self ): 305split = ["--native" ,"/m/x.gguf" ,"--draft" ,"dflash2" ,"--draft-model" ,"/d/p.pack" ,"--draft-vocab" ,"/e/draft_vocab_en.bin" ,"--max-context" ,"131072" , 306"--spec" ,"6" ,"--lookup" ,"15" ,"--conversation-cache-mib" ,"4096" ,"--batch" ,"6" ] 307args ,note = self .build (args = list (split ),drafting = "dflash2" ,split_engine_note = "Using the all-cards split engine on 2 cards." ,gpu = [0 ,1 ],parallel = 3 ) 308self .assertEqual (args [:len (split )- 2 ],split [:- 2 ],"nothing added or taken out" ) 309self .assertEqual ((self .value (args ,"--batch" ),"--mtp" in args ,"--draft-fallback" in args ,note ), ("3" ,False ,False ,"" )) 310args ,_ = self .build (args = list (split ),drafting = "dflash2" ,split_engine_note = "x" ,gpu = [0 ,1 ]) 311self .assertEqual (self .value (args ,"--batch" ),"6" ) 312 313 314class PickSlot (unittest .TestCase ): 315def engine (self ,n ): 316e = StrataEngine ("missing-executable" , [],lazy = True ) 317e .batch = n 318e .slot_order = list (range (n )) 319e .slot_busy = [False ]* n 320e .slot_held = [[]for _ in range (n )] 321e .slot_used = [0.0 ]* n 322e .slot_live = [None ]* n 323e .slot_group = [0 ]* n 324return e 325 326def test_the_slot_that_holds_the_conversation (self ): 327e = self .engine (3 ) 328e .slot_held = [[1 ,2 ,3 ], [], [1 ,2 ,3 ,4 ,5 ]] 329e .slot_used = [5.0 ,0.0 ,9.0 ] 330self .assertEqual (e .pick_slot ([1 ,2 ,3 ,4 ,5 ,6 ]),2 )# the longest held start 331self .assertEqual (e .pick_slot ([1 ,2 ,3 ,9 ]),0 ) 332self .assertEqual (e .pick_slot ([7 ,8 ]),1 )# no match: the empty slot first 333e .slot_busy [1 ]= True 334self .assertEqual (e .pick_slot ([7 ,8 ]),0 )# then the one used longest ago 335e .slot_busy = [True ]* 3 336self .assertIsNone (e .pick_slot ([7 ,8 ])) 337e .slot_busy = [False ]* 3 338self .assertEqual (e .pick_slot ([1 ,2 ,3 ]),1 )# a held prompt is never the WHOLE prompt 339 340def test_a_rewritten_next_turn_goes_to_the_slot_of_its_chat (self ): 341# #2518: two chats in two slots; each next turn renders the history again but not the reply it decoded or the 342# assistant header, so the held stream (prompt + reply) is no start of it. The engine's turn checkpoint sits at 343# the last <|im_start|> of the old prompt: the prompt that agrees up to there belongs to that slot. Before, both 344# went to the least recently used slot in turn, and the first one overwrote the other chat's cache. 345T = StrataEngine .TURN_ID 346hist_a ,hist_b = list (range (1000 ,1600 )),list (range (2000 ,2600 )) 347held_a = hist_a + [T ,7 ,8 ,9 ]+ [50 ,51 ,52 ]# prompt (ends with the assistant header) + reply 348held_b = hist_b + [T ,7 ,8 ,9 ]+ [60 ,61 ] 349e = self .engine (2 ) 350e .slot_held = [held_a ,held_b ] 351e .slot_used = [10.0 ,20.0 ]# slot 0 was used longer ago 352next_a = hist_a + [T ,5 ,6 ,7 ,8 ,9 ]+ list (range (3000 ,3100 ))# the history again, then new turns 353next_b = hist_b + [T ,5 ,6 ,7 ,8 ,9 ]+ list (range (3000 ,3100 )) 354self .assertEqual (e .pick_slot (next_b ),1 )# the LRU slot 0 holds the other chat 355self .assertEqual (e .pick_slot (next_a ),0 ) 356e .slot_busy [0 ]= True # a busy slot is never picked 357self .assertEqual (e .pick_slot (next_a ),1 ) 358e .slot_busy [0 ]= False 359# a chat that agrees with neither (a new one, or one that rewrote its history) keeps the old order 360self .assertEqual (e .pick_slot (list (range (5000 ,5200 ))),0 ) 361self .assertEqual (e .pick_slot (hist_a [:300 ]+ [T ,5 ,6 ]+ list (range (3000 ,3100 ))),0 ) 362e .slot_held [0 ]= []# an empty slot still comes before evicting one 363self .assertEqual (e .pick_slot (list (range (5000 ,5200 ))),0 ) 364# the whole held stream continued is still the longer match 365e .slot_held = [held_a ,held_b + [T ,1 ,2 ]] 366self .assertEqual (e .pick_slot (held_b + [T ,1 ,2 ,3 ,4 ]),1 ) 367 368# ---- #2518: a branching follow-up (same history, the last question replaced) belongs to the slot of its chat 369@staticmethod 370def chat (base ,turns = 12 ,per = 800 ): 371"""A chat history of `turns` messages of `per` tokens each (every one opens with the turn marker), token ids 372distinct from any other chat's; ~9600 tokens, so its earlier message boundaries are past 8192.""" 373T = StrataEngine .TURN_ID 374out = [] 375for m in range (turns ): 376out += [T ]+ list (range (base + m * per ,base + m * per + per - 1 )) 377return out 378 379def held_of (self ,hist ,q ,reply ): 380"""what a slot holds after a request: the prompt (history, the question, the assistant header) and the reply""" 381T = StrataEngine .TURN_ID 382return hist + [T ]+ q + [T ,7 ,8 ,9 ]+ reply 383 384def branch_of (self ,hist ,q ): 385T = StrataEngine .TURN_ID 386return hist + [T ]+ q + [T ,7 ,8 ,9 ] 387 388def test_a_branch_goes_to_its_earlier_message_boundary (self ): 389T = StrataEngine .TURN_ID 390hists = [self .chat (100000 * (i + 1 ))for i in range (4 )] 391e = self .engine (4 ) 392e .slot_held = [self .held_of (h , [31 ,32 ,33 ], [50 ,51 ])for h in hists ] 393e .slot_used = [1.0 ,2.0 ,3.0 ,4.0 ]# slot 0 is the least recently used 394for owner in (1 ,2 ,3 ,0 ): 395branch = self .branch_of (hists [owner ], [61 ,62 ,63 ,64 ])# another final question, the same history 396self .assertEqual (e .pick_slot (branch ),owner ,owner ) 397# a pure append of the held stream and the engine's own turn rule are unchanged 398self .assertEqual (e .pick_slot (e .slot_held [2 ]+ [T ,1 ,2 ,3 ]),2 ) 399self .assertEqual (e .pick_slot (self .branch_of (hists [1 ], [31 ,32 ,33 ])),1 ) 400 401def test_a_branch_never_takes_a_busy_owner (self ): 402hists = [self .chat (100000 * (i + 1 ))for i in range (3 )] 403e = self .engine (3 ) 404e .slot_held = [self .held_of (h , [31 ], [50 ])for h in hists ] 405e .slot_used = [1.0 ,2.0 ,3.0 ] 406e .slot_busy [1 ]= True # the owner is still working 407self .assertEqual (e .pick_slot (self .branch_of (hists [1 ], [61 ,62 ])),0 )# the old order: the least recent free slot 408e .slot_busy = [True ,False ,True ] 409self .assertEqual (e .pick_slot (self .branch_of (hists [1 ], [61 ,62 ])),1 ) 410 411def test_a_boundary_every_chat_shares_is_no_owner (self ): 412# one client's chats share a long system prompt: its end is a boundary every slot agrees on, so it names 413# nobody; a new chat keeps the empty slot, then the least recent one 414T = StrataEngine .TURN_ID 415root = self .chat (500000 ,turns = 11 )# ~8800 shared tokens 416e = self .engine (4 ) 417e .slot_held = [self .held_of (root + self .chat (100000 * (i + 1 ),turns = 1 ), [31 ], [50 ])for i in range (3 )]+ [[]] 418e .slot_used = [5.0 ,6.0 ,7.0 ,0.0 ] 419new_chat = root + [T ]+ list (range (900000 ,900100 ))+ [T ,7 ,8 ,9 ] 420self .assertEqual (e .pick_slot (new_chat ),3 )# the empty slot 421e .slot_held [3 ]= self .held_of (root + self .chat (400000 ,turns = 1 ), [31 ], [50 ]) 422e .slot_used [3 ]= 8.0 423self .assertEqual (e .pick_slot (new_chat ),0 )# then the least recently used 424 425def test_interleaved_branches_keep_their_prefixes (self ): 426# four chats in four slots, then three rounds of branching follow-ups in an interleaved order; the engine finds 427# the best source among ALL slots (copying it into the slot pick_slot chose, overwriting that one), so a 428# follow-up keeps its prefix only while its chat's slot was not overwritten. Measured: the tokens reused. 429def old_pick (e ,prompt ): 430T = StrataEngine .TURN_ID 431free = [b for b in e .slot_order if not e .slot_busy [b ]] 432def hp (b ): 433h = e .slot_held [b ] 434if not h : 435return 0 436if len (h )< len (prompt )and prompt [:len (h )]== h : 437return len (h ) 438k = len (h )- 1 - h [::- 1 ].index (T )if T in h else 0 439return k if 0 < k < len (prompt )and prompt [:k ]== h [:k ]else 0 440best = max (free ,key = hp ) 441if hp (best )>= 1 : 442return best 443return min (free ,key = lambda b : (bool (e .slot_held [b ]),e .slot_used [b ])) 444 445def run (pick ): 446T = StrataEngine .TURN_ID 447hists = [self .chat (100000 * (i + 1 ))for i in range (4 )] 448e = self .engine (4 ) 449clock = [0.0 ] 450def serve (prompt ,reply ): 451b = pick (e ,prompt ) 452# the engine's own source search: the longest message boundary any slot holds of this prompt 453reused = 0 454for h in e .slot_held : 455k = max ((i for i in range (len (h ))if h [i ]== T and i < len (prompt )and prompt [:i ]== h [:i ]),default = 0 ) 456reused = max (reused ,k ) 457e .slot_held [b ]= prompt + reply 458clock [0 ]+= 1.0 459e .slot_used [b ]= clock [0 ] 460return reused 461for i ,h in enumerate (hists ):# the first request of every chat 462serve (self .branch_of (h , [31 ,32 ]), [50 ,51 ]) 463total = 0 464for rnd in range (3 ): 465for owner in (2 ,0 ,3 ,1 ):# interleaved 466total += serve (self .branch_of (hists [owner ], [600 + rnd ,61 ,62 + owner ]), [50 ,51 ]) 467return total 468 469old ,new = run (old_pick ),run (lambda e ,p :e .pick_slot (p )) 470f"#2518 retained prefix over 12 branching follow-ups: before { old } tokens, after { new } tokens" ,file = sys .stderr ) 471self .assertGreater (new ,old ) 472self .assertEqual (new ,12 * (len (self .chat (1 ))+ 0 ))# every follow-up resumed at its history's end 473 474def test_batch_groups_spread_requests_over_the_groups (self ): 475# #1249: with --batch-groups 2 over 4 slots (groups {0,1} and {2,3}) a second request goes to the other group, 476# and a short held prefix does not pull it back into the busy one 477e = self .engine (4 ) 478e .slot_groups = 2 479e .slot_group = [0 ,0 ,1 ,1 ] 480e .slot_busy [0 ]= True 481e .slot_held [1 ]= [1 ,2 ,3 ] 482self .assertEqual (e .pick_slot ([1 ,2 ,3 ,4 ,5 ]),2 ) 483e .slot_held [1 ]= list (range (1 ,601 ))# a long prefix is worth the unbalanced group 484self .assertEqual (e .pick_slot (list (range (1 ,700 ))),1 ) 485e .slot_groups ,e .slot_group = 1 , [0 ]* 4 # without groups: any held prefix, as before 486e .slot_held [1 ]= [1 ,2 ,3 ] 487self .assertEqual (e .pick_slot ([1 ,2 ,3 ,4 ,5 ]),1 ) 488 489def test_slots_view (self ): 490e = self .engine (2 ) 491e .slot_held [1 ]= [1 ,2 ] 492e .slot_live [0 ]= {"slot" :0 ,"state" :"decoding" ,"prompt_tokens" :9 ,"generated" :4 , 493"started" :time .time ()- 2 ,"first_token" :time .time ()- 1 } 494v = e .slots_view () 495self .assertEqual (v [0 ]["state" ],"decoding" ) 496self .assertEqual (v [0 ]["generated" ],4 ) 497self .assertEqual (v [1 ], {"slot" :1 ,"state" :"idle" ,"held_tokens" :2 }) 498 499 500class FakeEngineCase (unittest .TestCase ): 501"""The real StrataEngine and Service over HTTP, the fake engine behind them.""" 502 503def start (self ,slots ,fit = None ,slot_cache = False ,fail = False ,reuse = False ,says_groups = 0 , 504more = (),stage_plan = False ,batch_sample = False ,stage_sample = False ): 505import serve .server as server 506self .tmp = tempfile .TemporaryDirectory () 507script = Path (self .tmp .name )/ "fake_strata.py" 508script .write_text (FAKE_BATCH ,encoding = "utf-8" ) 509self .log = Path (self .tmp .name )/ "requests.log" 510real = server .subprocess .Popen 511extra = ["--batch" ,str (slots )]+ (["--fit" ,str (fit )]if fit is not None else [])+ ["--log" ,str (self .log )] 512extra += ["--slotcache" ]if slot_cache else [] 513extra += ["--fail-window" ]if fail else [] 514extra += ["--reuse" ]if reuse else [] 515extra += ["--says-groups" ,str (says_groups )]if says_groups else [] 516extra += ["--fake-stage-plan" ]if stage_plan else [] 517extra += ["--fake-batch-sample" ]if batch_sample else [] 518extra += ["--fake-stage-sample" ]if stage_sample else [] 519extra += list (more ) 520with mock .patch .object (server .subprocess ,"Popen" , 521lambda cmd ,** kw :real ([sys .executable ,str (script ),* cmd [1 :]],** kw )): 522self .engine = StrataEngine ("strata" ,extra ,log = str (Path (self .tmp .name )/ "engine.log" )if stage_plan else None ) 523tok = ByteTokenizer () 524self .svc = Service (self .engine ,tok ,ChatTemplate (Path (__file__ ).parent / "chat_template.jinja" )) 525self .httpd = serve (self .svc ,port = 0 ) 526self .base = f"http://127.0.0.1: { self . httpd . server_address [ 1 ] } " 527 528def tearDown (self ): 529if getattr (self ,"httpd" ,None ): 530self .httpd .shutdown () 531self .httpd .server_close () 532if getattr (self ,"engine" ,None ): 533self .engine .unload () 534if getattr (self ,"tmp" ,None ): 535self .tmp .cleanup () 536 537def chat (self ,text ,max_tokens = 64 ): 538body = {"messages" : [{"role" :"user" ,"content" :text }],"max_tokens" :max_tokens ,"reasoning_effort" :"none" } 539req = urllib .request .Request (self .base + "/v1/chat/completions" ,data = json .dumps (body ).encode (), 540headers = {"Content-Type" :"application/json" }) 541with urllib .request .urlopen (req ,timeout = 60 )as r : 542return json .loads (r .read ().decode ()) 543 544def message (self ,text ,max_tokens = 64 ): 545body = {"model" :"m" ,"messages" : [{"role" :"user" ,"content" :text }],"max_tokens" :max_tokens } 546req = urllib .request .Request (self .base + "/v1/messages" ,data = json .dumps (body ).encode (), 547headers = {"Content-Type" :"application/json" ,"anthropic-version" :"2023-06-01" }) 548with urllib .request .urlopen (req ,timeout = 60 )as r : 549return json .loads (r .read ().decode ()) 550 551def get (self ,path ): 552with urllib .request .urlopen (self .base + path ,timeout = 10 )as r : 553return json .loads (r .read ().decode ()) 554 555def _two_at_once (self ,text_b ): 556"""A long request first, then one that has to go to a batch slot (the engine is busy with the first).""" 557out = {} 558def go (k ,text ): 559try : 560out [k ]= ("ok" ,self .chat (text ,max_tokens = 64 )) 561except urllib .error .HTTPError as e : 562out [k ]= ("http" ,e .code ,e .read ().decode (),dict (e .headers )) 563ta = threading .Thread (target = go ,args = ("a" ,"LONGREPLY please" )) 564ta .start () 565time .sleep (0.15 ) 566tb = threading .Thread (target = go ,args = ("b" ,text_b )) 567tb .start () 568ta .join (30 );tb .join (30 ) 569return out 570 571def race (self ,first ,second ,delay = 0.15 ,max_tokens = 64 ): 572"""`first` sent, `second` after `delay` seconds; -> {text: (reply, seconds it took)}""" 573res = {} 574 575def go (t ): 576t0 = time .time () 577r = self .chat (t ,max_tokens = max_tokens ) 578res [t ]= (r ["choices" ][0 ]["message" ]["content" ],time .time ()- t0 ) 579a = threading .Thread (target = go ,args = (first ,)) 580a .start () 581time .sleep (delay ) 582go (second ) 583a .join (30 ) 584return res 585 586 587class BatchLegAccounting (FakeEngineCase ): 588"""The admission's DONE times one token; BDONE counts that token but times only the slot.""" 589 590def queued_chats (self ,texts = ("first" ,"second" ),max_tokens = 10 ,stop = None ): 591replies ,errors = {}, [] 592 593def request (text ): 594body = {"messages" : [{"role" :"user" ,"content" :text }],"max_tokens" :max_tokens , 595"reasoning_effort" :"none" ,** ({"stop" : [stop ]}if stop else {})} 596req = urllib .request .Request (self .base + "/v1/chat/completions" ,data = json .dumps (body ).encode (), 597headers = {"Content-Type" :"application/json" }) 598try : 599with urllib .request .urlopen (req ,timeout = 15 )as response : 600replies [text ]= json .loads (response .read ()) 601except Exception as error : 602errors .append (repr (error )) 603 604workers = [threading .Thread (target = request ,args = (text ,))for text in texts ] 605# Both requests must be waiting before either takes control: the first cannot take the solo shortcut. 606with self .engine .ctl : 607for worker in workers : 608worker .start () 609deadline = time .monotonic ()+ 3 610while self .engine .waiting < 2 and time .monotonic ()< deadline : 611time .sleep (0.01 ) 612self .assertEqual (self .engine .waiting ,2 ) 613for worker in workers : 614worker .join (15 ) 615self .assertFalse (worker .is_alive ()) 616self .assertEqual (errors , []) 617self .assertEqual (len (replies ),2 ) 618self .assertEqual ([line .split ()[0 ]for line in self .log .read_text ().splitlines ()][:2 ], ["BGEN" ,"BGEN" ]) 619return replies 620 621def test_eos_adds_admission_time_without_counting_its_token_twice (self ): 622self .start (2 ) 623with mock .patch .object (server ,"EOS_IDS" , {257 }): 624replies = self .queued_chats () 625for reply in replies .values (): 626timings = reply ["timings" ] 627self .assertEqual ((timings ["predicted_n" ],timings ["predicted_ms" ]), (10 ,21.0 )) 628self .assertEqual (timings ["predicted_per_second" ],476.2 ) 629metrics = self .get ("/metrics" ) 630self .assertEqual ([(row ["engine_generated" ],row ["decode_ms" ])for row in metrics ["requests" ]], 631 [(10 ,21.0 ), (10 ,21.0 )]) 632self .assertEqual (metrics ["totals" ]["decode_ms" ],42.0 ) 633 634def test_length_finish_also_adds_admission_time (self ): 635self .start (2 ) 636for reply in self .queued_chats (max_tokens = 8 ).values (): 637self .assertEqual ((reply ["timings" ]["predicted_n" ],reply ["timings" ]["predicted_ms" ]), (8 ,21.0 )) 638 639def test_zero_slot_time_is_known_and_still_includes_admission (self ): 640self .start (2 ,more = ("--zero-bdone-ms" ,)) 641with mock .patch .object (server ,"EOS_IDS" , {257 }): 642replies = self .queued_chats () 643for reply in replies .values (): 644self .assertEqual (reply ["timings" ]["predicted_ms" ],20.0 ) 645 646def assert_incomplete_after_stop (self ,stop ): 647self .start (2 ) 648replies = self .queued_chats (stop = stop ) 649for reply in replies .values (): 650self .assertIsNone (reply ["timings" ]["predicted_ms" ]) 651self .assertIsNone (reply ["timings" ]["predicted_per_second" ]) 652for row in self .get ("/metrics" )["requests" ]: 653self .assertIsNone (row ["engine_generated" ]) 654self .assertIsNone (row ["decode_ms" ]) 655self .assertIsNone (row ["decode_tok_s" ]) 656self .assertEqual (self .get ("/metrics" )["totals" ]["decode_ms" ],0.0 ) 657 658def test_close_at_admission_token_does_not_publish_partial_totals (self ): 659self .assert_incomplete_after_stop ("o" ) 660 661def test_close_in_slot_does_not_publish_partial_totals (self ): 662self .assert_incomplete_after_stop ("k, " ) 663 664def test_slot_to_solo_carry_includes_admission_once (self ): 665self .start (2 ,slot_cache = True ) 666with mock .patch .object (server ,"EOS_IDS" , {257 }): 667replies = self .queued_chats (("short" ,"LONGREPLY" ),max_tokens = 200 ) 668lines = [line .split ()for line in self .log .read_text ().splitlines ()] 669solos = [line for line in lines if line [0 ]== "GEN" ] 670self .assertEqual (len (solos ),1 ,lines ) 671prompt_lengths = [int (line [2 ])for line in lines if line [0 ]== "BGEN" ] 672slot_tokens = int (solos [0 ][2 ])- max (prompt_lengths ) 673self .assertGreaterEqual (slot_tokens ,2 ) 674self .assertLess (slot_tokens ,55 ) 675# "ok, " + 15 * "la " + "done." + EOS: 55 total tokens. The solo leg times its remaining tokens at 20 ms each. 676expected_ms = 21.0 + (55 - slot_tokens )* 20.0 677reply = replies ["LONGREPLY" ] 678self .assertEqual ((reply ["timings" ]["predicted_n" ],reply ["timings" ]["predicted_ms" ]), (55 ,expected_ms )) 679row = max (self .get ("/metrics" )["requests" ],key = lambda item :item ["output_tokens" ]) 680self .assertEqual ((row ["engine_generated" ],row ["decode_ms" ]), (55 ,expected_ms )) 681 682 683class ParallelService (FakeEngineCase ): 684"""The real StrataEngine and Service over HTTP, the fake engine behind them: slots, queues, benchmarks, telemetry. 685The yielding, restart and failure tests are in serve/test_parallel_yield.py (this file alone ran past 100 s).""" 686 687def test_bgen_refused_by_the_engine_is_retried_not_a_400 (self ): 688"""#1994: the engine refuses a BGEN ("no such free slot") although the server saw the slot free: the request 689goes to another slot (or waits) and is answered; the same conversation's next turn works too.""" 690self .start (2 ) 691self .engine .SLOT_PARK_S = 0.2 692out = self ._two_at_once ("BUSYSLOT hello" ) 693self .assertEqual (out ["b" ][0 ],"ok" ,out ["b" ]) 694self .assertIn ("REFUSED" ,self .log .read_text ()) 695again = self .chat ("BUSYSLOT hello" )# the conversation is not poisoned 696self .assertEqual (again ["choices" ][0 ]["message" ]["content" ],"ok, done." ) 697time .sleep (0.5 ) 698self .assertEqual (self .engine .slot_busy , [False ,False ]) 699 700def test_bgen_refused_for_good_is_a_retryable_503_and_frees_the_slots (self ): 701"""#1994: when the engine keeps refusing, the answer is a 503 (retryable), never a 400, and no slot stays busy. 702#3040 / #5044: the refused admission keeps an error row but is not a completed request (no prompt tokens, no 703part in the totals).""" 704self .start (2 ) 705self .engine .SLOT_PARK_S = 0.05 706out = self ._two_at_once ("BUSYALL hello" ) 707self .assertEqual (out ["b" ][0 ],"http" ,out ["b" ]) 708self .assertEqual (out ["b" ][1 ],503 ,out ["b" ]) 709metrics = self .get ("/metrics" ) 710refused = [row for row in metrics ["requests" ]if row ["output_tokens" ]== 0 ] 711self .assertEqual (len (refused ),1 ,metrics ["requests" ]) 712self .assertEqual ((refused [0 ]["finish" ],refused [0 ]["prompt_tokens" ],refused [0 ]["prompt_read" ]), 713 ("error" ,0 ,None )) 714self .assertEqual (metrics ["totals" ]["requests" ],1 ,"only the admitted request counts" ) 715time .sleep (0.5 ) 716self .assertEqual (self .engine .slot_busy , [False ,False ]) 717self .assertEqual (self .chat ("fine again" )["choices" ][0 ]["message" ]["content" ],"ok, done." ) 718self .assertEqual (self .get ("/metrics" )["totals" ]["requests" ],2 ,"a later admitted request counts" ) 719 720def test_engine_reports_fewer_slots (self ): 721self .start (4 ,fit = 2 ) 722self .assertEqual (self .engine .batch ,2 ) 723self .assertEqual (self .get ("/v1/status" )["concurrency" ]["serving" ],2 ) 724 725def test_admission_cap_uses_effective_slots_and_rejects_before_stream (self ): 726self .start (4 ,fit = 2 ) 727self .svc .max_queue = 1 728self .assertEqual (self .svc .admission_limit (),3 ) 729self .assertTrue (all (self .svc .reserve_inference ()for _ in range (3 ))) 730cases = ( 731 ("/v1/chat/completions" , {"messages" : [{"role" :"user" ,"content" :"hi" }],"stream" :True }), 732 ("/v1/messages" , {"model" :"m" ,"max_tokens" :8 , 733"messages" : [{"role" :"user" ,"content" :"hi" }],"stream" :True }), 734 ("/v1/responses" , {"model" :"m" ,"input" :"hi" ,"stream" :True }), 735 ) 736try : 737for path ,body in cases : 738req = urllib .request .Request (self .base + path ,data = json .dumps (body ).encode (), 739headers = {"Content-Type" :"application/json" }) 740with self .assertRaises (urllib .error .HTTPError )as caught : 741urllib .request .urlopen (req ,timeout = 10 ) 742err = caught .exception 743self .assertEqual (err .code ,429 ) 744self .assertEqual (err .headers .get ("Retry-After" ),"1" ) 745self .assertIn ("admission_full" ,err .read ().decode ()) 746snapshot = self .get ("/v1/telemetry" )["work" ] 747self .assertEqual ((snapshot ["admission_reserved" ],snapshot ["admission_limit" ], 748snapshot ["max_queue" ],snapshot ["admission_rejected" ]), (3 ,3 ,1 ,3 )) 749finally : 750for _ in range (3 ): 751self .svc .release_inference () 752self .assertEqual (self .chat ("capacity freed" )["choices" ][0 ]["message" ]["content" ],"ok, done." ) 753self .assertEqual (self .get ("/v1/telemetry" )["work" ]["admission_reserved" ],0 ) 754 755def test_queue_timeout_serial_fifo_returns_429_and_recovers (self ): 756self .start (1 ) 757self .svc .queue_timeout_s = 0.12 758self .svc .max_queue = 1 759self .svc .fifo .acquire () 760try : 761with self .assertRaises (urllib .error .HTTPError )as caught : 762self .chat ("waiting for serial turn" ) 763self .assertEqual (caught .exception .code ,429 ) 764self .assertEqual (caught .exception .headers .get ("Retry-After" ),"1" ) 765self .assertEqual (json .loads (caught .exception .read ())["error" ]["code" ],"queue_wait_timeout" ) 766work = self .get ("/v1/telemetry" )["work" ] 767self .assertEqual ((work ["queue_timeout_s" ],work ["queue_timeouts" ],work ["queued" ]), 768 (0.12 ,1 ,0 )) 769finally : 770self .svc .fifo .release () 771self .assertEqual (self .chat ("next turn" )["choices" ][0 ]["message" ]["content" ],"ok, done." ) 772self .assertEqual (self .get ("/v1/telemetry" )["work" ]["admission_reserved" ],0 ) 773 774def test_queue_timeout_parallel_control_and_stream_formats (self ): 775self .start (2 ) 776self .svc .queue_timeout_s = 0.12 777self .svc .max_queue = 1 778self .engine .ctl .acquire () 779cases = ( 780 ("/v1/chat/completions" , {"messages" : [{"role" :"user" ,"content" :"hi" }]},"data: " ), 781 ("/v1/messages" , {"model" :"m" ,"max_tokens" :8 , 782"messages" : [{"role" :"user" ,"content" :"hi" }]},"event: error" ), 783 ("/v1/responses" , {"model" :"m" ,"input" :"hi" },"event: response.failed" ), 784 ) 785try : 786for path ,body ,marker in cases : 787for stream in (False ,True ): 788req = urllib .request .Request (self .base + path , 789data = json .dumps ({** body ,"stream" :stream }).encode (), 790headers = {"Content-Type" :"application/json" }) 791if stream : 792with urllib .request .urlopen (req ,timeout = 10 )as response : 793data = response .read ().decode () 794self .assertIn (marker ,data ) 795self .assertIn ("queue_wait_timeout" ,data ) 796else : 797with self .assertRaises (urllib .error .HTTPError )as caught : 798urllib .request .urlopen (req ,timeout = 10 ) 799self .assertEqual (caught .exception .code ,429 ) 800self .assertIn ("queue_wait_timeout" ,caught .exception .read ().decode ()) 801work = self .get ("/v1/telemetry" )["work" ] 802self .assertEqual (work ["queue_timeouts" ],6 ) 803self .assertEqual ((work ["admission_reserved" ],work ["waiting" ]), (0 ,0 )) 804finally : 805self .engine .ctl .release () 806self .assertEqual (self .chat ("healthy" )["choices" ][0 ]["message" ]["content" ],"ok, done." ) 807 808def test_queue_timeout_parallel_slot_wait_releases_control (self ): 809self .start (2 ) 810self .svc .queue_timeout_s = 0.12 811with self .engine .slot_cv : 812self .engine .slot_busy [:]= [True ,True ] 813try : 814with self .assertRaises (urllib .error .HTTPError )as caught : 815self .chat ("waiting for a batch slot" ) 816self .assertEqual (caught .exception .code ,429 ) 817self .assertIn ("queue_wait_timeout" ,caught .exception .read ().decode ()) 818self .assertFalse (self .engine .ctl .locked ()) 819self .assertEqual (self .engine .waiting ,0 ) 820finally : 821with self .engine .slot_cv : 822self .engine .slot_busy [:]= [False ,False ] 823self .engine .slot_cv .notify_all () 824self .assertEqual (self .chat ("slot freed" )["choices" ][0 ]["message" ]["content" ],"ok, done." ) 825 826def test_benchmark_overload_suite_preserves_batch_recovery (self ): 827self .start (2 ) 828self .svc .max_queue = 0 829self .svc .queue_timeout_s = 0.15 830out = Path (self .tmp .name )/ "overload" 831report = bench .run (Endpoint (self .base ,None ),Endpoint (self .base ,None ),out , 832suite = "parallel-overload-v1" ,concurrency = 6 ) 833self .assertTrue (report ["successful" ]) 834overload = report ["phases" ][1 ] 835self .assertEqual (overload ["kind" ],"overload" ) 836self .assertGreater (overload ["summary" ]["expected_overload" ],0 ) 837self .assertEqual (overload ["summary" ]["failed" ],0 ) 838self .assertTrue (report ["phases" ][2 ]["passed" ]) 839self .assertEqual (self .get ("/v1/telemetry" )["work" ]["admission_reserved" ],0 ) 840 841def test_benchmark_cancel_suite_releases_batch_queue_and_slots (self ): 842self .start (2 ) 843self .svc .max_queue = 1 844self .svc .queue_timeout_s = 5 845out = Path (self .tmp .name )/ "cancel" 846report = bench .run (Endpoint (self .base ,None ),Endpoint (self .base ,None ),out , 847suite = "parallel-cancel-v1" ,concurrency = 2 ,request_timeout = 15 ) 848self .assertTrue (report ["successful" ],bench .format_summary (bench .summary (report ))) 849self .assertEqual ([row ["kind" ]for row in report ["phases" ]], 850 ["warmup" ,"cancel_active" ,"cancel_queued" ,"recovery" ]) 851self .assertEqual (report ["phases" ][2 ]["summary" ]["companion_successful" ],2 ) 852self .assertEqual (self .get ("/v1/telemetry" )["work" ]["admission_reserved" ],0 ) 853 854def test_benchmark_prefill_cancel_observes_progress_and_companion_completion (self ): 855self .start (2 ) 856out = Path (self .tmp .name )/ "prefill-cancel" 857report = bench .run (Endpoint (self .base ,None ),Endpoint (self .base ,None ),out , 858suite = "parallel-prefill-cancel-v1" ,concurrency = 2 ,request_timeout = 15 ) 859self .assertTrue (report ["successful" ],bench .format_summary (bench .summary (report ))) 860self .assertEqual ([row ["kind" ]for row in report ["phases" ]], 861 ["warmup" ,"cancel_prefill" ,"recovery" ]) 862phase = report ["phases" ][1 ] 863self .assertTrue (phase ["summary" ]["prompt_read_seen" ]) 864self .assertGreater (phase ["requests" ][0 ]["prompt_read_at_close" ],0 ) 865self .assertLess (phase ["requests" ][0 ]["prompt_read_at_close" ], 866phase ["requests" ][0 ]["prompt_tokens_at_close" ]) 867self .assertEqual (phase ["summary" ]["client_disconnect_delta" ],1 ) 868self .assertEqual (phase ["summary" ]["companion_successful" ],1 ) 869self .assertEqual (self .get ("/v1/telemetry" )["work" ]["admission_reserved" ],0 ) 870data = (out / "results.json" ).read_text () 871self .assertNotIn ("Explain how a serving system" ,data ) 872 873def test_telemetry_keeps_engine_waiting_age_visible (self ): 874self .start (2 ) 875self .svc .max_queue = 1 876self .svc .queue_timeout_s = 0.5 877self .engine .ctl .acquire () 878outcome = [] 879def request (): 880try : 881self .chat ("waiting" ) 882except urllib .error .HTTPError as error : 883outcome .append (error .code ) 884error .read () 885worker = threading .Thread (target = request ) 886try : 887worker .start () 888cutoff = time .monotonic ()+ 2 889while time .monotonic ()< cutoff : 890work = self .get ("/v1/telemetry" )["work" ] 891if any (row ["state" ]== "waiting" for row in work ["requests" ]): 892break 893time .sleep (0.01 ) 894else : 895self .fail ("engine wait was not visible in telemetry" ) 896time .sleep (0.04 ) 897work = self .get ("/v1/telemetry" )["work" ] 898self .assertGreater (work ["oldest_queue_s" ],0.03 ) 899self .assertTrue (any (row ["state" ]== "waiting" for row in work ["requests" ])) 900finally : 901self .engine .ctl .release () 902worker .join (timeout = 3 ) 903self .assertEqual (outcome , []) 904 905def test_batch_groups_auto_follows_the_engine (self ): 906"""--batch-groups auto: the engine picks the groups and says so (INFO batch_groups=G); the server spreads the 907requests over those groups, and a plain number is read as before.""" 908self .start (8 ,says_groups = 4 ,more = ["--batch-groups" ,"auto" ]) 909e = self .engine 910self .assertEqual ((e .batch ,e .slot_groups ), (8 ,4 )) 911self .assertEqual (e .slot_group , [0 ,0 ,1 ,1 ,2 ,2 ,3 ,3 ]) 912self .assertEqual (e .slot_order [:4 ], [0 ,2 ,4 ,6 ]) 913telemetry = self .get ("/v1/telemetry" ) 914self .assertEqual ([s ["group" ]for s in telemetry ["work" ]["slots" ]], [0 ,0 ,1 ,1 ,2 ,2 ,3 ,3 ]) 915self .tearDown ();self .httpd = self .engine = self .tmp = None 916self .start (8 ,more = ["--batch-groups" ,"auto" ])# an engine that reports none: one group 917self .assertEqual (self .engine .slot_groups ,1 ) 918self .tearDown ();self .httpd = self .engine = self .tmp = None 919self .start (8 ,more = ["--batch-groups" ,"2" ]) 920self .assertEqual (self .engine .slot_groups ,2 ) 921self .tearDown ();self .httpd = self .engine = self .tmp = None 922self .start (8 ,says_groups = 4 )# 0.1.41: no flag on a layer split = the engine's choice 923self .assertEqual (self .engine .slot_groups ,4 ) 924self .tearDown ();self .httpd = self .engine = self .tmp = None 925self .start (8 ,says_groups = 4 ,more = ["--batch-groups" ,"1" ])# the opt-out 926self .assertEqual (self .engine .slot_groups ,1 ) 927 928def test_engine_log_resolves_four_stage_layer_and_device_mapping (self ): 929self .start (8 ,says_groups = 4 ,stage_plan = True ) 930self .svc .terminal_visibility_order = [2 ,0 ,3 ,1 ] 931self .svc .gpu_indices = [2 ,0 ,3 ,1 ] 932telemetry = self .get ("/v1/telemetry" ) 933topology = telemetry ["topology" ] 934self .assertEqual (topology ["source" ],"engine_start_log" ) 935self .assertTrue (topology ["resolved" ]) 936self .assertEqual (telemetry ["quality" ]["placement" ],"reported" ) 937self .assertEqual ([(row ["stage" ],row ["device_index" ],row ["layer_start" ],row ["layer_end" ]) 938for row in topology ["stages" ]], 939 [(0 ,2 ,0 ,11 ), (1 ,0 ,12 ,23 ), (2 ,3 ,24 ,35 ), (3 ,1 ,36 ,47 )]) 940clean = Endpoint (self .base ).snapshot () 941self .assertEqual (clean ["topology" ]["stages" ],topology ["stages" ]) 942self .svc .terminal_visibility_order = [] 943partial = self .get ("/v1/telemetry" ) 944self .assertFalse (partial ["topology" ]["resolved" ]) 945self .assertEqual (len (partial ["topology" ]["stages" ]),4 ) 946self .assertIsNone (partial ["topology" ]["stages" ][0 ]["device_index" ]) 947self .assertEqual (partial ["quality" ]["placement" ],"partial" ) 948self .engine .unload () 949unloaded = self .get ("/v1/telemetry" )["topology" ] 950self .assertFalse (unloaded ["resolved" ]) 951self .assertEqual (unloaded ["stages" ], []) 952 953def test_engine_batch_window_sample_reaches_telemetry_without_entering_reply (self ): 954self .start (2 ,batch_sample = True ) 955replies = self .race ("first LONGREPLY" ,"second LONGREPLY" ,delay = 0.05 ,max_tokens = 64 ) 956self .assertTrue (all ("ok, " in reply for reply ,_ in replies .values ())) 957self .assertTrue (any (line .startswith ("BGEN" )for line in self .log .read_text ().splitlines ())) 958deadline = time .monotonic ()+ 2 959while True : 960telemetry = self .get ("/v1/telemetry" ) 961if telemetry ["quality" ]["batch_window_rows" ]== "measured" : 962break 963if time .monotonic ()>= deadline : 964self .fail ("fake engine's BSTAT sample did not reach telemetry" ) 965time .sleep (0.02 ) 966work = telemetry ["work" ] 967self .assertGreaterEqual (work ["effective_rows_window" ],1.0 ) 968self .assertLessEqual (work ["effective_rows_window" ],2.0 ) 969self .assertEqual (work ["batch_active_rows_window" ],work ["effective_rows_window" ]) 970self .assertEqual (work ["batch_sample_windows" ],1 ) 971self .assertEqual (work ["batch_sample_span_s" ],0.02 ) 972self .assertGreaterEqual (work ["batch_sample_age_s" ],0 ) 973clean = Endpoint (self .base ).snapshot () 974self .assertEqual (clean ["quality" ]["batch_window_rows" ],"measured" ) 975self .assertGreaterEqual (clean ["work" ]["batch_sample_rows" ],1 ) 976self .engine .unload () 977unloaded = self .get ("/v1/telemetry" ) 978self .assertIsNone (unloaded ["work" ]["effective_rows_window" ]) 979self .assertEqual (unloaded ["quality" ]["batch_window_rows" ],"unavailable" ) 980 981def test_pipeline_stage_host_spans_reach_telemetry_without_entering_reply (self ): 982self .start (2 ,says_groups = 2 ,stage_plan = True ,stage_sample = True ) 983replies = self .race ("first LONGREPLY" ,"second LONGREPLY" ,delay = 0.05 ,max_tokens = 64 ) 984self .assertTrue (all ("ok, " in reply for reply ,_ in replies .values ())) 985deadline = time .monotonic ()+ 2 986while True : 987telemetry = self .get ("/v1/telemetry" ) 988if telemetry ["quality" ].get ("stage_in_flight_source" )== "engine_pstat_host_span" : 989break 990if time .monotonic ()>= deadline : 991self .fail ("fake engine's PSTAT sample did not reach telemetry" ) 992time .sleep (0.02 ) 993self .assertEqual (telemetry ["work" ]["stage_in_flight_us" ], [16000 ,14000 ,12000 ,10000 ]) 994clean = Endpoint (self .base ).snapshot () 995self .assertEqual (clean ["quality" ]["stage_in_flight" ],"measured_host_span" ) 996self .assertEqual ([row ["percent" ]for row in clean ["work" ]["stage_in_flight" ]], 997 [80.0 ,70.0 ,60.0 ,50.0 ]) 998self .engine .unload () 999unloaded = self .get ("/v1/telemetry" ) 1000self .assertNotIn ("stage_in_flight_us" ,unloaded ["work" ]) 1001 1002def test_a_burst_of_connections_is_not_reset (self ): 1003"""30-40 clients at once got "connection reset by peer" with the listen backlog of 5 (4 x R9700 burst): the 1004server listens with a deep backlog (STRATA_HTTP_BACKLOG, 256), so 60 simultaneous requests all get answers.""" 1005import serve .server as server 1006self .assertGreaterEqual (server .Server .request_queue_size ,64 ) 1007self .start (2 ) 1008errs ,ok = [], [] 1009def one (i ): 1010try : 1011self .chat (f"burst { i } " ,max_tokens = 8 ) 1012ok .append (i ) 1013except Exception as e :# noqa: BLE001 1014errs .append (repr (e )) 1015th = [threading .Thread (target = one ,args = (i ,))for i in range (60 )] 1016for t in th :t .start () 1017for t in th :t .join () 1018self .assertEqual ((len (ok ),errs [:2 ]), (60 , [])) 1019 1020def test_stop_strings_in_a_batch_slot (self ): 1021"""#454: a stop string cuts the answer in --batch mode too, and the slot is freed for the next request.""" 1022self .start (2 ) 1023body = {"messages" : [{"role" :"user" ,"content" :"hi LONGREPLY" }],"max_tokens" :64 ,"reasoning_effort" :"none" , 1024"stop" : ["la la" ]} 1025req = urllib .request .Request (self .base + "/v1/chat/completions" ,data = json .dumps (body ).encode (), 1026headers = {"Content-Type" :"application/json" }) 1027with urllib .request .urlopen (req ,timeout = 60 )as r : 1028c = json .loads (r .read ().decode ())["choices" ][0 ] 1029self .assertEqual ((c ["message" ]["content" ],c ["finish_reason" ]), ("ok, " ,"stop" )) 1030self .assertEqual (self .chat ("again" )["choices" ][0 ]["message" ]["content" ],"ok, done." ) 1031 1032def test_engine_turns_batching_off (self ): 1033self .start (4 ,fit = 0 ) 1034self .assertEqual (self .engine .batch ,0 ) 1035self .assertEqual (self .chat ("hi" )["choices" ][0 ]["message" ]["content" ],"ok, done." ) 1036 1037def test_concurrent_requests_share_the_slots (self ): 1038self .start (2 ) 1039# the first one decodes long enough for the others to arrive while it runs (also on a busy PC) 1040texts = ["first question LONGREPLY" ,"second question, longer" ,"a third one waits for a slot" ] 1041reply = {t :"ok, " + "la " * 15 + "done." if "LONGREPLY" in t else "ok, done." for t in texts } 1042out ,errors ,seen ,terminal_seen = {}, [], [], [] 1043 1044def go (t ): 1045try : 1046out [t ]= self .chat (t ) 1047except Exception as e :# noqa: BLE001 - reported below 1048errors .append (e ) 1049 1050threads = [threading .Thread (target = go ,args = (t ,))for t in texts ] 1051for th in threads : 1052th .start () 1053time .sleep (0.05 ) 1054deadline = time .time ()+ 30 1055while any (th .is_alive ()for th in threads )and time .time ()< deadline : 1056m = self .get ("/metrics" )["live" ] 1057seen .append (m ) 1058terminal_seen .append (self .get ("/v1/telemetry" )) 1059time .sleep (0.01 ) 1060for th in threads : 1061th .join (30 ) 1062self .assertEqual (errors , []) 1063for t in texts : 1064self .assertEqual (out [t ]["choices" ][0 ]["message" ]["content" ],reply [t ]) 1065# the slots were reported, and a request was admitted while another decoded in a slot (the fake logs how many 1066# slots were active at each admission) 1067self .assertTrue (any (m .get ("parallel" )== 2 and len (m .get ("slots" , []))== 2 for m in seen )) 1068self .assertTrue (any (t ["work" ]["requests" ]for t in terminal_seen )) 1069self .assertTrue (any (s .get ("request_id" )for t in terminal_seen for s in t ["work" ]["slots" ])) 1070self .assertTrue (any (isinstance (r .get ("first_engine_token_s" ), (int ,float ))and 1071r ["first_engine_token_s" ]> 0 1072for t in terminal_seen for r in t ["work" ]["requests" ] 1073if r ["state" ]== "decoding" ),"live per-request first engine token was not observed" ) 1074for t in terminal_seen : 1075self .assertEqual (t ["quality" ]["request_correlation" ],"reported" ) 1076self .assertNotIn ("input" ,json .dumps (t )) 1077admitted = [int (x .split ()[3 ])for x in self .log .read_text ().splitlines ()if x .startswith ("BGEN" )] 1078self .assertIn (1 ,admitted ) 1079# every request recorded its own row; nothing is left running 1080with self .svc .status_lock : 1081self .assertEqual (len (self .svc .history ),3 ) 1082self .assertEqual (self .svc .live_reqs , {}) 1083self .assertFalse (self .svc .status ["busy" ]) 1084self .assertEqual (sorted (r ["output_tokens" ]for r in self .svc .history ), 1085sorted (len (reply [t ])+ 1 for t in texts )) 1086self .assertTrue (all (isinstance (r .get ("first_engine_token_s" ), (int ,float ))and 1087r ["first_engine_token_s" ]> 0 for r in self .svc .history )) 1088clean = Endpoint (self .base ).snapshot () 1089self .assertTrue (all (isinstance (r .get ("first_engine_token_s" ), (int ,float )) 1090for r in clean ["recent" ][:3 ])) 1091# never more than two in the slots at once (the fake logs how many were active at each admission) 1092active = [int (x .split ()[3 ])for x in self .log .read_text ().splitlines ()if x .startswith ("BGEN" )] 1093self .assertTrue (all (a <= 1 for a in active ),active ) 1094 1095 1096 1097class EngineOwnedDefaults (unittest .TestCase ): 1098"""The parallel stack, the GDN speedups, the Q8_0 hyper-connection read and the Metal fp16 windows are the engine's own defaults 1099(src/core/arch_defaults.cpp, generate.cpp): the server adds none of them, and a value the config or the shell sets still reaches the engine.""" 1100NAMES = ("STRATA_CKPT_POOL" ,"STRATA_CKPT_POOL_READY" ,"STRATA_SLOT_CKPT_MOVE" ,"STRATA_SLOT_COPY_DIRECT" ,"STRATA_SLOT_COPY_BATCHSYNC" , 1101"STRATA_BATCH_GDN_GROUPS" ,"STRATA_BATCH_ATTN_ROWS" ,"STRATA_BATCH_SELF_COMMIT" ,"STRATA_QSA_SLOTS" , 1102"STRATA_GDN_TC" ,"STRATA_GDN_CONVL2" ,"STRATA_GDN_CHUNKED" ,"STRATA_HC_Q8" ,"STRATA_METAL_F16" ) 1103 1104def env_for (self ,cfg ,base = None ): 1105import os 1106from unittest import mock 1107with mock .patch .dict (os .environ ,base or {},clear = False ): 1108for k in self .NAMES : 1109if not (base and k in base ): 1110os .environ .pop (k ,None ) 1111return server .child_env (cfg ) 1112 1113def test_server_adds_none (self ): 1114for cfg in ({"parallel" :8 ,"args" : []}, {"args" : ["--batch" ,"4" ]}, {"parallel" :8 ,"args" : [],"backend" :"hip" }, {}): 1115env = self .env_for (cfg ) 1116for k in self .NAMES : 1117self .assertNotIn (k ,env , (k ,cfg )) 1118 1119def test_explicit_values_reach_the_engine (self ): 1120env = self .env_for ({"parallel" :8 ,"args" : [],"env" : {"STRATA_BATCH_GDN_GROUPS" :"0" }}, {"STRATA_CKPT_POOL" :"0" }) 1121self .assertEqual (env ["STRATA_BATCH_GDN_GROUPS" ],"0" ) 1122self .assertEqual (env ["STRATA_CKPT_POOL" ],"0" ) 1123 1124 1125if __name__ == "__main__" : 1126unittest .main ()