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: stage prebuilt installs in dirs that inherit the parent ACL on Windows (#14212)
Daniel Han2a4b4980d4a6
diff --git a/studio/install_audio_cpp_prebuilt.py b/studio/install_audio_cpp_prebuilt.pyindex d599cb33de5..deb7a890448 100644--- a/studio/install_audio_cpp_prebuilt.py+++ b/studio/install_audio_cpp_prebuilt.py@@ -51,7 +51,6 @@ import shutilimport subprocessimport sysimport tarfile-import tempfileimport urllib.errorimport urllib.requestimport zipfile@@ -753,7 +752,7 @@ def _fetch_model_specs(repo: str, commit: Optional[str], dest_dir: Path) -> boolpool.map(lambda item: _spec_bytes(repo, commit, *item), entries.items()),))- tmp = Path(tempfile.mkdtemp(prefix = ".model_specs-", dir = str(dest_dir)))+ tmp = core.make_staging_dir(dest_dir, ".model_specs-")for name, data in blobs.items():(tmp / name).write_bytes(data)os.replace(tmp, dest)@@ -805,7 +804,12 @@ def _sweep_retired_trees(target: Path) -> None:"""Remove ``<target>.old-*`` trees an earlier swap could not delete (Windows keeps a runningserver's files open). Best-effort: one still in use stays for the next run."""for old in target.parent.glob(target.name + ".old-*"):- if old.is_dir() and (old / OWNERSHIP_MARKER).is_file():+ try:+ owned = old.is_dir() and (old / OWNERSHIP_MARKER).is_file()+ except OSError:+ # Unreadable (an elevated run's tree, #14052): only an elevated run can remove it.+ owned = False+ if owned:shutil.rmtree(old, ignore_errors = True)# Staging dirs of a killed run; the install lock is held, so none belongs to a live one.for staging in target.parent.glob(".audio.cpp-staging-*"):@@ -813,6 +817,19 @@ def _sweep_retired_trees(target: Path) -> None:shutil.rmtree(staging, ignore_errors = True)+def _is_unreadable(target: Path) -> bool:+ """Whether this account cannot look inside ``target``: a tree an elevated run staged under+ mkdtemp's Windows ACL is owned by Administrators and denies the same user unelevated (#14052).+ Renaming it is refused too, so only an elevated shell can clear it."""+ try:+ os.stat(target / OWNERSHIP_MARKER)+ except PermissionError:+ return True+ except OSError:+ pass+ return False++def _server_in_use(server: Optional[Path]) -> bool:"""Whether a running audiocpp_server holds this binary. Windows maps a running imagewithout write sharing, so opening it for writing fails; elsewhere a replace is safe anyway."""@@ -1089,6 +1106,17 @@ def install(target = (install_dir or default_install_dir()).resolve()if target.exists() and not target.is_dir():raise RuntimeError(f"audio.cpp install target is not a directory: {target}")+ if _is_unreadable(target):+ # Matched by setup.ps1, which shows the repair instead of a generic failure.+ repair = (+ f'from an elevated PowerShell with Remove-Item -Recurse -Force "{target}"'+ if sys.platform == "win32"+ else f"with sudo rm -rf '{target}'"+ )+ raise RuntimeError(+ f"{target} cannot be read by this account (left by an elevated run); remove it "+ f"{repair}, then run the install again"+ )if target.exists() and not (target / OWNERSHIP_MARKER).is_file():entries = {p.name for p in target.iterdir()}if entries - _STUDIO_LEFTOVERS:@@ -1223,7 +1251,7 @@ def _install_locked(# Checked again before the swap; here it saves the download.raise PermissionError(f"audiocpp_server in {target} is running")target.parent.mkdir(parents = True, exist_ok = True)- staging = Path(tempfile.mkdtemp(prefix = ".audio.cpp-staging-", dir = str(target.parent)))+ staging = core.make_staging_dir(target.parent, ".audio.cpp-staging-")try:archive = staging / chosenprint(f"audio.cpp: downloading {chosen} from {repo} {tag}", flush = True)diff --git a/studio/install_llama_prebuilt.py b/studio/install_llama_prebuilt.pyindex a86a9042a09..2a7e2ce790c 100644--- a/studio/install_llama_prebuilt.py+++ b/studio/install_llama_prebuilt.py@@ -4978,10 +4978,8 @@ def prune_install_staging_root(install_dir: Path) -> None:def create_install_staging_dir(install_dir: Path) -> Path:- staging_dir = Path(- tempfile.mkdtemp(- prefix = f"{install_dir.name}.staging-", dir = install_staging_root(install_dir)- )+ staging_dir = _core.make_staging_dir(+ install_staging_root(install_dir), f"{install_dir.name}.staging-")log(f"created install staging dir {staging_dir}")return staging_dirdiff --git a/studio/install_node_prebuilt.py b/studio/install_node_prebuilt.pyindex d370a108e3c..13713b77a13 100644--- a/studio/install_node_prebuilt.py+++ b/studio/install_node_prebuilt.py@@ -51,7 +51,7 @@ _STUDIO_DIR = str(Path(__file__).resolve().parent)if _STUDIO_DIR not in sys.path:sys.path.insert(0, _STUDIO_DIR)-from prebuilt_core import DownloadProgress # noqa: E402+from prebuilt_core import DownloadProgress, make_staging_dir # noqa: E402try:from filelock import FileLock, Timeout as FileLockTimeout@@ -1195,9 +1195,7 @@ def install_prebuilt(install_dir: Path, *, channel: str, min_major: int, force:staging_root = install_dir.parent / INSTALL_STAGING_ROOT_NAMEstaging_root.mkdir(parents = True, exist_ok = True)- staging = Path(- tempfile.mkdtemp(prefix = f"{install_dir.name}.staging-", dir = staging_root)- )+ staging = make_staging_dir(staging_root, f"{install_dir.name}.staging-")try:archive_path = staging / assetlog(f"downloading {node_download_url(version, asset)}")diff --git a/studio/prebuilt_core.py b/studio/prebuilt_core.pyindex 67a543fa03b..23049764ef8 100644--- a/studio/prebuilt_core.py+++ b/studio/prebuilt_core.py@@ -492,6 +492,25 @@ def sleep_backoff(# ── Atomic writes and hashing ──+def make_staging_dir(parent: Path, prefix: str) -> Path:+ """``tempfile.mkdtemp``, except a Windows dir inherits ``parent``'s ACL.++ mkdtemp's 0o700 gives a Windows dir a protected SYSTEM / Administrators / OWNER RIGHTS DACL+ (CPython gh-118486), and a tree renamed out of it keeps those entries. An elevated run owns it+ as Administrators, so the same account cannot read it unelevated (#14052, #9928).+ """+ if sys.platform != "win32":+ return Path(tempfile.mkdtemp(prefix = prefix, dir = str(parent)))+ for _ in range(100):+ path = Path(parent) / f"{prefix}{os.urandom(6).hex()}"+ try:+ os.mkdir(path)+ except FileExistsError:+ continue+ return path+ raise FileExistsError(f"no free staging name under {parent}")++def atomic_write_bytes(destination: Path, data: bytes) -> None:destination.parent.mkdir(parents = True, exist_ok = True)with tempfile.NamedTemporaryFile(@@ -2786,7 +2805,7 @@ def install_from_bundle() -> None:staging_root = install_dir.parent / ops.INSTALL_STAGING_ROOT_NAMEstaging_root.mkdir(parents = True, exist_ok = True)- staging = Path(tempfile.mkdtemp(prefix = f"{install_dir.name}.staging-", dir = staging_root))+ staging = make_staging_dir(staging_root, f"{install_dir.name}.staging-")try:archive_path = staging / selection.asseturl = ops.asset_download_url(bundle, selection.asset)diff --git a/studio/setup.ps1 b/studio/setup.ps1index e53b5bf3d64..80000eaa111 100644--- a/studio/setup.ps1+++ b/studio/setup.ps1@@ -10557,6 +10557,9 @@ if ($env:AUDIOCPP_SERVER_PATH -or $env:UNSLOTH_AUDIO_CPP_PATH) {}} elseif ($audioCppExit -eq 3) {step "audio.cpp" "install busy; keeping existing runtime" "Yellow"+ } elseif ($audioCppOutput -match "cannot be read by this account") {+ # An elevated run left it owned by Administrators (#14052); only an elevated shell can remove it.+ step "audio.cpp" "$AudioCppDir is unreadable (left by an elevated run); in an elevated PowerShell run Remove-Item -Recurse -Force `"$AudioCppDir`", then unsloth studio update" "Yellow"} else {step "audio.cpp" "prebuilt install failed; audio.cpp models are unavailable; retry setup or inspect verbose output; other audio engines remain available" "Yellow"}diff --git a/tests/studio/install/test_install_audio_cpp_prebuilt_logic.py b/tests/studio/install/test_install_audio_cpp_prebuilt_logic.pyindex ebd2b3536cb..32c4ed0a4ef 100644--- a/tests/studio/install/test_install_audio_cpp_prebuilt_logic.py+++ b/tests/studio/install/test_install_audio_cpp_prebuilt_logic.py@@ -2226,3 +2226,73 @@ def test_an_existing_specs_folder_is_kept_without_a_fetch(monkeypatch, tmp_path)calls = _spec_repo(monkeypatch)assert M._fetch_model_specs(FORK, _SPEC_COMMIT, tmp_path) is Trueassert calls == []+++# #14052: a tree an elevated run staged under mkdtemp's ACL is unreadable to the same account unelevated+++def test_windows_staging_dirs_inherit_the_parent_acl(monkeypatch, tmp_path):+ # mkdtemp's 0o700 is a protected owner-only ACL on Windows, which a tree renamed out of it keeps.+ made = []+ real_mkdir = M.core.os.mkdir++ def mkdir(path, *args, **kwargs):+ made.append((Path(path), args, kwargs))+ real_mkdir(path)++ monkeypatch.setattr(M.core.sys, "platform", "win32")+ monkeypatch.setattr(M.core.os, "mkdir", mkdir)+ monkeypatch.setattr(M.core.tempfile, "mkdtemp", lambda *a, **k: pytest.fail("mkdtemp used"))+ path = M.core.make_staging_dir(tmp_path, ".audio.cpp-staging-")+ assert path.is_dir() and path.parent == tmp_path+ assert path.name.startswith(".audio.cpp-staging-")+ assert made == [(path, (), {})]+++def _unreadable(path):+ # Write but no search: nothing inside can be stat'ed.+ path.chmod(0o200)+ if M.os.access(path, M.os.X_OK):+ path.chmod(0o755)+ pytest.skip("chmod denies nothing to root or on Windows")+++def test_an_unreadable_install_names_the_repair_instead_of_in_use(monkeypatch, tmp_path, capsys):+ release = _release(tmp_path, CPU_ZIP)+ _install(monkeypatch, tmp_path, release)+ root = tmp_path / "audio.cpp"+ downloaded = []+ monkeypatch.setattr(M, "_download", lambda *a, **k: downloaded.append(a))+ _unreadable(root)+ try:+ assert M.main(["--install-dir", str(root), "--accelerator", "cpu"]) == M.EXIT_FAILED+ assert root.is_dir() and not list(tmp_path.glob("audio.cpp.old-*"))+ finally:+ root.chmod(0o755)+ err = capsys.readouterr().err+ assert "cannot be read by this account" in err and f"sudo rm -rf '{root}'" in err+ assert "in use" not in err and downloaded == []+ assert (root / M.OWNERSHIP_MARKER).is_file()+++def test_the_unreadable_repair_on_windows_is_powershell(monkeypatch, tmp_path):+ root = tmp_path / "audio.cpp"+ root.mkdir()+ monkeypatch.setattr(M, "_is_unreadable", lambda target: True)+ monkeypatch.setattr(M.sys, "platform", "win32")+ with pytest.raises(RuntimeError, match = "elevated PowerShell with Remove-Item -Recurse -Force"):+ M.install(install_dir = root, accelerator = "cpu")+++def test_the_sweep_skips_a_retired_tree_it_cannot_read(monkeypatch, tmp_path):+ release = _release(tmp_path, CPU_ZIP)+ _install(monkeypatch, tmp_path, release)+ stuck = tmp_path / "audio.cpp.old-123"+ stuck.mkdir()+ (stuck / M.OWNERSHIP_MARKER).touch()+ _unreadable(stuck)+ try:+ server = _install(monkeypatch, tmp_path, release, force = True)+ assert server.is_file() and stuck.is_dir()+ finally:+ stuck.chmod(0o755)