Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Preflight the Codex GGUF check before loading the model (#7873)
Nilaybece6d2ab433
diff --git a/studio/backend/hub/schemas/inventory.py b/studio/backend/hub/schemas/inventory.pyindex 8aee14deaa2..2e99dca4e81 100644--- a/studio/backend/hub/schemas/inventory.py+++ b/studio/backend/hub/schemas/inventory.py@@ -34,6 +34,13 @@ class GgufVariantDetail(BaseModel):False,description = "Whether this variant has an in-progress (.incomplete) blob in cache",)+ cleanable: bool = Field(+ False,+ description = (+ "Row exists only to offer deleting an empty leftover <quant>/ folder; the "+ "listing has no such weights, so it never proves a load would find any"+ ),+ )partial_transport: Optional[str] = Field(None,description = (@@ -57,6 +64,21 @@ class GgufVariantsResponse(BaseModel):default_variant: Optional[str] = Field(None, description = "Recommended default quantization variant")+ resolved_locally: bool = Field(+ False,+ description = "Whether this answer came from resolving repo_id as a local path",+ )+ loadable_variants: Optional[List[str]] = Field(+ None,+ description = (+ "Quants the load resolver resolves for this identifier; None when unanswered "+ "(remote answers, or a server that predates the field)"+ ),+ )+ loadable: Optional[bool] = Field(+ None,+ description = "Whether a variantless load resolves GGUF weights; None when unanswered",+ )class LocalModelCapabilities(BaseModel):diff --git a/studio/backend/hub/services/models/gguf_variants.py b/studio/backend/hub/services/models/gguf_variants.pyindex 717f693164f..2aaac31a187 100644--- a/studio/backend/hub/services/models/gguf_variants.py+++ b/studio/backend/hub/services/models/gguf_variants.py@@ -6,6 +6,7 @@from __future__ import annotationsimport asyncio+import reimport threadingimport timeimport weakref@@ -27,6 +28,7 @@ from hub.utils.hf_cache_state import (repo_cache_dir_name,)from hub.utils.gguf import (+ GgufVariantInfo,extract_quant_label,iter_hf_cache_snapshots,is_big_endian_gguf_path,@@ -41,6 +43,9 @@ from hub.utils.paths import (is_local_path,is_valid_repo_id as _is_valid_repo_id,)++# Loader's normalizer, not the hub's: they disagree on WSL, and only it names what the load opens.+from utils.paths import normalize_path as _loader_normalize_pathfrom hub.services.models.common import (_is_mmproj_filename,_is_mtp_drafter_path,@@ -526,10 +531,234 @@ def _mark_empty_dir_cleanables(variants[i] = v.model_copy(update = {"partial": True})for key, label in sorted(empty_by_key.items()):if key not in listed:- variants.append(GgufVariantDetail(filename = f"{label}.gguf", quant = label, partial = True))+ variants.append(+ GgufVariantDetail(+ filename = f"{label}.gguf", quant = label, partial = True, cleanable = True+ )+ )return response.model_copy(update = {"variants": variants})+def _direct_gguf_loads(path: Path) -> bool:+ """Whether the load path takes *path* itself as the model.++ Mirrors ``detect_gguf_model``: refuses companions (mmproj, MTP/dspark+ drafter) and big-endian builds by name+parent, same as the load path.+ """+ # Load extractor, not the hub one: they disagree on F16-be-checkpoint-Q4_K_M shapes.+ from utils.models.model_config import _extract_quant_label++ context = f"{path.parent.name}/{path.name}"+ return not (+ _is_mmproj_filename(path.name)+ or _is_mtp_drafter_path(context)+ or is_big_endian_gguf_path(context, _extract_quant_label(context))+ )+++# llama.cpp's split grammar (model_config._GGUF_SPLIT_FILE_RE): five digits exactly, since a+# shorter name loads as an ordinary file, not the cache scan's looser -\d{3,}- resume form.+_DIRECT_SPLIT_RE = re.compile(r"^(?P<stem>.+)-(?P<index>\d{5})-of-(?P<total>\d{5})$", re.IGNORECASE)+++def _direct_gguf_split_is_whole(path: Path) -> bool:+ """Whether *path*'s split set is entirely beside it (True when it is not a split).++ llama.cpp resolves a split's siblings from the main shard's directory (see+ llama_cpp._snapshot_has_all_shards), so a lone shard fails after teardown.+ A symlinked shard follows its target, like _local_gguf_load_path. Unknown+ (unreadable directory, nonsense total) reports whole to keep the row ready.+ """+ match = _DIRECT_SPLIT_RE.match(path.name.rsplit(".", 1)[0])+ if match is None:+ return True+ total = int(match.group("total"))+ if total < 2:+ return True+ sibling = re.compile(+ re.escape(match.group("stem"))+ + r"-(\d{"+ + str(len(match.group("index")))+ + r"})-of-"+ + re.escape(match.group("total"))+ + r"\.gguf$",+ re.IGNORECASE,+ )++ def _indexes_beside(target: Path, pattern) -> set:+ return {+ int(m.group(1))+ for p in target.parent.iterdir()+ if (m := pattern.match(p.name)) and p.is_file() and p.stat().st_size > 0+ }++ def _target_set_is_whole(target: Path) -> bool:+ """Whether the symlink target's own declared set is beside it.++ The target names its own grammar/total (need not match the alias); the+ load launches whatever the target declares.+ """+ m = _DIRECT_SPLIT_RE.match(target.name.rsplit(".", 1)[0])+ if m is None:+ # Split-named link on an ordinary target: loads as-is, nothing missing.+ return True+ target_total = int(m.group("total"))+ pattern = re.compile(+ re.escape(m.group("stem"))+ + r"-(\d{"+ + str(len(m.group("index")))+ + r"})-of-"+ + re.escape(m.group("total"))+ + r"\.gguf$",+ re.IGNORECASE,+ )+ return _indexes_beside(target, pattern) >= set(range(1, target_total + 1))++ try:+ found = _indexes_beside(path, sibling)+ if not found >= set(range(1, total + 1)) and path.is_symlink():+ # _local_gguf_load_path resolves siblings from the TARGET, so a renamed alias+ # still loads the target's real set -- and a torn target stays torn.+ return _target_set_is_whole(path.resolve())+ except OSError:+ return True+ # Declared indexes, not a count: an over-indexed stray must not stand in for a missing+ # shard, and a zero-byte sibling is an interrupted copy.+ return found >= set(range(1, total + 1))+++# Cache scan's looser grammar (hub.utils.inventory_scan._GGUF_SPLIT_RE), not the five digits above.+_CACHE_SPLIT_RE = re.compile(r"-(\d{3,})-of-(\d{3,})(?=\.gguf$)", re.IGNORECASE)++# Only enumerates candidates for the resolver to adjudicate; drift costs a candidate, not a verdict.+_KNOWN_QUANT_RE = re.compile(+ r"(UD-)?"+ r"(MXFP[0-9]+(?:_[A-Z0-9]+)*"+ r"|IQ[0-9]+_[A-Z]+(?:_[A-Z0-9]+)?"+ r"|TQ[0-9]+_[0-9]+"+ r"|Q[0-9]+_K_[A-Z]+"+ r"|Q[0-9]+_[0-9]+"+ r"|Q[0-9]+_K"+ r"|BF16|F16|F32)"+ r"(-[0-9]+(?:\.[0-9]+)?bpw)?",+ re.IGNORECASE,+)+++def _will_serve(resolved: Optional[str]) -> bool:+ """Whether llama-server can actually open what the resolver chose.++ The resolver is extension-authoritative by design (it must answer inside+ the Windows lock window), so it says yes to an empty copy or a torn split+ too -- the two ways a resolved path still fails after teardown.+ """+ if not resolved:+ return False+ try:+ path = Path(resolved)+ # The resolver answers for nonexistent paths, so absence is caught here: "no such+ # file" is definite, a read error (Windows lock window) stays unknown and serves.+ # stat(), not exists(), which swallows every OSError on 3.14 and would read a+ # sharing violation as absence.+ try:+ size = path.stat().st_size+ except (FileNotFoundError, NotADirectoryError):+ return False+ return size > 0 and _direct_gguf_split_is_whole(path)+ except OSError:+ return True+++def _loadable_variants(identifier: str, variants):+ """The advertised quants a load of *identifier* would actually serve.++ Authoritative by construction: asks the same resolver /api/inference/load+ uses, then checks the chosen file as llama-server would find it, so a+ client never has to predict either from filenames. One resolver call per+ row, local answers only. None when the question does not apply.+ """+ from utils.models.model_config import _find_local_gguf_by_variant++ # from_identifier only consults the variant for a DIRECTORY; a direct file loads itself+ # regardless, so leave it unanswered rather than be stricter than the load. stat(), not+ # is_file(): a locked file must stay unanswered (an empty list is authoritative at the+ # gate), which is_file() cannot express -- it raises here, and answers False from 3.14.+ import stat as _stat++ try:+ if _stat.S_ISREG(Path(identifier).expanduser().stat().st_mode):+ return None+ except (FileNotFoundError, NotADirectoryError):+ pass+ except OSError:+ return None++ # The resolver walks the tree per call, so spellings are deduped against `seen` first:+ # ~2 calls per row (36 for 18 quants, 179ms over 144 files), not one per spelling. Each+ # alias is still confirmed, so a token binding a different file is never advertised.+ accepted: list = []+ seen = set()+ for variant in variants:+ quant = getattr(variant, "quant", None)+ if not isinstance(quant, str) or not quant:+ continue+ try:+ bound = _find_local_gguf_by_variant(identifier, quant)+ if not _will_serve(bound):+ continue+ except Exception:+ continue+ key = quant.strip().lower()+ if key not in seen:+ seen.add(key)+ accepted.append(quant)+ # The resolver also takes the snapshot-relative stem (BF16/model) and the basename's+ # own tokens; derive those and let it confirm each. It returns an absolute path, so a+ # relative identifier must be resolved the same way or its alias is lost. Unresolved+ # first: a symlink out of the tree still answers BF16/model there, but not resolved.+ relative = Path(bound).name+ for base_raw, bound_path in (+ (Path(identifier).expanduser(), Path(bound)),+ (Path(identifier).expanduser().resolve(), Path(bound).resolve()),+ ):+ try:+ base = base_raw.parent if base_raw.is_file() else base_raw+ relative = bound_path.relative_to(base).as_posix()+ break+ except (OSError, ValueError):+ continue+ basename = Path(bound).name+ derived = {+ re.sub(r"-\d{3,}-of-\d{3,}$", "", relative.rsplit(".", 1)[0]),+ re.sub(r"-\d{3,}-of-\d{3,}$", "", basename.rsplit(".", 1)[0]),+ }+ for match in _KNOWN_QUANT_RE.finditer(basename.rsplit(".", 1)[0]):+ prefix, core, bpw = match.group(1) or "", match.group(2), match.group(3) or ""+ derived.add(f"{prefix}{core}")+ if bpw:+ derived.add(f"{prefix}{core}{bpw}")+ for spelling in sorted(derived):+ key = spelling.strip().lower()+ if not key or key in seen:+ continue+ seen.add(key)+ try:+ if _will_serve(_find_local_gguf_by_variant(identifier, spelling)):+ accepted.append(spelling)+ except Exception:+ continue+ return accepted+++def _loads_without_variant(identifier: str) -> bool:+ """Whether a variantless load of *identifier* would serve GGUF weights."""+ from utils.models.model_config import detect_gguf_model+ try:+ return _will_serve(detect_gguf_model(identifier))+ except Exception:+ return False++def _complete_quants_under(snapshot: str):"""Quants whose shards are all present under *snapshot*, or None if unknown.@@ -537,9 +766,36 @@ def _complete_quants_under(snapshot: str):working folder unusable."""try:- return hf_cache_scan.complete_snapshot_variants(snapshot)+ complete = hf_cache_scan.complete_snapshot_variants(snapshot)except Exception:return None+ if complete is None:+ return None+ return complete+++def _complete_with_servable(snapshot: str, complete, variants):+ """*complete* plus the quants whose bound file the load would actually serve.++ The scan's looser -\\d{3,}- grammar can read a name the LOAD treats as an+ ordinary file (five-digit splits only) as a torn set. Rather than re-judge+ names here, ask the resolver what it actually chose for the quant.+ """+ if complete is None:+ return None+ from utils.models.model_config import _find_local_gguf_by_variant++ repaired = set(complete)+ for variant in variants:+ quant = getattr(variant, "quant", None)+ if not isinstance(quant, str) or not quant or quant in repaired:+ continue+ try:+ if _will_serve(_find_local_gguf_by_variant(snapshot, quant)):+ repaired.add(quant)+ except Exception:+ continue+ return repaired# One scan per identical request in flight. Aborting the HTTP request cannot stop the scan@@ -599,6 +855,10 @@ async def get_gguf_variants_answer(# Set by whichever branch answers, and returned with the listing: the HF cache answers# before local_path, so a caller cannot infer the copy from the request alone.answered_from: list[Optional[str]] = [None]+ # Set by the existence-first local branch below: a repo-shaped id resolving to a directory+ # is answered by that directory alone, not the HF cache of the same-named repo -- else a+ # GGUF-less directory could evict the resident model via a cleanable row from the cache.+ answered_locally = [False]def _compute() -> GgufVariantsResponse:repo_cache_dir = (@@ -703,12 +963,67 @@ async def get_gguf_variants_answer(return responsereturn response.model_copy(update = {"variants": [*response.variants, *extra]})- # Local directory path (e.g. LM Studio models) — scan filesystem- if is_local_path(repo_id):- variants, has_vision = list_local_gguf_variants(repo_id)+ # Local directory path (e.g. LM Studio models) — scan filesystem. Load-path parity:+ # from_identifier resolves existence-first, so a marker-less relative name that exists+ # here is a local model, not a Hub id, and a direct .gguf file loads without the+ # metadata siblings the directory scan requires. It also normalizes first, so every+ # question below must ask about the same path: under WSL "C:\\models\\qwen" maps to+ # /mnt/c/models/qwen, and probing the raw spelling would report a working model+ # unloadable.+ local_id = _loader_normalize_path(repo_id) if is_local_path(repo_id) else repo_id+ local_target = None+ try:+ probe = Path(local_id).expanduser()+ if is_local_path(repo_id) or probe.exists():+ local_target = probe+ except OSError:+ local_target = None+ if local_target is not None:+ variants, has_vision = list_local_gguf_variants(local_id)+ # The load id is this path, so a scan-torn quant is still ready when the file the+ # resolver binds opens fine.+ complete = _complete_with_servable(local_id, _complete_quants_under(local_id), variants)+ if (+ not variants+ and local_target.is_file()+ and local_target.suffix.lower() == ".gguf"+ and _direct_gguf_loads(local_target)+ ):+ # An unmarked-parent .gguf is skipped by the directory scan but detect_gguf_model+ # still loads it; falling back only here keeps a marked parent's siblings.+ try:+ size = local_target.stat().st_size+ except OSError:+ size = 0+ # The load resolver's own extractor over the context it reads, so the quant is+ # what the echoed load resolves (the hub one differs on F16-checkpoint-Q4_K_M).+ from utils.models.model_config import _extract_quant_label++ variants = [+ GgufVariantInfo(+ filename = local_target.name,+ quant = _extract_quant_label(+ f"{local_target.parent.name}/{local_target.name}"+ ),+ size_bytes = size,+ )+ ]+ # The shard scan resolves a file to its marked parent, so an unmarked one walks+ # a bare file and misreports the row. Ask the file itself: whole unless it is a+ # split missing a sibling or a zero-byte interrupted copy.+ complete = None if size > 0 and _direct_gguf_split_is_whole(local_target) else set()answered_from[0] = repo_id- # The load id is this path, so a quant offered here has to resolve here.- return _local_response(repo_id, variants, has_vision, _complete_quants_under(repo_id))+ answered_locally[0] = True+ # Surface the resolution so the CLI gate matches on the local resolver's exact+ # labels rather than the id's shape, and answers its real question -- would this+ # load resolve -- with the loader itself, so no client mirrors its grammar.+ return _local_response(repo_id, variants, has_vision, complete).model_copy(+ update = {+ "resolved_locally": True,+ "loadable_variants": _loadable_variants(local_id, variants),+ "loadable": _loads_without_variant(local_id),+ }+ )# Reject invalid remote repo_ids up front (like download/delete) so a# malformed id returns 400 instead of a 500 from the HF client.@@ -1081,7 +1396,7 @@ async def get_gguf_variants_answer(if enriched.variants:return enrichedraise- if skip:+ if skip or answered_locally[0]:return responsereturn _mark_empty_dir_cleanables(repo_id,diff --git a/studio/backend/hub/tests/test_model_services.py b/studio/backend/hub/tests/test_model_services.pyindex 054f1395284..9e39d084a6a 100644--- a/studio/backend/hub/tests/test_model_services.py+++ b/studio/backend/hub/tests/test_model_services.py@@ -2877,6 +2877,21 @@ def test_completed_gguf_split_variant_requires_all_shards(tmp_path):assert "Q8_0" in inventory_scan._completed_gguf_variants(snapshot)+def test_completed_gguf_variants_ignores_big_endian_by_the_loader_label(tmp_path):+ # The scan reads Q4_K_M here, the loader reads F16 and refuses the file as big-endian. By+ # the scan's label it would vouch for Q4_K_M, and _complete_with_servable skips complete+ # quants, so the torn split below would be reported downloaded.+ snapshot = tmp_path / "snapshot"+ snapshot.mkdir()+ (snapshot / "0-F16-be-checkpoint-Q4_K_M.gguf").write_bytes(b"GGUF")+ (snapshot / "z-Q4_K_M-00001-of-00002.gguf").write_bytes(b"GGUF")++ assert "Q4_K_M" not in inventory_scan._completed_gguf_variants(snapshot)++ (snapshot / "z-Q4_K_M-00002-of-00002.gguf").write_bytes(b"GGUF")+ assert "Q4_K_M" in inventory_scan._completed_gguf_variants(snapshot)++def test_variant_partial_accepts_variant_filtered_legacy_hashes(monkeypatch, tmp_path):monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path)diff --git a/studio/backend/hub/utils/gguf.py b/studio/backend/hub/utils/gguf.pyindex 6efcf465784..7a2e3d1ab99 100644--- a/studio/backend/hub/utils/gguf.py+++ b/studio/backend/hub/utils/gguf.py@@ -578,7 +578,11 @@ def list_gguf_variants(has_vision = Truecontinuequant = extract_quant_label(filename)- if is_big_endian_gguf_path(filename, quant):+ # The two extractors disagree on F16-be-checkpoint-Q4_K_M shapes; judge with the+ # loader's label so no row is advertised for a file the remote detector refuses.+ from utils.models.model_config import _extract_quant_label as _loader_quant++ if is_big_endian_gguf_path(filename, _loader_quant(filename)):continuequant_totals[quant] = quant_totals.get(quant, 0) + int(getattr(sibling, "size", 0) or 0)quant_first_file.setdefault(quant, filename)@@ -648,7 +652,11 @@ def list_local_gguf_variants(if _is_local_mtp_drafter(file, custom_root, rel):continuequant = extract_quant_label(rel)- if is_big_endian_gguf_path(rel, quant):+ # The two extractors disagree on F16-be-checkpoint-Q4_K_M shapes; judge with the+ # loader's label so no row is listed for a file the local detector refuses.+ from utils.models.model_config import _extract_quant_label as _loader_quant++ if is_big_endian_gguf_path(rel, _loader_quant(rel)):continuequant_totals[quant] = quant_totals.get(quant, 0) + sizequant_first_file.setdefault(quant, rel)diff --git a/studio/backend/hub/utils/inventory_scan.py b/studio/backend/hub/utils/inventory_scan.pyindex d43d6772f9a..ce6cd1ba26b 100644--- a/studio/backend/hub/utils/inventory_scan.py+++ b/studio/backend/hub/utils/inventory_scan.py@@ -732,8 +732,12 @@ def _completed_gguf_variants(snapshot_dir: Optional[Path]) -> set[str]:if not is_gguf_filename(rel) or is_mmproj_filename(rel) or is_mtp_drafter_path(rel):continuequant = extract_quant_label(rel)- # Mirror the lister: a big-endian build is never offered, so it cannot vouch for the quant.- if is_big_endian_gguf_path(rel, quant):+ # Mirror the lister: a big-endian build is never offered, so it cannot vouch for the+ # quant. Judged with the loader's label, since the two extractors disagree on+ # F16-be-checkpoint-Q4_K_M and this file must not mark Q4_K_M complete.+ from utils.models.model_config import _extract_quant_label as _loader_quant++ if is_big_endian_gguf_path(rel, _loader_quant(rel)):continueif empty:# The resolver still opens this file, so a zero-byte first pick is unjudgeable.diff --git a/studio/backend/models/models.py b/studio/backend/models/models.pyindex e03e8969ed3..63bb543a205 100644--- a/studio/backend/models/models.py+++ b/studio/backend/models/models.py@@ -149,6 +149,11 @@ class GgufVariantDetail(BaseModel):"already computes it; carry it through so callers can hide a quant whose shards ""are incomplete instead of offering one that cannot load.",)+ cleanable: bool = Field(+ False,+ description = "Row exists only to offer deleting an empty leftover <quant>/ folder; "+ "the listing has no such weights, so it never proves a load would find any.",+ )class GgufVariantsResponse(BaseModel):@@ -168,6 +173,21 @@ class GgufVariantsResponse(BaseModel):None,description = "Native max context from GGUF metadata; set once a variant is downloaded",)+ resolved_locally: bool = Field(+ False,+ description = "Whether this answer came from resolving repo_id as a local path",+ )+ loadable_variants: Optional[List[str]] = Field(+ None,+ description = (+ "Quants the load resolver resolves for this identifier; None when unanswered "+ "(remote answers, or a server that predates the field)"+ ),+ )+ loadable: Optional[bool] = Field(+ None,+ description = "Whether a variantless load resolves GGUF weights; None when unanswered",+ )class LocalModelInfo(BaseModel):diff --git a/studio/backend/routes/models.py b/studio/backend/routes/models.pyindex f37c8eece35..6d8d0d2479b 100644--- a/studio/backend/routes/models.py+++ b/studio/backend/routes/models.py@@ -3284,12 +3284,16 @@ async def get_gguf_variants(downloaded = bool(v.downloaded),update_available = bool(getattr(v, "update_available", False)),partial = bool(getattr(v, "partial", False)),+ cleanable = bool(getattr(v, "cleanable", False)),)for v in response.variants],has_vision = response.has_vision,default_variant = response.default_variant,context_length = await _read_native_context_length_bounded(context_model, local),+ resolved_locally = bool(getattr(response, "resolved_locally", False)),+ loadable_variants = getattr(response, "loadable_variants", None),+ loadable = getattr(response, "loadable", None),)except HTTPException:raisediff --git a/studio/backend/tests/test_cached_gguf_routes.py b/studio/backend/tests/test_cached_gguf_routes.pyindex d643f325b82..9b76ce0b1f0 100644--- a/studio/backend/tests/test_cached_gguf_routes.py+++ b/studio/backend/tests/test_cached_gguf_routes.py@@ -3837,6 +3837,21 @@ def test_switching_cache_storage_does_not_join_a_stuck_scan(monkeypatch, tmp_patassert any("healthyvol" in root for root in scanned), scanned+def test_gguf_variants_route_carries_local_resolution(monkeypatch, tmp_path):+ # The CLI gate reads resolved_locally, so the legacy constructor must carry it.+ monkeypatch.chdir(tmp_path)+ (tmp_path / "models" / "qwen").mkdir(parents = True)+ (tmp_path / "models" / "qwen" / "q-Q4_K_M.gguf").write_bytes(b"GGUF")++ result = asyncio.run(+ models_route.get_gguf_variants(+ repo_id = "models/qwen", hf_token = None, current_subject = "test-user"+ )+ )+ assert result.resolved_locally is True+ assert [v.quant for v in result.variants] == ["Q4_K_M"]++def _write_cached_gguf(hub_cache: Path,repo_id: str,diff --git a/studio/backend/tests/test_gguf_variants_local_resolution.py b/studio/backend/tests/test_gguf_variants_local_resolution.pynew file mode 100644index 00000000000..d37816d7e10--- /dev/null+++ b/studio/backend/tests/test_gguf_variants_local_resolution.py@@ -0,0 +1,679 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Load-path parity for /api/models/gguf-variants local resolution."""++import asyncio+import os++import pytest++from hub.services.models.gguf_variants import get_gguf_variants_response+++def _variants(repo_id: str, **kwargs):+ return asyncio.run(get_gguf_variants_response(repo_id, **kwargs))+++def in_tmp_cwd(tmp_path, monkeypatch):+ monkeypatch.chdir(tmp_path)+ return tmp_path+++def test_markerless_relative_dir_resolves_locally(in_tmp_cwd):+ gguf_dir = in_tmp_cwd / "models" / "qwen"+ gguf_dir.mkdir(parents = True)+ (gguf_dir / "qwen-Q4_K_M.gguf").write_bytes(b"GGUF")++ response = _variants("models/qwen")+ assert [v.quant for v in response.variants] == ["Q4_K_M"]+ # Lets the CLI gate match against the local resolver's labels.+ assert response.resolved_locally is True+++def test_direct_gguf_file_is_a_loadable_variant(in_tmp_cwd):+ gguf = in_tmp_cwd / "foo-Q4_K_M.gguf"+ gguf.write_bytes(b"GGUF")++ response = _variants(os.fspath(gguf))+ assert [v.filename for v in response.variants] == ["foo-Q4_K_M.gguf"]+ assert response.variants[0].quant == "Q4_K_M"+ # The file is the model; the shard scan's empty answer must not mark the only row partial.+ assert response.variants[0].downloaded is True+ assert response.variants[0].partial is False+++def test_markerless_relative_gguf_file_resolves_locally(in_tmp_cwd):+ (in_tmp_cwd / "models").mkdir()+ (in_tmp_cwd / "models" / "foo.gguf").write_bytes(b"GGUF")++ response = _variants("models/foo.gguf")+ assert [v.filename for v in response.variants] == ["foo.gguf"]+++def test_nonexistent_local_syntax_path_still_returns_empty(in_tmp_cwd):+ response = _variants(os.fspath(in_tmp_cwd / "missing-dir"))+ assert response.variants == []+++def test_direct_gguf_file_in_marked_dir_still_lists_siblings(in_tmp_cwd):+ # The load resolves a .gguf in a marked directory to the directory, so the listing keeps+ # sibling quants and the vision flag.+ (in_tmp_cwd / "config.json").write_text("{}")+ (in_tmp_cwd / "model-Q4_K_M.gguf").write_bytes(b"GGUF")+ (in_tmp_cwd / "model-Q8_0.gguf").write_bytes(b"GGUF" * 2)+ (in_tmp_cwd / "mmproj-F16.gguf").write_bytes(b"GGUF")++ response = _variants(os.fspath(in_tmp_cwd / "model-Q4_K_M.gguf"))+ assert sorted(v.quant for v in response.variants) == ["Q4_K_M", "Q8_0"]+ assert response.has_vision is True+ # A marked parent is still scanned for completeness.+ assert all(v.downloaded for v in response.variants)+++ "relpath",+ [+ "mmproj-F16.gguf",+ "mtp-model-Q4_K_M.gguf",+ "MTP/model-Q8_0-MTP.gguf",+ "dspark/dspark-model-Q8_0.gguf",+ "stories260K-be.gguf",+ ],+)+def test_direct_auxiliary_gguf_file_is_not_a_variant(in_tmp_cwd, relpath):+ # detect_gguf_model refuses companions and big-endian builds, so a row would offer a+ # load that cannot happen.+ from utils.models.model_config import detect_gguf_model++ target = in_tmp_cwd / relpath+ target.parent.mkdir(parents = True, exist_ok = True)+ target.write_bytes(b"GGUF")++ assert detect_gguf_model(os.fspath(target)) is None+ assert _variants(os.fspath(target)).variants == []+++def test_direct_gguf_file_quant_round_trips_through_the_load_path(in_tmp_cwd):+ # Clients echo the quant back as gguf_variant, so it must resolve for the same identifier.+ from utils.models.model_config import ModelConfig++ gguf = in_tmp_cwd / "foo-Q4_K_M.gguf"+ gguf.write_bytes(b"GGUF")++ quant = _variants(os.fspath(gguf)).variants[0].quant+ config = ModelConfig.from_identifier(os.fspath(gguf), gguf_variant = quant)+ assert config is not None and config.is_gguf+ assert config.gguf_file == os.fspath(gguf)+ # from_identifier consults the quant only for a directory, so the listing must not be stricter.+ assert ModelConfig.from_identifier(os.fspath(gguf), gguf_variant = "Q8_0").is_gguf is True+ assert _variants(os.fspath(gguf)).loadable_variants is None+++def test_direct_gguf_file_quant_round_trips_case_insensitively(in_tmp_cwd):+ # llama.cpp matches quant labels case-insensitively, so a lowercase --gguf-variant must+ # resolve here too, or the load evicts the resident model before failing.+ from utils.models.model_config import ModelConfig++ gguf = in_tmp_cwd / "foo-Q4_K_M.gguf"+ gguf.write_bytes(b"GGUF")++ config = ModelConfig.from_identifier(os.fspath(gguf), gguf_variant = "q4_k_m")+ assert config is not None and config.is_gguf+ assert config.gguf_file == os.fspath(gguf)+ # A directory of the same weights answers the same spelling.+ marked = in_tmp_cwd / "marked"+ marked.mkdir()+ (marked / "config.json").write_text("{}")+ (marked / "foo-Q4_K_M.gguf").write_bytes(b"GGUF")+ dir_config = ModelConfig.from_identifier(os.fspath(marked), gguf_variant = "q4_k_m")+ assert dir_config is not None and dir_config.is_gguf+++def test_direct_gguf_label_is_the_load_resolvers_label(in_tmp_cwd):+ # The extractors disagree on F16-checkpoint-Q4_K_M; the advertised quant must be the+ # one the echoed load resolves.+ from utils.models.model_config import ModelConfig++ gguf = in_tmp_cwd / "F16-checkpoint-Q4_K_M.gguf"+ gguf.write_bytes(b"GGUF")++ quant = _variants(os.fspath(gguf)).variants[0].quant+ config = ModelConfig.from_identifier(os.fspath(gguf), gguf_variant = quant)+ assert config is not None and config.is_gguf+ assert config.gguf_file == os.fspath(gguf)+++def test_marked_dir_resolves_the_bpw_stripped_label(in_tmp_cwd):+ # Listings advertise the hub-style stripped spelling, which the directory resolver takes too.+ from utils.models.model_config import ModelConfig++ marked = in_tmp_cwd / "m"+ marked.mkdir()+ (marked / "config.json").write_text("{}")+ (marked / "model-IQ4_XS-3.53bpw.gguf").write_bytes(b"GGUF")++ config = ModelConfig.from_identifier(os.fspath(marked), gguf_variant = "IQ4_XS")+ assert config is not None and config.is_gguf+++def test_direct_big_endian_check_uses_the_load_extractor(in_tmp_cwd):+ # detect_gguf_model refuses this shape (F16 reads before the be marker), so it must+ # not be advertised as loadable.+ from utils.models.model_config import detect_gguf_model++ gguf = in_tmp_cwd / "F16-be-checkpoint-Q4_K_M.gguf"+ gguf.write_bytes(b"GGUF")++ assert detect_gguf_model(os.fspath(gguf)) is None+ assert _variants(os.fspath(gguf)).variants == []+++def test_variantless_pick_prefers_a_complete_candidate(in_tmp_cwd):+ # detect_gguf_model sorts by size and a torn split's lone shard can be the largest, so+ # the load must prefer a candidate it can open.+ from utils.models.model_config import detect_gguf_model++ (in_tmp_cwd / "config.json").write_text("{}")+ (in_tmp_cwd / "model-Q8_0.gguf").write_bytes(b"GGUF")+ (in_tmp_cwd / "model-Q4_K_M-00001-of-00002.gguf").write_bytes(b"GGUF" * 100)++ assert detect_gguf_model(os.fspath(in_tmp_cwd)).endswith("model-Q8_0.gguf")+++def test_parent_quant_does_not_resolve_a_different_basename_quant(in_tmp_cwd):+ # Q8_0/model-Q4_K_M.gguf IS the Q4_K_M file; matching it for Q8_0 serves wrong weights.+ from utils.models.model_config import ModelConfig, _find_local_gguf_by_variant++ marked = in_tmp_cwd / "m"+ (marked / "Q8_0").mkdir(parents = True)+ (marked / "config.json").write_text("{}")+ (marked / "Q8_0" / "model-Q4_K_M.gguf").write_bytes(b"GGUF")++ assert _find_local_gguf_by_variant(os.fspath(marked), "Q8_0") is None+ assert ModelConfig.from_identifier(os.fspath(marked), gguf_variant = "Q8_0").is_gguf is False+ # The file's own label still resolves it.+ assert _find_local_gguf_by_variant(os.fspath(marked), "Q4_K_M") is not None+++def test_direct_file_default_variant_resolves(in_tmp_cwd):+ # Clients load the advertised default directly, so it must resolve for the same file.+ from utils.models.model_config import ModelConfig++ gguf = in_tmp_cwd / "F16-checkpoint-Q4_K_M.gguf"+ gguf.write_bytes(b"GGUF")++ response = _variants(os.fspath(gguf))+ config = ModelConfig.from_identifier(os.fspath(gguf), gguf_variant = response.default_variant)+ assert config is not None and config.is_gguf+ assert config.gguf_file == os.fspath(gguf)+++def test_dir_resolver_accepts_the_advertised_hub_style_label(in_tmp_cwd):+ # The listing labels F16-checkpoint-Q4_K_M.gguf as Q4_K_M; echoing it back must resolve it.+ from utils.models.model_config import ModelConfig++ marked = in_tmp_cwd / "m"+ marked.mkdir()+ (marked / "config.json").write_text("{}")+ (marked / "F16-checkpoint-Q4_K_M.gguf").write_bytes(b"GGUF")++ quant = _variants(os.fspath(marked)).variants[0].quant+ config = ModelConfig.from_identifier(os.fspath(marked), gguf_variant = quant)+ assert config is not None and config.is_gguf+++def test_local_listing_filters_what_the_local_detector_refuses(in_tmp_cwd):+ # The local detector reads F16 before the be marker and refuses the file, so the+ # listing must not advertise a row for it.+ from utils.models.model_config import detect_gguf_model++ (in_tmp_cwd / "config.json").write_text("{}")+ (in_tmp_cwd / "F16-be-checkpoint-Q4_K_M.gguf").write_bytes(b"GGUF")++ assert detect_gguf_model(os.fspath(in_tmp_cwd)) is None+ assert _variants(os.fspath(in_tmp_cwd)).variants == []+++def test_short_shard_like_name_is_not_a_torn_split(in_tmp_cwd):+ # The split grammar is five digits exactly, so a -001-of-002 file loads on its own.+ lone = in_tmp_cwd / "model-Q4_K_M-001-of-002.gguf"+ lone.write_bytes(b"GGUF")++ row = _variants(os.fspath(lone)).variants[0]+ assert row.downloaded is True and row.partial is False+++def test_remote_listing_filters_what_the_remote_detector_refuses(monkeypatch):+ # The remote detector extracts F16 and refuses the be marker, so no row for that sibling.+ from types import SimpleNamespace++ from hub.utils.gguf import list_gguf_variants++ info = SimpleNamespace(+ siblings = [+ SimpleNamespace(rfilename = "F16-be-checkpoint-Q4_K_M.gguf", size = 100),+ SimpleNamespace(rfilename = "model-Q8_0.gguf", size = 10),+ ]+ )+ api = SimpleNamespace(model_info = lambda *a, **k: info)+ monkeypatch.setattr("huggingface_hub.HfApi", lambda token = None: api)++ variants, _, _ = list_gguf_variants("owner/repo")+ assert [v.quant for v in variants] == ["Q8_0"]+++def test_direct_gguf_bpw_label_round_trips_through_the_load_path(in_tmp_cwd):+ # The hub extractor drops the bpw modifier, so the shorter advertised label must still+ # resolve this file.+ from utils.models.model_config import ModelConfig++ gguf = in_tmp_cwd / "model-IQ4_XS-3.53bpw.gguf"+ gguf.write_bytes(b"GGUF")++ quant = _variants(os.fspath(gguf)).variants[0].quant+ config = ModelConfig.from_identifier(os.fspath(gguf), gguf_variant = quant)+ assert config is not None and config.is_gguf+ assert config.gguf_file == os.fspath(gguf)+++def test_torn_direct_split_is_not_offered_as_downloaded(in_tmp_cwd):+ # llama.cpp resolves siblings from the main shard's directory, so a lone shard fails+ # after teardown and must not be called ready.+ shard = in_tmp_cwd / "model-Q4_K_M-00001-of-00002.gguf"+ shard.write_bytes(b"GGUF")++ row = _variants(os.fspath(shard)).variants[0]+ assert row.quant == "Q4_K_M"+ assert row.downloaded is False and row.partial is True++ # The whole set beside it is ready, and an unsplit file is untouched.+ (in_tmp_cwd / "model-Q4_K_M-00002-of-00002.gguf").write_bytes(b"GGUF")+ whole = _variants(os.fspath(shard)).variants[0]+ assert whole.downloaded is True and whole.partial is False+++def test_local_answers_report_what_a_load_would_serve(in_tmp_cwd):+ # The gate's real question: the loader, plus the two ways a resolvable path still+ # fails llama-server (empty bytes, torn split).+ def _mk(name, *files):+ d = in_tmp_cwd / name+ d.mkdir()+ (d / "config.json").write_text("{}")+ for rel, data in files:+ target = d / rel+ target.parent.mkdir(parents = True, exist_ok = True)+ target.write_bytes(data)+ return _variants(os.fspath(d))++ ready = _mk("ready", ("m-Q4_K_M.gguf", b"GGUF"))+ assert ready.loadable is True and "Q4_K_M" in ready.loadable_variants++ empty = _mk("empty", ("m-Q4_K_M.gguf", b""))+ assert empty.loadable is False and empty.loadable_variants == []++ torn = _mk("torn", ("m-Q8_0-00001-of-00002.gguf", b"GGUF"))+ assert torn.loadable is False and torn.loadable_variants == []++ whole = _mk(+ "whole",+ ("m-Q8_0-00001-of-00002.gguf", b"GGUF"),+ ("m-Q8_0-00002-of-00002.gguf", b"GGUF"),+ )+ assert whole.loadable is True and "Q8_0" in whole.loadable_variants++ # Weights only under a quant subdirectory: variantless finds nothing, the quant resolves.+ nested = _mk("nested", ("BF16/model.gguf", b"GGUF"))+ assert nested.loadable is False and "BF16" in nested.loadable_variants++ # Every spelling the resolver accepts is listed, so echoing the default is never rejected.+ aliased = _mk("aliased", ("F16-checkpoint-Q4_K_M.gguf", b"GGUF"))+ assert aliased.default_variant in aliased.loadable_variants+++def test_symlink_outside_the_tree_keeps_its_relative_alias(in_tmp_cwd):+ # The resolver reads the snapshot-relative spelling, so a link out of the tree still+ # answers BF16/model; resolving first loses that.+ from utils.models.model_config import _find_local_gguf_by_variant++ pool = in_tmp_cwd / "pool"+ pool.mkdir()+ (pool / "real.gguf").write_bytes(b"GGUF")+ model = in_tmp_cwd / "m"+ (model / "BF16").mkdir(parents = True)+ (model / "config.json").write_text("{}")+ (model / "BF16" / "model.gguf").symlink_to(pool / "real.gguf")++ offered = _variants(os.fspath(model)).loadable_variants+ assert "BF16/model" in offered+ for spelling in offered:+ assert _find_local_gguf_by_variant(os.fspath(model), spelling)+++def test_a_missing_direct_path_is_not_loadable(in_tmp_cwd):+ # The extension is authoritative, so the resolver answers for paths that do not exist+ # and absence must be caught before the gate trusts it.+ response = _variants(os.fspath(in_tmp_cwd / "typo-Q4_K_M.gguf"))+ assert response.loadable is False++ # A present file still serves, and a direct file leaves the list unanswered because+ # the load ignores the quant for one.+ real = in_tmp_cwd / "real-Q8_0.gguf"+ real.write_bytes(b"GGUF")+ served = _variants(os.fspath(real))+ assert served.loadable is True and served.loadable_variants is None+++def test_relative_identifiers_keep_their_relative_alias(in_tmp_cwd):+ # The resolver returns an absolute path, so a relative identifier must be resolved the+ # same way or its spelling is lost.+ from utils.models.model_config import _find_local_gguf_by_variant++ (in_tmp_cwd / "models" / "qwen" / "BF16").mkdir(parents = True)+ (in_tmp_cwd / "models" / "qwen" / "config.json").write_text("{}")+ (in_tmp_cwd / "models" / "qwen" / "BF16" / "model.gguf").write_bytes(b"GGUF")++ offered = _variants("models/qwen").loadable_variants+ assert "BF16/model" in offered+ for spelling in offered:+ assert _find_local_gguf_by_variant("models/qwen", spelling)+++def test_loadable_variants_include_the_relative_fallback_label(in_tmp_cwd):+ # The resolver accepts the snapshot-relative stem, so the answer must not omit it.+ from utils.models.model_config import _find_local_gguf_by_variant++ (in_tmp_cwd / "config.json").write_text("{}")+ (in_tmp_cwd / "BF16").mkdir()+ (in_tmp_cwd / "BF16" / "model.gguf").write_bytes(b"GGUF")++ offered = _variants(os.fspath(in_tmp_cwd)).loadable_variants+ assert "BF16/model" in offered+ for spelling in offered:+ assert _find_local_gguf_by_variant(os.fspath(in_tmp_cwd), spelling)+++def test_a_torn_split_keeps_its_quant_partial(in_tmp_cwd):+ # A short shard-like name is ready alone, but not when the file the resolver binds for+ # that quant is an earlier torn five-digit split.+ (in_tmp_cwd / "config.json").write_text("{}")+ (in_tmp_cwd / "a-Q4_K_M-00001-of-00002.gguf").write_bytes(b"GGUF")+ (in_tmp_cwd / "z-Q4_K_M-001-of-002.gguf").write_bytes(b"GGUF")++ response = _variants(os.fspath(in_tmp_cwd))+ assert response.variants[0].partial is True+ assert response.loadable_variants == []+++def test_short_shard_like_name_in_a_directory_reads_ready(in_tmp_cwd):+ # The cache scan's looser grammar calls this torn, but the load opens a -001-of-002+ # name as an ordinary file.+ from utils.models.model_config import detect_gguf_model++ (in_tmp_cwd / "config.json").write_text("{}")+ (in_tmp_cwd / "model-Q4_K_M-001-of-002.gguf").write_bytes(b"GGUF")++ assert detect_gguf_model(os.fspath(in_tmp_cwd)) is not None+ row = _variants(os.fspath(in_tmp_cwd)).variants[0]+ assert row.downloaded is True and row.partial is False++ # A real five-digit split missing a shard is still partial.+ torn = in_tmp_cwd / "torn"+ torn.mkdir()+ (torn / "config.json").write_text("{}")+ (torn / "m-Q8_0-00001-of-00002.gguf").write_bytes(b"GGUF")+ torn_row = _variants(os.fspath(torn)).variants[0]+ assert torn_row.downloaded is False and torn_row.partial is True+++def test_parent_quant_short_shard_reads_ready(in_tmp_cwd):+ # The label comes from the snapshot-relative path, so a parent directory's quant is+ # honored; a zero-byte file stays partial either way.+ (in_tmp_cwd / "config.json").write_text("{}")+ (in_tmp_cwd / "Q4_K_M").mkdir()+ (in_tmp_cwd / "Q4_K_M" / "model-001-of-002.gguf").write_bytes(b"GGUF")++ row = _variants(os.fspath(in_tmp_cwd)).variants[0]+ assert row.quant == "Q4_K_M"+ assert row.downloaded is True and row.partial is False++ empty = in_tmp_cwd / "empty"+ empty.mkdir()+ (empty / "config.json").write_text("{}")+ (empty / "model-Q8_0-001-of-002.gguf").write_bytes(b"")+ empty_row = _variants(os.fspath(empty)).variants[0]+ assert empty_row.downloaded is False and empty_row.partial is True+++def test_symlinked_split_target_with_a_different_total_is_checked(in_tmp_cwd):+ # The load launches the set the target declares, so a torn target is torn however the+ # alias is spelled.+ real = in_tmp_cwd / "real"+ real.mkdir()+ (real / "m-Q4_K_M-00001-of-00003.gguf").write_bytes(b"GGUF")+ links = in_tmp_cwd / "links"+ links.mkdir()+ alias = links / "alias-Q4_K_M-00001-of-00002.gguf"+ alias.symlink_to(real / "m-Q4_K_M-00001-of-00003.gguf")++ torn = _variants(os.fspath(alias)).variants[0]+ assert torn.downloaded is False and torn.partial is True++ # Completing the target's own set makes it ready.+ (real / "m-Q4_K_M-00002-of-00003.gguf").write_bytes(b"GGUF")+ (real / "m-Q4_K_M-00003-of-00003.gguf").write_bytes(b"GGUF")+ whole = _variants(os.fspath(alias)).variants[0]+ assert whole.downloaded is True and whole.partial is False+++def test_variantless_pick_keeps_a_symlinked_whole_split(in_tmp_cwd):+ # A shard symlink with a complete target set is loadable, so it stays a candidate.+ from utils.models.model_config import detect_gguf_model++ real = in_tmp_cwd / "real"+ real.mkdir()+ (real / "big-Q8_0-00001-of-00002.gguf").write_bytes(b"GGUF" * 100)+ (real / "big-Q8_0-00002-of-00002.gguf").write_bytes(b"GGUF" * 100)+ marked = in_tmp_cwd / "m"+ marked.mkdir()+ (marked / "config.json").write_text("{}")+ (marked / "small-Q4_K_M.gguf").write_bytes(b"GGUF")+ (marked / "big-Q8_0-00001-of-00002.gguf").symlink_to(real / "big-Q8_0-00001-of-00002.gguf")++ assert detect_gguf_model(os.fspath(marked)).endswith("big-Q8_0-00001-of-00002.gguf")+++def test_split_named_symlink_to_a_plain_target_is_ready(in_tmp_cwd):+ # The load launches the ordinary target, so the alias's split-shaped name means nothing.+ real = in_tmp_cwd / "real-Q4_K_M.gguf"+ real.write_bytes(b"GGUF")+ alias = in_tmp_cwd / "alias-Q4_K_M-00001-of-00002.gguf"+ alias.symlink_to(real)++ row = _variants(os.fspath(alias)).variants[0]+ assert row.downloaded is True and row.partial is False+++def test_high_count_split_is_still_checked(in_tmp_cwd):+ # A declared shard count above the old cap is a real split, not a pass.+ lone = in_tmp_cwd / "m-Q4_K_M-00001-of-01001.gguf"+ lone.write_bytes(b"GGUF")++ row = _variants(os.fspath(lone)).variants[0]+ assert row.downloaded is False and row.partial is True+++def test_aliased_split_symlink_uses_the_target_name(in_tmp_cwd):+ # _local_gguf_load_path names siblings from the target, so a differing stem still loads it.+ real = in_tmp_cwd / "real"+ real.mkdir()+ (real / "model-Q4_K_M-00001-of-00002.gguf").write_bytes(b"GGUF")+ (real / "model-Q4_K_M-00002-of-00002.gguf").write_bytes(b"GGUF")+ links = in_tmp_cwd / "links"+ links.mkdir()+ alias = links / "alias-Q4_K_M-00001-of-00002.gguf"+ alias.symlink_to(real / "model-Q4_K_M-00001-of-00002.gguf")++ row = _variants(os.fspath(alias)).variants[0]+ assert row.downloaded is True and row.partial is False+++def test_symlinked_split_follows_its_target_set(in_tmp_cwd):+ # The load resolves a symlinked shard to its target's set, so a link with no siblings+ # beside it is ready when that set is whole.+ real = in_tmp_cwd / "real"+ real.mkdir()+ (real / "m-Q4_K_M-00001-of-00002.gguf").write_bytes(b"GGUF")+ (real / "m-Q4_K_M-00002-of-00002.gguf").write_bytes(b"GGUF")+ links = in_tmp_cwd / "links"+ links.mkdir()+ link = links / "m-Q4_K_M-00001-of-00002.gguf"+ link.symlink_to(real / "m-Q4_K_M-00001-of-00002.gguf")++ row = _variants(os.fspath(link)).variants[0]+ assert row.downloaded is True and row.partial is False++ # A torn target set is still torn.+ (real / "m-Q4_K_M-00002-of-00002.gguf").unlink()+ torn = _variants(os.fspath(link)).variants[0]+ assert torn.downloaded is False and torn.partial is True+++def test_stray_over_indexed_shard_does_not_complete_a_split(in_tmp_cwd):+ # Completeness is the declared index set, not a count: a stray 00003-of-00002 is not shard 2.+ shard = in_tmp_cwd / "model-Q4_K_M-00001-of-00002.gguf"+ shard.write_bytes(b"GGUF")+ (in_tmp_cwd / "model-Q4_K_M-00003-of-00002.gguf").write_bytes(b"GGUF")++ row = _variants(os.fspath(shard)).variants[0]+ assert row.downloaded is False and row.partial is True+++def test_zero_byte_split_sibling_does_not_complete_a_split(in_tmp_cwd):+ # An empty sibling is an interrupted copy; the name alone must not count as the shard.+ shard = in_tmp_cwd / "model-Q4_K_M-00001-of-00002.gguf"+ shard.write_bytes(b"GGUF")+ (in_tmp_cwd / "model-Q4_K_M-00002-of-00002.gguf").write_bytes(b"")++ row = _variants(os.fspath(shard)).variants[0]+ assert row.downloaded is False and row.partial is True+++def test_zero_byte_direct_gguf_is_partial(in_tmp_cwd):+ # The directory scan calls an empty gguf incomplete, so the direct-file fallback must too.+ empty = in_tmp_cwd / "foo-Q4_K_M.gguf"+ empty.write_bytes(b"")++ row = _variants(os.fspath(empty)).variants[0]+ assert row.downloaded is False and row.partial is True+++def test_local_dir_answer_ignores_the_hub_cache_of_the_same_name(in_tmp_cwd, monkeypatch):+ # A repo-shaped id existing as a directory resolves existence-first, so it must not gain+ # rows from the same-named HF cache: the attach gate reads any row as a GGUF model.+ from types import SimpleNamespace++ hub_cache = in_tmp_cwd / "hub"+ (hub_cache / "models--unsloth--foo" / "snapshots" / "rev" / "Q4_K_M").mkdir(parents = True)+ monkeypatch.setattr(+ "utils.hf_cache_settings.get_hf_cache_paths",+ lambda: SimpleNamespace(+ hub_cache = hub_cache,+ hf_home = in_tmp_cwd,+ source = "studio",+ cache_home = in_tmp_cwd,+ ),+ )+ (in_tmp_cwd / "unsloth" / "foo").mkdir(parents = True)+ (in_tmp_cwd / "unsloth" / "foo" / "config.json").write_text("{}")++ from utils.models.model_config import detect_gguf_model++ assert detect_gguf_model("unsloth/foo") is None+ assert _variants("unsloth/foo").variants == []+++def test_wsl_drive_path_is_normalized_like_the_load(in_tmp_cwd, monkeypatch):+ # from_identifier normalizes first, so under WSL "C:\models\qwen" is served from the+ # mapped path and probing the raw spelling would call a working model unloadable.+ #+ # Which mapping is the live question: hub.utils.paths honours [automount] root while the+ # loader hardcodes /mnt, so on a custom-root host only the loader's answer predicts the+ # load. Its real root is unwritable from a test, so it is stood in for in the tmp tree+ # (the binding is pinned below) while the hub root points at a decoy of another quant.+ from hub.utils import paths as hub_paths+ from hub.services.models import gguf_variants+ from utils.paths import normalize_path as loader_normalize_path++ assert gguf_variants._loader_normalize_path is loader_normalize_path++ monkeypatch.setattr(hub_paths, "_IS_WSL", True)+ monkeypatch.setattr(hub_paths, "_WSL_AUTOMOUNT_ROOT", f"{in_tmp_cwd}/custom/")+ monkeypatch.setattr(+ gguf_variants,+ "_loader_normalize_path",+ lambda path: f"{in_tmp_cwd}/mnt/{path[0].lower()}/{path[3:].replace(chr(92), '/')}"+ if len(path) >= 3 and path[1] == ":"+ else path,+ )+ gguf_dir = in_tmp_cwd / "mnt" / "c" / "models" / "qwen"+ gguf_dir.mkdir(parents = True)+ (gguf_dir / "qwen-Q4_K_M.gguf").write_bytes(b"GGUF")+ decoy = in_tmp_cwd / "custom" / "c" / "models" / "qwen"+ decoy.mkdir(parents = True)+ (decoy / "qwen-Q8_0.gguf").write_bytes(b"GGUF")++ response = _variants(r"C:\models\qwen")++ assert response.resolved_locally is True+ assert [v.quant for v in response.variants] == ["Q4_K_M"]+ assert "Q4_K_M" in (response.loadable_variants or [])+ assert response.loadable is True+++ "error, serves",+ [+ (FileNotFoundError(2, "No such file"), False),+ (PermissionError(13, "Permission denied"), True),+ (OSError(11, "Resource temporarily unavailable"), True),+ ],+)+def test_will_serve_only_treats_definite_absence_as_unloadable(+ in_tmp_cwd, monkeypatch, error, serves+):+ # Only "no such file" is definite; a read error (Windows sharing violation) must stay+ # unknown and serve. exists() cannot express that: on 3.14 it swallows every OSError.+ from hub.services.models import gguf_variants++ gguf = in_tmp_cwd / "foo-Q4_K_M.gguf"+ gguf.write_bytes(b"GGUF")++ def raising_stat(self, *args, **kwargs):+ raise error++ monkeypatch.setattr(gguf_variants.Path, "stat", raising_stat)+ # Stand in for 3.14, where exists() swallows the error and calls all of these absent.+ monkeypatch.setattr(gguf_variants.Path, "exists", lambda self: False)+ assert gguf_variants._will_serve(os.fspath(gguf)) is serves+++def test_loadable_variants_stays_unanswered_for_an_unstatable_direct_file(in_tmp_cwd, monkeypatch):+ # An empty list is authoritative at the attach gate, so a locked direct file must stay+ # unanswered: from_identifier ignores the variant for a file and loads it regardless.+ from hub.services.models import gguf_variants+ from hub.utils.gguf import list_local_gguf_variants++ gguf = in_tmp_cwd / "model-Q4_K_M.gguf"+ gguf.write_bytes(b"GGUF")+ variants, _ = list_local_gguf_variants(os.fspath(gguf))+ assert gguf_variants._loadable_variants(os.fspath(gguf), variants) is None++ def locked(self, *args, **kwargs):+ raise PermissionError(13, "sharing violation")++ monkeypatch.setattr(gguf_variants.Path, "stat", locked)+ # is_file() cannot express this: it raises here, and answers False from 3.14.+ monkeypatch.setattr(gguf_variants.Path, "is_file", lambda self: False)+ assert gguf_variants._loadable_variants(os.fspath(gguf), variants) is Nonediff --git a/studio/backend/utils/models/model_config.py b/studio/backend/utils/models/model_config.pyindex acfa93cb9c2..f6468f6e937 100644--- a/studio/backend/utils/models/model_config.py+++ b/studio/backend/utils/models/model_config.py@@ -2132,6 +2132,30 @@ def detect_gguf_model(path: str, model_root: Optional[str] = None) -> Optional[scontinuegguf_files.append(f)gguf_files.sort(key = lambda f: f.stat().st_size, reverse = True)++ # A torn split's lone shard can sort largest but cannot load; prefer a complete+ # candidate, keeping the old pick when nothing is whole.+ def _split_is_whole(f: Path) -> bool:+ if _GGUF_SPLIT_FILE_RE.match(f.name) is None:+ return True+ if _colocated_first_split_shard(f)[1]:+ return True+ # Follow a shard symlink to the target's set, like _local_gguf_load_path: the+ # alias's own empty directory proves nothing.+ try:+ if not f.is_symlink():+ return False+ target = f.resolve()+ except OSError:+ return True+ return (+ _GGUF_SPLIT_FILE_RE.match(target.name) is None+ or _colocated_first_split_shard(target)[1]+ )++ whole = [f for f in gguf_files if _split_is_whole(f)]+ if whole:+ gguf_files = wholeif gguf_files:return str(_local_gguf_load_path(gguf_files[0]))@@ -2559,6 +2583,50 @@ def list_local_gguf_variants(return variants, has_vision+def _variant_matches(variant: str, *labels: str) -> bool:+ """Whether a requested variant names one of *labels*, case-insensitively.++ Mirrors llama.cpp's comparison (``core.inference.llama_cpp._gguf_files_for_variant``),+ so a local path resolves the same spelling the hub path does.+ """+ wanted = str(variant).casefold()+ return any(wanted == str(label).casefold() for label in labels)+++def _direct_gguf_for_variant(+ path: str,+ variant: str,+ model_root: Optional[str] = None,+) -> Optional[str]:+ """A loose ``.gguf`` file resolved by the quant it already is, or None.++ A marker-less parent leaves ``detect_gguf_model`` loading the file itself, so a+ request naming its own quant must resolve too, or load and gate disagree. Only that+ one label matches (companions still refused); any other quant finds nothing.++ Case-insensitive, mirroring llama.cpp's own resolution (``_gguf_files_for_variant``):+ a lowercase ``--gguf-variant`` must resolve here too, or the load evicts the resident+ model on the transformers path before failing.+ """+ f = Path(path).expanduser()+ if f.suffix.lower() != ".gguf" or not f.is_file():+ return None+ context = f"{f.parent.name}/{f.name}"+ quant = _extract_quant_label(context)+ fallback_variant = re.sub(r"-\d{3,}-of-\d{3,}$", "", f.name.rsplit(".", 1)[0])+ # The hub extractor drops the -bpw modifier, so accept the shorter label it advertises.+ stripped = re.sub(r"-[0-9]+(?:\.[0-9]+)?bpw$", "", quant, flags = re.IGNORECASE)+ # The listing can also name it by another of its own tokens (the hub extractor prefers the+ # K-quant in F16-checkpoint-Q4_K_M), and only this file could be meant, so any token resolves.+ stem_tokens = [+ f"{m.group(1) or ''}{m.group(2)}"+ for m in _GGUF_KNOWN_QUANT_RE.finditer(fallback_variant.rsplit("/", 1)[-1])+ ]+ if not _variant_matches(variant, quant, fallback_variant, stripped, *stem_tokens):+ return None+ return detect_gguf_model(str(f), model_root)++def _find_local_gguf_by_variant(directory: str,variant: str,@@ -2573,7 +2641,7 @@ def _find_local_gguf_by_variant("""p = _resolve_gguf_dir(Path(directory))if p is None:- return None+ return _direct_gguf_for_variant(directory, variant, model_root)root = (Path(os.path.abspath(Path(model_root).expanduser()))if model_root is not None@@ -2589,7 +2657,17 @@ def _find_local_gguf_by_variant(continuequant = _extract_quant_label(rel)fallback_variant = re.sub(r"-\d{3,}-of-\d{3,}$", "", rel.rsplit(".", 1)[0])- if variant not in (quant, fallback_variant) or _is_big_endian_gguf_path(rel, quant):+ # Listings advertise the bpw-stripped spelling, and the hub extractor can prefer another+ # token of the same BASENAME (F16-checkpoint-Q4_K_M advertises Q4_K_M), so both label this+ # file -- but never a parent's quant: Q8_0/model-Q4_K_M.gguf IS the Q4_K_M file.+ stripped = re.sub(r"-[0-9]+(?:\.[0-9]+)?bpw$", "", quant, flags = re.IGNORECASE)+ basename_stem = fallback_variant.rsplit("/", 1)[-1]+ stem_tokens = [+ f"{m.group(1) or ''}{m.group(2)}" for m in _GGUF_KNOWN_QUANT_RE.finditer(basename_stem)+ ]+ if not _variant_matches(+ variant, quant, fallback_variant, stripped, *stem_tokens+ ) or _is_big_endian_gguf_path(rel, quant):continuematches.append(f)matches.sort()diff --git a/tests/studio/test_model_picker_contracts.py b/tests/studio/test_model_picker_contracts.pyindex b9d9a8361af..cd203909d68 100644--- a/tests/studio/test_model_picker_contracts.py+++ b/tests/studio/test_model_picker_contracts.py@@ -2173,7 +2173,7 @@ def test_a_local_quant_folder_resolves_its_variants_by_path():assert "repoId: modelId, hfToken, preferLocalCache: true, localPath: localGgufPath," in card# The backend scans a path in the repo_id position before the validation that would 400.variants = _read_backend("hub/services/models/gguf_variants.py")- scan = variants.split("if is_local_path(repo_id):", 1)+ scan = variants.split("if is_local_path(repo_id) or probe.exists():", 1)assert len(scan) == 2, "the local-path branch this leans on"assert "_is_valid_repo_id(repo_id)" in scan[1], "the branch has to come first"diff --git a/unsloth_cli/commands/start.py b/unsloth_cli/commands/start.pyindex d9288bc5937..156414bf152 100644--- a/unsloth_cli/commands/start.py+++ b/unsloth_cli/commands/start.py@@ -1529,6 +1529,7 @@ def _resolve_model(key: str,requested: Optional[str],load: LoadOptions = LoadOptions(),+ preload_check = None,) -> dict:models = _loaded_models(base, key)load_requested = False@@ -1566,7 +1567,65 @@ def _resolve_model()if requested and match is None:load_requested = True+ # Only here is an evicting load certain: the gate must not reject a request the+ # resident model already satisfies (a path-loaded GGUF shown as a bare basename+ # can collide with a non-GGUF unsloth/<name>).active = next((m for m in models if m.get("loaded") is not False), None)+ if preload_check is not None:+ # An explicit knob forces match to None so the server's disk-free dedupe can+ # answer already_loaded; gating it would reject a second session for the model+ # already serving, whose file may have moved. Only the quant is checked below:+ # any other run knob changes the runtime intent, a real reload nothing dedupes.+ other_overrides = bool(+ load.max_seq_length+ or not load.load_in_4bit+ or load.tensor_parallel+ or load.gpu_memory_mode is not None+ )+ # /v1/models shows a path-loaded GGUF under its basename, so match that spelling+ # too, or a second session reruns the gate.+ wanted_ids = {requested, _public_model_id(requested)} - {None}+ resident_serves_request = not other_overrides and any(+ m.get("loaded") is not False+ and any(+ _model_id_matches(m.get("id"), want, allow_casefold = allow_casefold)+ for want in wanted_ids+ )+ for m in models+ )+ # /v1/models shows only the basename, so confirm a path request against the+ # identifier the server loaded -- else /new/foo.gguf reads as resident because+ # /old/foo.gguf is.+ if resident_serves_request and _is_model_path(requested):+ try:+ status = _http_json("GET", f"{base}/api/inference/status", key)+ except Exception:+ status = {}+ loaded_paths = {+ str(status.get(field))+ for field in ("model_identifier", "gguf_path", "model_path")+ if status.get(field)+ }+ wanted_path = os.path.abspath(os.path.expanduser(requested))+ resident_serves_request = any(+ os.path.abspath(os.path.expanduser(path)) == wanted_path+ for path in loaded_paths+ )+ if resident_serves_request and load.gguf_variant:+ try:+ status = _http_json("GET", f"{base}/api/inference/status", key)+ except Exception:+ status = {}+ resident_variant = status.get("gguf_variant") if status.get("is_gguf") else None+ # Casefold, not _normalized_variant (it strips separators): a mistyped Q4KM+ # would skip the gate here yet still really reload on the server.+ resident_serves_request = (+ bool(resident_variant)+ and str(resident_variant).strip().lower()+ == str(load.gguf_variant).strip().lower()+ )+ if not resident_serves_request:+ preload_check(base, key, requested, load.gguf_variant)active_id = active.get("id") if active else Noneannounced_switch = Falseif active_id and not _model_id_matches(@@ -1662,6 +1721,594 @@ def _resolve_model(return resident+_HF_OFFLINE_TRUE_VALUES = frozenset({"1", "true", "yes", "on"})+++def _hf_offline() -> bool:+ return any(+ os.environ.get(var, "").strip().lower() in _HF_OFFLINE_TRUE_VALUES+ for var in ("HF_HUB_OFFLINE", "TRANSFORMERS_OFFLINE")+ )+++def _hub_gguf_files(repo: str) -> Optional[list]:+ if _hf_offline():+ return None+ endpoint = os.environ.get("HF_ENDPOINT", "https://huggingface.co").rstrip("/")+ try:+ request = urllib.request.Request(+ f"{endpoint}/api/models/{repo}",+ headers = {"User-Agent": _USER_AGENT},+ )+ with urllib.request.urlopen(request, timeout = 10) as response:+ info = json.loads(response.read().decode() or "{}")+ except Exception:+ return None+ siblings = info.get("siblings")+ if not isinstance(siblings, list) or not siblings:+ return None+ names = [s.get("rfilename") for s in siblings if isinstance(s, dict)]+ ggufs = [n for n in names if isinstance(n, str) and n.lower().endswith(".gguf")]+ return [n for n in ggufs if not _is_auxiliary_gguf(n)]+++# Mirrors hub.utils.gguf._DRAFTER_KINDS / _DRAFTER_DIR_KINDS: dspark and dflash are the same+# DeepSeek V4 Flash drafter, but dflash/ is also a real family name, so only mtp/ and dspark/+# count as a companion folder.+_DRAFTER_KINDS = ("mtp", "dspark", "dflash")+_DRAFTER_DIR_KINDS = ("mtp", "dspark")+++def _is_auxiliary_gguf(filename: str) -> bool:+ # Mirrors detect_gguf_model_remote (hub.utils.gguf.is_mtp_drafter_path): projectors,+ # separate-file drafters and big-endian builds are not loadable weights. Drafters match+ # by basename prefix or exact parent dir, never substring -- the kind names double as+ # family names, so Qwen3.6-...-DFlash-Q4_K_M.gguf IS the model. Only the root-level+ # trailing -be form is filtered; the fuller quant-aware check would over-reject here.+ p = filename.lower().replace("\\", "/")+ parts = [segment for segment in p.split("/") if segment]+ if not parts:+ return False+ name, parents = parts[-1], parts[:-1]+ if "mmproj" in p:+ return True+ if any(name.startswith(f"{kind}-") for kind in _DRAFTER_KINDS):+ return True+ if any(kind in parents for kind in _DRAFTER_DIR_KINDS):+ return True+ stem = name.rsplit(".", 1)[0]+ return not parents and stem.endswith(("-be", "_be"))+++def _direct_gguf_is_companion(path: str) -> bool:+ """Whether the server refuses this .gguf path as a model in its own right.++ A strict subset of detect_gguf_model / gguf_variants._direct_gguf_loads: projector and+ drafter prefixes read off the basename, companion-only folders off the immediate+ parent -- the same context the server reads, so nothing loadable is refused here.+ Big-endian is left out on purpose: that check needs quant context the CLI can't mirror.+ """+ parts = [segment for segment in path.replace("\\", "/").split("/") if segment]+ if not parts:+ return False+ name = parts[-1].lower()+ if not name.endswith(".gguf"):+ return False+ # Root-independent refusals only: name prefixes read the basename alone, so they mean+ # the same under any model root. A drafter FOLDER does not.+ if "mmproj" in name:+ return True+ return any(name.startswith(f"{kind}-") for kind in _DRAFTER_KINDS)+++def _path_syntax_is_native(path: str) -> bool:+ """Whether *path* is spelled the way this OS spells paths.++ A Windows path read from WSL, or a POSIX one read from Windows, parses into+ something this process cannot judge -- ``C:\\models\\m.gguf`` has parent+ ``.`` here -- so its absence locally says nothing about the server's disk.+ """+ windows_drive = len(path) >= 2 and path[1] == ":" and path[0].isalpha()+ if os.name == "nt":+ return True+ return not windows_drive and "\\" not in path+++def _direct_gguf_companion_is_uncertain(path: str) -> bool:+ """Whether only the server can say if this path is a companion.++ detect_gguf_model reads drafter folders relative to the registered model root, so+ ``/models/MTP/foo-Q8_0.gguf`` is refused or loaded depending on where that root sits+ -- a question only the server can answer, since this process doesn't know its roots.+ """+ parts = [segment for segment in path.replace("\\", "/").split("/") if segment]+ return any(segment.lower() in _DRAFTER_DIR_KINDS for segment in parts[:-1])+++# Mirrors model_config._extract_quant_label's pattern; change in lockstep.+_QUANT_LABEL_RE = re.compile(+ r"(UD-)?"+ r"(MXFP[0-9]+(?:_[A-Z0-9]+)*"+ r"|IQ[0-9]+_[A-Z]+(?:_[A-Z0-9]+)?"+ r"|TQ[0-9]+_[0-9]+"+ r"|Q[0-9]+_K_[A-Z]+"+ r"|Q[0-9]+_[0-9]+"+ r"|Q[0-9]+_K"+ r"|BF16|F16|F32)"+ r"(-[0-9]+(?:\.[0-9]+)?bpw)?",+ re.IGNORECASE,+)+++def _direct_gguf_variant_labels(path: str) -> tuple:+ """The labels the server's direct-file resolver accepts for *path*.++ Mirrors _direct_gguf_for_variant: the quant label read from the basename+ first, the immediate parent only when the basename carries none, plus the+ shard-stripped stem itself. The basename wins the disagreement -- a+ Q8_0/foo-Q4_K_M.gguf answers Q4_K_M, so its parent must not vouch for+ Q8_0 here while the load resolves nothing and evicts.+ """+ norm = path.replace("\\", "/").rstrip("/")+ name = norm.rsplit("/", 1)[-1]+ stem = re.sub(r"-\d{3,}-of-\d{3,}$", "", name.rsplit(".", 1)[0])+ match = _QUANT_LABEL_RE.search(stem)+ if match is None and "/" in norm:+ match = _QUANT_LABEL_RE.search(norm.rsplit("/", 2)[-2])+ labels = [stem]+ if match is not None:+ label = f"{match.group(1) or ''}{match.group(2)}{match.group(3) or ''}"+ labels.append(label)+ # The resolver also accepts the hub-style bpw-stripped spelling.+ stripped = re.sub(r"-[0-9]+(?:\.[0-9]+)?bpw$", "", label, flags = re.IGNORECASE)+ if stripped != label:+ labels.append(stripped)+ else:+ # The extractor's own fallback: the last hyphen-separated segment.+ labels.append(stem.split("-")[-1])+ return tuple(labels)+++# Mirrors hub.utils.gguf._BIG_ENDIAN_GGUF_FILENAME_RE; change in lockstep.+_BIG_ENDIAN_FILENAME_RE = re.compile(r"(^|[-_])be(?:[._-]|$)", re.IGNORECASE)+++def _direct_gguf_is_big_endian(path: str) -> bool:+ """Mirrors hub.utils.gguf.is_big_endian_gguf_path over the same one-parent+ context detect_gguf_model reads; change in lockstep. A quant-named parent+ exempts a bare -be basename (that file loads); a be marker at or after a+ basename quant does not.+ """+ norm = path.replace("\\", "/").rstrip("/")+ parts = [segment for segment in norm.split("/") if segment]+ name = parts[-1]+ stem = name.rsplit(".", 1)[0].lower()+ quant_stem = re.sub(r"-\d{3,}-of-\d{3,}$", "", stem)+ match = _QUANT_LABEL_RE.search(quant_stem)+ parent = parts[-2].lower() if len(parts) > 1 else ""+ if match is None and parent:+ match = _QUANT_LABEL_RE.search(parent)+ quant_key = (+ f"{match.group(1) or ''}{match.group(2)}{match.group(3) or ''}".lower()+ if match is not None+ else quant_stem.split("-")[-1]+ )+ quant_index = stem.find(quant_key) if quant_key else -1+ quant_in_parent_only = (+ bool(parent)+ and quant_index < 0+ and (+ (quant_key and quant_key in parent)+ or (not quant_key and _QUANT_LABEL_RE.search(parent))+ )+ )+ for be in _BIG_ENDIAN_FILENAME_RE.finditer(stem):+ if quant_index >= 0 and quant_index < be.start():+ return True+ tail = stem[be.end() :].lstrip("._-")+ if not tail or _QUANT_LABEL_RE.search(tail) is None:+ return not quant_in_parent_only+ return False+++# Mirrors gguf_variants._DIRECT_SPLIT_RE / the load path's _GGUF_SPLIT_FILE_RE; change in+# lockstep. Five digits exactly: a shorter -001-of-002 name loads as an ordinary file.+_DIRECT_SPLIT_FILE_RE = re.compile(+ r"^(?P<stem>.+)-(?P<index>\d{5})-of-(?P<total>\d{5})$", re.IGNORECASE+)+++def _direct_gguf_file_is_ready(path: str) -> bool:+ """Whether a CLI-visible direct .gguf file can actually serve a load.++ Mirrors the backend's completeness rules: zero bytes is an interrupted copy, a split+ needs every sibling index present and non-empty. Unknowable reports ready, so a path+ this process can't judge never blocks the load.+ """++ def _split_set_complete(candidate: Path) -> Optional[bool]:+ match = _DIRECT_SPLIT_FILE_RE.match(candidate.name.rsplit(".", 1)[0])+ if match is None:+ return None+ total = int(match.group("total"))+ if total < 2:+ return None+ sibling = re.compile(+ re.escape(match.group("stem"))+ + r"-(\d{"+ + str(len(match.group("index")))+ + r"})-of-"+ + re.escape(match.group("total"))+ + r"\.gguf$",+ re.IGNORECASE,+ )+ found = {+ int(m.group(1))+ for q in candidate.parent.iterdir()+ if (m := sibling.match(q.name)) and q.is_file() and q.stat().st_size > 0+ }+ return found >= set(range(1, total + 1))++ try:+ p = Path(os.path.expanduser(path))+ # A broken symlink is visible here, and the .gguf suffix alone still makes it a+ # load, which fails after teardown.+ if p.is_symlink() and not p.exists():+ return False+ if not p.is_file():+ return True+ if p.stat().st_size == 0:+ return False+ whole = _split_set_complete(p)+ if whole is not False:+ return True+ # Mirror _local_gguf_load_path: an incomplete nominal set still loads when the shard+ # is a symlink whose target sits with the full set.+ if p.is_symlink():+ target = p.resolve()+ return _split_set_complete(target) is not False+ return False+ except OSError:+ return True+++def _answer_offers_variant(+ variants: list,+ variant: str,+ strict: bool = False,+) -> bool:+ """Whether a live variants answer can resolve *variant* to a file.++ Mirrors llama.cpp's resolution, case-insensitively: quant label first, then the+ whole-token filename fallback (as loose as it gets -- a separator-differing label+ resolves to nothing there either). A row missing both fields can't be disproven, so+ it vouches. ``strict`` drops the filename-token tier: the LOCAL resolver takes only+ exact labels, so a local answer must not vouch for a shorter token (Q4 inside+ model-Q4_K_M.gguf) the load would never resolve.+ """+ wanted = str(variant).strip().lower()+ if not wanted:+ return True+ token = re.compile(r"(?<![a-z0-9])" + re.escape(wanted) + r"(?![a-z0-9])")+ for row in variants:+ if not isinstance(row, dict):+ return True+ # A torn local row proves a load llama cannot serve, so its labels do not vouch in+ # strict mode; hub partials stay resumable and count.+ if strict and row.get("partial") is True:+ continue+ quant = row.get("quant")+ filename = row.get("filename")+ if not isinstance(quant, str) and not isinstance(filename, str):+ return True+ if isinstance(quant, str):+ label = quant.strip().lower()+ # The resolver also accepts the hub-style bpw-stripped spelling.+ if wanted in (label, re.sub(r"-[0-9]+(?:\.[0-9]+)?bpw$", "", label)):+ return True+ if isinstance(filename, str):+ # The local resolver also takes the exact shard-stripped stem: full relative+ # spelling only, never a nested file's bare basename.+ stem = re.sub(r"-\d{3,}-of-\d{3,}$", "", filename.rsplit(".", 1)[0]).lower()+ if wanted == stem:+ return True+ # Also any whole quant token of the BASENAME, which is how the listing's default+ # can name the file by its other label (F16-checkpoint-Q4_K_M -> Q4_K_M).+ if any(+ wanted+ in (+ f"{m.group(1) or ''}{m.group(2)}".lower(),+ # Keeps the bpw modifier the hub extractor drops, so both spellings match.+ f"{m.group(1) or ''}{m.group(2)}{m.group(3) or ''}".lower(),+ )+ for m in _QUANT_LABEL_RE.finditer(stem.rsplit("/", 1)[-1])+ ):+ return True+ if strict:+ if not isinstance(quant, str):+ return True+ continue+ if isinstance(filename, str) and token.search(filename.lower()):+ return True+ return False+++def _fail_codex_variant_missing(model_id: str, variant: str, variants: list) -> NoReturn:+ offered = [+ row.get("quant")+ for row in variants+ if isinstance(row, dict) and isinstance(row.get("quant"), str) and row.get("quant")+ ]+ message = f"{model_id} has no GGUF variant {variant}."+ if offered:+ message += " Available: " + ", ".join(dict.fromkeys(offered))+ _fail(message)+++def _fail_codex_needs_gguf(model_id: str) -> NoReturn:+ message = f"Codex needs a GGUF model served by llama-server, but {model_id} is not one."+ guess = f"{model_id}-GGUF"+ if "gguf" not in model_id.lower() and _is_hub_model_id(guess) and _hub_gguf_files(guess):+ message += f" Try: unsloth start codex --model {guess}"+ _fail(message)+++def _preflight_codex_gguf(+ model: Optional[str],+ *,+ serve: bool = True,+ launch: bool = True,+) -> None:+ # Hub-listing preflight for the auto-start path only: with a server running, identifiers+ # resolve against its cwd/cache/token, so _attach_gguf_check_for_codex asks the server+ # instead. Only a complete listing with no .gguf files rejects; unknown defers to the+ # post-connect check. Mirrors _require_studio's auto-start condition, so with no start+ # possible its "no running server" error comes first, without a hub probe.+ if not (serve and launch and model):+ return+ expected = os.environ.get("UNSLOTH_STUDIO_URL", "http://127.0.0.1:8888").rstrip("/")+ if not is_loopback_url(expected) or urlparse(expected).scheme != "http":+ return+ if find_studio_server() is not None:+ return+ repo, _ = _split_repo_variant(model)+ # A bare foo.gguf naming no local file is a shorthand, not a path: the load+ # canonicalizes it like any other owner-less name.+ if "/" not in repo and (not _is_model_path(repo) or repo.lower().endswith(".gguf")):+ # The server canonicalizes owner-less shorthands to unsloth/<name>.+ try:+ if Path(os.path.expanduser(repo)).exists():+ return+ except OSError:+ return+ repo = f"unsloth/{repo}"+ if not _is_hub_model_id(repo):+ return+ files = _hub_gguf_files(repo)+ if files is not None and not files:+ _fail_codex_needs_gguf(repo)+++def _attach_gguf_check_for_codex(+ base: str,+ key: str,+ model: Optional[str],+ variant: Optional[str] = None,+) -> None:+ # Attach path: the server resolves the identifier with its own cwd, cache and token, so+ # ask it before the load evicts the resident model. A live empty list is definitive;+ # any error (an older server included) defers.+ if not model:+ return+ repo, inline_variant = _split_repo_variant(model)+ # `--model repo:QUANT` is split before the gate runs, so the caller passes the quant on.+ variant = variant or inline_variant+ # A .gguf filesystem path is GGUF by definition; only the hub-id shape (owner/name.gguf)+ # gets probed. A bare foo.gguf naming no local file takes the shorthand route, since the+ # load canonicalizes it to unsloth/foo.gguf.+ bare_missing_gguf = False+ if repo.lower().endswith(".gguf") and not _is_model_path(repo.rsplit(".", 1)[0]):+ try:+ bare_missing_gguf = not Path(os.path.expanduser(repo)).exists()+ except OSError:+ bare_missing_gguf = False+ if (+ repo.lower().endswith(".gguf")+ and not bare_missing_gguf+ and not (+ repo.count("/") == 1+ and not repo.startswith(("/", ".", "~"))+ and ":" not in repo+ and "\\" not in repo+ )+ ):+ # detect_gguf_model refuses a companion or big-endian build, so the load falls through+ # to transformers and unloads llama-server before failing. Settled by name: the probe's+ # empty answer defers whenever the path exists here, which on a loopback attach is+ # exactly when it does. The quant never redirects a direct file (from_identifier+ # consults it only for a DIRECTORY), though an explicit one still reaches the probe.+ refused = _direct_gguf_is_companion(repo) or _direct_gguf_is_big_endian(repo)+ if refused:+ _fail_codex_needs_gguf(repo)+ # A drafter folder further up is the server's call.+ uncertain = _direct_gguf_companion_is_uncertain(repo)+ # The variant does not exempt this: a direct file is loaded as itself, so a complete+ # sibling matching the quant is never substituted for it.+ if not refused and not uncertain:+ # Only when this process really shares the server's filesystem: the .gguf suffix+ # alone gets an incomplete file loaded, and llama-server finds the missing bytes+ # only after teardown. Loopback does not prove that -- 127.0.0.1 may be an SSH or+ # container forward where a server-valid path is simply absent here -- so confirm+ # this machine's Unsloth and otherwise defer to the probe.+ if is_loopback_url(base) and verify_studio_identity(base):+ # A .gguf-NAMED DIRECTORY is scanned, not loaded, so the suffix proves nothing.+ try:+ is_gguf_dir = Path(os.path.expanduser(repo)).is_dir()+ except OSError:+ is_gguf_dir = False+ if not is_gguf_dir:+ # On loopback this reads the server's filesystem, so a name absent from a+ # listable directory is absent for the load too, and the .gguf suffix+ # still makes it a load that fails after teardown. An unreadable parent+ # stays unknowable and defers.+ try:+ probe = Path(os.path.expanduser(repo))+ missing = (+ # Only a path this OS spells: a Windows path seen from WSL parses+ # to nonsense (C:\... has parent '.') and the server may hold the+ # real file, so it defers to the probe.+ _path_syntax_is_native(repo)+ and not probe.is_symlink()+ and probe.parent.is_dir()+ and not probe.exists()+ )+ except OSError:+ missing = False+ if missing:+ _fail(f"{repo} does not exist. Check the path before pointing Codex at it.")+ if not _direct_gguf_file_is_ready(repo):+ _fail(+ f"{repo} is incomplete (zero bytes or a split missing shards); "+ "re-download or re-copy it before pointing Codex at it."+ )+ # Only a spelling this OS can judge is settled here: a Windows path read+ # from WSL skipped the absence check above and reads as ready, so returning+ # would vouch for a file nobody looked at. An explicit variant also goes to+ # the probe, which judges the marked parent.+ if not variant and _path_syntax_is_native(repo):+ return+ # A remote server's filesystem is not ours to read, and the load takes the .gguf+ # suffix as authoritative, so ask the server instead. Its errors defer as always.+ # Mirrors the load path's shorthand precedence: the raw name first (it may be a directory+ # under the server's cwd), then the unsloth/<name> form the load falls back to only when+ # the raw name resolves to nothing. A live answer settles that exact id, so the canonical+ # form must not vouch for a raw name already answered, else a non-GGUF directory in the+ # server's cwd passes the gate and evicts. Only an error falls through.+ candidates = [repo]+ if "/" not in repo and (not _is_model_path(repo) or bare_missing_gguf):+ candidates.append(f"unsloth/{repo}")+ for candidate in candidates:+ try:+ info = _http_json(+ "GET", f"{base}/api/models/gguf-variants?{urlencode({'repo_id': candidate})}", key+ )+ except Exception:+ continue+ variants = info.get("variants") if isinstance(info, dict) else None+ if isinstance(variants, list):+ # A cleanable row is an empty leftover <quant>/ folder: it offers a delete, never+ # weights, so it cannot stand in for the load finding something.+ variants = [+ row for row in variants if not (isinstance(row, dict) and row.get("cleanable"))+ ]+ # The load uses a bare name only when it resolves locally, else it canonicalizes to+ # unsloth/<name>, so a raw answer the server calls non-local settles nothing. Without+ # the flag (older server) the raw answer is still the best evidence there is.+ if (+ "/" not in candidate+ and candidate != candidates[-1]+ and isinstance(info, dict)+ and "resolved_locally" in info+ and not info["resolved_locally"]+ ):+ continue+ # The server can answer the gate's real question with the load resolver itself, so it+ # settles the round -- even an EMPTY listing, since a root-blind lister can miss a file+ # detect_gguf_model still resolves. No filename grammar beats the code that loads.+ if isinstance(variants, list) and isinstance(info, dict):+ offered = info.get("loadable_variants")+ # No allow-list means a direct file, which loads as itself whatever the quant, so+ # the variantless verdict decides. Only a server omitting the field falls through.+ if variant and offered is None and isinstance(info.get("loadable"), bool):+ if not info["loadable"]:+ _fail_codex_needs_gguf(candidate)+ return+ if variant and isinstance(offered, list):+ wanted_variant = str(variant).strip().lower()+ if not any(+ isinstance(q, str) and q.strip().lower() == wanted_variant for q in offered+ ):+ _fail_codex_variant_missing(candidate, variant, variants)+ return+ if not variant and isinstance(info.get("loadable"), bool):+ if not info["loadable"]:+ _fail_codex_needs_gguf(candidate)+ return+ if isinstance(variants, list) and variants:+ # llama.cpp kills the resident model before resolving the quant, so a quant this+ # answer cannot serve is settled here. Local answers take exact labels only; the+ # looser filename-token tier is for hub answers.+ #+ # "Local" means the server says so (resolved_locally) or, predating that field,+ # path syntax / bare names, which resolve locally anyway. owner/name.gguf is+ # exempted like the direct-file branch (_is_model_path sees only the suffix),+ # since a remote answer wrongly judged local would face local-only rules.+ hub_shaped = (+ candidate.count("/") == 1+ and not candidate.startswith(("/", ".", "~"))+ and ":" not in candidate+ and "\\" not in candidate+ )+ local_answer = bool(info.get("resolved_locally")) or (+ not hub_shaped and (_is_model_path(candidate) or "/" not in candidate)+ )+ # A local answer of only torn rows has no resumable side: llama-server would get+ # the incomplete split only after teardown.+ if local_answer and all(+ isinstance(row, dict) and row.get("partial") is True for row in variants+ ):+ _fail(+ f"{candidate} has only incomplete GGUF weights on the server; "+ "finish or re-copy the download before pointing Codex at it."+ )+ # A variantless local load picks from the directory's top level, so rows living+ # only in quant subdirectories need the variant that resolves them -- else this+ # answer evicts for a load that finds nothing.+ if (+ local_answer+ and not variant+ and variants+ and all(+ isinstance(row, dict)+ and isinstance(row.get("filename"), str)+ and "/" in row["filename"]+ for row in variants+ )+ ):+ offered = ", ".join(+ dict.fromkeys(+ row["quant"]+ for row in variants+ if isinstance(row.get("quant"), str) and row["quant"]+ )+ )+ _fail(+ f"{candidate} keeps its GGUF weights in quant subdirectories, which a "+ "variantless load cannot pick. Pass --gguf-variant"+ + (f" (available: {offered})." if offered else ".")+ )+ if variant and not _answer_offers_variant(variants, variant, strict = local_answer):+ _fail_codex_variant_missing(candidate, variant, variants)+ return+ if isinstance(variants, list):+ # Explicit local syntax resolves locally on every server version, so its live empty+ # answer settles the load; deferring would let the same GGUF-less directory go down+ # the transformers path and evict. Only marker-less names keep deferring: older+ # servers read them as hub ids, and a local hit may be a server-side model from the+ # server's cwd -- unless it reports resolved_locally, having already resolved them.+ # A bare foo.gguf naming no local file is only the canonicalized spelling, so it+ # settles nothing until the canonical form has answered too.+ if bare_missing_gguf and candidate != candidates[-1]:+ continue+ if not _is_model_path(repo) and not info.get("resolved_locally"):+ try:+ if Path(os.path.expanduser(repo)).exists():+ return+ except OSError:+ return+ _fail_codex_needs_gguf(candidate)++def _require_gguf_for_codex(base: str, key: str, model_id: str) -> None:# Codex always streams, and Unsloth only streams /v1/responses from llama-server.try:@@ -1672,11 +2319,7 @@ def _require_gguf_for_codex(base: str, key: str, model_id: str) -> None:raiseif status.get("is_gguf"):return- hint = model_id if "gguf" in model_id.lower() else f"{model_id}-GGUF"- _fail(- f"Codex needs a GGUF model served by llama-server, but {model_id} is on "- f"the transformers backend. Try: unsloth start codex --model {hint}"- )+ _fail_codex_needs_gguf(model_id)_DYNAMIC_SECTIONS_FLAG = "--exclude-dynamic-system-prompt-sections"@@ -2946,6 +3589,7 @@ def _connect(serve: bool = False,launch: bool = True,server_options: ServerOptions = ServerOptions(),+ preload_check = None,) -> tuple:# `--model org/name:QUANT` is shorthand for `--model org/name --gguf-variant QUANT`.# Split it before we match/serve so the attach path resolves against the already-loaded@@ -2964,7 +3608,15 @@ def _connect(key = _agent_api_key(base, api_key, auto_started = server is not None)# A server we just started has exactly the requested model loaded, so resolve to# whatever it is serving instead of re-matching the raw --model string.- entry = _resolve_model(base, key, None if server is not None else model, load)+ # Only an attach can still trigger an evicting load, so _resolve_model gets the+ # pre-load check and runs it only when that load is imminent.+ entry = _resolve_model(+ base,+ key,+ None if server is not None else model,+ load,+ preload_check = None if server is not None else preload_check,+ )except BaseException:_shutdown_auto_served()raise@@ -3744,12 +4396,14 @@ def codex(model, ctx.args[:] = _consume_positional_model(model, ctx.args)install_hint = _npm_install_hint("@openai/codex")_require_agent_for_launch("codex", install_hint, launch)+ _preflight_codex_gguf(model, serve = serve, launch = launch)base, key, entry = _connect(api_key,model,LoadOptions(gguf_variant, max_seq_length, load_in_4bit, tensor_parallel, gpu_memory_mode),serve = serve,launch = launch,+ preload_check = _attach_gguf_check_for_codex,server_options = ServerOptions(enable_tools = enable_tools,tool_call_healing = tool_call_healing,diff --git a/unsloth_cli/tests/test_start.py b/unsloth_cli/tests/test_start.pyindex 9f50b85241d..b877210347b 100644--- a/unsloth_cli/tests/test_start.py+++ b/unsloth_cli/tests/test_start.py@@ -1318,6 +1318,8 @@ def fake_studio(tmp_path, monkeypatch):monkeypatch.setattr(start, "find_studio_server", lambda: BASE)# Identity handshake has its own tests; trust the loopback server here.monkeypatch.setattr(start, "verify_studio_identity", lambda base: True)+ # Hub listing unavailable: the Codex preflight defers to the stubbed post-connect check.+ monkeypatch.setattr(start, "_hub_gguf_files", lambda repo: None)# _studio_token / api-keys are faked so the mint flow stays offline.monkeypatch.setattr(start, "_studio_token", lambda: "jwt-token")monkeypatch.setattr(start, "_http_json", http_json)@@ -3327,6 +3329,13 @@ def test_connect_no_studio_errors(fake_studio, monkeypatch):assert "No running Unsloth server" in result.output[email protected](autouse = True)+def _studio_is_this_machine(monkeypatch):+ # 127.0.0.1 can be a tunnel, so the gate judges the local filesystem only once the server+ # is confirmed to be this machine's. Default to local; the tunneled case overrides this.+ monkeypatch.setattr(start, "verify_studio_identity", lambda base, **_kw: True)++@pytest.fixture(autouse = True)def _reset_auto_served():# Never let a test leave a fake server in the module slot (an atexit backstop would@@ -3938,9 +3947,9 @@ def test_startup_failure_output_redacts_minted_key(monkeypatch, tmp_path, capsysdef test_codex_preflight_failure_tears_down_auto_served(fake_studio, monkeypatch):- # The Codex GGUF preflight runs after _connect may have auto-started a server but- # before _run's teardown finally, so a preflight rejection must not leave the server- # holding the port/GPU (waiting on the atexit backstop).+ # Listing unavailable: the check falls back to post-connect and must still tear down an+ # auto-started server instead of leaving it to atexit.+ monkeypatch.setattr(start, "_hub_gguf_files", lambda repo: None)monkeypatch.setattr(start, "find_studio_server", lambda: None)started = {}fake = SimpleNamespace(pid = 999, poll = lambda: None)@@ -6101,3 +6110,1326 @@ def test_native_resume_flag_passes_through_unchanged(fake_studio, monkeypatch):# Unsloth never auto-appends its own resume token when the user drives resume.assert captured["command"].count("--resume") == 1assert "--continue" not in captured["command"]+++def _fake_hub_listing(monkeypatch, files_by_repo):+ monkeypatch.delenv("UNSLOTH_STUDIO_URL", raising = False)+ monkeypatch.setattr(start, "find_studio_server", lambda: None)+ calls = []++ def fake(repo):+ calls.append(repo)+ return files_by_repo.get(repo)++ monkeypatch.setattr(start, "_hub_gguf_files", fake)+ return calls+++def test_codex_preflight_rejects_non_gguf_repo(monkeypatch, capsys):+ _fake_hub_listing(monkeypatch, {"mlx-community/Qwen3-0.6B-4bit": []})+ with pytest.raises(typer.Exit) as excinfo:+ start._preflight_codex_gguf("mlx-community/Qwen3-0.6B-4bit")+ assert excinfo.value.exit_code == 1+ err = capsys.readouterr().err+ assert "Codex needs a GGUF model" in err+ assert "Try:" not in err+++def test_codex_preflight_passes_gguf_repo_and_splits_variant(monkeypatch):+ calls = _fake_hub_listing(monkeypatch, {"unsloth/Qwen3-0.6B-GGUF": ["Qwen3-0.6B-Q4_K_M.gguf"]})+ start._preflight_codex_gguf("unsloth/Qwen3-0.6B-GGUF:Q4_K_M")+ assert calls == ["unsloth/Qwen3-0.6B-GGUF"]+++def test_codex_preflight_defers_when_listing_unavailable(monkeypatch):+ _fake_hub_listing(monkeypatch, {})+ start._preflight_codex_gguf("owner/private-model")+++def test_codex_preflight_skips_paths_and_empty_model(monkeypatch):+ calls = _fake_hub_listing(monkeypatch, {})+ start._preflight_codex_gguf("./models/foo.gguf")+ start._preflight_codex_gguf(None)+ assert calls == []+++def test_codex_preflight_skips_remote_studio(monkeypatch):+ # A one-slash server-side path can look like a hub id; do not reject it from here.+ calls = _fake_hub_listing(monkeypatch, {"models/qwen-finetune": []})+ monkeypatch.setenv("UNSLOTH_STUDIO_URL", "http://studio.example:8888")+ start._preflight_codex_gguf("models/qwen-finetune")+ assert calls == []+++def test_codex_gguf_failure_suggests_only_a_verified_sibling(monkeypatch, capsys):+ _fake_hub_listing(monkeypatch, {"owner/model-GGUF": ["model-Q4_K_M.gguf"]})+ with pytest.raises(typer.Exit):+ start._fail_codex_needs_gguf("owner/model")+ assert "Try: unsloth start codex --model owner/model-GGUF" in capsys.readouterr().err+++def test_hub_gguf_files_parses_listing(monkeypatch):+ monkeypatch.delenv("HF_HUB_OFFLINE", raising = False)+ monkeypatch.delenv("TRANSFORMERS_OFFLINE", raising = False)+ payload = {"siblings": [{"rfilename": "README.md"}, {"rfilename": "model-Q4_K_M.GGUF"}]}+ monkeypatch.setattr(+ start.urllib.request,+ "urlopen",+ lambda request, timeout: io.BytesIO(json.dumps(payload).encode()),+ )+ assert start._hub_gguf_files("owner/model") == ["model-Q4_K_M.GGUF"]+++def test_hub_gguf_files_unknown_on_error_or_empty_listing(monkeypatch):+ monkeypatch.delenv("HF_HUB_OFFLINE", raising = False)+ monkeypatch.delenv("TRANSFORMERS_OFFLINE", raising = False)++ def unauthorized(request, timeout):+ raise urllib.error.HTTPError(request.full_url, 401, "unauthorized", None, None)++ monkeypatch.setattr(start.urllib.request, "urlopen", unauthorized)+ assert start._hub_gguf_files("owner/missing") is None+ monkeypatch.setattr(+ start.urllib.request, "urlopen", lambda request, timeout: io.BytesIO(b'{"siblings": []}')+ )+ assert start._hub_gguf_files("owner/empty") is None+++def test_codex_rejects_non_gguf_model_before_connect(monkeypatch):+ monkeypatch.delenv("UNSLOTH_STUDIO_URL", raising = False)+ monkeypatch.setattr(start, "find_studio_server", lambda: None)+ monkeypatch.setattr(start.shutil, "which", lambda _: "/usr/local/bin/codex")+ monkeypatch.setattr(start, "_hub_gguf_files", lambda repo: [])+ monkeypatch.setattr(+ start, "_connect", lambda *a, **k: pytest.fail("preflight must run before connect")+ )+ result = CliRunner().invoke(+ start.start_app, ["codex", "--model", "mlx-community/Qwen3-0.6B-4bit"]+ )+ assert result.exit_code == 1+ assert "Codex needs a GGUF model" in result.output+++def test_codex_preflight_normalizes_ownerless_shorthand(monkeypatch):+ calls = _fake_hub_listing(monkeypatch, {"unsloth/Qwen3-0.6B": []})+ with pytest.raises(typer.Exit):+ start._preflight_codex_gguf("Qwen3-0.6B")+ assert calls[0] == "unsloth/Qwen3-0.6B"+++def test_codex_preflight_shorthand_skips_existing_local_dir(monkeypatch, tmp_path):+ calls = _fake_hub_listing(monkeypatch, {})+ (tmp_path / "Qwen3-0.6B").mkdir()+ monkeypatch.chdir(tmp_path)+ start._preflight_codex_gguf("Qwen3-0.6B")+ assert calls == []+++def test_hub_gguf_files_ignores_auxiliary_ggufs(monkeypatch):+ monkeypatch.delenv("HF_HUB_OFFLINE", raising = False)+ monkeypatch.delenv("TRANSFORMERS_OFFLINE", raising = False)+ payload = {+ "siblings": [+ {"rfilename": "mmproj-F16.gguf"},+ {"rfilename": "mtp-gemma.gguf"},+ {"rfilename": "MTP/gemma-Q8_0-MTP.gguf"},+ {"rfilename": "README.md"},+ ]+ }+ monkeypatch.setattr(+ start.urllib.request,+ "urlopen",+ lambda request, timeout: io.BytesIO(json.dumps(payload).encode()),+ )+ assert start._hub_gguf_files("owner/mmproj-pack") == []+++def test_hub_gguf_files_ignores_dspark_and_dflash_drafters(monkeypatch):+ # Mirrors hub.utils.gguf.is_mtp_drafter_path: basename prefix (all three kinds) or exact+ # parent dir (mtp/, dspark/ only -- dflash/ is a real family name).+ monkeypatch.delenv("HF_HUB_OFFLINE", raising = False)+ monkeypatch.delenv("TRANSFORMERS_OFFLINE", raising = False)+ payload = {+ "siblings": [+ {"rfilename": "DSpark-drafter-Q2K-Q8.gguf"},+ {"rfilename": "dflash-drafter-Q8_0.gguf"},+ {"rfilename": "dspark/DeepSeek-V4-Flash-Q8_0.gguf"},+ # Family names, not companions: these ARE the model.+ {"rfilename": "Qwen3.6-35B-A3B-DFlash-Q4_K_M.gguf"},+ {"rfilename": "DFlash/Qwen3.6-27B-DFlash-Q4_K_M.gguf"},+ ]+ }+ monkeypatch.setattr(+ start.urllib.request,+ "urlopen",+ lambda request, timeout: io.BytesIO(json.dumps(payload).encode()),+ )+ assert start._hub_gguf_files("owner/dspark-pack") == [+ "Qwen3.6-35B-A3B-DFlash-Q4_K_M.gguf",+ "DFlash/Qwen3.6-27B-DFlash-Q4_K_M.gguf",+ ]+++def test_hub_gguf_files_filters_root_big_endian_only(monkeypatch):+ monkeypatch.delenv("HF_HUB_OFFLINE", raising = False)+ monkeypatch.delenv("TRANSFORMERS_OFFLINE", raising = False)+ payload = {+ "siblings": [+ {"rfilename": "model-Q4_K_M-be.gguf"},+ {"rfilename": "model-Q4_K_M_be.gguf"},+ {"rfilename": "quants/model-be.gguf"},+ {"rfilename": "model-belle.gguf"},+ ]+ }+ monkeypatch.setattr(+ start.urllib.request,+ "urlopen",+ lambda request, timeout: io.BytesIO(json.dumps(payload).encode()),+ )+ assert start._hub_gguf_files("owner/be-pack") == ["quants/model-be.gguf", "model-belle.gguf"]+++def test_codex_preflight_defers_to_running_server(monkeypatch):+ # With a server running, identifiers resolve against its cwd/cache/token, so the attach+ # check asks it rather than guessing here.+ calls = _fake_hub_listing(monkeypatch, {"mlx-community/Qwen3-0.6B-4bit": []})+ monkeypatch.setattr(start, "find_studio_server", lambda: "http://127.0.0.1:8888")+ start._preflight_codex_gguf("mlx-community/Qwen3-0.6B-4bit")+ assert calls == []+++def _fake_variants(monkeypatch, responses):+ urls = []++ def http_json(+ method,+ url,+ token,+ payload = None,+ timeout = 30,+ error = None,+ ):+ urls.append(url)+ if isinstance(responses, Exception):+ raise responses+ return responses++ monkeypatch.setattr(start, "_http_json", http_json)+ return urls+++def test_codex_attach_check_rejects_on_empty_variants(monkeypatch, capsys):+ monkeypatch.setattr(start, "_hub_gguf_files", lambda repo: None)+ _fake_variants(monkeypatch, {"variants": [], "has_vision": False})+ with pytest.raises(typer.Exit):+ start._attach_gguf_check_for_codex(BASE, "sk-test", "mlx-community/Qwen3-0.6B-4bit")+ assert "Codex needs a GGUF model" in capsys.readouterr().err+++def test_codex_attach_check_passes_on_variants(monkeypatch):+ urls = _fake_variants(monkeypatch, {"variants": [{"quant": "Q4_K_M"}]})+ start._attach_gguf_check_for_codex(BASE, "sk-test", "unsloth/Qwen3-0.6B-GGUF:Q4_K_M")+ assert "repo_id=unsloth%2FQwen3-0.6B-GGUF" in urls[0]+++def test_codex_attach_check_rejects_unavailable_variant(monkeypatch, capsys):+ # llama.cpp kills the resident server before resolving the quant, so a typo'd quant on a+ # real GGUF repo evicts and then fails the download.+ _fake_variants(monkeypatch, {"variants": [{"quant": "Q4_K_M"}, {"quant": "Q8_0"}]})+ with pytest.raises(typer.Exit):+ start._attach_gguf_check_for_codex(BASE, "sk-test", "unsloth/Qwen3-0.6B-GGUF:Q4_KM")+ err = capsys.readouterr().err+ assert "no GGUF variant Q4_KM" in err+ assert "Q4_K_M, Q8_0" in err+++ "requested,rows",+ [+ # Case-insensitive, exactly as the load path compares quant labels.+ ("q4_k_m", [{"quant": "Q4_K_M"}]),+ # The load falls back to a whole-token filename match, so a quant that is only part+ # of a longer label still resolves.+ ("Q4_K_XL", [{"quant": "UD-Q4_K_XL", "filename": "Qwen3-0.6B-UD-Q4_K_XL.gguf"}]),+ # An answer that carries neither field cannot disprove anything.+ ("Q4_K_M", [{"size_bytes": 1}]),+ ],+)+def test_codex_attach_check_passes_resolvable_variants(monkeypatch, requested, rows):+ _fake_variants(monkeypatch, {"variants": rows})+ start._attach_gguf_check_for_codex(BASE, "sk-test", f"unsloth/Qwen3-0.6B-GGUF:{requested}")+++def test_codex_attach_check_takes_the_variant_from_the_caller(monkeypatch):+ # `--gguf-variant` never reaches the identifier and _connect strips `repo:QUANT` before+ # the gate runs, so the quant arrives as an argument.+ _fake_variants(monkeypatch, {"variants": [{"quant": "Q8_0"}]})+ with pytest.raises(typer.Exit):+ start._attach_gguf_check_for_codex(BASE, "sk-test", "unsloth/Qwen3-0.6B-GGUF", "Q4_K_M")+++def test_codex_attach_check_defers_on_server_error(monkeypatch):+ _fake_variants(+ monkeypatch,+ urllib.error.HTTPError(f"{BASE}/api/models/gguf-variants", 404, "nope", None, None),+ )+ start._attach_gguf_check_for_codex(BASE, "sk-test", "mlx-community/Qwen3-0.6B-4bit")+ start._attach_gguf_check_for_codex(BASE, "sk-test", "unsloth/Qwen3-0.6B-GGUF:Q4_K_M")+++def test_codex_attach_check_skips_without_model(monkeypatch):+ urls = _fake_variants(monkeypatch, {"variants": []})+ start._attach_gguf_check_for_codex(BASE, "sk-test", None)+ assert urls == []++[email protected]("var", ["HF_HUB_OFFLINE", "TRANSFORMERS_OFFLINE"])+def test_hub_gguf_files_skips_hub_when_offline(monkeypatch, var):+ monkeypatch.setenv(var, "1")+ monkeypatch.setattr(+ start.urllib.request,+ "urlopen",+ lambda request, timeout: pytest.fail("offline mode must not call the hub"),+ )+ assert start._hub_gguf_files("owner/model") is None+++def test_codex_preflight_defers_bare_names_to_attached_server(monkeypatch):+ # A bare name may be a directory under the attached server's cwd, invisible here, so+ # only the auto-start path may canonicalize it.+ calls = _fake_hub_listing(monkeypatch, {"unsloth/Qwen3-0.6B": []})+ monkeypatch.setattr(start, "find_studio_server", lambda: "http://127.0.0.1:8888")+ monkeypatch.setattr(start, "verify_studio_identity", lambda base: True)+ start._preflight_codex_gguf("Qwen3-0.6B")+ assert calls == []+++def test_codex_gguf_failure_skips_hint_probe_for_non_hub_ids(monkeypatch, capsys):+ monkeypatch.setattr(+ start,+ "_hub_gguf_files",+ lambda repo: pytest.fail("must not probe the hub for a non-hub id"),+ )+ with pytest.raises(typer.Exit):+ start._fail_codex_needs_gguf("models/Llama/customer-model")+ assert "Try:" not in capsys.readouterr().err+++def test_codex_attach_rejects_before_load(fake_studio, monkeypatch):+ inner = start._http_json++ def http_json(+ method,+ url,+ token,+ payload = None,+ timeout = 30,+ error = None,+ ):+ if "/api/models/gguf-variants" in url:+ return {"variants": []}+ if url.endswith("/api/inference/load"):+ pytest.fail("rejected model must not be loaded")+ return inner(method, url, token, payload, timeout, error)++ monkeypatch.setattr(start, "_http_json", http_json)+ result = CliRunner().invoke(+ start.start_app, ["codex", "--model", "mlx-community/Qwen3-0.6B-4bit", "--no-launch"]+ )+ assert result.exit_code == 1+ assert "Codex needs a GGUF model" in result.output+++def test_codex_attach_rejects_unavailable_variant_before_load(fake_studio, monkeypatch):+ inner = start._http_json++ def http_json(+ method,+ url,+ token,+ payload = None,+ timeout = 30,+ error = None,+ ):+ if "/api/models/gguf-variants" in url:+ return {"variants": [{"quant": "Q4_K_M"}]}+ if url.endswith("/api/inference/load"):+ pytest.fail("a quant the repo does not have must not evict the resident model")+ return inner(method, url, token, payload, timeout, error)++ monkeypatch.setattr(start, "_http_json", http_json)+ result = CliRunner().invoke(+ start.start_app,+ ["codex", "--model", "unsloth/Qwen3-0.6B-GGUF:Q4_KM", "--no-launch"],+ )+ assert result.exit_code == 1+ assert "no GGUF variant Q4_KM" in result.output+++def test_codex_attach_reuses_resident_model_without_preload_probe(fake_studio, monkeypatch):+ # No load happens when the resident model already answers --model, so the gate must not+ # run: a canonical empty listing would reject a session that works.+ inner = start._http_json+ probes = []++ def http_json(+ method,+ url,+ token,+ payload = None,+ timeout = 30,+ error = None,+ ):+ if "/api/models/gguf-variants" in url:+ probes.append(url)+ return {"variants": []}+ if url.endswith("/api/inference/load"):+ pytest.fail("the resident model already matches; no load is needed")+ return inner(method, url, token, payload, timeout, error)++ monkeypatch.setattr(start, "_http_json", http_json)+ result = CliRunner().invoke(start.start_app, ["codex", "--model", MODEL["id"], "--no-launch"])+ assert result.exit_code == 0, result.output+ assert probes == []++[email protected]("endpoint", ["", "huggingface.co", "not a url"])+def test_hub_gguf_files_unknown_on_malformed_endpoint(monkeypatch, endpoint):+ monkeypatch.delenv("HF_HUB_OFFLINE", raising = False)+ monkeypatch.delenv("TRANSFORMERS_OFFLINE", raising = False)+ monkeypatch.setenv("HF_ENDPOINT", endpoint)+ assert start._hub_gguf_files("owner/model") is None+++def test_codex_attach_check_skips_direct_gguf_files(monkeypatch):+ monkeypatch.setattr(+ start,+ "_http_json",+ lambda *a, **k: pytest.fail("a direct .gguf file needs no variants probe"),+ )+ start._attach_gguf_check_for_codex(BASE, "sk-test", "/models/foo-Q4_K_M.gguf")+ start._attach_gguf_check_for_codex(BASE, "sk-test", "./local/model.GGUF")+ # A quant folder or an unrelated parent name is still the model itself.+ start._attach_gguf_check_for_codex(BASE, "sk-test", "/models/Q4_K_M/model-be.gguf")+ start._attach_gguf_check_for_codex(BASE, "sk-test", "/models/mmproj-dumps/foo-Q4_K_M.gguf")+ start._attach_gguf_check_for_codex(BASE, "sk-test", "/models/dflash/Qwen-DFlash-Q4_K_M.gguf")+++def test_codex_attach_check_direct_variant_always_asks_the_server(monkeypatch):+ # The resolver scans the file's marked parent and may bind a different sibling, so every+ # explicit variant goes to the probe.+ probes = []++ def http_json(+ method,+ url,+ token,+ payload = None,+ timeout = 30,+ error = None,+ ):+ probes.append(url)+ return {+ "variants": [{"quant": "Q4_K_M"}],+ "resolved_locally": True,+ "loadable_variants": ["Q4_K_M", "q4_k_m"],+ "loadable": True,+ }++ monkeypatch.setattr(start, "_http_json", http_json)+ start._attach_gguf_check_for_codex(BASE, "sk-test", "/models/foo-Q4_K_M.gguf", "q4_k_m")+ assert probes, "an explicit variant must reach the server"++ # Without a variant the load takes this very file, so no probe is needed.+ monkeypatch.setattr(+ start,+ "_http_json",+ lambda *a, **k: pytest.fail("a variantless direct file needs no probe"),+ )+ start._attach_gguf_check_for_codex(BASE, "sk-test", "/models/foo-Q4_K_M.gguf")+++def test_codex_attach_check_asks_server_for_foreign_direct_variant(monkeypatch, capsys):+ # A quant that is not the file's own label is the marked parent's business: an answer+ # carrying it passes, one without it fails before the load can evict.+ _fake_variants(monkeypatch, {"variants": [{"quant": "Q4_K_M"}, {"quant": "Q8_0"}]})+ start._attach_gguf_check_for_codex(BASE, "sk-test", "/models/m/model-Q4_K_M.gguf", "Q8_0")+ _fake_variants(monkeypatch, {"variants": [{"quant": "Q4_K_M"}]})+ with pytest.raises(typer.Exit):+ start._attach_gguf_check_for_codex(BASE, "sk-test", "/models/foo-Q4_K_M.gguf", "Q8_0")+ assert "no GGUF variant Q8_0" in capsys.readouterr().err+ # The parent folder cannot vouch for a quant the file is not.+ with pytest.raises(typer.Exit):+ start._attach_gguf_check_for_codex(BASE, "sk-test", "/models/Q8_0/foo-Q4_K_M.gguf", "Q8_0")+++def test_codex_attach_check_fails_live_empty_explicit_paths(tmp_path, monkeypatch, capsys):+ # Every server version resolves explicit local syntax locally, so a live empty answer+ # settles the load; deferring would send a GGUF-less directory down the transformers path.+ _fake_variants(monkeypatch, {"variants": []})+ target = tmp_path / "hf-dir"+ target.mkdir()+ with pytest.raises(typer.Exit):+ start._attach_gguf_check_for_codex(BASE, "sk-test", os.fspath(target))+ assert "Codex needs a GGUF model" in capsys.readouterr().err+++def test_codex_attach_check_still_defers_existing_raw_names(tmp_path, monkeypatch):+ # Marker-less names keep the deferral: older servers read them as hub ids, so a CLI-side+ # hit may be a server-side model.+ monkeypatch.chdir(tmp_path)+ (tmp_path / "my-model-dir").mkdir()+ _fake_variants(monkeypatch, {"variants": []})+ start._attach_gguf_check_for_codex(BASE, "sk-test", "my-model-dir")+++def test_codex_attach_check_strictness_follows_the_server_answer(monkeypatch):+ # A one-slash id can be a hub repo or a server-cwd directory; the answer says which, and+ # a local answer takes exact labels only.+ rows = [{"quant": "Q4_K_M", "filename": "model-Q4_K_M.gguf"}]+ _fake_variants(monkeypatch, {"variants": rows, "resolved_locally": True})+ with pytest.raises(typer.Exit):+ start._attach_gguf_check_for_codex(BASE, "sk-test", "models/qwen", "Q4")+ _fake_variants(monkeypatch, {"variants": rows})+ start._attach_gguf_check_for_codex(BASE, "sk-test", "models/qwen", "Q4")+++def test_codex_attach_check_strict_accepts_the_full_stem(monkeypatch):+ # The local resolver accepts the exact shard-stripped stem as a label too.+ _fake_variants(+ monkeypatch,+ {+ "variants": [{"quant": "Q4_K_M", "filename": "model-Q4_K_M.gguf"}],+ "resolved_locally": True,+ },+ )+ start._attach_gguf_check_for_codex(BASE, "sk-test", "./m", "model-Q4_K_M")+++def test_codex_attach_check_strict_rejects_nested_basename_labels(monkeypatch):+ # The local resolver answers the full relative stem, never a nested file's basename.+ _fake_variants(+ monkeypatch,+ {+ "variants": [{"quant": "BF16", "filename": "BF16/model.gguf"}],+ "resolved_locally": True,+ },+ )+ with pytest.raises(typer.Exit):+ start._attach_gguf_check_for_codex(BASE, "sk-test", "./m", "model")+++def test_codex_attach_check_rejects_torn_named_file_despite_sibling_variant(tmp_path, monkeypatch):+ # A variant does not redirect a DIRECT FILE, so the torn file named here is what loads+ # and a ready sibling row must not vouch for it.+ shard = tmp_path / "model-Q4_K_M-00001-of-00002.gguf"+ shard.write_bytes(b"GGUF")+ (tmp_path / "model-Q8_0.gguf").write_bytes(b"GGUF")+ _fake_variants(+ monkeypatch,+ {"variants": [{"quant": "Q8_0", "partial": False}], "resolved_locally": True},+ )+ with pytest.raises(typer.Exit):+ start._attach_gguf_check_for_codex(BASE, "sk-test", os.fspath(shard), "Q8_0")+++def test_codex_attach_check_rejects_a_requested_torn_local_variant(monkeypatch):+ # A torn local row's labels do not vouch: llama gets the incomplete split after teardown.+ rows = {+ "variants": [+ {"quant": "Q8_0", "partial": False},+ {"quant": "Q4_K_M", "partial": True},+ ],+ "resolved_locally": True,+ }+ _fake_variants(monkeypatch, rows)+ with pytest.raises(typer.Exit):+ start._attach_gguf_check_for_codex(BASE, "sk-test", "./m", "Q4_K_M")+ _fake_variants(monkeypatch, rows)+ start._attach_gguf_check_for_codex(BASE, "sk-test", "./m", "Q8_0")+++def test_codex_attach_check_probes_direct_paths_on_remote_servers(monkeypatch, capsys):+ # A remote filesystem is not ours, and the load takes the .gguf suffix as authoritative,+ # so a missing file evicts before failing.+ remote = "http://studio.example:8888"+ _fake_variants(monkeypatch, {"variants": [], "resolved_locally": True})+ with pytest.raises(typer.Exit):+ start._attach_gguf_check_for_codex(remote, "sk-test", "/models/gone-Q4_K_M.gguf")+ assert "Codex needs a GGUF model" in capsys.readouterr().err+ # A server that has it answers with rows, and loopback still short-circuits.+ _fake_variants(+ monkeypatch,+ {"variants": [{"quant": "Q4_K_M", "partial": False}], "resolved_locally": True},+ )+ start._attach_gguf_check_for_codex(remote, "sk-test", "/models/foo-Q4_K_M.gguf")+ monkeypatch.setattr(start, "_http_json", lambda *a, **k: pytest.fail("loopback needs no probe"))+ start._attach_gguf_check_for_codex(BASE, "sk-test", "/models/foo-Q4_K_M.gguf")++[email protected](os.name == "nt", reason = "every spelling is native on Windows")+def test_codex_attach_check_probes_non_native_direct_paths(monkeypatch, capsys):+ # A Windows path read from WSL parses to nonsense here, so it is exempt from the absence+ # check and reads as ready without anything being verified. Returning on it would vouch+ # for a file nobody looked at, and the load trusts the .gguf suffix: teardown, then failure.+ urls = _fake_variants(monkeypatch, {"variants": [], "resolved_locally": True})+ with pytest.raises(typer.Exit):+ start._attach_gguf_check_for_codex(BASE, "sk-test", r"C:\models\typo-Q4_K_M.gguf")+ assert "Codex needs a GGUF model" in capsys.readouterr().err+ assert urls, "the server was never asked"+ # The server holding it still passes.+ _fake_variants(+ monkeypatch,+ {"variants": [{"quant": "Q4_K_M", "partial": False}], "resolved_locally": True},+ )+ start._attach_gguf_check_for_codex(BASE, "sk-test", r"C:\models\foo-Q4_K_M.gguf")+++def test_codex_attach_check_honors_a_negative_verdict_without_an_allow_list(monkeypatch, capsys):+ # No loadable_variants means a direct file, which loads as itself whatever the quant, so+ # the variantless verdict decides for a variant too. The shapes differ (the row scan judges+ # the immediate parent, the resolver the model root), so a row can outlive a false verdict.+ negative = {+ "variants": [{"quant": "Q8_0", "partial": False}],+ "resolved_locally": True,+ "loadable": False,+ }+ _fake_variants(monkeypatch, negative)+ with pytest.raises(typer.Exit):+ start._attach_gguf_check_for_codex(BASE, "sk-test", "/models/MTP/sub/foo-Q8_0.gguf", "Q8_0")+ assert "Codex needs a GGUF model" in capsys.readouterr().err+ # A positive verdict passes, and a server too old to send the flag falls through to rows.+ _fake_variants(monkeypatch, {**negative, "loadable": True})+ start._attach_gguf_check_for_codex(BASE, "sk-test", "/models/sub/foo-Q8_0.gguf", "Q8_0")+ _fake_variants(monkeypatch, {k: v for k, v in negative.items() if k != "loadable"})+ start._attach_gguf_check_for_codex(BASE, "sk-test", "/models/sub/foo-Q8_0.gguf", "Q8_0")+++def test_codex_attach_check_refuses_companion_paths_with_a_variant(monkeypatch, capsys):+ # The loader consults gguf_variant only for a directory, so a refused direct file cannot+ # be rescued by naming a sibling quant.+ monkeypatch.setattr(+ start,+ "_http_json",+ lambda *a, **k: pytest.fail("a refused direct file needs no variants probe"),+ )+ with pytest.raises(typer.Exit):+ start._attach_gguf_check_for_codex(BASE, "sk-test", "/models/m/mmproj-F16.gguf", "Q4_K_M")+ assert "Codex needs a GGUF model" in capsys.readouterr().err+ with pytest.raises(typer.Exit):+ start._attach_gguf_check_for_codex(BASE, "sk-test", "/models/m/mmproj-F16.gguf")+++def test_codex_attach_check_ignores_cleanable_only_answers(monkeypatch, capsys):+ # A cleanable row offers deleting an empty leftover folder, never weights.+ _fake_variants(+ monkeypatch,+ {"variants": [{"quant": "Q4_K_M", "partial": True, "cleanable": True}]},+ )+ with pytest.raises(typer.Exit):+ start._attach_gguf_check_for_codex(BASE, "sk-test", "owner/no-gguf")+ assert "Codex needs a GGUF model" in capsys.readouterr().err+ # A real listed row beside it still answers.+ _fake_variants(+ monkeypatch,+ {+ "variants": [+ {"quant": "Q8_0", "partial": True, "cleanable": True},+ {"quant": "Q4_K_M"},+ ]+ },+ )+ start._attach_gguf_check_for_codex(BASE, "sk-test", "owner/has-gguf")+++def test_codex_attach_check_follows_bare_names_the_server_calls_remote(monkeypatch):+ # The load uses a bare name only when it resolves locally, so an answer the server marks+ # non-local must not settle the shorthand.+ urls = []++ def http_json(+ method,+ url,+ token,+ payload = None,+ timeout = 30,+ error = None,+ ):+ urls.append(url)+ if "unsloth" in url:+ return {"variants": [{"quant": "Q4_K_M"}], "resolved_locally": False}+ return {"variants": [], "resolved_locally": False}++ monkeypatch.setattr(start, "_http_json", http_json)+ start._attach_gguf_check_for_codex(BASE, "sk-test", "Qwen3-0.6B-GGUF")+ assert len(urls) == 2 and "unsloth%2FQwen3-0.6B-GGUF" in urls[1]+++def test_codex_attach_check_trusts_the_servers_loadable_answer(monkeypatch, capsys):+ # When the server answers with the load resolver itself, that settles the round.+ _fake_variants(+ monkeypatch,+ {+ "variants": [{"quant": "BF16", "filename": "BF16/model.gguf"}],+ "resolved_locally": True,+ "loadable_variants": ["BF16"],+ "loadable": False,+ },+ )+ # Naming the quant works even though every row is nested...+ start._attach_gguf_check_for_codex(BASE, "sk-test", "./m", "BF16")+ _fake_variants(+ monkeypatch,+ {+ "variants": [{"quant": "BF16", "filename": "BF16/model.gguf"}],+ "resolved_locally": True,+ "loadable_variants": ["BF16"],+ "loadable": False,+ },+ )+ # ...and a variantless load, which cannot pick it, is refused.+ with pytest.raises(typer.Exit):+ start._attach_gguf_check_for_codex(BASE, "sk-test", "./m")+ assert "Codex needs a GGUF model" in capsys.readouterr().err+ # A quant the load would not serve is refused even though a row lists it.+ _fake_variants(+ monkeypatch,+ {+ "variants": [{"quant": "Q8_0", "filename": "m-Q8_0-00001-of-00002.gguf"}],+ "resolved_locally": True,+ "loadable_variants": [],+ "loadable": False,+ },+ )+ with pytest.raises(typer.Exit):+ start._attach_gguf_check_for_codex(BASE, "sk-test", "./m", "Q8_0")+++def test_codex_attach_check_probes_missing_bare_gguf_shorthands(tmp_path, monkeypatch, capsys):+ # A bare foo.gguf naming no local file is not a path: the load canonicalizes it to+ # unsloth/foo.gguf, so the gate follows it there.+ monkeypatch.chdir(tmp_path)+ urls = []++ def http_json(+ method,+ url,+ token,+ payload = None,+ timeout = 30,+ error = None,+ ):+ urls.append(url)+ return {"variants": []}++ monkeypatch.setattr(start, "_http_json", http_json)+ with pytest.raises(typer.Exit):+ start._attach_gguf_check_for_codex(BASE, "sk-test", "foo.gguf")+ assert any("repo_id=unsloth%2Ffoo.gguf" in url for url in urls)+ # A file that does exist is still the direct path it names.+ (tmp_path / "real-Q4_K_M.gguf").write_bytes(b"GGUF")+ monkeypatch.setattr(+ start, "_http_json", lambda *a, **k: pytest.fail("an existing file needs no probe")+ )+ start._attach_gguf_check_for_codex(BASE, "sk-test", "real-Q4_K_M.gguf")+++def test_codex_attach_check_treats_gguf_suffixed_hub_ids_as_remote(monkeypatch):+ # owner/name.gguf is a repo, not a path: the remote load scans siblings recursively and+ # matches loosely, so local-only rules must not apply.+ _fake_variants(+ monkeypatch,+ {"variants": [{"quant": "Q4_K_M", "filename": "BF16/model-Q4_K_M.gguf"}]},+ )+ start._attach_gguf_check_for_codex(BASE, "sk-test", "owner/model.gguf")+ _fake_variants(+ monkeypatch,+ {"variants": [{"quant": "UD-Q4_K_XL", "filename": "m-UD-Q4_K_XL.gguf"}]},+ )+ start._attach_gguf_check_for_codex(BASE, "sk-test", "owner/model.gguf", "Q4_K_XL")+++def test_codex_attach_check_accepts_bpw_qualified_local_requests(monkeypatch):+ # The listing advertises the stripped label, the local loader takes the full bpw+ # spelling; both name the same file, so both must pass.+ _fake_variants(+ monkeypatch,+ {+ "variants": [{"quant": "IQ4_XS", "filename": "model-IQ4_XS-3.53bpw.gguf"}],+ "resolved_locally": True,+ },+ )+ start._attach_gguf_check_for_codex(BASE, "sk-test", "./m", "IQ4_XS-3.53bpw")+++def test_codex_attach_check_strict_accepts_basename_quant_tokens(monkeypatch):+ # The loose-file resolver takes any whole quant token of the basename, so the listing's+ # own default (the file's other label) must pass.+ _fake_variants(+ monkeypatch,+ {+ "variants": [{"quant": "F16", "filename": "F16-checkpoint-Q4_K_M.gguf"}],+ "resolved_locally": True,+ },+ )+ start._attach_gguf_check_for_codex(+ BASE, "sk-test", "/models/F16-checkpoint-Q4_K_M.gguf", "Q4_K_M"+ )+++def test_codex_attach_check_honors_resolved_locally_empty_for_raw_names(+ tmp_path, monkeypatch, capsys+):+ # A server that resolved the name locally already answered for the directory the load+ # will take, so deferring on CLI existence would let it evict the resident model.+ monkeypatch.chdir(tmp_path)+ (tmp_path / "models" / "qwen").mkdir(parents = True)+ _fake_variants(monkeypatch, {"variants": [], "resolved_locally": True})+ with pytest.raises(typer.Exit):+ start._attach_gguf_check_for_codex(BASE, "sk-test", "models/qwen")+ assert "Codex needs a GGUF model" in capsys.readouterr().err+ # A legacy answer without the flag keeps the deferral.+ _fake_variants(monkeypatch, {"variants": []})+ start._attach_gguf_check_for_codex(BASE, "sk-test", "models/qwen")+++def test_codex_attach_check_requires_a_pickable_row_without_a_variant(monkeypatch, capsys):+ # detect_gguf_model picks from the top level, so rows living only in quant subdirectories+ # need an explicit variant.+ rows = {+ "variants": [{"quant": "BF16", "filename": "BF16/model.gguf"}],+ "resolved_locally": True,+ }+ _fake_variants(monkeypatch, rows)+ with pytest.raises(typer.Exit):+ start._attach_gguf_check_for_codex(BASE, "sk-test", "./m")+ err = capsys.readouterr().err+ assert "quant subdirectories" in err and "BF16" in err+ # Naming the variant resolves it, and a top-level row needs nothing.+ _fake_variants(monkeypatch, rows)+ start._attach_gguf_check_for_codex(BASE, "sk-test", "./m", "BF16")+ _fake_variants(+ monkeypatch,+ {"variants": [{"quant": "Q4_K_M", "filename": "m-Q4_K_M.gguf"}], "resolved_locally": True},+ )+ start._attach_gguf_check_for_codex(BASE, "sk-test", "./m")+++def test_codex_attach_check_probes_gguf_named_directories(tmp_path, monkeypatch, capsys):+ # The detector scans a .gguf-named directory instead of trusting the suffix.+ gguf_dir = tmp_path / "foo.gguf"+ gguf_dir.mkdir()+ _fake_variants(monkeypatch, {"variants": [], "resolved_locally": True})+ with pytest.raises(typer.Exit):+ start._attach_gguf_check_for_codex(BASE, "sk-test", os.fspath(gguf_dir))+ assert "Codex needs a GGUF model" in capsys.readouterr().err+ # One holding weights answers with rows and passes.+ _fake_variants(+ monkeypatch,+ {"variants": [{"quant": "Q4_K_M", "filename": "m-Q4_K_M.gguf"}], "resolved_locally": True},+ )+ start._attach_gguf_check_for_codex(BASE, "sk-test", os.fspath(gguf_dir))+++def test_codex_attach_check_allows_short_shard_like_names(tmp_path, monkeypatch):+ # The split grammar is five digits exactly, so a -001-of-002 name loads as an ordinary file.+ monkeypatch.setattr(+ start,+ "_http_json",+ lambda *a, **k: pytest.fail("a direct .gguf file needs no variants probe"),+ )+ lone = tmp_path / "model-Q4_K_M-001-of-002.gguf"+ lone.write_bytes(b"GGUF")+ start._attach_gguf_check_for_codex(BASE, "sk-test", os.fspath(lone))+++def test_codex_attach_check_honors_loadable_on_an_empty_listing(monkeypatch):+ # A root-blind lister can miss a file detect_gguf_model resolves, so an empty answer+ # reporting loadable is loadable.+ _fake_variants(monkeypatch, {"variants": [], "resolved_locally": True, "loadable": True})+ start._attach_gguf_check_for_codex(BASE, "sk-test", "/models/MTP/foo-Q8_0.gguf")+ # Empty and not loadable still fails.+ _fake_variants(monkeypatch, {"variants": [], "resolved_locally": True, "loadable": False})+ with pytest.raises(typer.Exit):+ start._attach_gguf_check_for_codex(BASE, "sk-test", "/models/MTP/foo-Q8_0.gguf")+++def test_codex_preload_gate_checks_direct_path_identity(fake_studio, monkeypatch, tmp_path):+ # /v1/models shows only the basename, so a different path with the same name reloads.+ inner = start._http_json+ probed = []+ resident = tmp_path / "old" / "foo-Q4_K_M.gguf"+ resident.parent.mkdir()+ resident.write_bytes(b"GGUF")+ other = tmp_path / "new" / "foo-Q4_K_M.gguf"+ other.parent.mkdir()+ other.write_bytes(b"GGUF")++ def http_json(+ method,+ url,+ token,+ payload = None,+ timeout = 30,+ error = None,+ ):+ if url.endswith("/v1/models"):+ return {"data": [{"id": "foo-Q4_K_M", "loaded": True}]}+ if url.endswith("/api/inference/status"):+ return {+ "is_gguf": True,+ "gguf_variant": "Q4_K_M",+ "model_identifier": os.fspath(resident),+ }+ if "/api/models/gguf-variants" in url:+ probed.append(url)+ return {"variants": [{"quant": "Q4_K_M"}], "resolved_locally": True, "loadable": True}+ return inner(method, url, token, payload, timeout, error)++ monkeypatch.setattr(start, "_http_json", http_json)+ CliRunner().invoke(+ start.start_app,+ ["codex", "--model", os.fspath(other), "--gguf-variant", "Q4_K_M", "--no-launch"],+ )+ assert probed, "a different path with the same basename is not the resident model"+++def test_codex_preload_gate_runs_for_a_settings_reload(fake_studio, monkeypatch):+ # A knob that changes the runtime intent is a real reload nothing dedupes, so the gate+ # runs even for the resident id.+ inner = start._http_json+ probed = []++ def http_json(+ method,+ url,+ token,+ payload = None,+ timeout = 30,+ error = None,+ ):+ if "/api/models/gguf-variants" in url:+ probed.append(url)+ return {"variants": [{"quant": "Q4_K_M"}], "resolved_locally": False}+ return inner(method, url, token, payload, timeout, error)++ monkeypatch.setattr(start, "_http_json", http_json)+ CliRunner().invoke(+ start.start_app,+ ["codex", "--model", MODEL["id"], "--max-seq-length", "8192", "--no-launch"],+ )+ assert probed, "a context-length change reloads, so the gate must check it"+++def test_codex_preload_gate_runs_for_a_mistyped_resident_variant(fake_studio, monkeypatch):+ # The server matches intent case-insensitively but keeps separators, so Q4KM is not the+ # resident Q4_K_M and really reloads.+ inner = start._http_json+ probed = []++ def http_json(+ method,+ url,+ token,+ payload = None,+ timeout = 30,+ error = None,+ ):+ if url.endswith("/api/inference/status"):+ return {"is_gguf": True, "gguf_variant": "Q4_K_M"}+ if "/api/models/gguf-variants" in url:+ probed.append(url)+ return {"variants": [{"quant": "Q4_K_M"}], "resolved_locally": False}+ return inner(method, url, token, payload, timeout, error)++ monkeypatch.setattr(start, "_http_json", http_json)+ CliRunner().invoke(+ start.start_app,+ ["codex", "--model", MODEL["id"], "--gguf-variant", "Q4KM", "--no-launch"],+ )+ assert probed, "a separator-mangled quant is not the resident one"+++def test_codex_preload_gate_defers_to_the_resident_model(fake_studio, monkeypatch):+ # An explicit knob forces the load endpoint's disk-free dedupe to answer; gating it would+ # reject a second session for the model already serving, whose file may have moved.+ inner = start._http_json++ def http_json(+ method,+ url,+ token,+ payload = None,+ timeout = 30,+ error = None,+ ):+ if url.endswith("/api/inference/status"):+ return {"is_gguf": True, "gguf_variant": "Q4_K_M"}+ if "/api/models/gguf-variants" in url:+ pytest.fail("the resident model already serves this request")+ return inner(method, url, token, payload, timeout, error)++ monkeypatch.setattr(start, "_http_json", http_json)+ result = CliRunner().invoke(+ start.start_app,+ ["codex", "--model", MODEL["id"], "--gguf-variant", "Q4_K_M", "--no-launch"],+ )+ assert result.exit_code == 0, result.output+++def test_codex_preload_gate_still_runs_for_a_different_variant(fake_studio, monkeypatch):+ # A different quant is a real reload, so the gate has to run.+ inner = start._http_json+ probed = []++ def http_json(+ method,+ url,+ token,+ payload = None,+ timeout = 30,+ error = None,+ ):+ if url.endswith("/api/inference/status"):+ return {"is_gguf": True, "gguf_variant": "Q4_K_M"}+ if "/api/models/gguf-variants" in url:+ probed.append(url)+ return {"variants": [{"quant": "Q4_K_M"}], "resolved_locally": False}+ return inner(method, url, token, payload, timeout, error)++ monkeypatch.setattr(start, "_http_json", http_json)+ CliRunner().invoke(+ start.start_app,+ ["codex", "--model", MODEL["id"], "--gguf-variant", "Q8_0", "--no-launch"],+ )+ assert probed, "a different quant reloads, so the gate must check it"+++def test_codex_attach_check_asks_about_nested_drafter_folders(monkeypatch, capsys):+ # detect_gguf_model reads drafter folders relative to the model root, so the same nested+ # path loads or is refused depending on a root this process cannot see.+ _fake_variants(monkeypatch, {"variants": [], "resolved_locally": True})+ with pytest.raises(typer.Exit):+ start._attach_gguf_check_for_codex(BASE, "sk-test", "/models/MTP/copies/foo-Q8_0.gguf")+ assert "Codex needs a GGUF model" in capsys.readouterr().err+ # A server that serves it answers with rows and the attach proceeds.+ _fake_variants(+ monkeypatch,+ {"variants": [{"quant": "Q8_0"}], "resolved_locally": True, "loadable": True},+ )+ start._attach_gguf_check_for_codex(BASE, "sk-test", "/models/MTP/copies/foo-Q8_0.gguf")+ # A drafter NAME PREFIX means the same under any root, so it is refused with no probe.+ monkeypatch.setattr(+ start, "_http_json", lambda *a, **k: pytest.fail("an immediate companion needs no probe")+ )+ with pytest.raises(typer.Exit):+ start._attach_gguf_check_for_codex(BASE, "sk-test", "/models/mtp-foo-Q8_0.gguf")+++def test_codex_attach_check_defers_foreign_path_syntax(monkeypatch, tmp_path):+ # A Windows path read from POSIX parses to nonsense here (parent '.'), so its local+ # absence says nothing about the server's disk.+ monkeypatch.chdir(tmp_path)+ monkeypatch.setattr(start, "_http_json", lambda *a, **k: {"variants": [{"quant": "Q4_K_M"}]})+ start._attach_gguf_check_for_codex(BASE, "sk-test", "C:\\models\\foo-Q4_K_M.gguf")+ # A native path that really is absent is still failed.+ with pytest.raises(typer.Exit):+ start._attach_gguf_check_for_codex(+ BASE, "sk-test", os.fspath(tmp_path / "gone-Q4_K_M.gguf")+ )+++def test_codex_attach_check_defers_when_loopback_is_not_this_machine(monkeypatch, tmp_path):+ # 127.0.0.1 can be an SSH or container forward, where a server-valid path is simply absent+ # here. Without a confirmed identity the local filesystem says nothing, so the probe decides.+ monkeypatch.chdir(tmp_path)+ monkeypatch.setattr(start, "verify_studio_identity", lambda base, **_kw: False)+ probes = []++ def http_json(+ method,+ url,+ token,+ payload = None,+ timeout = 30,+ error = None,+ ):+ probes.append(url)+ return {"variants": [{"quant": "Q4_K_M"}]}++ monkeypatch.setattr(start, "_http_json", http_json)+ # Absent locally, and an incomplete local shard: neither may settle it now.+ start._attach_gguf_check_for_codex(BASE, "sk-test", os.fspath(tmp_path / "gone-Q4_K_M.gguf"))+ torn = tmp_path / "torn-Q4_K_M-00001-of-00002.gguf"+ torn.write_bytes(b"GGUF")+ start._attach_gguf_check_for_codex(BASE, "sk-test", os.fspath(torn))+ assert probes, "the server must be asked when its filesystem is not ours"+++def test_codex_attach_check_treats_both_spellings_as_native_on_windows(monkeypatch, tmp_path):+ # The other half of the asymmetry above: Windows accepts forward slashes, so both spellings+ # are native there and an absent file is really absent.+ monkeypatch.chdir(tmp_path)+ _simulate_windows(monkeypatch)+ assert start._path_syntax_is_native("C:\\models\\foo-Q4_K_M.gguf") is True+ assert start._path_syntax_is_native("/models/foo-Q4_K_M.gguf") is True+ monkeypatch.setattr(+ start,+ "_http_json",+ lambda *a, **k: pytest.fail("a visible missing file needs no probe"),+ )+ with pytest.raises(typer.Exit):+ start._attach_gguf_check_for_codex(+ BASE, "sk-test", os.fspath(tmp_path / "gone-Q4_K_M.gguf")+ )+++def test_codex_attach_check_rejects_missing_direct_paths(tmp_path, monkeypatch, capsys):+ # A mistyped or deleted path is still a GGUF load, so it tears the resident model down+ # and only then fails.+ monkeypatch.setattr(+ start,+ "_http_json",+ lambda *a, **k: pytest.fail("a visible missing file needs no probe"),+ )+ with pytest.raises(typer.Exit):+ start._attach_gguf_check_for_codex(+ BASE, "sk-test", os.fspath(tmp_path / "typo-Q4_K_M.gguf")+ )+ assert "does not exist" in capsys.readouterr().err+ # A path under a directory this process cannot list stays unknowable.+ start._attach_gguf_check_for_codex(BASE, "sk-test", "/nonexistent-root/dir/m-Q4_K_M.gguf")+++def test_codex_attach_check_rejects_broken_direct_symlinks(tmp_path, monkeypatch, capsys):+ # A broken symlink is visible here, and the suffix alone still makes it a GGUF load that+ # fails after teardown.+ monkeypatch.setattr(+ start,+ "_http_json",+ lambda *a, **k: pytest.fail("a direct .gguf file needs no variants probe"),+ )+ link = tmp_path / "gone-Q4_K_M.gguf"+ link.symlink_to(tmp_path / "missing-target.gguf")+ with pytest.raises(typer.Exit):+ start._attach_gguf_check_for_codex(BASE, "sk-test", os.fspath(link))+ assert "incomplete" in capsys.readouterr().err+++def test_codex_attach_check_fails_all_partial_local_answers(monkeypatch, capsys):+ # A local answer of only torn rows proves a load llama cannot serve; a hub answer passes+ # because the downloader resumes hub partials.+ rows = {"variants": [{"quant": "Q4_K_M", "partial": True}], "resolved_locally": True}+ _fake_variants(monkeypatch, rows)+ with pytest.raises(typer.Exit):+ start._attach_gguf_check_for_codex(BASE, "sk-test", "./m")+ assert "incomplete GGUF weights" in capsys.readouterr().err+ _fake_variants(monkeypatch, {"variants": [{"quant": "Q4_K_M", "partial": True}]})+ start._attach_gguf_check_for_codex(BASE, "sk-test", "unsloth/Qwen3-0.6B-GGUF")+ # A server predating resolved_locally still resolves explicit path syntax locally.+ _fake_variants(monkeypatch, {"variants": [{"quant": "Q4_K_M", "partial": True}]})+ with pytest.raises(typer.Exit):+ start._attach_gguf_check_for_codex(BASE, "sk-test", "./m")+++def test_codex_attach_check_local_answers_take_exact_labels_only(monkeypatch):+ # The local resolver takes exact labels only, so a local answer must not let the+ # filename-token tier vouch for a shorter quant; hub answers keep that tier.+ rows = {"variants": [{"quant": "Q4_K_M", "filename": "model-Q4_K_M.gguf"}]}+ _fake_variants(monkeypatch, rows)+ with pytest.raises(typer.Exit):+ start._attach_gguf_check_for_codex(BASE, "sk-test", "./m", "Q4")+ _fake_variants(monkeypatch, rows)+ start._attach_gguf_check_for_codex(BASE, "sk-test", "unsloth/Qwen3-0.6B-GGUF", "Q4")+++def test_codex_attach_check_rejects_incomplete_direct_files(tmp_path, monkeypatch, capsys):+ # On a loopback attach the CLI sees the server's filesystem, and llama finds missing bytes+ # or shards only after the resident model is torn down.+ monkeypatch.setattr(+ start,+ "_http_json",+ lambda *a, **k: pytest.fail("a direct .gguf file needs no variants probe"),+ )+ empty = tmp_path / "zero-Q4_K_M.gguf"+ empty.write_bytes(b"")+ with pytest.raises(typer.Exit):+ start._attach_gguf_check_for_codex(BASE, "sk-test", os.fspath(empty))+ assert "incomplete" in capsys.readouterr().err++ shard = tmp_path / "m-Q4_K_M-00001-of-00002.gguf"+ shard.write_bytes(b"GGUF")+ with pytest.raises(typer.Exit):+ start._attach_gguf_check_for_codex(BASE, "sk-test", os.fspath(shard))++ # The complete set beside it passes, and a CLI-invisible path stays open.+ (tmp_path / "m-Q4_K_M-00002-of-00002.gguf").write_bytes(b"GGUF")+ start._attach_gguf_check_for_codex(BASE, "sk-test", os.fspath(shard))+ start._attach_gguf_check_for_codex(BASE, "sk-test", "/nonexistent/other-Q4_K_M.gguf")+++def test_codex_attach_check_accepts_symlinked_split_shards(tmp_path, monkeypatch):+ # The load resolves an incomplete nominal set through the symlink to the target's shards,+ # so the readiness check does the same.+ monkeypatch.setattr(+ start,+ "_http_json",+ lambda *a, **k: pytest.fail("a direct .gguf file needs no variants probe"),+ )+ real = tmp_path / "real"+ real.mkdir()+ (real / "m-Q4_K_M-00001-of-00002.gguf").write_bytes(b"GGUF")+ (real / "m-Q4_K_M-00002-of-00002.gguf").write_bytes(b"GGUF")+ links = tmp_path / "links"+ links.mkdir()+ link = links / "m-Q4_K_M-00001-of-00002.gguf"+ link.symlink_to(real / "m-Q4_K_M-00001-of-00002.gguf")+ start._attach_gguf_check_for_codex(BASE, "sk-test", os.fspath(link))++ # A target set that is itself torn still fails.+ (real / "m-Q4_K_M-00002-of-00002.gguf").unlink()+ with pytest.raises(typer.Exit):+ start._attach_gguf_check_for_codex(BASE, "sk-test", os.fspath(link))+++ "path",+ [+ "/models/mmproj-F16.gguf",+ "./local/MMPROJ-F32.GGUF",+ "/models/mtp-Qwen3-Q8_0.gguf",+ "/models/dspark/dspark-DeepSeek-Q8_0.gguf",+ "C:\\models\\mmproj-F16.gguf",+ ],+)+def test_codex_attach_check_refuses_companion_gguf_files(monkeypatch, capsys, path):+ # Projector and drafter name prefixes read the basename alone, so detect_gguf_model refuses+ # these under any root and the name settles it; probing would defer on a path that exists.+ # A drafter FOLDER is root-dependent instead (see the nested-drafter test).+ monkeypatch.setattr(+ start,+ "_http_json",+ lambda *a, **k: pytest.fail("a companion .gguf needs no variants probe"),+ )+ with pytest.raises(typer.Exit):+ start._attach_gguf_check_for_codex(BASE, "sk-test", path)+ assert "Codex needs a GGUF model" in capsys.readouterr().err+++def test_codex_preflight_canonicalizes_missing_bare_gguf_names(tmp_path, monkeypatch):+ # A bare foo.gguf naming no local file is a shorthand the load canonicalizes, so the+ # preflight checks the repo that will load.+ monkeypatch.chdir(tmp_path)+ calls = _fake_hub_listing(monkeypatch, {"unsloth/foo.gguf": []})+ with pytest.raises(typer.Exit):+ start._preflight_codex_gguf("foo.gguf")+ assert calls == ["unsloth/foo.gguf"]++[email protected]("kwargs", [{"serve": False}, {"launch": False}])+def test_codex_preflight_skips_when_autostart_impossible(monkeypatch, kwargs):+ calls = _fake_hub_listing(monkeypatch, {"mlx-community/Qwen3-0.6B-4bit": []})+ start._preflight_codex_gguf("mlx-community/Qwen3-0.6B-4bit", **kwargs)+ assert calls == []+++def test_codex_attach_check_normalizes_shorthand_after_raw_probe(monkeypatch, capsys):+ monkeypatch.setattr(start, "_hub_gguf_files", lambda repo: None)+ urls = []++ def http_json(+ method,+ url,+ token,+ payload = None,+ timeout = 30,+ error = None,+ ):+ urls.append(url)+ if "repo_id=Qwen3-0.6B" in url and "unsloth" not in url:+ raise urllib.error.HTTPError(url, 400, "invalid repo_id", None, None)+ return {"variants": []}++ monkeypatch.setattr(start, "_http_json", http_json)+ with pytest.raises(typer.Exit):+ start._attach_gguf_check_for_codex(BASE, "sk-test", "Qwen3-0.6B")+ assert len(urls) == 2+ assert "repo_id=unsloth%2FQwen3-0.6B" in urls[1]+ assert "unsloth/Qwen3-0.6B" in capsys.readouterr().err+++def test_codex_attach_check_trusts_raw_server_dir_answer(monkeypatch):+ urls = []++ def http_json(+ method,+ url,+ token,+ payload = None,+ timeout = 30,+ error = None,+ ):+ urls.append(url)+ return {"variants": [{"quant": "Q4_K_M"}]}++ monkeypatch.setattr(start, "_http_json", http_json)+ start._attach_gguf_check_for_codex(BASE, "sk-test", "local-gguf-dir")+ assert len(urls) == 1+++def test_codex_attach_check_rejects_live_empty_raw_shorthand(monkeypatch, tmp_path, capsys):+ # A live empty answer for the raw name is the server resolving it against its own cwd,+ # exactly what the load does; unsloth/<name> is tried only when that resolves to nothing.+ monkeypatch.chdir(tmp_path)+ monkeypatch.setattr(start, "_hub_gguf_files", lambda repo: None)+ urls = []++ def http_json(+ method,+ url,+ token,+ payload = None,+ timeout = 30,+ error = None,+ ):+ urls.append(url)+ if "unsloth" in url:+ return {"variants": [{"quant": "Q4_K_M"}]}+ return {"variants": []}++ monkeypatch.setattr(start, "_http_json", http_json)+ with pytest.raises(typer.Exit):+ start._attach_gguf_check_for_codex(BASE, "sk-test", "Qwen3-0.6B-GGUF")+ assert len(urls) == 1+ assert "Qwen3-0.6B-GGUF" in capsys.readouterr().err+++def test_codex_attach_check_defers_shorthand_when_canonical_probe_errors(monkeypatch):+ def http_json(+ method,+ url,+ token,+ payload = None,+ timeout = 30,+ error = None,+ ):+ raise urllib.error.HTTPError(url, 404, "nope", None, None)++ monkeypatch.setattr(start, "_http_json", http_json)+ start._attach_gguf_check_for_codex(BASE, "sk-test", "Qwen3-0.6B")+++def test_codex_attach_check_probes_hub_shaped_gguf_ids(monkeypatch, capsys):+ monkeypatch.setattr(start, "_hub_gguf_files", lambda repo: None)+ urls = _fake_variants(monkeypatch, {"variants": []})+ with pytest.raises(typer.Exit):+ start._attach_gguf_check_for_codex(BASE, "sk-test", "owner/model.gguf")+ assert len(urls) == 1+ assert "owner%2Fmodel.gguf" in urls[0]+++def test_codex_attach_check_defers_when_raw_name_exists_locally(monkeypatch, tmp_path):+ (tmp_path / "models" / "qwen").mkdir(parents = True)+ monkeypatch.chdir(tmp_path)+ _fake_variants(monkeypatch, {"variants": []})+ start._attach_gguf_check_for_codex(BASE, "sk-test", "models/qwen")