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: a BUILD.json is trusted only beside an engine binary of the source's version; a build that leaves the old binary is neither stamped nor installed (#2054)

Niko1221d1ab65a18b9a
diff --git a/setup.py b/setup.py
index 5fbe72c8b..e50829894 100644
--- a/setup.py
+++ b/setup.py
@@ -2642,7 +2642,7 @@ def build_engine_hip(gpu, llama, vision="none") -> Path:
has_archs = set(archs) <= set(meta.get("archs", []))
floor = cpu_floor(cpu_info()[1]) # "" on an AVX2 CPU: the normal engine
engine_ok = meta.get("backend") == "hip" and (eng / EXE).exists() and meta.get("src") == src and has_archs and \
- (meta.get("isa_floor") or "") == floor
+ (meta.get("isa_floor") or "") == floor and not stale_binary(eng / EXE)
vision_ok = vision == "none" or ((eng / VEXE).exists() and meta.get("vision_src") == vsrc)
if engine_ok and vision_ok:
ok("engine already built for this PC")
@@ -2671,6 +2671,10 @@ def build_engine_hip(gpu, llama, vision="none") -> Path:
"-DCMAKE_PREFIX_PATH=" + ";".join([str(root), *libs]),
f"-DCMAKE_HIP_FLAGS=--rocm-path={root} --rocm-device-lib-path={bitcode}",
f"-DSTRATA_GGML_DIR={llama}", *isa_floor_defs(floor, ROOT / "build-hip", meta)], None, "")
+ if stale_binary(ROOT / "build-hip" / EXE): # #2054: no stamp for a binary of another version
+ fail(f"the engine build finished without a new engine ({EXE} is version "
+ f"{binary_engine_version(ROOT / 'build-hip' / EXE)}, this source is {source_version()}): "
+ "the installed engine is left as it was", "delete the folder build-hip and run this again")
shutil.copy2(ROOT / "build-hip" / EXE, eng / EXE)
meta = {"source": "local-hip", "backend": "hip", "version": source_version(), "archs": archs, "vision": "none",
"lib_dirs": dirs, "src": src, **({"isa_floor": floor} if floor else {})}
@@ -3108,7 +3112,7 @@ def update_installed_engine(url_base, toolkit=None) -> None:
"starting the installed one")
return
if meta.get("backend") == "hip": # AMD: compiled here, again when its source changed
- if meta.get("src") != source_hash(ENGINE_SOURCES):
+ if meta.get("src") != source_hash(ENGINE_SOURCES) or stale_binary(eng / EXE):
try:
usable = [x for x in amd_gpus() if amd_problem(x) is None]
g = next((x for x in usable if x["arch"] in meta.get("archs", [])), usable[0] if usable else None)
@@ -3125,7 +3129,7 @@ def update_installed_engine(url_base, toolkit=None) -> None:
local = meta.get("source") == "local"
vision = meta.get("vision") or "none"
if local: # compiled here: is it older than the source (a git pull)?
- if meta.get("src") == source_hash(ENGINE_SOURCES) and \
+ if meta.get("src") == source_hash(ENGINE_SOURCES) and not stale_binary(eng / EXE) and \
(vision == "none" or meta.get("vision_src") == source_hash(VISION_SOURCES)):
return
elif ver >= MIN_ENGINE:
@@ -3400,7 +3404,7 @@ def build_engine(gpu, vision, yes, llama, toolkit=None) -> Path:
new_arch = local and not set(archs) <= built
floor = cpu_floor(cpu_info()[1]) # "" on an AVX2 CPU: the normal engine
engine_ok = local and (eng / EXE).exists() and meta.get("src") == src and not new_arch and \
- (meta.get("isa_floor") or "") == floor
+ (meta.get("isa_floor") or "") == floor and not stale_binary(eng / EXE)
vision_ok = not want_vision or ((eng / VEXE).exists() and (not local or meta.get("vision_src") == vsrc))
if engine_ok and vision_ok:
ok("engine already built for this PC")
@@ -3421,6 +3425,10 @@ def build_engine(gpu, vision, yes, llama, toolkit=None) -> Path:
*host_compiler_defs(True), *engine_defs(archs, toolkit),
*isa_floor_defs(floor, bdir, meta)],
vcvars, "build-strata-cuda12.bat" if t12 else "build-strata.bat")
+ if stale_binary(bdir / EXE): # #2054: the stamp below is written only for a binary of this source
+ fail(f"the engine build finished without a new engine ({EXE} is version {binary_engine_version(bdir / EXE)}, "
+ f"this source is {source_version()}): the installed engine and its stamp are left as they were",
+ "the build folder " + str(bdir) + " may be configured for something else: delete it and run this again")
shutil.copy2(bdir / EXE, eng / EXE)
if not vision_ok:
say(" Compiling the image encoder" + (" with CUDA (10-20 minutes, once) ..." if vision == "gpu" else " ..."))
@@ -4067,6 +4075,24 @@ def source_version() -> str:
return m.group(1) if m else "0"
+def binary_engine_version(exe) -> str | None:
+ """The version compiled into an engine binary (the `engine=X.Y.Z` line it prints at start; 0.1.13 and newer carry
+ it), read from the file without running it. None: unreadable, or a binary without it."""
+ try:
+ m = re.search(rb"engine=(\d+\.\d+\.\d+(?:\.\d+)?)\n", Path(exe).read_bytes())
+ except OSError:
+ return None
+ return m.group(1).decode() if m else None
+
+
+def stale_binary(exe) -> bool:
+ """#2054: the engine binary is of another version than this source tree builds. A BUILD.json that carries the
+ source's hash and version cannot be trusted alone: a build that stopped (a host compiler the toolkit rejects) can
+ leave the old binary beside a stamp of the new source, and nothing would ever compile it again."""
+ v = binary_engine_version(exe)
+ return v is not None and v != source_version()
+
+
def engine_version(exe: Path) -> tuple:
"""The version in the engine folder's BUILD.json, or else the one compiled into the binary. A locally compiled
engine is not necessarily the source's version: when compiling a `git pull` fails, the previous engine is kept
diff --git a/tools/test_setup_stale_stamp.py b/tools/test_setup_stale_stamp.py
new file mode 100644
index 000000000..b282215d6
--- /dev/null
+++ b/tools/test_setup_stale_stamp.py
@@ -0,0 +1,144 @@
+"""#2054: BUILD.json is trusted only beside a binary of the source's version.
+
+A build that stopped (nvcc rejecting a newer host gcc) once left the old engine next to a stamp of the new source, and
+every later update said "engine already built for this PC" for good. `stale_binary` reads the version compiled into the
+binary; `build_engine` refuses to stamp or install a binary of another version and compiles again when the installed
+one is stale.
+
+ python -m unittest tools.test_setup_stale_stamp
+"""
+from __future__ import annotations
+
+import json
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+from unittest import mock
+
+ROOT = Path(__file__).resolve().parents[1]
+sys.path.insert(0, str(ROOT))
+import setup # noqa: E402
+
+GPU = {"arch": 86, "archs": [86], "name": "RTX 3060"}
+
+
+def binary(version: str | None) -> bytes:
+ return b"\x7fELF....tail_role_token=0 vram_elastic=0 engine=" + version.encode() + b"\n...." if version else b"old binary"
+
+
+class StaleBinary(unittest.TestCase):
+ def test_reads_the_compiled_in_version(self):
+ with tempfile.TemporaryDirectory() as d, mock.patch.object(setup, "source_version", lambda: "0.1.43"):
+ exe = Path(d) / "strata"
+ exe.write_bytes(binary("0.1.42"))
+ self.assertEqual(setup.binary_engine_version(exe), "0.1.42")
+ self.assertTrue(setup.stale_binary(exe))
+ exe.write_bytes(binary("0.1.43"))
+ self.assertFalse(setup.stale_binary(exe))
+
+ def test_four_part_version_and_unknowns(self):
+ with tempfile.TemporaryDirectory() as d, mock.patch.object(setup, "source_version", lambda: "0.1.43.1"):
+ exe = Path(d) / "strata"
+ exe.write_bytes(binary("0.1.43.1"))
+ self.assertFalse(setup.stale_binary(exe))
+ exe.write_bytes(binary("0.1.43"))
+ self.assertTrue(setup.stale_binary(exe))
+ exe.write_bytes(binary(None)) # a binary that carries no version: not judged
+ self.assertFalse(setup.stale_binary(exe))
+ self.assertFalse(setup.stale_binary(Path(d) / "missing"))
+
+
+class BuildEngineStamp(unittest.TestCase):
+ def setUp(self):
+ tmp = tempfile.TemporaryDirectory()
+ self.addCleanup(tmp.cleanup)
+ self.root = Path(tmp.name)
+ self.eng = self.root / "engine"
+ self.eng.mkdir()
+ (self.eng / setup.EXE).write_bytes(binary("0.1.42"))
+ self.old_stamp = {"source": "local", "version": "0.1.42", "archs": [86], "vision": "none",
+ "cuda_dirs": [], "src": "oldhash", "vision_src": None}
+ (self.eng / "BUILD.json").write_text(json.dumps(self.old_stamp))
+ self.built = binary("0.1.43") # what the fake compile leaves in the build folder
+ self.compiles = 0
+ patches = [mock.patch.object(setup, "ROOT", self.root),
+ mock.patch.object(setup, "source_hash", lambda parts: "newhash"),
+ mock.patch.object(setup, "source_version", lambda: "0.1.43"),
+ mock.patch.object(setup, "install_build_tools", lambda gpu, yes: ("nvcc", None)),
+ mock.patch.object(setup, "toolkit_root_defs", lambda nvcc: []),
+ mock.patch.object(setup, "host_compiler_defs", lambda cuda: []),
+ mock.patch.object(setup, "engine_defs", lambda archs, tk=13: []),
+ mock.patch.object(setup, "isa_floor_defs", lambda *a: []),
+ mock.patch.object(setup, "cpu_floor", lambda avx2: ""),
+ mock.patch.object(setup, "cpu_info", lambda: ("cpu", True)),
+ mock.patch.object(setup, "cmake_build", self.fake_build),
+ mock.patch.object(setup, "say", lambda *a, **k: None),
+ mock.patch.object(setup, "ok", lambda *a, **k: None)]
+ for p in patches:
+ p.start()
+ self.addCleanup(p.stop)
+
+ def fake_build(self, src, bdir, target, defs, vcvars, bat):
+ self.compiles += 1
+ bdir.mkdir(parents=True, exist_ok=True)
+ (bdir / setup.EXE).write_bytes(self.built)
+
+ def stamp(self):
+ return json.loads((self.eng / "BUILD.json").read_text())
+
+ def test_a_good_build_is_stamped(self):
+ setup.build_engine(GPU, "none", True, Path("llama"), toolkit=13)
+ self.assertEqual(self.compiles, 1)
+ self.assertEqual(self.stamp()["src"], "newhash")
+ self.assertEqual(self.stamp()["version"], "0.1.43")
+ self.assertEqual((self.eng / setup.EXE).read_bytes(), self.built)
+
+ def test_a_build_that_leaves_the_old_binary_is_not_stamped_or_installed(self):
+ self.built = binary("0.1.42") # the build "succeeded" without producing the new engine
+ with self.assertRaises(SystemExit):
+ setup.build_engine(GPU, "none", True, Path("llama"), toolkit=13)
+ self.assertEqual(self.stamp(), self.old_stamp) # still the old hash: the next update compiles again
+ self.assertEqual((self.eng / setup.EXE).read_bytes(), binary("0.1.42"))
+
+ def test_a_poisoned_stamp_is_compiled_again(self):
+ """The state #2054 found: the new source hash and version in BUILD.json, the old binary beside it."""
+ (self.eng / "BUILD.json").write_text(json.dumps({**self.old_stamp, "version": "0.1.43", "src": "newhash"}))
+ setup.build_engine(GPU, "none", True, Path("llama"), toolkit=13)
+ self.assertEqual(self.compiles, 1)
+ self.assertEqual((self.eng / setup.EXE).read_bytes(), self.built)
+
+ def test_a_healthy_install_is_left_alone(self):
+ (self.eng / setup.EXE).write_bytes(binary("0.1.43"))
+ (self.eng / "BUILD.json").write_text(json.dumps({**self.old_stamp, "version": "0.1.43", "src": "newhash"}))
+ setup.build_engine(GPU, "none", True, Path("llama"), toolkit=13)
+ self.assertEqual(self.compiles, 0)
+
+
+class UpdateInstalledEngine(unittest.TestCase):
+ def test_a_poisoned_stamp_makes_the_update_compile(self):
+ with tempfile.TemporaryDirectory() as d:
+ root = Path(d)
+ eng = root / "engine"
+ eng.mkdir()
+ (eng / setup.EXE).write_bytes(binary("0.1.42"))
+ (eng / "BUILD.json").write_text(json.dumps({"source": "local", "version": "0.1.43", "archs": [86],
+ "vision": "none", "src": "newhash"}))
+ built = []
+ with mock.patch.object(setup, "ROOT", root), \
+ mock.patch.object(setup, "source_hash", lambda parts: "newhash"), \
+ mock.patch.object(setup, "source_version", lambda: "0.1.43"), \
+ mock.patch.object(setup, "update_engine_gpu", lambda tk: dict(GPU)), \
+ mock.patch.object(setup, "get_llama_cpp", lambda: Path("llama")), \
+ mock.patch.object(setup, "build_engine", lambda *a, **k: built.append(a)), \
+ mock.patch.object(setup, "say", lambda *a, **k: None):
+ setup.update_installed_engine("http://x", 13)
+ self.assertEqual(len(built), 1)
+ built.clear()
+ (eng / setup.EXE).write_bytes(binary("0.1.43"))
+ setup.update_installed_engine("http://x", 13)
+ self.assertEqual(built, [])
+
+
+if __name__ == "__main__":
+ unittest.main()