okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
53623e56f
main
1"""A disconnect reaches the real engine pipe during a quiet prompt read, before its first PP or token. 2 3The native stand-in deliberately says nothing until STOP. This covers the boundary that a MockEngine watching 4the cancel Event itself cannot test: HTTP disconnect -> Event -> STOP -> DONE/BADM -> the next request. 5No GPU or model is used. 6""" 7import json 8import io 9from pathlib import Path 10import queue 11import socket 12import sys 13import tempfile 14import threading 15import time 16import unittest 17from unittest import mock 18import urllib .request 19 20from serve import server 21 22 23FAKE = r'''import json, queue, sys, threading, time 24from pathlib import Path 25log = Path(sys.argv[sys.argv.index('--events') + 1]) 26batch = int(sys.argv[sys.argv.index('--batch') + 1]) 27commands, stop = queue.Queue(), threading.Event() 28def note(event): 29with log.open('a') as f: 30f.write(json.dumps({'event': event, 'at': time.monotonic()}) + '\n') 31def reader(): 32for line in sys.stdin: 33line = line.strip() 34if line == 'STOP': 35note('stop') 36stop.set() 37else: 38commands.put(line) 39commands.put('QUIT') 40threading.Thread(target=reader, daemon=True).start() 41if batch: 42print(f'INFO batch_slots={batch}', flush=True) 43print('READY 4096 stop', flush=True) 44count = 0 45while True: 46line = commands.get() 47if line == 'QUIT': 48break 49if not line.startswith(('GEN ', 'BGEN ')): 50continue 51count += 1 52stop.clear() 53note('request_' + str(count)) 54fields = line.split() 55slot = int(fields[1]) if fields[0] == 'BGEN' else None 56if count == 1: 57# The test's cleanup also sends STOP, so even a failed assertion leaves no long-lived child. 58stop.wait(15) 59time.sleep(.15) # STOP was received, but the current chunk has not finished yet: it must drain. 60print('DONE 0 128 1 0 cancel 0 0 0', flush=True) 61else: 62print('T 90\nDONE 1 20 1 1 stop', flush=True) 63if slot is not None: 64print(f'BADM {slot} 0', flush=True) 65''' 66 67 68class QuietPromptCancel (unittest .TestCase ): 69def check_hangup (self ,api ,stream ,batch ,max_new = 1 ): 70with tempfile .TemporaryDirectory ()as directory : 71root = Path (directory ) 72script ,events = root / 'engine.py' ,root / 'events.jsonl' 73script .write_text (FAKE ,encoding = 'utf-8' ) 74real_popen = server .subprocess .Popen 75with mock .patch .object (server .subprocess ,'Popen' ,lambda cmd ,** kw : 76real_popen ([sys .executable ,str (script ),* cmd [1 :]],** kw )): 77engine = server .StrataEngine ('strata' , ['--batch' ,str (batch ),'--events' ,str (events )]) 78service = server .Service (engine ,server .ByteTokenizer (), 79server .ChatTemplate (Path (__file__ ).parent / 'chat_template.jinja' )) 80http = server .serve (service ,port = 0 ) 81port = http .server_address [1 ] 82sock = None 83reply ,errors = [], [] 84follower = None 85try : 86body = {'model' :'m' ,'stream' :stream ,'max_tokens' :max_new , 87'messages' : [{'role' :'user' ,'content' :'a long prompt' }], 88'reasoning_effort' :'none' } 89if api == 'responses' : 90body = {'model' :'m' ,'stream' :stream ,'max_output_tokens' :max_new , 91'input' :'a long prompt' ,'reasoning' : {'effort' :'none' }} 92data = json .dumps (body ).encode () 93path = {'openai' :'/v1/chat/completions' ,'anthropic' :'/v1/messages' , 94'responses' :'/v1/responses' }[api ] 95sock = socket .create_connection (('127.0.0.1' ,port ),timeout = 5 ) 96sock .sendall (f'POST { path } HTTP/1.1\r\nHost: 127.0.0.1\r\nContent-Type: application/json\r\n' 97f'Content-Length: { len ( data ) } \r\n\r\n' .encode ()+ data ) 98 99def has (event ): 100return events .exists ()and any (json .loads (row )['event' ]== event 101for row in events .read_text ().splitlines ()) 102 103deadline = time .monotonic ()+ 3 104while not has ('request_1' )and time .monotonic ()< deadline : 105time .sleep (.01 ) 106self .assertTrue (has ('request_1' ),'the first request did not reach the native pipe' ) 107closed = time .monotonic () 108sock .close () 109sock = None 110 111def follow (): 112data = json .dumps ({'messages' : [{'role' :'user' ,'content' :'hi' }], 113'max_tokens' :1 ,'reasoning_effort' :'none' }).encode () 114req = urllib .request .Request (f'http://127.0.0.1: { port } /v1/chat/completions' ,data = data , 115headers = {'Content-Type' :'application/json' }) 116try : 117with urllib .request .urlopen (req ,timeout = 15 )as response : 118reply .append (json .load (response )) 119except Exception as exc : 120errors .append (exc ) 121 122follower = threading .Thread (target = follow ) 123follower .start () 124deadline = closed + 2.5 125while not has ('stop' )and time .monotonic ()< deadline : 126time .sleep (.01 ) 127self .assertTrue (has ('stop' ),'disconnect must send STOP before a PP line or 10 s heartbeat' ) 128follower .join (timeout = 2.5 ) 129self .assertFalse (follower .is_alive (),'the cancelled request did not release the next request' ) 130self .assertEqual (errors , []) 131self .assertEqual (reply [0 ]['choices' ][0 ]['message' ]['content' ],'Z' ) 132self .assertTrue (engine .alive (),'cancellation must preserve the resident engine' ) 133self .assertEqual (reply [0 ]['usage' ]['completion_tokens' ],1 ) 134self .assertEqual (service .history [- 1 ]['engine_generated' ],1 , 135'the next request must record its own DONE, not the cancelled request' ) 136if batch : 137self .assertFalse (any (engine .slot_busy ),'the cancelled admission must release its slot' ) 138else : 139self .assertEqual (engine .last ['finish' ],'stop' ,'the next request must read its own DONE' ) 140finally : 141if sock is not None : 142sock .close () 143engine ._send ('STOP' ) 144if follower is not None : 145follower .join (timeout = 3 ) 146http .shutdown () 147http .server_close () 148engine .close () 149 150def test_anthropic_stream (self ): 151self .check_hangup ('anthropic' ,True ,0 ) 152 153def test_batch_solo_stream (self ): 154# A batch-enabled engine runs an isolated request with more than one output token through GEN first. 155self .check_hangup ('anthropic' ,True ,2 ,max_new = 2 ) 156 157def test_other_http_modes (self ): 158for api in ('openai' ,'anthropic' ,'responses' ): 159for stream in (False ,True ): 160for batch in (0 ,2 ): 161if (api ,stream ,batch )== ('anthropic' ,True ,0 ): 162continue 163with self .subTest (api = api ,stream = stream ,batch = batch ): 164self .check_hangup (api ,stream ,batch ) 165 166 167class QuietWaitPolicy (unittest .TestCase ): 168def test_expired_silence_is_not_a_heartbeat (self ): 169engine = object .__new__ (server .StrataEngine ) 170engine .proc = mock .Mock () 171engine .proc .poll .return_value = None 172engine .proc .stdin = io .StringIO () 173engine .lines = mock .Mock () 174engine .can_stop ,engine .silence_s ,engine .log_path = True ,10 ,None 175now = [0.0 ] 176 177def clock (): 178now [0 ]+= .001 # time also passes between calculating a wait and starting it 179return now [0 ] 180 181def get (timeout ): 182now [0 ]+= timeout 183raise queue .Empty 184 185engine .lines .get .side_effect = get 186with mock .patch .object (server .time ,'monotonic' ,clock ): 187gen = engine .generate ([],10 , {},threading .Event ()) 188with self .assertRaises (server .EngineSilent ): 189next (gen )# must fail before yielding an overdue heartbeat to a slow consumer 190engine .proc .kill .assert_called_once () 191self .assertNotIn ('STOP' ,engine .proc .stdin .getvalue ()) 192 193def test_polling_keeps_ten_second_heartbeats (self ): 194for control in (False ,True ): 195with self .subTest (control = control ): 196engine = object .__new__ (server .StrataEngine ) 197engine .proc = mock .Mock () 198engine .proc .poll .return_value = None 199engine .proc .stdin = io .StringIO () 200engine .lines = mock .Mock () 201engine .can_stop ,engine .silence_s = True ,0 202engine ._ctl_mode = 'solo' 203engine ._send = mock .Mock () 204now = [0.0 ] 205waits = [] 206 207def get (timeout ): 208waits .append (timeout ) 209if now [0 ]>= 21.0 : 210return 'DONE 0 1 1 0 length' 211now [0 ]+= timeout 212raise queue .Empty 213 214engine .lines .get .side_effect = get 215cancel = threading .Event () 216with mock .patch .object (server .time ,'monotonic' ,lambda :now [0 ]): 217gen = engine ._control (cancel ,lambda t :None )if control else engine .generate ([1 ],1 , {},cancel ) 218heartbeats = list (gen ) 219self .assertEqual (heartbeats , [None ,None ],'a quiet 21 seconds emits two heartbeats, not 42' ) 220self .assertTrue (all (0 < wait <= .5 for wait in waits ),'cancellation uses bounded blocking waits' ) 221engine ._send .assert_not_called () 222self .assertNotIn ('STOP' ,engine .proc .stdin .getvalue ()) 223 224 225if __name__ == '__main__' : 226unittest .main ()