okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
714ff8242
main
1"""A start through the owner runtime finds its engine in the component folder, or says clearly that there is none. 2 3The engine here is the fake one the runtime tests use (a script behind a manifest-declared entrypoint), so this proves 4the path the installed app takes: run config "component:strata-engine" -> `strata runtime start` -> the server resolves 5the package -> the engine runs from the component folder -> stop ends it. It also proves the absence is a notice, not a 6fetch: with an empty component folder and the no-acquire switch set, a start fails with the typed message, starts no 7engine, and the state ends up stopped.""" 8 9import hashlib 10import io 11import json 12import os 13import sys 14import tempfile 15import time 16import unittest 17from contextlib import redirect_stdout 18from pathlib import Path 19from unittest import mock 20 21from strata_cli .cli import main 22from strata_control import components ,engine_component as ec ,profiles ,runtime 23 24WINDOWS = os .name == "nt" 25FAKE_ENGINE = ( 26"import sys, os\nfrom pathlib import Path\n" 27"Path(os.environ['FAKE_ENGINE_MARK']).write_text(os.path.abspath(__file__) + '\\n' + ' '.join(sys.argv[1:]))\n" 28"print('READY 4096 stop', flush=True)\n" 29"for line in sys.stdin:\n" 30" if line.strip() == 'QUIT': break\n" 31" if line.startswith(('GEN ', 'BGEN ')):\n" 32" slot = int(line.split()[1]) if line.startswith('BGEN ') else None\n" 33" print('T 97', flush=True)\n" 34" print('DONE 1 1 1.0 1.0 length 0 0 0', flush=True)\n" 35" if slot is not None: print(f'BADM {slot} 0', flush=True)\n" ) 36 37 38def install_fake_engine (components_dir :Path )-> Path : 39folder = components_dir / "engine" / f"0.1.45- { components . host_platform () } -cuda" 40folder .mkdir (parents = True ) 41 (folder / "engine_main.py" ).write_text (FAKE_ENGINE ,encoding = "utf-8" ) 42if WINDOWS : 43entry = "engine.cmd" 44 (folder / entry ).write_bytes (f'@echo off\r\n" { sys . executable } " "%~dp0engine_main.py" %*\r\n' .encode ()) 45else : 46entry = "engine" 47 (folder / entry ).write_text (f'#!/bin/sh\nexec " { sys . executable } " "$(dirname "$0")/engine_main.py" "$@"\n' ) 48 (folder / entry ).chmod (0o755 ) 49files = [{"path" :name ,"sha256" :hashlib .sha256 ((folder / name ).read_bytes ()).hexdigest (), 50"bytes" : (folder / name ).stat ().st_size }for name in (entry ,"engine_main.py" )] 51 (folder / ec .MANIFEST ).write_text (json .dumps ({ 52"schema_version" :1 ,"id" :"strata-engine" ,"version" :"0.1.45" ,"platform" :components .host_platform (), 53"backend" :"cuda" ,"entrypoint" :entry ,"files" :files }),encoding = "utf-8" ) 54return folder 55 56 57@ unittest . skipUnless ( os . name in ( "posix" , "nt" ), "no qualified owner transport on this platform" ) 58class ComponentStart (unittest .TestCase ): 59def setUp (self ): 60self .temp = tempfile .TemporaryDirectory (prefix = "strata-component-start-" ) 61self .addCleanup (self .temp .cleanup ) 62self .root = Path (self .temp .name ) 63self .components = self .root / "components" 64self .components .mkdir () 65env = mock .patch .dict (os .environ , { 66"STRATA_PROFILE_DIR" :str (self .root / "profiles" ),"STRATA_RUNTIME_DIR" :str (self .root / "runtime" ), 67"STRATA_COMPONENTS_DIR" :str (self .components ),"STRATA_ENGINE_BACKEND" :"cuda" , 68"STRATA_NO_ACQUIRE" :"1" ,"FAKE_ENGINE_MARK" :str (self .root / "ran.txt" )}) 69env .start () 70self .addCleanup (env .stop ) 71os .environ .pop ("STRATA_API_KEY" ,None ) 72from tools .strata_tokenizer import BYTE_TO_UNICODE 73tokenizer = self .root / "tokenizer" 74tokenizer .mkdir () 75tokens = [BYTE_TO_UNICODE [i ]for i in range (256 )]+ ["ab" ,"<|im_start|>" ,"<|im_end|>" ,"<|endoftext|>" ] 76 (tokenizer / "vocab.json" ).write_text (json .dumps ({token :i for i ,token in enumerate (tokens )})) 77 (tokenizer / "merges.txt" ).write_text ("a b" ) 78 (tokenizer / "token_type.json" ).write_text (json .dumps ([0 ]* 257 + [3 ,3 ,3 ])) 79self .config = self .root / "run.json" 80self .config .write_text (json .dumps ({"exe" :"component:strata-engine" ,"backend" :"cuda" , 81"tokenizer" :str (tokenizer ),"args" : [],"cwd" :str (self .root ), 82"model_name" :"fake" ,"host" :"127.0.0.1" ,"port" :0 }),encoding = "utf-8" ) 83profiles .create ("app" ,str (self .config )) 84self .addCleanup (self ._stop ) 85 86def _stop (self ): 87try : 88if runtime ._read_state ("app" )is not None : 89runtime .stop ("app" ,timeout = 12 ) 90except (OSError ,profiles .ProfileError ): 91pass 92 93def _cli (self ,* args ): 94out = io .StringIO () 95with redirect_stdout (out ): 96code = main ([* args ,"--output" ,"json" ]) 97return code ,json .loads (out .getvalue ()) 98 99def test_start_runs_the_engine_from_the_component_folder_and_stop_ends_it (self ): 100folder = install_fake_engine (self .components ) 101code ,started = self ._cli ("runtime" ,"start" ,"--profile" ,"app" ,"--wait" ,"30" ,"--shutdown-timeout" ,"2" ) 102self .assertEqual (code ,0 ,started ) 103self .assertEqual (started ["state" ],"ready" ) 104self .assertTrue (started ["generation_ready" ]) 105ran = (self .root / "ran.txt" ).read_text ().splitlines ()[0 ] 106self .assertEqual (Path (ran ).resolve (), (folder / "engine_main.py" ).resolve ()) 107status = self ._cli ("runtime" ,"status" ,"--profile" ,"app" )[1 ] 108self .assertEqual (status ["instance_id" ],started ["instance_id" ]) 109code ,stopped = self ._cli ("runtime" ,"stop" ,"--profile" ,"app" ,"--wait" ,"20" ) 110self .assertEqual ((code ,stopped ["state" ]), (0 ,"stopped" )) 111deadline = time .monotonic ()+ 5 112while runtime ._read_state ("app" )is not None and time .monotonic ()< deadline : 113time .sleep (0.05 ) 114self .assertIsNone (runtime ._read_state ("app" )) 115 116def test_a_packaged_stub_engine_starts_and_a_changed_library_does_not (self ): 117"""The package is made by packaging/package_engine.py (schema 2: archs, min_driver, build_id), the start hashes 118every file: one flipped byte in a library the stub never loads still refuses the start, and no engine runs.""" 119sys .path .insert (0 ,str (Path (__file__ ).resolve ().parents [2 ]/ "packaging" )) 120import package_engine 121src = self .root / "stub-src" 122src .mkdir () 123 (src / "engine_main.py" ).write_text (FAKE_ENGINE ,encoding = "utf-8" ) 124if WINDOWS : 125entry = "strata.cmd" 126 (src / entry ).write_bytes (f'@echo off\r\n" { sys . executable } " "%~dp0engine_main.py" %*\r\n' .encode ()) 127library = "cudart64_13.dll" 128else : 129entry = "strata" 130 (src / entry ).write_text (f'#!/bin/sh\nexec " { sys . executable } " "$(dirname "$0")/engine_main.py" "$@"\n' ) 131library = "libcudart.so.13" 132 (src / library ).write_bytes (b"a runtime library the stub never loads " * 200 ) 133 (src / "BUILD.json" ).write_text (json .dumps ({"version" :"0.1.45" })) 134out = self .components / "engine" 135out .mkdir () 136folder = package_engine .build (src ,"cuda" ,"0.1.45" ,components .host_platform (),out ,entry = entry , 137archs = ("sm_86" ,"compute_89" ),min_driver = {"nvidia" :"580.65" }, 138build_id = "stub-1" ,variant = "cuda13" ,include = ["engine_main.py" ]) 139patches = (mock .patch .object (ec ,"cuda_archs_present" ,return_value = ["sm_86" ]), 140mock .patch .object (ec ,"nvidia_driver_version" ,return_value = "610.47" )) 141for item in patches : 142item .start () 143self .addCleanup (item .stop ) 144code ,started = self ._cli ("runtime" ,"start" ,"--profile" ,"app" ,"--wait" ,"30" ,"--shutdown-timeout" ,"2" ) 145log = self .root / "runtime" / "app.server.log" 146self .assertEqual (code ,0 , (started ,log .read_text (errors = "replace" )[- 1500 :]if log .exists ()else "no server log" )) 147self .assertEqual (started ["state" ],"ready" ) 148self .assertEqual (Path ((self .root / "ran.txt" ).read_text ().splitlines ()[0 ]).resolve (), 149 (folder / "engine_main.py" ).resolve ()) 150self .assertEqual (self ._cli ("runtime" ,"stop" ,"--profile" ,"app" ,"--wait" ,"20" )[1 ]["state" ],"stopped" ) 151deadline = time .monotonic ()+ 5 152while runtime ._read_state ("app" )is not None and time .monotonic ()< deadline : 153time .sleep (0.05 ) 154 (self .root / "ran.txt" ).unlink () 155body = bytearray ((folder / library ).read_bytes ()) 156body [100 ]^= 0xFF # same size; only the full hash sees it 157 (folder / library ).write_bytes (bytes (body )) 158code ,result = self ._cli ("runtime" ,"start" ,"--profile" ,"app" ,"--wait" ,"60" ,"--shutdown-timeout" ,"2" ) 159self .assertEqual (code ,5 ,result )# the refusal is the first thing the user sees: no host, no server 160self .assertFalse (result ["ok" ]) 161self .assertFalse ((self .root / "ran.txt" ).exists (),"a package with a changed library must not run" ) 162self .assertIn ("integrity check" ,json .dumps (result )) 163self .assertIn (library ,json .dumps (result )) 164self .assertIn ("not started" ,json .dumps (result )) 165self .assertIsNone (runtime ._read_state ("app" ),"no runtime host may exist after the refusal" ) 166 167def test_no_engine_is_a_notice_and_starts_nothing (self ): 168code ,result = self ._cli ("runtime" ,"start" ,"--profile" ,"app" ,"--wait" ,"60" ,"--shutdown-timeout" ,"2" ) 169self .assertNotEqual (code ,0 ) 170self .assertFalse (result ["ok" ]) 171self .assertFalse ((self .root / "ran.txt" ).exists (),"no engine may run" ) 172log = (self .root / "runtime" / "app.server.log" ) 173text = log .read_text (errors = "replace" )if log .exists ()else "" 174self .assertIn ("No engine for this PC" ,text + json .dumps (result )) 175self .assertIn ("never downloads" ,text + json .dumps (result )) 176self .assertIn (runtime .status ("app" )["state" ], ("stopped" ,"failed" )) 177self .assertEqual (sorted (p .name for p in self .components .iterdir ()), [], 178"looking for an engine must not create or fetch anything" ) 179 180def test_a_tampered_engine_is_not_started (self ): 181folder = install_fake_engine (self .components ) 182 (folder / "engine_main.py" ).write_text (FAKE_ENGINE + "# changed\n" ,encoding = "utf-8" ) 183code ,result = self ._cli ("runtime" ,"start" ,"--profile" ,"app" ,"--wait" ,"60" ,"--shutdown-timeout" ,"2" ) 184self .assertNotEqual (code ,0 ) 185self .assertFalse ((self .root / "ran.txt" ).exists (),"a changed package must not run" ) 186 187def test_the_package_folder_is_first_on_the_library_path (self ): 188from serve import server 189folder = install_fake_engine (self .components ) 190cfg = server .with_component_engine ({"exe" :"component:strata-engine" ,"backend" :"cuda" ,"lib_dirs" : ["/other" ]}) 191self .assertEqual (Path (cfg ["exe" ]).parent .resolve (),folder .resolve ()) 192self .assertEqual (cfg ["lib_dirs" ][0 ],str (folder / ("engine.cmd" if WINDOWS else "engine" )).rsplit (os .sep ,1 )[0 ]) 193self .assertEqual (cfg ["lib_dirs" ][1 :], ["/other" ]) 194env = server .child_env (cfg ) 195var = "PATH" if WINDOWS else "LD_LIBRARY_PATH" 196self .assertTrue (env [var ].startswith (str (folder ))) 197plain = {"exe" :"/some/where/strata" ,"args" : []} 198self .assertIs (server .with_component_engine (plain ),plain ) 199with self .assertRaises (SystemExit )as caught : 200for entry in (folder / "engine.cmd" ,folder / "engine" ): 201entry .unlink (missing_ok = True ) 202server .with_component_engine ({"exe" :"component:strata-engine" ,"backend" :"cuda" }) 203self .assertEqual (caught .exception .code ,5 ) 204 205def test_a_picture_reader_path_from_an_older_engine_folder_follows_the_installed_package (self ): 206"""After an engine update the folder name changes; the run config's absolute vision exe must not stop the server.""" 207from serve import server 208folder = install_fake_engine (self .components ) 209reader = folder / "strata-vision" 210reader .write_text ("x" ,encoding = "utf-8" ) 211gone = str (self .components / "engine" / "0.0.1-old" / "strata-vision" ) 212cfg = server .with_component_engine ({"exe" :"component:strata-engine" ,"backend" :"cuda" , 213"vision" : {"exe" :gone ,"cpu_exe" :gone ,"mmproj" :"/m.gguf" }}) 214self .assertEqual (cfg ["vision" ]["exe" ],str (reader )) 215self .assertEqual (cfg ["vision" ]["cpu_exe" ],str (reader )) 216self .assertEqual (cfg ["vision" ]["mmproj" ],"/m.gguf" ) 217ok = {"exe" :"component:strata-engine" ,"backend" :"cuda" ,"vision" : {"exe" :str (reader )}} 218self .assertEqual (server .with_component_engine (ok )["vision" ], {"exe" :str (reader )}) 219none = server .with_component_engine ({"exe" :"component:strata-engine" ,"backend" :"cuda" ,"vision" : {"exe" :gone .replace ("strata-vision" ,"other" )}}) 220self .assertTrue (none ["vision" ]["exe" ].endswith ("other" ))# no such file in the package: left as it is 221 222def test_the_build_json_lib_dirs_follow_the_package_folder (self ): 223"""The Windows HIP package keeps the ROCm DLLs in rocm/bin (BUILD.json lib_dirs): strata.exe does not load without them on PATH.""" 224from serve import server 225folder = install_fake_engine (self .components ) 226 (folder / "rocm" / "bin" ).mkdir (parents = True ) 227 (folder / "BUILD.json" ).write_text (json .dumps ({"lib_dirs" : ["rocm/bin" ,"../escape" ,"missing" ,"/abs" ]}),encoding = "utf-8" ) 228cfg = server .with_component_engine ({"exe" :"component:strata-engine" ,"backend" :"cuda" ,"lib_dirs" : ["/other" ]}) 229self .assertEqual (cfg ["lib_dirs" ], [str (folder ),str (folder / "rocm" / "bin" ),"/other" ]) 230env = server .child_env (cfg ) 231var = "PATH" if WINDOWS else "LD_LIBRARY_PATH" 232self .assertTrue (env [var ].startswith (str (folder )+ os .pathsep + str (folder / "rocm" / "bin" ))) 233 234def test_doctor_names_the_missing_engine (self ): 235from strata_control .doctor import inspect 236report = inspect (self .config ) 237engine = next (row for row in report ["components" ]if row ["name" ]== "engine" ) 238self .assertEqual (engine ["status" ],"missing" ) 239install_fake_engine (self .components ) 240report = inspect (self .config ) 241engine = next (row for row in report ["components" ]if row ["name" ]== "engine" ) 242self .assertEqual (engine ["status" ],"ok" ) 243 244 245if __name__ == "__main__" : 246unittest .main ()