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: preview JSON Lines datasets with the stdlib, not pyarrow's JSON reader (#15713)

Shubhankar Tripathy998661dad964
diff --git a/studio/backend/hub/services/datasets/local.py b/studio/backend/hub/services/datasets/local.py
index 0c1dd5bd265..db52f97b069 100644
--- a/studio/backend/hub/services/datasets/local.py
+++ b/studio/backend/hub/services/datasets/local.py
@@ -202,6 +202,56 @@ def _build_local_dataset_items() -> list[LocalDatasetItem]:
return items
+# The datasets json loader types its first batch of this many bytes; the preview types the same window.
+_JSONL_SCHEMA_BYTES = 10 << 20
+
+
+def _jsonl_head(path: Path, preview_size: int) -> tuple[list[dict], bytes] | None:
+ """First ``preview_size`` JSON Lines objects and the bytes of the loader's first batch. ``None`` if not JSON Lines."""
+ rows, keys, window, scanned = [], {}, [], 0
+ with path.open("rb") as f:
+ for line in f:
+ if line.strip():
+ try:
+ row = json.loads(line.decode("utf-8"))
+ except ValueError:
+ row = None
+ if not isinstance(row, dict):
+ # Within the preview rows the loader decides; past them the window ends.
+ if len(rows) < preview_size:
+ return None
+ break
+ keys.update(dict.fromkeys(row))
+ if len(rows) < preview_size:
+ rows.append(row)
+ window.append(line)
+ scanned += len(line)
+ if len(rows) >= preview_size and scanned >= _JSONL_SCHEMA_BYTES:
+ break
+ # Columns are the union over the window, as the Arrow reader builds them (from_list reads row 0's keys).
+ return [{key: row.get(key) for key in keys} for row in rows], b"".join(window)
+
+
+def _jsonl_rows_dataset(rows: list[dict], window: bytes):
+ import io
+
+ import pyarrow as pa
+ import pyarrow.json as paj
+ from datasets import Dataset
+
+ try:
+ # The loader's reader types as training does; one block, no threads: #15681 segfaults only threaded.
+ options = paj.ReadOptions(use_threads = False, block_size = len(window))
+ table = paj.read_json(io.BytesIO(window), read_options = options)
+ return Dataset.from_list(table.slice(0, len(rows)).to_pylist())
+ except pa.ArrowException as error:
+ # A field that is a string in one row and an object in another (#15681): show the rows as written.
+ try:
+ return Dataset.from_list(rows)
+ except (TypeError, ValueError, OverflowError):
+ raise error from None
+
+
def _stream_file_preview_slice(path: Path, preview_size: int, **load_kwargs):
"""Stream the first ``preview_size`` rows so a large file is never fully parsed into Arrow; returns ``(Dataset, None)`` or ``None`` if empty/unsupported."""
from itertools import islice
@@ -210,6 +260,10 @@ def _stream_file_preview_slice(path: Path, preview_size: int, **load_kwargs):
name = path.name.lower()
if name.endswith((".json", ".jsonl")):
+ if not load_kwargs:
+ head = _jsonl_head(path, preview_size)
+ if head is not None:
+ return (_jsonl_rows_dataset(*head), None) if head[0] else None
loader = "json"
elif name.endswith((".csv", ".tsv")):
loader = "csv"
diff --git a/studio/backend/tests/test_jsonl_preview_head.py b/studio/backend/tests/test_jsonl_preview_head.py
new file mode 100644
index 00000000000..8b3b518d2ac
--- /dev/null
+++ b/studio/backend/tests/test_jsonl_preview_head.py
@@ -0,0 +1,160 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""JSON Lines previews skip the datasets loader, whose threaded pyarrow JSON reader segfaulted the server (#15681)."""
+
+from __future__ import annotations
+
+import json
+
+import pytest
+
+from hub.services.datasets import local
+
+
+def _write_jsonl(
+ path,
+ rows,
+ tail = "",
+):
+ path.write_text("".join(json.dumps(row) + "\n" for row in rows) + tail, encoding = "utf-8")
+
+
+def loader_calls(monkeypatch):
+ import datasets
+
+ calls = []
+ real = datasets.load_dataset
+
+ def spy(*args, **kwargs):
+ calls.append(args[0] if args else kwargs.get("path"))
+ return real(*args, **kwargs)
+
+ monkeypatch.setattr(datasets, "load_dataset", spy)
+ return calls
+
+
+def test_jsonl_preview_skips_the_threaded_loader(tmp_path, loader_calls):
+ rows = [
+ {
+ "tools": [
+ {
+ "type": "function",
+ "function": {"name": "search", "parameters": {"type": "object"}},
+ }
+ ],
+ "messages": [
+ {"role": "user", "content": "q" * 50_000},
+ {
+ "role": "assistant",
+ "content": "",
+ "tool_calls": [
+ {
+ "id": "c0",
+ "type": "function",
+ "function": {"name": "search", "arguments": "{}"},
+ }
+ ],
+ },
+ {"role": "tool", "tool_call_id": "c0", "content": "r" * 50_000},
+ ],
+ }
+ for _ in range(8)
+ ]
+ path = tmp_path / "train.jsonl"
+ _write_jsonl(path, rows)
+ dataset, total = local._stream_file_preview_slice(path, 3)
+ assert loader_calls == []
+ assert total is None and len(dataset) == 3
+ assert dataset.column_names == ["tools", "messages"]
+ assert dataset[0]["messages"][2]["content"] == "r" * 50_000
+
+
+def test_mixed_nested_types_raise_without_the_threaded_loader(tmp_path, loader_calls):
+ def row(search):
+ call = {"function": {"name": "s", "arguments": {"json_body": {"searchContent": search}}}}
+ return {"messages": [{"role": "assistant", "content": "", "tool_calls": [call]}]}
+
+ path = tmp_path / "train.jsonl"
+ _write_jsonl(path, [row("text"), row({"q": "x"})] * 50)
+ # Token preview reads 100 rows: an Arrow column cannot be both string and struct.
+ with pytest.raises((TypeError, ValueError)):
+ local._stream_file_preview_slice(path, 100)
+ assert loader_calls == []
+
+
+ "lines, expected",
+ [
+ (['{"id": 9223372036854775808}', '{"id": 1}'], [9223372036854775808.0, 1.0]),
+ (['{"id": 9223372036854775807}', '{"id": 9223372036854775808}'], [2.0**63, 2.0**63]),
+ (['{"v": 9007199254740993}', '{"v": 1.5}'], [9007199254740992.0, 1.5]),
+ ],
+)
+def test_large_numbers_preview_like_the_loader(tmp_path, loader_calls, lines, expected):
+ path = tmp_path / "train.jsonl"
+ path.write_text("".join(line + "\n" for line in lines), encoding = "utf-8")
+ dataset, _ = local._stream_file_preview_slice(path, 10)
+ assert dataset[dataset.column_names[0]] == expected and loader_calls == []
+
+
+def test_a_float_after_the_preview_rows_types_the_column_like_the_loader(tmp_path, loader_calls):
+ path = tmp_path / "train.jsonl"
+ _write_jsonl(path, [{"output": 7}] * 20 + [{"output": 1.5}])
+ dataset, _ = local._stream_file_preview_slice(path, 10)
+ assert dataset["output"] == [7.0] * 10 and isinstance(dataset["output"][0], float)
+
+
+def test_columns_are_the_union_over_rows(tmp_path, loader_calls):
+ path = tmp_path / "train.jsonl"
+ _write_jsonl(path, [{"text": "a"}, {"text": "b", "label": 1}])
+ dataset, _ = local._stream_file_preview_slice(path, 10)
+ assert dataset.column_names == ["text", "label"]
+ assert dataset["label"] == [None, 1]
+
+
+def test_a_column_first_seen_after_the_preview_rows_is_kept(tmp_path, loader_calls):
+ path = tmp_path / "train.jsonl"
+ rows = [{"question": "Q", "answer": "A"}] * 10 + [
+ {"question": "Q", "answer": "A", "system": "S"}
+ ]
+ _write_jsonl(path, rows)
+ dataset, _ = local._stream_file_preview_slice(path, 10)
+ assert dataset.column_names == ["question", "answer", "system"] and len(dataset) == 10
+
+
+def test_reading_stops_at_the_preview_size(tmp_path, loader_calls):
+ path = tmp_path / "train.jsonl"
+ _write_jsonl(path, [{"text": str(i)} for i in range(3)], tail = "{not json\n")
+ dataset, _ = local._stream_file_preview_slice(path, 3)
+ assert dataset["text"] == ["0", "1", "2"] and loader_calls == []
+ undecodable = tmp_path / "tail.jsonl"
+ _write_jsonl(undecodable, [{"text": str(i)} for i in range(3)])
+ undecodable.write_bytes(undecodable.read_bytes() + b"\xff\n")
+ assert local._stream_file_preview_slice(undecodable, 3)[0]["text"] == ["0", "1", "2"]
+
+
+def test_blank_lines_are_skipped_and_an_empty_file_has_no_preview(tmp_path, loader_calls):
+ path = tmp_path / "train.jsonl"
+ path.write_text('\n{"text": "a"}\n\n{"text": "b"}\n', encoding = "utf-8")
+ assert local._stream_file_preview_slice(path, 10)[0]["text"] == ["a", "b"]
+ empty = tmp_path / "empty.jsonl"
+ empty.write_text("\n\n", encoding = "utf-8")
+ assert local._stream_file_preview_slice(empty, 10) is None
+ assert loader_calls == []
+
+
+ "text",
+ [
+ json.dumps([{"text": "a"}, {"text": "b"}]),
+ json.dumps([{"text": "a"}, {"text": "b"}], indent = 2),
+ ],
+)
+def test_a_file_that_is_not_json_lines_keeps_the_loader(tmp_path, loader_calls, text):
+ path = tmp_path / "train.json"
+ path.write_text(text, encoding = "utf-8")
+ dataset, _ = local._stream_file_preview_slice(path, 10)
+ assert loader_calls == ["json"]
+ assert dataset["text"] == ["a", "b"]