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.

Installer: clear damaged uv cache entries before retrying an install (#17398)

Daniel Han0dce385fc7d9
diff --git a/.github/workflows/cross-platform-parity-ci.yml b/.github/workflows/cross-platform-parity-ci.yml
index d3961078349..b3e96d0c9fd 100644
--- a/.github/workflows/cross-platform-parity-ci.yml
+++ b/.github/workflows/cross-platform-parity-ci.yml
@@ -71,6 +71,7 @@ on:
- 'tests/sh/test_install_rollback_lifecycle.sh'
- 'tests/studio/test_install_rollback_lifecycle.ps1'
- 'tests/studio/test_intel_registry_fallback.ps1'
+ - 'tests/studio/test_uv_damaged_cache_repair.ps1'
- 'studio/setup.ps1'
- 'tests/studio/test_setup_xpu_runtime_prereport.ps1'
- 'tests/studio/test_xpu_arm64_torchaudio.ps1'
@@ -177,6 +178,7 @@ on:
- 'tests/sh/test_install_rollback_lifecycle.sh'
- 'tests/studio/test_install_rollback_lifecycle.ps1'
- 'tests/studio/test_intel_registry_fallback.ps1'
+ - 'tests/studio/test_uv_damaged_cache_repair.ps1'
- 'studio/setup.ps1'
- 'tests/studio/test_setup_xpu_runtime_prereport.ps1'
- 'tests/studio/test_xpu_arm64_torchaudio.ps1'
@@ -280,6 +282,14 @@ jobs:
- name: Intel registry fallback tests
shell: pwsh
run: pwsh -NoProfile -File tests/studio/test_intel_registry_fallback.ps1
+ - name: uv damaged cache repair tests
+ shell: pwsh
+ run: |
+ python -m pip install uv
+ pwsh -NoProfile -File tests/studio/test_uv_damaged_cache_repair.ps1
+ - name: uv damaged cache repair tests (Windows PowerShell 5.1)
+ if: runner.os == 'Windows'
+ run: powershell -NoProfile -File tests\studio\test_uv_damaged_cache_repair.ps1
- name: Setup XPU pre-report tests
shell: pwsh
run: pwsh -NoProfile -File tests/studio/test_setup_xpu_runtime_prereport.ps1
diff --git a/.github/workflows/studio-backend-ci.yml b/.github/workflows/studio-backend-ci.yml
index 41e88564ef4..56d484e4de1 100644
--- a/.github/workflows/studio-backend-ci.yml
+++ b/.github/workflows/studio-backend-ci.yml
@@ -573,6 +573,8 @@ jobs:
with:
python-version: '3.12'
+ - run: pip install uv
+
- name: Shell installer tests
# Auto-discovered; tests/studio/test_ci_shell_suite_coverage.py guards discovery and skips.
# Skipped: test_install_rollback_lifecycle.sh (covered by cross-platform-parity-ci.yml).
diff --git a/install.ps1 b/install.ps1
index cd194725aeb..b0e0196d1df 100644
--- a/install.ps1
+++ b/install.ps1
@@ -4495,18 +4495,11 @@ function Install-UnslothStudio {
if ($script:UnslothVerbose) {
# Merge stderr into stdout without flipping $? (5.1 treats stderr records as errors).
# Redact per record, verbose mode included.
- if ($NoMirror -or -not $env:_UNSLOTH_MIRROR_SPARE) {
- & $Command 2>&1 | ForEach-Object {
- Write-UvDownloadMarker "$_"
- Redact-InstallOutput "$_"
- } | Out-Host
- } else {
- & $Command 2>&1 | ForEach-Object {
- [void]$collected.AppendLine("$_")
- Write-UvDownloadMarker "$_"
- Redact-InstallOutput "$_"
- } | Out-Host
- }
+ & $Command 2>&1 | ForEach-Object {
+ [void]$collected.AppendLine("$_")
+ Write-UvDownloadMarker "$_"
+ Redact-InstallOutput "$_"
+ } | Out-Host
} else {
# Streamed, not collected, so a marker reaches the app mid-download.
& $Command 2>&1 | ForEach-Object {
@@ -4520,6 +4513,7 @@ function Install-UnslothStudio {
}
}
$exitCode = [int]$LASTEXITCODE
+ $script:LastInstallOutput = if ($exitCode -eq 0) { "" } else { $collected.ToString() }
if ($exitCode -eq 0) {
Clear-TauriInstallError "$Label recovered"
} else {
@@ -4562,6 +4556,27 @@ function Install-UnslothStudio {
return $code
}
+ # uv reuses a damaged cached wheel on every run, --refresh included (#17375).
+ function Repair-UvDamagedWheels {
+ param([string]$Output, [hashtable]$Cleaned)
+ $names = @(foreach ($m in [regex]::Matches("$Output", '(?m)Failed to install: \S+ \(([A-Za-z0-9][A-Za-z0-9._-]*)(?:==| @ )[^\r\n]*\r?\n\s*(?:cause|Caused by): The wheel is invalid')) {
+ $n = $m.Groups[1].Value.ToLowerInvariant()
+ if (-not $Cleaned.ContainsKey($n) -and $Cleaned.Count -lt 50) { $Cleaned[$n] = $true; $n }
+ })
+ if (-not $names) { return $false }
+ substep "clearing damaged uv cache entries for $($names -join ', ')..." "Yellow"
+ # Another uv process may hold the cache lock.
+ $prevLock = $env:UV_LOCK_TIMEOUT
+ if (-not $prevLock) { $env:UV_LOCK_TIMEOUT = "60" }
+ $prevEap = $ErrorActionPreference
+ $ErrorActionPreference = "Continue"
+ try { & $script:UvExe cache clean @names 2>&1 | Out-Null } finally {
+ $ErrorActionPreference = $prevEap
+ $env:UV_LOCK_TIMEOUT = $prevLock
+ }
+ return ($LASTEXITCODE -eq 0)
+ }
+
function Invoke-InstallCommandRetry {
param(
[Parameter(Mandatory = $true, Position = 0)][ScriptBlock]$Command,
@@ -4578,9 +4593,13 @@ function Install-UnslothStudio {
$delay = $parsedDelay
}
$attempt = 1
+ $cleaned = @{}
while ($true) {
+ $script:LastInstallOutput = ""
$code = Invoke-InstallCommand -Command $Command -Label $Label -NoMirror:($attempt -lt $maxAttempts)
if ($code -eq 0) { return 0 }
+ # Not an attempt: uv names one damaged package per run.
+ if (Repair-UvDamagedWheels -Output $script:LastInstallOutput -Cleaned $cleaned) { continue }
if ($attempt -ge $maxAttempts) { return $code }
substep ("retrying ""$Label"" after transient failure (attempt $($attempt + 1)/$maxAttempts, waiting ${delay}s)...") "Yellow"
Start-Sleep -Seconds $delay
diff --git a/install.sh b/install.sh
index f9a93497a53..23e02a4d9de 100755
--- a/install.sh
+++ b/install.sh
@@ -299,22 +299,18 @@ _run_install_cmd_once() {
if _is_verbose; then
_rcf=$(mktemp)
tauri_stream_log stdout "OUTPUT_CLEAR" "$_label"
- _log=""
- if [ -n "${_UNSLOTH_MIRROR_SPARE:-}" ]; then
- _log=$(mktemp)
- _ric_run "$@" | _ric_tee "$_log" | _uv_download_markers "" "$UNSLOTH_DL_MARKER_MIN_BYTES" | _redact_install_output
- else
- _ric_run "$@" | _uv_download_markers "" "$UNSLOTH_DL_MARKER_MIN_BYTES" | _redact_install_output
- fi
+ _log=$(mktemp)
+ _ric_run "$@" | _ric_tee "$_log" | _uv_download_markers "" "$UNSLOTH_DL_MARKER_MIN_BYTES" | _redact_install_output
_rc=$(cat "$_rcf" 2>/dev/null || echo 1)
rm -f "$_rcf"
_rc=${_rc:-1}
if [ "$_rc" -eq 0 ] 2>/dev/null; then
- [ -z "$_log" ] || rm -f "$_log"
+ rm -f "$_log"
tauri_clear_install_error "$_label recovered"
return 0
fi
- _ric_log=$_log
+ _ric_damaged=$(_uv_damaged_wheels "$_log")
+ if [ -n "${_UNSLOTH_MIRROR_SPARE:-}" ]; then _ric_log=$_log; else rm -f "$_log"; fi
tauri_stream_log stdout "ERROR_OUTPUT" "$_label failed (exit code $_rc)"
step "error" "$_label failed (exit code $_rc)" "$C_ERR" >&2
return "$_rc"
@@ -341,10 +337,39 @@ _run_install_cmd_once() {
step "error" "$_label failed (exit code $_rc)" "$C_ERR" >&2
_redact_install_output "$_log" >&2
tauri_stream_log stderr "ERROR_OUTPUT" "$_label failed (exit code $_rc)"
+ _ric_damaged=$(_uv_damaged_wheels "$_log")
if [ -n "${_UNSLOTH_MIRROR_SPARE:-}" ]; then _ric_log=$_log; else rm -f "$_log"; fi
return $_rc
}
+# uv reuses a damaged cached wheel on every run, --refresh included (#17375).
+_uv_damaged_wheels() {
+ [ -f "$1" ] || return 0
+ awk '
+ p != "" && /^[ \t]*(cause|Caused by): The wheel is invalid/ { print tolower(p) }
+ { p = "" }
+ /Failed to install: [^ ]+ \(/ {
+ p = $0; sub(/.*Failed to install: [^ ]+ \(/, "", p); sub(/(==| @ ).*/, "", p)
+ if (p !~ /^[A-Za-z0-9][A-Za-z0-9._-]*$/) p = ""
+ }' "$1"
+}
+
+_repair_uv_damaged_wheels() {
+ _rudw_new=""
+ for _rudw_n in ${_ric_damaged:-}; do
+ case "$_ricr_cleaned" in *" $_rudw_n "*) continue ;; esac
+ [ "$_ricr_cleaned_n" -lt 50 ] || break
+ _ricr_cleaned="$_ricr_cleaned$_rudw_n "
+ _ricr_cleaned_n=$((_ricr_cleaned_n + 1))
+ _rudw_new="$_rudw_new $_rudw_n"
+ done
+ [ -n "$_rudw_new" ] || return 1
+ substep "clearing damaged uv cache entries for$_rudw_new..." "$C_WARN"
+ # Another uv process may hold the cache lock.
+ # shellcheck disable=SC2086
+ UV_LOCK_TIMEOUT=${UV_LOCK_TIMEOUT:-60} uv cache clean $_rudw_new >/dev/null 2>&1
+}
+
: "${UNSLOTH_INSTALL_RETRIES:=3}"
: "${UNSLOTH_INSTALL_RETRY_DELAY:=3}"
run_install_cmd_retry() {
@@ -359,10 +384,15 @@ run_install_cmd_retry() {
*) if [ "${#UNSLOTH_INSTALL_RETRY_DELAY}" -le 4 ] && [ "$UNSLOTH_INSTALL_RETRY_DELAY" -ge 0 ] 2>/dev/null && [ "$UNSLOTH_INSTALL_RETRY_DELAY" -le 3600 ] 2>/dev/null; then _ricr_delay=$UNSLOTH_INSTALL_RETRY_DELAY; else _ricr_delay=3; fi ;;
esac
_ricr_attempt=1
+ _ricr_cleaned=" "
+ _ricr_cleaned_n=0
while :; do
+ _ric_damaged=""
# AND-OR (not `if`) preserves the real failure code for the rollback path.
_run_install_cmd_once "$@" && return 0
_ricr_rc=$?
+ # Not an attempt: uv names one damaged package per run.
+ _repair_uv_damaged_wheels && continue
if [ "$_ricr_attempt" -ge "$_ricr_max" ]; then
_mirror_retry_install "$_ricr_rc" "$@" && return 0
return $?
diff --git a/tests/sh/test_tauri_retry_failure_context.sh b/tests/sh/test_tauri_retry_failure_context.sh
index c264cc1cd2b..c8b6c6d7172 100755
--- a/tests/sh/test_tauri_retry_failure_context.sh
+++ b/tests/sh/test_tauri_retry_failure_context.sh
@@ -15,7 +15,7 @@ _FUNC_FILE=$(mktemp)
{
sed -n '/^run_install_cmd()/,/^}/p' "$INSTALL_SH"
sed -n '/^run_install_cmd_retry()/,/^}/p' "$INSTALL_SH"
- for _f in _ric_tee _ric_run _run_install_cmd_once _mirror_retry_install _mirror_failed_host; do sed -n "/^$_f()/,/^}/p" "$INSTALL_SH"; done
+ for _f in _ric_tee _ric_run _run_install_cmd_once _mirror_retry_install _mirror_failed_host _uv_damaged_wheels _repair_uv_damaged_wheels; do sed -n "/^$_f()/,/^}/p" "$INSTALL_SH"; done
sed -n '/^tauri_log()/,/^}/p' "$INSTALL_SH"
sed -n '/^tauri_stream_log()/,/^}/p' "$INSTALL_SH"
sed -n '/^tauri_clear_install_error()/,/^}/p' "$INSTALL_SH"
diff --git a/tests/sh/test_uv_damaged_cache_repair.sh b/tests/sh/test_uv_damaged_cache_repair.sh
new file mode 100755
index 00000000000..ac2ec40d2f2
--- /dev/null
+++ b/tests/sh/test_uv_damaged_cache_repair.sh
@@ -0,0 +1,124 @@
+#!/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
+# run_install_cmd_retry clears wheels uv calls invalid from its cache (#17375).
+
+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
+INSTALL_SH="$SCRIPT_DIR/../../install.sh"
+
+_FUNC_FILE=$(mktemp)
+for _f in run_install_cmd_retry _ric_tee _ric_run _run_install_cmd_once _mirror_retry_install _mirror_failed_host \
+ _uv_damaged_wheels _repair_uv_damaged_wheels tauri_log tauri_stream_log tauri_clear_install_error _uv_download_markers; do
+ sed -n "/^$_f()/,/^}/p" "$INSTALL_SH" >> "$_FUNC_FILE"
+done
+# shellcheck disable=SC1090
+. "$_FUNC_FILE"
+rm -f "$_FUNC_FILE"
+
+substep() { printf '%s\n' "$1" >> "$_SUBSTEPS"; }
+step() { :; }
+sleep() { :; }
+_is_verbose() { return 1; }
+_redact_install_output() { cat "$@"; }
+
+WORK=$(mktemp -d)
+trap 'rm -rf "${WORK:?}"' EXIT
+_SUBSTEPS="$WORK/substeps"
+fail=0
+check() {
+ if [ "$2" = 0 ]; then echo " PASS $1"; else echo " FAIL $1"; fail=1; fi
+}
+
+echo "=== _uv_damaged_wheels ==="
+# Verbatim from #17375 (Windows), plus the older "Caused by:" spelling.
+cat > "$WORK/issue.log" <<'EOF'
+Using Python 3.13.16 environment at: .unsloth\studio\unsloth_studio
+Resolved 87 packages in 227ms
+Uninstalled 1 package in 8ms
+error: Failed to install: tqdm-4.70.1-py3-none-any.whl (tqdm==4.70.1)
+ cause: The wheel is invalid: Missing .dist-info directory
+error: Failed to install: Nest_Asyncio-1.6.0-py3-none-any.whl (nest-asyncio==1.6.0)
+ Caused by: The wheel is invalid: Metadata field Name not found
+error: Failed to install: zoo-1.0-py3-none-any.whl (unsloth-zoo @ git+https://github.com/unslothai/unsloth-zoo)
+ cause: The wheel is invalid: Missing .dist-info directory
+EOF
+[ "$(_uv_damaged_wheels "$WORK/issue.log" | tr '\n' ' ')" = "tqdm nest-asyncio unsloth-zoo " ]
+check "names every package uv called an invalid wheel" $?
+cat > "$WORK/other.log" <<'EOF'
+error: Failed to install: torch-2.10.0-cp313-cp313-win_amd64.whl (torch==2.10.0)
+ cause: failed to hardlink file: Access is denied. (os error 5)
+error: Request failed after 3 retries: error sending request for url (https://pypi.org/simple/tqdm/)
+The wheel is invalid: Missing .dist-info directory
+EOF
+[ -z "$(_uv_damaged_wheels "$WORK/other.log")" ]
+check "ignores other install failures and an unattributed message" $?
+
+echo "=== retry loop with a stub uv ==="
+mkdir -p "$WORK/stub"
+cat > "$WORK/stub/uv" <<'EOF'
+#!/bin/sh
+if [ "$1" = cache ]; then shift 2; for n in "$@"; do touch "$STUB_STATE/clean-$n"; done; exit 0; fi
+for n in tqdm nest-asyncio; do
+ if [ ! -e "$STUB_STATE/clean-$n" ]; then
+ echo "error: Failed to install: $n-1.0-py3-none-any.whl ($n==1.0)"
+ echo " cause: The wheel is invalid: Missing .dist-info directory"
+ exit 2
+ fi
+done
+EOF
+chmod +x "$WORK/stub/uv"
+export STUB_STATE="$WORK/state"
+mkdir -p "$STUB_STATE"
+: > "$_SUBSTEPS"
+UNSLOTH_INSTALL_RETRIES=1
+UNSLOTH_INSTALL_RETRY_DELAY=0
+PATH="$WORK/stub:$PATH" run_install_cmd_retry "install unsloth" uv pip install x > /dev/null 2>&1
+check "two damaged packages repaired within one attempt" $?
+[ "$(grep -c 'clearing damaged uv cache entries' "$_SUBSTEPS")" = 2 ]
+check "one cache clean per damaged package" $?
+
+cat > "$WORK/stub/uv" <<'EOF'
+#!/bin/sh
+[ "$1" = cache ] && { echo x >> "$STUB_STATE/cleans"; exit 0; }
+echo "error: Failed to install: tqdm-1.0-py3-none-any.whl (tqdm==1.0)"
+echo " cause: The wheel is invalid: Missing .dist-info directory"
+exit 2
+EOF
+PATH="$WORK/stub:$PATH" UNSLOTH_INSTALL_RETRIES=2 run_install_cmd_retry "install unsloth" uv pip install x > /dev/null 2>&1
+rc=$?
+[ "$rc" = 2 ] && [ "$(wc -l < "$STUB_STATE/cleans")" -eq 1 ]
+check "a package still damaged after its clean is not cleaned again (exit $rc)" $?
+
+echo "=== real uv, damaged cache archive ==="
+if ! command -v uv > /dev/null 2>&1; then
+ echo " FAIL uv is not on PATH (CI installs it)"
+ exit 1
+fi
+python3 - "$WORK/wheels" alpha_pkg beta_pkg <<'EOF'
+import os, sys, zipfile
+os.makedirs(sys.argv[1])
+for name in sys.argv[2:]:
+ di = f"{name}-1.0.dist-info"
+ files = {f"{name}/__init__.py": "", f"{di}/METADATA": f"Metadata-Version: 2.1\nName: {name}\nVersion: 1.0\n",
+ f"{di}/WHEEL": "Wheel-Version: 1.0\nGenerator: t\nRoot-Is-Purelib: true\nTag: py3-none-any\n"}
+ files[f"{di}/RECORD"] = "".join(f"{p},,\n" for p in files) + f"{di}/RECORD,,\n"
+ with zipfile.ZipFile(os.path.join(sys.argv[1], f"{name}-1.0-py3-none-any.whl"), "w") as z:
+ for p, c in files.items():
+ z.writestr(p, c)
+EOF
+export UV_CACHE_DIR="$WORK/cache"
+uv venv -q "$WORK/v1"
+uv venv -q "$WORK/v2"
+uv pip install -q --python "$WORK/v1/bin/python" --no-index --find-links "$WORK/wheels" alpha_pkg beta_pkg
+for d in "$UV_CACHE_DIR"/archive-v0/*/*.dist-info; do rm -rf "${d:?}"; done
+uv pip install -q --python "$WORK/v2/bin/python" --no-index --find-links "$WORK/wheels" alpha_pkg beta_pkg > "$WORK/base.log" 2>&1
+rc=$?
+[ "$rc" != 0 ] && grep -q 'The wheel is invalid' "$WORK/base.log"
+check "control: the damaged cache fails a plain install" $?
+: > "$_SUBSTEPS"
+UNSLOTH_INSTALL_RETRIES=1 run_install_cmd_retry "install unsloth" uv pip install --python "$WORK/v2/bin/python" --no-index --find-links "$WORK/wheels" alpha_pkg beta_pkg > /dev/null 2>&1
+check "retry loop repairs the cache and installs" $?
+"$WORK/v2/bin/python" -c "import alpha_pkg, beta_pkg"
+check "both packages import" $?
+
+exit "$fail"
diff --git a/tests/studio/test_mirror_fallback.ps1 b/tests/studio/test_mirror_fallback.ps1
index 11e3436ea80..864472cc756 100644
--- a/tests/studio/test_mirror_fallback.ps1
+++ b/tests/studio/test_mirror_fallback.ps1
@@ -8,7 +8,7 @@ $ast = [System.Management.Automation.Language.Parser]::ParseFile($installPath, [
if ($errors) { throw "install.ps1 has parse errors" }
$setupAst = [System.Management.Automation.Language.Parser]::ParseFile((Resolve-Path ([System.IO.Path]::Combine($PSScriptRoot, "..", "..", "studio", "setup.ps1"))).Path, [ref]$tokens, [ref]$errors)
$load = 'Test-UvEnvFlag', 'Test-MirrorConfigured', 'Start-MirrorProbe', 'Wait-MirrorProbe', 'Invoke-MirrorFallback', 'Get-MirrorName', 'Set-MirrorEnv', 'Pop-MirrorSpare', 'Use-MirrorSpare', 'Get-MirrorFailedHost',
- 'Install-UvFromRelease', 'Redact-InstallOutput', 'Invoke-InstallCommand', 'Invoke-InstallMirrorRetry', 'Invoke-InstallCommandRetry'
+ 'Install-UvFromRelease', 'Redact-InstallOutput', 'Invoke-InstallCommand', 'Invoke-InstallMirrorRetry', 'Repair-UvDamagedWheels', 'Invoke-InstallCommandRetry'
foreach ($pair in @($load | ForEach-Object { , @($ast, $_) }) + (@('Install-UvFromPinnedRelease', 'Get-UvInstallDir', 'Invoke-SetupCommand', 'Invoke-NpmMirrorRetry') | ForEach-Object { , @($setupAst, $_) })) {
$fn = $pair[0].FindAll({ param($n) $n -is [System.Management.Automation.Language.FunctionDefinitionAst] -and $n.Name -eq $pair[1] }, $true)
Invoke-Expression $fn[0].Extent.Text
diff --git a/tests/studio/test_uv_damaged_cache_repair.ps1 b/tests/studio/test_uv_damaged_cache_repair.ps1
new file mode 100644
index 00000000000..874a12ca16e
--- /dev/null
+++ b/tests/studio/test_uv_damaged_cache_repair.ps1
@@ -0,0 +1,116 @@
+#!/usr/bin/env pwsh
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+# Invoke-InstallCommandRetry clears wheels uv calls invalid from its cache (#17375).
+
+$ErrorActionPreference = "Stop"
+Set-StrictMode -Version Latest
+$installPath = (Resolve-Path ([System.IO.Path]::Combine($PSScriptRoot, "..", "..", "install.ps1"))).Path
+$tokens = $null; $errors = $null
+$ast = [System.Management.Automation.Language.Parser]::ParseFile($installPath, [ref]$tokens, [ref]$errors)
+if ($errors) { throw "install.ps1 has parse errors" }
+foreach ($name in 'Redact-InstallOutput', 'Invoke-InstallCommand', 'Invoke-InstallMirrorRetry', 'Repair-UvDamagedWheels', 'Invoke-InstallCommandRetry') {
+ $fn = $ast.FindAll({ param($n) $n -is [System.Management.Automation.Language.FunctionDefinitionAst] -and $n.Name -eq $name }, $true)
+ Invoke-Expression $fn[0].Extent.Text
+}
+function Write-UvDownloadMarker { param($Line) }
+function Clear-TauriInstallError { param($Message) }
+function Write-TauriLog { param($Kind, $Message) }
+function Write-StudioLine { param($Text, $ForegroundColor) }
+$script:Substeps = [System.Collections.Generic.List[string]]::new()
+function substep { param($Message, $Color) $script:Substeps.Add($Message) }
+$script:InstallTorchMirror = $null
+$script:UnslothVerbose = $false
+$script:UvExe = 'uv'
+$env:_UNSLOTH_MIRROR_SPARE = $null
+$env:UNSLOTH_INSTALL_RETRY_DELAY = '0'
+
+$failures = 0
+function Check($name, $cond) {
+ if ($cond) { Write-Host " PASS $name" } else { Write-Host " FAIL $name" -ForegroundColor Red; $script:failures++ }
+}
+
+Write-Host "=== Repair-UvDamagedWheels ==="
+$script:UvExe = { param([Parameter(ValueFromRemainingArguments)]$a) $script:Cleans.Add(($a -join ' ')); $global:LASTEXITCODE = 0 }
+$script:Cleans = [System.Collections.Generic.List[string]]::new()
+# Verbatim from #17375 (CRLF, as Windows collects it), plus the older "Caused by:" spelling.
+$issue = (@(
+ 'Resolved 87 packages in 227ms',
+ 'error: Failed to install: tqdm-4.70.1-py3-none-any.whl (tqdm==4.70.1)',
+ ' cause: The wheel is invalid: Missing .dist-info directory',
+ 'error: Failed to install: Nest_Asyncio-1.6.0-py3-none-any.whl (Nest-Asyncio==1.6.0)',
+ ' Caused by: The wheel is invalid: Metadata field Name not found',
+ 'error: Failed to install: torch-2.10.0-cp313-cp313-win_amd64.whl (torch==2.10.0)',
+ ' cause: failed to hardlink file: Access is denied. (os error 5)'
+ ) -join "`r`n")
+$cleaned = @{}
+Check "repairs what uv called invalid wheels" (Repair-UvDamagedWheels -Output $issue -Cleaned $cleaned)
+Check "cleans exactly tqdm and nest-asyncio" ($script:Cleans.Count -eq 1 -and $script:Cleans[0] -eq 'cache clean tqdm nest-asyncio')
+Check "a package already cleaned is not cleaned again" (-not (Repair-UvDamagedWheels -Output $issue -Cleaned $cleaned) -and $script:Cleans.Count -eq 1)
+Check "a network failure is not a damaged wheel" (-not (Repair-UvDamagedWheels -Output 'error: Request failed after 3 retries: error sending request for url (https://pypi.org/simple/tqdm/)' -Cleaned @{}))
+Check "empty output is not a damaged wheel" (-not (Repair-UvDamagedWheels -Output '' -Cleaned @{}))
+
+Write-Host "=== real uv, damaged cache archive ==="
+$script:UvExe = 'uv'
+if (-not (Get-Command uv -ErrorAction SilentlyContinue)) { Write-Host " FAIL uv is not on PATH (CI installs it)" -ForegroundColor Red; exit 1 }
+$python = if ($env:OS -ne 'Windows_NT' -and (Get-Command python3 -ErrorAction SilentlyContinue)) { 'python3' } else { 'python' }
+$maker = @'
+import os, sys, zipfile
+os.makedirs(sys.argv[1])
+for name in sys.argv[2:]:
+ di = f"{name}-1.0.dist-info"
+ files = {f"{name}/__init__.py": "", f"{di}/METADATA": f"Metadata-Version: 2.1\nName: {name}\nVersion: 1.0\n",
+ f"{di}/WHEEL": "Wheel-Version: 1.0\nGenerator: t\nRoot-Is-Purelib: true\nTag: py3-none-any\n"}
+ files[f"{di}/RECORD"] = "".join(f"{p},,\n" for p in files) + f"{di}/RECORD,,\n"
+ with zipfile.ZipFile(os.path.join(sys.argv[1], f"{name}-1.0-py3-none-any.whl"), "w") as z:
+ for p, c in files.items():
+ z.writestr(p, c)
+'@
+foreach ($verbose in $false, $true) {
+ $script:UnslothVerbose = $verbose
+ Write-Host " -- verbose=$verbose"
+ $work = Join-Path ([System.IO.Path]::GetTempPath()) ("uvdamaged-" + [guid]::NewGuid().ToString("N"))
+ New-Item -ItemType Directory -Path $work | Out-Null
+ $savedCache = $env:UV_CACHE_DIR
+ try {
+ $wheels = Join-Path $work "wheels"
+ $makerPath = Join-Path $work "make_wheels.py"
+ [System.IO.File]::WriteAllText($makerPath, $maker)
+ & $python $makerPath $wheels alpha_pkg beta_pkg
+ $env:UV_CACHE_DIR = Join-Path $work "cache"
+ $ErrorActionPreference = "Continue"
+ & uv venv -q (Join-Path $work "v1") 2>&1 | Out-Null
+ & uv venv -q (Join-Path $work "v2") 2>&1 | Out-Null
+ $ErrorActionPreference = "Stop"
+ $bin = if ($env:OS -eq 'Windows_NT') { 'Scripts\python.exe' } else { 'bin/python' }
+ $py1 = Join-Path (Join-Path $work "v1") $bin
+ $py2 = Join-Path (Join-Path $work "v2") $bin
+ $ErrorActionPreference = "Continue"
+ & uv pip install -q --python $py1 --no-index --find-links $wheels alpha_pkg beta_pkg 2>&1 | Out-Null
+ $ErrorActionPreference = "Stop"
+ foreach ($d in @(Get-ChildItem -Path (Join-Path $env:UV_CACHE_DIR "archive-v0") -Directory | ForEach-Object { Get-ChildItem -LiteralPath $_.FullName -Directory -Filter "*.dist-info" })) {
+ Remove-Item -LiteralPath $d.FullName -Recurse -Force
+ }
+ $ErrorActionPreference = "Continue"
+ $base = (& uv pip install -q --python $py2 --no-index --find-links $wheels alpha_pkg beta_pkg 2>&1 | ForEach-Object { "$_" }) -join "`n"
+ $baseExit = $LASTEXITCODE
+ $ErrorActionPreference = "Stop"
+ Check "control: the damaged cache fails a plain install" ($baseExit -ne 0 -and $base -match 'The wheel is invalid')
+ $env:UNSLOTH_INSTALL_RETRIES = '1'
+ $script:Substeps.Clear()
+ $code = Invoke-InstallCommandRetry -Label "install unsloth" { & $script:UvExe pip install --python $py2 --no-index --find-links $wheels alpha_pkg beta_pkg }
+ Check "retry loop repairs the cache and installs (exit $code)" ($code -eq 0)
+ Check "one cache clean per damaged package" (@($script:Substeps | Where-Object { $_ -like 'clearing damaged uv cache entries*' }).Count -eq 2)
+ $ErrorActionPreference = "Continue"
+ & $py2 -c "import alpha_pkg, beta_pkg" 2>&1 | Out-Null
+ $importExit = $LASTEXITCODE
+ $ErrorActionPreference = "Stop"
+ Check "both packages import" ($importExit -eq 0)
+ } finally {
+ $env:UV_CACHE_DIR = $savedCache
+ Remove-Item -LiteralPath $work -Recurse -Force -ErrorAction SilentlyContinue
+ }
+}
+
+if ($failures) { Write-Host "$failures failure(s)" -ForegroundColor Red; exit 1 }
+Write-Host "all passed"