okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
0fff115df
main
1"""Real pipe/process protocol regression for a native ERR that leaves its process alive.""" 2import os 3from pathlib import Path 4import sys 5import tempfile 6import threading 7import time 8import unittest 9import json 10import urllib .request 11from serve .server import StrataEngine ,Service ,ChatTemplate ,EngineDied ,serve 12from serve .test_server import ByteTokenizer 13 14FAKE = r''' 15import sys 16from pathlib import Path 17state=Path(sys.argv[sys.argv.index('--state')+1]) 18mode=sys.argv[sys.argv.index('--mode')+1] 19print('READY 4096 stop',flush=True) 20for line in sys.stdin: 21if line.startswith('QUIT'):break 22if line.startswith(('GEN','BGEN')): 23if not state.exists(): 24state.write_text('first request was attempted') 25if mode=='invalid':print('ERR prompt exceeds context',flush=True) 26else: 27kind='verify batch' if mode=='batch' else 'verify' 28print(f'ERR {kind}: timed out at layer 18; its GPU waits were released and the GPU finished (#267)',flush=True) 29print('DONE 0 1 0 1 error',flush=True) 30continue 31print('T 90\nDONE 1 1 0 1 stop',flush=True) 32''' 33 34class FatalRecovery (unittest .TestCase ): 35def setUp (self ): 36self .tmp = tempfile .TemporaryDirectory ();self .addCleanup (self .tmp .cleanup ) 37self .root = Path (self .tmp .name );py = self .root / 'native.py' 38if os .name == 'nt' :# no shebangs on Windows: a .cmd runs the same fake engine 39py .write_text (FAKE );self .script = self .root / 'native.cmd' 40self .script .write_text (f'@" { sys . executable } " " { py } " %*\r\n' ) 41else : 42self .script = py ;py .write_text ('#!' + sys .executable + '\n' + FAKE );py .chmod (0o700 ) 43def engine (self ,mode = 'fatal' ): 44e = StrataEngine (str (self .script ),['--state' ,str (self .root / 'state' ),'--mode' ,mode ]) 45self .addCleanup (e .close );return e 46def service (self ,e ): 47return Service (e ,ByteTokenizer (),ChatTemplate (Path (__file__ ).parent / 'chat_template.jinja' )) 48def wait_dead (self ,e ): 49end = time .monotonic ()+ 2 50while e .alive ()and time .monotonic ()< end :time .sleep (.01 ) 51self .assertFalse (e .alive (),'unrecoverable native ERR must invalidate health before a new request' ) 52def run_request (self ,svc ): 53return list (svc .run ([1 ],False ,[],8 ,{},threading .Event ())) 54def test_fatal_error_is_not_a_success_and_next_request_reloads (self ): 55e = self .engine ();svc = self .service (e ) 56with self .assertRaises (EngineDied ):self .run_request (svc ) 57self .wait_dead (e ) 58self .assertIs (svc .engine ,e ,'the failed request must not be retried automatically' ) 59self .assertEqual (svc .history [- 1 ]['finish' ],'error' ) 60result = self .run_request (svc );self .addCleanup (svc .engine .close ) 61self .assertTrue (svc .engine .alive ()) 62self .assertTrue (svc .loaded ());self .assertEqual (result [- 1 ][1 ]['completion_tokens' ],1 ) 63def test_http_health_and_next_request_recovery (self ): 64old = self .engine ();svc = self .service (old );http = serve (svc ,port = 0 ) 65base = f'http://127.0.0.1: { http . server_address [ 1 ] } ' 66body = {'messages' :[{'role' :'user' ,'content' :'hi' }],'max_tokens' :8 , 67'chat_template_kwargs' :{'enable_thinking' :False },'stream' :True } 68try : 69def post (): 70req = urllib .request .Request (base + '/v1/chat/completions' ,data = json .dumps (body ).encode (),headers = {'Content-Type' :'application/json' }) 71with urllib .request .urlopen (req ,timeout = 5 )as r :return r .read ().decode () 72text = post () 73self .assertIn ('"error"' ,text );self .assertTrue (text .rstrip ().endswith ('data: [DONE]' )) 74with urllib .request .urlopen (base + '/health' ,timeout = 5 )as r :self .assertFalse (json .load (r )['loaded' ]) 75body ['stream' ]= False 76self .assertEqual (json .loads (post ())['usage' ]['completion_tokens' ],1 ) 77with urllib .request .urlopen (base + '/health' ,timeout = 5 )as r :self .assertTrue (json .load (r )['loaded' ]) 78finally : 79http .shutdown ();http .server_close ();svc .engine .close () 80def test_batch_timeout_signature_also_invalidates_engine (self ): 81e = self .engine ('batch' ) 82with self .assertRaises (EngineDied ):list (e .generate ([1 ],8 ,{},threading .Event ())) 83self .wait_dead (e ) 84 85def feed (self ,e ,lines ,slots ): 86import queue 87class P : 88stdout = iter (lines ) 89terminated = False 90def terminate (self ):self .terminated = True 91old = e .proc ;e .proc = P ();e .lines = queue .Queue ();e .slot_q = [queue .Queue ()for _ in range (slots )];e .ended = False 92e ._pump () 93self .assertTrue (e .ended );self .assertTrue (e .proc .terminated ) 94self .assertIsNone (e .lines .get_nowait ());self .assertTrue (e .lines .empty ())# EOF, never the trailing DONE 95e .proc = old 96def test_fatal_lines_are_checked_before_batch_routing (self ): 97e = self .engine ('fatal' ) 98self .feed (e ,['ERR verify batch: timed out at layer 3\n' ,'BDONE 0 1 0 1 error\n' ],2 ) 99self .assertTrue (all (q .get_nowait ()is None and q .empty ()for q in e .slot_q ))# only the EOF reached a slot, not the BDONE 100def test_an_earlier_window_never_finished_is_fatal (self ): 101e = self .engine ('fatal' ) 102self .feed (e ,['ERR verify: an earlier window never finished on the GPU (#267); restart the engine\n' ,'DONE 0 1 0 1 error\n' ],0 ) 103self .feed (e ,['ERR verify batch: an earlier window never finished on the GPU (#267)\n' ],2 ) 104def test_generate_batched_refuses_a_dead_engine (self ): 105e = self .engine ('fatal' );e .close () 106with self .assertRaises (EngineDied ):list (e .generate_batched ([1 ],8 ,{},threading .Event ())) 107 108def test_validation_error_does_not_kill_engine (self ): 109e = self .engine ('invalid' ) 110with self .assertRaises (ValueError ):list (e .generate ([1 ],8 ,{},threading .Event ())) 111self .assertTrue (e .alive ()) 112self .assertEqual (list (e .generate ([1 ],8 ,{},threading .Event ())),[90 ]) 113def test_closed_serial_engine_rejects_without_accessing_closed_pipe (self ): 114e = self .engine ();e .close () 115with self .assertRaises (EngineDied ):list (e .generate ([1 ],8 ,{},threading .Event ())) 116if __name__ == '__main__' :unittest .main ()