diff --git a/packaging/locks/runtime-darwin-arm64-cp312.txt b/packaging/locks/runtime-darwin-arm64-cp312.txt index 6fd1b931..4094cd88 100644 --- a/packaging/locks/runtime-darwin-arm64-cp312.txt +++ b/packaging/locks/runtime-darwin-arm64-cp312.txt @@ -2,8 +2,8 @@ # Made by packaging/lock_wheels.py from requirements.txt + requirements-monitor.txt; installed at BUILD time with # pip install --require-hashes --no-deps --only-binary=:all: -r # and never on the user's PC. To change a package: edit requirements.txt, run lock_wheels.py, review the diff. -certifi==2026.7.22 \ - --hash=sha256:62f22742b58a1a33014a2b6b706588a8d7e2a88ae7bd1a6ebe8c992928483775 +certifi==2026.10.19 \ + --hash=sha256:42d35340cc5b9ba78e818ddbff0c5b1c2b779de448a340fd1b989f5fa8670e1b charset-normalizer==3.5.1 \ --hash=sha256:5b6d1386bf0096d26d3a863dc0a487a5b4eb9aa93cf5ba69683d29dde6b9d60f idna==3.20 \ diff --git a/packaging/locks/runtime-linux-x86_64-cp312.txt b/packaging/locks/runtime-linux-x86_64-cp312.txt index d2637ec1..a2014bfd 100644 --- a/packaging/locks/runtime-linux-x86_64-cp312.txt +++ b/packaging/locks/runtime-linux-x86_64-cp312.txt @@ -2,8 +2,8 @@ # Made by packaging/lock_wheels.py from requirements.txt + requirements-monitor.txt; installed at BUILD time with # pip install --require-hashes --no-deps --only-binary=:all: -r # and never on the user's PC. To change a package: edit requirements.txt, run lock_wheels.py, review the diff. -certifi==2026.7.22 \ - --hash=sha256:62f22742b58a1a33014a2b6b706588a8d7e2a88ae7bd1a6ebe8c992928483775 +certifi==2026.10.19 \ + --hash=sha256:42d35340cc5b9ba78e818ddbff0c5b1c2b779de448a340fd1b989f5fa8670e1b charset-normalizer==3.5.1 \ --hash=sha256:b9af956078716df40d985fb0dfeb2c2120c5ca92ba4ff4b388acfd01cdc14d08 idna==3.20 \ diff --git a/packaging/locks/runtime-windows-x86_64-cp312.txt b/packaging/locks/runtime-windows-x86_64-cp312.txt index 90e68f67..8d82608d 100644 --- a/packaging/locks/runtime-windows-x86_64-cp312.txt +++ b/packaging/locks/runtime-windows-x86_64-cp312.txt @@ -2,8 +2,8 @@ # Made by packaging/lock_wheels.py from requirements.txt + requirements-monitor.txt; installed at BUILD time with # pip install --require-hashes --no-deps --only-binary=:all: -r # and never on the user's PC. To change a package: edit requirements.txt, run lock_wheels.py, review the diff. -certifi==2026.7.22 \ - --hash=sha256:62f22742b58a1a33014a2b6b706588a8d7e2a88ae7bd1a6ebe8c992928483775 +certifi==2026.10.19 \ + --hash=sha256:42d35340cc5b9ba78e818ddbff0c5b1c2b779de448a340fd1b989f5fa8670e1b charset-normalizer==3.5.1 \ --hash=sha256:3617ac3cfd8b9888f145ad89dd6e692285834b0201c6074a5eeaad3fd4d668c2 colorama==0.4.6 \ diff --git a/packaging/package_terminal.py b/packaging/package_terminal.py index 41005f36..e546e4db 100644 --- a/packaging/package_terminal.py +++ b/packaging/package_terminal.py @@ -115,8 +115,11 @@ TOOLS_SUBSET = ( #: (STRATA_CONTROL_INSTALL=1: no pip, no engine fetch, no compiler). Entry points; their local imports under tools/ come with them. #: The same list the app's Control component stages (apps/desktop/scripts/stage-control.py uses these names). INSTALLER_FILES = ("setup.py", "ref/load.py") # ref/load.py: strata_pack.py (the Q2_0 AVX-512 repack) imports it +#: calibrate: setup.py imports it after a tune (calibrate_config, and the earlier tuning that a rerun applies); it was missing from this +#: list in 0.1.47, so every launch after a tune failed (#3613, #3467). setup_tool_imports() below also reads setup.py itself, so a tools/ +#: module it starts to import is never forgotten again; tests/terminal/test_bundle_imports.py checks the staged bundle. INSTALLER_TOOLS = ("strata_mcp", "iq_pack", "strata_pack", "pack_index", "mtp_fetch", "mtp_pack", "mtp_rt", "draft_vocab", - "strata_tokenizer", "gguf_reader") + "strata_tokenizer", "gguf_reader", "calibrate") INSTALLER_DATA = "data" # draft vocabularies, expert profiles: 2 MB #: packages the bundle must import after the install (the API server's and the CLI's). @@ -247,9 +250,22 @@ def local_imports(folder: Path, entry: tuple[str, ...]) -> list[str]: return sorted(seen) +def setup_tool_imports(source: Path = ROOT) -> list[str]: + """The `tools/.py` modules that the installer files import (any import statement, at any depth: setup.py imports most of them + inside functions after putting tools/ on sys.path). tools/hip and tools/image hold engine-install code that Control's mode never runs.""" + import ast + found: set[str] = set() + for name in INSTALLER_FILES: + for node in ast.walk(ast.parse((source / name).read_text(encoding="utf-8-sig"))): + names = [a.name.split(".")[0] for a in node.names] if isinstance(node, ast.Import) else \ + [node.module.split(".")[0]] if isinstance(node, ast.ImportFrom) and node.module and node.level == 0 else [] + found.update(m for m in names if (source / "tools" / f"{m}.py").exists()) + return sorted(found) + + def add_installer(folder: Path, source: Path = ROOT) -> dict: """Copy the installer's files from the source tree into a staged terminal folder (after the terminal payload is in place).""" - tools = local_imports(source, INSTALLER_TOOLS) + tools = local_imports(source, tuple(sorted(set(INSTALLER_TOOLS) | set(setup_tool_imports(source))))) copied = [] for name in INSTALLER_FILES: (folder / name).parent.mkdir(parents=True, exist_ok=True) diff --git a/requirements.txt b/requirements.txt index b6f4d38b..19a0ce8d 100644 --- a/requirements.txt +++ b/requirements.txt @@ -15,7 +15,7 @@ psutil==7.2.2 # their dependencies markupsafe==3.0.3 -certifi==2026.7.22 +certifi==2026.10.19 charset-normalizer==3.5.1 idna==3.20 urllib3==2.8.0 diff --git a/setup.py b/setup.py index 8358380b..bf800d3c 100644 --- a/setup.py +++ b/setup.py @@ -7429,7 +7429,7 @@ def install_own_path(a, family, gpu, hip, amd, cuda_tk, multi, port, ram, adopte 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") + fail(f"not enough free disk space in {folder}: need ~{left:.0f} GB, {free_gb(folder):.0f} GB free", ("use --data-dir on a bigger drive (strata launch --data-dir)" if CONTROL else "use --models-dir on a bigger drive")) if left and free_gb(folder) < left + 1: 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") @@ -7576,7 +7576,7 @@ def preview_family(a) -> int: 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") + fail(f"not enough free disk space in {folder}: need ~{left:.0f} GB, {free_gb(folder):.0f} GB free", ("use --data-dir on a bigger drive (strata launch --data-dir)" if CONTROL else "use --models-dir on a bigger drive")) if left and free_gb(folder) < left + 1: 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}") @@ -7752,6 +7752,9 @@ def mac_control_setup(a) -> int: ok("the experts stream from the SSD: no MTP draft layer (one token per step is faster there)") elif stream: ok(f"the experts stream from the SSD; the MTP draft layer stays on, with --spec {MF.STREAM_SPEC}") + if use_mtp and a.mtp == "off" and not (mtp / "mtp-q2_0.gguf").exists(): + ok("the draft layer (MTP) is off: its ~5 GB are not downloaded (`--mtp on` fetches it later)") # round 8, N3 + use_mtp = False if use_mtp and not (mtp / "mtp-q2_0.gguf").exists(): say(" The MTP draft layer (speculative decoding) comes from the original Qwen checkpoint: only its ~5 GB of MTP tensors are downloaded.") fetch_mtp(mtp, env) @@ -8609,7 +8612,7 @@ def main() -> int: 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") + ("use --data-dir on a bigger drive (strata launch --data-dir)" if CONTROL 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") @@ -8740,7 +8743,9 @@ def main() -> int: if corrupt: warn("some MTP tensors are not the checkpoint's (a download mirror that ignored range requests, #327): " "fetching them again and rebuilding the draft layer") - if corrupt or not (rt / "experts.bin").exists(): + if a.mtp == "off" and not (rt / "experts.bin").exists(): + ok("the draft layer (MTP) is off: its ~5 GB are not downloaded (`--mtp on` fetches it later)") # round 8, N3 + elif corrupt or not (rt / "experts.bin").exists(): say(" The MTP draft layer (speculative decoding, ~2x faster output) comes from the original Qwen checkpoint:") say(" only its ~5 GB of MTP tensors are downloaded.") fetch_mtp(mtp, env) @@ -8750,8 +8755,9 @@ def main() -> int: env=env) # a setup run again without --draft-vocab keeps the subset this model's config chose before (cyrillic, fr, en) draft_vocab = a.draft_vocab or saved_draft_vocab(home() / f"strata-{tag.lower()}.json") - refresh_draft_vocab(rt, draft_vocab or "cjk") - ok(f"MTP draft layer: {rt}") + if (rt / "experts.bin").exists(): + refresh_draft_vocab(rt, draft_vocab or "cjk") + ok(f"MTP draft layer: {rt}") for line in draft_vocab_note(gpu.get("vram_gb", 0.0), draft_vocab): # #474: a recommendation, nothing changes say(" " + line) diff --git a/strata_cli/launch/adopt.py b/strata_cli/launch/adopt.py index 83529fe2..8c01a3c7 100644 --- a/strata_cli/launch/adopt.py +++ b/strata_cli/launch/adopt.py @@ -5,7 +5,7 @@ that this Terminal does not run. When setup says it cannot set this card up, and prepared before, "use model files I already have"), the run config is simple enough to write here: the same arguments setup writes for the GSQ-RCO models, with the engine named as the component (`component:strata-engine`). Nothing is downloaded, prepared or compiled; if a file is missing the person is told which. -Only the GSQ-RCO families (qwen, swift, coder) are adopted this way; images stay off. +Only the GSQ-RCO families (qwen, swift, coder) and Gyro (one GGUF with its n-gram table inside) are adopted this way; images stay off. """ from __future__ import annotations @@ -15,7 +15,7 @@ import re from pathlib import Path SHARD = re.compile(r"^(?P.+)-(?P\d{5})-of-(?P\d{5})\.gguf$") -FAMILIES = ("qwen", "swift", "coder") +FAMILIES = ("qwen", "swift", "coder", "gyro") # the catalog offers Gyro-S / Gyro-M on an Arc card too (round 8, N11) UNSUPPORTED = ("no nvidia gpu found", "no amd gpu", "nvidia gpu", "not supported", "cannot be used") @@ -52,16 +52,25 @@ def find_shards(folder: Path) -> list[Path]: return [] +def find_single(folder: Path) -> list[Path]: + """The one model file of a Gyro folder (a single GGUF, not a picture reader); [] when there is none or several.""" + files = [p for p in sorted(Path(folder).glob("*.gguf")) if not p.name.lower().startswith("mmproj")] + return files if len(files) == 1 else [] + + def plan(*, family: str, model: str, model_dir: Path, data_dir: Path, src: Path, context: int, kv: str | None, model_name: str, family_def: dict, - log: Path, backend: str | None, vram_gb: float = 0.0, notes: list | None = None) -> tuple[dict | None, list[str]]: - """(config, problems): the config to write, or None with plain-words problems (what is missing).""" + log: Path, backend: str | None, vram_gb: float = 0.0, notes: list | None = None, pack_name: str | None = None) -> tuple[dict | None, list[str]]: + """(config, problems): the config to write, or None with plain-words problems (what is missing). `pack_name`: the pack folder under + packs/ (default the model's name in lower case; Gyro's is its tag, gyro-gyro-s).""" problems: list[str] = [] if family not in FAMILIES: - return None, [f"Strata can write the settings itself only for the Qwen3.8-Flash-Next, Swift and Coder files, not for {family}."] - shards = find_shards(model_dir) + # no full stop: the caller joins the problems with "; " and ends the sentence (a "gyro.." came out of the old text, round 8, N11) + return None, [f"Strata can write the settings itself only for the Qwen3.8-Flash-Next, Swift, Coder and Gyro files, not for {family}"] + shards = find_single(model_dir) if family == "gyro" else find_shards(model_dir) if not shards: - problems.append(f"the model files are not all in {model_dir} (every -0000N-of-0000N.gguf shard is needed)") - pack = Path(data_dir) / "packs" / model.lower() + problems.append(f"the model file is not in {model_dir}" if family == "gyro" else + f"the model files are not all in {model_dir} (every -0000N-of-0000N.gguf shard is needed)") + pack = Path(data_dir) / "packs" / (pack_name or model.lower()) if not (pack / "experts.bin").exists() and not (pack / "index.txt").exists(): problems.append(f"the prepared pack {pack} is missing (this installer cannot prepare it for this graphics card)") tokenizer = pack / "tokenizer" @@ -74,7 +83,7 @@ def plan(*, family: str, model: str, model_dir: Path, data_dir: Path, src: Path, return None, problems mtp = Path(data_dir) / "mtp" / "rt" args = ["--pack", str(pack), "--native", str(shards[0])] - if len(shards) > 1: + if len(shards) > 1 or family == "gyro": # Gyro's one file holds the n-gram table too args += ["--ple-gguf", str(shards[-1])] if backend == "metal": # a Mac: the Metal defaults metal/setup_mac.py writes for a model that streams from the SSD (one token per step, no draft layer, the GGUF mapped in place) diff --git a/strata_cli/launch/cmd.py b/strata_cli/launch/cmd.py index 18e88b68..fd3f5c94 100644 --- a/strata_cli/launch/cmd.py +++ b/strata_cli/launch/cmd.py @@ -465,7 +465,15 @@ def _move_data_choice(a: argparse.Namespace, s: S.LaunchSettings, catalog, machi gb = library.movable_library(catalog.data_dir(), Path(a.data_dir).expanduser()) except Exception: # noqa: BLE001 - no answer to "where are my models": nothing to ask about return False - return library.ask_move(gb, Path(a.data_dir).expanduser()) if gb > 0 else False + if gb <= 0: + return False + new = Path(a.data_dir).expanduser() + if getattr(a, "no_tui", False) or not sys.stdin.isatty(): + # --no-tui and a run without a keyboard never ask (round 8, M): the default that loses nothing, said out loud + size = f"{gb:.0f} GB" if gb >= 10 else f"{gb:.1f} GB" + _say(f"Keeping your {size} of models where they are; {new} is used for new downloads. (--move-data moves them instead.)") + return False + return library.ask_move(gb, new) def open_page(url: str) -> bool: @@ -615,8 +623,8 @@ def run_launch(a: argparse.Namespace) -> int: 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: - 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 " + if machine or a.no_tui or catalog is None or not _can_ask(): # --no-tui never asks (round 8, M) + return fail("`strata launch` with no choices opens screens, and this is not a terminal (or --no-tui was given). 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 diff --git a/strata_cli/launch/modelstate.py b/strata_cli/launch/modelstate.py index fc4729da..1afd01b7 100644 --- a/strata_cli/launch/modelstate.py +++ b/strata_cli/launch/modelstate.py @@ -91,7 +91,8 @@ def mmproj_name(catalog, family: str | None) -> str: def assess(catalog, family: str | None, model: str | None, *, vision: str = "off", model_path: str | None = None, - data_dir: str | Path | None = None, config: Path | None = None, desc: dict | None = None, rows: list | None = None) -> ModelState: + data_dir: str | Path | None = None, config: Path | None = None, desc: dict | None = None, rows: list | None = None, + mtp: str | None = None) -> ModelState: """The state of `family model` for these choices. `config` / `desc` are the installed run config and its description (looked up when not given).""" st = ModelState() @@ -104,7 +105,7 @@ def assess(catalog, family: str | None, model: str | None, *, vision: str = "off first = _first_gguf(Path(model_path)) beside = discovery.prepared_beside(first) if first else {} st.folder = beside.get("data_dir") - if beside.get("pack") is not None and beside.get("mtp") is None: + if beside.get("pack") is not None and beside.get("mtp") is None and mtp != "off": st.parts.append(Part("mtp", "the draft layer", MTP_FETCH_GB)) if wants_pictures and beside.get("pack") is not None and not beside.get("mmproj"): st.parts.append(Part("mmproj", "the picture reader", MMPROJ_GB)) @@ -128,7 +129,7 @@ def assess(catalog, family: str | None, model: str | None, *, vision: str = "off st.parts.append(Part("weights", "the model", max(st.total_gb, 0.0))) return st for m in fp.missing(): - if m.kind == "mtp": + if m.kind == "mtp" and mtp != "off": st.parts.append(Part("mtp", "the draft layer", MTP_FETCH_GB)) elif m.kind == "mmproj" and wants_pictures: st.parts.append(Part("mmproj", "the picture reader", MMPROJ_GB)) diff --git a/strata_cli/launch/runner.py b/strata_cli/launch/runner.py index e318f567..2eadcce9 100644 --- a/strata_cli/launch/runner.py +++ b/strata_cli/launch/runner.py @@ -34,6 +34,52 @@ ROOT = Path(__file__).resolve().parents[2] WINDOWS = os.name == "nt" +def install_isolation_words(catalog, data_dir: str | os.PathLike | None = None) -> list[str]: + """Round 8, N5: a clean test (a scratch data folder) silently ran an OLDER install found elsewhere (its run config and engine 0.1.41). + When a data folder was chosen (--data-dir, or STRATA_DATA_DIR from the installer) and the install in use is outside it, say which one is used + and why. Nothing is moved or switched.""" + chosen = data_dir or os.environ.get("STRATA_DATA_DIR") + places = getattr(catalog, "places", None) or [] + if not chosen or not places or places[0].source == "explicit": + return [] + main = Path(places[0].path) + try: + inside = os.path.commonpath([os.path.abspath(main), os.path.abspath(chosen)]) == os.path.abspath(chosen) + except ValueError: + inside = False + if inside: + return [] + return [f"Strata is using the earlier install in {main} ({places[0].configs} saved model setting(s) and its engine settings), not a clean one in " + f"{chosen}: the data folder only says where model files are kept. To test from scratch, use a new user account or remove the earlier install first."] + + +#: the first engine whose Metal build reads Gyro files (round 8, M: 0.1.45.3 was reused and failed on missing TQK6/TQK7 kernels) +GYRO_METAL_ENGINE = (0, 1, 47) + + +def version_tuple(version: str | None) -> tuple[int, ...]: + """'0.1.45.3' -> (0, 1, 45, 3); () when it is not a dotted run of numbers (a source build says so itself).""" + m = re.match(r"\d+(?:\.\d+)*", str(version or "").strip()) + return tuple(int(x) for x in m.group(0).split(".")) if m else () + + +def python_failure(lines: list[str]) -> str | None: + """The last line of a Python traceback in setup.py's output (ModuleNotFoundError: No module named 'calibrate'), or None when the + output holds no traceback. Frames are skipped; the exception line is the first unindented line after the last 'Traceback'.""" + for i in range(len(lines) - 1, -1, -1): + if lines[i].startswith("Traceback (most recent call last)"): + for line in lines[i + 1:]: + if line.strip() and not line[:1].isspace(): + return line.strip()[:300] + return None + return None + + +def missing_file(failure: str) -> bool: + """An import or file error: the install itself is short of a file, which an update of Strata brings back.""" + return failure.startswith(("ModuleNotFoundError", "ImportError", "FileNotFoundError")) + + class LaunchError(RuntimeError): """A step could not be done. `text` says what it means; `next` says what to do.""" @@ -42,6 +88,23 @@ class LaunchError(RuntimeError): self.text, self.next, self.code = text, next, code +def setup_failure(lines: list[str], err: str, hint: str, details: str | None, own_files: bool) -> LaunchError: + """The error for a setup.py run that exited non-zero. setup.py's own `[X]` line (err) is the message when there is one; when it + stopped with a Python error instead, that error's last line is (#3613, #3467: a file missing from the Terminal's tools/ ended every + launch after a tune with only "The model could not be installed"). `details` is the file that holds the rest of its output.""" + crashed = python_failure(lines) if not err else None + if crashed: + where = f" The whole setup output is in {details}." if details else "" + if missing_file(crashed): + return LaunchError(f"The model could not be installed. A file that setup needs is missing from this Strata install ({crashed}).", + "Update Strata (`strata update`) and run it again." + where, 6) + return LaunchError(f"The model could not be installed. Setup stopped with an error ({crashed}).", "Run it again." + where, 6) + return LaunchError("The model could not be installed." + (f" {err}." if err else ""), + (hint or ("Run it again: finished steps are skipped." if own_files else + "Run it again: finished steps are skipped and a download continues where it stopped.")) + + (f" Details: {details}" if details else ""), 6) + + class Cancelled(LaunchError): def __init__(self): super().__init__("Stopped. Nothing was changed on your computer beyond files already downloaded.", "", 130) @@ -384,6 +447,7 @@ class Runner: self.hardware_override = hardware self.children: list[subprocess.Popen] = [] self.notices: list[str] = [] + self.identity_notes: list[str] = [] self.tune_result: dict | None = None self.config_path: Path | None = None self._own_checked = False @@ -449,12 +513,18 @@ class Runner: from strata_control import engine_component as ec root = Path(self.components_dir) if self.components_dir else None report = ec.status(root) + stale = None if report.get("usable"): eng = report["engine"] - self.emit("engine", f"Engine {eng['version']} ({eng['backend']}) is installed.", 100) - return + stale = self.stale_engine(eng.get("version")) + if not stale: + self.emit("engine", f"Engine {eng['version']} ({eng['backend']}) is installed.", 100) + return feed = self.feed or os.environ.get("STRATA_UPDATE_FEED") - self.emit("engine", "No engine is installed yet. Getting the one for your graphics card…", 0) + if stale: + self.emit("engine", stale + " Looking for a newer one…", 0, level="warn") + else: + self.emit("engine", "No engine is installed yet. Getting the one for your graphics card…", 0) argv = self._cli("update", "--no-control", "--output", "jsonl") if feed: argv += ["--feed", feed] @@ -486,6 +556,19 @@ class Runner: self.emit("engine", str(ev.get("message") or "")) last = ev code = p.wait() + if stale: + # an engine is there and was too old: warn, never refuse (round 8, M: 0.1.45.3 was reused although 0.1.47 existed, and Gyro-S failed + # on kernels only the newer engine has). Whatever the update did, say where it stands. + after = ec.status(root) + now = (after.get("engine") or {}).get("version") if after.get("usable") else None + still = self.stale_engine(now) if now else stale + if still: + self.notices.append(still + " Run `strata update`, then start it again.") + self.emit("engine", still + (" The update did not bring a newer one." if code == 0 else " The update did not finish.") + + " Run `strata update`, then start it again.", 100, level="warn") + else: + self.emit("engine", f"Engine {now} is installed.", 100) + return if code == 0: # `strata update` exits 0 when the feed simply has no engine for this PC (or only one for another card family). That is not an # engine: refuse here, before the model (tens of GB) is touched. @@ -507,6 +590,27 @@ class Runner: "Check your internet connection, or point Strata at an update source with --feed, then try again.", 6) self.emit("engine", "The engine is installed.", 100) + def needed_engine(self) -> tuple[int, ...] | None: + """The oldest engine this model runs on, from setup.py's own tables (MIN_ENGINE for everything, GYRO_ENGINE for Gyro), or None.""" + try: + mod = self.catalog.strata.setup_module() + need = tuple(getattr(mod, "MIN_ENGINE", ()) or ()) + if self.s.family == "gyro": + need = max(need, tuple(getattr(mod, "GYRO_ENGINE", ()) or ())) + if sys.platform == "darwin": + need = max(need, GYRO_METAL_ENGINE) # the Metal Gyro kernels (TQK6/TQK7/TQ2_T) first shipped in 0.1.47; CUDA, HIP, SYCL had them earlier + return need or None + except Exception: # noqa: BLE001 - no table, no check + return None + + def stale_engine(self, version: str | None) -> str | None: + """A plain sentence when the installed engine is older than the model needs, else None.""" + have = version_tuple(version) + need = self.needed_engine() + if not have or not need or have >= need: + return None + return f"The engine installed here ({version}) is older than this model needs ({'.'.join(map(str, need))} or newer)." + def no_engine(self, reason: str) -> None: """There is no engine for this computer and none to get. This is a warning, not a refusal: the model may still be downloaded, because the engine can be installed afterwards. Ask first (the answer is yes unless the person says no; --yes skips the question) when a @@ -593,6 +697,8 @@ class Runner: args += ["--kv", s.kv] if fam in ("qwen", "coder"): args += ["--experimental-speed-projection", "off"] + if s.mtp in ("on", "off") and fam in ("qwen", "swift", "coder", "unsloth"): + args += ["--mtp", s.mtp] # round 8, N3: "--mtp off" never reached setup, which then fetched the 5.2 GB draft layer data = s.data_dir or self.existing_data_dir() if data: args += ["--data-dir", str(data)] @@ -607,6 +713,8 @@ class Runner: args += ["--gpu-roles", ",".join(f"{k}={v}" for k, v in sorted(s.gpu_roles.items(), key=lambda kv: int(kv[0])))] elif s.gpus: args += ["--gpus", ",".join(str(g) for g in s.gpus)] if len(s.gpus) > 1 else ["--gpu", str(s.gpus[0])] + else: + args += self.installed_card_args() 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", @@ -624,6 +732,25 @@ class Runner: args = out return args + def installed_card_args(self) -> list[str]: + """--gpu-roles / --gpus of the installed config when the launch names no cards itself. A change of context or pictures runs setup again; + without these it picked the cards and the Main/Helper roles afresh and reset an explicit choice (round 8, F3: 0=main,1=helper + came back as 0=helper,1=main). Only a choice that was made ("gpus_asked" / roles) is forwarded, never the automatic pick.""" + try: + path, _desc = self.installed_state() + base = read_config(path) if path is not None else None + if not isinstance(base, dict): + return [] + roles = base.get("gpu_roles") + if isinstance(roles, dict) and roles: + return ["--gpu-roles", ",".join(f"{k}={v}" for k, v in sorted(roles.items(), key=lambda kv: int(kv[0])))] + cards = installed_cards(base) + if cards: + return ["--gpus", ",".join(str(g) for g in cards)] if len(cards) > 1 else ["--gpu", str(cards[0])] + except Exception: # noqa: BLE001 - never block a launch over remembering the cards + pass + return [] + def installed_state(self) -> tuple[Path | None, dict | None]: tag = self.catalog.tag_of(self.s.family, self.s.model) path = self.catalog.installed_config(tag) @@ -664,7 +791,7 @@ class Runner: if s.family and s.model and not s.model_path: path, desc = self.installed_state() return modelstate.assess(self.catalog, s.family, s.model, vision=s.vision, model_path=s.model_path, data_dir=s.data_dir, - config=path, desc=desc) + config=path, desc=desc, mtp=s.mtp) def download_gb(self) -> float: """How much would be downloaded for this launch right now: 0 when everything is on disk (the model is installed with these choices @@ -810,9 +937,7 @@ class Runner: adopted = self.adopt_prepared_files(err) 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." if s.model_path else - "Run it again: finished steps are skipped and a download continues where it stopped."), 6) + raise setup_failure(lines, err, hint, self.keep_setup_output(lines), bool(s.model_path)) path, _desc = self.installed_state() if path is None: raise LaunchError("Setup finished but no run config was written for this model.", @@ -821,6 +946,18 @@ class Runner: self.check_pictures(path) return path + def keep_setup_output(self, lines: list[str]) -> str | None: + """The last lines setup.py printed, kept next to the launch's other logs so a failed install can be read afterwards (the message + shows one line; a traceback needs the rest). Best effort: None when it cannot be written.""" + try: + folder = launch_dir() + folder.mkdir(parents=True, exist_ok=True) + path = folder / f"{self.name}.setup.log" + path.write_text("\n".join(lines[-400:]) + "\n", encoding="utf-8", errors="replace") + return str(path) + except (OSError, ValueError): + return None + def adopt_prepared_files(self, setup_error: str) -> Path | None: """The installer cannot set this graphics card up (Intel Arc, for one): if the model's files and prepared pack are already on disk, write the run config here (strata_cli/launch/adopt.py); else say what is missing.""" @@ -843,7 +980,7 @@ class Runner: cfg, problems = adopt.plan(family=s.family, model=s.model, model_dir=model_dir, data_dir=data_dir, src=cat.src, context=s.context or 32768, kv=s.kv, model_name=f"{fam.get('name', s.family)}-{s.model.lower()}", family_def=fam, log=cat.root / f"strata-{tag}.log", backend=backend, - vram_gb=float(cat.computer().main_vram_gb or 0), notes=self.notices) + vram_gb=float(cat.computer().main_vram_gb or 0), notes=self.notices, pack_name=tag.lower()) if cfg is None: raise LaunchError("The installer cannot set up this graphics card yet, and the files Strata would need to write the settings itself are not all there: " + "; ".join(problems) + ".", @@ -879,6 +1016,14 @@ class Runner: 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: + sel = plan.get("candidate_selection") or {} + if sel.get("family") and sel.get("model") and (sel["family"], sel["model"]) != (s.family, s.model): + # round 8, N8: --family swift was accepted for an IQ3_XXS file. The files are not refused (setup takes the named model's files + # out of the folder by name), but the person is told what the file header says. + words = (f"These files look like {sel['family']} {sel['model']} (by the file headers), not {s.family} {s.model}. " + f"Setup will look for {s.family} {s.model} files in that folder and may stop; to use these files, leave out --family and --model.") + self.identity_notes.append(words) + self.notices.append(words) 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"] @@ -1057,8 +1202,8 @@ class Runner: raise LaunchError(f"The server could not start: {box['e']}", _log_hint(self.config_path), 6) r = box["r"] if not r.get("ok"): - raise LaunchError(f"The server did not become ready ({r.get('state')}: {r.get('error') or r.get('message') or 'see the engine log'}).", - _log_hint(self.config_path), 6) + text, nxt = explain_engine_exit(r, self.config_path) + raise LaunchError(text, nxt, 6) self.emit("start", "The model is loaded and answering.", 100) # ---- 6. access @@ -1108,11 +1253,20 @@ class Runner: 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}) - has_reader = list((data / "models").glob("mmproj*.gguf")) or list((data / "Models").glob("mmproj*.gguf")) + places = [data / "models", data / "Models"] + if s.model_path: # setup uses a reader that sits with the person's own files (setup.py --gguf-dir) + own = Path(s.model_path) + places += [own if own.is_dir() else own.parent, (own if own.is_dir() else own.parent).parent] + has_reader = any(list(d.glob("mmproj*.gguf")) for d in places if d.is_dir()) 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 + gap = self.ready_pack_gap() if st.own_files else None + if gap: + # a ready-made pack (NVFP4) is taken from setup's own models folder, not from where the person's files are (round 8, N2: the plan + # said "nothing to download" and setup then asked for 129 GB): count what setup will fetch + parts = [p for p in parts if p["kind"] != "weights"] + [{"kind": "weights", "label": "the ready-made pack", "gb": gap["gb"]}] gb = round(sum(p["gb"] for p in parts), 1) engine = True try: @@ -1130,14 +1284,64 @@ class Runner: 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 gap: + text += (f" This is a ready-made pack, and setup takes it from its own folder ({gap['folder']}), not from where your files are. " + "Copy or link your pack there to use it as it is" + + (f"; only {gap['free_gb']:.0f} GB are free on that drive, so choose a bigger drive with --data-dir" if gap.get("free_gb") is not None and gap["free_gb"] < gap["gb"] else "") + ".") + if any(p["kind"] == "mmproj" for p in parts): + text += " To skip the picture reader (the model then answers text only), add --vision off; or put its mmproj file next to your model files." + if any(p["kind"] == "mtp" for p in parts): + text += " To skip the draft layer (a little slower, less memory), add --mtp off." 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 ready_pack_gap(self) -> dict | None: + """For a ready-made pack family (NVFP4): what setup would still fetch into its models folder for these choices, {gb, folder, free_gb}, or None.""" + s = self.s + try: + mod = self.catalog.strata.setup_module() + _m, families, _c, _src = self.catalog.tables() + if mod is None or not (families.get(s.family or "") or {}).get("ready") or not hasattr(mod, "ready_needed"): + return None + data = Path(s.data_dir) if s.data_dir else (self.existing_data_dir() or self.catalog.data_dir()) + models_dir = data / "models" + need = 0 + for f in mod.ready_needed(s.model, models_dir): + if not mod.ready_verified(mod.ready_where(models_dir, f), f[5]): + need += int(f[4]) + if need <= 0: + return None + probe = next((q for q in (models_dir, *models_dir.parents) if q.exists()), None) + free = self.catalog.disk_free(probe) if probe is not None else None + return {"gb": round(need / 1e9, 1), "folder": str(models_dir), "free_gb": free} + except Exception: # noqa: BLE001 - a plan that cannot work this out still shows the rest + return None + + def preflight_words(self) -> list[str]: + """Plain warnings for `--plan` that the run itself would meet: an engine older than the model needs, an earlier install taking the + place of a clean one, files that are not the model that was named. Nothing is changed.""" + out: list[str] = list(self.identity_notes) + try: + from strata_control import engine_component as ec + report = ec.status(Path(self.components_dir) if self.components_dir else None) + if report.get("usable"): + stale = self.stale_engine(report["engine"].get("version")) + if stale: + out.append(stale + " Starting will look for a newer one first; `strata update` does the same.") + except Exception: # noqa: BLE001 + pass + try: + out += install_isolation_words(self.catalog, self.s.data_dir) + except Exception: # noqa: BLE001 + pass + return out + def plan(self) -> dict: s = self.s self.check_own_files() warns = [n.line() for n in (*S.check_access(s),)] + warns += self.preflight_words() row = self.row() try: self.resolved_vision() @@ -1204,6 +1408,65 @@ def _read_json(path: Path) -> dict | None: return None +#: lines of an engine log that say why it stopped (the last one wins), and a plain next step for the causes we know. Recommend, never force. +CAUSE_LINE = re.compile(r"error|exception|failed|cannot|can't|could not|no device|not found|out of memory|unsupported|abort|invalid|missing|" + r"no kernel|illegal|denied|refus", re.I) +KNOWN_CAUSES = ( + (re.compile(r"no device of requested type|device not found|no (gpu|sycl|level.zero) device|permission denied.*(dri|render)", re.I), + "The engine could not open the graphics card. On Linux the account must be allowed to use it: add it to the render group " + "(`sudo usermod -aG render $USER`), log in again and start it again."), + (re.compile(r"out of memory|not enough (gpu |video |free )?memory|cudaerrormemory|allocation failed", re.I), + "The card or memory ran out. Close other programs that use the card, or choose a smaller context (`--context 16k`) and start again."), + (re.compile(r"tqk\d|no kernel|unsupported (quant|type|model)|unknown (quant|tensor) type", re.I), + "This engine is too old for this model. Update it with `strata update` and start again."), + (re.compile(r"dll|libcu|cannot open shared object|0xc0000135", re.I), + "A library the engine needs is missing. Update the engine (`strata update`) or install the graphics driver again."), +) + + +def engine_log_tail(config: Path | None, limit: int = 65536) -> tuple[list[str], str | None]: + """(last lines of the engine log, its path); ([], path-or-None) when it cannot be read.""" + log = None + if config: + try: + log = read_config(config).get("log") + except (OSError, ValueError): + log = None + if not log: + return [], None + try: + with open(log, "rb") as stream: + stream.seek(0, os.SEEK_END) + stream.seek(max(0, stream.tell() - limit)) + data = stream.read().decode("utf-8", "replace") + except OSError: + return [], str(log) + return [x.rstrip() for x in data.splitlines() if x.strip()], str(log) + + +def explain_engine_exit(result: dict, config: Path | None) -> tuple[str, str]: + """(text, next) for a start that did not reach ready: the stage, the cause line from the engine log, the next step and the log path + (round 8, L3: an Arc engine died with 'No device of requested type available' and the person saw only 'server_exited').""" + lines, log = engine_log_tail(config) + lines = lines or [x.strip() for x in str(result.get("log_tail") or "").split(" | ") if x.strip()] + cause = next((x for x in reversed(lines) if CAUSE_LINE.search(x) and not x.lstrip().startswith(("strata generate: ", "strata serve: expert"))), None) + cause = (cause or (lines[-1] if lines else "")).strip() + cause = re.sub(r"^(\[strata\]\s*)?(\d{4}-\d\d-\d\d[ T][\d:.]+\s*)?", "", cause)[:240] + state, why = result.get("state"), result.get("error") or result.get("message") + if why == "startup_wait_expired": + stage = "The model did not finish loading in time" + elif why == "server_exited" or result.get("engine_exit_code") is not None: + code = result.get("engine_exit_code") + stage = "The engine stopped while it was loading the model" + (f" (exit code {code})" if code not in (None, 0) else "") + else: + stage = f"The server did not become ready ({state}: {why or 'see the engine log'})" + text = stage + (f": {cause}" if cause else ".") + if not text.endswith((".", "!")): + text += "." + step = next((words for pattern, words in KNOWN_CAUSES if pattern.search(" ".join([cause, str(why or "")]))), "Run it again; if it repeats, report the log.") + return text, step + (f" The engine's log: {log}" if log else " The engine's log has the reason (strata logs, or the log named in the run config).") + + def _log_hint(config: Path | None) -> str: log = None if config: diff --git a/strata_cli/update_cmd.py b/strata_cli/update_cmd.py index 67e89937..397fc5c3 100644 --- a/strata_cli/update_cmd.py +++ b/strata_cli/update_cmd.py @@ -139,6 +139,13 @@ def _print_check(report: dict) -> None: "current": f"{installed} is up to date", "none-for-this-pc": eng.get("note") or "the feed has no engine for this PC", "not-in-feed": "the feed lists no engines"}.get(eng["status"], eng.get("note") or eng["status"]) print(f" Engine {text}") + pick = eng.get("offered") + if pick and eng["status"] in ("available", "install", "current"): + # round 8, N9: the list below names only the packages that were NOT chosen; say which one was + label = pick.get("label") or (f"{pick.get('version')} {pick.get('platform')}-{pick.get('backend')}" + (f"-{pick['variant']}" if pick.get("variant") else "")) + print(f" selected for this PC: {label}") + if eng.get("reasons"): + print(" not used for this PC:") for reason in eng.get("reasons") or []: print(f" - {reason}") if eng.get("note") and eng["status"] not in ("failed-before", "skipped", "current"): diff --git a/strata_control/discovery.py b/strata_control/discovery.py index 93ac134c..f919655c 100644 --- a/strata_control/discovery.py +++ b/strata_control/discovery.py @@ -166,6 +166,9 @@ def places(*, here: Path | None = None, explicit: str | os.PathLike | None = Non p = Path(raw).expanduser() return [Place(p, "explicit", len(config_files(p)))] cands: list[tuple[Path, str]] = [] + data_root = environ.get("STRATA_DATA_DIR") + if data_root: # the installer's own folder (install.sh / install.ps1): an install kept inside it comes first + cands.append((Path(data_root).expanduser() / "install", "datadir")) if here is not None: cands.append((Path(here), "here")) own = own_settings_file(environ, windows=windows, home=home) diff --git a/strata_control/runtime.py b/strata_control/runtime.py index 440504a6..2497957d 100644 --- a/strata_control/runtime.py +++ b/strata_control/runtime.py @@ -468,6 +468,30 @@ def _engine_preflight(plan: dict) -> None: raise ProfileError(str(exc), exc.exit_code) from None +def _ready_pid_is_child(ready_pid, child_pid: int) -> bool: + """Is the process named in the ready file the one this host started? + + Normally the pids are equal. A Windows venv (the python.exe of a source checkout's .venv) starts its real interpreter as a + CHILD of the launcher it was given, so the server that writes the ready file is one process below the pid ``Popen`` returned + (#3683: the staged engine was ready, this check never matched, and the start waited out its whole deadline). Only on Windows, + and only for a process that sits within three parents of the process this host started, so another process cannot pass.""" + if type(ready_pid) is not int or ready_pid <= 0: + return False + if ready_pid == child_pid: + return True + if not WINDOWS: + return False + current = ready_pid + for _ in range(3): + parent = procs.parent_of(current) + if parent is None or parent <= 0: + return False + if parent == child_pid: + return True + current = parent + return False + + def _check_start_candidate(name: str, expected_profile_revision: str | None, expected_source_sha256: str | None) -> tuple[dict, str]: plan, digest = _start_candidate(name) @@ -481,9 +505,13 @@ def _check_start_candidate(name: str, expected_profile_revision: str | None, def start(name: str, *, wait: float = 300, shutdown_timeout: float = 30, expected_profile_revision: str | None = None, expected_source_sha256: str | None = None, - die_with_pid: int | None = None) -> dict: + die_with_pid: int | None = None, on_status=None) -> dict: """Start the saved profile under a new owner host. + ``on_status`` (optional) is called with each status answer while the start waits (about every 0.2 s; the caller throttles), so a + caller can show progress. The result of a wait that ran out names the last phase (``loading``, ``verifying_generation``, + ``ready_file_not_matched``). + The owner host is a background service: it is not tied to the terminal or the process that ran this command and keeps serving after they end. It stops on `runtime stop`, when its server ends, or - only if `die_with_pid` names a process - when that process is gone (the desktop app uses this for the engines it starts).""" @@ -542,14 +570,20 @@ def start(name: str, *, wait: float = 300, shutdown_timeout: float = 30, if wait == 0: return {"ok": True, "profile": name, "state": "starting", "plan": plan} deadline = time.monotonic() + wait + result: dict = {} while time.monotonic() < deadline: result = _rpc(name, "status") + if on_status is not None: + try: + on_status(result) + except Exception: # noqa: BLE001 - progress must never break a start + on_status = None if result.get("state") in ("ready", "failed"): return {**result, "ok": result["state"] == "ready", "exit_code": 6 if result["state"] == "failed" else 0} time.sleep(0.2) return {"ok": False, "profile": name, "state": "starting", "error": "startup_wait_expired", - "exit_code": 8} + "phase": result.get("phase"), "exit_code": 8} def plan_stop(name: str) -> dict: @@ -901,7 +935,7 @@ class Host: if self.ready_path is not None: try: ready = json.loads(self.ready_path.read_text(encoding="utf-8")) - if ready.get("pid") == child.pid and isinstance(ready.get("instance_id"), str): + if _ready_pid_is_child(ready.get("pid"), child.pid) and isinstance(ready.get("instance_id"), str): key = (child.pid, ready["instance_id"]) if self.probe_key != key: self.probe_key, self.probe_result = key, None @@ -920,9 +954,13 @@ class Host: return {**base, "state": "ready", "instance_id": ready["instance_id"], "model_state": ready.get("model_state"), **self.probe_result} + if isinstance(ready, dict): + # the server published its ready file but it is not the process this host started: say so, so a wait that + # ends can name it (before #3683 this looked exactly like a model that was still loading) + return {**base, "state": "starting", "phase": "ready_file_not_matched"} except (OSError, ValueError): pass - return {**base, "state": "starting"} + return {**base, "state": "starting", "phase": "loading"} def _wait_ready(self, timeout: float) -> dict: deadline = time.monotonic() + timeout @@ -1139,7 +1177,7 @@ class Host: return {"ok": False, "state": current["state"], "error": "runtime_not_ready", "exit_code": 6} try: ready = json.loads(self.ready_path.read_text(encoding="utf-8")) - if ready.get("pid") != self.child.pid or ready.get("instance_id") != current["instance_id"]: + if not _ready_pid_is_child(ready.get("pid"), self.child.pid) or ready.get("instance_id") != current["instance_id"]: raise readiness.ReadinessError("probe_instance_mismatch") host = self.args[self.args.index("--host") + 1] result = readiness.verify(ready, self.source_bytes, expected_host=host, diff --git a/strata_control/updater.py b/strata_control/updater.py index 0f504ab7..7f4d719e 100644 --- a/strata_control/updater.py +++ b/strata_control/updater.py @@ -76,12 +76,15 @@ class TestStartFailed(UpdateError): 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)) + def __init__(self, label: str, reason: str, *, busy: bool | None = None, hint: str | None = None): + # busy: True/False says outright whether the card or memory was busy (the wait-expired reasons carry the engine's log tail, which + # mentions VRAM on every healthy start and must not be read as a busy card, #3683); None reads it from the words of the reason + self.busy = bool(self.BUSY.search(reason)) if busy is None else busy + if hint is None and self.busy: + hint = ("The graphics card or memory looks busy: close programs that use the card (games, video, other models) " + "and run `strata update` again.") super().__init__(f"The new engine {label} did not pass its test start ({reason}). It was not installed; " - "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) + "your current engine is unchanged." + (" " + hint if hint else ""), 6) self.label = label self.reason = reason @@ -702,6 +705,48 @@ def _warn_if_deep(ctx: Context, folder: Path, longest_inside: int) -> None: ctx.say("warn", words, component="engine") +def _test_progress(ctx: Context, component: ec.EngineComponent): + """What the person sees while the staged engine is test-started: a line when the phase changes and one about every 30 seconds, + so a long load or a stuck probe is never a silent wait (#3683: 10 minutes of nothing, then a timeout).""" + began = time.monotonic() + seen = {"phase": None, "at": 0.0} + words = {"loading": "is loading the model", + "verifying_generation": "has loaded the model; waiting for it to answer one token", + "ready_file_not_matched": "says it is ready; checking that it is the engine Strata started"} + + def progress(status: dict) -> None: + phase = status.get("phase") if status.get("state") == "starting" else None + if phase not in words: + return + now = time.monotonic() + if phase != seen["phase"] or now - seen["at"] >= 30: + seen["phase"], seen["at"] = phase, now + ctx.say("test", f"Engine {component.version} {words[phase]} ({int(now - began)} s)", component="engine") + + return progress + + +def _test_start_failure(component: ec.EngineComponent, started: dict, ctx: Context, tail: str) -> TestStartFailed: + """The plain reason a test start did not pass, in the words of what the engine was doing when it ran out of time.""" + error = started.get("error") + minutes = max(1, int(min(ctx.test_timeout, 600) // 60)) + log = updates_dir(ctx.components) / "logs" / f"test-start-{component.version}.log" + if error == "startup_wait_expired": + phase = started.get("phase") + kept = f" The engine's log from this test is in {log}." + if phase == "verifying_generation": + return TestStartFailed(component.version, f"it loaded the model but did not answer one token within {minutes} minutes", + busy=False, hint="Nothing was changed. Run `strata update` again; if it happens again, report it with the log." + kept) + if phase == "ready_file_not_matched": + return TestStartFailed(component.version, f"it reported that it was ready, but Strata could not match it to the engine process it " + f"started", busy=False, + hint="This looks like a problem in Strata, not in your engine or card. Nothing was changed; report it with the log." + kept) + return TestStartFailed(component.version, f"it was still loading the model after {minutes} minutes", busy=True, + hint="Nothing was changed. A slow disk or a card that other programs are using can do this: close them and run " + "`strata update` again." + kept) + return TestStartFailed(component.version, f"it did not answer a one-token probe ({error or started.get('state')}){tail}") + + def default_test_start(stage_root: Path, component: ec.EngineComponent, ctx: Context) -> dict: """Start the staged engine through the real start path (owner runtime, `component:strata-engine`, a saved model), wait for the one-token generation probe, and stop it. Everything runs in an isolated runtime, profile and component folder, so a @@ -732,15 +777,16 @@ def default_test_start(stage_root: Path, component: ec.EngineComponent, ctx: Con profiles.create(name, str(config_path)) started = None try: - started = runtime.start(name, wait=min(ctx.test_timeout, 600), shutdown_timeout=20) + started = runtime.start(name, wait=min(ctx.test_timeout, 600), shutdown_timeout=20, + on_status=_test_progress(ctx, component)) if started.get("ok") and started.get("state") == "ready" and started.get("generation_ready") is not True: # a server that loads its model on the first request is "ready" without having generated anything: # force the load and the one-token probe, because that is what the new engine has to be able to do + ctx.say("test", f"Engine {component.version} is up; asking it for one token", component="engine") started = {**started, **runtime.verify(name, timeout=min(ctx.test_timeout, 600), load=True)} if not started.get("ok") or started.get("state") != "ready" or started.get("generation_ready") is not True: - raise TestStartFailed(component.version, - f"it did not answer a one-token probe ({started.get('error') or started.get('state')})" - + _log_tail(sandbox, component)) + _keep_log(sandbox, component, ctx) + raise _test_start_failure(component, started, ctx, _log_tail(sandbox, component)) _keep_log(sandbox, component, ctx) return {"mode": "full", "model": cfg.get("model_name") or source.stem, "state": started["state"], "generation_ready": True, "detail": "started, answered a one-token probe, stopped"} diff --git a/tests/terminal/test_bundle_imports.py b/tests/terminal/test_bundle_imports.py new file mode 100644 index 00000000..a12b2b75 --- /dev/null +++ b/tests/terminal/test_bundle_imports.py @@ -0,0 +1,101 @@ +"""The Terminal / Control bundle holds every tools/ module that setup.py can import (#3613, #3467). + +0.1.47 shipped without tools/calibrate.py: setup.py imports it after a tune, so every launch after a tune ended in +ModuleNotFoundError. The bundle is staged here the way packaging/package_terminal.py stages it (the payload, the read-only tools, +then add_installer), and setup.py's tool imports are resolved against tools/ as the bundle has it, not against the source tree. +""" + +import ast +import os +import shutil +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(ROOT / "packaging")) +import package_terminal as pt # noqa: E402 + + +def imports_of(path: Path) -> set[str]: + found: set[str] = set() + for node in ast.walk(ast.parse(path.read_text(encoding="utf-8-sig"))): + if isinstance(node, ast.Import): + found.update(a.name.split(".")[0] for a in node.names) + elif isinstance(node, ast.ImportFrom) and node.module and node.level == 0: + found.add(node.module.split(".")[0]) + return found + + +class BundleImports(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.temp = tempfile.TemporaryDirectory(prefix="strata-bundle-") + cls.root = Path(cls.temp.name) / "strata-terminal" + cls.root.mkdir() + ignore = shutil.ignore_patterns("__pycache__", "*.pyc") + for item in pt.PAYLOAD: + src, dst = ROOT / item, cls.root / item + dst.parent.mkdir(parents=True, exist_ok=True) + if src.is_dir(): + shutil.copytree(src, dst, ignore=ignore) + else: + shutil.copy2(src, dst) + (cls.root / "tools").mkdir(exist_ok=True) + for item in pt.TOOLS_SUBSET: + shutil.copy2(ROOT / "tools" / item, cls.root / "tools" / item) + cls.installer = pt.add_installer(cls.root, ROOT) + + @classmethod + def tearDownClass(cls): + cls.temp.cleanup() + + def test_calibrate_is_in_the_bundle(self): + # the exact file #3613 and #3467 lacked + self.assertTrue((self.root / "tools" / "calibrate.py").is_file()) + self.assertIn("calibrate", pt.INSTALLER_TOOLS) + + def test_every_tools_module_setup_py_imports_is_in_the_bundle(self): + in_bundle = {p.stem for p in (self.root / "tools").glob("*.py")} + in_source = {p.stem for p in (ROOT / "tools").glob("*.py")} + wanted = imports_of(self.root / "setup.py") & in_source + self.assertIn("calibrate", wanted, "setup.py no longer imports calibrate: update this test") + self.assertEqual(sorted(wanted - in_bundle), [], "setup.py imports tools/ modules that the bundle does not carry") + + def test_the_bundled_tools_import_nothing_the_bundle_lacks(self): + in_bundle = {p.stem for p in (self.root / "tools").glob("*.py")} + in_source = {p.stem for p in (ROOT / "tools").glob("*.py")} + for module in sorted(in_bundle): + missing = sorted((imports_of(self.root / "tools" / f"{module}.py") & in_source) - in_bundle) + self.assertEqual(missing, [], f"tools/{module}.py imports tools/ modules the bundle does not carry") + + def test_setup_py_and_each_of_its_tools_import_with_tools_limited_to_the_bundle(self): + modules = sorted(set(pt.setup_tool_imports(self.root)) | set(pt.INSTALLER_TOOLS)) + code = ("import sys, os, importlib\n" + f"sys.path[:0] = [{str(self.root)!r}, {str(self.root / 'tools')!r}]\n" + "import setup\n" + f"for name in {modules!r}:\n" + " module = importlib.import_module(name)\n" + f" assert os.path.samefile(os.path.dirname(module.__file__), {str(self.root / 'tools')!r}), (name, module.__file__)\n" + "print('imports ok')\n") + env = {**os.environ, "STRATA_CONTROL_INSTALL": "1", "PYTHONNOUSERSITE": "1"} + for key in ("PYTHONPATH", "PYTHONHOME"): + env.pop(key, None) + done = subprocess.run([sys.executable, "-I", "-c", code], cwd=str(self.root.parent), env=env, + capture_output=True, text=True, timeout=120) + self.assertEqual(done.returncode, 0, (done.stdout or "") + (done.stderr or "")[-1500:]) + self.assertIn("imports ok", done.stdout) + + def test_a_tool_setup_starts_to_import_is_added_without_editing_the_list(self): + # setup_tool_imports reads setup.py, so INSTALLER_TOOLS cannot go stale the way it did for calibrate + self.assertTrue(set(pt.setup_tool_imports(ROOT)) <= set(pt.local_imports(ROOT, tuple(sorted( + set(pt.INSTALLER_TOOLS) | set(pt.setup_tool_imports(ROOT))))))) + without = tuple(x for x in pt.INSTALLER_TOOLS if x != "calibrate") + self.assertNotIn("calibrate", pt.local_imports(ROOT, without)) # the old list really lacked it + self.assertIn("calibrate", pt.setup_tool_imports(ROOT)) # and the scan finds it anyway + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/terminal/test_launch.py b/tests/terminal/test_launch.py index 8dece84c..5a3625a1 100644 --- a/tests/terminal/test_launch.py +++ b/tests/terminal/test_launch.py @@ -506,9 +506,10 @@ class AdoptRules(unittest.TestCase): self.assertIsNone(cfg) self.assertTrue(any("prepared pack" in p for p in problems)) self.assertTrue(any("tokenizer" in p for p in problems)) - cfg, problems = adopt.plan(family="gyro", model="Gyro-S", model_dir=m, data_dir=d, src=Path("."), context=8192, kv=None, model_name="x", + cfg, problems = adopt.plan(family="unsloth", model="UD-Q4_K_XL", model_dir=m, data_dir=d, src=Path("."), context=8192, kv=None, model_name="x", family_def={}, log=h.base / "x.log", backend=None) self.assertIn("only for the Qwen3.8-Flash-Next", problems[0]) + self.assertNotIn("..", problems[0] + ".") # round 8, N11: the caller adds the full stop def test_pictures_on_is_setups_yes_and_setup_picks_the_encoder(self): with Home() as h: diff --git a/tests/terminal/test_round8_fixes.py b/tests/terminal/test_round8_fixes.py new file mode 100644 index 00000000..1a891483 --- /dev/null +++ b/tests/terminal/test_round8_fixes.py @@ -0,0 +1,310 @@ +"""Owner test round 8 (7 machines), the Control / TUI / setup fixes: F5, F3, N2 to N9, N11.""" + +import argparse +import io +import json +import os +import sys +import tempfile +import unittest +from contextlib import redirect_stdout +from pathlib import Path +from unittest import mock + +from strata_cli.launch import adopt, library, runner as R +from strata_cli.launch import settings as S +from strata_cli.launch.runner import Runner +from tests.terminal.launch_support import HW_12, Home, catalog + + +def runner_for(**kw) -> Runner: + return Runner(S.LaunchSettings(family="qwen", model="IQ3_XXS", context=32768, vision="off", **kw), catalog=catalog(HW_12)) + + +class EngineExitIsExplained(unittest.TestCase): + """F5 (L3): an Arc engine died with 'No device of requested type available' and the person saw only 'server_exited'.""" + + def config_with_log(self, lines): + folder = tempfile.TemporaryDirectory() + self.addCleanup(folder.cleanup) + log = Path(folder.name) / "engine.log" + log.write_text("\n".join(lines) + "\n", encoding="utf-8") + cfg = Path(folder.name) / "run.json" + cfg.write_text(json.dumps({"log": str(log)}), encoding="utf-8") + return cfg, log + + def test_arc_without_the_render_group_names_the_cause_the_next_step_and_the_log(self): + cfg, log = self.config_with_log(["strata generate: memory guard: limit 61.6 GiB", "strata generate: SYCL init", + "terminate called after throwing an instance of 'sycl::exception'", + " what(): No device of requested type available. -1 (PI_ERROR_DEVICE_NOT_FOUND)"]) + text, nxt = R.explain_engine_exit({"state": "failed", "error": "server_exited", "engine_exit_code": 134}, cfg) + self.assertIn("stopped while it was loading the model", text) + self.assertIn("No device of requested type available", text) + self.assertNotIn("server_exited", text + nxt) + self.assertIn("render group", nxt) + self.assertIn(str(log), nxt) + + def test_out_of_memory_and_old_engine_get_their_own_next_step(self): + cfg, _ = self.config_with_log(["strata generate: CUDA error: out of memory"]) + self.assertIn("--context 16k", R.explain_engine_exit({"error": "server_exited"}, cfg)[1]) + cfg, _ = self.config_with_log(["strata generate: no kernel for TQK6 on this engine"]) + self.assertIn("strata update", R.explain_engine_exit({"error": "server_exited"}, cfg)[1]) + + def test_an_unreadable_log_still_says_the_stage_and_where_to_look(self): + text, nxt = R.explain_engine_exit({"state": "failed", "error": "server_exited", "log_tail": "boom | Error: cannot map the pack"}, None) + self.assertIn("cannot map the pack", text) + self.assertIn("strata logs", nxt) + text, _ = R.explain_engine_exit({"state": "starting", "error": "startup_wait_expired"}, None) + self.assertIn("did not finish loading in time", text) + + +class NoTuiNeverAsks(unittest.TestCase): + def test_no_tui_keeps_the_models_and_says_so_without_input(self): + with tempfile.TemporaryDirectory() as old, tempfile.TemporaryDirectory() as new: + (Path(old) / "models").mkdir() + (Path(old) / "models" / "a.gguf").write_bytes(b"x" * 2048) + from strata_cli.launch import cmd + a = argparse.Namespace(data_dir=new, move_data=False, yes=False, plan=False, no_tui=True) + cat = mock.Mock() + cat.data_dir.return_value = Path(old) + out = io.StringIO() + with mock.patch.object(library, "movable_library", return_value=40.0), mock.patch("builtins.input", side_effect=AssertionError("asked")), \ + mock.patch.object(sys, "stdin") as stdin, redirect_stdout(out): + stdin.isatty.return_value = True + self.assertFalse(cmd._move_data_choice(a, S.LaunchSettings(), cat, False)) + self.assertIn("Keeping your 40 GB of models where they are", out.getvalue()) + self.assertIn("--move-data", out.getvalue()) + + def test_a_run_without_a_keyboard_says_the_same(self): + from strata_cli.launch import cmd + a = argparse.Namespace(data_dir="/new", move_data=False, yes=False, plan=False, no_tui=False) + out = io.StringIO() + with mock.patch.object(library, "movable_library", return_value=3.0), mock.patch("builtins.input", side_effect=AssertionError("asked")), \ + mock.patch.object(sys, "stdin") as stdin, redirect_stdout(out): + stdin.isatty.return_value = False + self.assertFalse(cmd._move_data_choice(a, S.LaunchSettings(), mock.Mock(), False)) + self.assertIn("Keeping your 3.0 GB", out.getvalue()) + + +class SetupArguments(unittest.TestCase): + def installed(self, h: Home, **cfg): + path = h.base / "install" / "strata-iq3_xxs.json" + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps({"exe": "x", "args": [], **cfg}), encoding="utf-8") + return path + + def test_a_context_change_forwards_the_installed_roles(self): + # F3: 0=main,1=helper came back from a 32k to 16k change as 0=helper,1=main + with Home() as h: + path = self.installed(h, gpu=[1, 0], gpus_asked=True, gpu_roles={"0": "main", "1": "helper"}) + r = runner_for() + with mock.patch.object(Runner, "installed_state", return_value=(path, None)): + a = r.setup_args() + self.assertEqual(a[a.index("--gpu-roles") + 1], "0=main,1=helper") + + def test_installed_cards_are_forwarded_and_the_automatic_pick_is_not(self): + with Home() as h: + path = self.installed(h, gpu=[1, 0], gpus_asked=True) + with mock.patch.object(Runner, "installed_state", return_value=(path, None)): + a = runner_for().setup_args() + self.assertEqual(a[a.index("--gpus") + 1], "1,0") + path = self.installed(h, gpu=0) # never asked: setup picks again + with mock.patch.object(Runner, "installed_state", return_value=(path, None)): + a = runner_for().setup_args() + self.assertNotIn("--gpus", a) + self.assertNotIn("--gpu", a) + + def test_cards_named_on_the_command_line_win_over_the_installed_ones(self): + with Home() as h: + path = self.installed(h, gpu=[1, 0], gpus_asked=True, gpu_roles={"0": "main", "1": "helper"}) + with mock.patch.object(Runner, "installed_state", return_value=(path, None)): + a = runner_for(gpus=[0]).setup_args() + self.assertEqual(a[a.index("--gpu") + 1], "0") + self.assertNotIn("--gpu-roles", a) + + def test_mtp_off_reaches_setup(self): + with Home(): + a = runner_for(mtp="off").setup_args() + self.assertEqual(a[a.index("--mtp") + 1], "off") + self.assertNotIn("--mtp", runner_for().setup_args()) + + def test_setup_skips_the_draft_layer_download_for_mtp_off(self): + # setup.py is a script; its two fetch sites must be guarded by the explicit --mtp off (N3: a 5.2 GB download happened anyway) + text = (Path(__file__).resolve().parents[2] / "setup.py").read_text(encoding="utf-8") + self.assertIn('if a.mtp == "off" and not (rt / "experts.bin").exists():', text) + self.assertIn('if use_mtp and a.mtp == "off" and not (mtp / "mtp-q2_0.gguf").exists():', text) + self.assertIn('"use --data-dir on a bigger drive (strata launch --data-dir)" if CONTROL', text) # N2: a launch option, not --models-dir + + +class PlanPredictsEveryDownload(unittest.TestCase): + def plan_text(self, h: Home, own: Path, **kw) -> dict: + s = S.LaunchSettings(family="qwen", model="IQ3_XXS", context=32768, vision="on", model_path=str(own), data_dir=str(h.base / "data"), **kw) + r = Runner(s, catalog=catalog(HW_12)) + with mock.patch.object(Runner, "check_own_files"), mock.patch.object(Runner, "ready_pack_gap", return_value=None): + return r.download_plan() + + def test_a_local_gguf_without_a_reader_shows_the_picture_reader_and_the_switch(self): + with Home() as h: + own = h.base / "own" + own.mkdir() + (own / "m-00001-of-00002.gguf").write_bytes(b"x") + plan = self.plan_text(h, own) + self.assertIn("picture reader", plan["text"]) + self.assertIn("--vision off", plan["text"]) + self.assertIn("draft layer", plan["text"]) + self.assertIn("--mtp off", plan["text"]) + + def test_a_reader_beside_the_files_is_used_and_not_counted(self): + with Home() as h: + own = h.base / "own" + own.mkdir() + (own / "m-00001-of-00002.gguf").write_bytes(b"x") + (own / "mmproj-Qwen3.8-Flash-Next-BF16.gguf").write_bytes(b"x") + plan = self.plan_text(h, own) + self.assertNotIn("picture reader", plan["text"]) + + def test_mtp_off_is_not_counted(self): + with Home() as h: + own = h.base / "own" + own.mkdir() + (own / "m-00001-of-00002.gguf").write_bytes(b"x") + self.assertNotIn("draft layer", self.plan_text(h, own, mtp="off")["text"]) + + +class ReadyPackPlan(unittest.TestCase): + def test_a_ready_made_pack_is_counted_and_the_hint_is_a_launch_option(self): + with Home() as h: + own = h.base / "own" + own.mkdir() + r = Runner(S.LaunchSettings(family="qwen", model="IQ3_XXS", context=32768, vision="off", model_path=str(own)), catalog=catalog(HW_12)) + gap = {"gb": 129.0, "folder": str(h.base / "data" / "models"), "free_gb": 110.0} + with mock.patch.object(Runner, "ready_pack_gap", return_value=gap): + plan = r.download_plan() + self.assertGreaterEqual(plan["gb"], 129.0) + self.assertIn("ready-made pack", plan["text"]) + self.assertIn("--data-dir", plan["text"]) + self.assertNotIn("Nothing to download", plan["text"]) + + +class EngineIsFreshEnough(unittest.TestCase): + def test_versions_compare_by_numbers(self): + self.assertEqual(R.version_tuple("0.1.45.3"), (0, 1, 45, 3)) + self.assertEqual(R.version_tuple("junk"), ()) + + def test_an_old_engine_is_named_in_plain_words_and_a_current_one_is_not(self): + with Home(): + r = runner_for() + r.catalog.strata.setup_module() # loads setup.py's tables (MIN_ENGINE) + words = r.stale_engine("0.1.45.3") + self.assertIn("older than this model needs", words) + self.assertIn("0.1.45.3", words) + self.assertIsNone(r.stale_engine("0.1.47")) + self.assertIsNone(r.stale_engine("source")) + + def test_gyro_on_a_mac_needs_engine_0_1_47(self): + with Home(): + r = Runner(S.LaunchSettings(family="gyro", model="Gyro-S", context=32768, vision="off"), catalog=catalog(HW_12)) + with mock.patch.object(sys, "platform", "darwin"): + self.assertEqual(r.needed_engine(), (0, 1, 47)) + self.assertIn("older than this model needs (0.1.47", r.stale_engine("0.1.45.3")) + self.assertIsNone(r.stale_engine("0.1.47")) + with mock.patch.object(sys, "platform", "linux"): + self.assertLess(r.needed_engine(), (0, 1, 47)) # CUDA, HIP and SYCL had the kernels earlier + self.assertIsNone(r.stale_engine("0.1.46")) + with mock.patch.object(sys, "platform", "darwin"): + q = Runner(S.LaunchSettings(family="qwen", model="IQ3_XXS", context=32768, vision="off"), catalog=catalog(HW_12)) + self.assertLess(q.needed_engine(), (0, 1, 47)) # only Gyro is held to it + + def test_a_stale_engine_is_updated_or_said_never_ignored(self): + with Home(): + r = runner_for() + events = [] + r.emit = lambda stage, text, pct=None, level="info", **kw: events.append((level, text)) + before = {"usable": True, "engine": {"version": "0.1.45.3", "backend": "cuda"}} + proc = mock.Mock() + proc.stdout = iter([]) + proc.wait.return_value = 0 + from strata_control import engine_component as ec + with mock.patch.object(ec, "status", return_value=before), mock.patch.object(Runner, "_spawn", return_value=proc): + r.ensure_engine() + self.assertTrue(any(level == "warn" and "older than this model needs" in text for level, text in events), events) + self.assertTrue(any("strata update" in n for n in r.notices), r.notices) + + +class InstallIsNotHijacked(unittest.TestCase): + def test_an_earlier_install_outside_the_chosen_data_folder_is_named(self): + with Home() as h: + cat = mock.Mock() + cat.places = [mock.Mock(path=h.base / "old" / "Strata", source="app", configs=2)] + words = R.install_isolation_words(cat, str(h.base / "scratch")) + self.assertEqual(len(words), 1) + self.assertIn("earlier install", words[0]) + self.assertIn(str(h.base / "old" / "Strata"), words[0]) + cat.places = [mock.Mock(path=h.base / "scratch" / "install", source="app", configs=1)] + self.assertEqual(R.install_isolation_words(cat, str(h.base / "scratch")), []) + cat.places = [mock.Mock(path=h.base / "old", source="explicit", configs=1)] + self.assertEqual(R.install_isolation_words(cat, str(h.base / "scratch")), []) + self.assertEqual(R.install_isolation_words(cat, None), []) + + def test_an_install_inside_strata_data_dir_comes_first(self): + from strata_control import discovery + with tempfile.TemporaryDirectory() as data, tempfile.TemporaryDirectory() as other: + for folder in (Path(data) / "install", Path(other) / "install"): + folder.mkdir() + (folder / "strata-q.json").write_text("{}", encoding="utf-8") + env = {"STRATA_DATA_DIR": data} + found = discovery.places(environ=env, here=Path(other) / "install", home=Path(other)) + self.assertEqual(Path(found[0].path).resolve(), (Path(data) / "install").resolve()) + + +class IdentityAndAdoption(unittest.TestCase): + def test_family_that_does_not_match_the_file_header_is_warned_about(self): + with Home() as h: + r = Runner(S.LaunchSettings(family="swift", model="IQ2_XS", model_path=str(h.base)), catalog=catalog(HW_12)) + plan = {"candidate_selection": {"family": "qwen", "model": "IQ3_XXS"}, "folder_holds": [], "issues": []} + from strata_control import models + with mock.patch.object(models, "own_path_problem", return_value=None), mock.patch.object(models, "plan_import", return_value=plan), \ + mock.patch.object(models, "import_target", return_value=str(h.base)): + r.resolve_own_files() + self.assertEqual(len(r.identity_notes), 1) + self.assertIn("look like qwen IQ3_XXS", r.identity_notes[0]) + self.assertIn("not swift IQ2_XS", r.identity_notes[0]) + self.assertEqual((r.s.family, r.s.model), ("swift", "IQ2_XS")) # warned, never forced + + def test_gyro_is_adopted_like_the_others_and_the_text_has_no_double_period(self): + with Home() as h: + data = h.base / "data" + model_dir = data / "models" / "gyro-Gyro-S" + model_dir.mkdir(parents=True) + (model_dir / "Qwen3.8-Flash-Next-Gyro-S-TQ1_0.gguf").write_bytes(b"x") + pack = data / "packs" / "gyro-gyro-s" + (pack / "tokenizer").mkdir(parents=True) + (pack / "index.txt").write_text("x", encoding="utf-8") + cfg, problems = adopt.plan(family="gyro", model="Gyro-S", model_dir=model_dir, data_dir=data, src=Path(__file__).resolve().parents[2], + context=8192, kv=None, model_name="gyro", family_def={}, log=h.base / "x.log", backend="sycl", + pack_name="gyro-gyro-s") + self.assertEqual(problems, [], problems) + self.assertEqual(cfg["args"][cfg["args"].index("--ple-gguf") + 1], cfg["args"][cfg["args"].index("--native") + 1]) + _, refused = adopt.plan(family="nvfp4", model="NVFP4", model_dir=model_dir, data_dir=data, src=Path("."), context=8192, kv=None, + model_name="x", family_def={}, log=h.base / "x.log", backend=None) + self.assertTrue(refused[0].endswith("not for nvfp4")) # the caller adds the one full stop + + +class UpdateCheckNamesTheChoice(unittest.TestCase): + def test_the_selected_package_is_printed_before_the_rejected_ones(self): + from strata_cli import update_cmd + report = {"feed": {"sequence": 107, "channel": "stable", "key_id": "k", "trusted_by": "built-in keys"}, + "engine": {"status": "install", "installed": None, "download_bytes": 5 << 20, + "offered": {"version": "0.1.47", "platform": "linux-x86_64", "backend": "cuda", "variant": "cuda12"}, + "reasons": ["0.1.47 linux-x86_64-cuda-cuda13 needs driver 580"], "note": None}, + "control": {"status": "current", "installed": "0.1.47", "offered": None}, "app": {"status": "not-in-feed"}} + out = io.StringIO() + with redirect_stdout(out): + update_cmd._print_check(report) + text = out.getvalue() + self.assertIn("selected for this PC: 0.1.47 linux-x86_64-cuda-cuda12", text) + self.assertLess(text.index("selected for this PC"), text.index("not used for this PC")) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/terminal/test_runtime.py b/tests/terminal/test_runtime.py index c54b9c6a..7b795b9b 100644 --- a/tests/terminal/test_runtime.py +++ b/tests/terminal/test_runtime.py @@ -1195,6 +1195,53 @@ class RuntimeTests(unittest.TestCase): with self.assertRaisesRegex(profiles.ProfileError, "Everyone"): runtime.runtime_dir() + def test_ready_pid_may_be_a_child_of_the_launcher_on_windows_only(self): + # #3683: a Windows venv's python.exe starts the real interpreter as its child, so the server that writes the ready file + # is one process below the pid the host started. It must still match; a stranger or a distant process must not. + parents = {200: 100, 300: 200, 400: 300, 500: 400} + with mock.patch.object(runtime.procs, "parent_of", side_effect=lambda pid: parents.get(pid)): + with mock.patch.object(runtime, "WINDOWS", True): + self.assertTrue(runtime._ready_pid_is_child(100, 100)) + self.assertTrue(runtime._ready_pid_is_child(200, 100)) + self.assertTrue(runtime._ready_pid_is_child(300, 100)) + self.assertTrue(runtime._ready_pid_is_child(400, 100)) + self.assertFalse(runtime._ready_pid_is_child(500, 100)) # too far below + self.assertFalse(runtime._ready_pid_is_child(999, 100)) # unrelated + self.assertFalse(runtime._ready_pid_is_child(None, 100)) + self.assertFalse(runtime._ready_pid_is_child("200", 100)) + self.assertFalse(runtime._ready_pid_is_child(0, 100)) + with mock.patch.object(runtime, "WINDOWS", False): + self.assertTrue(runtime._ready_pid_is_child(100, 100)) + self.assertFalse(runtime._ready_pid_is_child(200, 100)) # POSIX has no launcher in between + + @unittest.skipUnless(WINDOWS, "the venv launcher is a Windows thing") + def test_server_started_through_a_launcher_process_becomes_ready(self): + launcher = self.root / "launcher.cmd" + launcher.write_bytes(f'@echo off\r\n"{sys.executable}" %*\r\n'.encode()) + host = runtime.Host("local", shutdown_timeout=2, startup_wait=20) + plan, args, source, original = host._plan() + with mock.patch.object(sys, "executable", str(launcher)): + host._launch(args, source, original, plan["profile_revision"]) + try: + result = host._wait_ready(30) + self.assertTrue(result["ok"], result) + self.assertTrue(result["generation_ready"]) + ready = json.loads(host.ready_path.read_text(encoding="utf-8")) + self.assertNotEqual(ready["pid"], host.child.pid) # the server is below the launcher + finally: + host._stop_child() + + def test_a_ready_file_that_is_not_ours_is_named_in_the_status_phase(self): + host = runtime.Host("local", shutdown_timeout=2, startup_wait=10) + host.child = mock.Mock(pid=111) + host.child.poll.return_value = None + host.ready_path = self.root / "ready.json" + host.ready_path.write_text(json.dumps({"pid": 222, "instance_id": "a" * 32}), encoding="utf-8") + with mock.patch.object(runtime.procs, "parent_of", return_value=None): + self.assertEqual(host._status()["phase"], "ready_file_not_matched") + host.ready_path.unlink() + self.assertEqual(host._status()["phase"], "loading") + def test_exclusive_lease_waits_for_shared_holders_and_shared_holders_coexist(self): first = runtime.acquire_activity_lease(shared=True) second = runtime.acquire_activity_lease(shared=True) diff --git a/tests/terminal/test_setup_failure_words.py b/tests/terminal/test_setup_failure_words.py new file mode 100644 index 00000000..44db19a8 --- /dev/null +++ b/tests/terminal/test_setup_failure_words.py @@ -0,0 +1,72 @@ +"""When setup.py stops with a Python error, `strata launch` says what it was and where the rest of the output is (#3613, #3467).""" + +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +from strata_cli.launch import runner +from strata_cli.launch.runner import LaunchError, Runner, missing_file, python_failure, setup_failure + +TRACEBACK = [ + " [..] Tuning Strata for this PC", + "Traceback (most recent call last):", + ' File "C:\\Strata\\setup.py", line 6414, in calibrate_config', + " import calibrate as CAL", + "ModuleNotFoundError: No module named 'calibrate'", +] + + +class SetupFailureWords(unittest.TestCase): + def test_the_last_line_of_a_traceback_is_found(self): + self.assertEqual(python_failure(TRACEBACK), "ModuleNotFoundError: No module named 'calibrate'") + self.assertIsNone(python_failure(["[X] Not enough disk space", " Free some space"])) + self.assertIsNone(python_failure(["Traceback (most recent call last):", ' File "x.py", line 1, in '])) + # the last traceback wins, frames and blank lines are skipped + two = TRACEBACK[:1] + ["Traceback (most recent call last):", " frame", "ValueError: old"] + TRACEBACK[1:] + self.assertEqual(python_failure(two), "ModuleNotFoundError: No module named 'calibrate'") + + def test_a_missing_module_is_said_as_a_missing_file_with_the_next_step_and_the_output_path(self): + error = setup_failure(TRACEBACK, "", "", r"C:\Users\x\launch\a.setup.log", False) + self.assertIsInstance(error, LaunchError) + self.assertIn("The model could not be installed.", error.text) + self.assertIn("missing from this Strata install", error.text) + self.assertIn("No module named 'calibrate'", error.text) + self.assertIn("strata update", error.next) + self.assertIn(r"C:\Users\x\launch\a.setup.log", error.next) + + def test_another_python_error_keeps_its_line_and_the_path(self): + error = setup_failure(["Traceback (most recent call last):", " f", "KeyError: 'cuda'"], "", "", "/tmp/a.setup.log", True) + self.assertIn("KeyError: 'cuda'", error.text) + self.assertNotIn("missing", error.text) + self.assertIn("/tmp/a.setup.log", error.next) + + def test_a_setup_error_line_still_wins_and_gets_the_details_path(self): + error = setup_failure(TRACEBACK, "Not enough disk space", "Free some space.", "/tmp/a.setup.log", False) + self.assertEqual(error.text, "The model could not be installed. Not enough disk space.") + self.assertEqual(error.next, "Free some space. Details: /tmp/a.setup.log") + plain = setup_failure([], "", "", None, False) + self.assertEqual(plain.text, "The model could not be installed.") + self.assertIn("a download continues where it stopped", plain.next) + self.assertNotIn("Details", plain.next) + + def test_missing_file_kinds(self): + self.assertTrue(missing_file("ModuleNotFoundError: No module named 'x'")) + self.assertTrue(missing_file("ImportError: cannot import name 'y'")) + self.assertFalse(missing_file("ValueError: bad")) + + def test_the_setup_output_is_kept_in_the_launch_folder(self): + with tempfile.TemporaryDirectory() as folder: + run = Runner.__new__(Runner) + with mock.patch.object(Runner, "name", new_callable=mock.PropertyMock, return_value="gyro-s-32k"), mock.patch.object(runner, "launch_dir", return_value=Path(folder)): + kept = run.keep_setup_output([f"line {i}" for i in range(1000)] + TRACEBACK) + self.assertEqual(Path(kept), Path(folder) / "gyro-s-32k.setup.log") + text = Path(kept).read_text(encoding="utf-8") + self.assertIn("ModuleNotFoundError: No module named 'calibrate'", text) + self.assertEqual(len(text.splitlines()), 400) # the tail, not a runaway file + with mock.patch.object(Runner, "name", new_callable=mock.PropertyMock, return_value="gyro-s-32k"), mock.patch.object(runner, "launch_dir", side_effect=OSError("read-only")): + self.assertIsNone(run.keep_setup_output(["x"])) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/terminal/test_updater.py b/tests/terminal/test_updater.py index f8b6747c..803bdba0 100644 --- a/tests/terminal/test_updater.py +++ b/tests/terminal/test_updater.py @@ -180,6 +180,7 @@ class EngineUpdate(UpdaterCase): ran = (self.root / "ran.txt").read_text().splitlines()[0] self.assertIn(os.sep + ".s" + os.sep, ran) phases = [e.get("phase") for e in events if e.get("event") == "phase"] + phases = [p for i, p in enumerate(phases) if i == 0 or p != "test" or phases[i - 1] != "test"] # progress lines of the test start repeat it self.assertEqual(phases, ["feed", "download", "verify", "verify", "test", "switch", "done"]) progress = [e for e in events if e.get("event") == "progress"] self.assertTrue(progress and progress[-1]["percent"] == 100 and progress[-1]["done"] == progress[-1]["total"]) @@ -457,7 +458,7 @@ class StartPathSignature(UpdaterCase): class LazyModel(UpdaterCase): """A server that is "ready" with its model unloaded has not generated anything yet; the test start forces the load and the probe.""" - def run_default(self, started, verified): + def run_default(self, started, verified, tail=None): from strata_control import runtime self.install_current() folder = fx.build_package(self.root / "lazy", "0.1.46", key=self.key) @@ -466,7 +467,8 @@ class LazyModel(UpdaterCase): shutil.copytree(folder, stage / "engine" / folder.name) component = ec.read_manifest(stage / "engine" / folder.name) with mock.patch.object(runtime, "start", return_value=started), mock.patch.object(runtime, "verify", return_value=verified) as verify, mock.patch.object(runtime, "stop", return_value={}): - result = updater.default_test_start(stage, component, self.ctx()) + with mock.patch.object(updater, "_log_tail", return_value=tail or ""): + result = updater.default_test_start(stage, component, self.ctx()) return result, verify def test_an_unloaded_ready_server_is_made_to_answer_before_the_engine_passes(self): @@ -478,6 +480,51 @@ class LazyModel(UpdaterCase): def test_an_engine_that_cannot_answer_does_not_pass(self): with self.assertRaisesRegex(updater.TestStartFailed, "one-token probe"): self.run_default({"ok": True, "state": "ready", "generation_ready": False}, {"ok": False, "state": "failed", "error": "probe_generation_no_tokens"}) + def expired(self, phase, words, busy): + # #3683: the engine log always mentions VRAM, so a wait that expired used to be blamed on a busy graphics card + tail = " | strata serve: 358 MiB of VRAM free with everything loaded" + with self.assertRaises(updater.TestStartFailed) as raised: + self.run_default({"ok": False, "state": "starting", "error": "startup_wait_expired", "phase": phase}, {}, tail=tail) + text = str(raised.exception) + self.assertIn(words, text) + self.assertEqual(raised.exception.busy, busy) + self.assertNotIn("graphics card or memory looks busy", text) + self.assertNotIn("358 MiB", text) + self.assertIn("test-start-", text) # where the kept log is + + def test_an_expired_start_with_the_model_loaded_says_it_did_not_answer(self): + self.expired("verifying_generation", "did not answer one token", False) + + def test_an_expired_start_with_an_unmatched_ready_file_says_so(self): + self.expired("ready_file_not_matched", "could not match it to the engine process", False) + + def test_an_expired_start_that_was_still_loading_says_so(self): + self.expired("loading", "still loading the model", True) + + def test_the_test_start_shows_progress_while_it_waits(self): + self.install_current() + folder = fx.build_package(self.root / "lazy", "0.1.46", key=self.key) + stage = self.root / "stage" + (stage / "engine").mkdir(parents=True) + shutil.copytree(folder, stage / "engine" / folder.name) + component = ec.read_manifest(stage / "engine" / folder.name) + events = [] + ctx = self.ctx() + ctx.emit = events.append + + def fake_start(name, **kw): + for status in ({"state": "starting", "phase": "loading"}, {"state": "starting", "phase": "loading"}, + {"state": "starting", "phase": "verifying_generation"}, {"state": "ready"}): + kw["on_status"](status) + return {"ok": True, "state": "ready", "generation_ready": True} + + from strata_control import runtime + with mock.patch.object(runtime, "start", side_effect=fake_start), mock.patch.object(runtime, "stop", return_value={}): + updater.default_test_start(stage, component, ctx) + lines = [e["message"] for e in events if e.get("phase") == "test"] + self.assertEqual(len(lines), 2) # one per phase change, not one per poll + self.assertIn("loading the model", lines[0]) + self.assertIn("answer one token", lines[1]) class OtherComponents(UpdaterCase):