okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
466626cbb
main
1"""The Terminal / Control bundle holds every tools/ module that setup.py can import (#3613, #3467). 2 30.1.47 shipped without tools/calibrate.py: setup.py imports it after a tune, so every launch after a tune ended in 4ModuleNotFoundError. The bundle is staged here the way packaging/package_terminal.py stages it (the payload, the read-only tools, 5then add_installer), and setup.py's tool imports are resolved against tools/ as the bundle has it, not against the source tree. 6""" 7 8import ast 9import os 10import shutil 11import subprocess 12import sys 13import tempfile 14import unittest 15from pathlib import Path 16 17ROOT = Path (__file__ ).resolve ().parents [2 ] 18sys .path .insert (0 ,str (ROOT / "packaging" )) 19import package_terminal as pt # noqa: E402 20 21 22def imports_of (path :Path )-> set [str ]: 23found :set [str ]= set () 24for node in ast .walk (ast .parse (path .read_text (encoding = "utf-8-sig" ))): 25if isinstance (node ,ast .Import ): 26found .update (a .name .split ("." )[0 ]for a in node .names ) 27elif isinstance (node ,ast .ImportFrom )and node .module and node .level == 0 : 28found .add (node .module .split ("." )[0 ]) 29return found 30 31 32class BundleImports (unittest .TestCase ): 33@classmethod 34def setUpClass (cls ): 35cls .temp = tempfile .TemporaryDirectory (prefix = "strata-bundle-" ) 36cls .root = Path (cls .temp .name )/ "strata-terminal" 37cls .root .mkdir () 38ignore = shutil .ignore_patterns ("__pycache__" ,"*.pyc" ) 39for item in pt .PAYLOAD : 40src ,dst = ROOT / item ,cls .root / item 41dst .parent .mkdir (parents = True ,exist_ok = True ) 42if src .is_dir (): 43shutil .copytree (src ,dst ,ignore = ignore ) 44else : 45shutil .copy2 (src ,dst ) 46 (cls .root / "tools" ).mkdir (exist_ok = True ) 47for item in pt .TOOLS_SUBSET : 48shutil .copy2 (ROOT / "tools" / item ,cls .root / "tools" / item ) 49cls .installer = pt .add_installer (cls .root ,ROOT ) 50 51@classmethod 52def tearDownClass (cls ): 53cls .temp .cleanup () 54 55def test_gguf_py_and_the_converter_are_in_the_bundle (self ): 56"""OWN-1B: the Terminal and Control packages carry third_party/strata-gguf-py (the preparation tools' gguf-py and llama.cpp's converter), so 57preparing a model downloads no llama.cpp; the bundled copy is byte-identical to the source tree's.""" 58here = self .root / "third_party" / "strata-gguf-py" 59for rel in ("gguf/__init__.py" ,"gguf/quants.py" ,"converter/convert_hf_to_gguf.py" ,"converter/conversion/qwen4exp.py" ,"LICENSE" ,"UPSTREAM.md" ): 60self .assertTrue ((here / rel ).is_file (),rel ) 61self .assertEqual ((here / rel ).read_bytes (), (ROOT / "third_party" / "strata-gguf-py" / rel ).read_bytes (),rel ) 62self .assertIn ("third_party/strata-gguf-py/" ,self .installer ["files" ]) 63probe = subprocess .run ([sys .executable ,"-I" ,"-c" ,f"import sys; sys.path.insert(0, { str ( self . root / 'tools' )!r } ); import _paths; print(_paths.gguf_py())" ], 64capture_output = True ,text = True ,timeout = 60 ,env = {k :v for k ,v in os .environ .items ()if k != "STRATA_GGUF_PY" }) 65self .assertEqual (probe .returncode ,0 ,probe .stderr [- 500 :]) 66self .assertEqual (Path (probe .stdout .strip ()).resolve (),here .resolve (),"a bundled tool finds the bundled copy" ) 67 68def test_calibrate_is_in_the_bundle (self ): 69# the exact file #3613 and #3467 lacked 70self .assertTrue ((self .root / "tools" / "calibrate.py" ).is_file ()) 71self .assertIn ("calibrate" ,pt .INSTALLER_TOOLS ) 72 73def test_every_tools_module_setup_py_imports_is_in_the_bundle (self ): 74in_bundle = {p .stem for p in (self .root / "tools" ).glob ("*.py" )} 75in_source = {p .stem for p in (ROOT / "tools" ).glob ("*.py" )} 76wanted = imports_of (self .root / "setup.py" )& in_source 77self .assertIn ("calibrate" ,wanted ,"setup.py no longer imports calibrate: update this test" ) 78self .assertEqual (sorted (wanted - in_bundle ), [],"setup.py imports tools/ modules that the bundle does not carry" ) 79 80def test_the_bundled_tools_import_nothing_the_bundle_lacks (self ): 81in_bundle = {p .stem for p in (self .root / "tools" ).glob ("*.py" )} 82in_source = {p .stem for p in (ROOT / "tools" ).glob ("*.py" )} 83for module in sorted (in_bundle ): 84missing = sorted ((imports_of (self .root / "tools" / f" { module } .py" )& in_source )- in_bundle ) 85self .assertEqual (missing , [],f"tools/ { module } .py imports tools/ modules the bundle does not carry" ) 86 87def test_setup_py_and_each_of_its_tools_import_with_tools_limited_to_the_bundle (self ): 88modules = sorted (set (pt .setup_tool_imports (self .root ))| set (pt .INSTALLER_TOOLS )) 89probe = subprocess .run ([sys .executable ,"-I" ,"-c" ,f"import sys; sys.path.insert(0, { str ( self . root / 'tools' )!r } ); import _paths; _paths.gguf_py()" ], 90capture_output = True ,text = True ,timeout = 60 ,env = {** os .environ ,"STRATA_CONTROL_INSTALL" :"1" }) 91if probe .returncode != 0 :# a tool reads llama.cpp's gguf-py when it is imported: a test box without any llama.cpp checkout cannot import it 92self .skipTest ("no llama.cpp gguf-py on this box (set STRATA_GGUF_PY to run this check)" ) 93code = ("import sys, os, importlib\n" 94f"sys.path[:0] = [ { str ( self . root )!r } , { str ( self . root / 'tools' )!r } ]\n" 95"import setup\n" 96f"for name in { modules !r } :\n" 97" module = importlib.import_module(name)\n" 98f" assert os.path.samefile(os.path.dirname(module.__file__), { str ( self . root / 'tools' )!r } ), (name, module.__file__)\n" 99"print('imports ok')\n" ) 100env = {** os .environ ,"STRATA_CONTROL_INSTALL" :"1" ,"PYTHONNOUSERSITE" :"1" } 101for key in ("PYTHONPATH" ,"PYTHONHOME" ): 102env .pop (key ,None ) 103done = subprocess .run ([sys .executable ,"-I" ,"-c" ,code ],cwd = str (self .root .parent ),env = env , 104capture_output = True ,text = True ,timeout = 120 ) 105self .assertEqual (done .returncode ,0 , (done .stdout or "" )+ (done .stderr or "" )[- 1500 :]) 106self .assertIn ("imports ok" ,done .stdout ) 107 108def test_a_tool_setup_starts_to_import_is_added_without_editing_the_list (self ): 109# setup_tool_imports reads setup.py, so INSTALLER_TOOLS cannot go stale the way it did for calibrate 110self .assertTrue (set (pt .setup_tool_imports (ROOT ))<= set (pt .local_imports (ROOT ,tuple (sorted ( 111set (pt .INSTALLER_TOOLS )| set (pt .setup_tool_imports (ROOT ))))))) 112without = tuple (x for x in pt .INSTALLER_TOOLS if x != "calibrate" ) 113self .assertNotIn ("calibrate" ,pt .local_imports (ROOT ,without ))# the old list really lacked it 114self .assertIn ("calibrate" ,pt .setup_tool_imports (ROOT ))# and the scan finds it anyway 115 116 117class ProbeLeavesNoBytecode (unittest .TestCase ): 118"""The import probe of package_terminal.py must not write compiled files into the bundle, whoever runs the build.""" 119 120def setUp (self ): 121self .temp = tempfile .TemporaryDirectory (prefix = "strata-probe-" ) 122self .addCleanup (self .temp .cleanup ) 123self .root = Path (self .temp .name )/ "bundle" 124self .root .mkdir () 125 (self .root / "probe_mod.py" ).write_text ("VALUE = 7\n" ,encoding = "utf-8" ) 126self .code = "import probe_mod; print('probe ok', probe_mod.VALUE)" 127self .saved = {k :os .environ .pop (k ,None )for k in ("PYTHONDONTWRITEBYTECODE" ,"PYTHONPYCACHEPREFIX" )} 128self .addCleanup (self .restore ) 129 130def restore (self ): 131for key ,value in self .saved .items (): 132if value is None : 133os .environ .pop (key ,None ) 134else : 135os .environ [key ]= value 136 137def leftovers (self ,folder :Path ): 138return sorted (str (p .relative_to (folder ))for p in list (folder .rglob ("__pycache__" ))+ list (folder .rglob ("*.pyc" ))) 139 140def test_the_check_itself_can_see_bytecode (self ): 141# without the protection the same import does leave a compiled file, so the test below proves something 142plain = Path (self .temp .name )/ "plain" 143plain .mkdir () 144 (plain / "probe_mod.py" ).write_text ("VALUE = 7\n" ,encoding = "utf-8" ) 145done = subprocess .run ([sys .executable ,"-c" ,self .code ],cwd = str (plain ),capture_output = True ,text = True ,timeout = 60 ) 146self .assertEqual (done .returncode ,0 ,done .stderr ) 147self .assertTrue (self .leftovers (plain )) 148 149def test_the_probe_writes_no_bytecode_when_the_caller_did_not_ask_for_that (self ): 150done = pt .run_probe (Path (sys .executable ),self .root ,code = self .code ) 151self .assertEqual (done .returncode ,0 ,done .stderr ) 152self .assertIn ("probe ok 7" ,done .stdout ) 153self .assertEqual (self .leftovers (self .root ), []) 154 155def test_the_probe_writes_no_bytecode_when_the_caller_asked_for_it (self ): 156os .environ ["PYTHONDONTWRITEBYTECODE" ]= "" # an empty value means "write" 157done = pt .run_probe (Path (sys .executable ),self .root ,code = self .code ) 158self .assertEqual (done .returncode ,0 ,done .stderr ) 159self .assertEqual (self .leftovers (self .root ), []) 160 161 162if __name__ == "__main__" : 163unittest .main ()