okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
aff3a132f
main
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).""" 23if CYGPATH is None : 24return str (p ) 25return 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" ) 30def test_shell_scripts_parse (self ): 31for name in ("entrypoint.sh" ,"strata-wrapper.sh" ,"healthcheck.sh" ,"build.sh" ,"publish.sh" ): 32r = subprocess .run ([SH ,"-n" ,sh_path (DOCKER / name )],capture_output = True ,text = True ) 33self .assertEqual (r .returncode ,0 ,f" { name } : { r . stderr } " ) 34 35@ unittest . skipIf ( BASH is None , "needs bash" ) 36def test_smoke_test_parses_with_bash (self ):# it is a bash script (process substitution), not POSIX sh 37r = subprocess .run ([BASH ,"-n" ,sh_path (DOCKER / "smoke-test.sh" )],capture_output = True ,text = True ) 38self .assertEqual (r .returncode ,0 ,r .stderr ) 39 40@ unittest . skipIf ( SH is None or shutil . which ( "tar" ) is None , "needs sh and tar" ) 41def 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.""" 43import tempfile 44with tempfile .TemporaryDirectory ()as tmp : 45pkg = Path (tmp )/ "pkg" 46pkg .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 ) 50ctx = Path (tmp )/ "ctx" 51r = subprocess .run ([SH ,sh_path (DOCKER / "build.sh" ),"--flavor" ,"cuda" ,"--engine" ,sh_path (pkg ),"--ctx" ,sh_path (ctx ),"--ctx-only" ], 52capture_output = True ,text = True ) 53self .assertEqual (r .returncode ,0 ,r .stdout + r .stderr ) 54self .assertTrue ((ctx / "Dockerfile" ).is_file ()) 55self .assertTrue ((ctx / "terminal-src" / "docs" / "TERMINAL_LAUNCH.md" ).is_file ()) 56self .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) 59pt = ast .parse ((ROOT / "packaging" / "package_terminal.py" ).read_text (encoding = "utf-8" )) 60tools :set [str ]= set () 61for node in pt .body : 62if isinstance (node ,ast .Assign )and any (getattr (t ,"id" ,"" )in ("INSTALLER_TOOLS" ,"INSTALLER_SCRIPTS" )for t in node .targets ): 63tools .update (ast .literal_eval (node .value )) 64self .assertTrue (tools ,"package_terminal.py names its installer tools" ) 65for name in sorted (tools ): 66self .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") 68metal :set [str ]= set () 69for node in pt .body : 70if isinstance (node ,ast .Assign )and any (getattr (t ,"id" ,"" )== "INSTALLER_METAL_TOOLS" for t in node .targets ): 71metal .update (ast .literal_eval (node .value )) 72self .assertTrue (metal ) 73for name in sorted (metal ): 74self .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 76def test_scripts_use_unix_line_ends (self ): 77for name in ("entrypoint.sh" ,"strata-wrapper.sh" ,"healthcheck.sh" ,"build.sh" ,"publish.sh" ): 78self .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 ): 82FILES = (DOCKER / "Dockerfile" ,ROOT / "Dockerfile" ) 83 84def test_only_legacy_builder_syntax (self ): 85for f in self .FILES : 86text = f .read_text (encoding = "utf-8" ) 87self .assertNotRegex (text ,r"<<\s*-?['\"]?\w+" ,f" { f . name } : a heredoc needs BuildKit" ) 88self .assertNotIn ("--mount=" ,text ,f .name ) 89self .assertNotRegex (text ,r"COPY\s+--chmod" ,f .name ) 90 91def test_runtime_contract (self ): 92for f in self .FILES : 93text = f .read_text (encoding = "utf-8" ) 94self .assertIn ("HEALTHCHECK" ,text ,f .name ) 95self .assertIn ("STOPSIGNAL SIGTERM" ,text ,f .name ) 96self .assertIn ('ENTRYPOINT ["/usr/bin/tini", "--", "/opt/strata/entrypoint.sh"]' ,text ,f .name ) 97self .assertIn ("VOLUME [\"/data\"]" ,text ,f .name ) 98self .assertIn ("STRATA_COMPONENTS_DIR=/opt/strata/components" ,text ,f .name ) 99 100def test_component_image_checks_the_package_before_use (self ): 101text = (DOCKER / "Dockerfile" ).read_text (encoding = "utf-8" ) 102self .assertIn ("package_engine.py" ,text ) 103self .assertIn ("binary_deps.py" ,text ) 104self .assertIn ("ldd" ,text )# the finished image resolves every library of the package 105 106def test_binary_deps_and_package_engine_exist_where_the_dockerfile_copies_them (self ): 107for name in ("package_engine.py" ,"binary_deps.py" ,"package_terminal.py" ): 108self .assertTrue ((ROOT / "packaging" / name ).is_file (),name ) 109 110 111class Compose (unittest .TestCase ): 112def load (self ,name :str )-> dict : 113data = yaml .safe_load ((DOCKER / "compose" / name ).read_text (encoding = "utf-8" )) 114self .assertIn ("strata" ,data ["services" ],name ) 115return data 116 117def test_common_settings (self ): 118for name in ("docker-compose.nvidia.yml" ,"docker-compose.amd.yml" ,"docker-compose.intel.yml" ): 119svc = self .load (name )["services" ]["strata" ] 120self .assertIn ("strata-data:/data" ,svc ["volumes" ],name ) 121self .assertEqual (svc ["ulimits" ]["memlock" ], {"soft" :- 1 ,"hard" :- 1 },name ) 122self .assertEqual (svc ["shm_size" ],"2gb" ,name ) 123self .assertEqual (svc ["stop_grace_period" ],"2m" ,name ) 124self .assertTrue (svc ["ports" ][0 ].startswith ("${STRATA_BIND:-127.0.0.1}:" ),f" { name } : the port must default to this computer only" ) 125for var in ("MODEL" ,"MODEL_PATH" ,"CONTEXT" ,"PARALLEL" ,"VISION" ,"TUNE" ,"API_KEY" ): 126self .assertIn (var ,svc ["environment" ],f" { name } : { var } " ) 127self .assertIn ("strata-data" ,self .load (name )["volumes" ],name ) 128 129def test_gpu_access_per_vendor (self ): 130nv = self .load ("docker-compose.nvidia.yml" )["services" ]["strata" ] 131dev = nv ["deploy" ]["resources" ]["reservations" ]["devices" ][0 ] 132self .assertEqual (dev ["driver" ],"nvidia" ) 133self .assertIn ("gpu" ,dev ["capabilities" ]) 134amd = self .load ("docker-compose.amd.yml" )["services" ]["strata" ] 135self .assertIn ("/dev/kfd:/dev/kfd" ,amd ["devices" ]) 136self .assertIn ("/dev/dri:/dev/dri" ,amd ["devices" ]) 137self .assertIn ("video" ,amd ["group_add" ]) 138self .assertTrue (any ("render" in str (g ).lower ()or "RENDER" in str (g )for g in amd ["group_add" ])) 139intel = self .load ("docker-compose.intel.yml" )["services" ]["strata" ] 140self .assertIn ("/dev/dri:/dev/dri" ,intel ["devices" ]) 141self .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, 147so 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 149def run_guard (self ,folder ,model_path = "" ,allow = None ): 150import os 151import tempfile 152entry = (DOCKER / "entrypoint.sh" ).read_text (encoding = "utf-8" ) 153body = entry [entry .index ("legacy_models_guard() {" ):] 154body = body [:body .index ("\n}\n" )+ 3 ] 155with tempfile .TemporaryDirectory ()as tmp : 156script = Path (tmp )/ "guard.sh" 157script .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" ) 159env = dict (os .environ ) 160env .pop ("ALLOW_DOWNLOAD" ,None ) 161if allow is not None : 162env ["ALLOW_DOWNLOAD" ]= allow 163return subprocess .run ([SH ,sh_path (script )],capture_output = True ,text = True ,env = env ) 164 165def test_files_in_the_older_place_stop_the_start_with_the_folder_named (self ): 166import tempfile 167with tempfile .TemporaryDirectory ()as tmp : 168shards = Path (tmp )/ "IQ3_XXS" 169shards .mkdir () 170 (shards / "model-00001-of-00002.gguf" ).write_bytes (b"GGUF" ) 171done = self .run_guard (Path (tmp )) 172self .assertEqual (done .returncode ,2 ,done .stdout + done .stderr ) 173self .assertNotIn ("CONTINUED" ,done .stdout ) 174self .assertIn (shards .name ,done .stderr ) 175self .assertIn ("MODEL_PATH" ,done .stderr ) 176self .assertIn ("ALLOW_DOWNLOAD=1" ,done .stderr ) 177self .assertIn ("Nothing was downloaded" ,done .stderr ) 178 179def test_model_path_allow_download_an_empty_folder_and_a_missing_one_go_on (self ): 180import tempfile 181with tempfile .TemporaryDirectory ()as tmp : 182 (Path (tmp )/ "IQ3_XXS" ).mkdir () 183 (Path (tmp )/ "IQ3_XXS" / "model-00001-of-00002.gguf" ).write_bytes (b"GGUF" ) 184named = self .run_guard (Path (tmp ),model_path = "/models" ) 185self .assertEqual ((named .returncode ,"CONTINUED" in named .stdout ), (0 ,True ),named .stderr ) 186allowed = self .run_guard (Path (tmp ),allow = "1" ) 187self .assertEqual ((allowed .returncode ,"CONTINUED" in allowed .stdout ), (0 ,True ),allowed .stderr ) 188self .assertIn ("[!]" ,allowed .stderr ) 189self .assertIn ("ALLOW_DOWNLOAD=1" ,allowed .stderr ) 190with tempfile .TemporaryDirectory ()as empty : 191nothing = self .run_guard (Path (empty )) 192self .assertEqual ((nothing .returncode ,"CONTINUED" in nothing .stdout ), (0 ,True ),nothing .stderr ) 193missing = self .run_guard (Path ("/no/such/folder" )) 194self .assertEqual ((missing .returncode ,"CONTINUED" in missing .stdout ), (0 ,True ),missing .stderr ) 195 196def test_the_entry_point_runs_the_guard_before_any_flag_is_built (self ): 197entry = (DOCKER / "entrypoint.sh" ).read_text (encoding = "utf-8" ) 198self .assertLess (entry .index ('legacy_models_guard "$model_path"' ),entry .index ('--model "$MODEL"' )) 199 200 201class Document (unittest .TestCase ): 202def test_every_documented_setting_is_read_by_the_entry_point (self ): 203doc = (ROOT / "docs" / "DOCKER.md" ).read_text (encoding = "utf-8" ) 204section = doc .split ("## Settings" ,1 )[1 ].split ("###" ,1 )[0 ] 205entry = (DOCKER / "entrypoint.sh" ).read_text (encoding = "utf-8" ) 206names :set [str ]= set () 207for line in section .splitlines (): 208if line .startswith ("| `" ): 209names .update (re .findall (r"`([A-Z][A-Z_]+)`" ,line .split ("|" )[1 ])) 210self .assertTrue ({"MODEL" ,"CONTEXT" ,"API_KEY" ,"TUNE" ,"VISION" ,"MODEL_PATH" ,"STRATA_SET" }<= names ,names ) 211for name in sorted (names ): 212self .assertIn (name ,entry ,f"docs/DOCKER.md lists { name } but docker/entrypoint.sh does not read it" ) 213 214def test_tags_in_the_document_match_the_compose_defaults (self ): 215doc = (ROOT / "docs" / "DOCKER.md" ).read_text (encoding = "utf-8" ) 216for 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" ): 217self .assertIn (tag ,doc ) 218for 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" )): 220self .assertIn (tag , (DOCKER / "compose" / name ).read_text (encoding = "utf-8" )) 221 222def test_the_user_doc_says_images_are_published_from_0_2_1 (self ): 223doc = (ROOT / "docs" / "DOCKER.md" ).read_text (encoding = "utf-8" ) 224self .assertNotIn ("TODO(owner)" ,doc ) 225self .assertNotIn ("not available yet" ,doc ) 226self .assertIn ("published from version 0.2.1 on" ,doc ) 227self .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).""" 232WORKFLOW = ROOT / ".github" / "workflows" / "docker-images.yml" 233 234@ unittest . skipIf ( SH is None , "needs sh" ) 235def test_publish_script_parses_and_defaults_to_not_pushing (self ): 236path = DOCKER / "publish.sh" 237self .assertEqual (subprocess .run ([SH ,"-n" ,sh_path (path )],capture_output = True ,text = True ).returncode ,0 ) 238text = path .read_text (encoding = "utf-8" ) 239self .assertNotIn ("\r" ,text ) 240self .assertIn ('push=""' ,text )# no --push, no docker push 241pushes = re .findall (r'^[^#\n]*docker push "' ,text ,re .M ) 242self .assertEqual (len (pushes ),2 ,pushes )# the version tag and latest-<flavor>, both inside `if [ -n "$push" ]` 243 244def test_every_flavor_of_the_document_is_one_the_fetch_script_knows (self ): 245src = (DOCKER / "fetch-engines.py" ).read_text (encoding = "utf-8" ) 246flavors = re .findall (r'^ "([a-z0-9-]+)": \("' ,src ,re .M ) 247doc = (ROOT / "docs" / "DOCKER.md" ).read_text (encoding = "utf-8" ) 248self .assertTrue ({"cuda13" ,"cuda12" ,"rocm-gfx120x" ,"rocm-gfx110x" ,"rocm-gfx1151" ,"sycl" }<= set (flavors ),flavors ) 249for flavor in flavors : 250self .assertIn (f"0.2.7- { flavor } " ,doc ) 251 252def 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).""" 254build = (DOCKER / "build.sh" ).read_text (encoding = "utf-8" ) 255listed = re .search (r'^paths="([^"]+)"' ,build ,re .M ).group (1 ).split () 256pt = ast .parse ((ROOT / "packaging" / "package_terminal.py" ).read_text (encoding = "utf-8" )) 257payload = None 258for node in pt .body : 259if isinstance (node ,ast .Assign )and any (getattr (t ,"id" ,"" )== "PAYLOAD" for t in node .targets ): 260payload = ast .literal_eval (node .value ) 261self .assertTrue (payload ) 262for item in payload : 263self .assertTrue (any (item == p or item .startswith (p .rstrip ("/" )+ "/" )for p in listed ),f"build.sh does not copy { item } " ) 264 265def 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 267docker/Dockerfile does; without it package_terminal.py stops (#3644). The documented source-build commands pass it.""" 268for dockerfile in (ROOT / "Dockerfile" ,DOCKER / "Dockerfile" ): 269text = dockerfile .read_text (encoding = "utf-8" ) 270self .assertRegex (text ,r"(?m)^ARG STRATA_COMMIT=" ,dockerfile .name ) 271self .assertIn ("ENV STRATA_BUILD_COMMIT=${STRATA_COMMIT}" ,text ,dockerfile .name ) 272self .assertIn (".git" , (ROOT / ".dockerignore" ).read_text (encoding = "utf-8" ).split ()) 273doc = (ROOT / "docs" / "DOCKER.md" ).read_text (encoding = "utf-8" ) 274self .assertEqual (doc .count ("docker build -t strata:src" ),doc .count ("--build-arg STRATA_COMMIT=$(git rev-parse HEAD)" )) 275self .assertIn ("/data/install/" , (ROOT / ".dockerignore" ).read_text (encoding = "utf-8" )) 276 277def test_workflow_is_manual_and_pushes_only_on_request (self ): 278data = yaml .safe_load (self .WORKFLOW .read_text (encoding = "utf-8" )) 279triggers = data .get ("on" ,data .get (True ))# YAML 1.1 reads a bare `on` as True 280self .assertEqual (set (triggers ), {"workflow_dispatch" }) 281inputs = triggers ["workflow_dispatch" ]["inputs" ] 282self .assertIn ("release_tag" ,inputs ) 283self .assertFalse (inputs ["push" ]["default" ]) 284self .assertEqual (data ["permissions" ], {"contents" :"read" }) 285self .assertEqual (data ["jobs" ]["image" ]["permissions" ], {"contents" :"read" ,"packages" :"write" }) 286text = self .WORKFLOW .read_text (encoding = "utf-8" ) 287self .assertIn ("ghcr.io/niko1221/strata" ,text ) 288self .assertIn ("docker/publish.sh" ,text ) 289self .assertNotIn ("${{ secrets.GITHUB_TOKEN }}\" |" ,text )# the token goes through an env variable, not into the command line 290 291 292if __name__ == "__main__" : 293unittest .main ()