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.

Use hybrid uv cache migration for Studio installs (#10204)

Wasim Yousef Said919922c416a5
diff --git a/README.md b/README.md
index 9b34dac0b42..7d6c6801a26 100644
--- a/README.md
+++ b/README.md
@@ -319,6 +319,21 @@ curl -fsSL https://unsloth.ai/install.sh | UNSLOTH_SKIP_AUTOSTART=1 sh
$env:UNSLOTH_SKIP_AUTOSTART=1; irm https://unsloth.ai/install.ps1 | iex
```
+Keep the install-time package cache under the Studio directory instead of reusing an existing uv cache. Downloads are slower the first time, and an explicit `UV_CACHE_DIR` still wins over this:
+```bash
+curl -fsSL https://unsloth.ai/install.sh | UNSLOTH_ISOLATE_UV_CACHE=1 sh
+```
+```powershell
+$env:UNSLOTH_ISOLATE_UV_CACHE=1; irm https://unsloth.ai/install.ps1 | iex
+```
+For a local run the flag is `--isolated-uv-cache`:
+```bash
+./install.sh --local --isolated-uv-cache
+```
+```powershell
+.\install.ps1 --local --isolated-uv-cache
+```
+
Pinning the Python version:
```bash
curl -fsSL https://unsloth.ai/install.sh | UNSLOTH_PYTHON=3.12 sh
diff --git a/install.ps1 b/install.ps1
index d68328456a5..b7bcfd79004 100644
--- a/install.ps1
+++ b/install.ps1
@@ -5,8 +5,9 @@
# AMSI scans this file in full before a line of it runs and nothing reads the header from inside.
#
# The web entry point cannot forward arguments, so it takes options as environment variables set
-# beforehand (UNSLOTH_NO_TORCH, UNSLOTH_SKIP_AUTOSTART, UNSLOTH_PYTHON, UNSLOTH_STUDIO_HOME); a
-# local run takes the equivalent flags (--no-torch, --skip-autostart, --python, --local).
+# beforehand (UNSLOTH_NO_TORCH, UNSLOTH_SKIP_AUTOSTART, UNSLOTH_ISOLATE_UV_CACHE,
+# UNSLOTH_PYTHON, UNSLOTH_STUDIO_HOME); a local run takes the equivalent flags
+# (--no-torch, --skip-autostart, --isolated-uv-cache, --python, --local).
#
# Install dir priority: UNSLOTH_STUDIO_HOME > STUDIO_HOME (alias) > $USERPROFILE\.unsloth\studio
#
@@ -651,6 +652,7 @@ function Install-UnslothStudio {
$TauriMode = $false
$SkipTorch = $false
$SkipAutostart = $false
+ $IsolateUvCache = $false
$ShortcutsOnly = $false
$WithLlamaCppDir = ""
$argList = $args
@@ -659,6 +661,7 @@ function Install-UnslothStudio {
"--local" { $StudioLocalInstall = $true }
"--tauri" { $TauriMode = $true }
"--no-torch" { $SkipTorch = $true }
+ "--isolated-uv-cache" { $IsolateUvCache = $true }
"--verbose" { $script:UnslothVerbose = $true }
"-v" { $script:UnslothVerbose = $true }
"--shortcuts-only" { $ShortcutsOnly = $true }
@@ -684,6 +687,7 @@ function Install-UnslothStudio {
# Env-var equivalent for web installs; an explicit flag still wins.
if ($env:UNSLOTH_NO_TORCH -in @('1', 'true', 'yes', 'on')) { $SkipTorch = $true }
if ($env:UNSLOTH_SKIP_AUTOSTART -in @('1', 'true', 'yes', 'on')) { $SkipAutostart = $true }
+ if ($env:UNSLOTH_ISOLATE_UV_CACHE -in @('1', 'true', 'yes', 'on')) { $IsolateUvCache = $true }
if ($script:UnslothVerbose) {
$env:UNSLOTH_VERBOSE = '1'
@@ -1217,6 +1221,124 @@ public static class UnslothStudioFinalPathV2
}
$VenvDir = Join-Path $StudioHome "unsloth_studio"
+ function Set-StudioUvCacheEnvironment {
+ param(
+ [Parameter(Mandatory = $true)][string]$StudioRoot,
+ [bool]$Isolated = $false,
+ [string]$UvExecutable = ""
+ )
+ $studioCache = Join-Path (Join-Path $StudioRoot "cache") "uv"
+ if (-not [string]::IsNullOrWhiteSpace($env:UV_CACHE_DIR)) {
+ $script:StudioUvCacheMode = "custom"
+ step "uv cache" "preserving custom UV_CACHE_DIR ($env:UV_CACHE_DIR)"
+ return
+ }
+
+ if ($Isolated) {
+ $selectedCache = $studioCache
+ $script:StudioUvCacheMode = "isolated"
+ } else {
+ $sharedCache = $null
+ $sharedCachePopulated = $false
+ $scanBlocked = $false
+ try {
+ # Ask uv so uv.toml / UV_CONFIG_FILE / the default count; remove a
+ # blank inherited value so it cannot override them.
+ Remove-Item -LiteralPath Env:UV_CACHE_DIR -ErrorAction SilentlyContinue
+ if ($UvExecutable) {
+ $resolvedCache = @(& $UvExecutable cache dir 2>$null)
+ $uvCacheExit = $LASTEXITCODE
+ # Last nonblank line, not [0]: a notice would become the path.
+ $resolvedLine = $resolvedCache |
+ Where-Object { -not [string]::IsNullOrWhiteSpace([string]$_) } |
+ Select-Object -Last 1
+ if ($uvCacheExit -eq 0 -and $null -ne $resolvedLine) {
+ $sharedCache = ([string]$resolvedLine).Trim()
+ }
+ }
+ if (-not $sharedCache -and -not [string]::IsNullOrWhiteSpace($env:LOCALAPPDATA)) {
+ $sharedCache = Join-Path (Join-Path $env:LOCALAPPDATA "uv") "cache"
+ }
+ if ($sharedCache -and (Test-Path -LiteralPath $sharedCache -PathType Container)) {
+ # Warm means package BYTES: wheels-* is metadata only (.msgpack/
+ # .http on uv 0.10), so a bare `--dry-run` used to read as warm.
+ $buckets = Get-ChildItem -LiteralPath $sharedCache -Directory -Force -ErrorAction Stop |
+ Where-Object { $_.Name -match '^(archive|builds|built-wheels|wheels|sdists)-' }
+ foreach ($bucket in $buckets) {
+ # SilentlyContinue, not Stop: one denied subdirectory must not
+ # make a populated cache read as empty. `find` also skips and continues.
+ $scanErrors = $null
+ $entry = Get-ChildItem -LiteralPath $bucket.FullName -File -Recurse -Force `
+ -ErrorAction SilentlyContinue -ErrorVariable scanErrors |
+ Where-Object {
+ $_.Name -notin @("CACHEDIR.TAG", ".git", ".gitignore") -and
+ $_.Extension -notin @(".lock", ".msgpack", ".http", ".rev")
+ } |
+ Select-Object -First 1
+ if ($null -ne $entry) {
+ $sharedCachePopulated = $true
+ break
+ }
+ # Unreadable is not empty; remembered so the message says why.
+ if ($scanErrors -and $scanErrors.Count -gt 0) { $scanBlocked = $true }
+ }
+ }
+ } catch {
+ # An uninspectable cache is not an install error; isolation is safe.
+ $sharedCache = $null
+ $sharedCachePopulated = $false
+ $scanBlocked = $true
+ }
+
+ if ($sharedCachePopulated) {
+ $selectedCache = $sharedCache
+ $script:StudioUvCacheMode = "shared"
+ } else {
+ $selectedCache = $studioCache
+ $script:StudioUvCacheMode = "studio"
+ }
+ }
+ Set-Item -LiteralPath Env:UV_CACHE_DIR -Value $selectedCache
+
+ switch ($script:StudioUvCacheMode) {
+ "shared" {
+ step "uv cache" "reusing existing shared cache ($selectedCache) to avoid duplicate Torch/CUDA downloads; use --isolated-uv-cache to isolate"
+ }
+ "isolated" {
+ step "uv cache" "forced Studio cache isolation ($selectedCache); already-cached packages may download again" "Yellow"
+ }
+ "studio" {
+ if ($scanBlocked -and -not [string]::IsNullOrWhiteSpace([string]$sharedCache)) {
+ step "uv cache" "using new Studio-owned cache ($selectedCache); part of $sharedCache could not be read, so cached packages may download again" "Yellow"
+ } elseif ($scanBlocked) {
+ step "uv cache" "using new Studio-owned cache ($selectedCache); the existing uv cache could not be inspected, so cached packages may download again" "Yellow"
+ } else {
+ step "uv cache" "using new Studio-owned cache ($selectedCache)"
+ }
+ }
+ }
+ }
+
+ function Set-StudioUvCacheForLaunch {
+ param([Parameter(Mandatory = $true)][string]$StudioRoot)
+ if ($script:StudioUvCacheMode -eq "shared") {
+ Set-Item -LiteralPath Env:UV_CACHE_DIR -Value (Join-Path (Join-Path $StudioRoot "cache") "uv")
+ }
+ }
+
+ function Restore-StudioUvCacheEnvironment {
+ param(
+ [bool]$WasPresent,
+ [AllowNull()][string]$PreviousValue
+ )
+ # The provider, not the .NET API: that maps empty to deletion on Windows.
+ if ($WasPresent) {
+ Set-Item -LiteralPath Env:UV_CACHE_DIR -Value $PreviousValue
+ } else {
+ Remove-Item -LiteralPath Env:UV_CACHE_DIR -ErrorAction SilentlyContinue
+ }
+ }
+
$Rule = [string]::new([char]0x2500, 52)
$Sloth = [char]::ConvertFromUtf32(0x1F9A5)
@@ -3058,6 +3180,8 @@ exit 0
$studioNeedsRuntimeLock = $true
$studioUsesLegacyLayout = ($StudioRedirectMode -ne 'env') -or $studioUsesTauriManagedRoot
$studioAutoStartProcess = $null
+ $hadPreviousUvCacheDir = [Environment]::GetEnvironmentVariables().ContainsKey("UV_CACHE_DIR")
+ $previousUvCacheDir = [Environment]::GetEnvironmentVariable("UV_CACHE_DIR", "Process")
try {
if ($studioNeedsRuntimeLock) {
try {
@@ -3810,6 +3934,8 @@ exit 0
return (Exit-InstallFailure "uv could not be installed")
}
+ Set-StudioUvCacheEnvironment -StudioRoot $StudioHome -Isolated $IsolateUvCache -UvExecutable $script:UvExe
+
# Bytecode compilation can exceed uv's 60s default on slow machines ("0" disables).
if (-not $env:UV_COMPILE_BYTECODE_TIMEOUT) {
$env:UV_COMPILE_BYTECODE_TIMEOUT = "180"
@@ -6512,6 +6638,8 @@ sys.exit(2 if conflict else (0 if installed else 1))
# Through the interpreter, not the generated console script: the
# autostart must not be the one step an Application Control policy
# can still refuse after a clean install.
+ Set-StudioUvCacheForLaunch -StudioRoot $StudioHome
+
$studioAutoStartProcess = Start-Process -FilePath $VenvPython `
-ArgumentList (Get-ManagedUnslothCliCommandLine -Arguments @("studio", "-p", "8888")) `
-NoNewWindow -PassThru
@@ -6576,6 +6704,7 @@ sys.exit(2 if conflict else (0 if installed else 1))
Write-StudioLine ""
}
} finally {
+ Restore-StudioUvCacheEnvironment -WasPresent $hadPreviousUvCacheDir -PreviousValue $previousUvCacheDir
for ($i = $studioRuntimeMutexes.Count - 1; $i -ge 0; $i--) {
Exit-StudioInstallMutex -Mutex $studioRuntimeMutexes[$i]
}
diff --git a/install.sh b/install.sh
index fa26c7d2d40..3b74d938a1b 100755
--- a/install.sh
+++ b/install.sh
@@ -9,9 +9,9 @@
# and nothing in the script consults it.
#
# A piped install takes options as environment variables after the pipe (UNSLOTH_NO_TORCH,
-# UNSLOTH_SKIP_AUTOSTART, UNSLOTH_PYTHON, UNSLOTH_STUDIO_HOME) because a bare `--no-torch` after
-# the pipe would be read as an option to sh itself; a local run takes the equivalent flags
-# (--no-torch, --python, --local).
+# UNSLOTH_SKIP_AUTOSTART, UNSLOTH_ISOLATE_UV_CACHE, UNSLOTH_PYTHON, UNSLOTH_STUDIO_HOME)
+# because a bare `--no-torch` after the pipe would be read as an option to sh itself; a local
+# run takes the equivalent flags (--no-torch, --isolated-uv-cache, --python, --local).
#
# Install dir priority: UNSLOTH_STUDIO_HOME > STUDIO_HOME (alias) > $HOME/.unsloth/studio
#
@@ -61,6 +61,7 @@ TAURI_MODE=false
_USER_PYTHON=""
_NO_TORCH_FLAG=false
_SKIP_AUTOSTART=false
+_ISOLATE_UV_CACHE=false
_VERBOSE=false
_SHORTCUTS_ONLY=false
_next_is_package=false
@@ -89,6 +90,7 @@ for arg in "$@"; do
--tauri) TAURI_MODE=true ;;
--python) _next_is_python=true ;;
--no-torch) _NO_TORCH_FLAG=true ;;
+ --isolated-uv-cache) _ISOLATE_UV_CACHE=true ;;
--verbose|-v) _VERBOSE=true ;;
--shortcuts-only) _SHORTCUTS_ONLY=true ;;
--with-llama-cpp-dir) _next_is_llama_cpp_dir=true ;;
@@ -98,6 +100,7 @@ done
# Env-var equivalents for piped installs; an explicit flag still wins.
case "${UNSLOTH_NO_TORCH:-}" in 1|true|TRUE|yes|YES|on|ON) _NO_TORCH_FLAG=true ;; esac
case "${UNSLOTH_SKIP_AUTOSTART:-}" in 1|true|TRUE|yes|YES|on|ON) _SKIP_AUTOSTART=true ;; esac
+case "${UNSLOTH_ISOLATE_UV_CACHE:-}" in 1|true|TRUE|yes|YES|on|ON) _ISOLATE_UV_CACHE=true ;; esac
[ -z "$_USER_PYTHON" ] && [ -n "${UNSLOTH_PYTHON:-}" ] && _USER_PYTHON="$UNSLOTH_PYTHON"
if [ "$_VERBOSE" = true ]; then
@@ -615,6 +618,95 @@ _resolve_studio_destinations() {
_LOCAL_BIN="$HOME/.local/bin"
_STUDIO_HOME_REDIRECT=default
}
+
+_configure_uv_cache() {
+ _uv_studio_cache="$STUDIO_HOME/cache/uv"
+ case "${UV_CACHE_DIR-}" in
+ *[![:space:]]*)
+ _UV_CACHE_MODE=custom
+ export UV_CACHE_DIR
+ step "uv cache" "preserving custom UV_CACHE_DIR ($UV_CACHE_DIR)"
+ return 0
+ ;;
+ esac
+
+ if [ "$_ISOLATE_UV_CACHE" = true ]; then
+ UV_CACHE_DIR="$_uv_studio_cache"
+ _UV_CACHE_MODE=isolated
+ export UV_CACHE_DIR
+ step "uv cache" "forced Studio cache isolation ($UV_CACHE_DIR); already-cached packages may download again" "$C_WARN"
+ return 0
+ fi
+
+ # Ask uv so uv.toml / UV_CONFIG_FILE / platform defaults count; -u so a blank
+ # inherited value cannot override them; last line so a notice ahead of the path
+ # does not become the path.
+ _uv_default_cache=$(env -u UV_CACHE_DIR uv cache dir 2>/dev/null \
+ | sed -e 's/[[:space:]]*$//' -e '/^$/d' | tail -n 1) || _uv_default_cache=""
+ if [ -z "$_uv_default_cache" ]; then
+ if [ -n "${XDG_CACHE_HOME:-}" ]; then
+ _uv_default_cache="${XDG_CACHE_HOME}/uv"
+ elif [ -n "${HOME:-}" ]; then
+ _uv_default_cache="${HOME}/.cache/uv"
+ fi
+ fi
+
+ _uv_default_populated=false
+ _uv_scan_blocked=false
+ if [ -n "$_uv_default_cache" ] && [ -d "$_uv_default_cache" ] && [ -r "$_uv_default_cache" ]; then
+ # Warm means package BYTES: wheels-* is metadata only (.msgpack/.http on uv
+ # 0.10), so a bare `--dry-run` used to read as warm. -L to match Get-ChildItem.
+ for _uv_bucket in \
+ "$_uv_default_cache"/archive-* \
+ "$_uv_default_cache"/builds-* \
+ "$_uv_default_cache"/built-wheels-* \
+ "$_uv_default_cache"/wheels-* \
+ "$_uv_default_cache"/sdists-*; do
+ [ -d "$_uv_bucket" ] || continue
+ # Unreadable is not empty; remembered so the message below says why.
+ if [ ! -r "$_uv_bucket" ] || [ ! -x "$_uv_bucket" ]; then
+ _uv_scan_blocked=true
+ continue
+ fi
+ _uv_artifact=$(find -L "$_uv_bucket" -type f \
+ ! -name CACHEDIR.TAG ! -name .git ! -name .gitignore \
+ ! -name '*.lock' ! -name '*.msgpack' ! -name '*.http' ! -name '*.rev' \
+ -print 2>/dev/null | head -n 1) || _uv_artifact=""
+ if [ -n "$_uv_artifact" ]; then
+ _uv_default_populated=true
+ break
+ fi
+ done
+ fi
+
+ if [ "$_uv_default_populated" = true ]; then
+ UV_CACHE_DIR="$_uv_default_cache"
+ _UV_CACHE_MODE=shared
+ else
+ UV_CACHE_DIR="$_uv_studio_cache"
+ _UV_CACHE_MODE=studio
+ fi
+ export UV_CACHE_DIR
+
+ case "$_UV_CACHE_MODE" in
+ shared)
+ step "uv cache" "reusing existing shared cache ($UV_CACHE_DIR) to avoid duplicate Torch/CUDA downloads; use --isolated-uv-cache to isolate"
+ ;;
+ studio)
+ if [ "$_uv_scan_blocked" = true ]; then
+ step "uv cache" "using new Studio-owned cache ($UV_CACHE_DIR); part of $_uv_default_cache could not be read, so cached packages may download again" "$C_WARN"
+ else
+ step "uv cache" "using new Studio-owned cache ($UV_CACHE_DIR)"
+ fi
+ ;;
+ esac
+}
+
+_prepare_studio_uv_cache_for_launch() {
+ [ "${_UV_CACHE_MODE:-}" = shared ] || return 0
+ UV_CACHE_DIR="$STUDIO_HOME/cache/uv"
+ export UV_CACHE_DIR
+}
_resolve_studio_destinations
# The PATH we inherited, before anything below prepends to it. The shim setup at the end asks
# whether a NEW login shell will find _LOCAL_BIN, and by then this process has prepended it
@@ -2126,6 +2218,17 @@ _maybe_reroute_strixhalo_to_2404() {
fi
_rr_q() { printf "'%s'" "$(printf '%s' "$1" | sed "s/'/'\\\\''/g")"; }
_rr_exports="set -o pipefail; export UNSLOTH_WSL_REROUTED=1"
+
+ # An automatic path belongs to the origin distro; only an override is portable.
+ case "${UV_CACHE_DIR-}" in
+ *[![:space:]]*)
+ _rr_exports="$_rr_exports; export UV_CACHE_DIR=$(_rr_q "$UV_CACHE_DIR")"
+ ;;
+ *)
+ _rr_exports="$_rr_exports; unset UV_CACHE_DIR"
+ ;;
+ esac
+ [ "$_ISOLATE_UV_CACHE" = true ] && _rr_exports="$_rr_exports; export UNSLOTH_ISOLATE_UV_CACHE=1"
[ "$_STUDIO_HOME_REDIRECT" = "env" ] && _rr_exports="$_rr_exports; export UNSLOTH_STUDIO_HOME=$(_rr_q "$STUDIO_HOME")"
[ "${UNSLOTH_ROCM_WSL_AUTO:-0}" = "1" ] && _rr_exports="$_rr_exports; export UNSLOTH_ROCM_WSL_AUTO=1"
[ -n "${UNSLOTH_TORCH_INDEX_URL:-}" ] && _rr_exports="$_rr_exports; export UNSLOTH_TORCH_INDEX_URL=$(_rr_q "$UNSLOTH_TORCH_INDEX_URL")"
@@ -2720,6 +2823,8 @@ if ! command -v uv >/dev/null 2>&1 || ! _uv_version_ok uv; then
fi
fi
+_configure_uv_cache
+
# ── Create venv (migrate old layout if possible, otherwise fresh) ──
tauri_log "STEP" "Creating virtual environment"
mkdir -p "$STUDIO_HOME"
@@ -5955,6 +6060,8 @@ if [ "$_SKIP_AUTOSTART" != true ] && [ -t 1 ]; then
case "${_reply:-y}" in
[Yy]*|"")
step "launch" "starting Unsloth Studio..."
+
+ _prepare_studio_uv_cache_for_launch
# Detach stdin from the piped web install's pipe: as a foreground server the
# studio would otherwise drain the rest of this piped script, leaving
# the shell to die parsing the now-truncated tail (`unexpected fi`).
diff --git a/tests/python/test_cross_platform_parity.py b/tests/python/test_cross_platform_parity.py
index 5148ef318cb..871ecbb9612 100644
--- a/tests/python/test_cross_platform_parity.py
+++ b/tests/python/test_cross_platform_parity.py
@@ -1086,3 +1086,112 @@ class TestAmdBnbFloorParity:
assert (
"4-bit QLoRA needs a source build" in text
), f"{name} must tell aarch64 users 4-bit needs a source build"
+
+
+class TestInstallUvCacheRootParity:
+ """Both top-level installers must expose the same automatic cache policy."""
+
+ def test_option_and_environment_names_match(self):
+ sh = INSTALL_SH.read_text(encoding = "utf-8")
+ ps1 = INSTALL_PS1.read_text(encoding = "utf-8")
+ for source in (sh, ps1):
+ assert "--isolated-uv-cache" in source
+ assert "UNSLOTH_ISOLATE_UV_CACHE" in source
+ assert "--isolated-uv-cache" in source[:1200]
+ assert "UNSLOTH_ISOLATE_UV_CACHE" in source[:1200]
+
+ assert "_ISOLATE_UV_CACHE=false" in sh
+ assert "--isolated-uv-cache) _ISOLATE_UV_CACHE=true" in sh
+ assert "$IsolateUvCache = $false" in ps1
+ assert '"--isolated-uv-cache" { $IsolateUvCache = $true }' in ps1
+ assert "$env:UNSLOTH_ISOLATE_UV_CACHE -in @('1', 'true', 'yes', 'on')" in ps1
+
+ def test_selectors_share_precedence_markers_modes_and_messages(self):
+ sh = INSTALL_SH.read_text(encoding = "utf-8")
+ ps1 = INSTALL_PS1.read_text(encoding = "utf-8")
+ for source in (sh, ps1):
+ for marker in ("CACHEDIR.TAG", ".gitignore"):
+ assert marker in source
+ for mode in ("custom", "shared", "studio", "isolated"):
+ assert f'"{mode}"' in source or f"'{mode}'" in source or f"={mode}" in source
+ for message in (
+ "preserving custom UV_CACHE_DIR",
+ "reusing existing shared cache",
+ "avoid duplicate Torch/CUDA downloads",
+ "using new Studio-owned cache",
+ "already-cached packages may download again",
+ "so cached packages may download again",
+ ):
+ assert message in source
+ # Both selectors must agree: a metadata-only cache is cold.
+ for bucket in ("archive", "builds", "built-wheels", "wheels", "sdists"):
+ assert bucket in source, bucket
+ for metadata_suffix in (".msgpack", ".http", ".rev", ".lock"):
+ assert metadata_suffix in source, metadata_suffix
+
+ assert "${XDG_CACHE_HOME}/uv" in sh
+ assert "${HOME}/.cache/uv" in sh
+ assert 'Join-Path (Join-Path $env:LOCALAPPDATA "uv") "cache"' in ps1
+ selector = ps1.split("function Set-StudioUvCacheEnvironment", 1)[1].split(
+ "function Set-StudioUvCacheForLaunch", 1
+ )[0]
+ assert "Get-ChildItem -LiteralPath $sharedCache -Directory -Force" in selector
+ assert "Get-ChildItem -LiteralPath $bucket.FullName -File -Recurse -Force" in selector
+ # Must not fail closed: one denied subdirectory would read as an empty cache.
+ assert "-ErrorAction SilentlyContinue -ErrorVariable scanErrors" in selector
+ assert "-ErrorAction Stop" not in selector.split("foreach ($bucket in $buckets)", 1)[1]
+ # -L on the sh side for the same reason Get-ChildItem -Recurse follows links.
+ assert "find -L " in sh
+
+ def test_shell_order_wsl_handoff_and_autostart_boundary(self):
+ source = INSTALL_SH.read_text(encoding = "utf-8")
+ resolved = source.index("\n_resolve_studio_destinations\n")
+ uv_setup = source.index("\n# ── Install uv ──\n")
+ configured = source.index("\n_configure_uv_cache\n", uv_setup)
+ launch_boundary = source.index("_prepare_studio_uv_cache_for_launch\n", configured)
+ autostart = source.index(
+ '(trap - INT; exec "$VENV_DIR/bin/unsloth" studio', launch_boundary
+ )
+
+ assert "_configure_uv_cache() {" in source
+ assert "_prepare_studio_uv_cache_for_launch() {" in source
+ assert resolved < uv_setup < configured < launch_boundary < autostart
+ reroute = source.split("_maybe_reroute_strixhalo_to_2404() {", 1)[1].split(
+ "_maybe_reroute_strixhalo_to_2404 || true", 1
+ )[0]
+ assert "export UNSLOTH_ISOLATE_UV_CACHE=1" in reroute
+ assert "unset UV_CACHE_DIR" in reroute
+ assert 'case "${UV_CACHE_DIR-}" in' in reroute
+ assert "*[![:space:]]*)" in reroute
+
+ def test_powershell_order_handoff_and_restoration(self):
+ source = INSTALL_PS1.read_text(encoding = "utf-8")
+ resolved = source.index('$VenvDir = Join-Path $StudioHome "unsloth_studio"')
+ captured = source.index("$hadPreviousUvCacheDir =")
+ uv_setup = source.index("if (-not (Test-UvVersionOk))", captured)
+ configured = source.index(
+ "Set-StudioUvCacheEnvironment -StudioRoot $StudioHome -Isolated $IsolateUvCache",
+ uv_setup,
+ )
+ tauri_return = source.index("if ($TauriMode)", configured)
+ handoff = source.index("Set-StudioUvCacheForLaunch -StudioRoot $StudioHome", tauri_return)
+ autostart = source.index("$studioAutoStartProcess = Start-Process", handoff)
+ restored = source.index("Restore-StudioUvCacheEnvironment -WasPresent", autostart)
+
+ assert (
+ resolved
+ < captured
+ < uv_setup
+ < configured
+ < tauri_return
+ < handoff
+ < autostart
+ < restored
+ )
+ selector = source.split("function Set-StudioUvCacheEnvironment", 1)[1].split(
+ "function Set-StudioUvCacheForLaunch", 1
+ )[0]
+ assert "Read-Host" not in selector
+ assert "Set-StudioUvCacheForLaunch" in source
+ assert "Set-Item -LiteralPath Env:UV_CACHE_DIR -Value $PreviousValue" in source
+ assert "Remove-Item -LiteralPath Env:UV_CACHE_DIR" in source
diff --git a/tests/python/test_windows_python_venv_hardening.py b/tests/python/test_windows_python_venv_hardening.py
index 58c54f98bb1..0b95d18e04b 100644
--- a/tests/python/test_windows_python_venv_hardening.py
+++ b/tests/python/test_windows_python_venv_hardening.py
@@ -5,6 +5,7 @@
from __future__ import annotations
+import json
import os
import re
import shlex
@@ -62,6 +63,17 @@ def _run_powershell(shell: str, script: str, env: dict[str, str]) -> str:
return result.stdout.strip()
+def _uv_cache_functions(source: str) -> str:
+ return "".join(
+ _extract(rf" function {name} \{{.*?\n \}}\n", source)
+ for name in (
+ "Set-StudioUvCacheEnvironment",
+ "Set-StudioUvCacheForLaunch",
+ "Restore-StudioUvCacheEnvironment",
+ )
+ )
+
+
@pytest.mark.skipif(not POWERSHELLS, reason = "PowerShell is unavailable")
@pytest.mark.parametrize("shell", POWERSHELLS)
def test_path_python_wrapper_resolves_to_real_executable(tmp_path: Path, shell: str):
@@ -429,3 +441,355 @@ def test_readiness_gate_precedes_installs_and_names_both_interpreters():
assert 'Write-StudioLine " Managed Python: $VenvPython"' in source
assert 'Write-StudioLine " Recorded base Python home: $recordedBaseHome"' in source
assert 'return (Exit-InstallFailure "Managed Python is unavailable' in source
+
+
+def test_uv_cache_lifecycle_wraps_all_install_time_uv_work():
+ source = INSTALL_PS1.read_text(encoding = "utf-8")
+ root = source.index('$VenvDir = Join-Path $StudioHome "unsloth_studio"')
+ capture = source.index("$hadPreviousUvCacheDir =")
+ first_uv_probe = source.index("if (-not (Test-UvVersionOk))", capture)
+ final_uv_gate = source.index(
+ 'return (Exit-InstallFailure "uv could not be installed")', first_uv_probe
+ )
+ configure = source.index(
+ "Set-StudioUvCacheEnvironment -StudioRoot $StudioHome "
+ "-Isolated $IsolateUvCache -UvExecutable $script:UvExe",
+ final_uv_gate,
+ )
+ first_uv_work = source.index("& $script:UvExe venv", configure)
+ handoff = source.index("Set-StudioUvCacheForLaunch -StudioRoot $StudioHome", first_uv_work)
+ autostart = source.index("$studioAutoStartProcess = Start-Process", handoff)
+ restore = source.index("Restore-StudioUvCacheEnvironment -WasPresent", autostart)
+
+ assert root < capture < first_uv_probe < final_uv_gate < configure < first_uv_work
+ assert first_uv_work < handoff < autostart < restore
+ assert '[Environment]::GetEnvironmentVariables().ContainsKey("UV_CACHE_DIR")' in source
+ assert "$previousUvCacheDir = [Environment]::GetEnvironmentVariable(" in source
+ assert "Remove-Item -LiteralPath Env:UV_CACHE_DIR" in source
+
+
+def test_uv_cache_option_and_environment_parsers_cannot_drift():
+ source = INSTALL_PS1.read_text(encoding = "utf-8")
+ parse_start = source.index("# ── Parse flags ──")
+ root = source.index('$VenvDir = Join-Path $StudioHome "unsloth_studio"', parse_start)
+ parser = source[parse_start:root]
+
+ assert "$IsolateUvCache = $false" in parser
+ assert '"--isolated-uv-cache" { $IsolateUvCache = $true }' in parser
+ assert "$env:UNSLOTH_ISOLATE_UV_CACHE -in @('1', 'true', 'yes', 'on')" in parser
+ assert "UNSLOTH_ISOLATE_UV_CACHE" in source[:1000]
+ assert "--isolated-uv-cache" in source[:1000]
+
+
+def _prepare_uv_default(local_app_data: Path, state: str) -> Path:
+ shared = local_app_data / "uv" / "cache"
+ if state == "missing":
+ return shared
+ shared.parent.mkdir(parents = True)
+ if state == "unavailable":
+ shared.write_text("not a directory", encoding = "utf-8")
+ return shared
+ shared.mkdir()
+ if state == "markers":
+ (shared / "CACHEDIR.TAG" / "inside").mkdir(parents = True)
+ (shared / "CACHEDIR.TAG" / "inside" / "payload").write_text("keep", encoding = "utf-8")
+ (shared / ".gitignore").write_text("*\n", encoding = "utf-8")
+ elif state == "scaffolding":
+ (shared / "sdists-v9").mkdir()
+ (shared / "sdists-v9" / ".git").write_text("", encoding = "utf-8")
+ (shared / "sdists-v9" / ".gitignore").write_text("", encoding = "utf-8")
+ (shared / "interpreter-v4" / "key").mkdir(parents = True)
+ (shared / "interpreter-v4" / "key" / "metadata.msgpack").write_bytes(b"metadata")
+ (shared / ".lock").write_text("", encoding = "utf-8")
+ elif state == "populated":
+ (shared / "archive-v0" / "package").mkdir(parents = True)
+ (shared / "archive-v0" / "package" / "payload.py").write_text(
+ "cached = True\n", encoding = "utf-8"
+ )
+ elif state == "metadata-only":
+ # wheels-v* is .msgpack/.http only on uv 0.10: one `--dry-run` leaves a file.
+ (shared / "wheels-v6" / "pypi" / "torch").mkdir(parents = True)
+ (shared / "wheels-v6" / "pypi" / "torch" / "2.11.0-cp313.msgpack").write_bytes(b"meta")
+ (shared / "wheels-v6" / "pypi" / "torch" / "2.11.0.http").write_bytes(b"meta")
+ (shared / "sdists-v9" / "pypi" / "pkg").mkdir(parents = True)
+ (shared / "sdists-v9" / "pypi" / "pkg" / "revision.rev").write_bytes(b"meta")
+ (shared / "sdists-v9" / "pypi" / "pkg" / "download.lock").write_bytes(b"")
+ elif state == "builds":
+ # What modern uv calls the old built-wheels-* bucket.
+ (shared / "builds-v0" / "pkg").mkdir(parents = True)
+ (shared / "builds-v0" / "pkg" / "module.py").write_text("x = 1\n", encoding = "utf-8")
+ elif state == "symlinked-bucket":
+ target = local_app_data / "elsewhere" / "pkg"
+ target.mkdir(parents = True)
+ (target / "payload.so").write_bytes(b"data")
+ (shared / "archive-v0").symlink_to(target.parent, target_is_directory = True)
+ elif state == "denied-bucket":
+ (shared / "archive-v0" / "package").mkdir(parents = True)
+ (shared / "archive-v0" / "package" / "payload.py").write_text("x\n", encoding = "utf-8")
+ (shared / "archive-v0").chmod(0o000)
+ elif state == "denied-leaf":
+ (shared / "archive-v0" / "visible").mkdir(parents = True)
+ (shared / "archive-v0" / "visible" / "payload.py").write_text("x\n", encoding = "utf-8")
+ hidden = shared / "archive-v0" / "aaa hidden"
+ hidden.mkdir()
+ (hidden / "other.py").write_text("y\n", encoding = "utf-8")
+ hidden.chmod(0o000)
+ else:
+ raise AssertionError(f"unknown uv cache fixture: {state}")
+ return shared
+
+
[email protected](not POWERSHELLS, reason = "PowerShell is unavailable")
[email protected]("shell", POWERSHELLS)
+ ("case", "initial_value", "isolated", "default_state", "expected_mode"),
+ [
+ ("missing", None, False, "missing", "studio"),
+ ("marker-only", None, False, "markers", "studio"),
+ ("venv-scaffolding", None, False, "scaffolding", "studio"),
+ ("populated", None, False, "populated", "shared"),
+ ("configured", None, False, "missing", "shared"),
+ ("unavailable", None, False, "unavailable", "studio"),
+ ("blank-populated", " ", False, "populated", "shared"),
+ ("custom", "CUSTOM", False, "populated", "custom"),
+ ("custom-over-isolation", "CUSTOM", True, "populated", "custom"),
+ ("forced-isolation", None, True, "populated", "isolated"),
+ ("metadata-only", None, False, "metadata-only", "studio"),
+ ("builds-bucket", None, False, "builds", "shared"),
+ ("symlinked-bucket", None, False, "symlinked-bucket", "shared"),
+ ("denied-leaf", None, False, "denied-leaf", "shared"),
+ # Uninspectable: falling back is right, doing it silently is not.
+ ("denied-bucket", None, False, "denied-bucket", "studio"),
+ ],
+)
+def test_uv_cache_selector_precedence_and_launch_handoff(
+ tmp_path: Path,
+ shell: str,
+ case: str,
+ initial_value: str | None,
+ isolated: bool,
+ default_state: str,
+ expected_mode: str,
+):
+ if default_state.startswith("denied") and (os.name == "nt" or os.geteuid() == 0):
+ pytest.skip("POSIX mode bits do not deny this caller")
+ source = INSTALL_PS1.read_text(encoding = "utf-8")
+ functions = _uv_cache_functions(source)
+ studio_root = tmp_path / "studio root"
+ local_app_data = tmp_path / "local app data"
+ shared = _prepare_uv_default(local_app_data, default_state)
+ studio = studio_root / "cache" / "uv"
+ custom = tmp_path / "caller cache" / "uv artifacts"
+ configured = tmp_path / "uv.toml cache"
+ effective_cache = configured if case == "configured" else shared
+ if case == "configured":
+ (configured / "wheels-v5" / "package").mkdir(parents = True)
+ (configured / "wheels-v5" / "package" / "torch.whl").write_bytes(b"wheel")
+ if initial_value == "CUSTOM":
+ initial_value = str(custom)
+
+ if os.name == "nt":
+ uv_stub = tmp_path / "uv-cache-dir.cmd"
+ uv_stub.write_text("@echo %TEST_UV_EFFECTIVE_CACHE%\r\n", encoding = "utf-8")
+ else:
+ uv_stub = tmp_path / "uv-cache-dir"
+ uv_stub.write_text(
+ '#!/bin/sh\nprintf "%s\\n" "$TEST_UV_EFFECTIVE_CACHE"\n', encoding = "utf-8"
+ )
+ uv_stub.chmod(0o755)
+
+ script = f"""
+$ErrorActionPreference = "Stop"
+{functions}
+function step {{
+ param([string]$Label, [string]$Text, [string]$Color)
+ $script:UvMessage = $Text
+}}
+Remove-Item -LiteralPath Env:UV_CACHE_DIR -ErrorAction SilentlyContinue
+if ($env:TEST_INITIAL_PRESENT -eq "1") {{
+ Set-Item -LiteralPath Env:UV_CACHE_DIR -Value $env:TEST_INITIAL_VALUE
+}}
+$hadPreviousUvCacheDir = [Environment]::GetEnvironmentVariables().ContainsKey("UV_CACHE_DIR")
+$previousUvCacheDir = [Environment]::GetEnvironmentVariable("UV_CACHE_DIR", "Process")
+$providerPresentBefore = Test-Path -LiteralPath Env:UV_CACHE_DIR
+try {{
+ Set-StudioUvCacheEnvironment -StudioRoot $env:TEST_STUDIO_HOME `
+ -Isolated ($env:TEST_ISOLATED -eq "1") -UvExecutable $env:TEST_UV_EXE
+ $selected = [string][Environment]::GetEnvironmentVariable("UV_CACHE_DIR", "Process")
+ $mode = $script:StudioUvCacheMode
+ $message = $script:UvMessage
+ Set-StudioUvCacheForLaunch -StudioRoot $env:TEST_STUDIO_HOME
+ $launch = [string][Environment]::GetEnvironmentVariable("UV_CACHE_DIR", "Process")
+}} finally {{
+ Restore-StudioUvCacheEnvironment -WasPresent $hadPreviousUvCacheDir -PreviousValue $previousUvCacheDir
+}}
+[pscustomobject]@{{
+ Selected = $selected
+ Mode = $mode
+ Message = $message
+ Launch = $launch
+ PresentBefore = $hadPreviousUvCacheDir
+ ProviderPresentBefore = $providerPresentBefore
+ StoredBefore = [string]$previousUvCacheDir
+ PresentAfter = [Environment]::GetEnvironmentVariables().ContainsKey("UV_CACHE_DIR")
+ ProviderPresentAfter = Test-Path -LiteralPath Env:UV_CACHE_DIR
+ Restored = [string][Environment]::GetEnvironmentVariable("UV_CACHE_DIR", "Process")
+}} | ConvertTo-Json -Compress
+"""
+ env = os.environ.copy()
+ env.pop("UV_CACHE_DIR", None)
+ env["TEST_INITIAL_PRESENT"] = "1" if initial_value is not None else "0"
+ env["TEST_INITIAL_VALUE"] = initial_value or ""
+ env["TEST_STUDIO_HOME"] = str(studio_root)
+ env["TEST_ISOLATED"] = "1" if isolated else "0"
+ env["TEST_UV_EXE"] = str(uv_stub)
+ env["TEST_UV_EFFECTIVE_CACHE"] = str(effective_cache)
+ env["LOCALAPPDATA"] = str(local_app_data)
+ result = json.loads(_run_powershell(shell, script, env).splitlines()[-1])
+
+ expected_selected = {
+ "custom": custom,
+ "shared": effective_cache,
+ "studio": studio,
+ "isolated": studio,
+ }[expected_mode]
+ expected_launch = studio if expected_mode == "shared" else expected_selected
+ expected_message = {
+ "custom": f"preserving custom UV_CACHE_DIR ({custom})",
+ "shared": (
+ f"reusing existing shared cache ({effective_cache}) to avoid duplicate Torch/CUDA downloads; "
+ "use --isolated-uv-cache to isolate"
+ ),
+ "studio": (
+ f"using new Studio-owned cache ({studio}); part of {shared} could not be "
+ "read, so cached packages may download again"
+ if default_state == "denied-bucket"
+ else f"using new Studio-owned cache ({studio})"
+ ),
+ "isolated": (
+ f"forced Studio cache isolation ({studio}); already-cached packages may download again"
+ ),
+ }[expected_mode]
+
+ norm = lambda value: os.path.normcase(os.path.normpath(value))
+ assert norm(result["Selected"]) == norm(str(expected_selected)), case
+ assert result["Mode"] == expected_mode, case
+ assert result["Message"] == expected_message, case
+ assert norm(result["Launch"]) == norm(str(expected_launch)), case
+ assert result["PresentAfter"] is result["PresentBefore"]
+ assert result["ProviderPresentAfter"] is result["ProviderPresentBefore"]
+ assert result["Restored"] == result["StoredBefore"]
+ if default_state == "markers":
+ assert (shared / "CACHEDIR.TAG" / "inside" / "payload").read_text(
+ encoding = "utf-8"
+ ) == "keep"
+ assert (shared / ".gitignore").read_text(encoding = "utf-8") == "*\n"
+
+
[email protected](not POWERSHELLS, reason = "PowerShell is unavailable")
[email protected]("shell", POWERSHELLS)
+ ("initial_present", "initial_value"),
+ [(False, ""), (True, ""), (True, " "), (True, "caller cache")],
+)
[email protected]("fail", [False, True])
+def test_uv_cache_selection_restores_caller_on_success_and_failure(
+ tmp_path: Path, shell: str, initial_present: bool, initial_value: str, fail: bool
+):
+ source = INSTALL_PS1.read_text(encoding = "utf-8")
+ functions = _uv_cache_functions(source)
+ script = f"""
+$ErrorActionPreference = "Stop"
+{functions}
+function step {{ param([string]$Label, [string]$Text, [string]$Color) }}
+Remove-Item -LiteralPath Env:UV_CACHE_DIR -ErrorAction SilentlyContinue
+if ($env:TEST_INITIAL_PRESENT -eq "1") {{
+ Set-Item -LiteralPath Env:UV_CACHE_DIR -Value $env:TEST_INITIAL_VALUE
+}}
+$hadPreviousUvCacheDir = [Environment]::GetEnvironmentVariables().ContainsKey("UV_CACHE_DIR")
+$previousUvCacheDir = [Environment]::GetEnvironmentVariable("UV_CACHE_DIR", "Process")
+$providerPresentBefore = Test-Path -LiteralPath Env:UV_CACHE_DIR
+try {{
+ Set-StudioUvCacheEnvironment -StudioRoot $env:TEST_STUDIO_HOME -Isolated $false
+ $active = [string][Environment]::GetEnvironmentVariable("UV_CACHE_DIR", "Process")
+ if ($env:TEST_FAIL -eq "1") {{ throw "intentional failure" }}
+}} catch {{
+}} finally {{
+ Restore-StudioUvCacheEnvironment -WasPresent $hadPreviousUvCacheDir -PreviousValue $previousUvCacheDir
+}}
+[pscustomobject]@{{
+ Active = $active
+ PresentBefore = $hadPreviousUvCacheDir
+ ProviderPresentBefore = $providerPresentBefore
+ StoredBefore = [string]$previousUvCacheDir
+ PresentAfter = [Environment]::GetEnvironmentVariables().ContainsKey("UV_CACHE_DIR")
+ ProviderPresentAfter = Test-Path -LiteralPath Env:UV_CACHE_DIR
+ Restored = [string][Environment]::GetEnvironmentVariable("UV_CACHE_DIR", "Process")
+}} | ConvertTo-Json -Compress
+"""
+ env = os.environ.copy()
+ env.pop("UV_CACHE_DIR", None)
+ env["TEST_INITIAL_PRESENT"] = "1" if initial_present else "0"
+ env["TEST_INITIAL_VALUE"] = initial_value
+ env["TEST_STUDIO_HOME"] = str(tmp_path / "studio")
+ env["TEST_FAIL"] = "1" if fail else "0"
+ env["LOCALAPPDATA"] = str(tmp_path / "local app data")
+ result = json.loads(_run_powershell(shell, script, env).splitlines()[-1])
+
+ expected = initial_value if initial_value.strip() else str(tmp_path / "studio" / "cache" / "uv")
+ assert os.path.normcase(os.path.normpath(result["Active"])) == os.path.normcase(
+ os.path.normpath(expected)
+ )
+ # Windows normalizes a requested present-empty process variable to absent. Compare
+ # against the platform-representable state captured before installer code ran.
+ assert result["PresentAfter"] is result["PresentBefore"]
+ assert result["ProviderPresentAfter"] is result["ProviderPresentBefore"]
+ assert result["Restored"] == result["StoredBefore"]
+
+
[email protected](not POWERSHELLS, reason = "PowerShell is unavailable")
[email protected]("shell", POWERSHELLS)
+def test_two_uv_cache_lifecycles_in_one_session_use_their_own_roots(tmp_path: Path, shell: str):
+ source = INSTALL_PS1.read_text(encoding = "utf-8")
+ functions = _uv_cache_functions(source)
+ script = f"""
+$ErrorActionPreference = "Stop"
+{functions}
+function step {{ param([string]$Label, [string]$Text, [string]$Color) }}
+Remove-Item -LiteralPath Env:UV_CACHE_DIR -ErrorAction SilentlyContinue
+$active = @()
+$modes = @()
+foreach ($root in @($env:TEST_STUDIO_HOME_ONE, $env:TEST_STUDIO_HOME_TWO)) {{
+ $hadPreviousUvCacheDir = [Environment]::GetEnvironmentVariables().ContainsKey("UV_CACHE_DIR")
+ $previousUvCacheDir = [Environment]::GetEnvironmentVariable("UV_CACHE_DIR", "Process")
+ try {{
+ Set-StudioUvCacheEnvironment -StudioRoot $root -Isolated $false
+ $active += [string][Environment]::GetEnvironmentVariable("UV_CACHE_DIR", "Process")
+ $modes += $script:StudioUvCacheMode
+ }} finally {{
+ Restore-StudioUvCacheEnvironment -WasPresent $hadPreviousUvCacheDir -PreviousValue $previousUvCacheDir
+ }}
+}}
+[pscustomobject]@{{
+ Active = @($active)
+ Modes = @($modes)
+ PresentAfter = [Environment]::GetEnvironmentVariables().ContainsKey("UV_CACHE_DIR")
+ ProviderPresentAfter = Test-Path -LiteralPath Env:UV_CACHE_DIR
+}} | ConvertTo-Json -Compress
+"""
+ first = tmp_path / "first studio"
+ second = tmp_path / "second studio"
+ env = os.environ.copy()
+ env.pop("UV_CACHE_DIR", None)
+ env["LOCALAPPDATA"] = str(tmp_path / "empty local app data")
+ env["TEST_STUDIO_HOME_ONE"] = str(first)
+ env["TEST_STUDIO_HOME_TWO"] = str(second)
+ result = json.loads(_run_powershell(shell, script, env).splitlines()[-1])
+
+ assert [os.path.normcase(os.path.normpath(value)) for value in result["Active"]] == [
+ os.path.normcase(os.path.normpath(str(first / "cache" / "uv"))),
+ os.path.normcase(os.path.normpath(str(second / "cache" / "uv"))),
+ ]
+ assert result["Modes"] == ["studio", "studio"]
+ assert result["PresentAfter"] is False
+ assert result["ProviderPresentAfter"] is False
diff --git a/tests/sh/test_install_uv_cache_root.sh b/tests/sh/test_install_uv_cache_root.sh
new file mode 100644
index 00000000000..d986580071a
--- /dev/null
+++ b/tests/sh/test_install_uv_cache_root.sh
@@ -0,0 +1,283 @@
+#!/bin/sh
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+#
+# Exercise the real install-time uv cache selector under POSIX sh and bash.
+set -e
+
+SCRIPT_DIR=$(CDPATH= cd -- "$(dirname "$0")" && pwd)
+INSTALL_SH="$SCRIPT_DIR/../../install.sh"
+PASS=0
+FAIL=0
+
+ok() { echo " PASS: $1"; PASS=$((PASS + 1)); }
+bad() { echo " FAIL: $1"; FAIL=$((FAIL + 1)); }
+
+HELPERS=$(awk '
+ /^_configure_uv_cache\(\) \{/ { grab = 1 }
+ /^_prepare_studio_uv_cache_for_launch\(\) \{/ { grab = 1 }
+ grab { print }
+ grab && /^}/ { grab = 0 }
+' "$INSTALL_SH")
+for _helper in _configure_uv_cache _prepare_studio_uv_cache_for_launch; do
+ if ! printf '%s\n' "$HELPERS" | grep -q "^${_helper}() {"; then
+ echo " FAIL: could not extract $_helper from install.sh"
+ exit 1
+ fi
+done
+
+WORK=$(mktemp -d)
+PROBE="$WORK/probe.sh"
+UV_STUB_DIR="$WORK/bin"
+export UV_STUB_DIR
+trap 'rm -rf "$WORK"' EXIT INT TERM
+mkdir -p "$UV_STUB_DIR"
+cat > "$UV_STUB_DIR/uv" <<'UV'
+#!/bin/sh
+[ "$1" = cache ] && [ "$2" = dir ] || exit 2
+printf '%s\n' "$TEST_UV_EFFECTIVE_CACHE"
+UV
+chmod +x "$UV_STUB_DIR/uv"
+printf '%s\n' "$HELPERS" > "$PROBE"
+cat >> "$PROBE" <<'PROBE'
+step() { printf 'message=%s\n' "$2"; }
+C_WARN=""
+case "$1" in
+ unset) unset UV_CACHE_DIR ;;
+ value) UV_CACHE_DIR=$2 ;;
+ *) exit 2 ;;
+esac
+_ISOLATE_UV_CACHE=$3
+HOME=$4
+case "$5" in
+ unset) unset XDG_CACHE_HOME ;;
+ value) XDG_CACHE_HOME=$6 ;;
+ *) exit 2 ;;
+esac
+STUDIO_HOME=$7
+
+TEST_UV_EFFECTIVE_CACHE=$9
+export TEST_UV_EFFECTIVE_CACHE
+PATH="$UV_STUB_DIR:$PATH"
+export PATH
+_configure_uv_cache
+_child=$($8 -c 'printf "%s" "${UV_CACHE_DIR+x}:$UV_CACHE_DIR"')
+printf 'value=%s\nmode=%s\nchild=%s\n' "$UV_CACHE_DIR" "$_UV_CACHE_MODE" "$_child"
+_prepare_studio_uv_cache_for_launch
+printf 'launch=%s\n' "$UV_CACHE_DIR"
+PROBE
+
+run_case() { # shell, label, state, input, isolate, home, xdg-state, xdg, root, effective, value, mode, message, launch
+ _shell=$1
+ _label=$2
+ _state=$3
+ _input=$4
+ _isolate=$5
+ _home=$6
+ _xdg_state=$7
+ _xdg=$8
+ _root=$9
+ shift 9
+ _effective=$1
+ _expected=$2
+ _mode=$3
+ _message=$4
+ _launch=$5
+ _actual=$($_shell "$PROBE" "$_state" "$_input" "$_isolate" "$_home" "$_xdg_state" "$_xdg" "$_root" "$_shell" "$_effective")
+ _wanted=$(printf 'message=%s\nvalue=%s\nmode=%s\nchild=x:%s\nlaunch=%s' \
+ "$_message" "$_expected" "$_mode" "$_expected" "$_launch")
+ if [ "$_actual" = "$_wanted" ]; then
+ ok "$_shell: $_label"
+ else
+ bad "$_shell: $_label (expected [$_wanted], got [$_actual])"
+ fi
+}
+
+echo "=== test_install_uv_cache_root ==="
+for shell in sh bash; do
+ command -v "$shell" >/dev/null 2>&1 || continue
+ CASE="$WORK/$shell case"
+ HOME_DIR="$CASE/home with spaces"
+ XDG_DIR="$CASE/xdg with spaces"
+ ROOT="$CASE/studio root"
+ STUDIO_CACHE="$ROOT/cache/uv"
+ HOME_CACHE="$HOME_DIR/.cache/uv"
+ XDG_CACHE="$XDG_DIR/uv"
+ OVERRIDE="$CASE/caller cache/uv artifacts"
+ mkdir -p "$HOME_DIR" "$ROOT"
+
+ run_case "$shell" "missing default selects Studio" unset "" false \
+ "$HOME_DIR" unset "" "$ROOT" "$HOME_CACHE" "$STUDIO_CACHE" studio \
+ "using new Studio-owned cache ($STUDIO_CACHE)" "$STUDIO_CACHE"
+
+ mkdir -p "$HOME_CACHE/CACHEDIR.TAG/inside"
+ : > "$HOME_CACHE/CACHEDIR.TAG/inside/payload"
+ : > "$HOME_CACHE/.gitignore"
+ run_case "$shell" "marker-only default stays Studio and is not traversed" unset "" false \
+ "$HOME_DIR" unset "" "$ROOT" "$HOME_CACHE" "$STUDIO_CACHE" studio \
+ "using new Studio-owned cache ($STUDIO_CACHE)" "$STUDIO_CACHE"
+ if [ -f "$HOME_CACHE/CACHEDIR.TAG/inside/payload" ] && [ -f "$HOME_CACHE/.gitignore" ]; then
+ ok "$shell: marker-only probe is non-destructive"
+ else
+ bad "$shell: marker-only probe modified the shared cache"
+ fi
+
+ mkdir -p "$HOME_CACHE/sdists-v9" "$HOME_CACHE/interpreter-v4/key"
+ : > "$HOME_CACHE/sdists-v9/.git"
+ : > "$HOME_CACHE/sdists-v9/.gitignore"
+ : > "$HOME_CACHE/interpreter-v4/key/metadata.msgpack"
+ : > "$HOME_CACHE/.lock"
+ run_case "$shell" "uv venv scaffolding stays Studio-owned" unset "" false \
+ "$HOME_DIR" unset "" "$ROOT" "$HOME_CACHE" "$STUDIO_CACHE" studio \
+ "using new Studio-owned cache ($STUDIO_CACHE)" "$STUDIO_CACHE"
+
+ mkdir -p "$HOME_CACHE/archive-v0/package"
+ : > "$HOME_CACHE/archive-v0/package/payload.py"
+ run_case "$shell" "populated HOME cache is reused" unset "" false \
+ "$HOME_DIR" unset "" "$ROOT" "$HOME_CACHE" "$HOME_CACHE" shared \
+ "reusing existing shared cache ($HOME_CACHE) to avoid duplicate Torch/CUDA downloads; use --isolated-uv-cache to isolate" \
+ "$STUDIO_CACHE"
+
+ run_case "$shell" "blank override still reuses populated default" value " " false \
+ "$HOME_DIR" unset "" "$ROOT" "$HOME_CACHE" "$HOME_CACHE" shared \
+ "reusing existing shared cache ($HOME_CACHE) to avoid duplicate Torch/CUDA downloads; use --isolated-uv-cache to isolate" \
+ "$STUDIO_CACHE"
+
+ mkdir -p "$XDG_CACHE/wheels-v5/package"
+ : > "$XDG_CACHE/wheels-v5/package/cached.whl"
+ run_case "$shell" "XDG default wins over HOME" unset "" false \
+ "$HOME_DIR" value "$XDG_DIR" "$ROOT" "$XDG_CACHE" "$XDG_CACHE" shared \
+ "reusing existing shared cache ($XDG_CACHE) to avoid duplicate Torch/CUDA downloads; use --isolated-uv-cache to isolate" \
+ "$STUDIO_CACHE"
+
+ EMPTY_XDG="$CASE/empty xdg"
+ EMPTY_XDG_CACHE="$EMPTY_XDG/uv"
+ mkdir -p "$EMPTY_XDG_CACHE"
+ run_case "$shell" "empty XDG does not fall back to populated HOME" unset "" false \
+ "$HOME_DIR" value "$EMPTY_XDG" "$ROOT" "$EMPTY_XDG_CACHE" "$STUDIO_CACHE" studio \
+ "using new Studio-owned cache ($STUDIO_CACHE)" "$STUDIO_CACHE"
+
+ CONFIG_CACHE="$CASE/uv.toml cache"
+ mkdir -p "$CONFIG_CACHE/wheels-v5/package"
+ : > "$CONFIG_CACHE/wheels-v5/package/torch.whl"
+ run_case "$shell" "uv-configured cache is resolved and reused" unset "" false \
+ "$HOME_DIR" value "$EMPTY_XDG" "$ROOT" "$CONFIG_CACHE" "$CONFIG_CACHE" shared \
+ "reusing existing shared cache ($CONFIG_CACHE) to avoid duplicate Torch/CUDA downloads; use --isolated-uv-cache to isolate" \
+ "$STUDIO_CACHE"
+
+ run_case "$shell" "custom override is exact" value "$OVERRIDE" false \
+ "$HOME_DIR" value "$XDG_DIR" "$ROOT" "$XDG_CACHE" "$OVERRIDE" custom \
+ "preserving custom UV_CACHE_DIR ($OVERRIDE)" "$OVERRIDE"
+
+ run_case "$shell" "custom override wins over isolation" value "$OVERRIDE" true \
+ "$HOME_DIR" value "$XDG_DIR" "$ROOT" "$XDG_CACHE" "$OVERRIDE" custom \
+ "preserving custom UV_CACHE_DIR ($OVERRIDE)" "$OVERRIDE"
+
+ run_case "$shell" "forced isolation uses Studio despite populated default" unset "" true \
+ "$HOME_DIR" value "$XDG_DIR" "$ROOT" "$XDG_CACHE" "$STUDIO_CACHE" isolated \
+ "forced Studio cache isolation ($STUDIO_CACHE); already-cached packages may download again" "$STUDIO_CACHE"
+
+ run_case "$shell" "unresolvable default safely selects Studio" unset "" false \
+ "" unset "" "$ROOT" "" "$STUDIO_CACHE" studio \
+ "using new Studio-owned cache ($STUDIO_CACHE)" "$STUDIO_CACHE"
+
+ # wheels-v* is .msgpack/.http only on uv 0.10: one `--dry-run` leaves a file.
+ META_CACHE="$CASE/metadata only/uv"
+ mkdir -p "$META_CACHE/wheels-v6/pypi/torch" "$META_CACHE/simple-v20/pypi" \
+ "$META_CACHE/sdists-v9/pypi/pkg"
+ : > "$META_CACHE/wheels-v6/pypi/torch/2.11.0-cp313-none-any.msgpack"
+ : > "$META_CACHE/wheels-v6/pypi/torch/2.11.0.http"
+ : > "$META_CACHE/simple-v20/pypi/torch.rkyv"
+ : > "$META_CACHE/sdists-v9/pypi/pkg/revision.rev"
+ : > "$META_CACHE/sdists-v9/pypi/pkg/download.lock"
+ run_case "$shell" "metadata-only default is not a warm cache" unset "" false \
+ "$HOME_DIR" unset "" "$ROOT" "$META_CACHE" "$STUDIO_CACHE" studio \
+ "using new Studio-owned cache ($STUDIO_CACHE)" "$STUDIO_CACHE"
+
+ mkdir -p "$META_CACHE/archive-v0/hash/torch"
+ : > "$META_CACHE/archive-v0/hash/torch/_C.so"
+ run_case "$shell" "package bytes beside metadata do count" unset "" false \
+ "$HOME_DIR" unset "" "$ROOT" "$META_CACHE" "$META_CACHE" shared \
+ "reusing existing shared cache ($META_CACHE) to avoid duplicate Torch/CUDA downloads; use --isolated-uv-cache to isolate" \
+ "$STUDIO_CACHE"
+
+ # builds-v* is what modern uv calls the old built-wheels-* bucket.
+ BUILDS_CACHE="$CASE/builds cache/uv"
+ mkdir -p "$BUILDS_CACHE/builds-v0/pkg"
+ : > "$BUILDS_CACHE/builds-v0/pkg/module.py"
+ run_case "$shell" "builds-v0 counts as package data" unset "" false \
+ "$HOME_DIR" unset "" "$ROOT" "$BUILDS_CACHE" "$BUILDS_CACHE" shared \
+ "reusing existing shared cache ($BUILDS_CACHE) to avoid duplicate Torch/CUDA downloads; use --isolated-uv-cache to isolate" \
+ "$STUDIO_CACHE"
+
+ # `find` needs -L to descend a symlink; Get-ChildItem -Recurse already does.
+ LINK_CACHE="$CASE/symlinked bucket/uv"
+ LINK_TARGET="$CASE/symlinked bucket/elsewhere"
+ mkdir -p "$LINK_CACHE" "$LINK_TARGET/pkg"
+ : > "$LINK_TARGET/pkg/payload.so"
+ if ln -s "$LINK_TARGET" "$LINK_CACHE/archive-v0" 2>/dev/null; then
+ run_case "$shell" "symlinked bucket is still inspected" unset "" false \
+ "$HOME_DIR" unset "" "$ROOT" "$LINK_CACHE" "$LINK_CACHE" shared \
+ "reusing existing shared cache ($LINK_CACHE) to avoid duplicate Torch/CUDA downloads; use --isolated-uv-cache to isolate" \
+ "$STUDIO_CACHE"
+ fi
+
+ # Unreadable is not empty: falling back is right, doing it silently is not.
+ DENIED_CACHE="$CASE/denied bucket/uv"
+ mkdir -p "$DENIED_CACHE/archive-v0/pkg"
+ : > "$DENIED_CACHE/archive-v0/pkg/payload.so"
+ if [ "$(id -u 2>/dev/null || echo 0)" != 0 ] && chmod 000 "$DENIED_CACHE/archive-v0" 2>/dev/null; then
+ run_case "$shell" "unreadable bucket says why it fell back" unset "" false \
+ "$HOME_DIR" unset "" "$ROOT" "$DENIED_CACHE" "$STUDIO_CACHE" studio \
+ "using new Studio-owned cache ($STUDIO_CACHE); part of $DENIED_CACHE could not be read, so cached packages may download again" \
+ "$STUDIO_CACHE"
+ chmod 755 "$DENIED_CACHE/archive-v0" 2>/dev/null || true
+ fi
+
+ DEEP_CACHE="$CASE/denied leaf/uv"
+ mkdir -p "$DEEP_CACHE/archive-v0/visible" "$DEEP_CACHE/archive-v0/aaa hidden"
+ : > "$DEEP_CACHE/archive-v0/visible/payload.so"
+ : > "$DEEP_CACHE/archive-v0/aaa hidden/other.so"
+ if [ "$(id -u 2>/dev/null || echo 0)" != 0 ] && chmod 000 "$DEEP_CACHE/archive-v0/aaa hidden" 2>/dev/null; then
+ run_case "$shell" "unreadable leaf keeps a warm cache warm" unset "" false \
+ "$HOME_DIR" unset "" "$ROOT" "$DEEP_CACHE" "$DEEP_CACHE" shared \
+ "reusing existing shared cache ($DEEP_CACHE) to avoid duplicate Torch/CUDA downloads; use --isolated-uv-cache to isolate" \
+ "$STUDIO_CACHE"
+ chmod 755 "$DEEP_CACHE/archive-v0/aaa hidden" 2>/dev/null || true
+ fi
+done
+
+_resolve_line=$(grep -n '^_resolve_studio_destinations$' "$INSTALL_SH" | head -n1 | cut -d: -f1)
+_configure_line=$(grep -n '^_configure_uv_cache$' "$INSTALL_SH" | head -n1 | cut -d: -f1)
+_uv_line=$(grep -n '^# ── Install uv ──$' "$INSTALL_SH" | head -n1 | cut -d: -f1)
+_venv_line=$(grep -n '^# ── Create venv ' "$INSTALL_SH" | head -n1 | cut -d: -f1)
+if [ -n "$_resolve_line" ] && [ -n "$_configure_line" ] && [ -n "$_uv_line" ] && [ -n "$_venv_line" ] \
+ && [ "$_resolve_line" -lt "$_uv_line" ] && [ "$_uv_line" -lt "$_configure_line" ] \
+ && [ "$_configure_line" -lt "$_venv_line" ]; then
+ ok "helper runs after uv setup and before venv setup"
+else
+ bad "helper ordering (resolve=$_resolve_line uv=$_uv_line configure=$_configure_line venv=$_venv_line)"
+fi
+
+for _required in \
+ '_ISOLATE_UV_CACHE=false' \
+ '--isolated-uv-cache) _ISOLATE_UV_CACHE=true' \
+ 'UNSLOTH_ISOLATE_UV_CACHE' \
+ 'export UNSLOTH_ISOLATE_UV_CACHE=1' \
+ 'unset UV_CACHE_DIR' \
+ '_prepare_studio_uv_cache_for_launch'; do
+ if grep -Fq -- "$_required" "$INSTALL_SH"; then
+ ok "source contract: $_required"
+ else
+ bad "missing source contract: $_required"
+ fi
+done
+
+echo ""
+echo " PASS: $PASS"
+echo " FAIL: $FAIL"
+if [ "$FAIL" -gt 0 ]; then
+ echo "FAILED"
+ exit 1
+fi
+echo "ALL PASSED"