Skip to content

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.

Skip an Ollama manifest whose JSON is not an object, instead of 500ing the model picker (#9754)

Rajarshi Datta95fd60fa2436
diff --git a/studio/backend/routes/models.py b/studio/backend/routes/models.py
index 0d8e786bbd1..72c14c12b73 100644
--- a/studio/backend/routes/models.py
+++ b/studio/backend/routes/models.py
@@ -890,8 +890,20 @@ def _scan_ollama_dir(ollama_dir: Path, limit: Optional[int] = None) -> List[Loca
e,
)
continue
+ # Parsed, but the shape is still whatever was on disk. rglob("*") hands us every
+ # file under manifests/, so a pruned pull, an editor backup, or any stray JSON can
+ # be a list or a string; .get() on one raises AttributeError, which neither this
+ # loop's `except OSError` nor the caller's catches, and one such file would 500
+ # the whole picker. Mirrors hub/services/models/ollama.py, which already validates
+ # each level of the same document.
+ if not isinstance(manifest, dict):
+ logger.debug("Skipping Ollama manifest %s: top level is not an object", tag_file)
+ continue
- config_digest = manifest.get("config", {}).get("digest", "")
+ config = manifest.get("config")
+ config_digest = config.get("digest", "") if isinstance(config, dict) else ""
+ if not isinstance(config_digest, str):
+ config_digest = ""
model_type = ""
file_type = ""
if config_digest and blobs_dir.is_dir():
@@ -899,24 +911,32 @@ def _scan_ollama_dir(ollama_dir: Path, limit: Optional[int] = None) -> List[Loca
if config_blob.is_file():
try:
cfg = json.loads(config_blob.read_text(encoding = "utf-8-sig"))
- model_type = cfg.get("model_type", "")
- file_type = cfg.get("file_type", "")
except (json.JSONDecodeError, OSError, UnicodeDecodeError) as e:
logger.debug(
"Could not parse Ollama config blob %s: %s",
config_blob,
e,
)
+ cfg = None
+ if isinstance(cfg, dict):
+ model_type = cfg.get("model_type", "")
+ file_type = cfg.get("file_type", "")
model_link_dir = links_root / stem_hash
gguf_link_path: Optional[str] = None
quant = f"-{file_type}" if file_type else ""
safe_name = repo_name.replace("/", "-")
- for layer in manifest.get("layers") or []:
+ layers = manifest.get("layers") or []
+ if not isinstance(layers, list):
+ logger.debug("Skipping Ollama manifest %s: layers is not a list", tag_file)
+ continue
+ for layer in layers:
+ if not isinstance(layer, dict):
+ continue
media = layer.get("mediaType", "")
digest = layer.get("digest", "")
- if not digest:
+ if not isinstance(digest, str) or not digest:
continue
if media == "application/vnd.ollama.image.model":
@@ -1383,11 +1403,25 @@ def _dir_has_downloaded_model(directory: Path, max_entries: int = 4000) -> bool:
manifest = json.loads(m.read_text(encoding = "utf-8-sig"))
except (json.JSONDecodeError, OSError, ValueError):
continue
- for layer in manifest.get("layers") or []:
+ # Same shape check as _scan_ollama_dir: a valid-JSON non-object under
+ # manifests/ must be skipped, not walked, or the chip probe raises
+ # AttributeError past the `except OSError` below.
+ if not isinstance(manifest, dict):
+ continue
+ layers = manifest.get("layers") or []
+ if not isinstance(layers, list):
+ continue
+ for layer in layers:
+ if not isinstance(layer, dict):
+ continue
if layer.get("mediaType") != "application/vnd.ollama.image.model":
continue
digest = layer.get("digest", "")
- if digest and (blobs / digest.replace(":", "-")).is_file():
+ if (
+ isinstance(digest, str)
+ and digest
+ and (blobs / digest.replace(":", "-")).is_file()
+ ):
return True
except OSError:
pass
diff --git a/studio/backend/tests/test_ollama_manifest_shape_guard.py b/studio/backend/tests/test_ollama_manifest_shape_guard.py
new file mode 100644
index 00000000000..f8ebed3ab94
--- /dev/null
+++ b/studio/backend/tests/test_ollama_manifest_shape_guard.py
@@ -0,0 +1,101 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""A stray non-object JSON file under an Ollama ``manifests/`` tree must be skipped.
+
+``rglob("*")`` accepts every file below ``manifests/``, so an interrupted pull, an editor
+backup, or any unrelated JSON reaches the parser. Both readers used to call ``.get()`` on
+whatever ``json.loads`` returned; on a list or a string that raises ``AttributeError``, which
+neither reader's ``except OSError`` catches, so one such file 500'd ``GET /models/local`` and
+``GET /v1/models`` and emptied the whole model picker.
+"""
+
+import json
+
+import pytest
+
+from routes.models import _dir_has_downloaded_model, _scan_ollama_dir
+
+# Valid JSON, wrong shape. Each of these is something json.loads happily returns.
+NON_OBJECT_MANIFESTS = ("[]", '["a"]', '"just a string"', "3", "null", "true")
+
+
+def _manifest_dir(root, model = "foo"):
+ d = root / "manifests" / "registry.ollama.ai" / "library" / model
+ d.mkdir(parents = True, exist_ok = True)
+ return d
+
+
+def _write_good_model(
+ root,
+ model = "good",
+ blob = "sha256-abc123",
+):
+ """A manifest whose model layer resolves to a real blob, i.e. one the scan must surface."""
+ blobs = root / "blobs"
+ blobs.mkdir(exist_ok = True)
+ (blobs / blob.replace(":", "-")).write_bytes(b"GGUF fake weights")
+ (_manifest_dir(root, model) / "latest").write_text(
+ json.dumps(
+ {
+ "layers": [
+ {"mediaType": "application/vnd.ollama.image.model", "digest": blob},
+ ],
+ },
+ ),
+ encoding = "utf-8",
+ )
+
+
[email protected]("payload", NON_OBJECT_MANIFESTS)
+def test_scan_skips_non_object_manifest(tmp_path, payload):
+ (_manifest_dir(tmp_path, "bad") / "latest").write_text(payload, encoding = "utf-8")
+ (tmp_path / "blobs").mkdir(exist_ok = True)
+
+ assert _scan_ollama_dir(tmp_path) == []
+
+
[email protected]("payload", NON_OBJECT_MANIFESTS)
+def test_one_bad_manifest_does_not_hide_the_good_models(tmp_path, payload):
+ _write_good_model(tmp_path)
+ (_manifest_dir(tmp_path, "bad") / "latest").write_text(payload, encoding = "utf-8")
+
+ found = _scan_ollama_dir(tmp_path)
+
+ assert [m.model_id for m in found] == ["ollama/good:latest"]
+
+
+ "manifest",
+ [
+ {"layers": "not-a-list"},
+ {"layers": {"mediaType": "application/vnd.ollama.image.model"}},
+ {"layers": ["not-a-dict", 7, None]},
+ {"layers": [{"mediaType": "application/vnd.ollama.image.model", "digest": 42}]},
+ {"config": "not-a-dict"},
+ {"config": ["digest"]},
+ # A dict config carrying a non-string digest: truthy, so it reaches
+ # config_digest.replace(":", "-") once a blobs/ dir exists.
+ {"config": {"digest": 42}},
+ ],
+)
+def test_scan_survives_wrong_shapes_inside_the_manifest(tmp_path, manifest):
+ (_manifest_dir(tmp_path, "bad") / "latest").write_text(json.dumps(manifest), encoding = "utf-8")
+ (tmp_path / "blobs").mkdir(exist_ok = True)
+
+ assert _scan_ollama_dir(tmp_path) == []
+
+
[email protected]("payload", NON_OBJECT_MANIFESTS)
+def test_folder_chip_probe_skips_non_object_manifest(tmp_path, payload):
+ (_manifest_dir(tmp_path, "bad") / "latest").write_text(payload, encoding = "utf-8")
+ (tmp_path / "blobs").mkdir(exist_ok = True)
+
+ assert _dir_has_downloaded_model(tmp_path) is False
+
+
+def test_folder_chip_probe_still_finds_a_real_model(tmp_path):
+ _write_good_model(tmp_path)
+ (_manifest_dir(tmp_path, "bad") / "latest").write_text("[]", encoding = "utf-8")
+
+ assert _dir_has_downloaded_model(tmp_path) is True