Skip to content

Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.

C++

setup: reproducible installs - the checkout's own engine release, pinned Hugging Face revisions, pinned Python packages (#214)

Niko1221afc33c260e1f
diff --git a/Dockerfile b/Dockerfile
index b1b796176..6b62dae0e 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -60,8 +60,7 @@ ARG BUILD_VISION=1
RUN python3 -m venv .venv \
&& .venv/bin/pip install --no-cache-dir --upgrade pip \
- && .venv/bin/pip install --no-cache-dir \
- numpy jinja2 regex pyyaml tqdm requests cmake ninja pillow psutil \
+ && .venv/bin/pip install --no-cache-dir -r requirements.txt \
&& chmod +x setup.sh docker-entrypoint.sh
# llama.cpp at the pinned commit, then the engine and the image encoder, built
diff --git a/requirements.txt b/requirements.txt
new file mode 100644
index 000000000..3db8418ab
--- /dev/null
+++ b/requirements.txt
@@ -0,0 +1,23 @@
+# The Python packages setup.py installs into .venv, pinned so a checkout installs the same ones on any day (#214).
+# setup.py's pip step reads this file; an install from before it keeps the packages it has.
+# Python 3.10+ (numpy's newest releases need a newer Python: one line per range).
+numpy==2.5.3; python_version >= "3.12"
+numpy==2.4.6; python_version == "3.11"
+numpy==2.2.6; python_version < "3.11"
+jinja2==3.1.6
+regex==2026.9.10
+pyyaml==6.0.3
+tqdm==4.70.1
+requests==2.34.2
+cmake==4.4.3
+ninja==1.13.2
+pillow==12.3.0
+psutil==7.2.2
+
+# their dependencies
+markupsafe==3.0.3
+certifi==2026.7.22
+charset-normalizer==3.5.1
+idna==3.20
+urllib3==2.8.0
+colorama==0.4.6; sys_platform == "win32"
diff --git a/setup.py b/setup.py
index 3f42c38d4..6501c0fe7 100644
--- a/setup.py
+++ b/setup.py
@@ -43,26 +43,51 @@ import struct
import subprocess
import sys
import time
+import urllib.error
import urllib.request
import zipfile
from pathlib import Path
ROOT = Path(__file__).resolve().parent
WIN = os.name == "nt"
-HF = "https://huggingface.co/ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF/resolve/main/"
+# #214: every Hugging Face file comes from a fixed commit of its repository (the `sha` of
+# https://huggingface.co/api/models/<repo> when this was pinned), so a checkout installs the same files on any
+# day. A revision the repository no longer has falls back to its current files, with a message (download()).
+HF_REVISIONS = {
+ "ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF": "ed59f92082b1e93c0e96d60a8b11aab089b52f09", # 2026-09-29
+ "ukisai/Swift-1.5-Qwen3.8-Flash-Next-GSQ-RCO-GGUF": "b22d729eae29b5796f76fb70f91aef549b9fc52c", # 2026-09-24
+ "ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-Coder-GGUF": "5348543e0147355ac9cbcb031184a3546350988e", # 2026-09-29
+}
+
+
+def hf(repo: str) -> str:
+ """The download folder of a Hugging Face repository at its pinned revision."""
+ return f"https://huggingface.co/{repo}/resolve/{HF_REVISIONS[repo]}/"
+
+
+def hf_unpinned(url: str) -> str:
+ """The same file at the repository's current revision (main)."""
+ return re.sub(r"(https://huggingface\.co/.+?/resolve/)[0-9a-f]{40}/", r"\1main/", url, count=1)
+
+
+HF = hf("ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF")
LLAMA_CPP_COMMIT = "3cf03257f219afbe7334045ff7c6a06ac68c627d"
LLAMA_CPP_ZIP = f"https://github.com/ggml-org/llama.cpp/archive/{LLAMA_CPP_COMMIT}.zip"
# The ready-made engine: <PREBUILT_URL><asset>, a zip with strata(.exe), strata-vision(.exe) and BUILD.json, built
# by tools/make_release.py. Set this to the GitHub release download folder when publishing, e.g.
# "https://github.com/<you>/Strata/releases/latest/download/" (or pass --prebuilt / set STRATA_PREBUILT_URL).
+# With the default, the release of this checkout's own version (PREBUILT_TAG_URL, CMakeLists.txt's version) is
+# tried first and the latest release is the fallback (#214): an older checkout keeps the engine it shipped with.
PREBUILT_URL = "https://github.com/Niko1221/Strata/releases/latest/download/"
+PREBUILT_TAG_URL = "https://github.com/Niko1221/Strata/releases/download/v{version}/"
PREBUILT_ASSET = "strata-windows-x64.zip" if WIN else "strata-linux-x64.zip"
# the CUDA libraries the ready-made engine loads (the same CUDA 13.0 it is built with), from NVIDIA's pip packages
CUDA_WHEELS = ["nvidia-cublas==13.0.2.14", "nvidia-cuda-runtime==13.0.96"]
MIN_DRIVER = 580 # CUDA 13.0
MIN_ENGINE = (0, 1, 30) # v0.1.30: short prompts faster (streaming from 1024 tokens), resident low-RAM variant, multi-GPU session carve, RDNA4; v0.1.29: sampled answers faster (split top-k), #154 correctness fixes; v0.1.28: the expert cache reserves the draft head, a cancelled request no longer fails the next; v0.1.27: RTX 20 (sm_75) in the ready-made engine, the HIP build without CUDA headers; v0.1.26: the draft layer's prompt pass in batches; v0.1.25: faster prompts (grouping off the copy engine, fused hyper-connection kernels), AMD HIP backend, --kv k8v4; v0.1.24: long prompts faster (QSA select on tensor cores); v0.1.23: image requests honor sampling, 8 GB cards start, batched verify window; v0.1.22: faster prompts (tensor-core attention), multi-GPU across images/steering/KV streaming; v0.1.21: multi-GPU layer split (--gpus); v0.1.20: system-prompt checkpoint, PCIe probe, hit rate; v0.1.19: penalties
PY_PACKAGES = ["numpy", "jinja2", "regex", "pyyaml", "tqdm", "requests", "cmake", "ninja", "pillow", "psutil"]
+REQUIREMENTS = ROOT / "requirements.txt" # the same packages and their dependencies, pinned (#214)
MODELS = {
# the original model only for now: Swift 1.5's Q2_0 files split one layer's experts across the two shards, which
@@ -90,24 +115,24 @@ CONTEXTS = [8192, 32768, 65536, 131072, 262144, 393216, 524288]
FAMILIES = {
"qwen": {"title": "Qwen3.8-Flash-Next", "by": "Qwen; GSQ-RCO quants by ISTA-DASLab",
"about": "the original model",
- "hf": "https://huggingface.co/ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF/resolve/main/{q}/",
+ "hf": hf("ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF") + "{q}/",
"file": "Qwen3.8-Flash-Next-GSQ-RCO-{q}-0000{i}-of-00002.gguf", "tag": "",
- "mmproj_hf": "https://huggingface.co/ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF/resolve/main/",
+ "mmproj_hf": hf("ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF"),
"mmproj": "mmproj-Qwen3.8-Flash-Next-BF16.gguf", "name": "qwen3.8-flash-next"},
"swift": {"title": "Swift 1.5", "by": "UkisAI's fine-tune of Qwen3.8-Flash-Next",
"about": "thinks much shorter (-63% thinking tokens, 1.8x sooner answers by its authors' numbers)",
- "hf": "https://huggingface.co/ukisai/Swift-1.5-Qwen3.8-Flash-Next-GSQ-RCO-GGUF/resolve/main/",
+ "hf": hf("ukisai/Swift-1.5-Qwen3.8-Flash-Next-GSQ-RCO-GGUF"),
"file": "Swift-Qwen3.8-Flash-Next-GSQ-RCO-{q}-0000{i}-of-00002.gguf", "tag": "swift-",
- "mmproj_hf": "https://huggingface.co/ukisai/Swift-1.5-Qwen3.8-Flash-Next-GSQ-RCO-GGUF/resolve/main/",
+ "mmproj_hf": hf("ukisai/Swift-1.5-Qwen3.8-Flash-Next-GSQ-RCO-GGUF"),
"mmproj": "mmproj-Swift-Qwen3.8-Flash-Next-BF16.gguf", "name": "swift-1.5",
"license": "Swift Open License 1.0: https://huggingface.co/ukisai/Swift-1.5-Qwen3.8-Flash-Next-GSQ-RCO-GGUF"},
# ISTA-DASLab's expert-pruned release: half of each layer's experts removed, chosen for code, agentic tool use and
# vision; its shard 2 (the n-gram table) and vision encoder are the original's files, shared with it
"coder": {"title": "Qwen3.8-Flash-Next Coder", "by": "ISTA-DASLab's coding version",
"about": "half the experts (code, tools, images kept): needs ~32 GB of RAM, faster; weaker outside coding",
- "hf": "https://huggingface.co/ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-Coder-GGUF/resolve/main/{q}/",
+ "hf": hf("ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-Coder-GGUF") + "{q}/",
"file": "Qwen3.8-Flash-Next-GSQ-RCO-{q}-0000{i}-of-00002.gguf", "tag": "coder-",
- "mmproj_hf": "https://huggingface.co/ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-Coder-GGUF/resolve/main/",
+ "mmproj_hf": hf("ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-Coder-GGUF"),
"mmproj": "mmproj-Qwen3.8-Flash-Next-BF16.gguf", "name": "qwen3.8-flash-next-coder",
"profile": "expert-profile-coder.bin"},
}
@@ -573,6 +598,15 @@ def download(url, dst: Path, what=None):
req = urllib.request.Request(url, method="HEAD", headers={"User-Agent": "strata-setup"})
total = int(urllib.request.urlopen(req, timeout=60).headers.get("Content-Length", 0))
break
+ except urllib.error.HTTPError as e:
+ if e.code == 404 and hf_unpinned(url) != url: # #214: the pinned revision is gone from the repository
+ warn(f"{what or dst.name}: not at the pinned revision any more; downloading the repository's "
+ "current file")
+ url = hf_unpinned(url)
+ continue
+ if attempt == 4:
+ fail(f"cannot reach {url.split('/')[2]} ({e})", "check your internet connection and run it again")
+ time.sleep(5)
except OSError as e:
if attempt == 4:
fail(f"cannot reach {url.split('/')[2]} ({e})", "check your internet connection and run it again")
@@ -683,11 +717,39 @@ def get_llama_cpp():
return llama
+def req_name(line: str) -> str:
+ """The distribution name of a requirement line ("numpy==2.5.3; python_version >= '3.12'" -> "numpy")."""
+ return re.split(r"[\s<>=!~;\[]", line.strip(), maxsplit=1)[0].lower().replace("_", "-")
+
+
+def requirement_lines(path: Path | None = None) -> list[str]:
+ """requirements.txt's requirements, comments and blank lines left out."""
+ lines = []
+ for raw in (path or REQUIREMENTS).read_text(encoding="utf-8").splitlines():
+ line = raw.split("#", 1)[0].strip()
+ if line:
+ lines.append(line)
+ return lines
+
+
+def _installed(name: str) -> bool:
+ try:
+ import importlib.metadata as md
+ md.distribution(name)
+ return True
+ except Exception:
+ return False
+
+
def pip_install(packages, what):
- """pip install into .venv, skipped when the same list was installed before."""
+ """pip install into .venv, skipped when the same list was installed before. An install from before the pinned
+ requirements (#214) recorded bare names: those packages are kept as they are (nothing is reinstalled), and the
+ pinned dependencies it already has count as installed."""
stamp = Path(sys.prefix) / ".strata-pip.json"
have = json.loads(stamp.read_text()) if stamp.exists() else []
- need = [p for p in packages if p not in have]
+ bare = {p.lower() for p in have if req_name(p) == p.lower()}
+ need = [p for p in packages if p not in have and req_name(p) not in bare
+ and not (bare and "==" in p and _installed(req_name(p)))]
if not need:
ok(f"{what} already installed")
return
@@ -892,6 +954,15 @@ def driver_major(gpu):
return 0
+def prebuilt_bases(url_base) -> list[str]:
+ """Where to look for the ready-made engine, in order (each ending in a slash). The default: the release of this
+ checkout's version first, then the latest (#214); an explicit --prebuilt / STRATA_PREBUILT_URL: only that."""
+ base = url_base if url_base.endswith(("/", "\\")) else url_base + "/"
+ if base != PREBUILT_URL:
+ return [base]
+ return [PREBUILT_TAG_URL.format(version=source_version()), base]
+
+
def get_prebuilt(url_base, gpu, vision, updating=False) -> Path | None:
"""The ready-made engine in engine/ (kept between runs), or None when there is none for this PC.
updating: called to replace an installed engine, which starts instead when this fails (no compile)."""
@@ -917,12 +988,18 @@ def get_prebuilt(url_base, gpu, vision, updating=False) -> Path | None:
if not url_base:
return None
z = ROOT / "engine" / PREBUILT_ASSET
- base = url_base if url_base.endswith(("/", "\\")) else url_base + "/"
- if base.startswith(("http://", "https://")):
+ bases = prebuilt_bases(url_base)
+ for i, base in enumerate(bases):
+ if not base.startswith(("http://", "https://")):
+ break
try: # not published (yet), or no internet: compile instead
req = urllib.request.Request(base + PREBUILT_ASSET, method="HEAD", headers={"User-Agent": "strata-setup"})
urllib.request.urlopen(req, timeout=60).close()
+ break
except OSError as e:
+ if i + 1 < len(bases): # #214: this checkout's release is not published (yet)
+ say(f" No ready-made engine for v{source_version()} ({e}): the latest release instead")
+ continue
warn(f"no ready-made engine at {base} ({e})" + ("" if updating else ": compiling instead"))
return None
say(" Downloading the ready-made Strata engine ...")
@@ -2135,7 +2212,8 @@ def main() -> int:
# ---- 3. python packages
step(3, "Python packages")
- pip_install(PY_PACKAGES, "numpy, jinja2, regex, pyyaml, tqdm, requests, cmake, ninja, pillow, psutil")
+ pip_install(requirement_lines() if REQUIREMENTS.exists() else PY_PACKAGES,
+ "numpy, jinja2, regex, pyyaml, tqdm, requests, cmake, ninja, pillow, psutil")
# ---- 4. the engine
step(4, "the Strata engine")
diff --git a/tools/mtp_fetch.py b/tools/mtp_fetch.py
index 82defb5a4..b5454fe68 100644
--- a/tools/mtp_fetch.py
+++ b/tools/mtp_fetch.py
@@ -17,9 +17,14 @@ import os
import struct
import sys
import time
+import urllib.error
import urllib.request
-REPO = "https://huggingface.co/Qwen/Qwen3.8-Flash-Next/resolve/main/"
+# #214: a fixed commit of the checkpoint (its `sha` from https://huggingface.co/api/models/Qwen/Qwen3.8-Flash-Next
+# on 2026-09-30), so every install reads the same tensors; STRATA_MTP_REVISION overrides it (e.g. main). When the
+# repository no longer has it, the current files are read instead, with a message (resolve_repo).
+REVISION = os.environ.get("STRATA_MTP_REVISION") or "de4b8e4d43b917e7706784d8bb445c9af86a3540"
+REPO = "https://huggingface.co/Qwen/Qwen3.8-Flash-Next/resolve/%s/" % REVISION
DTYPE_BYTES = {"BF16": 2, "F16": 2, "F32": 4, "F8_E4M3": 1, "I64": 8, "I32": 4}
@@ -41,6 +46,23 @@ def get(url, start=None, end=None, retries=4):
print("retry %s: %s" % (url, e), file=sys.stderr)
+def resolve_repo():
+ """REPO, or the repository's current files when the pinned revision is gone from it (a 404 on its index)."""
+ global REPO
+ try:
+ req = urllib.request.Request(REPO + "model.safetensors.index.json", method="HEAD",
+ headers={"User-Agent": "strata-mtp-fetch"})
+ urllib.request.urlopen(req, timeout=120).close()
+ except urllib.error.HTTPError as e:
+ if e.code == 404 and "/resolve/main/" not in REPO:
+ print("the checkpoint's pinned revision %s is gone: reading its current files (main)" % REVISION,
+ file=sys.stderr)
+ REPO = REPO.replace("/resolve/%s/" % REVISION, "/resolve/main/")
+ except OSError:
+ pass # no answer: get() retries and reports it
+ return REPO
+
+
def shard_header(shard):
url = REPO + shard
n = struct.unpack("<Q", get(url, 0, 7))[0]
@@ -114,6 +136,7 @@ def main():
ap.add_argument("--out", required=True)
ap.add_argument("--only")
a = ap.parse_args()
+ resolve_repo()
inventory(a.out) if a.cmd == "inventory" else fetch(a.out, a.only)
diff --git a/tools/test_setup_pins.py b/tools/test_setup_pins.py
new file mode 100644
index 000000000..a9c366a25
--- /dev/null
+++ b/tools/test_setup_pins.py
@@ -0,0 +1,218 @@
+"""Tests for setup.py's reproducible installs (#214): the engine of the checkout's own release first (the latest as
+the fallback), Hugging Face files at pinned revisions (the current files when a revision is gone), the pinned
+requirements file, and an existing install left as it is. Mocked network - nothing is downloaded.
+
+ python -m unittest tools.test_setup_pins
+"""
+from __future__ import annotations
+
+import contextlib
+import io
+import json
+import re
+import sys
+import tempfile
+import unittest
+import urllib.error
+import zipfile
+from pathlib import Path
+from unittest import mock
+
+ROOT = Path(__file__).resolve().parents[1]
+sys.path.insert(0, str(ROOT))
+sys.path.insert(0, str(ROOT / "tools"))
+import setup # noqa: E402
+
+SHA = re.compile(r"/resolve/[0-9a-f]{40}/")
+
+
+class Response(io.BytesIO):
+ def __init__(self, body=b"", status=200):
+ super().__init__(body)
+ self.status = status
+ self.headers = {"Content-Length": str(len(body))}
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *exc):
+ self.close()
+
+
+def not_found(url):
+ return urllib.error.HTTPError(url, 404, "Not Found", {}, None)
+
+
+def quiet(fn, *args, **kw):
+ out = io.StringIO()
+ with contextlib.redirect_stdout(out):
+ return fn(*args, **kw), out.getvalue()
+
+
+class HuggingFacePins(unittest.TestCase):
+ def test_every_model_url_is_pinned(self):
+ for name, fam in setup.FAMILIES.items():
+ for key in ("hf", "mmproj_hf"):
+ with self.subTest(family=name, key=key):
+ self.assertRegex(fam[key], SHA)
+ self.assertNotIn("/resolve/main/", fam[key])
+ self.assertRegex(setup.HF, SHA)
+
+ def test_unpinned(self):
+ url = setup.FAMILIES["swift"]["hf"] + "x.gguf"
+ self.assertEqual(setup.hf_unpinned(url),
+ "https://huggingface.co/ukisai/Swift-1.5-Qwen3.8-Flash-Next-GSQ-RCO-GGUF/resolve/main/x.gguf")
+ self.assertEqual(setup.hf_unpinned("https://example.com/a/b"), "https://example.com/a/b")
+
+ def test_a_gone_revision_downloads_the_current_file(self):
+ seen = []
+
+ def urlopen(req, timeout=None):
+ seen.append((req.get_method(), req.full_url))
+ if "/resolve/main/" not in req.full_url:
+ raise not_found(req.full_url)
+ return Response(b"model bytes", status=200)
+
+ with tempfile.TemporaryDirectory() as d, mock.patch.object(setup.urllib.request, "urlopen", urlopen):
+ dst = Path(d) / "m.gguf"
+ _, out = quiet(setup.download, setup.FAMILIES["qwen"]["mmproj_hf"] + "m.gguf", dst)
+ self.assertEqual(dst.read_bytes(), b"model bytes")
+ self.assertIn("not at the pinned revision any more", out)
+ self.assertEqual([m for m, _ in seen], ["HEAD", "HEAD", "GET"])
+ self.assertTrue(all("/resolve/main/" in u for _, u in seen[1:]))
+
+ def test_mtp_fetch_is_pinned_and_falls_back(self):
+ import mtp_fetch
+ self.assertRegex(mtp_fetch.REPO, SHA)
+ self.assertIn(mtp_fetch.REVISION, mtp_fetch.REPO)
+ pinned = mtp_fetch.REPO
+
+ def urlopen(req, timeout=None):
+ raise not_found(req.full_url)
+
+ try:
+ with mock.patch.object(mtp_fetch.urllib.request, "urlopen", urlopen), \
+ contextlib.redirect_stderr(io.StringIO()) as err:
+ self.assertEqual(mtp_fetch.resolve_repo(), "https://huggingface.co/Qwen/Qwen3.8-Flash-Next/resolve/main/")
+ self.assertIn("pinned revision", err.getvalue())
+ finally:
+ mtp_fetch.REPO = pinned
+
+
+class Engine(unittest.TestCase):
+ def setUp(self):
+ self.tmp = tempfile.TemporaryDirectory()
+ self.root = Path(self.tmp.name)
+ (self.root / "engine").mkdir()
+ self.patches = [mock.patch.object(setup, "ROOT", self.root),
+ mock.patch.object(setup, "source_version", lambda: "0.1.31")]
+ for p in self.patches:
+ p.start()
+
+ def tearDown(self):
+ for p in reversed(self.patches):
+ p.stop()
+ self.tmp.cleanup()
+
+ def fake_download(self, got):
+ def download(url, dst, what=None):
+ got.append(url)
+ with zipfile.ZipFile(dst, "w") as z:
+ z.writestr("BUILD.json", json.dumps({"version": ".".join(map(str, setup.MIN_ENGINE)), "archs": [89]}))
+ z.writestr(setup.EXE, b"engine")
+ return download
+
+ def run_get(self, published):
+ heads, got = [], []
+
+ def urlopen(req, timeout=None):
+ heads.append(req.full_url)
+ if not any(req.full_url.startswith(p) for p in published):
+ raise not_found(req.full_url)
+ return Response()
+
+ with mock.patch.object(setup.urllib.request, "urlopen", urlopen), \
+ mock.patch.object(setup, "download", self.fake_download(got)):
+ eng, out = quiet(setup.get_prebuilt, setup.PREBUILT_URL, {"arch": 89}, "gpu")
+ return eng, out, heads, got
+
+ def test_bases(self):
+ self.assertEqual(setup.prebuilt_bases(setup.PREBUILT_URL),
+ ["https://github.com/Niko1221/Strata/releases/download/v0.1.31/", setup.PREBUILT_URL])
+ self.assertEqual(setup.prebuilt_bases("https://mirror.example/x"), ["https://mirror.example/x/"])
+
+ def test_the_checkout_s_release_first(self):
+ tag = "https://github.com/Niko1221/Strata/releases/download/v0.1.31/"
+ eng, out, heads, got = self.run_get([tag, setup.PREBUILT_URL])
+ self.assertEqual(eng, self.root / "engine")
+ self.assertEqual(got, [tag + setup.PREBUILT_ASSET])
+ self.assertEqual(len(heads), 1)
+
+ def test_latest_when_it_is_not_published(self):
+ eng, out, heads, got = self.run_get([setup.PREBUILT_URL])
+ self.assertEqual(eng, self.root / "engine")
+ self.assertEqual(got, [setup.PREBUILT_URL + setup.PREBUILT_ASSET])
+ self.assertIn("No ready-made engine for v0.1.31", out)
+
+ def test_an_installed_engine_is_kept(self):
+ (self.root / "engine" / "BUILD.json").write_text(json.dumps(
+ {"version": ".".join(map(str, setup.MIN_ENGINE)), "archs": [89]}))
+ (self.root / "engine" / setup.EXE).write_bytes(b"old")
+
+ def urlopen(req, timeout=None):
+ raise AssertionError("asked the network for an installed engine")
+
+ with mock.patch.object(setup.urllib.request, "urlopen", urlopen):
+ eng, out = quiet(setup.get_prebuilt, setup.PREBUILT_URL, {"arch": 89}, "gpu")
+ self.assertEqual(eng, self.root / "engine")
+ self.assertEqual((self.root / "engine" / setup.EXE).read_bytes(), b"old")
+
+
+class Requirements(unittest.TestCase):
+ def test_every_package_is_pinned(self):
+ lines = setup.requirement_lines()
+ names = {setup.req_name(x) for x in lines}
+ for p in setup.PY_PACKAGES:
+ self.assertIn(p, names)
+ for x in lines:
+ self.assertIn("==", x, x)
+ self.assertEqual(setup.req_name('numpy==2.5.3; python_version >= "3.12"'), "numpy")
+ self.assertEqual(setup.req_name("charset_normalizer==3"), "charset-normalizer")
+
+ def pip(self, stamp, packages, installed=()):
+ ran = []
+ with tempfile.TemporaryDirectory() as d:
+ if stamp is not None:
+ (Path(d) / ".strata-pip.json").write_text(json.dumps(stamp))
+ with mock.patch.object(setup.sys, "prefix", d), \
+ mock.patch.object(setup, "run", lambda cmd, **kw: ran.append(cmd)), \
+ mock.patch.object(setup, "_installed", lambda name: name in installed):
+ quiet(setup.pip_install, packages, "the packages")
+ after = json.loads((Path(d) / ".strata-pip.json").read_text()) if ran else stamp
+ return [c for cmd in ran for c in cmd if "==" in c or c in setup.PY_PACKAGES], after
+
+ def test_fresh_install_gets_every_pin(self):
+ lines = setup.requirement_lines()
+ ran, stamp = self.pip(None, lines)
+ self.assertEqual(ran, lines)
+ self.assertEqual(sorted(stamp), sorted(lines))
+ self.assertEqual(self.pip(stamp, lines)[0], []) # the second run: nothing
+
+ def test_an_install_from_before_the_pins_is_left_alone(self):
+ lines = setup.requirement_lines()
+ legacy = sorted(setup.PY_PACKAGES) + ["nvidia-cublas==13.0.2.14"]
+ deps = {"markupsafe", "certifi", "charset-normalizer", "idna", "urllib3", "colorama"}
+ self.assertEqual(self.pip(legacy, lines, installed=deps)[0], [])
+ missing = [p for p in legacy if p != "psutil"] # an older list without psutil
+ ran, _ = self.pip(missing, lines, installed=deps)
+ self.assertEqual(ran, ["psutil==7.2.2"])
+
+ def test_a_changed_pin_is_installed(self):
+ lines = setup.requirement_lines()
+ old = [x.replace("tqdm==4.70.1", "tqdm==4.60.0") for x in lines]
+ ran, _ = self.pip(old, lines)
+ self.assertEqual(ran, ["tqdm==4.70.1"])
+
+
+if __name__ == "__main__":
+ unittest.main()