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 installer: always build Studio on a uv-managed Python, never one already installed (#13399)
Daniel Hane2104761c584
diff --git a/install.ps1 b/install.ps1index 7e0f794adb8..66e2d2b1edb 100644--- a/install.ps1+++ b/install.ps1@@ -2005,7 +2005,12 @@ function Install-UnslothStudio {$ShortcutsOnly = $false$WithLlamaCppDir = ""$argList = $args+ $PythonRequestArg = $nullfor ($i = 0; $i -lt $argList.Count; $i++) {+ if ([string]$argList[$i] -like "--python=*") {+ $PythonRequestArg = ([string]$argList[$i]).Substring(9)+ continue+ }switch ($argList[$i]) {"--local" { $StudioLocalInstall = $true }"--tauri" { $TauriMode = $true }@@ -2023,6 +2028,14 @@ function Install-UnslothStudio {}$PackageName = $argList[$i]}+ "--python" {+ $i+++ if ($i -ge $argList.Count) {+ Write-StudioLine "[ERROR] --python requires a version argument, e.g. --python 3.13." -ForegroundColor Red+ return (Exit-InstallFailure "--python requires a version argument.")+ }+ $PythonRequestArg = [string]$argList[$i]+ }"--with-llama-cpp-dir" {$i++if ($i -ge $argList.Count) {@@ -2058,20 +2071,22 @@ function Install-UnslothStudio {return (Exit-InstallFailure "--package name contains invalid characters")}- # UNSLOTH_PYTHON pins the version (mirrors install.sh --python); default 3.13.- $PythonVersion = if ($env:UNSLOTH_PYTHON) { $env:UNSLOTH_PYTHON } else { "3.13" }- # python.org fallback patch when winget and the live listing fail; bump with $PythonVersion.- $PythonFallbackFullVersion = "3.13.13"+ # Always a uv-managed CPython: --python > UNSLOTH_PYTHON > the existing environment's minor > 3.13.+ $PythonExplicitRequest = if ($null -ne $PythonRequestArg) { $PythonRequestArg.Trim() } elseif ($env:UNSLOTH_PYTHON) { $env:UNSLOTH_PYTHON.Trim() } else { "" }+ if (($null -ne $PythonRequestArg -or $PythonExplicitRequest) -and $PythonExplicitRequest -notmatch '^3\.1[1-3](\.\d+)?$') {+ Write-StudioLine "[ERROR] Unsupported Python request '$PythonExplicitRequest': use 3.11, 3.12 or 3.13 (optionally with a patch, e.g. 3.13.9)." -ForegroundColor Red+ return (Exit-InstallFailure "Unsupported Python request '$PythonExplicitRequest'")+ }+ $PythonPatchRequest = if ($PythonExplicitRequest -match '^3\.1[1-3]\.\d+$') { $PythonExplicitRequest } else { "" }+ $PythonVersion = if ($PythonExplicitRequest) { (($PythonExplicitRequest -split '\.')[0..1]) -join '.' } else { "3.13" }# Patch releases the stack cannot run; mirrors PYTHON_SKIP in install.sh.- # Windows resolves an installed interpreter and hands uv its path rather- # than a version, so uv never picks one of these -- but the machine may- # already have it, and $PythonFallbackFullVersion above is what replaces it.$PythonSkip = @("3.13.8")- # The entry above is skipped for one reason: it cannot `import torch`. A- # -NoTorch install never imports it, so refusing the interpreter would send a- # locked-down GGUF-only machine into winget/python.org recovery it may not be- # able to complete, over a package it will not install.+ # It cannot `import torch`, which a -NoTorch install never does.if ($SkipTorch) { $PythonSkip = @() }+ if ($PythonPatchRequest -and ($PythonSkip -contains $PythonPatchRequest)) {+ Write-StudioLine "[ERROR] Python $PythonPatchRequest cannot import torch; request $PythonVersion or another patch." -ForegroundColor Red+ return (Exit-InstallFailure "Python $PythonPatchRequest cannot import torch")+ }# An elevated run writes the install root as Administrators and the same account cannot# read it back afterwards. Twin in studio/setup.ps1.@@ -6617,19 +6632,6 @@ exit 0substep "Get it from https://aka.ms/getwinget if Python / uv are not already on PATH." "Yellow"}- # ── Detect Python 3.11-3.13, skipping conda and venvs whose base_prefix is conda. ──- $script:CondaSkipPattern = '(?i)(conda|miniconda|anaconda|miniforge|mambaforge)'-- function Test-IsCondaPython {- param([string]$Exe)- if ($Exe -match $script:CondaSkipPattern) { return $true }- try {- $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.@@ -6640,298 +6642,6 @@ exit 0} catch { return "" }}- # Returns @{ Version = "3.13"; Path = "C:\...\python.exe" } or $null.- # The resolved Path is passed to `uv venv --python` to prevent uv from- # re-resolving the version string back to a conda interpreter.- # Candidates on $PythonSkip are dropped as they are enumerated, so no caller- # can be handed an interpreter that cannot import torch and the usual- # 3.13 -> 3.12 -> 3.11 fallback still applies when the preferred minor is bad.- function Find-CompatiblePython {- # -X64Only: best installed x64 interpreter or $null, never ARM64. Last resort for- # Install-X64Python, where x64 of a lower-priority minor beats ARM64.- param([switch]$X64Only)- # Windows on ARM: prefer x64. pyarrow (via datasets) and hf-transfer ship no- # win_arm64 wheel, so a native ARM64 Python source-builds both and dies on CMake /- # Rust minutes in; x64 runs fine emulated. ARM64 is still returned when it is all- # there is, and the caller then bootstraps x64 or warns.- # ARM64 first on a native host, so a leftover x64 interpreter does not capture the venv.- # And when UNSLOTH_ALLOW_ARM64_PYTHON is set: the opt-out has to reach the SELECTION,- # not only the swap after it. On a machine that already has x64 the swap never runs,- # so the variable would do nothing at all. -X64Only is Install-X64Python's own lookup- # and is never the place to honour it.- $preferArm64 = (-not $X64Only) -and (- $script:WoaNativeCudaTorch -or- ((Get-HostMachineArch) -eq "arm64" -and (Test-Arm64PythonOptOut))- )- $preferX64 = $X64Only -or ((Get-HostMachineArch) -eq "arm64" -and -not $preferArm64)- $rankByArch = $preferX64 -or $preferArm64- $candidates = @()- # Try the Python Launcher first (most reliable on Windows)- # py.exe resolves to the standard CPython install, not conda.- # Prefer the requested $PythonVersion, then newest-first fallback.- $minors = @($PythonVersion) + (@("3.13", "3.12", "3.11") | Where-Object { $_ -ne $PythonVersion })- # -All: Windows PowerShell 5.1 returns only the first launcher without it.- foreach ($pyLauncher in @(Get-Command py -All -CommandType Application -ErrorAction SilentlyContinue)) {- if ($pyLauncher.Source -match $script:CondaSkipPattern) { continue }- foreach ($minor in $minors) {- try {- $out = & $pyLauncher.Source "-$minor" --version 2>&1 | Out-String- if ($out -match "Python ((3\.1[1-3])\.\d+)") {- # Both captures first: Test-IsCondaPython below runs -match- # and overwrites $Matches. Screening the patch here costs no- # extra subprocess (the text is already in hand) and lets the- # loop carry on to the next launcher and the next minor.- $full = $Matches[1]- $ver = $Matches[2]- if ($PythonSkip -contains $full) { continue }- # Resolve the actual executable path and verify it is not conda-based- $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 $rankByArch) { return @{ Version = $ver; Path = $resolvedExe; Arch = "" } }- $candidates += @{ Version = $ver; Path = $resolvedExe }- }- }- } catch {}- }- }- # -All looks past shadowing stubs. Skip WindowsApps (alias stubs) and conda.- foreach ($name in @("python3", "python")) {- foreach ($cmd in @(Get-Command $name -All -ErrorAction SilentlyContinue)) {- if (-not $cmd.Source) { continue }- if ($cmd.Source -like "*\WindowsApps\*") { continue }- if (Test-IsCondaPython $cmd.Source) { continue }- try {- $out = & $cmd.Source --version 2>&1 | Out-String- if ($out -match "Python ((3\.1[1-3])\.\d+)") {- $full = $Matches[1]- $ver = $Matches[2]- if ($PythonSkip -contains $full) { continue }- # 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 $rankByArch) { return @{ Version = $ver; Path = $resolvedExe; Arch = "" } }- $candidates += @{ Version = $ver; Path = $resolvedExe }- }- }- } catch {}- }- }- # `py -3.12` runs the launcher's preferred build, normally the native ARM64 one, so- # a same-minor x64 install that is neither preferred nor on PATH never becomes a- # candidate. `-3.12-64` cannot disambiguate (deprecated, it only means "not- # 32-bit"), so enumerate every registration with -0p and probe each path.- if ($rankByArch) {- foreach ($pyLauncher in @(Get-Command py -All -CommandType Application -ErrorAction SilentlyContinue)) {- if ($pyLauncher.Source -match $script:CondaSkipPattern) { continue }- $listed = @()- try { $listed = @(& $pyLauncher.Source "-0p" 2>$null) } catch {}- foreach ($line in $listed) {- # " -V:3.12 * C:\...\python.exe": tag, optional default marker, path.- $m = [regex]::Match([string]$line, '(?i)^\s*-\S+\s+\*?\s*"?(?<p>\S.*?\.exe)"?\s*$')- if (-not $m.Success) { continue }- $exe = $m.Groups['p'].Value.Trim()- if ($candidates | Where-Object { $_.Path -eq $exe }) { continue }- if (-not (Test-Path -LiteralPath $exe)) { continue }- if (Test-IsCondaPython $exe) { continue }- try {- $out = & $exe --version 2>&1 | Out-String- if ($out -match "Python ((3\.1[1-3])\.\d+)") {- $full = $Matches[1]- $ver = $Matches[2]- if ($PythonSkip -contains $full) { continue }- $candidates += @{ Version = $ver; Path = $exe }- }- } catch {}- }- }- }- # Prefer x64, but only within one minor: $minors is the caller's version preference,- # so ranking on arch alone would answer UNSLOTH_PYTHON=3.12 with an x64 3.13 and- # never bootstrap x64 3.12. Probing costs a subprocess, so non-ARM returned above.- foreach ($c in $candidates) {- $tag = Get-PythonPlatformTag $c.Path- $c.Arch = if ($tag -eq "win-amd64") { "x86_64" } elseif ($tag -eq "win-arm64") { "arm64" } else { "unknown" }- }- # The per-minor loop answers the VERSION preference first, so with x64 3.13 and- # ARM64 3.12 installed the opt-out still produced an x64 environment. Sweep every- # supported minor for an ARM64 build first, then fall through.- if ($preferArm64) {- foreach ($minor in $minors) {- $arm = $candidates |- Where-Object { $_.Version -eq $minor -and $_.Arch -eq "arm64" } |- Select-Object -First 1- if ($arm) { return $arm }- }- }- foreach ($minor in $minors) {- $sameMinor = @($candidates | Where-Object { $_.Version -eq $minor })- if ($sameMinor.Count -eq 0) { continue }- if ($preferArm64) {- # x64 is still returned when no ARM64 build exists; the torch step re-checks the tag.- $arm = $sameMinor | Where-Object { $_.Arch -eq "arm64" } | Select-Object -First 1- if ($arm) { return $arm }- return $sameMinor[0]- }- $x64 = $sameMinor | Where-Object { $_.Arch -eq "x86_64" } | Select-Object -First 1- if ($x64) { return $x64 }- if (-not $X64Only) { return $sameMinor[0] }- }- if (-not $X64Only -and $candidates.Count -gt 0) { return $candidates[0] }- return $null- }-- # Which PATH switch the python.org installer gets. PrependPath=1 puts the interpreter at- # the FRONT of the User PATH, which inside an active conda environment permanently- # demotes conda's own entries (#5871). AppendPath registers it just as well.- function Get-PythonInstallerPathSwitch {- if (Test-ActiveCondaEnvironment) { return "AppendPath=1" }- return "PrependPath=1"- }-- # ── Fallback when winget fails (msstore 0x8a15005e): silent per-user python.org, no UAC. ──- function Install-PythonFromPythonOrg {- # $Arch overrides the host arch, to pull x64 onto an ARM64 box.- param([string]$Arch = "")- # python.org ships one installer per architecture.- $targetArch = if ($Arch) { $Arch } else { Get-TauriDiagArch }- $archSuffix = switch ($targetArch) {- "x86_64" { "-amd64" }- "arm64" { "-arm64" }- "x86" { "" }- default { $null }- }- if ($null -eq $archSuffix) {- substep "No python.org installer is available for this architecture." "Yellow"- return $null- }-- # The pinned full version applies only to a matching minor, so 3.12 cannot install 3.13.- $full = if ($PythonFallbackFullVersion -like "$PythonVersion.*") { $PythonFallbackFullVersion } else { "$PythonVersion.0" }- try {- $listing = [string](Invoke-RestMethod -Uri "https://www.python.org/ftp/python/" -UseBasicParsing -TimeoutSec 20)- $patches = [regex]::Matches($listing, ([regex]::Escape($PythonVersion) + '\.(\d+)/')) |- ForEach-Object { [int]$_.Groups[1].Value } | Sort-Object -Descending- if ($patches.Count -gt 0) { $full = "$PythonVersion.$($patches[0])" }- } catch {}-- $file = "python-$full$archSuffix.exe"- $url = "https://www.python.org/ftp/python/$full/$file"- $dest = Join-Path ([System.IO.Path]::GetTempPath()) $file- substep "downloading Python $full from python.org..." "Yellow"- try {- Invoke-WebRequest -Uri $url -OutFile $dest -UseBasicParsing- } catch {- substep "python.org download failed: $($_.Exception.Message)" "Yellow"- return $null- }-- # Same trust boundary as the VC++ runtime in studio/setup.ps1: $full moves per patch- # release, so there is no SHA-256 to pin and the publisher is what we can check.- # Inspection itself can fail (antivirus quarantining the download first), and the- # script-wide 'Stop' would let that escape the function, skipping the $null fallback- # and leaving the executable behind. Unreadable is unverified, so it takes the same- # route as a bad signature.- $sig = $null- try { $sig = Get-AuthenticodeSignature -LiteralPath $dest } catch { $sig = $null }- if ($null -eq $sig -or- $sig.Status -ne [System.Management.Automation.SignatureStatus]::Valid -or- $null -eq $sig.SignerCertificate -or- $sig.SignerCertificate.Subject -notmatch '(^|,\s*)O="?Python Software Foundation"?(,|$)') {- $sigStatus = if ($null -eq $sig) { "could not be read" } else { $sig.Status }- substep "python.org installer is not validly signed by the Python Software Foundation (signature status: $sigStatus); not running it." "Yellow"- Remove-Item -LiteralPath $dest -Force -ErrorAction SilentlyContinue- return $null- }-- # Per-user install => no UAC. The PATH switch puts python + py on PATH;- # Include_launcher installs py.exe (preferred by Find-CompatiblePython).- substep "installing Python $full (silent, per-user)..."- $installArgs = @(- "/quiet",- "InstallAllUsers=0",- (Get-PythonInstallerPathSwitch),- "Include_launcher=1",- # Launcher per-user too: Include_launcher defaults to all-users, which needs admin.- "InstallLauncherAllUsers=0",- "Include_pip=1",- "AssociateFiles=0",- "Shortcuts=0"- )- $rc = 1- try {- $proc = Start-Process -FilePath $dest -ArgumentList $installArgs -Wait -PassThru- $rc = $proc.ExitCode- } catch {- substep "python.org installer failed to start: $($_.Exception.Message)" "Yellow"- } finally {- Remove-Item -LiteralPath $dest -Force -ErrorAction SilentlyContinue- }- if ($rc -ne 0) {- substep "python.org installer exited with code $rc." "Yellow"- }- Refresh-SessionPath- return (Find-CompatiblePython)- }-- # Backstop for the screen inside Find-CompatiblePython, for an interpreter that- # reports one version to --version and another to sys.version_info (a wrapper or- # a shim). Returning $null sends the caller down the install path, which pins- # $PythonFallbackFullVersion.- function Remove-SkippedPython {- param($Candidate)- if (-not $Candidate) { return $null }- try {- $raw = (& $Candidate.Path -c "import sys; print('{}.{}.{}'.format(*sys.version_info[:3]))" 2>$null | Select-Object -First 1)- } catch {- return $Candidate # unreadable: not evidence of a bad version- }- if ($raw -and ($PythonSkip -contains $raw.Trim())) {- substep "Python $($raw.Trim()) cannot import torch -- installing another." "Yellow"- return $null- }- return $Candidate- }-- # ── Windows on ARM: get an x64 CPython ──- # --architecture x64 forces winget off the ARM64 build; python.org takes the same override.- function Install-X64Python {- # python.org first inside conda, same as the generic bootstrap below: winget's Python- # package hard-codes PrependPath=1 and offers no switch to ask otherwise, so a winget- # install recreates #5871. winget stays the fallback: no x64 Python at all is a STOP.- $pythonOrgTried = $false- if (Test-ActiveCondaEnvironment) {- substep "conda environment active ($env:CONDA_PREFIX) -- installing x64 Python from python.org, which can be installed without taking PATH priority." "Yellow"- $pythonOrgTried = $true- $found = Install-PythonFromPythonOrg -Arch "x86_64"- if ($found -and $found.Arch -eq "x86_64") { return $found }- if ($script:WingetAvailable) {- substep "python.org could not provide an x64 Python -- falling back to winget, whose package always puts Python ahead of conda on PATH." "Yellow"- }- }- if ($script:WingetAvailable) {- $prevEAP = $ErrorActionPreference- $ErrorActionPreference = "Continue"- try {- & $script:WingetExe install -e --id "Python.Python.$PythonVersion" --source winget --architecture x64 --accept-package-agreements --accept-source-agreements- } catch { }- $ErrorActionPreference = $prevEAP- Refresh-SessionPath- $found = Find-CompatiblePython- if ($found -and $found.Arch -eq "x86_64") { return $found }- substep "winget could not provide an x64 Python -- trying python.org..." "Yellow"- }- # $pythonOrgTried, so an offline box inside conda does not sit through the same- # failing download twice.- if (-not $pythonOrgTried) {- $found = Install-PythonFromPythonOrg -Arch "x86_64"- if ($found -and $found.Arch -eq "x86_64") { return $found }- }- # Nothing installable (offline / no winget): an x64 build of another supported minor- # still runs the wheels ARM64 cannot, so take it over the native interpreter.- return (Find-CompatiblePython -X64Only)- }-# "I want the native ARM64 interpreter." One reader, because both places that would# otherwise replace an ARM64 environment have to agree: the fresh selection and the# mismatch re-check on a migrated venv. Read at each site, not captured.@@ -6939,79 +6649,8 @@ exit 0return ($env:UNSLOTH_ALLOW_ARM64_PYTHON -in @('1', 'true', 'yes', 'on'))}- # ── Windows on ARM: the interpreter handed to uv has to be x64 ──- # PyPI has no win_arm64 pyarrow (via datasets) or hf-transfer, so a native ARM64- # interpreter source-builds both and dies minutes in (#8495). $null means this host- # cannot be served, which is a STOP rather than a warning (#10875).- # UNSLOTH_ALLOW_ARM64_PYTHON=1 opts out.- function Resolve-WindowsOnArmX64Python {- param($SelectedPython)- if (-not $SelectedPython) { return $null }- # Read BEFORE the x64 install is attempted, or the variable does nothing on the- # machines where that install succeeds. ARM64 only: discovery reports 32-bit `win32`- # and probe-failed "unknown" interpreters as "not x64" too.- if ((Test-Arm64PythonOptOut) -and ($SelectedPython.Arch -eq "arm64")) {- Write-StudioLine "[WARN] UNSLOTH_ALLOW_ARM64_PYTHON is set, so keeping native ARM64 Python $($SelectedPython.Version)." -ForegroundColor Yellow- Write-StudioLine " pyarrow (via datasets) and hf-transfer publish no win_arm64 wheels, so they will be" -ForegroundColor Yellow- Write-StudioLine " built from source, which needs CMake plus the MSVC and Rust toolchains." -ForegroundColor Yellow- Write-StudioLine " Unset UNSLOTH_ALLOW_ARM64_PYTHON to have x64 Python installed and used instead." -ForegroundColor Yellow- return $SelectedPython- }- substep "windows on arm: only a native ARM64 Python $($SelectedPython.Version) was found." "Yellow"- substep "pyarrow and hf-transfer publish no win_arm64 wheels, so installing x64 Python..." "Yellow"- $X64Python = Install-X64Python- if ($X64Python) {- step "python" "using x64 Python $($X64Python.Version) under emulation"- return $X64Python- }- Write-StudioLine "[ERROR] Could not install an x64 Python on this ARM64 machine." -ForegroundColor Red- Write-StudioLine " pyarrow (via datasets) and hf-transfer ship no win_arm64 wheels, so an install" -ForegroundColor Yellow- Write-StudioLine " on ARM64 Python $($SelectedPython.Version) fails while building them from source." -ForegroundColor Yellow- Write-StudioLine " Fix: install x64 Python from https://www.python.org/downloads/windows/" -ForegroundColor Yellow- Write-StudioLine " (choose 'Windows installer (64-bit)', not ARM64), then re-run this installer." -ForegroundColor Yellow- Write-StudioLine " To attempt the install on ARM64 Python anyway, with CMake, MSVC and Rust" -ForegroundColor Yellow- Write-StudioLine " already installed, set UNSLOTH_ALLOW_ARM64_PYTHON=1." -ForegroundColor Yellow- return $null- }-- function Get-StudioVenvBasePython {- param([Parameter(Mandatory = $true)][string]$VenvDir)- # The ARM64 interpreter the EXISTING environment was built from, for when the machine- # registers none of its own: the selection can only prefer what discovery sees, so- # the opt-out would rebuild on x64 anyway. pyvenv.cfg still names it. Read before the- # reinstall moves the environment aside.- $cfg = Join-Path $VenvDir "pyvenv.cfg"- if (-not (Test-Path -LiteralPath $cfg -PathType Leaf)) { return $null }- $venvHome = $null- $baseExe = $null- foreach ($line in @(Get-Content -LiteralPath $cfg -ErrorAction SilentlyContinue)) {- if ($line -match '^\s*home\s*=\s*(.+?)\s*$') { $venvHome = $Matches[1] }- elseif ($line -match '^\s*base-executable\s*=\s*(.+?)\s*$') { $baseExe = $Matches[1] }- }- # base-executable names the interpreter exactly; home is its directory, which is what- # a venv built by an older Python records on its own.- $candidates = @()- if ($baseExe) { $candidates += $baseExe }- if ($venvHome) { $candidates += (Join-Path $venvHome "python.exe") }- foreach ($exe in $candidates) {- if (-not $exe) { continue }- if (-not (Test-Path -LiteralPath $exe -PathType Leaf)) { continue }- if (Test-IsCondaPython $exe) { continue }- # ARM64 and a supported minor only: anything not provably native is no better- # than the x64 selection it would replace.- if ((Get-PythonPlatformTag $exe) -ne "win-arm64") { continue }- $out = (& $exe --version 2>&1 | Out-String)- if ($out -notmatch "Python ((3\.1[1-3])\.\d+)") { continue }- $full = $Matches[1]- $ver = $Matches[2]- if ($PythonSkip -contains $full) { continue }- return @{ Version = $ver; Path = $exe; Arch = "arm64" }- }- return $null- }-- # Does an environment we are about to REUSE still match the interpreter we chose? The- # swap above only changes a FRESH selection, so a migrated venv keeps whatever built it,+ # Does an environment we are about to REUSE still match the interpreter we chose? A+ # migrated venv keeps whatever built it,# which on Windows on ARM is native ARM64 CPython (#8495, #10875). True only with an x64# interpreter in hand, so a host served by native ARM64 wheels is left alone.function Test-StudioVenvArchMismatch {@@ -7033,9 +6672,7 @@ exit 0# Asked before the opt-out, so the message below is only printed when there really is# a native ARM64 environment to keep.if ($tag -ne "win-arm64") { return $false }- # Honoured HERE too: Resolve-WindowsOnArmX64Python never runs when the ordinary probe- # already found x64, so on a host with both interpreters this branch would otherwise- # replace the very ARM64 environment the user asked to keep.+ # Honoured here too, or a migrated ARM64 environment the user asked to keep is replaced.if (Test-Arm64PythonOptOut) {# Two outcomes, so two sentences: with an ARM64 interpreter the environment is# really not rebuilt on x64, and with none the reinstall has already moved the@@ -7052,193 +6689,53 @@ exit 0return $true}- # ── Install Python if no compatible version (3.11-3.13) found ──- Write-TauriLog "STEP" "Installing Python"- Initialize-WoaNativeCudaTorch -PythonMinor $PythonVersion- if ($script:WoaNativeCudaTorch) {- step "gpu" "Windows on ARM + NVIDIA: native CUDA wheels available -- installing the ARM64 stack" "Green"- substep "torch index: $(Remove-IndexUrlCredentials $script:WoaTorchIndexUrl)"- }- $DetectedPython = Remove-SkippedPython (Find-CompatiblePython)-- # No usable interpreter: uv provides one once it is installed below, instead of a- # system-wide winget / python.org install (#7802). Windows on ARM keeps the system- # install, whose x64-vs-ARM64 choice the steps below depend on.- $PythonFromUv = (-not $DetectedPython) -and ((Get-HostMachineArch) -ne "arm64")- if ($DetectedPython) {- step "python" "Python $($DetectedPython.Version) already installed"- } elseif ($PythonFromUv) {- step "python" "no Python 3.11-3.13 found; uv will provide Python $PythonVersion"- }- # Dot-sourced so $DetectedPython lands in this scope; also the fallback when uv cannot.- $InstallSystemPython = {- substep "installing Python ${PythonVersion}..."- $pythonPackageId = "Python.Python.$PythonVersion"- $wingetExit = $null-- # winget's Python package hard-codes PrependPath=1 with no switch to ask otherwise,- # so inside conda take the python.org route first, where we choose the switch. winget- # stays the fallback: a failed install is worse than a PATH we warn about.- $pythonOrgTried = $false- if (Test-ActiveCondaEnvironment) {- substep "conda environment active ($env:CONDA_PREFIX) -- installing Python from python.org, which can be installed without taking PATH priority." "Yellow"- $pythonOrgTried = $true- $DetectedPython = Install-PythonFromPythonOrg- if (-not $DetectedPython -and $script:WingetAvailable) {- substep "python.org could not provide Python -- falling back to winget, whose package always puts Python ahead of conda on PATH." "Yellow"- }- }-- if ($script:WingetAvailable -and -not $DetectedPython) {- # --source winget avoids msstore, whose cert-pinning (0x8a15005e) can abort the install.- $prevEAP = $ErrorActionPreference- $ErrorActionPreference = "Continue"- try {- & $script:WingetExe install -e --id $pythonPackageId --source winget --accept-package-agreements --accept-source-agreements- $wingetExit = $LASTEXITCODE- } catch { $wingetExit = 1 }- $ErrorActionPreference = $prevEAP- Refresh-SessionPath-- # Re-detect after install (PATH may have changed)- $DetectedPython = Remove-SkippedPython (Find-CompatiblePython)-- if (-not $DetectedPython) {- # Covers real failures and "already installed" codes where Python is not on PATH.- substep "Python not found on PATH after winget. Retrying with --force..." "Yellow"- $ErrorActionPreference = "Continue"- try {- & $script:WingetExe install -e --id $pythonPackageId --source winget --accept-package-agreements --accept-source-agreements --force- $wingetExit = $LASTEXITCODE- } catch { $wingetExit = 1 }- $ErrorActionPreference = $prevEAP- Refresh-SessionPath- $DetectedPython = Remove-SkippedPython (Find-CompatiblePython)- }+ # uv writes version_info to pyvenv.cfg, the stdlib venv writes version.+ function Get-StudioVenvPythonMinor {+ param([Parameter(Mandatory = $true)][string]$VenvDir)+ $cfg = Join-Path $VenvDir "pyvenv.cfg"+ if (-not (Test-Path -LiteralPath $cfg -PathType Leaf)) { return $null }+ foreach ($line in @(Get-Content -LiteralPath $cfg -Encoding UTF8 -ErrorAction SilentlyContinue)) {+ if ($line -match '^\s*version(_info)?\s*=\s*(3\.1[1-3])\.\d+') { return $Matches[2] }}+ return $null+ }- # $pythonOrgTried, so an offline box inside conda does not sit through the same- # failing download twice and then read "falling back to python.org" for a fallback- # that already ran.- if (-not $DetectedPython -and -not $pythonOrgTried) {- if ($script:WingetAvailable) {- substep "winget could not install Python -- falling back to python.org..." "Yellow"- } else {- substep "winget is unavailable -- installing Python from python.org..." "Yellow"- }- $DetectedPython = Install-PythonFromPythonOrg- }-- if (-not $DetectedPython) {- $exitNote = if ($null -ne $wingetExit) { " (winget exit code $wingetExit)" } else { "" }- Write-StudioLine "[ERROR] Python installation failed$exitNote" -ForegroundColor Red- Write-StudioLine " Please install Python $PythonVersion manually from https://www.python.org/downloads/" -ForegroundColor Yellow- Write-StudioLine " Make sure to check 'Add Python to PATH' during installation." -ForegroundColor Yellow- Write-StudioLine " Then re-run this installer." -ForegroundColor Yellow- }- }- if (-not $DetectedPython -and -not $PythonFromUv) {- . $InstallSystemPython- if (-not $DetectedPython) { return (Exit-InstallFailure "Python installation failed") }- }- # Re-probe for the interpreter actually selected: every native decision is keyed to a cp3XX tag.- $WoaProbedMinor = $PythonVersion- $WoaProbedFreeThreaded = $false- $WoaDetectedFreeThreaded = $false- if ($DetectedPython -and (Get-HostMachineArch) -eq "arm64") {- $WoaDetectedFreeThreaded = Test-PythonFreeThreaded -PythonExe $DetectedPython.Path- }- if ($DetectedPython -and (- ($DetectedPython.Version -ne $WoaProbedMinor) -or- ($WoaDetectedFreeThreaded -ne $WoaProbedFreeThreaded))) {- $WoaNativeBeforeReprobe = $script:WoaNativeCudaTorch- $WoaProbedMinor = $DetectedPython.Version- $WoaProbedFreeThreaded = $WoaDetectedFreeThreaded- Initialize-WoaNativeCudaTorch -PythonMinor $DetectedPython.Version `- -FreeThreaded $WoaDetectedFreeThreaded- if ($script:WoaNativeCudaTorch -ne $WoaNativeBeforeReprobe) {- $ReselectedPython = Remove-SkippedPython (Find-CompatiblePython)- if ($ReselectedPython) {- # The reselection can hand back an interpreter the probe has not answered for, so that one is probed too; when it has no stack the probe's interpreter is kept and its answer restored.- $_woaReselectedFreeThreaded = $false- if ((Get-HostMachineArch) -eq "arm64") {- $_woaReselectedFreeThreaded = Test-PythonFreeThreaded -PythonExe $ReselectedPython.Path- }- if (($ReselectedPython.Version -ne $WoaProbedMinor) -or- ($_woaReselectedFreeThreaded -ne $WoaProbedFreeThreaded)) {- Initialize-WoaNativeCudaTorch -PythonMinor $ReselectedPython.Version `- -FreeThreaded $_woaReselectedFreeThreaded- if ($script:WoaNativeCudaTorch) {- $WoaProbedMinor = $ReselectedPython.Version- $WoaProbedFreeThreaded = $_woaReselectedFreeThreaded- $DetectedPython = $ReselectedPython- } else {- substep "windows on arm: Python $($ReselectedPython.Version) has no win_arm64 CUDA stack; keeping Python $($DetectedPython.Version), which has one." "Yellow"- Initialize-WoaNativeCudaTorch -PythonMinor $WoaProbedMinor `- -FreeThreaded $WoaProbedFreeThreaded- }- } else {- $DetectedPython = $ReselectedPython- }- }- if ($script:WoaNativeCudaTorch) {- step "gpu" "Windows on ARM + NVIDIA: native CUDA wheels available -- installing the ARM64 stack" "Green"- substep "torch index: $(Remove-IndexUrlCredentials $script:WoaTorchIndexUrl)"- } else {- substep "windows on arm: no win_arm64 CUDA stack for Python $($DetectedPython.Version) -- using the x64 stack." "Yellow"+ # ── uv-managed Python: minor and arch now, the interpreter once uv is installed ──+ Write-TauriLog "STEP" "Installing Python"+ # A reinstall keeps its minor so cached cp3XX wheels (torch) are reused; UNSLOTH_TORCH_UPGRADE=1 moves it.+ if (-not $PythonExplicitRequest -and $env:UNSLOTH_TORCH_UPGRADE -ne '1') {+ $_existingPythonMinor = Get-StudioVenvPythonMinor -VenvDir $VenvDir+ # Legacy layouts keep their minor too (checked in the order they are migrated below).+ if (-not $_existingPythonMinor -and $studioUsesLegacyLayout) {+ $_legacyDirs = @((Join-Path $StudioHome ".venv"))+ if ($env:USERPROFILE) { $_legacyDirs += (Join-Path $env:USERPROFILE "unsloth_studio") }+ foreach ($_legacyDir in $_legacyDirs) {+ $_existingPythonMinor = Get-StudioVenvPythonMinor -VenvDir $_legacyDir+ if ($_existingPythonMinor) { break }}}+ if ($_existingPythonMinor) { $PythonVersion = $_existingPythonMinor }}- # An emulated x64 python cannot load the win_arm64 wheels the probe just found.- if ($script:WoaNativeCudaTorch -and $DetectedPython -and $DetectedPython.Arch -eq "x86_64") {- substep "windows on arm: found an x64 Python $($DetectedPython.Version); installing the native ARM64 build..." "Yellow"- $Arm64Python = Install-PythonFromPythonOrg -Arch "arm64"- if ($Arm64Python -and $Arm64Python.Arch -ne "x86_64") {- $DetectedPython = $Arm64Python- step "python" "using native ARM64 Python $($DetectedPython.Version)"- $_woaNewFreeThreaded = Test-PythonFreeThreaded -PythonExe $DetectedPython.Path- if (($DetectedPython.Version -ne $WoaProbedMinor) -or- ($_woaNewFreeThreaded -ne $WoaProbedFreeThreaded)) {- $WoaProbedMinor = $DetectedPython.Version- $WoaProbedFreeThreaded = $_woaNewFreeThreaded- Initialize-WoaNativeCudaTorch -PythonMinor $DetectedPython.Version `- -FreeThreaded $_woaNewFreeThreaded- if (-not $script:WoaNativeCudaTorch) {- substep "windows on arm: no win_arm64 CUDA stack for Python $($DetectedPython.Version) -- using the x64 stack." "Yellow"- }- }- } else {- substep "could not install a native ARM64 Python; falling back to the x64 stack." "Yellow"- $script:WoaNativeCudaTorch = $false- $script:WoaTorchIndexUrl = $null- }- }- # ── Windows on ARM: the opt-out's last ARM64 interpreter ──- # The selection prefers ARM64 under UNSLOTH_ALLOW_ARM64_PYTHON, but only among the- # interpreters discovery can see. With none left, an x64 one is selected and the native- # environment is rebuilt on it -- exactly what the variable asks against -- so the- # environment's own base interpreter, which pyvenv.cfg still names, is tried first.- if ((Get-HostMachineArch) -eq "arm64" -and (Test-Arm64PythonOptOut) -and- (-not $DetectedPython -or $DetectedPython.Arch -ne "arm64")) {- $ArmBasePython = Get-StudioVenvBasePython -VenvDir $VenvDir- if ($ArmBasePython) {- step "python" "windows on arm: UNSLOTH_ALLOW_ARM64_PYTHON is set and no other ARM64 Python is registered; using the ARM64 Python $($ArmBasePython.Version) the existing environment was built from"- $DetectedPython = $ArmBasePython- }+ # uv's builds are GIL-enabled, which is what this probe assumes.+ Initialize-WoaNativeCudaTorch -PythonMinor $PythonVersion+ if ($script:WoaNativeCudaTorch) {+ step "gpu" "Windows on ARM + NVIDIA: native CUDA wheels available -- installing the ARM64 stack" "Green"+ substep "torch index: $(Remove-IndexUrlCredentials $script:WoaTorchIndexUrl)"}-- # ── Windows on ARM: swap a native ARM64 interpreter for x64 ──- # No x64 interpreter means no install, so this stops rather than warning: see- # Resolve-WindowsOnArmX64Python.- # Not on a native CUDA torch host: there an ARM64 interpreter is the correct one- # and swapping it away would break sm_121.- if (-not $script:WoaNativeCudaTorch -and- $DetectedPython -and (Get-HostMachineArch) -eq "arm64" -and $DetectedPython.Arch -ne "x86_64") {- $DetectedPython = Resolve-WindowsOnArmX64Python -SelectedPython $DetectedPython- if (-not $DetectedPython) {- return (Exit-InstallFailure "windows on arm: no x64 Python could be installed, and ARM64 Python cannot resolve pyarrow or hf-transfer")+ # Windows on ARM: x64 under emulation unless the native CUDA stack applies (no win_arm64 pyarrow / hf-transfer, #8495).+ $PythonArch = "x86_64"+ if ((Get-HostMachineArch) -eq "arm64" -and ($script:WoaNativeCudaTorch -or (Test-Arm64PythonOptOut))) {+ $PythonArch = "arm64"+ if (-not $script:WoaNativeCudaTorch) {+ Write-StudioLine "[WARN] UNSLOTH_ALLOW_ARM64_PYTHON is set, so using native ARM64 Python $PythonVersion." -ForegroundColor Yellow+ Write-StudioLine " pyarrow (via datasets) and hf-transfer publish no win_arm64 wheels, so they will be" -ForegroundColor Yellow+ Write-StudioLine " built from source, which needs CMake plus the MSVC and Rust toolchains." -ForegroundColor Yellow+ Write-StudioLine " Unset UNSLOTH_ALLOW_ARM64_PYTHON to use x64 Python instead." -ForegroundColor Yellow}}+ $PythonRequestLabel = if ($PythonPatchRequest) { $PythonPatchRequest } else { $PythonVersion }+ step "python" "uv will provide Python $PythonRequestLabel ($PythonArch); a Python already on this machine is not used"+ $DetectedPython = $null$DiagPythonVersion = $PythonVersionif ($DetectedPython) { $DiagPythonVersion = $DetectedPython.Version }@@ -7608,51 +7105,105 @@ exit 0$env:UV_HTTP_TIMEOUT = "180"}- # --no-bin / --no-registry: only uv's own Python store changes, nothing on PATH or in- # the py launcher. --system: `find` otherwise answers with an active venv's python.- # $null sends the caller to the system install.+ # --no-bin / --no-registry leave PATH and the py launcher alone; --system skips an active venv;+ # --managed-python never returns an interpreter uv did not install.function Resolve-UvManagedPython {- # A range excluding $PythonSkip, as install.sh's _python_request: a bare "3.13" can- # resolve to 3.13.8, and a pinned patch may be newer than this uv knows or a cached one.- $request = $PythonVersion- $bad = @($PythonSkip | Where-Object { $_ -like "$PythonVersion.*" })- if ($bad.Count -gt 0 -and $PythonVersion -match '^(\d+)\.(\d+)$') {- $request = ">=$PythonVersion,<$($Matches[1]).$([int]$Matches[2] + 1)" + (($bad | ForEach-Object { ",!=$_" }) -join "")+ param([string]$Minor, [string]$Patch = "", [string]$Arch = "x86_64")+ $uvArch = if ($Arch -eq "arm64") { "aarch64" } else { "x86_64" }+ $wantTag = if ($Arch -eq "arm64") { "win-arm64" } else { "win-amd64" }+ # Arch-qualified keys take no range: past a skipped patch try the next, then an older (cached) one.+ $queue = [System.Collections.Generic.List[string]]::new()+ $queue.Add($(if ($Patch) { $Patch } else { $Minor }))+ $tried = @{}+ while ($queue.Count -gt 0 -and $tried.Count -lt 5) {+ $version = $queue[0]+ $queue.RemoveAt(0)+ if ($tried.ContainsKey($version)) { continue }+ $tried[$version] = $true+ $key = "cpython-$version-windows-$uvArch-none"+ $null = Invoke-InstallCommand -NoMirror -Label "install uv-managed Python $key" {+ & $script:UvExe python install --no-bin --no-registry $key+ }+ # Asked even when the install failed: a runtime installed earlier serves an offline machine.+ $exe = ""+ try {+ $exe = (& $script:UvExe python find --system --managed-python $key 2>$null | Select-Object -First 1)+ } catch {}+ $exe = "$exe".Trim()+ if (-not $exe -or -not (Test-Path -LiteralPath $exe -PathType Leaf)) { continue }+ $facts = ""+ try {+ $facts = (& $exe -S -I -c "import sys, sysconfig; print('{}.{}.{}'.format(*sys.version_info[:3]), sysconfig.get_platform(), int(bool(sysconfig.get_config_var('Py_GIL_DISABLED'))))" 2>$null | Select-Object -First 1)+ } catch {}+ $parts = @("$facts".Trim() -split '\s+')+ if ($parts.Count -ne 3) { return $null }+ $full = $parts[0]+ if ($full -notlike "$Minor.*" -or $parts[1].ToLowerInvariant() -ne $wantTag -or $parts[2] -ne "0") { return $null }+ if ($Patch -and $full -ne $Patch) { return $null }+ if ($PythonSkip -notcontains $full) {+ return @{ Version = $Minor; Full = $full; Path = $exe; Arch = $Arch }+ }+ if ($Patch) { return $null }+ $skipped = [int]($full.Split('.')[2])+ foreach ($n in @(($skipped + 1), ($skipped - 1), ($skipped + 2), ($skipped - 2))) {+ if ($n -ge 0) { $queue.Add("$Minor.$n") }+ }}- $installExit = Invoke-InstallCommand -NoMirror -Label "install uv-managed Python $request" {- & $script:UvExe python install --no-bin --no-registry $request+ return $null+ }++ # Reuse a legacy environment only on uv's store and the resolved Python (exact patch if requested).+ function Test-LegacyVenvReusable {+ param([Parameter(Mandatory = $true)][string]$VenvDir, $Python, [bool]$Exact = $false)+ $cfg = Join-Path $VenvDir "pyvenv.cfg"+ if (-not $Python -or -not (Test-Path -LiteralPath $cfg -PathType Leaf)) { return $false }+ $venvHome = $null+ $venvVersion = $null+ # uv writes pyvenv.cfg as UTF-8 without a BOM; Windows PowerShell 5.1 would read it as ANSI.+ foreach ($line in @(Get-Content -LiteralPath $cfg -Encoding UTF8 -ErrorAction SilentlyContinue)) {+ if ($line -match '^\s*home\s*=\s*(.+?)\s*$') { $venvHome = $Matches[1] }+ elseif ($line -match '^\s*version(_info)?\s*=\s*(\d+\.\d+\.\d+)') { $venvVersion = $Matches[2] }+ }+ if (-not $venvHome -or -not $venvVersion) { return $false }+ # uv names each build's directory cpython-<version>-windows-<arch>-none.+ $wantArch = if ($Python.Arch -eq "arm64") { "aarch64" } else { "x86_64" }+ if ((Split-Path -Leaf $venvHome.TrimEnd('\', '/')) -notmatch "-windows-$wantArch-") { return $false }+ if ($Exact) {+ if ($venvVersion -ne $Python.Full) { return $false }+ } elseif ($venvVersion -notlike "$($Python.Version).*") {+ return $false}- if ($installExit -ne 0) { return $null }- $exe = ""- try {- $exe = (& $script:UvExe python find --system --managed-python $request 2>$null | Select-Object -First 1)- } catch {}- $exe = "$exe".Trim()- if (-not $exe -or -not (Test-Path -LiteralPath $exe -PathType Leaf)) { return $null }- # -S: a sitecustomize banner would otherwise be read as the version.- $full = ""+ $store = ""+ try { $store = (& $script:UvExe python dir 2>$null | Select-Object -First 1) } catch {}+ $store = "$store".Trim()+ if (-not $store) { return $false }try {- $full = (& $exe -S -c "import sys; print('{}.{}.{}'.format(*sys.version_info[:3]))" 2>$null | Select-Object -First 1)- } catch {}- $full = "$full".Trim()- if ($full -notmatch '^(3\.1[1-3])\.\d+$') { return $null }- $minor = $Matches[1]- # find answers through uv's per-minor link, which can still name a skipped patch.- if ($PythonSkip -contains $full) { return $null }- return @{ Version = $minor; Path = $exe; Arch = "" }- }-- if ($PythonFromUv) {- $DetectedPython = Resolve-UvManagedPython- if ($DetectedPython) {- step "python" "using uv-managed Python $($DetectedPython.Version)"- } else {- substep "uv could not provide Python $PythonVersion -- installing it system-wide instead." "Yellow"- . $InstallSystemPython- if (-not $DetectedPython) { return (Exit-InstallFailure "Python installation failed") }- }+ $sep = [System.IO.Path]::DirectorySeparatorChar+ $venvHome = [System.IO.Path]::GetFullPath($venvHome).TrimEnd('\', '/') + $sep+ $store = [System.IO.Path]::GetFullPath($store).TrimEnd('\', '/') + $sep+ } catch { return $false }+ return $venvHome.StartsWith($store, [System.StringComparison]::OrdinalIgnoreCase)}+ $DetectedPython = Resolve-UvManagedPython -Minor $PythonVersion -Patch $PythonPatchRequest -Arch $PythonArch+ if (-not $DetectedPython -and $PythonArch -eq "arm64" -and -not (Test-Arm64PythonOptOut)) {+ substep "could not get a native ARM64 Python; falling back to the x64 stack." "Yellow"+ $script:WoaNativeCudaTorch = $false+ $script:WoaTorchIndexUrl = $null+ $PythonArch = "x86_64"+ $DetectedPython = Resolve-UvManagedPython -Minor $PythonVersion -Patch $PythonPatchRequest -Arch $PythonArch+ }+ if (-not $DetectedPython) {+ $_uvArchKey = if ($PythonArch -eq "arm64") { "aarch64" } else { "x86_64" }+ Write-StudioLine "[ERROR] uv could not provide Python $PythonRequestLabel ($PythonArch)." -ForegroundColor Red+ Write-StudioLine " Unsloth Studio always runs on its own uv-managed Python, never one already installed." -ForegroundColor Yellow+ Write-StudioLine " Offline, or downloads blocked: point UV_PYTHON_INSTALL_MIRROR at a python-build-standalone" -ForegroundColor Yellow+ Write-StudioLine " mirror, or run 'uv python install cpython-$PythonRequestLabel-windows-$_uvArchKey-none' once while online," -ForegroundColor Yellow+ Write-StudioLine " then re-run this installer. Your existing environment was not changed." -ForegroundColor Yellow+ return (Exit-InstallFailure "uv could not provide Python $PythonRequestLabel ($PythonArch)")+ }+ step "python" "using uv-managed Python $($DetectedPython.Full) ($($DetectedPython.Arch))"+# ── Create the venv; hand uv the resolved exe path so it does not re-resolve back to conda. ──Write-TauriLog "STEP" "Creating virtual environment"Write-StudioRootOwnerMarker -Root $StudioHome@@ -8252,7 +7803,9 @@ exit 0$legacyOk = ($LASTEXITCODE -eq 0)} catch { $legacyOk = $false }$ErrorActionPreference = $prevEAP2- if ($legacyOk) {+ if ($legacyOk -and -not (Test-LegacyVenvReusable -VenvDir $OldVenv -Python $DetectedPython -Exact ([bool]$PythonPatchRequest))) {+ substep "legacy environment is not on the uv-managed Python $($DetectedPython.Full) -- creating a fresh environment; the old one stays at $OldVenv" "Yellow"+ } elseif ($legacyOk) {substep "legacy environment is healthy -- migrating..."try {Clear-MigrationTargetDirectory -Path $VenvDir@@ -8275,16 +7828,20 @@ exit 0# CWD-relative venv from old install.ps1 -> migrate to absolute path.# Skip custom-root env-mode so it is not relocated into a workspace root.$CwdVenv = Join-Path $env:USERPROFILE "unsloth_studio"- substep "found CWD-relative Unsloth environment, migrating to $VenvDir..."- try {- Clear-MigrationTargetDirectory -Path $VenvDir- } catch {- Write-StudioLine "[ERROR] $($_.Exception.Message)" -ForegroundColor Red- return (Exit-InstallFailure "Could not clear $VenvDir for the environment migration")+ if (-not (Test-LegacyVenvReusable -VenvDir $CwdVenv -Python $DetectedPython -Exact ([bool]$PythonPatchRequest))) {+ substep "found a CWD-relative Unsloth environment not on the uv-managed Python $($DetectedPython.Full) -- creating a fresh environment; the old one stays at $CwdVenv" "Yellow"+ } else {+ substep "found CWD-relative Unsloth environment, migrating to $VenvDir..."+ try {+ Clear-MigrationTargetDirectory -Path $VenvDir+ } catch {+ Write-StudioLine "[ERROR] $($_.Exception.Message)" -ForegroundColor Red+ return (Exit-InstallFailure "Could not clear $VenvDir for the environment migration")+ }+ Move-Item -LiteralPath $CwdVenv -Destination $VenvDir -Force+ substep "moved ~/unsloth_studio -> ~/.unsloth/studio/unsloth_studio"+ $_Migrated = $true}- Move-Item -LiteralPath $CwdVenv -Destination $VenvDir -Force- substep "moved ~/unsloth_studio -> ~/.unsloth/studio/unsloth_studio"- $_Migrated = $true}# Re-check what is about to be REUSED, not only what was selected: see@@ -8347,12 +7904,8 @@ exit 0$_Migrated = $false}- # The opt-out has to keep something, or it only changes the wording. On a host that- # already has an x64 Python, Find-CompatiblePython picks it and the ordinary reinstall- # has already moved the ARM64 environment into a rollback that success would delete, so- # "not rebuilt on x64" would have been true of the message and of nothing else. The tree- # is kept, under the same unsloth_studio.arm64.* name the rebuild branch uses, and the- # user is told where it is and how to go back to it.+ # The reinstall already moved the ARM64 environment into a rollback success would delete, so+ # the opt-out keeps it as unsloth_studio.arm64.*.if ($script:PrevVenvPlatformTag -eq "win-arm64" -and (Test-Arm64PythonOptOut) -and$script:StudioVenvRollbackActive) {$script:StudioVenvRollbackPreserve = $truediff --git a/tests/python/test_installer_conda_path_guard.py b/tests/python/test_installer_conda_path_guard.pyindex ff1604b3868..178940f1c35 100644--- a/tests/python/test_installer_conda_path_guard.py+++ b/tests/python/test_installer_conda_path_guard.py@@ -175,53 +175,6 @@ def test_the_two_installers_agree_on_the_guard(path_label: str):assert "CONDA_DEFAULT_ENV" in conda[email protected](not POWERSHELLS, reason = "PowerShell is unavailable")[email protected]("shell", POWERSHELLS)- "env,expected",- [(_NO_CONDA, "PrependPath=1"), (_ACTIVE_CONDA, "AppendPath=1"), (_EMPTY, "PrependPath=1")],- ids = ["no-conda", "active-conda", "empty-vars"],-)-def test_the_system_python_install_follows_the_same_rule(- shell: str, env: dict[str, str], expected: str-):- """The reporter's own diagnosis was the system-wide Python, not our own directories."""- script = (- _function(INSTALL_PS1, " ", "Test-ActiveCondaEnvironment")- + _function(INSTALL_PS1, " ", "Get-PythonInstallerPathSwitch")- + "\nWrite-Host ('SWITCH=' + (Get-PythonInstallerPathSwitch))\n"- )- out = _run(shell, script, env = env)- assert f"SWITCH={expected}" in out---def test_the_python_org_installer_arguments_use_the_switch_function():- """A literal PrependPath=1 in the argument list would bypass the decision entirely."""- source = INSTALL_PS1.read_text(encoding = "utf-8")- args = re.search(r"\$installArgs = @\(.*?\n \)", source, flags = re.DOTALL)- assert args is not None, "install.ps1 no longer builds $installArgs for python.org"- block = args.group(0)- assert "Get-PythonInstallerPathSwitch" in block- assert (- "PrependPath" not in block- ), "the PATH switch has to come from Get-PythonInstallerPathSwitch, not be spelled here"---def test_winget_is_not_the_first_route_inside_an_active_conda_environment():- """winget's Python package hard-codes PrependPath=1, so it cannot be asked politely."""- source = INSTALL_PS1.read_text(encoding = "utf-8")- start = source.index('substep "installing Python ${PythonVersion}..."')- conda_first = source.index("if (Test-ActiveCondaEnvironment)", start)- winget = source.index("if ($script:WingetAvailable", start)- assert conda_first < winget, "the conda-safe route has to be attempted before winget"- # And the winget arm must now respect an interpreter the conda route already found.- arm = source[winget : source.index("\n", winget)]- assert "-not $DetectedPython" in arm, (- "winget would otherwise install a second Python over the one just installed, with "- "PrependPath=1, undoing the guard"- )--@pytest.mark.parametrize("path,funcs",[diff --git a/tests/python/test_windows_arm64_python_choice.py b/tests/python/test_windows_arm64_python_choice.pydeleted file mode 100644index 21db862c301..00000000000--- a/tests/python/test_windows_arm64_python_choice.py+++ /dev/null@@ -1,320 +0,0 @@-# SPDX-License-Identifier: AGPL-3.0-only-# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.--"""Windows on ARM: install.ps1 must not settle for a native ARM64 interpreter.--pyarrow (via datasets) and hf-transfer publish no win_arm64 wheels, so an ARM64-Python source-builds both and dies minutes into the run. The resolver prefers an-x64 build of the requested minor and bootstraps one otherwise; the case pinned-here is the recovery path, where nothing can be downloaded but an x64 build of a-lower-priority supported minor is already installed.-"""--from __future__ import annotations--import os-import re-import shutil-from pathlib import Path--import pytest--from unsloth_pwsh_runner import run_pwsh---REPO_ROOT = Path(__file__).resolve().parents[2]-INSTALL_PS1 = REPO_ROOT / "install.ps1"---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 _resolver_script(installed: list[tuple[str, str]], can_download: bool) -> str:- """Both production functions verbatim, over a fake set of interpreters.-- Extracted rather than reimplemented so the test cannot drift away from the- text install.ps1 actually runs. `installed` is (minor, arch) in py-launcher- order, so the first entry for a minor is what a bare `py -3.13` resolves to.- The fake interpreters are named `*.exe` and invoked through the call operator,- which resolves a string to a function, so no real binary is needed.- """- source = INSTALL_PS1.read_text(encoding = "utf-8")- finder = _extract(r" function Find-CompatiblePython \{.*?\n \}\n", source)- installer = _extract(r" function Install-X64Python \{.*?\n \}\n", source)- # The selection consults the ARM64 opt-out, so the real reader comes with it rather than- # a stub: a stub is a second copy of the thing under test, and without it the extracted- # function calls a command this scope does not have and the whole run aborts.- opt_out = _extract(r" function Test-Arm64PythonOptOut \{.*?\n \}\n", source)- # `Install-X64Python` asks this before anything else, and without it the extracted- # function aborts on an unknown command -- which is a pwsh error, not a resolver answer,- # so every case that reaches the x64 bootstrap failed for a reason that had nothing to- # do with what it was testing. Extracted too, for the same reason as the rest.- conda_active = _extract(r" function Test-ActiveCondaEnvironment \{.*?\n \}\n", source)-- names = [f"Py{minor.replace('.', '')}{arch}.exe" for minor, arch in installed]- table = ", ".join(- f'@{{ Minor = "{minor}"; Arch = "{arch}"; Name = "{name}" }}'- for (minor, arch), name in zip(installed, names)- )- downloaded = (- '@{ Version = "3.13"; Path = "Downloaded.exe"; Arch = "x86_64" }'- if can_download- else "$null"- )- version_stubs = "\n".join(- f"function {name} {{ param([Parameter(ValueFromRemainingArguments = $true)]$Rest)\n"- f' if ($Rest -contains "--version") {{ return "Python {minor}.0" }}\n'- f' return "{name}" }}'- for (minor, _arch), name in zip(installed, names)- )- return f"""-$ErrorActionPreference = "Stop"-$PythonVersion = "3.13"-$script:WingetAvailable = $false-$script:CondaSkipPattern = 'conda'-$Interpreters = @({table})-{version_stubs}-# `py -0p` lists every registration; `py -3.x` runs the launcher's preferred build-# for that minor, which on an ARM64 host is normally the native one.-function FakePy {{- param([Parameter(ValueFromRemainingArguments = $true)]$Rest)- if ($Rest -contains "-0p") {{- return @($Interpreters | ForEach-Object {{ " -V:$($_.Minor) * $($_.Name)" }})- }}- $minor = ([string]$Rest[0]).TrimStart('-')- $hit = @($Interpreters | Where-Object {{ $_.Minor -eq $minor }})- if ($hit.Count -eq 0) {{ return "" }}- if ($Rest -contains "--version") {{ return "Python $minor.0" }}- return $hit[0].Name-}}-function substep {{ param($a, $b) }}-function Get-HostMachineArch {{ return "arm64" }}-function Get-Command {{- param([Parameter(Position = 0)][string]$Name,- [Parameter(ValueFromRemainingArguments = $true)]$Rest)- if ($Name -eq "py") {{ return @([pscustomobject]@{{ Source = "FakePy" }}) }}- return @()-}}-function Test-Path {{ param([Parameter(ValueFromRemainingArguments = $true)]$Rest) return $true }}-function Test-IsCondaPython {{ param([string]$Exe) return $false }}-function Get-PythonPlatformTag {{- param([string]$Exe)- foreach ($i in $Interpreters) {{- if ($i.Name -eq $Exe) {{- if ($i.Arch -eq "x86_64") {{ return "win-amd64" }}- elseif ($i.Arch -eq "arm64") {{ return "win-arm64" }}- else {{ return $i.Arch }}- }}- }}- return "win-amd64"-}}-function Refresh-SessionPath {{ }}-function Install-PythonFromPythonOrg {{ param([string]$Arch = "") return {downloaded} }}-{opt_out}-{conda_active}-{finder}-{installer}-# The caller's ARM64 swap, condensed to what decides the interpreter.-$found = Find-CompatiblePython-if ($found -and $found.Arch -ne "x86_64") {{- $x64 = Install-X64Python- if ($x64) {{ $found = $x64 }}-}}-if ($found) {{ Write-Output "$($found.Version)|$($found.Arch)" }} else {{ Write-Output "none" }}-"""---def _opt_out_script(installed: list[tuple[str, str]], can_download: bool) -> str:- """The same fakes, but ending in the REAL swap resolver rather than a condensed one.-- UNSLOTH_ALLOW_ARM64_PYTHON is read in two places -- the selection and the swap after it- -- and the cases below are about both, so the swap cannot be a paraphrase here.- """- source = INSTALL_PS1.read_text(encoding = "utf-8")- resolver = _extract(r" function Resolve-WindowsOnArmX64Python \{.*?\n \}\n", source)- base = _resolver_script(installed, can_download)- tail = base.index("# The caller's ARM64 swap")- return base[:tail] + (- "function Write-StudioLine { param([Parameter(ValueFromRemainingArguments = $true)]$Rest) }\n"- "function step { param($a, $b, $c) }\n" + resolver + "\n$found = Find-CompatiblePython\n"- 'if ($found -and $found.Arch -ne "x86_64") { $found = Resolve-WindowsOnArmX64Python $found }\n'- 'if ($found) { Write-Output "$($found.Version)|$($found.Arch)" } else { Write-Output "none" }\n'- )--[email protected](shutil.which("pwsh") is None, reason = "PowerShell is unavailable")- ("installed", "can_download", "expected"),- [- # The opt-out asks for a NATIVE interpreter. With x64 3.13 and ARM64 3.12 installed- # the per-minor loop answered the version preference first, returned the x64 3.13 and- # stopped -- and the swap never runs on an x64 selection, so the variable produced an- # x64 environment after all, which is the opposite of what it asks for.- ([("3.13", "x86_64"), ("3.12", "arm64")], True, "3.12|arm64"),- # The requested minor's own ARM64 build still wins over a lower one.- ([("3.13", "arm64"), ("3.12", "arm64")], True, "3.13|arm64"),- # No ARM64 anywhere: the opt-out cannot invent one, so the x64 build is used.- ([("3.13", "x86_64")], False, "3.13|x86_64"),- # A 32-bit interpreter is NOT an ARM64 one. Its platform tag is neither win-amd64 nor- # win-arm64, so it reaches the swap as "not x64", and returning it under this- # variable would label it native ARM64 and install a stack it cannot hold. The x64- # bootstrap runs instead.- ([("3.13", "win32")], True, "3.13|x86_64"),- # And with nothing to download, that same interpreter fails closed rather than being- # accepted as native.- ([("3.13", "win32")], False, "none"),- ],-)-def test_the_arm64_opt_out_selects_a_native_interpreter(installed, can_download, expected):- environment = _environment_without_the_arm64_opt_out()- environment["UNSLOTH_ALLOW_ARM64_PYTHON"] = "1"- result = run_pwsh(- [- "pwsh",- "-NoProfile",- "-NonInteractive",- "-Command",- _opt_out_script(installed, can_download),- ],- check = True,- capture_output = True,- text = True,- env = environment,- )- assert result.stdout.strip() == expected---def _environment_without_the_arm64_opt_out() -> dict:- """These cases are the DEFAULT ARM64 host, which is the one that must prefer x64.-- UNSLOTH_ALLOW_ARM64_PYTHON now reaches the selection rather than only the swap after it,- so a developer who happens to have it exported would flip every expectation below and- read as a regression in the resolver.- """- environment = os.environ.copy()- environment.pop("UNSLOTH_ALLOW_ARM64_PYTHON", None)- # And these cases are not inside a conda environment either: `Install-X64Python` takes a- # different branch there, and a developer running the suite from one would read as a- # resolver regression.- environment.pop("CONDA_PREFIX", None)- environment.pop("CONDA_DEFAULT_ENV", None)- return environment---def _pwsh(script: str) -> str:- # Every ARM64 case below is decided by the one "version|arch" line this run prints, and check = True means a pwsh- # that aborts at startup would surface as the resolver block itself throwing.- result = run_pwsh(- ["pwsh", "-NoProfile", "-NonInteractive", "-Command", script],- check = True,- capture_output = True,- text = True,- env = _environment_without_the_arm64_opt_out(),- )- return result.stdout.strip()--[email protected](shutil.which("pwsh") is None, reason = "PowerShell is unavailable")- ("installed", "can_download", "expected"),- [- # An x64 build of the requested minor wins outright, downloads irrelevant.- ([("3.13", "arm64"), ("3.13", "x86_64")], False, "3.13|x86_64"),- # Requested minor is ARM64-only: bootstrap x64 rather than take the native one.- ([("3.13", "arm64")], True, "3.13|x86_64"),- # Offline, but an x64 build of a lower-priority minor is here. Use it: the native- # 3.13 cannot resolve pyarrow or hf-transfer, and this one can.- ([("3.13", "arm64"), ("3.11", "x86_64")], False, "3.11|x86_64"),- # ARM64 everywhere: still returned, and the caller warns.- ([("3.13", "arm64"), ("3.11", "arm64")], False, "3.13|arm64"),- ],-)-def test_arm64_host_prefers_an_x64_interpreter(installed, can_download, expected):- assert _pwsh(_resolver_script(installed, can_download)) == expected---def _venv_base_script(cfg_lines: str, base_arch: str, base_present: bool) -> str:- """The real Get-StudioVenvBasePython over a fake pyvenv.cfg and base interpreter."""- source = INSTALL_PS1.read_text(encoding = "utf-8")- reader = _extract(r" function Get-StudioVenvBasePython \{.*?\n \}\n", source)- tag = {"arm64": "win-arm64", "x86_64": "win-amd64"}.get(base_arch, base_arch)- present = "$true" if base_present else "$false"- return f"""-$ErrorActionPreference = "Stop"-$PythonSkip = @()-$CfgLines = @'-{cfg_lines}-'@ -split "`n"-function Test-Path {{- param([Parameter(Position = 0)][string]$LiteralPath,- [Parameter(ValueFromRemainingArguments = $true)]$Rest)- if ($LiteralPath -like "*pyvenv.cfg") {{ return $true }}- return {present}-}}-function Get-Content {{- param([Parameter(ValueFromRemainingArguments = $true)]$Rest)- return $CfgLines-}}-function Test-IsCondaPython {{ param([string]$Exe) return $false }}-function Get-PythonPlatformTag {{ param([string]$Exe) return "{tag}" }}-function BasePython.exe {{- param([Parameter(ValueFromRemainingArguments = $true)]$Rest)- return "Python 3.12.4"-}}-# The home-only spelling resolves to <home>/python.exe, so that exact name answers too.-function /py312/python.exe {{- param([Parameter(ValueFromRemainingArguments = $true)]$Rest)- return "Python 3.12.4"-}}-{reader}-$found = Get-StudioVenvBasePython -VenvDir "/home/unsloth_studio"-if ($found) {{ Write-Output "$($found.Version)|$($found.Arch)" }} else {{ Write-Output "none" }}-"""--[email protected](shutil.which("pwsh") is None, reason = "PowerShell is unavailable")- ("cfg", "arch", "present", "expected"),- [- # base-executable names it exactly, which is what a modern venv records.- ("home = /py312\nbase-executable = BasePython.exe\n", "arm64", True, "3.12|arm64"),- # An older venv records only home; the interpreter beside it is the same answer.- ("home = /py312\n", "arm64", True, "3.12|arm64"),- # The interpreter that built it is gone: nothing to honour the opt-out with, and- # inventing one would be worse than the x64 selection this replaces.- ("base-executable = BasePython.exe\n", "arm64", False, "none"),- # An x64 base is not what the opt-out asks for, so it is not preferred over the- # selection the ordinary rules already made.- ("base-executable = BasePython.exe\n", "x86_64", True, "none"),- # A cfg with neither key answers nothing rather than guessing a path.- ("include-system-site-packages = false\n", "arm64", True, "none"),- ],-)-def test_the_existing_environments_base_interpreter_is_the_last_arm64_python(- cfg, arch, present, expected-):- """UNSLOTH_ALLOW_ARM64_PYTHON with no ARM64 interpreter registered on the machine.-- The selection prefers ARM64 only among the interpreters discovery can see. Remove the- ARM64 CPython that built the venv and there is nothing left to prefer: an x64 interpreter- is selected, the reinstall has already moved the native environment aside, and the new one- is built on x64 -- while the opt-out's own message said it would not be. pyvenv.cfg still- names that base interpreter, so when it is on disk the variable has something to honour.- """- result = run_pwsh(- [- "pwsh",- "-NoProfile",- "-NonInteractive",- "-Command",- _venv_base_script(cfg, arch, present),- ],- check = True,- capture_output = True,- text = True,- env = _environment_without_the_arm64_opt_out(),- )- assert result.stdout.strip() == expecteddiff --git a/tests/python/test_windows_on_arm_python_arch.py b/tests/python/test_windows_on_arm_python_arch.pyindex af40363580f..9365739cde7 100644--- a/tests/python/test_windows_on_arm_python_arch.py+++ b/tests/python/test_windows_on_arm_python_arch.py@@ -73,15 +73,10 @@ def _run(# stands in for logic under test here: Get-HostMachineArch is exercised against real# hardware on the windows-11-arm leg, and Get-PythonPlatformTag asks an interpreter for# sysconfig.get_platform(), which needs a Windows interpreter to answer win-arm64.-def _preamble(host_arch: str, venv_tag: str, x64_available: bool) -> str:+def _preamble(host_arch: str, venv_tag: str) -> str:# Verbatim from install.ps1, not a stub: both the fresh-selection path and the venv# re-check call it, so a change to what the opt-out accepts has to move these cases too.opt_out = _function("Test-Arm64PythonOptOut")- x64 = (- '@{ Version = "3.13"; Path = "C:\\x64\\python.exe"; Arch = "x86_64" }'- if x64_available- else "$null"- )return f"""$ErrorActionPreference = "Stop"$script:StudioVtOk = $false@@ -94,122 +89,10 @@ function step {{ param([string]$Label, [string]$Value, [string]$Color = "Green")function substep {{ param([string]$Message, [string]$Color = "DarkGray") Write-Host "SUBSTEP $Message" }}function Get-HostMachineArch {{ return "{host_arch}" }}function Get-PythonPlatformTag {{ param([string]$Exe) return "{venv_tag}" }}-function Install-X64Python {{ Write-Host "INSTALL-X64-CALLED"; return {x64} }}{opt_out}"""[email protected](not POWERSHELLS, reason = "PowerShell is unavailable")[email protected]("shell", POWERSHELLS)-def test_arm64_host_takes_the_x64_interpreter_when_one_can_be_installed(shell: str):- """The path that already worked: ARM64 host, x64 obtainable, x64 is what is returned."""- script = (- _preamble("arm64", "win-arm64", x64_available = True)- + f"""-{_function("Resolve-WindowsOnArmX64Python")}-$selected = @{{ Version = "3.13"; Path = "C:\\arm\\python.exe"; Arch = "arm64" }}-$chosen = Resolve-WindowsOnArmX64Python -SelectedPython $selected-Write-Host ("CHOSEN=" + $(if ($chosen) {{ $chosen.Arch }} else {{ "none" }}))-Write-Host ("PATH=" + $(if ($chosen) {{ $chosen.Path }} else {{ "none" }}))-"""- )- out = _run(shell, script)- assert "CHOSEN=x86_64" in out- assert "PATH=C:\\x64\\python.exe" in out- assert "using x64 Python" in out--[email protected](not POWERSHELLS, reason = "PowerShell is unavailable")[email protected]("shell", POWERSHELLS)-def test_no_x64_interpreter_is_a_stop_not_a_warning(shell: str):- """$null is the answer when x64 cannot be had, and the advice names the real fix.-- This is the half of #10875 that survived re-checking. The installer used to print- [WARN] and carry on, which turns a diagnosable "install x64 Python" into a pyarrow- CMake failure several minutes later, in a log the reporter has to scroll to find.- """- script = (- _preamble("arm64", "win-arm64", x64_available = False)- + f"""-{_function("Resolve-WindowsOnArmX64Python")}-$selected = @{{ Version = "3.13"; Path = "C:\\arm\\python.exe"; Arch = "arm64" }}-$chosen = Resolve-WindowsOnArmX64Python -SelectedPython $selected-Write-Host ("CHOSEN=" + $(if ($chosen) {{ $chosen.Arch }} else {{ "none" }}))-"""- )- out = _run(shell, script)- assert "CHOSEN=none" in out, "an ARM64 interpreter must not be handed back as usable"- assert "[ERROR]" in out- assert "[WARN]" not in out- assert "python.org/downloads/windows" in out- assert "UNSLOTH_ALLOW_ARM64_PYTHON" in out, "a fail-closed path has to name its opt-out"--[email protected](not POWERSHELLS, reason = "PowerShell is unavailable")[email protected]("shell", POWERSHELLS)[email protected]("value", ["1", "true", "YES", "on"])-def test_the_opt_out_keeps_the_old_warn_and_continue(shell: str, value: str):- """Someone who has built both wheels locally can still ask for the ARM64 interpreter."""- script = (- _preamble("arm64", "win-arm64", x64_available = False)- + f"""-{_function("Resolve-WindowsOnArmX64Python")}-$selected = @{{ Version = "3.13"; Path = "C:\\arm\\python.exe"; Arch = "arm64" }}-$chosen = Resolve-WindowsOnArmX64Python -SelectedPython $selected-Write-Host ("CHOSEN=" + $(if ($chosen) {{ $chosen.Arch }} else {{ "none" }}))-"""- )- out = _run(shell, script, env = {"UNSLOTH_ALLOW_ARM64_PYTHON": value})- assert "CHOSEN=arm64" in out- assert "[WARN]" in out- assert "[ERROR]" not in out--[email protected](not POWERSHELLS, reason = "PowerShell is unavailable")[email protected]("shell", POWERSHELLS)[email protected]("value", ["1", "true", "YES", "on"])-def test_the_opt_out_is_read_before_the_x64_install_is_attempted(shell: str, value: str):- """The opt-out has to opt out on a machine where the x64 install would SUCCEED."""- script = (- _preamble("arm64", "win-arm64", x64_available = True)- + f"""-{_function("Resolve-WindowsOnArmX64Python")}-$selected = @{{ Version = "3.13"; Path = "C:\\arm\\python.exe"; Arch = "arm64" }}-$chosen = Resolve-WindowsOnArmX64Python -SelectedPython $selected-Write-Host ("CHOSEN=" + $(if ($chosen) {{ $chosen.Arch }} else {{ "none" }}))-"""- )- out = _run(shell, script, env = {"UNSLOTH_ALLOW_ARM64_PYTHON": value})- assert "CHOSEN=arm64" in out- assert (- "INSTALL-X64-CALLED" not in out- ), "an x64 Python was installed for someone who asked to keep the ARM64 one"- assert "[WARN]" in out- assert "[ERROR]" not in out- assert "Unset UNSLOTH_ALLOW_ARM64_PYTHON" in out, "the warning has to say how to undo it"---def test_the_python_org_route_is_not_attempted_twice_inside_conda():- """Inside conda, python.org is tried FIRST, so the later winget fallback must not- repeat it.-- On an offline machine the second attempt is the same failing download again, and it is- announced as "falling back to python.org" for a fallback that already ran.- """- source = INSTALL_PS1.read_text(encoding = "utf-8")- start = source.index('substep "installing Python ${PythonVersion}..."')- end = source.index("Python installation failed", start)- block = source[start:end]- assert (- block.count("Install-PythonFromPythonOrg") == 2- ), "the conda-first call and the winget fallback, and nothing else"- guard = source.index('substep "winget could not install Python', start)- condition = source.rindex("if (-not $DetectedPython", start, guard)- assert (- "-not $pythonOrgTried" in source[condition : source.index("\n", condition)]- ), "the winget fallback would otherwise run python.org a second time"--@pytest.mark.skipif(not POWERSHELLS, reason = "PowerShell is unavailable")@pytest.mark.parametrize("shell", POWERSHELLS)@pytest.mark.parametrize(@@ -248,7 +131,7 @@ def test_a_reused_environment_is_re_checked_for_its_interpreter_architecture(venv_python.write_text("", encoding = "utf-8")selected = f'@{{ Version = "3.13"; Path = "C:\\p\\python.exe"; Arch = "{selected_arch}" }}'script = (- _preamble(host_arch, venv_tag, x64_available = True)+ _preamble(host_arch, venv_tag)+ f"""{_function("Test-StudioVenvArchMismatch")}$selected = {selected}@@ -277,7 +160,7 @@ def test_the_opt_out_also_protects_an_existing_arm64_environment(venv_python.write_text("", encoding = "utf-8")selected = '@{ Version = "3.13"; Path = "C:\\p\\python.exe"; Arch = "x86_64" }'script = (- _preamble("arm64", "win-arm64", x64_available = True)+ _preamble("arm64", "win-arm64")+ f"""{_function("Test-StudioVenvArchMismatch")}$selected = {selected}@@ -299,7 +182,7 @@ def test_the_arm64_environment_is_still_replaced_without_the_opt_out(tmp_path: Pvenv_python.write_text("", encoding = "utf-8")selected = '@{ Version = "3.13"; Path = "C:\\p\\python.exe"; Arch = "x86_64" }'script = (- _preamble("arm64", "win-arm64", x64_available = True)+ _preamble("arm64", "win-arm64")+ f"""{_function("Test-StudioVenvArchMismatch")}$selected = {selected}@@ -339,33 +222,6 @@ def test_the_arm64_rebuild_tells_the_user_what_it_does_not_carry_over():assert "UNSLOTH_ALLOW_ARM64_PYTHON" in block, "the rebuild does not name its opt-out"-def test_the_installer_stops_when_no_x64_interpreter_can_be_installed():- """The caller must treat $null as a failure, not as "no change".-- Resolve-WindowsOnArmX64Python returning $null is only a stop if the call site says so,- and a call site that assigned the result and carried on would leave every case above- passing while the installer behaved exactly as it did before.- """- source = INSTALL_PS1.read_text(encoding = "utf-8")- # Anchored on the call, not on the shape of the if: the guard is multi-line since the- # native CUDA torch check joined it, and an anchor on "$DetectedPython -and" silently- # matched an unrelated earlier block instead of failing.- call = source.index("$DetectedPython = Resolve-WindowsOnArmX64Python")- opening = source.rindex("\n if (", 0, call)- match = re.search(r".*?\n \}\n", source[opening + 1 :], flags = re.DOTALL)- assert match is not None, "install.ps1 no longer guards the Windows-on-ARM swap"- block = match.group(0)- assert "Resolve-WindowsOnArmX64Python" in block- assert "-not $script:WoaNativeCudaTorch" in block, (- "a host with native ARM64 CUDA torch wants its ARM64 interpreter; swapping it for "- "x64 there gives a Triton that cannot do sm_121"- )- assert "Exit-InstallFailure" in block, (- "an unobtainable x64 interpreter has to end the install here; continuing moves the "- "failure to the pyarrow build, which is what #10875 reported"- )--def test_the_venv_reuse_path_re_checks_before_it_reuses():"""The re-check has to sit ahead of the branch that decides to reuse.@@ -386,151 +242,6 @@ def test_the_venv_reuse_path_re_checks_before_it_reuses():# ── The x64 bootstrap has to respect conda too ──-# The generic bootstrap takes the python.org route first inside an active conda environment,-# because winget's Python manifest hard-codes PrependPath=1 and there is no switch that asks-# it otherwise. Windows on ARM does not reach that bootstrap: it has a compatible (ARM64)-# interpreter already, so the "install Python" branch never runs and Install-X64Python is-# what actually performs the install. Ordered winget-first, it puts Python ahead of conda on-# PATH on exactly the machine this change exists to protect.---def _x64_bootstrap_preamble(- conda_active: bool, python_org_arch: str, winget_available: bool, winget_arch: str-) -> str:- """Stubs for everything Install-X64Python calls, so the case drives the decision.-- `python_org_arch` / `winget_arch` are what each source manages to produce: "x86_64",- "arm64" (installed, but the wrong architecture, which the caller rejects) or "" for- nothing at all.- """-- def _result(arch: str, path: str) -> str:- if not arch:- return "$null"- return f'@{{ Version = "3.13"; Path = "{path}"; Arch = "{arch}" }}'-- # Bound before the template rather than called inside it: a backslash inside an- # f-string expression is a 3.12 syntax addition, and this repo's ruff target is 3.11.- winget_installed = _result(winget_arch, "C:\\winget\\python.exe")- python_org_installed = _result(python_org_arch, "C:\\pyorg\\python.exe")-- return f"""-$ErrorActionPreference = "Stop"-function Write-StudioLine {{- param([string]$Message = "", [string]$ForegroundColor)- Write-Host $Message-}}-function substep {{ param([string]$Message, [string]$Color = "DarkGray") Write-Host "SUBSTEP $Message" }}-function Test-ActiveCondaEnvironment {{ return ${str(conda_active).lower()} }}-$PythonVersion = "3.13"-$script:WingetAvailable = ${str(winget_available).lower()}-$script:WingetExe = "winget.exe"-$script:WingetInstalled = {winget_installed}-$script:PythonOrgCalls = 0-function Install-PythonFromPythonOrg {{- param([string]$Arch = "")- $script:PythonOrgCalls++- Write-Host "PYTHON-ORG-CALLED arch=$Arch"- return {python_org_installed}-}}-function Refresh-SessionPath {{ }}-function Find-CompatiblePython {{- param([switch]$X64Only)- return $script:WingetInstalled-}}-"""--[email protected](not POWERSHELLS, reason = "PowerShell is unavailable")[email protected]("shell", POWERSHELLS)-def test_the_x64_bootstrap_skips_winget_inside_conda(shell: str):- """Inside conda, python.org is what installs the x64 interpreter."""- script = (- _x64_bootstrap_preamble(- conda_active = True,- python_org_arch = "x86_64",- winget_available = True,- winget_arch = "x86_64",- )- + f"""-function Invoke-Winget {{ Write-Host "WINGET-CALLED" }}-{_function("Install-X64Python").replace('& $script:WingetExe install', 'Invoke-Winget #')}-$found = Install-X64Python-Write-Host ("ARCH=" + $(if ($found) {{ $found.Arch }} else {{ "none" }}))-Write-Host ("PATH=" + $(if ($found) {{ $found.Path }} else {{ "none" }}))-Write-Host ("PYTHON-ORG-CALLS=" + $script:PythonOrgCalls)-"""- )- out = _run(shell, script)- assert "ARCH=x86_64" in out- assert (- "PATH=C:\\pyorg\\python.exe" in out- ), "the conda path must take the python.org interpreter"- assert "WINGET-CALLED" not in out, (- "winget hard-codes PrependPath=1, so reaching it inside conda puts Python ahead of "- "the active environment with no way to ask for anything else"- )- assert "PYTHON-ORG-CALLS=1" in out--[email protected](not POWERSHELLS, reason = "PowerShell is unavailable")[email protected]("shell", POWERSHELLS)-def test_the_x64_bootstrap_still_falls_back_to_winget_inside_conda(shell: str):- """A warned-about PATH beats no x64 Python at all."""- script = (- _x64_bootstrap_preamble(- conda_active = True,- python_org_arch = "",- winget_available = True,- winget_arch = "x86_64",- )- + f"""-function Invoke-Winget {{ Write-Host "WINGET-CALLED" }}-{_function("Install-X64Python").replace('& $script:WingetExe install', 'Invoke-Winget #')}-$found = Install-X64Python-Write-Host ("ARCH=" + $(if ($found) {{ $found.Arch }} else {{ "none" }}))-Write-Host ("PYTHON-ORG-CALLS=" + $script:PythonOrgCalls)-"""- )- out = _run(shell, script)- assert "WINGET-CALLED" in out- assert "ARCH=x86_64" in out- assert "ahead of conda on PATH" in out, "the fallback has to say what it costs"- assert "PYTHON-ORG-CALLS=1" in out, (- "the winget branch would otherwise repeat the same failing download, on the offline "- "machine that is the usual reason it failed"- )--[email protected](not POWERSHELLS, reason = "PowerShell is unavailable")[email protected]("shell", POWERSHELLS)-def test_the_x64_bootstrap_is_unchanged_outside_conda(shell: str):- """No conda, no reordering: winget first, exactly as before.-- winget is the faster and more reliable source on a normal machine, and this change is- only about the environment whose PATH it would break.- """- script = (- _x64_bootstrap_preamble(- conda_active = False,- python_org_arch = "x86_64",- winget_available = True,- winget_arch = "x86_64",- )- + f"""-function Invoke-Winget {{ Write-Host "WINGET-CALLED" }}-{_function("Install-X64Python").replace('& $script:WingetExe install', 'Invoke-Winget #')}-$found = Install-X64Python-Write-Host ("PATH=" + $(if ($found) {{ $found.Path }} else {{ "none" }}))-Write-Host ("PYTHON-ORG-CALLS=" + $script:PythonOrgCalls)-"""- )- out = _run(shell, script)- assert "WINGET-CALLED" in out- assert "PATH=C:\\winget\\python.exe" in out- assert "PYTHON-ORG-CALLS=0" in out--# ── The environment the rebuild promises to keep has to still be there ──@@ -756,26 +467,3 @@ def test_the_opt_out_keeps_the_environment_it_says_it_keeps():assert ("unsloth_studio.arm64.*" in source[optout : optout + 600]), "the user is not told where the kept environment is"---def test_the_opt_out_reaches_the_interpreter_selection():- """On a host that already has an x64 Python the swap never runs."""- body = _function("Find-CompatiblePython")- assert (- "Test-Arm64PythonOptOut" in body- ), "the interpreter selection does not consult the ARM64 opt-out"- prefer = body[body.index("$preferArm64 =") : body.index("$preferX64 =")]- # Never for Install-X64Python's own lookup, which exists to find x64 specifically.- assert "-not $X64Only" in prefer, prefer- assert "Get-HostMachineArch" in prefer, prefer- # The native-CUDA host keeps its own reason to prefer ARM64.- assert "WoaNativeCudaTorch" in prefer, prefer- # And x64 is still preferred on an ARM64 host WITHOUT the opt-out, which is the whole- # reason the preference exists.- x64 = body[body.index("$preferX64 =") :].split("\n", 1)[0]- assert "-not $preferArm64" in x64, x64-- # The swap still keeps an ARM64 selection rather than bootstrapping over it.- resolve = _function("Resolve-WindowsOnArmX64Python")- assert "Test-Arm64PythonOptOut" in resolve- assert "return $SelectedPython" in resolvediff --git a/tests/python/test_windows_python_313_8_screen.py b/tests/python/test_windows_python_313_8_screen.pydeleted file mode 100644index 4ee5a977c67..00000000000--- a/tests/python/test_windows_python_313_8_screen.py+++ /dev/null@@ -1,337 +0,0 @@-# SPDX-License-Identifier: AGPL-3.0-only-# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.--"""Windows must not build the venv on a CPython that cannot import torch.--CPython 3.13.8 carries python/cpython#139783: inspect.getsourcelines() drops a-function body when a decorator is followed by a comment, which is the shape of-the @_overload_method blocks torch/nn/modules/rnn.py parses at import time, so-`import torch` raises IndentationError (#7803).--Windows reaches such an interpreter differently from install.sh: uv is handed a-resolved path rather than a version, so it never picks the patch itself, but-Find-CompatiblePython matches on the *minor* version and would happily return an-already-installed 3.13.8. Remove-SkippedPython is what turns that into "not-found", so the caller installs $PythonFallbackFullVersion instead.--The function is extracted from install.ps1 and executed under pwsh rather than-reimplemented, so the test cannot drift from the text the installer runs.-"""--from __future__ import annotations--import os-import re-import shutil-import stat-from pathlib import Path--import pytest--from unsloth_pwsh_runner import run_pwsh---REPO_ROOT = Path(__file__).resolve().parents[2]-INSTALL_PS1 = REPO_ROOT / "install.ps1"--pytestmark = pytest.mark.skipif(- shutil.which("pwsh") is None, reason = "pwsh is required to execute install.ps1 blocks"-)---def _extract(pattern: str) -> str:- source = INSTALL_PS1.read_text(encoding = "utf-8")- match = re.search(pattern, source, flags = re.DOTALL)- assert match is not None, f"install.ps1 no longer contains {pattern!r}"- return match.group(0)---def _blocks() -> tuple:- """The skip list and the screen, straight out of install.ps1.-- Hoisted out of the f-strings below: a backslash inside an f-string expression- is a syntax error before 3.12, and this repo is 3.9+ (ruff targets py311).- """- return (- _extract(- r" # Patch releases the stack cannot run.*?"- r"if \(\$SkipTorch\) \{ \$PythonSkip = @\(\) \}"- ),- _extract(r" function Remove-SkippedPython \{.*?\n \}"),- )---def _fake_python(tmp_path: Path, version: str) -> Path:- """An executable that reports ``version`` for the resolver's probe."""- if os.name == "nt":- exe = tmp_path / "python.cmd"- exe.write_text(f"@echo off\r\necho {version}\r\n", encoding = "utf-8")- return exe- exe = tmp_path / "python"- exe.write_text(f'#!/bin/sh\necho "{version}"\n', encoding = "utf-8")- exe.chmod(exe.stat().st_mode | stat.S_IEXEC | stat.S_IXGRP | stat.S_IXOTH)- return exe---def _run(tmp_path: Path, version: str | None) -> str:- candidate = (- "$null"- if version is None- else f'@{{ Version = "3.13"; Path = "{_fake_python(tmp_path, version)}" }}'- )- skip_block, screen_block = _blocks()- script = f"""-$ErrorActionPreference = "Stop"-$SkipTorch = $false-# Write-Host, like the real substep: Write-Output would put the message on-# the pipeline, so the function would return @(message, $null) and every-# `if ($DetectedPython)` downstream would read it as truthy.-function substep {{ param($m, $c) Write-Host "SUBSTEP: $m" }}-{skip_block}-{screen_block}-$result = Remove-SkippedPython ({candidate})-if ($null -eq $result) {{ Write-Output "RESULT: rejected" }}-else {{ Write-Output "RESULT: kept" }}-"""- # The whole verdict is the single RESULT line this script prints, so a pwsh that aborts at startup would read as a- # screen that reached the opposite conclusion.- completed = run_pwsh(- ["pwsh", "-NoProfile", "-NonInteractive", "-Command", script],- capture_output = True,- text = True,- )- return completed.stdout + completed.stderr---def test_a_skipped_patch_is_rejected(tmp_path):- out = _run(tmp_path, "3.13.8")- assert "RESULT: rejected" in out, out- assert "cannot import torch" in out, "the user should be told why: " + out---def test_a_good_patch_of_the_same_minor_is_kept(tmp_path):- # The screen is per patch: 3.13 itself is fine and must not be refused.- out = _run(tmp_path, "3.13.13")- assert "RESULT: kept" in out, out---def test_nothing_found_stays_nothing(tmp_path):- out = _run(tmp_path, None)- assert "RESULT: rejected" in out, out---def test_an_unreadable_interpreter_is_not_treated_as_bad(tmp_path):- # A probe that cannot run is not evidence of a bad version, and refusing it would send a working machine down the- # install path for no reason.- missing = tmp_path / "does-not-exist"- skip_block, screen_block = _blocks()- script = f"""-$ErrorActionPreference = "Stop"-$SkipTorch = $false-# Write-Host, like the real substep: Write-Output would put the message on-# the pipeline, so the function would return @(message, $null) and every-# `if ($DetectedPython)` downstream would read it as truthy.-function substep {{ param($m, $c) Write-Host "SUBSTEP: $m" }}-{skip_block}-{screen_block}-$result = Remove-SkippedPython (@{{ Version = "3.13"; Path = "{missing}" }})-if ($null -eq $result) {{ Write-Output "RESULT: rejected" }}-else {{ Write-Output "RESULT: kept" }}-"""- # This case asserts the screen KEEPS an interpreter it could not probe, so an- # interpreter that dies would masquerade as the screen wrongly rejecting it.- completed = run_pwsh(- ["pwsh", "-NoProfile", "-NonInteractive", "-Command", script],- capture_output = True,- text = True,- )- assert "RESULT: kept" in completed.stdout + completed.stderr, (- completed.stdout + completed.stderr- )---def test_the_resolver_is_screened_at_every_entry_point():- """A bare Find-CompatiblePython in the install flow would defeat the screen."""- source = INSTALL_PS1.read_text(encoding = "utf-8")- flow = source[source.index("# ── Install Python if no compatible version") :]- flow = flow[: flow.index("# ── Install uv ──")]- bare = [- line.strip()- for line in flow.splitlines()- if "= Find-CompatiblePython" in line and "Remove-SkippedPython" not in line- ]- assert not bare, f"unscreened resolver calls in the install flow: {bare}"---# ── The screen inside the resolver ──-# The window above starts at the install step, so it never sees the recovery-# paths: Install-PythonFromPythonOrg and Install-X64Python both end in a bare-# `return (Find-CompatiblePython)`. Screening every candidate as it is-# enumerated is what makes those safe, and is also what lets the resolver carry-# on to its next minor instead of giving up on the machine.-def _every_version_match_screens_the_patch() -> list[str]:- body = _extract(r" function Find-CompatiblePython \{.*?\n \}")- lines = body.splitlines()- unscreened = []- for i, line in enumerate(lines):- if 'match "Python' not in line:- continue- window = "\n".join(lines[i : i + 9])- if "$PythonSkip -contains" not in window:- unscreened.append(line.strip())- return unscreened---def test_every_enumerated_candidate_is_screened():- assert (- len(- [- l- for l in _extract(r" function Find-CompatiblePython \{.*?\n \}").splitlines()- if 'match "Python' in l- ]- )- == 3- ), "the resolver's enumeration sites moved; re-check the screen"- assert not _every_version_match_screens_the_patch(), (- "Find-CompatiblePython enumerates a candidate without checking $PythonSkip: "- f"{_every_version_match_screens_the_patch()}"- )---# The launcher below is a /bin/sh script.-# Windows has no shebang and no PATHEXT entry for an extensionless file, so `Get-Command py` does not find it and the-# resolver reports "none" whatever the versions are -- which would make the negative case pass for the wrong reason.-# The PowerShell under test is the same text on every platform, and pwsh runs it here, so these three cases run on POSIX-# and the rest of the file still covers Windows.-_POSIX_LAUNCHER_ONLY = pytest.mark.skipif(- os.name == "nt", reason = "the fake py launcher is a /bin/sh script"-)---def _fake_launcher(root: Path, versions: dict[str, str]) -> Path:- """A `py` launcher over fake interpreters, one per minor in ``versions``."""- root.mkdir(parents = True, exist_ok = True)- branches = []- for minor, full in versions.items():- exe = root / f"python{minor.replace('.', '')}"- # -S -c "import sys; print(sys.base_prefix)" for the conda screen.- exe.write_text('#!/bin/sh\necho "/usr"\n', encoding = "utf-8")- exe.chmod(0o755)- branches.append(f' {minor}) ver="{full}"; exe="{exe}" ;;')- launcher = root / "py"- launcher.write_text(- "#!/bin/sh\n"- 'case "$1" in\n'- + "\n".join(f" -{b.lstrip()}" for b in branches)- + "\n *) exit 1 ;;\nesac\n"- "shift\n"- 'case "$1" in\n'- ' --version) echo "Python $ver" ;;\n'- ' -S) echo "$exe" ;;\n'- " *) exit 1 ;;\n"- "esac\n",- encoding = "utf-8",- )- launcher.chmod(0o755)- return launcher---def _resolve(tmp_path: Path, versions: dict[str, str]) -> str:- """Run the real Find-CompatiblePython over ``versions`` and report the hit."""- root = tmp_path / "bin"- _fake_launcher(root, versions)- skip_block, screen_block = _blocks()- # Hoisted for the same reason as _blocks: a backslash in an f-string expression does not parse before 3.12.- conda_block = _extract(r" function Test-IsCondaPython \{.*?\n \}")- tag_block = _extract(r" function Get-PythonPlatformTag \{.*?\n \}")- resolver_block = _extract(r" function Find-CompatiblePython \{.*?\n \}")- script = f"""-$ErrorActionPreference = "Stop"-$SkipTorch = $false-$env:PATH = "{root}"-$PythonVersion = "3.13"-function substep {{ param($m, $c) Write-Host "SUBSTEP: $m" }}-function Get-HostMachineArch {{ return "x86_64" }}-{skip_block}-$script:CondaSkipPattern = '(?i)(conda|miniconda|anaconda|miniforge|mambaforge)'-{conda_block}-{tag_block}-{resolver_block}-$found = Find-CompatiblePython-if ($null -eq $found) {{ Write-Output "RESULT: none" }}-else {{ Write-Output "RESULT: $($found.Version)" }}-"""- # The caller scrapes the resolver's chosen minor out of stdout; a crashed pwsh leaves nothing to scrape and would- # fail as if Find-CompatiblePython went silent.- completed = run_pwsh(- ["pwsh", "-NoProfile", "-NonInteractive", "-Command", script],- capture_output = True,- text = True,- )- out = completed.stdout + completed.stderr- match = re.search(r"RESULT: (\S+)", out)- assert match is not None, out- return match.group(1)---@_POSIX_LAUNCHER_ONLY-def test_the_resolver_falls_through_to_the_next_minor(tmp_path):- # The offline/locked-down case: 3.13.8 and a healthy 3.12 both installed and nothing installable. Ending the search- # on the 3.13 would leave the caller with a Python that cannot import torch; refusing it outright would fail a- # machine that has a perfectly good interpreter one entry down the list.- assert _resolve(tmp_path, {"3.13": "3.13.8", "3.12": "3.12.11"}) == "3.12"---@_POSIX_LAUNCHER_ONLY-def test_a_good_preferred_minor_still_wins(tmp_path):- assert _resolve(tmp_path, {"3.13": "3.13.13", "3.12": "3.12.11"}) == "3.13"---@_POSIX_LAUNCHER_ONLY-def test_nothing_usable_is_still_nothing(tmp_path):- # Paired with a positive control over the same tree, because "none" is also- # what a harness that cannot run the launcher at all reports: without the- # control this case would pass on a machine where it proves nothing.- assert _resolve(tmp_path / "good", {"3.13": "3.13.13"}) == "3.13"- assert _resolve(tmp_path / "bad", {"3.13": "3.13.8"}) == "none"---@_POSIX_LAUNCHER_ONLY-def test_no_torch_mode_keeps_the_skipped_patch(tmp_path):- """The list is about `import torch`; -NoTorch never imports it.-- A locked-down GGUF-only machine whose only Python is 3.13.8 would otherwise- be pushed into winget/python.org recovery it may not be able to complete.- """- root = tmp_path / "bin"- _fake_launcher(root, {"3.13": "3.13.8"})- skip_block, screen_block = _blocks()- conda_block = _extract(r" function Test-IsCondaPython \{.*?\n \}")- tag_block = _extract(r" function Get-PythonPlatformTag \{.*?\n \}")- resolver_block = _extract(r" function Find-CompatiblePython \{.*?\n \}")- script = f"""-$ErrorActionPreference = "Stop"-$SkipTorch = $true-$env:PATH = "{root}"-$PythonVersion = "3.13"-function substep {{ param($m, $c) Write-Host "SUBSTEP: $m" }}-function Get-HostMachineArch {{ return "x86_64" }}-{skip_block}-$script:CondaSkipPattern = '(?i)(conda|miniconda|anaconda|miniforge|mambaforge)'-{conda_block}-{tag_block}-{resolver_block}-$found = Find-CompatiblePython-if ($null -eq $found) {{ Write-Output "RESULT: none" }}-else {{ Write-Output "RESULT: $($found.Version)" }}-"""- # -NoTorch must leave 3.13.8 in place, and dying before the RESULT line is printed is indistinguishable here from- # the screen having removed it.- completed = run_pwsh(- ["pwsh", "-NoProfile", "-NonInteractive", "-Command", script],- capture_output = True,- text = True,- )- out = completed.stdout + completed.stderr- assert "RESULT: 3.13" in out, outdiff --git a/tests/python/test_windows_python_venv_hardening.py b/tests/python/test_windows_python_venv_hardening.pyindex 854dca01d0e..edddf1ce58b 100644--- a/tests/python/test_windows_python_venv_hardening.py+++ b/tests/python/test_windows_python_venv_hardening.py@@ -8,7 +8,6 @@ from __future__ import annotationsimport jsonimport osimport re-import shleximport shutilimport subprocessimport sys@@ -146,75 +145,6 @@ def _uv_cache_functions(source: str) -> str:)[email protected](not POWERSHELLS, reason = "PowerShell is unavailable")[email protected]("shell", POWERSHELLS)- "reported_version,accepted",- [- ("3.9.0", False),- ("3.10.0", False),- ("3.11.0", True),- ("3.12.0", True),- ("3.13.0", True),- ("3.13.8", False),- ("3.14.0", False),- ],-)-def test_path_python_wrapper_resolves_to_real_executable(- tmp_path: Path, shell: str, reported_version: str, accepted: bool-):- 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'@echo off\nif "%~1"=="--version" (\n'- f"echo Python {reported_version}\nexit /b 0\n)\n"- f'@"{sys.executable}" %*\n',- encoding = "utf-8",- )- else:- wrapper = tmp_path / "python-wrapper"- wrapper.write_text(- '#!/bin/sh\nif [ "$1" = "--version" ]; then\n'- f"printf 'Python {reported_version}\\n'\nexit 0\nfi\n"- f'exec {shlex.quote(sys.executable)} "$@"\n',- encoding = "utf-8",- )- wrapper.chmod(0o755)-- script = f"""-$ErrorActionPreference = "Stop"-$PythonVersion = "3.13"-$PythonSkip = @("3.13.8")-$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)- found = _run_powershell(shell, script, env)- if accepted:- assert found- assert Path(found).resolve() == Path(sys.executable).resolve()- else:- assert not found--@pytest.mark.skipif(not POWERSHELLS, reason = "PowerShell is unavailable")@pytest.mark.parametrize("shell", POWERSHELLS)def test_arch_probe_ignores_startup_output(tmp_path: Path, shell: str):diff --git a/tests/python/test_windows_uv_managed_python.py b/tests/python/test_windows_uv_managed_python.pyindex 6f78403880c..289cfc93b3e 100644--- a/tests/python/test_windows_uv_managed_python.py+++ b/tests/python/test_windows_uv_managed_python.py@@ -1,7 +1,9 @@# SPDX-License-Identifier: AGPL-3.0-only# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.-"""install.ps1 lets uv provide Python instead of a system-wide install (#7802)."""+"""install.ps1 always builds the Studio environment on a uv-managed CPython, never on a Python+already installed on the machine (a system 3.12 used to win over uv's 3.13 and close the+cu130 torch 2.13 route)."""from __future__ import annotations@@ -13,6 +15,7 @@ import sysfrom pathlib import Pathimport pytest+from unsloth_pwsh_runner import run_pwsh@@ -20,19 +23,27 @@ REPO_ROOT = Path(__file__).resolve().parents[2]INSTALL_PS1 = REPO_ROOT / "install.ps1"SOURCE = INSTALL_PS1.read_text(encoding = "utf-8")POWERSHELLS = [shell for shell in ("pwsh", "powershell") if shutil.which(shell)]-HOST_MINOR = "{}.{}".format(*sys.version_info[:2])-HOST_FULL = "{}.{}.{}".format(*sys.version_info[:3])-RANGE = ">={0}.{1},<{0}.{2},!={3}".format(- sys.version_info[0], sys.version_info[1], sys.version_info[1] + 1, HOST_FULL-)+needs_pwsh = pytest.mark.skipif(not POWERSHELLS, reason = "PowerShell is unavailable")++X64 = "cpython-3.13-windows-x86_64-none"+ARM = "cpython-3.13-windows-aarch64-none"+# Records every call; `find` answers with the fake interpreter only for keys in FAKE_UV_FACTS,+# after writing the facts that interpreter will report.FAKE_UV = r"""Add-Content -LiteralPath $env:FAKE_UV_LOG -Value ($args -join ' ')+$facts = if ($env:FAKE_UV_FACTS) { $env:FAKE_UV_FACTS | ConvertFrom-Json } else { $null }+$key = $args[-1]if ($args[0] -eq 'python' -and $args[1] -eq 'install') { exit [int]$env:FAKE_UV_INSTALL_EXIT }if ($args[0] -eq 'python' -and $args[1] -eq 'find') {- if ($env:FAKE_UV_FIND) { Write-Output $env:FAKE_UV_FIND; exit 0 }+ if ($facts -and $facts.PSObject.Properties.Name -contains $key) {+ Set-Content -LiteralPath $env:FAKE_PY_FACTS_FILE -Value $facts.$key+ Write-Output $env:FAKE_PY+ exit 0+ }exit 2}+if ($args[0] -eq 'python' -and $args[1] -eq 'dir') { Write-Output $env:FAKE_UV_DIR; exit 0 }exit 9"""@@ -43,131 +54,452 @@ def _function(name: str) -> str:return match.group(0)+def _between(start: str, end: str) -> str:+ a = SOURCE.index(start)+ return SOURCE[a : SOURCE.index(end, a)]+++def _fake_python(tmp_path: Path) -> Path:+ """An interpreter stand-in that prints whatever facts the fake uv last wrote."""+ if os.name == "nt":+ exe = tmp_path / "python.cmd"+ exe.write_text('@type "%FAKE_PY_FACTS_FILE%"\r\n', encoding = "utf-8")+ else:+ exe = tmp_path / "python"+ exe.write_text('#!/bin/sh\ncat "$FAKE_PY_FACTS_FILE"\n', encoding = "utf-8")+ exe.chmod(0o755)+ return exe+++def _pwsh(shell: str, script: str, env: dict[str, str]) -> str:+ return run_pwsh(+ [shell, "-NoProfile", "-NonInteractive", "-Command", script],+ check = True,+ capture_output = True,+ text = True,+ encoding = "utf-8",+ env = dict(os.environ, **env),+ timeout = 60,+ ).stdout.strip()++def _resolve(shell: str,tmp_path: Path,*,- install_exit: int = 0,- find: str = "",+ facts: dict[str, str],+ arch: str = "x86_64",+ patch: str = "",skip: list[str] | None = None,- extra_env: dict[str, str] | None = None,+ install_exit: int = 0,):(tmp_path / "uv.ps1").write_text(FAKE_UV, encoding = "utf-8")log = tmp_path / "uv.log"+ fake_py = _fake_python(tmp_path)skip_list = ", ".join(f"'{v}'" for v in (skip or []))script = f"""$ErrorActionPreference = "Stop"-function substep {{ param($m, $c) }}function Invoke-InstallCommand {{param([ScriptBlock]$Command, [string]$Label, [switch]$NoMirror)$global:LASTEXITCODE = 0& $Command | Out-Nullreturn [int]$LASTEXITCODE}}-$PythonVersion = "{HOST_MINOR}"$PythonSkip = @({skip_list})$script:UvExe = $env:FAKE_UV_EXE{_function("Resolve-UvManagedPython")}-$r = Resolve-UvManagedPython+$r = Resolve-UvManagedPython -Minor "3.13" -Patch "{patch}" -Arch "{arch}"if ($r) {{ $r | ConvertTo-Json -Compress }} else {{ 'null' }}"""- env = dict(- os.environ,- FAKE_UV_LOG = str(log),- FAKE_UV_EXE = str(tmp_path / "uv.ps1"),- FAKE_UV_INSTALL_EXIT = str(install_exit),- FAKE_UV_FIND = find,- **(extra_env or {}),+ out = _pwsh(+ shell,+ script,+ {+ "FAKE_UV_LOG": str(log),+ "FAKE_UV_EXE": str(tmp_path / "uv.ps1"),+ "FAKE_UV_INSTALL_EXIT": str(install_exit),+ "FAKE_UV_FACTS": json.dumps(facts),+ "FAKE_PY": str(fake_py),+ "FAKE_PY_FACTS_FILE": str(tmp_path / "facts.txt"),+ },)- out = run_pwsh(- [shell, "-NoProfile", "-NonInteractive", "-Command", script],- check = True,- capture_output = True,- text = True,- encoding = "utf-8",- env = env,- timeout = 60,- ).stdout.strip()calls = log.read_text(encoding = "utf-8").splitlines() if log.exists() else []- return json.loads(out.splitlines()[-1]), calls---needs_pwsh = pytest.mark.skipif(not POWERSHELLS, reason = "PowerShell is unavailable")-needs_supported_host = pytest.mark.skipif(- not re.fullmatch(r"3\.1[1-3]", HOST_MINOR),- reason = "the probe runs this interpreter, which must be 3.11-3.13",-)+ return json.loads(out.splitlines()[-1]), calls, str(fake_py)@needs_pwsh-@needs_supported_host@pytest.mark.parametrize("shell", POWERSHELLS)-def test_uv_managed_python_is_installed_without_touching_path(shell, tmp_path):- result, calls = _resolve(shell, tmp_path, find = sys.executable)- assert result == {"Version": HOST_MINOR, "Path": sys.executable, "Arch": ""}+ "arch, key, tag",+ [("x86_64", X64, "win-amd64"), ("arm64", ARM, "win-arm64")],+)+def test_the_request_names_the_architecture_and_touches_nothing_else(+ shell, tmp_path, arch, key, tag+):+ result, calls, fake_py = _resolve(shell, tmp_path, facts = {key: f"3.13.12 {tag} 0"}, arch = arch)+ assert result == {"Version": "3.13", "Full": "3.13.12", "Path": fake_py, "Arch": arch}assert calls == [- f"python install --no-bin --no-registry {HOST_MINOR}",- f"python find --system --managed-python {HOST_MINOR}",+ f"python install --no-bin --no-registry {key}",+ f"python find --system --managed-python {key}",]@needs_pwsh@pytest.mark.parametrize("shell", POWERSHELLS)-def test_a_failed_uv_install_falls_back(shell, tmp_path):- result, calls = _resolve(shell, tmp_path, install_exit = 1, find = sys.executable)- assert result is None- assert len(calls) == 1+def test_a_failed_download_still_finds_a_runtime_uv_installed_earlier(shell, tmp_path):+ result, calls, _ = _resolve(shell, tmp_path, facts = {X64: "3.13.12 win-amd64 0"}, install_exit = 1)+ assert result["Full"] == "3.13.12"+ assert calls[1] == f"python find --system --managed-python {X64}"@needs_pwsh@pytest.mark.parametrize("shell", POWERSHELLS)-def test_nothing_found_falls_back(shell, tmp_path):- result, _ = _resolve(shell, tmp_path, find = "")+def test_nothing_managed_is_nothing(shell, tmp_path):+ result, _, _ = _resolve(shell, tmp_path, facts = {}, install_exit = 1)assert result is None@needs_pwsh-@needs_supported_host@pytest.mark.parametrize("shell", POWERSHELLS)-def test_a_skipped_patch_is_excluded_from_the_request(shell, tmp_path):- result, calls = _resolve(shell, tmp_path, find = sys.executable, skip = [HOST_FULL])- # The fake uv still answers with the skipped interpreter, so the post-check refuses it.+ "arch, key, facts",+ [+ ("arm64", ARM, "3.13.12 win-amd64 0"), # emulated x64 build for a native request+ ("x86_64", X64, "3.13.12 win-arm64 0"),+ ("x86_64", X64, "3.13.12 win-amd64 1"), # free-threaded+ ("x86_64", X64, "3.12.9 win-amd64 0"), # another minor+ ("x86_64", X64, "garbage"),+ ],+)+def test_an_interpreter_that_is_not_what_was_asked_for_is_refused(+ shell, tmp_path, arch, key, facts+):+ result, _, _ = _resolve(shell, tmp_path, facts = {key: facts}, arch = arch)assert result is None- assert calls[0] == f"python install --no-bin --no-registry {RANGE}"- assert calls[1] == f"python find --system --managed-python {RANGE}"@needs_pwsh-@needs_supported_host@pytest.mark.parametrize("shell", POWERSHELLS)-def test_a_startup_banner_does_not_hide_a_skipped_patch(shell, tmp_path):- site = tmp_path / "site"- site.mkdir()- (site / "sitecustomize.py").write_text("print('banner')\n", encoding = "utf-8")- result, _ = _resolve(+def test_a_skipped_patch_is_stepped_past(shell, tmp_path):+ next_key = "cpython-3.13.9-windows-x86_64-none"+ result, calls, _ = _resolve(shell,tmp_path,- find = sys.executable,- skip = [HOST_FULL],- extra_env = {"PYTHONPATH": str(site)},+ facts = {X64: "3.13.8 win-amd64 0", next_key: "3.13.9 win-amd64 0"},+ skip = ["3.13.8"],)- assert result is None+ assert result["Full"] == "3.13.9"+ assert calls[2:] == [+ f"python install --no-bin --no-registry {next_key}",+ f"python find --system --managed-python {next_key}",+ ]-def test_non_arm64_defers_to_uv_and_keeps_the_system_install_as_fallback():- detect = SOURCE.index("$DetectedPython = Remove-SkippedPython (Find-CompatiblePython)")- defer = SOURCE.index(- '$PythonFromUv = (-not $DetectedPython) -and ((Get-HostMachineArch) -ne "arm64")'+@needs_pwsh[email protected]("shell", POWERSHELLS)+def test_a_skipped_patch_falls_back_to_an_older_cached_one_offline(shell, tmp_path):+ older = "cpython-3.13.7-windows-x86_64-none"+ result, calls, _ = _resolve(+ shell,+ tmp_path,+ facts = {X64: "3.13.8 win-amd64 0", older: "3.13.7 win-amd64 0"},+ skip = ["3.13.8"],+ install_exit = 1,)- system_block = SOURCE.index("$InstallSystemPython = {")- immediate = SOURCE.index(- "if (-not $DetectedPython -and -not $PythonFromUv) {\n . $InstallSystemPython"+ assert result["Full"] == "3.13.7"+ assert f"python find --system --managed-python cpython-3.13.9-windows-x86_64-none" in calls+ assert calls[-1] == f"python find --system --managed-python {older}"+++@needs_pwsh[email protected]("shell", POWERSHELLS)+def test_an_explicit_patch_is_exact(shell, tmp_path):+ key = "cpython-3.13.9-windows-x86_64-none"+ ok, calls, _ = _resolve(shell, tmp_path, facts = {key: "3.13.9 win-amd64 0"}, patch = "3.13.9")+ assert ok["Full"] == "3.13.9" and calls[0].endswith(key)+ wrong, _, _ = _resolve(shell, tmp_path, facts = {key: "3.13.12 win-amd64 0"}, patch = "3.13.9")+ assert wrong is None+++# ── The request: --python > UNSLOTH_PYTHON > 3.13, exact, validated ──++REQUEST = _between(+ " $argList = $args\n", " # Env-var equivalent for web installs"+) + _between(+ " # Always a uv-managed CPython:",+ " # An elevated run writes",+)+++def _request(+ shell: str,+ args: list[str],+ env_python: str | None = None,+) -> str:+ quoted = ", ".join("'" + a.replace("'", "''") + "'" for a in args)+ script = f"""+$ErrorActionPreference = "Stop"+function Write-StudioLine {{ param([string]$Message, [string]$ForegroundColor) }}+function Exit-InstallFailure {{ param([string]$Message) return "EXIT" }}+function Probe {{+ $SkipTorch = $false+ $PackageName = "unsloth"+{REQUEST}+ return "$PythonVersion|$PythonPatchRequest"+}}+$a = @({quoted})+Probe @a+"""+ env = {"UNSLOTH_PYTHON": env_python} if env_python is not None else {"UNSLOTH_PYTHON": ""}+ return _pwsh(shell, script, env).splitlines()[-1]+++@needs_pwsh[email protected]("shell", POWERSHELLS)+ "args, env_python, expected",+ [+ ([], None, "3.13|"),+ (["--python", "3.12"], None, "3.12|"),+ (["--python=3.11"], None, "3.11|"),+ (["--python", "3.13.9"], None, "3.13|3.13.9"),+ ([], "3.12", "3.12|"),+ (["--python", "3.11"], "3.12", "3.11|"),+ (["--no-torch", "--python", "3.13.8"], None, "3.13|3.13.8"),+ (["--python", "3.10"], None, "EXIT"),+ (["--python", "3.14"], None, "EXIT"),+ (["--python", "3.13.8"], None, "EXIT"),+ (["--python"], None, "EXIT"),+ (["--python="], None, "EXIT"),+ ([], "C:\\Python312\\python.exe", "EXIT"),+ ],+)+def test_the_request(shell, args, env_python, expected):+ assert _request(shell, args, env_python) == expected+++# ── The choice made before uv exists: minor and architecture ──++CHOOSE = _function("Get-StudioVenvPythonMinor") + _between(+ " # ── uv-managed Python: minor and arch now", " $DetectedPython = $null\n"+)+++def _choose(+ shell: str,+ tmp_path: Path,+ *,+ host: str = "x86_64",+ native: bool = False,+ opt_out: bool = False,+ venv_cfg: str | None = None,+ explicit: str = "",+ upgrade: bool = False,+ legacy_cfg: str | None = None,+ legacy_layout: bool = True,+) -> str:+ venv = tmp_path / "venv"+ venv.mkdir(exist_ok = True)+ if venv_cfg is not None:+ (venv / "pyvenv.cfg").write_text(venv_cfg, encoding = "utf-8")+ home = tmp_path / "home"+ (home / ".venv").mkdir(parents = True, exist_ok = True)+ if legacy_cfg is not None:+ (home / ".venv" / "pyvenv.cfg").write_text(legacy_cfg, encoding = "utf-8")+ script = f"""+$ErrorActionPreference = "Stop"+function Write-TauriLog {{ param($a, $b) }}+function Write-StudioLine {{ param([string]$Message, [string]$ForegroundColor) }}+function step {{ param($a, $b, $c) }}+function substep {{ param($a, $b) }}+function Remove-IndexUrlCredentials {{ param($u) return $u }}+function Get-HostMachineArch {{ return "{host}" }}+function Initialize-WoaNativeCudaTorch {{+ param([string]$PythonMinor)+ $script:WoaNativeCudaTorch = ("{host}" -eq "arm64" -and ${str(native).lower()})+ $script:WoaTorchIndexUrl = "https://example.invalid/idx"+}}+{_function("Test-Arm64PythonOptOut")}+function Probe {{+ $PythonVersion = if ("{explicit}") {{ "{explicit}" }} else {{ "3.13" }}+ $PythonExplicitRequest = "{explicit}"+ $PythonPatchRequest = ""+ $VenvDir = $env:FAKE_VENV+ $StudioHome = $env:FAKE_HOME+ $studioUsesLegacyLayout = ${str(legacy_layout).lower()}+{CHOOSE}+ return "$PythonVersion|$PythonArch"+}}+Probe+"""+ env = {+ "FAKE_VENV": str(venv),+ "FAKE_HOME": str(home),+ "USERPROFILE": str(tmp_path / "profile"),+ "UNSLOTH_ALLOW_ARM64_PYTHON": "1" if opt_out else "",+ "UNSLOTH_TORCH_UPGRADE": "1" if upgrade else "",+ }+ return _pwsh(shell, script, env).splitlines()[-1]+++@needs_pwsh[email protected]("shell", POWERSHELLS)+ "kwargs, expected",+ [+ ({}, "3.13|x86_64"),+ # A reinstall keeps the environment's minor (uv writes version_info, venv writes version).+ ({"venv_cfg": "home = C:\\py\nversion_info = 3.12.6\n"}, "3.12|x86_64"),+ ({"venv_cfg": "home = C:\\py\nversion = 3.11.9\n"}, "3.11|x86_64"),+ ({"venv_cfg": "version_info = 3.14.0\n"}, "3.13|x86_64"),+ ({"venv_cfg": "version_info = 3.12.6\n", "upgrade": True}, "3.13|x86_64"),+ ({"venv_cfg": "version_info = 3.12.6\n", "explicit": "3.13"}, "3.13|x86_64"),+ # A legacy layout keeps its minor too; the current layout wins when both exist.+ ({"legacy_cfg": "version_info = 3.12.6\n"}, "3.12|x86_64"),+ ({"legacy_cfg": "version_info = 3.12.6\n", "legacy_layout": False}, "3.13|x86_64"),+ (+ {"legacy_cfg": "version_info = 3.12.6\n", "venv_cfg": "version_info = 3.11.9\n"},+ "3.11|x86_64",+ ),+ ({"legacy_cfg": "version_info = 3.12.6\n", "upgrade": True}, "3.13|x86_64"),+ # Windows on ARM: x64 under emulation unless the native CUDA stack or the opt-out applies.+ ({"host": "arm64"}, "3.13|x86_64"),+ ({"host": "arm64", "native": True}, "3.13|arm64"),+ ({"host": "arm64", "opt_out": True}, "3.13|arm64"),+ ({"opt_out": True}, "3.13|x86_64"),+ ],+)+def test_the_choice(shell, tmp_path, kwargs, expected):+ assert _choose(shell, tmp_path, **kwargs) == expected+++# ── Resolution after uv: a failed native ARM64 build degrades to x64, anything else stops ──++RESOLVE_SITE = _between(+ " $DetectedPython = Resolve-UvManagedPython -Minor $PythonVersion",+ ' step "python" "using uv-managed Python',+)+++def _site(+ shell: str,+ arch: str,+ ok_arches: str,+ opt_out: bool = False,+) -> str:+ script = f"""+$ErrorActionPreference = "Stop"+function Write-StudioLine {{ param([string]$Message, [string]$ForegroundColor) }}+function substep {{ param($a, $b) }}+function Exit-InstallFailure {{ param([string]$Message) return "EXIT" }}+function Resolve-UvManagedPython {{+ param([string]$Minor, [string]$Patch, [string]$Arch)+ if (("{ok_arches}" -split ",") -contains $Arch) {{+ return @{{ Version = $Minor; Full = "$Minor.12"; Path = "p"; Arch = $Arch }}+ }}+ return $null+}}+{_function("Test-Arm64PythonOptOut")}+function Probe {{+ $PythonVersion = "3.13"; $PythonPatchRequest = ""; $PythonRequestLabel = "3.13"+ $PythonArch = "{arch}"+ $script:WoaNativeCudaTorch = ("{arch}" -eq "arm64")+{RESOLVE_SITE}+ return "$($DetectedPython.Arch)|$script:WoaNativeCudaTorch"+}}+Probe+"""+ return _pwsh(+ shell, script, {"UNSLOTH_ALLOW_ARM64_PYTHON": "1" if opt_out else ""}+ ).splitlines()[-1]+++@needs_pwsh[email protected]("shell", POWERSHELLS)+ "arch, ok_arches, opt_out, expected",+ [+ ("x86_64", "x86_64", False, "x86_64|False"),+ ("arm64", "arm64,x86_64", False, "arm64|True"),+ ("arm64", "x86_64", False, "x86_64|False"),+ ("arm64", "x86_64", True, "EXIT"),+ ("x86_64", "", False, "EXIT"),+ ],+)+def test_the_resolution(shell, arch, ok_arches, opt_out, expected):+ assert _site(shell, arch, ok_arches, opt_out) == expected+++# ── A legacy environment is reused only on the uv-managed Python this install resolved ──++STORE_HOME = "store/cpython-3.13.12-windows-x86_64-none"+++@needs_pwsh[email protected]("shell", POWERSHELLS)+ "home, version, exact, expected",+ [+ (STORE_HOME, "3.13.12", False, "True"),+ (STORE_HOME, "3.13.9", False, "True"), # same minor, another patch+ (STORE_HOME, "3.13.9", True, "False"), # --python 3.13.12 asked for exactly+ ("store/cpython-3.12.13-windows-x86_64-none", "3.12.13", False, "False"),+ ("Python312", "3.13.12", False, "False"), # the user's own Python+ ("store/cpython-3.13.12-windows-aarch64-none", "3.13.12", False, "False"), # another arch+ (STORE_HOME, None, False, "False"),+ (None, None, False, "False"),+ ],+)+def test_a_legacy_environment_is_reused_only_on_the_resolved_python(+ shell, tmp_path, home, version, exact, expected+):+ (tmp_path / "uv.ps1").write_text(FAKE_UV, encoding = "utf-8")+ venv = tmp_path / "legacy"+ venv.mkdir()+ if home is not None:+ cfg = f"home = {tmp_path / home}\n"+ if version:+ cfg += f"version_info = {version}\n"+ (venv / "pyvenv.cfg").write_text(cfg, encoding = "utf-8")+ script = f"""+$ErrorActionPreference = "Stop"+$script:UvExe = $env:FAKE_UV_EXE+{_function("Test-LegacyVenvReusable")}+$py = @{{ Version = "3.13"; Full = "3.13.12"; Path = "p"; Arch = "x86_64" }}+Test-LegacyVenvReusable -VenvDir $env:FAKE_VENV -Python $py -Exact ${str(exact).lower()}+"""+ out = _pwsh(+ shell,+ script,+ {+ "FAKE_UV_EXE": str(tmp_path / "uv.ps1"),+ "FAKE_UV_LOG": str(tmp_path / "uv.log"),+ "FAKE_UV_DIR": str(tmp_path / "store"),+ "FAKE_VENV": str(venv),+ },)+ assert out.splitlines()[-1] == expected+++def test_pyvenv_cfg_is_read_as_utf8():+ # uv writes it without a BOM; Windows PowerShell 5.1 would otherwise decode a non-ASCII home as ANSI.+ for name in ("Get-StudioVenvPythonMinor", "Test-LegacyVenvReusable"):+ assert "Get-Content -LiteralPath $cfg -Encoding UTF8" in _function(name), name+++def test_no_path_reaches_a_python_already_on_the_machine():+ for gone in (+ "Find-CompatiblePython",+ "Install-PythonFromPythonOrg",+ "Install-X64Python",+ '"Python.Python.',+ "python.org/ftp/python",+ '"-0p"',+ ):+ assert gone not in SOURCE, goneuv_ready = SOURCE.index("Set-StudioUvCacheEnvironment -StudioRoot $StudioHome")- resolve = SOURCE.index("$DetectedPython = Resolve-UvManagedPython")- fallback = SOURCE.index(". $InstallSystemPython", resolve)+ resolve = SOURCE.index("$DetectedPython = Resolve-UvManagedPython -Minor")+ rollback = SOURCE.index("Start-StudioVenvRollback -ExistingDir $VenvDir")venv = SOURCE.index("& $script:UvExe venv $VenvDir --python")- assert detect < defer < system_block < immediate < uv_ready < resolve < fallback < venv- assert SOURCE.count(". $InstallSystemPython") == 2- winget = SOURCE.index("& $script:WingetExe install -e --id $pythonPackageId")- assert system_block < winget < immediate+ # Resolved before the existing environment is moved aside, so a failure leaves it intact.+ assert uv_ready < resolve < rollback < venvdiff --git a/tests/studio/install/test_woa_torch_index_persistence.py b/tests/studio/install/test_woa_torch_index_persistence.pyindex 6f95d3c415e..9e006324a52 100644--- a/tests/studio/install/test_woa_torch_index_persistence.py+++ b/tests/studio/install/test_woa_torch_index_persistence.py@@ -34,7 +34,6 @@ from woa_ps_harness import (CORP_INDEX,INSTALL_PS1,INSTALL_SRC,- INVOKE_RESTMETHOD_NO_NETWORK,INVOKE_RESTMETHOD_OFFLINE,JOIN_URL_PATH,JOIN_URL_RETURNS_BASE,@@ -46,7 +45,6 @@ from woa_ps_harness import (NV_NIGHTLY,PACKAGE_ROOT,PWSH,- PYARROW_FLOOR,PYARROW_USABLE_FUNCS,PYPI,SETUP_PS1,@@ -1109,17 +1107,6 @@ class TestTheProbeAsksForTheInterpretersAbi:got = _ps_last(script)[1:-1]assert bool(got) is found, got- def test_the_probe_takes_the_flag_and_the_call_sites_supply_it(self):- assert (- "function Initialize-WoaNativeCudaTorch {\n param([string]$PythonMinor,"- " [bool]$FreeThreaded = $false)" in INSTALL_SRC- )- # Both re-probes know which interpreter was chosen, so both must answer for it.- # The flag is read into a variable first: a same-minor free-threaded build re-probes too.- assert INSTALL_SRC.count("Test-PythonFreeThreaded -PythonExe $DetectedPython.Path") == 2- assert "-FreeThreaded $WoaDetectedFreeThreaded" in INSTALL_SRC- assert "-FreeThreaded $_woaNewFreeThreaded" in INSTALL_SRC-def test_the_staging_scan_uses_the_venv_abi(self):"""Keyed on the python tag, staging kept the cp313-cp313 wheels a free-threaded venvcannot install and discarded the cp313-cp313t ones it can."""@@ -1156,50 +1143,6 @@ class TestTheProbeAsksForTheInterpretersAbi:assert _ps_last(script) == expected-class TestTheAbiReprobeFiresOnAMatchingMinor:- """The hole left by keying the re-probe on the minor alone."""-- def test_the_guard_compares_the_abi_as_well_as_the_minor(self):- assert "$WoaProbedFreeThreaded = $false" in INSTALL_SRC- assert (- "($WoaDetectedFreeThreaded -ne $WoaProbedFreeThreaded)" in INSTALL_SRC- ), "a 3.13t selected for a 3.13 request matches on minor and must still re-probe"-- def test_the_second_reprobe_compares_it_too(self):- """After Install-PythonFromPythonOrg the ABI can change without the minor doing so."""- assert "($_woaNewFreeThreaded -ne $WoaProbedFreeThreaded)" in INSTALL_SRC-- def test_the_detection_is_scoped_to_this_host(self):- """A subprocess per run on every Windows x64 host would buy nothing."""- block = INSTALL_SRC[INSTALL_SRC.index("$WoaDetectedFreeThreaded = $false") :][:600]- assert '(Get-HostMachineArch) -eq "arm64"' in block-- @requires_pwsh- @pytest.mark.parametrize(- "probed_minor, probed_ft, minor, ft, should_reprobe, why",- [- ("3.13", False, "3.13", False, False, "nothing changed"),- ("3.13", False, "3.12", False, True, "a different minor, as before"),- ("3.13", False, "3.13", True, True, "THE BUG: same minor, free-threaded"),- ("3.13", True, "3.13", False, True, "and back again, after a GIL install"),- ],- )- def test_the_guard_decides_correctly(- self, probed_minor, probed_ft, minor, ft, should_reprobe, why- ):- script = _script(- f"$WoaProbedMinor = '{probed_minor}'",- f"$WoaProbedFreeThreaded = ${str(probed_ft).lower()}",- f"$DetectedPython = @{{ Version = '{minor}' }}",- f"$WoaDetectedFreeThreaded = ${str(ft).lower()}",- "if ($DetectedPython -and (",- " ($DetectedPython.Version -ne $WoaProbedMinor) -or",- " ($WoaDetectedFreeThreaded -ne $WoaProbedFreeThreaded))) {",- " Write-Output 'REPROBE' } else { Write-Output 'SKIP' }",- )- assert (_ps_last(script) == "REPROBE") is should_reprobe, why--class TestAnExplicitPinOutranksThePersistedIndex:"""The recovery is a memory of what install.ps1 chose, not a decision."""@@ -4966,77 +4909,6 @@ class TestASuppliedWheelUnderAnotherNameIsReadFromItsArchive:assert self._probe(str(wheel)) == "local"-class TestAReselectedInterpreterIsProbedBeforeItIsTaken:- """After the re-probe flips native mode, Find-CompatiblePython runs again with the new arch- preference and ranks the requested minor first. It could hand back an ARM64 3.12 whose probe- had failed while the flip came from 3.13, and the 3.13 answers were then carried into a 3.12- venv. The reselected interpreter is probed too, and the accepted answer restored."""-- @staticmethod- def _block():- # Anchored on the code either side rather than on the comments that head them.- return slice_between(- INSTALL_SRC,- " $WoaProbedMinor = $PythonVersion",- " if ($script:WoaNativeCudaTorch -and $DetectedPython -and $DetectedPython.Arch -eq"- ' "x86_64") {',- )-- def _run(self, detected, reselected, native_minors):- natives = ", ".join(f"'{m}'" for m in native_minors)- script = _script(- "$PythonVersion = '3.12'",- substep_collector(),- "$script:Probes = @()",- "function step { param($a, $b, $c) }",- "function Get-HostMachineArch { 'arm64' }",- "function Remove-IndexUrlCredentials { param($u) $u }",- "function Test-PythonFreeThreaded { param($PythonExe) $false }",- "function Remove-SkippedPython { param($p) $p }",- f"$script:Natives = @({natives})",- "$script:WoaNativeCudaTorch = $false",- "function Initialize-WoaNativeCudaTorch { param($PythonMinor, $FreeThreaded)",- " $script:Probes += $PythonMinor",- " $script:WoaNativeCudaTorch = [bool]($script:Natives -contains $PythonMinor)",- " $script:WoaTorchIndexUrl = if ($script:WoaNativeCudaTorch) { 'https://i.test' }"- " else { $null } }",- f"$DetectedPython = @{{ Version = '{detected[0]}'; Path = 'p{detected[0]}';"- f" Arch = '{detected[1]}' }}",- f"function Find-CompatiblePython {{ @{{ Version = '{reselected[0]}';"- f" Path = 'p{reselected[0]}'; Arch = '{reselected[1]}' }} }}",- self._block(),- "Write-Output ('PY=' + $DetectedPython.Version)",- "Write-Output ('NATIVE=' + $script:WoaNativeCudaTorch)",- "Write-Output ('PROBED=' + $WoaProbedMinor)",- "Write-Output ('PROBES=' + ($script:Probes -join ','))",- "Write-Output ('MSG=' + ($script:Messages -join ' | '))",- )- return _ps_kv(script)-- @requires_pwsh- def test_a_reselected_minor_without_a_stack_is_not_taken(self):- # Requested 3.12 (no stack); detected 3.13 goes native; the reselection offers ARM64 3.12.- out = self._run(("3.13", "arm64"), ("3.12", "arm64"), ["3.13"])- assert out["PY"] == "3.13", out["MSG"]- assert out["NATIVE"] == "True" and out["PROBED"] == "3.13"- assert (- out["PROBES"] == "3.13,3.12,3.13"- ), "probed the offer, then restored the accepted answer"- assert "keeping Python 3.13, which has one" in out["MSG"]-- @requires_pwsh- def test_a_reselected_minor_with_a_stack_is_taken(self):- out = self._run(("3.13", "arm64"), ("3.12", "arm64"), ["3.13", "3.12"])- assert out["PY"] == "3.12" and out["NATIVE"] == "True" and out["PROBED"] == "3.12"- assert out["PROBES"] == "3.13,3.12"-- @requires_pwsh- def test_the_same_interpreter_back_is_not_probed_again(self):- out = self._run(("3.13", "x86_64"), ("3.13", "arm64"), ["3.13"])- assert out["PY"] == "3.13" and out["NATIVE"] == "True"- assert out["PROBES"] == "3.13"--class TestTheResolverVariablesDoNotOutliveTheInstaller:"""Under `irm | iex` the process-scoped UV_OVERRIDE, UV_FIND_LINKS and PIP_FIND_LINKS set forthe native stack were the caller's own session variables and stayed set, so every laterdiff --git a/tests/test_installer_profile_hardening.py b/tests/test_installer_profile_hardening.pyindex f03ba017cf4..12c5141c429 100644--- a/tests/test_installer_profile_hardening.py+++ b/tests/test_installer_profile_hardening.py@@ -634,10 +634,11 @@ def test_an_alias_to_a_real_uv_is_followed_to_the_executable(tmp_path):def test_no_bare_winget_token_survives_at_a_call_site():- """winget installs both Python and uv, so an alias on it owns the same ground.+ """winget installs uv, so an alias on it owns the same ground.- Detection used a bare Get-Command, and all five invocations were bare tokens, so the fix- applied to uv left the other half of the bootstrap exposed to the identical wrapper.+ Detection used a bare Get-Command and every invocation was a bare token, so the fix applied+ to uv left the winget half of the bootstrap exposed to the identical wrapper. (Python itself+ no longer comes from winget: the Studio environment is always on a uv-managed Python.)"""src = _install_ps1()assert (@@ -646,7 +647,7 @@ def test_no_bare_winget_token_survives_at_a_call_site():for bare in ("\n winget ", "\n winget ", "{ winget "):assert bare not in src, f"winget must be invoked through the resolved path, found {bare!r}"assert (- src.count("& $script:WingetExe ") >= 5+ src.count("& $script:WingetExe ") >= 2), "every winget invocation must route through the resolved path"