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.

Studio: load local JSON datasets whose later rows add keys (#15555)

Daniel Han8222149ee32c
diff --git a/studio/backend/tests/test_dataset_json_schema_drift.py b/studio/backend/tests/test_dataset_json_schema_drift.py
new file mode 100644
index 00000000000..0d0f5f9d760
--- /dev/null
+++ b/studio/backend/tests/test_dataset_json_schema_drift.py
@@ -0,0 +1,112 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import json
+import sys
+from pathlib import Path
+
+import pytest
+
+_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)
+if _BACKEND_DIR not in sys.path:
+ sys.path.insert(0, _BACKEND_DIR)
+
+from datasets.exceptions import DatasetGenerationError
+
+from utils.datasets.cache_safe import load_dataset_cache_safe
+from utils.datasets.json_rows import json_rows_features
+
+# A tiny block makes datasets type the file from its first rows, as it does a large upload.
+_SMALL_BLOCKS = {"chunksize": 256}
+
+
+def _chat(index, **assistant_keys):
+ return {
+ "messages": [
+ {"role": "user", "content": f"question {index}"},
+ {"role": "assistant", "content": f"answer {index}", **assistant_keys},
+ ]
+ }
+
+
+def _write_jsonl(path, rows):
+ path.write_text("".join(json.dumps(row) + "\n" for row in rows), encoding = "utf-8")
+ return str(path)
+
+
+def _load(files, tmp_path, **kwargs):
+ return load_dataset_cache_safe(
+ "json",
+ data_files = files,
+ split = "train",
+ cache_dir = str(tmp_path / "cache"),
+ **kwargs,
+ )
+
+
+def test_optional_message_key_after_first_block_loads(tmp_path):
+ rows = [_chat(i) for i in range(40)] + [_chat(40, weight = 0)]
+ path = _write_jsonl(tmp_path / "chat.jsonl", rows)
+ with pytest.raises(DatasetGenerationError):
+ from datasets import load_dataset
+ load_dataset(
+ "json", data_files = path, split = "train", cache_dir = str(tmp_path / "raw"), **_SMALL_BLOCKS
+ )
+
+ dataset = _load(path, tmp_path, **_SMALL_BLOCKS)
+
+ assert len(dataset) == 41
+ assert dataset[0]["messages"][1] == {"role": "assistant", "content": "answer 0", "weight": None}
+ assert dataset[40]["messages"][1]["weight"] == 0
+
+
+def test_tool_calls_only_in_a_later_file_load(tmp_path):
+ tool_call = {"type": "function", "function": {"name": "lookup", "arguments": "{}"}}
+ first = _write_jsonl(tmp_path / "a.jsonl", [_chat(0), _chat(1)])
+ second = _write_jsonl(
+ tmp_path / "b.jsonl", [{**_chat(2, tool_calls = [tool_call]), "source": "x"}]
+ )
+
+ dataset = _load([first, second], tmp_path)
+
+ assert len(dataset) == 3
+ assert dataset[0]["messages"][1]["tool_calls"] is None
+ assert dataset[0]["source"] is None
+ assert dataset[2]["messages"][1]["tool_calls"] == [tool_call]
+ assert dataset[2]["source"] == "x"
+
+
+def test_json_array_file_is_unified(tmp_path):
+ path = tmp_path / "chat.json"
+ path.write_text(json.dumps([{"a": {"x": 1}}, {"a": {"x": 2, "y": "z"}}]), encoding = "utf-8")
+
+ features = json_rows_features([str(path)])
+
+ assert set(features["a"]) == {"x", "y"}
+
+
+def test_conflicting_types_still_raise(tmp_path):
+ rows = [{"score": i} for i in range(40)] + [{"score": "high"}]
+ path = _write_jsonl(tmp_path / "bad.jsonl", rows)
+
+ assert json_rows_features([path]) is None
+ with pytest.raises(DatasetGenerationError):
+ _load(path, tmp_path, **_SMALL_BLOCKS)
+
+
+def test_explicit_features_are_not_overridden(tmp_path, monkeypatch):
+ from datasets import Features, Value
+
+ import utils.datasets.json_rows as json_rows
+
+ monkeypatch.setattr(json_rows, "json_rows_features", lambda files: pytest.fail("retried"))
+ rows = [_chat(i) for i in range(40)] + [_chat(40, weight = 0)]
+ path = _write_jsonl(tmp_path / "chat.jsonl", rows)
+
+ with pytest.raises(Exception):
+ _load(
+ path,
+ tmp_path,
+ features = Features({"messages": [{"role": Value("string")}]}),
+ **_SMALL_BLOCKS,
+ )
diff --git a/studio/backend/utils/datasets/cache_safe.py b/studio/backend/utils/datasets/cache_safe.py
index 13e13ff35a6..c8f6b4cee37 100644
--- a/studio/backend/utils/datasets/cache_safe.py
+++ b/studio/backend/utils/datasets/cache_safe.py
@@ -2,7 +2,8 @@
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
"""Retries load_dataset in an Unsloth-owned cache on Errno 13 from a shared HF cache; on Windows,
-only WinError 1314 retries in regular-file cache mode for this worker"""
+only WinError 1314 retries in regular-file cache mode for this worker. A local JSON load whose later
+rows add keys is retried with a schema covering every row."""
import logging
import os
@@ -68,7 +69,7 @@ def studio_datasets_cache() -> str:
def load_dataset_cache_safe(*args, **kwargs):
- """Load a dataset with narrow retries for known cache permission failures."""
+ """Load a dataset with narrow retries for known cache permission and JSON schema failures."""
from datasets import load_dataset
# datasets is in sys.modules exactly now.
@@ -76,6 +77,42 @@ def load_dataset_cache_safe(*args, **kwargs):
quiet_third_party_progress_bars()
+ try:
+ return _load_with_cache_retries(load_dataset, args, kwargs)
+ except Exception as error:
+ features = _json_retry_features(error, args, kwargs)
+ if features is None:
+ raise
+ logger.warning(
+ "Rows of %s do not share one structure (%s); reloading with a schema covering every row",
+ kwargs["data_files"],
+ error.__cause__ or error,
+ )
+ return _load_with_cache_retries(load_dataset, args, {**kwargs, "features": features})
+
+
+def _json_retry_features(error, args, kwargs):
+ """Features for a local JSON load that failed on rows typed unlike the first block, else None."""
+ loader = args[0] if args else kwargs.get("path")
+ files = kwargs.get("data_files")
+ if loader != "json" or kwargs.get("features") is not None or kwargs.get("streaming"):
+ return None
+ if isinstance(files, (str, os.PathLike)):
+ files = [files]
+ if not isinstance(files, (list, tuple)) or not files:
+ return None
+ if not all(isinstance(path, (str, os.PathLike)) and os.path.isfile(path) for path in files):
+ return None
+ from datasets.exceptions import DatasetGenerationError
+
+ if not isinstance(error, DatasetGenerationError):
+ return None
+ from utils.datasets.json_rows import json_rows_features
+
+ return json_rows_features(files)
+
+
+def _load_with_cache_retries(load_dataset, args, kwargs):
try:
return load_dataset(*args, **kwargs)
except OSError as error:
diff --git a/studio/backend/utils/datasets/json_rows.py b/studio/backend/utils/datasets/json_rows.py
new file mode 100644
index 00000000000..69fc86403a5
--- /dev/null
+++ b/studio/backend/utils/datasets/json_rows.py
@@ -0,0 +1,55 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""datasets types a JSON file from its first block, so a later row adding a key fails the whole load."""
+
+import json
+
+_CHUNK_ROWS = 10_000
+
+
+def _row_chunks(path):
+ with open(path, encoding = "utf-8") as file:
+ head = file.read(1)
+ while head.isspace():
+ head = file.read(1)
+ file.seek(0)
+ if head == "[":
+ rows = json.load(file)
+ if not isinstance(rows, list):
+ raise ValueError("not a JSON array")
+ for start in range(0, len(rows), _CHUNK_ROWS):
+ yield rows[start : start + _CHUNK_ROWS]
+ return
+ rows = []
+ for line in file:
+ if line.strip():
+ rows.append(json.loads(line))
+ if len(rows) == _CHUNK_ROWS:
+ yield rows
+ rows = []
+ if rows:
+ yield rows
+
+
+def json_rows_features(files):
+ """One schema every row of ``files`` fits (missing keys become nulls), or None if none does."""
+ import pyarrow as pa
+ from datasets import Features
+
+ schema = None
+ try:
+ for path in files:
+ for rows in _row_chunks(path):
+ if not all(isinstance(row, dict) for row in rows):
+ return None
+ # pa.array merges the keys of every object, at any depth.
+ chunk = pa.Table.from_struct_array(pa.array(rows)).schema
+ schema = (
+ chunk
+ if schema is None
+ else pa.unify_schemas([schema, chunk], promote_options = "permissive")
+ )
+ except (OSError, ValueError, TypeError, pa.ArrowException):
+ return None
+ return None if schema is None else Features.from_arrow_schema(schema)