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: stop MXC read grants looping on a Microsoft Store Python (#13025)
Daniel Hana72be552db67
diff --git a/studio/backend/core/inference/mxc_read_grants.py b/studio/backend/core/inference/mxc_read_grants.pyindex 729759df03d..49b4af023c8 100644--- a/studio/backend/core/inference/mxc_read_grants.py+++ b/studio/backend/core/inference/mxc_read_grants.py@@ -42,6 +42,8 @@ _lock = threading.Lock()# Root -> folder identity whose whole tree passed the credential scan in this process; a folder# replaced at the same path, or a new process, scans again._scanned: dict[str, dict[str, int] | None] = {}+# Root -> folder identity whose grant Windows refused in this process; skipped until restart.+_refused: dict[str, dict[str, int] | None] = {}class ReadGrantError(RuntimeError):@@ -353,6 +355,14 @@ def _revoke(root: str) -> tuple[bool, str]:return _icacls(root, "/remove:g", f"*{ALL_APPLICATION_PACKAGES}")+def _root_untouched(root: str) -> bool:+ """icacls writes the root before propagating, so a refusal there changed nothing (#12941)."""+ try:+ return not _package_aces(root)[1]+ except OSError:+ return False++def _save_quietly(record: dict) -> None:"""Persist a record change after the ACL already matches it; a failed write only costs a retry."""try:@@ -405,11 +415,16 @@ def _revoke_recorded_root(record: dict, key: str) -> str:# Only inherited Windows permissions remain; none belong to Studio.record.pop(key)return "dropped"+ # Read before revoking: a failed /remove:g may clear the root and still leave descendants.+ never_landed = record[key].get("state") == "pending" and _root_untouched(key)ok, output = _revoke(key)if ok:record.pop(key)_scanned.pop(key, None)return "revoked"+ if never_landed:+ record.pop(key)+ return "dropped"logger.warning("Could not remove the persistent MXC read grant from %s: %s", key, output)return "failed"@@ -464,6 +479,8 @@ def _ensure_root(record: dict, root: str) -> bool:return Trueif covers and not pending:return True+ if entry is None and _refused.get(key) == current:+ return Falseif explicit and entry is None:# Someone else set an entry for that group here; /remove:g on opt-out would take theirs too.logger.info(@@ -505,6 +522,15 @@ def _ensure_root(record: dict, root: str) -> bool:raise ReadGrantError(f"the MXC read grant on {root} failed ({output}) and the folder changed")+ if _root_untouched(root):+ # e.g. Store Python under WindowsApps (TrustedInstaller): the rollback is refused too.+ record.pop(key, None)+ _save_quietly(record)+ _refused[key] = identity+ logger.info(+ "Keeping the per-launch MXC grant for %s: Windows refused it (%s)", root, output+ )+ return Falserestored, restore_output = _revoke(root)if not restored:raise ReadGrantError(diff --git a/studio/backend/tests/test_mxc_read_grants.py b/studio/backend/tests/test_mxc_read_grants.pyindex 66dbceacb2b..055e05a6b26 100644--- a/studio/backend/tests/test_mxc_read_grants.py+++ b/studio/backend/tests/test_mxc_read_grants.py@@ -22,6 +22,8 @@ class _Host:self.calls: list[tuple[str, str]] = []self.fail_grant = Falseself.fail_revoke = False+ # Folders this account cannot re-ACL, like a Store Python package under WindowsApps.+ self.locked: set[str] = set()def aces(self, root):key = os.path.normcase(root)@@ -29,7 +31,11 @@ class _Host:def grant(self, root):self.calls.append(("grant", root))+ if os.path.normcase(root) in self.locked:+ return False, "Successfully processed 0 files; Failed processing 1 files"if self.fail_grant:+ # The root entry landed and propagation below it failed.+ self.explicit.add(os.path.normcase(root))return False, "Access is denied."self.granted.add(os.path.normcase(root))self.explicit.add(os.path.normcase(root))@@ -37,7 +43,7 @@ class _Host:def revoke(self, root):self.calls.append(("revoke", root))- if self.fail_revoke:+ if self.fail_revoke or os.path.normcase(root) in self.locked:return False, "Access is denied."self.granted.discard(os.path.normcase(root))self.explicit.discard(os.path.normcase(root))@@ -57,6 +63,7 @@ def _isolate(monkeypatch, tmp_path):mxc_runtime, "dacl_state_path", lambda: studio_home / "mxc-runtime" / "dacl-restore")mxc_read_grants._scanned.clear()+ monkeypatch.setattr(mxc_read_grants, "_refused", {}, raising = False)return studio_home@@ -218,6 +225,66 @@ def test_a_failed_rollback_refuses_the_launch_and_keeps_the_retry(host):assert _states() == {os.path.normcase(venv): "complete"}+def _store_python(host, tmp_path):+ root = tmp_path / "Program Files" / "WindowsApps" / "PythonSoftwareFoundation.Python.3.12"+ (root / "Lib" / "encodings").mkdir(parents = True)+ (root / "python.exe").write_text("")+ host.locked.add(os.path.normcase(str(root)))+ return str(root)+++def test_a_folder_windows_refuses_keeps_the_per_launch_grant(host, tmp_path):+ root = _store_python(host, tmp_path)+ for _ in range(3):+ assert mxc_read_grants.ensure([root]) == ()+ # One attempt per process, no rollback of a change that never happened.+ assert host.calls == [("grant", root)]+ assert _record() == {}+++def test_a_stuck_pending_grant_on_a_folder_windows_refuses_is_dropped(host, tmp_path):+ root = _store_python(host, tmp_path)+ key = os.path.normcase(root)+ pending = {key: {"state": "pending", "identity": mxc_read_grants._identity(root)}}+ mxc_read_grants._save_record(pending)+ assert mxc_read_grants.ensure([root]) == ()+ assert _record() == {}+ mxc_read_grants._save_record(pending)+ assert mxc_read_grants.revoke_recorded() == ()+ assert _record() == {}+ assert host.calls == [("grant", root), ("revoke", key)]+++def test_a_pending_grant_on_a_locked_folder_with_its_own_entry_still_refuses(host, tmp_path):+ root = _store_python(host, tmp_path)+ key = os.path.normcase(root)+ host.explicit.add(key)+ mxc_read_grants._save_record(+ {key: {"state": "pending", "identity": mxc_read_grants._identity(root)}}+ )+ with pytest.raises(mxc_read_grants.ReadGrantError):+ mxc_read_grants.ensure([root])+ assert _states() == {key: "pending"}+++def test_a_revoke_that_clears_the_root_but_fails_below_keeps_the_record(host, monkeypatch):+ # The grant reached the root; /remove:g clears it there, then fails on a descendant.+ venv = _runtime(host)+ key = os.path.normcase(venv)+ host.explicit.add(key)+ mxc_read_grants._save_record(+ {key: {"state": "pending", "identity": mxc_read_grants._identity(venv)}}+ )++ def partial_revoke(root):+ host.explicit.discard(os.path.normcase(root))+ return False, "Successfully processed 1 files; Failed processing 1 files"++ monkeypatch.setattr(mxc_read_grants, "_revoke", partial_revoke)+ assert mxc_read_grants.revoke_recorded() == ()+ assert _states() == {key: "pending"}++def test_a_grant_interrupted_by_a_crash_is_redone(host):venv = _runtime(host)host.granted.add(os.path.normcase(venv)) # the root ACE landed, the propagation may not havediff --git a/studio/backend/tests/test_mxc_read_grants_windows_acl.py b/studio/backend/tests/test_mxc_read_grants_windows_acl.pynew file mode 100644index 00000000000..bb58a70b9af--- /dev/null+++ b/studio/backend/tests/test_mxc_read_grants_windows_acl.py@@ -0,0 +1,168 @@+# SPDX-License-Identifier: AGPL-3.0-only+"""Persistent MXC read grants against real Windows ACLs and icacls (#12941).++A Microsoft Store Python lives under Program Files\\WindowsApps, owned by TrustedInstaller with+read and execute only for everyone else, so icacls can neither add nor remove an entry there. The+locked folder below reproduces that with the same owner and DACL.+"""++from __future__ import annotations++import ctypes+import os+from pathlib import Path+import shutil+import subprocess++import pytest++from core.inference import mxc_read_grants, mxc_runtime, os_sandbox++pytestmark = pytest.mark.skipif(os.name != "nt", reason = "real Windows ACLs")++TRUSTED_INSTALLER = "*S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464"+SYSTEM, ADMINISTRATORS, USERS = "*S-1-5-18", "*S-1-5-32-544", "*S-1-5-32-545"+++def _run(*argv: str) -> None:+ done = subprocess.run(argv, capture_output = True, text = True, errors = "replace")+ assert done.returncode == 0, f"{argv}: {done.stdout}{done.stderr}"+++def _is_admin() -> bool:+ try:+ return bool(ctypes.windll.shell32.IsUserAnAdmin())+ except Exception:+ return False+++def studio(monkeypatch, tmp_path):+ # Long canonical spelling: _identity refuses an 8.3 alias such as RUNNER~1.+ base = Path(os.path.realpath(tmp_path))+ studio_home = base / "home" / ".unsloth" / "studio"+ studio_home.mkdir(parents = True)+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(studio_home))+ monkeypatch.delenv(mxc_read_grants.PERSISTENT_GRANTS_ENV, raising = False)+ monkeypatch.setattr(mxc_read_grants, "enabled", lambda: True)+ monkeypatch.setattr(os_sandbox, "studio_state_roots", lambda: (str(studio_home),))+ monkeypatch.setattr(+ mxc_runtime, "dacl_state_path", lambda: studio_home / "mxc-runtime" / "dacl-restore"+ )+ mxc_read_grants._scanned.clear()+ monkeypatch.setattr(mxc_read_grants, "_refused", {}, raising = False)+ return base+++def store_python(studio):+ if not _is_admin():+ if os.environ.get("CI"):+ pytest.fail("CI must run as an administrator to build the locked folder")+ pytest.skip("building a TrustedInstaller-owned folder needs an administrator")+ root = (+ studio+ / "WindowsApps"+ / "PythonSoftwareFoundation.Python.3.12_3.12.2800.0_x64__qbz5n2kfra8p0"+ )+ (root / "Lib" / "encodings").mkdir(parents = True)+ (root / "python.exe").write_bytes(b"")+ (root / "Lib" / "encodings" / "__init__.py").write_text("")+ try:+ _run(+ "icacls",+ str(root),+ "/inheritance:r",+ "/grant:r",+ f"{TRUSTED_INSTALLER}:(OI)(CI)(F)",+ f"{SYSTEM}:(OI)(CI)(RX)",+ f"{ADMINISTRATORS}:(OI)(CI)(RX)",+ f"{USERS}:(OI)(CI)(RX)",+ )+ _run("icacls", str(root), "/setowner", TRUSTED_INSTALLER, "/T", "/C")+ yield str(root)+ finally:+ subprocess.run(["takeown", "/F", str(root), "/R", "/D", "Y"], capture_output = True)+ subprocess.run(+ ["icacls", str(root), "/grant", f"{ADMINISTRATORS}:(OI)(CI)(F)", "/T", "/C"],+ capture_output = True,+ )+ shutil.rmtree(root, ignore_errors = True)+++def _record():+ path = mxc_read_grants.record_path()+ if not path.exists():+ return {}+ import json++ return json.loads(path.read_text(encoding = "utf-8"))["grants"]+++def test_the_locked_folder_matches_the_store_python_acl(store_python):+ # The fixture is only evidence if Windows really refuses icacls here, as on the reporter's host.+ ok, output = mxc_read_grants._grant(store_python)+ assert not ok, output+ assert mxc_read_grants._package_aces(store_python)[1] is False+++def test_a_store_python_folder_keeps_the_per_launch_grant_on_every_launch(+ store_python, monkeypatch+):+ calls = []+ real_icacls = mxc_read_grants._icacls+ monkeypatch.setattr(+ mxc_read_grants, "_icacls", lambda *a: calls.append(a[1:]) or real_icacls(*a)+ )+ for _ in range(3):+ assert mxc_read_grants.ensure([store_python]) == ()+ assert _record() == {}+ assert [c[0] for c in calls] == ["/grant"]+++def test_a_stuck_pending_grant_from_an_older_studio_is_dropped(store_python):+ key = os.path.normcase(store_python)+ pending = {key: {"state": "pending", "identity": mxc_read_grants._identity(store_python)}}+ mxc_read_grants._save_record(pending)+ assert mxc_read_grants.ensure([store_python]) == ()+ assert _record() == {}+ mxc_read_grants._save_record(pending)+ assert mxc_read_grants.revoke_recorded() == ()+ assert _record() == {}+++def test_a_folder_studio_owns_is_still_granted_once_and_revoked(studio):+ venv = studio / "home" / ".unsloth" / "studio" / "unsloth_studio"+ (venv / "Lib" / "site-packages").mkdir(parents = True)+ (venv / "Lib" / "site-packages" / "six.py").write_text("")+ venv = str(venv)+ assert mxc_read_grants.ensure([venv]) == (venv,)+ assert mxc_read_grants._package_aces(venv) == (True, True)+ assert {v["state"] for v in _record().values()} == {"complete"}+ assert mxc_read_grants.ensure([venv]) == (venv,)+ assert mxc_read_grants.revoke_recorded() == (os.path.normcase(venv),)+ assert mxc_read_grants._package_aces(venv)[1] is False+ assert _record() == {}+++def _installed_packages() -> list[str]:+ windows_apps = Path(os.environ.get("ProgramFiles", r"C:\Program Files")) / "WindowsApps"+ try:+ return sorted(str(p) for p in windows_apps.iterdir() if p.is_dir())[:20]+ except OSError:+ return []+++ not os.environ.get("CI"), reason = "edits installed packages' ACLs; disposable CI runners only"+)+def test_real_windowsapps_packages_never_wedge_a_launch(studio):+ packages = _installed_packages()+ if not packages:+ pytest.skip("no readable Program Files\\WindowsApps packages on this host")+ try:+ for package in packages:+ mxc_read_grants.ensure([package]) # must not raise ReadGrantError+ assert {v.get("state") for v in _record().values()} <= {"complete"}+ finally:+ mxc_read_grants.revoke_recorded()