Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Ask uv for a Python that can import torch, and skip the one that cannot (#7830)

Daniel Han976a1152ad76
diff --git a/install.ps1 b/install.ps1
index 6f5f532015d..402d8e782ba 100644
--- a/install.ps1
+++ b/install.ps1
@@ -220,6 +220,16 @@ function Install-UnslothStudio {
# the live python.org listing can't be fetched. The installer URL scheme is
# stable so an older patch still installs. Bump alongside $PythonVersion.
$PythonFallbackFullVersion = "3.13.13"
+ # Patch releases the stack cannot run; mirrors PYTHON_SKIP in install.sh.
+ # Windows resolves an installed interpreter and hands uv its path rather
+ # than a version, so uv never picks one of these -- but the machine may
+ # already have it, and $PythonFallbackFullVersion above is what replaces it.
+ $PythonSkip = @("3.13.8")
+ # The entry above is skipped for one reason: it cannot `import torch`. A
+ # -NoTorch install never imports it, so refusing the interpreter would send a
+ # locked-down GGUF-only machine into winget/python.org recovery it may not be
+ # able to complete, over a package it will not install.
+ if ($SkipTorch) { $PythonSkip = @() }
# Resolve install destinations. Priority: UNSLOTH_STUDIO_HOME, then
# STUDIO_HOME alias, then USERPROFILE-redirect, then default.
@@ -1288,6 +1298,9 @@ exit 0
# Returns @{ Version = "3.13"; Path = "C:\...\python.exe" } or $null.
# The resolved Path is passed to `uv venv --python` to prevent uv from
# re-resolving the version string back to a conda interpreter.
+ # Candidates on $PythonSkip are dropped as they are enumerated, so no caller
+ # can be handed an interpreter that cannot import torch and the usual
+ # 3.13 -> 3.12 -> 3.11 fallback still applies when the preferred minor is bad.
function Find-CompatiblePython {
# -X64Only: best installed x64 interpreter or $null, never ARM64. Last resort for
# Install-X64Python, where x64 of a lower-priority minor beats ARM64.
@@ -1310,8 +1323,14 @@ exit 0
foreach ($minor in $minors) {
try {
$out = & $pyLauncher.Source "-$minor" --version 2>&1 | Out-String
- if ($out -match "Python (3\.1[1-3])\.\d+") {
- $ver = $Matches[1]
+ if ($out -match "Python ((3\.1[1-3])\.\d+)") {
+ # Both captures first: Test-IsCondaPython below runs -match
+ # and overwrites $Matches. Screening the patch here costs no
+ # extra subprocess (the text is already in hand) and lets the
+ # loop carry on to the next launcher and the next minor.
+ $full = $Matches[1]
+ $ver = $Matches[2]
+ if ($PythonSkip -contains $full) { continue }
# Resolve the actual executable path and verify it is not conda-based
$resolvedExe = (& $pyLauncher.Source "-$minor" -S -c "import sys; print(sys.executable)" 2>$null | Out-String).Trim()
if ($resolvedExe -and (Test-Path -LiteralPath $resolvedExe -PathType Leaf) -and -not (Test-IsCondaPython $resolvedExe)) {
@@ -1336,8 +1355,10 @@ exit 0
if (Test-IsCondaPython $cmd.Source) { continue }
try {
$out = & $cmd.Source --version 2>&1 | Out-String
- if ($out -match "Python (3\.1[1-3])\.\d+") {
- $ver = $Matches[1]
+ if ($out -match "Python ((3\.1[1-3])\.\d+)") {
+ $full = $Matches[1]
+ $ver = $Matches[2]
+ if ($PythonSkip -contains $full) { continue }
# PATH entries may be wrappers (e.g. pyenv-win's python.bat).
# Resolve the real executable so uv bypasses wrapper re-resolution.
$resolvedExe = (& $cmd.Source -S -c "import sys; print(sys.executable)" 2>$null | Out-String).Trim()
@@ -1368,8 +1389,11 @@ exit 0
if (Test-IsCondaPython $exe) { continue }
try {
$out = & $exe --version 2>&1 | Out-String
- if ($out -match "Python (3\.1[1-3])\.\d+") {
- $candidates += @{ Version = $Matches[1]; Path = $exe }
+ if ($out -match "Python ((3\.1[1-3])\.\d+)") {
+ $full = $Matches[1]
+ $ver = $Matches[2]
+ if ($PythonSkip -contains $full) { continue }
+ $candidates += @{ Version = $ver; Path = $exe }
}
} catch {}
}
@@ -1469,6 +1493,25 @@ exit 0
return (Find-CompatiblePython)
}
+ # Backstop for the screen inside Find-CompatiblePython, for an interpreter that
+ # reports one version to --version and another to sys.version_info (a wrapper or
+ # a shim). Returning $null sends the caller down the install path, which pins
+ # $PythonFallbackFullVersion.
+ function Remove-SkippedPython {
+ param($Candidate)
+ if (-not $Candidate) { return $null }
+ try {
+ $raw = (& $Candidate.Path -c "import sys; print('{}.{}.{}'.format(*sys.version_info[:3]))" 2>$null | Select-Object -First 1)
+ } catch {
+ return $Candidate # unreadable: not evidence of a bad version
+ }
+ if ($raw -and ($PythonSkip -contains $raw.Trim())) {
+ substep "Python $($raw.Trim()) cannot import torch -- installing another." "Yellow"
+ return $null
+ }
+ return $Candidate
+ }
+
# ── Windows on ARM: get an x64 CPython ──
# --architecture x64 forces winget off the ARM64 build; python.org takes the same override.
function Install-X64Python {
@@ -1494,7 +1537,7 @@ exit 0
# ── Install Python if no compatible version (3.11-3.13) found ──
# Find-CompatiblePython returns @{ Version = "3.13"; Path = "C:\...\python.exe" } or $null.
Write-TauriLog "STEP" "Installing Python"
- $DetectedPython = Find-CompatiblePython
+ $DetectedPython = Remove-SkippedPython (Find-CompatiblePython)
if ($DetectedPython) {
step "python" "Python $($DetectedPython.Version) already installed"
@@ -1522,7 +1565,7 @@ exit 0
Refresh-SessionPath
# Re-detect after install (PATH may have changed)
- $DetectedPython = Find-CompatiblePython
+ $DetectedPython = Remove-SkippedPython (Find-CompatiblePython)
if (-not $DetectedPython) {
# Python still not functional after winget -- force reinstall.
@@ -1537,7 +1580,7 @@ exit 0
} catch { $wingetExit = 1 }
$ErrorActionPreference = $prevEAP
Refresh-SessionPath
- $DetectedPython = Find-CompatiblePython
+ $DetectedPython = Remove-SkippedPython (Find-CompatiblePython)
}
}
diff --git a/install.sh b/install.sh
index 348757a59d6..95034ebd898 100755
--- a/install.sh
+++ b/install.sh
@@ -622,6 +622,23 @@ _start_studio_venv_replacement() {
substep "previous environment preserved for rollback"
}
+# Clear $VENV_DIR for a recreate without ever destroying the only copy. The
+# legacy-layout migration below moves $STUDIO_HOME/.venv straight into $VENV_DIR
+# without going through _start_studio_venv_replacement, so a plain `rm -rf` there
+# is unrecoverable: if the `uv venv` that follows cannot resolve an interpreter
+# (offline, or a uv whose managed-Python manifest predates the patch being asked
+# for) the user is left with no environment at all. Move it aside instead and let
+# the exit/signal traps put it back. When a replacement is already in flight the
+# rollback copy holds the user's real environment and $VENV_DIR is this run's own
+# work, so plain removal stays correct.
+_discard_venv_for_recreate() { # venv dir
+ if [ "$_VENV_ROLLBACK_ACTIVE" != true ] && [ -d "$1" ] \
+ && _start_studio_venv_replacement "$1"; then
+ return 0
+ fi
+ rm -rf "$1"
+}
+
_restore_studio_venv_replacement() {
[ "$_VENV_ROLLBACK_ACTIVE" = true ] || return 0
[ -n "$_VENV_ROLLBACK_DIR" ] && [ -d "$_VENV_ROLLBACK_DIR" ] || {
@@ -2208,7 +2225,15 @@ esac
# ── Install uv ──
tauri_log "STEP" "Installing uv package manager"
-UV_MIN_VERSION="0.8.16"
+# 0.9.3 is the first uv whose managed-Python manifest carries CPython 3.13.9.
+# Anything older tops out at 3.13.8, which cannot import torch (see PYTHON_SKIP),
+# so a bare "3.13" request on an older uv resolves straight to the broken patch.
+UV_MIN_VERSION="0.9.3"
+# The floor before this raised it. An offline host may keep a uv between the two,
+# since those installs worked without touching the network; below it the
+# installer rejected the uv outright and still has to, or it proceeds on a uv
+# missing flags it is about to be handed (--default-index, --torch-backend).
+UV_OFFLINE_MIN_VERSION="0.8.16"
# When bytecode compilation is enabled, large installs can exceed uv's 60s default on slow machines. Default to 180s, preserving overrides ("0" disables).
: "${UV_COMPILE_BYTECODE_TIMEOUT:=180}"
@@ -2262,25 +2287,118 @@ version_ge() {
return 0
}
-_uv_version_ok() {
+# Patch releases the stack cannot run, space separated.
+# 3.13.8: python/cpython#139783 makes inspect.getsourcelines() drop a function
+# body when a decorator is followed by a comment, which is the shape torch
+# 2.11's nn/modules/rnn.py has, and _overload_method reads its own source at
+# import time -- so `import torch` dies with IndentationError. 3.13.9 was an
+# expedited release carrying only that fix.
+PYTHON_SKIP="3.13.8"
+
+# Every entry above is skipped for one reason: it cannot `import torch`. A
+# --no-torch install never imports it, so refusing the interpreter there would
+# fail a GGUF-only setup on a locked-down host over a package it will not
+# install. SKIP_TORCH is set well before any of this runs.
+_python_skip_applies() {
+ [ "$SKIP_TORCH" != true ]
+}
+
+_python_is_skipped() { # full x.y.z version
+ _python_skip_applies || return 1
+ for _bad in $PYTHON_SKIP; do
+ [ "$1" = "$_bad" ] && return 0
+ done
+ return 1
+}
+
+# uv picks the patch itself for a bare "3.13", so name a range it cannot satisfy
+# with a skipped release rather than checking afterwards. uv accepts a PEP 440
+# specifier as a python request, and the exclusions come straight from
+# PYTHON_SKIP so there is one list to maintain.
+#
+# The exclusion is spelled "!=3.13.8" rather than ">=3.13.9" on purpose: a host
+# that is offline, or whose uv is too old to know 3.13.9, may still have a
+# perfectly good cached 3.13.7, and a floor would refuse it and fail the install
+# outright. Measured against uv 0.10.7 with only 3.13.7 and 3.13.8 installed and
+# --offline: "3.13" gives 3.13.8, ">=3.13.9,<3.14" errors, ">=3.13,<3.14,!=3.13.8"
+# gives 3.13.7.
+_python_request() { # requested version -> what uv is asked for
+ _python_skip_applies || { echo "$1"; return 0; }
+ case "$1" in
+ # An explicit patch is the caller's own choice, and a path or a uv
+ # download name is not a version at all. Pass those through untouched.
+ [0-9]*.[0-9]*.*|*/*|*\\*) echo "$1"; return 0 ;;
+ [0-9]*.[0-9]*) ;;
+ *) echo "$1"; return 0 ;;
+ esac
+ _req_minor=${1#*.}
+ # Only a plain X.Y gets a range. "3.13rc1", or a relative path like
+ # "3.13/bin/python" that slipped past the globs above, would otherwise reach
+ # the arithmetic below, and dash aborts the whole install on "Illegal number".
+ case "$_req_minor" in
+ ''|*[!0-9]*) echo "$1"; return 0 ;;
+ esac
+ _req=">=$1,<${1%%.*}.$((_req_minor + 1))"
+ for _bad in $PYTHON_SKIP; do
+ case "$_bad" in
+ "$1".*) _req="$_req,!=$_bad" ;;
+ esac
+ done
+ echo "$_req"
+}
+
+_uv_version_ok() { # uv command, floor (defaults to UV_MIN_VERSION)
+ _floor=${2:-$UV_MIN_VERSION}
_raw=$("$1" --version 2>/dev/null | awk '{print $2}') || return 1
[ -n "$_raw" ] || return 1
_ver=${_raw%%[-+]*}
case "$_ver" in
''|*[!0-9.]*) return 1 ;;
esac
- version_ge "$_ver" "$UV_MIN_VERSION" || return 1
+ version_ge "$_ver" "$_floor" || return 1
# Prerelease of the exact minimum (e.g. 0.7.14-rc1) is still below stable 0.7.14
- [ "$_ver" = "$UV_MIN_VERSION" ] && [ "$_raw" != "$_ver" ] && return 1
+ [ "$_ver" = "$_floor" ] && [ "$_raw" != "$_ver" ] && return 1
return 0
}
if ! command -v uv >/dev/null 2>&1 || ! _uv_version_ok uv; then
+ # Raising the floor pulled every 0.8.16-0.9.2 host into this block, and those
+ # installs used to succeed without touching the network, so a download
+ # failure must not be fatal for them. An unreadable version counts as
+ # present: that is a minimal image without awk, not an old uv.
+ _uv_present_before=false
+ if command -v uv >/dev/null 2>&1; then
+ # `|| _uv_prev_ver=`: on an image with no awk the pipeline exits 127 and
+ # set -e would kill the install here, which is exactly the host this
+ # block exists to keep working.
+ _uv_prev_ver=$(uv --version 2>/dev/null | awk '{print $2}' 2>/dev/null) \
+ || _uv_prev_ver=""
+ if [ -z "$_uv_prev_ver" ] || _uv_version_ok uv "$UV_OFFLINE_MIN_VERSION"; then
+ _uv_present_before=true
+ fi
+ fi
substep "installing uv package manager..."
- _uv_tmp=$(mktemp)
- download "https://astral.sh/uv/install.sh" "$_uv_tmp"
- run_maybe_quiet sh "$_uv_tmp" </dev/null
- rm -f "$_uv_tmp"
+ _uv_refreshed=true
+ # download() exits the shell outright when neither curl nor wget is present,
+ # which an `if` cannot catch, so probe first: a minimal image with uv copied
+ # in but no downloader must keep the install it had before the floor moved.
+ if command -v curl >/dev/null 2>&1 || command -v wget >/dev/null 2>&1; then
+ _uv_tmp=$(mktemp)
+ if download "https://astral.sh/uv/install.sh" "$_uv_tmp"; then
+ run_maybe_quiet sh "$_uv_tmp" </dev/null || _uv_refreshed=false
+ else
+ _uv_refreshed=false
+ fi
+ rm -f "$_uv_tmp"
+ else
+ _uv_refreshed=false
+ fi
+ if [ "$_uv_refreshed" = false ] && [ "$_uv_present_before" = false ]; then
+ tauri_log "ERROR" "Could not install uv"
+ step "error" "could not download uv, and none is installed" "$C_ERR"
+ substep "Check the network, or install uv manually: https://docs.astral.sh/uv/"
+ exit 1
+ fi
if [ -f "$HOME/.local/bin/env" ]; then
. "$HOME/.local/bin/env"
fi
@@ -2387,7 +2505,8 @@ if [ ! -x "$VENV_DIR/bin/python" ]; then
run_install_cmd "create venv" uv venv "$VENV_DIR" \
--python "cpython-${PYTHON_VERSION}-macos-aarch64-none"
else
- run_install_cmd "create venv" uv venv "$VENV_DIR" --python "$PYTHON_VERSION"
+ run_install_cmd "create venv" uv venv "$VENV_DIR" \
+ --python "$(_python_request "$PYTHON_VERSION")"
fi
fi
@@ -2439,7 +2558,7 @@ if [ -z "$_USER_PYTHON" ] && [ "$OS" = "macos" ] && [ "$_ARCH" = "arm64" ]; then
if [ "$_VENV_ARCH" = "x86_64" ]; then
echo " WARNING: venv was created with an x86_64 (Rosetta) Python on Apple Silicon."
echo " Recreating venv with native arm64 Python ${PYTHON_VERSION}..."
- rm -rf "$VENV_DIR"
+ _discard_venv_for_recreate "$VENV_DIR"
run_install_cmd "recreate venv (arm64)" uv venv "$VENV_DIR" \
--python "cpython-${PYTHON_VERSION}-macos-aarch64-none"
if [ -x "$VENV_DIR/bin/python" ]; then
@@ -2451,10 +2570,10 @@ if [ -z "$_USER_PYTHON" ] && [ "$OS" = "macos" ] && [ "$_ARCH" = "arm64" ]; then
_PY_VER=${_info##* }
fi
- if [ "$_PY_VER" = "3.13.8" ]; then
- echo " WARNING: Python 3.13.8 has a known torch import bug."
+ if _python_is_skipped "$_PY_VER"; then
+ echo " WARNING: Python $_PY_VER cannot import torch."
echo " Recreating venv with Python 3.12..."
- rm -rf "$VENV_DIR"
+ _discard_venv_for_recreate "$VENV_DIR"
PYTHON_VERSION="3.12"
run_install_cmd "recreate venv" uv venv "$VENV_DIR" \
--python "cpython-${PYTHON_VERSION}-macos-aarch64-none"
@@ -2464,6 +2583,24 @@ if [ -z "$_USER_PYTHON" ] && [ "$OS" = "macos" ] && [ "$_ARCH" = "arm64" ]; then
fi
fi
+# The request above only decides what a *new* venv gets. A venv from an earlier
+# run, on any platform, can still hold a skipped interpreter, and reusing it is
+# how the reported installs stayed broken across re-runs. Honour --python.
+if [ -z "$_USER_PYTHON" ] && [ -x "$VENV_DIR/bin/python" ]; then
+ _PY_VER=$("$VENV_DIR/bin/python" -c \
+ 'import sys; print("{}.{}.{}".format(*sys.version_info[:3]))' 2>/dev/null || echo "")
+ if _python_is_skipped "$_PY_VER"; then
+ echo " WARNING: Python $_PY_VER cannot import torch."
+ echo " Recreating venv..."
+ _discard_venv_for_recreate "$VENV_DIR"
+ run_install_cmd "recreate venv" uv venv "$VENV_DIR" \
+ --python "$(_python_request "$PYTHON_VERSION")"
+ if [ -x "$VENV_DIR/bin/python" ]; then
+ : > "$VENV_DIR/.unsloth-studio-owned" 2>/dev/null || true
+ fi
+ fi
+fi
+
if [ -x "$VENV_DIR/bin/python" ]; then
step "venv" "using environment"
substep "${VENV_DIR}"
diff --git a/tests/python/test_windows_python_313_8_screen.py b/tests/python/test_windows_python_313_8_screen.py
new file mode 100644
index 00000000000..7bc51c46401
--- /dev/null
+++ b/tests/python/test_windows_python_313_8_screen.py
@@ -0,0 +1,333 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+"""Windows must not build the venv on a CPython that cannot import torch.
+
+CPython 3.13.8 carries python/cpython#139783: inspect.getsourcelines() drops a
+function body when a decorator is followed by a comment, which is the shape of
+the @_overload_method blocks torch/nn/modules/rnn.py parses at import time, so
+`import torch` raises IndentationError (#7803).
+
+Windows reaches such an interpreter differently from install.sh: uv is handed a
+resolved path rather than a version, so it never picks the patch itself, but
+Find-CompatiblePython matches on the *minor* version and would happily return an
+already-installed 3.13.8. Remove-SkippedPython is what turns that into "not
+found", so the caller installs $PythonFallbackFullVersion instead.
+
+The function is extracted from install.ps1 and executed under pwsh rather than
+reimplemented, so the test cannot drift from the text the installer runs.
+"""
+
+from __future__ import annotations
+
+import os
+import re
+import shutil
+import stat
+import subprocess
+from pathlib import Path
+
+import pytest
+
+
+REPO_ROOT = Path(__file__).resolve().parents[2]
+INSTALL_PS1 = REPO_ROOT / "install.ps1"
+
+pytestmark = pytest.mark.skipif(
+ shutil.which("pwsh") is None, reason = "pwsh is required to execute install.ps1 blocks"
+)
+
+
+def _extract(pattern: str) -> str:
+ source = INSTALL_PS1.read_text(encoding = "utf-8")
+ match = re.search(pattern, source, flags = re.DOTALL)
+ assert match is not None, f"install.ps1 no longer contains {pattern!r}"
+ return match.group(0)
+
+
+def _blocks() -> tuple:
+ """The skip list and the screen, straight out of install.ps1.
+
+ Hoisted out of the f-strings below: a backslash inside an f-string expression
+ is a syntax error before 3.12, and this repo is 3.9+ (ruff targets py311).
+ """
+ return (
+ _extract(
+ r" # Patch releases the stack cannot run.*?"
+ r"if \(\$SkipTorch\) \{ \$PythonSkip = @\(\) \}"
+ ),
+ _extract(r" function Remove-SkippedPython \{.*?\n \}"),
+ )
+
+
+def _fake_python(tmp_path: Path, version: str) -> Path:
+ """An executable that reports ``version`` for the resolver's probe."""
+ if os.name == "nt":
+ exe = tmp_path / "python.cmd"
+ exe.write_text(f"@echo off\r\necho {version}\r\n", encoding = "utf-8")
+ return exe
+ exe = tmp_path / "python"
+ exe.write_text(f'#!/bin/sh\necho "{version}"\n', encoding = "utf-8")
+ exe.chmod(exe.stat().st_mode | stat.S_IEXEC | stat.S_IXGRP | stat.S_IXOTH)
+ return exe
+
+
+def _run(tmp_path: Path, version: str | None) -> str:
+ candidate = (
+ "$null"
+ if version is None
+ else f'@{{ Version = "3.13"; Path = "{_fake_python(tmp_path, version)}" }}'
+ )
+ skip_block, screen_block = _blocks()
+ script = f"""
+$ErrorActionPreference = "Stop"
+$SkipTorch = $false
+# Write-Host, like the real substep: Write-Output would put the message on
+# the pipeline, so the function would return @(message, $null) and every
+# `if ($DetectedPython)` downstream would read it as truthy.
+function substep {{ param($m, $c) Write-Host "SUBSTEP: $m" }}
+{skip_block}
+{screen_block}
+$result = Remove-SkippedPython ({candidate})
+if ($null -eq $result) {{ Write-Output "RESULT: rejected" }}
+else {{ Write-Output "RESULT: kept" }}
+"""
+ completed = subprocess.run(
+ ["pwsh", "-NoProfile", "-NonInteractive", "-Command", script],
+ capture_output = True,
+ text = True,
+ )
+ return completed.stdout + completed.stderr
+
+
+def test_a_skipped_patch_is_rejected(tmp_path):
+ out = _run(tmp_path, "3.13.8")
+ assert "RESULT: rejected" in out, out
+ assert "cannot import torch" in out, "the user should be told why: " + out
+
+
+def test_a_good_patch_of_the_same_minor_is_kept(tmp_path):
+ # The screen is per patch: 3.13 itself is fine and must not be refused.
+ out = _run(tmp_path, "3.13.13")
+ assert "RESULT: kept" in out, out
+
+
+def test_nothing_found_stays_nothing(tmp_path):
+ out = _run(tmp_path, None)
+ assert "RESULT: rejected" in out, out
+
+
+def test_an_unreadable_interpreter_is_not_treated_as_bad(tmp_path):
+ # A probe that cannot run is not evidence of a bad version, and refusing it
+ # would send a working machine down the install path for no reason.
+ missing = tmp_path / "does-not-exist"
+ skip_block, screen_block = _blocks()
+ script = f"""
+$ErrorActionPreference = "Stop"
+$SkipTorch = $false
+# Write-Host, like the real substep: Write-Output would put the message on
+# the pipeline, so the function would return @(message, $null) and every
+# `if ($DetectedPython)` downstream would read it as truthy.
+function substep {{ param($m, $c) Write-Host "SUBSTEP: $m" }}
+{skip_block}
+{screen_block}
+$result = Remove-SkippedPython (@{{ Version = "3.13"; Path = "{missing}" }})
+if ($null -eq $result) {{ Write-Output "RESULT: rejected" }}
+else {{ Write-Output "RESULT: kept" }}
+"""
+ completed = subprocess.run(
+ ["pwsh", "-NoProfile", "-NonInteractive", "-Command", script],
+ capture_output = True,
+ text = True,
+ )
+ assert "RESULT: kept" in completed.stdout + completed.stderr, (
+ completed.stdout + completed.stderr
+ )
+
+
+def test_the_resolver_is_screened_at_every_entry_point():
+ """A bare Find-CompatiblePython in the install flow would defeat the screen."""
+ source = INSTALL_PS1.read_text(encoding = "utf-8")
+ flow = source[source.index("# ── Install Python if no compatible version") :]
+ flow = flow[: flow.index("# ── Install uv ──")]
+ bare = [
+ line.strip()
+ for line in flow.splitlines()
+ if "= Find-CompatiblePython" in line and "Remove-SkippedPython" not in line
+ ]
+ assert not bare, f"unscreened resolver calls in the install flow: {bare}"
+
+
+# ── The screen inside the resolver ──
+# The window above starts at the install step, so it never sees the recovery
+# paths: Install-PythonFromPythonOrg and Install-X64Python both end in a bare
+# `return (Find-CompatiblePython)`. Screening every candidate as it is
+# enumerated is what makes those safe, and is also what lets the resolver carry
+# on to its next minor instead of giving up on the machine.
+
+
+def _every_version_match_screens_the_patch() -> list[str]:
+ body = _extract(r" function Find-CompatiblePython \{.*?\n \}")
+ lines = body.splitlines()
+ unscreened = []
+ for i, line in enumerate(lines):
+ if 'match "Python' not in line:
+ continue
+ window = "\n".join(lines[i : i + 9])
+ if "$PythonSkip -contains" not in window:
+ unscreened.append(line.strip())
+ return unscreened
+
+
+def test_every_enumerated_candidate_is_screened():
+ assert (
+ len(
+ [
+ l
+ for l in _extract(r" function Find-CompatiblePython \{.*?\n \}").splitlines()
+ if 'match "Python' in l
+ ]
+ )
+ == 3
+ ), "the resolver's enumeration sites moved; re-check the screen"
+ assert not _every_version_match_screens_the_patch(), (
+ "Find-CompatiblePython enumerates a candidate without checking $PythonSkip: "
+ f"{_every_version_match_screens_the_patch()}"
+ )
+
+
+# The launcher below is a /bin/sh script. Windows has no shebang and no PATHEXT
+# entry for an extensionless file, so `Get-Command py` does not find it and the
+# resolver reports "none" whatever the versions are -- which would make the
+# negative case pass for the wrong reason. The PowerShell under test is the same
+# text on every platform, and pwsh runs it here, so these three cases run on
+# POSIX and the rest of the file still covers Windows.
+_POSIX_LAUNCHER_ONLY = pytest.mark.skipif(
+ os.name == "nt", reason = "the fake py launcher is a /bin/sh script"
+)
+
+
+def _fake_launcher(root: Path, versions: dict[str, str]) -> Path:
+ """A `py` launcher over fake interpreters, one per minor in ``versions``."""
+ root.mkdir(parents = True, exist_ok = True)
+ branches = []
+ for minor, full in versions.items():
+ exe = root / f"python{minor.replace('.', '')}"
+ # -S -c "import sys; print(sys.base_prefix)" for the conda screen.
+ exe.write_text('#!/bin/sh\necho "/usr"\n', encoding = "utf-8")
+ exe.chmod(0o755)
+ branches.append(f' {minor}) ver="{full}"; exe="{exe}" ;;')
+ launcher = root / "py"
+ launcher.write_text(
+ "#!/bin/sh\n"
+ 'case "$1" in\n'
+ + "\n".join(f" -{b.lstrip()}" for b in branches)
+ + "\n *) exit 1 ;;\nesac\n"
+ "shift\n"
+ 'case "$1" in\n'
+ ' --version) echo "Python $ver" ;;\n'
+ ' -S) echo "$exe" ;;\n'
+ " *) exit 1 ;;\n"
+ "esac\n",
+ encoding = "utf-8",
+ )
+ launcher.chmod(0o755)
+ return launcher
+
+
+def _resolve(tmp_path: Path, versions: dict[str, str]) -> str:
+ """Run the real Find-CompatiblePython over ``versions`` and report the hit."""
+ root = tmp_path / "bin"
+ _fake_launcher(root, versions)
+ skip_block, screen_block = _blocks()
+ # Hoisted for the same reason as _blocks: a backslash in an f-string
+ # expression does not parse before 3.12.
+ conda_block = _extract(r" function Test-IsCondaPython \{.*?\n \}")
+ tag_block = _extract(r" function Get-PythonPlatformTag \{.*?\n \}")
+ resolver_block = _extract(r" function Find-CompatiblePython \{.*?\n \}")
+ script = f"""
+$ErrorActionPreference = "Stop"
+$SkipTorch = $false
+$env:PATH = "{root}"
+$PythonVersion = "3.13"
+function substep {{ param($m, $c) Write-Host "SUBSTEP: $m" }}
+function Get-HostMachineArch {{ return "x86_64" }}
+{skip_block}
+$script:CondaSkipPattern = '(?i)(conda|miniconda|anaconda|miniforge|mambaforge)'
+{conda_block}
+{tag_block}
+{resolver_block}
+$found = Find-CompatiblePython
+if ($null -eq $found) {{ Write-Output "RESULT: none" }}
+else {{ Write-Output "RESULT: $($found.Version)" }}
+"""
+ completed = subprocess.run(
+ ["pwsh", "-NoProfile", "-NonInteractive", "-Command", script],
+ capture_output = True,
+ text = True,
+ )
+ out = completed.stdout + completed.stderr
+ match = re.search(r"RESULT: (\S+)", out)
+ assert match is not None, out
+ return match.group(1)
+
+
+@_POSIX_LAUNCHER_ONLY
+def test_the_resolver_falls_through_to_the_next_minor(tmp_path):
+ # The offline/locked-down case: 3.13.8 and a healthy 3.12 both installed and
+ # nothing installable. Ending the search on the 3.13 would leave the caller
+ # with a Python that cannot import torch; refusing it outright would fail a
+ # machine that has a perfectly good interpreter one entry down the list.
+ assert _resolve(tmp_path, {"3.13": "3.13.8", "3.12": "3.12.11"}) == "3.12"
+
+
+@_POSIX_LAUNCHER_ONLY
+def test_a_good_preferred_minor_still_wins(tmp_path):
+ assert _resolve(tmp_path, {"3.13": "3.13.13", "3.12": "3.12.11"}) == "3.13"
+
+
+@_POSIX_LAUNCHER_ONLY
+def test_nothing_usable_is_still_nothing(tmp_path):
+ # Paired with a positive control over the same tree, because "none" is also
+ # what a harness that cannot run the launcher at all reports: without the
+ # control this case would pass on a machine where it proves nothing.
+ assert _resolve(tmp_path / "good", {"3.13": "3.13.13"}) == "3.13"
+ assert _resolve(tmp_path / "bad", {"3.13": "3.13.8"}) == "none"
+
+
+@_POSIX_LAUNCHER_ONLY
+def test_no_torch_mode_keeps_the_skipped_patch(tmp_path):
+ """The list is about `import torch`; -NoTorch never imports it.
+
+ A locked-down GGUF-only machine whose only Python is 3.13.8 would otherwise
+ be pushed into winget/python.org recovery it may not be able to complete.
+ """
+ root = tmp_path / "bin"
+ _fake_launcher(root, {"3.13": "3.13.8"})
+ skip_block, screen_block = _blocks()
+ conda_block = _extract(r" function Test-IsCondaPython \{.*?\n \}")
+ tag_block = _extract(r" function Get-PythonPlatformTag \{.*?\n \}")
+ resolver_block = _extract(r" function Find-CompatiblePython \{.*?\n \}")
+ script = f"""
+$ErrorActionPreference = "Stop"
+$SkipTorch = $true
+$env:PATH = "{root}"
+$PythonVersion = "3.13"
+function substep {{ param($m, $c) Write-Host "SUBSTEP: $m" }}
+function Get-HostMachineArch {{ return "x86_64" }}
+{skip_block}
+$script:CondaSkipPattern = '(?i)(conda|miniconda|anaconda|miniforge|mambaforge)'
+{conda_block}
+{tag_block}
+{resolver_block}
+$found = Find-CompatiblePython
+if ($null -eq $found) {{ Write-Output "RESULT: none" }}
+else {{ Write-Output "RESULT: $($found.Version)" }}
+"""
+ completed = subprocess.run(
+ ["pwsh", "-NoProfile", "-NonInteractive", "-Command", script],
+ capture_output = True,
+ text = True,
+ )
+ out = completed.stdout + completed.stderr
+ assert "RESULT: 3.13" in out, out
diff --git a/tests/sh/test_install_python_guard.sh b/tests/sh/test_install_python_guard.sh
new file mode 100755
index 00000000000..95eb50ef623
--- /dev/null
+++ b/tests/sh/test_install_python_guard.sh
@@ -0,0 +1,264 @@
+#!/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
+#
+# Behaviour tests for the #7803 fix: the Python request handed to uv, and the
+# guard that recreates a venv left on a skipped interpreter by an earlier run.
+# The real helpers and the real guard block are extracted from install.sh and
+# executed against a stubbed uv, so this cannot drift into testing a copy.
+set -e
+
+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
+INSTALL_SH="$SCRIPT_DIR/../../install.sh"
+
+PASS=0
+FAIL=0
+
+assert_eq() {
+ _label="$1"; _expected="$2"; _actual="$3"
+ if [ "$_actual" = "$_expected" ]; then
+ echo " PASS: $_label"
+ PASS=$((PASS + 1))
+ else
+ echo " FAIL: $_label (expected '$_expected', got '$_actual')"
+ FAIL=$((FAIL + 1))
+ fi
+}
+
+_HELPERS=$(mktemp)
+{
+ # Quiet stand-ins for the reporting helpers the extracted functions call.
+ printf 'substep() { :; }\nrollback_substep() { :; }\n'
+ sed -n '/^PYTHON_SKIP=/p' "$INSTALL_SH"
+ sed -n '/^_python_skip_applies()/,/^}/p' "$INSTALL_SH"
+ sed -n '/^_python_is_skipped()/,/^}/p' "$INSTALL_SH"
+ sed -n '/^_python_request()/,/^}/p' "$INSTALL_SH"
+ sed -n '/^_start_studio_venv_replacement()/,/^}/p' "$INSTALL_SH"
+ sed -n '/^_discard_venv_for_recreate()/,/^}/p' "$INSTALL_SH"
+ sed -n '/^_restore_studio_venv_replacement()/,/^}/p' "$INSTALL_SH"
+} > "$_HELPERS"
+for _needed in _python_skip_applies _python_is_skipped _python_request _start_studio_venv_replacement \
+ _discard_venv_for_recreate _restore_studio_venv_replacement; do
+ grep -q "^$_needed()" "$_HELPERS" || {
+ echo " FAIL: could not extract $_needed from install.sh"
+ exit 1
+ }
+done
+# shellcheck disable=SC1090
+. "$_HELPERS"
+
+echo "=== the request handed to uv ==="
+
+assert_eq "a bare 3.13 asks for its own series minus the bad patch" \
+ ">=3.13,<3.14,!=3.13.8" "$(_python_request 3.13)"
+# Not a floor: an offline host, or a uv whose manifest predates 3.13.9, may still
+# have a good cached 3.13.7, and ">=3.13.9" would refuse it and fail the install.
+assert_eq "the request never becomes a floor above the bad patch" \
+ "" "$(_python_request 3.13 | grep -o '>=3\.13\.9' || true)"
+assert_eq "a minor with nothing skipped still gets its own series" \
+ ">=3.12,<3.13" "$(_python_request 3.12)"
+assert_eq "an explicit patch from --python is the user's choice" \
+ "3.13.8" "$(_python_request 3.13.8)"
+assert_eq "a --python path is not a version and is passed through" \
+ "/usr/bin/python3.13" "$(_python_request /usr/bin/python3.13)"
+# The exclusions are generated from PYTHON_SKIP, so adding a patch there is the
+# only edit a future bad release needs.
+_saved_skip="$PYTHON_SKIP"
+PYTHON_SKIP="3.13.8 3.13.20 3.12.4"
+assert_eq "every skipped patch in the series is excluded" \
+ ">=3.13,<3.14,!=3.13.8,!=3.13.20" "$(_python_request 3.13)"
+assert_eq "a skipped patch from another series is not" \
+ ">=3.12,<3.13,!=3.12.4" "$(_python_request 3.12)"
+PYTHON_SKIP="$_saved_skip"
+
+echo "=== values that are not a plain X.Y ==="
+
+# dash aborts the whole install on "Illegal number", so anything that could
+# reach the arithmetic has to be turned away before it.
+assert_eq "a relative path whose first segment looks like a version" \
+ "3.13/bin/python" "$(_python_request 3.13/bin/python)"
+assert_eq "a Windows-style path" \
+ "C:\\Python313\\python.exe" "$(_python_request 'C:\Python313\python.exe')"
+assert_eq "a prerelease tag is not arithmetic" \
+ "3.13rc1" "$(_python_request 3.13rc1)"
+assert_eq "a uv download name is passed through" \
+ "cpython-3.13-macos-aarch64-none" "$(_python_request cpython-3.13-macos-aarch64-none)"
+
+echo "=== --no-torch does not need a torch-capable interpreter ==="
+
+_saved_skip_torch="${SKIP_TORCH:-false}"
+SKIP_TORCH=true
+assert_eq "the request is left alone when torch is never installed" \
+ "3.13" "$(_python_request 3.13)"
+if _python_is_skipped "3.13.8"; then
+ assert_eq "a skipped patch is usable without torch" "no" "yes"
+else
+ assert_eq "a skipped patch is usable without torch" "no" "no"
+fi
+SKIP_TORCH="$_saved_skip_torch"
+if _python_is_skipped "3.13.8"; then
+ assert_eq "and is skipped again once torch is back" "yes" "yes"
+else
+ assert_eq "and is skipped again once torch is back" "yes" "no"
+fi
+
+echo "=== the uv version probe on an image with no awk ==="
+
+# The comment on that block says an unreadable version counts as "uv present".
+# Without the guard the pipeline exits 127 and set -e kills the install first,
+# which is exactly the host the block exists to keep working.
+_PROBE=$(mktemp)
+sed -n '/^ _uv_prev_ver=\$(uv --version/,/_uv_prev_ver=""$/p' "$INSTALL_SH" > "$_PROBE"
+[ -s "$_PROBE" ] || { echo " FAIL: could not extract the uv version probe"; exit 1; }
+_probe_work=$(mktemp -d)
+mkdir -p "$_probe_work/bin"
+printf '#!/bin/sh\necho "uv 0.9.2"\n' > "$_probe_work/bin/uv"
+chmod +x "$_probe_work/bin/uv"
+# PATH is narrowed inside the child, not around it: narrowing it around the
+# child would hide `sh` itself and the test would pass for the wrong reason.
+_probe_out=$(sh -c "PATH='$_probe_work/bin'; export PATH; set -e; . '$_PROBE'; echo \"SURVIVED:\${_uv_prev_ver:-empty}\"" 2>&1 || true)
+assert_eq "no awk means an unreadable version, not a dead install" \
+ "SURVIVED:empty" "$(printf '%s' "$_probe_out" | tail -1)"
+rm -rf "$_probe_work" "$_PROBE"
+
+echo "=== the skip list ==="
+
+if _python_is_skipped "3.13.8"; then
+ assert_eq "3.13.8 is skipped" "yes" "yes"
+else
+ assert_eq "3.13.8 is skipped" "yes" "no"
+fi
+if _python_is_skipped "3.13.12"; then
+ assert_eq "a good patch is not skipped" "no" "yes"
+else
+ assert_eq "a good patch is not skipped" "no" "no"
+fi
+if _python_is_skipped ""; then
+ assert_eq "an unreadable version is not skipped" "no" "yes"
+else
+ assert_eq "an unreadable version is not skipped" "no" "no"
+fi
+
+echo "=== the venv guard ==="
+
+_GUARD=$(mktemp)
+sed -n '/^# The request above only decides/,/^fi$/p' "$INSTALL_SH" > "$_GUARD"
+[ -s "$_GUARD" ] || { echo " FAIL: could not extract the venv guard"; exit 1; }
+
+# Runs the guard against a fake venv whose python reports $1, with uv stubbed.
+# Echoes the request uv was asked for, or nothing when the guard did not fire.
+run_guard() {
+ _reported="$1"
+ _user_python="${2:-}"
+ _work=$(mktemp -d)
+ mkdir -p "$_work/venv/bin"
+ cat > "$_work/venv/bin/python" <<EOF
+#!/bin/sh
+echo "$_reported"
+EOF
+ chmod +x "$_work/venv/bin/python"
+
+ (
+ set -e
+ STUDIO_HOME="$_work"
+ VENV_DIR="$_work/venv"
+ _VENV_ROLLBACK_DIR=""
+ _VENV_ROLLBACK_TARGET="$VENV_DIR"
+ _VENV_ROLLBACK_ACTIVE=false
+ _USER_PYTHON="$_user_python"
+ PYTHON_VERSION="3.13"
+ # shellcheck disable=SC1090
+ . "$_HELPERS"
+ run_install_cmd() {
+ shift # label
+ shift # uv
+ shift # venv
+ shift # target dir
+ shift # --python
+ echo "REQUEST=$1" >&2
+ mkdir -p "$VENV_DIR/bin"
+ printf '#!/bin/sh\necho 3.13.12\n' > "$VENV_DIR/bin/python"
+ chmod +x "$VENV_DIR/bin/python"
+ }
+ # shellcheck disable=SC1090
+ . "$_GUARD"
+ ) 2>&1 >/dev/null | sed -n 's/^REQUEST=//p'
+ rm -rf "$_work"
+}
+
+assert_eq "a venv left on 3.13.8 is recreated on the screened request" \
+ ">=3.13,<3.14,!=3.13.8" "$(run_guard 3.13.8)"
+assert_eq "a healthy venv is left alone" \
+ "" "$(run_guard 3.13.12)"
+assert_eq "an unreadable interpreter is left alone" \
+ "" "$(run_guard '')"
+assert_eq "--python is honoured even on a skipped version" \
+ "" "$(run_guard 3.13.8 /usr/bin/python3.13)"
+
+echo "=== a failed recreate must not cost the user their environment ==="
+
+# The legacy-layout migration moves $STUDIO_HOME/.venv into $VENV_DIR without
+# arming _start_studio_venv_replacement, so the guard runs with no rollback in
+# place. If it removed the venv outright, a `uv venv` that cannot resolve an
+# interpreter (offline, or a uv older than the requested patch) would leave the
+# machine with nothing. $_rollback_active mirrors whether a replacement is
+# already in flight; $_recreate_rc is what the stubbed uv returns.
+# A separate `sh`, not a subshell: `( ... ) || true` puts the subshell in an ||
+# list, which switches set -e off for everything inside it, so the guard would
+# never abort the way it does in the real installer.
+_DRIVER=$(mktemp)
+cat > "$_DRIVER" <<'DRIVER'
+STUDIO_HOME="$1"
+VENV_DIR="$1/venv"
+_VENV_ROLLBACK_DIR=""
+_VENV_ROLLBACK_TARGET="$VENV_DIR"
+_VENV_ROLLBACK_ACTIVE=false
+_USER_PYTHON=""
+PYTHON_VERSION="3.13"
+# shellcheck disable=SC1090
+. "$2"
+if [ "$3" = true ]; then
+ # Stand in for the main path, which moved the user's real venv aside itself
+ # and then created the fresh one the guard is about to replace.
+ mkdir -p "$1/already-preserved"
+ _VENV_ROLLBACK_DIR="$1/already-preserved"
+ _VENV_ROLLBACK_ACTIVE=true
+fi
+_stub_rc="$4"
+run_install_cmd() { return "$_stub_rc"; }
+set -e
+# What _on_install_exit does for a non-zero status.
+trap '[ "$?" -eq 0 ] || _restore_studio_venv_replacement' EXIT
+# shellcheck disable=SC1090
+. "$5"
+DRIVER
+
+run_guard_failure() {
+ _rollback_active="$1"
+ _recreate_rc="$2"
+ _work=$(mktemp -d)
+ mkdir -p "$_work/venv/bin"
+ printf '#!/bin/sh\necho 3.13.8\n' > "$_work/venv/bin/python"
+ chmod +x "$_work/venv/bin/python"
+ # Only present in the environment the user already had.
+ : > "$_work/venv/USER_DATA"
+
+ sh "$_DRIVER" "$_work" "$_HELPERS" "$_rollback_active" "$_recreate_rc" "$_GUARD" \
+ >/dev/null 2>&1 || true
+
+ if [ -f "$_work/venv/USER_DATA" ]; then echo "preserved"; else echo "lost"; fi
+ rm -rf "$_work"
+}
+
+assert_eq "a migrated venv survives a recreate that fails" \
+ "preserved" "$(run_guard_failure false 1)"
+assert_eq "a rollback copy is not clobbered when one is already in flight" \
+ "lost" "$(run_guard_failure true 1)"
+assert_eq "a recreate that works still replaces the environment" \
+ "lost" "$(run_guard_failure false 0)"
+
+rm -f "$_HELPERS" "$_GUARD" "$_DRIVER"
+
+echo
+echo "Results: $PASS passed, $FAIL failed"
+[ "$FAIL" -eq 0 ]
diff --git a/tests/sh/test_mac_intel_compat.sh b/tests/sh/test_mac_intel_compat.sh
index 8a0ff4b641e..3510176a97e 100644
--- a/tests/sh/test_mac_intel_compat.sh
+++ b/tests/sh/test_mac_intel_compat.sh
@@ -571,8 +571,25 @@ echo "=== Apple Silicon x86_64 (Rosetta) venv rebuild ==="
# Extract the real guard block from install.sh so we exercise the shipped logic
# (comment header down to its column-0 closing fi).
_GUARD_FILE=$(mktemp)
-awk '/Guard against two independent Apple Silicon venv problems/{f=1} f{print} f&&/^fi$/{exit}' \
- "$INSTALL_SH" > "$_GUARD_FILE"
+# The guard calls _python_is_skipped and _discard_venv_for_recreate, so the skip
+# list, its reader, and the replacement helpers have to come along or the version
+# check silently never fires and the recreate loses the venv it was handed.
+{
+ printf 'substep() { :; }\n'
+ sed -n '/^PYTHON_SKIP=/p' "$INSTALL_SH"
+ sed -n '/^_python_skip_applies()/,/^}/p' "$INSTALL_SH"
+ sed -n '/^_python_is_skipped()/,/^}/p' "$INSTALL_SH"
+ sed -n '/^_start_studio_venv_replacement()/,/^}/p' "$INSTALL_SH"
+ sed -n '/^_discard_venv_for_recreate()/,/^}/p' "$INSTALL_SH"
+ awk '/Guard against two independent Apple Silicon venv problems/{f=1} f{print} f&&/^fi$/{exit}' \
+ "$INSTALL_SH"
+} > "$_GUARD_FILE"
+for _needed in _python_skip_applies _python_is_skipped _start_studio_venv_replacement _discard_venv_for_recreate; do
+ grep -q "^$_needed()" "$_GUARD_FILE" || {
+ echo " FAIL: could not extract $_needed from install.sh"
+ FAIL=$((FAIL + 1))
+ }
+done
if [ ! -s "$_GUARD_FILE" ]; then
echo " FAIL: could not extract Apple Silicon venv guard from install.sh"
@@ -585,6 +602,12 @@ else
_RUNNER=$(mktemp)
cat > "$_RUNNER" << 'RUNNER_EOF'
GUARD="$1"; VENV_DIR="$2"
+# _discard_venv_for_recreate moves the venv aside under $STUDIO_HOME rather than
+# removing it, and only when no replacement is already in flight.
+STUDIO_HOME=$(dirname "$VENV_DIR")
+_VENV_ROLLBACK_DIR=""
+_VENV_ROLLBACK_TARGET="$VENV_DIR"
+_VENV_ROLLBACK_ACTIVE=false
make_python() { # dir machine version
mkdir -p "$1/bin"
printf '#!/usr/bin/env bash\necho "%s %s"\n' "$2" "$3" > "$1/bin/python"