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: clear only the compiled cache unsloth_zoo writes to (#15628)

Daniel Hanf0cb2a8655a6
diff --git a/studio/backend/tests/test_compiled_cache_location.py b/studio/backend/tests/test_compiled_cache_location.py
new file mode 100644
index 00000000000..a85906876de
--- /dev/null
+++ b/studio/backend/tests/test_compiled_cache_location.py
@@ -0,0 +1,195 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""The compiled-cache clear acts on the directory unsloth_zoo.compiler writes to and nothing else:
+UNSLOTH_COMPILE_LOCATION when set, else unsloth_compiled_cache in the CWD. Never the shared temp dir the compiler
+falls back to past an unusable location: anyone on the machine can create or link that name."""
+
+import os
+import tempfile
+from pathlib import Path
+
+import pytest
+
+from utils import cache_cleanup
+
+MODULE = "unsloth_compiled_module_llama.py"
+TRAINER = "UnslothSFTTrainer.py"
+
+
+def _write(path: Path, text: str = "x = 1\n") -> Path:
+ path.parent.mkdir(parents = True, exist_ok = True)
+ path.write_text(text, encoding = "utf-8")
+ return path
+
+
+def launch(tmp_path, monkeypatch):
+ """A launch folder holding a same-named directory, and no source-tree candidates in play."""
+ folder = tmp_path / "launch"
+ folder.mkdir()
+ monkeypatch.chdir(folder)
+ monkeypatch.setattr(cache_cleanup, "_CACHE_DIRS", [])
+ monkeypatch.setattr(tempfile, "tempdir", str(tmp_path / "tmp"))
+ (tmp_path / "tmp").mkdir()
+ monkeypatch.delenv("UNSLOTH_COMPILE_LOCATION", raising = False)
+ return folder
+
+
+def _pinned(tmp_path, monkeypatch) -> Path:
+ pinned = tmp_path / "home" / "compiled_cache"
+ _write(pinned / cache_cleanup.CACHE_MARKER, "")
+ _write(pinned / MODULE)
+ _write(pinned / TRAINER)
+ monkeypatch.setenv("UNSLOTH_COMPILE_LOCATION", str(pinned))
+ return pinned
+
+
[email protected]("preserve", [["Unsloth*Trainer.py"], None])
+def test_a_configured_location_leaves_the_launch_folder_alone(
+ tmp_path, monkeypatch, launch, preserve
+):
+ stray = launch / "unsloth_compiled_cache"
+ _write(stray / MODULE)
+ _write(stray / "notes.txt")
+ pinned = _pinned(tmp_path, monkeypatch)
+
+ cache_cleanup.clear_unsloth_compiled_cache(preserve_patterns = preserve)
+
+ assert (stray / MODULE).is_file(), "deleted from a folder the compiler never wrote to"
+ assert (stray / "notes.txt").is_file()
+ assert not (pinned / MODULE).exists()
+ assert (pinned / TRAINER).is_file() is (preserve is not None)
+ assert (pinned / cache_cleanup.CACHE_MARKER).is_file()
+
+
+def test_a_configured_location_does_not_warn_about_the_launch_folder(tmp_path, monkeypatch, launch):
+ (launch / "unsloth_compiled_cache").mkdir()
+ _pinned(tmp_path, monkeypatch)
+ warnings: list = []
+ monkeypatch.setattr(
+ cache_cleanup.logger,
+ "warning",
+ lambda message, *args, **_k: warnings.append(message % args),
+ )
+
+ cache_cleanup.clear_unsloth_compiled_cache(preserve_patterns = ["Unsloth*Trainer.py"])
+
+ assert warnings == []
+
+
+def test_without_the_variable_the_launch_folder_is_the_cache(launch):
+ cwd_cache = launch / "unsloth_compiled_cache"
+ _write(cwd_cache / MODULE)
+ _write(cwd_cache / "notes.txt")
+
+ cache_cleanup.clear_unsloth_compiled_cache(preserve_patterns = ["Unsloth*Trainer.py"])
+
+ # Not ours by construction, so only what the compiler generated goes.
+ assert not (cwd_cache / MODULE).exists()
+ assert (cwd_cache / "notes.txt").is_file()
+
+
+def test_a_relative_location_is_taken_against_the_cwd(tmp_path, monkeypatch, launch):
+ relative = launch / "rel" / "ucc"
+ _write(relative / MODULE)
+ other = tmp_path / "rel" / "ucc"
+ _write(other / MODULE)
+ monkeypatch.setenv("UNSLOTH_COMPILE_LOCATION", "rel/ucc")
+
+ cache_cleanup.clear_unsloth_compiled_cache()
+
+ assert not (relative / MODULE).exists()
+ assert (other / MODULE).is_file()
+
+
+def _blocked(tmp_path, monkeypatch) -> Path:
+ """A location os.makedirs cannot create, so the compiler would write to <tempdir>/ucc instead."""
+ blocker = _write(tmp_path / "not_a_dir")
+ monkeypatch.setenv("UNSLOTH_COMPILE_LOCATION", str(blocker / "ucc"))
+ return tmp_path / "tmp" / "ucc"
+
+
[email protected]("preserve", [["Unsloth*Trainer.py"], None])
+def test_an_uncreatable_location_never_adopts_the_shared_temp_dir(
+ tmp_path, monkeypatch, launch, preserve
+):
+ """<tempdir>/<leaf> is a name every user and install on the machine shares, so nothing there is provably ours."""
+ fallback = _blocked(tmp_path, monkeypatch)
+ _write(fallback / cache_cleanup.CACHE_MARKER, "")
+ _write(fallback / MODULE)
+ _write(fallback / "notes.txt")
+ _write(launch / "unsloth_compiled_cache" / MODULE)
+
+ assert cache_cleanup.get_existing_cache_dirs() == []
+ cache_cleanup.clear_unsloth_compiled_cache(preserve_patterns = preserve)
+
+ assert (fallback / MODULE).is_file()
+ assert (fallback / "notes.txt").is_file()
+ assert (launch / "unsloth_compiled_cache" / MODULE).is_file()
+
+
[email protected](not hasattr(os, "symlink") or os.name == "nt", reason = "needs POSIX symlinks")
+def test_a_temp_dir_symlink_cannot_point_the_clear_at_another_cache(tmp_path, monkeypatch, launch):
+ fallback = _blocked(tmp_path, monkeypatch)
+ victim = tmp_path / "victim"
+ _write(victim / cache_cleanup.CACHE_MARKER, "")
+ witness = _write(victim / "keep.txt")
+ fallback.symlink_to(victim, target_is_directory = True)
+
+ cache_cleanup.clear_unsloth_compiled_cache()
+
+ assert witness.is_file()
+
+
+def test_a_temp_dir_is_never_put_on_the_import_path(tmp_path, monkeypatch, launch):
+ import sys
+
+ fallback = _blocked(tmp_path, monkeypatch)
+ _write(fallback / cache_cleanup.CACHE_MARKER, "")
+ _write(fallback / "sitecustomize.py")
+ monkeypatch.setattr(sys, "path", list(sys.path))
+ monkeypatch.setenv("PYTHONPATH", "")
+
+ cache_cleanup.register_compiled_cache_on_path()
+
+ assert str(fallback.resolve()) not in sys.path
+ assert str(fallback.resolve()) not in os.environ["PYTHONPATH"]
+
+
[email protected]("leaf", [".", ".."])
+def test_a_dot_leaf_does_not_reach_the_temp_root(tmp_path, monkeypatch, launch, leaf):
+ blocker = _write(tmp_path / "not_a_dir")
+ monkeypatch.setenv("UNSLOTH_COMPILE_LOCATION", str(blocker) + "/" + leaf)
+ _write(tmp_path / "tmp" / cache_cleanup.CACHE_MARKER, "")
+ witness = _write(tmp_path / "tmp" / "keep.txt")
+
+ cache_cleanup.clear_unsloth_compiled_cache()
+
+ assert witness.is_file()
+
+
+def test_a_creatable_location_never_reaches_the_temp_dir(tmp_path, monkeypatch, launch):
+ monkeypatch.setenv("UNSLOTH_COMPILE_LOCATION", str(tmp_path / "not_yet" / "ucc"))
+ temp_copy = _write(tmp_path / "tmp" / "ucc" / MODULE)
+
+ assert cache_cleanup.get_existing_cache_dirs() == []
+ cache_cleanup.clear_unsloth_compiled_cache()
+
+ assert temp_copy.is_file()
+
+
[email protected]("value", ["~/ucc", " ucc_padded "])
+def test_the_location_is_taken_verbatim_like_the_compiler(tmp_path, monkeypatch, launch, value):
+ """os.makedirs neither expands ``~`` nor strips spaces, so the compiler writes to <cwd>/~/ucc."""
+ home = tmp_path / "home_dir"
+ _write(home / "ucc" / MODULE)
+ monkeypatch.setenv("HOME", str(home))
+ monkeypatch.setenv("USERPROFILE", str(home))
+ monkeypatch.setenv("UNSLOTH_COMPILE_LOCATION", value)
+
+ dirs = cache_cleanup._configured_cache_dirs()
+ assert dirs == [Path.cwd() / value]
+ # Absolute, so the Settings purge gate and its ``expanduser`` see the folder the compiler writes to.
+ assert all(d.is_absolute() for d in dirs)
+ assert str(dirs[0]) in cache_cleanup._trusted_cache_paths()
diff --git a/studio/backend/tests/test_sandbox_files_and_storage_roots.py b/studio/backend/tests/test_sandbox_files_and_storage_roots.py
index 114ca8ae8c8..917b9190b53 100644
--- a/studio/backend/tests/test_sandbox_files_and_storage_roots.py
+++ b/studio/backend/tests/test_sandbox_files_and_storage_roots.py
@@ -446,8 +446,8 @@ def test_compiled_cache_is_pinned_under_the_studio_home(tmp_path, monkeypatch):
assert str(tmp_path / "studio_home") in str(location)
-def test_cache_cleanup_finds_the_configured_and_cwd_caches(tmp_path, monkeypatch):
- """Cache cleanup must find the pinned compiled cache and a legacy one left in the launcher's CWD."""
+def test_cache_cleanup_finds_the_configured_cache_and_not_the_cwd_one(tmp_path, monkeypatch):
+ """unsloth_zoo writes only to UNSLOTH_COMPILE_LOCATION once it is set, so a same-named folder in the launcher's CWD is not ours."""
from utils import cache_cleanup
monkeypatch.chdir(tmp_path)
@@ -457,10 +457,11 @@ def test_cache_cleanup_finds_the_configured_and_cwd_caches(tmp_path, monkeypatch
monkeypatch.setenv("UNSLOTH_COMPILE_LOCATION", str(configured))
found = {str(Path(d).resolve()) for d in cache_cleanup.get_existing_cache_dirs()}
- print("\nfound cache dirs:")
- for d in sorted(found):
- print(" ", d)
assert str(configured.resolve()) in found
+ assert str((tmp_path / "unsloth_compiled_cache").resolve()) not in found
+
+ monkeypatch.delenv("UNSLOTH_COMPILE_LOCATION")
+ found = {str(Path(d).resolve()) for d in cache_cleanup.get_existing_cache_dirs()}
assert str((tmp_path / "unsloth_compiled_cache").resolve()) in found
diff --git a/studio/backend/utils/cache_cleanup.py b/studio/backend/utils/cache_cleanup.py
index b64ba1f4ec4..17166cc58ea 100644
--- a/studio/backend/utils/cache_cleanup.py
+++ b/studio/backend/utils/cache_cleanup.py
@@ -24,19 +24,22 @@ _CACHE_DIRS = [
]
-def _configured_cache_dirs() -> List[Path]:
- """Cache dirs outside the source tree: the configured one, and the CWD. The candidates above are all source-tree relative, so a cache created in the launcher's CWD (the user profile on Windows) was invisible to cleanup. The CWD is still checked for installs that predate the pinned location."""
- import os
+_DEFAULT_COMPILE_LEAF = "unsloth_compiled_cache"
+
+
+def _configured_location() -> str:
+ """UNSLOTH_COMPILE_LOCATION verbatim, as os.makedirs in unsloth_zoo.compiler takes it (no ``~``, no strip). Blank = unset, as in setup_cache_env."""
+ configured = os.environ.get("UNSLOTH_COMPILE_LOCATION") or ""
+ return configured if configured.strip() else ""
- dirs: List[Path] = []
- configured = (os.environ.get("UNSLOTH_COMPILE_LOCATION") or "").strip()
- if configured:
- dirs.append(Path(configured).expanduser())
+
+def _configured_cache_dirs() -> List[Path]:
+ """Where unsloth_zoo.compiler writes (``_get_compile_folder``), a relative location anchored at the CWD as os.makedirs takes it. Never the CWD default beside a configured location (somebody else's folder), nor the compiler's ``<tempdir>/<leaf>`` fallback: every user on the machine shares that name, so it is not ours to clear or import from."""
+ raw = Path(_configured_location() or _DEFAULT_COMPILE_LEAF)
try:
- dirs.append(Path.cwd() / "unsloth_compiled_cache")
- except OSError:
- pass
- return dirs
+ return [raw if raw.is_absolute() else Path.cwd() / raw]
+ except (OSError, RuntimeError, ValueError):
+ return []
def get_existing_cache_dirs() -> List[Path]:
@@ -79,9 +82,8 @@ def _is_dedicated_cache(path: Path) -> bool:
def _trusted_cache_paths() -> set:
"""Where a cache is ours by where it is: the source-tree candidates, and whatever UNSLOTH_COMPILE_LOCATION names, since that is the caller's answer to where the cache lives. Never the launch directory."""
trusted = _builtin_cache_paths()
- configured = (os.environ.get("UNSLOTH_COMPILE_LOCATION") or "").strip()
- if configured:
- trusted.add(str(Path(configured).expanduser()))
+ if _configured_location():
+ trusted.update(str(path) for path in _configured_cache_dirs())
return trusted