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
Studio: reuse recipe shard row counts while no shard changed (#15869)
Daniel Han97a2f18e53c6
diff --git a/studio/backend/core/data_recipe/jobs/manager.py b/studio/backend/core/data_recipe/jobs/manager.pyindex 223131350f7..89f8ae43898 100644--- a/studio/backend/core/data_recipe/jobs/manager.py+++ b/studio/backend/core/data_recipe/jobs/manager.py@@ -17,6 +17,7 @@ from core.training.account_jobs import (from utils.account_context import account_threadimport asyncioimport json+import osimport queueimport threadingimport time@@ -125,6 +126,78 @@ class Subscription:return (f"id: {event_id}\n" f"event: {event_type}\n" f"data: {body}\n\n").encode("utf-8")+_SHARD_ROWS_CACHE: dict[str, tuple[tuple, tuple[tuple[str, int], ...]]] = {}+_SHARD_ROWS_CACHE_MAX = 8+_SHARD_ROWS_CACHE_LOCK = threading.Lock()+# A stamp this close to the read may hide a same-tick write, so it is never trusted.+_SHARD_ROWS_SETTLE_NS = 2_000_000_000+++def _stat_key(path: str, settled_before_ns: int) -> tuple | None:+ st = os.stat(path)+ if st.st_mtime_ns >= settled_before_ns or st.st_ctime_ns >= settled_before_ns:+ return None+ return (st.st_dev, st.st_ino, st.st_size, st.st_mtime_ns, st.st_ctime_ns)+++def _shard_rows_signature(+ parquet_dir: Path,+ file_names,+ read_started_ns: int | None = None,+) -> tuple | None:+ # Stamps must predate the footer read by the settle window, so a mid-read write never+ # pairs with old counts.+ if read_started_ns is None:+ read_started_ns = time.time_ns()+ settled_before_ns = read_started_ns - _SHARD_ROWS_SETTLE_NS+ # Cheapest first: a shard landing mid run moves the dir stamps, so most misses stop at one stat.+ try:+ dir_key = _stat_key(str(parquet_dir), settled_before_ns)+ if dir_key is None:+ return None+ # Names too: FAT leaves a dir mtime alone on add; DuckDB globs match dot-prefixed names.+ listed = sorted(+ entry for entry in os.listdir(parquet_dir) if entry.lower().endswith(".parquet")+ )+ if listed != sorted(os.path.basename(name) for name in file_names):+ return None+ file_keys = []+ for name in file_names:+ key = _stat_key(name, settled_before_ns)+ if key is None:+ return None+ file_keys.append(key)+ except (OSError, ValueError):+ return None+ return (dir_key, tuple(file_keys))+++def _cached_shard_rows(parquet_dir: Path, key: str) -> list[tuple[str, int]] | None:+ with _SHARD_ROWS_CACHE_LOCK:+ entry = _SHARD_ROWS_CACHE.get(key)+ if entry is None:+ return None+ signature, shards = entry+ if _shard_rows_signature(parquet_dir, [name for name, _ in shards]) != signature:+ with _SHARD_ROWS_CACHE_LOCK:+ if _SHARD_ROWS_CACHE.get(key) is entry:+ del _SHARD_ROWS_CACHE[key]+ return None+ return list(shards)+++def _remember_shard_rows(parquet_dir: Path, key: str, shards, read_started_ns: int) -> None:+ shards = [(str(name), int(num_rows)) for name, num_rows in shards]+ signature = _shard_rows_signature(parquet_dir, [name for name, _ in shards], read_started_ns)+ with _SHARD_ROWS_CACHE_LOCK:+ _SHARD_ROWS_CACHE.pop(key, None)+ if signature is None:+ return+ while len(_SHARD_ROWS_CACHE) >= _SHARD_ROWS_CACHE_MAX:+ del _SHARD_ROWS_CACHE[next(iter(_SHARD_ROWS_CACHE))]+ _SHARD_ROWS_CACHE[key] = (signature, tuple(shards))++class JobManager:def __init__(self) -> None:"""Single-job runner (in-mem). Simple on purpose, not a whole platform."""@@ -400,10 +473,14 @@ class JobManager:conn = duckdb.connect(":memory:")try:# Scan only the shards the page covers; the live preview polls page 1.- shards = conn.execute(- "SELECT file_name, num_rows FROM parquet_file_metadata(?) ORDER BY file_name",- [parquet_glob],- ).fetchall()+ shards = _cached_shard_rows(parquet_dir, parquet_glob)+ if shards is None:+ read_started_ns = time.time_ns()+ shards = conn.execute(+ "SELECT file_name, num_rows FROM parquet_file_metadata(?) ORDER BY file_name",+ [parquet_glob],+ ).fetchall()+ _remember_shard_rows(parquet_dir, parquet_glob, shards, read_started_ns)total = sum(int(num_rows) for _, num_rows in shards)frames = []skip, remaining = int(offset), int(limit)diff --git a/studio/backend/tests/test_data_recipe_shard_rows_reuse.py b/studio/backend/tests/test_data_recipe_shard_rows_reuse.pynew file mode 100644index 00000000000..46d7b2689bf--- /dev/null+++ b/studio/backend/tests/test_data_recipe_shard_rows_reuse.py@@ -0,0 +1,188 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Recipe pages reuse shard row counts only while no shard changed, and read the same rows."""++from __future__ import annotations++import os+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 core.data_recipe.jobs import manager as manager_module # noqa: E402+from core.data_recipe.jobs.manager import JobManager # noqa: E402++pd = pytest.importorskip("pandas")+pytest.importorskip("pyarrow")+duckdb = pytest.importorskip("duckdb")+++def metadata_queries(monkeypatch):+ calls = []+ real_connect = duckdb.connect++ class _Conn:+ def __init__(self, conn):+ self._conn = conn++ def execute(self, sql, *args, **kwargs):+ if "parquet_file_metadata" in sql:+ calls.append(sql)+ return self._conn.execute(sql, *args, **kwargs)++ def close(self):+ return self._conn.close()++ monkeypatch.setattr(duckdb, "connect", lambda *a, **k: _Conn(real_connect(*a, **k)))+ cache = getattr(manager_module, "_SHARD_ROWS_CACHE", None)+ if cache is not None:+ monkeypatch.setattr(manager_module, "_SHARD_ROWS_CACHE", {})+ return calls+++def _settle(monkeypatch):+ # Test files are seconds old; treat every stat as settled.+ monkeypatch.setattr(manager_module, "_SHARD_ROWS_SETTLE_NS", 0, raising = False)+++def _write(parquet_dir: Path, index: int, values) -> Path:+ path = parquet_dir / f"batch_file_{index:05d}.parquet"+ pd.DataFrame({"a": list(values), "text": [f"row {v}" for v in values]}).to_parquet(+ path, index = False+ )+ return path+++def _page(parquet_dir: Path, offset: int, limit: int):+ return JobManager._load_dataset_page_with_duckdb(+ parquet_dir = parquet_dir, limit = limit, offset = offset+ )+++def _fresh_page(parquet_dir: Path, offset: int, limit: int):+ saved = dict(getattr(manager_module, "_SHARD_ROWS_CACHE", {}))+ getattr(manager_module, "_SHARD_ROWS_CACHE", {}).clear()+ try:+ return _page(parquet_dir, offset, limit)+ finally:+ getattr(manager_module, "_SHARD_ROWS_CACHE", {}).clear()+ getattr(manager_module, "_SHARD_ROWS_CACHE", {}).update(saved)+++def test_repeated_page_reads_shard_footers_once(tmp_path, metadata_queries, monkeypatch):+ _settle(monkeypatch)+ for i in range(4):+ _write(tmp_path, i, range(i * 5, i * 5 + 5))+ first = _page(tmp_path, 0, 7)+ for _ in range(3):+ assert _page(tmp_path, 0, 7) == first+ assert _page(tmp_path, 3, 9) == _fresh_page(tmp_path, 3, 9)+ assert len(metadata_queries) == 2 # one shared, one for the uncached comparison+++def test_fresh_shards_are_not_reused(tmp_path, metadata_queries):+ _write(tmp_path, 0, range(3))+ _page(tmp_path, 0, 5)+ _page(tmp_path, 0, 5)+ assert len(metadata_queries) == 2++[email protected]("offset,limit", [(0, 5), (4, 6), (9, 4), (12, 20), (30, 5)])+def test_pages_follow_every_shard_change(tmp_path, metadata_queries, monkeypatch, offset, limit):+ _settle(monkeypatch)+ for i in range(3):+ _write(tmp_path, i, range(i * 5, i * 5 + 5))+ assert _page(tmp_path, offset, limit) == _fresh_page(tmp_path, offset, limit)++ _write(tmp_path, 3, range(15, 22))+ assert _page(tmp_path, offset, limit) == _fresh_page(tmp_path, offset, limit)+ assert _page(tmp_path, offset, limit)["total"] == 22++ path = tmp_path / "batch_file_00001.parquet"+ size = path.stat().st_size+ _write(tmp_path, 1, [9, 8, 7, 6, 5])+ assert path.stat().st_size == size+ assert _page(tmp_path, offset, limit) == _fresh_page(tmp_path, offset, limit)++ stat = path.stat()+ _write(tmp_path, 1, range(200, 209))+ os.utime(path, ns = (stat.st_atime_ns, stat.st_mtime_ns))+ assert _page(tmp_path, offset, limit) == _fresh_page(tmp_path, offset, limit)+ assert _page(tmp_path, offset, limit)["total"] == 26++ (tmp_path / "batch_file_00000.parquet").unlink()+ assert _page(tmp_path, offset, limit) == _fresh_page(tmp_path, offset, limit)+ pd.DataFrame({"a": [-1], "text": ["dot"]}).to_parquet(tmp_path / "._x.parquet", index = False)+ assert _page(tmp_path, offset, limit) == _fresh_page(tmp_path, offset, limit)+++def test_emptied_dir_is_not_served_from_cache(tmp_path, metadata_queries, monkeypatch):+ _settle(monkeypatch)+ path = _write(tmp_path, 0, range(3))+ assert _page(tmp_path, 0, 5)["total"] == 3+ path.unlink()+ assert _page(tmp_path, 0, 5) is None+ assert _fresh_page(tmp_path, 0, 5) is None+++def test_added_shard_is_seen_when_the_dir_stamps_do_not_move(+ tmp_path, metadata_queries, monkeypatch+):+ # FAT leaves a directory's mtime alone when an entry is added.+ _settle(monkeypatch)+ real_stat_key = manager_module._stat_key++ def frozen_dir_stat_key(path, settled_before_ns):+ if os.path.isdir(path):+ return ("dir",)+ return real_stat_key(path, settled_before_ns)++ monkeypatch.setattr(manager_module, "_stat_key", frozen_dir_stat_key)+ _write(tmp_path, 0, range(5))+ assert _page(tmp_path, 0, 20)["total"] == 5+ _write(tmp_path, 1, range(5, 12))+ assert _page(tmp_path, 0, 20) == _fresh_page(tmp_path, 0, 20)+ assert _page(tmp_path, 0, 20)["total"] == 12+++def test_shard_rewritten_during_the_footer_read_is_not_reused(tmp_path, monkeypatch):+ _settle(monkeypatch)+ monkeypatch.setattr(manager_module, "_SHARD_ROWS_CACHE", {})+ _write(tmp_path, 0, range(5))+ real_connect = duckdb.connect++ class _Conn:+ def __init__(self, conn):+ self._conn = conn++ def execute(self, sql, *args, **kwargs):+ result = self._conn.execute(sql, *args, **kwargs)+ if "parquet_file_metadata" in sql and not rewrites:+ rows = result.fetchall()+ # The writer replaces the shard after its footer was read, before the stat.+ rewrites.append(_write(tmp_path, 0, range(9)))+ return _Rows(rows)+ return result++ def close(self):+ return self._conn.close()++ class _Rows:+ def __init__(self, rows):+ self._rows = rows++ def fetchall(self):+ return self._rows++ rewrites = []+ monkeypatch.setattr(duckdb, "connect", lambda *a, **k: _Conn(real_connect(*a, **k)))+ assert _page(tmp_path, 0, 20)["total"] == 5+ assert rewrites+ assert _page(tmp_path, 0, 20)["total"] == 9