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: Data Recipe column names with a slash run again; the validator file name is made safe instead (#14644)
Daniel Han4a7058e44d8b
diff --git a/studio/backend/core/data_recipe/service.py b/studio/backend/core/data_recipe/service.pyindex 83bccba89c1..9abaefe0aa2 100644--- a/studio/backend/core/data_recipe/service.py+++ b/studio/backend/core/data_recipe/service.py@@ -6,11 +6,13 @@ from __future__ import annotationsfrom core.training.account_jobs import account_path, managed_account, validate_recipe_accessimport base64import functools+import hashlibimport ioimport jsonimport loggingimport mathimport os+import refrom pathlib import Pathfrom typing import Any@@ -746,20 +748,52 @@ def _strip_frontend_model_config_metadata(recipe: dict[str, Any]) -> dict[str, Adef validate_recipe_names(recipe: dict[str, Any]) -> None:- """Refuse a column, processor or validator target name holding a path separator: the code- validator writes `<tmp>/<record id>_<column>.py`, and Windows resolves `..` after it lexically."""- for field in ("columns", "processors"):- items = recipe.get(field)- for item in items if isinstance(items, list) else []:- if not isinstance(item, dict):- continue- # A validator's targets can be seed columns, named by the seed file rather than the recipe.- targets = item.get("target_columns")- for name in [item.get("name"), *(targets if isinstance(targets, list) else ())]:- if isinstance(name, str) and ("/" in name or "\\" in name or name in (".", "..")):- raise ValueError(- f"Column and processor names can't contain '/' or '\\' or be '.' / '..': {name!r}"- )+ """Processor names must be one folder: Data Designer stores them as `processors-files/<name>`+ and neither previews nor lists a nested one. Column names are sanitized by the validator patch."""+ processors = recipe.get("processors")+ for item in processors if isinstance(processors, list) else []:+ name = item.get("name") if isinstance(item, dict) else None+ if isinstance(name, str) and (+ "/" in name or "\\" in name or name in (".", "..") or re.match(r"^[A-Za-z]:", name)+ ):+ raise ValueError(+ f"Processor names can't contain '/' or '\\', start with a drive letter, or be '.' / '..': {name!r}"+ )+++def _safe_module_name(record_id: Any, column_name: str) -> str:+ # The code validator writes `<tmp>/<module>.py`: keep the column name readable but path-free.+ safe = re.sub(r"[^\w-]", "_", str(column_name))+ if safe != column_name:+ safe += "_" + hashlib.sha256(str(column_name).encode("utf-8")).hexdigest()[:8]+ return f"{record_id}_{safe}"+++def _apply_data_designer_python_validator_path_patch() -> None:+ try:+ from data_designer.engine.validators.python import ( # pyright: ignore[reportMissingImports]+ RECORD_ID_COLUMN_NAME,+ PythonValidator,+ )+ except ImportError:+ return++ if getattr(PythonValidator, "_unsloth_python_validator_path_patch_applied", False):+ return++ def _patched_write(self: Any, row: Any, code_column: str, path: str) -> None:+ root = Path(path).resolve()+ target = (+ root / f"{self._get_module_name(row[RECORD_ID_COLUMN_NAME], code_column)}.py"+ ).resolve()+ if target.parent != root:+ raise ValueError(f"Code validator file left its temp folder: {code_column!r}")+ with open(target, "w", encoding = "utf-8") as file:+ file.write(row[code_column])++ PythonValidator._get_module_name = staticmethod(_safe_module_name)+ PythonValidator._write_code_to_file = _patched_write+ setattr(PythonValidator, "_unsloth_python_validator_path_patch_applied", True)def build_config_builder(recipe: dict[str, Any]):@@ -813,6 +847,7 @@ def create_data_designer(recipe: dict[str, Any], *, artifact_path: str | None =_apply_data_designer_mixed_type_parquet_patch()_apply_data_designer_seed_uri_quote_patch()_apply_data_designer_sql_inline_config_patch()+ _apply_data_designer_python_validator_path_patch()from data_designer.interface.data_designer import DataDesigner # pyright: ignore[reportMissingImports]if artifact_path is None:diff --git a/studio/backend/tests/test_recipe_names_inside_folder.py b/studio/backend/tests/test_recipe_names_inside_folder.pyindex 953bf6bb260..cadee504288 100644--- a/studio/backend/tests/test_recipe_names_inside_folder.py+++ b/studio/backend/tests/test_recipe_names_inside_folder.py@@ -1,9 +1,9 @@# 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 strings that become path segments must not hold a path separator: column names become-`<tmp>/<record id>_<column>.py` in the code validator, and GitHub seed repo names become-`<base>/<owner>__<name>` in the scraper."""+"""Recipe strings that become path segments stay inside their folder: column names+(`<tmp>/<record id>_<column>.py`, sanitized), processor names (`processors-files/<name>/`) and+GitHub seed repo names (`<base>/<owner>__<name>`)."""import sysimport types@@ -20,44 +20,127 @@ _PLUGIN_SRC = _BACKEND / "plugins/data-designer-github-repo-seed/src"_B = chr(92)_ESCAPING_NAMES = ["x/../../marker", ".." + _B + ".." + _B + "x"]+_SLASH_NAMES = ["pros/cons", "input/output", "Q/A", "a" + _B + "b"][email protected]("name", _ESCAPING_NAMES)-def test_a_column_name_that_names_a_path_is_refused(name):- recipe = {"columns": [{"name": name, "column_type": "expression", "expr": "1"}]}- # build_config_builder is what validate, preview and the job worker all call.- with pytest.raises(ValueError):- service.build_config_builder(recipe)--[email protected]("name", _ESCAPING_NAMES)-def test_a_validator_target_that_names_a_path_is_refused(name):- # The target can be a seed column whose name comes from the seed file, not from `columns`.+ "name", _SLASH_NAMES + _ESCAPING_NAMES + ["answer", "a.b", "Step 1: answer"]+)+def test_any_column_or_validator_target_name_passes(name):column = {"name": "lint","column_type": "validation","validator_type": "code",- "validator_params": {"code_lang": "python"},"target_columns": ["code", name],}- with pytest.raises(ValueError):- service.build_config_builder({"columns": [column]})+ service.validate_recipe_names(+ {"columns": [{"name": name}, column], "processors": [{"name": "drop"}]}+ )[email protected]("name", [".", ".."])-def test_a_dot_only_processor_name_is_refused(name):- # Data Designer writes processor batches under processors-files/<name>/.[email protected]("name", ["drop", "drop.v2", "pros and cons"])+def test_a_single_folder_processor_name_passes(name):+ service.validate_recipe_names(+ {"processors": [{"name": name, "processor_type": "schema_transform"}]}+ )+++ "name",+ [+ ".",+ "..",+ "../x",+ "a/../../x",+ ".." + _B + "x",+ "/etc/x",+ _B + "x",+ "C:x",+ "c:" + _B + "x",+ "pros/cons",+ "a/b/c",+ "x/../y",+ "a" + _B + "b",+ ],+)+def test_a_processor_name_that_is_not_one_folder_is_refused(name):+ # Data Designer writes processor batches under processors-files/<name>/ and previews to+ # processors-files/<name>.parquet without creating a nested parent.recipe = {"processors": [{"name": name, "processor_type": "schema_transform"}]}with pytest.raises(ValueError):service.validate_recipe_names(recipe)[email protected]("name", ["answer", "code_v2", "a.b", "Question 1", "Step 1: answer"])-def test_ordinary_column_names_pass(name):- service.validate_recipe_names({"columns": [{"name": name}], "processors": [{"name": "drop"}]})+def python_validator(monkeypatch):+ # The two methods below are data_designer 0.5.4's PythonValidator, verbatim: the patch must keep+ # writing and reading back the same module name.+ class PythonValidator:+ def _write_code_to_file(self, row, code_column, path):+ with open(+ f"{path}/{self._get_module_name(row[RECORD_ID], code_column)}.py", "w"+ ) as file:+ file.write(row[code_column])++ @staticmethod+ def _get_module_name(record_id, column_name):+ return f"{record_id}_{column_name}"++ RECORD_ID = "internal_code_record_id"+ module = types.ModuleType("data_designer.engine.validators.python")+ module.PythonValidator = PythonValidator+ module.RECORD_ID_COLUMN_NAME = RECORD_ID+ for name in ("data_designer", "data_designer.engine", "data_designer.engine.validators"):+ monkeypatch.setitem(sys.modules, name, types.ModuleType(name))+ monkeypatch.setitem(sys.modules, module.__name__, module)+ service._apply_data_designer_python_validator_path_patch()+ service._apply_data_designer_python_validator_path_patch()+ return PythonValidator, RECORD_ID++[email protected]("name", _SLASH_NAMES + _ESCAPING_NAMES + ["code", "Q 1"])+def test_code_validator_file_stays_in_its_temp_folder(tmp_path, python_validator, name):+ validator_cls, record_id = python_validator+ box = tmp_path / "box" / "tmp"+ box.mkdir(parents = True)+ validator_cls()._write_code_to_file({record_id: "rid", name: "x = 1\n"}, name, str(box))++ written = [p for p in tmp_path.rglob("*") if p.is_file()]+ assert [p.parent for p in written] == [box]+ module = validator_cls._get_module_name("rid", name)+ assert written[0].name == module + ".py"+ assert written[0].read_text() == "x = 1\n"+ assert validator_cls._get_module_name("rid", name) == module+ if name == "code":+ assert module == "rid_code"+++def test_different_names_that_sanitize_alike_get_different_files(python_validator):+ validator_cls, _ = python_validator+ assert validator_cls._get_module_name("r", "a/b") != validator_cls._get_module_name("r", "a_b")+ assert validator_cls._get_module_name("r", "a/b") != validator_cls._get_module_name(+ "r", "a" + _B + "b"+ )++def test_job_with_a_slash_column_name_starts(monkeypatch):+ import routes.data_recipe.jobs as jobs_routes+ from models.data_recipe import RecipePayload-def test_job_with_an_escaping_column_name_is_refused_before_it_starts(monkeypatch):+ started = []+ monkeypatch.setattr(+ jobs_routes,+ "get_job_manager",+ lambda: type("M", (), {"start": lambda self, **k: started.append(k) or "job"})(),+ )+ recipe = {"columns": [{"name": "pros/cons", "column_type": "expression", "expr": "1"}]}+ jobs_routes.create_job(+ RecipePayload(recipe = recipe), request = None, credential = ("u", None), via_api_key = False+ )+ assert len(started) == 1+++def test_job_with_an_escaping_processor_name_is_refused_before_it_starts(monkeypatch):import routes.data_recipe.jobs as jobs_routesfrom models.data_recipe import RecipePayload@@ -67,7 +150,10 @@ def test_job_with_an_escaping_column_name_is_refused_before_it_starts(monkeypatc"get_job_manager",lambda: type("M", (), {"start": lambda self, **k: started.append(k)})(),)- recipe = {"columns": [{"name": "x/../../marker", "column_type": "expression", "expr": "1"}]}+ recipe = {+ "columns": [{"name": "a", "column_type": "expression", "expr": "1"}],+ "processors": [{"name": "../../marker", "processor_type": "schema_transform"}],+ }with pytest.raises(HTTPException) as exc:jobs_routes.create_job(RecipePayload(recipe = recipe), request = None, credential = ("u", None), via_api_key = False