From 968fcb70b0eea4b37d7072855b14570a10335423 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Tue, 20 Oct 2026 10:07:55 +0200 Subject: [PATCH 01/47] Drop the cached update notice when Control, engine or app version changed --- strata_control/engine_component.py | 30 +++++++++++++++++++++++++++--- strata_control/updater.py | 4 +++- tests/terminal/test_updater.py | 23 +++++++++++++++++++++++ 3 files changed, 53 insertions(+), 4 deletions(-) diff --git a/strata_control/engine_component.py b/strata_control/engine_component.py index 42834e68..715a571b 100644 --- a/strata_control/engine_component.py +++ b/strata_control/engine_component.py @@ -189,14 +189,38 @@ def engine_dir(root: Path | None = None) -> Path: return (root or components_dir()) / "engine" +def newest_installed_version(root: Path | None = None) -> str | None: + """The highest engine version in the component folder, or None. A quick scan; nothing is hashed.""" + try: + found, _ = scan(root) + except Exception: # noqa: BLE001 - informational only + return None + return max((item.version for item in found), key=_version_key, default=None) + + def cached_notice(root: Path | None = None) -> str | None: """"update available (x.y.z): run `strata update`" from the last explicit check, or None. Reads one small local file; it never - touches the network, so showing it at a start does not break the rule that only an update step downloads.""" + touches the network, so showing it at a start does not break the rule that only an update step downloads. + + The notice belongs to the versions the check was made for: it is dropped when Control or the installed engine is not the one + recorded then (an app install, an update, a rollback), and an engine that is not newer than the installed one is never offered.""" + base = root or components_dir() try: - last = (json.loads(((root or components_dir()) / UPDATE_STATE).read_text(encoding="utf-8-sig")).get("last_check") or {}) + last = (json.loads((base / UPDATE_STATE).read_text(encoding="utf-8-sig")).get("last_check") or {}) except (OSError, ValueError, AttributeError): return None - parts = [f"engine {last['engine']}" for _ in [0] if last.get("engine")] + [f"app {last['app']}" for _ in [0] if last.get("app")] + if not isinstance(last, dict): + return None + control = runtime_version() + if "control" in last and last["control"] != control: + return None + engine, app = last.get("engine"), last.get("app") + installed = newest_installed_version(base) + if "engine_installed" in last and last["engine_installed"] != installed: + engine = None + if engine and installed and _version_key(str(engine)) <= _version_key(installed): + engine = None + parts = ([f"engine {engine}"] if engine else []) + ([f"app {app}"] if app else []) return f"update available ({', '.join(parts)}): run `strata update`" if parts else None diff --git a/strata_control/updater.py b/strata_control/updater.py index 470f3d2e..9c12445c 100644 --- a/strata_control/updater.py +++ b/strata_control/updater.py @@ -490,7 +490,9 @@ def check(ctx: Context) -> dict: state.data["last_check"] = { "at": (ctx.now or dt.datetime.now(dt.timezone.utc)).isoformat(), "engine": report["engine"]["offered"]["version"] if report["engine"]["status"] in ("available", "install") and report["engine"]["offered"] else None, - "app": report["app"]["offered"] if report["app"]["status"] == "available" else None} + "app": report["app"]["offered"] if report["app"]["status"] == "available" else None, + # the versions this result is for, so a later Control, engine or app change drops the cached notice + "control": ec.runtime_version(), "engine_installed": ec.newest_installed_version(ctx.components)} state.save() return report diff --git a/tests/terminal/test_updater.py b/tests/terminal/test_updater.py index 5fa016ba..29f77922 100644 --- a/tests/terminal/test_updater.py +++ b/tests/terminal/test_updater.py @@ -630,6 +630,29 @@ class Cli(UpdaterCase): def common(self): return ["--feed", str(self.release), "--components-dir", str(self.components), "--model-config", str(self.config)] + def test_cached_update_notice_is_dropped_when_versions_change(self): + self.install_current() + self.publish(("0.1.46", fx.GOOD_ENGINE)) + self.assertEqual(self.cli("update", "--check", *self.common())[0], 0) + notice = "update available (engine 0.1.46): run `strata update`" + self.assertEqual(ec.cached_notice(self.components), notice) + state_file = self.components / ec.UPDATE_STATE + saved = json.loads(state_file.read_text(encoding="utf-8")) + self.assertEqual(saved["last_check"]["engine_installed"], "0.1.45") + # a new app brings a new Control: the old result is not shown again + with mock.patch.object(ec, "runtime_version", return_value="9.9.9"): + self.assertIsNone(ec.cached_notice(self.components)) + # the installed engine changed since the check (an update from elsewhere, a rollback) + with mock.patch.object(ec, "newest_installed_version", return_value="0.1.44"): + self.assertIsNone(ec.cached_notice(self.components)) + # an old file without the recorded versions: still never offers an engine that is not newer + saved["last_check"] = {"at": "x", "engine": "0.1.45", "app": None} + state_file.write_text(json.dumps(saved), encoding="utf-8") + self.assertIsNone(ec.cached_notice(self.components)) + saved["last_check"] = {"at": "x", "engine": "0.1.46", "app": None} + state_file.write_text(json.dumps(saved), encoding="utf-8") + self.assertEqual(ec.cached_notice(self.components), notice) + def test_check_update_and_rollback_from_the_terminal(self): self.install_current() self.publish(("0.1.46", fx.GOOD_ENGINE)) From f39d9519045f943ebe46504432d8fe4a80f77240 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Tue, 20 Oct 2026 13:18:07 +0200 Subject: [PATCH 02/47] Terminal hands over to the Control that strata update installed The Terminal on PATH ignored components/control/active.json, so after strata update the old Control kept running. strata.py now checks the pointer first (stdlib only) and runs the newer, whole Control with its own interpreter; never an older one, never outside the control folder, no loop (STRATA_HANDOVER), one warning and a fallback if it is broken. strata update says the next command already runs the new Control. --- strata.py | 5 + strata_cli/handover.py | 141 ++++++++++++++++++++++++++++ strata_cli/update_cmd.py | 2 +- strata_control/updater.py | 4 +- tests/terminal/test_handover.py | 160 ++++++++++++++++++++++++++++++++ 5 files changed, 309 insertions(+), 3 deletions(-) create mode 100644 strata_cli/handover.py create mode 100644 tests/terminal/test_handover.py diff --git a/strata.py b/strata.py index defae0b0..52b9c72a 100644 --- a/strata.py +++ b/strata.py @@ -28,6 +28,11 @@ def _preflight(argv): if __name__ == "__main__": + # a newer Control installed by `strata update` takes over before anything heavy is imported (stdlib only) + from strata_cli.handover import maybe_hand_over + handed = maybe_hand_over(sys.argv[1:]) + if handed is not None: + raise SystemExit(handed) code = _preflight(sys.argv[1:]) if code: raise SystemExit(code) diff --git a/strata_cli/handover.py b/strata_cli/handover.py new file mode 100644 index 00000000..50964593 --- /dev/null +++ b/strata_cli/handover.py @@ -0,0 +1,141 @@ +"""Hand the Terminal over to a newer Control that `strata update` installed. + +`strata update` stages a newer Control in ``/control//`` and writes ``/control/active.json``. The +desktop app follows that pointer; the Terminal on PATH is a different install, so without this it kept running the old one. +`maybe_hand_over` runs at the very start of ``strata.py``, before any heavy import, and (only when that Control is newer and whole) +runs the same command line with the newer Control's own interpreter and entry point. + +Rules: standard library only; never an older or equal target; never a pointer that leaves the control folder; never a loop +(``STRATA_HANDOVER`` marks a process that was already handed over); a broken target costs one warning line and the current +Control keeps running. ``STRATA_NO_HANDOVER=1`` turns it off. +""" + +from __future__ import annotations + +import json +import os +import re +import subprocess +import sys +from pathlib import Path + +ENV_GUARD = "STRATA_HANDOVER" +ENV_OFF = "STRATA_NO_HANDOVER" +_FOLDER = re.compile(r"^[\w.+-]+$") +_VERSION = re.compile(r"^[0-9]+(\.[0-9]+){1,3}$") + + +def components_dir(environ=None) -> Path: + """The per-user component folder (same rule as strata_control/engine_component.py components_dir).""" + environ = os.environ if environ is None else environ + if environ.get("STRATA_COMPONENTS_DIR"): + return Path(environ["STRATA_COMPONENTS_DIR"]) + home = Path.home() + if os.name == "nt": + return Path(environ.get("LOCALAPPDATA") or str(home / "AppData" / "Local")) / "Strata" / "components" + return Path(environ.get("XDG_DATA_HOME") or str(home / ".local" / "share")) / "strata" / "components" + + +def version_key(text) -> tuple[int, ...] | None: + if not isinstance(text, str) or not _VERSION.fullmatch(text.strip()): + return None + parts = [int(p) for p in text.strip().split(".")] + return tuple(parts + [0] * (4 - len(parts))) + + +def _read_json(path: Path): + return json.loads(path.read_text(encoding="utf-8-sig")) + + +def bundled_python(folder: Path) -> Path: + return folder / "python" / "python.exe" if os.name == "nt" else folder / "python" / "bin" / "python3" + + +def find_target(running: str, environ=None, root: Path | None = None): + """(folder, version, problem). folder is a newer, whole Control; or None with problem None (nothing to do) or a reason + (a newer Control is named but cannot be used).""" + root = components_dir(environ) if root is None else Path(root) + base = root / "control" + try: + pointer = _read_json(base / "active.json") + except (OSError, ValueError): + return None, None, None + if not isinstance(pointer, dict): + return None, None, None + name = pointer.get("folder") + if not isinstance(name, str) or not _FOLDER.fullmatch(name) or name in (".", ".."): + return None, None, "its pointer names a folder outside the control folder" + folder = base / name + try: + if folder.resolve().parent != base.resolve(): + return None, None, "its pointer names a folder outside the control folder" + except OSError: + return None, None, None + # the version that counts is the one in the folder; the pointer's claim is only a fallback + version = None + for source in ("VERSION", "BUNDLE.json"): + try: + if source == "VERSION": + version = (folder / source).read_text(encoding="utf-8-sig").strip() + else: + version = _read_json(folder / source).get("version") + except (OSError, ValueError, AttributeError): + continue + if version_key(version): + break + version = None + if version is None: + version = pointer.get("version") + have, want = version_key(running), version_key(version) + if want is None or have is None or want <= have: + return None, None, None # never an older or equal Control; an unreadable version is ignored + if not (bundled_python(folder).is_file() and (folder / "strata.py").is_file() and (folder / "strata_control").is_dir()): + return None, version, f"{folder} is missing its interpreter or entry point" + return folder, version, None + + +def _child_env(environ) -> dict: + env = dict(environ) + env[ENV_GUARD] = "1" + env["PYTHONNOUSERSITE"] = "1" + env.pop("PYTHONHOME", None) + env.pop("PYTHONPATH", None) + return env + + +def maybe_hand_over(argv, environ=None, root=None, running=None, execv=None, run=None, warn=None) -> int | None: + """Returns None to carry on with the current Control, or an exit code when a newer Control already ran this command + (Windows; on POSIX the process is replaced and this does not return).""" + environ = os.environ if environ is None else environ + if environ.get(ENV_GUARD) or environ.get(ENV_OFF): + return None + if running is None: + import strata_cli + running = strata_cli.version() + warn = warn or (lambda text: sys.stderr.write(text + "\n")) + try: + folder, version, problem = find_target(running, environ, root) + except Exception: # noqa: BLE001 - a hand-over must never be the thing that breaks the CLI + return None + if problem: + what = f"Control {version}" if version else "Control" + warn(f"strata: a newer {what} was installed but {problem}; running {running} instead. Run `strata update` again to repair it.") + return None + if folder is None: + return None + python, entry = str(bundled_python(folder)), str(folder / "strata.py") + command = [python, entry, *argv] + env = _child_env(environ) + if os.name != "nt": + try: + (execv or os.execve)(python, command, env) + except OSError as exc: + warn(f"strata: could not start the updated Control {version} ({exc.strerror or exc}); running {running} instead.") + return None + try: + return (run or subprocess.call)(command, env=env, cwd=os.getcwd()) + except KeyboardInterrupt: + return 130 + except OSError as exc: + warn(f"strata: could not start the updated Control {version} ({exc.strerror or exc}); running {running} instead.") + return None diff --git a/strata_cli/update_cmd.py b/strata_cli/update_cmd.py index 4bdb089c..67e89937 100644 --- a/strata_cli/update_cmd.py +++ b/strata_cli/update_cmd.py @@ -114,7 +114,7 @@ def _line(name: str, result: dict) -> str: return f"{name:<8}{before or 'none'} {result.get('note') or status}" if result.get("component") == "control": if status == "updated": - return f"{name:<8}{result.get('installed_before') or '?'} -> {result.get('installed_after')} updated (takes effect on the next start)" + return f"{name:<8}{result.get('installed_before') or '?'} -> {result.get('installed_after')} updated. The next `strata` command already runs it; the app switches on its next start" if status == "current": return f"{name:<8}{result.get('installed_before')} up to date" if status == "not-in-feed": diff --git a/strata_control/updater.py b/strata_control/updater.py index 9c12445c..308c1094 100644 --- a/strata_control/updater.py +++ b/strata_control/updater.py @@ -931,7 +931,7 @@ def update_control(ctx: Context, feed: feedmod.Feed, state: State) -> dict: ctx.say("test", f"Test-starting Control {pkg.version}", component="control") try: done = subprocess.run([interpreter, str(entry), "--version"], capture_output=True, text=True, timeout=120, cwd=str(stage), - env={**ctx.environ, "PYTHONNOUSERSITE": "1", "STRATA_NO_ACQUIRE": "1"}, + env={**ctx.environ, "PYTHONNOUSERSITE": "1", "STRATA_NO_ACQUIRE": "1", "STRATA_HANDOVER": "1"}, creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0)) except (OSError, subprocess.SubprocessError) as exc: raise TestStartFailed(f"Control {pkg.version}", f"{type(exc).__name__}: {exc}") from None @@ -957,7 +957,7 @@ def update_control(ctx: Context, feed: feedmod.Feed, state: State) -> dict: "from": decision["installed"], "to": pkg.version, "ok": True}) archive.unlink(missing_ok=True) result.update({"changed": True, "status": "updated", "installed_after": pkg.version, - "note": "Control switches on the next start of the app or the terminal"}) + "note": "the Terminal hands over to it from the next command; the app uses it from its next start"}) return result finally: shutil.rmtree(longpath.long_path(stage), ignore_errors=True) diff --git a/tests/terminal/test_handover.py b/tests/terminal/test_handover.py new file mode 100644 index 00000000..a623d76d --- /dev/null +++ b/tests/terminal/test_handover.py @@ -0,0 +1,160 @@ +"""`strata update` installs a newer Control; the Terminal on PATH hands over to it (it used to keep running the old one).""" + +import json +import os +import stat +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path + +from strata_cli import handover + +ROOT = Path(__file__).resolve().parents[2] +WINDOWS = os.name == "nt" + + +def make_control(components: Path, version: str, folder: str | None = None, whole: bool = True, point: bool = True) -> Path: + folder = folder or version + d = components / "control" / folder + (d / "strata_control").mkdir(parents=True, exist_ok=True) + (d / "VERSION").write_text(version + "\n", encoding="utf-8") + (d / "strata.py").write_text("print('control', %r)\n" % version, encoding="utf-8") + if whole: + py = handover.bundled_python(d) + py.parent.mkdir(parents=True, exist_ok=True) + py.write_text("stub", encoding="utf-8") + if point: + (components / "control" / "active.json").write_text(json.dumps({"version": version, "folder": folder}), encoding="utf-8") + return d + + +class Handover(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory(prefix="strata-handover-") + self.addCleanup(self.temp.cleanup) + self.comp = Path(self.temp.name) / "components" + self.comp.mkdir() + self.env = {"STRATA_COMPONENTS_DIR": str(self.comp)} + self.calls, self.warnings = [], [] + + def go(self, running="0.1.46", env=None, argv=("status",)): + def fake(*args, **kwargs): + self.calls.append((args, kwargs)) + return 7 + env = {**self.env, **(env or {})} + return handover.maybe_hand_over(list(argv), environ=env, running=running, execv=fake, run=fake, warn=self.warnings.append) + + def test_a_newer_control_takes_over_with_its_own_interpreter_and_the_same_arguments(self): + d = make_control(self.comp, "0.1.46.1") + result = self.go(argv=("serve", "--port", "1")) + self.assertEqual(len(self.calls), 1) + args, kwargs = self.calls[0] + python, command = (args[0], args[1]) if not WINDOWS else (args[0][0], args[0]) + self.assertEqual(Path(python), handover.bundled_python(d)) + self.assertEqual(command[1:], [str(d / "strata.py"), "serve", "--port", "1"]) + env = kwargs.get("env") or args[2] + self.assertEqual(env["STRATA_HANDOVER"], "1") + if WINDOWS: + self.assertEqual(result, 7, "the exit code of the newer Control is passed through") + self.assertEqual(self.warnings, []) + + def test_no_loop_when_already_handed_over(self): + make_control(self.comp, "0.1.46.1") + self.assertIsNone(self.go(env={"STRATA_HANDOVER": "1"})) + self.assertIsNone(self.go(env={"STRATA_NO_HANDOVER": "1"})) + self.assertEqual(self.calls, []) + + def test_a_broken_target_falls_back_with_one_warning(self): + make_control(self.comp, "0.1.46.1", whole=False) + self.assertIsNone(self.go()) + self.assertEqual(self.calls, []) + self.assertEqual(len(self.warnings), 1) + self.assertIn("0.1.46.1", self.warnings[0]) + self.assertIn("running 0.1.46 instead", self.warnings[0]) + + def test_a_target_that_fails_to_start_falls_back(self): + make_control(self.comp, "0.1.46.1") + + def boom(*a, **k): + raise OSError(8, "Exec format error") + result = handover.maybe_hand_over(["status"], environ=self.env, running="0.1.46", execv=boom, run=boom, warn=self.warnings.append) + self.assertIsNone(result) + self.assertEqual(len(self.warnings), 1) + + def test_an_older_or_equal_target_is_ignored(self): + make_control(self.comp, "0.1.45") + self.assertIsNone(self.go(running="0.1.46")) + make_control(self.comp, "0.1.46") + self.assertIsNone(self.go(running="0.1.46")) + self.assertIsNone(self.go(running="0.1.46.1")) + self.assertEqual((self.calls, self.warnings), ([], [])) + + def test_the_version_in_the_folder_counts_not_the_pointers_claim(self): + d = make_control(self.comp, "0.1.45") + (self.comp / "control" / "active.json").write_text(json.dumps({"version": "9.9.9", "folder": "0.1.45"}), encoding="utf-8") + self.assertIsNone(self.go(running="0.1.46")) + self.assertTrue(d.is_dir()) + + def test_a_pointer_cannot_leave_the_control_folder(self): + outside = Path(self.temp.name) / "etc" + (outside / "strata_control").mkdir(parents=True) + (outside / "VERSION").write_text("9.0.0", encoding="utf-8") + (outside / "strata.py").write_text("print('evil')", encoding="utf-8") + py = handover.bundled_python(outside) + py.parent.mkdir(parents=True) + py.write_text("x", encoding="utf-8") + (self.comp / "control").mkdir(exist_ok=True) + for folder in ("../../etc", "..", "../etc", "a/b", "/etc", "..\\etc", ""): + (self.comp / "control" / "active.json").write_text(json.dumps({"version": "9.0.0", "folder": folder}), encoding="utf-8") + self.assertIsNone(self.go(), folder) + self.assertEqual(self.calls, []) + + @unittest.skipIf(WINDOWS, "needs a symlink") + def test_a_folder_that_is_a_link_out_of_the_control_folder_is_refused(self): + real = make_control(Path(self.temp.name) / "elsewhere", "9.0.0", point=False) + (self.comp / "control").mkdir(exist_ok=True) + (self.comp / "control" / "9.0.0").symlink_to(real, target_is_directory=True) + (self.comp / "control" / "active.json").write_text(json.dumps({"version": "9.0.0", "folder": "9.0.0"}), encoding="utf-8") + self.assertIsNone(self.go()) + self.assertEqual(self.calls, []) + + def test_no_pointer_or_garbage_means_nothing_happens(self): + self.assertIsNone(self.go()) + (self.comp / "control").mkdir() + for text in ("{", "[]", "null", json.dumps({"folder": "x"})): + (self.comp / "control" / "active.json").write_text(text, encoding="utf-8") + self.assertIsNone(self.go(), text) + self.assertEqual((self.calls, self.warnings), ([], [])) + + @unittest.skipIf(WINDOWS, "a shell stub stands in for the bundled interpreter") + def test_end_to_end_the_real_entry_point_hands_over_and_does_not_loop(self): + newer = make_control(self.comp, "99.0.0") + py = handover.bundled_python(newer) + py.write_text('#!/bin/sh\nexec "%s" "$@"\n' % sys.executable, encoding="utf-8") + py.chmod(py.stat().st_mode | stat.S_IXUSR) + (newer / "strata.py").write_text("import os,sys\nprint('control 99', os.environ.get('STRATA_HANDOVER'), sys.argv[1:])\nraise SystemExit(3)\n", + encoding="utf-8") + done = subprocess.run([sys.executable, str(ROOT / "strata.py"), "--version"], capture_output=True, text=True, + env={**os.environ, "STRATA_COMPONENTS_DIR": str(self.comp)}) + self.assertEqual(done.returncode, 3, done.stderr) + self.assertIn("control 99 1 ['--version']", done.stdout) + # with the guard set the current Control runs, and says its own version + done = subprocess.run([sys.executable, str(ROOT / "strata.py"), "--version"], capture_output=True, text=True, + env={**os.environ, "STRATA_COMPONENTS_DIR": str(self.comp), "STRATA_HANDOVER": "1"}) + self.assertEqual(done.returncode, 0, done.stderr) + self.assertTrue(done.stdout.startswith("strata "), done.stdout) + + def test_the_entry_point_falls_back_when_the_target_is_broken(self): + make_control(self.comp, "99.0.0", whole=False) + done = subprocess.run([sys.executable, str(ROOT / "strata.py"), "--version"], capture_output=True, text=True, + env={**os.environ, "STRATA_COMPONENTS_DIR": str(self.comp)}) + self.assertEqual(done.returncode, 0, done.stderr) + self.assertTrue(done.stdout.startswith("strata "), done.stdout) + self.assertEqual(len(done.stderr.strip().splitlines()), 1, done.stderr) + self.assertIn("99.0.0", done.stderr) + + +if __name__ == "__main__": + unittest.main() From c0c3a06ce40ceb35693a711eb52717547ba1933a Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Tue, 20 Oct 2026 13:21:46 +0200 Subject: [PATCH 03/47] Hand-over: a source checkout never hands over to an installed Control --- strata_cli/handover.py | 8 ++++++++ tests/terminal/test_handover.py | 19 ++++++++++++++++--- 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/strata_cli/handover.py b/strata_cli/handover.py index 50964593..7067abc3 100644 --- a/strata_cli/handover.py +++ b/strata_cli/handover.py @@ -21,6 +21,12 @@ from pathlib import Path ENV_GUARD = "STRATA_HANDOVER" ENV_OFF = "STRATA_NO_HANDOVER" +ENV_CHECKOUT = "STRATA_HANDOVER_IN_CHECKOUT" # tests only: allow a hand-over from a source checkout + + +def running_from_checkout() -> bool: + """True when this Terminal runs from a git checkout (the source route) rather than an installed bundle.""" + return (Path(__file__).resolve().parents[1] / ".git").exists() _FOLDER = re.compile(r"^[\w.+-]+$") _VERSION = re.compile(r"^[0-9]+(\.[0-9]+){1,3}$") @@ -109,6 +115,8 @@ def maybe_hand_over(argv, environ=None, root=None, running=None, execv=None, run environ = os.environ if environ is None else environ if environ.get(ENV_GUARD) or environ.get(ENV_OFF): return None + if root is None and not environ.get(ENV_CHECKOUT) and running_from_checkout(): + return None # a source checkout runs its own code, never an installed Control if running is None: import strata_cli running = strata_cli.version() diff --git a/tests/terminal/test_handover.py b/tests/terminal/test_handover.py index a623d76d..8fc7f22e 100644 --- a/tests/terminal/test_handover.py +++ b/tests/terminal/test_handover.py @@ -36,7 +36,7 @@ class Handover(unittest.TestCase): self.addCleanup(self.temp.cleanup) self.comp = Path(self.temp.name) / "components" self.comp.mkdir() - self.env = {"STRATA_COMPONENTS_DIR": str(self.comp)} + self.env = {"STRATA_COMPONENTS_DIR": str(self.comp), handover.ENV_CHECKOUT: "1"} self.calls, self.warnings = [], [] def go(self, running="0.1.46", env=None, argv=("status",)): @@ -46,6 +46,19 @@ class Handover(unittest.TestCase): env = {**self.env, **(env or {})} return handover.maybe_hand_over(list(argv), environ=env, running=running, execv=fake, run=fake, warn=self.warnings.append) + def test_a_source_checkout_never_hands_over(self): + make_control(self.comp, "0.1.46.1") + env = {k: v for k, v in self.env.items() if k != handover.ENV_CHECKOUT} + original = handover.running_from_checkout + handover.running_from_checkout = lambda: True + try: + result = handover.maybe_hand_over(["status"], environ=env, running="0.1.46", execv=None, + run=lambda *a, **k: self.fail("handed over"), warn=self.warnings.append) + finally: + handover.running_from_checkout = original + self.assertIsNone(result) + self.assertEqual(self.warnings, []) + def test_a_newer_control_takes_over_with_its_own_interpreter_and_the_same_arguments(self): d = make_control(self.comp, "0.1.46.1") result = self.go(argv=("serve", "--port", "1")) @@ -137,7 +150,7 @@ class Handover(unittest.TestCase): (newer / "strata.py").write_text("import os,sys\nprint('control 99', os.environ.get('STRATA_HANDOVER'), sys.argv[1:])\nraise SystemExit(3)\n", encoding="utf-8") done = subprocess.run([sys.executable, str(ROOT / "strata.py"), "--version"], capture_output=True, text=True, - env={**os.environ, "STRATA_COMPONENTS_DIR": str(self.comp)}) + env={**os.environ, "STRATA_COMPONENTS_DIR": str(self.comp), handover.ENV_CHECKOUT: "1"}) self.assertEqual(done.returncode, 3, done.stderr) self.assertIn("control 99 1 ['--version']", done.stdout) # with the guard set the current Control runs, and says its own version @@ -149,7 +162,7 @@ class Handover(unittest.TestCase): def test_the_entry_point_falls_back_when_the_target_is_broken(self): make_control(self.comp, "99.0.0", whole=False) done = subprocess.run([sys.executable, str(ROOT / "strata.py"), "--version"], capture_output=True, text=True, - env={**os.environ, "STRATA_COMPONENTS_DIR": str(self.comp)}) + env={**os.environ, "STRATA_COMPONENTS_DIR": str(self.comp), handover.ENV_CHECKOUT: "1"}) self.assertEqual(done.returncode, 0, done.stderr) self.assertTrue(done.stdout.startswith("strata "), done.stdout) self.assertEqual(len(done.stderr.strip().splitlines()), 1, done.stderr) From e52668857c344a98c095eca6470ec0e369dcbcde Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Tue, 20 Oct 2026 13:28:53 +0200 Subject: [PATCH 04/47] API key is optional beyond this computer: warn, never refuse The server and strata serve start on 0.0.0.0 without a key and print one plain warning. strata launch gets --no-api-key; the Access screen makes a key by default and t turns it off. api_key "none" in a config means no key on purpose. Cloudflare without a key gets a stronger warning. Docs updated. --- AGENTS.md | 2 +- README.md | 2 +- docs/AI_SETUP.md | 10 +++++---- docs/DETAILS.md | 4 +++- docs/SAFETY.md | 2 +- docs/TERMINAL_LAUNCH.md | 2 +- serve/server.py | 35 ++++++++++++++++++++++++------ serve/test_security.py | 19 ++++++++++++++++ setup.py | 2 +- strata_cli/cli.py | 17 ++++++++------- strata_cli/launch/access.py | 2 +- strata_cli/launch/cmd.py | 14 +++++++++--- strata_cli/launch/runner.py | 2 ++ strata_cli/launch/screens.py | 24 ++++++++++++--------- strata_cli/launch/settings.py | 15 +++++++++++-- strata_control/readiness.py | 2 ++ tests/terminal/test_launch.py | 36 +++++++++++++++++++++++++++++++ tests/terminal/test_launch_tui.py | 23 +++++++++++++++++++- tests/terminal/test_runtime.py | 14 ++++++++++++ tests/terminal/test_terminal.py | 30 +++++++++++++------------- tools/strata_mcp.py | 7 ++++-- 21 files changed, 205 insertions(+), 59 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 92f91882..6615dc04 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -45,7 +45,7 @@ Follow **[docs/AI_SETUP.md](docs/AI_SETUP.md)**. For an agent that has a shell, 4. Connect the user's apps: `strata connect` lists them, `strata connect --check` sends one prompt and one tool call the way that app does. -Never expose the server beyond `127.0.0.1` without an API key. `--access lan` makes a key for you. The old route (clone +Keep the server on `127.0.0.1` unless the user asks for more. Beyond it an API key is recommended: `--access lan` makes one for you, and `--no-api-key` serves without one (a warning, never a refusal; on a public tunnel the warning is stronger). The old route (clone the repository and run `START-HERE.bat --yes` or `./setup.sh --yes`) still works and is the fallback when the Terminal cannot run. Strata's MCP server ([docs/MCP_SERVER.md](docs/MCP_SERVER.md)) offers the same steps as tools. diff --git a/README.md b/README.md index a8df65bf..4b7b92e4 100644 --- a/README.md +++ b/README.md @@ -246,7 +246,7 @@ strata doctor # check the installed engine file `strata --help` lists everything. Starting and serving never download anything. Only the install, `strata launch` (when you choose a model) and `strata update` do. To reach Strata from your phone or another PC, use -`strata launch --access lan`. It makes an API key and will not start on a network without one. No browser opens unless +`strata launch --access lan`. It makes an API key (recommended; add `--no-api-key` to go without, with a warning). No browser opens unless you add `--open`. Guide: [docs/TERMINAL_LAUNCH.md](docs/TERMINAL_LAUNCH.md). Whole client: [docs/TERMINAL.md](docs/TERMINAL.md). ### With AI agents diff --git a/docs/AI_SETUP.md b/docs/AI_SETUP.md index b84bdf4e..36ae9d42 100644 --- a/docs/AI_SETUP.md +++ b/docs/AI_SETUP.md @@ -13,10 +13,11 @@ Work through the steps in order. Tell the user what you are doing in plain words ## 0. Ground rules -- **Never expose the server without an API key.** Keep the default (`--access local`, the server listens on - `127.0.0.1` only). Only if the user asks for access from other devices, use `--access lan`. Strata makes a long - random key for you then and will not start on a network without one. Give the user the key - (`strata launch --show-key`). Never put a tunnel or port forward in front of a server without a key. +- **Recommend an API key beyond this computer; do not force it.** Keep the default (`--access local`, the server listens on + `127.0.0.1` only, no key needed). Only if the user asks for access from other devices, use `--access lan`. Strata makes a long + random key for you then. Give the user the key (`strata launch --show-key`). If the user says they do not want a key, use + `--no-api-key`: it starts and warns that anyone who can reach the port can use the model and its tools. Tell the user so. + Do not put a tunnel or port forward in front of a server without a key unless the user asks for it. - Do not change the user's system beyond what Strata does. The Terminal installs into the user's home folder and needs no administrator rights. It does not install drivers, Python packages or compilers. Ask before installing drivers. - The model download is ~70 GB (94 GB for Unsloth's UD-IQ4_XS, 111 GB for UD-Q4_K_XL). Confirm the user is fine with @@ -114,6 +115,7 @@ The flags (all of them, with examples: `strata launch --help`): | `--access local\|lan\|cloudflare\|tailscale` | who can connect; beyond `local` a key is made for you | | `--port N` | the server port (default 8080) | | `--api-key KEY`, `--api-key-env NAME`, `--new-key` | the key clients must send | +| `--no-api-key` | share without a key (a warning, not a refusal; recommended only on a network you trust) | | `--save-preset NAME` | keep these choices; `strata launch --preset NAME` starts them again | | `--plan` | show what would happen and exit | | `--yes`, `--no-tui` | no questions, no screens | diff --git a/docs/DETAILS.md b/docs/DETAILS.md index 2d72e592..80d6d704 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -1072,7 +1072,9 @@ print(r.choices[0].message.content) editable there. - **From other devices on your network.** The server listens on your PC only (`127.0.0.1`) unless you say otherwise: run setup with `START-HERE.bat --setup --host 0.0.0.0 --api-key some-long-secret` (or add `"host": "0.0.0.0"` and - `"api_key": "..."` to `strata-.json`). The server window then prints this PC's addresses + `"api_key": "..."` to `strata-.json`). The key is recommended, not required: without one the server still starts and + warns that anyone who can reach the port can use the model and its tools (to say it is on purpose, use `--no-api-key` on + the server or `"api_key": "none"` in the config, which silences the config-empty note). The server window then prints this PC's addresses (`from other devices: http://192.168.x.x:8080/`); open that on the other device, or use `.../v1` as an API base URL. On Windows the firewall blocks it until you allow it: accept its prompt for Python (private networks), or run `New-NetFirewallRule -DisplayName "Strata 8080" -Direction Inbound -Protocol TCP -LocalPort 8080 -Action Allow -Profile Private` diff --git a/docs/SAFETY.md b/docs/SAFETY.md index 892f6363..6145c448 100644 --- a/docs/SAFETY.md +++ b/docs/SAFETY.md @@ -49,7 +49,7 @@ Like any download, each connection below shows the other side your IP address an | llama.cpp source code (a fixed commit) | github.com/ggml-org/llama.cpp | During a model install, if it is not on your PC yet. Strata uses only its model-preparation scripts | | Web search and web pages | DuckDuckGo, with Bing as the second source; or Exa, Perplexity or DeepSeek if you save a key for them. Any page the agent is asked to open goes to that page's site | When the agent uses its search or "open web pages" tool. In Manual mode it asks you first, once per chat | | Outside model services | The service you add (OpenAI, Anthropic, OpenRouter, a server on your network and others) | Only for chats with that model, and only after you add its key | -| Cloudflare tunnel | Cloudflare, through the `cloudflared` program | Only while you have the tunnel on, and it will not start without an API key | +| Cloudflare tunnel | Cloudflare, through the `cloudflared` program | Only while you have the tunnel on, and Strata makes an API key for it unless you pass `--no-api-key` (then it warns that anyone who finds the address can use your model) | | Tailscale, local network | Not Strata's traffic. Strata only reads Tailscale's status and shows the address | Only if you choose that access in `strata launch` | | An image link in an API request | The address in the link | Only when a program sends your server a request with an `http(s)` image link. `--offline` refuses it | | Remote tool servers (MCP) | The address you put in the run config | Only when you add one | diff --git a/docs/TERMINAL_LAUNCH.md b/docs/TERMINAL_LAUNCH.md index 5c230737..80549729 100644 --- a/docs/TERMINAL_LAUNCH.md +++ b/docs/TERMINAL_LAUNCH.md @@ -38,7 +38,7 @@ The release folder is the latest GitHub release of Niko1221/Strata (`https://git 8. **Advanced** (optional): every engine setting with default, tuned value and your value; edit, reset, add a setting by name (checked against the engine's own list; a warning, not a refusal); the exact command (it includes the context, memory format and picture choice you made above; it has its own scroll area: Tab, then the arrows) and the matching `strata launch` flags. 9. **Access**: this computer only (127.0.0.1), your network (LAN address, key), Cloudflare quick tunnel (needs `cloudflared`), Tailscale (needs it installed and connected); port; API key - (made for you beyond this computer: the server will not start on a network without one). + (optional, recommended beyond this computer: Strata makes one for you, and one keypress (`t`) turns it off. Without a key the server still starts and warns that anyone who can reach the port can use the model and its tools; `--no-api-key` does the same without the screens, and on a Cloudflare tunnel the warning is stronger. This computer only never needs a key). 10. **Save as preset** and launch. Then downloads (with progress), engine start, and the monitor. In a small window the summary shrinks so the three choices stay on screen, and the key line says what Enter will do. No web page opens by itself; only `--open` opens one. diff --git a/serve/server.py b/serve/server.py index b0e2df9a..dc653e90 100644 --- a/serve/server.py +++ b/serve/server.py @@ -7200,6 +7200,22 @@ def key_list(value) -> list[str]: return [k.strip() for k in str(value).split(",") if k.strip()] +def explicit_no_key(value) -> bool: + """The owner chose to serve without a key: "api_key": "none" in the config, STRATA_API_KEY=none or --api-key none + (or --no-api-key, handled by the caller). Never a key called "none".""" + return isinstance(value, str) and value.strip().lower() == "none" + + +def open_server_warning(port, public=False, tools=False) -> str: + """The one plain warning for a server on the network with no API key (recommend, never force).""" + msg = f"no API key: anyone who can reach port {port} can use the model" + (" and its tools" if tools else "") + "." + if tools: + msg += " The tools can read and change files on this computer." + if public: + msg += " This address is on the public internet, so anyone who finds it can use it." + return msg + " Add an API key to keep others out." + + def api_key_of(value): """The key as a client can send it (#725). An HTTP header loses the spaces and line ends around its value, so a key kept with them (a config file or an environment file with CRLF line ends, a quoted " key ") matched no @@ -7698,6 +7714,9 @@ def main(argv=None, *, lifecycle_event=None, interrupt_exit_code: int = 0) -> in ap.add_argument("--api-key", default=os.environ.get("STRATA_API_KEY", ""), help="require this key on /v1/* (Authorization: Bearer ... or x-api-key); also $STRATA_API_KEY. " "Several keys: separate them with commas (key1,key2), as llama.cpp does") + ap.add_argument("--no-api-key", action="store_true", + help="serve on the network without an API key (anyone who can reach the port can use the model; " + "also \"api_key\": \"none\" in the config). Warns once, never refuses") ap.add_argument("--mcp-config", help="a JSON file with MCP servers in Claude Desktop's format ({\"mcpServers\": " "{...}}); the web app's chat can use their tools (also \"mcp_servers\" in " "the config)") @@ -7803,14 +7822,16 @@ def main(argv=None, *, lifecycle_event=None, interrupt_exit_code: int = 0) -> in x.strip() == "--api-key=" for i, x in enumerate(supplied_args)): print("[strata] an API key was given but it is empty: set a key, or leave it out", file=sys.stderr) return 2 + raw_key = a.api_key or cfg.get("api_key", "") + no_key_chosen = bool(getattr(a, "no_api_key", False)) or explicit_no_key(raw_key) + if explicit_no_key(raw_key): + raw_key = "" try: - preflight_api_key = api_key_of(a.api_key or cfg.get("api_key", "")) + preflight_api_key = api_key_of(raw_key) except ValueError as e: print(f"[strata] {e}: set a key, or leave it out", file=sys.stderr) return 2 - if a.host not in ("127.0.0.1", "localhost", "::1") and not preflight_api_key: - print("[strata] a non-loopback bind requires an inference API key", file=sys.stderr, flush=True) - return 2 + # A key is recommended on a network, never required (owner decision 2026-10-20): the banner below warns once. try: # before the minutes of loading: is the port free? Server((a.host, a.port), BaseHTTPRequestHandler).server_close() except OSError as e: @@ -7992,7 +8013,7 @@ def main(argv=None, *, lifecycle_event=None, interrupt_exit_code: int = 0) -> in if set(key_list(svc.api_key)) & set(key_list(svc.telemetry_key)): print("[strata] telemetry_read_key must differ from every inference API key", file=sys.stderr) return 2 - if not svc.api_key and "api_key" in cfg: # #569: written, but empty: the server has none (a warning, not a stop) + if not svc.api_key and "api_key" in cfg and not no_key_chosen: # #569: written, but empty: the server has none (a warning, not a stop) print("[strata] the api_key in the config is empty: this server has no API key (anyone who can reach it can " "use it); set one, or leave api_key out", file=sys.stderr, flush=True) svc.cors_origins = origins_of(cfg.get("cors_origins"), "cors_origins", wildcard=True) @@ -8116,8 +8137,8 @@ def main(argv=None, *, lifecycle_event=None, interrupt_exit_code: int = 0) -> in if not ips: print(" from other devices: http://:" + str(bound_port) + "/", flush=True) if not svc.api_key: - print(" WARNING: no API key - anyone on your network can use this model. Add \"api_key\": \"...\" " - "to the config (clients send it as their API key; the web page asks for it)", flush=True) + print(" WARNING: " + open_server_warning(bound_port, tools=svc.mcp is not None), + flush=True) if os.name == "nt": print(" nothing arrives? Windows Firewall blocks it until allowed: accept its prompt for Python, or run " "in an admin PowerShell:\n New-NetFirewallRule -DisplayName \"Strata " + str(bound_port) + "\" " diff --git a/serve/test_security.py b/serve/test_security.py index c50ee69a..4b00f440 100644 --- a/serve/test_security.py +++ b/serve/test_security.py @@ -344,5 +344,24 @@ class OverHttp(unittest.TestCase): host="rebind.example.com")[0], 403) +class NoApiKey(unittest.TestCase): + """A key is recommended on a network, never required (owner decision 2026-10-20).""" + + def test_none_means_no_key_on_purpose(self): + from serve.server import explicit_no_key + for v in ("none", " None ", "NONE"): + self.assertTrue(explicit_no_key(v)) + for v in ("", None, "sk-none", ["none"], "none,x"): + self.assertFalse(explicit_no_key(v)) + + def test_the_warning_is_plain(self): + from serve.server import open_server_warning + w = open_server_warning(8080) + self.assertIn("anyone who can reach port 8080 can use the model", w) + self.assertNotIn("tools", w) + self.assertIn("and its tools", open_server_warning(8080, tools=True)) + self.assertIn("public internet", open_server_warning(8080, public=True)) + + if __name__ == "__main__": unittest.main() diff --git a/setup.py b/setup.py index 27a36944..25cc50ff 100644 --- a/setup.py +++ b/setup.py @@ -7383,7 +7383,7 @@ def main() -> int: ap.add_argument("--no-remote-expert-opt", action="store_true", help="with two or more GPUs: leave out --remote-expert-opt, which setup adds there (#578)") ap.add_argument("--host", help="where the server listens: 127.0.0.1 = this PC only (default), 0.0.0.0 = also other " - "devices on your network (issue #26; set --api-key too)") + "devices on your network (issue #26; an --api-key is recommended)") ap.add_argument("--api-key", help="require this key from clients (recommended with --host 0.0.0.0); several keys: key1,key2") ap.add_argument("--no-browser", dest="browser", action="store_false", default=None, help="do not open the chat page in the browser when the model is ready (for a harness or an app " diff --git a/strata_cli/cli.py b/strata_cli/cli.py index a03030a5..cc1dded4 100644 --- a/strata_cli/cli.py +++ b/strata_cli/cli.py @@ -684,13 +684,14 @@ def _launch_plan(ref: str, cli: argparse.Namespace | None = None) -> tuple[dict, path, saved, revision, cfg = _source(ref) values, origins = _effective(cfg, saved, cli) host = values["host"] - from serve.server import api_key_of, key_list - try: - has_key = bool(key_list(api_key_of(os.environ.get("STRATA_API_KEY") or cfg.get("api_key", "")))) - except ValueError: - raise ProfileError("the inference API key is invalid", 5) from None - if host not in ("127.0.0.1", "localhost", "::1") and not has_key: - raise ProfileError("non-loopback serving requires an API key in the run config or STRATA_API_KEY") + from serve.server import api_key_of, explicit_no_key, key_list + raw_key = os.environ.get("STRATA_API_KEY") or cfg.get("api_key", "") + if not explicit_no_key(raw_key): + try: + key_list(api_key_of(raw_key)) + except ValueError: + raise ProfileError("the inference API key is invalid", 5) from None + # A key is recommended on a network, never required: the server warns once at start (owner decision 2026-10-20). server_args = ["--engine", getattr(cli, "engine", "strata"), "--config", str(path), "--host", str(host), "--port", str(values["port"])] if cli is not None: @@ -1161,7 +1162,7 @@ def _bench_standard(a: argparse.Namespace, machine: bool) -> int: host = "127.0.0.1" if host in ("0.0.0.0", "::") else host authority = f"[{host}]" if ":" in host and not host.startswith("[") else host url = f"http://{authority}:{plan['effective']['port']}" - if not key and cfg.get("api_key"): + if not key and cfg.get("api_key") and str(cfg["api_key"]).strip().lower() != "none": from serve.server import api_key_of, key_list keys = key_list(api_key_of(cfg["api_key"])) key = keys[0] if keys else None diff --git a/strata_cli/launch/access.py b/strata_cli/launch/access.py index 5c8598eb..b040263b 100644 --- a/strata_cli/launch/access.py +++ b/strata_cli/launch/access.py @@ -376,7 +376,7 @@ def start_tunnel(name: str, port: int, *, wait: float = 45.0) -> tuple[str | Non stop_tunnel(name) return None, ("The Cloudflare tunnel did not come up in time. Check your internet connection and try again; " "the server itself is running and still works on this computer.") - return url, "The Cloudflare tunnel is up. Anyone with the address can reach the server, so keep the API key on." + (" " + note if note else "") + return url, "The Cloudflare tunnel is up. Anyone with the address can reach the server; an API key keeps others out." + (" " + note if note else "") def tunnel_info(name: str) -> dict | None: diff --git a/strata_cli/launch/cmd.py b/strata_cli/launch/cmd.py index 3eb551eb..d3c8c5b1 100644 --- a/strata_cli/launch/cmd.py +++ b/strata_cli/launch/cmd.py @@ -107,6 +107,7 @@ def add_parsers(sp: argparse._SubParsersAction) -> list[argparse.ArgumentParser] a.add_argument("--api-key", metavar="KEY", help="the key clients must send (made for you when you share beyond this computer)") a.add_argument("--api-key-env", metavar="NAME", help="read the key from this environment variable") a.add_argument("--new-key", action="store_true", help="make a new API key") + a.add_argument("--no-api-key", action="store_true", help="share beyond this computer without an API key (a warning is shown, nothing is refused)") o = p.add_argument_group("running") o.add_argument("--save-preset", metavar="NAME", help="save these choices under this name") o.add_argument("--no-tui", action="store_true", help="no screens: serve, print the address and return") @@ -219,6 +220,13 @@ def settings_from_args(a: argparse.Namespace, catalog=None) -> tuple[S.LaunchSet if not val: raise ValueError(f"The environment variable {a.api_key_env} is empty or not set.") s.api_key = val + if a.no_api_key: + if a.api_key or a.api_key_env: + notices.append(S.Notice("warn", "An API key was given as well as --no-api-key, so the key is kept.", "")) + else: + s.api_key, s.no_key = None, True # also drops a key a saved preset had + elif s.api_key: + s.no_key = False if a.set: s.extra = {**s.extra, **S.settings_from_pairs(a.set)} if a.save_preset: @@ -258,7 +266,7 @@ def apply_defaults(s: S.LaunchSettings, catalog) -> tuple[S.LaunchSettings, list notices.append(S.Notice("warn", "The engine installed here has no picture reader, so pictures are off.", "Update the engine to read pictures, or add --vision off to silence this.")) notices += S.check_context(s, max_fit_tokens=None) - if s.access != "local" and not s.api_key: + if s.access != "local" and not s.api_key and not s.no_key: from strata_cli.launch import access s.api_key = access.new_key() notices.append(S.Notice("warn", "A new API key was made, because the server is shared beyond this computer.", @@ -462,7 +470,7 @@ def launch_info(name: str | None = None) -> dict | None: if pick is None and preset is None: return None port = (pick or {}).get("port") or (preset.port if preset else S.DEFAULT_PORT) - return {"url": (pick or {}).get("url") or f"http://127.0.0.1:{port}", "key": cfg.get("api_key") or (preset.api_key if preset else None), + return {"url": (pick or {}).get("url") or f"http://127.0.0.1:{port}", "key": (cfg.get("api_key") if str(cfg.get("api_key") or "").strip().lower() != "none" else None) or (preset.api_key if preset else None), "model": cfg.get("model_name") or "strata", "context": _cfg_context(cfg), "running": bool(pick), "name": (pick or {}).get("name") or (preset.name if preset else None), "port": port, "access": preset.access if preset else None} @@ -541,7 +549,7 @@ def run_launch(a: argparse.Namespace) -> int: return fail(errors[0].line(), 2) if a.new_key: from strata_cli.launch import access - s.api_key = access.new_key() + s.api_key, s.no_key = access.new_key(), False if not s.name: s.name = f"{s.model or 'model'} {S.context_label(s.context)}" move_data = _move_data_choice(a, s, catalog, machine) diff --git a/strata_cli/launch/runner.py b/strata_cli/launch/runner.py index e44c038d..3a8b7071 100644 --- a/strata_cli/launch/runner.py +++ b/strata_cli/launch/runner.py @@ -221,6 +221,8 @@ def derive_config(base: dict, s: S.LaunchSettings, *, bool_flags: frozenset[str] cfg["port"] = int(s.port) if s.api_key: cfg["api_key"] = s.api_key + elif s.no_key and s.access != "local": + cfg["api_key"] = "none" # served without a key on purpose (the server warns once at start) else: cfg.pop("api_key", None) cfg.setdefault("exe", "component:strata-engine") diff --git a/strata_cli/launch/screens.py b/strata_cli/launch/screens.py index d6ff5a7f..5d7bf172 100644 --- a/strata_cli/launch/screens.py +++ b/strata_cli/launch/screens.py @@ -1167,8 +1167,8 @@ class AdvancedScreen(Base): 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. Anything beyond it needs the API key: the server will not " - "start on a network without one.") + 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.") BINDINGS = Base.BINDINGS + [Binding("p", "port", show=False), Binding("k", "newkey", show=False), Binding("t", "keytoggle", show=False)] @@ -1203,7 +1203,7 @@ class AccessScreen(Base): t = Text() t.append(f"\n Port [ {s.port} ] press p to change\n") t.append(f" API key [ {'on' if on else 'off'} ] {acc.mask_key(s.api_key)} ", style=FG if on else WARN) - t.append("(recommended for anything beyond this computer)" if beyond else "(optional on this computer)", style=MUTE) + t.append(("(recommended for anything beyond this computer; t = no key)" if on else "(t = make a key)") if beyond else "(not needed on this computer)", style=MUTE) self.query_one("#portkey", Static).update(t) def explain(self) -> Text: @@ -1217,9 +1217,9 @@ class AccessScreen(Base): if fw: out.append(fw + "\n", style=WARN) if cur.key == "cloudflare": - out.append("A Cloudflare quick tunnel gives a temporary public address; anyone with it can try to use the server, so keep the API key on.", style=MUTE) + out.append("A Cloudflare quick tunnel gives a temporary public address; anyone with it can try to use the server, so an API key keeps others out.", style=MUTE) elif cur.key == "lan": - out.append("Other computers on your network can use it at the address shown. Keep the API key on.", style=MUTE) + out.append("Other computers on your network can use it at the address shown. An API key is recommended.", style=MUTE) elif cur.key == "tailscale": out.append("Only devices signed in to your Tailscale network can reach it.", style=MUTE) else: @@ -1230,9 +1230,11 @@ class AccessScreen(Base): kind = self.menu().current.key s = self.ctx.settings s.access = kind - if kind != "local" and not s.api_key: + if kind != "local" and not s.api_key and not s.no_key: s.api_key = acc.new_key() - self.say("An API key was made for you, because this reaches beyond your computer.") + self.say("An API key was made for you (recommended beyond this computer). Press t if you want no key.") + elif kind != "local" and s.no_key: + self.say(S.NO_KEY_PUBLIC if kind == "cloudflare" else S.NO_KEY_NETWORK, True) def action_port(self) -> None: self.open_field("portfield", str(self.ctx.settings.port), "port number") @@ -1253,6 +1255,7 @@ class AccessScreen(Base): def action_newkey(self) -> None: self.ctx.settings.api_key = acc.new_key() + self.ctx.settings.no_key = False self.say("A new API key was made. Apps that used the old one need the new one (strata connect shows it).") self.paint() @@ -1260,9 +1263,10 @@ class AccessScreen(Base): s = self.ctx.settings if s.api_key: s.api_key = None - self.say("The API key is off." + (" The server will not start on a network without one." if s.access != "local" else ""), s.access != "local") + s.no_key = s.access != "local" + self.say("The API key is off." + ((" " + (S.NO_KEY_PUBLIC if s.access == "cloudflare" else S.NO_KEY_NETWORK)) if s.access != "local" else ""), s.access != "local") else: - s.api_key = acc.new_key() + s.api_key, s.no_key = acc.new_key(), False self.say("The API key is on.") self.paint() @@ -1275,7 +1279,7 @@ class AccessScreen(Base): def commit(self) -> None: s = self.ctx.settings s.access = self.menu().current.key - if s.access != "local" and not s.api_key: + if s.access != "local" and not s.api_key and not s.no_key: s.api_key = acc.new_key() def action_back(self) -> None: diff --git a/strata_cli/launch/settings.py b/strata_cli/launch/settings.py index 2a218648..df27ce32 100644 --- a/strata_cli/launch/settings.py +++ b/strata_cli/launch/settings.py @@ -92,6 +92,7 @@ class LaunchSettings: access: str = "local" port: int = DEFAULT_PORT api_key: str | None = None # never shown whole; stored only in the private preset file + no_key: bool = False # served beyond this computer without a key, on purpose (--no-api-key); a warning, never a refusal extra: dict[str, str] = field(default_factory=dict) # Advanced: --set key=value (flags and STRATA_* variables) # filled in by the run, kept in the preset tuned_preset: str | None = None # id of the tuning preset the tuner saved @@ -153,6 +154,11 @@ def check_port(port: Any) -> Notice | None: return None +NO_KEY_NETWORK = "No API key: anyone who can reach this port can use the model and its tools (they can read and change files on this computer)." +NO_KEY_PUBLIC = ("No API key on a public address: anyone on the internet who finds it can use the model and its tools " + "(they can read and change files on this computer).") + + def check_access(s: LaunchSettings) -> list[Notice]: out: list[Notice] = [] if s.access not in ACCESS_KINDS: @@ -164,8 +170,13 @@ def check_access(s: LaunchSettings) -> list[Notice]: if port: out.append(port) if s.access != "local" and not s.api_key: - out.append(Notice("warn", f"{ACCESS_WORDS[s.access]} without an API key lets anyone who can reach it use your computer's model.", - "Add an API key (Strata makes one for you in the Access step).")) + if s.access == "cloudflare": + out.append(Notice("warn", NO_KEY_PUBLIC, "Leave --no-api-key out to get a key.")) + elif s.no_key: + out.append(Notice("warn", NO_KEY_NETWORK, "Leave --no-api-key out to get a key.")) + else: + out.append(Notice("warn", f"{ACCESS_WORDS[s.access]} without an API key lets anyone who can reach it use your computer's model.", + "Add an API key (Strata makes one for you in the Access step).")) return out diff --git a/strata_control/readiness.py b/strata_control/readiness.py index 91a15802..859cb668 100644 --- a/strata_control/readiness.py +++ b/strata_control/readiness.py @@ -46,6 +46,8 @@ def _credential(source_bytes: bytes) -> str | None: if not isinstance(cfg, dict): raise ValueError("run config must be an object") raw = os.environ.get("STRATA_API_KEY") or cfg.get("api_key", "") + if str(raw).strip().lower() == "none": # "api_key": "none" = served without a key on purpose + return None keys = key_list(api_key_of(raw)) return keys[0] if keys else None diff --git a/tests/terminal/test_launch.py b/tests/terminal/test_launch.py index 49949325..78c718fe 100644 --- a/tests/terminal/test_launch.py +++ b/tests/terminal/test_launch.py @@ -43,6 +43,17 @@ class SettingsRules(unittest.TestCase): self.assertEqual(S.check_parallel(S.LaunchSettings(parallel=9), vram_gb=12)[0].level, "error") self.assertEqual(S.check_parallel(S.LaunchSettings(parallel=2), vram_gb=24), []) + def test_no_key_warnings_are_plain_and_stronger_in_public(self): + lan = S.check_access(S.LaunchSettings(access="lan", no_key=True)) + self.assertEqual([n.level for n in lan], ["warn"]) + self.assertIn("anyone who can reach this port can use the model and its tools", lan[0].line()) + pub = S.check_access(S.LaunchSettings(access="cloudflare", no_key=True)) + self.assertEqual([n.level for n in pub], ["warn"]) + self.assertIn("public address", pub[0].line()) + self.assertIn("anyone on the internet", pub[0].line()) + self.assertEqual(S.check_access(S.LaunchSettings(access="lan", api_key="k")), []) + self.assertEqual(S.check_access(S.LaunchSettings(access="local", no_key=True)), []) + def test_access_notes(self): self.assertEqual(S.check_access(S.LaunchSettings(access="local")), []) lan = S.check_access(S.LaunchSettings(access="lan")) @@ -294,6 +305,14 @@ class RunConfig(unittest.TestCase): self.assertEqual(cfg["host"], "127.0.0.1") self.assertNotIn("api_key", cfg) + def test_no_key_is_written_as_none_and_a_key_wins(self): + cfg = derive_config(self.BASE, S.LaunchSettings(access="lan", no_key=True), bool_flags=frozenset()) + self.assertEqual((cfg["host"], cfg["api_key"]), ("0.0.0.0", "none")) + cfg = derive_config(self.BASE, S.LaunchSettings(access="lan", no_key=True, api_key="sk-x"), bool_flags=frozenset()) + self.assertEqual(cfg["api_key"], "sk-x") + cfg = derive_config(self.BASE, S.LaunchSettings(access="local", no_key=True), bool_flags=frozenset()) + self.assertNotIn("api_key", cfg) + def test_installed_config_matching(self): d = {"context": 32768, "kv": "int8", "images": "off"} self.assertTrue(desc_matches(d, S.LaunchSettings(context=32768))) @@ -742,6 +761,23 @@ class FlagsCommand(unittest.TestCase): p = self.plan("--model", "q2_0", "--new-key") self.assertEqual(p["settings"]["api_key"], "set") + def test_no_api_key_flag(self): + p = self.plan("--model", "q2_0", "--access", "lan", "--no-api-key") + self.assertIsNone(p["settings"]["api_key"]) + self.assertFalse(any("new API key was made" in w for w in p["warnings"])) + self.assertTrue(any("anyone who can reach this port can use the model and its tools" in w for w in p["warnings"])) + p = self.plan("--model", "q2_0", "--access", "cloudflare", "--no-api-key") + self.assertTrue(any("public address" in w and "anyone on the internet" in w for w in p["warnings"])) + p = self.plan("--model", "q2_0", "--access", "local", "--no-api-key") + self.assertEqual([w for w in p["warnings"] if "API key" in w], []) + # scripts that name LAN without a key flag keep getting a key, as before + p = self.plan("--model", "q2_0", "--access", "lan", "--yes") + self.assertEqual(p["settings"]["api_key"], "set") + self.assertTrue(any("new API key was made" in w for w in p["warnings"])) + # a key given as well wins over --no-api-key, with a note + p = self.plan("--model", "q2_0", "--access", "lan", "--api-key", "sk-a", "--no-api-key") + self.assertEqual(p["settings"]["api_key"], "set") + def test_model_path_is_used_instead_of_a_catalog_model(self): p = self.plan("--model-path", "/data/models/IQ3_XXS") s = p["settings"] diff --git a/tests/terminal/test_launch_tui.py b/tests/terminal/test_launch_tui.py index 99ef4a60..50ac2318 100644 --- a/tests/terminal/test_launch_tui.py +++ b/tests/terminal/test_launch_tui.py @@ -715,9 +715,30 @@ class AccessStep(Base): self.assertNotEqual(ctx.settings.api_key, first) await press(pilot, "t") self.assertIsNone(ctx.settings.api_key) - self.assertIn("will not start on a network without one", text_of(app)) + self.assertTrue(ctx.settings.no_key) + self.assertIn("anyone who can reach this port can use the model and its tools", text_of(app)) await press(pilot, "t") self.assertTrue(ctx.settings.api_key) + self.assertFalse(ctx.settings.no_key) + self.run_app(case) + + def test_default_is_a_key_and_no_key_survives_moving_on(self): + async def case(app, pilot, ctx): + await press(pilot, *self.reach(), "down") + self.assertTrue(ctx.settings.api_key) # default: Strata makes a key + await press(pilot, "t") # one keypress: no key + await press(pilot, "down") # moving the cursor does not bring the key back + await press(pilot, "up") + self.assertIsNone(ctx.settings.api_key) + self.assertTrue(ctx.settings.no_key) + self.run_app(case) + + def test_local_never_asks_for_a_key(self): + async def case(app, pilot, ctx): + await press(pilot, *self.reach()) + self.assertEqual(ctx.settings.access, "local") + self.assertIsNone(ctx.settings.api_key) + self.assertNotIn("An API key was made", text_of(app)) self.run_app(case) diff --git a/tests/terminal/test_runtime.py b/tests/terminal/test_runtime.py index feef2dec..9351195d 100644 --- a/tests/terminal/test_runtime.py +++ b/tests/terminal/test_runtime.py @@ -845,6 +845,20 @@ class RuntimeTests(unittest.TestCase): self.assertEqual(plan["effective"]["host"], "0.0.0.0") self.assertNotIn("first", json.dumps(plan)) + def test_remote_bind_without_a_key_is_planned_not_refused(self): + # owner decision 2026-10-20: a key is recommended on a network, never required + from strata_cli.cli import _launch_plan + for key in (None, "none"): + cfg = json.loads(self.config.read_text()) + cfg["host"] = "0.0.0.0" + cfg.pop("api_key", None) + if key: + cfg["api_key"] = key + self.config.write_text(json.dumps(cfg)) + with mock.patch.dict(os.environ, {"STRATA_API_KEY": ""}): + plan, args = _launch_plan("local") + self.assertEqual(plan["effective"]["host"], "0.0.0.0") + def test_lazy_model_is_verified_as_unloaded_without_generation(self): cfg = json.loads(self.config.read_text()) cfg["lazy_load"] = True diff --git a/tests/terminal/test_terminal.py b/tests/terminal/test_terminal.py index 2a177a06..5f4c74ed 100644 --- a/tests/terminal/test_terminal.py +++ b/tests/terminal/test_terminal.py @@ -2,6 +2,7 @@ import asyncio import copy +import contextlib import io import json import os @@ -588,22 +589,21 @@ class ContractTests(unittest.TestCase): with self.assertRaisesRegex(ValueError, "offline mode cannot download"): svc.prepare(messages, [], {}) - def test_non_loopback_serve_requires_inference_key(self): - with tempfile.TemporaryDirectory() as directory: - profile = Path(directory) / "model.json" - profile.write_text('{"host":"0.0.0.0","args":[]}', encoding="utf-8") - with mock.patch.dict(os.environ, {"STRATA_API_KEY": ""}), redirect_stdout(io.StringIO()): - self.assertEqual(main(["serve", "--profile", str(profile)]), 2) - - def test_direct_server_rejects_remote_bind_before_engine_load(self): + def test_direct_server_remote_bind_without_key_reaches_engine_load(self): + # no early exit over the key any more: every way of saying "no key" gets past the key check import serve.server as server - with tempfile.TemporaryDirectory() as directory: - profile = Path(directory) / "model.json" - profile.write_text('{"args":[]}', encoding="utf-8") - with mock.patch.dict(os.environ, {}, clear=True), \ - mock.patch.object(server, "StrataEngine", side_effect=AssertionError("engine started")): - self.assertEqual(server.main(["--engine", "strata", "--config", str(profile), - "--host", "0.0.0.0", "--port", "0"]), 2) + cases = [('{"args":[]}', []), ('{"args":[],"api_key":"none"}', []), ('{"args":[]}', ["--no-api-key"]), + ('{"args":[]}', ["--api-key", "none"])] + for body, extra in cases: + with tempfile.TemporaryDirectory() as directory: + profile = Path(directory) / "model.json" + profile.write_text(body, encoding="utf-8") + err = io.StringIO() + with mock.patch.dict(os.environ, {}, clear=True), contextlib.redirect_stderr(err): + with self.assertRaises(SystemExit): + server.main(["--engine", "strata", "--config", str(profile), + "--host", "0.0.0.0", "--port", "0", *extra]) + self.assertIn("tokenizer is missing", err.getvalue(), (body, extra)) # past the key check, stopped later def test_code_run_uses_missing_component_exit_until_shared_harness_arrives(self): output = io.StringIO() diff --git a/tools/strata_mcp.py b/tools/strata_mcp.py index 0977497a..9993a185 100644 --- a/tools/strata_mcp.py +++ b/tools/strata_mcp.py @@ -1241,12 +1241,15 @@ class Strata: def api_key_for(self, port: int) -> str | None: """The key a config of this folder set for that port (used for our own requests; never shown).""" + def real(cfg): # "api_key": "none" = served without a key on purpose + k = cfg.get("api_key") + return k if k and str(k).strip().lower() != "none" else None for c in self.configs(): cfg = self.read_config(c) - if cfg.get("api_key") and int(cfg.get("port", DEFAULT_PORT)) == port: + if real(cfg) and int(cfg.get("port", DEFAULT_PORT)) == port: return cfg["api_key"] for c in self.configs(): - if self.read_config(c).get("api_key"): + if real(self.read_config(c)): return self.read_config(c)["api_key"] return None From c6a0e739becce52ca500c0ad2f90fe043a924dfd Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Tue, 20 Oct 2026 13:56:13 +0200 Subject: [PATCH 05/47] Fix #3417: the hardware report counts physical cores, so the Work profile no longer asks for more CPU workers than the CPU has cores --- tools/strata_mcp.py | 17 +++++++++++++++-- tools/test_strata_mcp.py | 16 ++++++++++++++++ 2 files changed, 31 insertions(+), 2 deletions(-) diff --git a/tools/strata_mcp.py b/tools/strata_mcp.py index 9993a185..3ccfe1e2 100644 --- a/tools/strata_mcp.py +++ b/tools/strata_mcp.py @@ -890,9 +890,9 @@ class Strata: name, avx2, avx512 = S.cpu_info() else: name, avx2, avx512 = platform.processor() or "unknown CPU", None, None - hw["cpu"] = {"name": name, "cores": os.cpu_count(), "avx2": avx2, "avx512": avx512} + hw["cpu"] = {"name": name, "cores": physical_cores(), "threads": os.cpu_count(), "avx2": avx2, "avx512": avx512} except Exception: # noqa: BLE001 - hw["cpu"] = {"name": platform.processor(), "cores": os.cpu_count()} + hw["cpu"] = {"name": platform.processor(), "cores": physical_cores(), "threads": os.cpu_count()} if sys.platform == "darwin": # a Mac: one pool of unified memory, the Metal engine (strata_control/mac_fit.py) return self._mac_hardware(hw) nv = [] @@ -1511,6 +1511,19 @@ def install_progress(lines: list[str]) -> dict: return out +def physical_cores() -> int | None: + """The CPU's physical cores (os.cpu_count() counts logical threads: 16 on an 8-core SMT chip, and the app's Work profile took + 80% of that for --pool-workers, more than the cores, #3417). Falls back to the thread count when the machine cannot say.""" + try: + from strata_control import tune_machine + n = tune_machine.cpu().get("physical") + if isinstance(n, int) and n > 0: + return n + except Exception: # noqa: BLE001 - a hardware report must never fail on this + pass + return os.cpu_count() + + def own_ram_gb() -> float: if WIN: class MS(ctypes.Structure): diff --git a/tools/test_strata_mcp.py b/tools/test_strata_mcp.py index 2cec253b..8f0c1540 100644 --- a/tools/test_strata_mcp.py +++ b/tools/test_strata_mcp.py @@ -653,6 +653,22 @@ class Helpers(unittest.TestCase): self.assertEqual(r["context"], 32768) +class PhysicalCores(unittest.TestCase): + """#3417: the hardware report's cpu.cores is the physical cores; the Work profile takes 80% of it for --pool-workers.""" + + def test_physical_not_logical(self): + from strata_control import tune_machine + with mock.patch.object(tune_machine, "cpu", return_value={"model": "x", "logical": 16, "physical": 8, "hybrid": False}), mock.patch.object(M.os, "cpu_count", return_value=16): + self.assertEqual(M.physical_cores(), 8) + + def test_unknown_falls_back_to_threads(self): + from strata_control import tune_machine + with mock.patch.object(tune_machine, "cpu", return_value={"physical": None}), mock.patch.object(M.os, "cpu_count", return_value=16): + self.assertEqual(M.physical_cores(), 16) + with mock.patch.object(tune_machine, "cpu", side_effect=OSError("no")), mock.patch.object(M.os, "cpu_count", return_value=4): + self.assertEqual(M.physical_cores(), 4) + + class MacCatalog(unittest.TestCase): """A Mac (Apple Silicon): one pool of unified memory, judged by strata_control/mac_fit.py (the rules metal/setup_mac.py uses).""" From af189129a4dc7bf3df4da356cab93deb2b974bc7 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Tue, 20 Oct 2026 13:58:47 +0200 Subject: [PATCH 06/47] Calls to this computer's own servers skip the system proxy (tuner, tune session, launch self-check) --- strata_cli/launch/check.py | 4 ++- strata_control/loopback.py | 28 ++++++++++++++++++++ strata_control/tune_api.py | 5 ++-- strata_control/tune_session.py | 8 +++--- tests/terminal/test_loopback.py | 47 +++++++++++++++++++++++++++++++++ 5 files changed, 85 insertions(+), 7 deletions(-) create mode 100644 strata_control/loopback.py create mode 100644 tests/terminal/test_loopback.py diff --git a/strata_cli/launch/check.py b/strata_cli/launch/check.py index 93d46284..5edd8515 100644 --- a/strata_cli/launch/check.py +++ b/strata_cli/launch/check.py @@ -15,6 +15,8 @@ import urllib.error import urllib.request from dataclasses import dataclass +from strata_control import loopback + #: harness id -> the endpoint family it speaks (the others use chat completions) WIRE = {"codex": "responses", "claude-code": "messages"} @@ -37,7 +39,7 @@ def _post(url: str, key: str, body: dict, headers: dict | None = None, timeout: h["Authorization"] = "Bearer " + key h["x-api-key"] = key req = urllib.request.Request(url, data=json.dumps(body).encode("utf-8"), headers=h, method="POST") - with urllib.request.urlopen(req, timeout=timeout) as r: + with loopback.urlopen(req, timeout=timeout) as r: return json.loads(r.read().decode("utf-8", "replace")) diff --git a/strata_control/loopback.py b/strata_control/loopback.py new file mode 100644 index 00000000..969c8db2 --- /dev/null +++ b/strata_control/loopback.py @@ -0,0 +1,28 @@ +"""HTTP calls to this computer's own servers (127.0.0.1, localhost, ::1) never go through a proxy. + +`urllib.request.urlopen` follows the system proxy (HTTP_PROXY, the Windows registry, a PAC file). A school or office PC sends +`http://127.0.0.1:PORT/health` to that proxy, which cannot reach it, and Strata then reports a healthy server as "did not answer". +Everything that talks to a local server uses `urlopen` below; any other address is passed on unchanged. +""" + +from __future__ import annotations + +import urllib.request +from urllib.parse import urlsplit + +_OPENER = urllib.request.build_opener(urllib.request.ProxyHandler({})) +_LOCAL = {"127.0.0.1", "localhost", "::1"} + + +def is_loopback(url: str) -> bool: + try: + return (urlsplit(url).hostname or "").lower() in _LOCAL + except ValueError: + return False + + +def urlopen(request, timeout: float | None = None): + url = request if isinstance(request, str) else request.full_url + if is_loopback(url): + return _OPENER.open(request, timeout=timeout) + return urllib.request.urlopen(request, timeout=timeout) diff --git a/strata_control/tune_api.py b/strata_control/tune_api.py index 635b5c43..7cb330eb 100644 --- a/strata_control/tune_api.py +++ b/strata_control/tune_api.py @@ -34,6 +34,7 @@ from dataclasses import dataclass, field from pathlib import Path from typing import Any +from strata_control import loopback from strata_control.tune_engine import EngineMeasurement, MeasurementError, process_tree_peak_mib @@ -94,7 +95,7 @@ class ApiHarness: f"the worker exited with code {self._proc.returncode} before becoming ready" + self._log_tail()) try: - with urllib.request.urlopen(f"{self.url}/health", timeout=2) as response: + with loopback.urlopen(f"{self.url}/health", timeout=2) as response: if response.status == 200: return except (urllib.error.URLError, OSError): @@ -172,7 +173,7 @@ class ApiHarness: usage: dict[str, Any] = {} finish: str | None = None try: - with urllib.request.urlopen(request, timeout=self.request_timeout_s) as response: + with loopback.urlopen(request, timeout=self.request_timeout_s) as response: for raw in response: line = raw.decode("utf-8", errors="replace").strip() if not line.startswith("data:"): diff --git a/strata_control/tune_session.py b/strata_control/tune_session.py index aa1a3dc3..be82408a 100644 --- a/strata_control/tune_session.py +++ b/strata_control/tune_session.py @@ -31,7 +31,7 @@ from dataclasses import dataclass, field from pathlib import Path from typing import Any, Callable, Iterator, Protocol -from strata_control import tune_machine +from strata_control import loopback, tune_machine # --------------------------------------------------------------------------- the contract @@ -304,7 +304,7 @@ class WorkerEngine: def _model_id(self) -> None: try: req = urllib.request.Request(f"http://127.0.0.1:{self.port}/v1/models", headers=self._h()) - with urllib.request.urlopen(req, timeout=10) as r: + with loopback.urlopen(req, timeout=10) as r: data = json.loads(r.read()) self.model = ((data.get("data") or [{}])[0]).get("id") or self.model except Exception: # noqa: BLE001 @@ -326,7 +326,7 @@ class WorkerEngine: req = urllib.request.Request(f"http://127.0.0.1:{self.port}/v1/chat/completions", data=json.dumps(body).encode(), headers=self._h(), method="POST") try: - with urllib.request.urlopen(req, timeout=timeout) as r: + with loopback.urlopen(req, timeout=timeout) as r: data = json.loads(r.read()) except urllib.error.HTTPError as e: raise StartFailed("NO_TOKENS", f"the worker refused the request ({e.code}): {e.read()[:200]!r}") from None @@ -488,7 +488,7 @@ class WorkerSession: try: req = urllib.request.Request(f"http://127.0.0.1:{port}/health", headers={"authorization": f"Bearer {key}"}) - with urllib.request.urlopen(req, timeout=2) as r: + with loopback.urlopen(req, timeout=2) as r: if r.status == 200: ready = True break diff --git a/tests/terminal/test_loopback.py b/tests/terminal/test_loopback.py new file mode 100644 index 00000000..43f4d3f8 --- /dev/null +++ b/tests/terminal/test_loopback.py @@ -0,0 +1,47 @@ +"""Calls to this computer's own servers must ignore the system proxy (a company proxy cannot reach 127.0.0.1).""" + +import http.server +import os +import threading +import unittest +from unittest import mock + +from strata_control import loopback + + +class Hello(http.server.BaseHTTPRequestHandler): + def do_GET(self): + self.send_response(200) + self.end_headers() + self.wfile.write(b"ok") + + def log_message(self, *a): + pass + + +class LoopbackTests(unittest.TestCase): + def test_is_loopback(self): + for u in ("http://127.0.0.1:1/x", "http://localhost:2/", "http://[::1]:3/"): + self.assertTrue(loopback.is_loopback(u), u) + for u in ("https://example.com/", "http://192.168.1.5:8080/", "not a url"): + self.assertFalse(loopback.is_loopback(u), u) + + def test_local_server_is_reached_with_a_dead_proxy_set(self): + srv = http.server.HTTPServer(("127.0.0.1", 0), Hello) + threading.Thread(target=srv.serve_forever, daemon=True).start() + try: + env = {"HTTP_PROXY": "http://127.0.0.1:9", "http_proxy": "http://127.0.0.1:9", "NO_PROXY": "", "no_proxy": ""} + with mock.patch.dict(os.environ, env): + with loopback.urlopen(f"http://127.0.0.1:{srv.server_port}/", timeout=5) as r: + self.assertEqual(r.read(), b"ok") + finally: + srv.shutdown() + + def test_other_addresses_still_use_urllib(self): + with mock.patch("urllib.request.urlopen", return_value="remote") as m: + self.assertEqual(loopback.urlopen("https://example.com/", timeout=3), "remote") + m.assert_called_once() + + +if __name__ == "__main__": + unittest.main() From aa44b9ce537b164e2626e8b05caf3fbf5230eb95 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Tue, 20 Oct 2026 14:00:31 +0200 Subject: [PATCH 07/47] No engine for this PC: say it plainly (no graphics card Strata can use, or no engine for the card), no feed address as the next step --- docs/TROUBLESHOOTING.md | 5 +-- strata_cli/launch/runner.py | 37 +++++++++++++++++++--- tests/terminal/test_launch_engine_first.py | 15 +++++++++ 3 files changed, 51 insertions(+), 6 deletions(-) diff --git a/docs/TROUBLESHOOTING.md b/docs/TROUBLESHOOTING.md index 38f64785..df94d8bb 100644 --- a/docs/TROUBLESHOOTING.md +++ b/docs/TROUBLESHOOTING.md @@ -10,8 +10,9 @@ The engine is the part that talks to your graphics card. Strata only warns and s model, and the model files stay on your computer, but the model may not run until the right engine is installed. The usual reasons are that no engine is installed yet and the update source has none for your card, that the engine found is for another make of card, or that the graphics driver is too old. In the app, open Settings, then Engine. In the Terminal, the -message names the next step: run `strata update --feed
` with the update source you were given (or ask whoever sent -you Strata for the engine that matches your card), then run `strata launch` again. +message names the next step: run `strata update` and start again. If your computer has no NVIDIA or AMD graphics card +(only an Intel UHD or Iris chip, an AMD processor graphics chip, a virtual machine, or Windows on ARM), Strata says so and +there is nothing to install: it needs a computer that has one. The model files stay where they are. **"This model needs a newer engine." (the app), or a button called Update engine.** Some models need an engine newer than the one installed: Gyro needs 0.1.45.1 or newer, NVFP4 needs 0.1.44, and NVFP4 (NVIDIA, diff --git a/strata_cli/launch/runner.py b/strata_cli/launch/runner.py index 3a8b7071..dfb27a4b 100644 --- a/strata_cli/launch/runner.py +++ b/strata_cli/launch/runner.py @@ -69,24 +69,45 @@ class Result: final_text: str = "" # what to tell the person when serving is False -NO_ENGINE_NEXT = ("Get the engine that matches this computer's graphics card (from whoever sent you Strata, or with `strata update --feed
`), " - "then run `strata launch` again. Nothing was downloaded, and any model files you already have are kept.") +NO_ENGINE_NEXT = ("Update Strata (`strata update`) and run `strata launch` again. Nothing was downloaded, and any model files you already have are kept.") STAGES = ("engine", "model", "config", "tune", "start", "access") -NO_ENGINE_STEP = ("run `strata update --feed
` with the update source you were given, or ask whoever sent you Strata for the engine " - "that matches this computer's graphics card, then run `strata launch` again") +NO_ENGINE_STEP = ("run `strata update` to get the newest engines and start again; if this stays, your graphics card is not one Strata supports yet, " + "and the model files stay on this computer for when it is") + +#: no graphics card Strata can use at all (an Intel UHD/Iris only, an AMD APU-only laptop, a virtual machine, Windows on ARM) +NO_GPU_PREFIX = "no graphics card that Strata can use was found" +NO_GPU_STEP = ("Strata needs an NVIDIA or AMD graphics card, an Intel Arc card or an Apple Silicon Mac, and there is no CPU-only engine for this " + "computer. Run Strata on a computer that has one; the model files stay here") + + +def no_gpu_words(names: list[str] | None = None) -> str: + """The plain reason when nothing Strata can run on is in this computer, naming what is there when it is known.""" + names = [n for n in (names or []) if n] + if names: + return f"{NO_GPU_PREFIX}; this computer has {', '.join(names[:3])}" + return NO_GPU_PREFIX + + +def _step_for(reason: str) -> str: + return NO_GPU_STEP if reason.startswith(NO_GPU_PREFIX) else NO_ENGINE_STEP def no_engine_warning(reason: str) -> str: """The plain warning shown before a model is downloaded on a computer with no engine to run it.""" reason = reason.strip().rstrip(".") + if reason.startswith(NO_GPU_PREFIX): + return (f"Strata can't run on this computer: {reason}. The model will download, but it will not run here " + f"(next step: {NO_GPU_STEP}).") return (f"Strata couldn't find an engine for this computer ({reason}). The model will download, but it may not run until you install " f"the right engine (next step: {NO_ENGINE_STEP}).") def no_engine_final(reason: str, name: str = "") -> str: reason = reason.strip().rstrip(".") + if reason.startswith(NO_GPU_PREFIX): + return f"The model is ready, but Strata can't start it on this computer: {reason}. Next step: {NO_GPU_STEP}." return (f"The model is ready, but Strata can't start it yet: it couldn't find an engine for this computer ({reason}). " f"Next step: {NO_ENGINE_STEP}. The model files stay on this computer.") @@ -455,6 +476,14 @@ class Runner: note = str(res.get("note") or "").strip() if not note: note = str(report.get("notice") or "").strip() + if "backend" in report and report["backend"] is None: # not even a graphics card Strata knows: say that, not "the feed has nothing" + names = [] + try: + from strata_control import engine_component as ec + names = [a.get("name", "") for a in ec.windows_display_adapters()] if os.name == "nt" else [] + except Exception: # noqa: BLE001 - the names are a nicety + pass + return no_gpu_words(names) if not note or note.startswith("No engine for this PC was found"): note = "There is no engine for this computer's graphics card in the update source." return note diff --git a/tests/terminal/test_launch_engine_first.py b/tests/terminal/test_launch_engine_first.py index 371a3cb1..50ef4eaa 100644 --- a/tests/terminal/test_launch_engine_first.py +++ b/tests/terminal/test_launch_engine_first.py @@ -96,6 +96,21 @@ class EngineBeforeModel(unittest.TestCase): self.assertIn(NO_ENGINE_STEP, warning) self.assertNotIn("The app never downloads", warning) # not the generic line + def test_no_graphics_card_is_said_plainly_with_no_feed_address(self): + report = dict(UNUSABLE, backend=None) + spawns, err, r = self.run_ensure_runner([report, report], update_events("none-for-this-pc")) + self.assertIsNone(err) + self.assertTrue(r.engine_problem.startswith("no graphics card that Strata can use was found")) + text = r.events[-1].text + self.assertIn("Strata needs an NVIDIA or AMD graphics card", text) + self.assertNotIn("--feed", text) + self.assertNotIn("
", text) + self.assertNotIn("--feed", no_engine_final(r.engine_problem)) + + def test_the_other_no_engine_texts_do_not_ask_for_a_feed_address_either(self): + self.assertNotIn("
", NO_ENGINE_STEP) + self.assertNotIn("--feed", no_engine_warning("The feed has no engine package for this PC.")) + def test_wrong_family_names_the_plain_reason_in_the_warning(self): spawns, err, r = self.run_ensure_runner([UNUSABLE, UNUSABLE], update_events("none-for-this-pc", WRONG_FAMILY)) self.assertIsNone(err) From 7ebdd343567dc1d56047ae28a35f913dea6fc82b Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Tue, 20 Oct 2026 14:04:57 +0200 Subject: [PATCH 08/47] Windows file in use: every state-file swap goes through atomic.replace (retry); a sharing violation no longer says run as yourself --- serve/runconfig.py | 3 +- strata_cli/bench.py | 3 +- strata_cli/cli.py | 9 +++-- strata_cli/connections.py | 8 ++++- strata_cli/launch/runner.py | 3 +- strata_cli/launch/store.py | 3 +- strata_cli/tune_commands.py | 3 +- strata_control/calibration.py | 3 +- strata_control/components.py | 13 +++---- strata_control/preset_marks.py | 3 +- strata_control/presets.py | 3 +- strata_control/private_files.py | 14 +++++++- strata_control/procs.py | 3 +- strata_control/profiles.py | 3 +- strata_control/tune_apply.py | 3 +- strata_control/updater.py | 7 ++-- tests/terminal/test_file_in_use.py | 54 ++++++++++++++++++++++++++++++ 17 files changed, 114 insertions(+), 24 deletions(-) create mode 100644 tests/terminal/test_file_in_use.py diff --git a/serve/runconfig.py b/serve/runconfig.py index 1d84ba8e..3448db06 100644 --- a/serve/runconfig.py +++ b/serve/runconfig.py @@ -15,6 +15,7 @@ import shutil from pathlib import Path from strata_control import user_args +from strata_control import atomic as _atomic_mod # (key, kind, help). kind: "bool", "int>=0", "num>=0", ("enum", values), "names", or ("sampling", check) for a key # of the "sampling" block, ("arg", flag) for an engine option kept in "args". @@ -179,7 +180,7 @@ def save(path: str | Path, cfg: dict) -> Path: shutil.copyfile(path, bak) tmp = path.with_name(path.name + ".tmp") tmp.write_text(json.dumps(cfg, indent=1), encoding="utf-8") - os.replace(tmp, path) + _atomic_mod.replace(tmp, path) return bak diff --git a/strata_cli/bench.py b/strata_cli/bench.py index 898fe589..80d673c1 100644 --- a/strata_cli/bench.py +++ b/strata_cli/bench.py @@ -33,6 +33,7 @@ from pathlib import Path from strata_cli.client import ClientError, Endpoint, _NoRedirect from strata_control.profiles import ProfileError +from strata_control import atomic as _atomic_mod SCHEMA = 1 @@ -685,7 +686,7 @@ def _progress_write(path: Path, record: dict, *, first: bool = False) -> None: temporary = path.with_name(".progress-" + uuid.uuid4().hex + ".tmp") try: _write_new(temporary, encoded) - os.replace(temporary, path) + _atomic_mod.replace(temporary, path) finally: temporary.unlink(missing_ok=True) diff --git a/strata_cli/cli.py b/strata_cli/cli.py index cc1dded4..62aa0f7a 100644 --- a/strata_cli/cli.py +++ b/strata_cli/cli.py @@ -1979,10 +1979,15 @@ def _access_retry(a: argparse.Namespace, error: BaseException) -> int | None: if not (isinstance(error, PermissionError) or "PermissionError" in str(error)): return None as_json = bool(getattr(a, "json", False) or getattr(a, "output", None) in ("json", "jsonl")) + in_use = private_files.is_sharing_violation(error) if getattr(a, "_access_retried", False): - return _error(f"{private_files.ACCESS_MESSAGE} (details: {error})", 5, as_json) + message = private_files.IN_USE_MESSAGE if in_use else private_files.ACCESS_MESSAGE + return _error(f"{message} (details: {error})", 5, as_json) a._access_retried = True - private_files.repair_known_roots() + if in_use: + time.sleep(1.5) # a scanner or a sync tool lets go of the file in a moment; repairing would not help + else: + private_files.repair_known_roots() return _run(a) diff --git a/strata_cli/connections.py b/strata_cli/connections.py index 769ed51a..586b73ce 100644 --- a/strata_cli/connections.py +++ b/strata_cli/connections.py @@ -6,12 +6,18 @@ CLI resolve the same saved connection without importing server or installer code from __future__ import annotations +import os try: from strata_control.private_files import private_mkdir as _private_mkdir except ImportError: # a thin bundle (monitor only) ships without strata_control def _private_mkdir(path, *, parents=False, exist_ok=True): path.mkdir(mode=0o700, parents=parents, exist_ok=exist_ok) return path +try: + from strata_control import atomic as _atomic_mod +except ImportError: # the same thin bundle: a plain replace + class _atomic_mod: # noqa: N801 + replace = staticmethod(os.replace) import hashlib import json import os @@ -158,7 +164,7 @@ def _replace(path: Path, data: bytes) -> None: stream.write(data) stream.flush() os.fsync(stream.fileno()) - os.replace(name, path) + _atomic_mod.replace(name, path) if os.name == "posix": try: parent = os.open(path.parent, os.O_RDONLY) diff --git a/strata_cli/launch/runner.py b/strata_cli/launch/runner.py index dfb27a4b..9fd72a24 100644 --- a/strata_cli/launch/runner.py +++ b/strata_cli/launch/runner.py @@ -21,6 +21,7 @@ import sys import tempfile import threading import time +from strata_control import atomic as _atomic_mod from dataclasses import dataclass, field from pathlib import Path from typing import Any, Callable @@ -277,7 +278,7 @@ def write_private(path: Path, data: dict) -> None: os.chmod(tmp, 0o600) except OSError: pass - os.replace(tmp, path) + _atomic_mod.replace(tmp, path) finally: if os.path.exists(tmp): os.unlink(tmp) diff --git a/strata_cli/launch/store.py b/strata_cli/launch/store.py index 21b43298..a7439883 100644 --- a/strata_cli/launch/store.py +++ b/strata_cli/launch/store.py @@ -13,6 +13,7 @@ import json import os import tempfile import time +from strata_control import atomic as _atomic_mod from pathlib import Path from typing import Any @@ -47,7 +48,7 @@ def _private_write(path: Path, payload: bytes) -> None: os.chmod(tmp, 0o600) except OSError: pass - os.replace(tmp, path) + _atomic_mod.replace(tmp, path) finally: if os.path.exists(tmp): os.unlink(tmp) diff --git a/strata_cli/tune_commands.py b/strata_cli/tune_commands.py index ff21cd08..83f95e5a 100644 --- a/strata_cli/tune_commands.py +++ b/strata_cli/tune_commands.py @@ -10,6 +10,7 @@ import sys import tempfile import threading import time +from strata_control import atomic as _atomic_mod from pathlib import Path from typing import Any @@ -151,7 +152,7 @@ def _write_status(path: str | None, payload: dict[str, Any]) -> None: try: tmp = path + ".tmp" Path(tmp).write_text(json.dumps(payload, ensure_ascii=False, default=str), encoding="utf-8") - os.replace(tmp, path) + _atomic_mod.replace(tmp, path) except OSError: pass diff --git a/strata_control/calibration.py b/strata_control/calibration.py index a020f2f7..2dcec1be 100644 --- a/strata_control/calibration.py +++ b/strata_control/calibration.py @@ -26,6 +26,7 @@ from pathlib import Path from strata_control import profiles from strata_control.doctor import inspect as inspect_components from strata_control.profiles import ProfileError +from strata_control import atomic as _atomic_mod SUITE = "legacy-decode-v1" @@ -412,7 +413,7 @@ def _replace_bytes(path: Path, payload: bytes) -> None: stream.write(payload) stream.flush() os.fsync(stream.fileno()) - os.replace(temp, path) + _atomic_mod.replace(temp, path) finally: if os.path.exists(temp): os.unlink(temp) diff --git a/strata_control/components.py b/strata_control/components.py index 0950a1c4..8d6665ff 100644 --- a/strata_control/components.py +++ b/strata_control/components.py @@ -52,6 +52,7 @@ from typing import Any, Iterable, Sequence SCHEMA_VERSION = 1 from strata_control.targets import BACKEND_MATRIX, ComponentError, backend_supported, host_platform # noqa: E402,F401 +from strata_control import atomic as _atomic_mod #: Component kinds, so a manifest cannot claim a role the architecture does not have. KINDS = ("application", "runtime", "agent-runtime", "tuning", "engine", "prepared-data") @@ -426,7 +427,7 @@ class ComponentStore: def _save_state(self, data: dict[str, Any]) -> None: temp = self.state_path.parent / (self.state_path.name + ".tmp") temp.write_text(json.dumps(data, indent=1, sort_keys=True) + "\n", encoding="utf-8") - os.replace(temp, self.state_path) + _atomic_mod.replace(temp, self.state_path) # ------------------------------------------------------------------ cache and installation @@ -487,7 +488,7 @@ class ComponentStore: indent=1) + "\n", encoding="utf-8") if destination.exists(): shutil.rmtree(destination, ignore_errors=True) - os.replace(staging, destination) + _atomic_mod.replace(staging, destination) except BaseException: # Leave nothing that looks complete. shutil.rmtree(staging, ignore_errors=True) @@ -590,7 +591,7 @@ class ComponentStore: if active.exists(): if previous.exists(): shutil.rmtree(previous, ignore_errors=True) - os.replace(active, previous) + _atomic_mod.replace(active, previous) moved_aside = str(previous) # Record what is being displaced BEFORE the activation, so a crash between the two leaves a @@ -611,7 +612,7 @@ class ComponentStore: if incoming.exists(): shutil.rmtree(incoming, ignore_errors=True) shutil.copytree(source, incoming, symlinks=False) - os.replace(incoming, active) + _atomic_mod.replace(incoming, active) state = self.state() entry = state["components"].setdefault(component.id, {}) @@ -636,8 +637,8 @@ class ComponentStore: abandoned = self.root / "previous" / f"{component_id}.replaced" if abandoned.exists(): shutil.rmtree(abandoned, ignore_errors=True) - os.replace(active, abandoned) - os.replace(previous, active) + _atomic_mod.replace(active, abandoned) + _atomic_mod.replace(previous, active) state = self.state() entry = state["components"].get(component_id, {}) restored = entry.get("rollback", {}) diff --git a/strata_control/preset_marks.py b/strata_control/preset_marks.py index b67ecde2..f8c1dba9 100644 --- a/strata_control/preset_marks.py +++ b/strata_control/preset_marks.py @@ -26,6 +26,7 @@ import uuid from pathlib import Path from strata_control import paths +from strata_control import atomic as _atomic_mod SCHEMA_VERSION = 1 IDENTITY_KEYS = ("version", "build_id", "manifest_sha256", "backend", "platform", "variant") @@ -58,7 +59,7 @@ def _write(path: Path, data: dict) -> None: with os.fdopen(descriptor, "w", encoding="utf-8") as stream: json.dump(data, stream, indent=1, sort_keys=True) stream.write("\n") - os.replace(temp, path) + _atomic_mod.replace(temp, path) finally: if os.path.exists(temp): os.unlink(temp) diff --git a/strata_control/presets.py b/strata_control/presets.py index 7a04937f..ad95c940 100644 --- a/strata_control/presets.py +++ b/strata_control/presets.py @@ -29,6 +29,7 @@ from pathlib import Path from typing import Any from strata_control import tune_knobs, tune_machine +from strata_control import atomic as _atomic_mod SCHEMA = "strata.preset/1" RECHECK_SET = "recheck/1" @@ -57,7 +58,7 @@ def _atomic(path: Path, payload: bytes) -> None: fh.write(payload) fh.flush() os.fsync(fh.fileno()) - os.replace(tmp, path) + _atomic_mod.replace(tmp, path) finally: if os.path.exists(tmp): os.unlink(tmp) diff --git a/strata_control/private_files.py b/strata_control/private_files.py index 0a37309a..19cae983 100644 --- a/strata_control/private_files.py +++ b/strata_control/private_files.py @@ -383,7 +383,19 @@ def read_bytes_repairing(path: str | os.PathLike) -> bytes: return target.read_bytes() -ACCESS_MESSAGE = "Strata can't open its settings file. Run Strata once as yourself (not as administrator) or press Repair." +ACCESS_MESSAGE = ("Strata is not allowed to open one of its own files. Run `strata repair-access` (or press Repair in the app); " + "these files were probably made while Strata ran as administrator, so run it as your normal user from now on.") +IN_USE_MESSAGE = ("A file Strata needs is in use by another program (usually antivirus, a backup or a sync tool). " + "Wait a moment and run the same command again.") + + +def is_sharing_violation(error: BaseException) -> bool: + """Windows "file in use" (WinError 32 or 33), as opposed to a real refusal (WinError 5): waiting helps, repairing does not.""" + code = getattr(error, "winerror", None) + if code in (32, 33): + return True + text = str(error) + return "WinError 32" in text or "WinError 33" in text or "being used by another process" in text _SKIP_DIRS = {"models", "node_modules", "harness", "python", "host", "node", "control", "__pycache__", ".git"} diff --git a/strata_control/procs.py b/strata_control/procs.py index ee473532..2f7be854 100644 --- a/strata_control/procs.py +++ b/strata_control/procs.py @@ -30,6 +30,7 @@ from dataclasses import dataclass from pathlib import Path from strata_control import paths +from strata_control import atomic as _atomic_mod WINDOWS = os.name == "nt" SCHEMA = 1 @@ -192,7 +193,7 @@ def write_record(pid: int, role: str, *, profile: str | None = None, cmd: list[s path = procs_dir() / f"{pid}.json" tmp = path.with_suffix(f".{os.getpid()}.tmp") tmp.write_text(json.dumps(record), encoding="utf-8") - os.replace(tmp, path) + _atomic_mod.replace(tmp, path) return token except (OSError, ValueError): return None diff --git a/strata_control/profiles.py b/strata_control/profiles.py index 4c82d833..c5ea6a56 100644 --- a/strata_control/profiles.py +++ b/strata_control/profiles.py @@ -17,6 +17,7 @@ import shlex import stat import subprocess import tempfile +from strata_control import atomic as _atomic_mod from contextlib import contextmanager from pathlib import Path @@ -216,7 +217,7 @@ def _atomic(path: Path, data: bytes) -> None: stream.write(data) stream.flush() os.fsync(stream.fileno()) - os.replace(temp_name, path) + _atomic_mod.replace(temp_name, path) if os.name != "nt": try: parent_fd = os.open(path.parent, os.O_RDONLY) diff --git a/strata_control/tune_apply.py b/strata_control/tune_apply.py index 70d4c664..6025b5a7 100644 --- a/strata_control/tune_apply.py +++ b/strata_control/tune_apply.py @@ -42,6 +42,7 @@ from pathlib import Path from typing import Any, Callable, Sequence from strata_control import user_args +from strata_control import atomic as _atomic_mod SCHEMA_VERSION = 1 @@ -66,7 +67,7 @@ def _atomic_write(path: Path, payload: bytes) -> None: stream.write(payload) stream.flush() os.fsync(stream.fileno()) - os.replace(temp, path) + _atomic_mod.replace(temp, path) finally: if os.path.exists(temp): os.unlink(temp) diff --git a/strata_control/updater.py b/strata_control/updater.py index 308c1094..390708a9 100644 --- a/strata_control/updater.py +++ b/strata_control/updater.py @@ -44,6 +44,7 @@ from typing import Callable from strata_control import acquisition, components, engine_component as ec, feed as feedmod, longpath, preset_marks, signing, transfer from strata_control.targets import host_platform +from strata_control import atomic as _atomic_mod STATE_DIR = ".updates" STAGE_DIR = ".s" # staging is short on purpose: \.s\<4 hex>\engine\ (see longpath.py) @@ -152,7 +153,7 @@ class State: with os.fdopen(descriptor, "w", encoding="utf-8") as stream: json.dump(self.data, stream, indent=1, sort_keys=True) stream.write("\n") - os.replace(temp, self.path) + _atomic_mod.replace(temp, self.path) finally: if os.path.exists(temp): os.unlink(temp) @@ -948,7 +949,7 @@ def update_control(ctx: Context, feed: feedmod.Feed, state: State) -> dict: pointer = control_dir(root) / "active.json" temp = pointer.with_suffix(".tmp") temp.write_text(json.dumps({"version": pkg.version, "folder": pkg.version, "sha256": pkg.sha256}), encoding="utf-8") - os.replace(temp, pointer) + _atomic_mod.replace(temp, pointer) keep = {pkg.version} | ({previous["folder"]} if previous else set()) for entry_dir in control_dir(root).iterdir(): if entry_dir.is_dir() and entry_dir.name not in keep: @@ -1022,7 +1023,7 @@ def update_app(ctx: Context, feed: feedmod.Feed) -> dict: target_dir.mkdir(parents=True, exist_ok=True) name = Path(transfer.resolve_ref(transfer.base_of(feed.source), entry["url"]).replace("\\", "/")).name or f"strata-app-{feed.app.version}" target = target_dir / name - os.replace(archive, target) + _atomic_mod.replace(archive, target) result.update({"changed": True, "status": "downloaded", "installed_after": None, "version": feed.app.version, "path": str(target), "note": "Verified. Run the installer to finish; models and settings are kept."}) return result diff --git a/tests/terminal/test_file_in_use.py b/tests/terminal/test_file_in_use.py new file mode 100644 index 00000000..f3346ed7 --- /dev/null +++ b/tests/terminal/test_file_in_use.py @@ -0,0 +1,54 @@ +"""Windows 'file in use': every swap of a state file waits and retries (atomic.replace), and the message does not blame permissions.""" + +import re +import unittest +from pathlib import Path +from unittest import mock + +from strata_control import atomic, private_files + +ROOT = Path(__file__).resolve().parents[2] +SITES = ["strata_control/calibration.py", "strata_control/components.py", "strata_control/presets.py", + "strata_control/preset_marks.py", "strata_control/procs.py", "strata_control/profiles.py", + "strata_control/tune_apply.py", "strata_control/updater.py", "strata_cli/bench.py", "strata_cli/connections.py", + "strata_cli/launch/runner.py", "strata_cli/launch/store.py", "strata_cli/tune_commands.py", "serve/runconfig.py"] + + +class Sites(unittest.TestCase): + def test_no_bare_os_replace_is_left_in_the_state_file_writers(self): + for rel in SITES: + text = (ROOT / rel).read_text(encoding="utf-8") + bare = [l for l in text.splitlines() if re.search(r"(? Date: Tue, 20 Oct 2026 14:07:31 +0200 Subject: [PATCH 09/47] Own model files: the checker in front of setup accepts what setup --gguf-dir accepted (Unsloth split sets with a metadata-only first shard, links, several sizes in a folder, a folder above the model folder, more than 128 files); Unsloth Q5/Q6/Q8 and Swift IQ3_S are in the table --- data/gguf_fingerprints.json | 80 ++++++++++ strata_control/gguf_preflight.py | 30 +++- strata_control/models.py | 221 +++++++++++++++++++------- tests/terminal/test_own_files.py | 261 +++++++++++++++++++++++++++++++ tools/strata_inspect.py | 4 + 5 files changed, 535 insertions(+), 61 deletions(-) create mode 100644 tests/terminal/test_own_files.py diff --git a/data/gguf_fingerprints.json b/data/gguf_fingerprints.json index ac99a748..e82ace8b 100644 --- a/data/gguf_fingerprints.json +++ b/data/gguf_fingerprints.json @@ -215,6 +215,86 @@ ], "repo": "agentionai/Qwen3.8-Flash-Next-Gyro-GGUF" }, + "unsloth/UD-Q5_K_XL": { + "arch": "qwen4exp", + "tensors": 1224, + "bytes": 158275381760, + "expert_bytes": { + "Q5_K": 54211379200, + "Q6_K": 1376256000, + "Q8_0": 42781900800 + }, + "experts_bpw": 6.515, + "bpw": 7.156, + "files": [ + "UD-Q5_K_XL/Qwen3.8-Flash-Next-UD-Q5_K_XL-00001-of-00006.gguf", + "UD-Q5_K_XL/Qwen3.8-Flash-Next-UD-Q5_K_XL-00002-of-00006.gguf", + "UD-Q5_K_XL/Qwen3.8-Flash-Next-UD-Q5_K_XL-00003-of-00006.gguf", + "UD-Q5_K_XL/Qwen3.8-Flash-Next-UD-Q5_K_XL-00004-of-00006.gguf", + "UD-Q5_K_XL/Qwen3.8-Flash-Next-UD-Q5_K_XL-00005-of-00006.gguf", + "UD-Q5_K_XL/Qwen3.8-Flash-Next-UD-Q5_K_XL-00006-of-00006.gguf" + ], + "repo": "unsloth/Qwen3.8-Flash-Next-GGUF" + }, + "unsloth/UD-Q6_K_XL": { + "arch": "qwen4exp", + "tensors": 1224, + "bytes": 169154357760, + "expert_bytes": { + "Q6_K": 64684032000, + "Q8_0": 44564480000 + }, + "experts_bpw": 7.235, + "bpw": 7.648, + "files": [ + "UD-Q6_K_XL/Qwen3.8-Flash-Next-UD-Q6_K_XL-00001-of-00006.gguf", + "UD-Q6_K_XL/Qwen3.8-Flash-Next-UD-Q6_K_XL-00002-of-00006.gguf", + "UD-Q6_K_XL/Qwen3.8-Flash-Next-UD-Q6_K_XL-00003-of-00006.gguf", + "UD-Q6_K_XL/Qwen3.8-Flash-Next-UD-Q6_K_XL-00004-of-00006.gguf", + "UD-Q6_K_XL/Qwen3.8-Flash-Next-UD-Q6_K_XL-00005-of-00006.gguf", + "UD-Q6_K_XL/Qwen3.8-Flash-Next-UD-Q6_K_XL-00006-of-00006.gguf" + ], + "repo": "unsloth/Qwen3.8-Flash-Next-GGUF" + }, + "unsloth/Q8_0": { + "arch": "qwen4exp", + "tensors": 1224, + "bytes": 188214008320, + "expert_bytes": { + "Q8_0": 128345702400 + }, + "experts_bpw": 8.5, + "bpw": 8.51, + "files": [ + "Q8_0/Qwen3.8-Flash-Next-Q8_0-00001-of-00006.gguf", + "Q8_0/Qwen3.8-Flash-Next-Q8_0-00002-of-00006.gguf", + "Q8_0/Qwen3.8-Flash-Next-Q8_0-00003-of-00006.gguf", + "Q8_0/Qwen3.8-Flash-Next-Q8_0-00004-of-00006.gguf", + "Q8_0/Qwen3.8-Flash-Next-Q8_0-00005-of-00006.gguf", + "Q8_0/Qwen3.8-Flash-Next-Q8_0-00006-of-00006.gguf" + ], + "repo": "unsloth/Qwen3.8-Flash-Next-GGUF" + }, + "swift/IQ3_S": { + "arch": "qwen4exp", + "tensors": 1224, + "bytes": 83732712960, + "expert_bytes": { + "IQ2_S": 10747904000, + "IQ3_S": 7208960000, + "IQ3_XXS": 10918297600, + "IQ4_NL": 18402508800, + "IQ4_XS": 891289600, + "Q2_0": 2123366400 + }, + "experts_bpw": 3.331, + "bpw": 3.786, + "files": [ + "Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf", + "Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00002-of-00002.gguf" + ], + "repo": "ukisai/Swift-1.5-Qwen3.8-Flash-Next-GSQ-RCO-GGUF" + }, "_roles": { "blk.N.attn_gate.weight": [ "IQ3_S", diff --git a/strata_control/gguf_preflight.py b/strata_control/gguf_preflight.py index b8e03748..ed83b1eb 100644 --- a/strata_control/gguf_preflight.py +++ b/strata_control/gguf_preflight.py @@ -86,12 +86,27 @@ class _Reader: return None -def inspect_metadata(path: Path) -> dict: - """Return only bounded compatibility signals from one regular GGUF v3 shard.""" +def real_model_file(path: Path) -> Path: + """The regular file a model path stands for. A model file the person picked can be a link (a Hugging Face cache snapshot, an + Ollama blob, a shortcut to a bigger drive): it is followed here, once, and the target is what gets opened. Strata's own state files + (run configs, profiles, runtime records) keep the strict no-link rule in their readers.""" try: - if stat.S_ISLNK(path.lstat().st_mode): - raise ProfileError("GGUF shard is a symlink", 5) - descriptor = os.open(path, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0)) + target = Path(os.path.realpath(path)) + info = target.stat() + except OSError: + if os.path.islink(path): + raise ProfileError(f"{Path(path).name} is a link to a file that is not there", 5) from None + raise ProfileError(f"{Path(path).name} is missing", 5) from None + if not stat.S_ISREG(info.st_mode): + raise ProfileError("GGUF shard must be a regular file", 5) + return target + + +def inspect_metadata(path: Path) -> dict: + """Return only bounded compatibility signals from one regular GGUF v3 shard (a link to one is followed).""" + try: + path = real_model_file(Path(path)) + descriptor = os.open(path, os.O_RDONLY) with os.fdopen(descriptor, "rb") as stream: details = os.fstat(stream.fileno()) if not stat.S_ISREG(details.st_mode): @@ -102,7 +117,8 @@ def inspect_metadata(path: Path) -> dict: version, tensors, keys = reader.u32(), reader.u64(), reader.u64() if version != 3: raise ProfileError("Strata metadata preflight requires GGUF v3", 5) - if not 1 <= tensors <= MAX_TENSORS or keys > MAX_METADATA_KEYS: + # tensors == 0 is a real file: a split set made with llama.cpp's gguf-split (Unsloth's) keeps only the metadata in its first shard + if not 0 <= tensors <= MAX_TENSORS or keys > MAX_METADATA_KEYS: raise ProfileError("GGUF tensor or metadata count exceeds the inspection limit", 5) found: dict[str, object] = {} for _ in range(keys): @@ -159,7 +175,7 @@ def inspect_metadata(path: Path) -> dict: extents.sort() if any(next_start < end for (_, end), (next_start, _) in zip(extents, extents[1:])): raise ProfileError("GGUF tensor byte ranges overlap", 5) - if data_start + required_payload_bytes > details.st_size: + if tensors and data_start + required_payload_bytes > details.st_size: raise ProfileError("GGUF tensor payload is shorter than its directory requires", 5) if tensors == 1 and details.st_size - (data_start + required_payload_bytes) >= 64: raise ProfileError("single-tensor GGUF shard has unexplained trailing bytes", 5) diff --git a/strata_control/models.py b/strata_control/models.py index f07dc10e..f499b1c3 100644 --- a/strata_control/models.py +++ b/strata_control/models.py @@ -23,7 +23,7 @@ from pathlib import Path from strata_control import discovery from strata_control.doctor import inspect as inspect_components -from strata_control.gguf_preflight import inspect_metadata +from strata_control.gguf_preflight import inspect_metadata, real_model_file from strata_control.profiles import ProfileError @@ -34,8 +34,9 @@ MAX_CONFIGS = 128 MAX_IMPORT_SHARDS = 128 SHARD = re.compile(r"(.+)-(\d{5})-of-(\d{5})\.gguf\Z", re.I) SUPPORTED_SELECTIONS = frozenset({"qwen/Q2_0", "qwen/IQ2_XS", "qwen/IQ3_XXS", "qwen/IQ3_S", - "swift/IQ2_XS", "swift/IQ3_XXS", "coder/IQ1_M", - "unsloth/UD-IQ4_XS", "unsloth/UD-Q4_K_XL", "gyro/Gyro-S", "gyro/Gyro-M"}) + "swift/IQ2_XS", "swift/IQ3_XXS", "swift/IQ3_S", "coder/IQ1_M", + "unsloth/UD-IQ4_XS", "unsloth/UD-Q4_K_XL", "unsloth/UD-Q5_K_XL", "unsloth/UD-Q6_K_XL", + "unsloth/Q8_0", "gyro/Gyro-S", "gyro/Gyro-M"}) def settings_path() -> Path: @@ -216,10 +217,10 @@ def inspect(model_id: str, override: str | None = None) -> dict: def _gguf_header(path: Path) -> dict: + """The first bytes of one model file (a link to it is followed: Hugging Face cache snapshots and Ollama blobs are links).""" + real = real_model_file(path) try: - if stat.S_ISLNK(path.lstat().st_mode): - raise ProfileError("GGUF shard is a symlink", 5) - descriptor = os.open(path, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0)) + descriptor = os.open(real, os.O_RDONLY) with os.fdopen(descriptor, "rb") as stream: details = os.fstat(stream.fileno()) if not stat.S_ISREG(details.st_mode) or details.st_size < 8: @@ -333,31 +334,144 @@ def _assess_projector(path: Path) -> dict: return row +MAX_LISTED = 5000 # .gguf files looked at in one folder (the checker reads headers of the chosen set only) +MAX_TREE_DIRS = 300 # folders looked into when the picked folder holds no GGUF itself +TREE_DEPTH = 3 +SKIP_DIRS = frozenset({"packs", "mtp", "engine", "node_modules", "windows", "program files", "program files (x86)", + "$recycle.bin", "system volume information", "appdata"}) + + +def _list_gguf(folder: Path) -> tuple[list[Path], list[str], bool]: + """(model files, picture-reader file names, cut) of one folder. A link to a file counts (it is followed when read); a name that + only ends in .gguf but is a folder does not.""" + shards: list[Path] = [] + readers: list[str] = [] + cut = False + try: + with os.scandir(folder) as entries: + for entry in entries: + low = entry.name.lower() + if not low.endswith(".gguf"): + continue + try: + is_file = entry.is_file() or entry.is_symlink() + except OSError: + is_file = False + if not is_file: + continue + if low.startswith("mmproj"): + readers.append(entry.name) + continue + if len(shards) >= MAX_LISTED: + cut = True + break + shards.append(Path(entry.path)) + except OSError: + raise ProfileError("cannot inspect GGUF directory", 5) from None + return shards, readers, cut + + +def _folders_with_models(root: Path) -> list[Path]: + """The folders under `root` (a Strata data folder, a whole Hugging Face repository, a drive's model folder) that hold model files, + breadth first, `TREE_DEPTH` levels deep. A folder with models is not searched further.""" + found: list[Path] = [] + seen: set[str] = set() + queue = [(root, 0)] + while queue and len(seen) < MAX_TREE_DIRS: + folder, depth = queue.pop(0) + try: + key = os.path.normcase(os.path.realpath(folder)) + except OSError: + continue + if key in seen: + continue + seen.add(key) + try: + with os.scandir(folder) as scan: + entries = sorted(scan, key=lambda e: e.name.lower()) + except OSError: + continue + if any(e.name.lower().endswith(".gguf") and not e.name.lower().startswith("mmproj") for e in entries): + found.append(folder) + continue + if depth >= TREE_DEPTH: + continue + for e in entries: + try: + if e.is_dir() and not e.name.startswith(".") and e.name.lower() not in SKIP_DIRS: + queue.append((Path(e.path), depth + 1)) + except OSError: + continue + return found + + +def _split_groups(shards: list[Path]) -> dict: + """Model files by set: (name before -0000i-of-0000N, N) -> files. A file with no shard number is a set of its own.""" + groups: dict = {} + for item in shards: + match = SHARD.fullmatch(item.name) + key = (match.group(1), int(match.group(3))) if match else (item.name, 1) + groups.setdefault(key, []).append(item) + return groups + + +def _known(members: list[Path]) -> dict | None: + try: + return _candidate_selection(sorted(members, key=lambda item: item.name)) + except ProfileError: + return None + + +def _holds(groups_by_place: list) -> list[dict]: + """What a folder (or several) holds, set by set, for the message that asks the person to point at one.""" + rows = [] + for place, members_by_key in groups_by_place: + for key in sorted(members_by_key): + members = sorted(members_by_key[key], key=lambda item: item.name) + sel = _known(members) + rows.append({"file": members[0].name, "files": len(members), "folder": str(place), + "family": sel["family"] if sel else None, "model": sel["model"] if sel else None}) + return rows + + def plan_import(raw_path: str) -> dict: - """Inspect a local candidate without copying, parsing tensors or adopting it.""" + """Inspect a local candidate without copying, parsing tensors or adopting it. + + The picked path can be a .gguf file (any shard of a split set), the folder with the files, or a folder above it (a Strata data + folder, a whole Hugging Face repository): the folder with the model is looked for, and when a folder holds several models + the one Strata knows is used if it is the only one; with two it says which and asks for the file. The result's `model_dir` + is the folder to hand to setup (--gguf-dir). Links to files and folders are followed.""" path = Path(raw_path).expanduser() if not path.is_absolute(): raise ProfileError("model import path must be absolute") try: - details = path.lstat() + details = path.stat() except OSError: - raise ProfileError("model import path does not exist", 5) from None - if stat.S_ISLNK(details.st_mode): - raise ProfileError("model import path must not be a symlink", 5) + raise ProfileError("model import path does not exist (or is a link to something that is gone)", 5) from None + notes: list[str] = [] + folder_holds: list[dict] = [] + issues: list[str] = [] if stat.S_ISDIR(details.st_mode): - try: - shards = [] - ignored_auxiliary = [] - for child in path.iterdir(): - if child.name.lower().endswith(".gguf"): - if child.name.lower().startswith("mmproj"): - ignored_auxiliary.append(child.name) - continue - shards.append(child) - if len(shards) > MAX_IMPORT_SHARDS: - raise ProfileError("more than 128 GGUF candidates in the directory", 5) - except OSError: - raise ProfileError("cannot inspect GGUF directory", 5) from None + shards, ignored_auxiliary, cut = _list_gguf(path) + if cut: + notes.append(f"This folder holds more than {MAX_LISTED} GGUF files; only the first {MAX_LISTED} were looked at.") + if not shards: + places = _folders_with_models(path) + if not places: + raise ProfileError("no GGUF files found at the model import path (or in the folders inside it)", 5) + scanned = [(place, *_list_gguf(place)[:2]) for place in places] + usable = [(place, files, readers, members) for place, files, readers in scanned + for _key, members in sorted(_split_groups(files).items(), key=lambda kv: kv[0]) if _known(members)] + if len(usable) == 1: + place, shards, ignored_auxiliary, members = usable[0] + notes.append(f"The model files are in {place}.") + else: + place, shards, ignored_auxiliary = scanned[0] + if len(usable) > 1 or len(scanned) > 1: + issues.append("multiple_model_groups") + folder_holds = _holds([(p, _split_groups(f)) for p, f, _r in scanned]) + else: + notes.append(f"The model files are in {place}.") elif stat.S_ISREG(details.st_mode) and path.name.lower().endswith(".gguf"): ignored_auxiliary = [] try: # the picture reader that sits next to a chosen model file @@ -382,31 +496,24 @@ def plan_import(raw_path: str) -> dict: if not shards: raise ProfileError("no GGUF files found at the model import path", 5) shards.sort(key=lambda item: item.name) - groups = {} - for item in shards: - match = SHARD.fullmatch(item.name) - if match: - key = (match.group(1), int(match.group(3))) - groups.setdefault(key, set()).add(int(match.group(2))) + groups = _split_groups(shards) + if len(groups) != 1 and "multiple_model_groups" not in issues: + known_sets = [key for key, members in groups.items() if _known(members)] + if len(known_sets) == 1: + # one set in the folder is a model Strata knows: use it and say what else is there + keep = known_sets[0] + others = sorted(sorted(m, key=lambda x: x.name)[0].name for k, m in groups.items() if k != keep) + shards = sorted(groups[keep], key=lambda item: item.name) + notes.append("The folder also holds " + ", ".join(others[:6]) + (" and more" if len(others) > 6 else "") + + f"; Strata uses {shards[0].name} and leaves the others alone.") + groups = {keep: shards} else: - groups.setdefault((item.name, 1), set()).add(1) - issues = [] - folder_holds = [] - if len(groups) != 1: - issues.append("multiple_model_groups") - # a folder with several models: say which ones Strata knows, so the person can point at one of them - for key in sorted(groups): - members = [item for item in shards if (SHARD.fullmatch(item.name) and (SHARD.fullmatch(item.name).group(1), - int(SHARD.fullmatch(item.name).group(3))) == key) or (not SHARD.fullmatch(item.name) and (item.name, 1) == key)] - try: - known = _candidate_selection(members) - except ProfileError: - known = None - folder_holds.append({"file": members[0].name if members else key[0], "files": len(members), - "family": known["family"] if known else None, "model": known["model"] if known else None}) - if len(groups) == 1: - (_, total), indices = next(iter(groups.items())) - if total > MAX_IMPORT_SHARDS or indices != set(range(1, total + 1)): + issues.append("multiple_model_groups") + folder_holds = _holds([(shards[0].parent, groups)]) + if len(groups) == 1 and "multiple_model_groups" not in issues: + (_, total), members = next(iter(groups.items())) + found = {int(m.group(2)) for m in (SHARD.fullmatch(item.name) for item in members) if m} or {1} + if total > MAX_IMPORT_SHARDS or found != set(range(1, total + 1)): issues.append("incomplete_or_invalid_shard_set") files = [] for item in shards: @@ -438,9 +545,13 @@ def plan_import(raw_path: str) -> dict: if metadata["tokenizer_model"] != "gpt2" or not metadata["tokenizer_tokens_present"] or \ not metadata["tokenizer_merges_present"]: issues.append("unsupported_or_incomplete_tokenizer_metadata") - projectors = [_assess_projector(path.parent / n if path.is_file() else path / n) - for n in sorted(ignored_auxiliary)[:8]] - messages = [] + model_dir = shards[0].parent + projectors = [_assess_projector(model_dir / n) for n in sorted(ignored_auxiliary)[:8]] + messages = list(notes) + if folder_holds: + names = [f"{h['family']} {h['model']} ({h['file']})" if h.get("model") else h["file"] for h in folder_holds[:8]] + messages.append(f"The folder holds {len(folder_holds)} models: " + "; ".join(names) + (" and more" if len(folder_holds) > 8 else "") + + ". Choose the folder of the one you want, or type the path of its .gguf file.") if any(i.endswith("unsupported_architecture") or i == "unsupported_or_missing_architecture" for i in issues): messages.append(UNSUPPORTED_MODEL_TYPE) elif projectors: @@ -448,13 +559,15 @@ 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: + 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): issues.append("unrecognized_or_unsupported_model_variant") - elif metadata is not None: + elif candidate is not None and metadata is not None: expected = set(candidate["expected_expert_types"]) if not observed_experts or observed_experts - expected: issues.append("missing_or_unexpected_expert_quantization") - return {"source": str(path), "scope": "local_gguf_candidate", "files": files, + return {"source": str(path), "model_dir": str(model_dir), "scope": "local_gguf_candidate", "files": files, "file_count": len(files), "total_bytes": sum(item["bytes"] for item in files), "metadata": metadata, "candidate_selection": candidate, "observed_expert_types": sorted(observed_experts), diff --git a/tests/terminal/test_own_files.py b/tests/terminal/test_own_files.py new file mode 100644 index 00000000..4d94bd1a --- /dev/null +++ b/tests/terminal/test_own_files.py @@ -0,0 +1,261 @@ +"""0.2.2: "use my own model files" accepts every layout 0.1.45's `setup.py --gguf-dir` accepted (issues #3316 #3292 #3190 #3209 #3331). + +The checker in front of setup (strata_control/models.plan_import) used to be stricter than setup itself: a split set whose first shard +holds only the metadata (Unsloth's), a link to the file (Hugging Face cache, Ollama), a folder holding several sizes, a folder above the +model folder (a whole repository, a 0.1.45 data folder), more than 128 files in a folder. Tiny GGUF files with the real shard names +stand for the real ones (the shard names and the expert types are what the table checks).""" + +from __future__ import annotations + +import json +import os +import struct +import tempfile +import unittest +from pathlib import Path + +from strata_control import gguf_preflight, models +from strata_control.profiles import ProfileError +from tools.gguf_reader import BLOCK_GEOMETRY + +TYPE_IDS = {"Q8_0": 8, "IQ3_S": 21, "IQ4_NL": 20, "IQ4_XS": 23, "IQ3_XXS": 18, "Q2_0": 42, "IQ2_S": 22, "IQ2_XS": 17} + + +def string(value: str) -> bytes: + raw = value.encode() + return struct.pack(" bytes: + """A tiny qwen4exp GGUF with one routed-expert tensor per type named; `experts=[]` is the metadata-only first shard of a split set.""" + pairs = [("general.architecture", 8, string("qwen4exp")), ("tokenizer.ggml.model", 8, string("gpt2")), + ("tokenizer.ggml.tokens", 9, struct.pack(" Path: + folder.mkdir(parents=True, exist_ok=True) + for n in names: + (folder / n).write_bytes(gguf_bytes(experts)) + return folder + + def gsq(self, folder: Path, names: list[str], kind: str) -> Path: + return self.put(folder, names, [kind]) + + def unsloth(self, folder: Path, names: list[str], kinds: list[str]) -> Path: + """The first shard has only the metadata (what llama.cpp's gguf-split makes), the others carry tensors.""" + folder.mkdir(parents=True, exist_ok=True) + (folder / names[0]).write_bytes(gguf_bytes([])) + for n in names[1:]: + (folder / n).write_bytes(gguf_bytes(kinds, metadata=False)) + return folder + + +class MetadataOnlyFirstShard(Base): + def test_unsloth_split_set_is_recognised(self): + folder = self.unsloth(self.base / "u", UNSLOTH_Q4, ["IQ4_NL"]) + plan = models.plan_import(str(folder)) + # the tiny files carry IQ4_NL experts, which UD-Q4_K_XL does not list: the set is found, the quantization is what is flagged + self.assertNotIn("unsupported_or_missing_architecture", plan["issues"]) + self.assertNotIn("unsupported_or_incomplete_tokenizer_metadata", plan["issues"]) + self.assertNotIn("GGUF tensor or metadata count", " ".join(plan["issues"])) + self.assertEqual((plan["candidate_selection"]["family"], plan["candidate_selection"]["model"]), ("unsloth", "UD-Q4_K_XL")) + + def test_unsloth_iq4_xs_passes_with_its_real_expert_types(self): + folder = self.unsloth(self.base / "u", UNSLOTH_IQ4, ["IQ3_S", "IQ4_NL", "IQ4_XS", "Q8_0"]) + plan = models.plan_import(str(folder)) + self.assertEqual(plan["issues"], []) + self.assertEqual(plan["candidate_selection"]["model"], "UD-IQ4_XS") + self.assertEqual(plan["model_dir"], str(folder)) + + def test_a_shard_with_no_tensors_and_no_metadata_is_still_refused(self): + f = self.base / "x.gguf" + f.write_bytes(gguf_bytes([], metadata=False)) + plan = models.plan_import(str(f)) + self.assertIn("unsupported_or_missing_architecture", plan["issues"]) + + +class Links(Base): + def make_links(self): + blobs = self.base / "blobs" + snap = self.base / "snapshots" / "abc" / "Q2_0" + blobs.mkdir() + snap.mkdir(parents=True) + for i, n in enumerate(Q2): + (blobs / f"sha{i}").write_bytes(gguf_bytes(["Q2_0"])) + try: + os.symlink(blobs / f"sha{i}", snap / n) + except (OSError, NotImplementedError): + self.skipTest("this account cannot create symbolic links") + return snap + + def test_a_hugging_face_cache_snapshot_is_used_through_its_links(self): + snap = self.make_links() + plan = models.plan_import(str(snap)) + self.assertEqual(plan["issues"], []) + self.assertEqual(plan["candidate_selection"]["model"], "Q2_0") + self.assertEqual(plan["file_count"], 2) + + def test_a_link_to_the_folder_is_followed(self): + real = self.gsq(self.base / "real", Q2, "Q2_0") + link = self.base / "link" + try: + os.symlink(real, link, target_is_directory=True) + except (OSError, NotImplementedError): + self.skipTest("this account cannot create symbolic links") + self.assertEqual(models.plan_import(str(link))["issues"], []) + + def test_a_link_to_a_file_that_is_gone_says_so(self): + snap = self.base / "s" + snap.mkdir() + try: + os.symlink(self.base / "gone", snap / Q2[0]) + except (OSError, NotImplementedError): + self.skipTest("this account cannot create symbolic links") + with self.assertRaises(ProfileError) as ctx: + gguf_preflight.real_model_file(snap / Q2[0]) + self.assertIn("link to a file that is not there", str(ctx.exception)) + + def test_a_missing_file_is_missing_not_a_link(self): + with self.assertRaises(ProfileError) as ctx: + gguf_preflight.real_model_file(self.base / "nope.gguf") + self.assertIn("is missing", str(ctx.exception)) + + def test_run_configs_keep_the_no_link_rule(self): + cfg = self.base / "real.json" + cfg.write_text("{}") + link = self.base / "strata-x.json" + try: + os.symlink(cfg, link) + except (OSError, NotImplementedError): + self.skipTest("this account cannot create symbolic links") + with self.assertRaises(ProfileError) as ctx: + models._read(link) # noqa: SLF001 + self.assertIn("symlink", str(ctx.exception)) + + +class Folders(Base): + def test_many_other_gguf_files_in_the_folder_do_not_refuse(self): + folder = self.gsq(self.base / "m", Q2, "Q2_0") + for i in range(140): + (folder / f"other-{i:03d}.gguf").write_bytes(b"GGUF") + plan = models.plan_import(str(folder)) + self.assertEqual(plan["candidate_selection"]["model"], "Q2_0") + self.assertEqual(plan["file_count"], 2) + + def test_several_sizes_in_one_folder_name_them_and_ask_for_one_file(self): + folder = self.gsq(self.base / "many", Q2, "Q2_0") + self.gsq(folder, IQ3XXS, "IQ3_XXS") + plan = models.plan_import(str(folder)) + self.assertEqual(plan["issues"], ["multiple_model_groups"]) + self.assertIsNone(plan["candidate_selection"]) + self.assertEqual(sorted(h["model"] for h in plan["folder_holds"]), ["IQ3_XXS", "Q2_0"]) + self.assertTrue(any("holds 2 models" in m and "type the path of its .gguf file" in m for m in plan["messages"])) + + def test_one_known_size_among_other_files_is_used_and_the_rest_is_named(self): + folder = self.gsq(self.base / "mix", Q2, "Q2_0") + (folder / "some-other-model-Q4_K_M.gguf").write_bytes(gguf_bytes(["IQ3_S"])) + plan = models.plan_import(str(folder)) + self.assertEqual(plan["issues"], []) + self.assertEqual(plan["candidate_selection"]["model"], "Q2_0") + self.assertEqual(plan["file_count"], 2) + self.assertTrue(any("some-other-model-Q4_K_M.gguf" in m and "leaves the others alone" in m for m in plan["messages"])) + + def test_a_shard_file_picks_its_set_out_of_a_folder_of_several(self): + folder = self.gsq(self.base / "many", Q2, "Q2_0") + self.gsq(folder, IQ3XXS, "IQ3_XXS") + plan = models.plan_import(str(folder / IQ3XXS[1])) + self.assertEqual(plan["issues"], []) + self.assertEqual(plan["candidate_selection"]["model"], "IQ3_XXS") + self.assertEqual(plan["model_dir"], str(folder)) + + def test_a_folder_above_the_model_folder_is_searched(self): + data = self.base / "Strata-data" + self.gsq(data / "models" / "q2_0", Q2, "Q2_0") + (data / "packs").mkdir() + for start in (data, data / "models"): + plan = models.plan_import(str(start)) + self.assertEqual(plan["issues"], [], start) + self.assertEqual(plan["model_dir"], str(data / "models" / "q2_0")) + self.assertTrue(any("The model files are in" in m for m in plan["messages"])) + + def test_a_whole_repository_with_one_folder_per_size_asks_which(self): + repo = self.base / "repo" + self.gsq(repo / "Q2_0", Q2, "Q2_0") + self.gsq(repo / "IQ3_XXS", IQ3XXS, "IQ3_XXS") + plan = models.plan_import(str(repo)) + self.assertIn("multiple_model_groups", plan["issues"]) + self.assertEqual(sorted((Path(h["folder"]).name, h["model"]) for h in plan["folder_holds"]), + [("IQ3_XXS", "IQ3_XXS"), ("Q2_0", "Q2_0")]) + self.assertTrue(plan["file_set_status"] == "invalid_or_incomplete") + + def test_one_known_folder_next_to_unrelated_ones_is_used(self): + top = self.base / "all" + self.gsq(top / "models" / "q2_0", Q2, "Q2_0") + (top / "stuff").mkdir() + (top / "stuff" / "notes.txt").write_text("x") + plan = models.plan_import(str(top)) + self.assertEqual(plan["candidate_selection"]["model"], "Q2_0") + + def test_a_folder_with_no_gguf_anywhere_says_so(self): + (self.base / "empty" / "a" / "b").mkdir(parents=True) + with self.assertRaises(ProfileError) as ctx: + models.plan_import(str(self.base / "empty")) + self.assertIn("no GGUF files found", str(ctx.exception)) + + def test_a_folder_name_with_spaces_and_a_second_drive_style_path(self): + folder = self.gsq(self.base / "my models" / "Qwen 3.8 files", Q2, "Q2_0") + self.assertEqual(models.plan_import(str(folder))["issues"], []) + + def test_a_missing_second_shard_is_one_plain_issue(self): + folder = self.put(self.base / "half", Q2[:1], ["Q2_0"]) + plan = models.plan_import(str(folder)) + self.assertEqual(plan["issues"], ["incomplete_or_invalid_shard_set"]) + + +class Table(unittest.TestCase): + def test_every_size_setup_installs_is_in_the_table(self): + """Setup can install it from --gguf-dir, so the checker in front of it must know it too (0.2.0 knew 7 of 10).""" + import importlib.util + spec = importlib.util.spec_from_file_location("strata_setup_for_test", models.ROOT / "setup.py") + setup = importlib.util.module_from_spec(spec) + spec.loader.exec_module(setup) + table = json.loads((models.ROOT / "data" / "gguf_fingerprints.json").read_text(encoding="utf-8")) + missing = [] + for family, fam in setup.FAMILIES.items(): + if fam.get("ready"): + continue + for model, row in setup.MODELS.items(): + if family not in row.get("families", ("qwen", "swift")): + continue + names = {setup.model_file(fam, model, i) for i in range(1, setup.model_shards(fam, model) + 1)} + key = f"{family}/{model}" + have = {Path(n).name for n in (table.get(key) or {}).get("files", [])} + if key not in models.SUPPORTED_SELECTIONS or have != names: + missing.append(key) + self.assertEqual(missing, []) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/strata_inspect.py b/tools/strata_inspect.py index 5d094d80..425954a1 100644 --- a/tools/strata_inspect.py +++ b/tools/strata_inspect.py @@ -40,9 +40,13 @@ KNOWN = [ ("swift", "Q2_0", "ukisai/Swift-1.5-Qwen3.8-Flash-Next-GSQ-RCO-GGUF", "Swift-Qwen3.8-Flash-Next-GSQ-RCO-Q2_0"), ("swift", "IQ2_XS", "ukisai/Swift-1.5-Qwen3.8-Flash-Next-GSQ-RCO-GGUF", "Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS"), ("swift", "IQ3_XXS", "ukisai/Swift-1.5-Qwen3.8-Flash-Next-GSQ-RCO-GGUF", "Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS"), + ("swift", "IQ3_S", "ukisai/Swift-1.5-Qwen3.8-Flash-Next-GSQ-RCO-GGUF", "Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S"), ("coder", "IQ1_M", "ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-Coder-GGUF", "IQ1_M/"), ("unsloth", "UD-IQ4_XS", "unsloth/Qwen3.8-Flash-Next-GGUF", "UD-IQ4_XS/"), ("unsloth", "UD-Q4_K_XL", "unsloth/Qwen3.8-Flash-Next-GGUF", "UD-Q4_K_XL/"), + ("unsloth", "UD-Q5_K_XL", "unsloth/Qwen3.8-Flash-Next-GGUF", "UD-Q5_K_XL/"), + ("unsloth", "UD-Q6_K_XL", "unsloth/Qwen3.8-Flash-Next-GGUF", "UD-Q6_K_XL/"), + ("unsloth", "Q8_0", "unsloth/Qwen3.8-Flash-Next-GGUF", "Q8_0/"), ] From 34d6c37df3671482afb39a20e248441cc0cb998c Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Tue, 20 Oct 2026 14:08:31 +0200 Subject: [PATCH 10/47] Disk space: stop only when the bytes do not fit, warn inside the working-room margin, a resumed download's partial file is not counted twice --- setup.py | 20 +++++++--- strata_control/updater.py | 27 ++++++++++--- tests/terminal/test_disk_space.py | 66 +++++++++++++++++++++++++++++++ 3 files changed, 102 insertions(+), 11 deletions(-) create mode 100644 tests/terminal/test_disk_space.py diff --git a/setup.py b/setup.py index 25cc50ff..dcf464f5 100644 --- a/setup.py +++ b/setup.py @@ -6976,8 +6976,10 @@ def install_own_path(a, family, gpu, hip, amd, cuda_tk, multi, port, ram, adopte size = fam["sha256"][gguf.name][0] part = gguf.with_name(gguf.name + ".part") left = 0 if gguf.exists() and done(gguf) else (size - (part.stat().st_size if part.is_file() else 0)) / 1e9 + if left and free_gb(folder) < left: + fail(f"not enough free disk space in {folder}: need ~{left:.0f} GB, {free_gb(folder):.0f} GB free", "use --models-dir on a bigger drive") if left and free_gb(folder) < left + 1: - fail(f"not enough free disk space in {folder}: need ~{left + 1:.0f} GB", "use --models-dir on a bigger drive") + warn(f"little free disk space in {folder}: {free_gb(folder):.1f} GB free for about {left:.1f} GB. Setup goes on and should fit") step(3, "Python packages") pip_install(requirement_lines() if REQUIREMENTS.exists() else PY_PACKAGES, @@ -7121,8 +7123,10 @@ def preview_family(a) -> int: left = sum(fam["sha256"][f.name][0] - (f.with_name(f.name + ".part").stat().st_size if f.with_name(f.name + ".part").is_file() else 0) for f in files if not (f.exists() and done(f))) / 1e9 + if left and free_gb(folder) < left: + fail(f"not enough free disk space in {folder}: need ~{left:.0f} GB, {free_gb(folder):.0f} GB free", "use --models-dir on a bigger drive") if left and free_gb(folder) < left + 1: - fail(f"not enough free disk space in {folder}: need ~{left + 1:.0f} GB", "use --models-dir on a bigger drive") + warn(f"little free disk space in {folder}: {free_gb(folder):.1f} GB free for about {left:.1f} GB. Setup goes on and should fit") step(5, f"downloading {fam['title']} {model}") for f in files: url = (fam["mmproj_hf"] if f.name == fam["mmproj"] else fam["hf"]) + f.name @@ -8103,13 +8107,19 @@ def main() -> int: q2_avx = model == "Q2_0" and avx512 and family == "qwen" prep_gb = MODELS[model].get("prepare_gb", 0.0) if ready and MODELS[model].get("prepare") and \ not prepared_done(model, models_dir) else 0.0 - need = to_fetch + prep_gb + (2 if mtp_have else 8) + \ + margin = 2 if mtp_have else 8 # working room: a guess, not bytes that will be written + real = to_fetch + prep_gb + \ (40 if q2_avx and not pack_bin else 0) + (1 if vision != "none" else 0) + \ (MODELS[model]["arena_gb"] + 1 if low_ram and not q2_avx and not pack_bin else 0) - if free_gb(models_dir) < need: - fail(f"not enough free disk space in {models_dir}: need ~{need:.0f} GB" + + need = real + margin + free_now = free_gb(models_dir) + if free_now < real: + fail(f"not enough free disk space in {models_dir}: need ~{real:.0f} GB, {free_now:.0f} GB free" + (f" ({on_disk:.0f} GB of the model is already there)" if on_disk >= 1 and not have_model else ""), "use --models-dir on a bigger drive") + if free_now < need: + warn(f"little free disk space in {models_dir}: {free_now:.0f} GB free for about {real:.0f} GB of files. " + "Setup goes on and should fit; free up space if it stops") # ---- 3. python packages step(3, "Python packages") diff --git a/strata_control/updater.py b/strata_control/updater.py index 390708a9..65c5e62b 100644 --- a/strata_control/updater.py +++ b/strata_control/updater.py @@ -366,11 +366,26 @@ def extract(archive: Path, destination: Path, fmt: str, installed_bytes: int, *, raise UpdateError(f"the package could not be unpacked: {longpath.describe_oserror(exc)}", 6) from None -def _free_space_check(root: Path, need: int) -> None: +def _free_space_check(root: Path, need: int, ctx: "Context | None" = None, sha256: str = "", component: str = "") -> None: + """Stop only when the drive cannot hold the bytes that are still to be written (the package not yet downloaded plus its unpacked + size). The 1.15 margin is a guess at working room, not a need: below it the update warns and goes on. A resumed download's + partial file is already on the drive, so it is not counted a second time.""" root.mkdir(parents=True, exist_ok=True) free = shutil.disk_usage(root).free - if free < need * SKEW_FREE_BYTES: - raise UpdateError(f"not enough free space in {root}: {free // (1 << 20)} MiB free, about {int(need * SKEW_FREE_BYTES) // (1 << 20)} MiB needed", 6) + have = 0 + if ctx is not None and sha256: + try: + have = (updates_dir(ctx.components) / "partial" / f"{sha256[:16]}.part").stat().st_size + except OSError: + have = 0 + real = max(need - have, 0) + drive = root.anchor or str(root) + if free < real: + raise UpdateError(f"not enough free space on {drive}: {free // (1 << 20)} MiB free, {real // (1 << 20)} MiB needed. " + f"Free up some space on {drive} and run the update again", 6) + if free < real * SKEW_FREE_BYTES and ctx is not None: + ctx.say("warn", f"Little free space on {drive}: {free // (1 << 20)} MiB free for about {real // (1 << 20)} MiB. " + "The update goes on and should fit; free up space if it stops.", component=component or "update") def _download(ctx: Context, state_name: str, url_ref: str, size: int, sha256: str, label: str, feed: feedmod.Feed) -> Path: @@ -752,7 +767,7 @@ def update_engine(ctx: Context, feed: feedmod.Feed, state: State) -> dict: return result root = ctx.components _warn_if_deep(ctx, ec.engine_dir(root) / folder_name(pkg), longpath.LONGEST_IN_PACKAGE.get(pkg.backend, longpath.LONGEST_IN_PACKAGE_DEFAULT) + 1) - _free_space_check(root, pkg.size + pkg.installed_bytes) + _free_space_check(root, pkg.size + pkg.installed_bytes, ctx, pkg.sha256, "engine") archive = _download(ctx, "engine", pkg.url, pkg.size, pkg.sha256, f"engine {pkg.label}", feed) # busy check after the long download: a model may have been started meanwhile; the verified archive is kept for the retry wait_until_idle(ctx.serving, wait=ctx.wait, emit=ctx.emit, cancel=ctx.cancel, poll=ctx.poll) @@ -918,7 +933,7 @@ def update_control(ctx: Context, feed: feedmod.Feed, state: State) -> dict: return result pkg = next(p for p in feed.control if p.platform == ctx.hardware["platform"]) root = ctx.components - _free_space_check(root, pkg.size + pkg.installed_bytes) + _free_space_check(root, pkg.size + pkg.installed_bytes, ctx, pkg.sha256, "control") archive = _download(ctx, "control", pkg.url, pkg.size, pkg.sha256, f"Control {pkg.version}", feed) stage = new_stage(root, "c") try: @@ -1008,7 +1023,7 @@ def update_app(ctx: Context, feed: feedmod.Feed) -> dict: if not key: raise UpdateError("this build has no app update key (update_keys.json app_minisign_public); the app installer cannot be verified, so it was not downloaded", 5) root = ctx.components - _free_space_check(root, entry["size"]) + _free_space_check(root, entry["size"], ctx, entry["sha256"], "app") archive = _download(ctx, "app", entry["url"], entry["size"], entry["sha256"], f"Strata app {feed.app.version}", feed) def chunks(): diff --git a/tests/terminal/test_disk_space.py b/tests/terminal/test_disk_space.py new file mode 100644 index 00000000..cac89436 --- /dev/null +++ b/tests/terminal/test_disk_space.py @@ -0,0 +1,66 @@ +"""Disk-space checks stop only when the bytes to write do not fit; the working-room margin warns; a resumed download's partial file is not counted twice.""" + +import tempfile +import unittest +from collections import namedtuple +from pathlib import Path +from unittest import mock + +from strata_control import updater + +Usage = namedtuple("Usage", "total used free") +MiB = 1 << 20 + + +class Ctx: + def __init__(self, root): + self.components = root + self.said = [] + + def say(self, phase, message, **extra): + self.said.append((phase, message)) + + +class FreeSpace(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.root = Path(self.tmp.name) + self.addCleanup(self.tmp.cleanup) + + def check(self, free_mib, need_mib, ctx=None, sha=""): + with mock.patch.object(updater.shutil, "disk_usage", return_value=Usage(10 ** 12, 0, free_mib * MiB)): + updater._free_space_check(self.root, need_mib * MiB, ctx, sha, "engine") + + def test_plenty_of_room_is_silent(self): + ctx = Ctx(self.root) + self.check(5000, 1000, ctx) + self.assertEqual(ctx.said, []) + + def test_between_the_real_need_and_the_margin_warns_and_goes_on(self): + ctx = Ctx(self.root) + self.check(1050, 1000, ctx) # 1.15x would be 1150 + self.assertEqual(len(ctx.said), 1) + self.assertEqual(ctx.said[0][0], "warn") + + def test_below_the_real_need_stops_and_names_the_drive_and_the_step(self): + with self.assertRaises(updater.UpdateError) as caught: + self.check(800, 1000, Ctx(self.root)) + self.assertEqual(caught.exception.exit_code, 6) + self.assertIn("800 MiB free", str(caught.exception)) + self.assertIn("Free up some space", str(caught.exception)) + + def test_the_partial_file_of_a_resumed_download_is_not_counted_twice(self): + ctx = Ctx(self.root) + sha = "ab" * 32 + part = updater.updates_dir(self.root) / "partial" + part.mkdir(parents=True) + (part / f"{sha[:16]}.part").write_bytes(b"x" * 600) + with mock.patch.object(updater.shutil, "disk_usage", return_value=Usage(10 ** 12, 0, 500)): + updater._free_space_check(self.root, 1000, ctx, sha, "engine") # 400 still to write, 500 free: fine and silent + self.assertEqual(ctx.said, []) + with self.assertRaises(updater.UpdateError): + updater._free_space_check(self.root, 1000, ctx, "") # without the partial file's credit 1000 > 500 + + +if __name__ == "__main__": + unittest.main() From bcda2e4b0d1bd5b347103e4ce20ebaee56f9379e Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Tue, 20 Oct 2026 13:08:01 +0200 Subject: [PATCH 11/47] Fix #3298: --mtp with a depth number is not a folder in the model file checks --- strata_cli/launch/runner.py | 2 + strata_control/doctor.py | 2 + tests/terminal/test_issues_022.py | 69 +++++++++++++++++++++++++++++++ 3 files changed, 73 insertions(+) create mode 100644 tests/terminal/test_issues_022.py diff --git a/strata_cli/launch/runner.py b/strata_cli/launch/runner.py index 9fd72a24..ef1565fd 100644 --- a/strata_cli/launch/runner.py +++ b/strata_cli/launch/runner.py @@ -164,6 +164,8 @@ def files_present(cfg: dict) -> list[str]: missing.append(tok) for flag in ("--pack", "--mtp"): args = [str(a) for a in cfg.get("args") or []] + if flag == "--mtp" and flag in args and args.index(flag) + 1 < len(args) and args[args.index(flag) + 1].isdigit(): + continue # Qwen3.6: a number is the draft depth, not a folder (#3298) if flag in args and args.index(flag) + 1 < len(args) and not Path(args[args.index(flag) + 1]).exists(): missing.append(args[args.index(flag) + 1]) vision = cfg.get("vision") diff --git a/strata_control/doctor.py b/strata_control/doctor.py index 3691febb..610b505d 100644 --- a/strata_control/doctor.py +++ b/strata_control/doctor.py @@ -192,6 +192,8 @@ def inspect(config_path: Path | None, *, profile_id: str | None = None, live: bo "required": True, "reason": "missing argument value"}) continue raw = args[index + 1] + if arg == "--mtp" and str(raw).isdigit(): + continue # Qwen3.6: --mtp 2 is the draft depth, not a folder (#3298) if kind == "file_with_scale": candidate, separator, scale = raw.rpartition(":") if separator: diff --git a/tests/terminal/test_issues_022.py b/tests/terminal/test_issues_022.py new file mode 100644 index 00000000..85ebc126 --- /dev/null +++ b/tests/terminal/test_issues_022.py @@ -0,0 +1,69 @@ +"""Small fixes from the 0.2.2 issue sweep, one test class per issue number.""" + +from __future__ import annotations + +import json +import sys +import tempfile +import unittest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[2])) + + +class Issue3298MtpDepth(unittest.TestCase): + """Qwen3.6 passes `--mtp 2` (a draft depth); it is not a folder.""" + + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.root = Path(self.tmp.name) + + def test_doctor_does_not_look_for_a_folder_named_2(self): + from strata_control import doctor + engine = self.root / "engine" + engine.write_text("x", encoding="utf-8") + engine.chmod(0o700) + tok = self.root / "tok" + tok.mkdir() + for n in ("vocab.json", "merges.txt", "token_type.json"): + (tok / n).write_text("{}", encoding="utf-8") + model = self.root / "m.gguf" + model.write_bytes(b"x") + cfg = self.root / "run.json" + cfg.write_text(json.dumps({"exe": str(engine), "args": ["--native", str(model), "--mtp", "2", "--vision"], + "cwd": str(self.root), "tokenizer": str(tok), "model_name": "q36", "port": 8095}), + encoding="utf-8") + report = doctor.inspect(cfg) + self.assertNotIn("mtp", [c["name"] for c in report["components"]]) + self.assertEqual([c["name"] for c in report["components"] if c["status"] not in ("ok",) + and c.get("required") and c["name"] in ("native", "mtp", "pack")], []) + + def test_doctor_still_checks_an_mtp_folder(self): + from strata_control import doctor + engine = self.root / "engine" + engine.write_text("x", encoding="utf-8") + engine.chmod(0o700) + tok = self.root / "tok" + tok.mkdir() + for n in ("vocab.json", "merges.txt", "token_type.json"): + (tok / n).write_text("{}", encoding="utf-8") + cfg = self.root / "run.json" + cfg.write_text(json.dumps({"exe": str(engine), "args": ["--mtp", str(self.root / "gone")], + "cwd": str(self.root), "tokenizer": str(tok), "model_name": "x", "port": 8095}), + encoding="utf-8") + report = doctor.inspect(cfg) + mtp = [c for c in report["components"] if c["name"] == "mtp"] + self.assertEqual(len(mtp), 1) + self.assertEqual(mtp[0]["status"], "missing") + + def test_launch_files_present_ignores_a_depth_number(self): + from strata_cli.launch.runner import files_present + model = self.root / "m.gguf" + model.write_bytes(b"x") + self.assertEqual(files_present({"args": ["--native", str(model), "--mtp", "2"]}), []) + self.assertEqual(files_present({"args": ["--mtp", str(self.root / "gone")]}), [str(self.root / "gone")]) + + +if __name__ == "__main__": + unittest.main() From ef5d8ab946e09518c8a0cf3cc495e31ba325a9ff Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Tue, 20 Oct 2026 13:08:39 +0200 Subject: [PATCH 12/47] Fix #3302: owner-only file checks accept the built-in Administrator (SDDL alias LA) --- strata_control/private_files.py | 30 +++++++++++++++++++--- tests/terminal/test_issues_022.py | 42 +++++++++++++++++++++++++++++++ 2 files changed, 69 insertions(+), 3 deletions(-) diff --git a/strata_control/private_files.py b/strata_control/private_files.py index 19cae983..e163c602 100644 --- a/strata_control/private_files.py +++ b/strata_control/private_files.py @@ -95,6 +95,28 @@ def current_user_sid() -> str: return _sid_cache +def _same_sid(sddl_trustee: str, sid: str) -> bool: + """True when an SDDL trustee names ``sid``. SDDL prints well-known accounts as two-letter aliases (the built-in + Administrator, RID 500, is ``LA``), so an alias is turned into its string SID before the compare (#3302).""" + if sddl_trustee == sid: + return True + if sddl_trustee.upper().startswith("S-1-") or not WINDOWS: + return False + pointer = ctypes.c_void_p() + if not _advapi.ConvertStringSidToSidW(sddl_trustee, ctypes.byref(pointer)): + return False + try: + text = wintypes.LPWSTR() + if not _advapi.ConvertSidToStringSidW(pointer.value, ctypes.byref(text)): + return False + try: + return text.value == sid + finally: + _kernel.LocalFree(ctypes.cast(text, ctypes.c_void_p)) + finally: + _kernel.LocalFree(pointer) + + def restrict_to_current_user(path: str | os.PathLike, *, directory: bool | None = None) -> None: """Make ``path`` readable and writable by the current user only. @@ -171,7 +193,7 @@ def is_private(path: str | os.PathLike) -> bool: if not head.startswith("D:") or "P" not in head[2:] or len(entries) != 1: return False fields = entries[0].split(";") - return len(fields) >= 6 and fields[0] == "A" and fields[5] == current_user_sid() + return len(fields) >= 6 and fields[0] == "A" and _same_sid(fields[5], current_user_sid()) _PRIVILEGED = {"SY", "BA", "OW", "CO", "CG", "S-1-5-18", "S-1-5-32-544", "S-1-3-4"} @@ -188,10 +210,12 @@ def is_unshared(path: str | os.PathLike) -> bool: if not WINDOWS: return is_private(path) sddl = dacl_sddl(path) - allowed = _PRIVILEGED | {current_user_sid()} + me = current_user_sid() + allowed = _PRIVILEGED | {me} for entry in re.findall(r"\(([^()]*)\)", sddl): fields = entry.split(";") - if len(fields) >= 6 and fields[0] in ("A", "OA") and fields[5] not in allowed: + if (len(fields) >= 6 and fields[0] in ("A", "OA") and fields[5] not in allowed + and not _same_sid(fields[5], me)): return False return True diff --git a/tests/terminal/test_issues_022.py b/tests/terminal/test_issues_022.py index 85ebc126..9de268ec 100644 --- a/tests/terminal/test_issues_022.py +++ b/tests/terminal/test_issues_022.py @@ -65,5 +65,47 @@ class Issue3298MtpDepth(unittest.TestCase): self.assertEqual(files_present({"args": ["--mtp", str(self.root / "gone")]}), [str(self.root / "gone")]) +@unittest.skipUnless(sys.platform == "win32", "SDDL aliases exist on Windows only") +class Issue3302AdministratorAlias(unittest.TestCase): + """SDDL prints the built-in Administrator (RID 500) as `LA`; the owner-only checks must still accept it.""" + + def setUp(self): + from unittest import mock + from strata_control import private_files as pf + self.pf = pf + self.mock = mock + # the built-in Administrator's string SID on this machine: resolve the alias the same way the fix does + import ctypes + from ctypes import wintypes + pointer = ctypes.c_void_p() + pf._advapi.ConvertStringSidToSidW("LA", ctypes.byref(pointer)) + text = wintypes.LPWSTR() + pf._advapi.ConvertSidToStringSidW(pointer.value, ctypes.byref(text)) + self.admin_sid = text.value + self.assertTrue(self.admin_sid.endswith("-500")) + + def test_alias_matches_the_account_it_names(self): + self.assertTrue(self.pf._same_sid("LA", self.admin_sid)) + self.assertTrue(self.pf._same_sid(self.admin_sid, self.admin_sid)) + self.assertFalse(self.pf._same_sid("LA", "S-1-5-21-1-2-3-1001")) + self.assertFalse(self.pf._same_sid("WD", self.admin_sid)) + self.assertFalse(self.pf._same_sid("S-1-5-21-1-2-3-1001", self.admin_sid)) + + def test_private_and_unshared_hold_for_the_built_in_administrator(self): + pf = self.pf + with self.mock.patch.object(pf, "current_user_sid", return_value=self.admin_sid), \ + self.mock.patch.object(pf, "dacl_sddl", return_value="D:PAI(A;OICI;FA;;;LA)"): + self.assertTrue(pf.is_private("x")) + self.assertTrue(pf.is_unshared("x")) + with self.mock.patch.object(pf, "current_user_sid", return_value=self.admin_sid), \ + self.mock.patch.object(pf, "dacl_sddl", return_value="D:PAI(A;OICI;FA;;;S-1-5-21-1-2-3-1001)"): + self.assertFalse(pf.is_private("x")) + self.assertFalse(pf.is_unshared("x")) + with self.mock.patch.object(pf, "current_user_sid", return_value=self.admin_sid), \ + self.mock.patch.object(pf, "dacl_sddl", return_value="D:PAI(A;OICI;FA;;;LA)(A;OICI;FR;;;WD)"): + self.assertFalse(pf.is_private("x")) + self.assertFalse(pf.is_unshared("x")) + + if __name__ == "__main__": unittest.main() From 461d0baee701174db9f228c3855bc02048f4b825 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Tue, 20 Oct 2026 13:09:20 +0200 Subject: [PATCH 13/47] Fix #3188: strata_bench names the port it starts its own server on --- tests/terminal/test_issues_022.py | 29 +++++++++++++++++++++++++++++ tools/strata_bench.py | 3 ++- 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/tests/terminal/test_issues_022.py b/tests/terminal/test_issues_022.py index 9de268ec..f6e12581 100644 --- a/tests/terminal/test_issues_022.py +++ b/tests/terminal/test_issues_022.py @@ -65,6 +65,35 @@ class Issue3298MtpDepth(unittest.TestCase): self.assertEqual(files_present({"args": ["--mtp", str(self.root / "gone")]}), [str(self.root / "gone")]) +class Issue3188BenchStartsItsOwnServer(unittest.TestCase): + """tools/strata_bench.py named `port` in the start-a-server branch without ever setting it.""" + + def test_the_start_branch_runs_with_the_config_port(self): + from unittest import mock + from tools import strata_bench as sb + import io + from contextlib import redirect_stdout + with tempfile.TemporaryDirectory() as tmp: + cfg = Path(tmp) / "run.json" + cfg.write_text(json.dumps({"port": 18999, "args": []}), encoding="utf-8") + started = [] + with mock.patch.object(sb, "is_strata", return_value=False), \ + mock.patch.object(sb, "try_json", return_value=None), \ + mock.patch.object(sb, "start_server", side_effect=lambda c, p, g, log: started.append(p) or object()), \ + mock.patch.object(sb, "wait_ready", return_value=False), \ + mock.patch.object(sb, "stop_server"): + out = io.StringIO() + with redirect_stdout(out), mock.patch("sys.stderr", io.StringIO()): + code = sb.main(["--config", str(cfg)]) + self.assertEqual(code, 1) + self.assertEqual(started, [18999]) + self.assertIn("on port 18999", out.getvalue()) + started.clear() + with redirect_stdout(io.StringIO()), mock.patch("sys.stderr", io.StringIO()): + sb.main(["--config", str(cfg), "--port", "18777"]) + self.assertEqual(started, [18777]) + + @unittest.skipUnless(sys.platform == "win32", "SDDL aliases exist on Windows only") class Issue3302AdministratorAlias(unittest.TestCase): """SDDL prints the built-in Administrator (RID 500) as `LA`; the owner-only checks must still accept it.""" diff --git a/tools/strata_bench.py b/tools/strata_bench.py index 3a9877fc..93d92ee1 100644 --- a/tools/strata_bench.py +++ b/tools/strata_bench.py @@ -975,7 +975,8 @@ def main(argv=None) -> int: if a.url: base = a.url.rstrip("/") else: - base = server_base(cfg.get("host"), a.port or int(cfg.get("port", 8080))) + port = a.port or int(cfg.get("port", 8080)) + base = server_base(cfg.get("host"), port) red = redactor(key=key) started = False try: From a569d80680a91b9a45c42acf2d0d7b16bfaaa760 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Tue, 20 Oct 2026 13:09:21 +0200 Subject: [PATCH 14/47] Fix #3187: calibrate checks the report folder before the sweep, not after it --- strata_control/calibration.py | 4 +++- tests/terminal/test_calibration.py | 7 +++++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/strata_control/calibration.py b/strata_control/calibration.py index 2dcec1be..8128639c 100644 --- a/strata_control/calibration.py +++ b/strata_control/calibration.py @@ -291,8 +291,10 @@ def _measure_locked(ref: str, path: Path, profile: dict | None, revision: str | _exclusive_preflight(cfg, profile) if output.exists() or output.is_symlink(): raise ProfileError("calibration report path already exists", 2) + if not output.parent.is_dir(): # before the 19 minute sweep, not after it (#3187) + raise ProfileError("report output directory does not exist", 5) identity = _identity(path, cfg, profile, revision) - cal = _full_folder("tools.calibrate") + cal =_full_folder("tools.calibrate") execute = runner or cal.run runner_cfg = _runtime_cfg(cfg, profile) runner_cfg["exe"] = str(_resolved(cfg["exe"], cfg, path)) diff --git a/tests/terminal/test_calibration.py b/tests/terminal/test_calibration.py index 127463d9..5ebc74ac 100644 --- a/tests/terminal/test_calibration.py +++ b/tests/terminal/test_calibration.py @@ -326,6 +326,13 @@ class CalibrationFlowTests(unittest.TestCase): ["engine.calibrate.rollback", "engine.calibrate.apply", "engine.calibrate.measure"]) + def test_missing_report_folder_is_refused_before_the_sweep(self): + # #3187: the sweep takes ~19 minutes; the folder check must not wait until after it + for output in (self.root / "no-such-dir" / "report.json", self.config / "report.json"): + with self.assertRaisesRegex(profiles.ProfileError, "report output directory does not exist"): + calibration.measure("local", output, exclusive_ack=True, + runner=lambda *_a, **_k: self.fail("the sweep must not start")) + def test_calibration_rechecks_reviewed_digests_inside_operation_lock(self): report_path = self.root / "pinned-calibration.json" with self.assertRaisesRegex(profiles.ProfileError, "source changed after review"): From ff64e08bba62eabc894089673844621b8a54efab Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Tue, 20 Oct 2026 13:11:20 +0200 Subject: [PATCH 15/47] Fix #3403: the Mac setup installs cmake and ninja before it compiles --- docs/MAC.md | 2 +- metal/setup_mac.py | 8 +++++--- setup.py | 11 +++++++++-- tests/terminal/test_issues_022.py | 32 +++++++++++++++++++++++++++++++ 4 files changed, 47 insertions(+), 6 deletions(-) diff --git a/docs/MAC.md b/docs/MAC.md index 19483ab6..d21131e8 100644 --- a/docs/MAC.md +++ b/docs/MAC.md @@ -56,7 +56,7 @@ What the first run does (each step is skipped when it is already done): 1. **Python.** It needs Python 3.10 or newer, but macOS ships 3.9. If that is all your Mac has, `setup.sh` downloads a standalone Python 3.12 (25 MB, pinned by SHA-256) into `.python`. No sudo, no Homebrew. 2. **Checks your Mac:** the chip, the memory, the macOS version, the Command Line Tools and the free disk. -3. **Python packages** into `.venv`. CMake and Ninja come from pip. +3. **Python packages** into `.venv`. CMake and Ninja come from pip too, installed just before the build in step 4. 4. **Builds the engine** (`build-metal/strata`). It uses Apple's metal-cpp headers (pinned by SHA-256) and llama.cpp's ggml at the commit the PC build pins. 5. **Downloads the model.** The download resumes if interrupted. `--gguf-dir` uses files you already have. 6. **Prepares the model:** the pack (seconds), and the MTP draft layer (about 5 GB of the original checkpoint). On a Mac that streams: the experts' copy instead of the draft layer (about 3 minutes on the M4, checked byte for byte against the model file). diff --git a/metal/setup_mac.py b/metal/setup_mac.py index d7ebb96f..834de130 100644 --- a/metal/setup_mac.py +++ b/metal/setup_mac.py @@ -6,7 +6,7 @@ What it does, each step skipped when it is already done: 1. checks the Mac: Apple Silicon, the chip, unified memory, macOS version, the Command Line Tools, free disk 2. recommends a model by memory (recommend, never force: an explicit --model is kept, with what it risks) - 3. installs the Python packages into .venv (cmake and ninja come from pip: no Homebrew, no sudo) + 3. installs the Python packages into .venv (cmake and ninja come from pip, just before step 4: no Homebrew, no sudo) 4. builds the Metal engine from source: metal-cpp (Apple's headers) and llama.cpp's ggml at the pinned commit 5. downloads the model (setup.py's downloader: resumable, the pinned revision) 6. prepares the model: the native pack (tools/iq_pack.py) and the MTP draft layer (tools/mtp_fetch.py, mtp_pack.py) @@ -127,6 +127,7 @@ def build_engine(llama: Path, jobs: int | None = None) -> Path: S.ok(f"Metal engine: {EXE} (built for this source)") return EXE mcpp = metal_cpp() + S.ensure_build_tools() # cmake and ninja are in requirements-build.txt, not requirements.txt (#3403) S.say(" Building the Metal engine from source (5-15 minutes the first time) ...") BUILD_DIR.mkdir(exist_ok=True) log = BUILD_DIR / "build.log" @@ -170,6 +171,7 @@ def build_vision(llama: Path) -> Path: return VISION_EXE except (OSError, ValueError): pass + S.ensure_build_tools() S.say(" Building the image encoder (1-3 minutes) ...") env = dict(os.environ, PATH=str(Path(sys.executable).parent) + os.pathsep + os.environ.get("PATH", "")) log = ROOT / "build-vision.log" @@ -416,9 +418,9 @@ def main(argv=None) -> int: if free < need: S.warn(f"about {need:.0f} GB are needed on the disk ({free:.0f} GB free): kept as you chose; it may run out") - # ---- 3. Python packages (cmake and ninja among them: the engine build's tools) + # ---- 3. Python packages (cmake and ninja come with the build in step 4, from requirements-build.txt) S.step(3, "Python packages") - S.pip_install(S.requirement_lines() if S.REQUIREMENTS.exists() else S.PY_PACKAGES, "numpy, jinja2, ..., cmake, ninja") + S.pip_install(S.requirement_lines() if S.REQUIREMENTS.exists() else S.PY_PACKAGES, "numpy, jinja2, ...") # ---- 4. the engine S.step(4, "the Strata engine (Metal)") diff --git a/setup.py b/setup.py index dcf464f5..bbb3380a 100644 --- a/setup.py +++ b/setup.py @@ -4869,8 +4869,9 @@ def install_build_tools(gpu, yes): return nvcc, find_vcvars(cuda_v) if WIN else None -def cmake_build(src, bdir, target, defs, vcvars, bat_name): - acquisition.require("a compile (cmake)") +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 @@ -4880,6 +4881,12 @@ def cmake_build(src, bdir, target, defs, vcvars, bat_name): cmake, ninja = find_tool("cmake"), find_tool("ninja") if cmake is None or ninja is None: fail("cmake / ninja not found after installing them", "run: .venv python -m pip install -r requirements-build.txt") + return cmake, ninja + + +def cmake_build(src, bdir, target, defs, vcvars, bat_name): + acquisition.require("a compile (cmake)") + cmake, ninja = ensure_build_tools() conf = [cmake, "-G", "Ninja", f"-DCMAKE_MAKE_PROGRAM={ninja}", "-S", str(src), "-B", str(bdir), "-DCMAKE_BUILD_TYPE=Release", *defs] build = [cmake, "--build", str(bdir), "--target", target, "-j", str(max(2, (os.cpu_count() or 4) // 2))] diff --git a/tests/terminal/test_issues_022.py b/tests/terminal/test_issues_022.py index f6e12581..136f722e 100644 --- a/tests/terminal/test_issues_022.py +++ b/tests/terminal/test_issues_022.py @@ -65,6 +65,38 @@ class Issue3298MtpDepth(unittest.TestCase): self.assertEqual(files_present({"args": ["--mtp", str(self.root / "gone")]}), [str(self.root / "gone")]) +class Issue3403MacBuildTools(unittest.TestCase): + """The Mac setup compiles without setup.cmake_build(), so cmake and ninja must be installed for it too.""" + + def test_missing_build_tools_are_installed_before_the_mac_compile(self): + from unittest import mock + import setup + sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "metal")) + import setup_mac as M + installed = {"cmake": None, "ninja": None} + + def find(name): + return installed[name] + + def pip(packages, what): + self.assertTrue(all(p.split("==")[0] in ("cmake", "ninja") for p in packages), packages) + 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: + 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 + self.assertEqual(pi.call_count, 1) + + def test_both_mac_builds_ask_for_the_tools_first(self): + import inspect + sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "metal")) + import setup_mac as M + for fn in (M.build_engine, M.build_vision): + self.assertIn("S.ensure_build_tools()", inspect.getsource(fn), fn.__name__) + + class Issue3188BenchStartsItsOwnServer(unittest.TestCase): """tools/strata_bench.py named `port` in the start-a-server branch without ever setting it.""" From 386155fa25da2033a900805ddc0442cce9f9778f Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Tue, 20 Oct 2026 13:12:58 +0200 Subject: [PATCH 16/47] Fix #3370: the vision work folder is made again when a temp cleaner removed it --- serve/server.py | 9 +++++++ serve/test_vision_workdir.py | 46 ++++++++++++++++++++++++++++++++++++ 2 files changed, 55 insertions(+) create mode 100644 serve/test_vision_workdir.py diff --git a/serve/server.py b/serve/server.py index dc653e90..9a04d39f 100644 --- a/serve/server.py +++ b/serve/server.py @@ -2560,6 +2560,13 @@ class Vision: args += ["--min-tokens", str(cfg["min_tokens"])] return args + def _ensure_dir(self): + """#3370: a temp cleaner (Windows Storage Sense) removes the empty work folder while the encoder is unloaded; the next + start then failed with WinError 267 for as long as the server lived. Make it again; pictures cached in it are gone.""" + if not self.dir.is_dir(): + self.dir.mkdir(parents=True, exist_ok=True) + self.cache.clear() + def _start(self): """Start the reader. When a GPU reader that has a CPU reader to fall back on does not start (the GPU runtime does not load, the card is not in its build, the card is busy), the CPU reader is started instead, for good, with one log line @@ -2577,6 +2584,7 @@ class Vision: def _start_reader(self): args, log, env = self.spawn + self._ensure_dir() # cwd is the encoder's directory: the ENC lines name the files relative to it (#480: no space in the line) self.proc = popen("the image encoder", args, role="vision", stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=log or subprocess.DEVNULL, text=True, encoding="utf-8", bufsize=1, env=env, @@ -2739,6 +2747,7 @@ class Vision: data = self.normalize(source if isinstance(source, bytes) else self.load(source)) key = hashlib.sha256(data).hexdigest()[:32] with self.lock: + self._ensure_dir() if key in self.cache: self.cache[key] = self.cache.pop(key) # most recently used last return self.cache[key] diff --git a/serve/test_vision_workdir.py b/serve/test_vision_workdir.py new file mode 100644 index 00000000..2bba189c --- /dev/null +++ b/serve/test_vision_workdir.py @@ -0,0 +1,46 @@ +"""#3370: the encoder's work folder is made again when a temp cleaner removed it while the encoder was unloaded. + + python -m serve.test_vision_workdir +""" +import io +import tempfile +import unittest +from pathlib import Path +from types import SimpleNamespace +from unittest import mock + +import serve.server as server + + +class WorkDir(unittest.TestCase): + def test_start_makes_a_removed_work_folder_again(self): + proc = SimpleNamespace(stdin=io.StringIO(), stdout=io.StringIO("READY\n"), kill=lambda: None, + wait=lambda timeout=None: 0, poll=lambda: None) + with tempfile.TemporaryDirectory() as tmp: + v = server.Vision.__new__(server.Vision) + v.spawn = (["strata-vision"], None, None) + v.dir = Path(tmp) / "strata-vision-gone" + v.cache = {"k": (v.dir / "k.sve", 4)} + seen = [] + + def fake_popen(*a, **k): + seen.append(Path(k["cwd"]).is_dir()) # the real popen raises WinError 267 when it is not + return proc + + with mock.patch.object(server, "popen", fake_popen): + v._start() + self.assertEqual(seen, [True]) + self.assertTrue(v.dir.is_dir()) + self.assertEqual(v.cache, {}) # its cached embeddings went with the folder + + def test_an_existing_folder_and_its_cache_are_left_alone(self): + with tempfile.TemporaryDirectory() as tmp: + v = server.Vision.__new__(server.Vision) + v.dir = Path(tmp) + v.cache = {"k": (v.dir / "k.sve", 4)} + v._ensure_dir() + self.assertEqual(len(v.cache), 1) + + +if __name__ == "__main__": + unittest.main() From ddbbda4824f54c37898dc5a51c3d0d17b01c33e2 Mon Sep 17 00:00:00 2001 From: MEsfits <90729048+MEsfits@users.noreply.github.com> Date: Tue, 20 Oct 2026 13:13:30 +0200 Subject: [PATCH 17/47] Fix #3275: calibrate a dual config whose gpu is the string 0,1 (from PR #3276; a single card given as a number keeps asking for that card) --- setup.py | 20 +++++++++++++++++++- tools/test_setup_amd.py | 16 ++++++++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/setup.py b/setup.py index bbb3380a..fec02400 100644 --- a/setup.py +++ b/setup.py @@ -1738,7 +1738,7 @@ def recommend_remote_expert_opt(cfg: dict, off: bool = False) -> None: plain helper path). The engine uses it only with a helper cache; a layer split runs as before. A recommendation: `off` (setup's --no-remote-expert-opt) or "remote_expert_opt": false in the config keeps it out, and a single-GPU config is not touched.""" - if not isinstance(cfg.get("gpu"), list) or len(cfg["gpu"]) < 2: + if len(gpu_sel(cfg.get("gpu"))) < 2: return args = cfg.setdefault("args", []) if off or cfg.get("remote_expert_opt") is False: @@ -5949,11 +5949,29 @@ def hip_config_cards(sel) -> list[dict]: return cards +def gpu_sel(value) -> list: + """A config's "gpu" as a list of card numbers: 0, [0, 2] or the string form "0,2" (which serve splits + the same way). [] when it names none. Without this, a string "0,1" reached gpu_info() whole and + calibrate died with "there is no GPU 0,1" on a dual-GPU config.""" + if value is None or value == "": + return [] + items = value if isinstance(value, (list, tuple)) else str(value).split(",") + sel = [] + for x in items: + x = str(x).strip() + if x == "": + continue + sel.append(int(x) if x.isdigit() else x) + return sel + + def hardware_key(cfg: dict) -> str: """What a calibration is valid for: this GPU, CPU and RAM, and the model with its context and images setting (the context's KV cache and the image encoder take VRAM from the expert cache). #566: a HIP config's cards are AMD's (hip_config_cards) - nvidia-smi's list named them "?" (or another card with that number) before.""" sel = cfg.get("gpu") + if isinstance(sel, str): + sel = gpu_sel(sel) if cfg.get("backend") == "hip": gl = hip_config_cards(sel) else: diff --git a/tools/test_setup_amd.py b/tools/test_setup_amd.py index 3e1001b8..6a3f121a 100644 --- a/tools/test_setup_amd.py +++ b/tools/test_setup_amd.py @@ -416,6 +416,22 @@ class CalibrationKey(unittest.TestCase): "NVIDIA GeForce RTX 5070 + NVIDIA GeForce RTX 5070|24GB|AMD Ryzen 9 7950X|64GB|" "qwen3.8-flash-next-iq3_xxs|32768|text") + def test_nvidia_string_dual_keys_like_the_list(self): + """A dual config's string "0,1" keys like [0, 1] (calibrate died with "there is no GPU 0,1").""" + def amd(*a, **k): + raise AssertionError("amd_gpus called for an NVIDIA config") + with mock.patch.object(setup, "amd_gpus", amd), \ + mock.patch.object(setup, "gpu_info", lambda i=None: {"name": "NVIDIA GeForce RTX 5070", "vram_gb": 11.94}): + self.assertEqual(setup.hardware_key(self.cfg("0,1", backend="cuda")), + setup.hardware_key(self.cfg([0, 1], backend="cuda"))) + self.assertEqual(setup.gpu_sel("0,1"), [0, 1]) + self.assertEqual(setup.gpu_sel("0"), [0]) + asked = [] + with mock.patch.object(setup, "amd_gpus", amd), \ + mock.patch.object(setup, "gpu_info", lambda i=None: asked.append(i) or {"name": "NVIDIA GeForce RTX 5070", "vram_gb": 11.94}): + setup.hardware_key(self.cfg(1, backend="cuda")) # a single card given as a number still asks for that card + self.assertEqual(asked, [1]) + def test_setup_reuses_a_saved_calibration_on_linux_hip(self): cfg = self.cfg(1) saved = {"settings": {"pcie_frac": 0.0}, "tok_s": 40.1, "date": "2026-10-03"} From b611ec5f1e5d0a57217d68fcf77d84e62fe41bfd Mon Sep 17 00:00:00 2001 From: xrip Date: Tue, 20 Oct 2026 13:16:30 +0200 Subject: [PATCH 18/47] Fix #2141: honour llama-server's thinking_budget_tokens (from PR #2140) --- docs/DETAILS.md | 3 ++- serve/server.py | 11 +++++++---- serve/test_server.py | 11 +++++++++++ 3 files changed, 20 insertions(+), 5 deletions(-) diff --git a/docs/DETAILS.md b/docs/DETAILS.md index 80d6d704..8090cea4 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -907,7 +907,8 @@ print(r.choices[0].message.content) from going to sleep while at least one request is running or waiting (Windows' `SetThreadExecutionState` with `ES_SYSTEM_REQUIRED`; the screen may still turn off), and gives the normal sleep rules back when the server is idle and when it exits. Default off. On Linux and macOS it does nothing (one line at startup says so). -- **A hard thinking budget (opt-in).** `"reasoning_budget_tokens": N` in a request (OpenAI or Anthropic) caps the +- **A hard thinking budget (opt-in).** `"reasoning_budget_tokens": N` (or llama.cpp's `"thinking_budget_tokens": N`, which + clients written for llama-server send) in a request (OpenAI or Anthropic) caps the thinking at N tokens: when it gets there the server ends it with a short wrap-up line and ``, and the model answers from there (the engine continues from what it already holds, so nothing is read again). The wrap-up is part of the thinking the client sees and counts as output tokens. `"reasoning_budget_tokens": N` in diff --git a/serve/server.py b/serve/server.py index 9a04d39f..0ad37df2 100644 --- a/serve/server.py +++ b/serve/server.py @@ -3785,10 +3785,13 @@ class Service: return int(getattr(self.engine, "max_context", 0) or getattr(self.engine, "known_ctx", 0) or 0) def reasoning_budget(self, req) -> int | None: - """#123: the most tokens this request may think, or None: the request's `reasoning_budget_tokens`, else the - config's. 0 (or less) means no budget, so a request can turn a configured one off. ValueError (a 400) for - anything that is not a whole number.""" - value = (req or {}).get("reasoning_budget_tokens") if isinstance(req, dict) else None + """#123: the most tokens this request may think, or None: the request's `reasoning_budget_tokens` (or, as + llama.cpp reads it, `thinking_budget_tokens`), else the config's. 0 (or less) means no budget, so a request can + turn a configured one off. ValueError (a 400) for anything that is not a whole number.""" + req = req if isinstance(req, dict) else {} + value = req.get("reasoning_budget_tokens") + if value is None: # a null does not hide the other name + value = req.get("thinking_budget_tokens") if value is None: value = self.reasoning_budget_tokens if isinstance(value, float) and value.is_integer(): diff --git a/serve/test_server.py b/serve/test_server.py index 235d6910..b1a5fe28 100644 --- a/serve/test_server.py +++ b/serve/test_server.py @@ -4129,6 +4129,17 @@ class ThinkingBudget(unittest.TestCase): self.assertEqual(b["usage"]["completion_tokens"], 20 + len(extra) + len(ThinkingEngine.ANSWER) + 1) self.assertEqual(b["usage"]["prompt_tokens"], len(first)) + def test_llama_cpp_thinking_budget_tokens_is_the_same_budget(self): + """llama.cpp's name (pi-llama-cpp sends it): the same wrap-up; reasoning_budget_tokens wins when both are set.""" + from serve.server import REASONING_WRAP_UP + wrap = REASONING_WRAP_UP.split("")[0] + code, b = self.openai(thinking_budget_tokens=20) + self.assertEqual(code, 200, b) + self.assertEqual(b["choices"][0]["message"]["reasoning_content"], ThinkingEngine.THOUGHT[:20] + wrap) + code, b = self.openai(reasoning_budget_tokens=10, thinking_budget_tokens=20) + self.assertEqual(code, 200, b) + self.assertEqual(b["choices"][0]["message"]["reasoning_content"], ThinkingEngine.THOUGHT[:10] + wrap) + def test_a_stop_string_is_found_in_the_answer_after_the_wrap_up(self): """#454: the continuation after the thinking budget is cut at a stop string too.""" code, b = self.openai(reasoning_budget_tokens=20, stop=["answer is"]) From 9d2870d1872a95edf04cbbbd21668f0608e0c3f4 Mon Sep 17 00:00:00 2001 From: xrip Date: Tue, 20 Oct 2026 13:17:47 +0200 Subject: [PATCH 19/47] Fix #2289: Anthropic usage reports cache_creation_input_tokens, the prompt tokens read now and kept for the next request (from PR #2290) --- serve/server.py | 10 +++++----- serve/test_parallel_yield.py | 2 +- serve/test_request_accounting.py | 4 ++-- serve/test_server.py | 7 +++++-- 4 files changed, 13 insertions(+), 10 deletions(-) diff --git a/serve/server.py b/serve/server.py index 0ad37df2..434043df 100644 --- a/serve/server.py +++ b/serve/server.py @@ -5596,14 +5596,14 @@ def anthropic_events(svc: Service, req: dict, ids, thinking, tools, max_new, can stop = "stop_sequence" if x.get("stop_sequence") is not None else \ "tool_use" if used_tool and streamed <= finished and x["finish"] == "stop" else \ {"stop": "end_turn", "length": "max_tokens", "cancel": "end_turn"}[x["finish"]] - # the final counts, Anthropic's way: input_tokens leaves out what the conversation cache already held, - # which is cache_read_input_tokens (message_start could only say the whole prompt). At least the last - # prompt token is always read, and Claude Code takes an input_tokens of 0 as "not given" and keeps - # message_start's whole prompt beside cache_read_input_tokens: the prompt counted twice (#1013) + # the final counts (message_start could only say the whole prompt): what was read now stays for the next + # request, a cache write; input_tokens keeps the last token, as 0 makes Claude Code count the prompt twice (#1013) reused = max(0, min(x.get("reused") or 0, len(ids) - 1)) + read_now = len(ids) - reused yield "message_delta", {"type": "message_delta", "delta": {"stop_reason": stop, "stop_sequence": x.get("stop_sequence")}, - "usage": {"input_tokens": len(ids) - reused, "cache_read_input_tokens": reused, + "usage": {"input_tokens": 1, "cache_creation_input_tokens": read_now - 1, + "cache_read_input_tokens": reused, "output_tokens": x["completion_tokens"]}} yield "message_stop", {"type": "message_stop"} diff --git a/serve/test_parallel_yield.py b/serve/test_parallel_yield.py index b807ee7c..eeabe383 100644 --- a/serve/test_parallel_yield.py +++ b/serve/test_parallel_yield.py @@ -240,7 +240,7 @@ class ParallelServiceYield(tp.FakeEngineCase): prompt = self.svc.history[[h["output_tokens"] for h in self.svc.history].index( max(h["output_tokens"] for h in self.svc.history))]["prompt_total"] self.assertGreaterEqual(u["input_tokens"], 1, u) - self.assertEqual(u["input_tokens"] + u["cache_read_input_tokens"], prompt, u) + self.assertEqual(u["input_tokens"] + u["cache_creation_input_tokens"] + u["cache_read_input_tokens"], prompt, u) self.assertEqual(u["cache_read_input_tokens"], 3, u) # the first read's reuse, not the continuation's def test_a_slot_request_ended_by_its_stop_token_reports_the_slot_leg(self): diff --git a/serve/test_request_accounting.py b/serve/test_request_accounting.py index 145fdd56..55ff0540 100644 --- a/serve/test_request_accounting.py +++ b/serve/test_request_accounting.py @@ -148,14 +148,14 @@ class RequestAccounting(unittest.TestCase): usage = self.chat("/v1/messages")["usage"] self.assertEqual(self.engine.attempts, 2) self.assertEqual(usage["cache_read_input_tokens"], 5) - self.assertEqual(usage["input_tokens"], len(self.engine.prompts[0]) - 5) + self.assertEqual(usage["input_tokens"] + usage["cache_creation_input_tokens"], len(self.engine.prompts[0]) - 5) def test_anthropic_stream_classifies_only_original_input_as_cached(self): events = self.chat("/v1/messages", stream=True) usage = next(event["usage"] for event in events if event["type"] == "message_delta") self.assertEqual(self.engine.attempts, 2) self.assertEqual(usage["cache_read_input_tokens"], 5) - self.assertEqual(usage["input_tokens"], len(self.engine.prompts[0]) - 5) + self.assertEqual(usage["input_tokens"] + usage["cache_creation_input_tokens"], len(self.engine.prompts[0]) - 5) def test_single_segment_keeps_its_own_usage_and_timings(self): response = self.chat(budget=10000) diff --git a/serve/test_server.py b/serve/test_server.py index b1a5fe28..1e3d7f3d 100644 --- a/serve/test_server.py +++ b/serve/test_server.py @@ -74,7 +74,8 @@ class MaxTokens(unittest.TestCase): return s, b, u.get("prompt_tokens"), u.get("completion_tokens") s, b = self.post("/v1/messages", {"model": "m", "messages": msgs, **budget}) u = b.get("usage", {}) - return s, b, u.get("input_tokens"), u.get("output_tokens") + prompt = sum(u.get(k) or 0 for k in ("input_tokens", "cache_creation_input_tokens", "cache_read_input_tokens")) + return s, b, prompt if u else None, u.get("output_tokens") def test_anthropic_thinks_only_when_asked(self): # #278: Anthropic's thinking is opt-in; "thinking", an effort or a reasoning_budget_tokens (#123) asks for it @@ -3713,7 +3714,9 @@ class UsageAndStatus(unittest.TestCase): def test_anthropic(self): u = self.chat("/v1/messages")["usage"] self.assertEqual(u["cache_read_input_tokens"], ClockedEngine.REUSED) - self.assertEqual(u["input_tokens"] + u["cache_read_input_tokens"], len(self.engine.last_prompt)) + self.assertEqual(u["input_tokens"], 1) # what was read now is kept: written to the cache + self.assertEqual(u["input_tokens"] + u["cache_creation_input_tokens"] + u["cache_read_input_tokens"], + len(self.engine.last_prompt)) self.assertGreater(u["output_tokens"], 0) def test_v1_status(self): From fb2f38740783ea445f6a1371bdde2db6c9ee2d88 Mon Sep 17 00:00:00 2001 From: Yash Raj Pandey Date: Tue, 20 Oct 2026 13:18:18 +0200 Subject: [PATCH 20/47] Fix #2496: an engine program that cannot be started is a 503 with the reason, not a dropped connection (from PR #2497) --- serve/server.py | 17 ++++++++++++++--- serve/test_ready_timeout.py | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+), 3 deletions(-) diff --git a/serve/server.py b/serve/server.py index 434043df..aca6c5a7 100644 --- a/serve/server.py +++ b/serve/server.py @@ -1015,8 +1015,15 @@ class StrataEngine: pin["preexec_fn"] = lambda: os.sched_setaffinity(0, cpus) end_leftover_engines(exe) # one an earlier run lost still holds the GPU and the memory spawned_at = time.monotonic() - self.proc = popen("the Strata engine", [exe, "--serve", *args], cwd=cwd, stdin=subprocess.PIPE, - stdout=subprocess.PIPE, stderr=self.log, text=True, encoding="utf-8", bufsize=1, env=env, **pin) + try: + self.proc = popen("the Strata engine", [exe, "--serve", *args], cwd=cwd, stdin=subprocess.PIPE, + stdout=subprocess.PIPE, stderr=self.log, text=True, encoding="utf-8", bufsize=1, env=env, + **pin) + except OSError: # nothing started: the narrator stops, the log handle goes back + loading.set() + if log: + self.log.close() + raise # the READY read has a timeout (#1317): the lines come from a thread, up to READY, so the rest of the stream # stays for _pump (one reader at a time) ready_q: queue.Queue = queue.Queue() @@ -3963,9 +3970,13 @@ class Service: "(a minute or two) ...", flush=True) try: self.engine.restart() - except Exception: + except Exception as e: if vision_started: self.vision.unload() + # the program could not be started at all (missing, not executable, or blocked by Windows - #735): the + # request path answers EngineDied with a 503, but takes a bare OSError for a client that went away (#2496) + if isinstance(e, OSError): + raise EngineDied(f"the engine could not be started: {e}") from e raise print("[strata] the engine is running again", flush=True) if self.restore_after_load: # an image job unloaded it: its conversation comes back diff --git a/serve/test_ready_timeout.py b/serve/test_ready_timeout.py index 78ef33d0..009d9ecc 100644 --- a/serve/test_ready_timeout.py +++ b/serve/test_ready_timeout.py @@ -104,5 +104,40 @@ class ReadyTimeout(unittest.TestCase): self.assertFalse(svc.engine.starting) +class SpawnFailure(unittest.TestCase): + """The engine program cannot be started at all (missing, not executable, or blocked by Windows - #735): the + request that was loading it gets a 503 with the reason, not a dropped connection.""" + BODIES = {'/v1/chat/completions': {'messages': [{'role': 'user', 'content': 'hi'}], 'max_tokens': 8}, + '/v1/messages': {'model': 'strata', 'max_tokens': 8, 'messages': [{'role': 'user', 'content': 'hi'}]}, + '/v1/responses': {'input': 'hi', 'max_output_tokens': 8}} + + def test_missing_engine_answers_503_and_leaves_nothing_running(self): + tmp = tempfile.TemporaryDirectory(); self.addCleanup(tmp.cleanup) + root = Path(tmp.name) + eng = StrataEngine(str(root / 'no-such-engine'), [], log=str(root / 'engine.log'), lazy=True) + svc = Service(eng, ByteTokenizer(), ChatTemplate(Path(__file__).parent / 'chat_template.jinja')) + httpd = serve(svc, port=0) + self.addCleanup(httpd.shutdown); self.addCleanup(httpd.server_close) + base = f'http://127.0.0.1:{httpd.server_address[1]}' + before = set(threading.enumerate()) + cases = list(self.BODIES.items()) + [('/v1/chat/completions', + {**self.BODIES['/v1/chat/completions'], 'stream': True})] + for path, body in cases: + with self.subTest(path=path, stream=body.get('stream', False)): + req = urllib.request.Request(base + path, data=json.dumps(body).encode(), + headers={'Content-Type': 'application/json'}) + with self.assertRaises(urllib.error.HTTPError) as cm: + urllib.request.urlopen(req, timeout=30) + self.assertEqual(cm.exception.code, 503) + self.assertIn('the engine could not be started', cm.exception.read().decode()) + self.assertTrue(eng.log.closed) # our handle on the engine log is given back + # the start narrator ("still starting ... please wait") ends with the failed start + deadline = time.monotonic() + 5 + while (narrators := [t for t in set(threading.enumerate()) - before if '(narrate_start)' in t.name]) \ + and time.monotonic() < deadline: + time.sleep(0.1) + self.assertEqual(narrators, []) + + if __name__ == '__main__': unittest.main() From ce938fb8c9a002d922341eafde950eb8bc1ce571 Mon Sep 17 00:00:00 2001 From: ctr-137 Date: Tue, 20 Oct 2026 13:20:09 +0200 Subject: [PATCH 21/47] Fix #2971: a tool call no longer widens the web page on phones (from PR #3156) --- serve/web/app.css | 7 ++++--- tests/terminal/test_issues_022.py | 20 ++++++++++++++++++++ 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/serve/web/app.css b/serve/web/app.css index 0c75e60e..66d96acd 100644 --- a/serve/web/app.css +++ b/serve/web/app.css @@ -4,7 +4,7 @@ html, body { height: 100%; } body { display: flex; flex-direction: column; overflow: hidden; } main { flex: 1; min-height: 0; display: flex; } -.view { flex: 1; min-height: 0; display: flex; flex-direction: column; } +.view { flex: 1; min-height: 0; min-width: 0; display: flex; flex-direction: column; } .view[hidden] { display: none; } .muted { color: var(--st-ink-muted); } .small { font-size: var(--st-fs-xs); } @@ -53,8 +53,9 @@ main { flex: 1; min-height: 0; display: flex; } font-size: var(--st-fs-md); } /* MCP tool calls inside an answer: one compact collapsible block per call */ .st-bubble .tool-call { margin: var(--st-s-3) 0; } -.tool-call > summary { min-width: 0; padding: 8px 12px; } -.tool-call__name { font: 500 var(--st-fs-sm)/1.2 var(--st-font-mono); color: var(--st-ink); white-space: nowrap; } +.tool-call > summary { min-width: 0; padding: 8px 12px; overflow: hidden; } +.tool-call__name { font: 500 var(--st-fs-sm)/1.2 var(--st-font-mono); color: var(--st-ink); white-space: nowrap; + min-width: 0; overflow: hidden; text-overflow: ellipsis; } .tool-call__preview { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: var(--st-fs-xs); } .tool-call .st-badge, .tool-call summary .small { flex: none; } .tool-call[data-state="error"] { border-color: color-mix(in srgb, var(--st-danger) 35%, var(--st-line)); } diff --git a/tests/terminal/test_issues_022.py b/tests/terminal/test_issues_022.py index 136f722e..c93f2644 100644 --- a/tests/terminal/test_issues_022.py +++ b/tests/terminal/test_issues_022.py @@ -97,6 +97,26 @@ class Issue3403MacBuildTools(unittest.TestCase): self.assertIn("S.ensure_build_tools()", inspect.getsource(fn), fn.__name__) +class Issue2971WebToolRowFitsPhones(unittest.TestCase): + """A tool row widened the whole page on a phone (752 px page at a 412 px viewport, measured in Chrome). The three rules + that keep it inside the viewport; a long tool name is cut with an ellipsis instead of pushing the page.""" + + def test_the_rules_are_in_the_stylesheet(self): + import re + css = (Path(__file__).resolve().parents[2] / "serve" / "web" / "app.css").read_text(encoding="utf-8") + + def rule(selector): + m = re.search(r"(?m)^" + re.escape(selector) + r"\s*\{([^}]*)\}", css) + self.assertIsNotNone(m, selector) + return m.group(1) + + self.assertIn("min-width: 0", rule(".view")) + self.assertIn("overflow: hidden", rule(".tool-call > summary")) + name = rule(".tool-call__name") + for part in ("min-width: 0", "overflow: hidden", "text-overflow: ellipsis"): + self.assertIn(part, name) + + class Issue3188BenchStartsItsOwnServer(unittest.TestCase): """tools/strata_bench.py named `port` in the start-a-server branch without ever setting it.""" From 73b68dfd8835614f11278db27ce94ff40e963b7e Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Tue, 20 Oct 2026 13:21:10 +0200 Subject: [PATCH 22/47] Fix #3410: a Strata folder in the Trash is not remembered or offered as an install --- setup.py | 6 ++++-- strata_control/discovery.py | 15 ++++++++++++++- tests/terminal/test_issues_022.py | 31 +++++++++++++++++++++++++++++++ 3 files changed, 49 insertions(+), 3 deletions(-) diff --git a/setup.py b/setup.py index fec02400..b39d3c7b 100644 --- a/setup.py +++ b/setup.py @@ -64,6 +64,7 @@ from pathlib import Path from strata_control import acquisition from strata_control import draft_layer +from strata_control.discovery import in_trash from strata_control import user_args ROOT = Path(__file__).resolve().parent @@ -5348,7 +5349,7 @@ def has_data(folder: Path) -> bool: def other_installs(settings: dict) -> list: """Strata folders besides this one that may hold model files: the ones this user ran before, and Strata* folders next to this one (a zip unpacked again lands in e.g. `Strata-main (1)\\Strata-main`).""" - cands = [Path(p) for p in settings.get("installs", [])] + cands = [Path(p) for p in settings.get("installs", []) if not in_trash(p)] for base in dict.fromkeys(() if app_settings_file() else (home().parent, home().parent.parent)): try: for d in base.iterdir(): @@ -5525,7 +5526,8 @@ def data_folder(requested: str | None, move: bool = False, yes: bool = True, set warn(f"some model files are still in {folder} (in use, or already in {dest})") else: ok(f"model files from {folder} moved to {dest} (a new copy of Strata finds them there)") - installs = [str(home())] + [p for p in settings.get("installs", []) if p != str(home()) and Path(p).is_dir()] + installs = [str(home())] + [p for p in settings.get("installs", []) + if p != str(home()) and Path(p).is_dir() and not in_trash(p)] save_settings({**settings, "data_dir": str(dest), "installs": installs[:20]}) return dest, elsewhere diff --git a/strata_control/discovery.py b/strata_control/discovery.py index 6280185c..96443808 100644 --- a/strata_control/discovery.py +++ b/strata_control/discovery.py @@ -96,13 +96,26 @@ def _read_json(path: Path) -> dict: return data if isinstance(data, dict) else {} +def in_trash(path: str | os.PathLike) -> bool: + """#3410: True when ``path`` is inside a Trash / Recycle Bin folder (a Strata folder that was deleted with the file manager + is still a folder there, and was remembered as an install): ~/.local/share/Trash/files/.., /.Trash-1000/.., ~/.Trash/.., + $RECYCLE.BIN\\..""" + parts = [x.lower() for x in Path(path).parts] + for i, x in enumerate(parts): + if x in (".trash", "$recycle.bin", "recycler", "$recycle.bin.old") or x.startswith(".trash-"): + return True + if x == "trash" and i + 1 < len(parts) and parts[i + 1] in ("files", "info", "expunged"): + return True # the XDG Trash: ~/.local/share/Trash/files + return False + + def _installs_in(settings: dict) -> list[Path]: items = settings.get("installs") found: list[Path] = [] for raw in (items if isinstance(items, list) else [])[:20]: if isinstance(raw, str) and raw: p = Path(raw).expanduser() - if p.is_absolute() and p not in found: + if p.is_absolute() and p not in found and not in_trash(p): found.append(p) return found diff --git a/tests/terminal/test_issues_022.py b/tests/terminal/test_issues_022.py index c93f2644..de5a9208 100644 --- a/tests/terminal/test_issues_022.py +++ b/tests/terminal/test_issues_022.py @@ -97,6 +97,37 @@ class Issue3403MacBuildTools(unittest.TestCase): self.assertIn("S.ensure_build_tools()", inspect.getsource(fn), fn.__name__) +class Issue3410TrashIsNotAnInstall(unittest.TestCase): + def test_trash_folders_are_recognised(self): + from strata_control.discovery import in_trash + for p in ("/home/u/.local/share/Trash/files/strata", "/mnt/d/.Trash-1000/files/Strata", "/Users/u/.Trash/Strata", + "C:\\$Recycle.Bin\\S-1-5-21\\$R123\\Strata", "/home/u/.local/share/trash/files/strata/x"): + self.assertTrue(in_trash(p), p) + for p in ("/home/u/bin/strata", "/home/u/Trash-talk/strata", "/home/u/trash/strata", "/opt/Strata", + "C:\\Users\\u\\Strata"): + self.assertFalse(in_trash(p), p) + + def test_remembered_installs_in_the_trash_are_not_listed(self): + from strata_control import discovery + with tempfile.TemporaryDirectory() as tmp: + good = Path(tmp) / "bin" / "strata" + trash = Path(tmp) / ".local" / "share" / "Trash" / "files" / "strata" + got = discovery._installs_in({"installs": [str(trash), str(good)]}) + self.assertEqual(got, [good]) + + def test_setup_does_not_pass_a_trash_folder_on(self): + import setup + with tempfile.TemporaryDirectory() as tmp: + trash = Path(tmp) / ".local" / "share" / "Trash" / "files" / "strata" + trash.mkdir(parents=True) + (trash / "setup.py").write_text("x") + from unittest import mock + nowhere = Path(tmp) / "none" / "none" / "home" # no Strata* folders beside it on this PC + with mock.patch.object(setup, "home", return_value=nowhere): + self.assertEqual(setup.other_installs({"installs": [str(trash)]}), []) + self.assertEqual(setup.other_installs({"installs": [str(trash)] + [str(trash.parent.parent)]}), []) + + class Issue2971WebToolRowFitsPhones(unittest.TestCase): """A tool row widened the whole page on a phone (752 px page at a 412 px viewport, measured in Chrome). The three rules that keep it inside the viewport; a long tool name is cut with an ellipsis instead of pushing the page.""" From c316a7c2155b60b9e0b4dc6c88565bf9ff4b3712 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Tue, 20 Oct 2026 13:46:19 +0200 Subject: [PATCH 23/47] Fix: Windows runtime folder refused as not owner-only --- strata_control/private_files.py | 125 +++++++++++++++++----- strata_control/runtime.py | 59 ++++++++++- tests/terminal/test_issues_022.py | 169 ++++++++++++++++++++++++++++++ tests/terminal/test_runtime.py | 12 ++- 4 files changed, 337 insertions(+), 28 deletions(-) diff --git a/strata_control/private_files.py b/strata_control/private_files.py index e163c602..318fee9a 100644 --- a/strata_control/private_files.py +++ b/strata_control/private_files.py @@ -100,21 +100,9 @@ def _same_sid(sddl_trustee: str, sid: str) -> bool: Administrator, RID 500, is ``LA``), so an alias is turned into its string SID before the compare (#3302).""" if sddl_trustee == sid: return True - if sddl_trustee.upper().startswith("S-1-") or not WINDOWS: + if not WINDOWS: return False - pointer = ctypes.c_void_p() - if not _advapi.ConvertStringSidToSidW(sddl_trustee, ctypes.byref(pointer)): - return False - try: - text = wintypes.LPWSTR() - if not _advapi.ConvertSidToStringSidW(pointer.value, ctypes.byref(text)): - return False - try: - return text.value == sid - finally: - _kernel.LocalFree(ctypes.cast(text, ctypes.c_void_p)) - finally: - _kernel.LocalFree(pointer) + return _string_sid(sddl_trustee) == sid.upper() def restrict_to_current_user(path: str | os.PathLike, *, directory: bool | None = None) -> None: @@ -187,6 +175,8 @@ def is_private(path: str | os.PathLike) -> bool: """ if not WINDOWS: return not (os.lstat(path).st_mode & 0o077) + if not volume_has_acls(path): + return True # FAT / exFAT: there are no permissions to check sddl = dacl_sddl(path) head = sddl.split("(", 1)[0] entries = re.findall(r"\(([^()]*)\)", sddl) @@ -196,9 +186,6 @@ def is_private(path: str | os.PathLike) -> bool: return len(fields) >= 6 and fields[0] == "A" and _same_sid(fields[5], current_user_sid()) -_PRIVILEGED = {"SY", "BA", "OW", "CO", "CG", "S-1-5-18", "S-1-5-32-544", "S-1-3-4"} - - def is_unshared(path: str | os.PathLike) -> bool: """True when nobody but this user, SYSTEM and the administrators can reach ``path``. @@ -209,15 +196,105 @@ def is_unshared(path: str | os.PathLike) -> bool: """ if not WINDOWS: return is_private(path) - sddl = dacl_sddl(path) - me = current_user_sid() - allowed = _PRIVILEGED | {me} + if not volume_has_acls(path): + return True # FAT / exFAT: there are no permissions to check + return not unshared_offenders(dacl_sddl(path)) + + +def volume_has_acls(path: str | os.PathLike) -> bool: + """False for a drive without file permissions (FAT, exFAT); True for NTFS/ReFS, and when it cannot be told (Windows only).""" + if not WINDOWS: + return True + try: + drive = os.path.splitdrive(os.path.abspath(os.fspath(path)))[0] + if not drive: + return True + flags = wintypes.DWORD() + fn = _kernel.GetVolumeInformationW + fn.argtypes = [wintypes.LPCWSTR, wintypes.LPWSTR, wintypes.DWORD, ctypes.c_void_p, ctypes.c_void_p, + ctypes.POINTER(wintypes.DWORD), wintypes.LPWSTR, wintypes.DWORD] + if not fn(drive.rstrip("\\") + "\\", None, 0, None, None, ctypes.byref(flags), None, 0): + return True + return bool(flags.value & 0x00000008) # FILE_PERSISTENT_ACLS + except (OSError, ValueError): + return True + + +_ACCOUNT_NAMES = {"WD": "Everyone", "BU": "Users", "AU": "Authenticated Users", "IU": "Interactive users", + "NU": "Network users", "AN": "Anonymous", "DU": "Domain Users", "S-1-1-0": "Everyone", + "S-1-5-32-545": "Users", "S-1-5-11": "Authenticated Users", "S-1-5-4": "Interactive users"} + + +def _string_sid(trustee: str) -> str: + """An SDDL trustee (a string SID or a two-letter alias such as LA, BA, SY, WD) as an upper-case string SID; the text itself + when Windows does not know it.""" + if trustee.upper().startswith("S-1-"): + return trustee.upper() + pointer = ctypes.c_void_p() + if not _advapi.ConvertStringSidToSidW(trustee, ctypes.byref(pointer)): + return trustee.upper() + try: + text = wintypes.LPWSTR() + if not _advapi.ConvertSidToStringSidW(pointer.value, ctypes.byref(text)): + return trustee.upper() + try: + return text.value.upper() + finally: + _kernel.LocalFree(ctypes.cast(text, ctypes.c_void_p)) + finally: + _kernel.LocalFree(pointer) + + +def _is_privileged_sid(sid: str) -> bool: + """SYSTEM, the Administrators group, the built-in Administrator account (RID 500, SDDL "LA"), OWNER RIGHTS / CREATOR OWNER / GROUP.""" + return sid in ("S-1-5-18", "S-1-5-32-544", "S-1-3-4", "S-1-3-0", "S-1-3-1") or \ + re.fullmatch(r"S-1-5-21-[0-9-]+-500", sid) is not None + + +def unshared_offenders(sddl: str) -> list[str]: + """The trustees of an SDDL DACL that make the object reachable by someone besides this user, SYSTEM and the administrators: + every allow entry that applies to the object itself, whatever form its account is written in (a string SID or an alias such + as LA). An inherit-only entry (flag IO) is for the children of a folder, not for the folder, and is left out.""" + me = current_user_sid().upper() + out: list[str] = [] for entry in re.findall(r"\(([^()]*)\)", sddl): fields = entry.split(";") - if (len(fields) >= 6 and fields[0] in ("A", "OA") and fields[5] not in allowed - and not _same_sid(fields[5], me)): - return False - return True + if len(fields) < 6 or fields[0] not in ("A", "OA") or "IO" in re.findall("..", fields[1].upper()): + continue + sid = _string_sid(fields[5]) + if sid == me or _is_privileged_sid(sid) or fields[5].upper() in ("SY", "BA", "OW", "CO", "CG", "LA"): + continue + if fields[5] not in out: + out.append(fields[5]) + return out + + +def account_name(trustee: str) -> str: + """A plain name for an SDDL trustee (Everyone, Users, DOMAIN\\name), or the SID text when it cannot be looked up.""" + plain = _ACCOUNT_NAMES.get(trustee.upper()) or _ACCOUNT_NAMES.get(_string_sid(trustee)) + if plain or not WINDOWS: + return plain or trustee + pointer = ctypes.c_void_p() + if not _advapi.ConvertStringSidToSidW(trustee, ctypes.byref(pointer)): + return trustee + try: + name, domain = ctypes.create_unicode_buffer(256), ctypes.create_unicode_buffer(256) + n, d, use = wintypes.DWORD(256), wintypes.DWORD(256), wintypes.DWORD() + lookup = _advapi.LookupAccountSidW + lookup.argtypes = [wintypes.LPCWSTR, ctypes.c_void_p, wintypes.LPWSTR, ctypes.POINTER(wintypes.DWORD), + wintypes.LPWSTR, ctypes.POINTER(wintypes.DWORD), ctypes.POINTER(wintypes.DWORD)] + if lookup(None, pointer, name, ctypes.byref(n), domain, ctypes.byref(d), ctypes.byref(use)): + return f"{domain.value}\\{name.value}" if domain.value else name.value + return trustee + finally: + _kernel.LocalFree(pointer) + + +def who_can_reach(path: str | os.PathLike) -> list[str]: + """Plain names of the accounts besides this user, SYSTEM and the administrators that can reach ``path`` (Windows; [] elsewhere).""" + if not WINDOWS: + return [] + return [account_name(t) for t in unshared_offenders(dacl_sddl(path))] # ---------------------------------------------------------------------------------------------- access repair diff --git a/strata_control/runtime.py b/strata_control/runtime.py index c88a9455..da16698f 100644 --- a/strata_control/runtime.py +++ b/strata_control/runtime.py @@ -109,14 +109,67 @@ def runtime_dir() -> Path: raise ProfileError("STRATA_RUNTIME_DIR must be absolute") existed = base.exists() _private_mkdir(base, parents=True, exist_ok=True) - if WINDOWS and not existed: - private_files.restrict_to_current_user(base, directory=True) # no mode bits on NTFS: a protected ACL details = base.lstat() + if WINDOWS and stat.S_ISDIR(details.st_mode): + if not private_files.volume_has_acls(base): # exFAT / FAT: no permissions exist, so there is nothing to check + _warn_no_acls(base) + return base + if not existed: + _make_private(base) # no mode bits on NTFS: a protected ACL + if not _is_private(details, base): + # A folder that was there before (made by an elevated install, an older version, or with the parent's ACL inherited) can + # name other accounts. It is the user's own state folder: take that away instead of stopping the launch, then check again. + _make_private(base) + try: + details = base.lstat() + except OSError: + pass if not stat.S_ISDIR(details.st_mode) or not _is_private(details, base): - raise ProfileError("runtime directory must be owner-only (mode 0700)", 5) + raise ProfileError(_not_private_message(base), 5) return base +def _make_private(base: Path) -> None: + """Windows: a protected ACL naming this user; where that is refused (a folder made by an elevated run), take ownership first.""" + try: + private_files.restrict_to_current_user(base, directory=True) + except OSError: + pass + if _is_private(None, base): # type: ignore[arg-type] - details are not used on Windows + return + try: + private_files.repair_access(base, tree=False) + except OSError: + pass + + +_NO_ACL_WARNED: set[str] = set() + + +def _warn_no_acls(base: Path) -> None: + if str(base) not in _NO_ACL_WARNED: + _NO_ACL_WARNED.add(str(base)) + print(f"[strata] {base} is on a drive that has no file permissions (FAT or exFAT), so other accounts on this PC could " + f"read what Strata keeps there. Use a drive formatted as NTFS if that matters.", file=sys.stderr, flush=True) + + +def _not_private_message(base: Path) -> str: + if WINDOWS: + try: + names = private_files.who_can_reach(base) if base.is_dir() else [] + readable = True + except OSError: + names, readable = [], False + if not readable: + return (f"Strata cannot read the permissions of {base}, the folder where it keeps its running state. Run Strata once as " + f"yourself (not as administrator), or delete that folder: Strata makes a private one again.") + who = ", ".join(names) if names else "other accounts" + return (f"Strata keeps its running state in {base}, and {who} can open that folder. Strata could not change that. " + f"Right-click the folder, choose Properties > Security, and remove those accounts (or delete the folder: Strata " + f"makes a private one again).") + return "runtime directory must be owner-only (mode 0700)" + + def acquire_activity_lease(*, shared: bool) -> int: """Let managed hosts coexist while excluding a local calibration run.""" directory = runtime_dir() diff --git a/tests/terminal/test_issues_022.py b/tests/terminal/test_issues_022.py index de5a9208..3385aca8 100644 --- a/tests/terminal/test_issues_022.py +++ b/tests/terminal/test_issues_022.py @@ -3,6 +3,7 @@ from __future__ import annotations import json +import os import sys import tempfile import unittest @@ -97,6 +98,174 @@ class Issue3403MacBuildTools(unittest.TestCase): self.assertIn("S.ensure_build_tools()", inspect.getsource(fn), fn.__name__) +@unittest.skipUnless(sys.platform == "win32", "ACLs are Windows only") +class WindowsRuntimeFolderRefused(unittest.TestCase): + """The owner's fresh Windows PC: `strata launch` stopped with "runtime directory must be owner-only" on a folder that was already + there with another account in its ACL. Fake SDDL strings for each way an ACL can look.""" + + def setUp(self): + from unittest import mock + from strata_control import private_files as pf + self.pf, self.mock = pf, mock + self.me = "S-1-5-21-1-2-3-1001" + patch = mock.patch.object(pf, "current_user_sid", return_value=self.me) + patch.start() + self.addCleanup(patch.stop) + + def offenders(self, sddl): + return self.pf.unshared_offenders(sddl) + + def test_the_usual_acls_are_fine(self): + for sddl in ("D:PAI(A;OICI;FA;;;S-1-5-21-1-2-3-1001)", + "D:PAI(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;OICI;FA;;;S-1-5-21-1-2-3-1001)", + "D:PAI(A;OICI;FA;;;LA)(A;OICI;FA;;;SY)", # the built-in Administrator's alias + "D:P(A;OICI;FA;;;S-1-5-18)(A;OICI;FA;;;S-1-5-32-544)(A;OICIIO;GA;;;CO)(A;OICI;FA;;;OW)"): + self.assertEqual(self.offenders(sddl), [], sddl) + + def test_another_account_is_named(self): + self.assertEqual(self.offenders("D:PAI(A;OICI;FA;;;S-1-5-21-1-2-3-1001)(A;OICI;FR;;;BU)"), ["BU"]) + self.assertEqual(self.offenders("D:PAI(A;;FA;;;WD)(A;;FA;;;AU)"), ["WD", "AU"]) + self.assertEqual(self.offenders("D:PAI(A;OICI;FA;;;S-1-5-21-1-2-3-1002)"), ["S-1-5-21-1-2-3-1002"]) + + def test_an_inherit_only_entry_is_not_for_the_folder_itself(self): + self.assertEqual(self.offenders("D:PAI(A;OICI;FA;;;S-1-5-21-1-2-3-1001)(A;OICIIO;FR;;;BU)(A;CIIO;GR;;;WD)"), []) + # the same entry without the IO flag does apply + self.assertEqual(self.offenders("D:PAI(A;OICI;FR;;;BU)"), ["BU"]) + + def test_deny_entries_do_not_make_it_reachable(self): + self.assertEqual(self.offenders("D:PAI(D;;FA;;;BU)(A;OICI;FA;;;S-1-5-21-1-2-3-1001)"), []) + + def test_plain_names(self): + self.assertEqual(self.pf.account_name("BU"), "Users") + self.assertEqual(self.pf.account_name("WD"), "Everyone") + self.assertEqual(self.pf.account_name("S-1-5-32-545"), "Users") + + def test_runtime_dir_repairs_a_folder_that_names_other_accounts(self): + from strata_control import runtime + pf = self.pf + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) / "runtime" + base.mkdir() + state = {"fixed": False} + + def sddl(_path): + return "D:PAI(A;OICI;FA;;;S-1-5-21-1-2-3-1001)" if state["fixed"] else \ + "D:PAI(A;OICI;FA;;;S-1-5-21-1-2-3-1001)(A;OICI;0x1200a9;;;BU)" + + def restrict(path, directory=None): + state["fixed"] = True + + env = {"STRATA_RUNTIME_DIR": str(base)} + with self.mock.patch.dict(os.environ, env), self.mock.patch.object(pf, "dacl_sddl", side_effect=sddl), \ + self.mock.patch.object(pf, "restrict_to_current_user", side_effect=restrict) as r, \ + self.mock.patch.object(pf, "private_mkdir"), self.mock.patch.object(runtime, "_private_mkdir"): + self.assertEqual(runtime.runtime_dir(), base) + self.assertEqual(r.call_count, 1) + + def test_runtime_dir_still_refuses_and_says_who_when_the_repair_fails(self): + from strata_control import profiles, runtime + pf = self.pf + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) / "runtime" + base.mkdir() + with self.mock.patch.dict(os.environ, {"STRATA_RUNTIME_DIR": str(base)}), \ + self.mock.patch.object(pf, "dacl_sddl", return_value="D:PAI(A;OICI;FA;;;S-1-5-21-1-2-3-1001)(A;OICI;FR;;;BU)"), \ + self.mock.patch.object(pf, "restrict_to_current_user", side_effect=OSError("denied")), \ + self.mock.patch.object(runtime, "_private_mkdir"): + with self.assertRaises(profiles.ProfileError) as cm: + runtime.runtime_dir() + self.assertIn("Users", str(cm.exception)) + self.assertIn(str(base), str(cm.exception)) + self.assertIn("Properties", str(cm.exception)) + + +@unittest.skipUnless(sys.platform == "win32", "ACLs are Windows only") +class WindowsRuntimeFolderMoreCases(unittest.TestCase): + """The cases beyond the first repair (audit-refusals-022.md item 5): a data drive's inherited Users entries, an ACL that cannot be + read, a folder made by an elevated run, a drive without permissions, and a message in plain words.""" + + ME = "S-1-5-21-1-2-3-1001" + + def run_dir(self, *, sddl, restrict=None, repair=None, acls=True): + from unittest import mock + from strata_control import private_files as pf, runtime + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) / "runtime" + base.mkdir() + calls = {"restrict": 0, "repair": 0} + + def r(path, directory=None): + calls["restrict"] += 1 + if restrict: + return restrict(calls) + def rp(path, tree=True): + calls["repair"] += 1 + return repair(calls) if repair else False + with mock.patch.dict(os.environ, {"STRATA_RUNTIME_DIR": str(base)}), \ + mock.patch.object(pf, "current_user_sid", return_value=self.ME), \ + mock.patch.object(pf, "dacl_sddl", side_effect=sddl), \ + mock.patch.object(pf, "restrict_to_current_user", side_effect=r), \ + mock.patch.object(pf, "repair_access", side_effect=rp), \ + mock.patch.object(pf, "volume_has_acls", return_value=acls), \ + mock.patch.object(runtime, "_private_mkdir"), mock.patch.object(runtime, "_NO_ACL_WARNED", set()), \ + mock.patch("sys.stderr", new_callable=lambda: __import__("io").StringIO()) as err: + try: + return runtime.runtime_dir(), calls, None, err.getvalue() + except Exception as exc: # noqa: BLE001 - the test looks at the ProfileError text + return None, calls, exc, err.getvalue() + + def test_a_data_drive_folder_with_users_and_authenticated_users_is_repaired_once(self): + state = {"fixed": False} + def sddl(_): + return f"D:PAI(A;OICI;FA;;;{self.ME})" if state["fixed"] else \ + f"D:PAI(A;OICI;FA;;;{self.ME})(A;OICI;0x1301bf;;;AU)(A;OICI;0x1200a9;;;BU)" + base, calls, exc, _ = self.run_dir(sddl=sddl, restrict=lambda c: state.update(fixed=True)) + self.assertIsNone(exc) + self.assertEqual(calls["restrict"], 1) + + def test_an_acl_that_cannot_be_read_is_repaired_then_refused_in_plain_words(self): + def sddl(_): + raise OSError("access denied") + base, calls, exc, _ = self.run_dir(sddl=sddl) + self.assertIsNotNone(exc) + self.assertEqual((calls["restrict"], calls["repair"]), (1, 1)) # tried both, once each + self.assertIn("cannot read the permissions", str(exc)) + self.assertNotIn("0700", str(exc)) + + def test_a_folder_made_by_an_elevated_run_gets_ownership_taken_back(self): + state = {"fixed": False} + def sddl(_): + if not state["fixed"]: + raise OSError("access denied") + return f"D:PAI(A;OICI;FA;;;{self.ME})" + def restrict(calls): + raise PermissionError("denied") + base, calls, exc, _ = self.run_dir(sddl=sddl, restrict=restrict, repair=lambda c: state.update(fixed=True) or True) + self.assertIsNone(exc) + self.assertEqual((calls["restrict"], calls["repair"]), (1, 1)) + + def test_a_drive_without_permissions_is_used_with_one_warning(self): + def sddl(_): + raise AssertionError("FAT has no ACL to read") + base, calls, exc, err = self.run_dir(sddl=sddl, acls=False) + self.assertIsNone(exc) + self.assertEqual((calls["restrict"], calls["repair"]), (0, 0)) + self.assertIn("no file permissions", err) + + def test_the_refusal_names_the_accounts_and_never_says_mode_0700(self): + sddl = lambda _: f"D:PAI(A;OICI;FA;;;{self.ME})(A;OICI;FR;;;AU)(A;OICI;FR;;;WD)" # noqa: E731 + base, calls, exc, _ = self.run_dir(sddl=sddl) + text = str(exc) + self.assertIn("Authenticated Users", text) + self.assertIn("Everyone", text) + self.assertNotIn("0700", text) + self.assertEqual(calls["restrict"], 1) + + def test_the_real_system_drive_has_permissions(self): + from strata_control import private_files as pf + self.assertTrue(pf.volume_has_acls(os.environ.get("SystemRoot", "C:\\Windows"))) + + class Issue3410TrashIsNotAnInstall(unittest.TestCase): def test_trash_folders_are_recognised(self): from strata_control.discovery import in_trash diff --git a/tests/terminal/test_runtime.py b/tests/terminal/test_runtime.py index 9351195d..1b7a2a27 100644 --- a/tests/terminal/test_runtime.py +++ b/tests/terminal/test_runtime.py @@ -1167,7 +1167,17 @@ class RuntimeTests(unittest.TestCase): if done.returncode != 0: self.skipTest("icacls could not widen the test directory") with mock.patch.dict(os.environ, {"STRATA_RUNTIME_DIR": str(shared)}): - with self.assertRaisesRegex(profiles.ProfileError, "owner-only"): + # a folder that names Everyone is the user's own state folder: it is locked down once and used (never a stop) + self.assertEqual(runtime.runtime_dir(), shared) + self.assertTrue(private_files.is_unshared(shared)) + again = Path(self.temp.name) / "shared-runtime-2" + again.mkdir() + subprocess.run(["icacls", str(again), "/grant", "*S-1-1-0:(OI)(CI)R"], capture_output=True) + with mock.patch.dict(os.environ, {"STRATA_RUNTIME_DIR": str(again)}), \ + mock.patch.object(private_files, "restrict_to_current_user"), \ + mock.patch.object(private_files, "repair_access", return_value=False): + # when the lock-down does not happen it still refuses, in plain words and naming who can open it + with self.assertRaisesRegex(profiles.ProfileError, "Everyone"): runtime.runtime_dir() def test_exclusive_lease_waits_for_shared_holders_and_shared_holders_coexist(self): From 4dee320dd5984560410a21a7c23e434e98be9686 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Tue, 20 Oct 2026 14:17:29 +0200 Subject: [PATCH 24/47] setup --gguf-dir never deletes the person's own file: a size or SHA-256 mismatch stops with the file's name and why, and the file stays --- setup.py | 14 +++++--- tools/test_setup_golden.py | 2 +- tools/test_setup_ownfiles.py | 68 ++++++++++++++++++++++++++++++++++++ tools/test_setup_qwen36.py | 2 +- 4 files changed, 80 insertions(+), 6 deletions(-) create mode 100644 tools/test_setup_ownfiles.py diff --git a/setup.py b/setup.py index b39d3c7b..5dd45684 100644 --- a/setup.py +++ b/setup.py @@ -2526,7 +2526,7 @@ def gguf_dir_problem(folder: Path, first: Path, fam: dict, model: str) -> tuple return f"{folder} has no {fam['title']} {model} file", hint -def verify_sha256(s: Path, size: int, sha: str) -> None: +def verify_sha256(s: Path, size: int, sha: str, own: bool = False) -> 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.""" m = s.with_name(s.name + ".done") @@ -2534,6 +2534,9 @@ def verify_sha256(s: Path, size: int, sha: str) -> None: return have = s.stat().st_size if s.exists() else -1 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:,}", + "it may be cut short or another version; your file was left as it is. Copy the whole published file into the folder") fail(f"{s.name} is {have:,} bytes, not {size:,}", "delete it and run setup again (the download restarts)") say(f" checking {s.name} (SHA-256, {size / 1e9:.1f} GB) ...") h = hashlib.sha256() @@ -2544,6 +2547,9 @@ def verify_sha256(s: Path, size: int, sha: str) -> None: break h.update(b) if h.hexdigest() != sha: + if own: + fail(f"{s.name} does not match the published file (SHA-256 {h.hexdigest()}, expected {sha})", + "it may be damaged or another version; your file was left as it is. Copy the whole published file into the folder") s.unlink(missing_ok=True) m.unlink(missing_ok=True) fail(f"{s.name} has the wrong SHA-256 ({h.hexdigest()}, expected {sha}): deleted", @@ -7032,7 +7038,7 @@ def install_own_path(a, family, gpu, hip, amd, cuda_tk, multi, port, ram, adopte if a.gguf_dir: fail(f"{gguf} is missing", f"put {gguf.name} in {folder}, or drop --gguf-dir to download it") download(fam["hf"] + gguf.name, gguf) - verify_sha256(gguf, *fam["sha256"][gguf.name]) + verify_sha256(gguf, *fam["sha256"][gguf.name], own=bool(a.gguf_dir)) ok(f"model file: {gguf}") mmproj = folder / fam["mmproj"] if vision != "none": # the image encoder: Unsloth's mmproj, pinned, size + SHA-256 checked @@ -7042,7 +7048,7 @@ def install_own_path(a, family, gpu, hip, amd, cuda_tk, multi, port, ram, adopte if a.gguf_dir: fail(f"{mmproj} is missing", f"put {mmproj.name} in {folder}, or drop --gguf-dir to download it") download(fam["mmproj_hf"] + mmproj.name, mmproj, "vision encoder") - verify_sha256(mmproj, *fam["sha256"][mmproj.name]) + verify_sha256(mmproj, *fam["sha256"][mmproj.name], own=bool(a.gguf_dir)) ok(f"vision encoder: {mmproj}") step(6, "preparing the model for Strata") @@ -8214,7 +8220,7 @@ def main() -> int: check_shards(shards) for s in ([] if ready else shards): # the Unsloth files: pinned sizes and SHA-256 if s.name in fam.get("sha256", {}): - verify_sha256(s, *fam["sha256"][s.name]) + verify_sha256(s, *fam["sha256"][s.name], own=bool(a.gguf_dir)) ok("model files present") mmproj = Path(a.models_dir) / fam.get("mmproj", MMPROJ) if not mmproj.exists(): # an earlier install's copy (the same file for every family) diff --git a/tools/test_setup_golden.py b/tools/test_setup_golden.py index 03a439d1..01c712b8 100644 --- a/tools/test_setup_golden.py +++ b/tools/test_setup_golden.py @@ -113,7 +113,7 @@ def install(ram, found, argv, answers=None, extra=(), avx512=False, configs=()): mock.patch.object(setup, "update_installed_engine", lambda *a, **k: None), mock.patch.object(setup, "download", fake_download), mock.patch.object(setup, "check_shards", lambda shards: None), - mock.patch.object(setup, "verify_sha256", lambda *a: None), + mock.patch.object(setup, "verify_sha256", lambda *a, **k: None), mock.patch.object(setup, "run", lambda *a, **k: None), mock.patch.object(setup, "mtp_corrupt", lambda *a, **k: False), mock.patch.object(setup, "refresh_draft_vocab", lambda *a, **k: None), diff --git a/tools/test_setup_ownfiles.py b/tools/test_setup_ownfiles.py new file mode 100644 index 00000000..363bf822 --- /dev/null +++ b/tools/test_setup_ownfiles.py @@ -0,0 +1,68 @@ +"""setup.py and the person's own model files (--gguf-dir): setup checks them, it never deletes them (0.2.2). + + python -m unittest tools.test_setup_ownfiles +""" +from __future__ import annotations + +import contextlib +import hashlib +import io +import sys +import tempfile +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) +sys.path.insert(0, str(ROOT / "tools")) +import setup # noqa: E402 + + +def run(fn, *args, **kw): + out = io.StringIO() + with contextlib.redirect_stdout(out): + try: + fn(*args, **kw) + code = 0 + except SystemExit as e: + code = e.code + return code, out.getvalue() + + +class OwnFileChecks(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.file = Path(self.tmp.name) / "model-00001-of-00002.gguf" + self.file.write_bytes(b"abcdefgh" * 100) + self.sha = hashlib.sha256(self.file.read_bytes()).hexdigest() + + def test_a_downloaded_file_of_the_wrong_size_asks_to_delete_it(self): + code, text = run(setup.verify_sha256, self.file, 801, self.sha) + self.assertEqual(code, 1) + self.assertIn("delete it and run setup again", text) + + def test_an_own_file_of_the_wrong_size_is_left_and_the_text_says_so(self): + code, text = run(setup.verify_sha256, self.file, 801, self.sha, own=True) + self.assertEqual(code, 1) + self.assertIn("your file was left as it is", text) + self.assertTrue(self.file.exists()) + + def test_an_own_file_with_another_hash_is_not_deleted(self): + code, text = run(setup.verify_sha256, self.file, 800, "0" * 64, own=True) + self.assertEqual(code, 1) + self.assertIn("does not match the published file", text) + self.assertTrue(self.file.exists()) + + def test_a_downloaded_file_with_another_hash_is_deleted_as_before(self): + code, _text = run(setup.verify_sha256, self.file, 800, "0" * 64) + self.assertEqual(code, 1) + self.assertFalse(self.file.exists()) + + 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) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/test_setup_qwen36.py b/tools/test_setup_qwen36.py index 2d47302b..0baef2e9 100644 --- a/tools/test_setup_qwen36.py +++ b/tools/test_setup_qwen36.py @@ -106,7 +106,7 @@ class InstallOwnPath(unittest.TestCase): self.calls.append(("config", path.name)) patches = [mock.patch.object(setup, "download", lambda url, dst, what=None: self.calls.append(("get", url, dst))), - mock.patch.object(setup, "verify_sha256", lambda s, size, sha: self.calls.append(("sha", s.name))), + mock.patch.object(setup, "verify_sha256", lambda s, size, sha, own=False: self.calls.append(("sha", s.name))), mock.patch.object(setup, "free_gb", lambda p: 500.0), mock.patch.object(setup, "pip_install", lambda *a, **k: None), mock.patch.object(setup, "engine_step", engine_step), From bf2926e05a8ecbf903ce4d0dc04fb9da8d212572 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Tue, 20 Oct 2026 14:17:32 +0200 Subject: [PATCH 25/47] Terminal and app checker: the folder holding the model is found above the picked one, links keep their model name, one plain wording for every refusal (file name + why) --- strata_cli/cli.py | 7 +-- strata_cli/launch/runner.py | 47 ++++++++------------ strata_cli/launch/screens.py | 8 ++-- strata_control/models.py | 67 +++++++++++++++++++++++++++- tests/terminal/test_discovery.py | 2 +- tests/terminal/test_launch_tui.py | 4 +- tests/terminal/test_own_files.py | 73 +++++++++++++++++++++++++++++++ 7 files changed, 168 insertions(+), 40 deletions(-) diff --git a/strata_cli/cli.py b/strata_cli/cli.py index 62aa0f7a..c15e00a6 100644 --- a/strata_cli/cli.py +++ b/strata_cli/cli.py @@ -597,12 +597,9 @@ def _import_problem(plan: dict) -> str: issues = [x for x in issues if x != "unrecognized_or_unsupported_model_variant"] words = "; ".join(dict.fromkeys(plain_issue(x) for x in issues)) text = f"These files cannot be used as they are: {words}." - holds = plan.get("folder_holds") or [] + holds = next((m for m in plan.get("messages") or [] if "holds" in m), "") if holds: - known = [f"{h['family']} {h['model']} ({h['file']})" for h in holds if h.get("model")] - other = [h["file"] for h in holds if not h.get("model")] - text += " The folder holds " + str(len(holds)) + " models" + (": " + ", ".join(known + other) if known or other else "") + \ - ". Point at the .gguf file of the one you want." + text += " " + holds return text diff --git a/strata_cli/launch/runner.py b/strata_cli/launch/runner.py index ef1565fd..4a3ebb06 100644 --- a/strata_cli/launch/runner.py +++ b/strata_cli/launch/runner.py @@ -621,7 +621,7 @@ class Runner: def ensure_model(self) -> Path: s, cat = self.s, self.catalog - if s.model_path and not (s.family and s.model): + if s.model_path: self.resolve_own_files() self.resolved_vision() if not (s.family and s.model): @@ -732,20 +732,34 @@ class Runner: return path def resolve_own_files(self) -> None: - """"Use model files I already have": the fingerprint table says which catalog model the files are.""" + """"Use model files I already have": the fingerprint table says which catalog model the files are, and which folder holds them (the + person may have named the folder above it). When the person also named the model (--model), the files are never refused here: setup + takes the files of that model out of the folder by name, as it always did (0.1.45), and says what is wrong when it cannot.""" from strata_control import models s = self.s + given = bool(s.family and s.model) try: - plan = models.plan_import(str(Path(s.model_path).expanduser().resolve())) + plan = models.plan_import(models.absolute(s.model_path)) except Exception as e: # noqa: BLE001 + if given: + return raise LaunchError(f"These model files cannot be used: {e}.", "Pick the folder with every shard of one model, or a .gguf file of it.", 5) from None + if given: + hold = [h for h in plan.get("folder_holds") or [] if (h.get("family"), h.get("model")) == (s.family, s.model)] + if len(hold) == 1 and hold[0].get("folder"): + s.model_path = hold[0]["folder"] + elif not plan.get("issues"): + s.model_path = models.import_target(s.model_path, plan) + return sel = plan.get("candidate_selection") or {} fam, model = sel.get("family"), sel.get("model") if not (fam and model) or plan.get("issues"): issues = "; ".join(plain_issue(str(x)) for x in (plan.get("issues") or [])[:3]) or "they are not a model Strata knows" - raise LaunchError(f"These files cannot be used as they are ({issues}).", + more = " " + next((m for m in plan.get("messages") or [] if "holds" in m), "") + raise LaunchError(f"These files cannot be used as they are ({issues}).{more.rstrip()}", "Choose the matching model in the list, or check that every shard is in the folder.", 5) s.family, s.model = fam, model + s.model_path = models.import_target(s.model_path, plan) self.emit("model", f"These files are {fam} {model}.", None) # ---- 3. config and profile @@ -955,30 +969,7 @@ class Runner: return out -ISSUE_WORDS = { - "multiple_model_groups": "the folder holds more than one model", - "incomplete_or_invalid_shard_set": "some shards are missing", - "unrecognized_or_unsupported_model_variant": "this is not a model size Strata knows", - "unsupported_or_missing_architecture": "this model type is not supported by the Strata engine (add it as a Custom model API with llama-server instead)", - "unsupported_or_incomplete_tokenizer_metadata": "the file has no usable tokenizer", - "missing_or_unexpected_expert_quantization": "its quantization is not one Strata knows", -} - - -def plain_issue(code: str) -> str: - """One problem from the GGUF preview, in words (it may be `file.gguf: GGUF shard is not a nonempty regular file` and the like).""" - if code in ISSUE_WORDS: - return ISSUE_WORDS[code] - low = code.lower() - if "not a nonempty regular file" in low or "unreadable" in low: - return "a file is empty, unreadable or not a regular file" - if "does not begin with a gguf header" in low or "header version" in low: - return "a file is not a GGUF model file" - if "unsupported_architecture" in low: - return "this model type is not supported by the Strata engine (add it as a Custom model API with llama-server instead)" - if "symlink" in low: - return "a file is a shortcut (symbolic link); point at the real file" - return code.replace("_", " ") +from strata_control.models import ISSUE_WORDS, plain_issue # noqa: E402,F401 (one wording for the app, the Terminal and `models import`) def _read_json(path: Path) -> dict | None: diff --git a/strata_cli/launch/screens.py b/strata_cli/launch/screens.py index 5d7bf172..617363ba 100644 --- a/strata_cli/launch/screens.py +++ b/strata_cli/launch/screens.py @@ -495,14 +495,14 @@ class ModelScreen(Base): from strata_cli.launch.runner import plain_issue from strata_control import models try: - plan = models.plan_import(str(Path(path).expanduser().resolve())) + plan = models.plan_import(models.absolute(path)) except Exception as e: # noqa: BLE001 self.say(f"These files cannot be used: {e}. Pick the folder with every shard of one model, or a .gguf file of it.", True) return sel = plan.get("candidate_selection") or {} if sel.get("family") and sel.get("model") and not plan.get("issues"): s = self.ctx.settings - s.model_path, s.family, s.model = str(Path(path).expanduser()), sel["family"], sel["model"] + s.model_path, s.family, s.model = models.import_target(path, plan), sel["family"], sel["model"] self.ctx.picked_in_list = False self.close_field("own") gb = plan.get("total_bytes", 0) / 1e9 @@ -511,7 +511,9 @@ class ModelScreen(Base): self.paint() else: why = "; ".join(plain_issue(str(x)) for x in (plan.get("issues") or [])[:3]) or "they are not a model Strata knows" - self.say(f"These files cannot be used as they are ({why}). Check that every shard is in the folder, or pick a model from the list.", True) + holds = next((m for m in plan.get("messages") or [] if "holds" in m), "") + self.say(f"These files cannot be used as they are ({why}). " + (holds + " " if holds else "") + + "Check that every shard is in the folder, or pick a model from the list.", True) def action_back(self) -> None: if self.input_open(): diff --git a/strata_control/models.py b/strata_control/models.py index f499b1c3..74914ed2 100644 --- a/strata_control/models.py +++ b/strata_control/models.py @@ -294,6 +294,51 @@ def _already_set_up(shards: list[Path], candidate: dict | None) -> dict | None: return {"config": str(cfg) if cfg else None, **{k: (str(v) if v else None) for k, v in beside.items()}} +ISSUE_WORDS = { + "multiple_model_groups": "the folder holds more than one model", + "incomplete_or_invalid_shard_set": "some parts of the model are missing", + "unrecognized_or_unsupported_model_variant": "this is not a model size Strata knows", + "unsupported_or_missing_architecture": "this model type is not supported by the Strata engine (add it as a Custom model API with llama-server instead)", + "unsupported_or_incomplete_tokenizer_metadata": "the file has no usable tokenizer", + "missing_or_unexpected_expert_quantization": "its quantization is not one Strata knows", +} +# the checker's own sentences about one file, in words +_REASON_WORDS = ( + ("not a nonempty regular file", "the file is empty or is not a file"), + ("unreadable", "the file cannot be read (is it open in another program, or on a drive that is gone?)"), + ("could not be read", "the file cannot be read (is it open in another program, or on a drive that is gone?)"), + ("is missing", "the file is not there"), + ("link to a file that is not there", "this is a shortcut to a file that is not there any more"), + ("does not begin with a gguf header", "this is not a GGUF model file"), + ("header version", "this GGUF is from a format Strata does not read"), + ("requires gguf v3", "this GGUF is in an old format (version 2); Strata reads version 3"), + ("metadata is truncated", "the file is cut short (a download or copy that did not finish)"), + ("payload is shorter", "the file is shorter than its own header says (a download or copy that did not finish)"), + ("exceeds the bounded inspection limit", "its header is larger than Strata reads"), + ("too large to inspect", "its header is larger than Strata reads"), + ("unsupported encoding or shape", "it stores weights in a format Strata does not read"), + ("unsupported array type", "its header uses a type Strata does not read"), + ("unsupported value type", "its header uses a type Strata does not read"), + ("byte ranges overlap", "its header is damaged"), + ("unsupported_architecture", "this model type is not supported by the Strata engine (add it as a Custom model API with llama-server instead)"), + ("symlink", "this is a shortcut (symbolic link) that cannot be followed"), +) + + +def plain_issue(code: str) -> str: + """One problem from the GGUF preview, in words, with the file's name when it is about one file + (`file.gguf: GGUF shard is not a nonempty regular file`).""" + code = str(code) + if code in ISSUE_WORDS: + return ISSUE_WORDS[code] + name, sep, reason = code.partition(": ") + if not (sep and name.lower().endswith(".gguf")): + name, reason = "", code + low = reason.lower() + words = next((w for key, w in _REASON_WORDS if key in low), reason.replace("_", " ")) + return f"{name}: {words}" if name else words + + UNSUPPORTED_MODEL_TYPE = ("This model type isn't supported by the Strata engine. " "Add it as a Custom model API (llama-server) instead.") # The picture readers Strata ships a pinned copy of (setup downloads and checks one of these next to the model). @@ -434,6 +479,23 @@ def _holds(groups_by_place: list) -> list[dict]: return rows +def absolute(picked: str) -> str: + """The picked path as an absolute path, links left alone (a snapshot file in the Hugging Face cache keeps its model name).""" + return os.path.abspath(os.path.expanduser(str(picked))) + + +def import_target(picked: str, plan: dict) -> str: + """What to hand on as the person's model files: the file when they picked a file (a folder of several sizes needs the name), else the + folder the model files are really in (they may have picked the folder above it).""" + picked = absolute(picked) + try: + if Path(picked).is_file(): + return picked + except OSError: + pass + return plan.get("model_dir") or picked + + def plan_import(raw_path: str) -> dict: """Inspect a local candidate without copying, parsing tensors or adopting it. @@ -549,7 +611,9 @@ def plan_import(raw_path: str) -> dict: projectors = [_assess_projector(model_dir / n) for n in sorted(ignored_auxiliary)[:8]] messages = list(notes) if folder_holds: - names = [f"{h['family']} {h['model']} ({h['file']})" if h.get("model") else h["file"] for h in folder_holds[:8]] + several = len({h.get("folder") for h in folder_holds}) > 1 + names = [(f"{h['family']} {h['model']}" if h.get("model") else h["file"]) + (f" in {h['folder']}" if several else f" ({h['file']})") + for h in folder_holds[:8]] messages.append(f"The folder holds {len(folder_holds)} models: " + "; ".join(names) + (" and more" if len(folder_holds) > 8 else "") + ". Choose the folder of the one you want, or type the path of its .gguf file.") if any(i.endswith("unsupported_architecture") or i == "unsupported_or_missing_architecture" for i in issues): @@ -570,6 +634,7 @@ def plan_import(raw_path: str) -> dict: return {"source": str(path), "model_dir": str(model_dir), "scope": "local_gguf_candidate", "files": files, "file_count": len(files), "total_bytes": sum(item["bytes"] for item in files), "metadata": metadata, "candidate_selection": candidate, + "plain_issues": list(dict.fromkeys(plain_issue(i) for i in issues)), "observed_expert_types": sorted(observed_experts), "observed_tensor_count": observed_tensor_count, "ignored_auxiliary_files": sorted(ignored_auxiliary), diff --git a/tests/terminal/test_discovery.py b/tests/terminal/test_discovery.py index 2dcdcb11..7ea7efca 100644 --- a/tests/terminal/test_discovery.py +++ b/tests/terminal/test_discovery.py @@ -198,7 +198,7 @@ class GuiLayout(unittest.TestCase): self.assertIn("more than one model", text) self.assertIn("holds 2 models", text) self.assertIn("gyro Gyro-S", text) - self.assertIn("Point at the .gguf file of the one you want", text) + self.assertIn("type the path of its .gguf file", text) self.assertNotIn("multiple_model_groups", text) self.assertNotIn("not a model size", text) diff --git a/tests/terminal/test_launch_tui.py b/tests/terminal/test_launch_tui.py index 50ac2318..003fb305 100644 --- a/tests/terminal/test_launch_tui.py +++ b/tests/terminal/test_launch_tui.py @@ -262,7 +262,7 @@ class ModelStep(Base): with mock.patch("strata_control.models.plan_import", return_value=plan) as pi: await typed(pilot, "/data/models/IQ3_XXS") await press(pilot, "enter") - self.assertEqual(ctx.settings.model_path, str(Path("/data/models/IQ3_XXS"))) + self.assertEqual(ctx.settings.model_path, os.path.abspath("/data/models/IQ3_XXS")) self.assertEqual((ctx.settings.family, ctx.settings.model), ("qwen", "IQ3_XXS")) self.assertIn("These files are qwen IQ3_XXS (2 file(s), 44 GB)", text_of(app)) await press(pilot, "enter") @@ -278,7 +278,7 @@ class ModelStep(Base): await typed(pilot, "/x") await press(pilot, "enter") t = flat(app) - self.assertIn("some shards are missing", t) + self.assertIn("some parts of the model are missing", t) self.assertIn("pick a model from the list", t) self.assertIsNone(ctx.settings.model_path) self.run_app(case) diff --git a/tests/terminal/test_own_files.py b/tests/terminal/test_own_files.py index 4d94bd1a..e4f0de8b 100644 --- a/tests/terminal/test_own_files.py +++ b/tests/terminal/test_own_files.py @@ -234,6 +234,79 @@ class Folders(Base): self.assertEqual(plan["issues"], ["incomplete_or_invalid_shard_set"]) +class Launcher(Base): + """`strata launch --model-path` and the TUI's "use my own files" (strata_cli/launch/runner.py, screens.py).""" + + def runner(self, **kw): + from strata_cli.launch import settings as S + from strata_cli.launch.catalog import Catalog + from strata_cli.launch.runner import Runner + from tests.terminal.launch_support import HW_12 + return Runner(S.LaunchSettings(**kw), catalog=Catalog(hardware=HW_12)) + + def test_a_folder_above_the_model_is_resolved_to_the_model_folder(self): + data = self.base / "Strata-data" + self.gsq(data / "models" / "q2_0", Q2, "Q2_0") + r = self.runner(model_path=str(data)) + r.resolve_own_files() + self.assertEqual((r.s.family, r.s.model), ("qwen", "Q2_0")) + self.assertEqual(Path(r.s.model_path), data / "models" / "q2_0") + argv = r.setup_args() + self.assertEqual(Path(argv[argv.index("--gguf-dir") + 1]), data / "models" / "q2_0") + + def test_a_named_model_in_a_folder_of_several_sizes_is_never_refused_here(self): + folder = self.gsq(self.base / "many", Q2, "Q2_0") + self.gsq(folder, IQ3XXS, "IQ3_XXS") + r = self.runner(model_path=str(folder), family="qwen", model="IQ3_XXS") + r.resolve_own_files() + self.assertEqual(Path(r.s.model_path), folder) # setup picks the IQ3_XXS files by name, as in 0.1.45 + self.assertEqual((r.s.family, r.s.model), ("qwen", "IQ3_XXS")) + + def test_a_named_model_is_found_in_the_folder_that_holds_it(self): + repo = self.base / "repo" + self.gsq(repo / "Q2_0", Q2, "Q2_0") + self.gsq(repo / "IQ3_XXS", IQ3XXS, "IQ3_XXS") + r = self.runner(model_path=str(repo), family="qwen", model="IQ3_XXS") + r.resolve_own_files() + self.assertEqual(Path(r.s.model_path), repo / "IQ3_XXS") + + def test_two_models_and_none_named_says_which_in_plain_words(self): + from strata_cli.launch.runner import LaunchError + repo = self.base / "repo" + self.gsq(repo / "Q2_0", Q2, "Q2_0") + self.gsq(repo / "IQ3_XXS", IQ3XXS, "IQ3_XXS") + r = self.runner(model_path=str(repo)) + with self.assertRaises(LaunchError) as ctx: + r.resolve_own_files() + text = str(ctx.exception) + self.assertIn("more than one model", text) + self.assertIn("holds 2 models", text) + + def test_a_linked_model_file_keeps_its_name(self): + snap = Links.make_links(self) + r = self.runner(model_path=str(snap / Q2[0])) + r.resolve_own_files() + self.assertEqual((r.s.family, r.s.model), ("qwen", "Q2_0")) + self.assertEqual(Path(r.s.model_path).name, Q2[0]) # not the blob's hash name + + +class Words(unittest.TestCase): + def test_a_file_problem_names_the_file_and_says_why(self): + self.assertEqual(models.plain_issue("model-00002-of-00002.gguf: GGUF metadata is truncated"), + "model-00002-of-00002.gguf: the file is cut short (a download or copy that did not finish)") + self.assertIn("shorter than its own header", models.plain_issue("a.gguf: GGUF tensor payload is shorter than its directory requires")) + self.assertIn("old format (version 2)", models.plain_issue("a.gguf: Strata metadata preflight requires GGUF v3")) + self.assertEqual(models.plain_issue("incomplete_or_invalid_shard_set"), "some parts of the model are missing") + + def test_the_plan_carries_the_words(self): + with tempfile.TemporaryDirectory() as tmp: + f = Path(tmp) / Q2[0] + f.write_bytes(gguf_bytes(["Q2_0"])[:60]) + plan = models.plan_import(str(f)) + self.assertTrue(plan["plain_issues"]) + self.assertTrue(any(x.startswith(Q2[0] + ":") or x.startswith(Q2[1] + ":") for x in plan["plain_issues"]), plan["plain_issues"]) + + class Table(unittest.TestCase): def test_every_size_setup_installs_is_in_the_table(self): """Setup can install it from --gguf-dir, so the checker in front of it must know it too (0.2.0 knew 7 of 10).""" From 7db513297df2a28a25c95d7e06dbb6e6ac014561 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Tue, 20 Oct 2026 14:19:55 +0200 Subject: [PATCH 26/47] Launch: a tuning that found the standard settings already fastest counts as tuned (no 20-minute measurement at every start) --- strata_cli/launch/cmd.py | 2 +- strata_cli/launch/runner.py | 3 +++ strata_cli/launch/screens.py | 8 ++++---- strata_cli/launch/settings.py | 6 ++++++ strata_cli/launch/store.py | 2 +- tests/terminal/test_launch.py | 14 ++++++++++++++ 6 files changed, 29 insertions(+), 6 deletions(-) diff --git a/strata_cli/launch/cmd.py b/strata_cli/launch/cmd.py index d3c8c5b1..fc4d54e9 100644 --- a/strata_cli/launch/cmd.py +++ b/strata_cli/launch/cmd.py @@ -500,7 +500,7 @@ def run_launch(a: argparse.Namespace) -> int: sm = store.summary(i) _say(f"{i.name:<28} {sm['model']:<14} {S.context_label(i.context):<6} " f"{(str(i.parallel) + ' request' + ('s' if i.parallel != 1 else '')) if i.parallel else 'fit to card':<14} " - f"{('tuned ' + (i.tuned_at or '')) if i.tuned_preset else 'not tuned':<16} {i.last_used or ''}") + f"{('tuned ' + (i.tuned_at or '')) if i.is_tuned else 'not tuned':<16} {i.last_used or ''}") return 0 if a.delete_preset: store.delete(a.delete_preset) diff --git a/strata_cli/launch/runner.py b/strata_cli/launch/runner.py index 4a3ebb06..9ce63b3a 100644 --- a/strata_cli/launch/runner.py +++ b/strata_cli/launch/runner.py @@ -812,6 +812,9 @@ class Runner: 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) + return mode = "thorough" if s.tune == "thorough" else "quick" status_file = launch_dir() / f"{self.name}.tune.json" try: diff --git a/strata_cli/launch/screens.py b/strata_cli/launch/screens.py index 617363ba..f2ec0db7 100644 --- a/strata_cli/launch/screens.py +++ b/strata_cli/launch/screens.py @@ -241,9 +241,9 @@ class StartScreen(Base): for p in self.presets: sm = store.summary(p) req = (f"{p.parallel} request" + ("s" if p.parallel != 1 else "")) if p.parallel else "fit to card" - tuned = f"tuned {p.tuned_at[5:]}" if p.tuned_preset and p.tuned_at else "not tuned" + tuned = f"tuned {p.tuned_at[5:]}" if p.is_tuned and p.tuned_at else "not tuned" used = f"last used {p.last_used[5:10]}" if p.last_used else "not used yet" - items.append(Item([p.name or "?", str(sm["model"]), S.context_label(p.context), req, Cell(tuned, MUTE if not p.tuned_preset else ""), + items.append(Item([p.name or "?", str(sm["model"]), S.context_label(p.context), req, Cell(tuned, MUTE if not p.is_tuned else ""), Cell(used, MUTE)], key=("preset", p.name))) items.append(Item([Cell("Set up from the beginning", "")], key=("new", None))) items.append(Item([Cell("Use model files I already have", "")], key=("own", None))) @@ -921,11 +921,11 @@ class TuningScreen(Base): def on_mount(self) -> None: s = self.ctx.settings - first = self.ctx.fresh_setup and not s.tuned_preset + first = self.ctx.fresh_setup and not s.is_tuned items = [Item(["Quick", "about 20 minutes", "checks the most likely gains" + ("; suggested the first time" if first else "")], key="quick"), Item(["Thorough", "up to 2 hours", "tries more settings, measures each one several times"], key="thorough"), Item(["Skip", "", "use the default settings (already good on most computers)"], key="skip")] - if not self.ctx.tune_chosen and s.tune == "skip" and not s.tuned_preset and self.ctx.fresh_setup: + if not self.ctx.tune_chosen and s.tune == "skip" and not s.is_tuned and self.ctx.fresh_setup: s.tune = "quick" self.query_one(Menu).set_items(items, {"quick": 0, "thorough": 1, "skip": 2}.get(s.tune, 0)) self.paint() diff --git a/strata_cli/launch/settings.py b/strata_cli/launch/settings.py index df27ce32..8079fb16 100644 --- a/strata_cli/launch/settings.py +++ b/strata_cli/launch/settings.py @@ -100,6 +100,12 @@ class LaunchSettings: last_used: str | None = None created: str | None = None + @property + def is_tuned(self) -> bool: + """Tuning was done for this preset: it saved faster settings (tuned_preset), or it measured that the standard settings are already the + fastest (only tuned_at is set). Either way the next start must not tune again.""" + return bool(self.tuned_preset or self.tuned_at) + def to_dict(self, *, with_key: bool = True) -> dict[str, Any]: d = {"schema": SCHEMA, **asdict(self)} if not with_key: diff --git a/strata_cli/launch/store.py b/strata_cli/launch/store.py index a7439883..4176835f 100644 --- a/strata_cli/launch/store.py +++ b/strata_cli/launch/store.py @@ -139,5 +139,5 @@ def touch_used(name: str) -> None: def summary(s: LaunchSettings) -> dict[str, Any]: """The columns of the start screen.""" return {"name": s.name, "model": s.model or ("own files" if s.model_path else "-"), - "context": s.context, "parallel": s.parallel, "tuned": bool(s.tuned_preset), "tuned_at": s.tuned_at, + "context": s.context, "parallel": s.parallel, "tuned": s.is_tuned, "tuned_at": s.tuned_at, "last_used": s.last_used, "access": s.access} diff --git a/tests/terminal/test_launch.py b/tests/terminal/test_launch.py index 78c718fe..6b722e36 100644 --- a/tests/terminal/test_launch.py +++ b/tests/terminal/test_launch.py @@ -609,6 +609,20 @@ class AdoptRules(unittest.TestCase): r.check_pictures(path) self.assertEqual(seen, []) + def test_tuning_that_found_the_standard_settings_fastest_is_not_run_again(self): + # "already fastest" saves no tuning preset, only tuned_at: the next start (a container restart with TUNE=quick) must not measure for 20 minutes again + with Home(): + seen = [] + s = S.LaunchSettings(family="qwen", model="IQ3_XXS", context=32768, tune="quick", tuned_at="2026-10-20") + self.assertTrue(s.is_tuned) + r = Runner(s, catalog=catalog(HW_12), emit=seen.append) + with mock.patch.object(r, "_spawn", side_effect=AssertionError("tuned again")): + r.tune() + self.assertTrue(any("Already tuned on 2026-10-20" in e.text for e in seen)) + self.assertFalse(S.LaunchSettings(tune="quick").is_tuned) + store.save(s, "Fastest") + self.assertTrue(store.summary(store.load("Fastest"))["tuned"]) + def test_runner_adopts_when_setup_cannot_handle_the_card(self): with Home() as h: d, m = self.files(h.base) From 1972af6da13ef8f6973a73998bb9fca44233b940 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Tue, 20 Oct 2026 14:29:58 +0200 Subject: [PATCH 27/47] Download and prepare steps say what they are: one set of plain sentences (draft layer download, packing experts, checking files, picture reader) for the app and the Terminal; the SHA-256 check shows its own figure instead of a download stuck at 99%; a step's heading is kept in view; the .part file no longer jumps the bar --- setup.py | 7 ++ strata_cli/launch/runner.py | 21 ++-- strata_control/progress_words.py | 116 +++++++++++++++++++ tests/terminal/test_progress_words.py | 148 +++++++++++++++++++++++++ tests/terminal/test_terminal_polish.py | 3 +- tools/strata_mcp.py | 37 ++++++- tools/test_setup_ownfiles.py | 25 +++++ tools/test_strata_mcp.py | 2 +- 8 files changed, 342 insertions(+), 17 deletions(-) create mode 100644 strata_control/progress_words.py create mode 100644 tests/terminal/test_progress_words.py diff --git a/setup.py b/setup.py index 5dd45684..8d9f89c5 100644 --- a/setup.py +++ b/setup.py @@ -2540,12 +2540,19 @@ def verify_sha256(s: Path, size: int, sha: str, own: bool = False) -> None: fail(f"{s.name} is {have:,} bytes, not {size:,}", "delete it and run setup again (the download restarts)") say(f" checking {s.name} (SHA-256, {size / 1e9:.1f} GB) ...") h = hashlib.sha256() + seen, last = 0, 0.0 with open(s, "rb") as f: while True: b = f.read(16 << 20) if not b: break h.update(b) + seen += len(b) + if time.time() - last > 2 and size >= (1 << 30): # a figure for the app and the Terminal: hashing 60 GB takes minutes + last = time.time() + print(f"\r checking {s.name}: {seen / 1e9:6.2f} / {size / 1e9:.2f} GB ({100 * seen // size}%) ", end="", flush=True) + if seen >= (1 << 30): + print() if h.hexdigest() != sha: if own: fail(f"{s.name} does not match the published file (SHA-256 {h.hexdigest()}, expected {sha})", diff --git a/strata_cli/launch/runner.py b/strata_cli/launch/runner.py index 9ce63b3a..bec861f7 100644 --- a/strata_cli/launch/runner.py +++ b/strata_cli/launch/runner.py @@ -302,11 +302,12 @@ def launch_dir() -> Path: # ----------------------------------------------------------------------------------------------- the runner -def download_text(dl: dict, already: bool) -> str: - """The step line for the model download. A model whose files were all on disk before this run says so instead of "Downloading 58.5 of 58.5 GB".""" +def download_text(dl: dict, already: bool, label: str | None = None) -> str: + """The step line for a download or a check. `label` is what is being fetched, in words (strata_control/progress_words.py). A model whose + files were all on disk before this run says so instead of "Downloading 58.5 of 58.5 GB".""" if already: - return f"Model already downloaded ({dl['total_gb']:.1f} GB), checking the files" - return f"Downloading {dl['done_gb']:.1f} of {dl['total_gb']:.1f} GB" + return f"The model files are already on this computer ({dl['total_gb']:.1f} GB); checking them" + return f"{label}: {dl['done_gb']:.1f} of {dl['total_gb']:.1f} GB" if label else f"Downloading {dl['done_gb']:.1f} of {dl['total_gb']:.1f} GB" class Runner: @@ -662,15 +663,17 @@ class Runner: if not line: continue lines.append(line) - lines[:] = lines[-400:] + lines[:] = lines[-1500:] prog = cat.mcp.install_progress(lines) prog = cat.mcp.combined_progress(prog, {"folder": folder, "total_gb": total}) - dl = prog.get("download") - if dl and not s.model_path and dl.get("total_gb", 0) >= 0.05: - if already is None: + dl, phase, label = prog.get("download"), prog.get("phase"), prog.get("label") + if dl and dl.get("total_gb", 0) >= 0.05 and not (s.model_path and phase == "download"): + if phase == "download" and already is None: already = float(dl["percent"]) >= 99.5 - text = download_text(dl, already) + text = download_text(dl, bool(already) and phase == "download", label) self.emit("model", text, float(dl["percent"]), step=prog.get("step")) + elif label: + self.emit("model", label, None, step=prog.get("step")) elif prog.get("step"): self.emit("model", f"Setup step {prog['step']}", None, step=prog.get("step")) code = p.wait() diff --git a/strata_control/progress_words.py b/strata_control/progress_words.py new file mode 100644 index 00000000..bd8344a8 --- /dev/null +++ b/strata_control/progress_words.py @@ -0,0 +1,116 @@ +"""What the person is told while a model downloads and is prepared: ONE place for the words, read by the app (through +tools/strata_mcp.py `install_progress`) and by the Terminal (`strata launch`, strata_cli/launch/runner.py). + +Setup prints its work in seven steps and the tools it runs print their command lines (`> python tools/strata_pack.py build ...`) +and progress lines (`name: 1.20 / 5.04 GB (24%)`). Those titles are for people who read the setup log ("writing the start script", +"preparing the model for Strata"), and the name in a progress line is a file name or an internal label ("MTP draft layer", +"llama.cpp source"). This turns what setup last printed into one plain sentence that says what is really happening now. +The sentences are English; the app translates them like its other texts. + +Nothing here reads a file or starts a process: it works on the last lines of setup's output. +""" + +from __future__ import annotations + +import re +from dataclasses import dataclass + +STEP_RE = re.compile(r"=== Step (\d+): (.+?) ===") +CHECKING_RE = re.compile(r"^\s*checking\b.*\bSHA-256\b", re.I) +PROGRESS_RE = re.compile(r"\s*(\S.*?): +([\d.]+) / ([\d.]+) GB \((\d+)%\)") + + +@dataclass(frozen=True) +class Words: + phase: str # a short key for tests and for the app to pick an icon: check, helpers, engine, download, verify, pictures, + # pack, tokenizer, draft_download, draft, settings, ... + label: str # the sentence + + def as_dict(self) -> dict: + return {"phase": self.phase, "label": self.label} + + +def _after_last_step(lines: list[str]) -> list[str]: + for i in range(len(lines) - 1, -1, -1): + if STEP_RE.search(lines[i]): + return lines[i + 1:] + return lines + + +def _last_matching(lines: list[str], *needles: str) -> str | None: + """The newest line that holds one of the needles (lower case compare).""" + for line in reversed(lines): + low = line.lower() + if any(n in low for n in needles): + return line + return None + + +def describe(step: int | None, lines: list[str], download: dict | None = None) -> Words: + """The sentence for setup's step `step` (1 to 7; None when unknown) given the lines it printed since the step began and the + download figure in them (`{"file": ..., "percent": ...}` or None).""" + recent = _after_last_step(lines) + dl_file = str((download or {}).get("file", "")).lower() + if step is None: + return Words("working", "Getting your model ready") + if step <= 2: + return Words("check", "Checking your computer") + if step == 3: + return Words("helpers", "Getting the helper packages ready") + if step == 4: + if "engine" in dl_file: + return Words("engine", "Downloading the engine for this PC") + if "source" in dl_file or "llama.cpp" in dl_file: + return Words("helpers", "Downloading the small tools used to prepare models") + return Words("engine", "Checking the engine for this PC") + if step == 5: + last = recent[-1] if recent else "" + if dl_file.startswith("checking") or CHECKING_RE.search(last): + return Words("verify", "Checking that the model files are complete (a few minutes for a big model; nothing is downloaded)") + if "vision" in dl_file or "picture" in dl_file or "mmproj" in dl_file: + return Words("pictures", "Downloading the picture reader") + if download and not dl_file.startswith("checking"): + return Words("download", "Downloading the model files") + if _last_matching(recent, "already downloaded", "model files present"): + return Words("verify", "The model files are on this computer; checking them") + return Words("download", "Getting the model files") + if step == 6: + marker = _last_matching(recent, "mtp_rt.py", "mtp_pack.py", "mtp_fetch.py", "mtp draft layer:", "strata_pack.py", "pack_index.py", + "strata_tokenizer.py", "iq_pack.py", "nvfp4_local_pack.py", "converting the q2_0 experts", + "writing the experts into one file", "of mtp tensors", "[ok] model prepared") + low = (marker or "").lower() + if not marker and dl_file.startswith("mtp draft"): + low = "mtp draft layer:" + if "[ok] mtp draft layer" in low: + return Words("draft", "Preparing the draft layer") + if "mtp_fetch.py" in low or "mtp draft layer:" in low or "of mtp tensors" in low: + return Words("draft_download", "Downloading the draft layer (about 5 GB; it makes answers about twice as fast)") + if "mtp_rt.py" in low or "mtp_pack.py" in low or "[ok] model prepared" in low: + return Words("draft", "Preparing the draft layer") + if "strata_pack.py" in low or "converting the q2_0 experts" in low: + return Words("pack", "Packing the model's experts for your processor (one time, a few minutes)") + if "pack_index.py" in low: + return Words("pack", "Indexing the packed experts") + if "strata_tokenizer.py" in low: + return Words("tokenizer", "Preparing the tokenizer") + if "writing the experts into one file" in low or ("iq_pack.py" in low and "--experts-bin" in low): + return Words("pack", "Packing the experts into one file for low-memory mode (one time)") + if "iq_pack.py" in low: + return Words("pack", "Preparing the model data for the engine (one time)") + if "nvfp4_local_pack.py" in low: + return Words("pack", "Converting NVIDIA's FP4 checkpoint on this PC (20 to 40 minutes, one time)") + return Words("pack", "Preparing your model for Strata (one time)") + return Words("settings", "Saving the model's settings") + + +def with_numbers(words: Words, download: dict | None) -> str: + """The sentence with the figure after it when there is one: `Downloading the model files: 12.3 of 66.4 GB`.""" + if not download: + return words.label + try: + done, total = float(download["done_gb"]), float(download["total_gb"]) + except (KeyError, TypeError, ValueError): + return words.label + if total <= 0.05: + return words.label + return f"{words.label}: {done:.1f} of {total:.1f} GB" diff --git a/tests/terminal/test_progress_words.py b/tests/terminal/test_progress_words.py new file mode 100644 index 00000000..ea8efd70 --- /dev/null +++ b/tests/terminal/test_progress_words.py @@ -0,0 +1,148 @@ +"""0.2.2: the words for a model download and its preparation are plain and true (strata_control/progress_words.py), and the app's +and the Terminal's progress read the same lines the same way (tools/strata_mcp.py install_progress / combined_progress). + +The excerpts are from real setup logs (Gyro-S on the RTX 5070 PC, 2026-10-19) and from the steps a Q2_0 install adds.""" + +from __future__ import annotations + +import sys +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(ROOT)) +sys.path.insert(0, str(ROOT / "tools")) + +import strata_mcp # noqa: E402 +from strata_control import progress_words as W # noqa: E402 + +HEAD = ["Strata - Qwen3.8-Flash-Next on a normal PC", "=== Step 1: checking your PC ===", " [ok] GPU: NVIDIA GeForce RTX 5070", + "=== Step 2: your choices ===", " [ok] size: Gyro-S", "=== Step 3: Python packages ===", " [ok] numpy ...", + "=== Step 4: the Strata engine ==="] +STEP5 = ["=== Step 5: downloading Qwen3.8-Flash-Next (Gyro) Gyro-S ===", + " The model files go in C:\\Users\\x\\Documents\\Strata\\models\\gyro-Gyro-S"] +MODEL_PROGRESS = " Qwen3.8-Flash-Next-Gyro-S-TQ1_0.gguf: 30.53 / 58.49 GB (52%) " +CHECK = " checking Qwen3.8-Flash-Next-Gyro-S-TQ1_0.gguf (SHA-256, 58.5 GB) ..." +STEP6 = ["=== Step 6: preparing the model for Strata ==="] + + +def prog(lines): + p = strata_mcp.install_progress(lines) + return p, p.get("label"), p.get("phase") + + +class StepWords(unittest.TestCase): + def test_checking_the_pc(self): + self.assertEqual(prog(HEAD[:3])[1:], ("Checking your computer", "check")) + + def test_the_engine_and_the_helper_download_have_their_own_words(self): + self.assertEqual(prog(HEAD + [" llama.cpp source: 0.01 / 0.04 GB (21%) "])[2], "helpers") + self.assertIn("small tools", prog(HEAD + [" llama.cpp source: 0.01 / 0.04 GB (21%) "])[1]) + self.assertEqual(prog(HEAD + [" Strata engine: 0.20 / 0.90 GB (22%) "])[1], "Downloading the engine for this PC") + self.assertEqual(prog(HEAD)[2], "engine") + + def test_the_model_download(self): + _p, label, phase = prog(HEAD + STEP5 + [MODEL_PROGRESS]) + self.assertEqual((label, phase), ("Downloading the model files", "download")) + + def test_a_figure_from_an_earlier_step_does_not_leak_into_the_next(self): + """Step 4's 'llama.cpp source' line must not make step 5 'Downloading ...' before any model line is printed.""" + p, label, phase = prog(HEAD + [" llama.cpp source: 0.04 / 0.04 GB (100%) "] + STEP5) + self.assertNotIn("download", p) + self.assertEqual(phase, "download") + self.assertEqual(label, "Getting the model files") + + def test_the_hash_check_is_checking_not_downloading(self): + lines = HEAD + STEP5 + [MODEL_PROGRESS, " [ok] downloaded", CHECK] + p, label, phase = prog(lines) + self.assertEqual(phase, "verify") + self.assertIn("Checking that the model files are complete", label) + self.assertNotIn("Downloading", label) + # with its own figure + p, label, phase = prog(lines + [" checking Qwen3.8-Flash-Next-Gyro-S-TQ1_0.gguf: 12.00 / 58.49 GB (20%) "]) + self.assertEqual(phase, "verify") + self.assertEqual(p["download"]["percent"], 20) + + def test_the_picture_reader(self): + lines = HEAD + STEP5 + [" [ok] model files present", " vision encoder: 0.30 / 0.91 GB (33%) "] + self.assertEqual(prog(lines)[1:], ("Downloading the picture reader", "pictures")) + + def test_files_already_there(self): + lines = HEAD + STEP5 + [" [ok] Qwen3.8-Flash-Next-Q2_0-00001-of-00002.gguf already downloaded"] + self.assertEqual(prog(lines)[2], "verify") + + def test_step_six_packing_the_experts(self): + lines = HEAD + STEP5 + STEP6 + [" Converting the Q2_0 experts for the AVX-512 kernel (one time, ~40 GB written, 2-5 min) ...", + " > python tools/strata_pack.py build --gguf x --out y --skip-hash --force"] + self.assertEqual(prog(lines)[1:], ("Packing the model's experts for your processor (one time, a few minutes)", "pack")) + self.assertEqual(prog(lines + [" > python tools/pack_index.py --pack y"])[1], "Indexing the packed experts") + self.assertEqual(prog(lines + [" > python tools/strata_tokenizer.py --gguf x --out y"])[1], "Preparing the tokenizer") + + def test_step_six_the_draft_layer_download_then_its_preparation(self): + fetch = [" [ok] model prepared: y", " The MTP draft layer (speculative decoding, ~2x faster output) comes from the original Qwen checkpoint:", + " only its ~5 GB of MTP tensors are downloaded.", " > python tools/mtp_fetch.py fetch --out z", + " MTP draft layer: 1.65 / 5.21 GB (31%)"] + p, label, phase = prog(HEAD + STEP5 + STEP6 + fetch) + self.assertEqual(phase, "draft_download") + self.assertIn("Downloading the draft layer", label) + # the download is over: the numbers it printed are stale, the next tool is running + p, label, phase = prog(HEAD + STEP5 + STEP6 + fetch + [" MTP draft layer: 5.21 / 5.21 GB (100%)", " > python tools/mtp_pack.py --src z"]) + self.assertEqual((label, phase), ("Preparing the draft layer", "draft")) + p, label, phase = prog(HEAD + STEP5 + STEP6 + fetch + [" > python tools/mtp_rt.py --gguf g --out rt"]) + self.assertEqual(phase, "draft") + + def test_step_six_with_everything_already_there(self): + lines = HEAD + STEP5 + STEP6 + [" [ok] model prepared: y", " [ok] MTP draft layer: z"] + self.assertEqual(prog(lines)[2], "draft") + + def test_low_memory_mode_packing(self): + lines = HEAD + STEP5 + STEP6 + [" Writing the experts into one file for the low-memory mode (one time, 80 GB) ...", + " > python tools/iq_pack.py --gguf x --out y --experts-bin"] + self.assertEqual(prog(lines)[1], "Packing the experts into one file for low-memory mode (one time)") + + def test_the_last_step(self): + lines = HEAD + STEP5 + STEP6 + ["=== Step 7: writing the start script ===", " [ok] KV streaming on"] + self.assertEqual(prog(lines)[1:], ("Saving the model's settings", "settings")) + + def test_the_heading_is_found_even_after_hundreds_of_tool_lines(self): + lines = HEAD + STEP5 + STEP6 + [" > python tools/iq_pack.py --gguf x --out y"] + [f" layer {i}/40" for i in range(900)] + self.assertEqual(prog(lines)[2], "pack") + + def test_no_step_yet(self): + self.assertEqual(prog(["Strata - Qwen3.8-Flash-Next"])[1:], ("Getting your model ready", "working")) + + def test_with_numbers(self): + w = W.describe(5, STEP5, {"file": "x.gguf", "done_gb": 12.34, "total_gb": 58.49, "percent": 21}) + self.assertEqual(W.with_numbers(w, {"done_gb": 12.34, "total_gb": 58.49}), "Downloading the model files: 12.3 of 58.5 GB") + self.assertEqual(W.with_numbers(w, None), "Downloading the model files") + + +class CombinedFigure(unittest.TestCase): + def test_a_part_file_the_pieces_filled_ahead_is_not_a_finished_download(self): + """The parallel download writes the last pieces early, so the .part is full length while the pieces done are 50%: the log's + figure is the truth (the bar used to jump to 99%).""" + import tempfile + with tempfile.TemporaryDirectory() as tmp: + folder = Path(tmp) + part = folder / "m-00001-of-00002.gguf.part" + part.write_bytes(b"\0" * 1000) + files = [{"path": str(folder / "m-00001-of-00002.gguf"), "bytes": 1_000_000_000, "role": "model"}] + prog_ = {"step": "5/7: downloading X", "download": {"file": "m-00001-of-00002.gguf", "done_gb": 0.5, "total_gb": 1.0, "percent": 50}} + # the .part says 1000 bytes here; make it say 1 GB without writing it + import os + with open(part, "r+b") as f: + f.truncate(1_000_000_000) + out = strata_mcp.files_progress(prog_, {"total_gb": 1.0}, files) + self.assertAlmostEqual(out["download"]["done_gb"], 0.5, places=2) + self.assertEqual(out["download"]["percent"], 50) + + def test_the_hash_check_has_its_own_figure(self): + lines = HEAD + STEP5 + [CHECK, " checking Qwen3.8-Flash-Next-Gyro-S-TQ1_0.gguf: 12.00 / 58.49 GB (20%) "] + p = strata_mcp.install_progress(lines) + out = strata_mcp.combined_progress(p, {"folder": None, "total_gb": 58.5}) + self.assertEqual(out["download"]["file"], "checking files") + self.assertEqual(out["download"]["percent"], 20) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/terminal/test_terminal_polish.py b/tests/terminal/test_terminal_polish.py index 6ff558a9..fe99d953 100644 --- a/tests/terminal/test_terminal_polish.py +++ b/tests/terminal/test_terminal_polish.py @@ -14,11 +14,12 @@ from strata_cli.launch.runner import download_text class AlreadyDownloaded(unittest.TestCase): def test_a_model_on_disk_is_not_called_a_download(self): dl = {"done_gb": 58.5, "total_gb": 58.5, "percent": 100.0} - self.assertEqual(download_text(dl, True), "Model already downloaded (58.5 GB), checking the files") + self.assertEqual(download_text(dl, True), "The model files are already on this computer (58.5 GB); checking them") def test_a_real_download_keeps_its_numbers(self): dl = {"done_gb": 12.0, "total_gb": 58.5, "percent": 20.5} self.assertEqual(download_text(dl, False), "Downloading 12.0 of 58.5 GB") + self.assertEqual(download_text(dl, False, "Downloading the draft layer"), "Downloading the draft layer: 12.0 of 58.5 GB") class MonitorFindsLaunch(unittest.TestCase): diff --git a/tools/strata_mcp.py b/tools/strata_mcp.py index 3ccfe1e2..c863e3b4 100644 --- a/tools/strata_mcp.py +++ b/tools/strata_mcp.py @@ -1319,7 +1319,7 @@ class Strata: res = self.state("install-result") running = proc_alive(j.get("pid"), j.get("ident")) log_path = Path(j.get("log", "")) - tail = read_tail(log_path, 400) if log_path.name else [] + tail = read_tail(log_path, 1500) if log_path.name else [] # a step's heading must stay inside it: the pack tools print hundreds of lines prog = install_progress(tail) prog = combined_progress(prog, j) out = {"running": running, "started": j.get("started"), "model": j.get("model"), "family": j.get("family"), @@ -1406,8 +1406,12 @@ def files_progress(prog: dict, job: dict, files: list) -> dict: except OSError: state, have = "waiting", 0 total = f.get("bytes") or (have if state == "done" else 0) - if state == "downloading" and not total and cur_gb and p.name in str(log.get("file", "")): # the log line names this file - total = int(cur_gb * 1e9) + if state == "downloading" and cur_gb and p.name in str(log.get("file", "")): # the log line names this file + # The .part file is as long as the furthest byte written, which the parallel pieces push to the full size well before the + # download is done: the pieces setup counts are the truth. + have = min(have, int(float(log.get("done_gb") or 0) * 1e9)) if have else have + if not total: + total = int(cur_gb * 1e9) rows.append({"role": f.get("role", "model"), "state": state, "have": have, "total": max(total, have)}) plan_total = float(job.get("total_gb") or 0) * 1e9 parts = [] @@ -1443,12 +1447,12 @@ def draft_progress(prog: dict, job: dict, dl: dict) -> dict: if job.get("files"): base = files_progress({}, job, job["files"]) parts = [dict(p, state="done", done_gb=p["total_gb"]) for p in base.get("parts", []) if p.get("state") == "done"] - parts.append({"kind": "draft", "name": "Speed-up layer", "state": "done" if int(dl.get("percent") or 0) >= 100 else "downloading", + parts.append({"kind": "draft", "name": "Draft layer", "state": "done" if int(dl.get("percent") or 0) >= 100 else "downloading", "done_gb": round(done_gb, 3), "total_gb": round(total_gb, 3)}) total = sum(p["total_gb"] for p in parts) done = min(sum(p["done_gb"] for p in parts), total) prog["parts"] = parts - prog["download"] = {"file": "Speed-up layer", "done_gb": round(done, 3), "total_gb": round(total, 3), + prog["download"] = {"file": "Draft layer", "done_gb": round(done, 3), "total_gb": round(total, 3), "remaining_gb": round(max(0.0, total - done), 3), "percent": min(99, int(100 * done / total)) if total else 0} return prog @@ -1463,6 +1467,13 @@ def combined_progress(prog: dict, job: dict) -> dict: dl = prog.get("download") or {} if step.startswith("6/") and str(dl.get("file", "")).startswith("MTP draft layer"): return draft_progress(prog, job, dl) + if step.startswith("5/") and str(dl.get("file", "")).startswith("checking "): + # setup is hashing files that are all on disk: the figure is the check's own (not a download at "99%") + if job.get("files"): + prog = files_progress(prog, job, job["files"]) + prog["download"] = {"file": "checking files", "done_gb": dl["done_gb"], "total_gb": dl["total_gb"], + "remaining_gb": round(max(0.0, dl["total_gb"] - dl["done_gb"]), 3), "percent": int(dl["percent"])} + return prog if job.get("files") and step.startswith("5/"): # the install knows its files: count each of them return files_progress(prog, job, job["files"]) if not folder or not total or not step.startswith("5/"): @@ -1494,7 +1505,7 @@ def install_progress(lines: list[str]) -> dict: for i, line in enumerate(lines): m = re.search(r"=== Step (\d+): (.+?) ===", line) if m: - step, title, err = int(m.group(1)), m.group(2), None + step, title, err, dl = int(m.group(1)), m.group(2), None, None # a download figure belongs to its own step m = re.match(r"\s*(\S.*?): +([\d.]+) / ([\d.]+) GB \((\d+)%\)", line) if m: dl = {"file": m.group(1), "done_gb": float(m.group(2)), "total_gb": float(m.group(3)), @@ -1508,6 +1519,9 @@ def install_progress(lines: list[str]) -> dict: out["download"] = dl if err: out["error"] = err + words = progress_words_for(step, lines, dl) + if words: + out["label"], out["phase"] = words return out @@ -1524,6 +1538,17 @@ def physical_cores() -> int | None: return os.cpu_count() +def progress_words_for(step, lines, download): + """(the plain sentence, its phase) for what setup is doing now (strata_control/progress_words.py, the words the Terminal uses too); + None when this Strata folder does not carry the module.""" + try: + from strata_control import progress_words + except ImportError: + return None + w = progress_words.describe(step, lines, download) + return w.label, w.phase + + def own_ram_gb() -> float: if WIN: class MS(ctypes.Structure): diff --git a/tools/test_setup_ownfiles.py b/tools/test_setup_ownfiles.py index 363bf822..9d799d50 100644 --- a/tools/test_setup_ownfiles.py +++ b/tools/test_setup_ownfiles.py @@ -64,5 +64,30 @@ class OwnFileChecks(unittest.TestCase): self.assertEqual(code, 0) +class CheckingShowsItsProgress(unittest.TestCase): + def test_a_big_file_is_hashed_with_a_progress_line_of_its_own(self): + """Hashing a 60 GB shard takes minutes: the app and the Terminal show it as 'checking', with a figure (not a download stuck at 99%).""" + with tempfile.TemporaryDirectory() as tmp: + f = Path(tmp) / "big-00001-of-00002.gguf" + size = (1 << 30) + 4096 + with open(f, "wb") as g: + g.truncate(size) + sha = hashlib.sha256() + with open(f, "rb") as g: + for block in iter(lambda: g.read(16 << 20), b""): + sha.update(block) + import time + original = time.time + ticks = iter(range(0, 10_000, 3)) + setup.time.time = lambda: float(next(ticks)) # every read looks 3 s later: the progress line prints + try: + code, text = run(setup.verify_sha256, f, size, sha.hexdigest()) + finally: + setup.time.time = original + self.assertEqual(code, 0) + self.assertIn("checking big-00001-of-00002.gguf (SHA-256", text) + self.assertRegex(text, r"checking big-00001-of-00002\.gguf: +\d+\.\d\d / 1\.07 GB \(\d+%\)") + + if __name__ == "__main__": unittest.main() diff --git a/tools/test_strata_mcp.py b/tools/test_strata_mcp.py index 8f0c1540..8bc0acd7 100644 --- a/tools/test_strata_mcp.py +++ b/tools/test_strata_mcp.py @@ -944,7 +944,7 @@ class DraftLayerAndCancel(unittest.TestCase): shard.write_bytes(b"x" * 20_000_000) job = {"files": [{"path": str(shard), "bytes": None, "role": "model"}], "total_gb": 60} prog = M.combined_progress(M.install_progress(lines), job) - self.assertEqual(prog["download"]["file"], "Speed-up layer") + self.assertEqual(prog["download"]["file"], "Draft layer") self.assertEqual([p["kind"] for p in prog["parts"]], ["model", "draft"]) self.assertEqual(prog["parts"][0]["state"], "done") self.assertAlmostEqual(prog["parts"][1]["done_gb"], 2.0) From 32b9f75376769e18e628bb1a5550ea954f31507c Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Tue, 20 Oct 2026 14:34:20 +0200 Subject: [PATCH 28/47] Tests: loopback.py is the one allowed opener for this computer's own servers --- tests/terminal/test_no_acquisition.py | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/terminal/test_no_acquisition.py b/tests/terminal/test_no_acquisition.py index b4590055..09b7d178 100644 --- a/tests/terminal/test_no_acquisition.py +++ b/tests/terminal/test_no_acquisition.py @@ -46,6 +46,7 @@ NETWORK_ALLOWED = { ("serve/mcp.py", "urlopen"): "the MCP servers the user configured, at request time", ("strata_control/tune_api.py", "urlopen"): "the loopback engine/server of a tuning job the user started", ("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", } #: Modules that import the installer on purpose, with the explicit command that reaches them. From e728a132d74b274344fc9c9b88ad5fabee7311bf Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Tue, 20 Oct 2026 14:34:20 +0200 Subject: [PATCH 29/47] POSIX owner-only checks: repair our own folders whose mode drifted, note drives without modes, and name the chown command for folders another account owns --- strata_cli/bench.py | 6 +- strata_cli/connections.py | 21 ++++-- strata_control/benchmarking.py | 21 +++--- strata_control/calibration.py | 15 ++--- strata_control/calibration_jobs.py | 11 ++-- strata_control/journal.py | 9 +-- strata_control/posix_owner.py | 100 +++++++++++++++++++++++++++++ strata_control/recipes.py | 23 +++---- strata_control/runtime.py | 4 +- tests/terminal/test_connections.py | 11 ++-- tests/terminal/test_posix_owner.py | 88 +++++++++++++++++++++++++ 11 files changed, 255 insertions(+), 54 deletions(-) create mode 100644 strata_control/posix_owner.py create mode 100644 tests/terminal/test_posix_owner.py diff --git a/strata_cli/bench.py b/strata_cli/bench.py index 80d673c1..a324f94c 100644 --- a/strata_cli/bench.py +++ b/strata_cli/bench.py @@ -34,6 +34,7 @@ from pathlib import Path from strata_cli.client import ClientError, Endpoint, _NoRedirect from strata_control.profiles import ProfileError from strata_control import atomic as _atomic_mod +from strata_control import posix_owner SCHEMA = 1 @@ -698,9 +699,8 @@ def progress(path: Path) -> dict: try: details = target.lstat() if not stat.S_ISREG(details.st_mode) or details.st_size > 4096 or \ - (os.name == "posix" and (details.st_uid != os.getuid() or - stat.S_IMODE(details.st_mode) & 0o077)): - raise ProfileError("benchmark progress must be an owner-only regular file under 4 KiB", 5) + (os.name == "posix" and (posix_owner.owner_only_wrong(target, details))): + raise ProfileError(posix_owner.owner_only_text("benchmark progress must be an owner-only regular file under 4 KiB", target), 5) record = json.loads(target.read_text(encoding="utf-8")) except (OSError, UnicodeError, ValueError) as exc: if isinstance(exc, ProfileError): diff --git a/strata_cli/connections.py b/strata_cli/connections.py index 586b73ce..f5b8088b 100644 --- a/strata_cli/connections.py +++ b/strata_cli/connections.py @@ -13,6 +13,14 @@ except ImportError: # a thin bundle (monitor def _private_mkdir(path, *, parents=False, exist_ok=True): path.mkdir(mode=0o700, parents=parents, exist_ok=exist_ok) return path +try: + from strata_control import posix_owner +except ImportError: # the same thin bundle: the old plain check + import stat as _stat + + class posix_owner: # noqa: N801 + owner_only_wrong = staticmethod(lambda path, details: os.name == "posix" and (details.st_uid != os.getuid() or _stat.S_IMODE(details.st_mode) & 0o077)) + owner_only_text = staticmethod(lambda text, path: text) try: from strata_control import atomic as _atomic_mod except ImportError: # the same thin bundle: a plain replace @@ -77,8 +85,8 @@ def connection_dir(*, create: bool = False) -> Path: if directory.exists() or directory.is_symlink(): details = directory.lstat() if not stat.S_ISDIR(details.st_mode) or (os.name == "posix" and - (details.st_uid != os.getuid() or stat.S_IMODE(details.st_mode) & 0o077)): - raise ConnectionError("connection directory must be owner-only", 5) + (posix_owner.owner_only_wrong(directory, details))): + raise ConnectionError(posix_owner.owner_only_text("connection directory must be owner-only", directory), 5) return directory @@ -122,9 +130,8 @@ def load(name: str) -> tuple[dict, str]: try: details = path.lstat() if not stat.S_ISREG(details.st_mode) or details.st_size > MAX_BYTES or \ - (os.name == "posix" and (details.st_uid != os.getuid() or - stat.S_IMODE(details.st_mode) & 0o077)): - raise ConnectionError("connection file must be a private regular file under 4 KiB", 5) + (os.name == "posix" and (posix_owner.owner_only_wrong(path, details))): + raise ConnectionError(posix_owner.owner_only_text("connection file must be a private regular file under 4 KiB", path), 5) data = path.read_bytes() value = json.loads(data.decode("utf-8")) except FileNotFoundError: @@ -187,8 +194,8 @@ def _lock(name: str): with os.fdopen(descriptor, "r+b") as stream: details = os.fstat(stream.fileno()) if not stat.S_ISREG(details.st_mode) or (os.name == "posix" and - (details.st_uid != os.getuid() or stat.S_IMODE(details.st_mode) & 0o077)): - raise ConnectionError("connection lock must be owner-only", 5) + (posix_owner.owner_only_wrong(path, details))): + raise ConnectionError(posix_owner.owner_only_text("connection lock must be owner-only", path), 5) if os.name == "nt": import msvcrt stream.seek(0) diff --git a/strata_control/benchmarking.py b/strata_control/benchmarking.py index a6617354..9d89149f 100644 --- a/strata_control/benchmarking.py +++ b/strata_control/benchmarking.py @@ -17,6 +17,7 @@ from strata_cli.cli import _launch_plan, _source from strata_cli.client import ClientError, Endpoint from strata_control import journal, profiles, runtime from strata_control.profiles import ProfileError +from strata_control import posix_owner #: Windows byte-range locks are mandatory: a locked byte cannot be read through any other handle. The lock @@ -33,8 +34,8 @@ def _lease_file(profile: str, *, create: bool) -> Path | None: return None details = directory.lstat() if not stat.S_ISDIR(details.st_mode) or (os.name == "posix" and - (details.st_uid != os.getuid() or stat.S_IMODE(details.st_mode) & 0o077)): - raise ProfileError("benchmark lease directory must be owner-only", 5) + (posix_owner.owner_only_wrong(directory, details))): + raise ProfileError(posix_owner.owner_only_text("benchmark lease directory must be owner-only", directory), 5) return directory / f".bench-{profile}.lock" @@ -45,9 +46,9 @@ def _lease_descriptor(path: Path, *, create: bool) -> int: descriptor = os.open(path, flags, 0o600) details = os.fstat(descriptor) if not stat.S_ISREG(details.st_mode) or details.st_nlink != 1 or details.st_size > 65 or (os.name == "posix" and - (details.st_uid != os.getuid() or stat.S_IMODE(details.st_mode) & 0o077)): + (posix_owner.owner_only_wrong(path, details))): os.close(descriptor) - raise ProfileError("benchmark lease file must be owner-only", 5) + raise ProfileError(posix_owner.owner_only_text("benchmark lease file must be owner-only", path), 5) return descriptor @@ -139,8 +140,8 @@ def request_cancel(profile: str, path: Path) -> dict: directory = path.parent if path.name in ("results.json", "progress.json") else path details = directory.lstat() if not stat.S_ISDIR(details.st_mode) or (os.name == "posix" and - (details.st_uid != os.getuid() or stat.S_IMODE(details.st_mode) & 0o077)): - raise ProfileError("benchmark output directory must be owner-only", 5) + (posix_owner.owner_only_wrong(directory, details))): + raise ProfileError(posix_owner.owner_only_text("benchmark output directory must be owner-only", directory), 5) if benchmark_activity(profile, directory) != "active": raise ProfileError("the exact benchmark run is not active", 6) if bench.progress(directory)["state"] != "running": @@ -152,7 +153,7 @@ def request_cancel(profile: str, path: Path) -> dict: except FileExistsError: details = marker.lstat() if not stat.S_ISREG(details.st_mode) or details.st_nlink != 1 or details.st_size != 1 or (os.name == "posix" and - (details.st_uid != os.getuid() or stat.S_IMODE(details.st_mode) & 0o077)): + (posix_owner.owner_only_wrong(marker, details))): raise ProfileError("benchmark cancellation marker is invalid", 5) else: try: @@ -175,7 +176,7 @@ def cancel_requested(directory: Path) -> bool: except FileNotFoundError: return False if not stat.S_ISREG(details.st_mode) or details.st_nlink != 1 or details.st_size != 1 or (os.name == "posix" and - (details.st_uid != os.getuid() or stat.S_IMODE(details.st_mode) & 0o077)): + (posix_owner.owner_only_wrong(marker, details))): raise ProfileError("benchmark cancellation marker is invalid", 5) return True @@ -321,8 +322,8 @@ def job_status(profile: str, job_id: str) -> dict: if directory.exists() or directory.is_symlink(): details = directory.lstat() if not stat.S_ISDIR(details.st_mode) or (os.name == "posix" and - (details.st_uid != os.getuid() or stat.S_IMODE(details.st_mode) & 0o077)): - raise ProfileError("benchmark output directory must be owner-only", 5) + (posix_owner.owner_only_wrong(directory, details))): + raise ProfileError(posix_owner.owner_only_text("benchmark output directory must be owner-only", directory), 5) activity = benchmark_activity(profile, directory) try: phase = bench.progress(directory) diff --git a/strata_control/calibration.py b/strata_control/calibration.py index 8128639c..a0d8e027 100644 --- a/strata_control/calibration.py +++ b/strata_control/calibration.py @@ -27,6 +27,7 @@ from strata_control import profiles from strata_control.doctor import inspect as inspect_components from strata_control.profiles import ProfileError from strata_control import atomic as _atomic_mod +from strata_control import posix_owner SUITE = "legacy-decode-v1" @@ -463,9 +464,8 @@ def _backup_directory(path: Path, *, create: bool = False) -> Path: except OSError as exc: raise ProfileError(f"cannot access calibration backup directory ({type(exc).__name__})", 5) from None if not stat.S_ISDIR(details.st_mode) or (os.name == "posix" and - (details.st_uid != os.getuid() or - stat.S_IMODE(details.st_mode) & 0o077)): - raise ProfileError("calibration backup directory must be owner-only and not a symlink", 5) + (posix_owner.owner_only_wrong(directory, details))): + raise ProfileError(posix_owner.owner_only_text("calibration backup directory must be owner-only and not a symlink", directory), 5) return directory @@ -485,9 +485,8 @@ def _load_application(path: Path, report: dict) -> dict: try: details = manifest.lstat() if not stat.S_ISREG(details.st_mode) or details.st_size > MAX_APPLICATION_BYTES or \ - (os.name == "posix" and (details.st_uid != os.getuid() or - stat.S_IMODE(details.st_mode) & 0o077)): - raise ProfileError("calibration application record is not an owner-only regular file", 5) + (os.name == "posix" and (posix_owner.owner_only_wrong(manifest, details))): + raise ProfileError(posix_owner.owner_only_text("calibration application record is not an owner-only regular file", manifest), 5) data = json.loads(manifest.read_text(encoding="utf-8")) except FileNotFoundError: raise ProfileError("calibration application record was not found", 5) from None @@ -636,8 +635,8 @@ def _saved_bytes(path: Path, *, required: bool = True, owner_only: bool = False) raise ProfileError("calibration rollback file is missing", 5) from None if not stat.S_ISREG(details.st_mode) or details.st_size > MAX_REPORT_BYTES or \ (owner_only and os.name == "posix" and - (details.st_uid != os.getuid() or stat.S_IMODE(details.st_mode) & 0o077)): - raise ProfileError("calibration rollback file must be a regular owner-only file under 2 MiB", 5) + (posix_owner.owner_only_wrong(path, details))): + raise ProfileError(posix_owner.owner_only_text("calibration rollback file must be a regular owner-only file under 2 MiB", path), 5) try: return path.read_bytes() except OSError as exc: diff --git a/strata_control/calibration_jobs.py b/strata_control/calibration_jobs.py index 2f03541c..29bf9f31 100644 --- a/strata_control/calibration_jobs.py +++ b/strata_control/calibration_jobs.py @@ -14,6 +14,7 @@ from pathlib import Path from strata_control import calibration, journal, profiles from strata_control.profiles import ProfileError +from strata_control import posix_owner KINDS = {"measure": "engine.calibrate.measure", "apply": "engine.calibrate.apply", @@ -43,9 +44,9 @@ def _open_lease(profile: str, *, create: bool) -> int | None: details = os.fstat(descriptor) if not stat.S_ISREG(details.st_mode) or details.st_nlink != 1 or details.st_size > 32 or \ (os.name == "posix" and - (details.st_uid != os.getuid() or stat.S_IMODE(details.st_mode) & 0o077)): + (posix_owner.owner_only_wrong(_lease_path(profile), details))): os.close(descriptor) - raise ProfileError("calibration worker lease must be owner-only", 5) + raise ProfileError(posix_owner.owner_only_text("calibration worker lease must be owner-only", _lease_path(profile)), 5) return descriptor @@ -129,7 +130,7 @@ def _cancel_requested(profile: str, job_id: str) -> bool: return False if not stat.S_ISREG(details.st_mode) or details.st_nlink != 1 or details.st_size != 1 or \ (os.name == "posix" and - (details.st_uid != os.getuid() or stat.S_IMODE(details.st_mode) & 0o077)): + (posix_owner.owner_only_wrong(path, details))): raise ProfileError("calibration cancellation marker is invalid", 5) descriptor = os.open(path, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0)) try: @@ -187,8 +188,8 @@ def _load_progress(profile: str, job_id: str) -> dict | None: return None if not stat.S_ISREG(details.st_mode) or details.st_nlink != 1 or details.st_size > 1024 or \ (os.name == "posix" and - (details.st_uid != os.getuid() or stat.S_IMODE(details.st_mode) & 0o077)): - raise ProfileError("calibration progress file must be owner-only", 5) + (posix_owner.owner_only_wrong(path, details))): + raise ProfileError(posix_owner.owner_only_text("calibration progress file must be owner-only", path), 5) try: value = json.loads(path.read_text(encoding="utf-8")) except (OSError, UnicodeError, ValueError): diff --git a/strata_control/journal.py b/strata_control/journal.py index c8f51a37..972fce9e 100644 --- a/strata_control/journal.py +++ b/strata_control/journal.py @@ -19,6 +19,7 @@ from pathlib import Path from strata_control import profiles, recipes from strata_control.profiles import ProfileError +from strata_control import posix_owner MAX_RECORDS = 500 @@ -51,8 +52,8 @@ def _directory(profile: str, *, create: bool = False) -> Path: details = directory.lstat() if not stat.S_ISDIR(details.st_mode): raise ProfileError("operation journal directory must not be a symlink", 5) - if os.name == "posix" and (details.st_uid != os.getuid() or stat.S_IMODE(details.st_mode) & 0o077): - raise ProfileError("operation journal directory must be owner-only", 5) + if os.name == "posix" and (posix_owner.owner_only_wrong(directory, details)): + raise ProfileError(posix_owner.owner_only_text("operation journal directory must be owner-only", directory), 5) return directory @@ -186,8 +187,8 @@ def _load_file(path: Path, profile: str) -> dict: details = path.lstat() if not stat.S_ISREG(details.st_mode) or details.st_size > MAX_RECORD_BYTES: raise ProfileError("operation record must be a regular file under 64 KiB", 5) - if os.name == "posix" and (details.st_uid != os.getuid() or stat.S_IMODE(details.st_mode) & 0o077): - raise ProfileError("operation record must be owner-only", 5) + if os.name == "posix" and (posix_owner.owner_only_wrong(path, details)): + raise ProfileError(posix_owner.owner_only_text("operation record must be owner-only", path), 5) record = json.loads(path.read_text(encoding="utf-8")) except FileNotFoundError: raise ProfileError("operation record was not found", 5) from None diff --git a/strata_control/posix_owner.py b/strata_control/posix_owner.py new file mode 100644 index 00000000..a6f20d77 --- /dev/null +++ b/strata_control/posix_owner.py @@ -0,0 +1,100 @@ +"""POSIX 'owner-only' checks that repair what is ours and explain what is not. + +Strata keeps its private state in folders (0700) and files (0600) of the user. The checks used to refuse as soon as a mode had drifted +(a `chmod -R`, an rsync, a restored backup) or the owner was not the current user (one `sudo strata ...` leaves root-owned folders behind). +Now: + +* the folder or file is ours and only the mode bits are wrong: the mode is put back (0700 / 0600) and the command goes on; +* the filesystem cannot hold modes at all (a Windows drive seen from WSL, vfat, some network shares): one note, then it goes on; +* another account owns it (root after sudo): the check still refuses, because that is the real boundary, but the message names the + cause and the exact command that fixes it. + +Windows has no mode bits; its own check lives in `private_files` and is not touched here. +""" + +from __future__ import annotations + +import os +import stat +import sys +from pathlib import Path + +POSIX = os.name == "posix" +_NOTED: set[str] = set() + + +def owner_only_wrong(path: str | os.PathLike, details: os.stat_result) -> bool: + """True when `path` (whose lstat or fstat is `details`) is not private to this user and could not be made so. + + Replaces `details.st_uid != os.getuid() or stat.S_IMODE(details.st_mode) & 0o077`. Never follows a link and never touches + a file that another account owns. + """ + if not POSIX: + return False + if details.st_uid != os.getuid(): + return True + if not stat.S_IMODE(details.st_mode) & 0o077: + return False + if stat.S_ISLNK(details.st_mode): + return True + want = 0o700 if stat.S_ISDIR(details.st_mode) else 0o600 + try: + os.chmod(path, want) # not a link (checked above), so this is the file itself + after = os.lstat(path) + except (OSError, NotImplementedError): + after = None + if after is not None and after.st_uid == os.getuid() and not stat.S_IMODE(after.st_mode) & 0o077: + return False + # The mode did not stick although the owner is right: the filesystem has no real modes. Say it once and carry on. + folder = str(path if stat.S_ISDIR(details.st_mode) else Path(path).parent) + if folder not in _NOTED: + _NOTED.add(folder) + print(f"strata: {folder} is on a drive that cannot keep files private to your account (a Windows drive seen from Linux, " + "a USB stick or a network share). Strata goes on; keep your data on the Linux disk to make it private.", file=sys.stderr) + return False + + +def _owner_name(uid: int) -> str: + try: + import pwd + return pwd.getpwuid(uid).pw_name + except (ImportError, KeyError): + return f"user {uid}" + + +def fix_target(path: str | os.PathLike) -> Path: + """The highest folder above `path` (below the home folder) that another account owns: one `chown` there fixes the whole tree.""" + target = Path(path) + home = Path.home() + uid = os.getuid() + best = target + current = target + for _ in range(6): + parent = current.parent + if parent == current or parent == home or parent == Path(parent.anchor): + break + try: + if parent.lstat().st_uid == uid: + break + except OSError: + break + best = parent + current = parent + return best + + +def owner_only_text(text: str, path: str | os.PathLike) -> str: + """The message for a refused check. `text` is the old sentence ("recipe directory must be owner-only"); when another account owns + `path` it becomes a sentence with the cause and the exact command, otherwise it is returned unchanged.""" + if not POSIX: + return text + try: + owner = os.lstat(path).st_uid + except OSError: + return text + if owner == os.getuid(): + return text + subject = text.split(" must ")[0].split(" is not ")[0].strip() + target = fix_target(path) + return (f"{subject} belongs to {_owner_name(owner)}, not to you (usually from running Strata once with sudo). " + f"Run this once, then try again: sudo chown -R \"$USER\" {target}") diff --git a/strata_control/recipes.py b/strata_control/recipes.py index 0451e524..2c85631a 100644 --- a/strata_control/recipes.py +++ b/strata_control/recipes.py @@ -22,6 +22,7 @@ from pathlib import Path from strata_control import profiles from strata_control.profiles import ProfileError +from strata_control import posix_owner KINDS = frozenset({"runtime.restart", "engine.calibrate.measure", "components.verify"}) @@ -44,8 +45,8 @@ def _directory(profile: str, *, create: bool = False) -> Path: details = path.lstat() if not stat.S_ISDIR(details.st_mode): raise ProfileError("recipe directory must not be a symlink", 5) - if os.name == "posix" and (details.st_uid != os.getuid() or stat.S_IMODE(details.st_mode) & 0o077): - raise ProfileError("recipe directory must be owner-only (mode 0700)", 5) + if os.name == "posix" and (posix_owner.owner_only_wrong(path, details)): + raise ProfileError(posix_owner.owner_only_text("recipe directory must be owner-only (mode 0700)", path), 5) if create: _private_mkdir(directory.parent, exist_ok=True) _private_mkdir(directory, exist_ok=True) @@ -53,8 +54,8 @@ def _directory(profile: str, *, create: bool = False) -> Path: details = directory.lstat() if not stat.S_ISDIR(details.st_mode): raise ProfileError("recipe directory must not be a symlink", 5) - if os.name == "posix" and (details.st_uid != os.getuid() or stat.S_IMODE(details.st_mode) & 0o077): - raise ProfileError("recipe directory must be owner-only (mode 0700)", 5) + if os.name == "posix" and (posix_owner.owner_only_wrong(directory, details)): + raise ProfileError(posix_owner.owner_only_text("recipe directory must be owner-only (mode 0700)", directory), 5) return directory @@ -80,8 +81,8 @@ def _history_dir(profile: str, name: str, *, create: bool = False) -> Path: if path.exists(): details = path.lstat() if not stat.S_ISDIR(details.st_mode) or (os.name == "posix" and - (details.st_uid != os.getuid() or stat.S_IMODE(details.st_mode) & 0o077)): - raise ProfileError("recipe history directory must be owner-only", 5) + (posix_owner.owner_only_wrong(path, details))): + raise ProfileError(posix_owner.owner_only_text("recipe history directory must be owner-only", path), 5) return directory @@ -182,8 +183,8 @@ def load(profile: str, name: str) -> tuple[dict, str]: details = path.lstat() if not stat.S_ISREG(details.st_mode) or details.st_size > MAX_BYTES: raise ProfileError("recipe must be a regular file under 64 KiB", 5) - if os.name == "posix" and (details.st_uid != os.getuid() or stat.S_IMODE(details.st_mode) & 0o077): - raise ProfileError("recipe file must be owner-only (mode 0600)", 5) + if os.name == "posix" and (posix_owner.owner_only_wrong(path, details)): + raise ProfileError(posix_owner.owner_only_text("recipe file must be owner-only (mode 0600)", path), 5) data = path.read_bytes() value = json.loads(data.decode("utf-8-sig")) except FileNotFoundError: @@ -227,7 +228,7 @@ def save(profile: str, name: str, proposed: dict, expected_revision: str) -> tup if backup.exists() or backup.is_symlink(): details = backup.lstat() if not stat.S_ISREG(details.st_mode) or (os.name == "posix" and - (details.st_uid != os.getuid() or stat.S_IMODE(details.st_mode) & 0o077)) or \ + (posix_owner.owner_only_wrong(backup, details))) or \ backup.read_bytes() != old: raise ProfileError("recipe history conflicts with the saved revision", 5) else: @@ -258,8 +259,8 @@ def rollback(profile: str, name: str, target_revision: str) -> tuple[dict, str, details = path.lstat() if not stat.S_ISREG(details.st_mode) or details.st_size > MAX_BYTES: raise ProfileError("recipe history must be a regular file under 64 KiB", 5) - if os.name == "posix" and (details.st_uid != os.getuid() or stat.S_IMODE(details.st_mode) & 0o077): - raise ProfileError("recipe history file must be owner-only", 5) + if os.name == "posix" and (posix_owner.owner_only_wrong(path, details)): + raise ProfileError(posix_owner.owner_only_text("recipe history file must be owner-only", path), 5) data = path.read_bytes() if profiles._revision(data) != target_revision: raise ProfileError("recipe history content does not match its revision", 5) diff --git a/strata_control/runtime.py b/strata_control/runtime.py index da16698f..e2676db2 100644 --- a/strata_control/runtime.py +++ b/strata_control/runtime.py @@ -38,7 +38,7 @@ try: except ImportError: # Windows has no qualified owner transport yet. fcntl = None -from strata_control import owner_transport, paths, private_files, procs, profiles, readiness, winproc +from strata_control import owner_transport, paths, posix_owner, private_files, procs, profiles, readiness, winproc from serve import launch_identity from strata_control.profiles import ProfileError @@ -56,7 +56,7 @@ def _is_private(details: os.stat_result, path: Path) -> bool: return private_files.is_unshared(path) except OSError: return False - return details.st_uid == os.getuid() and not stat.S_IMODE(details.st_mode) & 0o077 + return not posix_owner.owner_only_wrong(path, details) def _lock_file(descriptor: int, *, exclusive: bool) -> bool: diff --git a/tests/terminal/test_connections.py b/tests/terminal/test_connections.py index 0bec26e3..9d829f00 100644 --- a/tests/terminal/test_connections.py +++ b/tests/terminal/test_connections.py @@ -3,6 +3,7 @@ import io import json import os +import stat import subprocess import sys import tempfile @@ -149,10 +150,12 @@ class ConnectionTests(unittest.TestCase): connections.create("local", "http://127.0.0.1:8095") if os.name == "posix": record = self.directory / "local.json" - record.chmod(0o644) - with self.assertRaisesRegex(connections.ConnectionError, "private regular"): - connections.load("local") - record.chmod(0o600) + record.chmod(0o644) # our own file with drifted modes is put back, not refused + connections.load("local") + self.assertEqual(stat.S_IMODE(record.stat().st_mode), 0o600) + with mock.patch("os.getuid", return_value=os.getuid() + 1): # a file that belongs to another account is refused + with self.assertRaisesRegex(connections.ConnectionError, "belongs to .*sudo chown"): + connections.load("local") record = self.directory / "local.json" corrupted = json.loads(record.read_text()) corrupted["url"] = 42 diff --git a/tests/terminal/test_posix_owner.py b/tests/terminal/test_posix_owner.py new file mode 100644 index 00000000..85b01e96 --- /dev/null +++ b/tests/terminal/test_posix_owner.py @@ -0,0 +1,88 @@ +"""POSIX owner-only checks: our own folders with drifted modes are repaired; another account's folders get a message with the exact fix.""" + +import os +import stat +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +from strata_control import posix_owner + +posix_only = unittest.skipUnless(os.name == "posix", "POSIX modes") + + +@posix_only +class Repair(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.root = Path(self.tmp.name) + self.addCleanup(self.tmp.cleanup) + + def test_our_folder_with_open_modes_is_put_back_to_0700(self): + d = self.root / "recipes" + d.mkdir() + os.chmod(d, 0o755) + self.assertFalse(posix_owner.owner_only_wrong(d, d.lstat())) + self.assertEqual(stat.S_IMODE(d.lstat().st_mode), 0o700) + + def test_our_file_with_open_modes_is_put_back_to_0600(self): + f = self.root / "x.json" + f.write_text("{}") + os.chmod(f, 0o666) + self.assertFalse(posix_owner.owner_only_wrong(f, f.lstat())) + self.assertEqual(stat.S_IMODE(f.lstat().st_mode), 0o600) + + def test_a_private_one_is_left_alone(self): + d = self.root / "ok" + d.mkdir(mode=0o700) + self.assertFalse(posix_owner.owner_only_wrong(d, d.lstat())) + + def test_a_link_is_never_followed_or_repaired(self): + target = self.root / "t" + target.mkdir() + os.chmod(target, 0o755) + link = self.root / "l" + os.symlink(target, link) + self.assertTrue(posix_owner.owner_only_wrong(link, link.lstat())) + self.assertEqual(stat.S_IMODE(target.lstat().st_mode), 0o755) + + def test_a_folder_owned_by_someone_else_is_refused_and_not_touched(self): + d = self.root / "root-made" + d.mkdir() + os.chmod(d, 0o755) + with mock.patch.object(posix_owner.os, "getuid", return_value=os.getuid() + 1): + self.assertTrue(posix_owner.owner_only_wrong(d, d.lstat())) + text = posix_owner.owner_only_text("recipe directory must be owner-only (mode 0700)", d) + self.assertEqual(stat.S_IMODE(d.lstat().st_mode), 0o755) + self.assertIn("recipe directory belongs to", text) + self.assertIn("sudo", text) + self.assertIn("sudo chown -R \"$USER\"", text) + self.assertNotIn("0700", text) + + def test_a_filesystem_that_keeps_no_modes_warns_once_and_goes_on(self): + d = self.root / "drvfs" + d.mkdir() + os.chmod(d, 0o777) + posix_owner._NOTED.discard(str(d)) + with mock.patch.object(posix_owner.os, "chmod"), mock.patch("sys.stderr") as err: + self.assertFalse(posix_owner.owner_only_wrong(d, d.lstat())) + self.assertFalse(posix_owner.owner_only_wrong(d, d.lstat())) + printed = "".join(str(c.args[0]) for c in err.write.call_args_list) + self.assertEqual(printed.count("cannot keep files private"), 1) + + def test_the_text_of_our_own_folder_is_unchanged(self): + d = self.root / "mine" + d.mkdir() + self.assertEqual(posix_owner.owner_only_text("x must be owner-only", d), "x must be owner-only") + + +class Windows(unittest.TestCase): + def test_nothing_changes_off_posix(self): + with mock.patch.object(posix_owner, "POSIX", False): + self.assertFalse(posix_owner.owner_only_wrong(".", os.stat("."))) + self.assertEqual(posix_owner.owner_only_text("x", "."), "x") + + +if __name__ == "__main__": + unittest.main() From 6b29adad1af17e949a40a4c0fc0df2ed0a793873 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Tue, 20 Oct 2026 14:34:21 +0200 Subject: [PATCH 30/47] strata launch without a real tty (Git Bash, mintty): say so and go on with plain questions instead of refusing --- strata_cli/launch/cmd.py | 28 ++++++++++++++++++++++++++-- tests/terminal/test_launch.py | 23 ++++++++++++++++++++++- 2 files changed, 48 insertions(+), 3 deletions(-) diff --git a/strata_cli/launch/cmd.py b/strata_cli/launch/cmd.py index fc4d54e9..7abd7b79 100644 --- a/strata_cli/launch/cmd.py +++ b/strata_cli/launch/cmd.py @@ -359,6 +359,16 @@ def _stop_all(name: str | None) -> int: return 0 +def _can_ask() -> bool: + """A person may be typing although the streams are not a terminal (Git Bash, mintty): a normal Windows or Linux terminal session says so + through the environment. A pipe from a script or CI does not.""" + if sys.stdin is None or sys.stdin.closed: + return False + if os.environ.get("CI") or os.environ.get("STRATA_NO_PROMPT"): + return False + return bool(os.environ.get("MSYSTEM") or os.environ.get("TERM_PROGRAM") or os.environ.get("TERM") or os.environ.get("WT_SESSION")) + + def _ask_yes(title: str, text: str) -> bool: """Ask a yes/no question on the terminal. Enter means yes. When nobody can answer (no keyboard), the answer is yes: the person already named the model on the command line.""" @@ -533,9 +543,15 @@ def run_launch(a: argparse.Namespace) -> int: s, notices = settings_from_args(a, catalog) have_choices = bool(a.preset or a.model or a.model_path or a.context or a.vision or a.parallel or a.access or a.tune) interactive = sys.stdin.isatty() and sys.stdout.isatty() and not a.no_tui and not machine and not a.plan + plain_questions = False if not have_choices and not interactive and not a.plan: - return fail("`strata launch` with no choices opens screens, and this is not a terminal. Name what to start: --preset NAME, or --model NAME " - "(strata launch --help has examples; --plan shows what would happen without changing anything).", 2) + if machine or catalog is None or not _can_ask(): + return fail("`strata launch` with no choices opens screens, and this is not a terminal. Name what to start: --preset NAME, or --model NAME " + "(strata launch --help has examples; --plan shows what would happen without changing anything).", 2) + # Git Bash, mintty and some editor panels cannot show the screens although a person is typing: go on in plain lines, and ask first + plain_questions = True + _say("This window cannot show Strata's screens (Git Bash and similar windows do not pass the keyboard through). " + "For the screens, open Windows Terminal, PowerShell or cmd, or run `winpty strata launch`. Going on with plain questions.") if interactive and not have_choices: if catalog is None: return fail("This Terminal does not carry the model list, so the screens cannot open. Install it again with the one-line installer.", 5) @@ -578,6 +594,14 @@ def run_launch(a: argparse.Namespace) -> int: fw = _access.firewall_note(s.access) if fw and not machine: _say(f"[!] {fw}") + if plain_questions: + try: + answer = input("Start it now? Models can be tens of GB to download. [Y/n] ").strip().lower() + except EOFError: + return fail("There is nobody to answer. Name what to start: --preset NAME, or --model NAME (strata launch --help has examples).", 2) + if answer not in ("", "y", "yes"): + _say("Nothing was changed.") + return 0 if interactive and have_choices: from strata_cli.launch import app return _tui(app.run_tui, s, catalog=catalog, feed=a.feed, auto_run=True, save=bool(a.save_preset), open_page=bool(a.open), diff --git a/tests/terminal/test_launch.py b/tests/terminal/test_launch.py index 6b722e36..bf2b4a0a 100644 --- a/tests/terminal/test_launch.py +++ b/tests/terminal/test_launch.py @@ -799,12 +799,33 @@ class FlagsCommand(unittest.TestCase): self.assertIsNone(s["model"]) def test_no_choices_and_no_terminal_does_not_start_anything(self): - with mock.patch.object(Runner, "run", side_effect=AssertionError("must not run")): + with mock.patch.dict(os.environ, {"CI": "1"}), mock.patch.object(Runner, "run", side_effect=AssertionError("must not run")): code, out, err = run_cli(["launch"]) self.assertEqual(code, 2) self.assertIn("not a terminal", err) self.assertIn("--preset NAME", err) + def test_git_bash_without_a_tty_goes_on_in_plain_questions(self): + fake = Result("launch-x", ["http://127.0.0.1:8080"], None, None, [], "/x") + with mock.patch.dict(os.environ, {"MSYSTEM": "MINGW64"}), mock.patch("builtins.input", return_value="y"), mock.patch.object(Runner, "run", return_value=fake) as run: + code, out, err = run_cli(["launch"]) + self.assertEqual(code, 0, err) + run.assert_called_once() + self.assertIn("cannot show Strata's screens", out + err) + self.assertIn("winpty strata launch", out + err) + + def test_git_bash_answering_no_changes_nothing(self): + with mock.patch.dict(os.environ, {"MSYSTEM": "MINGW64"}), mock.patch("builtins.input", return_value="n"), mock.patch.object(Runner, "run", side_effect=AssertionError("must not run")): + code, out, err = run_cli(["launch"]) + self.assertEqual(code, 0, err) + self.assertIn("Nothing was changed", out + err) + + def test_a_pipe_with_nobody_to_answer_still_says_what_to_name(self): + with mock.patch.dict(os.environ, {"MSYSTEM": "MINGW64"}), mock.patch("builtins.input", side_effect=EOFError), mock.patch.object(Runner, "run", side_effect=AssertionError("must not run")): + code, out, err = run_cli(["launch"]) + self.assertEqual(code, 2) + self.assertIn("--preset NAME", err) + def test_unknown_model_names_the_closest_one(self): code, out, err = run_cli(["launch", "--plan", "--model", "iq3xxs"]) self.assertEqual(code, 2) From 14be49605f9d8a6446db444efa65457d483747d2 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Tue, 20 Oct 2026 14:38:00 +0200 Subject: [PATCH 31/47] Models folder: a whole drive becomes D:\Strata (and D:\Strata\Models), the person's folder is written into the settings file Control reads (so the installer accepts it whatever it is called), no link where the disk cannot hold one, plain words for a folder that is gone or not writable; the Terminal remembers a chosen --data-dir; docs: moving models to another disk and what stays on C: --- docs/DOCKER.md | 3 +++ docs/INSTALL.md | 20 ++++++++++++++++++++ strata_cli/launch/runner.py | 7 +++++-- tests/terminal/test_launch.py | 4 +++- tools/test_strata_mcp.py | 11 +++++++++++ 5 files changed, 42 insertions(+), 3 deletions(-) diff --git a/docs/DOCKER.md b/docs/DOCKER.md index c87dafe7..dc8ce616 100644 --- a/docs/DOCKER.md +++ b/docs/DOCKER.md @@ -134,6 +134,9 @@ variable; the model and tuning stay in `/data`. Anything else: `docker exec stra What is in the volume `/data`: `Strata-data/` (model files, the prepared pack), `state/` (presets, tuning, the key), `install/` (run settings and logs), `home/`. The engine and the Terminal are in the image, so updating the image never touches your files. +To keep it all on a big disk, mount a folder there instead of the named volume: `-v /mnt/big/strata:/data` (the folder must be writable by the +container's user). Nothing large is written anywhere else in the container. + ### Files you already have Mount the folder with the model's GGUF files read-only and name it: `-v /srv/gguf/IQ3_XXS:/models:ro -e MODEL_PATH=/models diff --git a/docs/INSTALL.md b/docs/INSTALL.md index 80db9797..d860d042 100644 --- a/docs/INSTALL.md +++ b/docs/INSTALL.md @@ -305,6 +305,26 @@ says so and starts the engine you had. GitHub at the commit `LLAMA_CPP_COMMIT` in `setup.py` names. Put that commit's tree in `third_party/llama.cpp` yourself (from a mirror or another PC) and setup uses it instead (#585). +### Keeping the models on another disk + +The model files are the only big part (70 to 190 GB). Put them where there is room; the app and the Terminal use the same folder. + +- **In the app:** the first screen shows the model folder with a button to change it, and Settings > Storage changes it + later. Pick a folder you can save files in; a whole drive (`D:\`) becomes `D:\Strata`, which Strata makes and says so. + Models you already have in the old folder stay there and keep working; nothing is moved or deleted for you. +- **In the Terminal:** `strata launch --data-dir D:\Strata` once. The folder is remembered for the next `strata launch` + and `strata models list`. Until you give it one, the Terminal uses the folder the app chose; the app keeps its own setting + (Settings > Storage) and does not read the Terminal's. `--move-data` moves the models you already have into it; without it they stay where they + are and the new folder gets the new downloads. Use your own files in place with `strata launch --model-path FOLDER` (a + folder of shards, a folder above it, or one `.gguf` file); a folder that holds several sizes needs the one `.gguf` file. +- **Drives that are not NTFS** (exFAT, FAT32, a network share) work: Strata writes straight into `\models` and makes no + link there. +- **What stays on C:** the engine (`%LOCALAPPDATA%\Strata\components`, 1 to 2 GB per version; `STRATA_COMPONENTS_DIR` moves it), + the app itself (the installer asks), your settings, chat history, tuning results and logs (`%LOCALAPPDATA%\Strata`, + `%APPDATA%\Strata`; a few MB). Nothing else large: downloads, the prepared model data (`packs`) and the draft layer (`mtp`) are + written in the model folder, and so are the half-finished files of an interrupted download. +- **Docker:** `-v /mnt/big/strata:/data` (a folder on the big disk) instead of the volume `strata-data`; everything above lives in it. + ## Setup's questions These are the questions of the installer from source (`START-HERE.bat`, `./setup.sh`). The app's first screen and diff --git a/strata_cli/launch/runner.py b/strata_cli/launch/runner.py index bec861f7..709675b8 100644 --- a/strata_cli/launch/runner.py +++ b/strata_cli/launch/runner.py @@ -542,6 +542,8 @@ class Runner: args += ["--data-dir", str(data)] if self.move_data and s.data_dir: # only when the person said so: setup moves nothing otherwise args.append("--move-data") + if s.data_dir: # a folder the person chose is remembered for the next start and for the app + args.append("--set-default-data-dir") if s.model_path: p = Path(s.model_path) args += ["--gguf-dir", str(p if p.is_dir() else p.parent)] @@ -549,8 +551,9 @@ class Runner: args += ["--gpus", ",".join(str(g) for g in s.gpus)] if len(s.gpus) > 1 else ["--gpu", str(s.gpus[0])] if sys.platform == "darwin": # a Mac's setup (Control mode, strata_control/mac_fit.py) takes fewer options (no --kv, --gpu, speed projection) - keep = {"--yes", "--no-start", "--family", "--model", "--context", "--vision", "--data-dir", "--gguf-dir", "--move-data"} - flags = ("--yes", "--no-start", "--move-data") + keep = {"--yes", "--no-start", "--family", "--model", "--context", "--vision", "--data-dir", "--gguf-dir", "--move-data", + "--set-default-data-dir"} + flags = ("--yes", "--no-start", "--move-data", "--set-default-data-dir") out, i = [], 0 while i < len(args): if args[i] in keep: diff --git a/tests/terminal/test_launch.py b/tests/terminal/test_launch.py index bf2b4a0a..a6255e8d 100644 --- a/tests/terminal/test_launch.py +++ b/tests/terminal/test_launch.py @@ -407,11 +407,13 @@ class SetupArgs(unittest.TestCase): ["--gpu", "1"]): self.assertIn(pair[0], a) self.assertEqual(a[a.index(pair[0]) + 1], pair[1]) + self.assertIn("--set-default-data-dir", a) # a folder the person chose is the remembered one (the app and the next start use it) def test_a_mac_gets_only_the_options_its_setup_knows(self): with mock.patch.object(sys, "platform", "darwin"): a = self.runner(data_dir="/d", gpus=[0]) - self.assertEqual(a, ["--yes", "--no-start", "--family", "qwen", "--model", "IQ3_XXS", "--context", "32768", "--vision", "no", "--data-dir", "/d"]) + self.assertEqual(a, ["--yes", "--no-start", "--family", "qwen", "--model", "IQ3_XXS", "--context", "32768", "--vision", "no", "--data-dir", "/d", + "--set-default-data-dir"]) class AdoptRules(unittest.TestCase): diff --git a/tools/test_strata_mcp.py b/tools/test_strata_mcp.py index 8bc0acd7..3e490831 100644 --- a/tools/test_strata_mcp.py +++ b/tools/test_strata_mcp.py @@ -346,6 +346,17 @@ class Validation(FakeRoot): for d in ok: self.assertEqual(M.norm(self.tools.check_data_dir(str(d))), M.norm(d)) + def test_the_persons_own_data_folder_is_accepted_whatever_it_is_called(self): + """The app writes the folder the person chose into the settings file (apps/host model-folder.mjs); an AI tool naming a new + folder still needs a Strata... name.""" + chosen = self.root.parent / "my-big-disk" + chosen.mkdir() + self.assertRejected("strata_install", {"data_dir": str(chosen)}, "named Strata") + settings = self.tools.s.settings_path() + settings.parent.mkdir(parents=True, exist_ok=True) + settings.write_text(json.dumps({"data_dir": str(chosen)})) + self.assertEqual(M.norm(self.tools.check_data_dir(str(chosen))), M.norm(chosen)) + def test_other_tools_arguments(self): self.assertRejected("strata_start", {"model": "../../etc/passwd"}, "not valid") self.assertRejected("strata_start", {"model": "q2_0"}, "no model is installed") From cf34e915c4ebfc90e7c545847f81530c11c6affd Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Tue, 20 Oct 2026 14:40:35 +0200 Subject: [PATCH 32/47] Update rules: Control --version waits longer and tries twice, a busy card is not held against an engine (other failures expire after a day), pre-release Control handover, a wrong PC clock says so --- strata_cli/handover.py | 24 +++- strata_control/feed.py | 17 ++- strata_control/transfer.py | 28 ++++- strata_control/updater.py | 61 ++++++++-- tests/terminal/test_update_rules_022.py | 155 ++++++++++++++++++++++++ 5 files changed, 266 insertions(+), 19 deletions(-) create mode 100644 tests/terminal/test_update_rules_022.py diff --git a/strata_cli/handover.py b/strata_cli/handover.py index 7067abc3..1e511950 100644 --- a/strata_cli/handover.py +++ b/strata_cli/handover.py @@ -28,7 +28,7 @@ def running_from_checkout() -> bool: """True when this Terminal runs from a git checkout (the source route) rather than an installed bundle.""" return (Path(__file__).resolve().parents[1] / ".git").exists() _FOLDER = re.compile(r"^[\w.+-]+$") -_VERSION = re.compile(r"^[0-9]+(\.[0-9]+){1,3}$") +_VERSION = re.compile(r"^[0-9]+(\.[0-9]+){1,3}(-[0-9A-Za-z][0-9A-Za-z.]*)?$") # 0.2.2, or a pre-release such as 0.2.2-rc1 def components_dir(environ=None) -> Path: @@ -45,8 +45,18 @@ def components_dir(environ=None) -> Path: def version_key(text) -> tuple[int, ...] | None: if not isinstance(text, str) or not _VERSION.fullmatch(text.strip()): return None - parts = [int(p) for p in text.strip().split(".")] - return tuple(parts + [0] * (4 - len(parts))) + base, dash, _pre = text.strip().partition("-") + parts = [int(p) for p in base.split(".")] + # a pre-release sorts below the same number without the suffix (0.2.2-rc1 < 0.2.2); two pre-releases of one number compare by name + return tuple(parts + [0] * (4 - len(parts))) + ((0, _pre_rank(_pre)) if dash else (1, ())) + + +def _pre_rank(pre: str) -> tuple: + """alpha < beta < rc < anything else, then the number inside ("rc2" > "rc1").""" + order = {"alpha": 0, "a": 0, "beta": 1, "b": 1, "rc": 2} + m = re.match(r"([A-Za-z]*)\.?([0-9]*)", pre) + word, number = (m.group(1).lower(), int(m.group(2) or 0)) if m else ("", 0) + return (order.get(word, 3), number) def _read_json(path: Path): @@ -93,8 +103,12 @@ def find_target(running: str, environ=None, root: Path | None = None): if version is None: version = pointer.get("version") have, want = version_key(running), version_key(version) - if want is None or have is None or want <= have: - return None, None, None # never an older or equal Control; an unreadable version is ignored + if have is None: + return None, None, None # this Control has no readable version (a development tree): nothing to compare + if want is None: + return (None, None, f"its version ({version!r}) cannot be read") if version else (None, None, None) + if want <= have: + return None, None, None # never an older or equal Control if not (bundled_python(folder).is_file() and (folder / "strata.py").is_file() and (folder / "strata_control").is_dir()): return None, version, f"{folder} is missing its interpreter or entry point" return folder, version, None diff --git a/strata_control/feed.py b/strata_control/feed.py index 8497f7f5..688a41ed 100644 --- a/strata_control/feed.py +++ b/strata_control/feed.py @@ -279,9 +279,21 @@ def parse(payload: bytes, *, source: str, key_id: str) -> Feed: control=tuple(control), engine=tuple(engine), source=source, key_id=key_id, raw=payload) +def _expired_words(expires_at: str, now: dt.datetime, server_now: dt.datetime | None) -> str: + """Expired by this PC's clock. If the update server's own clock says otherwise (or says the PC is far off), the clock is what is wrong.""" + fix = "Set the date and time right (Windows: Settings, Time & language, Date & time, Set time automatically) and try again." + if server_now is not None: + off = abs((server_now - now).total_seconds()) + if off > 15 * 60 and _time(expires_at, "expires_at") >= server_now: + return (f"your PC clock is wrong: it says {now:%Y-%m-%d %H:%M} (UTC) but the update server says {server_now:%Y-%m-%d %H:%M}, " + f"so the update feed looks expired. {fix}") + return (f"the update feed expired on {expires_at} by this PC's clock ({now:%Y-%m-%d}). If that is not today's date, your PC clock is wrong. " + f"{fix} Otherwise the update source needs to publish a new feed; nothing was downloaded.") + + def verify_and_parse(payload: bytes, signature_bytes: bytes, *, source: str, trusted: dict[str, bytes], last_sequence: int | None = None, channel: str | None = None, - now: dt.datetime | None = None) -> Feed: + now: dt.datetime | None = None, server_now: dt.datetime | None = None) -> Feed: """Check the signature over `payload`, then parse; then the three guards: the channel is the one asked for, the feed has not expired, and its sequence is not lower than the last one accepted (a replayed older feed is a downgrade).""" if not trusted: @@ -300,7 +312,7 @@ def verify_and_parse(payload: bytes, signature_bytes: bytes, *, source: str, tru raise FeedError(f"the feed is for the {feed.channel!r} channel, this PC follows {channel!r}") now = now or dt.datetime.now(dt.timezone.utc) if feed.expires_at and _time(feed.expires_at, "expires_at") < now: - raise FeedError(f"the update feed expired on {feed.expires_at}; refusing a stale feed") + raise FeedError(_expired_words(feed.expires_at, now, server_now)) if last_sequence is not None and feed.sequence < last_sequence: raise FeedDowngrade(f"the update feed is older than the one already accepted (sequence {feed.sequence} < {last_sequence}); " "refusing a replayed feed") @@ -324,6 +336,7 @@ def fetch(source: str, trusted: dict[str, bytes], **guards) -> Feed: signature = transfer.read_small(location + SIGNATURE_SUFFIX) except transfer.TransferError as exc: raise FeedError(f"the update feed could not be read: {exc}", 6) from None + guards.setdefault("server_now", transfer.server_date()) return verify_and_parse(payload, signature, source=location, trusted=trusted, **guards) diff --git a/strata_control/transfer.py b/strata_control/transfer.py index 5aa85fb6..25687731 100644 --- a/strata_control/transfer.py +++ b/strata_control/transfer.py @@ -16,6 +16,8 @@ import http.client import ipaddress import os import threading +import email.utils +import datetime as _dt import urllib.error import urllib.parse import urllib.request @@ -131,14 +133,34 @@ _opener = urllib.request.build_opener(_PolicyRedirects) _USER_AGENT = "strata-updater/1" +_SERVER_DATE: list = [] + + +def server_date(): + """The time the update server named in the `Date` header of its last answer (a timezone-aware datetime), or None. It lets a feed that + looks expired be told from a PC whose clock is wrong.""" + return _SERVER_DATE[-1] if _SERVER_DATE else None + + +def _remember_date(response) -> None: + try: + parsed = email.utils.parsedate_to_datetime(response.headers.get("Date") or "") + if parsed is not None: + _SERVER_DATE[:] = [parsed if parsed.tzinfo else parsed.replace(tzinfo=_dt.timezone.utc)] + except (TypeError, ValueError): + pass + + def read_small(location: str, *, limit: int = SMALL_LIMIT, timeout: float = 30) -> bytes: """A small document (the feed, its signature). Larger than `limit` is refused, not truncated.""" kind = kind_of(location) + _SERVER_DATE.clear() # only the answer of this read counts try: if kind in ("http", "https"): check_url_policy(location) request = urllib.request.Request(location, headers={"User-Agent": _USER_AGENT, "Cache-Control": "no-cache"}) with _opener.open(request, timeout=timeout) as response: + _remember_date(response) data = response.read(limit + 1) else: path = _local_path(location) @@ -151,7 +173,11 @@ def read_small(location: str, *, limit: int = SMALL_LIMIT, timeout: float = 30) raise TransferError(f"the update server answered {exc.code} for {location}") from None except (urllib.error.URLError, OSError, TimeoutError) as exc: reason = getattr(exc, "reason", exc) - raise TransferError(f"could not read {location} ({type(exc).__name__}: {reason})") from None + hint = "" + if "CERTIFICATE_VERIFY_FAILED" in str(reason): + hint = (". This computer did not accept the update server's certificate: check that its date and time are right, " + "or that a company proxy is not replacing the certificate") + raise TransferError(f"could not read {location} ({type(exc).__name__}: {reason}){hint}") from None if len(data) > limit: raise TransferError(f"{location} is larger than {limit} bytes") return data diff --git a/strata_control/updater.py b/strata_control/updater.py index 65c5e62b..f93d9041 100644 --- a/strata_control/updater.py +++ b/strata_control/updater.py @@ -72,9 +72,16 @@ class Busy(UpdateError): class TestStartFailed(UpdateError): __test__ = False # not a pytest class + #: reasons that say the graphics card or memory was busy, not that the engine is broken + BUSY = re.compile(r"timed?[ -]?out|out of memory|\boom\b|not enough (gpu |video |free )?memory|vram|memory allocation|" + r"cudaerrormemory|device (is )?(busy|in use)|resource busy|no free (gpu|memory)", re.I) + def __init__(self, label: str, reason: str): + self.busy = bool(self.BUSY.search(reason)) super().__init__(f"The new engine {label} did not pass its test start ({reason}). It was not installed; " - "your current engine is unchanged.", 6) + "your current engine is unchanged." + + (" The graphics card or memory looks busy: close programs that use the card (games, video, other models) " + "and run `strata update` again." if self.busy else ""), 6) self.label = label self.reason = reason @@ -476,6 +483,8 @@ def _choose_engine(feed: feedmod.Feed, ctx: Context, state: State) -> tuple[dict else: report["status"] = "available" bad = (section.get("failed") or {}).get(offered.version) + if bad and _failed_mark_is_old(bad, ctx): + bad = None # a failure is held against a version for a day, not for ever if report["status"] == "available" and not ctx.force: if bad and bad.get("manifest_sha256") == offered.manifest_sha256: report["status"] = "failed-before" @@ -786,10 +795,11 @@ def update_engine(ctx: Context, feed: feedmod.Feed, state: State) -> dict: smoke = runner(stage_root, staged, ctx) except TestStartFailed as exc: section = state.section("engine") - section.setdefault("failed", {})[pkg.version] = { - "manifest_sha256": pkg.manifest_sha256, "reason": exc.reason[:300], - "at": (ctx.now or dt.datetime.now(dt.timezone.utc)).isoformat()} - state.history({"at": section["failed"][pkg.version]["at"], "action": "update-engine", "to": pkg.version, + at = (ctx.now or dt.datetime.now(dt.timezone.utc)).isoformat() + if not exc.busy: # a busy card says nothing about the engine: the next update tries again + section.setdefault("failed", {})[pkg.version] = { + "manifest_sha256": pkg.manifest_sha256, "reason": exc.reason[:300], "at": at} + state.history({"at": at, "action": "update-engine", "to": pkg.version, "from": before_installed.version if before_installed else None, "ok": False, "detail": f"test start failed: {exc.reason[:200]}"}) state.save() @@ -924,6 +934,40 @@ def decide_control(feed: feedmod.Feed, ctx: Context, state: State) -> dict: return report +CONTROL_VERSION_TIMEOUTS = (240, 360) # seconds: antivirus scans a fresh python.exe on its first run, which can take minutes + + +def _control_version(interpreter: str, entry: Path, stage: Path, ctx: Context, version: str): + """Run `--version` of the staged Control; once more, with more time, when the first try timed out, failed to start or said nothing.""" + last_error = None + done = None + for attempt, timeout in enumerate(CONTROL_VERSION_TIMEOUTS): + try: + done = subprocess.run([interpreter, str(entry), "--version"], capture_output=True, text=True, timeout=timeout, cwd=str(stage), + env={**ctx.environ, "PYTHONNOUSERSITE": "1", "STRATA_NO_ACQUIRE": "1", "STRATA_HANDOVER": "1"}, + creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0)) + last_error = None + if done.returncode == 0 and version in done.stdout: + return done + except (OSError, subprocess.SubprocessError) as exc: + last_error = exc + if attempt + 1 < len(CONTROL_VERSION_TIMEOUTS): + ctx.say("test", f"Control {version} did not answer yet (a virus scanner may be checking it); trying once more", component="control") + if last_error is not None: + raise TestStartFailed(f"Control {version}", f"{type(last_error).__name__}: {last_error}") from None + return done + + +def _failed_mark_is_old(mark: dict, ctx: Context, hours: float = 24.0) -> bool: + try: + then = dt.datetime.fromisoformat(str(mark.get("at"))) + if then.tzinfo is None: + then = then.replace(tzinfo=dt.timezone.utc) + return (ctx.now or dt.datetime.now(dt.timezone.utc)) - then > dt.timedelta(hours=hours) + except (TypeError, ValueError): + return False + + def update_control(ctx: Context, feed: feedmod.Feed, state: State) -> dict: """Stage a newer Control bundle beside the running one, run it once (`--version`), and only then point the app and the terminal at it (``components/control/active.json``). The running Control is never modified.""" @@ -945,12 +989,7 @@ def update_control(ctx: Context, feed: feedmod.Feed, state: State) -> dict: python = stage / "python" / ("python.exe" if os.name == "nt" else "bin/python3") interpreter = str(python) if python.is_file() else sys.executable ctx.say("test", f"Test-starting Control {pkg.version}", component="control") - try: - done = subprocess.run([interpreter, str(entry), "--version"], capture_output=True, text=True, timeout=120, cwd=str(stage), - env={**ctx.environ, "PYTHONNOUSERSITE": "1", "STRATA_NO_ACQUIRE": "1", "STRATA_HANDOVER": "1"}, - creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0)) - except (OSError, subprocess.SubprocessError) as exc: - raise TestStartFailed(f"Control {pkg.version}", f"{type(exc).__name__}: {exc}") from None + done = _control_version(interpreter, entry, stage, ctx, pkg.version) if done.returncode != 0 or pkg.version not in done.stdout: raise TestStartFailed(f"Control {pkg.version}", f"--version said {done.stdout.strip()[:120]!r} (exit {done.returncode})") final = control_dir(root) / pkg.version diff --git a/tests/terminal/test_update_rules_022.py b/tests/terminal/test_update_rules_022.py new file mode 100644 index 00000000..36111614 --- /dev/null +++ b/tests/terminal/test_update_rules_022.py @@ -0,0 +1,155 @@ +"""0.2.2 update rules: a slow first run of Control is waited for, a busy card is not held against an engine, a pre-release Control is +handed over to (or not) by its number, and a feed that looks expired on a PC with a wrong clock says so.""" + +import datetime as dt +import json +import subprocess +import tempfile +import unittest +from pathlib import Path +from types import SimpleNamespace +from unittest import mock + +from strata_cli import handover +from strata_control import feed as feedmod, signing, updater +from tests.terminal import update_fixture as fx +from tests.terminal.test_handover import make_control +from tests.terminal.test_update_feed import document, signed +from tests.terminal import test_updater + + +class ControlVersionTest(unittest.TestCase): + def ctx(self): + said = [] + return SimpleNamespace(environ={}, say=lambda *a, **k: said.append(a)), said + + def test_a_first_run_that_times_out_is_tried_once_more_with_more_time(self): + ctx, said = self.ctx() + good = SimpleNamespace(returncode=0, stdout="strata 0.2.2\n") + calls = [] + + def fake(cmd, **kw): + calls.append(kw["timeout"]) + if len(calls) == 1: + raise subprocess.TimeoutExpired(cmd, kw["timeout"]) + return good + with mock.patch.object(updater.subprocess, "run", fake): + done = updater._control_version("py", Path("strata.py"), Path("."), ctx, "0.2.2") + self.assertIs(done, good) + self.assertEqual(calls, list(updater.CONTROL_VERSION_TIMEOUTS)) + self.assertGreater(calls[0], 120) + self.assertEqual(len(said), 1) + + def test_two_failures_end_as_a_failed_test_start(self): + ctx, _ = self.ctx() + with mock.patch.object(updater.subprocess, "run", side_effect=subprocess.TimeoutExpired("x", 1)): + with self.assertRaises(updater.TestStartFailed): + updater._control_version("py", Path("strata.py"), Path("."), ctx, "0.2.2") + + +class BusyCardTest(test_updater.UpdaterCase): + def refuse(self, reason): + def runner(stage_root, staged, ctx): + raise updater.TestStartFailed(staged.version, reason) + return runner + + def test_a_busy_card_is_not_held_against_the_engine(self): + self.install_current() + self.publish(("0.1.47", fx.GOOD_ENGINE)) + out = updater.run_update(self.ctx(test_start=self.refuse("it timed out waiting for the graphics card")), control=False) + result = out["results"][0] + self.assertEqual(result["status"], "failed") + self.assertIn("looks busy", result["error"]) + again = updater.run_update(self.ctx(), control=False) + self.assertEqual(again["results"][0]["status"], "updated", again) + + def test_a_real_failure_is_remembered_for_a_day_and_then_tried_again(self): + self.install_current() + self.publish(("0.1.47", fx.GOOD_ENGINE)) + updater.run_update(self.ctx(test_start=self.refuse("the engine crashed on start")), control=False) + soon = updater.run_update(self.ctx(), control=False) + self.assertEqual(soon["results"][0]["status"], "failed-before") + later = dt.datetime.now(dt.timezone.utc) + dt.timedelta(hours=25) + retry = updater.run_update(self.ctx(now=later), control=False) + self.assertEqual(retry["results"][0]["status"], "updated", retry) + + +class HandoverPreRelease(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory(prefix="strata-rc-") + self.addCleanup(self.temp.cleanup) + self.comp = Path(self.temp.name) / "components" + self.comp.mkdir() + self.env = {"STRATA_COMPONENTS_DIR": str(self.comp)} + + def target(self, running): + return handover.find_target(running, self.env) + + def test_the_order_of_releases_and_candidates(self): + key = handover.version_key + self.assertLess(key("0.2.2-rc1"), key("0.2.2")) + self.assertLess(key("0.2.2-rc1"), key("0.2.2-rc2")) + self.assertLess(key("0.2.2-beta"), key("0.2.2-rc1")) + self.assertLess(key("0.2.1"), key("0.2.2-rc1")) + self.assertIsNone(key("banana")) + + def test_a_release_candidate_is_handed_over_to_from_an_older_release(self): + make_control(self.comp, "0.2.2-rc1") + folder, version, problem = self.target("0.2.1") + self.assertIsNone(problem) + self.assertEqual(version, "0.2.2-rc1") + self.assertEqual(folder.name, "0.2.2-rc1") + + def test_the_final_release_replaces_its_candidate_but_not_the_other_way(self): + make_control(self.comp, "0.2.2") + self.assertEqual(self.target("0.2.2-rc1")[1], "0.2.2") + make_control(self.comp, "0.2.2-rc1", point=False) + (self.comp / "control" / "active.json").write_text(json.dumps({"version": "0.2.2-rc1", "folder": "0.2.2-rc1"})) + self.assertEqual(self.target("0.2.2"), (None, None, None)) + + def test_a_version_nobody_can_read_is_said_not_ignored(self): + make_control(self.comp, "banana") + folder, version, problem = self.target("0.2.1") + self.assertIsNone(folder) + self.assertIn("cannot be read", problem) + + +class ClockTest(unittest.TestCase): + def setUp(self): + self.key = signing.generate_key() + self.trusted = fx.trusted_of(self.key) + + def load(self, **guards): + payload, sig = signed(document(expires_at="2026-10-01T00:00:00Z"), self.key) + return feedmod.verify_and_parse(payload, sig, source="/feeds/strata-feed.json", trusted=self.trusted, **guards) + + def test_the_server_clock_proves_the_pc_clock_wrong(self): + pc = dt.datetime(2027, 3, 1, tzinfo=dt.timezone.utc) + server = dt.datetime(2026, 9, 20, tzinfo=dt.timezone.utc) + with self.assertRaises(feedmod.FeedError) as caught: + self.load(now=pc, server_now=server) + text = str(caught.exception) + self.assertIn("your PC clock is wrong", text) + self.assertIn("2026-09-20", text) + self.assertNotIn("refusing a stale feed", text) + + def test_without_a_server_date_the_clock_is_named_as_a_cause(self): + with self.assertRaisesRegex(feedmod.FeedError, "your PC clock is wrong.*new feed"): + self.load(now=dt.datetime(2027, 3, 1, tzinfo=dt.timezone.utc)) + + def test_a_feed_the_server_also_calls_expired_is_still_refused_as_expired(self): + pc = dt.datetime(2026, 11, 1, tzinfo=dt.timezone.utc) + with self.assertRaisesRegex(feedmod.FeedError, "expired on"): + self.load(now=pc, server_now=pc) + + def test_a_certificate_error_hints_at_the_clock(self): + import urllib.error + from strata_control import transfer + err = urllib.error.URLError("[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed") + with mock.patch.object(transfer._opener, "open", side_effect=err): + with self.assertRaisesRegex(transfer.TransferError, "date and time"): + transfer.read_small("https://example.org/strata-feed.json") + + +if __name__ == "__main__": + unittest.main() From fa56c2b3878ef405e17c31cbf0bd04ae3664778e Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Tue, 20 Oct 2026 14:40:43 +0200 Subject: [PATCH 33/47] Start: a picture reader path from an older engine folder follows the installed package (engine update or other image no longer ends in server_exited) --- docs/DOCKER.md | 11 +++++++++++ serve/server.py | 21 +++++++++++++++++++++ tests/terminal/test_component_start.py | 17 +++++++++++++++++ 3 files changed, 49 insertions(+) diff --git a/docs/DOCKER.md b/docs/DOCKER.md index dc8ce616..fc89ef33 100644 --- a/docs/DOCKER.md +++ b/docs/DOCKER.md @@ -142,6 +142,17 @@ container's user). Nothing large is written anywhere else in the container. Mount the folder with the model's GGUF files read-only and name it: `-v /srv/gguf/IQ3_XXS:/models:ro -e MODEL_PATH=/models -e MODEL=IQ3_XXS`. Nothing is downloaded for the model itself; the prepared pack is made in the volume. +- The folder holds the shards of one model directly (`...-00001-of-00002.gguf`, `...-00002-of-00002.gguf`), not a folder of folders. + If you mount a parent folder, the container says which sub-folder to name in `MODEL_PATH`. +- The folder has to be mounted: a `MODEL_PATH` that is not in the container, or a folder with no `.gguf` files, stops the start at + once with a message, and nothing is downloaded. +- Read-only (`:ro`) is fine. The pack (about 40 GB for IQ3_XXS) and the draft layer (about 6 GB, fetched once) are written to the + volume, so it needs that room. +- Links to the files work when the links' targets are mounted too, and `MODEL` is set (without `MODEL`, Strata identifies the files itself + and does not follow links). +- Without `MODEL_PATH`, files you put into the volume by hand (`/data/Strata-data/models//`) are found as well, if they have the + published names. + ## The API key The server listens on every address **inside** the container (that is what lets the published port work), and Strata does not diff --git a/serve/server.py b/serve/server.py index aca6c5a7..126c171a 100644 --- a/serve/server.py +++ b/serve/server.py @@ -7648,6 +7648,26 @@ def default_model_name(cfg: dict) -> str: return cfg.get("model_name") or FAMILY_MODEL_NAMES.get(cfg.get("arch") or "qwen4exp", "qwen3.8-flash-next") +def with_current_reader(cfg: dict, package: Path) -> dict: + """The picture reader (vision "exe", "cpu_exe") is written into the run config as an absolute path inside the engine package's folder, + and that folder is named after the engine version: after an engine update, or in a container made for another card, the path is gone + and the server would stop with "server_exited". Use the same file of the package that is installed now (the reader ships in the package).""" + vision = cfg.get("vision") + if not isinstance(vision, dict): + return cfg + fixed = dict(vision) + for key in ("exe", "cpu_exe"): + old = fixed.get(key) + if isinstance(old, str) and old and not engine_component.is_reference(old) and os.path.isabs(old) and not os.path.exists(old): + new = package / old.replace("\\", "/").rsplit("/", 1)[-1] + if new.is_file(): + print(f"[strata] the picture reader {old} is not there any more; using {new} from the engine package in use", flush=True) + fixed[key] = str(new) + if fixed == vision: + return cfg + return {**cfg, "vision": fixed} + + def with_component_engine(cfg: dict) -> dict: """A run config that names "component:strata-engine" gets the engine package for this PC: the path in `exe`, and the package's own folder first on the library path (the GPU runtime libraries ship beside the binary).""" @@ -7656,6 +7676,7 @@ def with_component_engine(cfg: dict) -> dict: cfg = dict(cfg) cfg["exe"] = _component_exe(cfg["exe"], cfg) cfg["lib_dirs"] = [*engine_component.package_lib_dirs(Path(cfg["exe"]).parent), *(cfg.get("lib_dirs") or [])] + cfg = with_current_reader(cfg, Path(cfg["exe"]).parent) if cfg.get("backend") == "hip": # AMD: the package's own hipBLASLt tuning table for this card, when its hipBLASLt version matches cfg = hipblaslt_tuning.apply(cfg, Path(cfg["exe"]).parent, say=lambda line: print(line, flush=True)) return cfg diff --git a/tests/terminal/test_component_start.py b/tests/terminal/test_component_start.py index dbab849f..e9d95f99 100644 --- a/tests/terminal/test_component_start.py +++ b/tests/terminal/test_component_start.py @@ -202,6 +202,23 @@ class ComponentStart(unittest.TestCase): server.with_component_engine({"exe": "component:strata-engine", "backend": "cuda"}) self.assertEqual(caught.exception.code, 5) + def test_a_picture_reader_path_from_an_older_engine_folder_follows_the_installed_package(self): + """After an engine update the folder name changes; the run config's absolute vision exe must not stop the server.""" + from serve import server + folder = install_fake_engine(self.components) + reader = folder / "strata-vision" + reader.write_text("x", encoding="utf-8") + gone = str(self.components / "engine" / "0.0.1-old" / "strata-vision") + cfg = server.with_component_engine({"exe": "component:strata-engine", "backend": "cuda", + "vision": {"exe": gone, "cpu_exe": gone, "mmproj": "/m.gguf"}}) + self.assertEqual(cfg["vision"]["exe"], str(reader)) + self.assertEqual(cfg["vision"]["cpu_exe"], str(reader)) + self.assertEqual(cfg["vision"]["mmproj"], "/m.gguf") + ok = {"exe": "component:strata-engine", "backend": "cuda", "vision": {"exe": str(reader)}} + self.assertEqual(server.with_component_engine(ok)["vision"], {"exe": str(reader)}) + none = server.with_component_engine({"exe": "component:strata-engine", "backend": "cuda", "vision": {"exe": gone.replace("strata-vision", "other")}}) + self.assertTrue(none["vision"]["exe"].endswith("other")) # no such file in the package: left as it is + def test_the_build_json_lib_dirs_follow_the_package_folder(self): """The Windows HIP package keeps the ROCm DLLs in rocm/bin (BUILD.json lib_dirs): strata.exe does not load without them on PATH.""" from serve import server From bd4c6bf1afd268213a69d12ae6e4c5c125b96945 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Tue, 20 Oct 2026 15:41:30 +0200 Subject: [PATCH 34/47] Setup tests follow the merges: verify_sha256 takes own=, a tight disk margin warns and a real shortfall refuses --- tools/test_setup_unsloth.py | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/tools/test_setup_unsloth.py b/tools/test_setup_unsloth.py index b758db55..c14b9ed8 100644 --- a/tools/test_setup_unsloth.py +++ b/tools/test_setup_unsloth.py @@ -193,7 +193,7 @@ class Base(unittest.TestCase): mock.patch.object(setup, "get_prebuilt", lambda *a, **k: eng), mock.patch.object(setup, "download", fake_download), mock.patch.object(setup, "check_shards", lambda shards: None), - mock.patch.object(setup, "verify_sha256", lambda s, size, sha: self.verified.append((s.name, size, sha))), + mock.patch.object(setup, "verify_sha256", lambda s, size, sha, own=False: self.verified.append((s.name, size, sha))), mock.patch.object(setup, "run", fake_run), mock.patch.object(setup, "refresh_draft_vocab", lambda *a, **k: None), mock.patch.object(setup, "write_run_script", lambda tag, cfg, port, *_: self.t / f"start-{tag}.bat"), @@ -298,8 +298,17 @@ class Main(Base): import shutil shutil.rmtree(self.t / "data" / "mtp", ignore_errors=True) # #897: a draft layer already there needs less room (d / (list(setup.UNSLOTH_SHARDS)[0] + ".part")).write_bytes(b"x" * 1_500_000) - with mock.patch.dict(setup.MODELS[M], {"download_gb": 0.003}): # 1.5 MB still missing: no room + with mock.patch.dict(setup.MODELS[M], {"download_gb": 0.003}): # 1.5 MB still missing, but the 8 GB working room is only a guess (0.2.2): setup warns and goes on code, out, cfg = self.main(["--context", "8192"], free=8.001) + self.assertEqual(code, 0, out) + self.assertNotIn("not enough free disk space", out) + self.assertIn("little free disk space", out) + for f in d.iterdir(): + f.unlink() + shutil.rmtree(self.t / "data" / "mtp", ignore_errors=True) + (d / (list(setup.UNSLOTH_SHARDS)[0] + ".part")).write_bytes(b"x" * 1_500_000) + with mock.patch.dict(setup.MODELS[M], {"download_gb": 3.0}): # 1.5 GB of real files still to write, 1 GB free: refuse + code, out, cfg = self.main(["--context", "8192"], free=1.0) self.assertEqual(code, 1) self.assertIn("not enough free disk space", out) From c24f2a139ff06b33555e32a3dd360b960d9a52da Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Tue, 20 Oct 2026 15:50:42 +0200 Subject: [PATCH 35/47] Own model files: a --model-path that is not there or holds no model is said in plain words before the engine or setup start (no 'missing /Qwen...gguf', no promise of a download), also in --plan and the screens --- strata_cli/launch/cmd.py | 8 +++-- strata_cli/launch/runner.py | 23 +++++++++++--- strata_cli/launch/screens.py | 7 +++-- strata_control/models.py | 52 +++++++++++++++++++++++++++++++ tests/terminal/test_launch.py | 14 ++++++--- tests/terminal/test_launch_tui.py | 15 +++++++-- 6 files changed, 104 insertions(+), 15 deletions(-) diff --git a/strata_cli/launch/cmd.py b/strata_cli/launch/cmd.py index 7abd7b79..36510792 100644 --- a/strata_cli/launch/cmd.py +++ b/strata_cli/launch/cmd.py @@ -559,6 +559,11 @@ def run_launch(a: argparse.Namespace) -> int: return _tui(app.run_tui, None, catalog=catalog, feed=a.feed, open_page=bool(a.open)) if catalog is None: return fail("This Terminal does not carry the model list. Install it again with the one-line installer.", 5) + runner = Runner(s, catalog=catalog, emit=_printer(machine), feed=a.feed, assume_yes=bool(a.yes or machine), confirm=_ask_yes) + try: + runner.check_own_files() # the person's own files: a wrong path is said now, and the files name the model + except LaunchError as e: + return fail(f"{e.text}" + (f" {e.next}" if e.next else ""), e.code) s, notes = apply_defaults(s, catalog) errors = [n for n in notes if n.level == "error"] if errors: @@ -569,8 +574,7 @@ def run_launch(a: argparse.Namespace) -> int: if not s.name: s.name = f"{s.model or 'model'} {S.context_label(s.context)}" move_data = _move_data_choice(a, s, catalog, machine) - runner = Runner(s, catalog=catalog, emit=_printer(machine), feed=a.feed, assume_yes=bool(a.yes or machine), confirm=_ask_yes, - move_data=move_data) + runner.s, runner.move_data = s, move_data if a.plan: plan = runner.plan() plan["warnings"] = [n.line() for n in notes] diff --git a/strata_cli/launch/runner.py b/strata_cli/launch/runner.py index 709675b8..9cc81c48 100644 --- a/strata_cli/launch/runner.py +++ b/strata_cli/launch/runner.py @@ -331,6 +331,7 @@ class Runner: self.notices: list[str] = [] self.tune_result: dict | None = None self.config_path: Path | None = None + self._own_checked = False # ---- small helpers def emit(self, stage: str, text: str, pct: float | None = None, level: str = "info", **data: Any) -> None: @@ -625,8 +626,7 @@ class Runner: def ensure_model(self) -> Path: s, cat = self.s, self.catalog - if s.model_path: - self.resolve_own_files() + self.check_own_files() self.resolved_vision() if not (s.family and s.model): raise LaunchError("No model was chosen.", "Choose a model, or use --model NAME (strata launch --help lists them).", 2) @@ -641,7 +641,8 @@ class Runner: adopted = self.adopt_prepared_files("no Mac model installer in this Terminal") if adopted is not None: return adopted - self.emit("model", f"Getting {title} ready (a download may be large; it continues where it stopped if interrupted)…", 0) + self.emit("model", f"Preparing {title} from your model files…" if s.model_path else + f"Getting {title} ready (a download may be large; it continues where it stopped if interrupted)…", 0) argv = [self.python, str(cat.src / "setup.py"), *self.setup_args()] env = self._env() env.update(STRATA_CONTROL_INSTALL="1", STRATA_INSTALL_DIR=str(cat.root), PYTHONNOUSERSITE="1") @@ -695,7 +696,8 @@ class Runner: if adopted is not None: return adopted raise LaunchError("The model could not be installed." + (f" {err}." if err else ""), - hint or "Run it again: finished steps are skipped and a download continues where it stopped.", 6) + hint or ("Run it again: finished steps are skipped." if s.model_path else + "Run it again: finished steps are skipped and a download continues where it stopped."), 6) path, _desc = self.installed_state() if path is None: raise LaunchError("Setup finished but no run config was written for this model.", @@ -737,12 +739,22 @@ class Runner: self.emit("model", f"Used your prepared model files and wrote the run settings ({path.name}); this card is not one the built-in downloader sets up.", 100, level="warn") return path + def check_own_files(self) -> None: + """The person's own model files, looked at once: a path that is not there or holds no model is said in plain words first, and the + files are matched to the catalog model (resolve_own_files). Nothing else is done with a path that was already checked.""" + if self.s.model_path and not self._own_checked: + self.resolve_own_files() + self._own_checked = True + def resolve_own_files(self) -> None: """"Use model files I already have": the fingerprint table says which catalog model the files are, and which folder holds them (the person may have named the folder above it). When the person also named the model (--model), the files are never refused here: setup takes the files of that model out of the folder by name, as it always did (0.1.45), and says what is wrong when it cannot.""" from strata_control import models s = self.s + problem = models.own_path_problem(s.model_path) + if problem: # before the engine or setup are touched, with the path as typed + raise LaunchError(problem[0], problem[1], 2) given = bool(s.family and s.model) try: plan = models.plan_import(models.absolute(s.model_path)) @@ -760,7 +772,7 @@ class Runner: sel = plan.get("candidate_selection") or {} fam, model = sel.get("family"), sel.get("model") if not (fam and model) or plan.get("issues"): - issues = "; ".join(plain_issue(str(x)) for x in (plan.get("issues") or [])[:3]) or "they are not a model Strata knows" + issues = models.problem_words(plan.get("issues") or []) or "they are not a model Strata knows" more = " " + next((m for m in plan.get("messages") or [] if "holds" in m), "") raise LaunchError(f"These files cannot be used as they are ({issues}).{more.rstrip()}", "Choose the matching model in the list, or check that every shard is in the folder.", 5) @@ -941,6 +953,7 @@ class Runner: def run(self, *, start: bool = True) -> Result: try: + self.check_own_files() # a wrong --model-path is said before the engine is downloaded self.ensure_engine() self.check_cancel() base = self.ensure_model() diff --git a/strata_cli/launch/screens.py b/strata_cli/launch/screens.py index f2ec0db7..53730937 100644 --- a/strata_cli/launch/screens.py +++ b/strata_cli/launch/screens.py @@ -492,8 +492,11 @@ class ModelScreen(Base): self.check_own(path) def check_own(self, path: str) -> None: - from strata_cli.launch.runner import plain_issue from strata_control import models + problem = models.own_path_problem(path) + if problem: + self.say(f"{problem[0]} {problem[1]}", True) + return try: plan = models.plan_import(models.absolute(path)) except Exception as e: # noqa: BLE001 @@ -510,7 +513,7 @@ class ModelScreen(Base): self.menu().select((sel["family"], sel["model"])) self.paint() else: - why = "; ".join(plain_issue(str(x)) for x in (plan.get("issues") or [])[:3]) or "they are not a model Strata knows" + why = models.problem_words(plan.get("issues") or []) or "they are not a model Strata knows" holds = next((m for m in plan.get("messages") or [] if "holds" in m), "") self.say(f"These files cannot be used as they are ({why}). " + (holds + " " if holds else "") + "Check that every shard is in the folder, or pick a model from the list.", True) diff --git a/strata_control/models.py b/strata_control/models.py index 74914ed2..a42d8539 100644 --- a/strata_control/models.py +++ b/strata_control/models.py @@ -339,6 +339,34 @@ def plain_issue(code: str) -> str: return f"{name}: {words}" if name else words +def problem_words(issues: list, limit: int = 3) -> str: + """The problems of a file set as ONE sentence part, each said once: the same reason for several files names the files together + ("a.gguf and b.gguf: the file is cut short"), a reason that was already given is not given again, and a long list is cut with a count. + A folder that holds several models does not also say "not a size Strata knows".""" + codes = [str(x) for x in issues or []] + if "multiple_model_groups" in codes: + codes = [x for x in codes if x != "unrecognized_or_unsupported_model_variant"] + by_reason: dict[str, list[str]] = {} + for code in codes: + words = plain_issue(code) + name, sep, reason = words.partition(": ") + if sep and name.lower().endswith(".gguf"): + by_reason.setdefault(reason, []).append(name) + else: + by_reason.setdefault(words, []) + parts = [] + for reason, names in by_reason.items(): + if not names: + parts.append(reason) + elif len(names) <= 2: + parts.append(f"{' and '.join(names)}: {reason}") + else: + parts.append(f"{names[0]}, {names[1]} and {len(names) - 2} more files: {reason}") + if len(parts) > limit: + parts = parts[:limit] + [f"and {len(parts) - limit} more problem" + ("s" if len(parts) - limit > 1 else "")] + return "; ".join(parts) + + UNSUPPORTED_MODEL_TYPE = ("This model type isn't supported by the Strata engine. " "Add it as a Custom model API (llama-server) instead.") # The picture readers Strata ships a pinned copy of (setup downloads and checks one of these next to the model). @@ -496,6 +524,30 @@ def import_target(picked: str, plan: dict) -> str: return plan.get("model_dir") or picked +def own_path_problem(picked: str) -> tuple[str, str] | None: + """(what is wrong, what to do) when the path a person gave for their own model files is not there or holds no model file, in plain + words; None when there is something to look at. Said before anything is installed or downloaded, with the path the person typed.""" + path = Path(absolute(picked)) + kind = "file" if path.name.lower().endswith(".gguf") else "folder" + try: + if not path.exists(): + if path.is_symlink(): + return (f"This {kind} is a shortcut to something that is not there any more: {path}.", + "Point it at the real folder, or at the .gguf file itself. Nothing was downloaded or changed.") + return (f"This {kind} does not exist: {path}.", + "Check the spelling, and that the drive or folder is connected (in Docker or a virtual machine it has to be shared with it). " + "Nothing was downloaded or changed.") + if path.is_dir(): + has_files = any(entry.name.lower().endswith(".gguf") for entry in os.scandir(path)) + if not has_files and not _folders_with_models(path): + return (f"There are no .gguf model files in {path}, nor in the folders inside it.", + "Point it at the folder that holds the model's .gguf files (names like ...-00001-of-00002.gguf), or at one of the files. " + "Nothing was downloaded or changed.") + except OSError: + return None + return None + + def plan_import(raw_path: str) -> dict: """Inspect a local candidate without copying, parsing tensors or adopting it. diff --git a/tests/terminal/test_launch.py b/tests/terminal/test_launch.py index a6255e8d..18fd91bd 100644 --- a/tests/terminal/test_launch.py +++ b/tests/terminal/test_launch.py @@ -795,10 +795,16 @@ class FlagsCommand(unittest.TestCase): self.assertEqual(p["settings"]["api_key"], "set") def test_model_path_is_used_instead_of_a_catalog_model(self): - p = self.plan("--model-path", "/data/models/IQ3_XXS") - s = p["settings"] - self.assertEqual(s["model_path"], str(Path("/data/models/IQ3_XXS"))) - self.assertIsNone(s["model"]) + import tempfile + from tests.terminal.test_own_files import IQ3XXS, gguf_bytes + with tempfile.TemporaryDirectory() as tmp: + folder = Path(tmp) / "IQ3_XXS" + folder.mkdir() + for n in IQ3XXS: + (folder / n).write_bytes(gguf_bytes(["IQ3_XXS"])) + s = self.plan("--model-path", str(folder))["settings"] + self.assertEqual(s["model_path"], str(folder)) + self.assertEqual((s["family"], s["model"]), ("qwen", "IQ3_XXS")) # the files say which model they are def test_no_choices_and_no_terminal_does_not_start_anything(self): with mock.patch.dict(os.environ, {"CI": "1"}), mock.patch.object(Runner, "run", side_effect=AssertionError("must not run")): diff --git a/tests/terminal/test_launch_tui.py b/tests/terminal/test_launch_tui.py index 003fb305..e9b0a6f5 100644 --- a/tests/terminal/test_launch_tui.py +++ b/tests/terminal/test_launch_tui.py @@ -259,7 +259,7 @@ class ModelStep(Base): async def case(app, pilot, ctx): await press(pilot, "enter", "o") self.assertIn("Type or paste the folder", text_of(app)) - with mock.patch("strata_control.models.plan_import", return_value=plan) as pi: + with mock.patch("strata_control.models.plan_import", return_value=plan) as pi, mock.patch("strata_control.models.own_path_problem", return_value=None): await typed(pilot, "/data/models/IQ3_XXS") await press(pilot, "enter") self.assertEqual(ctx.settings.model_path, os.path.abspath("/data/models/IQ3_XXS")) @@ -274,7 +274,7 @@ class ModelStep(Base): async def case(app, pilot, ctx): await press(pilot, "enter", "o") - with mock.patch("strata_control.models.plan_import", return_value=plan): + with mock.patch("strata_control.models.plan_import", return_value=plan), mock.patch("strata_control.models.own_path_problem", return_value=None): await typed(pilot, "/x") await press(pilot, "enter") t = flat(app) @@ -283,6 +283,17 @@ class ModelStep(Base): self.assertIsNone(ctx.settings.model_path) self.run_app(case) + def test_own_files_folder_that_is_not_there_is_named(self): + async def case(app, pilot, ctx): + await press(pilot, "enter", "o") + await typed(pilot, "/no/such/folder") + await press(pilot, "enter") + t = flat(app) + self.assertIn("does not exist", t) + self.assertIn("Nothing was downloaded", t) + self.assertIsNone(ctx.settings.model_path) + self.run_app(case) + def test_own_files_path_from_the_start_screen(self): async def case(app, pilot, ctx): await press(pilot, "down", "enter") From 284552fe269f6856bcd087460cc3e99481e6ebba Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Tue, 20 Oct 2026 15:50:48 +0200 Subject: [PATCH 36/47] Own model files: links to shards are accepted with or without --model, and a problem that applies to several files is said once (problem_words), in the Terminal, the screens and 'models import'; tests for items 2 and 3 --- strata_cli/cli.py | 7 +- tests/terminal/test_flow2_022.py | 160 +++++++++++++++++++++++++++++++ 2 files changed, 162 insertions(+), 5 deletions(-) create mode 100644 tests/terminal/test_flow2_022.py diff --git a/strata_cli/cli.py b/strata_cli/cli.py index c15e00a6..2b12eba1 100644 --- a/strata_cli/cli.py +++ b/strata_cli/cli.py @@ -591,11 +591,8 @@ def _models(a: argparse.Namespace) -> int: def _import_problem(plan: dict) -> str: """Why `models import --plan` refused, in plain words (the codes stay in --output json).""" - from strata_cli.launch.runner import plain_issue - issues = [str(x) for x in plan.get("issues") or []] - if "multiple_model_groups" in issues: # several models in one folder: "not a size Strata knows" would only confuse - issues = [x for x in issues if x != "unrecognized_or_unsupported_model_variant"] - words = "; ".join(dict.fromkeys(plain_issue(x) for x in issues)) + from strata_control import models as own_models + words = own_models.problem_words(plan.get("issues") or []) text = f"These files cannot be used as they are: {words}." holds = next((m for m in plan.get("messages") or [] if "holds" in m), "") if holds: diff --git a/tests/terminal/test_flow2_022.py b/tests/terminal/test_flow2_022.py new file mode 100644 index 00000000..45bd8170 --- /dev/null +++ b/tests/terminal/test_flow2_022.py @@ -0,0 +1,160 @@ +"""0.2.2 flow walk, second round (phaseA-tests/flow-findings-022.md): what `strata launch` says and does with your own model files, the +plan, the download figure, the long silent step and a tuning result that already exists.""" + +from __future__ import annotations + +import json +import os +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +from strata_cli.launch import settings as S +from strata_cli.launch.catalog import Catalog +from strata_cli.launch.runner import LaunchError, Runner +from tests.terminal.launch_support import HW_12, Home, run_cli +from tests.terminal.test_own_files import IQ3XXS, Q2, gguf_bytes + + +class Base(unittest.TestCase): + def setUp(self): + self.home = Home().__enter__() + self.addCleanup(self.home.__exit__, None, None, None) + p = mock.patch.object(Catalog, "hardware", lambda self, fresh=False: dict(HW_12, disk_free_gb=500.0)) + p.start() + self.addCleanup(p.stop) + self.tmp = tempfile.TemporaryDirectory(prefix="strata-flow2-") + self.addCleanup(self.tmp.cleanup) + self.base = Path(self.tmp.name) + + def files(self, folder: Path, names: list[str], kind: str) -> Path: + folder.mkdir(parents=True, exist_ok=True) + for n in names: + (folder / n).write_bytes(gguf_bytes([kind])) + return folder + + def runner(self, **kw) -> Runner: + return Runner(S.LaunchSettings(**kw), catalog=Catalog(hardware=HW_12)) + + +class MissingOwnFiles(Base): + """Finding 2: a --model-path that is not there, or holds no model, is said in plain words before anything starts.""" + + def test_a_folder_that_does_not_exist_is_named_and_nothing_is_promised(self): + missing = self.base / "models" + code, out, err = run_cli(["launch", "--plan", "--model-path", str(missing)]) + self.assertEqual(code, 2) + self.assertIn(f"This folder does not exist: {missing}", err) + self.assertNotIn("Qwen", err) + self.assertNotIn("continues where it stopped", err) + self.assertNotIn("could not be installed", err) + + def test_a_missing_file_says_file(self): + code, out, err = run_cli(["launch", "--plan", "--model-path", str(self.base / "x-00001-of-00002.gguf")]) + self.assertEqual(code, 2) + self.assertIn("This file does not exist", err) + + def test_an_empty_folder_says_there_are_no_gguf_files(self): + empty = self.base / "empty" + empty.mkdir() + code, out, err = run_cli(["launch", "--plan", "--model", "q2_0", "--model-path", str(empty)]) + self.assertEqual(code, 2) + self.assertIn("no .gguf model files", err) + self.assertIn("...-00001-of-00002.gguf", err) + + def test_machine_output_carries_the_same_words(self): + code, out, err = run_cli(["launch", "--plan", "--output", "json", "--model-path", str(self.base / "gone")]) + self.assertEqual(code, 2) + self.assertIn("This folder does not exist", json.loads(out)["error"]["message"]) + + def test_the_engine_is_not_touched_for_a_wrong_path(self): + r = self.runner(model_path=str(self.base / "gone")) + with mock.patch.object(Runner, "ensure_engine", side_effect=AssertionError("engine step must not start")): + with self.assertRaises(LaunchError) as ctx: + r.run() + self.assertEqual(ctx.exception.code, 2) + self.assertIn("does not exist", ctx.exception.text) + + def test_the_failure_hint_of_own_files_promises_no_download(self): + r = self.runner(model_path=str(self.files(self.base / "m", Q2, "Q2_0")), family="qwen", model="Q2_0") + proc = mock.Mock() + proc.stdout = iter(["=== Step 5: Getting the model files ===", "[X] missing /m/x.gguf"]) + proc.wait.return_value = 1 + with mock.patch.object(Runner, "_spawn", return_value=proc), mock.patch.object(Runner, "adopt_prepared_files", return_value=None): + with self.assertRaises(LaunchError) as ctx: + r.ensure_model() + self.assertNotIn("download", ctx.exception.next) + self.assertIn("finished steps are skipped", ctx.exception.next) + + def test_the_screens_say_the_same(self): + from strata_control import models + text, nxt = models.own_path_problem(str(self.base / "nope")) + self.assertIn("This folder does not exist", text) + self.assertIn("Nothing was downloaded", nxt) + self.assertIsNone(models.own_path_problem(str(self.files(self.base / "ok", IQ3XXS, "IQ3_XXS")))) + + def test_a_folder_one_level_above_the_files_is_not_called_empty(self): + self.files(self.base / "repo" / "IQ3_XXS", IQ3XXS, "IQ3_XXS") + from strata_control import models + self.assertIsNone(models.own_path_problem(str(self.base / "repo"))) + + +class LinkedShards(Base): + """Finding 3: shards that are links are accepted with no --model, as with --model, and a problem is said once.""" + + def links(self, names: list[str], real: bool = True) -> Path: + blobs = self.base / "blobs" + snap = self.base / "snap" + blobs.mkdir(exist_ok=True) + snap.mkdir(exist_ok=True) + for i, n in enumerate(names): + target = blobs / f"sha{i}" + if real: + target.write_bytes(gguf_bytes(["Q2_0"])) + try: + os.symlink(target, snap / n) + except (OSError, NotImplementedError): + self.skipTest("this account cannot create symbolic links") + return snap + + def test_linked_shards_without_a_model_name_are_used(self): + snap = self.links(Q2) + code, out, err = run_cli(["launch", "--plan", "--output", "json", "--model-path", str(snap)]) + self.assertEqual(code, 0, err or out) + s = json.loads(out)["plan"]["settings"] + self.assertEqual((s["family"], s["model"]), ("qwen", "Q2_0")) + self.assertEqual(Path(s["model_path"]), snap) # the link names stay (the shard names are what setup reads) + + def test_linked_shards_with_the_model_named_give_the_same_folder(self): + snap = self.links(Q2) + code, out, err = run_cli(["launch", "--plan", "--output", "json", "--model", "q2_0", "--model-path", str(snap)]) + self.assertEqual(code, 0, err or out) + self.assertEqual(Path(json.loads(out)["plan"]["settings"]["model_path"]), snap) + + def test_links_to_nothing_are_one_sentence_not_one_per_file(self): + snap = self.links(Q2, real=False) + code, out, err = run_cli(["launch", "--plan", "--model-path", str(snap)]) + self.assertEqual(code, 5) + self.assertEqual(err.count("shortcut"), 1, err) + self.assertIn(Q2[0], err) + self.assertIn(Q2[1], err) + + def test_the_same_problem_for_many_files_is_said_once(self): + from strata_control import models + issues = [f"m-0000{i}-of-00005.gguf: GGUF metadata is truncated" for i in range(1, 6)] + ["incomplete_or_invalid_shard_set"] + words = models.problem_words(issues) + self.assertEqual(words.count("the file is cut short"), 1) + self.assertIn("m-00001-of-00005.gguf, m-00002-of-00005.gguf and 3 more files", words) + self.assertEqual(models.problem_words(["a.gguf: GGUF metadata is truncated", "b.gguf: GGUF metadata is truncated"]), + "a.gguf and b.gguf: the file is cut short (a download or copy that did not finish)") + self.assertEqual(models.problem_words(["multiple_model_groups", "unrecognized_or_unsupported_model_variant"]), + "the folder holds more than one model") + many = [f"unsupported_or_missing_architecture", "incomplete_or_invalid_shard_set", "multiple_model_groups", + "unsupported_or_incomplete_tokenizer_metadata", "missing_or_unexpected_expert_quantization"] + self.assertTrue(models.problem_words(many).endswith("and 2 more problems")) + + + +if __name__ == "__main__": + unittest.main() From 3d5594d656a4877d130216f59b9d69348d01d94d Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Tue, 20 Oct 2026 15:55:39 +0200 Subject: [PATCH 37/47] launch --plan: names the model your files are (title, size, picture setting, a copyable line with --model) instead of placeholders, and says what would be downloaded and how big (0 when everything is here, the draft layer and picture reader counted, engine mentioned) --- strata_cli/launch/cmd.py | 13 +++++- strata_cli/launch/runner.py | 70 +++++++++++++++++++++++++++++++- strata_cli/launch/settings.py | 2 +- tests/terminal/test_flow2_022.py | 56 +++++++++++++++++++++++++ 4 files changed, 137 insertions(+), 4 deletions(-) diff --git a/strata_cli/launch/cmd.py b/strata_cli/launch/cmd.py index 36510792..477d43b9 100644 --- a/strata_cli/launch/cmd.py +++ b/strata_cli/launch/cmd.py @@ -30,6 +30,9 @@ examples: """ +PICTURE_WORDS = {"off": "off", "on": "on", "cpu": "on (the reader runs on the processor)", "gpu": "on (the reader runs on the graphics card)"} + + def _choice(label: str, options: tuple[str, ...]): def convert(value: str) -> str: v = str(value).strip().lower() @@ -582,8 +585,14 @@ def run_launch(a: argparse.Namespace) -> int: print(json.dumps({"schema_version": 1, "ok": True, "plan": plan})) else: _say(f"Plan for '{s.name}':") - _say(f" model {s.family} {s.model}" if s.model else f" model your files at {s.model_path}") - _say(f" context {S.context_label(s.context)} pictures {s.vision} parallel {s.parallel or 'fit to your card'}") + m = plan.get("model") or {} + size = f", {m['model_gb']:.0f} GB" if m.get("model_gb") else "" + if s.model_path: + _say(f" model {m.get('title') or 'your model files'}{size} (your files in {s.model_path})") + else: + _say(f" model {m.get('title') or f'{s.family} {s.model}'}{size}") + _say(f" context {S.context_label(s.context)} pictures {PICTURE_WORDS.get(s.vision or 'off', s.vision)} parallel {s.parallel or 'fit to your card'}") + _say(f" download {(plan.get('download') or {}).get('text', '')}") _say(f" tuning {s.tune} access {S.ACCESS_WORDS[s.access]}, port {s.port}" + (" API key on" if s.api_key else "")) for n in notes: diff --git a/strata_cli/launch/runner.py b/strata_cli/launch/runner.py index 9cc81c48..ba20a5ea 100644 --- a/strata_cli/launch/runner.py +++ b/strata_cli/launch/runner.py @@ -945,11 +945,79 @@ class Runner: return tunnel # ---- all of it + def row(self): + """The catalog row of the chosen model (None for a model the list does not carry).""" + s = self.s + return next((r for r in self.catalog.rows() if (r.family, r.model) == (s.family, s.model)), None) + + def download_plan(self) -> dict: + """What this launch would download, in numbers and words (nothing is changed): the model's missing files, and for a model that is + not on this computer yet also the draft layer and the picture reader that setup fetches after it. 0 when everything is here.""" + from strata_control import engine_component + from strata_control.discovery import MMPROJ_GB, MTP_FETCH_GB + s = self.s + st = self.model_state() + parts = [{"kind": p.kind, "label": p.label, "gb": round(p.gb, 1)} for p in st.parts] + fresh = any(p.kind == "weights" for p in st.parts) and not st.own_files + row = self.row() + helpers = s.family in ("qwen", "swift", "coder", "unsloth") + wants_pictures = s.vision not in (None, "off") and row is not None and bool(row.images) + have = {p["kind"] for p in parts} + if fresh and helpers: + if s.mtp != "off": + parts.append({"kind": "mtp", "label": "the draft layer", "gb": MTP_FETCH_GB}) + if wants_pictures: + parts.append({"kind": "mmproj", "label": "the picture reader", "gb": MMPROJ_GB}) + elif st.own_files and helpers: + # the person's files come with no draft layer or picture reader: setup fetches them next to the prepared data, unless they are there + try: + data = Path(st.folder) if st.folder else (self.existing_data_dir() or self.catalog.data_dir()) + if s.mtp != "off" and "mtp" not in have and not (data / "mtp" / "rt" / "experts.bin").is_file(): + parts.append({"kind": "mtp", "label": "the draft layer", "gb": MTP_FETCH_GB}) + if wants_pictures and "mmproj" not in have and not list((data / "models").glob("mmproj*.gguf")): + parts.append({"kind": "mmproj", "label": "the picture reader", "gb": MMPROJ_GB}) + except OSError: + pass + gb = round(sum(p["gb"] for p in parts), 1) + engine = True + try: + engine = bool(engine_component.status(Path(self.components_dir) if self.components_dir else None).get("usable")) + except Exception: # noqa: BLE001 - the plan must not fail on this + pass + if gb < 0.05: + text = ("Nothing to download: your model files are used where they are." if st.own_files + else "Nothing to download: the model is already on this computer.") + else: + names = [f"{p['label']} ({p['gb']:.1f} GB)" for p in parts] + what = names[0] if len(names) == 1 else ", ".join(names[:-1]) + " and " + names[-1] + text = f"About {gb:.1f} GB to download: {what}." + if st.on_disk_gb >= 1: + text += f" {st.on_disk_gb:.0f} GB of the model is already in its folder." + if st.own_files: + text += " Your model files are used where they are." + if not engine: + text += " The engine for your graphics card is downloaded first (from the update source; its size is shown when it starts)." + return {"gb": gb, "parts": parts, "engine_missing": not engine, "own_files": st.own_files, "text": text} + def plan(self) -> dict: s = self.s + self.check_own_files() warns = [n.line() for n in (*S.check_access(s),)] + row = self.row() + try: + self.resolved_vision() + except Exception: # noqa: BLE001 + pass + try: + download = self.download_plan() + except Exception: # noqa: BLE001 - a plan that cannot count the download still shows the rest + download = {"gb": None, "parts": [], "engine_missing": None, "own_files": bool(s.model_path), + "text": "How much would be downloaded could not be worked out here."} + title = row.title if row is not None else (f"{s.family} {s.model}" if s.model else None) + model = {"title": title, "family": s.family, "model": s.model, "model_gb": row.download_gb if row is not None else None, + "own_files": bool(s.model_path), "folder": s.model_path} return {"profile": self.profile, "settings": s.to_dict(with_key=False), "warnings": warns, - "flags": S.flags_text(s), "steps": list(STAGES)} + "flags": S.flags_text(s), "steps": list(STAGES), "model": model, "download": download} def run(self, *, start: bool = True) -> Result: try: diff --git a/strata_cli/launch/settings.py b/strata_cli/launch/settings.py index 8079fb16..26588879 100644 --- a/strata_cli/launch/settings.py +++ b/strata_cli/launch/settings.py @@ -270,7 +270,7 @@ def flags_text(s: LaunchSettings, *, preset: str | None = None) -> str: else: if s.model_path: parts.append(f'--model-path "{s.model_path}"') - elif s.model: + if s.model: # own files the table recognised say which model they are, so the line stays exact parts.append(f"--model {s.model.lower()}" + (f" --family {s.family}" if s.family and s.family != "qwen" else "")) if s.data_dir: parts.append(f'--data-dir "{s.data_dir}"') diff --git a/tests/terminal/test_flow2_022.py b/tests/terminal/test_flow2_022.py index 45bd8170..067a2aa3 100644 --- a/tests/terminal/test_flow2_022.py +++ b/tests/terminal/test_flow2_022.py @@ -156,5 +156,61 @@ class LinkedShards(Base): +class PlanWords(Base): + """Findings 1 and 7: --plan shows the real model, the picture setting, a copyable line, and what would be downloaded.""" + + def plan_text(self, *args): + code, out, err = run_cli(["launch", "--plan", *args]) + self.assertEqual(code, 0, err or out) + return out + + def test_own_files_show_the_model_they_are(self): + folder = self.files(self.base / "IQ3_XXS", IQ3XXS, "IQ3_XXS") + out = self.plan_text("--model-path", str(folder)) + self.assertIn("Plan for 'IQ3_XXS", out) + self.assertNotIn("model default", out) + self.assertNotIn("None", out) + self.assertIn("Qwen3.8-Flash-Next IQ3_XXS", out) + self.assertIn(f"your files in {folder}", out) + self.assertRegex(out, r"pictures (on|off)") + self.assertIn("--model iq3_xxs", out.split("same as")[1]) # the copyable line names the model too + self.assertIn(f'--model-path "{folder}"', out.split("same as")[1]) + + def test_a_named_catalog_model_shows_its_size_and_the_download(self): + out = self.plan_text("--model", "q2_0") + self.assertIn("Qwen3.8-Flash-Next Q2_0, 66 GB", out) + self.assertRegex(out, r"download\s+About 7\d\.\d GB to download: the model \(66\.4 GB\), the draft layer \(5\.2 GB\)") + self.assertIn("The engine for your graphics card is downloaded first", out) + + def test_nothing_is_downloaded_when_everything_is_here(self): + folder = self.files(self.base / "IQ3_XXS", IQ3XXS, "IQ3_XXS") + data = self.base / "Strata" + (data / "models" / "x").mkdir(parents=True) + (data / "mtp" / "rt").mkdir(parents=True) + (data / "mtp" / "rt" / "experts.bin").write_bytes(b"x") + (data / "models" / "mmproj-Qwen3.8-Flash-Next-BF16.gguf").write_bytes(b"x") + # the files sit under /models/: the draft layer and the picture reader are found beside them + moved = data / "models" / "iq3_xxs" + folder.rename(moved) + out = self.plan_text("--model-path", str(moved)) + self.assertIn("download Nothing to download: your model files are used where they are.", out) + + def test_own_files_with_no_draft_layer_say_what_is_fetched(self): + folder = self.files(self.base / "IQ3_XXS", IQ3XXS, "IQ3_XXS") + with mock.patch.object(Runner, "existing_data_dir", return_value=None), mock.patch.object(Catalog, "data_dir", return_value=self.base / "emptydata"): + out = self.plan_text("--model-path", str(folder), "--vision", "off") + self.assertIn("About 5.2 GB to download: the draft layer (5.2 GB). Your model files are used where they are.", out) + + def test_json_plan_carries_the_numbers(self): + code, out, err = run_cli(["launch", "--plan", "--output", "json", "--model", "q2_0", "--mtp", "off", "--vision", "off"]) + self.assertEqual(code, 0, err) + plan = json.loads(out)["plan"] + self.assertEqual(plan["model"]["title"], "Qwen3.8-Flash-Next Q2_0") + self.assertEqual(plan["model"]["model_gb"], 66.4) + self.assertEqual(plan["download"]["gb"], 66.4) + self.assertEqual([p["kind"] for p in plan["download"]["parts"]], ["weights"]) + + + if __name__ == "__main__": unittest.main() From 0dbea601a02054b985790bc24884073cef6d430b Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Tue, 20 Oct 2026 15:56:33 +0200 Subject: [PATCH 38/47] Download label: the total counts every shard and the picture reader, in the data folder setup is given (--data-dir), not the first shard only --- strata_cli/launch/runner.py | 25 ++++++++++++++++++--- tests/terminal/test_flow2_022.py | 37 ++++++++++++++++++++++++++++++++ 2 files changed, 59 insertions(+), 3 deletions(-) diff --git a/strata_cli/launch/runner.py b/strata_cli/launch/runner.py index ba20a5ea..f24801ea 100644 --- a/strata_cli/launch/runner.py +++ b/strata_cli/launch/runner.py @@ -624,6 +624,26 @@ class Runner: """(title, text) of the question before a download starts, naming exactly what is fetched.""" return self.model_state().question() + def progress_job(self) -> dict: + """What the download figure is counted over: the folder setup writes the model into (the data folder it is GIVEN, which may be the + person's --data-dir and not the default one) and every file of the install with the catalog's total, so a model in several shards + shows 'of 66.4 GB' from the start and not the size of the file being fetched.""" + s, cat = self.s, self.catalog + data = Path(s.data_dir) if s.data_dir else (self.existing_data_dir() or cat.data_dir()) + models_dir = data / "models" + job = {"folder": str(models_dir / cat.tag_of(s.family, s.model)), + "total_gb": float(next((r.download_gb for r in cat.rows() if r.family == s.family and r.model == s.model), 0) or 0)} + try: + setup_module = cat.strata.setup_module() + if setup_module is not None and not s.model_path: + job["files"] = cat.mcp.expected_files(setup_module, str(s.family), str(s.model), models_dir, self.vision_word() != "no") + first = next((f for f in job["files"] if f.get("role") == "model"), None) + if first: # the folder setup names it (Q2_0), not the lower-case run-config tag (q2_0) + job["folder"] = str(Path(first["path"]).parent) + except Exception: # noqa: BLE001 - progress is a convenience; the folder scan still counts + pass + return job + def ensure_model(self) -> Path: s, cat = self.s, self.catalog self.check_own_files() @@ -657,8 +677,7 @@ class Runner: p = self._spawn(argv, env=env, cwd=str(cat.src)) lines: list[str] = [] already: bool | None = None # all the model's files were on disk before this run wrote anything - folder = str(cat.data_dir() / "models" / cat.tag_of(s.family, s.model)) - total = float(next((r.download_gb for r in cat.rows() if r.family == s.family and r.model == s.model), 0) or 0) + job = self.progress_job() for line in p.stdout: # type: ignore[union-attr] if self.cancel.is_set(): self._stop_children() @@ -669,7 +688,7 @@ class Runner: lines.append(line) lines[:] = lines[-1500:] prog = cat.mcp.install_progress(lines) - prog = cat.mcp.combined_progress(prog, {"folder": folder, "total_gb": total}) + prog = cat.mcp.combined_progress(prog, job) dl, phase, label = prog.get("download"), prog.get("phase"), prog.get("label") if dl and dl.get("total_gb", 0) >= 0.05 and not (s.model_path and phase == "download"): if phase == "download" and already is None: diff --git a/tests/terminal/test_flow2_022.py b/tests/terminal/test_flow2_022.py index 067a2aa3..9e773565 100644 --- a/tests/terminal/test_flow2_022.py +++ b/tests/terminal/test_flow2_022.py @@ -212,5 +212,42 @@ class PlanWords(Base): +class DownloadTotal(Base): + """Finding 4: the figure counts every shard (and the picture reader), in the folder the setup is really given.""" + + def run_lines(self, runner: Runner, lines: list[str]) -> list[str]: + seen: list[str] = [] + runner.emit_cb = lambda ev: seen.append(ev.text) + proc = mock.Mock() + proc.stdout = iter(lines) + proc.wait.return_value = 1 # stop after the lines: the failure path is not what is looked at + with mock.patch.object(Runner, "_spawn", return_value=proc), mock.patch.object(Runner, "adopt_prepared_files", return_value=None): + with self.assertRaises(LaunchError): + runner.ensure_model() + return seen + + def test_the_total_is_the_whole_model_in_the_chosen_data_folder(self): + data = self.base / "mydata" + folder = data / "models" / "Q2_0" + folder.mkdir(parents=True) + first = folder / (Q2[0] + ".part") + first.write_bytes(bytes(100_000_000)) + r = self.runner(family="qwen", model="Q2_0", data_dir=str(data), vision="on", context=32768) + job = r.progress_job() + self.assertEqual(Path(job["folder"]), folder) + self.assertEqual(len(job["files"]), 3) # two shards and the picture reader + seen = self.run_lines(r, ["=== Step 5: Getting the model files ===", f"{Q2[0]}: 0.10 / 37.60 GB (0%)"]) + text = [x for x in seen if "GB" in x] + self.assertTrue(text, seen) + self.assertIn("of 67.3 GB", text[-1]) # 66.4 GB of shards + 0.9 GB picture reader + self.assertNotIn("37.6", " ".join(text)) + + def test_the_default_data_folder_is_used_when_none_was_chosen(self): + r = self.runner(family="qwen", model="Q2_0", vision="off", context=32768) + self.assertEqual(Path(r.progress_job()["folder"]).parts[-2:], ("models", "Q2_0")) + self.assertEqual(len(r.progress_job()["files"]), 2) + + + if __name__ == "__main__": unittest.main() From 5dc151d4d33ee9abb6deb6add733501c04442840 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Tue, 20 Oct 2026 15:58:11 +0200 Subject: [PATCH 39/47] launch: setup step 6 (packing, converting) is no longer silent - the plain sentence for what it does is shown and a 'still working, N min so far' line comes every 30 s of silence; a cancel is seen at once --- strata_cli/launch/runner.py | 50 +++++++++++++++++++++++++++++- tests/terminal/test_flow2_022.py | 52 ++++++++++++++++++++++++++++++++ 2 files changed, 101 insertions(+), 1 deletion(-) diff --git a/strata_cli/launch/runner.py b/strata_cli/launch/runner.py index f24801ea..c51f0967 100644 --- a/strata_cli/launch/runner.py +++ b/strata_cli/launch/runner.py @@ -310,6 +310,15 @@ def download_text(dl: dict, already: bool, label: str | None = None) -> str: return f"{label}: {dl['done_gb']:.1f} of {dl['total_gb']:.1f} GB" if label else f"Downloading {dl['done_gb']:.1f} of {dl['total_gb']:.1f} GB" +_END = object() + + +def _elapsed(seconds: float) -> str: + """'40 s', '3 min' (plain, rounded down).""" + seconds = int(seconds) + return f"{seconds} s" if seconds < 90 else f"{seconds // 60} min" + + class Runner: def __init__(self, s: S.LaunchSettings, *, catalog: Catalog | None = None, emit: Callable[[Event], None] | None = None, cancel: threading.Event | None = None, feed: str | None = None, python: str | None = None, @@ -624,6 +633,32 @@ class Runner: """(title, text) of the question before a download starts, naming exactly what is fetched.""" return self.model_state().question() + #: seconds of silence from setup before a "still working" line (packing a 40 GB model prints nothing for minutes) + HEARTBEAT_S = 30.0 + + def _read_lines(self, p: subprocess.Popen): + """The lines setup prints, and None whenever a second passes with none, so a silent step can say it is still going and a cancel is + seen at once.""" + import queue + q: queue.Queue = queue.Queue() + + def pump() -> None: + try: + for ln in p.stdout: # type: ignore[union-attr] + q.put(ln) + finally: + q.put(_END) + threading.Thread(target=pump, daemon=True).start() + while True: + try: + ln = q.get(timeout=min(1.0, max(0.05, self.HEARTBEAT_S / 2))) + except queue.Empty: + yield None + continue + if ln is _END: + return + yield ln + def progress_job(self) -> dict: """What the download figure is counted over: the folder setup writes the model into (the data folder it is GIVEN, which may be the person's --data-dir and not the default one) and every file of the install with the catalog's total, so a model in several shards @@ -678,10 +713,17 @@ class Runner: lines: list[str] = [] already: bool | None = None # all the model's files were on disk before this run wrote anything job = self.progress_job() - for line in p.stdout: # type: ignore[union-attr] + step_seen, step_since, quiet_since, said = None, time.monotonic(), time.monotonic(), None + for line in self._read_lines(p): if self.cancel.is_set(): self._stop_children() raise Cancelled() + if line is None: # nothing printed for a while: the long steps (packing, converting) are silent + if said and said[1] != "download" and time.monotonic() - quiet_since >= self.HEARTBEAT_S: + quiet_since = time.monotonic() + self.emit("model", f"{said[0]} (still working, {_elapsed(time.monotonic() - step_since)} so far)", None, step=step_seen) + continue + quiet_since = time.monotonic() line = line.rstrip() if not line: continue @@ -690,6 +732,12 @@ class Runner: 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") + if prog.get("step") != step_seen: + step_seen, step_since = prog.get("step"), time.monotonic() + if label and not dl: + said = (label, phase) + else: + said = None if dl and dl.get("total_gb", 0) >= 0.05 and not (s.model_path and phase == "download"): if phase == "download" and already is None: already = float(dl["percent"]) >= 99.5 diff --git a/tests/terminal/test_flow2_022.py b/tests/terminal/test_flow2_022.py index 9e773565..2cd8c38f 100644 --- a/tests/terminal/test_flow2_022.py +++ b/tests/terminal/test_flow2_022.py @@ -249,5 +249,57 @@ class DownloadTotal(Base): +class QuietStep(Base): + """Finding 5: setup step 6 (packing) prints nothing for minutes: the person sees the plain sentence and a 'still working' line.""" + + def slow(self, steps): + import time + for delay, line in steps: + time.sleep(delay) + yield line + "\n" + + def run_steps(self, steps, heartbeat=0.3): + r = self.runner(family="qwen", model="Q2_0", vision="off", context=32768) + r.HEARTBEAT_S = heartbeat + seen = [] + r.emit_cb = lambda ev: seen.append(ev.text) + proc = mock.Mock() + proc.stdout = self.slow(steps) + proc.wait.return_value = 1 + with mock.patch.object(Runner, "_spawn", return_value=proc), mock.patch.object(Runner, "adopt_prepared_files", return_value=None): + with self.assertRaises(LaunchError): + r.ensure_model() + return seen + + def test_a_silent_pack_step_says_what_it_does_and_that_it_is_still_going(self): + seen = self.run_steps([(0, "=== Step 5: Getting the model files ==="), (0, "all model files present"), + (0, "=== Step 6: Preparing the model for Strata ==="), + (0, "> python tools/iq_pack.py --gguf x --out y --experts-bin"), (1.6, "[X] stopped for the test")]) + pack = [x for x in seen if x.startswith("Packing the experts into one file")] + self.assertTrue(pack, seen) + self.assertEqual(pack[0], "Packing the experts into one file for low-memory mode (one time)") + beats = [x for x in pack if "still working" in x] + self.assertGreaterEqual(len(beats), 2, seen) # a line every interval of silence + self.assertNotIn("Setup step 6", " ".join(seen)) + + def test_no_heartbeat_while_lines_keep_coming(self): + seen = self.run_steps([(0, "=== Step 6: Preparing the model for Strata ==="), (0, "> python tools/iq_pack.py --gguf x --out y --experts-bin")] + + [(0.1, f" layer {i}") for i in range(5)] + [(0, "[X] stopped")], heartbeat=2.0) + self.assertFalse([x for x in seen if "still working" in x]) + + def test_the_plain_printer_shows_each_heartbeat(self): + import io + from strata_cli.launch import cmd + from strata_cli.launch.runner import Event + buf = io.StringIO() + with mock.patch.object(cmd.sys, "stdout", buf): + emit = cmd._printer() + emit(Event("model", "Packing (still working, 30 s so far)")) + emit(Event("model", "Packing (still working, 60 s so far)")) + emit(Event("model", "Packing (still working, 60 s so far)")) + self.assertEqual(buf.getvalue().count("still working"), 2) + + + if __name__ == "__main__": unittest.main() From 176e11a597b2beb14ba2b63a12a4b38fe530646c Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Tue, 20 Oct 2026 16:02:35 +0200 Subject: [PATCH 40/47] launch: a run by flags reuses the tuning result stored for the same model, choices and computer and says so; --retune measures again --- docs/TERMINAL_LAUNCH.md | 2 +- strata_cli/launch/app.py | 7 +-- strata_cli/launch/cmd.py | 10 +++- strata_cli/launch/runner.py | 45 ++++++++++++++---- tests/terminal/test_flow2_022.py | 82 ++++++++++++++++++++++++++++++++ 5 files changed, 130 insertions(+), 16 deletions(-) diff --git a/docs/TERMINAL_LAUNCH.md b/docs/TERMINAL_LAUNCH.md index 80549729..23444e1d 100644 --- a/docs/TERMINAL_LAUNCH.md +++ b/docs/TERMINAL_LAUNCH.md @@ -70,7 +70,7 @@ strata launch --list-presets | --delete-preset NAME | --status | --stop [--prese `strata launch --help` lists everything with examples. An unknown model or flag gets a plain message with the closest match. Presets are small files in `launch-presets/` beside the profiles folder; the run uses the shared profile `launch-` and the shared tuning presets (`strata presets`), so the app sees them too. Flags next to `--preset` change that start only -(add `--save-preset` to keep them). +(add `--save-preset` to keep them). `--plan` shows the model (also for your own files, which it recognises), the context, the picture setting and what would be downloaded and how big (0 when everything is already here). A model that was tuned before for the same choices on the same computer is not measured again by `--tune quick`; the stored result is used and the run says so. Add `--retune` to measure again. ## Connect your apps: `strata connect` diff --git a/strata_cli/launch/app.py b/strata_cli/launch/app.py index b0a8500a..8a327b95 100644 --- a/strata_cli/launch/app.py +++ b/strata_cli/launch/app.py @@ -43,6 +43,7 @@ class Ctx: glyphs: Glyphs = field(default_factory=Glyphs) feed: str | None = None move_data: bool = False + retune: bool = False notes: list[str] = field(default_factory=list) start_own_files: bool = False picked_in_list: bool = False @@ -263,7 +264,7 @@ class LaunchApp(App): s = self.ctx.settings self.cancel = threading.Event() self.runner = Runner(s, catalog=self.ctx.catalog, emit=self._emit, cancel=self.cancel, feed=self.ctx.feed, confirm=self._ask_from_run, - move_data=self.ctx.move_data) + move_data=self.ctx.move_data, retune=self.ctx.retune) gb = getattr(self.runner, "download_gb", lambda: 0.0)() if not confirmed else 0.0 if gb >= 1.0: free = self.ctx.catalog.disk_free(s.data_dir or self.ctx.catalog.data_dir()) @@ -404,7 +405,7 @@ def run_monitor(info: dict, *, keep_default: bool = True, color: str = "auto") - def run_tui(settings: S.LaunchSettings | None, *, catalog: Catalog | None = None, feed: str | None = None, auto_run: bool = False, - save: bool = False, open_page: bool = False, move_data: bool = False) -> int: + save: bool = False, open_page: bool = False, move_data: bool = False, retune: bool = False) -> int: """Open the launch screens. `settings` given and `auto_run`: skip the questions and go straight to the run.""" catalog = catalog or Catalog() print("Looking at this computer…", flush=True) @@ -419,7 +420,7 @@ def run_tui(settings: S.LaunchSettings | None, *, catalog: Catalog | None = None s.name = f"{s.model or 'model'} {S.context_label(s.context)}" if save: store.save(s, s.name) - ctx = Ctx(catalog=catalog, computer=computer, rows=rows, settings=s, glyphs=Glyphs(), feed=feed, move_data=move_data) + ctx = Ctx(catalog=catalog, computer=computer, rows=rows, settings=s, glyphs=Glyphs(), feed=feed, move_data=move_data, retune=retune) app = LaunchApp(ctx, auto_run=auto_run) result = app.run() if getattr(app, "return_code", 0) not in (0, None) or getattr(app, "_exception", None) is not None: diff --git a/strata_cli/launch/cmd.py b/strata_cli/launch/cmd.py index 477d43b9..62807cf7 100644 --- a/strata_cli/launch/cmd.py +++ b/strata_cli/launch/cmd.py @@ -113,6 +113,9 @@ def add_parsers(sp: argparse._SubParsersAction) -> list[argparse.ArgumentParser] a.add_argument("--no-api-key", action="store_true", help="share beyond this computer without an API key (a warning is shown, nothing is refused)") o = p.add_argument_group("running") o.add_argument("--save-preset", metavar="NAME", help="save these choices under this name") + o.add_argument("--retune", action="store_true", + help="with --tune (quick is used when --tune is not given): measure again even when this model was already tuned on this computer " + "(by default a stored tuning result is reused and no measuring is done)") o.add_argument("--no-tui", action="store_true", help="no screens: serve, print the address and return") o.add_argument("--open", action="store_true", help="open the server's web page in your browser once it is serving (nothing opens a browser without this)") o.add_argument("--yes", action="store_true", help="do not ask questions (for one: whether to download the model on a computer with no engine yet)") @@ -562,7 +565,10 @@ def run_launch(a: argparse.Namespace) -> int: return _tui(app.run_tui, None, catalog=catalog, feed=a.feed, open_page=bool(a.open)) if catalog is None: return fail("This Terminal does not carry the model list. Install it again with the one-line installer.", 5) - runner = Runner(s, catalog=catalog, emit=_printer(machine), feed=a.feed, assume_yes=bool(a.yes or machine), confirm=_ask_yes) + if getattr(a, "retune", False) and s.tune == "skip": + s.tune = "quick" + runner = Runner(s, catalog=catalog, emit=_printer(machine), feed=a.feed, assume_yes=bool(a.yes or machine), confirm=_ask_yes, + retune=bool(getattr(a, "retune", False))) try: runner.check_own_files() # the person's own files: a wrong path is said now, and the files name the model except LaunchError as e: @@ -618,7 +624,7 @@ def run_launch(a: argparse.Namespace) -> int: if interactive and have_choices: from strata_cli.launch import app return _tui(app.run_tui, s, catalog=catalog, feed=a.feed, auto_run=True, save=bool(a.save_preset), open_page=bool(a.open), - move_data=move_data) + move_data=move_data, retune=bool(getattr(a, "retune", False))) try: result = runner.run() except LaunchError as e: diff --git a/strata_cli/launch/runner.py b/strata_cli/launch/runner.py index c51f0967..078ccc9f 100644 --- a/strata_cli/launch/runner.py +++ b/strata_cli/launch/runner.py @@ -323,8 +323,10 @@ class Runner: def __init__(self, s: S.LaunchSettings, *, catalog: Catalog | None = None, emit: Callable[[Event], None] | None = None, cancel: threading.Event | None = None, feed: str | None = None, python: str | None = None, components_dir: str | None = None, hardware: dict | None = None, - confirm: Callable[[str, str], bool] | None = None, assume_yes: bool = False, move_data: bool = False): + confirm: Callable[[str, str], bool] | None = None, assume_yes: bool = False, move_data: bool = False, + retune: bool = False): self.s = s + self.retune = retune # --retune: measure again even when a tuning result for this model on this computer is stored self.move_data = move_data # --move-data / the answer "move": the model files already here go to the new --data-dir self.confirm = confirm # asked (title, text) before a model is downloaded with no engine; True = go on self.assume_yes = assume_yes # --yes: no questions @@ -890,16 +892,23 @@ class Runner: if s.tune == "skip": return from strata_control import presets - if s.tuned_preset: - try: - presets.find(s.tuned_preset) - self.emit("tune", "This preset is already tuned for this computer.", 100) + if not self.retune: + if s.tuned_preset: + try: + presets.find(s.tuned_preset) + self.emit("tune", "This preset is already tuned for this computer.", 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) + return + stored = self.stored_tuning() + if stored: # the same model and choices were tuned on this computer before (a run by flags, no preset) + s.tuned_preset, s.tuned_at = stored["id"], stored["date"] + self.emit("tune", f"This model was already tuned for this computer on {stored['date']} ('{stored['name']}'), so that result is used " + "and nothing is measured again. 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) - return mode = "thorough" if s.tune == "thorough" else "quick" status_file = launch_dir() / f"{self.name}.tune.json" try: @@ -945,6 +954,22 @@ class Runner: s.tuned_at = time.strftime("%Y-%m-%d") self.emit("tune", f"Tuning result: {word}. {sentence}", 100, level="info" if word in ("faster", "already fastest") else "warn", word=word) + def stored_tuning(self) -> dict | None: + """The tuning result stored for this launch's model, choices and computer (the active preset of its slot in the shared presets store, + which the start applies), or None. A result whose computer changed in a way that matters (a different card, processor or memory, + another model file) is not reused: it is measured again.""" + if self.config_path is None: + return None + from strata_control import presets + try: + _cfg, info = presets.overlay(read_config(self.config_path)) + if not info.get("applied") or not info.get("preset"): + return None + made = str(presets.load(info["preset"]["id"]).get("created") or "")[:10] + return {"id": info["preset"]["id"], "name": info["preset"]["name"], "date": made or time.strftime("%Y-%m-%d")} + except Exception: # noqa: BLE001 - an unreadable store means: measure + return None + tune_word: str | None = None # ---- 5. start diff --git a/tests/terminal/test_flow2_022.py b/tests/terminal/test_flow2_022.py index 2cd8c38f..5a6d2f31 100644 --- a/tests/terminal/test_flow2_022.py +++ b/tests/terminal/test_flow2_022.py @@ -301,5 +301,87 @@ class QuietStep(Base): +class StoredTuning(Base): + """Finding 6: a run by flags (no saved preset) reuses the tuning result stored for the same model, choices and computer.""" + + IDENT = {"hardware": {"hard": {"gpus": ["RTX 5070"], "cpu": "test", "logical": 16, "ram_gib": 64}, "soft": {}}, + "engine": {"backend": "cuda"}, "model": {"sha256_shard1": "abc"}} + + def setUp(self): + super().setUp() + from strata_control import presets + self.presets = presets + self.cfg_path = self.base / "launch.json" + self.cfg = {"args": ["--native", "x/model-00001-of-00002.gguf", "--max-context", "32768", "--kv", "int8"], "model_name": "qwen"} + self.cfg_path.write_text(json.dumps(self.cfg), encoding="utf-8") + self.ident = json.loads(json.dumps(self.IDENT)) + p = mock.patch.object(presets, "current_identity", lambda cfg, **kw: self.ident) + p.start() + self.addCleanup(p.stop) + + def store(self): + return self.presets.create({"settings": {"args": {}, "env": {}, "per_request": {}}, "outcome": "improved"}, + choices=self.presets.choices_from_config(self.cfg), identity=self.ident, name="Q2 32K - Full speed") + + def runner_for_tune(self, retune=False): + r = self.runner(family="qwen", model="Q2_0", tune="quick") + r.retune = retune + r.config_path = self.cfg_path + return r + + def run_tune(self, r): + seen = [] + r.emit_cb = lambda ev: seen.append(ev.text) + with mock.patch.object(Runner, "_spawn", side_effect=RuntimeError("the tuner started")) as spawn: + try: + r.tune() + started = False + except RuntimeError: + started = True + return seen, started + + def test_nothing_stored_means_it_is_measured(self): + seen, started = self.run_tune(self.runner_for_tune()) + self.assertTrue(started) + + def test_a_stored_result_is_used_and_said(self): + saved = self.store() + r = self.runner_for_tune() + seen, started = self.run_tune(r) + self.assertFalse(started) + text = seen[-1] + self.assertIn("already tuned for this computer", text) + self.assertIn("Q2 32K - Full speed", text) + self.assertIn("--retune", text) + self.assertEqual(r.s.tuned_preset, saved["id"]) + self.assertTrue(r.s.is_tuned) + + def test_retune_measures_again(self): + self.store() + seen, started = self.run_tune(self.runner_for_tune(retune=True)) + self.assertTrue(started) + + def test_another_context_is_another_result(self): + self.store() + self.cfg["args"][3] = "65536" + self.cfg_path.write_text(json.dumps(self.cfg), encoding="utf-8") + seen, started = self.run_tune(self.runner_for_tune()) + self.assertTrue(started) + + def test_a_changed_graphics_card_is_measured_again(self): + self.store() + self.ident["hardware"]["hard"]["gpus"] = ["RTX 4090"] + seen, started = self.run_tune(self.runner_for_tune()) + self.assertTrue(started) + + def test_the_flag_asks_for_a_new_measurement_and_implies_quick(self): + code, out, err = run_cli(["launch", "--plan", "--output", "json", "--model", "q2_0", "--retune"]) + self.assertEqual(code, 0, err) + self.assertEqual(json.loads(out)["plan"]["settings"]["tune"], "quick") + code, out, err = run_cli(["launch", "--help"]) + self.assertIn("--retune", out) + + + if __name__ == "__main__": unittest.main() From ae456dfe5ccc4bccadc150c6cfce7fc8345da106 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Tue, 20 Oct 2026 16:03:23 +0200 Subject: [PATCH 41/47] iq_pack: an interrupted experts.bin write continues at the next layer (finished layers are flushed and recorded, the last kept one is checked against the GGUF) instead of starting from zero; says so --- tools/iq_pack.py | 36 ++++++++++++++++- tools/test_iq_pack.py | 89 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 123 insertions(+), 2 deletions(-) diff --git a/tools/iq_pack.py b/tools/iq_pack.py index b48af1aa..b33723a0 100644 --- a/tools/iq_pack.py +++ b/tools/iq_pack.py @@ -731,16 +731,48 @@ def main() -> int: # experts.bin, and an experts.bin without its sidecar is never reused sidecar.unlink(missing_ok=True) part = out / "experts.bin.tmp" - with open(part, "wb") as fo: - for l, gt, dt, off, blob, ts in layout: + progress = out / "experts.bin.tmp.json" + # A stop part-way (a kill, a power cut) used to cost the whole write again (40 GB, minutes). The finished layers are kept: + # after every layer the file is flushed to disk and experts.bin.tmp.json says how many layers are in it and which source they were + # cut from. The next run continues at that layer when the source is the same and the last kept layer still matches the GGUF. + start = 0 + if part.exists(): + done = read_json(progress) + k = done.get("layers") if isinstance(done, dict) and done.get("want") == want else None + if isinstance(k, int) and 0 < k <= len(layout) and part.stat().st_size >= (layout[k][3] if k < len(layout) else offset): + l, gt, dt, off, blob, ts = layout[k - 1] + last = layer_blobs(l, blob, ts) + if last is not None: + with open(part, "rb") as f: + f.seek(off) + kept = f.read(n_expert * blob) + if kept == last.tobytes(): + start = k + if start: + print("the earlier packing was interrupted: keeping its first %d of %d layers and continuing with layer %d" + % (start, len(layout), start), flush=True) + else: + print("the earlier packing was interrupted and cannot be continued: starting it again", flush=True) + resume_at = layout[start][3] if start < len(layout) else offset + with open(part, "r+b" if start else "wb") as fo: + if start: + fo.truncate(resume_at) # whatever followed the last recorded layer is a partial write + fo.seek(resume_at) + for l, gt, dt, off, blob, ts in layout[start:]: chunk = layer_blobs(l, blob, ts) if chunk is None: return 1 fo.write(chunk.tobytes()) + fo.flush() + os.fsync(fo.fileno()) + note = out / "experts.bin.tmp.json.new" + note.write_text(json.dumps({"want": want, "layers": l + 1}), encoding="utf-8") + note.replace(progress) if l % 8 == 0: print(" layer %2d %-8s/%-7s blob %8d at %.2f GiB" % (l, ts[0].type_name, ts[2].type_name, blob, off / 2**30), flush=True) part.replace(path) + progress.unlink(missing_ok=True) side_tmp = out / "experts.bin.src.json.tmp" side_tmp.write_text(json.dumps(want, indent=2) + "\n", encoding="utf-8") side_tmp.replace(sidecar) diff --git a/tools/test_iq_pack.py b/tools/test_iq_pack.py index 580bf274..0e0f5e8b 100644 --- a/tools/test_iq_pack.py +++ b/tools/test_iq_pack.py @@ -515,6 +515,95 @@ class SplitArtifactTests(unittest.TestCase): self.assertEqual(rc, 0, log) self.assertEqual((pack / "experts.bin").read_bytes(), expected_experts(iq_pack.Model(paths[0]))) + def test_interrupted_pack_continues_at_the_next_layer(self): + with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp: + root = Path(tmp) + paths = split_model(root) + pack = root / "pack" + real = np.concatenate + calls = [] + + def dies_on_layer_1(parts, axis): + calls.append(1) + if len(calls) == 2: + raise KeyboardInterrupt("killed") + return real(parts, axis=axis) + with patch.object(iq_pack.np, "concatenate", dies_on_layer_1): + with self.assertRaises(KeyboardInterrupt): + run_pack(paths[0], pack, "--experts-bin") + want = expected_experts(iq_pack.Model(paths[0])) + lines = [ln.split() for ln in (pack / "native_experts.txt").read_text().splitlines() if ln and not ln.startswith("#")] + one_layer = int(lines[1][3]) # where layer 1 starts + self.assertFalse((pack / "experts.bin").exists()) + self.assertEqual((pack / "experts.bin.tmp").stat().st_size, one_layer) # layer 0 is on disk + self.assertEqual(json.loads((pack / "experts.bin.tmp.json").read_text())["layers"], 1) + # a partial write after the recorded layer (the kill came mid-write) is cut off + with open(pack / "experts.bin.tmp", "ab") as f: + f.write(b"garbage") + written = [] + real_layer = iq_pack.np.concatenate + + def counting(parts, axis): + written.append(1) + return real_layer(parts, axis=axis) + with patch.object(iq_pack.np, "concatenate", counting): + rc, log = run_pack(paths[0], pack, "--experts-bin") + self.assertEqual(rc, 0, log) + self.assertIn("keeping its first 1 of 2 layers and continuing with layer 1", log) + self.assertEqual((pack / "experts.bin").read_bytes(), want) + self.assertEqual(len(written), 2) # one layer re-read to check the kept one, one layer written + self.assertFalse((pack / "experts.bin.tmp").exists()) + self.assertFalse((pack / "experts.bin.tmp.json").exists()) + self.assertEqual(json.loads((pack / "experts.bin.src.json").read_text())["bytes"], len(want)) + + def test_interrupted_pack_of_another_model_is_not_continued(self): + with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp: + root = Path(tmp) + (root / "a").mkdir() + (root / "b").mkdir() + other = split_model(root / "a", name="other", seed=100) + paths = split_model(root / "b") + pack = root / "pack" + real = np.concatenate + calls = [] + + def dies_on_layer_1(parts, axis): + calls.append(1) + if len(calls) == 2: + raise KeyboardInterrupt("killed") + return real(parts, axis=axis) + with patch.object(iq_pack.np, "concatenate", dies_on_layer_1): + with self.assertRaises(KeyboardInterrupt): + run_pack(other[0], pack, "--experts-bin") + rc, log = run_pack(paths[0], pack, "--experts-bin") # the same geometry, other weights + self.assertEqual(rc, 0, log) + self.assertIn("cannot be continued: starting it again", log) + self.assertEqual((pack / "experts.bin").read_bytes(), expected_experts(iq_pack.Model(paths[0]))) + + def test_a_kept_layer_that_no_longer_matches_is_not_trusted(self): + with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp: + root = Path(tmp) + paths = split_model(root) + pack = root / "pack" + real = np.concatenate + calls = [] + + def dies_on_layer_1(parts, axis): + calls.append(1) + if len(calls) == 2: + raise KeyboardInterrupt("killed") + return real(parts, axis=axis) + with patch.object(iq_pack.np, "concatenate", dies_on_layer_1): + with self.assertRaises(KeyboardInterrupt): + run_pack(paths[0], pack, "--experts-bin") + data = bytearray((pack / "experts.bin.tmp").read_bytes()) + data[0] ^= 0xFF # the disk lost a bit + (pack / "experts.bin.tmp").write_bytes(bytes(data)) + rc, log = run_pack(paths[0], pack, "--experts-bin") + self.assertEqual(rc, 0, log) + self.assertIn("cannot be continued", log) + self.assertEqual((pack / "experts.bin").read_bytes(), expected_experts(iq_pack.Model(paths[0]))) + def test_stale_same_size_experts_bin(self): with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp: root = Path(tmp) From 79cb59c574e87dbe0c67175a214701012a1623ea Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Tue, 20 Oct 2026 16:08:13 +0200 Subject: [PATCH 42/47] Updater tests reset a signature verifier left behind by an earlier test file --- tests/terminal/test_updater.py | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/terminal/test_updater.py b/tests/terminal/test_updater.py index 29f77922..f8b6747c 100644 --- a/tests/terminal/test_updater.py +++ b/tests/terminal/test_updater.py @@ -48,6 +48,7 @@ class UpdaterCase(unittest.TestCase): patch = mock.patch.object(target, value, return_value=["sm_86"] if value == "cuda_archs_present" else "610.47") patch.start() self.addCleanup(patch.stop) + ec.register_signature_verifier(None) # a verifier an earlier test file left behind (it holds the shipped keys only) must not decide here self.addCleanup(ec.register_signature_verifier, None) # the tests sign with throwaway keys that they hand over explicitly: the release key shipped in update_keys.json is not in play here # (ReleaseKeys below checks the shipped file itself) From dcbaa992d27fb7b29bdda8695d656e11fd98f726 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Tue, 20 Oct 2026 16:35:12 +0200 Subject: [PATCH 43/47] launch --plan: a part that is already on disk is not listed as a download, and a draft layer or picture reader found in the data folder is not counted --- strata_cli/launch/runner.py | 20 ++++++++------------ tests/terminal/test_flow2_022.py | 13 +++++++++++++ 2 files changed, 21 insertions(+), 12 deletions(-) diff --git a/strata_cli/launch/runner.py b/strata_cli/launch/runner.py index 078ccc9f..d8c22364 100644 --- a/strata_cli/launch/runner.py +++ b/strata_cli/launch/runner.py @@ -1049,24 +1049,20 @@ class Runner: from strata_control.discovery import MMPROJ_GB, MTP_FETCH_GB s = self.s st = self.model_state() - parts = [{"kind": p.kind, "label": p.label, "gb": round(p.gb, 1)} for p in st.parts] - fresh = any(p.kind == "weights" for p in st.parts) and not st.own_files + parts = [{"kind": p.kind, "label": p.label, "gb": round(p.gb, 1)} for p in st.parts if p.gb >= 0.05] # a part already on disk is not a download row = self.row() helpers = s.family in ("qwen", "swift", "coder", "unsloth") wants_pictures = s.vision not in (None, "off") and row is not None and bool(row.images) - have = {p["kind"] for p in parts} - if fresh and helpers: - if s.mtp != "off": - parts.append({"kind": "mtp", "label": "the draft layer", "gb": MTP_FETCH_GB}) - if wants_pictures: - parts.append({"kind": "mmproj", "label": "the picture reader", "gb": MMPROJ_GB}) - elif st.own_files and helpers: - # the person's files come with no draft layer or picture reader: setup fetches them next to the prepared data, unless they are there + if helpers and (st.own_files or not st.installed): + # a model that is not set up yet (or the person's own files) comes without the draft layer and the picture reader: setup fetches them + # next to the prepared data, unless they are there already + have = {p["kind"] for p in parts} try: - data = Path(st.folder) if st.folder else (self.existing_data_dir() or self.catalog.data_dir()) + data = Path(st.folder) if st.folder else (Path(s.data_dir) if s.data_dir else (self.existing_data_dir() or self.catalog.data_dir())) if s.mtp != "off" and "mtp" not in have and not (data / "mtp" / "rt" / "experts.bin").is_file(): parts.append({"kind": "mtp", "label": "the draft layer", "gb": MTP_FETCH_GB}) - if wants_pictures and "mmproj" not in have and not list((data / "models").glob("mmproj*.gguf")): + has_reader = list((data / "models").glob("mmproj*.gguf")) or list((data / "Models").glob("mmproj*.gguf")) + if wants_pictures and "mmproj" not in have and not has_reader: parts.append({"kind": "mmproj", "label": "the picture reader", "gb": MMPROJ_GB}) except OSError: pass diff --git a/tests/terminal/test_flow2_022.py b/tests/terminal/test_flow2_022.py index 5a6d2f31..fec09536 100644 --- a/tests/terminal/test_flow2_022.py +++ b/tests/terminal/test_flow2_022.py @@ -201,6 +201,19 @@ class PlanWords(Base): out = self.plan_text("--model-path", str(folder), "--vision", "off") self.assertIn("About 5.2 GB to download: the draft layer (5.2 GB). Your model files are used where they are.", out) + def test_a_model_whose_files_are_all_on_disk_does_not_list_a_zero_download(self): + from strata_cli.launch.modelstate import ModelState, Part + data = self.base / "d" + (data / "mtp" / "rt").mkdir(parents=True) + (data / "mtp" / "rt" / "experts.bin").write_bytes(b"x") + whole = ModelState(installed=False, parts=[Part("weights", "the model", 0.0)], on_disk_gb=66.4, total_gb=66.4) + with mock.patch.object(Runner, "model_state", return_value=whole): + out = self.plan_text("--model", "q2_0", "--data-dir", str(data), "--vision", "off") + self.assertIn("download Nothing to download: the model is already on this computer.", out) + out = self.plan_text("--model", "q2_0", "--data-dir", str(self.base / "other"), "--vision", "off") + self.assertIn("About 5.2 GB to download: the draft layer (5.2 GB). 66 GB of the model is already in its folder.", out) + self.assertNotIn("0.0 GB", out) + def test_json_plan_carries_the_numbers(self): code, out, err = run_cli(["launch", "--plan", "--output", "json", "--model", "q2_0", "--mtp", "off", "--vision", "off"]) self.assertEqual(code, 0, err) From 9e24f4ab3204065dd0d0e0e24b54c0656d3621ee Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Tue, 20 Oct 2026 17:01:22 +0200 Subject: [PATCH 44/47] Control 0.1.46.2: version bump for the Terminal/Control-only update (engine packages unchanged) --- CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index df8a7d5a..e0e30c6f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -8,7 +8,7 @@ # below refuses anything older: silently building for a pre-Ampere arch would produce a binary that runs # and is wrong about its own performance, which is the worst of both outcomes. cmake_minimum_required(VERSION 3.24) -project(strata VERSION 0.1.46.1 LANGUAGES CXX) +project(strata VERSION 0.1.46.2 LANGUAGES CXX) # EXPERIMENTAL: the Intel Arc engine, the SYCL port in sycl/ (PR #423; icpx + oneMKL, docs/INTEL_ARC.md). It is its # own project that takes the unported sources from src/; with this on, nothing below is configured. option(STRATA_ENABLE_SYCL "EXPERIMENTAL: build the Intel Arc (SYCL) engine from sycl/ - docs/INTEL_ARC.md" OFF) From f5c4047e7881f7d6dded0c1a13d49dbb0150277f Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Tue, 20 Oct 2026 16:58:14 +0200 Subject: [PATCH 45/47] Test: the unsloth setup tests answer every disk-space question themselves --- tools/test_setup_unsloth.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/tools/test_setup_unsloth.py b/tools/test_setup_unsloth.py index c14b9ed8..1fc97070 100644 --- a/tools/test_setup_unsloth.py +++ b/tools/test_setup_unsloth.py @@ -11,6 +11,7 @@ import contextlib import hashlib import io import json +import shutil import sys import tempfile import types @@ -186,6 +187,8 @@ class Base(unittest.TestCase): mock.patch.object(setup, "cpu_cores", lambda: None), # #642: not a hybrid CPU mock.patch.object(setup, "page_file_gb", lambda: 16.0), mock.patch.object(setup, "free_gb", lambda p: free), + # whatever else asks the disk (shutil.disk_usage) gets the same answer: the tests never depend on this PC's free space + mock.patch.object(shutil, "disk_usage", lambda p: shutil._ntuple_diskusage(int(max(free, 1000) * 1e9), int(max(free, 1000) * 1e9 - free * 1e9), int(free * 1e9))), mock.patch.object(setup, "rotational_disk", lambda p: None), # #605: not the test PC's disk mock.patch.object(setup, "is_wsl", lambda: False), # #974: the tests are not run inside WSL mock.patch.object(setup, "pip_install", lambda *a, **k: None), From 5db632e72ade6d04adfbfd92102e25de0c4fd600 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Tue, 20 Oct 2026 16:58:31 +0200 Subject: [PATCH 46/47] Test: engine minimums are checked against the tree's CMake version, not a fixed 0.1.45 --- tools/test_setup_menu.py | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/tools/test_setup_menu.py b/tools/test_setup_menu.py index 1f176836..284f7703 100644 --- a/tools/test_setup_menu.py +++ b/tools/test_setup_menu.py @@ -6,6 +6,7 @@ install removing a stale strata_kq library. """ from __future__ import annotations +import re import sys import tempfile import unittest @@ -155,7 +156,12 @@ class EnginePlaceholders(unittest.TestCase): self.assertEqual(setup.MIN_ENGINE, (0, 1, 45)) for m in ("UD-Q5_K_XL", "UD-Q6_K_XL", "NVFP4", "NVFP4-NVIDIA"): self.assertEqual(setup.MODELS[m]["engine"], (0, 1, 44), m) - self.assertIn("0.1.45", (ROOT / "CMakeLists.txt").read_text(encoding="utf-8").split("project(strata VERSION", 1)[1][:12]) + # No minimum may name an engine newer than this tree (a placeholder for a release that does not exist yet would make setup + # ask for an engine nobody can download). The tree's version is read from CMakeLists.txt, so this does not go stale each release. + text = (ROOT / "CMakeLists.txt").read_text(encoding="utf-8") + tree = tuple(int(n) for n in re.search(r"project\(strata VERSION ([0-9.]+)", text).group(1).split(".")) + for what, minimum in [("MIN_ENGINE", setup.MIN_ENGINE), ("NVFP4_ENGINE", setup.NVFP4_ENGINE)] + [(m, setup.MODELS[m]["engine"]) for m in setup.MODELS if "engine" in setup.MODELS[m]]: + self.assertLessEqual(tuple(minimum), tree[:len(minimum)], f"{what} {minimum} is ahead of the tree {tree}") class KqLibrary(unittest.TestCase): From 5b47f889b0f52f1b7b9cc4b0994193b85f4664b6 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Tue, 20 Oct 2026 17:17:45 +0200 Subject: [PATCH 47/47] Test: the calibrate setup test's data_folder stand-in takes the extra arguments --- tools/test_calibrate.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/test_calibrate.py b/tools/test_calibrate.py index defa9432..97e33597 100644 --- a/tools/test_calibrate.py +++ b/tools/test_calibrate.py @@ -442,7 +442,7 @@ class SetupIntegration(unittest.TestCase): self.assertNotIn("an earlier start", out.getvalue()) out = io.StringIO() with mock.patch.object(self.S, "ROOT", Path(self.tmp.name)), \ - mock.patch.object(self.S, "data_folder", lambda d: (Path(self.tmp.name) / "data", [])), \ + mock.patch.object(self.S, "data_folder", lambda d, *a, **k: (Path(self.tmp.name) / "data", [])), \ mock.patch.object(self.S, "update_installed_engine", lambda *a: None), \ mock.patch.object(sys, "argv", ["setup.py", "--calibrate", "--no-start"]), \ contextlib.redirect_stdout(out):