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
Windows: validate managed Python before package installation (#7763)
Etherl1770182b5aac
diff --git a/.github/workflows/cross-platform-parity-ci.yml b/.github/workflows/cross-platform-parity-ci.ymlindex f364fb6853b..c5c2b98955a 100644--- a/.github/workflows/cross-platform-parity-ci.yml+++ b/.github/workflows/cross-platform-parity-ci.yml@@ -23,6 +23,7 @@ on:- 'tests/test_installer_skip_autostart.py'- 'tests/test_installer_system32_guard.py'- 'tests/python/test_cross_platform_parity.py'+ - 'tests/python/test_windows_python_venv_hardening.py'- 'tests/sh/test_install_rollback_lifecycle.sh'- 'tests/studio/test_install_rollback_lifecycle.ps1'- '.github/workflows/cross-platform-parity-ci.yml'@@ -35,6 +36,7 @@ on:- 'tests/test_installer_skip_autostart.py'- 'tests/test_installer_system32_guard.py'- 'tests/python/test_cross_platform_parity.py'+ - 'tests/python/test_windows_python_venv_hardening.py'- 'tests/sh/test_install_rollback_lifecycle.sh'- 'tests/studio/test_install_rollback_lifecycle.ps1'- '.github/workflows/cross-platform-parity-ci.yml'@@ -71,6 +73,7 @@ jobs:run: >-python -m pytesttests/python/test_cross_platform_parity.py+ tests/python/test_windows_python_venv_hardening.pytests/test_installer_skip_autostart.pytests/test_installer_system32_guard.py-qdiff --git a/install.ps1 b/install.ps1index e4a09ab8abb..f9189460a32 100644--- a/install.ps1+++ b/install.ps1@@ -1269,17 +1269,19 @@ exit 0param([string]$Exe)if ($Exe -match $script:CondaSkipPattern) { return $true }try {- $basePrefix = (& $Exe -c "import sys; print(sys.base_prefix)" 2>$null | Out-String).Trim()+ $basePrefix = (& $Exe -S -c "import sys; print(sys.base_prefix)" 2>$null | Out-String).Trim()if ($basePrefix -match $script:CondaSkipPattern) { return $true }} catch { }return $false}# The interpreter's own arch, asked of it: win-amd64|win-arm64|win32|"".+ # -S: the caller compares this with -eq, so a sitecustomize banner would read as+ # "unknown" and lose the x64-over-ARM64 preference.function Get-PythonPlatformTag {param([string]$Exe)try {- return (& $Exe -c "import sysconfig; print(sysconfig.get_platform())" 2>$null | Out-String).Trim().ToLowerInvariant()+ return (& $Exe -S -c "import sysconfig; print(sysconfig.get_platform())" 2>$null | Out-String).Trim().ToLowerInvariant()} catch { return "" }}@@ -1311,8 +1313,8 @@ exit 0if ($out -match "Python (3\.1[1-3])\.\d+") {$ver = $Matches[1]# Resolve the actual executable path and verify it is not conda-based- $resolvedExe = (& $pyLauncher.Source "-$minor" -c "import sys; print(sys.executable)" 2>$null | Out-String).Trim()- if ($resolvedExe -and (Test-Path $resolvedExe) -and -not (Test-IsCondaPython $resolvedExe)) {+ $resolvedExe = (& $pyLauncher.Source "-$minor" -S -c "import sys; print(sys.executable)" 2>$null | Out-String).Trim()+ if ($resolvedExe -and (Test-Path -LiteralPath $resolvedExe -PathType Leaf) -and -not (Test-IsCondaPython $resolvedExe)) {if (-not $preferX64) { return @{ Version = $ver; Path = $resolvedExe; Arch = "" } }$candidates += @{ Version = $ver; Path = $resolvedExe }}@@ -1335,8 +1337,14 @@ exit 0try {$out = & $cmd.Source --version 2>&1 | Out-Stringif ($out -match "Python (3\.1[1-3])\.\d+") {- if (-not $preferX64) { return @{ Version = $Matches[1]; Path = $cmd.Source; Arch = "" } }- $candidates += @{ Version = $Matches[1]; Path = $cmd.Source }+ $ver = $Matches[1]+ # PATH entries may be wrappers (e.g. pyenv-win's python.bat).+ # Resolve the real executable so uv bypasses wrapper re-resolution.+ $resolvedExe = (& $cmd.Source -S -c "import sys; print(sys.executable)" 2>$null | Out-String).Trim()+ if ($resolvedExe -and (Test-Path -LiteralPath $resolvedExe -PathType Leaf) -and -not (Test-IsCondaPython $resolvedExe)) {+ if (-not $preferX64) { return @{ Version = $ver; Path = $resolvedExe; Arch = "" } }+ $candidates += @{ Version = $ver; Path = $resolvedExe }+ }}} catch {}}@@ -1677,6 +1685,38 @@ exit 0$script:StudioVenvRollbackTarget = $VenvDir$script:StudioVenvRollbackActive = $false+ function Test-VenvPythonReady {+ param([Parameter(Mandatory = $true)][string]$PythonExe)+ if (-not (Test-Path -LiteralPath $PythonExe -PathType Leaf)) { return $false }++ $previousErrorActionPreference = $ErrorActionPreference+ $ErrorActionPreference = "Continue"+ try {+ $global:LASTEXITCODE = -1+ $null = & $PythonExe -c "import sys; sys.exit(0)" 2>$null+ return ($LASTEXITCODE -eq 0)+ } catch {+ return $false+ } finally {+ $ErrorActionPreference = $previousErrorActionPreference+ }+ }++ function Get-VenvBaseHome {+ param([Parameter(Mandatory = $true)][string]$VenvRoot)+ $configPath = Join-Path $VenvRoot "pyvenv.cfg"+ if (-not (Test-Path -LiteralPath $configPath -PathType Leaf)) { return $null }++ try {+ foreach ($line in [System.IO.File]::ReadAllLines($configPath)) {+ if ($line -match '^\s*home\s*=\s*(.*?)\s*$') {+ return $Matches[1].Trim()+ }+ }+ } catch {}+ return $null+ }+function Start-StudioVenvRollback {param([Parameter(Mandatory = $true)][string]$ExistingDir)$stamp = Get-Date -Format "yyyyMMddHHmmss"@@ -1885,13 +1925,22 @@ exit 0substep "$VenvDir"}- # Mark the freshly-created venv as Unsloth-owned so a partial install can be- # repaired by re-running install.ps1; the env-mode deletion guard above- # accepts this marker as the primary sentinel.+ # Mark the managed venv before probing so failed installs can be replaced on rerun.if (Test-Path -LiteralPath $VenvDir -PathType Container) {try { [System.IO.File]::WriteAllText((Join-Path $VenvDir ".unsloth-studio-owned"), "") } catch {}}+ if (-not (Test-VenvPythonReady -PythonExe $VenvPython)) {+ $recordedBaseHome = Get-VenvBaseHome -VenvRoot $VenvDir+ Write-Host "[ERROR] The managed Python interpreter is missing or cannot be launched." -ForegroundColor Red+ Write-Host " Managed Python: $VenvPython" -ForegroundColor Yellow+ if (-not $recordedBaseHome) { $recordedBaseHome = "unavailable" }+ Write-Host " Recorded base Python home: $recordedBaseHome" -ForegroundColor Yellow+ # The ownership marker is written above, so a plain re-run replaces this venv.+ Write-Host " Restore that Python installation, or just re-run install.ps1." -ForegroundColor Yellow+ return (Exit-InstallFailure "Managed Python is unavailable at $VenvPython (recorded base home: $recordedBaseHome)")+ }+# ── Helper: run amd-smi without triggering a UAC elevation prompt ──# amd-smi on Windows auto-elevates to read GPU/APU memory, surfacing a confusing# DiskPart UAC prompt mid-install (Unsloth backend amd.py hits the same).diff --git a/tests/python/test_windows_python_venv_hardening.py b/tests/python/test_windows_python_venv_hardening.pynew file mode 100644index 00000000000..87c545aa68a--- /dev/null+++ b/tests/python/test_windows_python_venv_hardening.py@@ -0,0 +1,161 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""Focused contracts for Windows Python wrapper and venv validation."""++from __future__ import annotations++import os+import re+import shlex+import shutil+import subprocess+import sys+from pathlib import Path++import pytest+++REPO_ROOT = Path(__file__).resolve().parents[2]+INSTALL_PS1 = REPO_ROOT / "install.ps1"+POWERSHELLS = [shell for shell in ("pwsh", "powershell") if shutil.which(shell)]+++def _extract(pattern: str, source: str) -> str:+ match = re.search(pattern, source, flags = re.DOTALL)+ assert match is not None, f"install.ps1 block not found: {pattern}"+ return match.group(0)+++def _run_powershell(shell: str, script: str, env: dict[str, str]) -> str:+ result = subprocess.run(+ [shell, "-NoProfile", "-NonInteractive", "-Command", script],+ check = True,+ capture_output = True,+ text = True,+ env = env,+ timeout = 30,+ )+ return result.stdout.strip()++[email protected](not POWERSHELLS, reason = "PowerShell is unavailable")[email protected]("shell", POWERSHELLS)+def test_path_python_wrapper_resolves_to_real_executable(tmp_path: Path, shell: str):+ source = INSTALL_PS1.read_text(encoding = "utf-8")+ finder = _extract(r" function Find-CompatiblePython \{.*?\n \}\n", source)+ (tmp_path / "sitecustomize.py").write_text('print("STARTUP_BANNER")\n', encoding = "utf-8")+ if os.name == "nt":+ wrapper = tmp_path / "python.bat"+ wrapper.write_text(f'@"{sys.executable}" %*\n', encoding = "utf-8")+ else:+ wrapper = tmp_path / "python-wrapper"+ wrapper.write_text(+ f'#!/bin/sh\nexec {shlex.quote(sys.executable)} "$@"\n', encoding = "utf-8"+ )+ wrapper.chmod(0o755)++ script = f"""+$ErrorActionPreference = "Stop"+$PythonVersion = "3.13"+$script:CondaSkipPattern = '(?i)(conda|miniconda|anaconda)'+function Get-HostMachineArch {{ return "x86_64" }}+function Test-IsCondaPython {{ param([string]$Exe) return $false }}+function Get-PythonPlatformTag {{ param([string]$Exe) return "win-amd64" }}+function Get-Command {{+ param([Parameter(Position = 0)][string]$Name,+ [Parameter(ValueFromRemainingArguments = $true)]$Rest)+ if ($Name -eq "python") {{+ return @([pscustomobject]@{{ Source = $env:TEST_PYTHON_WRAPPER }})+ }}+ return @()+}}+{finder}+$found = Find-CompatiblePython+Write-Output $found.Path+"""+ env = os.environ.copy()+ env["TEST_PYTHON_WRAPPER"] = str(wrapper)+ env["PYTHONPATH"] = str(tmp_path)+ assert Path(_run_powershell(shell, script, env)).resolve() == Path(sys.executable).resolve()++[email protected](not POWERSHELLS, reason = "PowerShell is unavailable")[email protected]("shell", POWERSHELLS)+def test_arch_probe_ignores_startup_output(tmp_path: Path, shell: str):+ """Startup output must not reach the arch tag.++ The caller compares the tag with -eq "win-amd64", so a contaminated answer reads+ as "unknown" and Windows on ARM silently settles for a native ARM64 interpreter.+ """+ source = INSTALL_PS1.read_text(encoding = "utf-8")+ probe = _extract(r" function Get-PythonPlatformTag \{.*?\n \}\n", source)+ (tmp_path / "sitecustomize.py").write_text('print("STARTUP_BANNER")\n', encoding = "utf-8")++ script = f"""+$ErrorActionPreference = "Stop"+{probe}+Write-Output (Get-PythonPlatformTag $env:TEST_PYTHON)+"""+ env = os.environ.copy()+ env["TEST_PYTHON"] = sys.executable+ env["PYTHONPATH"] = str(tmp_path)+ tag = _run_powershell(shell, script, env)+ assert tag and "\n" not in tag and "startup_banner" not in tag, tag++[email protected](not POWERSHELLS, reason = "PowerShell is unavailable")[email protected]("shell", POWERSHELLS)+def test_venv_base_home_comes_from_pyvenv_config(tmp_path: Path, shell: str):+ source = INSTALL_PS1.read_text(encoding = "utf-8")+ reader = _extract(r" function Get-VenvBaseHome \{.*?\n \}\n", source)+ expected = tmp_path / "removed-base-python"+ (tmp_path / "pyvenv.cfg").write_text(f"home = {expected}\n", encoding = "utf-8")++ script = f"""+$ErrorActionPreference = "Stop"+{reader}+Write-Output (Get-VenvBaseHome -VenvRoot $env:TEST_VENV_ROOT)+"""+ env = os.environ.copy()+ env["TEST_VENV_ROOT"] = str(tmp_path)+ assert _run_powershell(shell, script, env) == str(expected)++[email protected](not POWERSHELLS, reason = "PowerShell is unavailable")[email protected]("shell", POWERSHELLS)[email protected]("case", ["missing", "unlaunchable", "working"])+def test_managed_python_readiness_probe(tmp_path: Path, shell: str, case: str):+ source = INSTALL_PS1.read_text(encoding = "utf-8")+ readiness = _extract(r" function Test-VenvPythonReady \{.*?\n \}\n", source)+ python_exe = tmp_path / "broken-python.cmd"+ expected = "False"+ if case == "unlaunchable":+ python_exe.write_text("@exit /b 17\n", encoding = "utf-8")+ elif case == "working":+ python_exe = Path(sys.executable)+ expected = "True"++ script = f"""+$ErrorActionPreference = "Stop"+{readiness}+Write-Output (Test-VenvPythonReady -PythonExe $env:TEST_MANAGED_PYTHON)+"""+ env = os.environ.copy()+ env["TEST_MANAGED_PYTHON"] = str(python_exe)+ assert _run_powershell(shell, script, env) == expected+++def test_readiness_gate_precedes_installs_and_names_both_interpreters():+ source = INSTALL_PS1.read_text(encoding = "utf-8")+ gate = source.index("if (-not (Test-VenvPythonReady -PythonExe $VenvPython))")+ marker = source.index(+ '[System.IO.File]::WriteAllText((Join-Path $VenvDir ".unsloth-studio-owned"), "")'+ )+ first_uv_pip = source.index("uv pip install --python $VenvPython")+ gpu_detection = source.index("function Invoke-AmdSmiNoElevate")++ assert marker < gate < gpu_detection < first_uv_pip+ assert 'Write-Host " Managed Python: $VenvPython"' in source+ assert 'Write-Host " Recorded base Python home: $recordedBaseHome"' in source+ assert 'return (Exit-InstallFailure "Managed Python is unavailable' in source