okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
e85f56209
main
1"""SAVE memory settling on a fake clock and real HTTP/FIFO; no GPU or model.""" 2from __future__import annotations 3import io 4from pathlib import Path 5import tempfile 6import threading 7import time 8from types import SimpleNamespace 9import unittest 10from unittest import mock 11 12from serve import session_save_retry as retry 13from serve .frontend import ChatTemplate 14from serve .server import ByteTokenizer ,EngineDied ,Service ,SessionRefused ,serve 15from serve import test_slots as slot_tests 16from serve .test_slots import FakeEngine ,FakeProc 17 18RESULT = {'tokens' :62993 ,'bytes' :1234 ,'ms' :401.5 } 19 20def refused (need = 355 ,floor = 768 ): 21return SessionRefused ('memory' ,f'not enough RAM to save the session ( { need } MiB plus a floor of { floor } MiB needed, 503 MiB available)' ) 22 23class Clock : 24def __init__ (self ):self .now = 0.0 ;self .on_sleep = lambda :None 25def monotonic (self ):return self .now 26def sleep (self ,seconds ): 27assert 0 <= seconds <= .5 28self .now += seconds 29self .on_sleep () 30 31class Retry (unittest .TestCase ): 32def setUp (self ): 33self .clock = Clock () 34self .proc = SimpleNamespace (poll = lambda :None ) 35self .engine = SimpleNamespace (proc = self .proc ,ended = False ,session_file = mock .Mock ()) 36self .service = SimpleNamespace (engine = self .engine ) 37self .clock_patch = mock .patch .object (retry ,'time' ,self .clock ) 38self .clock_patch .start () 39self .addCleanup (self .clock_patch .stop ) 40self .stdout = mock .patch ('sys.stdout' ,new_callable = io .StringIO ) 41self .stdout .start ();self .addCleanup (self .stdout .stop ) 42 43def call (self ,available = 5000 ,action = 'save' ): 44with mock .patch .object (retry ,'available_mib' ,side_effect = available if isinstance (available ,list )else None , 45return_value = None if isinstance (available ,list )else available ): 46return retry .session_file (self .service ,action ,'same.bin' ,SessionRefused ) 47 48def test_success_does_not_poll_or_wait (self ): 49self .engine .session_file .return_value = RESULT 50with mock .patch .object (retry ,'available_mib' ,side_effect = AssertionError ('unexpected memory probe' )): 51self .assertEqual (retry .session_file (self .service ,'save' ,'same.bin' ,SessionRefused ),RESULT ) 52self .assertEqual (self .clock .now ,0 ) 53self .engine .session_file .assert_called_once_with ('save' ,'same.bin' ) 54 55def test_delayed_ram_reuses_same_process_path_and_floor (self ): 56self .engine .session_file .side_effect = [refused (),RESULT ] 57self .assertEqual (self .call ([534 ,541 ,800 ,1400 ]),RESULT ) 58self .assertEqual (self .clock .now ,1.5 ) 59self .assertIs (self .engine .proc ,self .proc ) 60self .assertEqual (self .engine .session_file .call_args_list ,[mock .call ('save' ,'same.bin' )]* 2 ) 61self .assertEqual (retry .required_mib (refused ()),1125 ) 62 63def test_persistent_pressure_expires_without_another_save (self ): 64error = refused ();self .engine .session_file .side_effect = error 65with self .assertRaises (SessionRefused )as got :self .call (541 ) 66self .assertIs (got .exception ,error ) 67self .assertEqual (self .clock .now ,30 ) 68self .assertEqual (self .engine .session_file .call_count ,1 ) 69 70def test_admission_races_are_bounded_and_keep_latest_error (self ): 71errors = [refused (355 + n )for n in range (4 )] 72self .engine .session_file .side_effect = errors 73with self .assertRaises (SessionRefused )as got :self .call () 74self .assertIs (got .exception ,errors [- 1 ]) 75self .assertEqual (self .engine .session_file .call_count ,4 )# first SAVE plus three retries 76self .assertEqual (self .clock .now ,1 ) 77 78def test_new_refusal_rechecks_its_larger_estimate (self ): 79self .engine .session_file .side_effect = [refused (),refused (2048 ),RESULT ] 80self .assertEqual (self .call ([1400 ,1400 ,2900 ]),RESULT ) 81self .assertEqual (self .clock .now ,1 ) 82 83def test_unknown_telemetry_or_estimate_never_retries (self ): 84for error ,available in [(refused (),None ), 85 (SessionRefused ('memory' ,'not enough RAM to save the session' ),5000 ), 86 (SessionRefused ('memory' ,'not enough RAM to save the session (unknown MiB plus a floor of 768 MiB needed,' ),5000 )]: 87with self .subTest (error = error ): 88self .engine .session_file = mock .Mock (side_effect = error ) 89with self .assertRaises (SessionRefused )as got :self .call (available ) 90self .assertIs (got .exception ,error ) 91self .assertEqual (self .engine .session_file .call_count ,1 ) 92 93def test_restore_other_categories_and_published_files_never_retry (self ): 94for action ,error in [('restore' ,refused ()),('save' ,SessionRefused ('io' ,str (refused ()))), 95 ('save' ,SessionRefused ('storage' ,str (refused ()))),('save' ,SessionRefused ('invalid' ,str (refused ()))), 96 ('save' ,SessionRefused ('memory' ,str (refused ()),published = True ))]: 97with self .subTest (action = action ,error = error ): 98self .engine .session_file = mock .Mock (side_effect = error ) 99with self .assertRaises (SessionRefused )as got :self .call (action = action ) 100self .assertIs (got .exception ,error ) 101self .assertEqual (self .engine .session_file .call_count ,1 ) 102 103def test_process_death_or_replacement_ends_wait (self ): 104for change in [lambda :setattr (self .proc ,'poll' ,lambda :1 ), 105lambda :setattr (self .engine ,'proc' ,SimpleNamespace (poll = lambda :None )), 106lambda :setattr (self .service ,'engine' ,SimpleNamespace (proc = self .proc )), 107lambda :setattr (self .engine ,'ended' ,True )]: 108with self .subTest (change = change ): 109self .proc = SimpleNamespace (poll = lambda :None ) 110self .engine = SimpleNamespace (proc = self .proc ,ended = False ,session_file = mock .Mock (side_effect = refused ())) 111self .service .engine = self .engine 112self .clock .now = 0 ;self .clock .on_sleep = change 113with self .assertRaises (SessionRefused ):self .call (541 ) 114self .assertEqual (self .engine .session_file .call_count ,1 ) 115self .assertEqual (self .clock .now ,.5 ) 116 117def test_non_admission_error_during_retry_is_returned (self ): 118for error in [EngineDied ('gone' ),SessionRefused ('io' ,'flushing directory' ,published = True )]: 119self .engine .session_file = mock .Mock (side_effect = [refused (),error ]) 120with self .assertRaises (type (error ))as got :self .call () 121self .assertIs (got .exception ,error ) 122self .assertEqual (self .engine .session_file .call_count ,2 ) 123 124def test_memory_probe_is_portable_and_unknown_fails_closed (self ): 125for value ,expected in [(1400 * 2 ** 20 ,1400 ),(0 ,0 ),(- 1 ,None ),(True ,None ),(None ,None ),(float ('nan' ),None )]: 126with mock .patch .dict ('sys.modules' ,{'psutil' :SimpleNamespace (virtual_memory = lambda :SimpleNamespace (available = value ))}): 127self .assertEqual (retry .available_mib (),expected ) 128 129class AdmissionProc (FakeProc ): 130def write (self ,text ): 131if not self .sent and text .startswith ('SAVE ' ): 132self .sent .append (text ) 133self .engine .lines .put ('SERR memory 0 ' + str (refused ())+ '\n' ) 134return 135super ().write (text ) 136 137class HTTP (unittest .TestCase ): 138post = slot_tests .Slots .post 139def setUp (self ): 140self .directory = tempfile .TemporaryDirectory () 141self .addCleanup (self .directory .cleanup ) 142tok = ByteTokenizer ();self .engine = FakeEngine ();self .engine .session_save_reclaim = True 143self .engine .proc = AdmissionProc (self .engine ) 144self .svc = Service (self .engine ,tok ,ChatTemplate (Path (__file__ ).parent / 'chat_template.jinja' )) 145self .svc .slot_save_path = self .directory .name 146self .httpd = serve (self .svc ,port = 0 ) 147self .base = f'http://127.0.0.1: { self . httpd . server_address [ 1 ] } ' 148self .addCleanup (self .httpd .server_close );self .addCleanup (self .httpd .shutdown ) 149 150def test_opt_in_recovers_native_refusal_and_keeps_response_and_process (self ): 151proc = self .engine .proc 152with mock .patch .object (retry ,'available_mib' ,return_value = 1400 ): 153status ,body = self .post ('/slots/0?action=save' ,{'filename' :'a.bin' }) 154self .assertEqual (status ,200 ,body ) 155self .assertEqual (body ,{'id_slot' :0 ,'filename' :'a.bin' ,'n_saved' :62993 ,'n_written' :1234 ,'timings' :{'save_ms' :401.5 }}) 156self .assertEqual (proc .sent ,[f'SAVE { Path ( self . directory . name , "a.bin" ) } \n' ]* 2 ) 157self .assertIs (self .engine .proc ,proc );self .assertFalse (self .engine .ended ) 158self .assertEqual (Path (self .directory .name ,'a.bin' ).read_bytes (),b'x' * 1234 ) 159 160def test_default_refusal_is_immediate_and_byte_identical (self ): 161self .engine .session_save_reclaim = False 162with mock .patch .object (retry ,'available_mib' ,side_effect = AssertionError ('default must not probe' )): 163status ,body = self .post ('/slots/0?action=save' ,{'filename' :'off.bin' }) 164self .assertEqual (status ,503 ) 165self .assertEqual (body ,{'error' :{'code' :503 ,'message' :str (refused ()),'type' :'server_error' ,'kind' :'memory' }}) 166self .assertEqual (len (self .engine .proc .sent ),1 ) 167self .assertFalse (Path (self .directory .name ,'off.bin' ).exists ()) 168 169def test_fifo_blocks_restore_while_save_waits_and_releases_afterwards (self ): 170waiting = threading .Event ();enough = threading .Event () 171def available ():waiting .set ();return 1400 if enough .is_set ()else 541 172result = {} 173path = Path (self .directory .name ,'fifo.bin' );path .write_bytes (b'old file' ) 174a = threading .Thread (target = lambda :result .update (save = self .post ('/slots/0?action=save' ,{'filename' :'fifo.bin' }))) 175b = threading .Thread (target = lambda :result .update (restore = self .post ('/slots/0?action=restore' ,{'filename' :'fifo.bin' }))) 176with mock .patch .object (retry ,'available_mib' ,side_effect = available ),mock .patch .object (retry ,'POLL_SECONDS' ,.01 ): 177try : 178a .start ();self .assertTrue (waiting .wait (2 ));b .start () 179deadline = time .monotonic ()+ 2 180while self .svc .status ['queued' ]!= 1 and time .monotonic ()< deadline :time .sleep (.01 ) 181self .assertTrue (self .svc .status ['busy' ]);self .assertEqual (self .svc .status ['queued' ],1 ) 182self .assertEqual (len (self .engine .proc .sent ),1 ) 183finally : 184enough .set ();a .join (5 ) 185if b .ident is not None :b .join (5 ) 186self .assertFalse (a .is_alive ()or b .is_alive ()) 187self .assertEqual (result ['save' ][0 ],200 );self .assertEqual (result ['restore' ][0 ],200 ) 188self .assertEqual (self .engine .proc .sent ,[f'SAVE { path } \n' ,f'SAVE { path } \n' ,f'RESTORE { path } \n' ]) 189self .assertFalse (self .svc .status ['busy' ]);self .assertEqual (self .svc .status ['queued' ],0 ) 190self .assertTrue (self .svc .fifo .acquire (blocking = False ));self .svc .fifo .release () 191 192if __name__ == '__main__' :unittest .main ()