okami.mom/strata

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

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

main
18.0 KiB339 linesraw
1"""Starting and serving never acquire anything.
2
3The owner's rule: a user must never download random packages from the internet while starting or serving. Everything
4that installs, downloads or compiles lives behind an explicit command (SETUP, UPDATE, `strata install`). Three layers
5are checked here:
6
7* the import graph of the start/serve entry points does not reach installer code;
8* no module on the start/serve side runs pip, git, cmake, npm or a package manager, or opens a URL, outside a short
9  list of request-time and loopback uses, each with its reason;
10* a real start (setup.main with an installed model) with the network and every subprocess mocked makes no request and
11  runs no installer, and a start that WOULD need one stops with a typed error that names the explicit command.
12"""
13
14import ast
15import contextlib
16import io
17import json
18import os
19import subprocess
20import sys
21import tempfile
22import unittest
23import urllib.request
24from pathlib import Path
25from unittest import mock
26
27import setup
28from strata_cli import cli
29from strata_control import acquisition
30
31ROOT = Path(__file__).resolve().parents[2]
32
33#: Modules the start/serve entry points must never load.
34INSTALLER_MODULES = {"setup", "pip", "ensurepip", "venv", "huggingface_hub", "modelscope", "metal.setup_mac",
35                     "sycl.setup_intel"}
36#: Files that may be loaded on the start/serve side besides the control, cli and serve packages.
37ALLOWED_TOOLS = {"tools.strata_tokenizer", "tools.gguf_reader"}   # read-only: a tokenizer and a GGUF header reader
38
39#: argv words that mean "acquire": a subprocess whose literal argv contains one of these is an installer.
40INSTALL_WORDS = {"pip", "pip3", "git", "cmake", "ninja", "npm", "npx", "pnpm", "yarn", "winget", "apt-get", "apt",
41                 "dnf", "pacman", "brew", "curl", "wget", "choco"}
42
43#: (file, call) -> why a network call there is not an acquisition. Request-time and loopback only.
44NETWORK_ALLOWED = {
45    ("serve/server.py", "urlopen"): "an image_url a client sends in a chat request is fetched at request time",
46    ("serve/mcp.py", "urlopen"): "the MCP servers the user configured, at request time",
47    ("strata_control/tune_api.py", "urlopen"): "the loopback engine/server of a tuning job the user started",
48    ("strata_control/tune_session.py", "urlopen"): "the loopback engine (127.0.0.1) the auto-tuner a user started measures",
49    ("strata_control/loopback.py", "urlopen"): "the one opener for this computer's own servers (no proxy); any other address is passed on unchanged",
50    ("strata_control/components.py", "urlopen"): "the component fetcher: only `strata install`/UPDATE call it",
51}
52#: Modules that import the installer on purpose, with the explicit command that reaches them.
53INSTALLER_IMPORT_ALLOWED = {
54    "strata_control/calibration.py": "`strata engine calibrate`: an explicit tuning command, imports setup lazily",
55}
56
57SERVING_DIRS = ("serve", "strata_cli", "strata_control")
58
59
60def _sources():
61    for d in SERVING_DIRS:
62        for p in sorted((ROOT / d).glob("*.py")):
63            if p.name.startswith("test_") or p.name == "__init__.py":
64                continue
65            yield p
66    yield ROOT / "strata.py"
67
68
69class ImportGraphTests(unittest.TestCase):
70    def test_start_and_serve_modules_do_not_load_installer_code(self):
71        script = (
72            "import sys, os, json\n"
73            "sys.path.insert(0, os.getcwd())\n"
74            "import strata_cli.cli as c\n"
75            "import serve.server\n"
76            "from strata_control import runtime\n"
77            "c.parser()\n"
78            "root = os.getcwd()\n"
79            "mods = {n: os.path.relpath(m.__file__, root).replace(os.sep, '/') for n, m in list(sys.modules.items())\n"
80            "        if getattr(m, '__file__', None) and os.path.abspath(m.__file__).startswith(root)}\n"
81            "print(json.dumps({'mods': mods, 'names': sorted(sys.modules)}))\n")
82        r = subprocess.run([sys.executable, "-c", script], cwd=ROOT, capture_output=True, text=True, timeout=120)
83        self.assertEqual(r.returncode, 0, r.stderr[-1000:])
84        got = json.loads(r.stdout.strip().splitlines()[-1])
85        loaded = set(got["names"])
86        self.assertEqual(sorted(loaded & INSTALLER_MODULES), [])
87        for name, rel in got["mods"].items():
88            top = rel.split("/")[0]
89            self.assertIn(top, ("serve", "strata_cli", "strata_control"),
90                          f"{name} ({rel}) is loaded by starting/serving but is not part of it")
91        self.assertNotIn("strata_control.calibration", got["mods"])
92        self.assertNotIn("strata_control.components", got["mods"])
93
94    def test_static_imports_of_the_installer_are_explicit_commands_only(self):
95        found = {}
96        for p in _sources():
97            rel = p.relative_to(ROOT).as_posix()
98            tree = ast.parse(p.read_text(encoding="utf-8"))
99            for node in ast.walk(tree):
100                names = []
101                if isinstance(node, ast.Import):
102                    names = [a.name for a in node.names]
103                elif isinstance(node, ast.ImportFrom) and node.module:
104                    names = [node.module]
105                for n in names:
106                    top = n.split(".")[0]
107                    if top == "setup" or n.startswith(("tools.", "metal.", "sycl.")) and n not in ALLOWED_TOOLS:
108                        found.setdefault(rel, []).append(n)
109        for rel in found:
110            self.assertIn(rel, INSTALLER_IMPORT_ALLOWED, f"{rel} imports installer code: {found[rel]}")
111
112    def test_no_installer_subprocess_or_network_call_on_the_serving_side(self):
113        bad = []
114        for p in _sources():
115            rel = p.relative_to(ROOT).as_posix()
116            tree = ast.parse(p.read_text(encoding="utf-8"))
117            for node in ast.walk(tree):
118                if not isinstance(node, ast.Call):
119                    continue
120                fn = node.func
121                name = fn.attr if isinstance(fn, ast.Attribute) else fn.id if isinstance(fn, ast.Name) else ""
122                if name in ("urlopen", "urlretrieve") and (rel, name) not in NETWORK_ALLOWED \
123                        and (rel, "urlopen") not in NETWORK_ALLOWED:
124                    bad.append(f"{rel}:{node.lineno} {name}")
125                if name in ("run", "call", "Popen", "check_call", "check_output") and node.args:
126                    argv = node.args[0]
127                    words = []
128                    if isinstance(argv, (ast.List, ast.Tuple)):
129                        words = [e.value for e in argv.elts if isinstance(e, ast.Constant) and isinstance(e.value, str)]
130                    elif isinstance(argv, ast.Constant) and isinstance(argv.value, str):
131                        words = argv.value.split()
132                    hit = INSTALL_WORDS & {Path(w).stem if w.endswith(".exe") else w for w in words}
133                    if hit:
134                        bad.append(f"{rel}:{node.lineno} subprocess {sorted(hit)}")
135        self.assertEqual(bad, [])
136        for key, why in NETWORK_ALLOWED.items():
137            self.assertTrue(why)
138
139
140class _Recorder:
141    """Stands in for the network and for every way of starting a program; records what a start tries."""
142
143    def __init__(self):
144        self.network = []
145        self.programs = []
146
147    def urlopen(self, req, *a, **k):
148        self.network.append(getattr(req, "full_url", str(req)))
149        raise AssertionError("a start reached the network: " + self.network[-1])
150
151    def program(self, argv, *a, **k):
152        argv = [str(x) for x in (argv if isinstance(argv, (list, tuple)) else str(argv).split())]
153        self.programs.append(argv)
154        return subprocess.CompletedProcess(argv, 0, stdout="", stderr="")
155
156    def installers(self):
157        return [a for a in self.programs
158                if INSTALL_WORDS & {Path(w).stem.lower() if w.lower().endswith(".exe") else w for w in a}
159                or "pip" in a or "-m" in a and "pip" in a]
160
161
162class StartNeverAcquiresTests(unittest.TestCase):
163    def setUp(self):
164        self.tmp = tempfile.TemporaryDirectory()
165        self.addCleanup(self.tmp.cleanup)
166        self.root = Path(self.tmp.name) / "Strata"
167        self.root.mkdir()
168        self.data = Path(self.tmp.name) / "Strata-data"
169        (self.data / "models").mkdir(parents=True)
170        self.gguf = self.data / "models" / "m.gguf"
171        self.gguf.write_bytes(b"GGUF")
172        eng = self.root / "engine"
173        eng.mkdir()
174        (eng / setup.EXE).write_bytes(b"engine")
175        # an engine older than this Strata expects: a start used to download the new one
176        (eng / "BUILD.json").write_text(json.dumps({"version": "0.1.1", "source": "prebuilt", "backend": "cuda",
177                                                    "archs": [86]}))
178        self.cfg = self.root / "strata-q2_0.json"
179        self.cfg.write_text(json.dumps({
180            "exe": str(eng / setup.EXE), "args": ["--native", str(self.gguf), "--max-context", "8192"],
181            "tokenizer": str(self.data / "tok.json"), "model_name": "Q2_0", "port": 8080}))
182        self.settings_home = Path(self.tmp.name) / "appdata"
183        self.settings_home.mkdir()
184        env = {"APPDATA": str(self.settings_home), "XDG_CONFIG_HOME": str(self.settings_home)}
185        patcher = mock.patch.dict(os.environ, env)
186        patcher.start()
187        self.addCleanup(patcher.stop)
188        setup.settings_path().parent.mkdir(parents=True, exist_ok=True)
189        setup.settings_path().write_text(json.dumps({"data_dir": str(self.data), "installs": [str(self.root)]}))
190        self.settings_before = setup.settings_path().read_bytes()
191        # pip_install keeps its stamp in sys.prefix: never in the interpreter running the tests
192        prefix = mock.patch.object(sys, "prefix", str(self.root))
193        prefix.start()
194        self.addCleanup(prefix.stop)
195
196    def run_setup(self, rec, *argv, gpus=None):
197        out = io.StringIO()
198        started = []
199        with contextlib.ExitStack() as st:
200            st.enter_context(mock.patch.object(setup, "ROOT", self.root))
201            st.enter_context(mock.patch.object(sys, "argv", ["setup.py", *argv]))
202            st.enter_context(mock.patch.object(urllib.request, "urlopen", rec.urlopen))
203            st.enter_context(mock.patch.object(setup.netpolicy, "urlopen", rec.urlopen))
204            for n in ("run", "call", "Popen", "check_call", "check_output"):
205                st.enter_context(mock.patch.object(subprocess, n, rec.program))
206            st.enter_context(mock.patch.object(setup, "gpus", lambda: gpus or []))
207            st.enter_context(mock.patch.object(setup, "call_server", create=True))
208            st.enter_context(mock.patch.object(setup.subprocess, "call", lambda cmd, *a, **k: (
209                started.append(cmd), setattr(self, "env_of_start", (k.get("env") or {}).get(acquisition.ENV)), 0)[-1]))
210            st.enter_context(contextlib.redirect_stdout(out))
211            try:
212                code = setup.main()
213            except SystemExit as e:
214                code = e.code
215            except acquisition.AcquisitionRefused as e:
216                code = e
217        return code, out.getvalue(), started
218
219    def test_a_start_with_an_old_engine_makes_no_request_and_runs_no_installer(self):
220        rec = _Recorder()
221        code, text, started = self.run_setup(rec, "--yes", "--no-browser")
222        self.assertEqual(code, 0, text)
223        self.assertEqual(rec.network, [])
224        self.assertEqual(rec.installers(), [])
225        self.assertEqual(len(started), 1, text)                        # the server was started
226        self.assertIn("server.py", " ".join(started[0]))
227        self.assertEqual(self.env_of_start, "1")                         # the server is told, too
228        self.assertIn("is older than this Strata expects", text)
229        self.assertTrue("UPDATE" in text or "update.sh" in text, text)     # UPDATE.bat on Windows, ./update.sh elsewhere
230
231    def test_a_start_moves_copies_and_creates_nothing(self):
232        before = sorted(p.relative_to(self.tmp.name).as_posix() for p in Path(self.tmp.name).rglob("*"))
233        stamps = {p: p.stat().st_mtime_ns for p in Path(self.tmp.name).rglob("*") if p.is_file()}
234        rec = _Recorder()
235        code, text, _ = self.run_setup(rec, "--yes", "--no-browser")
236        self.assertEqual(code, 0, text)
237        after = sorted(p.relative_to(self.tmp.name).as_posix() for p in Path(self.tmp.name).rglob("*"))
238        self.assertEqual(before, after)
239        self.assertEqual(setup.settings_path().read_bytes(), self.settings_before)
240        for p, ns in stamps.items():
241            if p != self.cfg:                                          # a start touches the config (most recently used)
242                self.assertEqual(p.stat().st_mtime_ns, ns, p)
243
244    def test_a_card_the_engine_has_no_code_for_is_a_typed_error_naming_the_command(self):
245        rec = _Recorder()
246        card = {"index": 0, "name": "RTX 5090", "arch": "120", "vram_gb": 32.0, "driver": "580.0"}
247        with mock.patch.object(setup, "engine_runs_on", lambda g, tk=13: False), \
248                mock.patch.object(setup, "old_gpus_opt_in", lambda *a, **k: []):
249            code, text, started = self.run_setup(rec, "--yes", "--no-browser", gpus=[card])
250        self.assertIsInstance(code, acquisition.AcquisitionRefused)
251        self.assertIn("RTX 5090", str(code))
252        self.assertIn("setup", str(code).lower())
253        self.assertEqual((rec.network, rec.installers(), started), ([], [], []))
254
255    def test_main_script_reports_the_refusal_and_exits_5(self):
256        e = acquisition.AcquisitionRefused("an engine for sm_120")
257        self.assertEqual(e.exit_code, 5)
258        self.assertEqual(e.code, "acquisition_refused")
259        self.assertIn("never install or download", str(e))
260
261    def test_every_acquiring_primitive_refuses_while_a_model_starts(self):
262        rec = _Recorder()
263        calls = [
264            lambda: setup.download("https://example.invalid/x.bin", self.root / "x.bin"),
265            lambda: setup.download("file:///nonexistent", self.root / "y.bin"),
266            lambda: setup.pip_install(["definitely-not-installed==1.0"], "a test package"),
267            lambda: setup.run([sys.executable, "-m", "pip", "install", "x"]),
268            lambda: setup._urlopen(urllib.request.Request("https://example.invalid/")),
269            lambda: setup.reachable("https://example.invalid/"),
270            lambda: setup.get_prebuilt("https://example.invalid/", {"arch": "86"}, "none"),
271            lambda: setup.cmake_build(self.root, self.root / "b", "strata", [], None, ""),
272            lambda: setup.pip_cuda_libs(13),
273        ]
274        with mock.patch.object(urllib.request, "urlopen", rec.urlopen), mock.patch.object(setup.netpolicy, "urlopen", rec.urlopen), \
275                mock.patch.object(subprocess, "run", rec.program), mock.patch.object(subprocess, "Popen", rec.program):
276            with acquisition.forbidden():
277                for i, call in enumerate(calls):
278                    with self.subTest(i=i):
279                        with self.assertRaises(acquisition.AcquisitionRefused) as cm:
280                            call()
281                        self.assertIn("Run:", str(cm.exception))
282        self.assertEqual((rec.network, rec.programs), ([], []))
283
284    def test_the_environment_switch_forbids_a_whole_process(self):
285        with mock.patch.dict(os.environ, {acquisition.ENV: "1"}):
286            with self.assertRaises(acquisition.AcquisitionRefused):
287                setup.pip_install(["definitely-not-installed==1.0"], "a test package")
288
289    def test_update_still_installs(self):
290        """The explicit commands keep working: outside a start, the install step runs."""
291        installed = []
292        with tempfile.TemporaryDirectory() as prefix, mock.patch.object(sys, "prefix", prefix),                 mock.patch.object(setup, "run", lambda cmd, **k: installed.append([str(c) for c in cmd])):
293            setup.pip_install(["somepkg==1.0"], "a test package")
294        self.assertEqual(len(installed), 1)
295        self.assertIn("pip", installed[0])
296
297
298class CliServeIsOfflineTests(unittest.TestCase):
299    def test_serve_plan_reaches_no_network_and_runs_no_program(self):
300        rec = _Recorder()
301        with tempfile.TemporaryDirectory() as d:
302            cfg = Path(d) / "strata-x.json"
303            gguf = Path(d) / "m.gguf"
304            gguf.write_bytes(b"GGUF")
305            tok = Path(d) / "t.json"
306            tok.write_text("{}")
307            exe = Path(d) / "strata.exe"
308            exe.write_bytes(b"x")
309            cfg.write_text(json.dumps({"exe": str(exe), "args": ["--native", str(gguf)], "tokenizer": str(tok)}))
310            out = io.StringIO()
311            with mock.patch.object(urllib.request, "urlopen", rec.urlopen), \
312                    mock.patch.object(subprocess, "run", rec.program), mock.patch.object(subprocess, "Popen", rec.program), \
313                    mock.patch.dict(os.environ, {"STRATA_PROFILE_DIR": str(Path(d) / "profiles")}), \
314                    contextlib.redirect_stdout(out):
315                code = cli.main(["serve", "--profile", str(cfg), "--plan", "--output", "json"])
316        self.assertEqual(code, 0, out.getvalue())
317        # Reading the hardware is not acquiring anything: nvidia-smi / hipInfo / rocminfo and PowerShell's Get-CimInstance (display adapters) only
318        # print what is here. Whether a PC runs them depends on the PC (a machine with nvidia-smi on PATH does), so the check is that nothing else runs.
319        probes = {"nvidia-smi", "hipinfo", "rocminfo", "rocm-smi", "vulkaninfo"}
320
321        def read_only(argv):
322            stem = Path(argv[0]).stem.lower()
323            return stem in probes or (stem in ("powershell", "pwsh") and any("Get-CimInstance" in a for a in argv))
324        self.assertEqual(rec.network, [])
325        self.assertEqual([a for a in rec.programs if not read_only(a)], [])
326        self.assertNotIn("setup", sys.modules.get("strata_cli.cli").__dict__.get("__name__", ""))
327
328    def test_strata_install_without_the_installer_is_a_typed_error(self):
329        err = io.StringIO()
330        with tempfile.TemporaryDirectory() as d, \
331                mock.patch.dict(os.environ, {"STRATA_INSTALL_DIR": d}), \
332                mock.patch.object(cli, "ROOT", Path(d)), contextlib.redirect_stderr(err):
333            code = cli.main(["install"])
334        self.assertEqual(code, 5)
335        self.assertIn("installer", err.getvalue())
336
337
338if __name__ == "__main__":
339    unittest.main()