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
Installers: require x64 Python on Windows on ARM, and respect active conda (#11024)
Daniel Han37a66c8a7850
diff --git a/install.ps1 b/install.ps1index b624a71984e..3f9889e9b15 100644--- a/install.ps1+++ b/install.ps1@@ -3288,12 +3288,83 @@ exit 1# ── Helper: refresh PATH from registry (deduplicating entries) ──# Merge order: venv Scripts (if active) > Machine > User > current $env:Path.# Dedup compares both raw and expanded forms (%VAR% vs literal).+ # Every prefix an active conda session has put on PATH, deepest first: CONDA_PREFIX is+ # the active environment, CONDA_PREFIX_1.. the ones it was stacked on, and CONDA_EXE+ # names the installation root, which is on PATH for the whole session.+ function Get-ActiveCondaPrefixes {+ $prefixes = New-Object System.Collections.Generic.List[string]+ if (-not [string]::IsNullOrWhiteSpace($env:CONDA_PREFIX)) { $prefixes.Add($env:CONDA_PREFIX) }+ # Enumerated from CONDA_SHLVL, not a fixed list: a hard-coded tail of three dropped+ # everything past the fourth stacked environment, which sorted its PATH entries+ # after Machine and User and inverted the ordering the stack established. The+ # ceiling stops a bad value spinning.+ $levels = 0+ if (-not [string]::IsNullOrWhiteSpace($env:CONDA_SHLVL)) {+ [void][int]::TryParse($env:CONDA_SHLVL, [ref]$levels)+ }+ if ($levels -lt 1) { $levels = 1 }+ if ($levels -gt 64) { $levels = 64 }+ for ($level = 1; $level -le $levels; $level++) {+ $value = [Environment]::GetEnvironmentVariable("CONDA_PREFIX_$level")+ if (-not [string]::IsNullOrWhiteSpace($value)) { $prefixes.Add($value) }+ }+ if (-not [string]::IsNullOrWhiteSpace($env:_CONDA_ROOT)) { $prefixes.Add($env:_CONDA_ROOT) }+ if (-not [string]::IsNullOrWhiteSpace($env:CONDA_EXE)) {+ # ...\<root>\Scripts\conda.exe -> ...\<root>. Regex rather than Split-Path, which+ # is provider-aware and does not treat a backslash as a separator on the+ # non-Windows PowerShell the tests run under.+ $scripts = $env:CONDA_EXE -replace '[\\/][^\\/]*$', ''+ $root = $scripts -replace '[\\/][^\\/]*$', ''+ if ($root -and $root -ne $env:CONDA_EXE) { $prefixes.Add($root) }+ }+ return $prefixes+ }++ # Is $Path inside one of $Prefixes? On a directory boundary, so "C:\conda-backup" is not+ # dragged to the front along with "C:\conda".+ function Test-PathUnderCondaPrefix {+ param([string]$Path, $Prefixes)+ if ([string]::IsNullOrWhiteSpace($Path) -or -not $Prefixes) { return $false }+ $candidate = [Environment]::ExpandEnvironmentVariables($Path).Trim().Trim('"').TrimEnd('\')+ if (-not $candidate) { return $false }+ foreach ($prefix in $Prefixes) {+ $normalized = [Environment]::ExpandEnvironmentVariables($prefix).Trim().Trim('"').TrimEnd('\')+ if (-not $normalized) { continue }+ if ($candidate -ieq $normalized) { return $true }+ if ($candidate.StartsWith($normalized + '\', [System.StringComparison]::OrdinalIgnoreCase)) {+ return $true+ }+ }+ return $false+ }+function Refresh-SessionPath {$machine = [System.Environment]::GetEnvironmentVariable("Path", "Machine")$user = [System.Environment]::GetEnvironmentVariable("Path", "User")$venvScripts = if ($env:VIRTUAL_ENV) { Join-Path $env:VIRTUAL_ENV "Scripts" } else { $null }+ # An activated conda environment lives ONLY in the process PATH, so rebuilding as+ # machine + user + previous demotes it, and under `irm | iex` that PATH is the+ # caller's own prompt. Restored by position; the dedup below drops the copies.+ $condaFront = @()+ if (Test-ActiveCondaEnvironment) {+ $prefixes = Get-ActiveCondaPrefixes+ if ($prefixes) {+ foreach ($entry in ($env:Path -split ";")) {+ if (Test-PathUnderCondaPrefix -Path $entry -Prefixes $prefixes) {+ $condaFront += $entry+ }+ }+ } else {+ # A hook exporting CONDA_DEFAULT_ENV and no directory: nothing names which+ # entries are conda's, and guessing from the name would promote a stranger,+ # so the caller's PATH is kept whole and in front.+ $condaFront = @($env:Path)+ }+ }$sources = @()+ # Still first: this is the environment the installer is driving, and it is ours.if ($venvScripts) { $sources += $venvScripts }+ $sources += $condaFront$sources += @($machine, $user, $env:Path)$merged = ($sources | Where-Object { $_ }) -join ";"$seen = @{}@@ -3310,6 +3381,30 @@ exit 1$env:Path = $unique -join ";"}+ # ── Helper: is a conda environment ACTIVE in this session? ──+ # CONDA_PREFIX separates "conda is installed" from "we are inside one of its+ # environments". CONDA_DEFAULT_ENV is read too: a hook that exports only that one still+ # leaves the caller inside conda's PATH ordering.+ function Test-ActiveCondaEnvironment {+ foreach ($condaVar in @($env:CONDA_PREFIX, $env:CONDA_DEFAULT_ENV)) {+ if (-not [string]::IsNullOrWhiteSpace($condaVar)) { return $true }+ }+ return $false+ }++ # The position a PERSISTENT PATH write may actually use. A prepend outlives the conda+ # activation it was made under, so conda ends up resolving binaries and DLLs out of our+ # directory, which is what corrupts an Anaconda base on its next `conda update` (#5871).+ # An append registers the same directory without demoting anything.+ function Resolve-UserPathPosition {+ param(+ [ValidateSet('Append','Prepend')]+ [string]$Position = 'Append'+ )+ if ($Position -eq 'Prepend' -and (Test-ActiveCondaEnvironment)) { return 'Append' }+ return $Position+ }+# ── Helper: safely add a directory to the persistent User PATH ──# Direct registry access preserves REG_EXPAND_SZ (dotnet/runtime#1442).function Add-ToUserPath {@@ -3318,6 +3413,23 @@ exit 1[ValidateSet('Append','Prepend')][string]$Position = 'Append')+ # Every persistent PATH write goes through Resolve-UserPathPosition, so an active+ # conda environment cannot be demoted by any call site. Announced once per run: the+ # installer makes several of these writes and one note is information, five is noise.+ $resolvedPosition = Resolve-UserPathPosition -Position $Position+ # A downgraded request has to be able to MOVE an entry, not just decline to add one. After a+ # previous non-conda run our directory is already at the FRONT of the User PATH, and the+ # append-idempotent early return below would leave that ordering in place while this very+ # substep announced that conda keeps priority -- the #5871 demotion, still armed, reported as+ # fixed. Only a genuine Append request keeps the cheap no-op.+ $positionDowngraded = ($resolvedPosition -ne $Position)+ if ($positionDowngraded) {+ if (-not $script:CondaPathPositionNoted) {+ $script:CondaPathPositionNoted = $true+ substep "conda environment active ($env:CONDA_PREFIX) -- appending to PATH instead of prepending, so conda keeps priority." "Yellow"+ }+ $Position = $resolvedPosition+ }try {$regKey = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey('Environment')try {@@ -3340,7 +3452,9 @@ exit 1$kept.Add($entries[$i])}$alreadyPresent = $matchIndices.Count -gt 0- if ($alreadyPresent -and $Position -eq 'Append') { # Append: idempotent no-op+ # Not $positionDowngraded: that request has to reposition an existing front entry.+ # Already at the back is still a no-op, caught by the $newPath -ceq $rawPath check.+ if ($alreadyPresent -and $Position -eq 'Append' -and -not $positionDowngraded) {return $false}if ($alreadyPresent -and $Position -eq 'Prepend' -and # Prepend: no-op if already at front@@ -5291,7 +5405,14 @@ exit 0# 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.- $preferArm64 = $script:WoaNativeCudaTorch -and -not $X64Only+ # 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 = @()@@ -5382,6 +5503,17 @@ exit 0$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 }@@ -5399,6 +5531,14 @@ exit 0return $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.@@ -5454,13 +5594,13 @@ exit 0return $null}- # Per-user install => no UAC. PrependPath puts python + py on PATH;+ # 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",- "PrependPath=1",+ (Get-PythonInstallerPathSwitch),"Include_launcher=1",# Launcher per-user too: Include_launcher defaults to all-users, which needs admin."InstallLauncherAllUsers=0",@@ -5506,6 +5646,19 @@ exit 0# ── 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"@@ -5518,13 +5671,137 @@ exit 0if ($found -and $found.Arch -eq "x86_64") { return $found }substep "winget could not provide an x64 Python -- trying python.org..." "Yellow"}- $found = Install-PythonFromPythonOrg -Arch "x86_64"- if ($found -and $found.Arch -eq "x86_64") { return $found }+ # $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.+ function Test-Arm64PythonOptOut {+ return ($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,+ # 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 {+ param(+ [Parameter(Mandatory = $true)][string]$VenvPython,+ $SelectedPython,+ [string]$RecordedTag = $null+ )+ if ((Get-HostMachineArch) -ne "arm64") { return $false }+ # The interpreter may be gone: a reinstall moves the environment to its rollback path+ # BEFORE the x64 Python is chosen, so probing $VenvPython here would answer "no+ # mismatch" for every existing install. $RecordedTag is the tag read before that move.+ $tag = $null+ if (Test-Path -LiteralPath $VenvPython -PathType Leaf) {+ $tag = Get-PythonPlatformTag $VenvPython+ } elseif ($RecordedTag) {+ $tag = $RecordedTag+ }+ # 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.+ 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+ # tree aside and the new one IS on x64.+ if ($SelectedPython -and $SelectedPython.Arch -eq "x86_64") {+ substep "windows on arm: UNSLOTH_ALLOW_ARM64_PYTHON is set, but no ARM64 Python is left on" "Yellow"+ substep "this machine, so the new environment is built on x64; the ARM64 one is kept." "Yellow"+ } else {+ substep "windows on arm: UNSLOTH_ALLOW_ARM64_PYTHON is set, so the environment is not rebuilt on x64." "Yellow"+ }+ return $false+ }+ if (-not $SelectedPython -or $SelectedPython.Arch -ne "x86_64") { return $false }+ return $true+ }+# ── Install Python if no compatible version (3.11-3.13) found ──Write-TauriLog "STEP" "Installing Python"Initialize-WoaNativeCudaTorch -PythonMinor $PythonVersion@@ -5542,7 +5819,20 @@ exit 0$pythonPackageId = "Python.Python.$PythonVersion"$wingetExit = $null- if ($script:WingetAvailable) {+ # 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"@@ -5570,7 +5860,10 @@ exit 0}}- if (-not $DetectedPython) {+ # $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 {@@ -5660,24 +5953,30 @@ exit 0$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+ }+ }+# ── Windows on ARM: swap a native ARM64 interpreter for x64 ──- # pyarrow and hf-transfer publish no win_arm64 wheel, so an ARM64 Python source-builds- # both and fails deep into the run. Warn up front if x64 is unobtainable. Not on native.+ # 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") {- substep "windows on arm: only a native ARM64 Python $($DetectedPython.Version) was found." "Yellow"- substep "pyarrow and hf-transfer publish no win_arm64 wheels, so installing x64 Python..." "Yellow"- $X64Python = Install-X64Python- if ($X64Python) {- $DetectedPython = $X64Python- step "python" "using x64 Python $($DetectedPython.Version) under emulation"- } else {- Write-StudioLine "[WARN] Could not install an x64 Python on this ARM64 machine." -ForegroundColor Yellow- Write-StudioLine " Continuing with ARM64 Python $($DetectedPython.Version), but the install is likely to fail:" -ForegroundColor Yellow- Write-StudioLine " pyarrow (via datasets) and hf-transfer ship no win_arm64 wheels and will be" -ForegroundColor Yellow- Write-StudioLine " built from source, which needs CMake plus the MSVC and Rust toolchains." -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+ $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")}}@@ -6040,6 +6339,12 @@ exit 0$_Migrated = $false$script:StudioVenvRollbackDir = $null$script:StudioVenvRollbackTarget = $VenvDir+ # Set only by the Windows-on-ARM architecture rebuild, which promises the user the old+ # environment survives the run. Every other rollback is deleted once the replacement+ # commits, which is right: it is the same architecture and the same packages.+ $script:StudioVenvRollbackPreserve = $false+ # The existing interpreter's platform tag, read before any rollback move takes it away.+ $script:PrevVenvPlatformTag = $null$script:StudioVenvRollbackActive = $false$script:StudioVenvRollbackPartial = $false# Reset per run: under `irm | iex` the script scope IS the caller's session.@@ -6298,6 +6603,9 @@ exit 0# put one half of a committed install back and keep the other.if ($script:StudioInstallCommitted) { return }if (-not $script:StudioVenvRollbackActive) { return }+ # A restore puts the tree back at $VenvDir, so there is nothing left to preserve and+ # the flag must not survive into any later rollback in the same run.+ $script:StudioVenvRollbackPreserve = $false$backup = $script:StudioVenvRollbackDir$target = $script:StudioVenvRollbackTargetif (-not (Test-StudioPathPresent -Path $backup)) {@@ -6360,9 +6668,36 @@ exit 0$script:StudioVenvRollbackActive = $false$script:StudioVenvRollbackDir = $null$script:StudioVenvRollbackPartial = $false- if (Test-StudioPathPresent -Path $backup) {- Remove-StudioVenvTreeWithRetry -Path $backup -Label "environment rollback" | Out-Null+ $preserve = $script:StudioVenvRollbackPreserve+ $script:StudioVenvRollbackPreserve = $false+ if (-not (Test-StudioPathPresent -Path $backup)) { return }+ if ($preserve) {+ # The architecture rebuild told the user this tree would still be here to copy+ # packages out of, so keep the promise instead of the disk space. Renamed out of+ # the rollback namespace: Remove-StaleStudioVenvRollbacks globs+ # unsloth_studio.rollback.*, and a preserved copy left under that name would be+ # swept by the next run as soon as this PID stopped existing.+ $stamp = Get-Date -Format "yyyyMMddHHmmss"+ $kept = Join-Path $StudioHome "unsloth_studio.arm64.$stamp"+ $suffix = 0+ while (Test-Path -LiteralPath $kept) {+ $suffix+++ $kept = Join-Path $StudioHome "unsloth_studio.arm64.$stamp.$suffix"+ }+ try {+ Move-Item -LiteralPath $backup -Destination $kept -ErrorAction Stop+ substep "previous ARM64 environment kept at $kept"+ substep "delete it once you have re-installed any extra packages you had added to it."+ return+ } catch {+ # Naming it is the whole point, so a failed rename reports where it actually+ # is rather than silently deleting the copy the user was told to expect.+ Write-StudioLine "[WARN] Could not rename the previous ARM64 environment: $($_.Exception.Message)" -ForegroundColor Yellow+ Write-StudioLine " It is still at $backup" -ForegroundColor Yellow+ return+ }}+ Remove-StudioVenvTreeWithRetry -Path $backup -Label "environment rollback" | Out-Null}# Bounded probe (async-drained, 30s) so a wedged "import torch" cannot stall the installer.@@ -6424,6 +6759,12 @@ exit 0if (-not $SkipTorch) {$script:PrevTorchVer = Get-InstalledTorchVersionRaw -PythonExe $VenvPython}+ # And the interpreter's architecture, for the same reason and while it can still be+ # read: the move below takes $VenvPython with it, and the Windows-on-ARM rebuild+ # decision is made after the x64 Python is chosen, which is after that point.+ if ((Get-HostMachineArch) -eq "arm64" -and (Test-Path -LiteralPath $VenvPython -PathType Leaf)) {+ $script:PrevVenvPlatformTag = Get-PythonPlatformTag $VenvPython+ }# New layout already exists -- replace only after preserving rollback copy.substep "preserving existing environment for rollback..."try {@@ -6488,6 +6829,58 @@ exit 0$_Migrated = $true}+ # Re-check what is about to be REUSED, not only what was selected: see+ # Test-StudioVenvArchMismatch. Preserved through the ordinary rollback helper, so the+ # previous environment is restored if anything later in this run fails, and cleared from+ # $VenvDir so the branch below creates a fresh one on the x64 interpreter.+ if (Test-StudioVenvArchMismatch -VenvPython $VenvPython -SelectedPython $DetectedPython `+ -RecordedTag $script:PrevVenvPlatformTag) {+ substep "windows on arm: the existing environment runs native ARM64 Python, which cannot" "Yellow"+ substep "resolve pyarrow or hf-transfer -- rebuilding it on x64 Python $($DetectedPython.Version)." "Yellow"+ # Stated, not implied: the new environment is built from scratch on a different+ # architecture, so the ARM64 wheels in the old one cannot be carried into it and+ # anything the user pip-installed there is not reinstalled. The old tree is kept+ # under $StudioHome as unsloth_studio.arm64.* rather than deleted with the ordinary+ # rollback, so it can still be read: $script:StudioVenvRollbackPreserve below.+ substep "the ARM64 environment is kept under $StudioHome as unsloth_studio.arm64.*;" "Yellow"+ substep "re-install any extra packages you had added to it, or set UNSLOTH_ALLOW_ARM64_PYTHON=1 to keep it." "Yellow"+ try {+ if ($script:StudioVenvRollbackActive) {+ # The ordinary reinstall already moved this environment aside; a second+ # Start-StudioVenvRollback would try to move a directory that is no longer+ # there and throw, taking every architecture migration out through+ # Exit-InstallFailure. The tree is already where this branch wants it, so+ # all that is left is to mark it kept rather than swept.+ $script:StudioVenvRollbackPreserve = $true+ } else {+ Start-StudioVenvRollback -ExistingDir $VenvDir+ # After the move, so a rollback that never started cannot leave the flag set+ # for some later unrelated rollback to act on.+ $script:StudioVenvRollbackPreserve = $true+ }+ } catch {+ Write-StudioLine "[ERROR] Could not move the ARM64 environment aside: $($_.Exception.Message)" -ForegroundColor Red+ Write-StudioLine " Close Unsloth Studio, including its tray process, then re-run install.ps1." -ForegroundColor Yellow+ return (Exit-InstallFailure "Could not replace the native ARM64 environment at $VenvDir")+ }+ # Left set, the migrated-environment branch below would --no-deps into a fresh venv.+ $_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.+ if ($script:PrevVenvPlatformTag -eq "win-arm64" -and (Test-Arm64PythonOptOut) -and+ $script:StudioVenvRollbackActive) {+ $script:StudioVenvRollbackPreserve = $true+ substep "windows on arm: keeping the existing native ARM64 environment under" "Yellow"+ substep "$StudioHome as unsloth_studio.arm64.*; the new environment is built on" "Yellow"+ substep "Python $($DetectedPython.Version) ($($DetectedPython.Arch))." "Yellow"+ }+# A migrated environment has to be ARM64 too: an x64 one has a Triton that cannot do sm_121.if ($script:WoaNativeCudaTorch -and $_Migrated -and (Test-Path -LiteralPath $VenvPython)) {$_woaMigPlatform = ""diff --git a/install.sh b/install.shindex b80f8f0ec00..5a4f19a3fdd 100755--- a/install.sh+++ b/install.sh@@ -6315,27 +6315,111 @@ _path_has_dir() {}# fish reads none of the POSIX rc files, so an `export` line is a no-op for a fish user: the next session resolves neither uv nor the shim. conf.d is fish's own drop-in directory and fish_add_path is idempotent by design. ~/.config, not XDG_CONFIG_HOME, because that is where astral's installer put its own fish file.+# Is a conda environment ACTIVE in this shell? Both variables, matching install.ps1: a hook+# exporting only CONDA_DEFAULT_ENV still leaves the caller inside conda's PATH ordering.+# Replace a line THIS installer wrote with the form the current run needs, in place. A+# previous run outside conda persisted the PREPEND spelling, and the presence checks below+# accept any spelling, so without this the prepend would survive for ever (#5871). Only an+# exact whole-line match on what we write is touched, and the content is copied back into the+# ORIGINAL file so a symlinked rc keeps its link, mode and owner. A file that cannot be+# rewritten is a warning, never a failure.+_unsloth_repoint_rc_line() {+ [ -f "$1" ] || return 1+ # OURS, not merely matching: a hand-written `export PATH="$HOME/.local/bin:$PATH"` is a+ # line users have too, and demoting theirs would move that whole directory behind the+ # rest of PATH for good. The `# Added by Unsloth` marker above the line is the ownership+ # record, so a line without one is left alone.+ _URRL_OLD="$2" awk '+ $0 == ENVIRON["_URRL_OLD"] && prev ~ /^# Added by Unsloth/ { found = 1 }+ { prev = $0 }+ END { exit(found ? 0 : 1) }+ ' "$1" 2>/dev/null || return 1+ # Staged and renamed, because `cat tmp > file` truncates the profile first and an+ # interrupt leaves wreckage. Onto the RESOLVED path: renaming over a chezmoi or stow+ # symlink would replace it with a regular file. `readlink -f` is GNU-only, hence the walk.+ _urrl_real="$1"+ _urrl_hops=0+ while [ -L "$_urrl_real" ] && [ "$_urrl_hops" -lt 40 ]; do+ _urrl_hops=$((_urrl_hops + 1))+ _urrl_target="$(readlink -- "$_urrl_real" 2>/dev/null)" || break+ [ -n "$_urrl_target" ] || break+ case "$_urrl_target" in+ /*) _urrl_real="$_urrl_target" ;;+ *) _urrl_real="$(dirname -- "$_urrl_real")/$_urrl_target" ;;+ esac+ done+ [ -f "$_urrl_real" ] || return 1+ _urrl_tmp="$_urrl_real.unsloth-tmp.$$"+ # `cp -p` keeps the original's mode; without it the umask masks it and a 0644 .bashrc+ # comes back 0600. ENVIRON, not `-v`: POSIX awk decodes backslash escapes in `-v`, so an+ # escaped path arrived as something else and renamed an unchanged file.+ if { cp -p -- "$_urrl_real" "$_urrl_tmp" 2>/dev/null \+ || cp -- "$_urrl_real" "$_urrl_tmp" 2>/dev/null; } \+ && _URRL_OLD="$2" _URRL_NEW="$3" awk '+ $0 == ENVIRON["_URRL_OLD"] && prev ~ /^# Added by Unsloth/ { print ENVIRON["_URRL_NEW"]; prev = $0; next }+ { print; prev = $0 }+ ' "$_urrl_real" > "$_urrl_tmp" 2>/dev/null \+ && mv -f -- "$_urrl_tmp" "$_urrl_real" 2>/dev/null; then+ return 0+ fi+ # The original is untouched on every failure above; only the staged copy needs removing.+ rm -f -- "$_urrl_tmp" 2>/dev/null+ return 1+}++_unsloth_conda_env_active() {+ [ -n "${CONDA_PREFIX:-}" ] || [ -n "${CONDA_DEFAULT_ENV:-}" ]+}+_persist_fish_path_dir() {- _pfp_dir="$1"; _pfp_label="${2:-$1}"+ _pfp_dir="$1"; _pfp_label="${2:-$1}"; _pfp_mode="${3:-}"[ -n "${HOME:-}" ] || return 0_pfp_dir_conf="$HOME/.config/fish/conf.d"mkdir -p "$_pfp_dir_conf" 2>/dev/null || return 0_pfp_file="$_pfp_dir_conf/unsloth.fish"# Single-quoted: an unquoted path with a space is two arguments to fish_add_path and neither exists. Inside fish single quotes only \\ and \' carry meaning._pfp_quoted=$(printf '%s' "$_pfp_dir" | sed "s/\\\\/\\\\\\\\/g; s/'/\\\\'/g")- # The exact line we would write, not any occurrence of the directory: /opt/uv-old must not pass for /opt/uv, and fish reads none of the POSIX files that would otherwise cover it.- if ! grep -v '^[[:space:]]*#' "$_pfp_file" 2>/dev/null | grep -qxF "fish_add_path '$_pfp_quoted'"; then+ # fish_add_path PREPENDS, and that ordering outlives the conda activation (#5871), so+ # the conda arm appends. All three flags are load-bearing:+ # -a alone appends to $fish_user_paths, which fish prepends to PATH, so -P is what+ # makes it an append to PATH at all+ # -P edits $PATH for the session, which is right in conf.d: it is read alphabetically,+ # so conda.fish has already run+ # -m moves an entry already in PATH, which a bare `fish_add_path` from an older+ # install put there via the universal $fish_user_paths; without it the append is a+ # no-op and the stale prepend survives+ # https://fishshell.com/docs/current/cmds/fish_add_path.html+ _pfp_line="fish_add_path '$_pfp_quoted'"+ if _unsloth_conda_env_active; then+ _pfp_line="fish_add_path -a -P -m '$_pfp_quoted'"+ # Every earlier spelling is a prepend as far as PATH is concerned -- the bare -a+ # appends to $fish_user_paths, which fish itself puts in front of PATH -- so a line+ # left by any previous run is repointed rather than accepted by the check below, and+ # that includes the -a -P line without -m, which cannot move an entry already in PATH.+ for _pfp_stale in "fish_add_path '$_pfp_quoted'" "fish_add_path -a '$_pfp_quoted'" \+ "fish_add_path -a -P '$_pfp_quoted'"; do+ if _unsloth_repoint_rc_line "$_pfp_file" "$_pfp_stale" "$_pfp_line"; then+ step "path" "moved $_pfp_label after the active conda environment in $_pfp_file"+ fi+ done+ fi+ [ "$_pfp_mode" = "repoint" ] && return 0+ # The exact line we would write, not any occurrence of the directory: /opt/uv-old must+ # not pass for /opt/uv. EVERY spelling counts as present, or a run outside conda adds a+ # second line for a directory a run inside it already registered.+ if ! grep -v '^[[:space:]]*#' "$_pfp_file" 2>/dev/null \+ | grep -qxF -e "fish_add_path '$_pfp_quoted'" -e "fish_add_path -a '$_pfp_quoted'" -e "fish_add_path -a -P '$_pfp_quoted'" -e "fish_add_path -a -P -m '$_pfp_quoted'"; then# Same single-redirect, warning-not-failure contract as the POSIX arm. 2>/dev/null comes FIRST: redirections apply left to right, so the other order prints the shell's own "Permission denied" before the redirect can silence it.if {echo "# Added by Unsloth installer"- echo "fish_add_path '$_pfp_quoted'"+ echo "$_pfp_line"} 2>/dev/null >> "$_pfp_file"; thenstep "path" "added $_pfp_label to PATH in $_pfp_file"elsestep "path" "could not write $_pfp_file; add $_pfp_label to PATH yourself" "$C_WARN"substep "Unsloth is installed and works; only the PATH line is missing."substep "Add this to your fish config to get 'unsloth' in new shells:"- substep " fish_add_path '$_pfp_quoted'"+ substep " $_pfp_line"fifi}@@ -6344,12 +6428,17 @@ _persist_fish_path_dir() {_PATH_LINE_RE='(^|[^[:alnum:]_])(PATH[[:space:]]*=|fish_add_path|pathmunge|path_helper)'# Put a directory on the PATH of the NEXT shell, not just this process. $1 the directory, $2 the rc-file literal (~/.local/bin keeps $HOME unexpanded, as it always has), $3 how to name it in the line we print, $4 the grep that says it is already there, $5 an explicit profile file or empty to pick one the way this installer always has.+# $6 "repoint" asks for the repositioning pass ALONE: fix a line a previous run wrote and add+# nothing. The callers below are guarded on whether the directory is already on the login PATH,+# and it IS on it precisely because the previous run wrote the line, so the ordinary call is+# skipped in exactly the case the repointing exists for._persist_login_path_dir() {_plp_dir="$1"; _plp_literal="$2"; _plp_label="$3"; _plp_pattern="$4"; _plp_file="${5:-}"+ _plp_mode="${6:-}"[ -n "${HOME:-}" ] || return 0# fish reads none of the POSIX rc files, so an `export` line there is a no-op for a fish user. conf.d is fish's own drop-in directory and fish_add_path is idempotent by design.if [ -z "$_plp_file" ] && [ "$(basename "${SHELL:-}")" = "fish" ]; then- _persist_fish_path_dir "$_plp_dir" "$_plp_label"+ _persist_fish_path_dir "$_plp_dir" "$_plp_label" "$_plp_mode"return 0fi_SHELL_PROFILE="$_plp_file"@@ -6366,6 +6455,31 @@ _persist_login_path_dir() {_SHELL_PROFILE="$HOME/.profile"fi[ -n "$_SHELL_PROFILE" ] || return 0+ # A persisted PREPEND outlives the activation and leaves conda resolving out of our+ # directory in every later shell (#5871). Inside one, write the same line as an APPEND;+ # the grep below matches either spelling, so no second line is added. install.ps1 makes+ # the same choice for the Windows registry.+ _plp_line="export PATH=\"$_plp_literal:\$PATH\""+ if _unsloth_conda_env_active; then+ _plp_prepend="$_plp_line"+ _plp_line="export PATH=\"\$PATH:$_plp_literal\""+ # A prepend a previous run left behind is repositioned rather than accepted: the check+ # below treats it as present and would add nothing, leaving our directory ahead of the+ # active conda environment in every later shell.+ if grep -qxF "$_plp_prepend" "$_SHELL_PROFILE" 2>/dev/null; then+ if _unsloth_repoint_rc_line "$_SHELL_PROFILE" "$_plp_prepend" "$_plp_line"; then+ step "path" "moved $_plp_label after the active conda environment in $_SHELL_PROFILE"+ else+ step "path" "could not reposition $_plp_label in $_SHELL_PROFILE" "$C_WARN"+ substep "It is listed before conda, so conda resolves binaries out of it."+ substep "Replace that line with:"+ substep " $_plp_line"+ fi+ fi+ fi+ # Repointing was the whole job for this call: adding a line the caller did not ask for+ # would put an entry in the rc file of someone whose PATH comes from somewhere else.+ [ "$_plp_mode" = "repoint" ] && return 0# Comments stripped first, then only lines that actually set PATH: a commented-out old export is not an active entry, and neither is `UV_CACHE=/opt/uv` or `PYTHONPATH=/opt/uv`. The name boundary is what keeps PYTHONPATH out. Taking any of them for a PATH entry leaves the next shell with no uv at all.if ! grep -v '^[[:space:]]*#' "$_SHELL_PROFILE" 2>/dev/null \| grep -E "$_PATH_LINE_RE" | grep -qE "$_plp_pattern"; then@@ -6373,18 +6487,26 @@ _persist_login_path_dir() {if {echo ''echo '# Added by Unsloth installer'- echo "export PATH=\"$_plp_literal:\$PATH\""+ echo "$_plp_line"} 2>/dev/null >> "$_SHELL_PROFILE"; thenstep "path" "added $_plp_label to PATH in $_SHELL_PROFILE"elsestep "path" "could not write $_SHELL_PROFILE; add $_plp_label to PATH yourself" "$C_WARN"substep "Unsloth is installed and works; only the PATH line is missing."substep "Add this to your shell config to get 'unsloth' in new shells:"- substep " export PATH=\"$_plp_literal:\$PATH\""+ substep " $_plp_line"fifi}+# Before the guard below, because that guard is satisfied by the very line that needs moving:+# a previous run wrote the prepend, the shell that launched this installer evaluated it, and+# the directory is therefore already on the login PATH. Repointing only, so a machine whose+# PATH comes from somewhere else does not gain an rc line it never had.+if _unsloth_conda_env_active && [ "$_STUDIO_HOME_REDIRECT" != "env" ]; then+ _persist_login_path_dir "$_LOCAL_BIN" '$HOME/.local/bin' "~/.local/bin" '\.local/bin' "" repoint+fi+if ! _path_has_dir "$_UNSLOTH_LOGIN_PATH" "$_LOCAL_BIN"; then # not on a new shell's PATHif [ "$_STUDIO_HOME_REDIRECT" = "env" ]; thenexport PATH="$_LOCAL_BIN:$PATH"@@ -6399,6 +6521,38 @@ fiif [ -n "${_UNSLOTH_UV_BIN_DIR:-}" ] \&& [ -z "${UV_NO_MODIFY_PATH:-}" ] && [ -z "${UV_UNMANAGED_INSTALL:-}" ] \&& [ "$_STUDIO_HOME_REDIRECT" != "env" ]; then+ # Same repointing pass as the shim block, and ahead of the same guard for the same+ # reason: the directory is on the login PATH because the previous run's prepend put it+ # there. Computed here because the guard below owns the escaping.+ if _unsloth_conda_env_active; then+ _uv_repoint_literal=$(printf '%s' "$_UNSLOTH_UV_BIN_DIR" | sed 's/[\\"$`]/\\&/g')+ # And the $HOME-relative spelling, because that is what the shim block above writes:+ # the default uv destination IS ~/.local/bin, so a repoint built only from the+ # expanded path could never match `export PATH="$HOME/.local/bin:$PATH"` and the+ # line it was meant to move stayed in front of conda. The shim's own repoint pass+ # reaches one profile, whichever is selected now, so a prepend a previous run left+ # in .profile outlives a user who since acquired a .bashrc or changed shells; this+ # loop already visits every startup file astral's installer wired, so it is where+ # both spellings belong. $HOME is left unexpanded on purpose and only the rest of+ # the path is escaped.+ _uv_repoint_home_literal=""+ case "$_UNSLOTH_UV_BIN_DIR" in+ "$HOME"/*)+ _uv_repoint_home_literal='$HOME'$(printf '%s' "${_UNSLOTH_UV_BIN_DIR#$HOME}" | sed 's/[\\"$`]/\\&/g')+ ;;+ esac+ for _uv_prof in "$HOME/.profile" "$HOME/.bashrc" "$HOME/.bash_profile" \+ "$HOME/.bash_login" "${ZDOTDIR:-$HOME}/.zshrc" "${ZDOTDIR:-$HOME}/.zshenv"; do+ [ -f "$_uv_prof" ] || continue+ _persist_login_path_dir "$_UNSLOTH_UV_BIN_DIR" "$_uv_repoint_literal" \+ "$_UNSLOTH_UV_BIN_DIR" "" "$_uv_prof" repoint+ if [ -n "$_uv_repoint_home_literal" ]; then+ _persist_login_path_dir "$_UNSLOTH_UV_BIN_DIR" "$_uv_repoint_home_literal" \+ "$_UNSLOTH_UV_BIN_DIR" "" "$_uv_prof" repoint+ fi+ done+ _persist_fish_path_dir "$_UNSLOTH_UV_BIN_DIR" "" repoint+ fiif ! _path_has_dir "$_UNSLOTH_LOGIN_PATH" "$_UNSLOTH_UV_BIN_DIR"; then# The rc line is double-quoted, so a path holding $, ` or " would be expanded or terminated by the shell that reads it. The ~/.local/bin literal is exempt: its $HOME is meant to stay unexpanded._uv_rc_literal=$(printf '%s' "$_UNSLOTH_UV_BIN_DIR" | sed 's/[\\"$`]/\\&/g')diff --git a/studio/setup.ps1 b/studio/setup.ps1index a924c2a21a2..1f77756722e 100644--- a/studio/setup.ps1+++ b/studio/setup.ps1@@ -215,10 +215,33 @@ function Refresh-Environment {}$machinePath = [System.Environment]::GetEnvironmentVariable('Path', 'Machine')$userPath = [System.Environment]::GetEnvironmentVariable('Path', 'User')- # Merge: venv Scripts (if active) > Machine > User > current $env:Path. Dedup raw+expanded.+ # Merge: venv Scripts (if active) > active conda > Machine > User > current $env:Path.+ # Dedup raw+expanded.$venvScripts = if ($env:VIRTUAL_ENV) { Join-Path $env:VIRTUAL_ENV 'Scripts' } else { $null }+ # An activated conda environment lives ONLY in the process PATH, so rebuilding as+ # machine + user + previous puts every conda entry behind the User PATH. Running this+ # script directly shares the caller's process, so the demotion would outlive the setup.+ # Mirrors install.ps1's Refresh-SessionPath; parity is asserted in+ # tests/python/test_installer_conda_path_guard.py.+ $condaFront = @()+ if (Test-ActiveCondaEnvironment) {+ $prefixes = Get-ActiveCondaPrefixes+ if ($prefixes) {+ foreach ($entry in ($env:Path -split ";")) {+ if (Test-PathUnderCondaPrefix -Path $entry -Prefixes $prefixes) {+ $condaFront += $entry+ }+ }+ } else {+ # A hook that exports CONDA_DEFAULT_ENV and nothing that names a directory: which+ # entries are conda's cannot be established, so the caller's PATH is kept whole+ # and in front rather than reconstructed. Same reasoning as install.ps1.+ $condaFront = @($env:Path)+ }+ }$sources = @()if ($venvScripts) { $sources += $venvScripts }+ $sources += $condaFront$sources += @($machinePath, $userPath, $env:Path)$merged = ($sources | Where-Object { $_ }) -join ';'$seen = @{}@@ -235,6 +258,75 @@ function Refresh-Environment {$env:Path = $unique -join ";"}+# ── Helper: is a conda environment ACTIVE in this session? ──+# Mirrors install.ps1. CONDA_PREFIX separates "conda is installed" from "we are inside one+# of its environments".+function Test-ActiveCondaEnvironment {+ foreach ($condaVar in @($env:CONDA_PREFIX, $env:CONDA_DEFAULT_ENV)) {+ if (-not [string]::IsNullOrWhiteSpace($condaVar)) { return $true }+ }+ return $false+}++# Every directory the active conda installation owns: the environment itself, the stack of+# environments it was activated on top of, and the base installation. Mirrors install.ps1.+function Get-ActiveCondaPrefixes {+ $prefixes = New-Object System.Collections.Generic.List[string]+ if (-not [string]::IsNullOrWhiteSpace($env:CONDA_PREFIX)) { $prefixes.Add($env:CONDA_PREFIX) }+ # Enumerated from CONDA_SHLVL, not a fixed list: a hard-coded tail of three dropped+ # everything past the fourth stacked environment and inverted its ordering. The ceiling+ # stops a bad value spinning.+ $levels = 0+ if (-not [string]::IsNullOrWhiteSpace($env:CONDA_SHLVL)) {+ [void][int]::TryParse($env:CONDA_SHLVL, [ref]$levels)+ }+ if ($levels -lt 1) { $levels = 1 }+ if ($levels -gt 64) { $levels = 64 }+ for ($level = 1; $level -le $levels; $level++) {+ $value = [Environment]::GetEnvironmentVariable("CONDA_PREFIX_$level")+ if (-not [string]::IsNullOrWhiteSpace($value)) { $prefixes.Add($value) }+ }+ if (-not [string]::IsNullOrWhiteSpace($env:_CONDA_ROOT)) { $prefixes.Add($env:_CONDA_ROOT) }+ if (-not [string]::IsNullOrWhiteSpace($env:CONDA_EXE)) {+ # ...\<root>\Scripts\conda.exe -> ...\<root>. Regex rather than Split-Path, which is+ # provider-aware and keeps backslashes on the non-Windows PowerShell the tests use.+ $scripts = $env:CONDA_EXE -replace '[\\/][^\\/]*$', ''+ $root = $scripts -replace '[\\/][^\\/]*$', ''+ if ($root -and $root -ne $env:CONDA_EXE) { $prefixes.Add($root) }+ }+ return $prefixes+}++# Is $Path inside one of $Prefixes? On a directory boundary, so "C:\conda-backup" is not+# dragged to the front along with "C:\conda".+function Test-PathUnderCondaPrefix {+ param([string]$Path, $Prefixes)+ if ([string]::IsNullOrWhiteSpace($Path) -or -not $Prefixes) { return $false }+ $candidate = [Environment]::ExpandEnvironmentVariables($Path).Trim().Trim('"').TrimEnd('\')+ if (-not $candidate) { return $false }+ foreach ($prefix in $Prefixes) {+ $normalized = [Environment]::ExpandEnvironmentVariables($prefix).Trim().Trim('"').TrimEnd('\')+ if (-not $normalized) { continue }+ if ($candidate -ieq $normalized) { return $true }+ if ($candidate.StartsWith($normalized + '\', [System.StringComparison]::OrdinalIgnoreCase)) {+ return $true+ }+ }+ return $false+}++# The position a PERSISTENT PATH write may actually use: a prepend outlives the activation+# it was made under and leaves our directory ahead of conda's own entries (#5871). Mirrors+# install.ps1; parity is asserted in tests/python/test_installer_conda_path_guard.py.+function Resolve-UserPathPosition {+ param(+ [ValidateSet('Append','Prepend')]+ [string]$Position = 'Append'+ )+ if ($Position -eq 'Prepend' -and (Test-ActiveCondaEnvironment)) { return 'Append' }+ return $Position+}+# Direct registry access preserves REG_EXPAND_SZ (dotnet/runtime#1442).function Add-ToUserPath {param(@@ -243,6 +335,13 @@ function Add-ToUserPath {[string]$Position = 'Append')if (Get-Variable -Name StageRoot -ValueOnly -ErrorAction SilentlyContinue) { return $false }+ # Every persistent PATH write goes through Resolve-UserPathPosition, so an active conda+ # environment cannot be demoted by any call site.+ # A downgraded request has to be able to MOVE an entry that a previous non-conda run left at the+ # FRONT, not just decline to add one; see the same guard in install.ps1.+ $requestedPosition = $Position+ $Position = Resolve-UserPathPosition -Position $Position+ $positionDowngraded = ($Position -ne $requestedPosition)try {$regKey = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey('Environment')try {@@ -265,7 +364,8 @@ function Add-ToUserPath {$kept.Add($entries[$i])}$alreadyPresent = $matchIndices.Count -gt 0- if ($alreadyPresent -and $Position -eq 'Append') { # Append: idempotent no-op+ # Already at the back is still a no-op, caught by the $newPath -ceq $rawPath check below.+ if ($alreadyPresent -and $Position -eq 'Append' -and -not $positionDowngraded) {return $false}if ($alreadyPresent -and $Position -eq 'Prepend' -and # Prepend: no-op if already at frontdiff --git a/studio/setup.sh b/studio/setup.shindex b2f7bfa7b05..1a0105ed36d 100755--- a/studio/setup.sh+++ b/studio/setup.sh@@ -2179,6 +2179,60 @@ _setup_path_has_dir() {return "$_sphd_found"}+# Is a conda environment ACTIVE in this shell? Both variables, matching install.ps1: a hook+# exporting only CONDA_DEFAULT_ENV still leaves the caller inside conda's PATH ordering.+# A prepend a previous run persisted is repositioned, not accepted: otherwise a rerun+# inside conda leaves our directory ahead of it for ever (#5871).+# Only an exact whole-line match on what this writer writes is touched, and the content is+# copied back into the ORIGINAL file so a symlinked rc keeps its link, mode and owner.+_unsloth_repoint_rc_line() {+ [ -f "$1" ] || return 1+ # OURS, not merely matching: a hand-written `export PATH="$HOME/.local/bin:$PATH"` is a+ # line users have too, and demoting theirs would move that whole directory behind the+ # rest of PATH for good. The `# Added by Unsloth` marker above the line is the ownership+ # record, so a line without one is left alone.+ _URRL_OLD="$2" awk '+ $0 == ENVIRON["_URRL_OLD"] && prev ~ /^# Added by Unsloth/ { found = 1 }+ { prev = $0 }+ END { exit(found ? 0 : 1) }+ ' "$1" 2>/dev/null || return 1+ # Staged and renamed, because `cat tmp > file` truncates the profile first and an+ # interrupt leaves wreckage. Onto the RESOLVED path: renaming over a chezmoi or stow+ # symlink would replace it with a regular file. `readlink -f` is GNU-only, hence the walk.+ _urrl_real="$1"+ _urrl_hops=0+ while [ -L "$_urrl_real" ] && [ "$_urrl_hops" -lt 40 ]; do+ _urrl_hops=$((_urrl_hops + 1))+ _urrl_target="$(readlink -- "$_urrl_real" 2>/dev/null)" || break+ [ -n "$_urrl_target" ] || break+ case "$_urrl_target" in+ /*) _urrl_real="$_urrl_target" ;;+ *) _urrl_real="$(dirname -- "$_urrl_real")/$_urrl_target" ;;+ esac+ done+ [ -f "$_urrl_real" ] || return 1+ _urrl_tmp="$_urrl_real.unsloth-tmp.$$"+ # `cp -p` keeps the original's mode; without it the umask masks it and a 0644 .bashrc+ # comes back 0600. ENVIRON, not `-v`: POSIX awk decodes backslash escapes in `-v`, so an+ # escaped path arrived as something else and renamed an unchanged file.+ if { cp -p -- "$_urrl_real" "$_urrl_tmp" 2>/dev/null \+ || cp -- "$_urrl_real" "$_urrl_tmp" 2>/dev/null; } \+ && _URRL_OLD="$2" _URRL_NEW="$3" awk '+ $0 == ENVIRON["_URRL_OLD"] && prev ~ /^# Added by Unsloth/ { print ENVIRON["_URRL_NEW"]; prev = $0; next }+ { print; prev = $0 }+ ' "$_urrl_real" > "$_urrl_tmp" 2>/dev/null \+ && mv -f -- "$_urrl_tmp" "$_urrl_real" 2>/dev/null; then+ return 0+ fi+ # The original is untouched on every failure above; only the staged copy needs removing.+ rm -f -- "$_urrl_tmp" 2>/dev/null+ return 1+}++_unsloth_conda_env_active() {+ [ -n "${CONDA_PREFIX:-}" ] || [ -n "${CONDA_DEFAULT_ENV:-}" ]+}+_setup_persist_uv_path() {_supp_dir="$1"[ -n "$_supp_dir" ] || return 0@@ -2187,7 +2241,15 @@ _setup_persist_uv_path() {[ -z "${UV_UNMANAGED_INSTALL:-}" ] || return 0# The PATH a new shell inherits, not the one this process has already prepended to, and# compared entry by entry: a directory holding *, ? or [ is a glob inside a case pattern.- _setup_path_has_dir "${_SETUP_LOGIN_PATH:-$PATH}" "$_supp_dir" && return 0+ # Already on the login PATH BECAUSE a previous run wrote the line, and inside a conda+ # environment that line is in the wrong place, so the repointing pass has to run before+ # this early return rather than after it. `_setup_repoint_only` makes the rest of the+ # function a no-op: it repositions what is there and adds nothing.+ _setup_repoint_only=false+ if _setup_path_has_dir "${_SETUP_LOGIN_PATH:-$PATH}" "$_supp_dir"; then+ _unsloth_conda_env_active || return 0+ _setup_repoint_only=true+ fi# ~/.config, not XDG_CONFIG_HOME, because that is where astral's installer put its own fish# file, and it is written regardless of the current shell for the same reason._supp_fish_dir="$HOME/.config/fish/conf.d"@@ -2195,10 +2257,35 @@ _setup_persist_uv_path() {_supp_fish="$_supp_fish_dir/unsloth.fish"# Single-quoted: an unquoted path with a space is two arguments to fish_add_path._supp_quoted=$(printf '%s' "$_supp_dir" | sed "s/\\\\/\\\\\\\\/g; s/'/\\\\'/g")- # The exact line, not any occurrence: /opt/uv-old must not pass for /opt/uv.- if ! grep -v '^[[:space:]]*#' "$_supp_fish" 2>/dev/null | grep -qxF "fish_add_path '$_supp_quoted'"; then+ # fish_add_path PREPENDS, and that ordering outlives the conda activation (#5871),+ # so the conda arm appends. All three flags are load-bearing:+ # -a alone appends to $fish_user_paths, which fish prepends to PATH, so -P is what+ # makes it an append to PATH at all+ # -P edits $PATH for the session, right for a conf.d drop-in read after conda.fish+ # -m moves an entry a bare `fish_add_path` from an older install already put in+ # the universal $fish_user_paths; without it the append is a no-op+ # https://fishshell.com/docs/current/cmds/fish_add_path.html+ _supp_fish_line="fish_add_path '$_supp_quoted'"+ if _unsloth_conda_env_active; then+ _supp_fish_line="fish_add_path -a -P -m '$_supp_quoted'"+ # Every earlier spelling puts the directory in front of PATH, the bare -a by way of+ # $fish_user_paths, and the -a -P line without -m cannot move an entry already in PATH,+ # so any of them left by a previous run is repointed rather than accepted as present.+ for _supp_stale in "fish_add_path '$_supp_quoted'" "fish_add_path -a '$_supp_quoted'" \+ "fish_add_path -a -P '$_supp_quoted'"; do+ _unsloth_repoint_rc_line "$_supp_fish" "$_supp_stale" "$_supp_fish_line" || true+ done+ fi+ # The exact line, not any occurrence: /opt/uv-old must not pass for /opt/uv. EVERY+ # spelling counts as present, or a run outside conda adds a second line for a+ # directory a run inside it already registered; the bare -a one is kept because an+ # install from before this fix wrote it.+ if [ "$_setup_repoint_only" != true ] && ! grep -v '^[[:space:]]*#' "$_supp_fish" 2>/dev/null \+ | grep -qxF -e "fish_add_path '$_supp_quoted'" -e "fish_add_path -a '$_supp_quoted'" \+ -e "fish_add_path -a -P '$_supp_quoted'" \+ -e "fish_add_path -a -P -m '$_supp_quoted'"; thenecho "# Added by Unsloth setup" >> "$_supp_fish"- echo "fish_add_path '$_supp_quoted'" >> "$_supp_fish"+ echo "$_supp_fish_line" >> "$_supp_fish"fifi# An entry has to be active, whole and on a line that SETS PATH: a commented-out export,@@ -2209,6 +2296,43 @@ _setup_persist_uv_path() {# Escaped: the line is double-quoted, so a path holding $, ` or " would be expanded or# terminated by the shell that reads it._supp_literal=$(printf '%s' "$_supp_dir" | sed 's/[\\"$`]/\\&/g')+ # A persisted PREPEND outlives the activation and leaves conda resolving out of our+ # directory in every later shell (#5871). Inside one, write the same line as an APPEND;+ # the grep below matches either spelling, so no second line is added. install.ps1 makes+ # the same choice for the Windows registry.+ _supp_export_line="export PATH=\"$_supp_literal:\$PATH\""+ _supp_export_prepend="$_supp_export_line"+ # And the $HOME-relative spelling of the same prepend, because install.sh writes the shim+ # line that way and this script runs standalone on an update: _SETUP_LOGIN_PATH holds the+ # EXPANDED directory, which is what selects the repoint-only branch below, while the line+ # sitting in the profile says $HOME. Matching only the expanded form meant the rewrite+ # never fired and the stale prepend stayed ahead of the active conda environment. $HOME is+ # left unexpanded on purpose; only the rest of the path is escaped.+ _supp_export_home_prepend=""+ case "$_supp_dir" in+ "$HOME"/*)+ _supp_home_literal='$HOME'$(printf '%s' "${_supp_dir#$HOME}" | sed 's/[\\"$`]/\\&/g')+ _supp_export_home_prepend="export PATH=\"$_supp_home_literal:\$PATH\""+ ;;+ esac+ if _unsloth_conda_env_active; then+ _supp_export_line="export PATH=\"\$PATH:$_supp_literal\""+ fi+ if [ "$_setup_repoint_only" = true ]; then+ # The POSIX repointing pass, then out: nothing here may append a line the caller's+ # guard decided against.+ for _supp_profile in "$HOME/.profile" "$HOME/.bashrc" "$HOME/.bash_profile" \+ "$HOME/.bash_login" "${ZDOTDIR:-$HOME}/.zshrc" "${ZDOTDIR:-$HOME}/.zshenv"; do+ [ -f "$_supp_profile" ] || continue+ _unsloth_repoint_rc_line "$_supp_profile" "$_supp_export_prepend" \+ "$_supp_export_line" || true+ if [ -n "$_supp_export_home_prepend" ]; then+ _unsloth_repoint_rc_line "$_supp_profile" "$_supp_export_home_prepend" \+ "$_supp_export_line" || true+ fi+ done+ return 0+ fi# Every startup file astral's installer wired, because it is the installer this replaced:# ~/.profile always, each bash file that exists, and zsh under ZDOTDIR. Writing only the# file for the shell that happens to be running would leave a bash user whose .bash_profile@@ -2216,14 +2340,30 @@ _setup_persist_uv_path() {for _supp_profile in "$HOME/.profile" "$HOME/.bashrc" "$HOME/.bash_profile" \"$HOME/.bash_login" "${ZDOTDIR:-$HOME}/.zshrc" "${ZDOTDIR:-$HOME}/.zshenv"; doif [ "$_supp_profile" != "$HOME/.profile" ] && [ ! -f "$_supp_profile" ]; then continue; fi+ # Repointing comes BEFORE the presence check, not inside it. The check below matches+ # the EXPANDED directory, so it cannot see the $HOME-relative prepend install.sh+ # writes: gating the rewrite on it left that spelling in place and appended a second+ # line underneath it, which is both a duplicate entry and the original ordering bug,+ # since the surviving prepend still resolves ahead of the active conda environment.+ # Rewriting first also makes the check find the append it just produced.+ if _unsloth_conda_env_active; then+ _unsloth_repoint_rc_line "$_supp_profile" "$_supp_export_prepend" \+ "$_supp_export_line" || true+ if [ -n "$_supp_export_home_prepend" ]; then+ _unsloth_repoint_rc_line "$_supp_profile" "$_supp_export_home_prepend" \+ "$_supp_export_line" || true+ fi+ fi# Only lines that actually set PATH count: `UV_CACHE=/opt/uv` and `PYTHONPATH=/opt/uv`# are not PATH entries, and taking one for an entry leaves the next shell without uv.if grep -v '^[[:space:]]*#' "$_supp_profile" 2>/dev/null \| grep -E "$_supp_path_line" \- | grep -qE "(^|[^[:alnum:]_.~/-])$_supp_grep([^[:alnum:]_.~/-]|\$)"; then continue; fi+ | grep -qE "(^|[^[:alnum:]_.~/-])$_supp_grep([^[:alnum:]_.~/-]|\$)"; then+ continue+ fiecho '' >> "$_supp_profile"echo '# Added by Unsloth setup' >> "$_supp_profile"- echo "export PATH=\"$_supp_literal:\$PATH\"" >> "$_supp_profile"+ echo "$_supp_export_line" >> "$_supp_profile"done}diff --git a/tests/python/test_installer_conda_path_guard.py b/tests/python/test_installer_conda_path_guard.pynew file mode 100644index 00000000000..ff1604b3868--- /dev/null+++ b/tests/python/test_installer_conda_path_guard.py@@ -0,0 +1,895 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""No installer PATH write may demote an ACTIVE conda environment.++A prepend into the persistent User PATH outlives the activation it was made under, so from+the next shell on conda resolves binaries and DLLs out of our directory. That is #5871:+after installing Studio, `conda update --all --yes` leaves the Anaconda base unusable with+`ImportError: DLL load failed while importing _ctypes`.++One decision function per installer, with every persistent write routed through it, so a+new call site cannot reintroduce the defect. Asserted here: the decision, that both+PowerShell installers use it, and that the system-Python installer switch follows it. The+POSIX half is tests/sh/test_install_conda_path_guard.sh.+"""++from __future__ import annotations++import os+import re+import shutil+import stat+import subprocess+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"+SETUP_PS1 = REPO_ROOT / "studio" / "setup.ps1"+INSTALL_SH = REPO_ROOT / "install.sh"+SETUP_SH_POSIX = REPO_ROOT / "studio" / "setup.sh"+POWERSHELLS = [shell for shell in ("pwsh", "powershell") if shutil.which(shell)]++# install.ps1 nests its helpers inside Install-UnslothStudio, setup.ps1 defines them at top+# level, so the indent is part of the pattern rather than something to normalise away.+_PS_FILES = {+ "install.ps1": (INSTALL_PS1, " "),+ "studio/setup.ps1": (SETUP_PS1, ""),+}+++def _function(path: Path, indent: str, name: str) -> str:+ source = path.read_text(encoding = "utf-8")+ match = re.search(rf"{indent}function {name} \{{.*?\n{indent}\}}\n", source, flags = re.DOTALL)+ assert match is not None, f"{path.name} no longer defines {name}"+ return match.group(0)+++def _run(+ shell: str,+ script: str,+ env: dict[str, str] | None = None,+) -> str:+ base = {k: v for k, v in os.environ.items() if not k.startswith("CONDA_")}+ result = run_pwsh(+ [shell, "-NoProfile", "-NonInteractive", "-Command", script],+ check = True,+ capture_output = True,+ text = True,+ encoding = "utf-8",+ errors = "strict",+ env = {**base, **(env or {})},+ timeout = 60,+ )+ return result.stdout.strip()+++_NO_CONDA = {}+_ACTIVE_CONDA = {"CONDA_PREFIX": "E:\\anaconda\\install", "CONDA_DEFAULT_ENV": "base"}+_PREFIX_ONLY = {"CONDA_PREFIX": "E:\\anaconda\\install"}+# A hook that exports only CONDA_DEFAULT_ENV still leaves the caller inside conda's+# ordering, so it counts too.+_NAME_ONLY = {"CONDA_DEFAULT_ENV": "base"}+# Set but empty is not an activation: conda's own deactivate clears these by emptying them.+_EMPTY = {"CONDA_PREFIX": "", "CONDA_DEFAULT_ENV": ""}++[email protected](not POWERSHELLS, reason = "PowerShell is unavailable")[email protected]("shell", POWERSHELLS)[email protected]("path_label", sorted(_PS_FILES))+ "requested,env,expected",+ [+ ("Prepend", _NO_CONDA, "Prepend"),+ ("Prepend", _ACTIVE_CONDA, "Append"),+ ("Prepend", _PREFIX_ONLY, "Append"),+ ("Prepend", _NAME_ONLY, "Append"),+ ("Prepend", _EMPTY, "Prepend"),+ # An append was already behind everything; conda changes nothing about it.+ ("Append", _ACTIVE_CONDA, "Append"),+ ("Append", _NO_CONDA, "Append"),+ ],+ ids = [+ "prepend-no-conda",+ "prepend-active-conda",+ "prepend-prefix-only",+ "prepend-name-only",+ "prepend-empty-vars",+ "append-active-conda",+ "append-no-conda",+ ],+)+def test_a_prepend_becomes_an_append_inside_an_active_conda_environment(+ shell: str, path_label: str, requested: str, env: dict[str, str], expected: str+):+ path, indent = _PS_FILES[path_label]+ script = (+ _function(path, indent, "Test-ActiveCondaEnvironment")+ + _function(path, indent, "Resolve-UserPathPosition")+ + f"\nWrite-Host ('POSITION=' + (Resolve-UserPathPosition -Position '{requested}'))\n"+ )+ out = _run(shell, script, env = env)+ assert f"POSITION={expected}" in out++[email protected]("path_label", sorted(_PS_FILES))+def test_every_persistent_path_write_routes_through_the_guard(path_label: str):+ """Add-ToUserPath is the only persistent PATH writer, and it must not be bypassable.++ Asserted on the function body rather than on a call site, because the call sites are+ the thing that keeps changing: install.ps1 prepends the uv destination, the shim+ directory and the shortcut shim directory, setup.ps1 five more, and a sixth added later+ must inherit the guard without anyone remembering it exists.+ """+ path, indent = _PS_FILES[path_label]+ body = _function(path, indent, "Add-ToUserPath")+ assert (+ "Resolve-UserPathPosition" in body+ ), f"{path_label}: Add-ToUserPath must resolve its position through the guard"+ # Ahead of the registry read, or the decision lands after the value it decides is used.+ assert body.index("Resolve-UserPathPosition") < body.index(+ "Registry"+ ), f"{path_label}: the guard has to run before the registry write is prepared"++[email protected]("path_label", sorted(_PS_FILES))+def test_a_downgraded_prepend_still_repositions_an_existing_front_entry(path_label: str):+ """Declining to ADD is not the same as declining to DEMOTE.++ A machine that ran the installer once outside conda has our directory at the FRONT of+ the User PATH. Rerunning inside conda downgrades the Prepend to an Append, but an+ unconditional "already present, nothing to do" early return leaves that front entry in+ place, so the run says "conda keeps priority" while #5871 stays armed.++ Structural, because Add-ToUserPath writes through [Microsoft.Win32.Registry], which does+ not exist off Windows.+ """+ path, indent = _PS_FILES[path_label]+ body = _function(path, indent, "Add-ToUserPath")+ match = re.search(r"\$alreadyPresent -and \$Position -eq 'Append'([^\)]*)\)", body)+ assert match is not None, f"{path_label}: no append early-return found in Add-ToUserPath"+ assert "-not $positionDowngraded" in match.group(1), (+ f"{path_label}: the append early-return must not fire for a prepend that conda "+ f"downgraded, or an existing front entry is never moved to the back"+ )+ # The flag has to be derived from the guard's own answer, not hardcoded.+ assert re.search(+ r"\$positionDowngraded\s*=\s*\(", body+ ), f"{path_label}: $positionDowngraded must be computed from Resolve-UserPathPosition"++[email protected]("path_label", sorted(_PS_FILES))+def test_the_two_installers_agree_on_the_guard(path_label: str):+ """Both copies decide the same way. They are separate scripts, not a shared module."""+ path, indent = _PS_FILES[path_label]+ body = _function(path, indent, "Resolve-UserPathPosition")+ assert "Test-ActiveCondaEnvironment" in body+ assert "'Append'" in body+ conda = _function(path, indent, "Test-ActiveCondaEnvironment")+ assert "CONDA_PREFIX" in conda+ 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"+ )+++ "path,funcs",+ [+ (INSTALL_SH, ("_persist_login_path_dir", "_persist_fish_path_dir")),+ (SETUP_SH_POSIX, ("_setup_persist_uv_path",)),+ ],+ ids = ["install.sh", "studio/setup.sh"],+)+def test_the_posix_installers_carry_the_same_guard(path: Path, funcs: tuple[str, ...]):+ """Cross-platform parity, asserted here so the PowerShell and POSIX halves cannot drift.++ The behavioural cases are in tests/sh/test_install_conda_path_guard.sh, which runs the+ extracted shell functions; this only holds that the guard exists at all, so a rewrite of+ a PATH persistence block on the POSIX side cannot quietly drop it. Four writers in all:+ the registry in install.ps1 and setup.ps1, the rc files in install.sh and setup.sh.+ """+ source = path.read_text(encoding = "utf-8")+ for func in funcs:+ body = re.search(rf"\n{func}\(\) \{{.*?\n\}}\n", source, flags = re.DOTALL)+ assert body is not None, f"{path.name} no longer defines {func}"+ assert "_unsloth_conda_env_active" in body.group(0), f"{func} must not prepend inside conda"+++ "path", [INSTALL_SH, SETUP_SH_POSIX], ids = ["install.sh", "studio/setup.sh"]+)+def test_both_halves_call_the_same_environment_an_active_conda(path: Path):+ """The PowerShell and POSIX halves must agree on WHICH variables mean "inside conda"."""+ posix = path.read_text(encoding = "utf-8")+ body = re.search(r"\n_unsloth_conda_env_active\(\) \{.*?\n\}\n", posix, flags = re.DOTALL)+ assert body is not None, f"{path.name} no longer defines _unsloth_conda_env_active"+ posix_vars = set(re.findall(r"\bCONDA_[A-Z_]+", body.group(0)))++ windows = INSTALL_PS1.read_text(encoding = "utf-8")+ probe = re.search(+ r"function Test-ActiveCondaEnvironment \{.*?\n \}", windows, flags = re.DOTALL+ )+ assert probe is not None, "install.ps1 no longer defines Test-ActiveCondaEnvironment"+ windows_vars = set(re.findall(r"\bCONDA_[A-Z_]+", probe.group(0)))++ assert posix_vars == windows_vars, (+ f"{path.name} reads {sorted(posix_vars)} but install.ps1 reads " f"{sorted(windows_vars)}"+ )+++# ── The LIVE session PATH, not only the registry ──+# The registry half above fixes the NEXT shell. `irm ... | iex` is the documented command,+# and environment changes made by `iex` stay in the caller's own process, so the PATH the+# installer leaves behind IS that prompt. Rebuilt as machine + user + previous, every+# activated-conda entry lands behind the User PATH, because none of it is in the registry at+# all: `python` and `conda update` then resolve the non-conda install first, in a session the+# installer has just told the user keeps conda's priority.+++def _refresh_preamble(current_path: str) -> str:+ """Refresh-SessionPath with the two registry reads stubbed and $env:Path seeded."""+ body = (+ _function(INSTALL_PS1, " ", "Test-ActiveCondaEnvironment")+ + _function(INSTALL_PS1, " ", "Get-ActiveCondaPrefixes")+ + _function(INSTALL_PS1, " ", "Test-PathUnderCondaPrefix")+ + _function(INSTALL_PS1, " ", "Refresh-SessionPath")+ )+ return f"""+$ErrorActionPreference = "Stop"+{body}+# The suite itself runs inside a virtualenv, and Refresh-SessionPath puts $VIRTUAL_ENV+# first. That branch is not what these cases are about, and leaving it on would make the+# expected orderings depend on where the suite was launched from.+$env:VIRTUAL_ENV = ""+$env:Path = "{current_path}"+Refresh-SessionPath+Write-Host ("PATH=" + $env:Path)+"""+++MACHINE = "C:\\Windows\\system32;C:\\Windows"+USER_PATH = "C:\\Users\\me\\.local\\bin;C:\\Users\\me\\AppData\\Local\\Programs\\Python\\Python312"+CONDA_ROOT = "E:\\anaconda\\install"+_CONDA_ENTRIES = (+ f"{CONDA_ROOT}\\envs\\ml;"+ f"{CONDA_ROOT}\\envs\\ml\\Library\\bin;"+ f"{CONDA_ROOT}\\envs\\ml\\Scripts;"+ f"{CONDA_ROOT}\\Scripts"+)+++def _stub_registry(script: str) -> str:+ """Answer the two registry reads without touching the machine running the suite."""+ return script.replace(+ '$machine = [System.Environment]::GetEnvironmentVariable("Path", "Machine")',+ f'$machine = "{MACHINE}"',+ ).replace(+ '$user = [System.Environment]::GetEnvironmentVariable("Path", "User")',+ f'$user = "{USER_PATH}"',+ )++[email protected](not POWERSHELLS, reason = "PowerShell is unavailable")[email protected]("shell", POWERSHELLS)+def test_the_session_refresh_keeps_an_active_conda_ahead_of_the_user_path(shell: str):+ """The case #5871 is about, in the prompt the user is standing in.++ Without this the message that conda keeps priority is false for the rest of that+ session: the registry ordering is right and the live PATH is not.+ """+ script = _stub_registry(_refresh_preamble(f"{_CONDA_ENTRIES};{MACHINE}"))+ out = _run(+ shell,+ script,+ env = {+ "CONDA_PREFIX": f"{CONDA_ROOT}\\envs\\ml",+ "CONDA_DEFAULT_ENV": "ml",+ "CONDA_EXE": f"{CONDA_ROOT}\\Scripts\\conda.exe",+ },+ )+ assert out.startswith("PATH="), out+ entries = out[len("PATH=") :].split(";")+ lowered = [entry.rstrip("\\").lower() for entry in entries]++ conda_positions = [+ index for index, entry in enumerate(lowered) if entry.startswith(CONDA_ROOT.lower())+ ]+ assert conda_positions, f"the conda entries were dropped entirely: {entries}"+ user_first = min(+ index for index, entry in enumerate(lowered) if entry.startswith("c:\\users\\me")+ )+ assert (+ max(conda_positions) < user_first+ ), f"an activated conda environment was left behind the User PATH: {entries}"+ # Conda's own ordering inside the environment is preserved, not re-sorted.+ assert lowered[:4] == [+ f"{CONDA_ROOT}\\envs\\ml".lower(),+ f"{CONDA_ROOT}\\envs\\ml\\Library\\bin".lower(),+ f"{CONDA_ROOT}\\envs\\ml\\Scripts".lower(),+ f"{CONDA_ROOT}\\Scripts".lower(),+ ], entries+ # And nothing is duplicated by the move.+ assert len(lowered) == len(set(lowered)), entries++[email protected](not POWERSHELLS, reason = "PowerShell is unavailable")[email protected]("shell", POWERSHELLS)+def test_the_session_refresh_is_unchanged_outside_conda(shell: str):+ """No conda, no reordering. The refresh is on the hot path of the whole installer and+ must keep doing exactly what it did."""+ previous = "C:\\tools\\bin"+ script = _stub_registry(_refresh_preamble(previous))+ out = _run(shell, script, env = _NO_CONDA)+ entries = out[len("PATH=") :].split(";")+ assert entries == MACHINE.split(";") + USER_PATH.split(";") + [previous], entries++[email protected](not POWERSHELLS, reason = "PowerShell is unavailable")[email protected]("shell", POWERSHELLS)+def test_a_sibling_directory_is_not_dragged_forward_with_the_prefix(shell: str):+ """`C:\\conda-backup` is not inside `C:\\conda`. Matching on the raw string would move an+ unrelated directory to the front of PATH, which is the same class of defect this change+ exists to prevent, pointed the other way."""+ sibling = f"{CONDA_ROOT}-backup\\bin"+ script = _stub_registry(_refresh_preamble(f"{sibling};{CONDA_ROOT}\\Scripts"))+ out = _run(+ shell,+ script,+ env = {+ "CONDA_PREFIX": CONDA_ROOT,+ "CONDA_DEFAULT_ENV": "base",+ },+ )+ entries = out[len("PATH=") :].split(";")+ lowered = [entry.rstrip("\\").lower() for entry in entries]+ assert lowered[0] == f"{CONDA_ROOT}\\scripts".lower(), entries+ assert lowered.index(sibling.lower()) > lowered.index(+ USER_PATH.split(";")[0].lower()+ ), f"a sibling of the conda prefix was promoted with it: {entries}"++[email protected](not POWERSHELLS, reason = "PowerShell is unavailable")[email protected]("shell", POWERSHELLS)+def test_a_stacked_conda_activation_keeps_both_prefixes_in_front(shell: str):+ """`conda activate` inside another environment stacks them and records the outer one in+ CONDA_PREFIX_1. Its entries are on PATH exactly as the inner one's are."""+ outer = f"{CONDA_ROOT}\\envs\\outer\\Scripts"+ inner = f"{CONDA_ROOT}\\envs\\inner\\Scripts"+ script = _stub_registry(_refresh_preamble(f"{inner};{outer}"))+ out = _run(+ shell,+ script,+ env = {+ "CONDA_PREFIX": f"{CONDA_ROOT}\\envs\\inner",+ "CONDA_PREFIX_1": f"{CONDA_ROOT}\\envs\\outer",+ "CONDA_DEFAULT_ENV": "inner",+ },+ )+ entries = out[len("PATH=") :].split(";")+ lowered = [entry.rstrip("\\").lower() for entry in entries]+ assert lowered[:2] == [inner.lower(), outer.lower()], entries+++def test_the_refresh_consults_the_conda_helper_at_all():+ """The three helpers are only worth anything if Refresh-SessionPath calls them, and a+ refresh that rebuilt PATH the old way would leave every case above untouched if they+ were driven directly instead."""+ body = _function(INSTALL_PS1, " ", "Refresh-SessionPath")+ assert "Test-ActiveCondaEnvironment" in body+ assert "Get-ActiveCondaPrefixes" in body+ assert "Test-PathUnderCondaPrefix" in body+ # And the conda entries go in FRONT of the registry values, which is the whole point.+ assert body.index("$sources += $condaFront") < body.index(+ "$sources += @($machine"+ ), "the conda entries are appended after the User PATH, which changes nothing"++[email protected](not POWERSHELLS, reason = "PowerShell is unavailable")[email protected]("shell", POWERSHELLS)+def test_a_name_only_activation_keeps_the_session_it_already_had(shell: str):+ """A hook that exports CONDA_DEFAULT_ENV and nothing that names a directory.++ Test-ActiveCondaEnvironment accepts that shape on purpose, but nothing then identifies+ which PATH entries are conda's, so the refresh would rebuild PATH as Machine, User,+ previous and put the hook's entries behind the User PATH again. Guessing from the+ environment NAME would promote any directory containing it, so the caller's PATH is kept+ whole and in front instead.+ """+ previous = f"{CONDA_ROOT}\\envs\\ml\\Scripts;C:\\tools\\bin"+ script = _stub_registry(_refresh_preamble(previous))+ out = _run(shell, script, env = {"CONDA_DEFAULT_ENV": "ml"})+ entries = out[len("PATH=") :].split(";")+ assert entries[: len(previous.split(";"))] == previous.split(";"), entries+ # The registry values are still there, just behind, so a directory registered by this+ # run is reachable in the same session without displacing the environment.+ assert USER_PATH.split(";")[0] in entries, entries+ assert MACHINE.split(";")[0] in entries, entries+ assert entries.index(USER_PATH.split(";")[0]) > entries.index("C:\\tools\\bin"), entries++[email protected](not POWERSHELLS, reason = "PowerShell is unavailable")[email protected]("shell", POWERSHELLS)+def test_a_prefix_activation_still_takes_the_precise_route(shell: str):+ """The whole-PATH fallback is for the case where nothing better can be known, so an+ activation that DOES name its prefix must keep the targeted behaviour: only the conda+ entries move, and an unrelated directory that happened to be on PATH does not."""+ previous = f"C:\\tools\\bin;{CONDA_ROOT}\\envs\\ml\\Scripts"+ script = _stub_registry(_refresh_preamble(previous))+ out = _run(+ shell,+ script,+ env = {+ "CONDA_PREFIX": f"{CONDA_ROOT}\\envs\\ml",+ "CONDA_DEFAULT_ENV": "ml",+ },+ )+ entries = out[len("PATH=") :].split(";")+ assert entries[0] == f"{CONDA_ROOT}\\envs\\ml\\Scripts", entries+ assert entries.index("C:\\tools\\bin") > entries.index(USER_PATH.split(";")[0]), entries+++# ── setup.ps1 refreshes the session too ──+# install.ps1 hands off to studio/setup.ps1, which calls Refresh-Environment after it+# registers CMake or Python. Direct execution shares the caller's PowerShell process, so a+# rebuild as machine + user + previous demotes the active conda environment for the rest of+# the setup AND after it returns, which is the same defect in the second half of the install.+++def _setup_refresh_preamble(current_path: str) -> str:+ """Refresh-Environment with the registry reads stubbed and $env:Path seeded."""+ body = (+ _function(SETUP_PS1, "", "Test-ActiveCondaEnvironment")+ + _function(SETUP_PS1, "", "Get-ActiveCondaPrefixes")+ + _function(SETUP_PS1, "", "Test-PathUnderCondaPrefix")+ + _function(SETUP_PS1, "", "Refresh-Environment")+ )+ return f"""+$ErrorActionPreference = "Stop"+{body}+$env:VIRTUAL_ENV = ""+$env:Path = "{current_path}"+Refresh-Environment+Write-Host ("PATH=" + $env:Path)+"""+++def _stub_setup_registry(script: str) -> str:+ return script.replace(+ "$machinePath = [System.Environment]::GetEnvironmentVariable('Path', 'Machine')",+ f'$machinePath = "{MACHINE}"',+ ).replace(+ "$userPath = [System.Environment]::GetEnvironmentVariable('Path', 'User')",+ f'$userPath = "{USER_PATH}"',+ )++[email protected](not POWERSHELLS, reason = "PowerShell is unavailable")[email protected]("shell", POWERSHELLS)+def test_the_setup_refresh_keeps_an_active_conda_ahead_of_the_user_path(shell: str):+ script = _stub_setup_registry(_setup_refresh_preamble(f"{_CONDA_ENTRIES};{MACHINE}"))+ assert "GetEnvironmentVariable('Path'" not in script, "the registry stub stopped matching"+ out = _run(+ shell,+ script,+ env = {+ "CONDA_PREFIX": f"{CONDA_ROOT}\\envs\\ml",+ "CONDA_DEFAULT_ENV": "ml",+ "CONDA_EXE": f"{CONDA_ROOT}\\Scripts\\conda.exe",+ },+ )+ assert out.startswith("PATH="), out+ entries = out[len("PATH=") :].split(";")+ lowered = [entry.rstrip("\\").lower() for entry in entries]+ conda_positions = [+ index for index, entry in enumerate(lowered) if entry.startswith(CONDA_ROOT.lower())+ ]+ assert conda_positions, f"the conda entries were dropped entirely: {entries}"+ user_first = min(+ index for index, entry in enumerate(lowered) if entry.startswith("c:\\users\\me")+ )+ assert (+ max(conda_positions) < user_first+ ), f"setup.ps1 left an activated conda environment behind the User PATH: {entries}"+ assert len(lowered) == len(set(lowered)), entries++[email protected](not POWERSHELLS, reason = "PowerShell is unavailable")[email protected]("shell", POWERSHELLS)+def test_the_setup_refresh_is_unchanged_outside_conda(shell: str):+ """Refresh-Environment runs on the hot path of the whole setup and must keep doing+ exactly what it did when no conda environment is active."""+ previous = "C:\\tools\\bin"+ script = _stub_setup_registry(_setup_refresh_preamble(previous))+ out = _run(shell, script, env = _NO_CONDA)+ entries = out[len("PATH=") :].split(";")+ assert entries == MACHINE.split(";") + USER_PATH.split(";") + [previous], entries+++def test_the_setup_refresh_consults_the_conda_helper_at_all():+ """A static pair for the pwsh cases above, so a Windows-only regression is still caught+ on a runner without PowerShell."""+ body = _function(SETUP_PS1, "", "Refresh-Environment")+ assert "Test-ActiveCondaEnvironment" in body, body+ assert "Get-ActiveCondaPrefixes" in body, body+ assert "Test-PathUnderCondaPrefix" in body, body+++# ── a prepend a previous run persisted has to be REPOSITIONED, not accepted ──+# The presence checks accept any spelling, so they never add a second line. That is right for+# the duplicate it prevents and wrong for the one it hides: a run from outside conda writes the+# prepend, and a later run from inside one then finds "the directory is already there" and+# leaves our entry ahead of the environment in every shell from then on.+++def _shell_function(path: Path, name: str) -> str:+ source = path.read_text(encoding = "utf-8")+ match = re.search(rf"^{re.escape(name)}\(\) \{{.*?^\}}\n", source, flags = re.DOTALL | re.M)+ assert match is not None, f"{path.name} no longer defines {name}"+ return match.group(0)++[email protected]("path", [INSTALL_SH, SETUP_SH_POSIX], ids = ["install.sh", "setup.sh"])+def test_the_rc_repointer_rewrites_only_the_line_it_wrote(path: Path, tmp_path: Path):+ rc = tmp_path / "rc"+ rc.write_text(+ "# Added by Unsloth installer\n"+ 'export PATH="$HOME/.local/bin:$PATH"\n'+ "# a comment\n"+ 'export PATH="/opt/mine:$PATH"\n'+ "alias ll='ls -l'\n",+ encoding = "utf-8",+ )+ script = (+ _shell_function(path, "_unsloth_repoint_rc_line")+ + f'_unsloth_repoint_rc_line "{rc}"'+ + " 'export PATH=\"$HOME/.local/bin:$PATH\"'"+ + " 'export PATH=\"$PATH:$HOME/.local/bin\"'\n"+ + 'echo "status=$?"\n'+ )+ out = subprocess.run(+ ["sh", "-c", script],+ capture_output = True,+ text = True,+ timeout = 60,+ )+ assert "status=0" in out.stdout, (out.stdout, out.stderr)+ assert rc.read_text(encoding = "utf-8") == (+ "# Added by Unsloth installer\n"+ 'export PATH="$PATH:$HOME/.local/bin"\n'+ "# a comment\n"+ # The user's own line is untouched: only an exact match on what we write is ours.+ 'export PATH="/opt/mine:$PATH"\n'+ "alias ll='ls -l'\n"+ )+ # And no staging file is left in the user's home.+ assert [p.name for p in tmp_path.iterdir()] == ["rc"]+++def test_the_rc_repointer_keeps_a_symlinked_rc_a_symlink(tmp_path: Path):+ """An rc file managed by chezmoi or home-manager is a symlink into a repo. Replacing it+ with a fresh file would detach it from the thing that manages it."""+ real = tmp_path / "dotfiles" / "bashrc"+ real.parent.mkdir()+ real.write_text(+ '# Added by Unsloth installer\nexport PATH="$HOME/.local/bin:$PATH"\n',+ encoding = "utf-8",+ )+ link = tmp_path / ".bashrc"+ link.symlink_to(real)++ script = (+ _shell_function(INSTALL_SH, "_unsloth_repoint_rc_line")+ + f'_unsloth_repoint_rc_line "{link}"'+ + " 'export PATH=\"$HOME/.local/bin:$PATH\"'"+ + " 'export PATH=\"$PATH:$HOME/.local/bin\"'\n"+ )+ subprocess.run(["sh", "-c", script], capture_output = True, text = True, timeout = 60)+ assert link.is_symlink(), "the rc file was replaced instead of rewritten"+ assert real.read_text(encoding = "utf-8") == (+ '# Added by Unsloth installer\nexport PATH="$PATH:$HOME/.local/bin"\n'+ )+++ "path,arms",+ [+ (INSTALL_SH, ("_persist_login_path_dir", "_persist_fish_path_dir")),+ (SETUP_SH_POSIX, ("_setup_persist_uv_path",)),+ ],+ ids = ["install.sh", "studio/setup.sh"],+)+def test_every_posix_writer_repositions_a_stale_prepend(path: Path, arms: tuple[str, ...]):+ """A guard that only applies to a FIRST run is not a guard: every one of these writers is+ reached again by the next `irm | iex`."""+ for name in arms:+ body = _shell_function(path, name)+ assert (+ "_unsloth_repoint_rc_line" in body+ ), f"{path.name}:{name} accepts a stale prepend as present instead of moving it"+++def test_the_repoint_pass_runs_before_the_presence_guards():+ """The guard that skips the writers is satisfied by the very line that needs moving.++ A previous run wrote the prepend, the shell that launched this installer evaluated it,+ so the directory IS on the login PATH and `_path_has_dir` short-circuits the call. The+ repointing therefore has to happen ahead of that guard, and it has to add nothing when+ it gets there.+ """+ source = INSTALL_SH.read_text(encoding = "utf-8")+ shim_guard = source.index('if ! _path_has_dir "$_UNSLOTH_LOGIN_PATH" "$_LOCAL_BIN"')+ shim_repoint = source.index('"~/.local/bin" \'\\.local/bin\' "" repoint')+ assert shim_repoint < shim_guard, "the shim repoint is behind the guard that skips it"++ uv_guard = source.index('if ! _path_has_dir "$_UNSLOTH_LOGIN_PATH" "$_UNSLOTH_UV_BIN_DIR"')+ uv_repoint = source.index('"$_UNSLOTH_UV_BIN_DIR" "" "$_uv_prof" repoint')+ assert uv_repoint < uv_guard, "the uv repoint is behind the guard that skips it"++ setup = SETUP_SH_POSIX.read_text(encoding = "utf-8")+ early_return = setup.index('_setup_path_has_dir "${_SETUP_LOGIN_PATH:-$PATH}" "$_supp_dir"')+ assert (+ "_unsloth_conda_env_active || return 0" in setup[early_return : early_return + 300]+ ), "studio/setup.sh still returns before it can reposition anything"+++ "mode,expected",+ [+ ("repoint", '# Added by Unsloth installer\nexport PATH="$PATH:/opt/unsloth/bin"\n'),+ ("", '# Added by Unsloth installer\nexport PATH="$PATH:/opt/unsloth/bin"\n'),+ ],+ ids = ["repoint-only", "ordinary"],+)+def test_the_repoint_only_mode_adds_nothing(tmp_path: Path, mode: str, expected: str):+ """Repointing must not put a line in the rc file of someone whose PATH comes from+ somewhere else: the caller's guard already decided against adding one."""+ rc = tmp_path / "rc"+ rc.write_text(+ '# Added by Unsloth installer\nexport PATH="/opt/unsloth/bin:$PATH"\n',+ encoding = "utf-8",+ )+ empty = tmp_path / "empty"+ empty.write_text("# nothing here\n", encoding = "utf-8")+ source = INSTALL_SH.read_text(encoding = "utf-8")+ body = (+ _shell_function(INSTALL_SH, "_unsloth_repoint_rc_line")+ + _shell_function(INSTALL_SH, "_unsloth_conda_env_active")+ + _shell_function(INSTALL_SH, "_persist_fish_path_dir")+ + re.search(r"^_PATH_LINE_RE=.*$", source, flags = re.M).group(0)+ + "\n"+ + _shell_function(INSTALL_SH, "_persist_login_path_dir")+ )+ script = f"""+CONDA_PREFIX=/opt/conda+step() {{ :; }}+substep() {{ :; }}+C_WARN=""+{body}+_persist_login_path_dir "/opt/unsloth/bin" "/opt/unsloth/bin" "/opt/unsloth/bin" \\+ "/opt/unsloth/bin" "{rc}" "{mode}"+_persist_login_path_dir "/opt/unsloth/bin" "/opt/unsloth/bin" "/opt/unsloth/bin" \\+ "/opt/unsloth/bin" "{empty}" "{mode}"+"""+ subprocess.run(["sh", "-c", script], capture_output = True, text = True, timeout = 60)+ # The stale prepend is repositioned in both modes.+ assert rc.read_text(encoding = "utf-8") == expected+ # And only the ordinary mode adds a line where there was none.+ added = "/opt/unsloth/bin" in empty.read_text(encoding = "utf-8")+ assert added is (mode != "repoint"), empty.read_text(encoding = "utf-8")+++ "path",+ [INSTALL_SH, SETUP_SH_POSIX],+ ids = ["install.sh", "studio/setup.sh"],+)+def test_the_rc_repointer_never_exposes_a_truncated_rc_file(path: Path, tmp_path: Path):+ """`cat staged > rc` truncates the user's profile before it writes a byte back.++ An interrupt or an I/O error in between leaves a half-written rc file, and the failure+ branch then deleted the staged copy, which was the only complete one left. The next+ login sources the wreckage. A rename is atomic: the file is the old one or the new one+ and never neither, which is asserted here by making the rename itself fail.+ """+ rc = tmp_path / "rc"+ original = 'export PATH="$HOME/.local/bin:$PATH"\n# keep me\n'+ rc.write_text(original, encoding = "utf-8")+ script = (+ # `mv` is what commits the rewrite, so a shell function that shadows it and fails is+ # exactly "the commit did not complete".+ "mv() { return 1; }\n"+ + _shell_function(path, "_unsloth_repoint_rc_line")+ + f'_unsloth_repoint_rc_line "{rc}"'+ + " 'export PATH=\"$HOME/.local/bin:$PATH\"'"+ + " 'export PATH=\"$PATH:$HOME/.local/bin\"'\n"+ + 'echo "status=$?"\n'+ )+ out = subprocess.run(["sh", "-c", script], capture_output = True, text = True, timeout = 60)+ assert "status=1" in out.stdout, (out.stdout, out.stderr)+ # The whole point: the user's profile is intact, not empty and not half of itself.+ assert rc.read_text(encoding = "utf-8") == original+ assert [p.name for p in tmp_path.iterdir()] == ["rc"], "a staging file was left behind"+++def test_the_rc_repointer_keeps_the_permission_bits_it_found(tmp_path: Path):+ """A 0600 rc file must not come back 0644 because the rename handed it the umask.++ The staged file is created as a COPY for that reason, so it carries the original's bits+ before a line of it is rewritten.+ """+ rc = tmp_path / "rc"+ rc.write_text(+ '# Added by Unsloth installer\nexport PATH="$HOME/.local/bin:$PATH"\n',+ encoding = "utf-8",+ )+ rc.chmod(0o600)+ script = (+ _shell_function(INSTALL_SH, "_unsloth_repoint_rc_line")+ + f'_unsloth_repoint_rc_line "{rc}"'+ + " 'export PATH=\"$HOME/.local/bin:$PATH\"'"+ + " 'export PATH=\"$PATH:$HOME/.local/bin\"'\n"+ )+ subprocess.run(["sh", "-c", script], capture_output = True, text = True, timeout = 60)+ assert rc.read_text(encoding = "utf-8") == (+ '# Added by Unsloth installer\nexport PATH="$PATH:$HOME/.local/bin"\n'+ )+ assert stat.S_IMODE(rc.stat().st_mode) == 0o600, oct(rc.stat().st_mode)+++ "path,indent",+ [(INSTALL_PS1, " "), (SETUP_PS1, "")],+ ids = ["install.ps1", "studio/setup.ps1"],+)+def test_every_stacked_conda_prefix_is_enumerated(path: Path, indent: str):+ """`conda activate --stack` records the outer environments as CONDA_PREFIX_1, _2, _3,+ _4 and on, and CONDA_SHLVL counts them.++ A fixed list ending at _3 dropped everything past the fourth environment, so+ `Refresh-SessionPath` left those prefixes out of the conda front and their entries+ sorted after Machine and User -- the inverse of the ordering the stack established.+ """+ body = _function(path, indent, "Get-ActiveCondaPrefixes")+ assert "CONDA_SHLVL" in body, body+ assert 'GetEnvironmentVariable("CONDA_PREFIX_$level")' in body, body+ # And no hard-coded tail is left to go stale again.+ for stale in ("CONDA_PREFIX_1", "CONDA_PREFIX_2", "CONDA_PREFIX_3"):+ assert f"$env:{stale}" not in body, (stale, body)+ # A bad or absent CONDA_SHLVL must not spin or skip the active environment.+ assert "$levels -gt 64" in body, body+ assert "$env:CONDA_PREFIX)" in body, body+++ "path",+ [INSTALL_SH, SETUP_SH_POSIX],+ ids = ["install.sh", "studio/setup.sh"],+)+def test_the_rc_repointer_rewrites_a_line_holding_a_backslash(path: Path, tmp_path: Path):+ """POSIX awk decodes backslash escapes in a `-v` assignment.++ The writers escape a backslash before building the line, so the value handed to awk was+ not the value in the file: the literal `grep -qxF` matched, awk matched nothing, and the+ helper renamed an unchanged file and reported success -- the installer said the stale+ prepend had been moved while conda was still in front of it.+ """+ rc = tmp_path / "rc"+ old_line = 'export PATH="/opt/od\\\\d/bin:$PATH"'+ new_line = 'export PATH="$PATH:/opt/od\\\\d/bin"'+ rc.write_text("# Added by Unsloth installer\n" + old_line + "\n# keep me\n", encoding = "utf-8")+ script = (+ _shell_function(path, "_unsloth_repoint_rc_line")+ + "_unsloth_repoint_rc_line "+ + f"'{rc}' '{old_line}' '{new_line}'\n"+ + 'echo "status=$?"\n'+ )+ out = subprocess.run(["sh", "-c", script], capture_output = True, text = True, timeout = 60)+ assert "status=0" in out.stdout, (out.stdout, out.stderr)+ assert rc.read_text(encoding = "utf-8") == (+ "# Added by Unsloth installer\n" + new_line + "\n# keep me\n"+ ), rc.read_text(encoding = "utf-8")+++def test_the_uv_repoint_pass_moves_the_home_relative_spelling_too():+ """The default uv destination IS ~/.local/bin, and the shim block writes that line+ unexpanded as `$HOME/.local/bin`."""+ source = INSTALL_SH.read_text(encoding = "utf-8")+ start = source.index("_uv_repoint_literal=")+ block = source[start : source.index("_persist_fish_path_dir", start)]+ assert "_uv_repoint_home_literal" in block, block+ assert "'$HOME'" in block, block+ # Both spellings inside the per-profile loop, not only the expanded one.+ assert block.count("_persist_login_path_dir") == 2, block+ # $HOME stays unexpanded; only the rest of the path is escaped.+ assert "${_UNSLOTH_UV_BIN_DIR#$HOME}" in block, block+++def test_the_standalone_setup_repoints_the_home_relative_prepend_too():+ """`studio/setup.sh` runs on its own during an update, after install.sh wrote the shim line+ as `export PATH="$HOME/.local/bin:$PATH"`."""+ body = _shell_function(SETUP_SH_POSIX, "_setup_persist_uv_path")+ assert "_supp_export_home_prepend" in body, body+ assert "'$HOME'" in body, body+ assert "${_supp_dir#$HOME}" in body, body+ # In the repoint-only branch AND in the present-already branch, which are the two places+ # a stale prepend is reachable.+ assert body.count('_supp_export_home_prepend"') >= 2, body+++ "path",+ [INSTALL_SH, SETUP_SH_POSIX],+ ids = ["install.sh", "studio/setup.sh"],+)+def test_the_rc_repointer_leaves_a_line_the_user_wrote(path: Path, tmp_path: Path):+ """`export PATH="$HOME/.local/bin:$PATH"` is a line people write by hand all the time.++ Rewriting one moves every executable in that directory behind the rest of PATH for good,+ in every later shell, conda or not. Both installers write a `# Added by Unsloth ...`+ comment immediately above the line they add, so that marker is the ownership record and+ an identical line without it is not ours to touch.+ """+ rc = tmp_path / "rc"+ original = "# my own path\n" 'export PATH="$HOME/.local/bin:$PATH"\n' 'alias ll="ls -l"\n'+ rc.write_text(original, encoding = "utf-8")+ script = (+ _shell_function(path, "_unsloth_repoint_rc_line")+ + f'_unsloth_repoint_rc_line "{rc}"'+ + " 'export PATH=\"$HOME/.local/bin:$PATH\"'"+ + " 'export PATH=\"$PATH:$HOME/.local/bin\"'\n"+ + 'echo "status=$?"\n'+ )+ out = subprocess.run(["sh", "-c", script], capture_output = True, text = True, timeout = 60)+ # Not ours -> a refusal, and the caller's own branch prints the manual advice.+ assert "status=1" in out.stdout, (out.stdout, out.stderr)+ assert rc.read_text(encoding = "utf-8") == original, rc.read_text(encoding = "utf-8")diff --git a/tests/python/test_windows_arm64_python_choice.py b/tests/python/test_windows_arm64_python_choice.pyindex 176c168646f..21db862c301 100644--- a/tests/python/test_windows_arm64_python_choice.py+++ b/tests/python/test_windows_arm64_python_choice.py@@ -44,6 +44,15 @@ def _resolver_script(installed: list[tuple[str, str]], can_download: bool) -> stsource = 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(@@ -95,13 +104,17 @@ function Get-PythonPlatformTag {{param([string]$Exe)foreach ($i in $Interpreters) {{if ($i.Name -eq $Exe) {{- if ($i.Arch -eq "x86_64") {{ return "win-amd64" }} else {{ return "win-arm64" }}+ 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.@@ -114,6 +127,83 @@ if ($found) {{ Write-Output "$($found.Version)|$($found.Arch)" }} else {{ Write-"""+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.@@ -122,7 +212,7 @@ def _pwsh(script: str) -> str:check = True,capture_output = True,text = True,- env = os.environ.copy(),+ env = _environment_without_the_arm64_opt_out(),)return result.stdout.strip()@@ -144,3 +234,87 @@ def _pwsh(script: str) -> str:)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.pynew file mode 100644index 00000000000..2b4e254800b--- /dev/null+++ b/tests/python/test_windows_on_arm_python_arch.py@@ -0,0 +1,778 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""Windows on ARM has to end up on an x64 interpreter, or stop.++PyPI publishes no `win_arm64` wheel for pyarrow (reached through `datasets`) or+hf-transfer, at any version, so a native ARM64 CPython source-builds both and dies on CMake+or Rust minutes in. Measured on a windows-11-arm runner with ARM64 CPython 3.12.10:++ ERROR: Could not find a version that satisfies the requirement pyarrow (from versions: none)+ *** CMake configuration failed++The same probe on x64 resolved both, so it is the interpreter architecture. install.ps1+already swaps a freshly selected ARM64 interpreter for x64; these tests close what it does+when that swap CANNOT be made, and the fact that it only looks at a FRESH selection, so a+migrated environment is reused on whatever built it.++Provenance: #8495, #10875.+"""++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"+POWERSHELLS = [shell for shell in ("pwsh", "powershell") if shutil.which(shell)]+++def _function(name: str) -> str:+ """The named function's source, verbatim from install.ps1.++ Extracted rather than restated so these cases track the installer instead of a copy of+ it, and indented-brace delimited rather than marker delimited so rewording a comment+ cannot silently change what is under test.+ """+ source = INSTALL_PS1.read_text(encoding = "utf-8")+ match = re.search(rf" function {name} \{{.*?\n \}}\n", source, flags = re.DOTALL)+ assert match is not None, f"install.ps1 no longer defines {name}"+ return match.group(0)+++def _run(+ shell: str,+ script: str,+ env: dict[str, str] | None = None,+) -> str:+ # run_pwsh, not subprocess.run: both shells write UTF-8 while `text = True` alone+ # decodes with the runner's locale codec. See tests/_shared/unsloth_pwsh_runner.py.+ result = run_pwsh(+ [shell, "-NoProfile", "-NonInteractive", "-Command", script],+ check = True,+ capture_output = True,+ text = True,+ encoding = "utf-8",+ errors = "strict",+ env = {**os.environ, **(env or {})},+ timeout = 60,+ )+ return result.stdout.strip()+++# The shared preamble: the two host helpers the functions under test call, stubbed so the+# decision is driven by the case rather than by the machine running the suite. Neither stub+# 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:+ # 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+$script:StudioStdoutRedirected = $false+function Write-StudioLine {{+ param([string]$Message = "", [string]$ForegroundColor)+ Write-Host $Message+}}+function step {{ param([string]$Label, [string]$Value, [string]$Color = "Green") Write-Host "STEP ${{Label}}: $Value" }}+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"++[email protected](not POWERSHELLS, reason = "PowerShell is unavailable")[email protected]("shell", POWERSHELLS)+ "host_arch,venv_tag,selected_arch,venv_exists,expected",+ [+ # The reported shape: ARM64 host, x64 interpreter chosen for this run, environment+ # migrated from an older install and therefore still native ARM64.+ ("arm64", "win-arm64", "x86_64", True, True),+ # Already x64: nothing to rebuild.+ ("arm64", "win-amd64", "x86_64", True, False),+ # Not Windows on ARM at all.+ ("x86_64", "win-amd64", "x86_64", True, False),+ # ARM64 host where the chosen interpreter is ARM64 too. Nothing better is in hand,+ # so this must NOT fire: it is also the shape a host served by native ARM64 wheels+ # has, and rebuilding its environment would be a regression rather than a fix.+ ("arm64", "win-arm64", "arm64", True, False),+ # No environment to reuse: the fresh-venv branch handles this one.+ ("arm64", "win-arm64", "x86_64", False, False),+ # An interpreter that cannot be launched answers nothing; the managed-Python error+ # further down install.ps1 is what should report that, not a silent rebuild.+ ("arm64", "", "x86_64", True, False),+ ],+)+def test_a_reused_environment_is_re_checked_for_its_interpreter_architecture(+ tmp_path: Path,+ shell: str,+ host_arch: str,+ venv_tag: str,+ selected_arch: str,+ venv_exists: bool,+ expected: bool,+):+ """The swap only covers a fresh selection, so reuse has to be re-checked separately."""+ venv_python = tmp_path / "python.exe"+ if venv_exists:+ 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)+ + f"""+{_function("Test-StudioVenvArchMismatch")}+$selected = {selected}+$mismatch = Test-StudioVenvArchMismatch -VenvPython "{venv_python}" -SelectedPython $selected+Write-Host ("MISMATCH=" + $mismatch)+"""+ )+ out = _run(shell, script)+ assert f"MISMATCH={expected}" in out++[email protected](not POWERSHELLS, reason = "no PowerShell on this host")[email protected]("shell", POWERSHELLS)[email protected]("value", ["1", "true", "YES", "on"])+def test_the_opt_out_also_protects_an_existing_arm64_environment(+ tmp_path: Path, shell: str, value: str+):+ """The opt-out has to be read HERE, not only where a fresh interpreter is chosen.++ Resolve-WindowsOnArmX64Python never runs when the ordinary probe already found x64, so+ on an ARM64 box with both interpreters the variable was never consulted and this branch+ moved aside the very environment the user asked to keep. The rebuild is not a migration:+ nothing installed into the old venv carries over.+ """+ venv_python = tmp_path / "python.exe"+ 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)+ + f"""+{_function("Test-StudioVenvArchMismatch")}+$selected = {selected}+$mismatch = Test-StudioVenvArchMismatch -VenvPython "{venv_python}" -SelectedPython $selected+Write-Host ("MISMATCH=" + $mismatch)+"""+ )+ out = _run(shell, script, env = {"UNSLOTH_ALLOW_ARM64_PYTHON": value})+ assert (+ "MISMATCH=False" in out+ ), "the opt-out was ignored and an existing ARM64 environment was scheduled for replacement"++[email protected](not POWERSHELLS, reason = "no PowerShell on this host")[email protected]("shell", POWERSHELLS)+def test_the_arm64_environment_is_still_replaced_without_the_opt_out(tmp_path: Path, shell: str):+ """The other direction, so the guard above cannot be satisfied by never firing."""+ venv_python = tmp_path / "python.exe"+ 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)+ + f"""+{_function("Test-StudioVenvArchMismatch")}+$selected = {selected}+$mismatch = Test-StudioVenvArchMismatch -VenvPython "{venv_python}" -SelectedPython $selected+Write-Host ("MISMATCH=" + $mismatch)+"""+ )+ out = _run(shell, script)+ assert "MISMATCH=True" in out+++def test_both_arm64_opt_out_readers_go_through_one_helper():+ """Two spellings of the same question drift. The fresh-selection path and the reuse+ re-check must read it the same way, or an accepted value works in one and not the+ other."""+ source = INSTALL_PS1.read_text(encoding = "utf-8")+ assert source.count("function Test-Arm64PythonOptOut") == 1+ # The literal comparison lives in the helper and nowhere else.+ assert (+ source.count("$env:UNSLOTH_ALLOW_ARM64_PYTHON -in") == 1+ ), "the opt-out is compared in more than one place"+ assert (+ source.count("Test-Arm64PythonOptOut") >= 3+ ), "both the selection path and the venv re-check have to call it"+++def test_the_arm64_rebuild_tells_the_user_what_it_does_not_carry_over():+ """A rebuild on a different architecture cannot reuse the old wheels, so packages the+ user added to the ARM64 environment are gone from the new one. That is unavoidable; a+ silent version of it is not. The branch has to name where the old tree went and how to+ opt out."""+ source = INSTALL_PS1.read_text(encoding = "utf-8")+ start = source.find("Test-StudioVenvArchMismatch -VenvPython")+ assert start != -1+ block = source[start : source.find('step "venv" "creating Python', start)]+ assert "unsloth_studio.arm64" in block, "the rebuild does not say where the old venv went"+ 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.++ Ordering is the whole property: placed after `step "venv" "using migrated environment"`+ it would run once the installer had already committed to the environment.+ """+ source = INSTALL_PS1.read_text(encoding = "utf-8")+ recheck = source.find("Test-StudioVenvArchMismatch -VenvPython")+ create = source.find('step "venv" "creating Python')+ reuse = source.find('step "venv" "using migrated environment"')+ assert recheck != -1, "install.ps1 no longer re-checks the reused interpreter"+ assert create != -1 and reuse != -1+ assert recheck < create < reuse, "the re-check must precede the create/reuse branch"+ # And it must clear $_Migrated, or the install step downstream runs --no-deps into the+ # fresh venv it just created and installs nothing.+ tail = source[recheck:create]+ assert "$_Migrated = $false" in tail+++# ── 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 ──+++def _rollback_preamble(studio_home: Path) -> str:+ 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" }}+$StudioHome = "{studio_home}"+function Remove-StudioVenvTreeWithRetry {{+ param([string]$Path, [string]$Label)+ Write-Host "REMOVED $Path"+ Remove-Item -LiteralPath $Path -Recurse -Force+ return $true+}}+{_function("Test-StudioPathPresent")}+{_function("Complete-StudioVenvRollback")}+"""++[email protected](not POWERSHELLS, reason = "PowerShell is unavailable")[email protected]("shell", POWERSHELLS)+def test_the_preserved_arm64_environment_survives_a_successful_install(tmp_path: Path, shell: str):+ """The rebuild promises the ARM64 environment is kept so packages can be copied out.++ Complete-StudioVenvRollback deletes the backup on success, which is right for every+ other rollback but wrong for this one: the old tree holds packages the new architecture+ cannot have, and deleting it discards them and the message that said otherwise.+ """+ home = tmp_path / "studio"+ backup = home / "unsloth_studio.rollback.20260101000000.4242"+ (backup / "Lib").mkdir(parents = True)+ (backup / "Lib" / "marker.txt").write_text("a package the user added", encoding = "utf-8")++ script = (+ _rollback_preamble(home)+ + f"""+$script:StudioVenvRollbackActive = $true+$script:StudioVenvRollbackDir = "{backup}"+$script:StudioVenvRollbackPartial = $false+$script:StudioVenvRollbackPreserve = $true+Complete-StudioVenvRollback+Write-Host ("COMMITTED=" + $script:StudioInstallCommitted)+Write-Host ("PRESERVE=" + $script:StudioVenvRollbackPreserve)+"""+ )+ out = _run(shell, script)+ assert "COMMITTED=True" in out, "the commit flag is what stops a later restore"+ assert "PRESERVE=False" in out, "the flag must not survive into a later rollback"+ assert "REMOVED" not in out, "the tree the user was told to read must not be deleted"+ assert not backup.exists(), "it has to leave the rollback namespace, see below"++ kept = [path for path in home.iterdir() if path.name.startswith("unsloth_studio.arm64.")]+ assert len(kept) == 1, f"expected one preserved ARM64 tree, found {[p.name for p in kept]}"+ assert (kept[0] / "Lib" / "marker.txt").read_text(encoding = "utf-8") == (+ "a package the user added"+ )+ assert (+ f"previous ARM64 environment kept at {kept[0]}" in out+ ), "a preserved tree nobody is told the path of is just disk usage"++[email protected](not POWERSHELLS, reason = "PowerShell is unavailable")[email protected]("shell", POWERSHELLS)+def test_an_ordinary_rollback_is_still_deleted_on_success(tmp_path: Path, shell: str):+ """The preserve flag is opt-in, and every other rollback keeps the old behaviour.++ Without this the fix trades one bug for a slow leak: a full environment left behind by+ every reinstall, on the machine of every user who never asked for one.+ """+ home = tmp_path / "studio"+ backup = home / "unsloth_studio.rollback.20260101000000.4242"+ backup.mkdir(parents = True)++ script = (+ _rollback_preamble(home)+ + f"""+$script:StudioVenvRollbackActive = $true+$script:StudioVenvRollbackDir = "{backup}"+$script:StudioVenvRollbackPartial = $false+$script:StudioVenvRollbackPreserve = $false+Complete-StudioVenvRollback+"""+ )+ out = _run(shell, script)+ assert f"REMOVED {backup}" in out+ assert not backup.exists()+ assert not list(home.iterdir()), "nothing is kept when nothing was promised"+++def test_the_preserved_tree_leaves_the_swept_rollback_namespace():+ """Remove-StaleStudioVenvRollbacks globs unsloth_studio.rollback.*, and preserves an entry+ only while its owning PID is alive."""+ source = INSTALL_PS1.read_text(encoding = "utf-8")+ complete = source.index("function Complete-StudioVenvRollback")+ block = source[complete : source.index("\n }\n", complete)]+ # Comments out: this function's explain why it does NOT use the rollback name, and a+ # test that reads them as code would fail on the sentence describing the fix.+ code = "\n".join(line for line in block.splitlines() if not line.lstrip().startswith("#"))+ assert "unsloth_studio.arm64." in code, "the preserved copy is not renamed"+ assert (+ "unsloth_studio.rollback." not in code+ ), "a preserved copy under the swept name is removed by the next install"+ sweep = source.index("function Remove-StaleStudioVenvRollbacks")+ sweep_block = source[sweep : source.index("\n }\n", sweep)]+ assert (+ "'unsloth_studio.rollback.*'" in sweep_block+ ), "the sweep no longer matches what this test reasons about"+ assert "unsloth_studio.arm64" not in sweep_block+++# ── the interpreter is gone by the time the re-check runs ──+# An ordinary reinstall moves the whole environment to its rollback path, and that move+# happens BEFORE the x64 interpreter is chosen. Probing $VenvPython after it answers "no+# mismatch" for every existing install, so the rebuild proceeds on ARM64 and the tree is+# deleted with the ordinary rollback instead of being preserved.+++def test_the_platform_tag_is_read_before_the_rollback_move():+ source = INSTALL_PS1.read_text(encoding = "utf-8")+ record = source.find("$script:PrevVenvPlatformTag = Get-PythonPlatformTag")+ move = source.find("Start-StudioVenvRollback -ExistingDir $VenvDir")+ recheck = source.find("Test-StudioVenvArchMismatch -VenvPython")+ assert record != -1, "install.ps1 no longer records the existing interpreter's tag"+ assert record < move, "the tag is read after the move that takes the interpreter away"+ assert (+ "-RecordedTag $script:PrevVenvPlatformTag" in source[recheck : recheck + 400]+ ), "the re-check does not use the recorded tag, so it cannot see a moved environment"+++def _arch_mismatch_preamble(+ host_arch: str, opt_out: bool, venv_python_exists: bool, live_tag: str, recorded_tag: str+) -> str:+ selected = '@{ Version = "3.13"; Arch = "x86_64" }'+ exists = "$true" if venv_python_exists else "$false"+ recorded = f'"{recorded_tag}"' if recorded_tag else "$null"+ return f"""+$ErrorActionPreference = "Stop"+function substep {{ param([string]$Message = "", [string]$Color) Write-Host "SUBSTEP $Message" }}+function Get-HostMachineArch {{ return "{host_arch}" }}+function Test-Arm64PythonOptOut {{ return ${str(opt_out).lower()} }}+function Get-PythonPlatformTag {{ param($Exe) return "{live_tag}" }}+function Test-Path {{ param([Parameter(ValueFromRemainingArguments = $true)]$Rest) return {exists} }}+{_function("Test-StudioVenvArchMismatch")}+$answer = Test-StudioVenvArchMismatch -VenvPython "C:\\venv\\Scripts\\python.exe" `+ -SelectedPython {selected} -RecordedTag {recorded}+Write-Host ("ANSWER=" + $answer)+"""++[email protected](not POWERSHELLS, reason = "PowerShell is unavailable")[email protected]("shell", POWERSHELLS)+def test_a_moved_arm64_environment_is_still_detected(shell: str):+ """The case the reinstall actually takes: the interpreter has been moved aside already."""+ out = _run(+ shell,+ _arch_mismatch_preamble("arm64", False, False, "win-amd64", "win-arm64"),+ )+ assert out.splitlines()[-1] == "ANSWER=True", out++[email protected](not POWERSHELLS, reason = "PowerShell is unavailable")[email protected]("shell", POWERSHELLS)+def test_a_moved_x64_environment_is_not_mistaken_for_one(shell: str):+ """The other half. A recorded tag that is not win-arm64 answers no, and so does no+ recorded tag at all, which is the fresh-install case."""+ out = _run(shell, _arch_mismatch_preamble("arm64", False, False, "win-arm64", "win-amd64"))+ assert out.splitlines()[-1] == "ANSWER=False", out+ out = _run(shell, _arch_mismatch_preamble("arm64", False, False, "win-arm64", ""))+ assert out.splitlines()[-1] == "ANSWER=False", out++[email protected](not POWERSHELLS, reason = "PowerShell is unavailable")[email protected]("shell", POWERSHELLS)+def test_the_opt_out_message_is_only_printed_for_an_arm64_environment(shell: str):+ """`UNSLOTH_ALLOW_ARM64_PYTHON=1` on an x64 environment used to announce that a native+ ARM64 environment was being kept, which was true of nothing on the machine."""+ out = _run(shell, _arch_mismatch_preamble("arm64", True, False, "win-amd64", "win-amd64"))+ assert "SUBSTEP" not in out, out+ assert out.splitlines()[-1] == "ANSWER=False", out++ # With a real ARM64 environment the opt-out still says what it is doing, and still+ # answers no.+ out = _run(shell, _arch_mismatch_preamble("arm64", True, True, "win-arm64", "win-arm64"))+ assert "UNSLOTH_ALLOW_ARM64_PYTHON" in out, out+ assert out.splitlines()[-1] == "ANSWER=False", out+++def test_the_architecture_rebuild_does_not_move_the_venv_twice():+ """An ordinary reinstall has already moved $VenvDir into a rollback by the time this+ branch runs, so a second Start-StudioVenvRollback would move a directory that is no+ longer there, throw, and take every architecture migration out through+ Exit-InstallFailure. The tree is already where the branch wants it; only the flag that+ keeps it from being swept is missing."""+ source = INSTALL_PS1.read_text(encoding = "utf-8")+ branch = source.index("windows on arm: the existing environment runs native ARM64 Python")+ tail = source[branch : branch + 2500]+ guard = tail.index("if ($script:StudioVenvRollbackActive)")+ move = tail.index("Start-StudioVenvRollback -ExistingDir $VenvDir")+ assert guard < move, "the rebuild still moves the environment unconditionally"+ assert (+ "$script:StudioVenvRollbackPreserve = $true" in tail[guard:move]+ ), "an already-active rollback is not marked for preservation"+++def test_the_opt_out_keeps_the_environment_it_says_it_keeps():+ """`UNSLOTH_ALLOW_ARM64_PYTHON=1` returning $false is not, by itself, keeping anything:+ on a host that already has an x64 Python the reinstall has moved the ARM64 environment+ into a rollback that success deletes. The opt-out marks that rollback preserved."""+ source = INSTALL_PS1.read_text(encoding = "utf-8")+ optout = source.index(+ '$script:PrevVenvPlatformTag -eq "win-arm64" -and (Test-Arm64PythonOptOut)'+ )+ create = source.index('step "venv" "creating Python')+ assert optout < create, "the opt-out preservation runs after the rebuild has started"+ assert "$script:StudioVenvRollbackPreserve = $true" in source[optout : optout + 600]+ 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/sh/test_install_conda_path_guard.sh b/tests/sh/test_install_conda_path_guard.shnew file mode 100755index 00000000000..555bc103242--- /dev/null+++ b/tests/sh/test_install_conda_path_guard.sh@@ -0,0 +1,421 @@+#!/bin/bash+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0+#+# The POSIX half of #5871. install.sh persists a PATH entry into a shell rc file (or+# ~/.config/fish/conf.d/unsloth.fish); written as a PREPEND it lands after conda's own init+# block, so every later shell resolves out of our directory first, an ordering that outlives+# the activation. The Windows half is tests/python/test_installer_conda_path_guard.py.+#+# Checked, in order:+#+# 1. Outside conda the written line is unchanged.+# 2. Inside conda the same directory is registered at the BACK.+# 3. Either spelling counts as present, so no machine collects two lines.+# 4. The advice printed when the rc file cannot be written matches what would have been+# written, or the manual fix reintroduces the defect by hand.+#+# studio/setup.sh carries a third copy and is covered at the end: it runs in its own process+# right after install.sh. The functions are extracted from the installers and run rather+# than restated, so these cases track them instead of a copy.+set -e++SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+. "$SCRIPT_DIR/_harness.sh"+REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"+INSTALL_SH="$REPO_ROOT/install.sh"++echo "=== test_install_conda_path_guard ==="++# Both persisters plus the regex they share. Asserted non-empty below, so a rename is loud.+extract_function() {+ awk -v name="$1" '+ $0 == name "() {" { grab = 1 }+ grab { print }+ grab && $0 == "}" { exit }+ ' "$INSTALL_SH"+}++PATH_LINE_RE_SRC=$(grep -n "^_PATH_LINE_RE=" "$INSTALL_SH" | head -n1 | cut -d: -f2-)+LOGIN_FN=$(extract_function _persist_login_path_dir)+FISH_FN=$(extract_function _persist_fish_path_dir)+# The predicate both writers ask, extracted rather than restated so a change reaches here.+CONDA_FN=$(extract_function _unsloth_conda_env_active)+# The migration helper both writers call. Without it in the harness every repoint call is a+# `command not found` inside a conditional and the cases below still pass.+REPOINT_FN=$(extract_function _unsloth_repoint_rc_line)++for _chunk_label in _PATH_LINE_RE _persist_login_path_dir _persist_fish_path_dir _unsloth_conda_env_active _unsloth_repoint_rc_line; do+ case "$_chunk_label" in+ _PATH_LINE_RE) _chunk="$PATH_LINE_RE_SRC" ;;+ _persist_login_path_dir) _chunk="$LOGIN_FN" ;;+ _unsloth_conda_env_active) _chunk="$CONDA_FN" ;;+ _unsloth_repoint_rc_line) _chunk="$REPOINT_FN" ;;+ *) _chunk="$FISH_FN" ;;+ esac+ if [ -z "$_chunk" ]; then+ echo " FAIL: could not extract $_chunk_label from install.sh"+ exit 1+ fi+done++# `step` and `substep` print in install.sh; captured so assertion 4 can read the advice.+HARNESS=$(cat <<'EOF'+step() { echo "STEP $1 $2"; }+substep() { echo "SUBSTEP $1"; }+C_WARN=""+EOF+)++# One run of _persist_login_path_dir against a throwaway HOME.+# $1 rc file contents ("" for an empty file), $2 CONDA_PREFIX ("" for none).+run_login() {+ WORK=$(mktemp -d)+ RC_FILE=${RC_NAME:+$WORK/$RC_NAME}+ printf '%s' "$1" > "${RC_FILE:-$WORK/.bashrc}"+ (+ eval "$HARNESS"+ eval "$PATH_LINE_RE_SRC"+ eval "$CONDA_FN"+ eval "$REPOINT_FN"+ eval "$LOGIN_FN"+ HOME="$WORK"+ SHELL="${4:-/bin/bash}"+ unset CONDA_PREFIX CONDA_DEFAULT_ENV+ # $3 names WHICH variable carries the activation: a hook exporting only+ # CONDA_DEFAULT_ENV still leaves the caller inside conda's ordering.+ if [ -n "$2" ]; then eval "${3:-CONDA_PREFIX}=\"\$2\"; export ${3:-CONDA_PREFIX}"; fi+ _persist_login_path_dir "$WORK/.local/bin" '$HOME/.local/bin' "~/.local/bin" '\.local/bin' "${RC_FILE:-$WORK/.bashrc}"+ )+ RC_CONTENTS=$(cat "${RC_FILE:-$WORK/.bashrc}")+ rm -rf "$WORK"+}++# 1. Outside conda: unchanged behaviour, a prepend.+run_login "" ""+assert_contains "no conda: writes a PATH prepend" "$RC_CONTENTS" 'export PATH="$HOME/.local/bin:$PATH"'++# 2. Inside an active conda environment: the same directory, at the back.+run_login "" "/opt/anaconda3"+assert_contains "active conda: writes a PATH append" "$RC_CONTENTS" 'export PATH="$PATH:$HOME/.local/bin"'+assert_not_contains "active conda: does not prepend" "$RC_CONTENTS" 'export PATH="$HOME/.local/bin:$PATH"'++# 3. Either spelling is already-present. Both directions, because a machine can meet+# the installer inside conda first and outside it later, or the reverse.+run_login 'export PATH="$PATH:$HOME/.local/bin"' ""+assert_not_contains "append already there: no prepend added" "$RC_CONTENTS" 'export PATH="$HOME/.local/bin:$PATH"'+assert_eq "append already there: exactly one PATH line" "1" "$(printf '%s\n' "$RC_CONTENTS" | grep -c 'local/bin')"++# Seeded WITH the marker the installer writes: that comment is the ownership record.+run_login '# Added by Unsloth installer+export PATH="$HOME/.local/bin:$PATH"' "/opt/anaconda3"+assert_eq "prepend already there: exactly one PATH line" "1" "$(printf '%s\n' "$RC_CONTENTS" | grep -c 'local/bin')"+# And that one line is the APPEND: counting lines alone passes whether the stale prepend was+# repointed or merely accepted as present, which is #5871.+assert_contains "stale prepend inside conda: rewritten as the append" "$RC_CONTENTS" \+ 'export PATH="$PATH:$HOME/.local/bin"'+assert_not_contains "stale prepend inside conda: the prepend is gone" "$RC_CONTENTS" \+ 'export PATH="$HOME/.local/bin:$PATH"'++# An identical line the USER wrote, with no marker above it, is not ours to move: rewriting+# one would push every executable in that directory behind the rest of PATH for good.+run_login 'export PATH="$HOME/.local/bin:$PATH"' "/opt/anaconda3"+assert_contains "unmarked user line inside conda: left alone" "$RC_CONTENTS" \+ 'export PATH="$HOME/.local/bin:$PATH"'+assert_eq "unmarked user line inside conda: no second line added" "1" \+ "$(printf '%s\n' "$RC_CONTENTS" | grep -c 'local/bin')"++# The same stale prepend OUTSIDE conda is left alone: reordering it would change PATH for a+# user who never had the problem.+run_login '# Added by Unsloth installer+export PATH="$HOME/.local/bin:$PATH"' ""+assert_contains "stale prepend outside conda: left alone" "$RC_CONTENTS" \+ 'export PATH="$HOME/.local/bin:$PATH"'+assert_eq "stale prepend outside conda: still one PATH line" "1" \+ "$(printf '%s\n' "$RC_CONTENTS" | grep -c 'local/bin')"++# 4. An unwritable rc file: the advice has to be the conda-safe line, not the prepend.+# Chmod, not a directory: the failure path under test is the append redirect failing.+WORK=$(mktemp -d)+: > "$WORK/.bashrc"+chmod 400 "$WORK/.bashrc"+ADVICE=$(+ eval "$HARNESS"+ eval "$PATH_LINE_RE_SRC"+ eval "$CONDA_FN"+ eval "$REPOINT_FN"+ eval "$LOGIN_FN"+ HOME="$WORK"+ SHELL=/bin/bash+ CONDA_PREFIX="/opt/anaconda3"; export CONDA_PREFIX+ _persist_login_path_dir "$WORK/.local/bin" '$HOME/.local/bin' "~/.local/bin" '\.local/bin' "$WORK/.bashrc" 2>&1+)+chmod 600 "$WORK/.bashrc"+if printf '%s' "$ADVICE" | grep -q 'could not write'; then+ assert_contains "unwritable rc: advice is the append form" "$ADVICE" 'export PATH="$PATH:$HOME/.local/bin"'+else+ # Running as root, where a 400 file is still writable. The case is about the advice+ # text, so skipping it loudly beats asserting nothing.+ ok "unwritable rc: skipped (this user can write a mode-400 file)"+fi+rm -rf "$WORK"++# 5. CONDA_DEFAULT_ENV alone, which a hook can export without CONDA_PREFIX. install.ps1 has+# always read both; the POSIX writers read only CONDA_PREFIX, so the same user got a+# prepend on Linux and an append on Windows.+run_login "" "myenv" CONDA_DEFAULT_ENV+assert_contains "CONDA_DEFAULT_ENV alone: writes a PATH append" "$RC_CONTENTS" 'export PATH="$PATH:$HOME/.local/bin"'+assert_not_contains "CONDA_DEFAULT_ENV alone: does not prepend" "$RC_CONTENTS" 'export PATH="$HOME/.local/bin:$PATH"'++# 6. zsh, which is the default shell on macOS and lands in a different rc file. Same+# writer, so the same guard has to apply to it.+RC_NAME=.zshrc run_login "" "/opt/anaconda3" CONDA_PREFIX /bin/zsh+assert_contains "zsh rc, active conda: appends" "$RC_CONTENTS" 'export PATH="$PATH:$HOME/.local/bin"'+RC_NAME=.zshrc run_login "" "" CONDA_PREFIX /bin/zsh+assert_contains "zsh rc, no conda: prepends" "$RC_CONTENTS" 'export PATH="$HOME/.local/bin:$PATH"'++# ── fish ───────────────────────────────────────────────────────────────────────────+# fish reads none of the POSIX rc files: its own writer, and fish_add_path prepends.+run_fish() {+ WORK=$(mktemp -d)+ mkdir -p "$WORK/.config/fish/conf.d"+ printf '%s' "$1" > "$WORK/.config/fish/conf.d/unsloth.fish"+ (+ eval "$HARNESS"+ eval "$CONDA_FN"+ eval "$REPOINT_FN"+ eval "$FISH_FN"+ HOME="$WORK"+ unset CONDA_PREFIX CONDA_DEFAULT_ENV+ if [ -n "$2" ]; then eval "${3:-CONDA_PREFIX}=\"\$2\"; export ${3:-CONDA_PREFIX}"; fi+ _persist_fish_path_dir "$WORK/.local/bin" "~/.local/bin"+ )+ FISH_CONTENTS=$(cat "$WORK/.config/fish/conf.d/unsloth.fish")+ FISH_DIR="$WORK/.local/bin"+ rm -rf "$WORK"+}++run_fish "" ""+assert_contains "fish, no conda: prepends" "$FISH_CONTENTS" "fish_add_path '$FISH_DIR'"++# -a ALONE is not an append to PATH: without --path it edits $fish_user_paths, which fish+# prepends to PATH. The assertions are exact so a regression to the bare spelling fails here.+run_fish "" "/opt/anaconda3"+assert_contains "fish, active conda: appends to PATH itself" "$FISH_CONTENTS" \+ "fish_add_path -a -P -m '$FISH_DIR'"++run_fish "" "myenv" CONDA_DEFAULT_ENV+assert_contains "fish, CONDA_DEFAULT_ENV alone: appends to PATH itself" "$FISH_CONTENTS" \+ "fish_add_path -a -P -m '$FISH_DIR'"++# A bare -a would leave the directory inside fish_user_paths, ahead of the active conda+# environment: the exact defect #5871 reports, arriving through fish instead of an rc file.+run_fish "" "/opt/anaconda3"+assert_eq "fish, active conda: no bare -a line" "0" \+ "$(printf '%s\n' "$FISH_CONTENTS" | grep -cxF "fish_add_path -a '$FISH_DIR'")"++# Both stale spellings are rewritten rather than accepted by the presence check. Seeded here+# rather than through run_fish because the line has to name the throwaway HOME. The -a -P+# spelling without -m is in the list too: fish leaves a directory already in+# $fish_user_paths where it is unless --move is given, so that line appended nothing.+for _stale in "fish_add_path '%s/.local/bin'" "fish_add_path -a '%s/.local/bin'" \+ "fish_add_path -a -P '%s/.local/bin'"; do+ WORK=$(mktemp -d)+ mkdir -p "$WORK/.config/fish/conf.d"+ # shellcheck disable=SC2059+ {+ echo "# Added by Unsloth installer"+ # shellcheck disable=SC2059+ printf "$_stale\n" "$WORK"+ } > "$WORK/.config/fish/conf.d/unsloth.fish"+ _stale_line=$(printf "$_stale" "$WORK")+ (+ eval "$HARNESS"+ eval "$CONDA_FN"+ eval "$REPOINT_FN"+ eval "$FISH_FN"+ HOME="$WORK"+ CONDA_PREFIX="/opt/anaconda3"; export CONDA_PREFIX+ unset CONDA_DEFAULT_ENV+ _persist_fish_path_dir "$WORK/.local/bin" "~/.local/bin"+ ) >/dev/null+ _after=$(cat "$WORK/.config/fish/conf.d/unsloth.fish")+ assert_contains "fish: stale [$_stale_line] rewritten to -a -P -m" "$_after" \+ "fish_add_path -a -P -m '$WORK/.local/bin'"+ assert_eq "fish: stale [$_stale_line] is gone" "0" \+ "$(printf '%s\n' "$_after" | grep -cxF "$_stale_line")"+ assert_eq "fish: stale [$_stale_line] leaves one line" "1" \+ "$(printf '%s\n' "$_after" | grep -c 'fish_add_path')"+ rm -rf "$WORK"+done++# Idempotence across both spellings, the same way as the POSIX arm.+WORK=$(mktemp -d)+mkdir -p "$WORK/.config/fish/conf.d"+printf "fish_add_path -a '%s/.local/bin'\n" "$WORK" > "$WORK/.config/fish/conf.d/unsloth.fish"+(+ eval "$HARNESS"+ eval "$CONDA_FN"+ eval "$REPOINT_FN"+ eval "$FISH_FN"+ HOME="$WORK"+ unset CONDA_PREFIX CONDA_DEFAULT_ENV+ _persist_fish_path_dir "$WORK/.local/bin" "~/.local/bin"+) >/dev/null+assert_eq "fish: append already there, no second line" "1" \+ "$(grep -c 'fish_add_path' "$WORK/.config/fish/conf.d/unsloth.fish")"+rm -rf "$WORK"++# ── studio/setup.sh ────────────────────────────────────────────────────────────────+# The third copy of the same write. setup.sh runs after install.sh, in its own process,+# and persists the uv directory into the same rc files, so a guard in install.sh alone+# leaves the reported breakage reachable by the very next step of the same install.+SETUP_SH="$REPO_ROOT/studio/setup.sh"+extract_setup_function() {+ awk -v name="$1" '+ $0 == name "() {" { grab = 1 }+ grab { print }+ grab && $0 == "}" { exit }+ ' "$SETUP_SH"+}+SETUP_FN=$(extract_setup_function _setup_persist_uv_path)+SETUP_HAS_DIR_FN=$(extract_setup_function _setup_path_has_dir)+SETUP_CONDA_FN=$(extract_setup_function _unsloth_conda_env_active)+# setup.sh carries its own copy of the migration helper, so it is extracted from setup.sh+# rather than reused from install.sh: the two copies have to be able to drift apart and+# still be checked.+SETUP_REPOINT_FN=$(extract_setup_function _unsloth_repoint_rc_line)+if [ -z "$SETUP_FN" ] || [ -z "$SETUP_HAS_DIR_FN" ] || [ -z "$SETUP_CONDA_FN" ] \+ || [ -z "$SETUP_REPOINT_FN" ]; then+ echo " FAIL: could not extract the PATH persistence functions from studio/setup.sh"+ exit 1+fi++# $1 CONDA_PREFIX ("" for none). Reads back ~/.bashrc, which the function writes to+# because it exists; ~/.profile is created either way and is not what is asserted here.+# $SETUP_RC_SEED, when set, is a printf format given the throwaway HOME: that is how a+# stale line written by an earlier run can name a directory the caller does not know yet.+run_setup() {+ WORK=$(mktemp -d)+ if [ -n "${SETUP_RC_SEED:-}" ]; then+ # shellcheck disable=SC2059+ {+ echo "# Added by Unsloth setup"+ # shellcheck disable=SC2059+ printf "$SETUP_RC_SEED\n" "$WORK"+ } > "$WORK/.bashrc"+ else+ : > "$WORK/.bashrc"+ fi+ (+ eval "$HARNESS"+ eval "$SETUP_CONDA_FN"+ eval "$SETUP_REPOINT_FN"+ eval "$SETUP_HAS_DIR_FN"+ eval "$SETUP_FN"+ HOME="$WORK"+ _SETUP_LOGIN_PATH="/usr/bin"+ unset UV_NO_MODIFY_PATH UV_UNMANAGED_INSTALL CONDA_PREFIX CONDA_DEFAULT_ENV+ if [ -n "$1" ]; then eval "${2:-CONDA_PREFIX}=\"\$1\"; export ${2:-CONDA_PREFIX}"; fi+ _setup_persist_uv_path "$WORK/.local/bin"+ )+ SETUP_RC=$(cat "$WORK/.bashrc")+ SETUP_FISH=$(cat "$WORK/.config/fish/conf.d/unsloth.fish" 2>/dev/null)+ SETUP_DIR="$WORK/.local/bin"+ rm -rf "$WORK"+}++run_setup ""+assert_contains "setup.sh, no conda: prepends" "$SETUP_RC" "export PATH=\"$SETUP_DIR:\$PATH\""+assert_contains "setup.sh, no conda: fish prepends" "$SETUP_FISH" "fish_add_path '$SETUP_DIR'"++run_setup "myenv" CONDA_DEFAULT_ENV+assert_contains "setup.sh, CONDA_DEFAULT_ENV alone: appends" "$SETUP_RC" "export PATH=\"\$PATH:$SETUP_DIR\""++run_setup "/opt/anaconda3"+assert_contains "setup.sh, active conda: appends" "$SETUP_RC" "export PATH=\"\$PATH:$SETUP_DIR\""+assert_not_contains "setup.sh, active conda: does not prepend" "$SETUP_RC" "export PATH=\"$SETUP_DIR:\$PATH\""+assert_contains "setup.sh, active conda: fish appends to PATH itself" "$SETUP_FISH" \+ "fish_add_path -a -P -m '$SETUP_DIR'"+assert_eq "setup.sh, active conda: no bare -a line" "0" \+ "$(printf '%s\n' "$SETUP_FISH" | grep -cxF "fish_add_path -a '$SETUP_DIR'")"++# setup.sh's own migration pass. A prepend an earlier run left behind satisfies its+# presence check, so without the repoint the directory stays ahead of the active conda+# environment for ever. Both spellings it can have written are covered: the literal path+# and the $HOME-relative one.+# Set and unset around each call rather than as a command prefix: bash keeps an assignment+# that prefixes a FUNCTION call in the environment afterwards, which would seed every later+# case too.+SETUP_RC_SEED='export PATH="%s/.local/bin:$PATH"'+run_setup "/opt/anaconda3"+assert_contains "setup.sh, stale literal prepend inside conda: rewritten as the append" \+ "$SETUP_RC" "export PATH=\"\$PATH:$SETUP_DIR\""+assert_not_contains "setup.sh, stale literal prepend inside conda: the prepend is gone" \+ "$SETUP_RC" "export PATH=\"$SETUP_DIR:\$PATH\""+assert_eq "setup.sh, stale literal prepend inside conda: still one PATH line" "1" \+ "$(printf '%s\n' "$SETUP_RC" | grep -c 'local/bin')"++SETUP_RC_SEED='export PATH="$HOME/.local/bin:$PATH"'+run_setup "/opt/anaconda3"+assert_contains "setup.sh, stale home-relative prepend inside conda: rewritten as the append" \+ "$SETUP_RC" "export PATH=\"\$PATH:$SETUP_DIR\""+assert_not_contains "setup.sh, stale home-relative prepend inside conda: the prepend is gone" \+ "$SETUP_RC" 'export PATH="$HOME/.local/bin:$PATH"'+# The presence check reads the EXPANDED directory, so it cannot see the $HOME spelling.+# Gating the rewrite on it left the prepend alone and appended a second line under it.+assert_eq "setup.sh, stale home-relative prepend inside conda: still one PATH line" "1" \+ "$(printf '%s\n' "$SETUP_RC" | grep -c 'local/bin')"++# Outside conda the same stale prepend is the line this installer would write, so it is+# left exactly where it is.+SETUP_RC_SEED='export PATH="%s/.local/bin:$PATH"'+run_setup ""+assert_contains "setup.sh, stale prepend outside conda: left alone" "$SETUP_RC" \+ "export PATH=\"$SETUP_DIR:\$PATH\""+unset SETUP_RC_SEED++# ── rc-file permissions ────────────────────────────────────────────────────────────+# The rewrite renames a staged copy onto the user's profile, so whatever mode that copy+# has becomes the profile's mode for good. A plain `cp` does not carry the source's bits+# across: POSIX creates the destination with the source's mode as the mode ARGUMENT, and+# a mode argument is always modified by the file creation mask, so under `umask 077` a+# 0644 .bashrc came back 0600 -- or, in the other direction, a private file left more+# open than the user made it. Both copies of the helper are checked, because they are+# maintained separately and can drift.+check_mode_preserved() {+ _cmp_label="$1"+ _cmp_fn="$2"+ _cmp_mode="$3"+ _cmp_umask="$4"+ WORK=$(mktemp -d)+ {+ echo "# Added by Unsloth installer"+ echo "OLD LINE"+ } > "$WORK/.bashrc"+ chmod "$_cmp_mode" "$WORK/.bashrc"+ (+ eval "$_cmp_fn"+ umask "$_cmp_umask"+ _unsloth_repoint_rc_line "$WORK/.bashrc" "OLD LINE" "NEW LINE"+ )+ assert_eq "$_cmp_label: mode $_cmp_mode survives umask $_cmp_umask" "$_cmp_mode" \+ "$(ls -l "$WORK/.bashrc" | awk '{print $1}' | \+ awk '{ m = 0+ for (i = 2; i <= 10; i++) {+ c = substr($0, i, 1)+ if (c != "-") m += (c == "r" ? 4 : (c == "w" ? 2 : 1)) * \+ (i <= 4 ? 100 : (i <= 7 ? 10 : 1))+ }+ printf "%d", m }')"+ assert_eq "$_cmp_label: the line was rewritten" "1" \+ "$(grep -cxF "NEW LINE" "$WORK/.bashrc")"+ rm -rf "$WORK"+}++check_mode_preserved "install.sh" "$REPOINT_FN" 644 077+check_mode_preserved "install.sh" "$REPOINT_FN" 600 022+check_mode_preserved "studio/setup.sh" "$SETUP_REPOINT_FN" 644 077+check_mode_preserved "studio/setup.sh" "$SETUP_REPOINT_FN" 600 022++summary