okami.mom/strata

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

Niko1221Merge f-int-tidy 4e9dde87e into f-p4-int (conversation tests in the CPU check preset, packer probe without bytecode, a per-architecture spill-guard baseline, a log line for a driver GPU pause between requests on AMD under Linux)466626cbb

main
8.9 KiB163 linesraw
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]:
23    found: set[str] = set()
24    for node in ast.walk(ast.parse(path.read_text(encoding="utf-8-sig"))):
25        if isinstance(node, ast.Import):
26            found.update(a.name.split(".")[0] for a in node.names)
27        elif isinstance(node, ast.ImportFrom) and node.module and node.level == 0:
28            found.add(node.module.split(".")[0])
29    return found
30
31
32class BundleImports(unittest.TestCase):
33    @classmethod
34    def setUpClass(cls):
35        cls.temp = tempfile.TemporaryDirectory(prefix="strata-bundle-")
36        cls.root = Path(cls.temp.name) / "strata-terminal"
37        cls.root.mkdir()
38        ignore = shutil.ignore_patterns("__pycache__", "*.pyc")
39        for item in pt.PAYLOAD:
40            src, dst = ROOT / item, cls.root / item
41            dst.parent.mkdir(parents=True, exist_ok=True)
42            if src.is_dir():
43                shutil.copytree(src, dst, ignore=ignore)
44            else:
45                shutil.copy2(src, dst)
46        (cls.root / "tools").mkdir(exist_ok=True)
47        for item in pt.TOOLS_SUBSET:
48            shutil.copy2(ROOT / "tools" / item, cls.root / "tools" / item)
49        cls.installer = pt.add_installer(cls.root, ROOT)
50
51    @classmethod
52    def tearDownClass(cls):
53        cls.temp.cleanup()
54
55    def 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
57        preparing a model downloads no llama.cpp; the bundled copy is byte-identical to the source tree's."""
58        here = self.root / "third_party" / "strata-gguf-py"
59        for rel in ("gguf/__init__.py", "gguf/quants.py", "converter/convert_hf_to_gguf.py", "converter/conversion/qwen4exp.py", "LICENSE", "UPSTREAM.md"):
60            self.assertTrue((here / rel).is_file(), rel)
61            self.assertEqual((here / rel).read_bytes(), (ROOT / "third_party" / "strata-gguf-py" / rel).read_bytes(), rel)
62        self.assertIn("third_party/strata-gguf-py/", self.installer["files"])
63        probe = subprocess.run([sys.executable, "-I", "-c", f"import sys; sys.path.insert(0, {str(self.root / 'tools')!r}); import _paths; print(_paths.gguf_py())"],
64                               capture_output=True, text=True, timeout=60, env={k: v for k, v in os.environ.items() if k != "STRATA_GGUF_PY"})
65        self.assertEqual(probe.returncode, 0, probe.stderr[-500:])
66        self.assertEqual(Path(probe.stdout.strip()).resolve(), here.resolve(), "a bundled tool finds the bundled copy")
67
68    def test_calibrate_is_in_the_bundle(self):
69        # the exact file #3613 and #3467 lacked
70        self.assertTrue((self.root / "tools" / "calibrate.py").is_file())
71        self.assertIn("calibrate", pt.INSTALLER_TOOLS)
72
73    def test_every_tools_module_setup_py_imports_is_in_the_bundle(self):
74        in_bundle = {p.stem for p in (self.root / "tools").glob("*.py")}
75        in_source = {p.stem for p in (ROOT / "tools").glob("*.py")}
76        wanted = imports_of(self.root / "setup.py") & in_source
77        self.assertIn("calibrate", wanted, "setup.py no longer imports calibrate: update this test")
78        self.assertEqual(sorted(wanted - in_bundle), [], "setup.py imports tools/ modules that the bundle does not carry")
79
80    def test_the_bundled_tools_import_nothing_the_bundle_lacks(self):
81        in_bundle = {p.stem for p in (self.root / "tools").glob("*.py")}
82        in_source = {p.stem for p in (ROOT / "tools").glob("*.py")}
83        for module in sorted(in_bundle):
84            missing = sorted((imports_of(self.root / "tools" / f"{module}.py") & in_source) - in_bundle)
85            self.assertEqual(missing, [], f"tools/{module}.py imports tools/ modules the bundle does not carry")
86
87    def test_setup_py_and_each_of_its_tools_import_with_tools_limited_to_the_bundle(self):
88        modules = sorted(set(pt.setup_tool_imports(self.root)) | set(pt.INSTALLER_TOOLS))
89        probe = subprocess.run([sys.executable, "-I", "-c", f"import sys; sys.path.insert(0, {str(self.root / 'tools')!r}); import _paths; _paths.gguf_py()"],
90                               capture_output=True, text=True, timeout=60, env={**os.environ, "STRATA_CONTROL_INSTALL": "1"})
91        if 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
92            self.skipTest("no llama.cpp gguf-py on this box (set STRATA_GGUF_PY to run this check)")
93        code = ("import sys, os, importlib\n"
94                f"sys.path[:0] = [{str(self.root)!r}, {str(self.root / 'tools')!r}]\n"
95                "import setup\n"
96                f"for name in {modules!r}:\n"
97                "    module = importlib.import_module(name)\n"
98                f"    assert os.path.samefile(os.path.dirname(module.__file__), {str(self.root / 'tools')!r}), (name, module.__file__)\n"
99                "print('imports ok')\n")
100        env = {**os.environ, "STRATA_CONTROL_INSTALL": "1", "PYTHONNOUSERSITE": "1"}
101        for key in ("PYTHONPATH", "PYTHONHOME"):
102            env.pop(key, None)
103        done = subprocess.run([sys.executable, "-I", "-c", code], cwd=str(self.root.parent), env=env,
104                              capture_output=True, text=True, timeout=120)
105        self.assertEqual(done.returncode, 0, (done.stdout or "") + (done.stderr or "")[-1500:])
106        self.assertIn("imports ok", done.stdout)
107
108    def 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
110        self.assertTrue(set(pt.setup_tool_imports(ROOT)) <= set(pt.local_imports(ROOT, tuple(sorted(
111            set(pt.INSTALLER_TOOLS) | set(pt.setup_tool_imports(ROOT)))))))
112        without = tuple(x for x in pt.INSTALLER_TOOLS if x != "calibrate")
113        self.assertNotIn("calibrate", pt.local_imports(ROOT, without))      # the old list really lacked it
114        self.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
120    def setUp(self):
121        self.temp = tempfile.TemporaryDirectory(prefix="strata-probe-")
122        self.addCleanup(self.temp.cleanup)
123        self.root = Path(self.temp.name) / "bundle"
124        self.root.mkdir()
125        (self.root / "probe_mod.py").write_text("VALUE = 7\n", encoding="utf-8")
126        self.code = "import probe_mod; print('probe ok', probe_mod.VALUE)"
127        self.saved = {k: os.environ.pop(k, None) for k in ("PYTHONDONTWRITEBYTECODE", "PYTHONPYCACHEPREFIX")}
128        self.addCleanup(self.restore)
129
130    def restore(self):
131        for key, value in self.saved.items():
132            if value is None:
133                os.environ.pop(key, None)
134            else:
135                os.environ[key] = value
136
137    def leftovers(self, folder: Path):
138        return sorted(str(p.relative_to(folder)) for p in list(folder.rglob("__pycache__")) + list(folder.rglob("*.pyc")))
139
140    def 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
142        plain = Path(self.temp.name) / "plain"
143        plain.mkdir()
144        (plain / "probe_mod.py").write_text("VALUE = 7\n", encoding="utf-8")
145        done = subprocess.run([sys.executable, "-c", self.code], cwd=str(plain), capture_output=True, text=True, timeout=60)
146        self.assertEqual(done.returncode, 0, done.stderr)
147        self.assertTrue(self.leftovers(plain))
148
149    def test_the_probe_writes_no_bytecode_when_the_caller_did_not_ask_for_that(self):
150        done = pt.run_probe(Path(sys.executable), self.root, code=self.code)
151        self.assertEqual(done.returncode, 0, done.stderr)
152        self.assertIn("probe ok 7", done.stdout)
153        self.assertEqual(self.leftovers(self.root), [])
154
155    def test_the_probe_writes_no_bytecode_when_the_caller_asked_for_it(self):
156        os.environ["PYTHONDONTWRITEBYTECODE"] = ""        # an empty value means "write"
157        done = pt.run_probe(Path(sys.executable), self.root, code=self.code)
158        self.assertEqual(done.returncode, 0, done.stderr)
159        self.assertEqual(self.leftovers(self.root), [])
160
161
162if __name__ == "__main__":
163    unittest.main()