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: handle a deleted dataset file instead of failing with a 500 (#7800)
Nilayf26727faec6d
diff --git a/studio/backend/routes/datasets.py b/studio/backend/routes/datasets.pyindex 331eb5e1e0c..195165e8a1f 100644--- a/studio/backend/routes/datasets.py+++ b/studio/backend/routes/datasets.py@@ -505,6 +505,15 @@ async def get_dataset_download_progress()+_MISSING_DATASET_DETAIL = "This dataset is no longer on disk. Add it again or pick another dataset."+++def _is_local_dataset_ref(dataset_name: str) -> bool:+ """Absolute means local. Normalised like resolve_dataset_path, so a '~' or+ space-padded spelling is not mistaken for a Hub repo id."""+ return Path(str(dataset_name or "").strip()).expanduser().is_absolute()++@router.post("/check-format", response_model = CheckFormatResponse)def check_format(request: CheckFormatRequest, current_subject: str = Depends(get_current_subject)):"""Check if a dataset requires manual column mapping.@@ -529,7 +538,13 @@ def check_format(request: CheckFormatRequest, current_subject: str = Depends(getdataset_path = resolve_dataset_path(request.dataset_name)total_rows = None- if dataset_path.exists():+ # Uploads and recipes always arrive as absolute paths, so a missing one is a+ # deleted file, not a Hub repo id. One stat() for both branches.+ dataset_exists = dataset_path.exists()+ if not dataset_exists and _is_local_dataset_ref(request.dataset_name):+ raise HTTPException(status_code = 404, detail = _MISSING_DATASET_DETAIL)++ if dataset_exists:# ── Local file ──────────────────────────────────────────train_split = request.train_split or "train"preview_slice, total_rows = _load_local_preview_slice(diff --git a/studio/backend/tests/test_dataset_check_format_missing.py b/studio/backend/tests/test_dataset_check_format_missing.pynew file mode 100644index 00000000000..86257de8d2c--- /dev/null+++ b/studio/backend/tests/test_dataset_check_format_missing.py@@ -0,0 +1,119 @@+# 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 deleted upload must report itself, without swallowing other failures."""++import sys+from pathlib import Path++import pytest+from fastapi import HTTPException++_BACKEND_ROOT = Path(__file__).resolve().parents[1]+if str(_BACKEND_ROOT) not in sys.path:+ sys.path.insert(0, str(_BACKEND_ROOT))++from routes import datasets as datasets_route # noqa: E402++[email protected](autouse = True)+def isolated_studio_home(tmp_path, monkeypatch):+ """Keep fixtures out of the developer's real Studio uploads directory."""+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))+ return tmp_path+++def no_hub(monkeypatch):+ """Fail every Hub lookup in-process, recording what was asked for.++ HF_HUB_OFFLINE is read into huggingface_hub.constants at import time, so+ setting it from a test is a no-op and the lookups still dial out.+ """+ import huggingface_hub++ attempts: list[str] = []++ class _NoHubApi:+ def __init__(self, *args, **kwargs):+ pass++ def list_repo_files(self, repo_id, **kwargs):+ attempts.append(repo_id)+ raise ConnectionError("Hub is unavailable in tests")++ def _no_load_dataset(*args, **kwargs):+ path = kwargs.get("path", args[0] if args else None)+ attempts.append(str(path))+ raise ConnectionError("Hub is unavailable in tests")++ monkeypatch.setattr(huggingface_hub, "HfApi", _NoHubApi)+ monkeypatch.setattr("datasets.load_dataset", _no_load_dataset)+ return attempts+++def _check(dataset_name: str) -> HTTPException:+ request = datasets_route.CheckFormatRequest(dataset_name = dataset_name)+ with pytest.raises(HTTPException) as exc:+ datasets_route.check_format(request, current_subject = "test")+ return exc.value+++def test_missing_upload_reports_404(no_hub):+ from utils.paths import dataset_uploads_root++ missing = dataset_uploads_root() / "deleted-upload-test-fixture.jsonl"+ assert not missing.exists()+ error = _check(str(missing))+ assert error.status_code == 404+ assert "no longer on disk" in error.detail+ assert no_hub == [], "a local path must never be sent to the Hub as a repo id"+++ "spelling",+ [+ pytest.param("{path}", id = "as-sent-by-the-ui"),+ pytest.param(" {path}", id = "leading-whitespace"),+ pytest.param("{path} ", id = "trailing-whitespace"),+ ],+)+def test_every_spelling_of_a_missing_upload_reports_404(spelling, no_hub):+ """resolve_dataset_path strips before testing absoluteness, so a guard on the+ raw string disagrees here and ships the local path to the Hub as a repo id."""+ from utils.paths import dataset_uploads_root++ missing = dataset_uploads_root() / "deleted-upload-test-fixture.jsonl"+ error = _check(spelling.format(path = missing))+ assert error.status_code == 404+ assert no_hub == []+++def test_a_tilde_spelling_is_still_a_local_file(tmp_path, monkeypatch, no_hub):+ monkeypatch.setenv("HOME", str(tmp_path))+ monkeypatch.setenv("USERPROFILE", str(tmp_path))+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / ".unsloth" / "studio"))++ error = _check("~/.unsloth/studio/assets/datasets/uploads/deleted.jsonl")+ assert error.status_code == 404+ assert no_hub == []+++def test_corrupt_local_file_keeps_its_own_error(no_hub):+ from utils.paths import dataset_uploads_root++ corrupt = dataset_uploads_root() / "corrupt-test-fixture.jsonl"+ corrupt.parent.mkdir(parents = True, exist_ok = True)+ corrupt.write_text("{not valid json at all\n")++ error = _check(str(corrupt))+ assert error.status_code == 500, "an unreadable file is not a missing one"+ assert "no longer on disk" not in str(error.detail)+++def test_hub_repo_id_never_reports_a_deleted_file(no_hub):+ """A relative reference stays a Hub lookup, however local it looks."""+ error = _check("uploads/private-or-unreachable")++ assert error.status_code != 404+ assert no_hub, "the Hub branch is where a relative reference belongs"diff --git a/studio/frontend/src/features/studio/sections/dataset-preview-dialog.tsx b/studio/frontend/src/features/studio/sections/dataset-preview-dialog.tsxindex 71939aaee22..939ad8dbe66 100644--- a/studio/frontend/src/features/studio/sections/dataset-preview-dialog.tsx+++ b/studio/frontend/src/features/studio/sections/dataset-preview-dialog.tsx@@ -14,7 +14,11 @@ import { DataTable } from "@/components/ui/data-table";import { Badge } from "@/components/ui/badge";import { Spinner } from "@/components/ui/spinner";import { useTrainingActions, useTrainingConfigStore } from "@/features/training";-import { checkDatasetFormat } from "@/features/training/api/datasets-api";+import {+ checkDatasetFormat,+ DatasetFormatError,+} from "@/features/training/api/datasets-api";+import { clearDeletedDataset } from "@/features/training/stores/training-config-store";import { isRawTextDatasetFormat } from "@/features/training/lib/training-methods";import type { CheckFormatResponse } from "@/features/training/types/datasets";import type { DatasetSource } from "@/types/training";@@ -217,6 +221,10 @@ export function DatasetPreviewDialog({}}).catch((err) => {+ // Preview is a third way to learn the file is gone, so clear here too.+ if (err instanceof DatasetFormatError && err.status === 404) {+ clearDeletedDataset(datasetName);+ }if (!cancelled) setError(err.message || "Failed to load preview");}).finally(() => {diff --git a/studio/frontend/src/features/training/api/datasets-api.ts b/studio/frontend/src/features/training/api/datasets-api.tsindex 0b4f90c56c1..8777cedd4cb 100644--- a/studio/frontend/src/features/training/api/datasets-api.ts+++ b/studio/frontend/src/features/training/api/datasets-api.ts@@ -9,6 +9,16 @@ import type {import { authFetch } from "@/features/auth";import { readFastApiError } from "@/lib/format-fastapi-error";+export class DatasetFormatError extends Error {+ status: number;++ constructor(message: string, status: number) {+ super(message);+ this.name = "DatasetFormatError";+ this.status = status;+ }+}+type CheckDatasetFormatArgs = {datasetName: string;hfToken: string | null;@@ -37,7 +47,7 @@ export async function checkDatasetFormat({});if (!res.ok) {- throw new Error(await readFastApiError(res));+ throw new DatasetFormatError(await readFastApiError(res), res.status);}return res.json();diff --git a/studio/frontend/src/features/training/hooks/use-training-actions.ts b/studio/frontend/src/features/training/hooks/use-training-actions.tsindex 9bb8206f284..51509e6c6cc 100644--- a/studio/frontend/src/features/training/hooks/use-training-actions.ts+++ b/studio/frontend/src/features/training/hooks/use-training-actions.ts@@ -6,7 +6,7 @@ import { prepareHfTokenForUse } from "@/features/hf-auth";import { confirmRemoteCodeIfNeeded } from "@/features/security";import { useCallback } from "react";import { toast } from "@/lib/toast";-import { checkDatasetFormat } from "../api/datasets-api";+import { checkDatasetFormat, DatasetFormatError } from "../api/datasets-api";import { emitTrainingRunsChanged } from "../events";import { getTrainingRun } from "../api/history-api";import { buildTrainingStartPayload } from "../api/mappers";@@ -15,7 +15,7 @@ import { isRawTextDatasetFormat } from "../lib/training-methods";import { syncTrainingRuntimeFromBackend } from "../lib/sync-runtime";import { validateTrainingConfig } from "../lib/validation";import { useDatasetPreviewDialogStore } from "../stores/dataset-preview-dialog-store";-import { useTrainingConfigStore } from "../stores/training-config-store";+import { clearDeletedDataset, useTrainingConfigStore } from "../stores/training-config-store";import { useTrainingRuntimeStore } from "../stores/training-runtime-store";import type { TrainingStartRequest } from "../types/api";import type { TrainingConfigState } from "../types/config";@@ -182,6 +182,10 @@ export function useTrainingActions() {await syncTrainingRuntimeFromBackend();return true;} catch (error) {+ // A dataset deleted since the last check must not stay startable.+ if (error instanceof DatasetFormatError && error.status === 404) {+ clearDeletedDataset(getDatasetName(config) ?? "");+ }const rawMessage =error instanceof Error ? error.message : "Failed to start training";const safeMessage = normalizeTrainingStartError(rawMessage);diff --git a/studio/frontend/src/features/training/stores/training-config-store.ts b/studio/frontend/src/features/training/stores/training-config-store.tsindex d204e24f47b..ae0455674ec 100644--- a/studio/frontend/src/features/training/stores/training-config-store.ts+++ b/studio/frontend/src/features/training/stores/training-config-store.ts@@ -10,7 +10,7 @@ import type { ModelType, StepNumber, TrainingMethod } from "@/types/training";import { toast } from "sonner";import { create } from "zustand";import { persist } from "zustand/middleware";-import { checkDatasetFormat } from "../api/datasets-api";+import { checkDatasetFormat, DatasetFormatError } from "../api/datasets-api";import { checkVisionModel, getModelConfig } from "../api/models-api";import { mapBackendModelConfigToTrainingPatch } from "../lib/model-defaults";import { isRawTextDatasetFormat } from "../lib/training-methods";@@ -516,8 +516,13 @@ export const useTrainingConfigStore = create<TrainingConfigStore>()(}set(updates);})- .catch(() => {+ .catch((error: unknown) => {if (controller.signal.aborted) return;+ // Otherwise a deleted dataset stays selected and re-fails every visit.+ if (error instanceof DatasetFormatError && error.status === 404) {+ clearDeletedDataset(datasetName);+ toast.error(error.message);+ }set({ isDatasetImage: null, isCheckingDataset: false });});};@@ -1038,3 +1043,21 @@ const unsubscribeHfTokenMirror = mirrorHfTokenInto(useTrainingConfigStore);if (import.meta.hot) {import.meta.hot.dispose(unsubscribeHfTokenMirror);}++/** POSIX, Windows drive, UNC or extended-length path. A Hub repo id is never one. */+function isLocalDatasetPath(datasetName: string): boolean {+ return /^([/\\]|[A-Za-z]:[\\/])/.test(datasetName.trim());+}++/** Drop a selection whose file the backend reports as gone (404). */+export function clearDeletedDataset(datasetName: string): void {+ // Only a local file can be deleted, so an unrelated 404 cannot wipe a good pick.+ if (!isLocalDatasetPath(datasetName)) return;+ const { dataset, uploadedFile, setDataset, selectLocalDataset } =+ useTrainingConfigStore.getState();+ if (uploadedFile === datasetName) {+ selectLocalDataset(null);+ } else if (dataset === datasetName) {+ setDataset(null);+ }+}