From 0cd44323e4b1cb3f02993c754b315888d32f92f3 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 24 Oct 2026 13:03:56 +0200 Subject: [PATCH 01/22] Windows: a card taken out of the PC no longer decides the engine; only the display adapters Windows reports as present count when two makes are in the registry (#3892); test --- strata_control/engine_component.py | 10 +++++++++- tests/terminal/test_engine_component.py | 10 ++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/strata_control/engine_component.py b/strata_control/engine_component.py index bb4abcb8..586a1c63 100644 --- a/strata_control/engine_component.py +++ b/strata_control/engine_component.py @@ -627,7 +627,15 @@ def windows_display_adapters() -> list[dict]: """The display adapters Windows has a driver for: the display-class registry key (readable without admin and without running anything), then Win32_VideoController when the key lists nothing: {"vendor": "10de"|"1002"|"8086"|..., "device": int, "name", "vram_gb"}. Empty off Windows or when neither can be read.""" - return _windows_display_adapters_registry() or _windows_adapters_cim() + found = _windows_display_adapters_registry() + if len({a.get("vendor") for a in found} & {"10de", "1002"}) > 1: + # The registry keeps the driver entry of a card that was taken out (an NVIDIA card swapped for a Radeon, #3892): when two makes are + # listed, only the adapters Windows reports as present now count. + present = {(a["vendor"], a["device"]) for a in _windows_adapters_cim()} + now = [a for a in found if (a["vendor"], a["device"]) in present] + if now: + return now + return found or _windows_adapters_cim() def _windows_display_adapters_registry() -> list[dict]: diff --git a/tests/terminal/test_engine_component.py b/tests/terminal/test_engine_component.py index d67ef211..6f9fc567 100644 --- a/tests/terminal/test_engine_component.py +++ b/tests/terminal/test_engine_component.py @@ -258,6 +258,16 @@ class WindowsAmd(unittest.TestCase): {"vendor": "1002", "device": 0x744C, "name": "AMD Radeon RX 7900 XTX", "vram_gb": 24.0}] IGPU_ONLY = [{"vendor": "1002", "device": 0x15BF, "name": "AMD Radeon 780M Graphics", "vram_gb": 0.5}] + def test_a_removed_nvidia_card_left_in_the_registry_does_not_win(self): # #3892 + old = {"vendor": "10de", "device": 0x2684, "name": "NVIDIA GeForce RTX 4090", "vram_gb": 24.0} + new = self.TESTER_A[0] + with mock.patch.object(ec, "_windows_display_adapters_registry", return_value=[old, new]), mock.patch.object(ec, "_windows_adapters_cim", return_value=[dict(new)]): + self.assertEqual(ec._windows_vendor_backend(), "hip") + with mock.patch.object(ec, "_windows_display_adapters_registry", return_value=[old, new]), mock.patch.object(ec, "_windows_adapters_cim", return_value=[dict(old), dict(new)]): + self.assertEqual(ec._windows_vendor_backend(), "cuda") # both really there: NVIDIA first, as before + with mock.patch.object(ec, "_windows_display_adapters_registry", return_value=[old, new]), mock.patch.object(ec, "_windows_adapters_cim", return_value=[]): + self.assertEqual(ec._windows_vendor_backend(), "cuda") # Windows could not say: nothing is dropped + def test_nvidia_wins_and_an_integrated_radeon_is_not_a_card(self): self.assertEqual(ec._windows_vendor_backend(self.OWNER_PC), "cuda") self.assertEqual(ec.windows_amd_cards(self.OWNER_PC), []) From 1736b558bd042af8df4d1cc56f97fc9f83d74e84 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 24 Oct 2026 13:04:44 +0200 Subject: [PATCH 02/22] setup: a NVIDIA driver older than CUDA 13 needs (528 to 579) runs the CUDA 12 engine by itself and says so in one line instead of stopping and naming a flag strata launch does not have (#3843); tests --- setup.py | 11 ++++++----- tools/test_setup_older_gpus.py | 23 ++++++++++++++++++----- 2 files changed, 24 insertions(+), 10 deletions(-) diff --git a/setup.py b/setup.py index 83a09dcf..47e3fa48 100644 --- a/setup.py +++ b/setup.py @@ -1580,7 +1580,7 @@ def named_gpus(gpu, gpus) -> list: return [] -def cuda_choice(archs, cuda=None): +def cuda_choice(archs, cuda=None, driver=None): """The CUDA toolkit of one model's engine: (12 or 13, why). 13 (the ready-made engine) unless a card is older than CUDA 13 supports (Pascal / Volta: CUDA 13 cannot compile for them) - one engine runs per model, so its oldest card decides. `cuda` (--cuda 12|13) overrides it; setup recommends, it does not refuse (the caller warns).""" @@ -1595,6 +1595,9 @@ def cuda_choice(archs, cuda=None): if old: return 12, (f"sm_{old[0]} is older than CUDA 13 supports (it dropped Pascal and Volta): this model runs the " "experimental CUDA 12 engine") + if driver and CUDA12_MIN_DRIVER <= int(driver) < MIN_DRIVER: # #3843: a driver too old for CUDA 13 still runs the CUDA 12 engine + return 12, (f"the NVIDIA driver {driver} is older than CUDA 13 needs ({MIN_DRIVER}): this model runs the CUDA 12 engine " + f"(it works with driver {CUDA12_MIN_DRIVER} or newer; a newer driver from https://www.nvidia.com/drivers gives the CUDA 13 engine)") return 13, None @@ -8801,15 +8804,13 @@ def main() -> int: if multi: ok("GPUs: " + " + ".join(gpu_name(x) for x in chosen) + " together (the model's layers are split across them)") ok(f"GPU: {gpu['name']}, {gpu['vram_gb']:.1f} GB VRAM, compute capability {cc(gpu)}, driver {gpu['driver']}") - cuda_tk, why = cuda_choice(gpu["archs"], a.cuda) # one engine per model: its oldest card decides + cuda_tk, why = cuda_choice(gpu["archs"], a.cuda, driver_major(gpu)) # one engine per model: its oldest card decides if why: (warn if cuda_tk == 13 or str(a.cuda) == "12" else ok)(f"CUDA {cuda_tk}: {why}") min_driver = CUDA12_MIN_DRIVER if cuda_tk == 12 else MIN_DRIVER if driver_major(gpu) < min_driver: fail(f"the NVIDIA driver is too old ({gpu['driver']}; {min_driver} or newer is needed)", - "update it with the NVIDIA App or from https://www.nvidia.com/drivers, restart, and run this again" + - ("" if cuda_tk == 12 else f" (or --cuda 12: the experimental CUDA 12 engine runs with driver " - f"{CUDA12_MIN_DRIVER} or newer, docs/OLDER_GPUS.md)")) + "update it with the NVIDIA App or from https://www.nvidia.com/drivers, restart, and run this again") if gpu["vram_gb"] < 11: warn("less than 12 GB of " + ("GPU memory (this APU's carve-out + shared memory)" if gpu.get("uma") else "VRAM") + ": Strata will run, but most experts stay on the CPU and it will be slow") diff --git a/tools/test_setup_older_gpus.py b/tools/test_setup_older_gpus.py index 72d9a97c..d11419e1 100644 --- a/tools/test_setup_older_gpus.py +++ b/tools/test_setup_older_gpus.py @@ -39,6 +39,14 @@ class Choice(unittest.TestCase): self.assertEqual(tk, 12, archs) self.assertIn(f"sm_{min(archs)} is older than CUDA 13 supports", why) + def test_a_driver_too_old_for_cuda13_gets_the_cuda12_engine(self): # #3843 + self.assertEqual(setup.cuda_choice([86], None, 576)[0], 12) + self.assertIn("older than CUDA 13 needs", setup.cuda_choice([86], None, 576)[1]) + self.assertEqual(setup.cuda_choice([86], None, 580), (13, None)) + self.assertEqual(setup.cuda_choice([86], None, 0), (13, None)) # driver unknown: as before + self.assertEqual(setup.cuda_choice([86], None, 500), (13, None)) # too old for both: setup stops with the driver message + self.assertEqual(setup.cuda_choice([86], "13", 576)[0], 13) # chosen by hand: kept + def test_the_override_is_honored_with_a_warning(self): tk, why = setup.cuda_choice([70], "13") self.assertEqual(tk, 13) # recommend, never force: kept, and said @@ -225,12 +233,17 @@ class Install(unittest.TestCase): self.assertEqual((calls, cfg["cuda"]), ([12], 12)) self.assertIn("--cuda 12 (as you chose", out) - def test_an_old_driver_is_told_about_cuda12(self): - code, out, _, _, _ = self.run_setup(127.8, [card(0, "NVIDIA GeForce RTX 4090", 24.0, "89", "550.54")], + def test_an_old_driver_gets_cuda12_by_itself(self): # #3843: said in one line, not a stop + code, out, cfg, calls, _ = self.run_setup(127.8, [card(0, "NVIDIA GeForce RTX 4090", 24.0, "89", "550.54")], + argv_for("qwen", "IQ3_XXS")) + self.assertEqual(code, 0, out[-3000:]) + self.assertEqual((calls, cfg["cuda"]), ([12], 12)) + self.assertIn("older than CUDA 13 needs (580): this model runs the CUDA 12 engine", out) + code, out, _, _, _ = self.run_setup(127.8, [card(0, "NVIDIA GeForce RTX 4090", 24.0, "89", "470.10")], argv_for("qwen", "IQ3_XXS")) - self.assertEqual(code, 1) - self.assertIn("580 or newer is needed", out) - self.assertIn("--cuda 12", out) + self.assertEqual(code, 1) # too old for both: the stop stays + self.assertIn("is too old", out) + self.assertNotIn("--cuda 12", out) code, out, cfg, calls, _ = self.run_setup(127.8, [card(0, "NVIDIA GeForce RTX 4090", 24.0, "89", "550.54")], argv_for("qwen", "IQ3_XXS") + ["--cuda", "12"]) self.assertEqual(code, 0, out[-3000:]) From bdaa93edf07ab180ae0558f0f12797709b652fb9 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 24 Oct 2026 13:05:30 +0200 Subject: [PATCH 03/22] launch: a setup option error ('setup.py: error: argument --kv: invalid choice') is the cause shown, not only 'could not be installed'; setup accepts --kv fp16 as DOCKER.md says (#3785); tests --- setup.py | 7 ++++--- strata_cli/launch/runner.py | 11 +++++++++++ tests/terminal/test_setup_failure_words.py | 14 ++++++++++++++ 3 files changed, 29 insertions(+), 3 deletions(-) diff --git a/setup.py b/setup.py index 47e3fa48..f3689cac 100644 --- a/setup.py +++ b/setup.py @@ -6978,6 +6978,7 @@ UD_FIT_MIN_SLACK_MIB = 64 # at least a few cache slots beside the estima UD_FIT_CARD_GB = 9.5 # the check is for cards up to here UD_FIT_RUNTIME_MIB = 250 # CUDA / HIP: the runtime's own context (the SYCL measurement above has none of it) UD_FIT_ENGINE_RESERVE_MIB = 300 # the reserve the engine settles on when none is given and the card is tight +KV_WORDS = {"int8": "8-bit", "q4_0": "4-bit (Hadamard-rotated)", "k8v4": "8-bit keys, 4-bit values", "fp16": "16-bit"} UD_FIT_KV_BYTES = {"fp16": 2112, "int8": 1056, "q4_0": 576, "k8v4": 816} # per token per attention layer (13) UD_FIT_CTX_STEPS = (8192, 6144, 4608) @@ -8436,9 +8437,9 @@ def main() -> int: ap.add_argument("--rope-scale", type=float, help="the extension factor (default: the final context over the trained 262144, at least 1 - " "1.5 for 384K, 2 for 512K, 1 inside the trained range)") - ap.add_argument("--kv", choices=["int8", "q4_0", "k8v4"], + ap.add_argument("--kv", choices=["int8", "q4_0", "k8v4", "fp16"], help="KV cache precision above 8K context: int8 (default), q4_0 (half the memory, a little less " - "precise) or k8v4 (hybrid: INT8 K + 4-bit V, 816 B/cell)") + "precise) k8v4 (hybrid: INT8 K + 4-bit V, 816 B/cell) or fp16 (16-bit, twice the memory of int8)") ap.add_argument("--vision", choices=["yes", "no", "none", "gpu", "cpu"], help="let the model read images (on by default where the model can; yes = the best reader for this card: the CPU " "under 24 GB of VRAM, the GPU from 24 GB, any make; gpu / cpu = that reader; no = text only)") @@ -9105,7 +9106,7 @@ def main() -> int: say(" documents; long-context lookups (needle tests) still pass") kv = ["int8", "q4_0"][int(ask("KV cache?", ["1", "2"], "1", a.yes)) - 1] if ctx > 8192: - ok(f"KV cache: {'8-bit' if kv == 'int8' else '4-bit (Hadamard-rotated)'}") + ok(f"KV cache: {KV_WORDS.get(kv, kv)}") if MODELS[model].get("vision", fam.get("vision")) is False: # UD-IQ4_XS: images, unlike UD-Q4_K_XL vision = "none" if a.vision not in (None, "no", "none"): diff --git a/strata_cli/launch/runner.py b/strata_cli/launch/runner.py index a09f6b8f..e02a2032 100644 --- a/strata_cli/launch/runner.py +++ b/strata_cli/launch/runner.py @@ -77,6 +77,16 @@ def python_failure(lines: list[str]) -> str | None: return None +def argparse_failure(lines: list[str]) -> str: + """setup.py's own refusal of an option ("setup.py: error: argument --kv: invalid choice: ..."), which is neither an [X] line nor a + traceback (#3785): the words after "error:" are the cause.""" + for line in reversed(lines): + found = re.match(r"\s*(?:setup|strata)(?:\.py)?: error: (.+)", line) + if found: + return found.group(1).strip()[:300] + return "" + + def missing_file(failure: str) -> bool: """An import or file error: the install itself is short of a file, which an update of Strata brings back.""" return failure.startswith(("ModuleNotFoundError", "ImportError", "FileNotFoundError")) @@ -99,6 +109,7 @@ def setup_failure(lines: list[str], err: str, hint: str, details: str | None, ow """The error for a setup.py run that exited non-zero. setup.py's own `[X]` line (err) is the message when there is one; when it stopped with a Python error instead, that error's last line is (#3613, #3467: a file missing from the Terminal's tools/ ended every launch after a tune with only "The model could not be installed"). `details` is the file that holds the rest of its output.""" + err = err or argparse_failure(lines) crashed = python_failure(lines) if not err else None if crashed: where = f" The whole setup output is in {details}." if details else "" diff --git a/tests/terminal/test_setup_failure_words.py b/tests/terminal/test_setup_failure_words.py index 1cf70ec6..7d111714 100644 --- a/tests/terminal/test_setup_failure_words.py +++ b/tests/terminal/test_setup_failure_words.py @@ -18,6 +18,20 @@ TRACEBACK = [ class SetupFailureWords(unittest.TestCase): + def test_an_option_setup_refuses_is_said_with_its_reason(self): # #3785 + lines = ["Preparing unsloth UD-Q6_K_XL from your model files...", + "setup.py: error: argument --kv: invalid choice: 'bf16' (choose from int8, q4_0, k8v4, fp16)"] + error = setup_failure(lines, "", "", "/tmp/a.setup.log", True) + self.assertIn("The model could not be installed. Argument --kv: invalid choice: 'bf16'", error.text) + self.assertIn("/tmp/a.setup.log", error.next) + self.assertEqual(setup_failure(["nothing useful"], "", "", None, True).text, "The model could not be installed.") + + def test_setup_accepts_the_kv_format_the_docker_docs_offer(self): + import subprocess, sys + root = Path(__file__).resolve().parents[2] + done = subprocess.run([sys.executable, str(root / "setup.py"), "--kv", "bogus"], capture_output=True, text=True, cwd=str(root), timeout=120) + self.assertIn("choose from int8, q4_0, k8v4, fp16", done.stderr) + def test_the_last_line_of_a_traceback_is_found(self): self.assertEqual(python_failure(TRACEBACK), "ModuleNotFoundError: No module named 'calibrate'") self.assertIsNone(python_failure(["[X] Not enough disk space", " Free some space"])) From d924beffe5ae2dcc6c981f4fea10dc1d00233f50 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 24 Oct 2026 13:06:00 +0200 Subject: [PATCH 04/22] setup: a Mac with an Intel (Rosetta) Python is still an Apple Silicon Mac; the chip name and hw.optional.arm64 decide, one plain line says the Python is an Intel build (#3894); test --- setup.py | 3 +++ strata_control/mac_fit.py | 6 +++++- tools/test_setup_mac.py | 7 +++++++ 3 files changed, 15 insertions(+), 1 deletion(-) diff --git a/setup.py b/setup.py index f3689cac..d65c1608 100644 --- a/setup.py +++ b/setup.py @@ -8249,6 +8249,9 @@ def mac_control_setup(a) -> int: info = MF.mac_info() ram = float(info["ram_gb"] or ram_gb()) ok(f"{info['chip']}, {ram:.0f} GB unified memory, macOS {info['macos'] or '?'}") + if info.get("rosetta_python"): + say(" (the Python that runs this is an Intel build running through Rosetta: Strata works, and the Apple Silicon Python " + "from python.org or Homebrew in /opt/homebrew is a little faster to start)") problems = MF.mac_problems(info, need_compiler=False) # the app compiles nothing: no Command Line Tools needed for p in problems: warn(p) diff --git a/strata_control/mac_fit.py b/strata_control/mac_fit.py index 68a7b106..a273c741 100644 --- a/strata_control/mac_fit.py +++ b/strata_control/mac_fit.py @@ -94,7 +94,11 @@ def mac_info(run=subprocess.run) -> dict: clt_path = clt.stdout.strip() if clt.returncode == 0 else "" except (OSError, subprocess.SubprocessError): clt_path = "" - return {"chip": chip, "ram_gb": ram, "macos": ver, "arm64": platform.machine() == "arm64", + # platform.machine() is the PYTHON's build: an Intel Python running through Rosetta says x86_64 on an M1 Max (#3894). The chip name + # (Rosetta passes "Apple M1 Max" through) and hw.optional.arm64 say what the Mac is. + python_arm = platform.machine() == "arm64" + mac_arm = python_arm or _sysctl("hw.optional.arm64", run) == "1" or chip.startswith("Apple") + return {"chip": chip, "ram_gb": ram, "macos": ver, "arm64": mac_arm, "rosetta_python": mac_arm and not python_arm, "clt": clt_path, "perf_cores": int(_sysctl("hw.perflevel0.physicalcpu", run) or 0)} diff --git a/tools/test_setup_mac.py b/tools/test_setup_mac.py index fd0b5a95..92f2a596 100644 --- a/tools/test_setup_mac.py +++ b/tools/test_setup_mac.py @@ -49,6 +49,13 @@ class MacCheck(unittest.TestCase): self.assertTrue(info["clt"]) self.assertEqual(M.mac_problems(info), []) + def test_an_intel_python_on_apple_silicon_is_still_an_apple_silicon_mac(self): # #3894 + with mock.patch.object(M.platform, "machine", return_value="x86_64"): + info = M.mac_info(fake_run({**M5, "machdep.cpu.brand_string": "Apple M1 Max"})) + self.assertTrue(info["arm64"]) + self.assertTrue(info["rosetta_python"]) + self.assertNotIn("Intel", " ".join(M.mac_problems(info))) + def test_intel_old_macos_and_missing_tools_are_named(self): with mock.patch.object(M.platform, "machine", return_value="x86_64"): info = M.mac_info(fake_run({**M5, "macos": "14.6", "machdep.cpu.brand_string": "Intel Core i9"}, clt_rc=2)) From 7a03fc9414254327504b6390a06203acf84838cd Mon Sep 17 00:00:00 2001 From: demetree Date: Thu, 22 Oct 2026 09:43:42 -0230 Subject: [PATCH 05/22] strata connect: scale the app configs' compaction point with the server's context --- strata_cli/launch/harness.py | 29 +++++++++++++++++++++-------- tests/terminal/test_launch.py | 14 +++++++++++++- 2 files changed, 34 insertions(+), 9 deletions(-) diff --git a/strata_cli/launch/harness.py b/strata_cli/launch/harness.py index 5f9379c1..dc4e2de9 100644 --- a/strata_cli/launch/harness.py +++ b/strata_cli/launch/harness.py @@ -21,7 +21,8 @@ from typing import Callable PLACEHOLDER_KEY = "strata-local" # the tested configs' placeholder when the server has no key (not a secret) OUTPUT_CAP = 4096 # the output cap every tested config used -COMPACT_AT = 15000 # where the tested configs make the app compact its conversation +TESTED_CONTEXT = 32768 # the window every config below was tested on +COMPACT_AT = 15000 # and where those tested configs make the app compact its conversation @dataclass @@ -42,6 +43,17 @@ class Target: return max(1024, self.context - OUTPUT_CAP) +def compact_at(t: Target) -> int: + """Where the app should compact its conversation: the share of the input limit the tested configs used, so that the + summarising request (which carries the whole conversation) still fits the window. + + A flat 15,000 summarises a wider server every 15,000 tokens - 6% of a 256K window - while the tested configs compact + a 32K server at 52% of its input limit. The share is what carries over, not the number: a 32K server keeps exactly + the value it was tested at.""" + tested_limit = TESTED_CONTEXT - OUTPUT_CAP + return max(COMPACT_AT, int(t.input_limit * COMPACT_AT / tested_limit)) + + @dataclass class FileSpec: path: str # may start with ~ @@ -80,7 +92,7 @@ def _j(obj) -> str: def opencode_file(t: Target) -> str: return _j({"$schema": "https://opencode.ai/config.json", "model": f"strata/{t.model}", "small_model": f"strata/{t.model}", "autoupdate": False, - "compaction": {"auto": True, "buffer": max(1024, t.input_limit - COMPACT_AT)}, + "compaction": {"auto": True, "buffer": max(1024, t.input_limit - compact_at(t))}, "share": "disabled", "provider": {"strata": {"npm": "@ai-sdk/openai-compatible", "name": "Strata (local)", "options": {"baseURL": t.base, "apiKey": t.key}, @@ -90,7 +102,7 @@ def opencode_file(t: Target) -> str: def codex_file(t: Target) -> str: return (f'model = "{t.model}"\nmodel_provider = "strata"\nmodel_context_window = {t.context}\n' - f"model_auto_compact_token_limit = {COMPACT_AT}\nmodel_reasoning_summary = \"auto\"\napproval_policy = \"never\"\n" + f"model_auto_compact_token_limit = {compact_at(t)}\nmodel_reasoning_summary = \"auto\"\napproval_policy = \"never\"\n" 'sandbox_mode = "workspace-write"\ncheck_for_update_on_startup = false\n\n[model_providers.strata]\n' f'name = "Strata (local)"\nbase_url = "{t.base}"\nwire_api = "responses"\nenv_key = "STRATA_API_KEY"\n' "stream_idle_timeout_ms = 600000\n") @@ -118,7 +130,7 @@ def omp_models(t: Target) -> str: def omp_config(t: Target) -> str: return ("modelRoles:\n default: strata/" + t.model + "\ndefaultThinkingLevel: medium\ncompaction:\n enabled: true\n thresholdTokens: " - + str(COMPACT_AT) + "\n keepRecentTokens: 4000\n methodOrder:\n - soft\n idleEnabled: false\nsetupVersion: 2\n") + + str(compact_at(t)) + "\n keepRecentTokens: 4000\n methodOrder:\n - soft\n idleEnabled: false\nsetupVersion: 2\n") def pi_models(t: Target) -> str: @@ -131,12 +143,12 @@ def pi_models(t: Target) -> str: def pi_settings(t: Target) -> str: return _j({"defaultProvider": "strata", "defaultModel": t.model, "defaultThinkingLevel": "medium", - "compaction": {"enabled": True, "reserveTokens": max(1024, t.context - COMPACT_AT), "keepRecentTokens": 4000}}) + "compaction": {"enabled": True, "reserveTokens": max(1024, t.context - compact_at(t)), "keepRecentTokens": 4000}}) def hermes_file(t: Target) -> str: return ("model:\n default: " + t.model + "\n provider: lmstudio\n base_url: " + t.base + "\n context_length: " + str(t.context) + - "\ncompression:\n enabled: true\n threshold_tokens: " + str(COMPACT_AT) + "\nauxiliary:\n compression:\n context_length: 65536\n") + "\ncompression:\n enabled: true\n threshold_tokens: " + str(compact_at(t)) + "\nauxiliary:\n compression:\n context_length: 65536\n") def openclaw_file(t: Target) -> str: @@ -181,14 +193,15 @@ def _limits_omp(t: Target) -> list[str]: def _limits_pi(t: Target) -> list[str]: return ["pi has the smallest prompt of the eight (1.5K tokens): the most room for the conversation.", - "It compacts after the turn that crosses the line, so one turn can reach about 15K tokens before it summarises."] + "It compacts after the turn that crosses the line, so one turn can reach about %dK tokens before it summarises." + % round(compact_at(t) / 1000)] def _limits_hermes(t: Target) -> list[str]: out = ["Hermes refuses a window under 64,000 tokens unless the provider is lmstudio with an explicit context_length: the config uses " "that, and auxiliary.compression.context_length 65536 for its summariser (the same floor).", "Its system prompt and 20 tools take about 12.9K tokens (40% of a 32K window): about 19K is left for the conversation.", - "Its compaction threshold is floored at its own 64K minimum, so it compacts later than 15K (around 20K); it still fits 32K."] + "Its own 64K minimum floors the compaction threshold, so it compacts later than the value above (around 20K on a 32K window); it still fits 32K."] if t.context < 65536: out.insert(0, "WARNING: Hermes is built for 64K or more. At %dK it works only through the workaround above." % (t.context // 1024)) return out diff --git a/tests/terminal/test_launch.py b/tests/terminal/test_launch.py index 8093ef4f..ff217d2d 100644 --- a/tests/terminal/test_launch.py +++ b/tests/terminal/test_launch.py @@ -1236,7 +1236,19 @@ class ConnectCommand(unittest.TestCase): def test_context_flag_reaches_the_config(self): code, out, _ = run_cli(["connect", "pi", "--url", "http://127.0.0.1:8080", "--context", "64k", "--show-key"]) self.assertIn('"contextWindow": 65536', out) - self.assertIn('"reserveTokens": 50536', out) + self.assertIn('"reserveTokens": 33394', out) # 65536 - 32142: the tested 52.3% share, not a flat 15K + + def test_the_compaction_point_scales_with_the_window(self): + """A wider server must not be summarised every 15,000 tokens: the share the tested 32K configs used carries over.""" + wide = harness.target("http://127.0.0.1:18900", None, "qwen3.8-flash-next-q2_0", 262144) + self.assertEqual(harness.compact_at(wide), 135000) # 52.3% of the 258048 input limit + cfg = json.loads(self.render("opencode", context=262144)["files"][0]["text"]) + self.assertEqual(wide.input_limit - cfg["compaction"]["buffer"], 135000) + self.assertIn("model_auto_compact_token_limit = 135000", self.render("codex", context=262144)["files"][0]["text"]) + self.assertIn("thresholdTokens: 135000", self.render("omp", context=262144)["files"][1]["text"]) + # the window every config was tested on keeps exactly the value it was tested at + tested = harness.target("http://127.0.0.1:18900", None, "qwen3.8-flash-next-q2_0", 32768) + self.assertEqual(harness.compact_at(tested), 15000) class GpuRolesFlag(unittest.TestCase): From c02a0b8b0d8f1327ee089174436224dcdf041148 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 24 Oct 2026 13:08:46 +0200 Subject: [PATCH 06/22] UPDATE.bat / update.sh: an engine that stayed older than the minimum is said as 'the engine was NOT updated' with one next step, not '[ok] Strata is updated' (#3653); test --- setup.py | 9 ++++++++- tools/test_setup_update.py | 12 ++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/setup.py b/setup.py index d65c1608..e44a9c3b 100644 --- a/setup.py +++ b/setup.py @@ -6707,8 +6707,15 @@ def update_install(have: list, a) -> int: ok(f"{cfg.get('model_name', cfg_path.stem)}: up to date") ver = engine_version(Path(json.loads(have[0].read_text(encoding="utf-8-sig"))["exe"])) say() + start = "START-HERE.bat" if WIN else "./setup.sh" + if any(ver) and tuple(ver) < MIN_ENGINE: # #3653: the engine step failed above; "updated" would be untrue + warn(f"Strata's files are updated, but the engine was NOT: it is still {'.'.join(map(str, ver))} and this Strata wants " + f"{'.'.join(map(str, MIN_ENGINE))} or newer. The model still starts with the old engine.") + say(f" Next step: check the internet connection (and that the model window is closed), then run {'UPDATE.bat' if WIN else './update.sh'} again; " + "the line above this one says why the engine was not fetched.") + return 0 ok("Strata is updated" + (f" (engine {'.'.join(map(str, ver))})" if any(ver) else "") + - ". Start the model with " + ("START-HERE.bat" if WIN else "./setup.sh") + " when you want it.") + f". Start the model with {start} when you want it.") return 0 diff --git a/tools/test_setup_update.py b/tools/test_setup_update.py index 12b1026e..bebac3b3 100644 --- a/tools/test_setup_update.py +++ b/tools/test_setup_update.py @@ -54,6 +54,18 @@ class Update(unittest.TestCase): call.assert_not_called() self.assertIn("Strata is updated", out) + def test_an_engine_that_stayed_old_is_not_called_updated(self): # #3653 + with tempfile.TemporaryDirectory() as d: + p = self.config(Path(d)) + with mock.patch.object(setup, "engine_version", return_value=(0, 1, 44, 1)): + rc, pip, eng, dv, start, call, out = self.run_update([p]) + self.assertIn("the engine was NOT", out) + self.assertIn("Next step:", out) + self.assertNotIn("[ok] Strata is updated", out) + with mock.patch.object(setup, "engine_version", return_value=(0, 1, 49, 2)): + rc, pip, eng, dv, start, call, out = self.run_update([p]) + self.assertIn("Strata is updated (engine 0.1.49.2)", out) + def test_build_keeps_the_compiled_engine_path(self): with tempfile.TemporaryDirectory() as d: p = self.config(Path(d)) From ad9bb57ddcc345b0db56e13a0448563005fee0f1 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 24 Oct 2026 13:27:08 +0200 Subject: [PATCH 07/22] own model files: a qwen4exp file set that is no tested build but has the layout of one is used as that model with a plain notice, and setup keeps a complete GGUF of another size or hash with a warning instead of stopping (#3651 #3777); tests --- setup.py | 19 +++++++++++++++++++ strata_control/models.py | 32 ++++++++++++++++++++++++++++++++ tests/terminal/test_discovery.py | 19 +++++++++++++++++++ tools/test_setup_ownfiles.py | 16 ++++++++++++++++ 4 files changed, 86 insertions(+) diff --git a/setup.py b/setup.py index e44a9c3b..40793db7 100644 --- a/setup.py +++ b/setup.py @@ -2978,6 +2978,16 @@ def _hash_file(s: Path, size: int) -> str: return h.hexdigest() +def own_gguf_is_whole(path: Path) -> bool: + """The person's own GGUF reads as a whole file: its header parses and every tensor lies inside the file (a cut-short copy fails this).""" + try: + from strata_control import gguf_preflight + gguf_preflight.inspect_metadata(Path(path)) + return True + except Exception: # noqa: BLE001 - anything unreadable is "not whole" + return False + + def verify_sha256(s: Path, size: int, sha: str, own: bool = False, repair=None) -> None: """A shard's size and SHA-256 against the pinned values (the Unsloth file); the result is kept in its finish mark, so the ~5 minutes of hashing 111 GB happen once. A wrong file is deleted, so the next run downloads it again. @@ -2987,6 +2997,11 @@ def verify_sha256(s: Path, size: int, sha: str, own: bool = False, repair=None) if m.exists() and f"sha256 {sha}" in m.read_text(encoding="utf-8", errors="replace"): return have = s.stat().st_size if s.exists() else -1 + if own and have > 0 and have != size and own_gguf_is_whole(s): + # a fine-tune or another build with the layout of the published file (#3777: 96 bytes apart): recommend, never refuse + warn(f"{s.name} is {have:,} bytes; the published file is {size:,}. It is a complete GGUF file, so Strata uses it as it is; " + "it may be another version or a fine-tune, so check a few answers before you rely on it") + return if have != size: if own: # --gguf-dir: the person's own file is never deleted by setup fail(f"{s.name} is {have:,} bytes; the published file is {size:,}", @@ -3003,6 +3018,10 @@ def verify_sha256(s: Path, size: int, sha: str, own: bool = False, repair=None) else: say(" The damaged parts could not be found this way.") if digest != sha: + if own and own_gguf_is_whole(s): + warn(f"{s.name} is not the published file (SHA-256 {digest[:12]}..., expected {sha[:12]}...) but it is a complete GGUF file, so " + "Strata uses it as it is; it may be another version or a fine-tune, so check a few answers before you rely on it") + return if own: fail(f"{s.name} does not match the published file (SHA-256 {digest}, expected {sha})", "it may be damaged or another version; your file was left as it is. Copy the whole published file into the folder") diff --git a/strata_control/models.py b/strata_control/models.py index 263c2318..eed87046 100644 --- a/strata_control/models.py +++ b/strata_control/models.py @@ -294,6 +294,33 @@ def _candidate_by_header(shards: list[Path], tensors: int, payload: int, experts return None +def _candidate_by_layout(shards: list[Path], tensors: int, payload: int, experts: set[str]) -> dict | None: + """A qwen4exp file set that is no build Strata has tested (a fine-tune, a K-quant mix from another maker) but has the layout of one + (#3651 #3777): the closest row by expert formats, then by size. Strata uses the files as that model and says so; it never refuses a + working file for not being on the list (recommend, never force).""" + try: + catalog = json.loads((ROOT / "data" / "gguf_fingerprints.json").read_text(encoding="utf-8")) + except (OSError, UnicodeError, ValueError): + return None + best = None + for selection in sorted(SUPPORTED_SELECTIONS): + row = catalog.get(selection) if isinstance(catalog, dict) else None + if not isinstance(row, dict) or row.get("tensors") != tensors or not isinstance(row.get("expert_bytes"), dict): + continue + have = set(row["expert_bytes"]) + union = have | experts + score = (len(have & experts) / len(union)) if union else 0.0 + key = (-score, abs(int(row.get("bytes") or 0) - payload), selection) + if score > 0 and (best is None or key < best[0]): + best = (key, selection, have) + if best is None: + return None + family, model = best[1].split("/", 1) + return {"family": family, "model": model, "basis": "same_layout_other_build", + "expected_expert_types": sorted(best[2] | experts), "expected_tensor_count": tensors, + "setup_args_hint": ["--family", family, "--model", model, "--gguf-dir", str(shards[0].parent)]} + + def _already_set_up(shards: list[Path], candidate: dict | None) -> dict | None: """Is this model already installed (a run config of any known install names the file) and what was prepared beside it (pack, draft layer, picture reader)? Read-only; None when the file set is not one Strata knows.""" @@ -709,6 +736,11 @@ def plan_import(raw_path: str) -> dict: candidate = _candidate_selection(shards) if candidate is None and metadata is not None and not issues: candidate = _candidate_by_header(shards, observed_tensor_count, observed_payload, observed_experts) + if candidate is None: + candidate = _candidate_by_layout(shards, observed_tensor_count, observed_payload, observed_experts) + if candidate is not None: + messages.append(f"These files are not exactly a build Strata has tested; they have the layout of {candidate['family']} " + f"{candidate['model']}, so Strata uses them as that model. Check a few answers before you rely on them.") if "multiple_model_groups" in issues: candidate = None # nothing is chosen for the person if candidate is None and not {"multiple_model_groups", "incomplete_or_invalid_shard_set"} & set(issues): diff --git a/tests/terminal/test_discovery.py b/tests/terminal/test_discovery.py index 7ea7efca..98cd13c3 100644 --- a/tests/terminal/test_discovery.py +++ b/tests/terminal/test_discovery.py @@ -229,6 +229,25 @@ class GuiLayout(unittest.TestCase): self.assertEqual(plan["candidate_selection"]["model"], "Gyro-S") self.assertEqual(payload, 124) + def test_a_fine_tune_with_the_layout_of_a_known_build_is_used_not_refused(self): # #3651 #3777 + folder = self.base / "finetune" + folder.mkdir() + (folder / "Qwen3.8-Flash-Next-Gyro-S-abliterated-TQ1_0.gguf").write_bytes(gyro_s_bytes()) + fake_root = self.base / "fake-root2" + (fake_root / "data").mkdir(parents=True) + table = {"gyro/Gyro-S": {"arch": "qwen4exp", "tensors": 2, "bytes": 999_999, "expert_bytes": {"TQK6": 52, "TQK7": 60}, + "files": [GYRO_S], "repo": "x"}, + "gyro/Gyro-M": {"arch": "qwen4exp", "tensors": 2, "bytes": 888_888, "expert_bytes": {"TQ2_T": 40}, + "files": [GYRO_S], "repo": "x"}} + (fake_root / "data" / "gguf_fingerprints.json").write_text(json.dumps(table)) + with mock.patch.object(models, "ROOT", fake_root): + plan = models.plan_import(str(folder)) + self.assertEqual(plan["issues"], []) + self.assertEqual(plan["candidate_selection"]["basis"], "same_layout_other_build") + self.assertEqual(plan["candidate_selection"]["model"], "Gyro-S") # the closest by expert formats + self.assertTrue(any("not exactly a build Strata has tested" in m for m in plan["messages"])) + self.assertIn("unrecognized_or_unsupported_model_variant", models.plan_import(str(folder))["issues"]) # the real table has 1224 tensors + # ---- T05: where it is, what is missing def test_the_folder_defaults_to_where_the_model_is(self): cat = self.catalog() diff --git a/tools/test_setup_ownfiles.py b/tools/test_setup_ownfiles.py index 9d799d50..eeb82fef 100644 --- a/tools/test_setup_ownfiles.py +++ b/tools/test_setup_ownfiles.py @@ -59,6 +59,22 @@ class OwnFileChecks(unittest.TestCase): self.assertEqual(code, 1) self.assertFalse(self.file.exists()) + def test_a_complete_own_gguf_of_another_size_or_hash_is_used_with_a_warning(self): # #3777 + from tests.terminal.test_own_files import gguf_bytes + gguf = Path(self.tmp.name) / "fine-tune.gguf" + gguf.write_bytes(gguf_bytes(["Q8_0"])) + for size, sha in ((gguf.stat().st_size + 96, "0" * 64), (gguf.stat().st_size, "0" * 64)): + code, text = run(setup.verify_sha256, gguf, size, sha, own=True) + self.assertEqual(code, 0, text) + self.assertIn("Strata uses it as it is", text) + cut = Path(self.tmp.name) / "cut.gguf" + cut.write_bytes(gguf.read_bytes()[:-40]) # cut short: the tensor payload is not all there + code, text = run(setup.verify_sha256, cut, gguf.stat().st_size, "0" * 64, own=True) + self.assertEqual(code, 1) + self.assertIn("your file was left as it is", text) + code, text = run(setup.verify_sha256, gguf, gguf.stat().st_size + 96, "0" * 64) # a download is still checked + self.assertEqual(code, 1) + def test_a_matching_own_file_passes(self): code, _text = run(setup.verify_sha256, self.file, 800, self.sha, own=True) self.assertEqual(code, 0) From 5bfce4bea06306ab1bbccc628ab2245809523bf5 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 24 Oct 2026 13:28:02 +0200 Subject: [PATCH 08/22] setup: the build tools come from the virtualenv first and an older system cmake (below the 3.24 CMakeLists.txt needs) counts as missing, so pip installs the right one (#3822); tests --- setup.py | 64 +++++++++++++++++++++++++--------- tools/test_setup_find_tool.py | 65 +++++++++++++++++++++++++++++++++++ tools/test_setup_pins.py | 1 + 3 files changed, 114 insertions(+), 16 deletions(-) create mode 100644 tools/test_setup_find_tool.py diff --git a/setup.py b/setup.py index 40793db7..432de323 100644 --- a/setup.py +++ b/setup.py @@ -2100,22 +2100,43 @@ def find_vcvars(cuda_v=None): return v if v and v.exists() else None +CMAKE_MIN = (3, 24) # CMakeLists.txt: cmake_minimum_required(VERSION 3.24) + + +def _tool_version(path, name): + """(ok, version tuple) of `path --version`: ok False when it does not run (a pip launcher whose Python is gone).""" + try: + done = subprocess.run([path, "--version"], capture_output=True, text=True, timeout=30) + except (OSError, subprocess.SubprocessError): + return False, () + if done.returncode != 0: + return False, () + found = re.search(r"(\d+)\.(\d+)(?:\.(\d+))?", done.stdout or "") + return True, tuple(int(x) for x in found.groups() if x) if found else () + + def find_tool(name): - """A tool on PATH, or the one pip installed next to this Python (cmake, ninja). A PATH copy that does not run - (a pip launcher whose Python is gone) is skipped for the one next to this Python.""" - p = shutil.which(name) - if p: - try: - if subprocess.run([p, "--version"], capture_output=True, timeout=30).returncode == 0: - return p - except (OSError, subprocess.SubprocessError): - pass - for d in (Path(sys.executable).parent / "Scripts", Path(sys.executable).parent, - Path.home() / ".local" / "bin"): - c = d / (name + (".exe" if WIN else "")) - if c.exists(): - return str(c) - return None + """The tool the build uses (cmake, ninja): the one pip installed next to THIS Python first (the virtualenv's own, #3822), then PATH, + then ~/.local/bin. One that does not run (a pip launcher whose Python is gone) is skipped, and so is a cmake older than the + one CMakeLists.txt needs while another is found; with only an older one it is returned and the build says so.""" + exe = name + (".exe" if WIN else "") + candidates = [str(d / exe) for d in (Path(sys.executable).parent / "Scripts", Path(sys.executable).parent) if (d / exe).exists()] + on_path = shutil.which(name) + if on_path and on_path not in candidates: + candidates.append(on_path) + local = Path.home() / ".local" / "bin" / exe + if local.exists() and str(local) not in candidates: + candidates.append(str(local)) + older = None + for c in candidates: + runs, version = _tool_version(c, name) + if not runs: + continue + if name == "cmake" and version and version[:2] < CMAKE_MIN: + older = older or c + continue + return c + return older def free_gb(path): @@ -5483,13 +5504,24 @@ def install_build_tools(gpu, yes): return nvcc, find_vcvars(cuda_v) if WIN else None +def tool_usable(name): + """find_tool found one that runs and (cmake) is new enough: an older system cmake counts as missing, so pip puts the right one in the venv.""" + found = find_tool(name) + if found is None: + return False + if name == "cmake": + runs, version = _tool_version(found, name) + return runs and (not version or version[:2] >= CMAKE_MIN) + return True + + def ensure_build_tools(): """cmake and ninja for a local compile, installed from requirements-build.txt when missing (#3403: the Mac setup compiles without cmake_build(), so it calls this too). Returns (cmake, ninja).""" # The ready-made engine path never calls this function. Keep build helpers out of # the normal serving environment, and use already installed tools offline. build_packages = requirement_lines(BUILD_REQUIREMENTS) if BUILD_REQUIREMENTS.exists() else BUILD_PACKAGES - missing = [package for package in build_packages if find_tool(req_name(package)) is None] + missing = [package for package in build_packages if not tool_usable(req_name(package))] if missing: pip_install(missing, "CMake and Ninja build tools") cmake, ninja = find_tool("cmake"), find_tool("ninja") diff --git a/tools/test_setup_find_tool.py b/tools/test_setup_find_tool.py new file mode 100644 index 00000000..419efa7a --- /dev/null +++ b/tools/test_setup_find_tool.py @@ -0,0 +1,65 @@ +"""setup.find_tool takes the virtualenv's own cmake before a PATH one and skips a cmake older than CMakeLists.txt needs (#3822). + + python -m unittest tools.test_setup_find_tool +""" +from __future__ import annotations + +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 + + +class FindTool(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.bin = Path(self.tmp.name) / "venv" / "bin" + self.bin.mkdir(parents=True) + self.venv_python = self.bin / "python" + + def versions(self, table): + return lambda path, name: table.get(str(path), (False, ())) + + def venv_tool(self, name="cmake"): + return str(self.bin / (name + (".exe" if setup.WIN else ""))) + + def find(self, table, on_path, name="cmake", venv_copy=True): + if venv_copy: + Path(self.venv_tool(name)).write_text("x") + with mock.patch.object(setup.sys, "executable", str(self.venv_python)), \ + mock.patch.object(setup.shutil, "which", return_value=on_path), \ + mock.patch.object(setup, "_tool_version", side_effect=self.versions(table)), \ + mock.patch.object(setup.Path, "home", return_value=Path(self.tmp.name) / "home"): + return setup.find_tool(name), setup.tool_usable(name) + + def test_the_virtualenv_copy_wins_over_an_old_system_cmake(self): + got, usable = self.find({"/usr/bin/cmake": (True, (3, 22, 1)), self.venv_tool(): (True, (4, 1, 0))}, "/usr/bin/cmake") + self.assertEqual(got, self.venv_tool()) + self.assertTrue(usable) + + def test_an_old_cmake_on_its_own_is_returned_but_not_usable(self): + got, usable = self.find({"/usr/bin/cmake": (True, (3, 22, 1))}, "/usr/bin/cmake", venv_copy=False) + self.assertEqual(got, "/usr/bin/cmake") # the build would say "CMake 3.24 or higher is required" + self.assertFalse(usable) # so setup installs the pip cmake first + + def test_a_new_enough_system_cmake_is_fine_without_a_venv_one(self): + got, usable = self.find({"/usr/bin/cmake": (True, (3, 28, 3))}, "/usr/bin/cmake", venv_copy=False) + self.assertEqual((got, usable), ("/usr/bin/cmake", True)) + + def test_ninja_has_no_version_floor(self): + got, usable = self.find({"/usr/bin/ninja": (True, (1, 10))}, "/usr/bin/ninja", "ninja", venv_copy=False) + self.assertTrue(usable) + + def test_a_launcher_that_does_not_run_is_skipped(self): + got, _ = self.find({self.venv_tool(): (False, ()), "/usr/bin/cmake": (True, (3, 30, 0))}, "/usr/bin/cmake") + self.assertEqual(got, "/usr/bin/cmake") + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/test_setup_pins.py b/tools/test_setup_pins.py index 83d73fb2..052c9a97 100644 --- a/tools/test_setup_pins.py +++ b/tools/test_setup_pins.py @@ -378,6 +378,7 @@ class Requirements(unittest.TestCase): with mock.patch.object(setup, "WIN", False), \ mock.patch.object(setup, "find_tool", side_effect=find_tool), \ + mock.patch.object(setup, "_tool_version", return_value=(True, (3, 28, 1))), \ mock.patch.object(setup, "pip_install", side_effect=pip_install), \ mock.patch.object(setup, "run", side_effect=run): setup.cmake_build(ROOT, ROOT / "build-test", "strata", [], None, "unused.bat") From 77284b5e336dba4f6265db2b1193031092f02128 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 24 Oct 2026 13:32:44 +0200 Subject: [PATCH 09/22] update: the test start runs the new engine with a short context and no picture reader (#3842), and an update keeps the CUDA build that runs here (#3835); launch: the summary names the engine log (#3656) and a tuned model says how to measure again (#3874); tests --- strata_cli/launch/cmd.py | 12 +++++++++++ strata_cli/launch/runner.py | 4 ++-- strata_control/feed.py | 8 +++++++ strata_control/updater.py | 34 +++++++++++++++++++++++++++++- tests/terminal/test_flow2_022.py | 1 + tests/terminal/test_launch.py | 13 ++++++++++++ tests/terminal/test_update_feed.py | 10 +++++++++ tests/terminal/test_updater.py | 11 ++++++++++ 8 files changed, 90 insertions(+), 3 deletions(-) diff --git a/strata_cli/launch/cmd.py b/strata_cli/launch/cmd.py index 697e99d7..8df981b9 100644 --- a/strata_cli/launch/cmd.py +++ b/strata_cli/launch/cmd.py @@ -413,6 +413,15 @@ def gpu_notices(s: S.LaunchSettings, comp) -> list[S.Notice]: # ------------------------------------------------------------------------------------------------ plain-text run +def _engine_log_of(config) -> str: + """Where this launch writes the engine's log (#3656): the config's own "log", printed so a failure can be read without a search.""" + try: + from strata_cli.launch.runner import read_config + return str(read_config(Path(config)).get("log") or "") + except (OSError, ValueError, TypeError): + return "" + + def _say(line: str = "") -> None: sys.stdout.write(line + "\n") sys.stdout.flush() @@ -815,6 +824,9 @@ def run_launch(a: argparse.Namespace) -> int: from strata_cli.launch import access _say(f" {'API key':<14} {access.mask_key(result.key)} (show it: strata launch --show-key" + (f" --preset \"{s.name}\")" if (a.preset or a.save_preset) else ")")) + engine_log = _engine_log_of(result.config) + if engine_log: + _say(f" {'Engine log':<14} {engine_log} (follow it: strata logs --follow)") for n in result.notices: _say(f"[!] {n}") local = next((u for u in result.urls if "127.0.0.1" in u), result.urls[0] if result.urls else "") diff --git a/strata_cli/launch/runner.py b/strata_cli/launch/runner.py index e02a2032..032e2117 100644 --- a/strata_cli/launch/runner.py +++ b/strata_cli/launch/runner.py @@ -1345,12 +1345,12 @@ class Runner: if s.tuned_preset: try: presets.find(s.tuned_preset) - self.emit("tune", "This preset is already tuned for this computer.", 100) + self.emit("tune", "This preset is already tuned for this computer. Add --retune to measure again.", 100) return except presets.PresetError: pass elif s.tuned_at: # measured before: the standard settings were already the fastest, nothing was saved - self.emit("tune", f"Already tuned on {s.tuned_at}: this computer runs best with the standard settings. Nothing to do.", 100) + self.emit("tune", f"Already tuned on {s.tuned_at}: this computer runs best with the standard settings. Nothing to do; add --retune to measure again.", 100) return stored = self.stored_tuning() if stored: # the same model and choices were tuned on this computer before (a run by flags, no preset) diff --git a/strata_control/feed.py b/strata_control/feed.py index da2c08b3..ddbdaafe 100644 --- a/strata_control/feed.py +++ b/strata_control/feed.py @@ -413,6 +413,14 @@ def select_engine(packages, hardware: dict) -> tuple[EnginePackage | None, list[ return None, reasons best = max(fitting, key=lambda p: (version_key(p.version), ec._version_key(p.min_driver.get("nvidia", "0")), ec.hip_preference(p.archs) if p.backend == "hip" else 1)) + kept = str(hardware.get("installed_variant") or "") + if best.backend == "cuda" and kept and best.variant != kept: + # An update never switches the CUDA build (#3835): a model on the CUDA 12 engine (its card is one CUDA 13 has no code for) must not + # be given CUDA 13 because ANOTHER card in the PC fits it. The same version of the build that runs here is kept when the feed has it. + same = [p for p in fitting if p.backend == "cuda" and p.variant == kept and version_key(p.version) == version_key(best.version)] + if same: + reasons.append(f"the installed {kept} build is kept; {best.variant} would also fit another card in this PC") + best = same[0] return best, reasons diff --git a/strata_control/updater.py b/strata_control/updater.py index d2a8548a..a1f17bbb 100644 --- a/strata_control/updater.py +++ b/strata_control/updater.py @@ -571,7 +571,7 @@ def _choose_engine(feed: feedmod.Feed, ctx: Context, state: State) -> tuple[dict "download_bytes": 0, "previous": state.section("engine").get("previous"), "pinned": state.section("engine").get("pinned"), "problem": None}, None installed, missing_reason = installed_engine(ctx.components, ctx.hardware) - sticky = {**ctx.hardware, "installed_variant": installed.variant if installed is not None and installed.backend == "hip" else ""} + sticky = {**ctx.hardware, "installed_variant": installed.variant if installed is not None and installed.backend in ("hip", "cuda") else ""} offered, reasons = feedmod.select_engine([p for p in feed.engine], sticky) section = state.section("engine") report = {"installed": _engine_view(installed), "offered": offered.to_dict() if offered else None, @@ -839,6 +839,36 @@ def _test_start_failure(component: ec.EngineComponent, started: dict, ctx: Conte return TestStartFailed(component.version, f"it did not answer a one-token probe ({error or started.get('state')}){tail}") +TEST_CONTEXT = 4096 +_TEST_DROP_WITH_VALUE = ("--kv-resident", "--vision-tokens") +_TEST_DROP_FLAGS = ("--vision",) + + +def light_test_args(args: list) -> list: + """The saved model's engine options made light for the test start (#3842): a short context, no KV kept in VRAM and no picture reader. The + test asks whether the NEW engine loads and answers one token, not whether this card holds the model's 262,144-token settings next to the + desktop and the running model; a 16 GB card refused good engines with 'out of memory' at the first weight upload.""" + out, i = [], 0 + values = [str(x) for x in args] + while i < len(values): + item = values[i] + nxt = values[i + 1] if i + 1 < len(values) else None + if item == "--max-context" and nxt is not None: + try: + out += [item, str(min(int(nxt), TEST_CONTEXT))] + except ValueError: + out += [item, nxt] + i += 2 + elif item in _TEST_DROP_WITH_VALUE and nxt is not None: + i += 2 + elif item in _TEST_DROP_FLAGS: + i += 2 if nxt is not None and not nxt.startswith("--") else 1 + else: + out.append(item) + i += 1 + return out + + def default_test_start(stage_root: Path, component: ec.EngineComponent, ctx: Context) -> dict: """Start the staged engine through the real start path (owner runtime, `component:strata-engine`, a saved model), wait for the one-token generation probe, and stop it. Everything runs in an isolated runtime, profile and component folder, so a @@ -855,6 +885,8 @@ def default_test_start(stage_root: Path, component: ec.EngineComponent, ctx: Con cfg["exe"] = ec.REFERENCE_PREFIX + ec.COMPONENT_ID cfg["backend"] = component.backend cfg.pop("lib_dirs", None) + if isinstance(cfg.get("args"), list): + cfg["args"] = light_test_args(cfg["args"]) cfg["host"] = "127.0.0.1" cfg["port"] = _free_port() cfg["log"] = str(sandbox / "engine.log") diff --git a/tests/terminal/test_flow2_022.py b/tests/terminal/test_flow2_022.py index fec09536..73fabe07 100644 --- a/tests/terminal/test_flow2_022.py +++ b/tests/terminal/test_flow2_022.py @@ -364,6 +364,7 @@ class StoredTuning(Base): self.assertFalse(started) text = seen[-1] self.assertIn("already tuned for this computer", text) + self.assertIn("Add --retune to measure again", text) self.assertIn("Q2 32K - Full speed", text) self.assertIn("--retune", text) self.assertEqual(r.s.tuned_preset, saved["id"]) diff --git a/tests/terminal/test_launch.py b/tests/terminal/test_launch.py index ff217d2d..487366cc 100644 --- a/tests/terminal/test_launch.py +++ b/tests/terminal/test_launch.py @@ -952,6 +952,19 @@ class FlagsCommand(unittest.TestCase): self.assertIn("Nothing was changed.", out) self.assertEqual(store.list_presets(), []) + def test_the_summary_says_where_the_engine_log_is(self): # #3656 + import tempfile + with tempfile.TemporaryDirectory() as d: + cfg = Path(d) / "x.json" + cfg.write_text(json.dumps({"log": str(Path(d) / "office.engine.log"), "args": []}), encoding="utf-8") + fake = Result(profile="launch-office", urls=["http://127.0.0.1:8080"], key=None, tune_word=None, notices=[], config=str(cfg)) + with mock.patch.object(Runner, "run", return_value=fake): + code, out, err = run_cli(["launch", "--no-tui", "--model", "q2_0"]) + self.assertEqual(code, 0, err) + self.assertIn("Engine log", out) + self.assertIn("office.engine.log", out) + self.assertIn("strata logs --follow", out) + def test_run_without_screens_prints_the_address_and_saves_the_preset(self): fake = Result(profile="launch-office", urls=["http://127.0.0.1:8080", "http://192.168.1.5:8080"], key="sk-strata-abcdefghijkl", tune_word=None, notices=[], config="/x") diff --git a/tests/terminal/test_update_feed.py b/tests/terminal/test_update_feed.py index d95680ad..983177d5 100644 --- a/tests/terminal/test_update_feed.py +++ b/tests/terminal/test_update_feed.py @@ -175,6 +175,16 @@ class Selection(unittest.TestCase): self.assertTrue(any("580.65" in r for r in old[1])) self.assertIsNone(self.pick(both, nvidia_driver="500.00")[0]) + def test_an_update_keeps_the_cuda_build_that_runs_here(self): # #3835 + both = [entry(variant="cuda12", driver="575.51", archs=("sm_60", "sm_61", "sm_86", "compute_89")), entry(variant="cuda13")] + two_cards = {"cuda_archs": ["sm_61", "sm_86"], "nvidia_driver": "615.71"} + self.assertEqual(self.pick(both, **two_cards)[0].variant, "cuda13") # nothing installed: as before + kept, reasons = self.pick(both, installed_variant="cuda12", **two_cards) + self.assertEqual(kept.variant, "cuda12") + self.assertTrue(any("is kept" in r for r in reasons)) + only13 = [entry(variant="cuda13")] + self.assertEqual(self.pick(only13, installed_variant="cuda12")[0].variant, "cuda13") # the feed has no 12: the best fit + def test_the_newest_version_wins_and_the_card_must_be_covered(self): newer = [entry("0.1.45"), entry("0.1.46")] self.assertEqual(self.pick(newer)[0].version, "0.1.46") diff --git a/tests/terminal/test_updater.py b/tests/terminal/test_updater.py index 153bdc4f..4969a34d 100644 --- a/tests/terminal/test_updater.py +++ b/tests/terminal/test_updater.py @@ -457,6 +457,17 @@ class StartPathSignature(UpdaterCase): ec.verify_signature(ec.read_manifest(folder), {ec.ENV_REQUIRE_SIGNED: "1"}) +class LightTestStart(unittest.TestCase): + def test_the_test_start_drops_the_big_context_and_the_picture_reader(self): # #3842 + args = ["--serve", "--pack", "p", "--max-context", "262144", "--kv", "int8", "--kv-resident", "32768", "--vision", + "--vision-tokens", "768", "--spec", "4"] + self.assertEqual(updater.light_test_args(args), ["--serve", "--pack", "p", "--max-context", "4096", "--kv", "int8", "--spec", "4"]) + self.assertEqual(updater.light_test_args(["--max-context", "2048", "--vision", "cpu", "--mtp", "x"]), + ["--max-context", "2048", "--mtp", "x"]) + self.assertEqual(updater.light_test_args(["--vision"]), []) + self.assertEqual(updater.light_test_args(["--max-context", "abc"]), ["--max-context", "abc"]) + + class LazyModel(UpdaterCase): """A server that is "ready" with its model unloaded has not generated anything yet; the test start forces the load and the probe.""" From 27cbbfe6d623ac70f4c56cc5c4f84d30925a3466 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 24 Oct 2026 13:34:04 +0200 Subject: [PATCH 10/22] launch: the start waits longer for a big model by itself (10 minutes, about 8 s more per GB above 40 GB, at most 30), the server's own engine wait follows, and the runtime accepts start waits up to 1800 s (#3949 #3459). Own fix instead of PR #3817: that one needs people to set STRATA_ENGINE_READY_S; tests --- strata_cli/launch/runner.py | 21 ++++++++++++++++++++- strata_control/runtime.py | 15 +++++++++------ tests/terminal/test_flow2_022.py | 12 ++++++++++++ tests/terminal/test_runtime.py | 11 +++++++++++ 4 files changed, 52 insertions(+), 7 deletions(-) diff --git a/strata_cli/launch/runner.py b/strata_cli/launch/runner.py index 032e2117..410e3141 100644 --- a/strata_cli/launch/runner.py +++ b/strata_cli/launch/runner.py @@ -227,6 +227,11 @@ def tune_words(result: dict | None, code: int | None = None) -> tuple[str, str]: # ----------------------------------------------------------------------------------------------- run config +def runtime_max_wait() -> int: + from strata_control import runtime + return int(runtime.MAX_START_WAIT) + + def read_config(path: Path) -> dict: return json.loads(Path(path).read_text(encoding="utf-8-sig")) @@ -883,6 +888,17 @@ class Runner: except Exception: # noqa: BLE001 return 0.0 + def start_wait(self) -> int: + """How long the start waits for the model to be ready (#3949 #3459): 10 minutes, more for a big model, which a slow disk needs + longer to read (about 8 more seconds per GB above 40 GB, at most 30 minutes). Automatic: nobody sets a variable for it.""" + gb = 0.0 + try: + row = next((r for r in self.catalog.rows() if r.family == self.s.family and r.model == self.s.model), None) + gb = float(getattr(row, "download_gb", 0) or 0) + except Exception: # noqa: BLE001 + gb = 0.0 + return int(min(runtime_max_wait(), max(600, 600 + (gb - 40.0) * 8.0))) + def download_question(self) -> tuple[str, str]: """(title, text) of the question before a download starts, naming exactly what is fetched.""" return self.model_state().question() @@ -1249,6 +1265,9 @@ class Runner: cfg = derive_config(base, self.s, bool_flags=tune_knobs.BOOL_FLAGS, log=str(launch_dir() / f"{self.name}.engine.log"), gpus=cards_for_launch(self.s, self.catalog, base=base)) self.use_own_dsv41_engine(cfg) + wait = self.start_wait() + if wait > 600 and not cfg.get("engine_ready_s"): # the server's own wait for the engine (900 s) must not end before the start's + cfg["engine_ready_s"] = wait + 60 out = launch_dir() / f"{self.name}.json" write_private(out, cfg) self.config_path = out @@ -1588,7 +1607,7 @@ class Runner: def go() -> None: try: - box["r"] = runtime.start(name, wait=600) + box["r"] = runtime.start(name, wait=self.start_wait()) except Exception as e: # noqa: BLE001 box["e"] = e finally: diff --git a/strata_control/runtime.py b/strata_control/runtime.py index b5c9c3c8..1988dae3 100644 --- a/strata_control/runtime.py +++ b/strata_control/runtime.py @@ -515,6 +515,9 @@ def _check_start_candidate(name: str, expected_profile_revision: str | None, return plan, digest +MAX_START_WAIT = 1800 # seconds a start may wait for the model: a 250 GB DeepSeek set on a slow disk needs more than 10 minutes (#3949) + + def start(name: str, *, wait: float = 300, shutdown_timeout: float = 30, expected_profile_revision: str | None = None, expected_source_sha256: str | None = None, @@ -535,8 +538,8 @@ def start(name: str, *, wait: float = 300, shutdown_timeout: float = 30, if token is None: raise ProfileError("the process to follow with --die-with-pid is not running") die_with = (die_with_pid, token) - if not 0 <= wait <= 600 or not 0 <= shutdown_timeout <= 300: - raise ProfileError("start wait must be 0..600 and shutdown timeout 0..300 seconds") + if not 0 <= wait <= MAX_START_WAIT or not 0 <= shutdown_timeout <= 300: + raise ProfileError(f"start wait must be 0..{MAX_START_WAIT} and shutdown timeout 0..300 seconds") if expected_profile_revision is not None and (not isinstance(expected_profile_revision, str) or not re.fullmatch(r"[0-9a-f]{16}", expected_profile_revision)): raise ProfileError("expected profile revision must be 16 lowercase hex characters") @@ -706,9 +709,9 @@ def restart(name: str, *, timeout: float = 1000, startup_wait: float = 300, allow_source_switch: bool = False, allow_source_migration: bool = False, expected_source_sha256: str | None = None) -> dict: - if (not 1 <= timeout <= 1800 or not 1 <= startup_wait <= 600 or + if (not 1 <= timeout <= 1800 or not 1 <= startup_wait <= MAX_START_WAIT or type(allow_source_switch) is not bool or type(allow_source_migration) is not bool): - raise ProfileError("restart wait must be 1..1800 and startup wait 1..600 seconds") + raise ProfileError(f"restart wait must be 1..1800 and startup wait 1..{MAX_START_WAIT} seconds") if expected_source_sha256 is not None and (not isinstance(expected_source_sha256, str) or not re.fullmatch(r"[0-9a-f]{64}", expected_source_sha256)): raise ProfileError("expected source SHA-256 must be 64 lowercase hex characters") @@ -1224,7 +1227,7 @@ class Host: return {**result, "profile": self.name} if command == "restart": startup_wait = request.get("startup_wait", 300) - if type(startup_wait) not in (int, float) or not 1 <= startup_wait <= 600: + if type(startup_wait) not in (int, float) or not 1 <= startup_wait <= MAX_START_WAIT: return {"ok": False, "error": "invalid_startup_wait", "exit_code": 2} revision = request.get("expected_profile_revision") if revision is not None and (not isinstance(revision, str) or @@ -1368,7 +1371,7 @@ def main(argv: list[str] | None = None) -> int: parser.add_argument("--die-with-pid", type=int) parser.add_argument("--die-with-token") args = parser.parse_args(argv) - if not 0 <= args.shutdown_timeout <= 300 or not 1 <= args.startup_wait <= 600: + if not 0 <= args.shutdown_timeout <= 300 or not 1 <= args.startup_wait <= MAX_START_WAIT: parser.error("shutdown timeout must be 0..300") if args.expected_profile_revision is not None and not re.fullmatch(r"[0-9a-f]{16}", args.expected_profile_revision): parser.error("expected profile revision must be 16 lowercase hex characters") diff --git a/tests/terminal/test_flow2_022.py b/tests/terminal/test_flow2_022.py index 73fabe07..c2e5e29a 100644 --- a/tests/terminal/test_flow2_022.py +++ b/tests/terminal/test_flow2_022.py @@ -357,6 +357,18 @@ class StoredTuning(Base): seen, started = self.run_tune(self.runner_for_tune()) self.assertTrue(started) + def test_a_big_model_gets_a_longer_start_wait_by_itself(self): # #3949 #3459 + r = self.runner_for_tune() + row = type("Row", (), {"family": r.s.family, "model": r.s.model, "download_gb": 20.0}) + with mock.patch.object(r.catalog, "rows", return_value=[row]): + self.assertEqual(r.start_wait(), 600) # a small model keeps ten minutes + row.download_gb = 250.0 + with mock.patch.object(r.catalog, "rows", return_value=[row]): + self.assertEqual(r.start_wait(), 1800) # 600 + 210 x 8, capped at 30 minutes + row.download_gb = 83.0 + with mock.patch.object(r.catalog, "rows", return_value=[row]): + self.assertEqual(r.start_wait(), 944) + def test_a_stored_result_is_used_and_said(self): saved = self.store() r = self.runner_for_tune() diff --git a/tests/terminal/test_runtime.py b/tests/terminal/test_runtime.py index 5db3cfe6..04dd6953 100644 --- a/tests/terminal/test_runtime.py +++ b/tests/terminal/test_runtime.py @@ -1308,5 +1308,16 @@ class RuntimeTests(unittest.TestCase): os.close(exclusive) +class StartWaitLimit(unittest.TestCase): + def test_a_start_may_wait_up_to_thirty_minutes_for_a_big_model(self): # #3949 + from strata_control import runtime as rt, profiles as pr + self.assertEqual(rt.MAX_START_WAIT, 1800) + with self.assertRaisesRegex(pr.ProfileError, "start wait must be 0..1800"): + rt.start("x", wait=1801) + with mock.patch.object(rt, "_name", side_effect=pr.ProfileError("reached")): + with self.assertRaisesRegex(pr.ProfileError, "reached"): + rt.start("x", wait=1800) + + if __name__ == "__main__": unittest.main() From aef053e353dce7cf4eae3bb28692655546e580c6 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 24 Oct 2026 13:34:18 +0200 Subject: [PATCH 11/22] launch: the Access screen's help names --show-key and --api-key, so a person can see or set a key of their own (#3713 #3951); test --- strata_cli/launch/screens.py | 3 ++- tests/terminal/test_launch.py | 5 +++++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/strata_cli/launch/screens.py b/strata_cli/launch/screens.py index d40c1adc..e15177ee 100644 --- a/strata_cli/launch/screens.py +++ b/strata_cli/launch/screens.py @@ -1328,7 +1328,8 @@ class AccessScreen(Base): step_id = "access" hints = "↑↓ choose Enter next p port k new key t key on/off Esc back ? help" help_text = ("Who can use the model. 'This computer only' is the safe default and never needs a key. Beyond it Strata makes an API key " - "for you (recommended); press t if you would rather have no key: it still starts, but anyone who can reach it can use it.") + "for you (recommended); press t if you would rather have no key: it still starts, but anyone who can reach it can use it. " + "To see the key later: strata launch --show-key. To use a key of your own: strata launch --api-key YOUR-KEY (or --api-key-env NAME).") BINDINGS = Base.BINDINGS + [Binding("p", "port", show=False), Binding("k", "newkey", show=False), Binding("t", "keytoggle", show=False)] diff --git a/tests/terminal/test_launch.py b/tests/terminal/test_launch.py index 487366cc..ccb9b7cd 100644 --- a/tests/terminal/test_launch.py +++ b/tests/terminal/test_launch.py @@ -952,6 +952,11 @@ class FlagsCommand(unittest.TestCase): self.assertIn("Nothing was changed.", out) self.assertEqual(store.list_presets(), []) + def test_the_access_help_names_the_flags_for_showing_and_setting_a_key(self): # #3713 #3951 + from strata_cli.launch import screens + self.assertIn("strata launch --show-key", screens.AccessScreen.help_text) + self.assertIn("--api-key YOUR-KEY", screens.AccessScreen.help_text) + def test_the_summary_says_where_the_engine_log_is(self): # #3656 import tempfile with tempfile.TemporaryDirectory() as d: From ed0c8939aa160334983cea4130e68bbe9f2a6f3f Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 24 Oct 2026 13:35:43 +0200 Subject: [PATCH 12/22] setup: a download that gets no data for two minutes says so with the percentage and the one next step, instead of a line that never moves (#3567); test --- setup.py | 26 ++++++++++++++++++++++++++ tools/test_setup_stall_note.py | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 60 insertions(+) create mode 100644 tools/test_setup_stall_note.py diff --git a/setup.py b/setup.py index 432de323..b47ad875 100644 --- a/setup.py +++ b/setup.py @@ -2543,6 +2543,27 @@ def _piece_worker(src: _Source, st: _Pieces, todo: list, part: Path): st.stop.set() +class StallNote: + """A download that gets no byte for a while says so (#3567): "stalled at 69%" instead of a silent line that never moves. `check` is called + often with the bytes so far; it answers a sentence at most once a minute while nothing arrives, and None otherwise.""" + + AFTER = 120.0 + + def __init__(self, now: float = 0.0): + self.have, self.since, self.said = -1, now, 0.0 + + def check(self, have: int, total: int, now: float) -> str | None: + if have != self.have: + self.have, self.since, self.said = have, now, 0.0 + return None + idle = now - self.since + if idle < self.AFTER or now - self.said < 60: + return None + self.said = now + return (f"no data for {int(idle // 60)} min at {100 * have // max(1, total)}%: the connection is stuck. It keeps trying; to stop, press Ctrl+C, " + "and run the same command again: the download continues where it stopped") + + def parallel_download(url: str, part: Path, total: int, label: str, conns: int, name: str) -> bool: """Fill `part` (total bytes) over `conns` ranged connections. True when every byte is there; False when the server does not do ranges (the caller reads the file in one stream).""" @@ -2562,6 +2583,7 @@ def parallel_download(url: str, part: Path, total: int, label: str, conns: int, if not part.with_name(part.name + ".chunks").is_file() and not _save_pieces(part, total, done): return False # no piece list can be kept here: the pieces would not be told from holes last_print = last_save = 0.0 + stall = StallNote(time.time()) def report(force=False): nonlocal last_print, last_save @@ -2570,6 +2592,10 @@ def parallel_download(url: str, part: Path, total: int, label: str, conns: int, last_print = now have = st.have() print(f"\r {label}: {have / 1e9:6.2f} / {total / 1e9:.2f} GB ({100 * have / total:.0f}%) ", end="", flush=True) + note = stall.check(have, total, now) + if note: + print() + warn(note) if now - last_save > DL_SAVE_EVERY: last_save = now _save_pieces(part, total, st.snapshot()) diff --git a/tools/test_setup_stall_note.py b/tools/test_setup_stall_note.py new file mode 100644 index 00000000..93d02a5d --- /dev/null +++ b/tools/test_setup_stall_note.py @@ -0,0 +1,34 @@ +"""A download with no data for two minutes says so (#3567). + + python -m unittest tools.test_setup_stall_note +""" +import sys +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) +import setup # noqa: E402 + + +class Stall(unittest.TestCase): + def test_silent_while_bytes_arrive_and_for_the_first_two_minutes(self): + s = setup.StallNote(0.0) + self.assertIsNone(s.check(10, 100, 1.0)) + self.assertIsNone(s.check(20, 100, 200.0)) # moving + self.assertIsNone(s.check(20, 100, 300.0)) # 100 s idle + + def test_says_it_once_a_minute_and_stops_when_data_comes(self): + s = setup.StallNote(0.0) + s.check(69, 100, 1.0) + said = s.check(69, 100, 130.0) + self.assertIn("no data for 2 min at 69%", said) + self.assertIn("run the same command again", said) + self.assertIsNone(s.check(69, 100, 150.0)) + self.assertIn("min at 69%", s.check(69, 100, 200.0)) + self.assertIsNone(s.check(70, 100, 201.0)) + self.assertIsNone(s.check(70, 100, 250.0)) + + +if __name__ == "__main__": + unittest.main() From fb3bae20c6cac9eec2fc8eebf1fb4dea10e9c34d Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 24 Oct 2026 13:36:55 +0200 Subject: [PATCH 13/22] setup: the list of installed packages remembers which system wrote it, so a .venv shared by Windows and Linux installs again instead of saying 'already installed' (#3634); test --- setup.py | 17 ++++++++++++++++- tools/test_setup_pins.py | 15 +++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/setup.py b/setup.py index b47ad875..b82861fa 100644 --- a/setup.py +++ b/setup.py @@ -3361,6 +3361,20 @@ def control_missing_packages() -> list: if importlib.util.find_spec(m) is None] +def pip_stamp_is_ours(stamp: Path) -> bool: + """The list of installed packages was written for THIS system (#3634). A .venv on a disk that Windows and Linux both start from keeps + the stamp of the other one, which then says "already installed" about packages this Python does not have. A marker beside the stamp + names the system that wrote it; an older stamp without a marker is believed only while the packages every run needs can be imported.""" + marker = stamp.with_name(stamp.name + ".os") + try: + if marker.exists(): + return marker.read_text(encoding="utf-8").strip() == sys.platform + except OSError: + return False + import importlib.util + return all(importlib.util.find_spec(m) is not None for m in ("numpy", "jinja2", "regex", "yaml")) + + def pip_install(packages, what, extra=()): """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 @@ -3372,7 +3386,7 @@ def pip_install(packages, what, extra=()): ok(f"{what}: bundled with the app") return stamp = Path(sys.prefix) / ".strata-pip.json" - have = json.loads(stamp.read_text(encoding="utf-8")) if stamp.exists() else [] + have = json.loads(stamp.read_text(encoding="utf-8")) if stamp.exists() and pip_stamp_is_ours(stamp) else [] 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)))] @@ -3383,6 +3397,7 @@ def pip_install(packages, what, extra=()): say(f" Installing {what} ...") run([sys.executable, "-m", "pip", "install", "--quiet", "--disable-pip-version-check", *extra, *need]) stamp.write_text(json.dumps(sorted(set(have) | set(need)), indent=0)) + stamp.with_name(stamp.name + ".os").write_text(sys.platform, encoding="utf-8") ok(f"{what} installed") diff --git a/tools/test_setup_pins.py b/tools/test_setup_pins.py index 052c9a97..f0be55ba 100644 --- a/tools/test_setup_pins.py +++ b/tools/test_setup_pins.py @@ -398,6 +398,21 @@ class Requirements(unittest.TestCase): 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_a_stamp_written_by_another_system_is_not_believed(self): # #3634 + lines = setup.requirement_lines() + with tempfile.TemporaryDirectory() as d: + (Path(d) / ".strata-pip.json").write_text(json.dumps(lines)) + (Path(d) / ".strata-pip.json.os").write_text("win32" if setup.sys.platform != "win32" else "linux") + ran = [] + with mock.patch.object(setup.sys, "prefix", d), mock.patch.object(setup, "run", lambda cmd, **kw: ran.append(cmd)): + quiet(setup.pip_install, lines, "the packages") + self.assertTrue(ran) # installed again, here + self.assertEqual((Path(d) / ".strata-pip.json.os").read_text(), setup.sys.platform) + ran.clear() + with mock.patch.object(setup.sys, "prefix", d), mock.patch.object(setup, "run", lambda cmd, **kw: ran.append(cmd)): + quiet(setup.pip_install, lines, "the packages") + self.assertFalse(ran) # and then skipped as before + def test_fresh_install_gets_every_pin(self): lines = setup.requirement_lines() ran, stamp = self.pip(None, lines) From d6c19360210791401bfb6b6fea26bfa45ca7312c Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 24 Oct 2026 13:37:35 +0200 Subject: [PATCH 14/22] setup: a source build on Windows needs Visual Studio 2022 (2019 cannot compile the C++20 sources) and the stop says so, with the ready-made engine as the way around (#3566); tests follow --- setup.py | 7 ++++--- tools/test_setup_choices.py | 8 ++++---- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/setup.py b/setup.py index b82861fa..bf2828b1 100644 --- a/setup.py +++ b/setup.py @@ -2093,7 +2093,7 @@ def find_vcvars(cuda_v=None): args = [str(vswhere), "-latest", "-products", "*"] if cuda_v is not None: upper = "19.0" if tuple(cuda_v) >= (13, 3) else "18.0" - args += ["-version", f"[16.0,{upper})"] + args += ["-version", f"[17.0,{upper})"] # 17 = Visual Studio 2022: the sources are C++20, and nvcc silently drops -std=c++20 under 2019 (#3566) args += ["-requires", "Microsoft.VisualStudio.Component.VC.Tools.x86.x64", "-property", "installationPath"] p = out(args).strip() v = Path(p) / "VC/Auxiliary/Build/vcvars64.bat" if p else None @@ -5581,8 +5581,9 @@ def cmake_build(src, bdir, target, defs, vcvars, bat_name): # the same command then gets past it (issue #45); a second attempt only compiles what is still missing. if WIN: if vcvars is None: # #881: the build needs MSVC's environment - fail("the Visual Studio C++ build tools were not found", - "install them (Visual Studio 2019 or 2022, workload 'Desktop development with C++') and run setup again") + fail("the Visual Studio 2022 C++ build tools were not found (Visual Studio 2019 is too old: the sources are C++20)", + "install Visual Studio 2022 Build Tools (workload 'Desktop development with C++'), then run setup again; a ready-made engine " + "needs no compiler: `strata update` fetches it") bat = ROOT / bat_name q = lambda c: " ".join(f'"{x}"' if " " in str(x) else str(x) for x in c) # noqa: E731 bat.write_text(f'@echo off\r\ncall "{vcvars}" >nul\r\n{q(conf)} || exit /b 1\r\n{q(build)} && exit /b 0\r\n' diff --git a/tools/test_setup_choices.py b/tools/test_setup_choices.py index db995bb1..2643d434 100644 --- a/tools/test_setup_choices.py +++ b/tools/test_setup_choices.py @@ -236,10 +236,10 @@ class VsRange(unittest.TestCase): def test_the_range_follows_the_toolkit(self): self.assertIsNone(self.asked(None)) # #881: without CUDA vswhere gets no version range - self.assertEqual(self.asked((13, 0)), "[16.0,18.0)") - self.assertEqual(self.asked((13, 2)), "[16.0,18.0)") - self.assertEqual(self.asked((13, 3)), "[16.0,19.0)") - self.assertEqual(self.asked((14, 0)), "[16.0,19.0)") + self.assertEqual(self.asked((13, 0)), "[17.0,18.0)") + self.assertEqual(self.asked((13, 2)), "[17.0,18.0)") + self.assertEqual(self.asked((13, 3)), "[17.0,19.0)") + self.assertEqual(self.asked((14, 0)), "[17.0,19.0)") def test_vcvars_by_hand(self): From 9c375ccb7d98495889cf738b68082844827e2648 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 24 Oct 2026 13:38:49 +0200 Subject: [PATCH 15/22] launch: setup's DeepSeek engine upgrade lines (the failure one 'A newer DeepSeek engine is available but could not be installed') are shown on the setup path too; test --- strata_cli/launch/runner.py | 21 +++++++++++++++++++++ tests/terminal/test_dsv41_upgrade.py | 14 ++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/strata_cli/launch/runner.py b/strata_cli/launch/runner.py index 410e3141..73f4d180 100644 --- a/strata_cli/launch/runner.py +++ b/strata_cli/launch/runner.py @@ -77,6 +77,20 @@ def python_failure(lines: list[str]) -> str | None: return None +DEEPSEEK_ENGINE_LINE = re.compile(r"(A newer DeepSeek engine (?:is available|may be available)[^\r\n]*|DeepSeek engine updated from [^\r\n]*)") + + +def deepseek_engine_note(line: str) -> tuple[str, str] | None: + """setup's line about the DeepSeek engine upgrade ("A newer DeepSeek engine is available but could not be installed: ...; still using X", + or "DeepSeek engine updated from X to Y"): ("warn" | "info", the sentence), None for any other line. The failure line must reach the + person: the model starts with the engine they have, and they should know there is a newer one.""" + found = DEEPSEEK_ENGINE_LINE.search(line) + if not found: + return None + text = found.group(1).strip() + return ("info" if text.startswith("DeepSeek engine updated") else "warn", text) + + def argparse_failure(lines: list[str]) -> str: """setup.py's own refusal of an option ("setup.py: error: argument --kv: invalid choice: ..."), which is neither an [X] line nor a traceback (#3785): the words after "error:" are the cause.""" @@ -498,6 +512,7 @@ class Runner: self.hardware_override = hardware self.children: list[subprocess.Popen] = [] self.notices: list[str] = [] + self._engine_notes: set[str] = set() self.identity_notes: list[str] = [] self.tune_result: dict | None = None self.config_path: Path | None = None @@ -1003,6 +1018,12 @@ class Runner: continue lines.append(line) lines[:] = lines[-1500:] + note = deepseek_engine_note(line) + if note and note[1] not in self._engine_notes: # setup's DeepSeek engine lines are shown, not condensed away (0.2.5 list) + self._engine_notes.add(note[1]) + if note[0] == "warn": + self.notices.append(note[1]) + self.emit("model", note[1], None, level=note[0], step=step_seen) prog = cat.mcp.install_progress(lines) prog = cat.mcp.combined_progress(prog, job) dl, phase, label = prog.get("download"), prog.get("phase"), prog.get("label") diff --git a/tests/terminal/test_dsv41_upgrade.py b/tests/terminal/test_dsv41_upgrade.py index 24eb0ee1..dc726ceb 100644 --- a/tests/terminal/test_dsv41_upgrade.py +++ b/tests/terminal/test_dsv41_upgrade.py @@ -159,5 +159,19 @@ class LaunchChoice(unittest.TestCase): self.assertEqual(self.runner().upgrade_dsv41_engine(found), new) +class SetupPathLines(unittest.TestCase): + """The upgrade lines setup prints are shown by strata launch, the failure one especially (0.2.5 list).""" + + def test_the_failure_line_is_a_warning_and_the_success_line_is_news(self): + from strata_cli.launch.runner import deepseek_engine_note + bad = deepseek_engine_note(" A newer DeepSeek engine is available but could not be installed: no space left; still using 0.1.49.") + self.assertEqual(bad[0], "warn") + self.assertTrue(bad[1].endswith("still using 0.1.49.")) + self.assertEqual(deepseek_engine_note("[!] A newer DeepSeek engine may be available but could not be checked (OSError); still using 0.1.49.")[0], "warn") + good = deepseek_engine_note(" DeepSeek engine updated from 0.1.49 to 0.1.49.2.") + self.assertEqual(good, ("info", "DeepSeek engine updated from 0.1.49 to 0.1.49.2.")) + self.assertIsNone(deepseek_engine_note(" checking model.gguf (SHA-256, 5 GB) ...")) + + if __name__ == "__main__": unittest.main() From d9d033be8622135dbbc21279c0ad3dd988c3b1dd Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 24 Oct 2026 13:40:22 +0200 Subject: [PATCH 16/22] launch: at 80 columns the model list keeps its verdict column (fits, tight, too big and the recommendation) instead of cutting it off; test --- strata_cli/launch/screens.py | 8 ++++++-- tests/terminal/test_launch_tui.py | 18 ++++++++++++++++++ 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/strata_cli/launch/screens.py b/strata_cli/launch/screens.py index e15177ee..a17bbd54 100644 --- a/strata_cli/launch/screens.py +++ b/strata_cli/launch/screens.py @@ -387,7 +387,7 @@ class ModelScreen(Base): w = self.width() if w >= 100: return [("Model", 42), ("Download", 10), ("Needs (RAM + VRAM)", 20), ("On this computer", 0)] - return [("Model", 41), ("Download", 9), ("Needs (RAM+VRAM)", 17), ("On this computer", 0)] + return [("Model", 41), ("Size", 8), ("Needs", 7), ("Fits?", 0)] # 80 columns: the verdict column keeps room (the long words are below the list) def build_menu(self, initial: bool = False) -> None: s = self.ctx.settings @@ -402,7 +402,11 @@ class ModelScreen(Base): tag = (" (recommended)" if r.recommended else "") + (" (installed)" if r.installed else "") + (" [experimental]" if r.experimental else "") need = f"{r.memory_gb:.0f} GB" if r.memory_gb else "-" ssd = f" · SSD {r.spill_gb:.0f} GB" if r.spill_gb >= 1 else "" - items.append(Item([r.title, f"{r.download_gb:.0f} GB", need, Cell((r.words.split(",")[0].split(":")[0] if ssd and "SSD" in r.words else r.words) + ssd + tag, col)], key=(r.family, r.model))) + verdict = (r.words.split(",")[0].split(":")[0] if ssd and "SSD" in r.words else r.words) + ssd + tag + if self.width() < 100: # a short verdict that fits the column; the full sentence is shown under the list + extra = " (recommended)" if r.recommended else " (installed)" if r.installed else " [experimental]" if r.experimental else "" + verdict = {"fits": "fits", "tight": "tight", "no": "too big"}[r.verdict] + extra + items.append(Item([r.title, f"{r.download_gb:.0f} GB", need, Cell(verdict, col)], key=(r.family, r.model))) if (s.family, s.model) == (r.family, r.model): sel = i m = self.query_one(Menu) diff --git a/tests/terminal/test_launch_tui.py b/tests/terminal/test_launch_tui.py index 25118b95..dff55798 100644 --- a/tests/terminal/test_launch_tui.py +++ b/tests/terminal/test_launch_tui.py @@ -236,6 +236,24 @@ class ModelStep(Base): self.assertIn("The n-gram table stays on your SSD", t) self.run_app(case) + def test_the_verdict_column_is_not_cut_off_at_80_columns(self): # 0.2.5 list + ctx = make_ctx() + app = LaunchApp(ctx) + + async def go(): + async with app.run_test(size=(80, 34)) as pilot: + await pilot.pause(0.2) + await press(pilot, "enter") + t = text_of(app) + self.assertIn("Fits?", t) + rec = next(l for l in t.splitlines() if "Qwen3.8-Flash-Next IQ3_S " in l) + self.assertIn("fits (recommended)", rec) + for model in ("Q2_0", "NVFP4 ", "UD-Q5_K_XL"): + row = next(l for l in t.splitlines() if model in l and "GB" in l) + self.assertTrue(any(w in row for w in ("fits", "tight", "too big")), row) + self.assertTrue(all(len(l) <= 80 for l in t.splitlines())) + asyncio.run(go()) + def test_choosing_a_model_and_going_on(self): async def case(app, pilot, ctx): await press(pilot, "enter", "up", "up", "up", "enter") From 08a5e6b34aa44daa51cf0d55f0dc7c01aa9bf573 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 24 Oct 2026 13:48:09 +0200 Subject: [PATCH 17/22] packaging smoke: the packaged Terminal carries the installer since 0.2.4, so 'strata install' without a keyboard stops at the first question instead of saying 'no installer'; the check accepts both --- packaging/smoke_terminal.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/packaging/smoke_terminal.py b/packaging/smoke_terminal.py index f6f5d20c..70c3e27b 100644 --- a/packaging/smoke_terminal.py +++ b/packaging/smoke_terminal.py @@ -185,8 +185,11 @@ def main() -> int: check("profile list", r["rc"] == 0, rc=r["rc"], output=r["stdout"].strip()[:300]) r = run([*strata, "install"], env, root) - check("install refuses without an installer", r["rc"] == 5 and "no installer" in r["stderr"], - rc=r["rc"], stderr=r["stderr"].strip()[:300]) + # since 0.2.4 the Terminal carries setup.py: with no keyboard it stops at the first question, in plain words and with a non-zero code + # (an older Terminal without the installer answers rc 5 "no installer") + stopped = r["rc"] not in (0, None) and ("no installer" in r["stderr"] or "setup stopped" in (r["stdout"] + r["stderr"]).lower()) + check("install stops without a keyboard (or without an installer)", stopped, rc=r["rc"], stderr=r["stderr"].strip()[:300], + output=r["stdout"].strip()[-300:]) # serve on the mock engine: a fake run config (the mock never loads it), a free port, a chat answer cfg_dir = sandbox / "cfg" From 569f7c739d39a315102ad784b9607a7578138e36 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 24 Oct 2026 14:18:47 +0200 Subject: [PATCH 18/22] test: the --kv choices check reads the last line of the error (Python 3.12 and 3.13 print the list differently) --- tests/terminal/test_setup_failure_words.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/terminal/test_setup_failure_words.py b/tests/terminal/test_setup_failure_words.py index 7d111714..fa558935 100644 --- a/tests/terminal/test_setup_failure_words.py +++ b/tests/terminal/test_setup_failure_words.py @@ -30,7 +30,7 @@ class SetupFailureWords(unittest.TestCase): import subprocess, sys root = Path(__file__).resolve().parents[2] done = subprocess.run([sys.executable, str(root / "setup.py"), "--kv", "bogus"], capture_output=True, text=True, cwd=str(root), timeout=120) - self.assertIn("choose from int8, q4_0, k8v4, fp16", done.stderr) + self.assertIn("fp16", done.stderr.splitlines()[-1]) # the choices line of the argparse error def test_the_last_line_of_a_traceback_is_found(self): self.assertEqual(python_failure(TRACEBACK), "ModuleNotFoundError: No module named 'calibrate'") From beeea0abf3c3a52bb6a20ee3941a3f566b8d329c Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 24 Oct 2026 14:19:31 +0200 Subject: [PATCH 19/22] test: the Mac build-tools test follows find_tool's version check --- tests/terminal/test_issues_022.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/terminal/test_issues_022.py b/tests/terminal/test_issues_022.py index 92cf35b3..7efd7322 100644 --- a/tests/terminal/test_issues_022.py +++ b/tests/terminal/test_issues_022.py @@ -84,7 +84,7 @@ class Issue3403MacBuildTools(unittest.TestCase): for p in packages: installed[p.split("==")[0]] = "/venv/bin/" + p.split("==")[0] - with mock.patch.object(setup, "find_tool", side_effect=find), mock.patch.object(setup, "pip_install", side_effect=pip) as pi: + with mock.patch.object(setup, "find_tool", side_effect=find), mock.patch.object(setup, "pip_install", side_effect=pip) as pi, mock.patch.object(setup, "_tool_version", return_value=(True, (3, 31, 0))): self.assertEqual(setup.ensure_build_tools(), ("/venv/bin/cmake", "/venv/bin/ninja")) self.assertEqual(pi.call_count, 1) setup.ensure_build_tools() # present now: nothing more is installed From 54768d25b12fddc4fbddf92deac504a9cd7eaf62 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 24 Oct 2026 14:29:49 +0200 Subject: [PATCH 20/22] test: the own-GGUF check finds tests.terminal when tools/ is run on its own --- tools/test_setup_ownfiles.py | 1 + 1 file changed, 1 insertion(+) diff --git a/tools/test_setup_ownfiles.py b/tools/test_setup_ownfiles.py index eeb82fef..a86f22fe 100644 --- a/tools/test_setup_ownfiles.py +++ b/tools/test_setup_ownfiles.py @@ -60,6 +60,7 @@ class OwnFileChecks(unittest.TestCase): self.assertFalse(self.file.exists()) def test_a_complete_own_gguf_of_another_size_or_hash_is_used_with_a_warning(self): # #3777 + sys.path.insert(0, str(Path(__file__).resolve().parents[1])) # `discover -s tools` puts only tools/ on the path from tests.terminal.test_own_files import gguf_bytes gguf = Path(self.tmp.name) / "fine-tune.gguf" gguf.write_bytes(gguf_bytes(["Q8_0"])) From dc2c4229e95c2e5ea1e726998c8b6c601bed8cfd Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 24 Oct 2026 15:25:07 +0200 Subject: [PATCH 21/22] test: launch_engine_first gives the runner a Qwen catalog (a bare Mock answered 'DeepSeek' to the 0.2.4 multi-file question and skipped the engine step); the launch code was right --- tests/terminal/test_launch_engine_first.py | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/tests/terminal/test_launch_engine_first.py b/tests/terminal/test_launch_engine_first.py index 62ba4baa..397249c5 100644 --- a/tests/terminal/test_launch_engine_first.py +++ b/tests/terminal/test_launch_engine_first.py @@ -24,6 +24,14 @@ UNUSABLE = {"usable": False, "engine": None, "notice": "No engine for this PC wa "The app never downloads an engine while it starts or serves."} +def qwen_catalog(): + """A catalog stand-in for a Qwen model: since 0.2.4 the runner asks it whether the family is DeepSeek (which has its own engine and skips this step); + a bare Mock answers yes to everything.""" + cat = mock.Mock() + cat.strata.multi_family.return_value = False + return cat + + class FakeProc: def __init__(self, events: list[dict], code: int = 0): self.stdout = iter(json.dumps(e) + "\n" for e in events) @@ -42,7 +50,7 @@ def update_events(status: str, note: str = "", code: int = 0) -> list[dict]: def runner(spawned: list) -> Runner: - r = Runner(S.LaunchSettings(family="qwen", model="Q2_0", context=32768), catalog=mock.Mock(), emit=lambda e: None) + r = Runner(S.LaunchSettings(family="qwen", model="Q2_0", context=32768), catalog=qwen_catalog(), emit=lambda e: None) r.check_cancel = lambda: None return r @@ -58,7 +66,7 @@ class EngineBeforeModel(unittest.TestCase): """ensure_engine() like run_ensure, returning (spawns, error or None, the runner with .events).""" spawns: list = [] seen: list = [] - r = Runner(S.LaunchSettings(family="qwen", model="Q2_0", context=32768), catalog=mock.Mock(), emit=seen.append, + r = Runner(S.LaunchSettings(family="qwen", model="Q2_0", context=32768), catalog=qwen_catalog(), emit=seen.append, confirm=confirm, assume_yes=assume_yes) r.events = seen r.check_cancel = lambda: None From a3e4cb64fd1ffaede89a9006dedc0424a5397472 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 24 Oct 2026 15:26:07 +0200 Subject: [PATCH 22/22] test: serving never reaches the DeepSeek engine check (only launch and setup import it), and 'serve --plan runs no program' means no installer or fetch: a PC's read-only hardware probes (nvidia-smi, Get-CimInstance) no longer fail it --- tests/terminal/test_no_acquisition.py | 32 ++++++++++++++++++++++++++- 1 file changed, 31 insertions(+), 1 deletion(-) diff --git a/tests/terminal/test_no_acquisition.py b/tests/terminal/test_no_acquisition.py index 09b7d178..196b5fa9 100644 --- a/tests/terminal/test_no_acquisition.py +++ b/tests/terminal/test_no_acquisition.py @@ -48,6 +48,8 @@ NETWORK_ALLOWED = { ("strata_control/tune_session.py", "urlopen"): "the loopback engine (127.0.0.1) the auto-tuner a user started measures", ("strata_control/loopback.py", "urlopen"): "the one opener for this computer's own servers (no proxy); any other address is passed on unchanged", ("strata_control/components.py", "urlopen"): "the component fetcher: only `strata install`/UPDATE call it", + ("strata_control/dsv41_engine.py", "urlopen"): "the DeepSeek engine's one 10-second 'is the feed reachable' check, called only by strata launch and " + "setup (test_the_deepseek_engine_check_is_reached_only_from_launch_and_setup); never while serving", } #: Modules that import the installer on purpose, with the explicit command that reaches them. INSTALLER_IMPORT_ALLOWED = { @@ -109,6 +111,26 @@ class ImportGraphTests(unittest.TestCase): for rel in found: self.assertIn(rel, INSTALLER_IMPORT_ALLOWED, f"{rel} imports installer code: {found[rel]}") + def test_the_deepseek_engine_check_is_reached_only_from_launch_and_setup(self): + """strata_control/dsv41_engine.py (the engine's self-upgrade, 0.2.4.2) reaches the network; serving must never import it.""" + importers = set() + for d in SERVING_DIRS: + for p in sorted((ROOT / d).glob("*.py")): + if p.name.startswith("test_") or p.name == "dsv41_engine.py": + continue + tree = ast.parse(p.read_text(encoding="utf-8")) + for node in ast.walk(tree): + names = [a.name for a in node.names] if isinstance(node, ast.Import) else [node.module] + [f"{node.module}.{a.name}" for a in node.names] if isinstance(node, ast.ImportFrom) and node.module else [] + if any(n.endswith("dsv41_engine") for n in names): + importers.add(p.relative_to(ROOT).as_posix()) + importers.update(p.relative_to(ROOT).as_posix() for p in (ROOT / "strata_cli" / "launch").glob("*.py") + if "dsv41_engine" in p.read_text(encoding="utf-8") and not p.name.startswith("test_")) + importers.discard("strata_cli/launch/runner.py") + if "dsv41_engine" in (ROOT / "setup.py").read_text(encoding="utf-8"): + importers.add("setup.py") + importers.discard("setup.py") + self.assertEqual(sorted(importers), [], "only strata_cli/launch/runner.py and setup.py may use the DeepSeek engine check") + def test_no_installer_subprocess_or_network_call_on_the_serving_side(self): bad = [] for p in _sources(): @@ -313,7 +335,15 @@ class CliServeIsOfflineTests(unittest.TestCase): contextlib.redirect_stdout(out): code = cli.main(["serve", "--profile", str(cfg), "--plan", "--output", "json"]) self.assertEqual(code, 0, out.getvalue()) - self.assertEqual((rec.network, rec.programs), ([], [])) + # Reading the hardware is not acquiring anything: nvidia-smi / hipInfo / rocminfo and PowerShell's Get-CimInstance (display adapters) only + # print what is here. Whether a PC runs them depends on the PC (a machine with nvidia-smi on PATH does), so the check is that nothing else runs. + probes = {"nvidia-smi", "hipinfo", "rocminfo", "rocm-smi", "vulkaninfo"} + + def read_only(argv): + stem = Path(argv[0]).stem.lower() + return stem in probes or (stem in ("powershell", "pwsh") and any("Get-CimInstance" in a for a in argv)) + self.assertEqual(rec.network, []) + self.assertEqual([a for a in rec.programs if not read_only(a)], []) self.assertNotIn("setup", sys.modules.get("strata_cli.cli").__dict__.get("__name__", "")) def test_strata_install_without_the_installer_is_a_typed_error(self):