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.

Fix datasets PyArrow registration after failed warm import (#9626)

Lee Jacksone745043b3d6d
diff --git a/studio/backend/tests/test_dataset_warmup_arrow_registry_repro.py b/studio/backend/tests/test_dataset_warmup_arrow_registry_repro.py
new file mode 100644
index 00000000000..45dbae50813
--- /dev/null
+++ b/studio/backend/tests/test_dataset_warmup_arrow_registry_repro.py
@@ -0,0 +1,189 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Regression coverage for the datasets/PyArrow warm-up failure."""
+
+from __future__ import annotations
+
+import subprocess
+import sys
+import textwrap
+from pathlib import Path
+
+
+BACKEND = Path(__file__).resolve().parents[1]
+
+
+def test_datasets_can_be_reimported_after_a_failed_warm_is_purged():
+ probe = textwrap.dedent(
+ """
+ import importlib
+ import sys
+
+ import datasets
+
+ from utils.torch_warmup import purge_partial_import
+
+ sys.modules.pop("datasets", None)
+ removed = purge_partial_import("datasets")
+ assert "datasets.features.features" in removed
+
+ reimported = importlib.import_module("datasets")
+ dataset = reimported.Dataset.from_dict({"text": ["hello"]})
+ assert dataset[0]["text"] == "hello"
+ """
+ )
+ result = subprocess.run(
+ [sys.executable, "-c", probe],
+ cwd = BACKEND,
+ text = True,
+ capture_output = True,
+ timeout = 60,
+ check = False,
+ )
+ combined = result.stdout + result.stderr
+ assert result.returncode == 0, combined
+
+
+def test_datasets_reimport_waits_for_arrow_registry_cleanup():
+ probe = textwrap.dedent(
+ """
+ import importlib
+ import sys
+ import threading
+ import time
+
+ import datasets
+ import pyarrow
+
+ from utils.torch_warmup import purge_partial_import
+
+ sys.modules.pop("datasets", None)
+ first_unregistered = threading.Event()
+ resume_cleanup = threading.Event()
+ real_unregister = pyarrow.unregister_extension_type
+
+ def paused_unregister(type_name):
+ real_unregister(type_name)
+ if type_name.endswith("Array2DExtensionType"):
+ first_unregistered.set()
+ assert resume_cleanup.wait(5), "cleanup was not resumed"
+
+ pyarrow.unregister_extension_type = paused_unregister
+ removed = []
+ purge = threading.Thread(
+ target=lambda: removed.extend(purge_partial_import("datasets")),
+ daemon=True,
+ )
+ purge.start()
+ assert first_unregistered.wait(5), "cleanup did not reach the registry"
+
+ outcome = {}
+
+ def reimport():
+ try:
+ outcome["module"] = importlib.import_module("datasets")
+ except BaseException as exc:
+ outcome["error"] = exc
+
+ retry = threading.Thread(target=reimport, daemon=True)
+ retry.start()
+ time.sleep(0.2)
+ retry_waited = retry.is_alive()
+ resume_cleanup.set()
+ purge.join(5)
+ retry.join(5)
+
+ assert not purge.is_alive(), "cleanup did not finish"
+ assert not retry.is_alive(), "reimport did not finish"
+ assert retry_waited, f"reimport raced cleanup: {outcome.get('error')!r}"
+ assert "error" not in outcome, repr(outcome["error"])
+ assert "datasets.features.features" in removed
+ dataset = outcome["module"].Dataset.from_dict({"text": ["hello"]})
+ assert dataset[0]["text"] == "hello"
+ """
+ )
+ result = subprocess.run(
+ [sys.executable, "-c", probe],
+ cwd = BACKEND,
+ text = True,
+ capture_output = True,
+ timeout = 60,
+ check = False,
+ )
+ combined = result.stdout + result.stderr
+ assert result.returncode == 0, combined
+
+
+def test_a_request_queued_on_the_failing_warm_import_still_gets_a_working_datasets():
+ """A request queued on a failing warm import must wait through cleanup."""
+ probe = textwrap.dedent(
+ """
+ import importlib
+ import importlib.abc
+ import sys
+ import threading
+ import time
+
+ # Fail late, after PyArrow registration, while holding the import lock.
+ FAIL_TARGET = "datasets.packaged_modules"
+ at_failure = threading.Event()
+ release = threading.Event()
+ armed = {"on": True}
+
+ class LateFailure(importlib.abc.MetaPathFinder):
+ def find_spec(self, name, path=None, target=None):
+ if name == FAIL_TARGET and armed["on"]:
+ armed["on"] = False
+ at_failure.set()
+ assert release.wait(30), "the warm import was never released"
+ raise RuntimeError("injected late warm failure")
+ return None
+
+ sys.meta_path.insert(0, LateFailure())
+
+ from utils import torch_warmup
+
+ warm = threading.Thread(
+ target=lambda: torch_warmup._run_stage("datasets", torch_warmup._warm_datasets),
+ daemon=True,
+ )
+ warm.start()
+ assert at_failure.wait(30), "the warm never reached the injected failure"
+
+ outcome = {}
+
+ def request():
+ try:
+ module = importlib.import_module("datasets")
+ outcome["rows"] = module.Dataset.from_dict({"text": ["hello"]})[0]
+ except BaseException as exc:
+ outcome["error"] = exc
+
+ requester = threading.Thread(target=request, daemon=True)
+ requester.start()
+ time.sleep(0.5)
+ # Confirm the request is blocked on the paused warm import.
+ assert requester.is_alive(), "the request did not queue behind the warm import"
+
+ release.set()
+ requester.join(30)
+ warm.join(30)
+
+ assert not requester.is_alive(), "the request never finished"
+ assert not warm.is_alive(), "the warm never finished"
+ assert torch_warmup._status["stages"]["datasets"]["ok"] is False
+ assert "error" not in outcome, repr(outcome["error"])
+ assert outcome["rows"]["text"] == "hello"
+ """
+ )
+ result = subprocess.run(
+ [sys.executable, "-c", probe],
+ cwd = BACKEND,
+ text = True,
+ capture_output = True,
+ timeout = 120,
+ check = False,
+ )
+ combined = result.stdout + result.stderr
+ assert result.returncode == 0, combined
diff --git a/studio/backend/utils/torch_warmup.py b/studio/backend/utils/torch_warmup.py
index 4aba5e84046..91e3d47f841 100644
--- a/studio/backend/utils/torch_warmup.py
+++ b/studio/backend/utils/torch_warmup.py
@@ -34,7 +34,8 @@ import sys
import threading
import time
from contextlib import contextmanager
-from functools import partial
+from functools import partial, wraps
+from importlib._bootstrap import _ModuleLockManager
from typing import Optional
from loggers import get_logger
@@ -61,6 +62,48 @@ def _is_extension_module(name: str) -> bool:
return origin.endswith(tuple(importlib.machinery.EXTENSION_SUFFIXES))
+_DATASETS_ARROW_EXTENSION_TYPES = tuple(
+ f"datasets.features.features.Array{dimensions}DExtensionType" for dimensions in range(2, 6)
+)
+
+
+def _clear_external_import_state(package: str) -> list[str]:
+ """Undo native registrations made by a pure-Python module before it failed."""
+ if package != "datasets":
+ return []
+ pyarrow = sys.modules.get("pyarrow")
+ unregister = getattr(pyarrow, "unregister_extension_type", None)
+ if unregister is None:
+ return []
+ cleared: list[str] = []
+ for type_name in _DATASETS_ARROW_EXTENSION_TYPES:
+ try:
+ unregister(type_name)
+ except KeyError:
+ continue
+ cleared.append(type_name)
+ if cleared:
+ logger.warning(
+ "unregistered %d PyArrow extension type(s) left by the failed %s "
+ "import so its modules can be executed again",
+ len(cleared),
+ package,
+ )
+ return cleared
+
+
+def _synchronize_with_imports(fn):
+ """Run cleanup under the same per-module lock used by CPython imports."""
+
+ @wraps(fn)
+ def synchronized(package: str):
+ with _ModuleLockManager(package):
+ return fn(package)
+
+ return synchronized
+
+
+@_synchronize_with_imports
def purge_partial_import(package: str) -> list:
"""Drop the submodules a failed package import left behind in sys.modules.
@@ -77,6 +120,8 @@ def purge_partial_import(package: str) -> list:
Declines when any submodule is a loaded C extension: evicting one re-runs its
module init, and pybind11 answers a duplicate type registration with
std::terminate. A torch missing attributes is bad; SIGABRT mid-serve is worse.
+ Known native registries populated by pure-Python modules are reset only after
+ every stale module has been removed and no importer has republished the parent.
"""
if package in sys.modules:
return []
@@ -116,6 +161,9 @@ def purge_partial_import(package: str) -> list:
break
if sys.modules.pop(name, None) is not None:
removed.append(name)
+ fully_purged = package not in sys.modules and not any(name in sys.modules for name in stale)
+ if fully_purged:
+ _clear_external_import_state(package)
if removed:
logger.warning(
"purged %d half-imported %s submodule(s) so the next import re-runs clean: %s",
@@ -133,23 +181,40 @@ _STAGE_PACKAGE = {
"datasets": "datasets",
}
+# Hold the import lock across a bare import and its failure cleanup. Locking only
+# the purge leaves a window where a queued importer can reuse stale submodules.
+# Hardware and transformers acquire additional locks, so exclude them to avoid
+# lock-order inversions.
+_BARE_IMPORT_STAGES = frozenset({"datasets"})
+
+
+@contextmanager
+def _held_import_lock(name: str, package: Optional[str]):
+ """Hold ``package``'s import lock for a bare-import stage; a no-op for the rest."""
+ if package is None or name not in _BARE_IMPORT_STAGES:
+ yield
+ return
+ with _ModuleLockManager(package):
+ yield
+
def _run_stage(name: str, fn) -> None:
+ package = _STAGE_PACKAGE.get(name)
started = time.perf_counter()
- try:
- fn()
- except BaseException as exc: # noqa: BLE001 - a warm failure must be visible, not fatal
- _status["stages"][name] = {"ok": False, "error": repr(exc)}
- # warning, not debug: the stage stays cold and the first request pays for it.
- logger.warning("torch warm stage %r failed: %r", name, exc)
- package = _STAGE_PACKAGE.get(name)
- if package:
- purge_partial_import(package)
- else:
- _status["stages"][name] = {
- "ok": True,
- "seconds": round(time.perf_counter() - started, 3),
- }
+ with _held_import_lock(name, package):
+ try:
+ fn()
+ except BaseException as exc: # noqa: BLE001 - a warm failure must be visible, not fatal
+ _status["stages"][name] = {"ok": False, "error": repr(exc)}
+ # warning, not debug: the stage stays cold and the first request pays for it.
+ logger.warning("torch warm stage %r failed: %r", name, exc)
+ if package:
+ purge_partial_import(package)
+ else:
+ _status["stages"][name] = {
+ "ok": True,
+ "seconds": round(time.perf_counter() - started, 3),
+ }
def _warm_hardware(epoch: Optional[int] = None) -> None: