okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
fd0e3766a
main
1"""An install made by today's Strata is found and used in place by the terminal. 2 3The fixture is today's layout: a Strata folder with strata-<model>.json run configs (absolute paths into it and into 4the data folder), an engine/ folder, run-<model> scripts, a .venv, and a separate data folder (Strata-data) holding the 5GGUF files, prepared packs and the MTP layer; the user's settings.json remembers the data folder and the install. The 6terminal archive is a NEW folder. Nothing may be copied, moved, created or rewritten in the old layout, and the real 7settings file and model folders are never touched: everything lives in a temporary directory, the settings file 8location is redirected (conftest.py does the same for the whole session). 9""" 10 11import contextlib 12import hashlib 13import io 14import json 15import os 16import sys 17import tempfile 18import unittest 19from pathlib import Path 20from unittest import mock 21 22import setup 23from strata_cli .cli import main 24from strata_control import models ,profiles 25 26from tests .terminal .test_models import gguf_fixture 27 28 29def snapshot (base :Path )-> dict : 30out = {} 31for path in sorted (base .rglob ("*" )): 32rel = path .relative_to (base ).as_posix () 33if path .is_dir (): 34out [rel ]= ("dir" ,) 35else : 36out [rel ]= ("file" ,path .stat ().st_size ,path .stat ().st_mtime_ns , 37hashlib .sha256 (path .read_bytes ()).hexdigest ()) 38return out 39 40 41class ExistingInstallIsFoundInPlace (unittest .TestCase ): 42def setUp (self ): 43self .tmp = tempfile .TemporaryDirectory () 44self .addCleanup (self .tmp .cleanup ) 45base = Path (self .tmp .name ) 46self .appdata = base / "appdata" 47self .old = base / "Strata" # today's install (a checkout or an unzipped release) 48self .data = base / "Strata-data" # the data folder settings.json remembers 49self .terminal = base / "Strata-terminal" # the new archive, extracted elsewhere 50self .profiles = base / "profiles" # profile storage is outside both layouts 51for d in (self .appdata ,self .old ,self .data ,self .terminal ): 52d .mkdir () 53env = mock .patch .dict (os .environ , {"APPDATA" :str (self .appdata ),"XDG_CONFIG_HOME" :str (self .appdata ), 54"STRATA_PROFILE_DIR" :str (self .profiles ), 55"STRATA_RUNTIME_DIR" :str (base / "runtime" ), 56# the desktop app's folders of whoever runs the tests are not part of this fixture 57"LOCALAPPDATA" :str (base / "local" ),"XDG_DATA_HOME" :str (base / "localshare" ), 58"STRATA_COMPONENTS_DIR" :"" }) 59env .start () 60self .addCleanup (env .stop ) 61os .environ .pop ("STRATA_INSTALL_DIR" ,None ) 62 63exe_name = "strata.exe" if os .name == "nt" else "strata" 64 (self .old / "engine" ).mkdir () 65 (self .old / "engine" / exe_name ).write_bytes (b"engine" ) 66 (self .old / "engine" / exe_name ).chmod (0o700 ) 67 (self .old / "engine" / "BUILD.json" ).write_text (json .dumps ({"version" :"0.1.45" ,"source" :"prebuilt" })) 68 (self .old / "setup.py" ).write_text ("# the installer of the old folder\n" ) 69 (self .old / ".venv" ).mkdir () 70 (self .old / ".venv" / "pyvenv.cfg" ).write_text ("home = elsewhere\n" ) 71tok = self .data / "packs" / "tokenizer" 72tok .mkdir (parents = True ) 73for name in ("vocab.json" ,"merges.txt" ,"token_type.json" ): 74 (tok / name ).write_bytes (b"placeholder" ) 75self .models = [] 76for tag ,ctx in (("q2_0" ,32768 ), ("iq3_xxs" ,65536 )): 77folder = self .data / "models" / tag .upper () 78folder .mkdir (parents = True ) 79gguf = folder / f"Qwen3.8-Flash-Next- { tag } -00001-of-00001.gguf" 80gguf .write_bytes (gguf_fixture ()) 81pack = self .data / "packs" / tag 82pack .mkdir () 83 (pack / "experts.bin" ).write_bytes (b"experts" ) 84mtp = self .data / "mtp" / tag 85mtp .mkdir (parents = True ) 86cfg = self .old / f"strata- { tag } .json" 87cfg .write_text (json .dumps ({ 88"exe" :str (self .old / "engine" / exe_name ),"tokenizer" :str (tok ),"cwd" :str (self .old ), 89"args" : ["--native" ,str (gguf ),"--pack" ,str (pack ),"--mtp" ,str (mtp ),"--max-context" ,str (ctx )], 90"backend" :"cuda" ,"model_name" :tag .upper (),"port" :8080 ,"log" :str (self .old / f" { tag } .log" )}), 91encoding = "utf-8" ) 92 (self .old / f"strata- { tag } .shared-settings.json" ).write_text ("{}" ) 93 (self .old / (f"run- { tag } .bat" if os .name == "nt" else f"run- { tag } .sh" )).write_text ("run\n" ) 94self .models .append (cfg ) 95 (self .terminal / "VERSION" ).write_text ("0.1.45\n" ) 96# never the real settings file or model folders: everything below lives in the temporary directory 97self .assertTrue (str (setup .settings_path ()).startswith (str (base )),setup .settings_path ()) 98setup .settings_path ().parent .mkdir (parents = True ) 99setup .settings_path ().write_text (json .dumps ({"data_dir" :str (self .data ),"installs" : [str (self .old )]})) 100self .before = snapshot (base ) 101self .base = base 102root = mock .patch .object (models ,"ROOT" ,self .terminal ) 103root .start () 104self .addCleanup (root .stop ) 105 106def cli (self ,* args ): 107out = io .StringIO () 108with contextlib .redirect_stdout (out ): 109code = main ([* args ,"--output" ,"json" ]) 110return code ,json .loads (out .getvalue ()) 111 112def assertNothingChanged (self ): 113after = snapshot (self .base ) 114created = sorted (set (after )- set (self .before )) 115self .assertEqual ([c for c in created if not c .startswith ("profiles" )], []) 116for rel ,was in self .before .items (): 117self .assertEqual (after .get (rel ),was ,rel ) 118 119def test_the_terminal_finds_the_old_install_through_settings_json (self ): 120self .assertEqual (models .resolve_install (), (self .old .resolve (),"remembered" )) 121code ,listed = self .cli ("models" ,"list" ,"--installed" ) 122self .assertEqual (code ,0 ) 123self .assertEqual (listed ["install_dir" ],str (self .old .resolve ())) 124self .assertEqual (listed ["install_dir_source" ],"remembered" ) 125self .assertEqual ([m ["id" ]for m in listed ["models" ]], ["iq3_xxs" ,"q2_0" ]) 126self .assertEqual ({m ["component_status" ]for m in listed ["models" ]}, {"present" }) 127self .assertEqual ({m ["context_tokens" ]for m in listed ["models" ]}, {32768 ,65536 }) 128code ,inspected = self .cli ("models" ,"inspect" ,"q2_0" ) 129self .assertEqual (code ,0 ) 130self .assertTrue (inspected ["components" ]["ok" ]) 131self .assertNothingChanged () 132 133def test_a_profile_and_serve_plan_use_the_old_engine_and_models_where_they_are (self ): 134found = models .install_dir () 135config = found / "strata-q2_0.json" 136profiles .create ("migrated" ,str (config )) 137code ,planned = self .cli ("serve" ,"--profile" ,"migrated" ,"--plan" ) 138self .assertEqual (code ,0 ) 139plan = planned ["plan" ] 140self .assertEqual (Path (plan ["source_config" ]),config .resolve ()) 141self .assertEqual (Path (plan ["engine_exe" ]).parent ,self .old / "engine" ) 142argv = plan ["engine_argv" ] 143native = argv [argv .index ("--native" )+ 1 ] 144self .assertEqual (Path (native ).parent .parent .parent ,self .data )# Strata-data/models/Q2_0/<gguf> 145self .assertNothingChanged () 146 147def test_a_folder_with_its_own_configs_and_an_explicit_dir_win_over_the_remembered_install (self ): 148 (self .terminal / "strata-local.json" ).write_bytes ((self .old / "strata-q2_0.json" ).read_bytes ()) 149self .assertEqual (models .resolve_install (), (self .terminal ,"here" )) 150 (self .terminal / "strata-local.json" ).unlink () 151self .assertEqual (models .resolve_install (str (self .old )), (self .old .resolve (),"explicit" )) 152with mock .patch .dict (os .environ , {"STRATA_INSTALL_DIR" :str (self .old )}): 153self .assertEqual (models .resolve_install ()[1 ],"explicit" ) 154 155def test_nothing_remembered_means_this_folder_and_no_error (self ): 156# nothing found anywhere: the folder a new model would be installed into (the desktop app's, which the Terminal shares), no error 157from strata_control import discovery 158default = (discovery .app_install_dir (),"default" ) 159setup .settings_path ().unlink () 160self .assertEqual (models .resolve_install (),default ) 161setup .settings_path ().write_text ("not json" ) 162self .assertEqual (models .resolve_install (),default ) 163setup .settings_path ().write_text (json .dumps ({"installs" : ["relative/path" ,7 ,str (self .base / "gone" )]})) 164self .assertEqual (models .resolve_install (),default ) 165self .assertEqual (models .list_installed ()["models" ], []) 166 167def test_the_settings_path_is_the_one_setup_writes (self ): 168self .assertEqual (models .settings_path (),setup .settings_path ()) 169 170def test_a_plain_start_from_the_old_folder_uses_the_remembered_data_folder_and_moves_nothing (self ): 171started = [] 172out = io .StringIO () 173with mock .patch .object (setup ,"ROOT" ,self .old ),mock .patch .object (sys ,"argv" , ["setup.py" ,"--yes" ]), \ 174mock .patch .object (setup ,"gpus" ,lambda : []), \ 175mock .patch .object (setup .subprocess ,"call" ,lambda cmd ,* a ,** k :started .append (cmd )or 0 ), \ 176contextlib .redirect_stdout (out ): 177self .assertEqual (setup .main (),0 ,out .getvalue ()) 178self .assertEqual (len (started ),1 ) 179self .assertIn ("server.py" ," " .join (map (str ,started [0 ]))) 180self .assertEqual (setup .data_folder_in_place (), (self .data , [])) 181# starting touches the most recently used config (its mtime) and nothing else 182after = snapshot (self .base ) 183changed = [rel for rel in self .before if after .get (rel )!= self .before [rel ]] 184self .assertEqual ([c for c in changed if not c .startswith ("Strata/strata-" )], []) 185self .assertEqual (sorted (set (after )- set (self .before )), []) 186 187def test_setup_from_a_new_copy_reuses_the_data_folder_and_moves_no_model_file (self ): 188"""The explicit setup path (which does gather files) finds the model files already in the data folder.""" 189new_copy = self .base / "Strata-new" 190new_copy .mkdir () 191 (new_copy / "setup.py" ).write_text ("# a new copy\n" ) 192models_before = {k :v for k ,v in self .before .items ()if k .startswith ("Strata-data/" )} 193with mock .patch .object (setup ,"ROOT" ,new_copy ),contextlib .redirect_stdout (io .StringIO ()): 194data ,elsewhere = setup .data_folder (None ) 195self .assertTrue (data .samefile (self .data )) 196self .assertEqual (elsewhere , []) 197after = snapshot (self .base ) 198self .assertEqual ({k :v for k ,v in after .items ()if k .startswith ("Strata-data/" )},models_before ) 199self .assertEqual ({k :v for k ,v in after .items ()if k .startswith ("Strata/" )}, 200 {k :v for k ,v in self .before .items ()if k .startswith ("Strata/" )}) 201saved = json .loads (setup .settings_path ().read_text ()) 202self .assertTrue (Path (saved ["data_dir" ]).samefile (self .data )) 203self .assertIn (str (self .old ),saved ["installs" ])# the old install stays remembered 204 205 206if __name__ == "__main__" : 207unittest .main ()