okami.mom/strata

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

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

main
17.3 KiB293 linesraw
1"""The Docker files stay consistent: shell scripts parse, Dockerfiles use only what the legacy builder knows, the compose examples carry what
2docs/DOCKER.md says they carry, and every setting the document lists is one the entry point reads."""
3from __future__ import annotations
4
5import ast
6import re
7import shutil
8import subprocess
9import unittest
10from pathlib import Path
11
12import yaml
13
14ROOT = Path(__file__).resolve().parents[2]
15DOCKER = ROOT / "docker"
16SH = shutil.which("sh")
17BASH = shutil.which("bash")      # the full path: on Windows a bare "bash" can start the WSL launcher in System32 instead of Git bash
18CYGPATH = shutil.which("cygpath")
19
20
21def sh_path(p) -> str:
22    """The path as the shell reads it. Git bash on Windows wants /c/Users/..., not C:\\Users\\... (tar even takes `C:` for a host)."""
23    if CYGPATH is None:
24        return str(p)
25    return subprocess.run([CYGPATH, "-u", str(p)], capture_output=True, text=True, check=True).stdout.strip()
26
27
28class Scripts(unittest.TestCase):
29    @unittest.skipIf(SH is None, "needs sh")
30    def test_shell_scripts_parse(self):
31        for name in ("entrypoint.sh", "strata-wrapper.sh", "healthcheck.sh", "build.sh", "publish.sh"):
32            r = subprocess.run([SH, "-n", sh_path(DOCKER / name)], capture_output=True, text=True)
33            self.assertEqual(r.returncode, 0, f"{name}: {r.stderr}")
34
35    @unittest.skipIf(BASH is None, "needs bash")
36    def test_smoke_test_parses_with_bash(self):           # it is a bash script (process substitution), not POSIX sh
37        r = subprocess.run([BASH, "-n", sh_path(DOCKER / "smoke-test.sh")], capture_output=True, text=True)
38        self.assertEqual(r.returncode, 0, r.stderr)
39
40    @unittest.skipIf(SH is None or shutil.which("tar") is None, "needs sh and tar")
41    def test_build_script_exits_zero_after_assembling_a_context(self):
42        """--ctx-only stops after the context is made (no docker needed). The EXIT trap once returned 1 there, so a good run reported failure."""
43        import tempfile
44        with tempfile.TemporaryDirectory() as tmp:
45            pkg = Path(tmp) / "pkg"
46            pkg.mkdir()
47            (pkg / "engine-component.json").write_text('{"entrypoint": "strata"}', encoding="utf-8")
48            (pkg / "strata").write_text("#!/bin/sh\n", encoding="utf-8")
49            (pkg / "strata").chmod(0o755)
50            ctx = Path(tmp) / "ctx"
51            r = subprocess.run([SH, sh_path(DOCKER / "build.sh"), "--flavor", "cuda", "--engine", sh_path(pkg), "--ctx", sh_path(ctx), "--ctx-only"],
52                               capture_output=True, text=True)
53            self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
54            self.assertTrue((ctx / "Dockerfile").is_file())
55            self.assertTrue((ctx / "terminal-src" / "docs" / "TERMINAL_LAUNCH.md").is_file())
56            self.assertTrue((ctx / "engine" / "pkg" / "engine-component.json").is_file())
57            # the bundle reads tools/ modules by path as well (INSTALLER_SCRIPTS), and the DeepSeek ones are nested: every name must be in the
58            # context, or package_terminal.py stops the build at "installer tool missing: tools/<name>.py" (the image build after v0.2.4.1 was broken this way)
59            pt = ast.parse((ROOT / "packaging" / "package_terminal.py").read_text(encoding="utf-8"))
60            tools: set[str] = set()
61            for node in pt.body:
62                if isinstance(node, ast.Assign) and any(getattr(t, "id", "") in ("INSTALLER_TOOLS", "INSTALLER_SCRIPTS") for t in node.targets):
63                    tools.update(ast.literal_eval(node.value))
64            self.assertTrue(tools, "package_terminal.py names its installer tools")
65            for name in sorted(tools):
66                self.assertTrue((ctx / "terminal-src" / "tools" / f"{name}.py").is_file(), f"build.sh did not copy tools/{name}.py into the context")
67            # the Mac repack scripts the bundle carries (the v0.2.11 image build stopped at "No such file ... metal/tools/metal_repack.py")
68            metal: set[str] = set()
69            for node in pt.body:
70                if isinstance(node, ast.Assign) and any(getattr(t, "id", "") == "INSTALLER_METAL_TOOLS" for t in node.targets):
71                    metal.update(ast.literal_eval(node.value))
72            self.assertTrue(metal)
73            for name in sorted(metal):
74                self.assertTrue((ctx / "terminal-src" / "metal" / "tools" / f"{name}.py").is_file(), f"build.sh did not copy metal/tools/{name}.py into the context")
75
76    def test_scripts_use_unix_line_ends(self):
77        for name in ("entrypoint.sh", "strata-wrapper.sh", "healthcheck.sh", "build.sh", "publish.sh"):
78            self.assertNotIn(b"\r", (DOCKER / name).read_bytes(), name)       # build.sh strips CR for a CRLF checkout, the files themselves stay LF
79
80
81class Dockerfiles(unittest.TestCase):
82    FILES = (DOCKER / "Dockerfile", ROOT / "Dockerfile")
83
84    def test_only_legacy_builder_syntax(self):
85        for f in self.FILES:
86            text = f.read_text(encoding="utf-8")
87            self.assertNotRegex(text, r"<<\s*-?['\"]?\w+", f"{f.name}: a heredoc needs BuildKit")
88            self.assertNotIn("--mount=", text, f.name)
89            self.assertNotRegex(text, r"COPY\s+--chmod", f.name)
90
91    def test_runtime_contract(self):
92        for f in self.FILES:
93            text = f.read_text(encoding="utf-8")
94            self.assertIn("HEALTHCHECK", text, f.name)
95            self.assertIn("STOPSIGNAL SIGTERM", text, f.name)
96            self.assertIn('ENTRYPOINT ["/usr/bin/tini", "--", "/opt/strata/entrypoint.sh"]', text, f.name)
97            self.assertIn("VOLUME [\"/data\"]", text, f.name)
98            self.assertIn("STRATA_COMPONENTS_DIR=/opt/strata/components", text, f.name)
99
100    def test_component_image_checks_the_package_before_use(self):
101        text = (DOCKER / "Dockerfile").read_text(encoding="utf-8")
102        self.assertIn("package_engine.py", text)
103        self.assertIn("binary_deps.py", text)
104        self.assertIn("ldd", text)                       # the finished image resolves every library of the package
105
106    def test_binary_deps_and_package_engine_exist_where_the_dockerfile_copies_them(self):
107        for name in ("package_engine.py", "binary_deps.py", "package_terminal.py"):
108            self.assertTrue((ROOT / "packaging" / name).is_file(), name)
109
110
111class Compose(unittest.TestCase):
112    def load(self, name: str) -> dict:
113        data = yaml.safe_load((DOCKER / "compose" / name).read_text(encoding="utf-8"))
114        self.assertIn("strata", data["services"], name)
115        return data
116
117    def test_common_settings(self):
118        for name in ("docker-compose.nvidia.yml", "docker-compose.amd.yml", "docker-compose.intel.yml"):
119            svc = self.load(name)["services"]["strata"]
120            self.assertIn("strata-data:/data", svc["volumes"], name)
121            self.assertEqual(svc["ulimits"]["memlock"], {"soft": -1, "hard": -1}, name)
122            self.assertEqual(svc["shm_size"], "2gb", name)
123            self.assertEqual(svc["stop_grace_period"], "2m", name)
124            self.assertTrue(svc["ports"][0].startswith("${STRATA_BIND:-127.0.0.1}:"), f"{name}: the port must default to this computer only")
125            for var in ("MODEL", "MODEL_PATH", "CONTEXT", "PARALLEL", "VISION", "TUNE", "API_KEY"):
126                self.assertIn(var, svc["environment"], f"{name}: {var}")
127            self.assertIn("strata-data", self.load(name)["volumes"], name)
128
129    def test_gpu_access_per_vendor(self):
130        nv = self.load("docker-compose.nvidia.yml")["services"]["strata"]
131        dev = nv["deploy"]["resources"]["reservations"]["devices"][0]
132        self.assertEqual(dev["driver"], "nvidia")
133        self.assertIn("gpu", dev["capabilities"])
134        amd = self.load("docker-compose.amd.yml")["services"]["strata"]
135        self.assertIn("/dev/kfd:/dev/kfd", amd["devices"])
136        self.assertIn("/dev/dri:/dev/dri", amd["devices"])
137        self.assertIn("video", amd["group_add"])
138        self.assertTrue(any("render" in str(g).lower() or "RENDER" in str(g) for g in amd["group_add"]))
139        intel = self.load("docker-compose.intel.yml")["services"]["strata"]
140        self.assertIn("/dev/dri:/dev/dri", intel["devices"])
141        self.assertNotIn("/dev/kfd:/dev/kfd", intel["devices"])
142
143
144@unittest.skipIf(SH is None, "needs sh")
145class LegacyModelsGuard(unittest.TestCase):
146    """#3421: model files left in the older image's /data/models (a folder the person mounted there, or a failed move) are not read by this image,
147    so the start would download the model again. It stops and says where the files are; MODEL_PATH names them, ALLOW_DOWNLOAD=1 goes on."""
148
149    def run_guard(self, folder, model_path="", allow=None):
150        import os
151        import tempfile
152        entry = (DOCKER / "entrypoint.sh").read_text(encoding="utf-8")
153        body = entry[entry.index("legacy_models_guard() {"):]
154        body = body[:body.index("\n}\n") + 3]
155        with tempfile.TemporaryDirectory() as tmp:
156            script = Path(tmp) / "guard.sh"
157            script.write_text("warn() { printf '[!] %s\\n' \"$*\" >&2; }\ndie() { printf '[X] %s\\n' \"$*\" >&2; exit \"${2:-1}\"; }\n" + body
158                              + f"\nlegacy_models_guard '{model_path}' '{sh_path(folder)}'\necho CONTINUED\n", encoding="utf-8", newline="\n")
159            env = dict(os.environ)
160            env.pop("ALLOW_DOWNLOAD", None)
161            if allow is not None:
162                env["ALLOW_DOWNLOAD"] = allow
163            return subprocess.run([SH, sh_path(script)], capture_output=True, text=True, env=env)
164
165    def test_files_in_the_older_place_stop_the_start_with_the_folder_named(self):
166        import tempfile
167        with tempfile.TemporaryDirectory() as tmp:
168            shards = Path(tmp) / "IQ3_XXS"
169            shards.mkdir()
170            (shards / "model-00001-of-00002.gguf").write_bytes(b"GGUF")
171            done = self.run_guard(Path(tmp))
172            self.assertEqual(done.returncode, 2, done.stdout + done.stderr)
173            self.assertNotIn("CONTINUED", done.stdout)
174            self.assertIn(shards.name, done.stderr)
175            self.assertIn("MODEL_PATH", done.stderr)
176            self.assertIn("ALLOW_DOWNLOAD=1", done.stderr)
177            self.assertIn("Nothing was downloaded", done.stderr)
178
179    def test_model_path_allow_download_an_empty_folder_and_a_missing_one_go_on(self):
180        import tempfile
181        with tempfile.TemporaryDirectory() as tmp:
182            (Path(tmp) / "IQ3_XXS").mkdir()
183            (Path(tmp) / "IQ3_XXS" / "model-00001-of-00002.gguf").write_bytes(b"GGUF")
184            named = self.run_guard(Path(tmp), model_path="/models")
185            self.assertEqual((named.returncode, "CONTINUED" in named.stdout), (0, True), named.stderr)
186            allowed = self.run_guard(Path(tmp), allow="1")
187            self.assertEqual((allowed.returncode, "CONTINUED" in allowed.stdout), (0, True), allowed.stderr)
188            self.assertIn("[!]", allowed.stderr)
189            self.assertIn("ALLOW_DOWNLOAD=1", allowed.stderr)
190        with tempfile.TemporaryDirectory() as empty:
191            nothing = self.run_guard(Path(empty))
192            self.assertEqual((nothing.returncode, "CONTINUED" in nothing.stdout), (0, True), nothing.stderr)
193        missing = self.run_guard(Path("/no/such/folder"))
194        self.assertEqual((missing.returncode, "CONTINUED" in missing.stdout), (0, True), missing.stderr)
195
196    def test_the_entry_point_runs_the_guard_before_any_flag_is_built(self):
197        entry = (DOCKER / "entrypoint.sh").read_text(encoding="utf-8")
198        self.assertLess(entry.index('legacy_models_guard "$model_path"'), entry.index('--model "$MODEL"'))
199
200
201class Document(unittest.TestCase):
202    def test_every_documented_setting_is_read_by_the_entry_point(self):
203        doc = (ROOT / "docs" / "DOCKER.md").read_text(encoding="utf-8")
204        section = doc.split("## Settings", 1)[1].split("###", 1)[0]
205        entry = (DOCKER / "entrypoint.sh").read_text(encoding="utf-8")
206        names: set[str] = set()
207        for line in section.splitlines():
208            if line.startswith("| `"):
209                names.update(re.findall(r"`([A-Z][A-Z_]+)`", line.split("|")[1]))
210        self.assertTrue({"MODEL", "CONTEXT", "API_KEY", "TUNE", "VISION", "MODEL_PATH", "STRATA_SET"} <= names, names)
211        for name in sorted(names):
212            self.assertIn(name, entry, f"docs/DOCKER.md lists {name} but docker/entrypoint.sh does not read it")
213
214    def test_tags_in_the_document_match_the_compose_defaults(self):
215        doc = (ROOT / "docs" / "DOCKER.md").read_text(encoding="utf-8")
216        for tag in ("0.2.7-cuda13", "0.2.7-cuda12", "0.2.7-rocm-gfx120x", "0.2.7-rocm-gfx110x", "0.2.7-rocm-gfx1151", "0.2.7-sycl"):
217            self.assertIn(tag, doc)
218        for name, tag in (("docker-compose.nvidia.yml", "ghcr.io/niko1221/strata:0.2.7-cuda13"), ("docker-compose.amd.yml", "ghcr.io/niko1221/strata:0.2.7-rocm-gfx120x"),
219                          ("docker-compose.intel.yml", "ghcr.io/niko1221/strata:0.2.7-sycl")):
220            self.assertIn(tag, (DOCKER / "compose" / name).read_text(encoding="utf-8"))
221
222    def test_the_user_doc_says_images_are_published_from_0_2_1(self):
223        doc = (ROOT / "docs" / "DOCKER.md").read_text(encoding="utf-8")
224        self.assertNotIn("TODO(owner)", doc)
225        self.assertNotIn("not available yet", doc)
226        self.assertIn("published from version 0.2.1 on", doc)
227        self.assertIn("Publishing the images (for maintainers)", doc)
228
229
230class Publishing(unittest.TestCase):
231    """The scripts and the workflow that publish the images (docker/publish.sh, docker/fetch-engines.py, .github/workflows/docker-images.yml)."""
232    WORKFLOW = ROOT / ".github" / "workflows" / "docker-images.yml"
233
234    @unittest.skipIf(SH is None, "needs sh")
235    def test_publish_script_parses_and_defaults_to_not_pushing(self):
236        path = DOCKER / "publish.sh"
237        self.assertEqual(subprocess.run([SH, "-n", sh_path(path)], capture_output=True, text=True).returncode, 0)
238        text = path.read_text(encoding="utf-8")
239        self.assertNotIn("\r", text)
240        self.assertIn('push=""', text)                      # no --push, no docker push
241        pushes = re.findall(r'^[^#\n]*docker push "', text, re.M)
242        self.assertEqual(len(pushes), 2, pushes)             # the version tag and latest-<flavor>, both inside `if [ -n "$push" ]`
243
244    def test_every_flavor_of_the_document_is_one_the_fetch_script_knows(self):
245        src = (DOCKER / "fetch-engines.py").read_text(encoding="utf-8")
246        flavors = re.findall(r'^    "([a-z0-9-]+)": \("', src, re.M)
247        doc = (ROOT / "docs" / "DOCKER.md").read_text(encoding="utf-8")
248        self.assertTrue({"cuda13", "cuda12", "rocm-gfx120x", "rocm-gfx110x", "rocm-gfx1151", "sycl"} <= set(flavors), flavors)
249        for flavor in flavors:
250            self.assertIn(f"0.2.7-{flavor}", doc)
251
252    def test_build_script_copies_everything_the_terminal_package_needs(self):
253        """docker/build.sh lists the Terminal's files by hand; the list must cover package_terminal.py's payload (it once missed docs/TERMINAL_LAUNCH.md)."""
254        build = (DOCKER / "build.sh").read_text(encoding="utf-8")
255        listed = re.search(r'^paths="([^"]+)"', build, re.M).group(1).split()
256        pt = ast.parse((ROOT / "packaging" / "package_terminal.py").read_text(encoding="utf-8"))
257        payload = None
258        for node in pt.body:
259            if isinstance(node, ast.Assign) and any(getattr(t, "id", "") == "PAYLOAD" for t in node.targets):
260                payload = ast.literal_eval(node.value)
261        self.assertTrue(payload)
262        for item in payload:
263            self.assertTrue(any(item == p or item.startswith(p.rstrip("/") + "/") for p in listed), f"build.sh does not copy {item}")
264
265    def test_the_source_build_passes_the_commit_to_the_terminal_stage(self):
266        """.git is not in the build context (.dockerignore), so the root Dockerfile's terminal stage gets the commit as a build argument, the way
267        docker/Dockerfile does; without it package_terminal.py stops (#3644). The documented source-build commands pass it."""
268        for dockerfile in (ROOT / "Dockerfile", DOCKER / "Dockerfile"):
269            text = dockerfile.read_text(encoding="utf-8")
270            self.assertRegex(text, r"(?m)^ARG STRATA_COMMIT=", dockerfile.name)
271            self.assertIn("ENV STRATA_BUILD_COMMIT=${STRATA_COMMIT}", text, dockerfile.name)
272        self.assertIn(".git", (ROOT / ".dockerignore").read_text(encoding="utf-8").split())
273        doc = (ROOT / "docs" / "DOCKER.md").read_text(encoding="utf-8")
274        self.assertEqual(doc.count("docker build -t strata:src"), doc.count("--build-arg STRATA_COMMIT=$(git rev-parse HEAD)"))
275        self.assertIn("/data/install/", (ROOT / ".dockerignore").read_text(encoding="utf-8"))
276
277    def test_workflow_is_manual_and_pushes_only_on_request(self):
278        data = yaml.safe_load(self.WORKFLOW.read_text(encoding="utf-8"))
279        triggers = data.get("on", data.get(True))            # YAML 1.1 reads a bare `on` as True
280        self.assertEqual(set(triggers), {"workflow_dispatch"})
281        inputs = triggers["workflow_dispatch"]["inputs"]
282        self.assertIn("release_tag", inputs)
283        self.assertFalse(inputs["push"]["default"])
284        self.assertEqual(data["permissions"], {"contents": "read"})
285        self.assertEqual(data["jobs"]["image"]["permissions"], {"contents": "read", "packages": "write"})
286        text = self.WORKFLOW.read_text(encoding="utf-8")
287        self.assertIn("ghcr.io/niko1221/strata", text)
288        self.assertIn("docker/publish.sh", text)
289        self.assertNotIn("${{ secrets.GITHUB_TOKEN }}\" |", text)   # the token goes through an env variable, not into the command line
290
291
292if __name__ == "__main__":
293    unittest.main()