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: treat a Smart App Control block of unsloth.exe like the AppLocker one (#13168)

oobabooga05366bf9d736
diff --git a/install.ps1 b/install.ps1
index bd52d4cada2..acd1e2bc10a 100644
--- a/install.ps1
+++ b/install.ps1
@@ -4915,8 +4915,8 @@ function Install-UnslothStudio {
$script:UnslothCmdShimMarker = "unsloth-studio-managed-launcher"
$script:UnslothCliTrampoline = "import sys, os; sys.path[:1] = [x for x in sys.path[:1] if getattr(sys.flags, 'safe_path', False) or x not in ('', os.getcwd())]; sys.argv[0] = 'unsloth'; from unsloth_cli import app; sys.exit(app())"
- # Recognize ERROR_ACCESS_DISABLED_BY_POLICY through PowerShell's wrapper exceptions,
- # the same way Test-AccessDeniedError above recognizes ERROR_ACCESS_DENIED.
+ # Policy refusal through PowerShell's wrapper exceptions: AppLocker 1260, App Control
+ # for Business and Smart App Control 4551 (ERROR_SYSTEM_INTEGRITY_POLICY_VIOLATION).
# $LASTEXITCODE cannot answer this: no process was created, so it still holds the
# exit code of whichever native command ran last.
function Test-ApplicationControlBlock {
@@ -4925,9 +4925,9 @@ function Install-UnslothStudio {
$ex = if ($ErrorRecord -is [System.Management.Automation.ErrorRecord]) { $ErrorRecord.Exception } else { $ErrorRecord }
while ($ex) {
# Win32Exception carries NativeErrorCode; outer wrappers keep only the HRESULT
- # form of the same code (0x800704EC).
- if ($ex -is [System.ComponentModel.Win32Exception] -and $ex.NativeErrorCode -eq 1260) { return $true }
- if ($ex.HResult -eq -2147023636) { return $true }
+ # form of the same code (0x800704EC, 0x800711C7).
+ if ($ex -is [System.ComponentModel.Win32Exception] -and $ex.NativeErrorCode -in @(1260, 4551)) { return $true }
+ if ($ex.HResult -in @(-2147023636, -2147020345)) { return $true }
$ex = $ex.InnerException
}
return $false
@@ -4940,11 +4940,11 @@ function Install-UnslothStudio {
param([Parameter(Mandatory = $true)][AllowEmptyString()][string]$Path)
Write-StudioLine "[ERROR] Windows Application Control blocked the managed Python runtime." -ForegroundColor Red
- Write-StudioLine " Windows error 1260 (ERROR_ACCESS_DISABLED_BY_POLICY)" -ForegroundColor Yellow
+ Write-StudioLine " AppLocker, App Control for Business or Smart App Control refused to start it." -ForegroundColor Yellow
Write-StudioLine " Blocked program: $Path" -ForegroundColor Yellow
- Write-StudioLine " Ask your administrator to review AppLocker `"EXE and DLL`" event 8004," -ForegroundColor Yellow
+ Write-StudioLine " Review AppLocker `"EXE and DLL`" event 8004," -ForegroundColor Yellow
Write-StudioLine " or CodeIntegrity/Operational event 3077." -ForegroundColor Yellow
- return "Windows Application Control blocked the managed Python runtime at $Path (Windows error 1260)."
+ return "Windows Application Control blocked the managed Python runtime at $Path."
}
# One pre-quoted command line, not an argument array: Start-Process joins
@@ -4995,8 +4995,8 @@ function Install-UnslothStudio {
# Does Application Control deny this launcher here? Windows cannot be asked without
# trying: AppLocker's cmdlets need the policy and an admin token, WDAC and Smart App
# Control expose nothing. A denial is free (CreateProcess fails synchronously, no
- # child, 1260 straight back); an unaffected machine pays one `--version`, measured
- # at a quarter second. A process that started is not blocked whatever it does next,
+ # child, the policy code straight back); an unaffected machine pays one `--version`,
+ # measured at a quarter second. A process that started is not blocked whatever it does next,
# so the timeout path still answers "not blocked" and just stops waiting.
function Test-ShimLaunchBlocked {
param([Parameter(Mandatory = $true)][string]$Path)
diff --git a/tests/python/test_windows_studio_update_launcher.py b/tests/python/test_windows_studio_update_launcher.py
index 2c4aa77963a..e5cf8643833 100644
--- a/tests/python/test_windows_studio_update_launcher.py
+++ b/tests/python/test_windows_studio_update_launcher.py
@@ -634,27 +634,42 @@ def test_a_failed_move_aside_warns_that_unsloth_may_not_upgrade(
# Application Control (#8490): Windows can deny the unsigned unsloth.exe while the signed python.exe runs.
-def _blocked_exe_run(interpreter_result, calls = None):
+POLICY_WINERRORS = [1260, 4551]
+
+
+def _blocked_exe_run(
+ interpreter_result,
+ calls = None,
+ *,
+ winerror = 1260,
+):
def run(argv, **kwargs):
if calls is not None:
calls.append((argv, kwargs))
if str(argv[0]).endswith("unsloth.exe"):
error = OSError(13, "An Application Control policy has blocked this file")
- error.winerror = 1260
+ error.winerror = winerror
raise error
return interpreter_result(argv, **kwargs)
return run
-def test_a_policy_blocked_launcher_falls_back_to_the_interpreter(monkeypatch, studio, tmp_path):
[email protected]("winerror", POLICY_WINERRORS)
+def test_a_policy_blocked_launcher_falls_back_to_the_interpreter(
+ monkeypatch, studio, tmp_path, winerror
+):
scripts, launcher = _configure_windows(monkeypatch, studio, tmp_path)
monkeypatch.setattr(studio, "_run_setup_script", lambda **_kwargs: None)
calls = []
monkeypatch.setattr(
studio.subprocess,
"run",
- _blocked_exe_run(lambda argv, **_kwargs: types.SimpleNamespace(returncode = 0), calls),
+ _blocked_exe_run(
+ lambda argv, **_kwargs: types.SimpleNamespace(returncode = 0),
+ calls,
+ winerror = winerror,
+ ),
)
_update(studio)
@@ -681,13 +696,39 @@ def test_a_policy_blocked_launcher_falls_back_to_the_interpreter(monkeypatch, st
assert calls[1][1]["timeout"] > calls[0][1]["timeout"]
-def test_a_policy_block_with_a_broken_package_still_fails(monkeypatch, studio, tmp_path):
[email protected]("winerror", POLICY_WINERRORS)
+def test_installer_setup_survives_a_policy_blocked_launcher(
+ monkeypatch, studio, tmp_path, winerror
+):
+ """install.ps1 runs `unsloth studio setup` on every install, so a refused launcher here fails the install itself."""
+ scripts, launcher = _configure_windows(monkeypatch, studio, tmp_path)
+ monkeypatch.setattr(
+ studio, "_run_setup_script", lambda **_kwargs: launcher.write_bytes(b"MZ-reinstalled")
+ )
+ monkeypatch.setattr(
+ studio.subprocess,
+ "run",
+ _blocked_exe_run(
+ lambda argv, **_kwargs: types.SimpleNamespace(returncode = 0), winerror = winerror
+ ),
+ )
+
+ studio.setup(verbose = False)
+
+ assert launcher.read_bytes() == b"MZ-reinstalled"
+ assert not (scripts / "unsloth.exe.update-backup").exists()
+
+
[email protected]("winerror", POLICY_WINERRORS)
+def test_a_policy_block_with_a_broken_package_still_fails(monkeypatch, studio, tmp_path, winerror):
scripts, launcher = _configure_windows(monkeypatch, studio, tmp_path)
monkeypatch.setattr(studio, "_run_setup_script", lambda **_kwargs: None)
monkeypatch.setattr(
studio.subprocess,
"run",
- _blocked_exe_run(lambda argv, **_kwargs: types.SimpleNamespace(returncode = 3)),
+ _blocked_exe_run(
+ lambda argv, **_kwargs: types.SimpleNamespace(returncode = 3), winerror = winerror
+ ),
)
_shared_setup_3(launcher, studio)
@@ -737,16 +778,38 @@ def test_an_ordinary_launcher_oserror_is_still_a_failure(monkeypatch, studio, tm
assert (scripts / "unsloth.exe.update-backup").exists()
-def test_the_policy_block_helper_only_matches_1260(studio):
- blocked = OSError(13, "blocked")
- blocked.winerror = 1260
- assert studio._is_application_control_block(blocked)
+ "winerror, blocked",
+ [
+ (1260, True),
+ (4551, True),
+ # A bad image hash can be a damaged file, which must still fail the update.
+ (577, False),
+ (5, False),
+ (None, False),
+ ],
+)
+def test_the_policy_block_helper_matches_only_policy_refusals(studio, winerror, blocked):
+ error = OSError(13, "refused")
+ if winerror is not None:
+ error.winerror = winerror
+ assert studio._is_application_control_block(error) is blocked
- denied = OSError(13, "denied")
- denied.winerror = 5
- assert not studio._is_application_control_block(denied)
- assert not studio._is_application_control_block(OSError(13, "denied"))
+def test_the_policy_block_codes_match_the_backend_code_integrity_table(studio):
+ """The backend recognises the same refusals for llama.cpp; the launcher drifted from it once (4551)."""
+ path = REPO_ROOT / "studio" / "backend" / "utils" / "code_integrity.py"
+ spec = importlib.util.spec_from_file_location("code_integrity_parity_test", path)
+ assert spec is not None and spec.loader is not None
+ code_integrity = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(code_integrity)
+
+ policy_winerrors = {
+ code
+ for code, reason in code_integrity._BLOCK_WINERRORS.items()
+ if reason not in code_integrity._INVALID_HASH_REASONS
+ }
+ assert studio._APPLICATION_CONTROL_WINERRORS == policy_winerrors
def test_a_quarantined_away_launcher_falls_back_to_the_interpreter(monkeypatch, studio, tmp_path):
diff --git a/tests/studio/test_application_control_cli_fallback.ps1 b/tests/studio/test_application_control_cli_fallback.ps1
index a61381f60e5..24e8d691a21 100644
--- a/tests/studio/test_application_control_cli_fallback.ps1
+++ b/tests/studio/test_application_control_cli_fallback.ps1
@@ -9,7 +9,7 @@
# with no exit code to report and no diagnostic worth reading.
#
# These checks pin the three things that fix has to get right: the failure is classified off the
-# exception (1260), never off $LASTEXITCODE, which no process was created to set; the CLI is
+# exception (1260 or 4551), never off $LASTEXITCODE, which no process was created to set; the CLI is
# reached through the interpreter with the trampoline intact as ONE argument; and the .cmd
# companion is byte-stable, so a re-run rewrites nothing.
# Run: pwsh -NoProfile -File tests/studio/test_application_control_cli_fallback.ps1
@@ -74,6 +74,7 @@ $preferFn = Get-FunctionText $install "Test-UnslothCmdShimPreferred"
# An empty or wrong extraction would make every case below pass vacuously.
Check "extraction kept the policy code" ($blockFn -match '1260')
+Check "extraction kept the code integrity code" ($blockFn -match '4551')
Check "extraction kept the utf8 pin" ($cmdlineFn -match '-X')
Check "extraction kept the classifier call" ($invokeFn -match 'Test-ApplicationControlBlock')
Check "extraction kept the walk-up" ($relFn -match '\.\.')
@@ -123,12 +124,19 @@ $hresultOnly = New-Object System.Exception("policy")
$hresultOnly.GetType().GetField("_HResult", "Instance,NonPublic").SetValue($hresultOnly, -2147023636)
Check "HRESULT 0x800704EC only" (Invoke-Block $hresultOnly)
Check "HRESULT inside an ErrorRecord" (Invoke-Block (New-Record $hresultOnly))
+Check "bare Win32Exception 4551" (Invoke-Block (New-Win32 4551))
+Check "4551 inside an ErrorRecord" (Invoke-Block (New-Record (New-Object System.Exception("outer", (New-Win32 4551)))))
+$sacHresultOnly = New-Object System.Exception("policy")
+$sacHresultOnly.GetType().GetField("_HResult", "Instance,NonPublic").SetValue($sacHresultOnly, -2147020345)
+Check "HRESULT 0x800711C7 only" (Invoke-Block $sacHresultOnly)
Write-Host "and nothing else is mistaken for one"
# 5 is ERROR_ACCESS_DENIED, the neighbouring failure Test-AccessDeniedError owns. Reporting a
# permissions problem as a security policy sends the user to the wrong administrator.
Check "access denied is not a policy block" (-not (Invoke-Block (New-Win32 5)))
Check "file not found is not a policy block" (-not (Invoke-Block (New-Win32 2)))
+# 577 is a bad image hash, which can be a damaged file rather than a policy verdict.
+Check "a bad image hash is not a policy block" (-not (Invoke-Block (New-Win32 577)))
Check "a plain exception" (-not (Invoke-Block (New-Object System.Exception("boom"))))
Check "a plain ErrorRecord" (-not (Invoke-Block (New-Record (New-Object System.Exception("boom")))))
Check "null" (-not (Invoke-Block $null))
diff --git a/unsloth_cli/commands/studio.py b/unsloth_cli/commands/studio.py
index fb1bb722d57..5b595e525a3 100644
--- a/unsloth_cli/commands/studio.py
+++ b/unsloth_cli/commands/studio.py
@@ -297,8 +297,8 @@ _MANAGED_CLI_IMPORT_PROBE = (
# Generous: cold interpreter start plus package import. A timeout means "no verdict", not failure.
_MANAGED_CLI_IMPORT_PROBE_TIMEOUT = 60
-# ERROR_ACCESS_DISABLED_BY_POLICY, surfaced by Python as OSError.winerror.
-_ERROR_ACCESS_DISABLED_BY_POLICY = 1260
+# Policy refusals: AppLocker 1260, App Control / Smart App Control 4551. Not 577: a bad hash can be a damaged file.
+_APPLICATION_CONTROL_WINERRORS = frozenset({1260, 4551})
def _managed_cli_argv(
@@ -314,7 +314,7 @@ def _managed_cli_argv(
def _is_application_control_block(error: OSError) -> bool:
"""True when Windows refused to start a program by policy: nothing ran."""
- return getattr(error, "winerror", None) == _ERROR_ACCESS_DISABLED_BY_POLICY
+ return getattr(error, "winerror", None) in _APPLICATION_CONTROL_WINERRORS
@contextlib.contextmanager