okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
aff3a132f
main
1"""The product never starts a debugger on a user's machine (strata_control/childenv.py). 2 3ggml's abort path forks `gdb --batch -ex attach <pid>` (Linux; lldb and backtrace_symbols after it). Every child Strata starts therefore gets 4GGML_NO_BACKTRACE=1, unless a developer sets STRATA_BACKTRACE=1. These tests check the helper, the environment of every spawn site that builds one, and 5list every place product code starts a process, so a new one has to be looked at (does it start a Strata program? then it needs the variable). 6 7python -m pytest tests/terminal/test_no_debugger_children.py 8""" 9import ast 10import os 11import sys 12import tempfile 13import unittest 14from pathlib import Path 15from unittest import mock 16 17from strata_control import childenv 18from strata_control .childenv import DEVELOPER_SWITCH ,NO_BACKTRACE ,quiet_crash_env 19 20ROOT = Path (__file__ ).resolve ().parents [2 ] 21 22 23class Helper (unittest .TestCase ): 24def test_sets_the_variable (self ): 25with mock .patch .dict (os .environ , {},clear = True ): 26self .assertEqual (quiet_crash_env ({})[NO_BACKTRACE ],"1" ) 27 28def test_without_an_argument_it_changes_this_process (self ): 29with mock .patch .dict (os .environ , {},clear = True ): 30quiet_crash_env () 31self .assertEqual (os .environ [NO_BACKTRACE ],"1" ) 32 33def test_a_value_that_is_already_there_is_kept (self ): 34with mock .patch .dict (os .environ , {},clear = True ): 35self .assertEqual (quiet_crash_env ({NO_BACKTRACE :"0" })[NO_BACKTRACE ],"0" )# ggml reads any value as "skip" 36 37def test_the_developer_switch_leaves_the_backtrace_on (self ): 38for how in ("1" ,"yes" ,"true" ,"anything" ): 39with self .subTest (how = how ),mock .patch .dict (os .environ , {DEVELOPER_SWITCH :how },clear = True ): 40self .assertNotIn (NO_BACKTRACE ,quiet_crash_env (dict (os .environ ))) 41with mock .patch .dict (os .environ , {},clear = True ): 42self .assertNotIn (NO_BACKTRACE ,quiet_crash_env ({DEVELOPER_SWITCH :"1" }))# named in the dict being built, not in this process 43 44def test_the_switch_set_to_nothing_or_zero_is_not_a_request (self ): 45for how in ("" ,"0" ,"no" ,"off" ,"False" ): 46with self .subTest (how = how ),mock .patch .dict (os .environ , {DEVELOPER_SWITCH :how },clear = True ): 47self .assertEqual (quiet_crash_env (dict (os .environ ))[NO_BACKTRACE ],"1" ) 48 49def test_it_returns_the_dict_it_was_given (self ): 50env = {"A" :"1" } 51self .assertIs (quiet_crash_env (env ),env ) 52 53 54class SpawnEnvironments (unittest .TestCase ): 55"""The environment each site that builds one hands to its child.""" 56 57def setUp (self ): 58patcher = mock .patch .dict (os .environ , {k :v for k ,v in os .environ .items ()if k not in (NO_BACKTRACE ,DEVELOPER_SWITCH )},clear = True ) 59patcher .start () 60self .addCleanup (patcher .stop ) 61 62def test_the_engine_and_the_picture_reader (self ): 63import serve .server as server 64env = server .child_env ({}) 65self .assertEqual (env [NO_BACKTRACE ],"1" ) 66self .assertEqual (server .vision_env ({},env )[NO_BACKTRACE ],"1" ) 67self .assertEqual (server .vision_env ({"vision" : {"cuda_device" :1 }},env )[NO_BACKTRACE ],"1" )# the copy for a reader on its own card 68self .assertEqual (server .child_env ({},offline = True )[NO_BACKTRACE ],"1" ) 69 70def test_the_developer_switch_reaches_the_engine_environment (self ): 71import serve .server as server 72with mock .patch .dict (os .environ , {DEVELOPER_SWITCH :"1" }): 73env = server .child_env ({}) 74self .assertNotIn (NO_BACKTRACE ,env ) 75 76def test_the_config_may_name_it_itself (self ): 77import serve .server as server 78self .assertEqual (server .child_env ({"env" : {NO_BACKTRACE :"0" }})[NO_BACKTRACE ],"0" ) 79 80def test_sd_cli (self ): 81from serve import images 82self .assertEqual (images .image_env ({})[NO_BACKTRACE ],"1" ) 83self .assertEqual (images .image_env ({},base = {"PATH" :"x" })[NO_BACKTRACE ],"1" ) 84 85def test_the_launcher_children (self ): 86from strata_cli .launch import runner as R 87r = R .Runner .__new__ (R .Runner )# _env() reads only components_dir 88r .components_dir = None 89self .assertEqual (r ._env ()[NO_BACKTRACE ],"1" ) 90r .components_dir = "/components" 91self .assertEqual (r ._env ()[NO_BACKTRACE ],"1" ) 92 93def test_the_tuning_engine_environment (self ): 94from strata_control import engine_component ,tuning 95with tempfile .TemporaryDirectory ()as d : 96 (Path (d )/ "engine-component.json" ).write_text ("{}" ,encoding = "utf-8" ) 97with mock .patch .object (engine_component ,"package_lib_dirs" ,return_value = []): 98self .assertEqual (tuning .engine_env (Path (d )/ "strata" )[NO_BACKTRACE ],"1" ) 99 100def test_the_tuning_workers (self ): 101from serve import lifeline 102from strata_control import tune_api ,tune_engine 103seen = [] 104 105def fake_popen (* args ,** kw ): 106seen .append (kw .get ("env" )) 107raise OSError ("not started in this test" ) 108 109with tempfile .TemporaryDirectory ()as d ,mock .patch .object (lifeline ,"popen" ,fake_popen ): 110exe = Path (d )/ "strata" 111exe .write_text ("" ,encoding = "utf-8" ) 112for env in ({"PATH" :"x" },None ): 113seen .clear () 114with self .assertRaises (tune_engine .MeasurementError ): 115tune_engine .EngineHarness (exe , {},cwd = Path (d ),env = env ).start () 116with self .assertRaises (tune_engine .MeasurementError ): 117tune_api .ApiHarness (python = sys .executable ,serve_dir = Path (d ),config_path = Path (d )/ "c.json" ,env = env ).start () 118if env is None : 119self .assertEqual (seen , [None ,None ],"no environment given: the child inherits this process's, set at the entry point" ) 120else : 121self .assertEqual ([e [NO_BACKTRACE ]for e in seen ], ["1" ,"1" ]) 122self .assertEqual ([e ["PATH" ]for e in seen ], ["x" ,"x" ]) 123 124 125class EntryPointsSetItForEveryChild (unittest .TestCase ): 126"""Programs started without an environment of their own inherit this process's: the entry points set it there.""" 127 128def test_each_entry_point_calls_the_helper (self ): 129for rel ,anchor in (("strata_cli/cli.py" ,"def main(" ), ("serve/server.py" ,"def main(" ), ("strata_control/runtime.py" ,"def main(" ), 130 ("setup.py" ,"def main(" )): 131text = (ROOT / rel ).read_text (encoding = "utf-8" ) 132body = text [text .index ("\n" + anchor ):] 133self .assertIn ("quiet_crash_env()" ,body [:6000 ],rel ) 134 135def test_the_server_and_the_tuning_session_environments_use_it (self ): 136for rel ,needle in (("strata_control/runtime.py" ,"quiet_crash_env(os.environ.copy())" ), 137 ("strata_control/tune_session.py" ,"quiet_crash_env(dict(os.environ))" )): 138self .assertIn (needle , (ROOT / rel ).read_text (encoding = "utf-8" ),rel ) 139 140 141# Every place product code starts a process, with what it starts. A file may hold at most this many; a new site fails the test until it is 142# listed here (and, when it starts a Strata program - the engine, the picture reader, sd-cli, setup, a worker - it builds its environment with 143# quiet_crash_env or inherits the one an entry point set). 144STRATA_PROGRAMS = { 145"serve/server.py" :7 ,# the engine, the picture reader (env from child_env / vision_env), the strata-device probe, before_load commands 146"serve/images.py" :1 ,# sd-cli (image_env) 147"serve/lifeline.py" :4 ,# the wrapper every child goes through (ps, a watcher); no program of ours of its own 148"serve/winjob.py" :2 ,# lifeline.popen's Windows start inside the job (suspended, then resumed) + the plain Popen off Windows: the caller's env as given 149"strata_control/runtime.py" :4 ,# the runtime host (inherits) and the server (quiet_crash_env on its environment); taskkill 150"strata_control/tune_api.py" :1 ,# tuning worker (wrapped) 151"strata_control/tune_engine.py" :2 ,# tuning engine (wrapped) + ps 152"strata_control/tune_session.py" :1 ,# tuning worker (quiet_crash_env) 153"strata_control/tuning.py" :1 ,# engine --help (engine_env) 154"strata_control/shape_engine.py" :2 ,# engine --version / --geometry (inherit) 155"strata_control/updater.py" :3 ,# --version probes (inherit) 156"strata_cli/bench_standard.py" :2 ,# `strata.py serve` (inherits: cli.main sets it) + taskkill 157"strata_cli/launch/runner.py" :2 ,# setup.py and the other children (_env) 158"strata_cli/launch/params.py" :2 ,# engine --help (inherits) 159"strata_cli/cli.py" :2 ,# setup.py, the revise command 160"setup.py" :17 ,# builds, engine probes, the helpers it runs (main sets it) 161} 162OTHER_PROGRAMS = { 163"serve/mcp.py" :2 ,# the person's MCP servers and taskkill 164"serve/telemetry.py" :2 ,# sysctl, a Metal tool 165"strata_control/doctor.py" :1 , 166"strata_control/engine_component.py" :4 ,# nvidia-smi, powershell, lspci-style probes 167"strata_control/gpu_roles.py" :1 ,# python -c 168"strata_control/procs.py" :3 ,# ps, taskkill 169"strata_control/profiles.py" :1 ,# the person's editor 170"strata_control/recipes.py" :1 ,# the person's editor 171"strata_control/split_engine.py" :1 ,# nvidia-smi 172"strata_control/time_skip.py" :3 ,# the person's check commands 173"strata_control/tune_machine.py" :3 ,# sysctl, vm_stat, a probe 174"strata_cli/bench_facts.py" :1 ,# a tool for the facts 175"strata_cli/launch/access.py" :5 ,# tunnel programs, powershell, ps 176} 177 178_SUBPROCESS = {"Popen" ,"run" ,"call" ,"check_output" ,"check_call" } 179_OS = {"execv" ,"execve" ,"execvp" ,"execvpe" ,"execl" ,"execle" ,"execlp" ,"execlpe" ,"spawnv" ,"spawnve" ,"spawnvp" ,"spawnl" ,"spawnle" ,"system" ,"startfile" } 180 181 182def _is_spawn (node )-> bool : 183f = node .func 184if isinstance (f ,ast .Attribute ): 185name = f .value .id if isinstance (f .value ,ast .Name )else "" 186return (name == "subprocess" and f .attr in _SUBPROCESS )or (name == "os" and f .attr in _OS )or (f .attr == "popen" and name in ("lifeline" ,"_lifeline" )) 187return isinstance (f ,ast .Name )and f .id in ("popen" ,"Popen" ,"_popen" ,"execv" ,"execve" ) 188 189 190def spawn_sites ()-> dict : 191files = [] 192for d in ("serve" ,"strata_control" ,"strata_cli" ): 193files += sorted ((ROOT / d ).rglob ("*.py" )) 194files += [ROOT / "strata.py" ,ROOT / "setup.py" ] 195out = {} 196for p in files : 197rel = p .relative_to (ROOT ).as_posix () 198if p .name .startswith ("test_" )or "/tests/" in rel or not p .is_file (): 199continue 200tree = ast .parse (p .read_text (encoding = "utf-8" )) 201n = sum (1 for node in ast .walk (tree )if isinstance (node ,ast .Call )and _is_spawn (node )) 202if n : 203out [rel ]= n 204return out 205 206 207class EverySpawnSiteIsListed (unittest .TestCase ): 208def test_no_process_is_started_that_nobody_has_looked_at (self ): 209known = {** STRATA_PROGRAMS ,** OTHER_PROGRAMS } 210new = {rel :n for rel ,n in spawn_sites ().items ()if n > known .get (rel ,0 )} 211self .assertEqual (new , {},"a new place that starts a process: if it starts a Strata program (engine, picture reader, sd-cli, setup, a worker) " 212"its environment must carry GGML_NO_BACKTRACE (strata_control.childenv.quiet_crash_env); then list it in " 213"STRATA_PROGRAMS (or OTHER_PROGRAMS when it starts nothing of ours) in tests/terminal/test_no_debugger_children.py" ) 214 215def test_the_two_lists_do_not_overlap (self ): 216self .assertEqual (set (STRATA_PROGRAMS )& set (OTHER_PROGRAMS ),set ()) 217 218 219if __name__ == "__main__" : 220unittest .main ()