okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-ds-out ac306afb2 into f-own-intaff3a132f

main
11.6 KiB220 linesraw
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
7    python -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):
24    def test_sets_the_variable(self):
25        with mock.patch.dict(os.environ, {}, clear=True):
26            self.assertEqual(quiet_crash_env({})[NO_BACKTRACE], "1")
27
28    def test_without_an_argument_it_changes_this_process(self):
29        with mock.patch.dict(os.environ, {}, clear=True):
30            quiet_crash_env()
31            self.assertEqual(os.environ[NO_BACKTRACE], "1")
32
33    def test_a_value_that_is_already_there_is_kept(self):
34        with mock.patch.dict(os.environ, {}, clear=True):
35            self.assertEqual(quiet_crash_env({NO_BACKTRACE: "0"})[NO_BACKTRACE], "0")      # ggml reads any value as "skip"
36
37    def test_the_developer_switch_leaves_the_backtrace_on(self):
38        for how in ("1", "yes", "true", "anything"):
39            with self.subTest(how=how), mock.patch.dict(os.environ, {DEVELOPER_SWITCH: how}, clear=True):
40                self.assertNotIn(NO_BACKTRACE, quiet_crash_env(dict(os.environ)))
41        with mock.patch.dict(os.environ, {}, clear=True):
42            self.assertNotIn(NO_BACKTRACE, quiet_crash_env({DEVELOPER_SWITCH: "1"}))       # named in the dict being built, not in this process
43
44    def test_the_switch_set_to_nothing_or_zero_is_not_a_request(self):
45        for how in ("", "0", "no", "off", "False"):
46            with self.subTest(how=how), mock.patch.dict(os.environ, {DEVELOPER_SWITCH: how}, clear=True):
47                self.assertEqual(quiet_crash_env(dict(os.environ))[NO_BACKTRACE], "1")
48
49    def test_it_returns_the_dict_it_was_given(self):
50        env = {"A": "1"}
51        self.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
57    def setUp(self):
58        patcher = mock.patch.dict(os.environ, {k: v for k, v in os.environ.items() if k not in (NO_BACKTRACE, DEVELOPER_SWITCH)}, clear=True)
59        patcher.start()
60        self.addCleanup(patcher.stop)
61
62    def test_the_engine_and_the_picture_reader(self):
63        import serve.server as server
64        env = server.child_env({})
65        self.assertEqual(env[NO_BACKTRACE], "1")
66        self.assertEqual(server.vision_env({}, env)[NO_BACKTRACE], "1")
67        self.assertEqual(server.vision_env({"vision": {"cuda_device": 1}}, env)[NO_BACKTRACE], "1")     # the copy for a reader on its own card
68        self.assertEqual(server.child_env({}, offline=True)[NO_BACKTRACE], "1")
69
70    def test_the_developer_switch_reaches_the_engine_environment(self):
71        import serve.server as server
72        with mock.patch.dict(os.environ, {DEVELOPER_SWITCH: "1"}):
73            env = server.child_env({})
74        self.assertNotIn(NO_BACKTRACE, env)
75
76    def test_the_config_may_name_it_itself(self):
77        import serve.server as server
78        self.assertEqual(server.child_env({"env": {NO_BACKTRACE: "0"}})[NO_BACKTRACE], "0")
79
80    def test_sd_cli(self):
81        from serve import images
82        self.assertEqual(images.image_env({})[NO_BACKTRACE], "1")
83        self.assertEqual(images.image_env({}, base={"PATH": "x"})[NO_BACKTRACE], "1")
84
85    def test_the_launcher_children(self):
86        from strata_cli.launch import runner as R
87        r = R.Runner.__new__(R.Runner)               # _env() reads only components_dir
88        r.components_dir = None
89        self.assertEqual(r._env()[NO_BACKTRACE], "1")
90        r.components_dir = "/components"
91        self.assertEqual(r._env()[NO_BACKTRACE], "1")
92
93    def test_the_tuning_engine_environment(self):
94        from strata_control import engine_component, tuning
95        with tempfile.TemporaryDirectory() as d:
96            (Path(d) / "engine-component.json").write_text("{}", encoding="utf-8")
97            with mock.patch.object(engine_component, "package_lib_dirs", return_value=[]):
98                self.assertEqual(tuning.engine_env(Path(d) / "strata")[NO_BACKTRACE], "1")
99
100    def test_the_tuning_workers(self):
101        from serve import lifeline
102        from strata_control import tune_api, tune_engine
103        seen = []
104
105        def fake_popen(*args, **kw):
106            seen.append(kw.get("env"))
107            raise OSError("not started in this test")
108
109        with tempfile.TemporaryDirectory() as d, mock.patch.object(lifeline, "popen", fake_popen):
110            exe = Path(d) / "strata"
111            exe.write_text("", encoding="utf-8")
112            for env in ({"PATH": "x"}, None):
113                seen.clear()
114                with self.assertRaises(tune_engine.MeasurementError):
115                    tune_engine.EngineHarness(exe, {}, cwd=Path(d), env=env).start()
116                with self.assertRaises(tune_engine.MeasurementError):
117                    tune_api.ApiHarness(python=sys.executable, serve_dir=Path(d), config_path=Path(d) / "c.json", env=env).start()
118                if env is None:
119                    self.assertEqual(seen, [None, None], "no environment given: the child inherits this process's, set at the entry point")
120                else:
121                    self.assertEqual([e[NO_BACKTRACE] for e in seen], ["1", "1"])
122                    self.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
128    def test_each_entry_point_calls_the_helper(self):
129        for 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(")):
131            text = (ROOT / rel).read_text(encoding="utf-8")
132            body = text[text.index("\n" + anchor):]
133            self.assertIn("quiet_crash_env()", body[:6000], rel)
134
135    def test_the_server_and_the_tuning_session_environments_use_it(self):
136        for 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))")):
138            self.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:
183    f = node.func
184    if isinstance(f, ast.Attribute):
185        name = f.value.id if isinstance(f.value, ast.Name) else ""
186        return (name == "subprocess" and f.attr in _SUBPROCESS) or (name == "os" and f.attr in _OS) or (f.attr == "popen" and name in ("lifeline", "_lifeline"))
187    return isinstance(f, ast.Name) and f.id in ("popen", "Popen", "_popen", "execv", "execve")
188
189
190def spawn_sites() -> dict:
191    files = []
192    for d in ("serve", "strata_control", "strata_cli"):
193        files += sorted((ROOT / d).rglob("*.py"))
194    files += [ROOT / "strata.py", ROOT / "setup.py"]
195    out = {}
196    for p in files:
197        rel = p.relative_to(ROOT).as_posix()
198        if p.name.startswith("test_") or "/tests/" in rel or not p.is_file():
199            continue
200        tree = ast.parse(p.read_text(encoding="utf-8"))
201        n = sum(1 for node in ast.walk(tree) if isinstance(node, ast.Call) and _is_spawn(node))
202        if n:
203            out[rel] = n
204    return out
205
206
207class EverySpawnSiteIsListed(unittest.TestCase):
208    def test_no_process_is_started_that_nobody_has_looked_at(self):
209        known = {**STRATA_PROGRAMS, **OTHER_PROGRAMS}
210        new = {rel: n for rel, n in spawn_sites().items() if n > known.get(rel, 0)}
211        self.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
215    def test_the_two_lists_do_not_overlap(self):
216        self.assertEqual(set(STRATA_PROGRAMS) & set(OTHER_PROGRAMS), set())
217
218
219if __name__ == "__main__":
220    unittest.main()