okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
4fb068a8c
main
1"""Fixes after the TUI stress re-run on 67a48427b: a failed start cleans up and quotes this attempt's logs, the Folder text, the save/restart order, 2the saved config without --mtp when drafting is off, and the reused-pack line.""" 3 4import json 5import os 6import socket 7import tempfile 8import unittest 9from pathlib import Path 10from unittest import mock 11 12from strata_cli .launch import settings as S 13from strata_cli .launch import runner as R 14from strata_cli .launch .catalog import Catalog 15from strata_cli .launch .runner import LaunchError ,Runner 16from tests .terminal .launch_support import HW_12 ,Home ,catalog 17 18 19class FailedStart (unittest .TestCase ): 20def setUp (self ): 21self .home = Home ().__enter__ () 22self .addCleanup (self .home .__exit__ ,None ,None ,None ) 23p = mock .patch .object (Catalog ,"hardware" ,lambda self ,fresh = False :dict (HW_12 ,disk_free_gb = 500.0 )) 24p .start () 25self .addCleanup (p .stop ) 26self .tmp = tempfile .TemporaryDirectory () 27self .addCleanup (self .tmp .cleanup ) 28self .base = Path (self .tmp .name ) 29 30def runner (self ,port = 8080 ): 31s = S .LaunchSettings (family = "qwen" ,model = "IQ3_XXS" ,context = 32768 ,name = "gyro" ,port = port ) 32r = Runner (s ,catalog = catalog ()) 33r .said = [] 34r .emit_cb = lambda e :r .said .append (e .text ) 35return r 36 37def test_a_busy_port_is_said_before_anything_starts (self ): 38with socket .socket ()as srv : 39srv .bind (("127.0.0.1" ,0 )) 40srv .listen (1 ) 41port = srv .getsockname ()[1 ] 42r = self .runner (port ) 43with mock .patch ("strata_control.runtime.status" ,return_value = {"state" :"stopped" }), \ 44mock .patch ("strata_control.runtime.start" ,side_effect = AssertionError ("must not start" )): 45with self .assertRaises (LaunchError )as cm : 46r .start () 47self .assertIn (f"Port { port } is already in use by another program." ,cm .exception .text ) 48self .assertIn ("--port" ,cm .exception .next ) 49 50def test_the_cause_comes_from_this_attempts_server_log_not_the_old_engine_log (self ): 51engine = self .base / "engine.log" 52server = self .base / "srv.log" 53engine .write_text ("strata verify: captured the 2-token window\nlong ago error: old cause\n" ) 54server .write_text ("" ) 55cfg = self .base / "cfg.json" 56cfg .write_text (json .dumps ({"log" :str (engine )})) 57marks = {str (engine ):engine .stat ().st_size ,str (server ):0 } 58with open (server ,"a" )as f : 59f .write ("server.py: error: port 8190 is already in use - is Strata (or another server) already running?\n" ) 60text ,nxt = R .explain_engine_exit ({"state" :"failed" ,"error" :"server_exited" ,"engine_exit_code" :2 },cfg ,marks = marks ,server_log = server ) 61self .assertIn ("Port 8190 is already in use by another program." ,text ) 62self .assertIn ("--port 8191" ,nxt ) 63self .assertNotIn ("old cause" ,text + nxt ) 64self .assertNotIn ("captured the 2-token" ,text + nxt ) 65 66def test_an_old_engine_log_is_never_quoted_when_this_attempt_wrote_nothing (self ): 67engine = self .base / "engine.log" 68engine .write_text ("error: from the earlier successful run\n" ) 69cfg = self .base / "cfg.json" 70cfg .write_text (json .dumps ({"log" :str (engine )})) 71marks = {str (engine ):engine .stat ().st_size } 72text ,_ = R .explain_engine_exit ({"state" :"failed" ,"error" :"server_exited" },cfg ,marks = marks ,server_log = None ) 73self .assertNotIn ("earlier successful run" ,text ) 74 75def test_a_failed_start_ends_its_own_host (self ): 76r = self .runner () 77r .config_path = None 78calls = [] 79with mock .patch ("strata_control.runtime.status" ,return_value = {"state" :"stopped" }), \ 80mock .patch .object (Runner ,"check_port_free" ), \ 81mock .patch ("strata_control.runtime.start" ,return_value = {"ok" :False ,"state" :"failed" ,"error" :"server_exited" ,"engine_exit_code" :2 }), \ 82mock .patch ("strata_control.runtime.stop" ,side_effect = lambda n ,timeout = 0 :calls .append (("stop" ,n ))), \ 83mock .patch ("strata_control.runtime.cleanup" ,side_effect = lambda n = None :calls .append (("cleanup" ,n ))): 84with self .assertRaises (LaunchError ): 85r .start () 86self .assertEqual (calls , [("stop" ,"launch-gyro" ), ("cleanup" ,"launch-gyro" )]) 87 88def test_a_start_that_raises_also_ends_its_host (self ): 89r = self .runner () 90calls = [] 91with mock .patch ("strata_control.runtime.status" ,return_value = {"state" :"stopped" }), \ 92mock .patch .object (Runner ,"check_port_free" ), \ 93mock .patch ("strata_control.runtime.start" ,side_effect = RuntimeError ("runtime host failed to start" )), \ 94mock .patch ("strata_control.runtime.stop" ,side_effect = lambda n ,timeout = 0 :calls .append ("stop" )), \ 95mock .patch ("strata_control.runtime.cleanup" ,side_effect = lambda n = None :calls .append ("cleanup" )): 96with self .assertRaises (LaunchError ): 97r .start () 98self .assertEqual (calls , ["stop" ,"cleanup" ]) 99 100 101class FolderChangeMovesNothing (unittest .TestCase ): 102"""The Folder step text: changing the folder never moves the models Strata already keeps (only --move-data / strata models move do).""" 103 104def setUp (self ): 105self .home = Home ().__enter__ () 106self .addCleanup (self .home .__exit__ ,None ,None ,None ) 107p = mock .patch .object (Catalog ,"hardware" ,lambda self ,fresh = False :dict (HW_12 ,disk_free_gb = 500.0 )) 108p .start () 109self .addCleanup (p .stop ) 110 111def test_start_passes_no_move_flag_unless_asked (self ): 112s = S .LaunchSettings (family = "qwen" ,model = "IQ3_XXS" ,context = 32768 ,data_dir = str (self .home .base / "new" )) 113self .assertNotIn ("--move-data" ,Runner (s ,catalog = catalog ()).setup_args ()) 114self .assertIn ("--move-data" ,Runner (s ,catalog = catalog (),move_data = True ).setup_args ()) 115 116def test_setup_keeps_the_existing_models_where_they_are (self ): 117import contextlib 118import io 119import setup 120base = self .home .base 121old ,new ,root = base / "old-data" ,base / "new-data" ,base / "Strata" 122root .mkdir () 123weights = old / "models" / "Q2_0" / "w.gguf" 124weights .parent .mkdir (parents = True ) 125weights .write_bytes (b"x" * 100 ) 126env = {"APPDATA" :str (base / "appdata" ),"XDG_CONFIG_HOME" :str (base / "appdata" )} 127with mock .patch .dict (os .environ ,env ),mock .patch .object (setup ,"ROOT" ,root ),mock .patch .object (setup ,"_CONTROL_HOME" ,None ): 128os .environ .pop ("STRATA_SETTINGS_FILE" ,None ) 129setup .settings_path ().parent .mkdir (parents = True ,exist_ok = True ) 130setup .settings_path ().write_text (json .dumps ({"data_dir" :str (old ),"installs" : []}),encoding = "utf-8" ) 131with contextlib .redirect_stdout (io .StringIO ()): 132setup .data_folder (str (new ),move = False ,yes = True ,set_default = True ) 133self .assertTrue (weights .is_file ()) 134self .assertFalse ((new / "models" ).exists ()) 135 136def test_the_screen_text_says_they_stay (self ): 137src = open (os .path .join (os .path .dirname (R .__file__ ),"screens.py" ),encoding = "utf-8" ).read () 138self .assertIn ("stay there and keep working" ,src ) 139self .assertNotIn ("are moved into this folder when you start" ,src ) 140 141 142class SaveWaitsForRestartAnswer (unittest .TestCase ): 143"""Save as a preset and launch: nothing is saved before the restart question is answered Restart.""" 144 145def _runner (self ,** kw ): 146s = S .LaunchSettings (family = "qwen" ,model = "IQ3_XXS" ,context = 32768 ,name = "gyro" ) 147return Runner (s ,catalog = catalog (),** kw ) 148 149def setUp (self ): 150self .home = Home ().__enter__ () 151self .addCleanup (self .home .__exit__ ,None ,None ,None ) 152p = mock .patch .object (Catalog ,"hardware" ,lambda self ,fresh = False :dict (HW_12 ,disk_free_gb = 500.0 )) 153p .start () 154self .addCleanup (p .stop ) 155 156def rows (self ,r ): 157return [{"profile" :"launch-gyro" ,"name" :"gyro" ,"port" :8080 , 158"choices" : {** r .choices (),"context" :65536 ,"family" :"qwen" ,"model" :"IQ3_XXS" }}] 159 160def test_cancel_saves_nothing_and_the_question_names_the_running_model (self ): 161saved ,asked = [], [] 162r = self ._runner (confirm_restart = lambda q ,d :asked .append ((q ,d ))or False ,after_check = lambda :saved .append (1 )) 163with mock .patch .object (Runner ,"serving_launches" ,lambda self :self .rows_ ): 164Runner .rows_ = self .rows (r ) 165with self .assertRaises (LaunchError ): 166r .run () 167self .assertEqual (saved , []) 168self .assertIn ("is running on port 8080 with 64K. Restart it with these settings?" ,asked [0 ][0 ]) 169self .assertIn ("IQ3_XXS" ,asked [0 ][0 ]) 170self .assertEqual (asked [0 ][1 ],"Answers in progress stop." ) 171 172def test_restart_saves_after_the_answer (self ): 173order = [] 174r = self ._runner (confirm_restart = lambda q ,d :order .append ("asked" )or True ,after_check = lambda :order .append ("saved" )) 175Runner .rows_ = self .rows (r ) 176with mock .patch .object (Runner ,"serving_launches" ,lambda self :self .rows_ ),mock .patch .object (Runner ,"ensure_engine" ,side_effect = RuntimeError ("went on" )): 177with self .assertRaises (RuntimeError ): 178r .run () 179self .assertEqual (order , ["asked" ,"saved" ]) 180 181def test_nothing_running_saves_at_once (self ): 182saved = [] 183r = self ._runner (after_check = lambda :saved .append (1 )) 184with mock .patch .object (Runner ,"serving_launches" ,lambda self : []),mock .patch .object (Runner ,"ensure_engine" ,side_effect = RuntimeError ("went on" )): 185with self .assertRaises (RuntimeError ): 186r .run () 187self .assertEqual (saved , [1 ]) 188 189def test_the_save_screen_no_longer_writes_the_preset_itself (self ): 190import asyncio 191from strata_cli .launch import store 192from tests .terminal .test_launch_tui import Base ,FakeRunner ,press ,make_ctx 193from strata_cli .launch .app import LaunchApp 194 195class Case (Base ): 196def runTest (self ): 197pass 198 199case = Case () 200case .setUp () 201self .addCleanup (case .tearDown ) 202seen = {} 203 204class Holding (FakeRunner ): 205def run (self ,start = True ): 206seen ["presets_during_run" ]= [p .name for p in store .list_presets ()] 207return super ().run (start ) 208 209with mock .patch ("strata_cli.launch.app.Runner" ,Holding ): 210async def go (): 211app = LaunchApp (make_ctx ()) 212async with app .run_test (size = (110 ,34 ))as pilot : 213await pilot .pause (0.2 ) 214await press (pilot ,* ("enter" ,)* 7 ,"n" ,"enter" ) 215self .assertEqual (store .list_presets (), [])# still nothing on the Save screen 216await press (pilot ,"enter" ) 217await pilot .pause (0.8 ) 218return [p .name for p in store .list_presets ()] 219after = asyncio .run (go ()) 220self .assertEqual (seen ["presets_during_run" ], [])# not saved before the runner's check 221self .assertEqual (after , ["IQ3_S 128K" ])# saved once the run went on 222 223 224class DraftingOffConfig (unittest .TestCase ): 225"""B10: the saved launch config has no --mtp in args when "mtp" is false, whatever made it false.""" 226 227BASE = {"args" : ["--model" ,"m.gguf" ,"--mtp" ,"C:/x/mtp" ,"--spec-min-p" ,"0.5" ,"--batch-mtp" ,"--max-context" ,"32768" ],"exe" :"x" } 228 229def derive (self ,base ,** kw ): 230from strata_control import tune_knobs 231s = S .LaunchSettings (family = "gyro" ,model = "Gyro-S" ,context = 32768 ,** kw ) 232return R .derive_config (base ,s ,bool_flags = tune_knobs .BOOL_FLAGS ) 233 234def test_drafting_off_and_mtp_off (self ): 235for kw in ({"drafting" :"off" }, {"mtp" :"off" }, {"drafting" :"off" ,"extra" : {"prefill" :"4096" }}): 236with self .subTest (kw = kw ): 237cfg = self .derive (self .BASE ,** kw ) 238self .assertIs (cfg ["mtp" ],False ) 239self .assertNotIn ("--mtp" ,cfg ["args" ]) 240self .assertIn ("--max-context" ,cfg ["args" ]) 241 242def test_an_installed_config_that_already_says_mtp_false (self ): 243cfg = self .derive ({** self .BASE ,"mtp" :False }) 244self .assertIs (cfg ["mtp" ],False ) 245self .assertNotIn ("--mtp" ,cfg ["args" ]) 246self .assertNotIn ("--spec-min-p" ,cfg ["args" ]) 247 248def test_mtp_stays_when_it_is_on (self ): 249cfg = self .derive (self .BASE ) 250self .assertIn ("--mtp" ,cfg ["args" ]) 251 252 253class ReusedDataLine (unittest .TestCase ): 254"""C08 note: one line says where the pack and the draft layer are read from.""" 255 256def setUp (self ): 257self .home = Home ().__enter__ () 258self .addCleanup (self .home .__exit__ ,None ,None ,None ) 259p = mock .patch .object (Catalog ,"hardware" ,lambda self ,fresh = False :dict (HW_12 ,disk_free_gb = 500.0 )) 260p .start () 261self .addCleanup (p .stop ) 262self .tmp = tempfile .TemporaryDirectory () 263self .addCleanup (self .tmp .cleanup ) 264self .base = Path (self .tmp .name ) 265 266def runner (self ,cfg_args ,** fields ): 267cfg = self .base / "strata-x.json" 268cfg .write_text (json .dumps ({"args" :cfg_args })) 269s = S .LaunchSettings (family = "qwen" ,model = "Q2_0" ,context = 32768 ,** fields ) 270r = Runner (s ,catalog = catalog ()) 271r .said = [] 272r .emit_cb = lambda e :r .said .append (e .text ) 273return r ,cfg 274 275def test_pack_and_draft_layer_from_the_old_folder_are_named (self ): 276old = self .base / "dl-data" 277r ,cfg = self .runner (["--pack" ,str (old / "packs" / "x" ),"--mtp" ,str (old / "mtp" / "rt" )], 278model_path = str (self .base / "docs" ),data_dir = str (self .base / "c08-data" )) 279r .say_reused_data (cfg ) 280self .assertEqual (len (r .said ),1 ) 281self .assertIn ("the prepared pack and the draft layer are read from" ,r .said [0 ].lower ()) 282self .assertIn ("dl-data" ,r .said [0 ]) 283self .assertIn ("nothing was copied" ,r .said [0 ]) 284 285def test_no_line_when_they_are_in_the_given_folder_or_nothing_was_given (self ): 286new = self .base / "c08-data" 287r ,cfg = self .runner (["--pack" ,str (new / "packs" / "x" )],model_path = str (self .base / "docs" ),data_dir = str (new )) 288r .say_reused_data (cfg ) 289self .assertEqual (r .said , []) 290r ,cfg = self .runner (["--pack" ,str (self .base / "o" / "packs" / "x" )],model_path = str (self .base / "docs" )) 291r .say_reused_data (cfg ) 292self .assertEqual (r .said , []) 293 294 295if __name__ == "__main__" : 296unittest .main ()