Run frontier MoE models on hardware you already own — pure C, zero deps, experts streamed from disk. Tiny engine, immense model. 🐦
C
setup: tests model their OS explicitly; Windows decoding and path fixes
JustVugg43df5d412735
diff --git a/c/setup_download.py b/c/setup_download.pyindex 118c4db9..658d37ac 100644--- a/c/setup_download.py+++ b/c/setup_download.py@@ -272,7 +272,7 @@ def windows_curl():def wsl_windows_path(path):try:out = subprocess.run(["wslpath", "-w", os.path.abspath(path)], capture_output=True,- text=True, timeout=10).stdout.strip()+ text=True, errors="replace", timeout=10).stdout.strip()return out or Noneexcept (OSError, subprocess.SubprocessError):return None@@ -311,7 +311,8 @@ def probe_throughput_windows(url, curl, *, token=None, max_bytes=4 << 20, max_seif token:cmd[1:1] = ["-H", f"Authorization: Bearer {token}"]try:- out = subprocess.run(cmd, capture_output=True, text=True, timeout=max_seconds + 20).stdout+ out = subprocess.run(cmd, capture_output=True, text=True, errors="replace",+ timeout=max_seconds + 20).stdoutexcept (OSError, subprocess.SubprocessError):return Nonespeed = parse_curl_speed(out)diff --git a/c/setup_flow.py b/c/setup_flow.pyindex 376b4e66..82c8ba82 100644--- a/c/setup_flow.py+++ b/c/setup_flow.py@@ -50,13 +50,28 @@ import setup_hw # noqa: E402from family_registry import family_by_id # noqa: E402GB = 1_000_000_000-EXE = ".exe" if sys.platform == "win32" else ""CONFIG_VERSION = 1DEFAULT_PORT = 8000DEFAULT_HOST = "127.0.0.1"RELEASES_API = "https://api.github.com/repos/JustVugg/colibri/releases"+def host_os():+ """The OS whose conventions decide what to build, fetch and call things:+ engine file names, the release asset, the package commands, the make+ invocation. One function, so a test can model Windows on Linux and the+ reverse; everything that calls an OS API checks sys.platform itself."""+ return sys.platform+++def host_machine():+ return setup_hw.platform.machine().lower()+++def exe_suffix():+ return ".exe" if host_os() == "win32" else ""++class SetupError(RuntimeError):"""A stop with a reason the user can act on (printed without a traceback)."""@@ -241,7 +256,7 @@ TEXT_HINTS = {def package_hint(kinds, os_info=None, platform_name=None):"""One line the user can run to get `kinds` (build, vulkan, cuda, python)."""kinds = [kinds] if isinstance(kinds, str) else list(kinds)- platform_name = platform_name or sys.platform+ platform_name = platform_name or host_os()if platform_name == "darwin":return " ; ".join(TEXT_HINTS.get(f"{k}-darwin", TEXT_HINTS.get(k, k)) for k in kinds)if platform_name == "win32":@@ -281,7 +296,7 @@ def choose_backend(hw, family, tc, requested="auto"):if requested == "cpu":decision["reason"] = "CPU only, as requested"return decision- cuda_engine = family.supports_accelerator and sys.platform.startswith("linux")+ cuda_engine = family.supports_accelerator and host_os().startswith("linux")if nvidia and requested in ("auto", "cuda"):if cuda_engine and tc.get("can_build_cuda"):decision.update(backend="cuda", gpu=nvidia[0]["name"],@@ -341,7 +356,7 @@ def binary_backend(path):def engine_path(directory, family):- return os.path.join(directory, family.engine_artifact + EXE)+ return os.path.join(directory, family.engine_artifact + exe_suffix())# ---------------------------------------------------------------- building@@ -355,7 +370,7 @@ def make_command(family, backend, tc):args.append("VK=1")elif backend == "cuda":args += ["CUDA=1", f"CUDA_ARCH={os.environ.get('CUDA_ARCH') or 'native'}"]- if sys.platform == "win32" and tc.get("msys2"):+ if host_os() == "win32" and tc.get("msys2"):bash = os.path.join(tc["msys2"], "usr", "bin", "bash.exe")script = 'cd "$(cygpath -u "$1")" && shift && exec make "$@"'env = dict(os.environ, MSYSTEM="UCRT64", CHERE_INVOKING="1", MSYS2_PATH_TYPE="inherit")@@ -370,7 +385,7 @@ def build_engine(family, backend, tc, out=print):write_state("build", engine=family.engine_artifact, backend=backend)with open(_ensure_log("build"), "w", encoding="utf-8", errors="replace") as log:process = subprocess.Popen(cmd, cwd=cwd, env=env, stdout=subprocess.PIPE,- stderr=subprocess.STDOUT, text=True, errors="replace")+ stderr=subprocess.STDOUT, encoding="utf-8", errors="replace")tail = []for line in process.stdout:log.write(line)@@ -393,8 +408,8 @@ def _ensure_log(name):def release_asset_suffix(os_name=None, machine=None):- os_name = os_name or sys.platform- machine = (machine or setup_hw.platform.machine()).lower()+ os_name = os_name or host_os()+ machine = (machine or host_machine()).lower()if os_name.startswith("linux") and machine in ("x86_64", "amd64"):return "linux-x86_64.tar.gz"if os_name == "darwin" and machine in ("arm64", "aarch64"):@@ -465,7 +480,7 @@ def extract_archive(archive, dest, only_prefix=None):if not only_prefix:for name in os.listdir(dest):path = os.path.join(dest, name)- if os.path.isfile(path) and sys.platform != "win32" and "." not in name:+ if os.path.isfile(path) and os.name == "posix" and "." not in name:os.chmod(path, 0o755)@@ -586,7 +601,7 @@ def resolve_engine(family, entry, decision, tc, out=print, allow_prebuilt=True):version = current_version()if release_asset_suffix() is None:raise SetupError(f"no compiler here, and no prebuilt engine is published for "- f"{sys.platform}/{setup_hw.platform.machine()}: {package_hint(['build'])}")+ f"{host_os()}/{host_machine()}: {package_hint(['build'])}")out(" no compiler found: using the prebuilt engine from the GitHub release")runtime, tag = fetch_release_archive(version, out=out)if entry is not None and setup_catalog.version_tuple(tag) < setup_catalog.version_tuple(entry.prebuilt_since):@@ -680,7 +695,7 @@ def launcher_in(directory):def equivalent_command(cfg):env = " ".join(f"{k}={_quote(v)}" for k, v in cfg.get("env", {}).items())cmd = " ".join(_quote(a) for a in ["coli"] + cfg.get("args", []))- if sys.platform == "win32":+ if host_os() == "win32":sets = "".join(f'set "{k}={v}" && ' for k, v in cfg.get("env", {}).items())return f"{sets}{cmd}"return f"{env} {cmd}".strip()@@ -706,7 +721,12 @@ def _pid_alive(pid):import ctypesfrom ctypes import wintypesk32 = ctypes.WinDLL("kernel32", use_last_error=True)+ k32.OpenProcess.argtypes = [wintypes.DWORD, wintypes.BOOL, wintypes.DWORD]k32.OpenProcess.restype = wintypes.HANDLE+ k32.GetExitCodeProcess.argtypes = [wintypes.HANDLE, ctypes.POINTER(wintypes.DWORD)]+ k32.GetExitCodeProcess.restype = wintypes.BOOL+ k32.CloseHandle.argtypes = [wintypes.HANDLE]+ k32.CloseHandle.restype = wintypes.BOOLhandle = k32.OpenProcess(0x1000, False, pid)if not handle:return False@@ -898,8 +918,10 @@ def stop_server(cfg, out=print):coli = COLI_SCRIPTif not os.path.isfile(coli):coli = cfg["launcher"]+ # coli prints UTF-8 (it reconfigures stdout on Windows); the locale codec+ # (cp1252 there) would raise on its box-drawing characters.result = subprocess.run([sys.executable, coli, "stop", "--port", str(cfg["port"])],- capture_output=True, text=True, timeout=120,+ capture_output=True, encoding="utf-8", errors="replace", timeout=120,env=dict(os.environ, COLI_COLOR="0"))text = (result.stdout + result.stderr).strip()lines = [re.sub(r"\x1b\[[0-9;]*m", "", line).strip() for line in text.splitlines()]@@ -1152,7 +1174,8 @@ def run_post_install(entry, launcher_dir, model_dir, ui):continuescript = os.path.join(launcher_dir, "tools", f"{tool}.py")ui.say(f" writing {creates} (tools/{tool}.py)")- result = subprocess.run([sys.executable, script, model_dir], capture_output=True, text=True)+ result = subprocess.run([sys.executable, script, model_dir], capture_output=True,+ encoding="utf-8", errors="replace")if result.returncode != 0 or not os.path.exists(os.path.join(model_dir, creates)):raise SetupError(f"tools/{tool}.py failed: {(result.stderr or result.stdout).strip()[-400:]}")@@ -1332,7 +1355,7 @@ def _recommend_for(hw, explicit_dir):if manifest:downloaded[entry.id] = setup_download.bytes_present(os.path.join(root, entry.id),manifest.get("files", []))- return setup_catalog.recommend(hw["memory"].get("total"), free, os_name=sys.platform,+ return setup_catalog.recommend(hw["memory"].get("total"), free, os_name=host_os(),machine=hw["os"].get("machine"), downloaded=downloaded)diff --git a/c/setup_hw.py b/c/setup_hw.pyindex 394a1957..2d4fcf79 100644--- a/c/setup_hw.py+++ b/c/setup_hw.py@@ -24,6 +24,7 @@ import globimport jsonimport osimport platform+import posixpathimport reimport shutilimport struct@@ -33,6 +34,12 @@ import sysHERE = os.path.dirname(os.path.realpath(__file__))GB = 1_000_000_000++def host_os():+ """The OS whose conventions decide which probes apply (WSL driver search,+ no Vulkan on macOS). Patchable, so tests model any OS on any host."""+ return sys.platform+# ---------------------------------------------------------------- memory@@ -267,10 +274,19 @@ def disk_free(path):def path_warnings(path, wsl):- """Advice about where a model lives; the engine streams it, so it matters."""+ """Advice about where a model lives; the engine streams it, so it matters.++ The WSL check is about a Linux path, so it is normalized with POSIX rules+ whatever Python runs it: os.path on Windows would turn /mnt/c/x into+ C:\\mnt\\c\\x and the check would silently pass everything."""warnings = []- absolute = os.path.abspath(os.path.expanduser(path))- if wsl and re.match(r"^/mnt/[a-zA-Z](/|$)", absolute):+ if not wsl:+ return warnings+ expanded = os.path.expanduser(path)+ if not expanded.startswith("/"):+ expanded = posixpath.join(os.getcwd(), expanded)+ absolute = posixpath.normpath(expanded)+ if re.match(r"^/mnt/[a-zA-Z](/|$)", absolute):warnings.append(f"{absolute} is a Windows drive seen from WSL: reading it is many times ""slower than the Linux disk, and the engine streams the model from it. "@@ -617,7 +633,7 @@ def detect_vulkan(wsl=None, home=None):usable GPU there, each user manifest is tried in turn and the first one thatyields a usable device is reported with its path, so the run configurationcan point the engine at the same driver."""- if sys.platform == "darwin":+ if host_os() == "darwin":return {"devices": [], "icd": None, "source": None}wsl = is_wsl() if wsl is None else wslprobe = _probe_vulkan_child()@@ -627,7 +643,7 @@ def detect_vulkan(wsl=None, home=None):summary = _run(["vulkaninfo", "--summary"], timeout=20) if shutil.which("vulkaninfo") else ""result = {"devices": parse_vulkaninfo_summary(summary), "icd": None,"source": "vulkaninfo" if summary else None}- if not any(vulkan_usable(d) for d in result["devices"]) and sys.platform.startswith("linux") \+ if not any(vulkan_usable(d) for d in result["devices"]) and host_os().startswith("linux") \and not os.environ.get("VK_ICD_FILENAMES") and not os.environ.get("VK_DRIVER_FILES"):for manifest in find_user_icds(home):extra = _probe_vulkan_child({"VK_ICD_FILENAMES": manifest, "VK_DRIVER_FILES": manifest})@@ -672,7 +688,10 @@ def detect_windows_video():def _run(cmd, timeout=10):try:- return subprocess.run(cmd, capture_output=True, text=True, timeout=timeout).stdout+ # errors="replace": a GPU name in the console code page must not turn+ # into a UnicodeDecodeError that throws the whole probe away.+ return subprocess.run(cmd, capture_output=True, text=True, errors="replace",+ timeout=timeout).stdoutexcept (OSError, subprocess.SubprocessError, ValueError):return ""diff --git a/c/tests/test_setup_download.py b/c/tests/test_setup_download.pyindex 171ce156..37b45e82 100644--- a/c/tests/test_setup_download.py+++ b/c/tests/test_setup_download.py@@ -205,25 +205,36 @@ class DownloadTest(unittest.TestCase):path.write_bytes(b"\1" * len(self.files[name]))self.assertFalse(setup_download.verify_file(str(path), self.spec(name)))- @unittest.skipUnless(os.name == "posix", "the stand-in curl.exe is a script")- def test_windows_curl_transport(self):- """WSL's slow-network path: Windows' curl.exe writes the .part file, then- the same size and hash checks decide whether it becomes the file."""- fake_curl = Path(self.tmp.name, "curl.exe")- fake_curl.write_text(- "#!" + sys.executable + "\n"+ def stand_in_curl(self):+ """A curl.exe that does what the transport asks of it: fetch the last+ argument into the file after -o. A script with a shebang on POSIX, a+ .cmd around the same script on Windows."""+ script = Path(self.tmp.name, "curl_stand_in.py")+ script.write_text("import sys, urllib.request\n""args = sys.argv[1:]\n""out = args[args.index('-o') + 1]\n""data = urllib.request.urlopen(args[-1]).read()\n""open(out, 'wb').write(data)\n")- fake_curl.chmod(0o755)+ if os.name == "nt":+ wrapper = Path(self.tmp.name, "curl.cmd")+ wrapper.write_text(f'@"{sys.executable}" "{script}" %*\r\n')+ return str(wrapper)+ wrapper = Path(self.tmp.name, "curl.exe")+ wrapper.write_text("#!" + sys.executable + "\n" + script.read_text())+ wrapper.chmod(0o755)+ return str(wrapper)++ def test_windows_curl_transport(self):+ """WSL's slow-network path: Windows' curl.exe writes the .part file, then+ the same size and hash checks decide whether it becomes the file."""+ fake_curl = self.stand_in_curl()name = "model-00000.safetensors"dest = os.path.join(self.dst, name)seen = []with mock.patch.object(setup_download, "wsl_windows_path", side_effect=lambda p: p):result = setup_download.download_file_windows(- self.url(name), dest, self.spec(name), str(fake_curl),+ self.url(name), dest, self.spec(name), fake_curl,progress=lambda done, total: seen.append((done, total)))self.assertEqual(result, "downloaded")self.assertEqual(Path(dest).read_bytes(), self.files[name])@@ -234,7 +245,7 @@ class DownloadTest(unittest.TestCase):with mock.patch.object(setup_download, "wsl_windows_path", side_effect=lambda p: p), \self.assertRaises(setup_download.DownloadError):setup_download.download_file_windows(self.url(other), os.path.join(self.dst, other),- bad, str(fake_curl))+ bad, fake_curl)self.assertFalse(os.path.exists(os.path.join(self.dst, other)))def test_token_from_file(self):diff --git a/c/tests/test_setup_flow.py b/c/tests/test_setup_flow.pyindex 1235fe15..be4b82b3 100644--- a/c/tests/test_setup_flow.py+++ b/c/tests/test_setup_flow.py@@ -5,6 +5,11 @@ No network, no real model, no real build: the hub is tests/fake_hub.py, thehardware report is canned, the engine is a file that names the Vulkan loader,and the server is a twenty-line stand-in that answers /health like `coli web`does and writes the same pidfile, so the real `coli stop` can stop it.++Every test that depends on an OS models it with modeled(): it patches the+setup's host_os()/host_machine(), never sys.platform, so a Linux test runs the+same on Windows and a Windows test the same on Linux (engine names, release+assets, package commands, the make invocation)."""import argparseimport contextlib@@ -40,6 +45,21 @@ from family_registry import family_by_id # noqa: E402REPO = "tester/tiny-model"+def modeled(os_name, machine="x86_64"):+ """Run the setup as if on `os_name` ("linux", "win32", "darwin"). The+ patches apply from the call; the returned stack undoes them on close or+ at the end of a `with`."""+ stack = contextlib.ExitStack()+ stack.enter_context(mock.patch.object(setup_flow, "host_os", return_value=os_name))+ stack.enter_context(mock.patch.object(setup_flow, "host_machine", return_value=machine))+ stack.enter_context(mock.patch.object(setup_hw, "host_os", return_value=os_name))+ return stack+++def engine_name(os_name):+ return "qwen36.exe" if os_name == "win32" else "qwen36"++def free_port():with socket.socket() as sock:sock.bind(("127.0.0.1", 0))@@ -93,7 +113,7 @@ class HomeTestCase(unittest.TestCase):class BackendChoice(unittest.TestCase):def choose(self, hw, family="qwen36", tc=None, requested="auto", platform="linux"):- with mock.patch.object(setup_flow.sys, "platform", platform):+ with modeled(platform):return setup_flow.choose_backend(hw, family_by_id(family), tc or TC_ALL, requested)def test_no_gpu_is_cpu(self):@@ -108,6 +128,9 @@ class BackendChoice(unittest.TestCase):def test_nvidia_with_toolkit_takes_cuda(self):self.assertEqual(self.choose(hw_report(vulkan=IGPU, nvidia=[RTX]))["backend"], "cuda")+ # The Windows CUDA build is a separate MSVC build: Vulkan there.+ self.assertEqual(self.choose(hw_report(vulkan=IGPU, nvidia=[RTX]), platform="win32")["backend"],+ "vulkan")def test_nvidia_without_toolkit_falls_to_vulkan_and_says_how(self):tc = dict(TC_ALL, nvcc=None, can_build_cuda=False)@@ -196,8 +219,11 @@ class RunConfiguration(HomeTestCase):self.assertEqual(loaded["urls"], {"browser": "http://127.0.0.1:8123/","openai_base_url": "http://127.0.0.1:8123/v1","anthropic_base_url": "http://127.0.0.1:8123"})- self.assertIn("COLI_VULKAN=1", setup_flow.equivalent_command(loaded))- self.assertIn("--port 8123", setup_flow.equivalent_command(loaded))+ with modeled("linux"):+ self.assertTrue(setup_flow.equivalent_command(loaded).startswith("COLI_VULKAN=1 "))+ self.assertIn("--port 8123", setup_flow.equivalent_command(loaded))+ with modeled("win32"):+ self.assertTrue(setup_flow.equivalent_command(loaded).startswith('set "COLI_VULKAN=1" && '))self.assertEqual(setup_flow.configured_port(), 8123)# an unknown layout is not trustedPath(setup_flow.config_path()).write_text(json.dumps({"version": 99}))@@ -219,28 +245,52 @@ class EngineResolution(HomeTestCase):self.assertEqual(setup_flow.binary_backend(str(path)), expected)def test_present_engine_with_the_right_backend_is_not_rebuilt(self):- Path(self.tmp.name, "qwen36").write_bytes(b"libvulkan.so.1")- decision = {"backend": "vulkan", "missing": []}- with mock.patch.object(setup_flow, "HERE", self.tmp.name), \- mock.patch.object(setup_flow, "build_engine") as build:- info = setup_flow.resolve_engine(family_by_id("qwen36"), None, decision, TC_ALL,- out=lambda *_: None)- build.assert_not_called()- self.assertEqual(info["source"], "present")+ for os_name, loader in (("linux", b"libvulkan.so.1"), ("win32", b"vulkan-1.dll")):+ with self.subTest(os=os_name), modeled(os_name), \+ tempfile.TemporaryDirectory() as engines:+ Path(engines, engine_name(os_name)).write_bytes(loader)+ decision = {"backend": "vulkan", "missing": []}+ with mock.patch.object(setup_flow, "HERE", engines), \+ mock.patch.object(setup_flow, "build_engine") as build:+ info = setup_flow.resolve_engine(family_by_id("qwen36"), None, decision, TC_ALL,+ out=lambda *_: None)+ build.assert_not_called()+ self.assertEqual(info["source"], "present")+ self.assertEqual(os.path.basename(info["engine"]), engine_name(os_name))++ def test_an_engine_without_the_exe_suffix_is_not_the_windows_engine(self):+ Path(self.tmp.name, "qwen36").write_bytes(b"vulkan-1.dll")+ with modeled("win32"), mock.patch.object(setup_flow, "HERE", self.tmp.name), \+ mock.patch.object(setup_flow, "build_engine", return_value="x") as build:+ setup_flow.resolve_engine(family_by_id("qwen36"), None,+ {"backend": "vulkan", "missing": []}, TC_ALL, out=lambda *_: None)+ build.assert_called_once()def test_a_cpu_engine_is_rebuilt_for_vulkan(self):- Path(self.tmp.name, "qwen36").write_bytes(b"plain")- decision = {"backend": "vulkan", "missing": []}- with mock.patch.object(setup_flow, "HERE", self.tmp.name), \- mock.patch.object(setup_flow, "build_engine", return_value="/built/qwen36") as build:- info = setup_flow.resolve_engine(family_by_id("qwen36"), None, decision, TC_ALL,- out=lambda *_: None)- build.assert_called_once()- self.assertEqual(info["source"], "built")+ for os_name in ("linux", "win32"):+ with self.subTest(os=os_name), modeled(os_name), \+ tempfile.TemporaryDirectory() as engines:+ Path(engines, engine_name(os_name)).write_bytes(b"plain")+ decision = {"backend": "vulkan", "missing": []}+ with mock.patch.object(setup_flow, "HERE", engines), \+ mock.patch.object(setup_flow, "build_engine", return_value="/built/qwen36") as build:+ info = setup_flow.resolve_engine(family_by_id("qwen36"), None, decision, TC_ALL,+ out=lambda *_: None)+ build.assert_called_once()+ self.assertEqual(info["source"], "built")++ def test_make_command_through_msys2_on_windows(self):+ tc = dict(TC_ALL, msys2=r"C:\msys64")+ with modeled("win32"), mock.patch.dict(os.environ, {"ARCH": ""}):+ cmd, _cwd, env = setup_flow.make_command(family_by_id("qwen36"), "vulkan", tc)+ self.assertTrue(cmd[0].endswith("bash.exe"))+ self.assertEqual(cmd[1], "-lc")+ self.assertIn("cygpath", cmd[2])+ self.assertEqual(cmd[-3:], ["qwen36", "ARCH=native", "VK=1"])+ self.assertEqual(env["MSYSTEM"], "UCRT64")def test_make_command(self):- with mock.patch.object(setup_flow.sys, "platform", "linux"), \- mock.patch.dict(os.environ, {"ARCH": ""}):+ with modeled("linux"), mock.patch.dict(os.environ, {"ARCH": ""}):cmd, _cwd, _env = setup_flow.make_command(family_by_id("deepseek_v4"), "vulkan", TC_ALL)self.assertEqual(cmd[-3:], ["deepseek-v4", "ARCH=native", "VK=1"])cmd, _cwd, _env = setup_flow.make_command(family_by_id("qwen36"), "cuda", TC_ALL)@@ -290,9 +340,9 @@ class Releases(HomeTestCase):setup_flow.extract_archive(evil_tar, os.path.join(self.tmp.name, "out2"))self.assertFalse(Path(self.tmp.name, "escape.txt").exists())- def serve_release(self, files):+ def serve_release(self, files, folder="release"):"""A local release: the archive and SHA256SUMS.txt over HTTP."""- folder = os.path.join(self.tmp.name, "release")+ folder = os.path.join(self.tmp.name, folder)os.makedirs(folder)for name, data in files.items():Path(folder, name).write_bytes(data)@@ -308,29 +358,46 @@ class Releases(HomeTestCase):base = f"http://127.0.0.1:{server.server_address[1]}"return {name: f"{base}/{name}" for name in files}- def make_archive(self, tag):+ #: What the release workflow packs, per OS (.github/workflows/release.yml).+ LAYOUTS = {"linux": ("linux-x86_64.tar.gz", ("coli", "qwen36")),+ "win32": ("windows-x86_64.zip", ("coli", "coli.cmd", "qwen36.exe"))}++ def make_archive(self, os_name):+ suffix, binaries = self.LAYOUTS[os_name]+ members = [(name, b"engine" if name.startswith("qwen36") else b"# launcher") for name in binaries]+ members += [("web/dist/index.html", b"<html></html>"), ("tools/k3_tokenizer.py", b"")]buffer = io.BytesIO()- with tarfile.open(fileobj=buffer, mode="w:gz") as tf:- for name, data in (("coli", b"# launcher"), ("qwen36", b"engine"),- ("web/dist/index.html", b"<html></html>"), ("tools/k3_tokenizer.py", b"")):- info = tarfile.TarInfo(name)- info.size = len(data)- tf.addfile(info, io.BytesIO(data))+ if suffix.endswith(".zip"):+ with zipfile.ZipFile(buffer, "w") as zf:+ for name, data in members:+ zf.writestr(name, data)+ else:+ with tarfile.open(fileobj=buffer, mode="w:gz") as tf:+ for name, data in members:+ info = tarfile.TarInfo(name)+ info.size = len(data)+ tf.addfile(info, io.BytesIO(data))return buffer.getvalue()def test_prebuilt_engine_when_there_is_no_compiler(self):+ for os_name in ("linux", "win32"):+ with self.subTest(os=os_name):+ self.check_prebuilt(os_name)++ def check_prebuilt(self, os_name):tag = "v1.12.1"- name = f"colibri-{tag}-linux-x86_64.tar.gz"- archive = self.make_archive(tag)+ name = f"colibri-{tag}-{self.LAYOUTS[os_name][0]}"+ archive = self.make_archive(os_name)sums = f"{hashlib.sha256(archive).hexdigest()} {name}\n".encode()- urls = self.serve_release({name: archive, "SHA256SUMS.txt": sums})+ urls = self.serve_release({name: archive, "SHA256SUMS.txt": sums}, folder=os_name)getter = lambda url: {"tag_name": tag, "assets": [{"name": n, "browser_download_url": u}for n, u in urls.items()]}tc = dict(TC_ALL, source_checkout=False, can_build=False, can_build_vulkan=False)- empty = os.path.join(self.tmp.name, "nothing-here")+ empty = os.path.join(self.tmp.name, f"nothing-here-{os_name}")os.makedirs(empty)- with mock.patch.object(setup_flow, "HERE", empty), \- mock.patch.object(setup_flow, "release_asset_suffix", return_value="linux-x86_64.tar.gz"), \+ home = os.path.join(self.tmp.name, f"home-{os_name}")+ with modeled(os_name), mock.patch.object(setup_flow, "HERE", empty), \+ mock.patch.dict(os.environ, {"COLI_SETUP_HOME": home}), \mock.patch.object(setup_flow, "_api_get", side_effect=getter):out = []info = setup_flow.resolve_engine(family_by_id("qwen36"), setup_catalog.by_id("qwen36-35b"),@@ -338,6 +405,8 @@ class Releases(HomeTestCase):self.assertEqual(info["backend"], "cpu") # prebuilt engines are CPU buildsself.assertTrue(info["source"].startswith("release v1.12.1"))self.assertTrue(os.path.isfile(info["engine"]))+ self.assertEqual(os.path.basename(info["engine"]), engine_name(os_name))+ self.assertTrue(os.path.isfile(setup_flow.launcher_in(info["launcher_dir"])))self.assertTrue(os.path.isfile(os.path.join(info["launcher_dir"], "web", "dist", "index.html")))# A model newer than the release is refused with the way forward.with self.assertRaises(setup_flow.SetupError) as caught:@@ -348,11 +417,11 @@ class Releases(HomeTestCase):def test_bad_checksum_is_refused(self):tag = "v1.12.1"name = f"colibri-{tag}-linux-x86_64.tar.gz"- urls = self.serve_release({name: self.make_archive(tag),+ urls = self.serve_release({name: self.make_archive("linux"),"SHA256SUMS.txt": f"{'0' * 64} {name}\n".encode()})getter = lambda url: {"tag_name": tag, "assets": [{"name": n, "browser_download_url": u}for n, u in urls.items()]}- with mock.patch.object(setup_flow, "release_asset_suffix", return_value="linux-x86_64.tar.gz"):+ with modeled("linux"):with self.assertRaises(setup_flow.SetupError) as caught:setup_flow.fetch_release_archive("1.12.1", out=lambda *_: None, getter=getter)self.assertIn("checksum", str(caught.exception))@@ -384,6 +453,7 @@ class WholeSetup(HomeTestCase):Path(self.engines, "qwen36").write_bytes(b"\x7fELF libvulkan.so.1")Path(self.engines, "coli").write_text("# launcher\n")self.models = os.path.join(self.tmp.name, "models")+ self.addCleanup(modeled("linux").close) # patches from here onfor patcher in (mock.patch.dict(os.environ, {"HF_ENDPOINT": self.hub.base,"COLI_SETUP_CATALOG": catalog}),@@ -452,6 +522,24 @@ class WholeSetup(HomeTestCase):self.assertEqual(Path(self.models, "tiny", "model-00000.safetensors").read_bytes(), self.shard)self.assertEqual(setup_flow.load_config()["status"], "ready")+ def test_install_on_windows_names_the_exe_engine(self):+ os.remove(os.path.join(self.engines, "qwen36"))+ Path(self.engines, "qwen36.exe").write_bytes(b"MZ vulkan-1.dll")+ windows = hw_report(vulkan=IGPU)+ windows["os"] = {"platform": "win32", "machine": "amd64", "wsl": False,+ "pretty_name": "Windows 11"}+ with modeled("win32", machine="amd64"), \+ mock.patch.object(setup_hw, "detect", return_value=windows):+ code, text = self.run_setup(pick="tiny")+ self.assertEqual(code, 0, text)+ cfg = setup_flow.load_config()+ self.assertEqual(os.path.basename(cfg["engine"]), "qwen36.exe")+ self.assertEqual(cfg["backend"], "vulkan")+ self.assertNotIn("VK_ICD_FILENAMES", cfg["env"]) # the loader finds Windows drivers itself+ self.assertIn('same as: set "COLI_VULKAN=1" && set "COLI_VK_SHADERS=', text)+ self.assertIn(" && coli web --model ", text)+ self.assertIn("System Windows 11", text)+def test_a_missing_engine_is_rebuilt_without_asking_again(self):code, text = self.run_setup(pick="tiny")self.assertEqual(code, 0, text)@@ -554,7 +642,7 @@ class WholeSetup(HomeTestCase):def test_no_compiler_and_no_prebuilt_says_what_to_install(self):tc = dict(TC_ALL, source_checkout=False, can_build=False, can_build_vulkan=False)os.remove(os.path.join(self.engines, "qwen36"))- with mock.patch.object(setup_flow, "release_asset_suffix", return_value=None):+ with modeled("linux", machine="riscv64"): # no release archive for itwith self.assertRaises(setup_flow.SetupError) as caught:setup_flow.resolve_engine(family_by_id("qwen36"), None,{"backend": "cpu", "missing": []}, tc, out=lambda *_: None)@@ -599,8 +687,10 @@ http.server.HTTPServer(("127.0.0.1", port), H).serve_forever()'''[email protected](os.name == "posix", "the stand-in server is stopped with SIGTERM")class ServerControl(HomeTestCase):+ """Runs on Windows too: `coli stop` ends the stand-in with TerminateProcess+ there (its SIGTERM handler simply never runs) and removes the pidfile itself."""+def setUp(self):super().setUp()self.launcher = os.path.join(self.tmp.name, "fake_coli.py")@@ -622,9 +712,13 @@ class ServerControl(HomeTestCase):pidfile = setup_flow.serve_pidfile(self.port)try:pid = int(Path(pidfile).read_text().split()[0])- os.kill(pid, 15)+ os.kill(pid, 15) # TerminateProcess on Windows: the handler never runsexcept (OSError, ValueError):pass+ try:+ os.unlink(pidfile) # so no stale pidfile outlives the test there+ except OSError:+ passdef wait_state(self, cfg, state, timeout=60):# A deadline, not a delay: a quick machine returns at once. A loaded CIdiff --git a/c/tests/test_setup_hw.py b/c/tests/test_setup_hw.pyindex f6340d2d..3aef649b 100644--- a/c/tests/test_setup_hw.py+++ b/c/tests/test_setup_hw.py@@ -168,10 +168,21 @@ class SystemParsing(unittest.TestCase):self.assertEqual(info["PRETTY_NAME"], "Ubuntu 24.04 LTS")def test_windows_drive_from_wsl_is_flagged(self):+ # POSIX rules whatever the host: on Windows os.path would read+ # /mnt/c/... as C:\\mnt\\c\\... and flag nothing.self.assertTrue(setup_hw.path_warnings("/mnt/c/Users/me/models", wsl=True))+ self.assertTrue(setup_hw.path_warnings("/mnt/d", wsl=True))+ self.assertTrue(setup_hw.path_warnings("/home/me/../../mnt/e/x", wsl=True))self.assertFalse(setup_hw.path_warnings("/home/me/colibri-models", wsl=True))+ self.assertFalse(setup_hw.path_warnings("/mnt/wslg/x", wsl=True))self.assertFalse(setup_hw.path_warnings("/mnt/c/Users/me/models", wsl=False))+ def test_a_relative_folder_is_resolved_against_the_wsl_cwd(self):+ with mock.patch.object(setup_hw.os, "getcwd", return_value="/mnt/c/Users/me"):+ self.assertTrue(setup_hw.path_warnings("models", wsl=True))+ with mock.patch.object(setup_hw.os, "getcwd", return_value="/home/me"):+ self.assertFalse(setup_hw.path_warnings("models", wsl=True))+def test_fixed_drives(self):kinds = {"C:\\": 3, "D:\\": 3, "E:\\": 2, "Z:\\": 4} # fixed, fixed, removable, networkmask = (1 << 2) | (1 << 3) | (1 << 4) | (1 << 25)@@ -290,7 +301,7 @@ class VulkanParsing(unittest.TestCase):if k not in ("VK_ICD_FILENAMES", "VK_DRIVER_FILES")}with mock.patch.object(setup_hw, "_probe_vulkan_child", side_effect=probe), \mock.patch.object(setup_hw, "find_user_icds", return_value=["/home/u/dzn.json"]), \- mock.patch.object(setup_hw.sys, "platform", "linux"), \+ mock.patch.object(setup_hw, "host_os", return_value="linux"), \mock.patch.dict(os.environ, env, clear=True):result = setup_hw.detect_vulkan(wsl=True)self.assertEqual(result["icd"], "/home/u/dzn.json")@@ -301,7 +312,7 @@ class VulkanParsing(unittest.TestCase):mock.patch.object(setup_hw.shutil, "which", return_value="/usr/bin/vulkaninfo"), \mock.patch.object(setup_hw, "_run", return_value=VULKANINFO_SUMMARY), \mock.patch.object(setup_hw, "find_user_icds", return_value=[]), \- mock.patch.object(setup_hw.sys, "platform", "linux"):+ mock.patch.object(setup_hw, "host_os", return_value="linux"):result = setup_hw.detect_vulkan(wsl=False)self.assertEqual(result["source"], "vulkaninfo")self.assertEqual(len(result["devices"]), 2)