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 CLI: stop `unsloth run` re-exec'ing itself forever when the Studio venv is a symlink (#11788)
Daniel Han69a8fa3e5616
diff --git a/tests/studio/test_run_windows_entry_point.py b/tests/studio/test_run_windows_entry_point.pyindex 7ea6ade1c3c..244ad11952a 100644--- a/tests/studio/test_run_windows_entry_point.py+++ b/tests/studio/test_run_windows_entry_point.py@@ -18,6 +18,7 @@ from __future__ import annotationsimport astfrom pathlib import Path+from typing import Optional_REPO_ROOT = Path(__file__).resolve().parents[2]_STUDIO = _REPO_ROOT / "unsloth_cli" / "commands" / "studio.py"@@ -77,41 +78,60 @@ def test_the_windows_branch_is_the_exe():}, "the .exe branch must be gated on platform.system() == 'Windows'"-def _launch_head_value() -> ast.expr:+def _assigned_launch_head(stmts) -> Optional[ast.expr]:+ for stmt in stmts:+ if isinstance(stmt, ast.Assign) and any(+ isinstance(t, ast.Name) and t.id == "launch_head" for t in stmt.targets+ ):+ return stmt.value+ return None+++def _launch_head_arms() -> tuple[ast.expr, ast.expr, ast.expr]:+ """(Windows arm, POSIX arm, platform test) from an IfExp or an if/elif/else chain."""for node in ast.walk(_run_function()):- if not isinstance(node, ast.Assign):- continue- for target in node.targets:- if isinstance(target, ast.Name) and target.id == "launch_head":- return node.value+ if isinstance(node, ast.Assign) and _assigned_launch_head([node]) is not None:+ value = node.value+ assert isinstance(+ value, ast.IfExp+ ), f"expected launch_head to branch per platform, got {ast.dump(value)}"+ return value.body, value.orelse, value.test+ if (+ isinstance(node, ast.If)+ and _assigned_launch_head(node.body) is not None+ and any(isinstance(c, ast.Constant) and c.value == "win32" for c in ast.walk(node.test))+ ):+ last = node+ while len(last.orelse) == 1 and isinstance(last.orelse[0], ast.If):+ last = last.orelse[0]+ posix = _assigned_launch_head(last.orelse)+ assert posix is not None, "the launch_head chain needs a final else for POSIX"+ return _assigned_launch_head(node.body), posix, node.testraise AssertionError("`run` never assigns a launch_head")def test_windows_respawns_through_the_interpreter_not_the_console_script():"""The blocked executable must not be argv[0] of the child on Windows."""- branch = _launch_head_value()- assert isinstance(- branch, ast.IfExp- ), f"expected launch_head to branch per platform, got {ast.dump(branch)}"+ windows_arm, posix_arm, platform_test = _launch_head_arms()# Windows arm: _managed_cli_argv(studio_python), i.e. the interpreter form.- assert isinstance(branch.body, ast.Call), ast.dump(branch.body)- assert isinstance(branch.body.func, ast.Name)- assert branch.body.func.id == "_managed_cli_argv", (+ assert isinstance(windows_arm, ast.Call), ast.dump(windows_arm)+ assert isinstance(windows_arm.func, ast.Name)+ assert windows_arm.func.id == "_managed_cli_argv", ("the Windows arm must build the interpreter argv via _managed_cli_argv, got "- f"{ast.dump(branch.body.func)}"+ f"{ast.dump(windows_arm.func)}")- assert [arg.id for arg in branch.body.args if isinstance(arg, ast.Name)] == [+ assert [arg.id for arg in windows_arm.args if isinstance(arg, ast.Name)] == ["studio_python"], "the interpreter argv must be built from studio_python"# POSIX arm: [str(studio_bin)] -- unchanged, and what os.execvp needs.- assert isinstance(branch.orelse, ast.List) and len(branch.orelse.elts) == 1- posix_head = branch.orelse.elts[0]+ assert isinstance(posix_arm, ast.List) and len(posix_arm.elts) == 1+ posix_head = posix_arm.elts[0]assert isinstance(posix_head, ast.Call) and isinstance(posix_head.func, ast.Name)assert posix_head.func.id == "str"assert isinstance(posix_head.args[0], ast.Name) and posix_head.args[0].id == "studio_bin"assert "win32" in {node.value- for node in ast.walk(branch.test)+ for node in ast.walk(platform_test)if isinstance(node, ast.Constant) and isinstance(node.value, str)}, "the interpreter arm must be gated on sys.platform == 'win32'"diff --git a/unsloth_cli/commands/studio.py b/unsloth_cli/commands/studio.pyindex 83f983b5d01..8e2dbdddc6c 100644--- a/unsloth_cli/commands/studio.py+++ b/unsloth_cli/commands/studio.py@@ -227,6 +227,8 @@ DESKTOP_SECRET_HASH_KEY = "desktop_secret_hash"DESKTOP_SECRET_CREATED_AT_KEY = "desktop_secret_created_at"PBKDF2_ITERATIONS = 100_000_START_API_KEY_MARKER_ENV = "_UNSLOTH_START_API_KEY_MARKER"+# Marks run()'s re-exec'd child; a marked child still outside the venv must stop, not loop.+_STUDIO_REEXEC_ENV = "_UNSLOTH_STUDIO_REEXEC"_CLOUDFLARE_INTENT_ENV = "_UNSLOTH_CLOUDFLARE_INTENT"@@ -447,6 +449,31 @@ def _studio_venv_python() -> Optional[Path]:return p if p.is_file() else None+def _resolved_or_self(path: Path) -> Path:+ try:+ return path.resolve()+ except (OSError, RuntimeError, ValueError): # RuntimeError: symlink loop, Python < 3.13+ return path+++def _running_in_studio_venv(venv_dir: Path) -> bool:+ """Compare resolved path components: console-script shebangs hold the resolved venv path,+ so a string prefix check against a symlinked venv_dir never matched and looped forever."""+ prefix = Path(sys.prefix)+ for a, b in (+ (prefix, venv_dir),+ (_resolved_or_self(prefix), _resolved_or_self(venv_dir)),+ ):+ a_s = os.path.normcase(str(a))+ b_s = os.path.normcase(str(b)).rstrip(os.sep + (os.altsep or ""))+ if a_s == b_s or a_s.startswith(b_s + os.sep):+ return True+ try:+ return os.path.samefile(prefix, venv_dir)+ except (OSError, ValueError):+ return False++def _managed_cli_site_packages_layout(python: Path) -> bool:"""On-disk hint that the venv still carries the CLI. Weaker than the import probe: an emptyunsloth_cli/ or an orphaned dist-info passes here."""@@ -584,7 +611,7 @@ def _clear_hsa_override_contradicting_install(venv_dir: Path) -> Optional[str]:def _clear_hsa_override_before_launch(silent: bool = False) -> Optional[str]:"""Run the #7331 spoof clear for whichever entry point is about to launch. Idempotent."""_venv = STUDIO_HOME / "unsloth_studio"- _root = Path(sys.prefix) if sys.prefix.startswith(str(_venv)) else _venv+ _root = Path(sys.prefix) if _running_in_studio_venv(_venv) else _venv_arch = _clear_hsa_override_contradicting_install(_root)# Published whether or not anything was cleared here: on a desktop launch the GUI# environment never carried the override, so the clear above is a no-op and the@@ -1906,7 +1933,7 @@ def studio_default(# Resolve the child launcher BEFORE the gate: a headless gate strips the seeded password, so aborting afterwards leaves no way to log in.studio_venv_dir = STUDIO_HOME / "unsloth_studio"- in_studio_venv = sys.prefix.startswith(str(studio_venv_dir))+ in_studio_venv = _running_in_studio_venv(studio_venv_dir)# Before the env reaches a child: an override contradicting single-arch wheels fails every kernel launch, and install.sh's unset cannot reach here (#7331)._clear_hsa_override_before_launch(silent = silent)studio_python = run_py = None@@ -2528,7 +2555,16 @@ def run()studio_venv_dir = STUDIO_HOME / "unsloth_studio"- in_studio_venv = sys.prefix.startswith(str(studio_venv_dir))+ in_studio_venv = _running_in_studio_venv(studio_venv_dir)+ reexeced = os.environ.pop(_STUDIO_REEXEC_ENV, None) == "1"+ if reexeced and not in_studio_venv:+ typer.echo(+ f"Error: re-launched through {studio_venv_dir} but still running from "+ f"{sys.prefix}, so not re-launching again. Check that UNSLOTH_STUDIO_HOME "+ "points at the Studio install, or re-run: unsloth studio setup",+ err = True,+ )+ raise typer.Exit(1)studio_bin = Noneresolved_frontend = frontendif not in_studio_venv:@@ -2578,9 +2614,13 @@ def run(if not in_studio_venv:# Application Control blocks the generated unsloth.exe on some machines but not the signed python.exe beside it.- launch_head = (- _managed_cli_argv(studio_python) if sys.platform == "win32" else [str(studio_bin)]- )+ if sys.platform == "win32":+ launch_head = _managed_cli_argv(studio_python)+ elif _resolved_or_self(studio_venv_dir) != studio_venv_dir:+ # Older child CLIs loop via the console script's resolved shebang; python keeps the link.+ launch_head = [str(studio_python), "-c", _WINDOWS_CLI_ENTRYPOINT]+ else:+ launch_head = [str(studio_bin)]args = [*launch_head,"studio",@@ -2635,6 +2675,7 @@ def run(if start_api_key_marker:os.environ[_START_API_KEY_MARKER_ENV] = "1"+ os.environ[_STUDIO_REEXEC_ENV] = "1"try:if sys.platform == "win32":with _studio_runtime_launch_guard(inherited = runtime_gate_handoff) as gate_held:@@ -2648,9 +2689,10 @@ def run(rc = proc.wait()raise typer.Exit(rc)else:- os.execvp(str(studio_bin), args)+ os.execvp(args[0], args)finally:os.environ.pop(_START_API_KEY_MARKER_ENV, None)+ os.environ.pop(_STUDIO_REEXEC_ENV, None)with _studio_deps.studio_backend_imports("unsloth studio"):run_mod = _load_run_module()diff --git a/unsloth_cli/tests/test_studio_home_symlink_reexec.py b/unsloth_cli/tests/test_studio_home_symlink_reexec.pynew file mode 100644index 00000000000..491474fa381--- /dev/null+++ b/unsloth_cli/tests/test_studio_home_symlink_reexec.py@@ -0,0 +1,186 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""`unsloth run` must not re-exec itself forever when the studio venv is reached through a symlink."""++from __future__ import annotations++import os+import sys+from pathlib import Path++import pytest+from typer.testing import CliRunner+++_REPO_ROOT = Path(__file__).resolve().parents[2]+if str(_REPO_ROOT) not in sys.path:+ sys.path.insert(0, str(_REPO_ROOT))+++def _studio():+ from unsloth_cli.commands import studio as _studio_mod+ return _studio_mod+++def _symlinked_venv(tmp_path):+ real = tmp_path / "disk2" / "unsloth_studio"+ real.mkdir(parents = True)+ home = tmp_path / "home"+ home.mkdir()+ link = home / "unsloth_studio"+ try:+ link.symlink_to(real, target_is_directory = True)+ except (OSError, NotImplementedError) as e:+ pytest.skip(f"symlinks unavailable here: {e}")+ return real, link+++def test_resolved_prefix_counts_as_symlinked_venv(tmp_path, monkeypatch):+ studio_mod = _studio()+ real, link = _symlinked_venv(tmp_path)+ monkeypatch.setattr(sys, "prefix", str(real))+ assert studio_mod._running_in_studio_venv(link)+ assert not sys.prefix.startswith(str(link))+++def test_link_prefix_counts_as_real_venv(tmp_path, monkeypatch):+ studio_mod = _studio()+ real, link = _symlinked_venv(tmp_path)+ monkeypatch.setattr(sys, "prefix", str(link))+ assert studio_mod._running_in_studio_venv(real)+ assert studio_mod._running_in_studio_venv(link)+++def test_sibling_with_shared_name_prefix_is_not_the_venv(tmp_path, monkeypatch):+ studio_mod = _studio()+ venv = tmp_path / "unsloth_studio"+ sibling = tmp_path / "unsloth_studio2"+ venv.mkdir()+ sibling.mkdir()+ monkeypatch.setattr(sys, "prefix", str(sibling))+ assert not studio_mod._running_in_studio_venv(venv)+++def test_prefix_inside_venv_and_unrelated_prefix(tmp_path, monkeypatch):+ studio_mod = _studio()+ venv = tmp_path / "unsloth_studio"+ (venv / "sub").mkdir(parents = True)+ monkeypatch.setattr(sys, "prefix", str(venv / "sub"))+ assert studio_mod._running_in_studio_venv(venv)+ monkeypatch.setattr(sys, "prefix", str(tmp_path / "elsewhere"))+ assert not studio_mod._running_in_studio_venv(venv)+++def test_missing_paths_do_not_raise(tmp_path, monkeypatch):+ studio_mod = _studio()+ monkeypatch.setattr(sys, "prefix", str(tmp_path / "gone" / "venv"))+ assert not studio_mod._running_in_studio_venv(tmp_path / "also_gone" / "unsloth_studio")+++def test_symlink_loop_does_not_raise(tmp_path, monkeypatch):+ studio_mod = _studio()++ def _loop(self, *a, **k):+ raise RuntimeError(f"Symlink loop from {self!r}")++ monkeypatch.setattr(Path, "resolve", _loop)+ monkeypatch.setattr(sys, "prefix", str(tmp_path / "outer"))+ assert not studio_mod._running_in_studio_venv(tmp_path / "unsloth_studio")+ monkeypatch.setattr(sys, "prefix", str(tmp_path / "unsloth_studio"))+ assert studio_mod._running_in_studio_venv(tmp_path / "unsloth_studio")+++class _Execd(SystemExit):+ def __init__(self):+ super().__init__(0)+++def _run_app(+ monkeypatch,+ *,+ prefix,+ guard_env = None,+ studio_home = None,+):+ """Drive run() up to its re-exec with a fake venv that the prefix is NOT inside."""+ import typer++ studio_mod = _studio()+ monkeypatch.setattr(sys, "prefix", prefix)+ if studio_home is not None:+ monkeypatch.setattr(studio_mod, "STUDIO_HOME", studio_home)+ fake_venv = (studio_home or Path("/fake/studio/venv")) / "unsloth_studio"+ fake_python = fake_venv / "bin" / "python"+ fake_bin = fake_python.parent / "unsloth"+ monkeypatch.setattr(studio_mod, "_studio_venv_python", lambda: fake_python)+ real_is_file = Path.is_file+ monkeypatch.setattr(+ Path, "is_file", lambda self: True if str(self) == str(fake_bin) else real_is_file(self)+ )+ from unsloth_cli import _tool_policy as _tp_mod++ monkeypatch.setattr(_tp_mod, "resolve_tool_policy", lambda host, flag, yes, silent: False)+ monkeypatch.setattr(sys, "platform", "linux")+ monkeypatch.setattr(studio_mod.platform, "system", lambda: "Linux")+ execs = []++ def fake_execvp(file, argv):+ execs.append((list(argv), os.environ.get(studio_mod._STUDIO_REEXEC_ENV)))+ raise _Execd()++ monkeypatch.setattr(studio_mod.os, "execvp", fake_execvp)+ if guard_env is None:+ monkeypatch.delenv(studio_mod._STUDIO_REEXEC_ENV, raising = False)+ else:+ monkeypatch.setenv(studio_mod._STUDIO_REEXEC_ENV, guard_env)+ app = typer.Typer()+ app.command(context_settings = {"allow_extra_args": True, "ignore_unknown_options": True})(+ studio_mod.run+ )+ result = CliRunner().invoke(app, ["--model", "unsloth/Qwen3-1.7B-GGUF"], catch_exceptions = True)+ return studio_mod, result, execs+++def test_reexec_marks_the_child(monkeypatch):+ studio_mod, result, execs = _run_app(monkeypatch, prefix = "/nonexistent/outer/venv")+ assert len(execs) == 1, result.output+ argv, guard = execs[0]+ # Head is the console script or, when the venv path resolves elsewhere, python -c.+ assert argv[argv.index("studio") + 1] == "run"+ assert guard == "1", "the re-exec'd child must see the marker"+ assert studio_mod._STUDIO_REEXEC_ENV not in os.environ, "the parent must not keep it"+++def test_marked_child_outside_the_venv_stops_instead_of_looping(monkeypatch):+ studio_mod, result, execs = _run_app(+ monkeypatch, prefix = "/nonexistent/outer/venv", guard_env = "1"+ )+ assert execs == [], "a marked child must not re-exec again"+ assert result.exit_code == 1+ assert "not re-launching again" in result.output+ assert studio_mod._STUDIO_REEXEC_ENV not in os.environ+++_posix_exec_only = pytest.mark.skipif(os.name == "nt", reason = "POSIX exec branch")+++@_posix_exec_only+def test_unlinked_venv_still_execs_the_console_script(monkeypatch):+ _, result, execs = _run_app(monkeypatch, prefix = "/nonexistent/outer/venv")+ assert len(execs) == 1, result.output+ assert execs[0][0][0] == "/fake/studio/venv/unsloth_studio/bin/unsloth"+++@_posix_exec_only+def test_symlinked_venv_execs_through_the_linked_interpreter(tmp_path, monkeypatch):+ # An older venv CLI would loop via the console script (resolved sys.prefix).+ studio_mod = _studio()+ real, link = _symlinked_venv(tmp_path)+ _, result, execs = _run_app(+ monkeypatch, prefix = "/nonexistent/outer/venv", studio_home = link.parent+ )+ assert len(execs) == 1, result.output+ argv = execs[0][0]+ assert argv[:3] == [str(link / "bin" / "python"), "-c", studio_mod._WINDOWS_CLI_ENTRYPOINT]+ assert argv[3:5] == ["studio", "run"]