From c67180edf1bf46c3ade72bd87e73b8cf69c0d6ab Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Thu, 22 Oct 2026 11:32:32 +0200 Subject: [PATCH] Owner round 8: show the real engine error, keep cards and roles, honour --mtp off, plan every download, check the engine version F5: a start that did not reach ready names the stage, the cause line from the engine log, a next step (render group on Linux, smaller context, strata update) and the log path; --no-tui and runs without a keyboard never ask 'Keep or move?' and print what was kept. F3: a context or picture change forwards the installed cards and Main/Helper roles to setup. N3: --mtp on|off reaches setup, and setup no longer fetches the draft layer for --mtp off. N4/N2: --plan counts a picture reader unless one sits beside the files, names the --vision off and --mtp off switches, and counts the ready-made pack (NVFP4) setup would fetch; setup's disk hint is --data-dir under launch. N5/N6: STRATA_DATA_DIR/install is looked at first, --plan says when an earlier install is the one in use, and an installed engine older than the model needs is updated or named. N8: --plan warns when the file headers say another family or model than the one named. N9: update --check names the package it selected. N11: the Arc adopt path takes Gyro and the sentence has no double full stop. --- setup.py | 18 +- strata_cli/launch/adopt.py | 27 ++- strata_cli/launch/cmd.py | 14 +- strata_cli/launch/modelstate.py | 7 +- strata_cli/launch/runner.py | 229 ++++++++++++++++++++- strata_cli/update_cmd.py | 7 + strata_control/discovery.py | 3 + tests/terminal/test_launch.py | 3 +- tests/terminal/test_round8_fixes.py | 296 ++++++++++++++++++++++++++++ 9 files changed, 574 insertions(+), 30 deletions(-) create mode 100644 tests/terminal/test_round8_fixes.py 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 9df6ce55..9d0903c9 100644 --- a/strata_cli/launch/runner.py +++ b/strata_cli/launch/runner.py @@ -34,6 +34,31 @@ 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."] + + +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'.""" @@ -418,6 +443,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 @@ -483,12 +509,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] @@ -520,6 +552,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. @@ -541,6 +586,25 @@ 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 ())) + 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 @@ -627,6 +691,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)] @@ -641,6 +707,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", @@ -658,6 +726,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) @@ -698,7 +785,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 @@ -887,7 +974,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) + ".", @@ -923,6 +1010,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"] @@ -1101,8 +1196,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 @@ -1152,11 +1247,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: @@ -1174,14 +1278,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() @@ -1248,6 +1402,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/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..6fac3b9e --- /dev/null +++ b/tests/terminal/test_round8_fixes.py @@ -0,0 +1,296 @@ +"""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_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()