Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
installer: the adaptive uv cache selection was unreachable on every writable install (#10626)
Daniel Hand728b5fc4e10
diff --git a/.github/scripts/Watch-ForCompiler.ps1 b/.github/scripts/Watch-ForCompiler.ps1index e4b42e01be7..11b3eaafd57 100644--- a/.github/scripts/Watch-ForCompiler.ps1+++ b/.github/scripts/Watch-ForCompiler.ps1@@ -347,12 +347,21 @@ function Get-StudioCompilerEvents {try {# Bounded at both ends. Open-ended, a compiler started by something else during# the recursive temp scan counted against the action that had already finished.+ #+ # Padded a second each way, then filtered exactly below: the hashtable's bounds do+ # not hold to the precision they are given. A csc.exe at 17:51:57.107 came back from+ # a window whose floor was 17:51:57.58, and failed a step that had not printed its+ # first line until 17:51:58.58. TimeCreated is the instant the claim is about. The+ # far pad covers the other end, where rounding could drop a real compile.$events = Get-WinEvent -FilterHashtable @{LogName = 'Security'Id = 4688- StartTime = $Since- EndTime = $Until+ StartTime = $Since.AddSeconds(-1)+ EndTime = $Until.AddSeconds(1)} -ErrorAction Stop+ $events = @($events | Where-Object {+ $_.TimeCreated -ge $Since -and $_.TimeCreated -le $Until+ })} catch [System.Exception] {# No matching events is an exception from Get-WinEvent, not an empty set, and on# a clean run that is expected. A log this cannot READ throws the same way, sodiff --git a/install.ps1 b/install.ps1index e4d358ed225..28bc4d7f955 100644--- a/install.ps1+++ b/install.ps1@@ -1579,17 +1579,28 @@ exit 1# Set-Location does not move. Mirrors _absolutize_uv_cache_dir in install.sh.function Resolve-StudioUvCachePath {param([Parameter(Mandatory = $true)][AllowEmptyString()][string]$Cache)- if ([string]::IsNullOrEmpty($Cache) -or [System.IO.Path]::IsPathRooted($Cache)) {- return $Cache- }+ if ([string]::IsNullOrEmpty($Cache)) { return $Cache }+ if (-not [System.IO.Path]::IsPathRooted($Cache)) {+ try {+ $base = if (-not [string]::IsNullOrWhiteSpace($env:UV_WORKING_DIR)) {+ if ([System.IO.Path]::IsPathRooted($env:UV_WORKING_DIR)) {+ $env:UV_WORKING_DIR+ } else { Join-Path $PWD.Path $env:UV_WORKING_DIR }+ } else { $PWD.Path }+ $Cache = [System.IO.Path]::GetFullPath((Join-Path $base $Cache))+ } catch { return $Cache }+ }+ # A trailing separator names the same directory but compares unequal, and that+ # comparison picks `studio` over `shared` in the selector. Never past the root, which+ # is a real directory. Mirrors the trim in _absolutize_uv_cache_dir.try {- $base = if (-not [string]::IsNullOrWhiteSpace($env:UV_WORKING_DIR)) {- if ([System.IO.Path]::IsPathRooted($env:UV_WORKING_DIR)) {- $env:UV_WORKING_DIR- } else { Join-Path $PWD.Path $env:UV_WORKING_DIR }- } else { $PWD.Path }- return [System.IO.Path]::GetFullPath((Join-Path $base $Cache))- } catch { return $Cache }+ $root = [System.IO.Path]::GetPathRoot($Cache)+ while ($Cache.Length -gt $root.Length -and+ ($Cache.EndsWith("\") -or $Cache.EndsWith("/"))) {+ $Cache = $Cache.Substring(0, $Cache.Length - 1)+ }+ } catch { }+ return $Cache}# Claim the root before anything of ours goes into it: the uv cache, the venv and the venv's@@ -1719,6 +1730,144 @@ exit 1$script:StudioUvMarkerSaved = $false}+ # uv --no-cache neither reads nor writes a cache: on uv 0.10.7 a caller's UV_CACHE_DIR stays+ # completely empty, CACHEDIR.TAG included, so nothing this install did belongs in the marker+ # whichever branch chose the directory. Lowercased, since uv takes it case-insensitively; not+ # trimmed, since uv rejects a padded value outright. The literals are clap's+ # BoolishValueParser set, `y` and `t` included. Mirrors _uv_no_cache_requested in install.sh.+ function Test-StudioUvNoCache {+ return (([string]$env:UV_NO_CACHE).ToLowerInvariant() -in @("1", "y", "yes", "t", "true", "on"))+ }++ # True for a name uv itself creates: <kind>-v<N>, whole suffix numeric. `archive-v0.backup`+ # is not uv's. Mirrors _uv_is_bucket_name, suffix from the LAST `-v` included.+ function Test-StudioUvBucketName {+ param([Parameter(Mandatory = $true)][AllowEmptyString()][string]$Name)+ $at = $Name.LastIndexOf("-v")+ if ($at -lt 0) { return $false }+ $suffix = $Name.Substring($at + 2)+ if ([string]::IsNullOrEmpty($suffix)) { return $false }+ # \A and \z, not ^ and $: in .NET `$` also matches before a final newline, so+ # `archive-v1<LF>` passed here while the sh helper rejected it.+ return ($suffix -match '\A[0-9]+\z')+ }++ # Readable is not usable: uv writes CACHEDIR.TAG into the root and renames distributions+ # into the buckets, aborting on either, and an ACL answers a different question than a real+ # create. So create and delete for real, in the root and in EVERY <kind>-v<N> bucket: uv+ # mutates interpreter-v4 too. Mirrors the probe loop in _configure_uv_cache.+ function Test-StudioUvCacheWritable {+ param([Parameter(Mandatory = $true)][string]$Cache)+ $probeDirs = [System.Collections.Generic.List[string]]::new()+ $probeDirs.Add($Cache)+ try {+ foreach ($entry in [System.IO.Directory]::GetFileSystemEntries($Cache)) {+ $name = [System.IO.Path]::GetFileName($entry)+ # Only where a BUCKET should be. Anything else up here is not uv's to write,+ # and a cache-dir on a mount point has a root-owned lost+found that must not+ # condemn it.+ if (-not (Test-StudioUvBucketName -Name $name)) { continue }+ # A file, or a link dangling or not, is an existing path to uv's own create,+ # which answers "already exists", so uv refuses it.+ if (-not [System.IO.Directory]::Exists($entry)) { return $false }+ $probeDirs.Add($entry)+ }+ } catch { return $false }+ foreach ($dir in $probeDirs) {+ # A generated name, not a fixed one: a predictable path can be pre-created as a link+ # for the write to follow.+ $probe = Join-Path $dir (".unsloth-write-probe." + [guid]::NewGuid().ToString("N").Substring(0, 8))+ try { [System.IO.File]::WriteAllText($probe, "") } catch { return $false }+ try { Remove-Item -LiteralPath $probe -Force -ErrorAction Stop } catch { return $false }+ }+ return $true+ }++ # Warm means package BYTES: wheels-* is metadata only on uv 0.10, so a bare `--dry-run`+ # used to read as warm. Stricter than the probe above, deliberately: the KIND must be one uv+ # fills, since `archive-v0.backup` holds bytes uv cannot reuse. Missing a future kind here+ # costs a fallback; missing one in the PROBE would let an unwritable cache through.+ # [ref] $Blocked: unreadable is not empty, and the caller's message says why.+ function Test-StudioUvCachePopulated {+ param(+ [Parameter(Mandatory = $true)][string]$Cache,+ [ref]$Blocked+ )+ try {+ $buckets = Get-ChildItem -LiteralPath $Cache -Directory -Force -ErrorAction Stop |+ Where-Object {+ (Test-StudioUvBucketName -Name $_.Name) -and+ ($_.Name.Substring(0, $_.Name.LastIndexOf("-v")) -in+ @("archive", "builds", "built-wheels", "wheels", "sdists"))+ }+ } catch {+ $Blocked.Value = $true+ return $false+ }+ 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+ -not $_.Name.StartsWith(".unsloth-write-probe.") -and+ $_.Extension -notin @(".lock", ".msgpack", ".http", ".rev")+ } |+ Select-Object -First 1+ if ($null -ne $entry) { return $true }+ if ($scanErrors -and $scanErrors.Count -gt 0) { $Blocked.Value = $true }+ }+ return $false+ }++ # Can we create AND fill this directory? A real create, since an existing unwritable one+ # satisfies CreateDirectory. For the Studio cache, which may not exist yet, where the bucket+ # probe above has nothing to walk.+ function Test-StudioUvCacheRootWritable {+ param([Parameter(Mandatory = $true)][string]$Cache)+ try {+ [System.IO.Directory]::CreateDirectory($Cache) | Out-Null+ $probe = Join-Path $Cache (".unsloth-write-probe." + [guid]::NewGuid().ToString("N").Substring(0, 8))+ [System.IO.File]::WriteAllText($probe, "")+ } catch { return $false }+ # NTFS carries DELETE as its own ACE, so a root can grant create and deny unlink. But+ # GONE is the answer, not the cmdlet's error: -ErrorAction Stop throws for a probe+ # something else already removed, where `rm -f` exits 0, and an indexer holding the+ # handle makes one delete fail and the next succeed. Retry, then ask the filesystem.+ for ($attempt = 0; $attempt -lt 3; $attempt++) {+ if ($attempt -gt 0) { Start-Sleep -Seconds 1 }+ Remove-Item -LiteralPath $probe -Force -ErrorAction SilentlyContinue+ if (-not [System.IO.File]::Exists($probe)) { return $true }+ }+ return $false+ }++ # Creatable AND fillable: the root helper answers for a cache that may not exist yet, the+ # bucket probe for one uv has already made buckets in. The fallback and the launch repoint+ # both need both, or they hand back a cache the candidate probe just rejected.+ function Test-StudioUvCacheUsable {+ param([Parameter(Mandatory = $true)][string]$Cache)+ if (-not (Test-StudioUvCacheRootWritable -Cache $Cache)) { return $false }+ return (Test-StudioUvCacheWritable -Cache $Cache)+ }++ # The cache THIS install last recorded, absolute, or "" when there is none. Read before the+ # selector writes its own. BOM and all: PowerShell 5.1 writes -Encoding utf8 WITH a BOM and+ # the update writes the same file BOM-less.+ function Read-StudioUvCacheMarker {+ param([Parameter(Mandatory = $true)][string]$StudioRoot)+ $markerFile = Join-Path (Join-Path $StudioRoot "cache") "uv-cache-dir"+ try {+ $recorded = Get-Content -LiteralPath $markerFile -Raw -Encoding UTF8 -ErrorAction Stop+ } catch { return "" }+ if ($null -eq $recorded) { return "" }+ $recorded = ([string]$recorded).Trim([char]0xFEFF).Trim()+ if ([string]::IsNullOrWhiteSpace($recorded)) { return "" }+ return (Resolve-StudioUvCachePath -Cache $recorded)+ }+function Set-StudioUvCacheEnvironment {param([Parameter(Mandatory = $true)][string]$StudioRoot,@@ -1731,6 +1880,10 @@ exit 1# Absolute before anything uses it, so every phase of one install and the# marker name the same directory (see _absolutize_uv_cache_dir in install.sh).$env:UV_CACHE_DIR = Resolve-StudioUvCachePath -Cache $env:UV_CACHE_DIR+ if (Test-StudioUvNoCache) {+ step "uv cache" "preserving custom UV_CACHE_DIR ($env:UV_CACHE_DIR); uv caching is off (UV_NO_CACHE), so nothing is recorded"+ return+ }# Recorded like any other choice; a caller still outranks the marker.Write-StudioUvCacheMarker -StudioRoot $StudioRoot -Cache $env:UV_CACHE_DIRstep "uv cache" "preserving custom UV_CACHE_DIR ($env:UV_CACHE_DIR)"@@ -1738,67 +1891,127 @@ exit 1}if ($Isolated) {- $selectedCache = $studioCache+ Set-Item -LiteralPath Env:UV_CACHE_DIR -Value $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 (Test-StudioUvNoCache)) {+ Write-StudioUvCacheMarker -StudioRoot $StudioRoot -Cache $studioCache+ }+ step "uv cache" "forced Studio cache isolation ($studioCache); already-cached packages may download again" "Yellow"+ return+ }++ # Nothing to select either: probing would touch a cache the caller told uv to leave alone.+ if (Test-StudioUvNoCache) {+ Set-Item -LiteralPath Env:UV_CACHE_DIR -Value $studioCache+ $script:StudioUvCacheMode = "studio"+ step "uv cache" "uv caching is off (UV_NO_CACHE); nothing to select or record"+ return+ }++ $defaultCache = $null+ $scanBlocked = $false+ $blockedCache = ""+ $warnCache = ""+ $chosenCache = ""+ 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) {+ $defaultCache = ([string]$resolvedLine).Trim()}- if (-not $sharedCache -and -not [string]::IsNullOrWhiteSpace($env:LOCALAPPDATA)) {- $sharedCache = Join-Path (Join-Path $env:LOCALAPPDATA "uv") "cache"+ }+ if (-not $defaultCache -and -not [string]::IsNullOrWhiteSpace($env:LOCALAPPDATA)) {+ $defaultCache = Join-Path (Join-Path $env:LOCALAPPDATA "uv") "cache"+ }+ # A relative cache-dir comes back verbatim and uv resolves it against its working+ # directory, so scanning it as written inspects a same-named directory beside us.+ if ($defaultCache) { $defaultCache = Resolve-StudioUvCachePath -Cache $defaultCache }++ # The cache THIS install last recorded outranks uv's default while it is still+ # warm, or a rerun abandons a Studio cache holding Torch and CUDA the moment one+ # unrelated wheel makes uv's default read as warm. Content cannot decide it, because+ # the repoint below leaves backend bytes in the losing cache; that is what the marker+ # is for. Same order as _configure_uv_cache and _with_studio_uv_cache.+ # An install from before the marker has a populated Studio cache and nothing+ # recording it, so it is worth keeping. But it goes LAST, behind uv's default: an+ # install old enough to have no marker is old enough that `shared` was reachable,+ # and in that mode the launch repoint leaves backend wheels in the Studio cache+ # while Torch and CUDA sit in the default. Ahead of the default it picked those+ # leftovers. Mirrors install.sh and unsloth_cli/commands/studio.py.+ $recorded = Read-StudioUvCacheMarker -StudioRoot $StudioRoot+ # A marker naming a directory that is gone is a stale pointer, not a decision, so+ # it lands in the same place.+ $unmarkedStudio = if ($recorded -and (Test-Path -LiteralPath $recorded -PathType Container -ErrorAction SilentlyContinue)) {+ $null+ } else { $studioCache }+ foreach ($candidate in @($recorded, $defaultCache, $unmarkedStudio)) {+ if ([string]::IsNullOrWhiteSpace([string]$candidate)) { continue }+ if ($chosenCache) { continue }+ # SilentlyContinue: under "Stop" a Test-Path inside an ACL-denied directory+ # THROWS, and that escapes to the outer catch and kills the whole loop, so one+ # unreachable marker would also cost us uv's default. install.sh's+ # `[ -d ] && [ -r ]` just reads false and moves on.+ if (-not (Test-Path -LiteralPath $candidate -PathType Container -ErrorAction SilentlyContinue)) { continue }+ # Per candidate: the scan can report blocked and still return $true, so a+ # shared flag pins the NEXT candidate's name into $blockedCache and suppresses+ # the message naming the cache actually refused.+ $candidateBlocked = $false+ $populated = Test-StudioUvCachePopulated -Cache $candidate -Blocked ([ref]$candidateBlocked)+ if ($candidateBlocked) {+ $scanBlocked = $true+ if (-not $blockedCache) { $blockedCache = $candidate }}- 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 }- }+ if (-not $populated) { continue }+ if (Test-StudioUvCacheWritable -Cache $candidate) {+ $chosenCache = $candidate+ } elseif (-not $warnCache) {+ $warnCache = $candidate}- } catch {- # An uninspectable cache is not an install error; isolation is safe.- $sharedCache = $null- $sharedCachePopulated = $false- $scanBlocked = $true}+ } catch {+ # An uninspectable cache is not an install error; isolation is safe.+ $chosenCache = ""+ $scanBlocked = $true+ }- if ($sharedCachePopulated) {- $selectedCache = $sharedCache- $script:StudioUvCacheMode = "shared"- } else {- $selectedCache = $studioCache- $script:StudioUvCacheMode = "studio"+ if ($chosenCache) {+ $selectedCache = $chosenCache+ # studio, not shared, when the choice IS the Studio cache: the launch repoint below+ # only has to move a cache that is not already ours.+ $script:StudioUvCacheMode = if ($chosenCache -eq $studioCache) { "studio" } else { "shared" }+ } else {+ $selectedCache = $studioCache+ $script:StudioUvCacheMode = "studio"+ # A fallback we cannot write is not a fallback. The certain failure and the merely+ # suspect cache can both be on the table, and landing on the certain one turns a+ # working install into "failed to create cache directory".+ # Root AND buckets: the root can be writable while a bucket uv renames into is+ # not, which is what the candidate probe rejected a cache for. Anything usable+ # beats landing there: the populated cache that only failed the probe first, then+ # uv's own default, which at worst costs the downloads this cache never saved.+ if (-not (Test-StudioUvCacheUsable -Cache $studioCache)) {+ # A cache that is WARM and merely failed the probe beats a cold one we can+ # write, including when it is the Studio cache itself: the probe refuses a+ # whole cache for one bucket-shaped entry uv may never touch, where a cold+ # cache guarantees the downloads and offline guarantees failure.+ if ($warnCache) {+ $selectedCache = $warnCache+ if ($warnCache -ne $studioCache) {+ $script:StudioUvCacheMode = "shared"+ }+ } elseif ($defaultCache -and $defaultCache -ne $studioCache -and+ (Test-StudioUvCacheUsable -Cache $defaultCache)) {+ $selectedCache = $defaultCache+ $script:StudioUvCacheMode = "shared"+ }}}Set-Item -LiteralPath Env:UV_CACHE_DIR -Value $selectedCache@@ -1808,14 +2021,19 @@ exit 1"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) {+ if ($chosenCache) {+ step "uv cache" "reusing this install's Studio cache ($selectedCache)"+ # Never about the directory we are falling back TO: the Studio cache is itself+ # a candidate now, so it can be the one refused, and naming it claims a fallback+ # that did not happen.+ } elseif ($scanBlocked -and -not [string]::IsNullOrWhiteSpace([string]$blockedCache) -and $blockedCache -ne $selectedCache) {+ step "uv cache" "using new Studio-owned cache ($selectedCache); part of $blockedCache could not be read, so cached packages may download again" "Yellow"+ } elseif ($scanBlocked -and [string]::IsNullOrWhiteSpace([string]$blockedCache)) {step "uv cache" "using new Studio-owned cache ($selectedCache); the existing uv cache could not be inspected, so cached packages may download again" "Yellow"+ # Warm and still here means the write probe refused it.+ } elseif ($warnCache -and $warnCache -ne $selectedCache) {+ step "uv cache" "using new Studio-owned cache ($selectedCache); $warnCache is populated but not writable, so cached packages may download again" "Yellow"} else {step "uv cache" "using new Studio-owned cache ($selectedCache)"}@@ -1825,9 +2043,16 @@ exit 1function 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")- }+ if ($script:StudioUvCacheMode -ne "shared") { return }+ # Only to a cache the backend can fill: repointing at one we cannot write hands the+ # autostarted backend a cache uv aborts on, after an install that succeeded. Keeping the+ # shared one is honest, it is the cache this install just filled. Mirrors+ # _prepare_studio_uv_cache_for_launch.+ # Root AND buckets, the same rule the selection used: a root-only check repoints into+ # the very cache the candidate probe rejected for a bucket uv cannot rename into.+ $launchCache = Join-Path (Join-Path $StudioRoot "cache") "uv"+ if (-not (Test-StudioUvCacheUsable -Cache $launchCache)) { return }+ Set-Item -LiteralPath Env:UV_CACHE_DIR -Value $launchCache}function Restore-StudioUvCacheEnvironment {diff --git a/install.sh b/install.shindex 120a3cd9434..8fec62d8d13 100755--- a/install.sh+++ b/install.sh@@ -570,21 +570,120 @@ _resolve_studio_destinations() {}# Records which cache this install used, so an update reuses it rather than guessing: the launch below repoints the backend at the Studio cache even in shared mode, so one on-demand install makes an empty Studio cache look full. Never fatal. A relative UV_CACHE_DIR names a different directory in each phase of one install, since uv resolves it against its working directory and setup.sh changes into its own before the dependency pass, so make it absolute once, here.-_absolutize_uv_cache_dir() {- case "$UV_CACHE_DIR" in- /*) return 0 ;;+# Takes $1, defaulting to UV_CACHE_DIR, and prints it. The scan resolves uv's answer on this+# same base, so two different bases cannot miss a warm cache.+# True for a name uv itself creates: <kind>-v<N>, whole suffix numeric. `archive-v0.backup`+# is not uv's. One rule for the probe and the warmth scan; tightening one is how they drift.+# uv --no-cache neither reads nor writes a cache: on uv 0.10.7 a caller's UV_CACHE_DIR stays+# completely empty, CACHEDIR.TAG included. So nothing this install did belongs in the marker,+# whichever branch chose the directory. Lowercased, since uv takes it case-insensitively; not+# trimmed, since uv rejects a padded value outright. The literals are clap's BoolishValueParser+# set, `y` and `t` included. Mirrors _uv_no_cache_requested() in unsloth_cli/commands/studio.py.+_uv_no_cache_requested() {+ case "$(printf '%s' "${UV_NO_CACHE:-}" | tr '[:upper:]' '[:lower:]')" in+ 1|y|yes|t|true|on) return 0 ;;+ esac+ return 1+}++_uv_is_bucket_name() {+ case "$1" in+ *-v[0-9]*) ;;+ *) return 1 ;;+ esac+ # '' too: `##*-v` strips through the LAST `-v`, so `archive-v1-v` leaves an empty suffix+ # that no `*[!0-9]*` matches. It read as a bucket, and one read-only directory named that+ # way condemned a warm cache. Test-StudioUvBucketName rejects it, so the two had split.+ case "${1##*-v}" in+ ''|*[!0-9]*) return 1 ;;esac- _uv_cache_base="${UV_WORKING_DIR:-$PWD}"- case "$_uv_cache_base" in+ return 0+}++_absolutize_uv_cache_dir() {+ _uv_cache_path="${1-$UV_CACHE_DIR}"+ case "$_uv_cache_path" in/*) ;;- *) _uv_cache_base="$PWD/$_uv_cache_base" ;;+ *)+ _uv_cache_base="${UV_WORKING_DIR:-$PWD}"+ case "$_uv_cache_base" in+ /*) ;;+ *) _uv_cache_base="$PWD/$_uv_cache_base" ;;+ esac+ _uv_cache_path="$_uv_cache_base/$_uv_cache_path"+ ;;esac- UV_CACHE_DIR="$_uv_cache_base/$UV_CACHE_DIR"+ # A trailing slash names the same directory but compares unequal, and that comparison is+ # what picks `studio` over `shared` below: `$STUDIO_HOME/cache/uv/` would be called shared+ # and get the repoint `studio` avoids. Stops at the root, which is a real directory.+ while [ "$_uv_cache_path" != / ]; do+ case "$_uv_cache_path" in+ */) _uv_cache_path="${_uv_cache_path%/}" ;;+ *) break ;;+ esac+ done+ printf '%s\n' "$_uv_cache_path"+}++# Can we create AND fill this directory? A real create, since mkdir -p exits 0 on an existing+# unwritable one and -w reads the mode, not the filesystem. mktemp, since a predictable name+# in another account's directory can be pre-created as a symlink to follow.+_uv_cache_root_is_writable() {+ mkdir -p "$1" 2>/dev/null || return 1+ _uv_root_probe=$(mktemp "$1/.unsloth-write-probe.XXXXXX" 2>/dev/null) || return 1+ # Creating is not enough: an ACL granting create but denying unlink leaves uv's renames+ # to fail later. But GONE is the answer, not rm's exit status -- a scanner holding the+ # handle makes one delete fail and the next succeed, and condemning the cache on the first+ # failure sends the install to a fallback that may be worse. Retry, then believe the fs.+ _uv_root_tries=0+ while :; do+ rm -f "$_uv_root_probe" 2>/dev/null || true+ [ -e "$_uv_root_probe" ] || break+ _uv_root_tries=$((_uv_root_tries + 1))+ if [ "$_uv_root_tries" -ge 3 ]; then+ unset _uv_root_probe _uv_root_tries+ return 1+ fi+ sleep 1+ done+ unset _uv_root_probe _uv_root_tries+ return 0+}++# The root AND every bucket uv would rename into. _uv_cache_root_is_writable answers only for+# the directory itself, which is not enough once uv has made buckets in it: a `sudo` run leaves+# one root-owned, and a dangling link is an existing path to mkdir(2), so uv aborts on a cache+# whose root we can write perfectly well.+_uv_cache_is_writable() {+ _uv_cache_root_is_writable "$1" || return 1+ _uv_w_bad=0+ _uv_w_glob=on+ case $- in *f*) _uv_w_glob=off ;; esac+ set +f+ for _uv_w_dir in "$1"/*; do+ _uv_is_bucket_name "${_uv_w_dir##*/}" || continue+ if [ ! -d "$_uv_w_dir" ]; then+ # A file, or a symlink dangling or not, is an existing path to mkdir(2).+ if [ -e "$_uv_w_dir" ] || [ -L "$_uv_w_dir" ]; then+ _uv_w_bad=1+ fi+ continue+ fi+ _uv_cache_root_is_writable "$_uv_w_dir" || _uv_w_bad=1+ done+ if [ "$_uv_w_glob" = off ]; then set -f; fi+ unset _uv_w_dir _uv_w_glob+ if [ "$_uv_w_bad" -ne 0 ]; then+ unset _uv_w_bad+ return 1+ fi+ unset _uv_w_bad+ return 0}_record_uv_cache_choice() {# In place, before anything reads it: every branch records, so this is the one point every phase of the install and the marker are made to agree on one directory.- _absolutize_uv_cache_dir+ UV_CACHE_DIR=$(_absolutize_uv_cache_dir)_uv_marker_dir="$STUDIO_HOME/cache"_uv_marker_file="$_uv_marker_dir/uv-cache-dir"_uv_marker_value="$UV_CACHE_DIR"@@ -624,26 +723,44 @@ _restore_uv_cache_marker() {_configure_uv_cache() {_uv_studio_cache="$STUDIO_HOME/cache/uv"- case "${UV_CACHE_DIR-}" in- *[![:space:]]*)- _UV_CACHE_MODE=custom- export UV_CACHE_DIR- # Recorded like any other choice; a caller still outranks the marker.- _record_uv_cache_choice- step "uv cache" "preserving custom UV_CACHE_DIR ($UV_CACHE_DIR)"- return 0- ;;- esac+ # A CALLER's UV_CACHE_DIR outranks everything below; our own default must not, and the+ # variable cannot tell them apart because the block above already exported it. Without the+ # flag this matched on every writable install, so nothing below ever ran.+ if [ "${_UV_CACHE_DIR_INSTALLER_DEFAULT:-false}" != true ]; then+ case "${UV_CACHE_DIR-}" in+ *[![:space:]]*)+ _UV_CACHE_MODE=custom+ export UV_CACHE_DIR+ if _uv_no_cache_requested; then+ step "uv cache" "preserving custom UV_CACHE_DIR ($UV_CACHE_DIR); uv caching is off (UV_NO_CACHE), so nothing is recorded"+ else+ # Recorded like any other choice; a caller still outranks the marker.+ _record_uv_cache_choice+ step "uv cache" "preserving custom UV_CACHE_DIR ($UV_CACHE_DIR)"+ fi+ return 0+ ;;+ esac+ fiif [ "$_ISOLATE_UV_CACHE" = true ]; thenUV_CACHE_DIR="$_uv_studio_cache"_UV_CACHE_MODE=isolatedexport UV_CACHE_DIR- _record_uv_cache_choice+ _uv_no_cache_requested || _record_uv_cache_choicestep "uv cache" "forced Studio cache isolation ($UV_CACHE_DIR); already-cached packages may download again" "$C_WARN"return 0fi+ # Nothing to select either: probing would touch a cache the caller told uv to leave alone.+ if _uv_no_cache_requested; then+ UV_CACHE_DIR="$_uv_studio_cache"+ _UV_CACHE_MODE=studio+ export UV_CACHE_DIR+ step "uv cache" "uv caching is off (UV_NO_CACHE); nothing to select or record"+ 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=""@@ -654,40 +771,151 @@ _configure_uv_cache() {_uv_default_cache="${HOME}/.cache/uv"fifi+ # A relative cache-dir comes back verbatim and uv resolves it against its working+ # directory, so scanning it as written inspects a same-named directory beside us.+ if [ -n "$_uv_default_cache" ]; then+ _uv_default_cache=$(_absolutize_uv_cache_dir "$_uv_default_cache")+ fi++ # The cache THIS install last recorded outranks uv's default while it is still warm, or a+ # rerun abandons a Studio cache holding Torch and CUDA the moment one unrelated wheel makes+ # uv's default read as warm. Content cannot decide it, because the repoint below leaves+ # backend bytes in the losing cache; that is what the marker is for. Same precedence as+ # unsloth_cli/commands/studio.py:_with_studio_uv_cache.+ # install.ps1 writes this with -Encoding utf8, which under PowerShell 5.1 means BOM and+ # CRLF, and a WSL install shares $STUDIO_HOME with the Windows one. The other two readers+ # already defend. Untreated, a CR fails [ -d ] and abandons the warm cache in silence, and+ # a BOM makes the value non-absolute so $PWD gets prepended.+ _uv_recorded=$(cat "$STUDIO_HOME/cache/uv-cache-dir" 2>/dev/null | tr -d '\r') || _uv_recorded=""+ _uv_bom=$(printf '\357\273\277')+ _uv_recorded="${_uv_recorded#"$_uv_bom"}"+ unset _uv_bom+ case "$_uv_recorded" in+ *[![:space:]]*) _uv_recorded=$(_absolutize_uv_cache_dir "$_uv_recorded") ;;+ *) _uv_recorded="" ;;+ esac- _uv_default_populated=false+ # An install from before the marker has a populated $STUDIO_HOME/cache/uv and nothing+ # recording it, so it is worth keeping rather than abandoning for uv's default. But it goes+ # LAST, behind uv's default, because content cannot prove whose it is: the marker arrived in+ # b66d2a4c8 on 2026-09-06 and the early block only in e12963071 the day after, so an install+ # old enough to have no marker is old enough that `shared` was reachable, and in that mode+ # the launch repoint leaves backend wheels in the Studio cache while Torch and CUDA sit in+ # the default. Ordering it ahead of the default picked those leftovers and redownloaded+ # gigabytes. Behind it, a warm Studio cache still wins whenever the default is cold, which+ # is the install this was added for. A marker naming a directory that is gone is a stale+ # pointer rather than a decision, so it lands in the same place.+ _uv_unmarked_studio=""+ if [ -z "$_uv_recorded" ] || [ ! -d "$_uv_recorded" ]; then+ _uv_unmarked_studio="$_uv_studio_cache"+ fi++ # Readable is not usable: uv writes CACHEDIR.TAG into the root and renames distributions+ # into the buckets, aborting on either. Nested entries are deliberately NOT probed: that+ # walks hundreds of thousands of files, and a denied leaf keeps a warm cache warm._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+ _uv_blocked_cache=""+ _uv_warn_cache=""+ _uv_chosen_cache=""+ for _uv_candidate in "$_uv_recorded" "$_uv_default_cache" "$_uv_unmarked_studio"; do+ { [ -n "$_uv_candidate" ] && [ -z "$_uv_chosen_cache" ]; } || continue+ _uv_cand_populated=false+ _uv_cand_writable=true+ if [ -d "$_uv_candidate" ] && [ -r "$_uv_candidate" ]; then+ # The globs below ARE the scan, so a caller's set -f reads every cache as empty.+ _uv_glob=on+ case $- in *f*) _uv_glob=off ;; esac+ set +f++ # Root and every bucket, through the one helper the fallback and the launch+ # repoint also use, so a cache rejected here cannot be handed back later.+ _uv_cache_is_writable "$_uv_candidate" || _uv_cand_writable=false++ # 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_candidate"/archive-* \+ "$_uv_candidate"/builds-* \+ "$_uv_candidate"/built-wheels-* \+ "$_uv_candidate"/wheels-* \+ "$_uv_candidate"/sdists-*; do+ [ -d "$_uv_bucket" ] || continue+ # Stricter than the probe above, deliberately: the KIND must be one uv fills,+ # since `archive-*` also matches `archive-v0.backup`, whose bytes uv cannot+ # reuse. Missing a future kind here costs a fallback; missing one in the PROBE+ # would let an unwritable cache through, so that stays on the open pattern.+ _uv_bucket_base="${_uv_bucket##*/}"+ _uv_is_bucket_name "$_uv_bucket_base" || continue+ case "${_uv_bucket_base%-v*}" in+ archive|builds|built-wheels|wheels|sdists) ;;+ *) continue ;;+ esac+ # Unreadable is not empty; remembered so the message below says why.+ if [ ! -r "$_uv_bucket" ] || [ ! -x "$_uv_bucket" ]; then+ _uv_scan_blocked=true+ [ -n "$_uv_blocked_cache" ] || _uv_blocked_cache="$_uv_candidate"+ continue+ fi+ # `|| true`: head closes the pipe, so find dies on SIGPIPE on a large bucket,+ # and under pipefail that cleared the path it had already printed.+ _uv_artifact=$(find -L "$_uv_bucket" -type f \+ ! -name CACHEDIR.TAG ! -name .git ! -name .gitignore \+ ! -name '.unsloth-write-probe.*' \+ ! -name '*.lock' ! -name '*.msgpack' ! -name '*.http' ! -name '*.rev' \+ -print 2>/dev/null | head -n 1) || true+ if [ -n "$_uv_artifact" ]; then+ _uv_cand_populated=true+ break+ fi+ done- if [ "$_uv_default_populated" = true ]; then- UV_CACHE_DIR="$_uv_default_cache"- _UV_CACHE_MODE=shared+ if [ "$_uv_glob" = off ]; then set -f; fi+ fi+ if [ "$_uv_cand_populated" = true ] && [ "$_uv_cand_writable" = true ]; then+ _uv_chosen_cache="$_uv_candidate"+ elif [ "$_uv_cand_populated" = true ] && [ -z "$_uv_warn_cache" ]; then+ _uv_warn_cache="$_uv_candidate"+ fi+ done+ unset _uv_candidate _uv_cand_populated _uv_cand_writable _uv_unmarked_studio++ if [ -n "$_uv_chosen_cache" ]; then+ UV_CACHE_DIR="$_uv_chosen_cache"+ # studio, not shared, when the choice IS the Studio cache: the launch repoint below+ # only has to move a cache that is not already ours.+ if [ "$_uv_chosen_cache" = "$_uv_studio_cache" ]; then+ _UV_CACHE_MODE=studio+ else+ _UV_CACHE_MODE=shared+ fielseUV_CACHE_DIR="$_uv_studio_cache"_UV_CACHE_MODE=studio+ # A fallback we cannot write is not a fallback. The early block has ALREADY given up+ # on $STUDIO_HOME/cache/uv, which is the only reason the selection is running, and the+ # root can be writable while a bucket uv renames into is not, which the probe rejected+ # a candidate for. Landing there turns a working install into a uv error, so anything+ # usable beats it: the populated cache that only failed the probe first, since the+ # certain failure and the merely suspect cache are both on the table, then uv's own+ # default, which at worst costs the downloads this cache was never going to save.+ if ! _uv_cache_is_writable "$_uv_studio_cache"; then+ # A cache that is WARM and merely failed the probe beats a cold one we can write:+ # the probe refuses a whole cache for one bucket-shaped entry uv may never touch,+ # where a cold cache guarantees the downloads, and offline guarantees failure. That+ # holds when the refused cache is the Studio cache itself.+ if [ -n "$_uv_warn_cache" ]; then+ UV_CACHE_DIR="$_uv_warn_cache"+ if [ "$_uv_warn_cache" != "$_uv_studio_cache" ]; then+ _UV_CACHE_MODE=shared+ fi+ elif [ -n "$_uv_default_cache" ] \+ && [ "$_uv_default_cache" != "$_uv_studio_cache" ] \+ && _uv_cache_is_writable "$_uv_default_cache"; then+ UV_CACHE_DIR="$_uv_default_cache"+ _UV_CACHE_MODE=shared+ _uv_studio_unusable=true+ fi+ fifiexport UV_CACHE_DIR_record_uv_cache_choice@@ -697,8 +925,16 @@ _configure_uv_cache() {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"+ if [ -n "$_uv_chosen_cache" ]; then+ step "uv cache" "reusing this install's Studio cache ($UV_CACHE_DIR)"+ # Never about the directory we are falling back TO: the Studio cache is itself a+ # candidate now, so it can be the one refused, and naming it claims a fallback+ # that did not happen.+ elif [ "$_uv_scan_blocked" = true ] && [ "$_uv_blocked_cache" != "$UV_CACHE_DIR" ]; then+ step "uv cache" "using new Studio-owned cache ($UV_CACHE_DIR); part of $_uv_blocked_cache could not be read, so cached packages may download again" "$C_WARN"+ # Warm and still here means the write probe refused it.+ elif [ -n "$_uv_warn_cache" ] && [ "$_uv_warn_cache" != "$UV_CACHE_DIR" ]; then+ step "uv cache" "using new Studio-owned cache ($UV_CACHE_DIR); $_uv_warn_cache is populated but not writable, so cached packages may download again" "$C_WARN"elsestep "uv cache" "using new Studio-owned cache ($UV_CACHE_DIR)"fi@@ -708,7 +944,15 @@ _configure_uv_cache() {_prepare_studio_uv_cache_for_launch() {[ "${_UV_CACHE_MODE:-}" = shared ] || return 0- UV_CACHE_DIR="$STUDIO_HOME/cache/uv"+ # Only to a cache the backend can fill. shared is reachable exactly when the early block+ # failed its write probe on $STUDIO_HOME/cache/uv, so repointing unconditionally hands the+ # autostarted backend a cache uv aborts on, after an install that succeeded. Keeping the+ # shared one is honest: it is the cache this install just filled.+ # Root AND buckets, the same rule the selection used: a root-only check repoints into the+ # very cache the candidate probe rejected for a bucket uv cannot rename into.+ _uv_launch_cache="$STUDIO_HOME/cache/uv"+ _uv_cache_is_writable "$_uv_launch_cache" || return 0+ UV_CACHE_DIR="$_uv_launch_cache"export UV_CACHE_DIR}_resolve_studio_destinations@@ -771,19 +1015,20 @@ _claim_studio_root# Keep uv's cache on the same filesystem as the venv it fills.# uv hardlinks wheels within one filesystem and copies across a boundary, so a moved STUDIO_HOME paid double the disk and stranded the cache. An explicit UV_CACHE_DIR wins. The fallback is required, since uv aborts on a cache it cannot create; mkdir -p exits 0 for an existing unwritable directory and -w reads the mode rather than the filesystem, so probe with a real create.+# True only where the installer assigns its own default; the variable reads the same either way.+_UV_CACHE_DIR_INSTALLER_DEFAULT=falseif [ -z "${UV_CACHE_DIR:-}" ]; thenUV_CACHE_DIR="$STUDIO_HOME/cache/uv"export UV_CACHE_DIR- # mktemp, not a $$ name: a predictable path in another account's directory can be pre-created as a symlink for `: >` to follow and truncate as root.- _uv_cache_probe=""- if ! mkdir -p "$UV_CACHE_DIR" 2>/dev/null \- || ! _uv_cache_probe=$(mktemp "$UV_CACHE_DIR/.unsloth-write-probe.XXXXXX" 2>/dev/null); then+ _UV_CACHE_DIR_INSTALLER_DEFAULT=true+ # The same question the selection asks later, through the same helper, so the two answers+ # cannot drift apart.+ if ! _uv_cache_root_is_writable "$UV_CACHE_DIR"; thenecho "[WARN] Cannot write to $UV_CACHE_DIR -- using uv's default cache." >&2echo "[WARN] Wheels will be copied into the venv rather than hardlinked, costing extra disk." >&2unset UV_CACHE_DIR+ _UV_CACHE_DIR_INSTALLER_DEFAULT=falsefi- [ -z "$_uv_cache_probe" ] || rm -f "$_uv_cache_probe" 2>/dev/null || true- unset _uv_cache_probefi_VENV_ROLLBACK_DIR=""_VENV_ROLLBACK_TARGET="$VENV_DIR"@@ -2213,15 +2458,21 @@ _maybe_reroute_strixhalo_to_2404() {_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+ # An automatic path belongs to the origin distro; only an override is portable, and the+ # variable alone cannot tell them apart. Forwarding our own default pins the child to+ # `custom`, which skips its adaptive selection and outranks its --isolated-uv-cache.+ _rr_uv_cache=""+ if [ "${_UV_CACHE_DIR_INSTALLER_DEFAULT:-false}" != true ]; then+ case "${UV_CACHE_DIR-}" in+ *[![:space:]]*) _rr_uv_cache="$UV_CACHE_DIR" ;;+ esac+ fi+ if [ -n "$_rr_uv_cache" ]; then+ _rr_exports="$_rr_exports; export UV_CACHE_DIR=$(_rr_q "$_rr_uv_cache")"+ else+ _rr_exports="$_rr_exports; unset UV_CACHE_DIR"+ fi+ unset _rr_uv_cache[ "$_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"diff --git a/tests/python/test_cross_platform_parity.py b/tests/python/test_cross_platform_parity.pyindex d49815294bd..59f634ddbfd 100644--- a/tests/python/test_cross_platform_parity.py+++ b/tests/python/test_cross_platform_parity.py@@ -1152,10 +1152,16 @@ class TestInstallUvCacheRootParity:# Written after the choice is made.assert "_record_uv_cache_choice() {" in sh- # Every mode records, custom included, or a previous install's marker survives.+ # Every mode records, custom included, or a previous install's marker survives. The+ # no-cache guard may precede the call, since uv fills nothing under it, but a branch+ # that stops calling it at all is the bug this counts.call_sites = [match.start()- for match in re.finditer(r"^[ \t]+_record_uv_cache_choice[ \t]*$", sh, re.MULTILINE)+ for match in re.finditer(+ r"^[ \t]+(?:_uv_no_cache_requested \|\| )?_record_uv_cache_choice[ \t]*$",+ sh,+ re.MULTILINE,+ )]assert len(call_sites) == 3, f"one call site per mode branch, found {len(call_sites)}"assert (@@ -1163,11 +1169,18 @@ class TestInstallUvCacheRootParity:< min(call_sites)< sh.index("_UV_CACHE_MODE=isolated")), "the custom branch records before it returns"- assert ps1.count("Write-StudioUvCacheMarker -StudioRoot") == 2+ # Three on the ps1 side too, one per recording mode: custom, isolated, and the+ # selection. UV_NO_CACHE is the deliberate fourth that records NOTHING on both sides,+ # since a marker there would name a cache the install never filled.+ assert ps1.count("Write-StudioUvCacheMarker -StudioRoot") == 3, ps1.count(+ "Write-StudioUvCacheMarker -StudioRoot"+ )# A marker is a preference, not a requirement, so neither installer may fail on it.+ # Sliced at the first selection helper, not at the selector: the helpers between them+ # do use -ErrorAction Stop, and on purpose.marker_write = ps1[ps1.index("function Write-StudioUvCacheMarker") : ps1.index(- "function Set-StudioUvCacheEnvironment"+ "function Test-StudioUvNoCache")]# Covers both marker functions, which sit together above the selector.@@ -1178,9 +1191,88 @@ class TestInstallUvCacheRootParity:assert "utf-8-sig" in cli# Absolute on both sides: the update resolves it against its own directory.- assert 'case "$UV_CACHE_DIR" in' in sh+ assert "_absolutize_uv_cache_dir() {" in sh+ assert "UV_CACHE_DIR=$(_absolutize_uv_cache_dir)" in shassert "IsPathRooted" in ps1+ # The selection rules, on both installers. install.sh gained them first, which left+ # Windows abandoning a warm Studio cache on every rerun and selecting caches uv aborts+ # on. The behaviour is asserted by running each installer; the PAIRING is asserted+ # here, so a rule added to one side alone fails even where neither shell can run.+ # 1. the marker outranks uv's default while it is still warm+ assert "cache/uv-cache-dir" in sh+ assert "function Read-StudioUvCacheMarker" in ps1+ # 2. UV_NO_CACHE stands the selection down, in every spelling uv honours+ for source in (sh, ps1):+ assert "UV_NO_CACHE" in source+ # clap's literals, which is what uv binds UV_NO_CACHE to. All three copies, or one of+ # them probes and records a cache uv is not using.+ assert "1|y|yes|t|true|on)" in sh+ assert '@("1", "y", "yes", "t", "true", "on")' in ps1+ assert '_UV_TRUE = ("1", "y", "yes", "t", "true", "on")' in cli+ # and it is honoured BEFORE a caller's cache is recorded, on both sides: uv leaves+ # UV_CACHE_DIR completely empty under --no-cache, so a marker naming it would send the+ # next repair to a cache this install never filled. The CLI already checked first.+ assert "_uv_no_cache_requested() {" in sh+ assert "function Test-StudioUvNoCache" in ps1+ sh_custom = sh[sh.index("_UV_CACHE_MODE=custom") :].split("return 0", 1)[0]+ assert "_uv_no_cache_requested" in sh_custom, sh_custom+ sh_iso = sh[sh.index("_UV_CACHE_MODE=isolated") :].split("return 0", 1)[0]+ assert "_uv_no_cache_requested" in sh_iso, sh_iso+ ps1_custom = ps1[ps1.index('$script:StudioUvCacheMode = "custom"') :].split(+ "if ($Isolated)", 1+ )[0]+ assert "Test-StudioUvNoCache" in ps1_custom, ps1_custom+ ps1_iso = ps1[ps1.index('$script:StudioUvCacheMode = "isolated"') :].split(+ "Test-StudioUvNoCache)", 1+ )+ assert len(ps1_iso) == 2, "the isolated branch no longer guards its marker write"+ # 3. only <kind>-v<N> is uv's to write, so a lookalike is neither probed nor warmth+ assert "_uv_is_bucket_name() {" in sh+ assert "function Test-StudioUvBucketName" in ps1+ # and the version cannot be EMPTY on either side: `##*-v` strips through the last+ # `-v`, so `archive-v1-v` leaves "" behind, which no `*[!0-9]*` matches. PowerShell+ # rejected it from the start, so this was a real split.+ bucket_sh = sh.split("_uv_is_bucket_name() {", 1)[1].split("\n}", 1)[0]+ assert "''|*[!0-9]*) return 1 ;;" in bucket_sh, bucket_sh+ bucket_ps1 = ps1.split("function Test-StudioUvBucketName", 1)[1].split("\n}", 1)[0]+ assert "IsNullOrEmpty($suffix)" in bucket_ps1, bucket_ps1+ # and the CLI validates the whole suffix too, or `unsloth studio update` prefers a+ # cache the installers just rejected. Its docstring claimed the same rule long before+ # it had it.+ assert "def _uv_is_bucket_name(name: str) -> bool:" in cli+ assert (+ '_UV_CACHE_BUCKETS = ("archive", "builds", "built-wheels", "wheels", "sdists")' in cli+ )+ # 4. readable is not usable: a real create-and-delete, root and every bucket+ assert ".unsloth-write-probe." in sh+ assert ".unsloth-write-probe." in ps1+ assert "function Test-StudioUvCacheWritable" in ps1+ # 5. and a fallback we cannot write is not a fallback, on both sides+ assert "_uv_cache_root_is_writable() {" in sh+ assert "function Test-StudioUvCacheRootWritable" in ps1+ # Root AND buckets there, and at the launch repoint: the root can be writable while a+ # bucket uv renames into is not, which is what the candidate probe rejects a cache for.+ # A root-only question at either site hands back the cache the probe just refused.+ assert "_uv_cache_is_writable() {" in sh+ assert "function Test-StudioUvCacheUsable" in ps1+ sh_launch = sh.split("_prepare_studio_uv_cache_for_launch() {", 1)[1].split("\n}", 1)[0]+ assert "_uv_cache_is_writable" in sh_launch, sh_launch+ ps1_launch = ps1.split("function Set-StudioUvCacheForLaunch", 1)[1].split("\n }", 1)[0]+ assert "Test-StudioUvCacheUsable" in ps1_launch, ps1_launch+ # 6. creating the probe is not enough: uv RENAMES into these directories, and NTFS+ # carries DELETE as its own ACE while an append-only directory does the same on ext4,+ # so a root can grant create and deny unlink.+ root_sh = sh.split("_uv_cache_root_is_writable() {", 1)[1].split("\n}", 1)[0]+ # Judged by whether the probe is GONE, not by rm's exit status, and retried: a scanner+ # holding the handle makes one delete fail and the next succeed, and Remove-Item throws+ # for a probe something else already removed where rm -f exits 0.+ assert '[ -e "$_uv_root_probe" ] || break' in root_sh, root_sh+ assert "_uv_root_tries" in root_sh, root_sh+ root_ps1 = ps1.split("function Test-StudioUvCacheRootWritable", 1)[1].split("\n }", 1)[0]+ assert "[System.IO.File]::Exists($probe)" in root_ps1, root_ps1+ assert "$attempt -lt 3" in root_ps1, root_ps1+# The reset must precede both consumers, the selector that writes the marker and# every Exit-InstallFailure that restores it. Under `irm | iex` the script scope is# the caller's session, so only the entry point is ahead of both.@@ -1238,11 +1330,13 @@ class TestInstallUvCacheRootParity:assert '[ -L "$_uv_marker_file" ]' in body[unlink:write], body[unlink:write]ps1_marker = ps1[ps1.index("function Write-StudioUvCacheMarker") : ps1.index(- "function Set-StudioUvCacheEnvironment"+ "function Test-StudioUvNoCache")]- # One helper for both, or they disagree the moment UV_WORKING_DIR is set.- assert ps1.count("Resolve-StudioUvCachePath -Cache") == 2, ps1.count(+ # One helper for every path that must end up absolute, or they disagree the moment+ # UV_WORKING_DIR is set: the caller's value, the marker write, the marker READ, and+ # uv's own answer, which comes back verbatim and may be relative.+ assert ps1.count("Resolve-StudioUvCachePath -Cache") == 4, ps1.count("Resolve-StudioUvCachePath -Cache")assert "$env:UV_CACHE_DIR = Resolve-StudioUvCachePath -Cache $env:UV_CACHE_DIR" in ps1@@ -1291,14 +1385,25 @@ class TestInstallUvCacheRootParity:assert "${XDG_CACHE_HOME}/uv" in shassert "${HOME}/.cache/uv" in shassert 'Join-Path (Join-Path $env:LOCALAPPDATA "uv") "cache"' in ps1- selector = ps1.split("function Set-StudioUvCacheEnvironment", 1)[1].split(+ # The warmth scan lives in Test-StudioUvCachePopulated now, so slicing at+ # Set-StudioUvCacheEnvironment alone would assert on a body that no longer holds the+ # scan and pass for the wrong reason.+ selector = ps1.split("function Test-StudioUvBucketName", 1)[1].split("function Set-StudioUvCacheForLaunch", 1)[0]- assert "Get-ChildItem -LiteralPath $sharedCache -Directory -Force" in selector+ assert "Get-ChildItem -LiteralPath $Cache -Directory -Force" in selectorassert "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]+ # The scan only. The helpers after it DO use Stop, and have to: a marker or a write+ # probe that fails is an answer, where a bucket that cannot be read is not.+ # Ends at the next function, not two on: Test-StudioUvCacheRootWritable sits between+ # this scan and the marker reader, and it uses Stop deliberately, so a slice reaching+ # past it asserts the opposite of what this test says it is asserting.+ bucket_loop = selector.split("foreach ($bucket in $buckets)", 1)[1].split(+ "function Test-StudioUvCacheRootWritable", 1+ )[0]+ assert "-ErrorAction Stop" not in bucket_loop, bucket_loop# -L on the sh side for the same reason Get-ChildItem -Recurse follows links.assert "find -L " in shdiff --git a/tests/python/test_windows_python_venv_hardening.py b/tests/python/test_windows_python_venv_hardening.pyindex 2307abe0a4a..17d675c37d8 100644--- a/tests/python/test_windows_python_venv_hardening.py+++ b/tests/python/test_windows_python_venv_hardening.py@@ -128,6 +128,17 @@ def _uv_cache_functions(source: str) -> str:for name in ("Resolve-StudioUvCachePath","Write-StudioUvCacheMarker",+ # Every one of them must be listed. The selector's candidate loop treats any+ # failure as an uninspectable cache, so a helper missing here does not raise: it+ # turns every case in this file into "studio, could not be inspected", which reads+ # as a product bug.+ "Test-StudioUvNoCache",+ "Test-StudioUvBucketName",+ "Test-StudioUvCacheWritable",+ "Test-StudioUvCachePopulated",+ "Test-StudioUvCacheRootWritable",+ "Test-StudioUvCacheUsable",+ "Read-StudioUvCacheMarker","Set-StudioUvCacheEnvironment","Set-StudioUvCacheForLaunch","Restore-StudioUvCacheEnvironment",diff --git a/tests/python/test_windows_uv_cache_selection.py b/tests/python/test_windows_uv_cache_selection.pynew file mode 100644index 00000000000..2a21748d3f2--- /dev/null+++ b/tests/python/test_windows_uv_cache_selection.py@@ -0,0 +1,618 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""install.ps1 must select a uv cache by the same rules install.sh does.++install.sh and install.ps1 hold two copies of one decision, and the copies drift silently+because nothing runs them against the same inputs. tests/sh/test_uv_cache_adaptive_selection.sh+covers the POSIX half; this file is the Windows half, and it asserts BEHAVIOUR by running+install.ps1's own selector, not text.++The four rules below were added to install.sh first and did not exist in install.ps1. Measured+against install.ps1 before this file: a rerun on Windows abandoned a warm Studio cache the moment+one unrelated wheel made uv's default read as warm (re-downloading the Torch and CUDA bytes it+already held), UV_NO_CACHE still probed and recorded a cache uv was not using, `archive-v0.backup`+counted as warmth, and a populated-but-unwritable cache was selected -- which uv aborts on, so+that one failed the install outright.++Runs under pwsh on any OS: the selector is filesystem logic, and the Linux and macOS CI jobs+carry pwsh, so the Windows path is exercised on every platform CI has rather than only on the+Windows runners.+"""++from __future__ import annotations++import json+import os+import shutil+from pathlib import Path++import pytest++from unsloth_pwsh_runner import run_pwsh+++REPO_ROOT = Path(__file__).resolve().parents[2]+INSTALL_PS1 = REPO_ROOT / "install.ps1"++requires_pwsh = pytest.mark.skipif(shutil.which("pwsh") is None, reason = "PowerShell is unavailable")++# The selector and everything it calls, in source order. Sliced rather than copied, so a change to+# install.ps1 that this file does not expect fails here instead of passing against a stale paste.+_FIRST = " function Resolve-StudioUvCachePath {"+_LAST = " function Restore-StudioUvCacheEnvironment {"+++def _selector_source() -> str:+ source = INSTALL_PS1.read_text(encoding = "utf-8")+ start = source.index(_FIRST)+ end = source.index(_LAST)+ # Dedented one level: the functions live inside Install-UnslothStudio in the real file.+ return "\n".join(+ line[4:] if line.startswith(" ") else line for line in source[start:end].splitlines()+ )+++def _ps_literal(value: str) -> str:+ """A PowerShell single-quoted string.++ Not json.dumps: a JSON string is double-quoted, and PowerShell does not treat `\\` in a+ double-quoted string as an escape, so `C:\\Users\\x` arrives as a path with DOUBLED+ separators. Every Windows assertion in this file then compared a doubled path against a+ real one, and the whole file only passed because POSIX paths have no backslashes to+ double. A single-quoted PowerShell string is literal; `''` is the only escape it has.+ """+ return "'" + value.replace("'", "''") + "'"+++def _script(studio_root: Path, uv_stub: Path, isolated: bool) -> str:+ """Run the real selector once and print its verdict as JSON."""+ return f"""+$ErrorActionPreference = "Stop"+function step {{ param($a, $b, $c) }}+$script:StudioUvMarkerSaved = $false+$script:StudioUvMarkerExisted = $false+$script:StudioUvMarkerPrevious = $null+$script:StudioInstallCommitted = $false+{_selector_source()}+$root = {_ps_literal(str(studio_root))}+$stub = {_ps_literal(str(uv_stub))}+Set-StudioUvCacheEnvironment -StudioRoot $root -Isolated ${str(isolated).lower()} -UvExecutable $stub+$mode = $script:StudioUvCacheMode+$dir = $env:UV_CACHE_DIR+Set-StudioUvCacheForLaunch -StudioRoot $root+$markerFile = Join-Path (Join-Path $root "cache") "uv-cache-dir"+$marker = ""+if (Test-Path -LiteralPath $markerFile) {{+ $marker = (Get-Content -LiteralPath $markerFile -Raw).Trim()+}}+[pscustomobject]@{{ mode = $mode; dir = $dir; launch = $env:UV_CACHE_DIR; marker = $marker }} |+ ConvertTo-Json -Compress+"""+++def _select(+ studio_root: Path,+ uv_answer: str,+ *,+ isolated: bool = False,+ env: dict | None = None,+) -> dict:+ studio_root.mkdir(parents = True, exist_ok = True)+ # A .ps1 rather than a shell script, so this runs on the Windows agents too; `exit 0` so+ # $LASTEXITCODE is set, which is what the selector reads before trusting the answer.+ stub = studio_root.parent / "uv-stub.ps1"+ stub.write_text(f"Write-Output {_ps_literal(uv_answer)}\nexit 0\n", encoding = "utf-8")+ merged = {+ key: value+ for key, value in os.environ.items()+ if key not in ("UV_CACHE_DIR", "UV_NO_CACHE")+ }+ merged.update(env or {})+ # run_pwsh, not subprocess.run: a pwsh that dies at startup would read here as the selector+ # answering the wrong mode. See tests/_shared/unsloth_pwsh_runner.py.+ result = run_pwsh(+ ["pwsh", "-NoProfile", "-NonInteractive", "-Command", _script(studio_root, stub, isolated)],+ check = True,+ capture_output = True,+ text = True,+ env = merged,+ )+ return json.loads(result.stdout.strip().splitlines()[-1])+++def _warm(cache: Path) -> Path:+ """A cache holding package BYTES, which is the only thing that counts as warm."""+ (cache / "archive-v0" / "torch").mkdir(parents = True, exist_ok = True)+ (cache / "archive-v0" / "torch" / "libtorch.so").write_text("x")+ (cache / "CACHEDIR.TAG").write_text("x")+ return cache+++def _cold(cache: Path) -> Path:+ cache.mkdir(parents = True, exist_ok = True)+ (cache / "CACHEDIR.TAG").write_text("x")+ return cache+++def _record(studio_root: Path, cache: Path) -> None:+ (studio_root / "cache").mkdir(parents = True, exist_ok = True)+ (studio_root / "cache" / "uv-cache-dir").write_text(f"{cache}\n", encoding = "utf-8")+++# ── the modes that already worked, so a regression in the port is visible ──────────────────+++@requires_pwsh+def test_a_warm_default_is_reused_and_the_launch_repoints(tmp_path):+ default = _warm(tmp_path / "uvdefault")+ root = tmp_path / "studio"+ verdict = _select(root, str(default))+ assert verdict["mode"] == "shared", verdict+ assert verdict["dir"] == str(default), verdict+ # The install fills the shared cache; the launch must not leave the backend pointed at it.+ assert verdict["launch"] == str(root / "cache" / "uv"), verdict+ # And the marker names what the INSTALL used, which is what the update reads.+ assert verdict["marker"] == str(default), verdict+++@requires_pwsh+def test_a_cold_default_falls_back_to_the_studio_cache(tmp_path):+ verdict = _select(tmp_path / "studio", str(_cold(tmp_path / "uvdefault")))+ assert verdict["mode"] == "studio", verdict+ assert verdict["dir"] == str(tmp_path / "studio" / "cache" / "uv"), verdict+++@requires_pwsh+def test_metadata_only_is_not_warm(tmp_path):+ default = tmp_path / "uvdefault"+ (default / "wheels-v1").mkdir(parents = True)+ (default / "wheels-v1" / "index.msgpack").write_text("x")+ assert _select(tmp_path / "studio", str(default))["mode"] == "studio"+++@requires_pwsh+def test_a_caller_override_still_outranks_everything(tmp_path):+ mine = _warm(tmp_path / "mine")+ verdict = _select(+ tmp_path / "studio", str(_warm(tmp_path / "uvdefault")), env = {"UV_CACHE_DIR": str(mine)}+ )+ assert verdict["mode"] == "custom", verdict+ assert verdict["dir"] == str(mine), verdict+ # No repoint for a cache the caller chose.+ assert verdict["launch"] == str(mine), verdict+++@requires_pwsh+def test_isolation_wins_over_a_warm_default(tmp_path):+ root = tmp_path / "studio"+ verdict = _select(root, str(_warm(tmp_path / "uvdefault")), isolated = True)+ assert verdict["mode"] == "isolated", verdict+ assert verdict["dir"] == str(root / "cache" / "uv"), verdict+ # Isolation records too, or a previous install's marker outlives the choice.+ assert verdict["marker"] == str(root / "cache" / "uv"), verdict+++@requires_pwsh[email protected]("isolated", [False, True])+def test_uv_no_cache_records_nothing_even_when_the_directory_is_decided(tmp_path, isolated):+ """uv leaves the chosen directory completely empty under --no-cache.++ Both branches that pick a directory without probing returned before the no-cache check, so+ the marker named a cache this install never filled and the next repair could prefer it.+ """+ root = tmp_path / "studio"+ env = {"UV_NO_CACHE": "1"}+ if not isolated:+ env["UV_CACHE_DIR"] = str(tmp_path / "callercache")+ verdict = _select(root, str(_warm(tmp_path / "uvdefault")), isolated = isolated, env = env)+ assert verdict["mode"] == ("isolated" if isolated else "custom"), verdict+ assert verdict["marker"] == "", verdict+++@requires_pwsh[email protected]("isolated", [False, True])+def test_the_same_two_branches_do_record_without_uv_no_cache(tmp_path, isolated):+ """So the guard above is not simply switching recording off."""+ root = tmp_path / "studio"+ env = {} if isolated else {"UV_CACHE_DIR": str(tmp_path / "callercache")}+ verdict = _select(root, str(_warm(tmp_path / "uvdefault")), isolated = isolated, env = env)+ assert verdict["marker"] != "", verdict+++# ── the four rules install.sh gained and install.ps1 did not ───────────────────────────────+++@requires_pwsh+def test_a_warm_recorded_cache_outranks_uvs_default(tmp_path):+ """The rerun case. One unrelated wheel in uv's default must not cost a Torch redownload."""+ root = tmp_path / "studio"+ studio_cache = _warm(root / "cache" / "uv")+ _record(root, studio_cache)+ verdict = _select(root, str(_warm(tmp_path / "uvdefault")))+ # studio, not shared: the launch repoint only has to move a cache that is not already ours.+ assert verdict["mode"] == "studio", verdict+ assert verdict["dir"] == str(studio_cache), verdict+++@requires_pwsh+def test_a_recorded_cache_that_went_cold_loses_to_the_default(tmp_path):+ """...and a machine that really has moved on still reaches the shared cache."""+ root = tmp_path / "studio"+ _record(root, tmp_path / "vanished")+ default = _warm(tmp_path / "uvdefault")+ assert _select(root, str(default))["dir"] == str(default)+++@requires_pwsh+def test_isolation_still_wins_over_a_warm_marker(tmp_path):+ root = tmp_path / "studio"+ _record(root, _warm(root / "cache" / "uv"))+ assert _select(root, str(_warm(tmp_path / "uvdefault")), isolated = True)["mode"] == "isolated"+++@requires_pwsh[email protected]("value", ["1", "y", "Y", "t", "T", "true", "TRUE", "Yes", "on"])+def test_uv_no_cache_stands_the_selection_down(tmp_path, value):+ root = tmp_path / "studio"+ verdict = _select(root, str(_warm(tmp_path / "uvdefault")), env = {"UV_NO_CACHE": value})+ assert verdict["mode"] == "studio", verdict+ # Nothing recorded: a marker written here would name a cache this install never filled.+ assert verdict["marker"] == "", verdict+++@requires_pwsh[email protected]("value", ["0", "false", "off", "no", ""])+def test_a_false_uv_no_cache_does_not_stand_it_down(tmp_path, value):+ root = tmp_path / "studio"+ assert (+ _select(root, str(_warm(tmp_path / "uvdefault")), env = {"UV_NO_CACHE": value})["mode"]+ == "shared"+ )+++@requires_pwsh[email protected]("name", ["archive-v0.backup", "archive-backup-v0", "archive-v0.tar.gz"])+def test_a_bucket_lookalike_is_not_warmth(tmp_path, name):+ """`archive-*` matches all three, and uv can reuse the bytes in none of them."""+ default = tmp_path / "uvdefault"+ (default / name / "pkg").mkdir(parents = True)+ (default / name / "pkg" / "payload.so").write_text("x")+ (default / "CACHEDIR.TAG").write_text("x")+ assert _select(tmp_path / "studio", str(default))["mode"] == "studio"+++@requires_pwsh+def test_a_studio_cache_with_an_unusable_bucket_is_not_a_fallback(tmp_path):+ """The root can be writable while a bucket uv renames into is not.++ A file where a bucket belongs is an existing path to the create uv makes, so uv refuses it.+ Selecting that cache anyway turns an install that reported success into a uv error.+ """+ root = tmp_path / "studio"+ (root / "cache" / "uv").mkdir(parents = True)+ (root / "cache" / "uv" / "archive-v0").write_text("not a directory")+ cold = tmp_path / "colddefault"+ cold.mkdir()+ verdict = _select(root, str(cold))+ assert verdict["mode"] == "shared", verdict+ assert verdict["dir"] == str(cold), verdict+++@requires_pwsh+def test_the_launch_does_not_repoint_into_a_rejected_studio_cache(tmp_path):+ """Selection already preferred the warm cache here; the repoint used to hand the backend+ the Studio cache regardless, because it only asked about the root."""+ root = tmp_path / "studio"+ (root / "cache" / "uv").mkdir(parents = True)+ (root / "cache" / "uv" / "archive-v0").write_text("not a directory")+ default = _warm(tmp_path / "uvdefault")+ verdict = _select(root, str(default))+ assert verdict["mode"] == "shared", verdict+ assert verdict["launch"] == str(default), verdict+++@requires_pwsh+def test_an_intact_studio_cache_is_still_the_ordinary_answer(tmp_path):+ """So the two cases above are not simply switching the Studio cache off."""+ cold = tmp_path / "colddefault"+ cold.mkdir()+ assert _select(tmp_path / "studio", str(cold))["mode"] == "studio"+++@requires_pwsh+def test_a_marker_naming_a_deleted_cache_is_no_more_evidence_than_none(tmp_path):+ """A stale pointer is not a decision, so it gets the same ordering as an absent marker:+ behind uv's default when that is warm, ahead of it when it is cold."""+ # A fresh root per half: the selector RECORDS its choice, so a second call against the+ # same root is no longer reading a stale marker.+ warm_root = tmp_path / "studio-warm"+ _warm(warm_root / "cache" / "uv")+ (warm_root / "cache" / "uv-cache-dir").write_text(+ str(tmp_path / "deleted-cache"), encoding = "utf-8"+ )+ chosen = _select(warm_root, str(_warm(tmp_path / "uvdefault")))+ assert chosen["mode"] == "shared", chosen++ cold_root = tmp_path / "studio-cold"+ studio_cache = _warm(cold_root / "cache" / "uv")+ (cold_root / "cache" / "uv-cache-dir").write_text(+ str(tmp_path / "deleted-cache"), encoding = "utf-8"+ )+ cold = tmp_path / "colddefault"+ cold.mkdir()+ chosen = _select(cold_root, str(cold))+ assert chosen["mode"] == "studio", chosen+ assert chosen["dir"].rstrip("\\/") == str(studio_cache).rstrip("\\/"), chosen+++@requires_pwsh+def test_a_cold_recorded_cache_that_still_exists_falls_through(tmp_path):+ """The other half of the same rule: a machine that really has moved on still gets shared."""+ root = tmp_path / "studio"+ _warm(root / "cache" / "uv")+ cold = tmp_path / "coldrec"+ cold.mkdir()+ (root / "cache" / "uv-cache-dir").write_text(str(cold), encoding = "utf-8")+ assert _select(root, str(_warm(tmp_path / "uvdefault")))["mode"] == "shared"+++@requires_pwsh+def test_a_real_bucket_beside_a_lookalike_is_still_warm(tmp_path):+ default = _warm(tmp_path / "uvdefault")+ (default / "archive-v0.backup").mkdir()+ (default / "archive-v0.tar.gz").write_text("x")+ assert _select(tmp_path / "studio", str(default))["mode"] == "shared"+++@requires_pwsh+ os.name == "nt", reason = "mode bits; the Windows ACL equivalent needs a second account"+)+ os.geteuid() == 0 if hasattr(os, "geteuid") else False,+ reason = "root writes through the mode bits",+)+def test_a_populated_cache_we_cannot_write_is_refused(tmp_path):+ """uv renames distributions into the buckets and aborts when it cannot, so selecting one+ we cannot write fails the install rather than saving a download."""+ default = _warm(tmp_path / "uvdefault")+ default.chmod(0o555)+ try:+ verdict = _select(tmp_path / "studio", str(default))+ finally:+ default.chmod(0o755)+ assert verdict["mode"] == "studio", verdict+++@requires_pwsh+ os.name == "nt", reason = "mode bits; the Windows ACL equivalent needs a second account"+)+ os.geteuid() == 0 if hasattr(os, "geteuid") else False,+ reason = "root writes through the mode bits",+)+def test_an_unwritable_bucket_is_refused_too(tmp_path):+ """The `sudo -E` leftover: the root is ours and one bucket is not."""+ default = _warm(tmp_path / "uvdefault")+ (default / "builds-v0").mkdir()+ (default / "builds-v0").chmod(0o555)+ try:+ verdict = _select(tmp_path / "studio", str(default))+ finally:+ (default / "builds-v0").chmod(0o755)+ assert verdict["mode"] == "studio", verdict+++@requires_pwsh+def test_the_write_probe_leaves_nothing_behind(tmp_path):+ """It writes into a cache uv is about to fill, and into the user's own shared one."""+ default = _warm(tmp_path / "uvdefault")+ _select(tmp_path / "studio", str(default))+ assert not list(default.rglob(".unsloth-write-probe.*"))+++@requires_pwsh+def test_a_lost_and_found_does_not_condemn_the_cache(tmp_path):+ """A cache-dir pointed at a mount point carries one, and uv never writes it."""+ default = _warm(tmp_path / "uvdefault")+ (default / "lost+found").mkdir()+ if os.name != "nt":+ (default / "lost+found").chmod(0o000)+ try:+ assert _select(tmp_path / "studio", str(default))["mode"] == "shared"+ finally:+ if os.name != "nt":+ (default / "lost+found").chmod(0o755)+++@requires_pwsh+def test_a_bucket_that_is_not_a_directory_is_refused(tmp_path):+ """A file where a bucket goes is an existing path to the create uv makes, which fails."""+ default = _warm(tmp_path / "uvdefault")+ (default / "builds-v0").write_text("not a directory")+ assert _select(tmp_path / "studio", str(default))["mode"] == "studio"+++# ── the installed base, and the ways the candidate loop can be knocked over ────────────────+++@requires_pwsh+def test_an_unmarked_warm_studio_cache_is_kept_when_the_default_is_cold(tmp_path):+ """An install from before the marker can hold gigabytes of Torch and CUDA in the Studio+ cache with nothing recording it, and abandoning that costs the downloads again.++ It is the LAST candidate though, behind uv's default: the marker arrived in b66d2a4c8 and+ the installer's early UV_CACHE_DIR block only in e12963071 the day after, so an install+ with no marker is old enough that `shared` was reachable, and there the launch repoint+ leaves backend wheels in the Studio cache while the real bytes sit in the default.+ """+ root = tmp_path / "studio"+ studio_cache = _warm(root / "cache" / "uv")+ cold = tmp_path / "colddefault"+ cold.mkdir()+ verdict = _select(root, str(cold))+ assert verdict["mode"] == "studio", verdict+ assert verdict["dir"] == str(studio_cache), verdict+++@requires_pwsh+def test_a_warm_default_outranks_an_unmarked_studio_cache(tmp_path):+ """The other half of the same rule, and what the CLI updater has always done."""+ root = tmp_path / "studio"+ _warm(root / "cache" / "uv")+ default = _warm(tmp_path / "uvdefault")+ verdict = _select(root, str(default))+ assert verdict["mode"] == "shared", verdict+ assert verdict["dir"] == str(default), verdict+++@requires_pwsh+def test_an_unmarked_cold_studio_cache_does_not_block_the_shared_one(tmp_path):+ root = tmp_path / "studio"+ _cold(root / "cache" / "uv")+ default = _warm(tmp_path / "uvdefault")+ verdict = _select(root, str(default))+ assert verdict["mode"] == "shared", verdict+ assert verdict["dir"] == str(default), verdict+++@requires_pwsh+ os.name == "nt", reason = "mode bits; the Windows ACL equivalent needs a second account"+)+ os.geteuid() == 0 if hasattr(os, "geteuid") else False,+ reason = "root reads through the mode bits",+)+def test_a_marker_we_cannot_even_stat_does_not_cost_us_uvs_default(tmp_path):+ """Test-Path throws inside an ACL-denied directory under ErrorActionPreference = Stop, and+ the selector wraps the whole candidate loop, so an unreachable marker used to take uv's+ default down with it -- a first run elevated, a second one not."""+ locked = tmp_path / "locked"+ (locked / "uv").mkdir(parents = True)+ locked.chmod(0o000)+ root = tmp_path / "studio"+ _record(root, locked / "uv")+ default = _warm(tmp_path / "uvdefault")+ try:+ verdict = _select(root, str(default))+ finally:+ locked.chmod(0o755)+ assert verdict["mode"] == "shared", verdict+ assert verdict["dir"] == str(default), verdict+++@requires_pwsh+def test_a_trailing_separator_in_the_marker_is_the_same_directory(tmp_path):+ """Otherwise it compares unequal to the Studio cache and gets the launch repoint that the+ studio branch exists to avoid."""+ root = tmp_path / "studio"+ studio_cache = _warm(root / "cache" / "uv")+ (root / "cache" / "uv-cache-dir").write_text(f"{studio_cache}{os.sep}\n", encoding = "utf-8")+ assert _select(root, str(_warm(tmp_path / "uvdefault")))["mode"] == "studio"+++@requires_pwsh+ os.name == "nt", reason = "mode bits; the Windows ACL equivalent needs a second account"+)+ os.geteuid() == 0 if hasattr(os, "geteuid") else False,+ reason = "root writes through the mode bits",+)+def test_the_launch_does_not_repoint_at_a_studio_cache_it_cannot_fill(tmp_path):+ """Repointing at a cache uv aborts on hands the autostarted backend a dead cache after an+ install that succeeded. The shared cache is the one this install actually filled."""+ root = tmp_path / "studio"+ root.mkdir()+ default = _warm(tmp_path / "uvdefault")+ root.chmod(0o555)+ try:+ verdict = _select(root, str(default))+ finally:+ root.chmod(0o755)+ assert verdict["mode"] == "shared", verdict+ assert verdict["launch"] == str(default), verdict+++@requires_pwsh+ os.name == "nt", reason = "mode bits; the Windows ACL equivalent needs a second account"+)+ os.geteuid() == 0 if hasattr(os, "geteuid") else False,+ reason = "root writes through the mode bits",+)+def test_a_fallback_we_cannot_write_is_not_a_fallback(tmp_path):+ """The probe refuses a whole cache for one bucket uv may never touch, so a warm cache and an+ unwritable Studio root can both be on the table. Landing on the Studio root is a certain+ failure; the refused cache is only a suspect one."""+ default = _warm(tmp_path / "uvdefault")+ (default / "builds-v0").mkdir()+ (default / "builds-v0").chmod(0o555)+ root = tmp_path / "studio"+ root.mkdir()+ root.chmod(0o555)+ try:+ verdict = _select(root, str(default))+ finally:+ root.chmod(0o755)+ (default / "builds-v0").chmod(0o755)+ assert verdict["mode"] == "shared", verdict+ assert verdict["dir"] == str(default), verdict+ assert verdict["launch"] == str(default), verdict+++@requires_pwsh+ os.name == "nt", reason = "mode bits; the Windows ACL equivalent needs a second account"+)+ os.geteuid() == 0 if hasattr(os, "geteuid") else False,+ reason = "root writes through the mode bits",+)+def test_a_writable_studio_cache_still_wins_over_a_refused_one(tmp_path):+ """The rule above must not turn into "a refused cache always wins"."""+ default = _warm(tmp_path / "uvdefault")+ (default / "builds-v0").mkdir()+ (default / "builds-v0").chmod(0o555)+ try:+ verdict = _select(tmp_path / "studio", str(default))+ finally:+ (default / "builds-v0").chmod(0o755)+ assert verdict["mode"] == "studio", verdict+ assert verdict["dir"] == str(tmp_path / "studio" / "cache" / "uv"), verdict+++# ── the harness's own guard ────────────────────────────────────────────────────────────────+++@requires_pwsh+ "value",+ [+ r"C:\Users\runneradmin\AppData\Local\Temp\studio\cache\uv",+ r"\\server\share\uv",+ "/tmp/plain/posix/uv",+ "with a space/uv",+ "with'a'quote/uv",+ ],+)+def test_the_harness_hands_powershell_the_path_it_was_given(value):+ """A path handed to pwsh must arrive byte-identical.++ json.dumps looked right and was not: a JSON string is double-quoted, and PowerShell does+ not read `\\` in a double-quoted string as an escape, so every Windows path arrived with+ DOUBLED separators and every assertion in this file compared a doubled path against a real+ one. It passed anyway on Linux and macOS, where paths have no backslashes to double, so+ only a Windows runner could see it. This case is the Windows runner, in one line.+ """+ result = run_pwsh(+ ["pwsh", "-NoProfile", "-NonInteractive", "-Command", f"Write-Output {_ps_literal(value)}"],+ check = True,+ capture_output = True,+ text = True,+ )+ assert result.stdout.strip("\r\n") == valuediff --git a/tests/sh/test_install_uv_cache_root.sh b/tests/sh/test_install_uv_cache_root.shindex b07a748924b..18a807405c7 100644--- a/tests/sh/test_install_uv_cache_root.sh+++ b/tests/sh/test_install_uv_cache_root.sh@@ -12,13 +12,18 @@ HELPERS=$(awk '/^_configure_uv_cache\(\) \{/ { grab = 1 }/^_prepare_studio_uv_cache_for_launch\(\) \{/ { grab = 1 }/^_record_uv_cache_choice\(\) \{/ { grab = 1 }+ /^_uv_is_bucket_name\(\) \{/ { grab = 1 }+ /^_uv_no_cache_requested\(\) \{/ { grab = 1 }+ /^_uv_cache_root_is_writable\(\) \{/ { grab = 1 }+ /^_uv_cache_is_writable\(\) \{/ { grab = 1 }/^_absolutize_uv_cache_dir\(\) \{/ { grab = 1 }/^_restore_uv_cache_marker\(\) \{/ { grab = 1 }grab { print }grab && /^}/ { grab = 0 }' "$INSTALL_SH")for _helper in _configure_uv_cache _prepare_studio_uv_cache_for_launch _record_uv_cache_choice \- _restore_uv_cache_marker _absolutize_uv_cache_dir; do+ _restore_uv_cache_marker _absolutize_uv_cache_dir _uv_is_bucket_name \+ _uv_cache_root_is_writable _uv_cache_is_writable _uv_no_cache_requested; doif ! printf '%s\n' "$HELPERS" | grep -q "^${_helper}() {"; thenecho " FAIL: could not extract $_helper from install.sh"exit 1@@ -82,6 +87,15 @@ run_case() { # shell, label, state, input, isolate, home, xdg-state, xdg, root,_mode=$3_message=$4_launch=$5+ # The marker is a selector INPUT now (an install reuses the cache it recorded), and these+ # cases share one studio root, so each starts from the state _PRESET_MARKER asks for.+ if [ "${_KEEP_MARKER:-0}" != 1 ]; then+ rm -f "$_root/cache/uv-cache-dir" 2>/dev/null || true+ if [ -n "${_PRESET_MARKER:-}" ]; then+ mkdir -p "$_root/cache" 2>/dev/null || true+ printf '%s\n' "$_PRESET_MARKER" > "$_root/cache/uv-cache-dir" 2>/dev/null || true+ fi+ fi_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")@@ -270,6 +284,40 @@ for shell in sh bash; do"$STUDIO_CACHE"check_marker "shared mode records the shared cache, not the Studio one" "$BUILDS_CACHE"+ # A rerun must not abandon the cache this install recorded while it is still warm: uv's+ # default reads as warm on ONE unrelated wheel, and switching re-downloads Torch and CUDA.+ mkdir -p "$STUDIO_CACHE/archive-v0/torch"+ : > "$STUDIO_CACHE/archive-v0/torch/libtorch.so"+ _PRESET_MARKER="$STUDIO_CACHE"+ run_case "$shell" "a warm recorded Studio cache outranks a warm default" unset "" false \+ "$HOME_DIR" unset "" "$ROOT" "$BUILDS_CACHE" "$STUDIO_CACHE" studio \+ "reusing this install's Studio cache ($STUDIO_CACHE)" "$STUDIO_CACHE"+ # ...and it does NOT outrank an explicit isolation request.+ run_case "$shell" "isolation still wins over a warm marker" unset "" true \+ "$HOME_DIR" unset "" "$ROOT" "$BUILDS_CACHE" "$STUDIO_CACHE" isolated \+ "forced Studio cache isolation ($STUDIO_CACHE); already-cached packages may download again" \+ "$STUDIO_CACHE"+ # A marker naming a cache that EXISTS and is no longer warm loses to uv's default, so a+ # machine that really has moved on still reaches the shared cache.+ mkdir -p "$CASE/coldrec/uv"+ _PRESET_MARKER="$CASE/coldrec/uv"+ run_case "$shell" "a cold recorded cache falls through to shared" 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"+ # A marker naming a directory that is GONE used to be treated the same, but it is a stale+ # pointer, not a decision. Treating it as one abandoned cached Torch and CUDA for uv's+ # default, which offline is an install that used to succeed and then failed.+ _PRESET_MARKER="$CASE/gone/uv"+ run_case "$shell" "a marker naming a deleted cache keeps Studio" unset "" false \+ "$HOME_DIR" unset "" "$ROOT" "$STUDIO_CACHE" "$STUDIO_CACHE" studio \+ "reusing this install's Studio cache ($STUDIO_CACHE)" \+ "$STUDIO_CACHE"+ _PRESET_MARKER=""+ rm -rf "$STUDIO_CACHE"++ # These cases drive the marker themselves, so the per-case reset stands down.+ _KEEP_MARKER=1rm -f "$MARKER"run_case "$shell" "isolation still forces the Studio cache" unset "" true \"$HOME_DIR" unset "" "$ROOT" "$BUILDS_CACHE" "$STUDIO_CACHE" isolated \@@ -315,6 +363,8 @@ for shell in sh bash; dofifi+ _KEEP_MARKER=0+# uv resolves a relative cache against its own working directory, which --directory# and UV_WORKING_DIR move.rm -rf "$ROOT/cache"@@ -443,13 +493,76 @@ EXPORTEDbad "$shell: custom cache exported as [$_exp], wanted [$CASE/relcache]"fi+ # UV_NO_CACHE leaves the caller's UV_CACHE_DIR completely empty, CACHEDIR.TAG included+ # (checked against uv 0.10.7), so recording it would point the next repair at a cache this+ # install never filled. Both branches that choose a directory without probing have to ask.+ NOCACHE_PROBE="$WORK/$shell nocache.sh"+ for _nc_mode in custom isolated; do+ {+ printf '%s\n' "$HELPERS"+ cat <<NOCACHED+step() { :; }+substep() { :; }+STUDIO_HOME='$ROOT'+_UV_MARKER_SAVED=false+UV_NO_CACHE=1+export UV_NO_CACHE+NOCACHED+ if [ "$_nc_mode" = custom ]; then+ printf "UV_CACHE_DIR='%s'\n_ISOLATE_UV_CACHE=false\n" "$OVERRIDE"+ else+ printf "unset UV_CACHE_DIR\n_ISOLATE_UV_CACHE=true\n"+ fi+ printf '%s\n' '_configure_uv_cache' 'printf "%s" "$_UV_CACHE_MODE"'+ } > "$NOCACHE_PROBE"+ rm -f "$MARKER"+ _nc_out=$($shell "$NOCACHE_PROBE")+ if [ "$_nc_out" = "$_nc_mode" ] && [ ! -e "$MARKER" ]; then+ ok "$shell: $_nc_mode under UV_NO_CACHE records nothing"+ else+ bad "$shell: $_nc_mode under UV_NO_CACHE (mode [$_nc_out], marker [$(cat "$MARKER" 2>/dev/null)])"+ fi+ done+ # ...and with UV_NO_CACHE absent the same two branches still record, so the guard above is+ # not simply switching recording off.+ for _nc_mode in custom isolated; do+ {+ printf '%s\n' "$HELPERS"+ cat <<RECORDED+step() { :; }+substep() { :; }+STUDIO_HOME='$ROOT'+_UV_MARKER_SAVED=false+unset UV_NO_CACHE+RECORDED+ if [ "$_nc_mode" = custom ]; then+ printf "UV_CACHE_DIR='%s'\n_ISOLATE_UV_CACHE=false\n" "$OVERRIDE"+ else+ printf "unset UV_CACHE_DIR\n_ISOLATE_UV_CACHE=true\n"+ fi+ printf '%s\n' '_configure_uv_cache' 'printf "%s" "$_UV_CACHE_MODE"'+ } > "$NOCACHE_PROBE"+ rm -f "$MARKER"+ _nc_out=$($shell "$NOCACHE_PROBE")+ if [ "$_nc_out" = "$_nc_mode" ] && [ -s "$MARKER" ]; then+ ok "$shell: $_nc_mode still records without UV_NO_CACHE"+ else+ bad "$shell: $_nc_mode without UV_NO_CACHE (mode [$_nc_out], marker [$(cat "$MARKER" 2>/dev/null)])"+ fi+ done+ rm -f "$MARKER"+# An unwritable STUDIO_HOME is a reason to skip the marker, never to fail the install.rm -rf "$ROOT/cache"if [ "$(id -u 2>/dev/null || echo 0)" != 0 ] && mkdir -p "$ROOT" && chmod 500 "$ROOT" 2>/dev/null; then+ # ...and the launch keeps the shared cache rather than repointing at the Studio one.+ # The only way shared is reachable with an unwritable root: the early block must have+ # failed its own write probe for the selection to run at all. Repointing would hand the+ # autostarted backend a cache uv aborts on, after an install that just succeeded.run_case "$shell" "an unwritable Studio root still installs" 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"+ "$BUILDS_CACHE"chmod 755 "$ROOT" 2>/dev/null || truefidonediff --git a/tests/sh/test_strixhalo_wsl_reroute.sh b/tests/sh/test_strixhalo_wsl_reroute.shindex 9c9b04cf210..694100b4b65 100644--- a/tests/sh/test_strixhalo_wsl_reroute.sh+++ b/tests/sh/test_strixhalo_wsl_reroute.sh@@ -326,6 +326,27 @@ assert_contains "non-tauri child fail -> CPU fallback" "$_out" "__NORassert_contains "non-tauri child fail -> skip ROCm bootstrap" "$_out" "SKIP_ROCM=1"rm -rf "$_d"+# 29) UV_CACHE_DIR: only a CALLER's override is portable. The installer's own default is a+# path in the ORIGIN distro, and forwarding it pins the child to `custom`, which skips+# its adaptive cache selection and outranks its --isolated-uv-cache.+_d=$(make_fixture 1 strix 0 26.04 1)+_out=$(run_func "$_d" UV_CACHE_DIR=/home/someone/.unsloth/studio/cache/uv \+ _UV_CACHE_DIR_INSTALLER_DEFAULT=true)+assert_contains "installer default is not forwarded" "$_out" "unset UV_CACHE_DIR"+assert_absent "installer default is not exported" "$_out" "export UV_CACHE_DIR="+rm -rf "$_d"++_d=$(make_fixture 1 strix 0 26.04 1)+_out=$(run_func "$_d" UV_CACHE_DIR=/mnt/shared/uv \+ _UV_CACHE_DIR_INSTALLER_DEFAULT=false)+assert_contains "a caller's override is forwarded" "$_out" "export UV_CACHE_DIR='/mnt/shared/uv'"+rm -rf "$_d"++_d=$(make_fixture 1 strix 0 26.04 1)+_out=$(run_func "$_d" UV_CACHE_DIR=)+assert_contains "an unset cache stays unset" "$_out" "unset UV_CACHE_DIR"+rm -rf "$_d"+echo ""echo "Results: $PASS passed, $FAIL failed"[ "$FAIL" -eq 0 ] || exit 1diff --git a/tests/sh/test_uv_cache_adaptive_selection.sh b/tests/sh/test_uv_cache_adaptive_selection.shnew file mode 100755index 00000000000..91eedf61274--- /dev/null+++ b/tests/sh/test_uv_cache_adaptive_selection.sh@@ -0,0 +1,523 @@+#!/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+#+# Guards that _configure_uv_cache's adaptive selection is REACHABLE. Both halves of install.sh+# read correctly on their own and the defect lived in the ORDER they run, so this runs the early+# UV_CACHE_DIR block and _configure_uv_cache in that order rather than inspecting either half.+#+# The contract:+# * caller-set UV_CACHE_DIR -> custom, left exactly as the caller wrote it+# * unset, uv's default is populated -> shared, and the launch repoint becomes live+# * unset, uv's default is empty -> studio+# * populated but not writable, root or bucket -> studio; uv aborts on either+# * a relative cache-dir -> resolved against UV_WORKING_DIR before scanning+# * a bucket too big for one pipe read -> still warm, pipefail or not+# * a caller's set -f -> the scan still expands its own globs+# * a dangling bucket link -> studio; mkdir(2) answers EEXIST on it+# * a bucket-name lookalike -> ignored; only <kind>-v<N> is uv's to write+# * a name ending in `-v` -> ignored; the version cannot be empty+# * UV_NO_CACHE -> studio, with nothing probed or recorded+# * --isolated-uv-cache -> isolated, whatever else is true+# * unwritable STUDIO_HOME -> the early block unsets, and the choice still runs+# * an unmarked warm Studio cache -> kept; that is every install from before the marker+# * a BOM/CRLF marker -> honoured; install.ps1 writes one, WSL shares a home+# * a trailing slash in the marker -> the same directory, so still `studio`+# * shared with an unwritable root -> the launch keeps the shared cache, not a dead one+# * every shell that can be /bin/sh -> same answers, with and without errexit+set -e++SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+. "$SCRIPT_DIR/_harness.sh"+INSTALL_SH="$SCRIPT_DIR/../../install.sh"++_TMP=$(mktemp -d)+_EARLY=$(mktemp)+_BOOT=$(mktemp)+_FN=$(mktemp)+trap 'rm -rf "$_TMP" "$_EARLY" "$_FN" "$_BOOT"' EXIT++# The real code, anchored on text that PREDATES the fix so this suite also runs against the+# old code and fails on an assertion, not on an empty extraction.+awk '/^# Keep uv.s cache on the same filesystem as the venv it fills\.$/,/^fi$/' \+ "$INSTALL_SH" > "$_EARLY"+awk '/^_configure_uv_cache\(\) \{$/,/^\}$/' "$INSTALL_SH" > "$_FN"+awk '/^_prepare_studio_uv_cache_for_launch\(\) \{$/,/^\}$/' "$INSTALL_SH" >> "$_FN"+awk '/^_absolutize_uv_cache_dir\(\) \{$/,/^\}$/' "$INSTALL_SH" >> "$_FN"+awk '/^_uv_is_bucket_name\(\) \{$/,/^\}$/' "$INSTALL_SH" >> "$_FN"+awk '/^_uv_no_cache_requested\(\) \{$/,/^\}$/' "$INSTALL_SH" >> "$_FN"+awk '/^_uv_cache_root_is_writable\(\) \{$/,/^\}$/' "$INSTALL_SH" >> "$_FN"+awk '/^_uv_cache_is_writable\(\) \{$/,/^\}$/' "$INSTALL_SH" >> "$_FN"++if ! grep -q 'UV_CACHE_DIR="\$STUDIO_HOME/cache/uv"' "$_EARLY"; then+ echo "FAIL: could not extract the early UV_CACHE_DIR block from install.sh"+ exit 1+fi+if ! grep -q '_UV_CACHE_MODE=shared' "$_FN"; then+ echo "FAIL: could not extract _configure_uv_cache from install.sh"+ exit 1+fi+# Extracting the pieces is not the same as being able to RUN them: a helper this harness has+# not defined yet exits 127, `if !` reads that as an unwritable cache, and the block unsets the+# default every ordering case below depends on. The suite would pass while testing nothing.+# Built ONCE and sourced by the runner and the check alike, so the order is stated in one+# place. A check that repeats the order instead of sharing it stays green while the runner does+# something else, which is how this went unnoticed.+cat "$_FN" "$_EARLY" > "$_BOOT"+_selfcheck=$(+ STUDIO_HOME=$(mktemp -d "$_TMP/selfcheck.XXXXXX")+ export STUDIO_HOME+ unset UV_CACHE_DIR+ . "$_BOOT" 2>/dev/null+ printf '%s' "${UV_CACHE_DIR:-<unset>}"+)+# Only that the block kept a cache it could create, NOT that the installer-default flag is+# true: that flag is what this branch adds, and this suite must keep running against code that+# predates it.+case "$_selfcheck" in+ */cache/uv) ;;+ *)+ echo "FAIL: the early block did not keep its own default in this harness ($_selfcheck)."+ echo " Every case below would run as though the cache were unwritable."+ exit 1+ ;;+esac+unset _selfcheck++_SH="${BASH:-/bin/bash}"++# $_BOOT is _FN then _EARLY, install.sh's own order: the helpers are defined around line 622+# and the early block RUNS at line 1001. Reversed, its call to _uv_cache_root_is_writable names+# a command that does not exist yet, and every unset-UV_CACHE_DIR case stops exercising the+# ordering bug this suite exists for.++# $1 = STUDIO_HOME, $2 = preset UV_CACHE_DIR ("" for unset), $3 = uv's default cache dir,+# $4 = "true" to isolate, $5 = UV_WORKING_DIR (also runs from $_TMP/cwd, so a relative $3+# resolved against the wrong base is visible), $6 = "true" to run under pipefail, $7 = "true"+# to run under set -f, $8 = "true" to run under set -e.+# Prints "<mode> <UV_CACHE_DIR> <after-launch-repoint>".+_run() {+ _stub_bin=$(mktemp -d)+ printf '#!/bin/sh\ncase "$1 $2" in "cache dir") printf "%%s\\n" "%s" ;; esac\n' \+ "$3" > "$_stub_bin/uv"+ chmod +x "$_stub_bin/uv"+ "$_SH" -c "+ [ '${8:-false}' = true ] && set -e+ [ '${6:-false}' = true ] && set -o pipefail+ [ '${7:-false}' = true ] && set -f+ STUDIO_HOME='$1'+ _ISOLATE_UV_CACHE='${4:-false}'+ if [ -n '$2' ]; then UV_CACHE_DIR='$2'; export UV_CACHE_DIR; else unset UV_CACHE_DIR; fi+ if [ -n '${5:-}' ]; then+ UV_WORKING_DIR='${5:-}'; export UV_WORKING_DIR; cd '$_TMP/cwd'+ else+ unset UV_WORKING_DIR+ fi+ # Stubs for the surface _configure_uv_cache leans on, and nothing more: the point is to+ # run the real selection, not a paraphrase of it.+ step() { :; }+ _record_uv_cache_choice() { :; }+ C_WARN=''+ # A real file on PATH, not a shell function: the probe runs env, which execs a binary,+ # so a function is skipped and the host's own uv answers. That is how the first version+ # of this test passed against the wrong cache.+ PATH='$_stub_bin':\"\$PATH\"+ . '$_BOOT'+ _configure_uv_cache >/dev/null 2>&1+ _mode=\"\${_UV_CACHE_MODE:-<none>}\"+ _dir=\"\${UV_CACHE_DIR:-<unset>}\"+ _prepare_studio_uv_cache_for_launch+ printf '%s %s %s' \"\$_mode\" \"\$_dir\" \"\${UV_CACHE_DIR:-<unset>}\"+ "+ rm -rf "$_stub_bin"+}++# Warm means package BYTES, not buckets: the probe skips .msgpack/.http metadata.+_populated="$_TMP/uvdefault"+mkdir -p "$_populated/archive-v0/torch"+: > "$_populated/archive-v0/torch/libtorch.so"+# Every fixture below carries the CACHEDIR.TAG uv writes at the root of a cache it has+# initialized, so a rule that trips over a non-directory entry cannot pass here.+: > "$_populated/CACHEDIR.TAG"+# Metadata only, which must NOT read as warm; that is why the probe looks at file names.+_metadata_only="$_TMP/uvmeta"+mkdir -p "$_metadata_only/wheels-v1"+: > "$_metadata_only/wheels-v1/index.msgpack"+: > "$_metadata_only/CACHEDIR.TAG"+_empty="$_TMP/uvempty"+mkdir -p "$_empty"+# Only the ROOT is closed, so this still reads as warm; uv cannot rewrite CACHEDIR.TAG in it.+_readonly="$_TMP/uvro"+mkdir -p "$_readonly/archive-v0/torch"+: > "$_readonly/archive-v0/torch/libtorch.so"+chmod a-w "$_readonly"+# The root is ours but a bucket is not, which is what a `sudo -E` run leaves behind.+_readonly_bucket="$_TMP/uvrobucket"+mkdir -p "$_readonly_bucket/archive-v0/torch" "$_readonly_bucket/wheels-v6"+: > "$_readonly_bucket/wheels-v6/index.msgpack"+: > "$_readonly_bucket/archive-v0/torch/libtorch.so"+chmod a-w "$_readonly_bucket/archive-v0"+# A bucket AFTER the one holding the artifact still has to be probed.+_readonly_late="$_TMP/uvrolate"+mkdir -p "$_readonly_late/archive-v0/torch" "$_readonly_late/sdists-v9"+: > "$_readonly_late/archive-v0/torch/libtorch.so"+chmod a-w "$_readonly_late/sdists-v9"+# Unenterable is unwritable: uv would still have to rename into the bucket it cannot open.+_denied_bucket="$_TMP/uvdenied"+mkdir -p "$_denied_bucket/archive-v0" "$_denied_bucket/builds-v0/pkg"+: > "$_denied_bucket/builds-v0/pkg/wheel.whl"+chmod 000 "$_denied_bucket/archive-v0"+# A cache-dir pointed at a mount point carries a root-owned lost+found. uv never writes it,+# so it must not condemn an otherwise usable warm cache.+_alien="$_TMP/uvalien"+mkdir -p "$_alien/archive-v0/torch" "$_alien/lost+found"+: > "$_alien/archive-v0/torch/libtorch.so"+: > "$_alien/CACHEDIR.TAG"+chmod 000 "$_alien/lost+found"+# A bucket NAME needs the whole suffix to be the version: a backup copy or a tarball beside+# the real bucket is not uv's to write, and must not condemn the cache.+_lookalike="$_TMP/uvlookalike"+mkdir -p "$_lookalike/archive-v0/torch"+: > "$_lookalike/archive-v0/torch/libtorch.so"+: > "$_lookalike/CACHEDIR.TAG"+: > "$_lookalike/archive-v0.tar.gz"+: > "$_lookalike/archive-v0.backup"+# A lookalike DIRECTORY full of files is not warmth either: `archive-*` matches+# `archive-v0.backup`, whose bytes uv cannot reuse, so counting it picks a cache that is empty+# in practice.+_lookalike_dir="$_TMP/uvlookalikedir"+mkdir -p "$_lookalike_dir/archive-v0.backup/pkg"+: > "$_lookalike_dir/archive-v0.backup/pkg/payload.so"+: > "$_lookalike_dir/CACHEDIR.TAG"+# Same for a qualifier BEFORE the version: `archive-backup-v0` passes the <kind>-v<N> shape,+# so warmth also has to check that the kind itself is one uv fills.+_lookalike_kind="$_TMP/uvlookalikekind"+mkdir -p "$_lookalike_kind/archive-backup-v0/pkg"+: > "$_lookalike_kind/archive-backup-v0/pkg/payload.so"+: > "$_lookalike_kind/CACHEDIR.TAG"+# `##*-v` strips through the LAST `-v`, so a name ending in one leaves an EMPTY suffix no+# `*[!0-9]*` matches: `archive-v1-v` read as a bucket, and one read-only directory named that+# way condemned a usable warm cache.+_empty_version="$_TMP/uvemptyver"+mkdir -p "$_empty_version/archive-v0/torch" "$_empty_version/archive-v1-v"+: > "$_empty_version/archive-v0/torch/libtorch.so"+: > "$_empty_version/CACHEDIR.TAG"+chmod a-w "$_empty_version/archive-v1-v"+# uv mutates interpreter-v4 too, so the verdict cannot stop at the five artifact families.+_denied_meta="$_TMP/uvmeta2"+mkdir -p "$_denied_meta/archive-v0/torch" "$_denied_meta/interpreter-v4"+: > "$_denied_meta/archive-v0/torch/libtorch.so"+chmod a-w "$_denied_meta/interpreter-v4"+# A dangling bucket link is an existing path to mkdir(2), which answers EEXIST, so uv reports+# `failed to create directory ...: File exists` the first time it needs that bucket.+_dangling="$_TMP/uvdangling"+mkdir -p "$_dangling/builds-v0/pkg"+: > "$_dangling/builds-v0/pkg/wheel.whl"+ln -s "$_TMP/no-such-target" "$_dangling/archive-v0"+# A same-named decoy beside the installer must not be what gets scanned.+mkdir -p "$_TMP/cwd/relcache/archive-v0/decoy"+: > "$_TMP/cwd/relcache/archive-v0/decoy/other.so"+mkdir -p "$_TMP/work/relcache/archive-v0/torch"+: > "$_TMP/work/relcache/archive-v0/torch/libtorch.so"+: > "$_TMP/work/relcache/CACHEDIR.TAG"+# Big enough that `head -n 1` closes the pipe before find is done, as every real cache is.+_big="$_TMP/uvbig"+mkdir -p "$_big/archive-v0/pkg"+: > "$_big/CACHEDIR.TAG"+_i=0+while [ "$_i" -lt 3000 ]; do : > "$_big/archive-v0/pkg/file-$_i.bin"; _i=$((_i + 1)); done++echo "=== the installer's own default does NOT count as a caller override ==="+# The regression: before the fix this was `custom` on every writable machine.+_out=$(_run "$_TMP/a" '' "$_populated")+assert_eq "populated default is reused" "shared" "$(echo "$_out" | cut -d' ' -f1)"+assert_eq "and it is uv's own cache" "$_populated" "$(echo "$_out" | cut -d' ' -f2)"+# _prepare_studio_uv_cache_for_launch is live again, and only in shared mode.+assert_eq "launch repoints to Studio" "$_TMP/a/cache/uv" "$(echo "$_out" | cut -d' ' -f3)"++_out=$(_run "$_TMP/b" '' "$_empty")+assert_eq "empty default -> studio" "studio" "$(echo "$_out" | cut -d' ' -f1)"+assert_eq "studio cache is used" "$_TMP/b/cache/uv" "$(echo "$_out" | cut -d' ' -f2)"+assert_eq "no launch repoint in studio" "$_TMP/b/cache/uv" "$(echo "$_out" | cut -d' ' -f3)"++_out=$(_run "$_TMP/e" '' "$_metadata_only")+assert_eq "metadata-only is not warm" "studio" "$(echo "$_out" | cut -d' ' -f1)"++echo "=== a populated cache we cannot WRITE is not a cache we can use ==="+if [ "$(id -u)" = "0" ]; then+ echo " SKIP: unwritable-cache case (root writes through the mode bits)"+else+ _out=$(_run "$_TMP/f" '' "$_readonly")+ assert_eq "unwritable root -> studio" "studio" "$(echo "$_out" | cut -d' ' -f1)"+ assert_eq "and the Studio cache is used" "$_TMP/f/cache/uv" "$(echo "$_out" | cut -d' ' -f2)"+ _out=$(_run "$_TMP/i" '' "$_readonly_bucket")+ assert_eq "unwritable bucket -> studio" "studio" "$(echo "$_out" | cut -d' ' -f1)"+ _out=$(_run "$_TMP/j" '' "$_readonly_late")+ assert_eq "a later bucket is probed too" "studio" "$(echo "$_out" | cut -d' ' -f1)"+ _out=$(_run "$_TMP/m" '' "$_denied_bucket")+ assert_eq "a denied bucket -> studio" "studio" "$(echo "$_out" | cut -d' ' -f1)"+ _out=$(_run "$_TMP/n" '' "$_denied_meta")+ assert_eq "a denied metadata bucket too" "studio" "$(echo "$_out" | cut -d' ' -f1)"+ _out=$(_run "$_TMP/q" '' "$_alien")+ assert_eq "lost+found does not condemn it" "shared" "$(echo "$_out" | cut -d' ' -f1)"+ _out=$(_run "$_TMP/v1" '' "$_empty_version")+ assert_eq "an empty -v suffix is not a bucket" "shared" "$(echo "$_out" | cut -d' ' -f1)"+fi+_out=$(_run "$_TMP/r" '' "$_lookalike")+assert_eq "a bucket lookalike is not a bucket" "shared" "$(echo "$_out" | cut -d' ' -f1)"+_out=$(_run "$_TMP/t" '' "$_lookalike_dir")+assert_eq "a lookalike dir is not warmth" "studio" "$(echo "$_out" | cut -d' ' -f1)"+_out=$(_run "$_TMP/u" '' "$_lookalike_kind")+assert_eq "a lookalike KIND is not warmth" "studio" "$(echo "$_out" | cut -d' ' -f1)"++echo "=== UV_NO_CACHE stands the selection down, in every spelling uv honours ==="+# uv takes this case-insensitively, so matching a fixed spelling would leave us probing and+# recording a cache uv is not using.+for _nc in 1 y Y true True TRUE tRuE t T yes Yes on On; do+ UV_NO_CACHE="$_nc"; export UV_NO_CACHE+ assert_eq "UV_NO_CACHE=$_nc -> studio" "studio" \+ "$(_run "$_TMP/nc$_nc" '' "$_populated" | cut -d' ' -f1)"+ unset UV_NO_CACHE+done+# ...and a false-ish value must not stand it down.+for _nc in 0 false; do+ UV_NO_CACHE="$_nc"; export UV_NO_CACHE+ assert_eq "UV_NO_CACHE=$_nc -> shared" "shared" \+ "$(_run "$_TMP/nf$_nc" '' "$_populated" | cut -d' ' -f1)"+ unset UV_NO_CACHE+done+chmod 700 "$_alien/lost+found"+chmod 700 "$_denied_bucket/archive-v0"+chmod u+w "$_readonly" "$_readonly_bucket/archive-v0" "$_readonly_late/sdists-v9" \+ "$_denied_meta/interpreter-v4" "$_empty_version/archive-v1-v"+# The probe writes into a directory uv is about to fill, so it has to leave nothing behind.+_run "$_TMP/g" '' "$_populated" >/dev/null+assert_eq "write probe cleaned up" "" "$(ls -A "$_populated" | grep 'unsloth-write-probe' || true)"++echo "=== a relative cache-dir resolves against UV_WORKING_DIR, not the installer's cwd ==="+_out=$(_run "$_TMP/h" '' "relcache" false "$_TMP/work")+assert_eq "relative default is still warm" "shared" "$(echo "$_out" | cut -d' ' -f1)"+assert_eq "resolved against UV_WORKING_DIR" "$_TMP/work/relcache" "$(echo "$_out" | cut -d' ' -f2)"++echo "=== a bucket that is not a directory is not usable either ==="+_out=$(_run "$_TMP/p" '' "$_dangling")+assert_eq "dangling bucket link -> studio" "studio" "$(echo "$_out" | cut -d' ' -f1)"++echo "=== a big warm bucket stays warm under pipefail ==="+assert_eq "big bucket without pipefail" "shared" \+ "$(_run "$_TMP/k" '' "$_big" | cut -d' ' -f1)"+assert_eq "big bucket under pipefail" "shared" \+ "$(_run "$_TMP/l" '' "$_big" false '' true | cut -d' ' -f1)"++echo "=== the scan still expands its globs under set -f ==="+assert_eq "populated default under set -f" "shared" \+ "$(_run "$_TMP/o" '' "$_populated" false '' false true | cut -d' ' -f1)"++echo "=== a CALLER's UV_CACHE_DIR still outranks the selection, untouched ==="+_out=$(_run "$_TMP/c" "$_TMP/mine" "$_populated")+assert_eq "caller value is custom" "custom" "$(echo "$_out" | cut -d' ' -f1)"+assert_eq "caller value is preserved" "$_TMP/mine" "$(echo "$_out" | cut -d' ' -f2)"+assert_eq "no launch repoint for custom" "$_TMP/mine" "$(echo "$_out" | cut -d' ' -f3)"++echo "=== --isolated-uv-cache still wins over a populated default ==="+_out=$(_run "$_TMP/d" '' "$_populated" true)+assert_eq "isolation is honoured" "isolated" "$(echo "$_out" | cut -d' ' -f1)"+assert_eq "and it uses the Studio cache" "$_TMP/d/cache/uv" "$(echo "$_out" | cut -d' ' -f2)"++echo "=== an unwritable STUDIO_HOME still reaches the selection ==="+# The early block unsets UV_CACHE_DIR there, so the choice must not depend on the flag.+: > "$_TMP/blocked"+_out=$(_run "$_TMP/blocked" '' "$_populated")+assert_eq "unwritable home -> shared" "shared" "$(echo "$_out" | cut -d' ' -f1)"++echo "=== an install that predates the marker keeps the cache it already has ==="+# The installed base from before the marker has a populated $STUDIO_HOME/cache/uv and nothing+# recording it, and abandoning it costs gigabytes of Torch and CUDA. It is the LAST candidate,+# though, behind uv's default: the marker arrived in b66d2a4c8 and the early block only in+# e12963071 the day after, so an install with no marker is old enough that `shared` was+# reachable, and there the launch repoint leaves backend wheels in the Studio cache while the+# real bytes sit in the default. So it wins when the default is cold, and loses when it is warm.+_cold_home="$_TMP/colddefault2"+mkdir -p "$_cold_home"+mkdir -p "$_TMP/pre/cache/uv/archive-v0/torch"+: > "$_TMP/pre/cache/uv/archive-v0/torch/libtorch.so"+: > "$_TMP/pre/cache/uv/CACHEDIR.TAG"+_out=$(_run "$_TMP/pre" '' "$_cold_home")+assert_eq "unmarked warm Studio beats a cold default" "studio" "$(echo "$_out" | cut -d' ' -f1)"+assert_eq "and it is the one that is used" "$_TMP/pre/cache/uv" "$(echo "$_out" | cut -d' ' -f2)"+# ...and loses to a WARM one, because content cannot say whose the Studio cache is.+assert_eq "a warm default outranks it" "shared" \+ "$(_run "$_TMP/pre3" '' "$_populated" | cut -d' ' -f1)"+# An unmarked but EMPTY Studio cache is not a reason to skip the shared one.+assert_eq "an unmarked cold Studio cache does not" "shared" \+ "$(_run "$_TMP/pre2" '' "$_populated" | cut -d' ' -f1)"++echo "=== a marker written by the Windows installer is readable here ==="+# install.ps1 writes it with Set-Content -Encoding utf8: a BOM and CRLF under PowerShell 5.1.+# A WSL install shares $STUDIO_HOME with the Windows one, so this file crosses over.+mkdir -p "$_TMP/crlf/cache/uv/archive-v0/torch"+: > "$_TMP/crlf/cache/uv/archive-v0/torch/libtorch.so"+printf '\357\273\277%s\r\n' "$_TMP/crlf/cache/uv" > "$_TMP/crlf/cache/uv-cache-dir"+_out=$(_run "$_TMP/crlf" '' "$_populated")+assert_eq "a BOM+CRLF marker is honoured" "studio" "$(echo "$_out" | cut -d' ' -f1)"+assert_eq "and names the right directory" "$_TMP/crlf/cache/uv" "$(echo "$_out" | cut -d' ' -f2)"++echo "=== a trailing slash in the marker is the same directory ==="+mkdir -p "$_TMP/slash/cache/uv/archive-v0/torch"+: > "$_TMP/slash/cache/uv/archive-v0/torch/libtorch.so"+printf '%s/\n' "$_TMP/slash/cache/uv" > "$_TMP/slash/cache/uv-cache-dir"+# studio, not shared: otherwise the launch repoint the studio branch exists to avoid fires.+assert_eq "a trailing slash still reads as ours" "studio" \+ "$(_run "$_TMP/slash" '' "$_populated" | cut -d' ' -f1)"++echo "=== the launch repoint refuses a Studio cache the backend could not fill ==="+# shared with an unwritable STUDIO_HOME is reachable only because the early block failed its+# own write probe, so repointing would hand the autostarted backend a cache uv aborts on.+if [ "$(id -u)" = "0" ]; then+ echo " SKIP: unwritable-root launch case (root writes through the mode bits)"+else+ mkdir -p "$_TMP/lockedhome"+ chmod a-w "$_TMP/lockedhome"+ _out=$(_run "$_TMP/lockedhome" '' "$_populated")+ assert_eq "unwritable root still selects shared" "shared" "$(echo "$_out" | cut -d' ' -f1)"+ assert_eq "and the launch keeps that cache" "$_populated" "$(echo "$_out" | cut -d' ' -f3)"+ chmod u+w "$_TMP/lockedhome"+fi++echo "=== a fallback we cannot write is not a fallback ==="+# The early block has already given up on an unwritable $STUDIO_HOME/cache/uv, which is the+# only reason the selection is running, so landing on that certain failure turns a working+# install into `failed to create cache directory`.+if [ "$(id -u)" = "0" ]; then+ echo " SKIP: unwritable-fallback case (root writes through the mode bits)"+else+ # A fresh fixture: the shared $_readonly above has had its mode restored by now.+ _refused="$_TMP/uvrefused"+ mkdir -p "$_refused/archive-v0/torch"+ : > "$_refused/archive-v0/torch/libtorch.so"+ : > "$_refused/CACHEDIR.TAG"+ chmod a-w "$_refused"+ mkdir -p "$_TMP/deadhome"+ chmod a-w "$_TMP/deadhome"+ _out=$(_run "$_TMP/deadhome" '' "$_refused")+ assert_eq "a warm cache beats a dead fallback" "shared" "$(echo "$_out" | cut -d' ' -f1)"+ assert_eq "and it is the one that is used" "$_refused" "$(echo "$_out" | cut -d' ' -f2)"+ assert_eq "the launch keeps it too" "$_refused" "$(echo "$_out" | cut -d' ' -f3)"+ chmod u+w "$_TMP/deadhome"+ # With a WRITABLE Studio cache the refused candidate still loses to it, unchanged.+ _out=$(_run "$_TMP/livehome" '' "$_refused")+ assert_eq "a writable fallback still wins" "studio" "$(echo "$_out" | cut -d' ' -f1)"+ assert_eq "and it is the Studio cache" "$_TMP/livehome/cache/uv" "$(echo "$_out" | cut -d' ' -f2)"+ chmod u+w "$_refused"+fi++echo "=== the same answers under a real /bin/sh, and under the errexit install.sh runs with ==="+# Everything above runs one shell without errexit, which is the one arrangement install.sh+# never uses: it is `#!/bin/sh` with `set -e` on line 5, /bin/sh is dash on Debian and busybox+# ash on Alpine, and a construct whose status leaks aborts the install rather than answering.+# The core verdicts are re-run here across every /bin/sh this box has, errexit both ways.+_SH_SAVED="$_SH"+for _alt in /bin/sh /bin/bash; do+ [ -x "$_alt" ] || continue+ _SH="$_alt"+ _alt_name=$(basename "$_alt")+ for _ee in false true; do+ _tag="$_alt_name errexit=$_ee"+ _out=$(_run "$_TMP/ee.$_alt_name.$_ee.a" '' "$_populated" false '' false false "$_ee")+ assert_eq "$_tag: populated default -> shared" "shared" "$(echo "$_out" | cut -d' ' -f1)"+ assert_eq "$_tag: and the launch repoints" "$_TMP/ee.$_alt_name.$_ee.a/cache/uv" \+ "$(echo "$_out" | cut -d' ' -f3)"+ assert_eq "$_tag: empty default -> studio" "studio" \+ "$(_run "$_TMP/ee.$_alt_name.$_ee.b" '' "$_empty" false '' false false "$_ee" | cut -d' ' -f1)"+ assert_eq "$_tag: caller value -> custom" "custom" \+ "$(_run "$_TMP/ee.$_alt_name.$_ee.c" "$_TMP/mine" "$_populated" false '' false false "$_ee" | cut -d' ' -f1)"+ assert_eq "$_tag: isolation is honoured" "isolated" \+ "$(_run "$_TMP/ee.$_alt_name.$_ee.d" '' "$_populated" true '' false false "$_ee" | cut -d' ' -f1)"+ assert_eq "$_tag: a lookalike is not warmth" "studio" \+ "$(_run "$_TMP/ee.$_alt_name.$_ee.e" '' "$_lookalike_dir" false '' false false "$_ee" | cut -d' ' -f1)"+ UV_NO_CACHE=1; export UV_NO_CACHE+ assert_eq "$_tag: UV_NO_CACHE -> studio" "studio" \+ "$(_run "$_TMP/ee.$_alt_name.$_ee.f" '' "$_populated" false '' false false "$_ee" | cut -d' ' -f1)"+ unset UV_NO_CACHE+ done+done+_SH="$_SH_SAVED"++echo "=== a Studio cache with a bucket uv cannot use is not a fallback either ==="+# A `sudo` run leaves a root-owned bucket and a dangling link is an existing path to mkdir(2),+# so the ROOT can be writable while uv still aborts on the cache. Selecting it anyway, or+# repointing the launch at it, turns an install that reported success into a uv error.+_brokenstudio="$_TMP/brokenstudio"+mkdir -p "$_brokenstudio/cache/uv"+ln -s "$_TMP/no-such-target" "$_brokenstudio/cache/uv/archive-v0"+_cold_default="$_TMP/colddefault"+mkdir -p "$_cold_default"+_out=$(_run "$_brokenstudio" '' "$_cold_default")+assert_eq "broken Studio bucket -> not studio" "shared" "$(echo "$_out" | cut -d' ' -f1)"+assert_eq "and uv's default is used instead" "$_cold_default" "$(echo "$_out" | cut -d' ' -f2)"+assert_eq "and the launch does not repoint" "$_cold_default" "$(echo "$_out" | cut -d' ' -f3)"+# With a WARM default the selection already preferred it; the repoint is the part that used to+# hand the backend the rejected cache anyway.+_out=$(_run "$_brokenstudio" '' "$_populated")+assert_eq "warm default beside a broken Studio" "shared" "$(echo "$_out" | cut -d' ' -f1)"+assert_eq "and the launch keeps it" "$_populated" "$(echo "$_out" | cut -d' ' -f3)"+# A Studio cache whose buckets are fine is still the ordinary answer.+_out=$(_run "$_TMP/okstudio" '' "$_cold_default")+assert_eq "an intact Studio cache still wins" "studio" "$(echo "$_out" | cut -d' ' -f1)"++echo "=== a marker naming a directory that is gone is stale, not a decision ==="+# The marker named a cache the user deleted. Treating that as a decision handed the install+# uv's default and abandoned a warm Studio cache holding Torch and CUDA, which offline is an+# install that used to succeed and then failed.+_stale=$_TMP/stalemarker+mkdir -p "$_stale/studio/cache/uv/archive-v0/torch"+: > "$_stale/studio/cache/uv/archive-v0/torch/libtorch.so"+: > "$_stale/studio/cache/uv/CACHEDIR.TAG"+printf '%s\n' "$_TMP/deleted-cache" > "$_stale/studio/cache/uv-cache-dir"+_out=$(_run "$_stale/studio" '' "$_cold_home")+assert_eq "stale marker -> keep the Studio cache" "studio" "$(echo "$_out" | cut -d' ' -f1)"+assert_eq "and not uv's default" "$_stale/studio/cache/uv" "$(echo "$_out" | cut -d' ' -f2)"+# A stale marker is no more evidence than no marker, so a warm default still outranks it.+assert_eq "a warm default still outranks a stale marker" "shared" \+ "$(_run "$_stale/studio" '' "$_populated" | cut -d' ' -f1)"++echo "=== a root we can create in but not unlink from is not writable ==="+# NTFS carries DELETE as its own ACE and an append-only directory does the same on ext4, so+# "create succeeded" does not mean "uv can rename into this". The bucket probe always failed+# the candidate here; the root probe swallowed it. A failing rm, not an ACL: the mode bits+# cannot express this and running as root would hide it.+_probe_unlink_case() {+ # shellcheck disable=SC2317+ rm() { return 1; }+ if _uv_cache_root_is_writable "$1"; then echo writable; else echo unwritable; fi+}+# A delete that FAILS but leaves nothing behind is a delete: an indexer holding the handle+# makes one rm fail and the next succeed, and a probe another process removed is cleaned up.+# `rm -f` exits 0 on a missing file where Remove-Item -ErrorAction Stop throws, which is the+# divergence this rule closes.+_probe_gone_case() {+ # shellcheck disable=SC2317+ rm() { command rm -f "$@" 2>/dev/null; return 1; }+ if _uv_cache_root_is_writable "$1"; then echo writable; else echo unwritable; fi+}+_out=$(+ . "$_FN" 2>/dev/null || true+ _probe_unlink_case "$_TMP/unlinkdenied"+)+assert_eq "create without unlink -> unwritable" "unwritable" "$_out"+# And the ordinary case still passes, so the check above is not just failing everything.+_out=$(+ . "$_FN" 2>/dev/null || true+ if _uv_cache_root_is_writable "$_TMP/unlinkok"; then echo writable; else echo unwritable; fi+)+assert_eq "an ordinary root is still writable" "writable" "$_out"+assert_eq "and the probe is not left behind" "" "$(ls -A "$_TMP/unlinkok" 2>/dev/null)"+_out=$(+ . "$_FN" 2>/dev/null || true+ _probe_gone_case "$_TMP/unlinkgone"+)+assert_eq "a failed rm that removed it is fine" "writable" "$_out"++echo ""+echo "PASS=$PASS FAIL=$FAIL"+[ "$FAIL" -eq 0 ]diff --git a/tests/sh/test_uv_cache_colocation.sh b/tests/sh/test_uv_cache_colocation.shindex 3f41c9249a1..18428bf7667 100755--- a/tests/sh/test_uv_cache_colocation.sh+++ b/tests/sh/test_uv_cache_colocation.sh@@ -26,13 +26,21 @@ INSTALL_SH="$SCRIPT_DIR/../../install.sh"_FN_FILE=$(mktemp)_TMP=$(mktemp -d)trap 'rm -rf "$_FN_FILE" "$_TMP"' EXIT+# The helper first: the block asks it whether the cache is usable, and leaving it out does not+# fail loudly. `command not found` exits 127, `if !` reads that as "not writable", and every+# case quietly reports an unset UV_CACHE_DIR.+awk '/^_uv_cache_root_is_writable\(\) \{$/,/^\}$/' "$INSTALL_SH" > "$_FN_FILE"awk '/^# Keep uv.s cache on the same filesystem as the venv it fills\.$/,/^fi$/' \- "$INSTALL_SH" > "$_FN_FILE"+ "$INSTALL_SH" >> "$_FN_FILE"if ! grep -q 'UV_CACHE_DIR="\$STUDIO_HOME/cache/uv"' "$_FN_FILE"; thenecho "FAIL: could not extract the UV_CACHE_DIR block from install.sh"exit 1fi+if ! grep -q '^_uv_cache_root_is_writable() {' "$_FN_FILE"; then+ echo "FAIL: could not extract _uv_cache_root_is_writable from install.sh"+ exit 1+fi_SH="${BASH:-/bin/bash}"_run() { # $1 = STUDIO_HOME, $2 = preset UV_CACHE_DIR ("" for unset)diff --git a/tests/studio/install/test_installed_release_backend_line.py b/tests/studio/install/test_installed_release_backend_line.pyindex 2242d4494fd..e9032257182 100644--- a/tests/studio/install/test_installed_release_backend_line.py+++ b/tests/studio/install/test_installed_release_backend_line.py@@ -23,6 +23,9 @@ from pathlib import Pathimport pytest+sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "_shared"))+from unsloth_pwsh_runner import run_pwsh # noqa: E402+PACKAGE_ROOT = Path(__file__).resolve().parents[3]SETUP_PS1 = PACKAGE_ROOT / "studio" / "setup.ps1"SETUP_SH = PACKAGE_ROOT / "studio" / "setup.sh"@@ -238,7 +241,12 @@ def _run_ps1_printer(install_dir, strict_mode):# to sit in the CALLER's scope.script_path = Path(install_dir).parent / f"drive_{strict_mode.replace('.', '_')}.ps1"script_path.write_text(script, encoding = "utf-8")- proc = subprocess.run(+ # run_pwsh, not subprocess.run: this file spawns one pwsh per parametrisation, and under+ # `-n 4` the workers shared one PowerShell startup cache. A torn cache kills the interpreter+ # before it reaches the script, and surfaces here as a FileLoadException instead of a+ # backend line: a runner crash wearing this file's name. The shared runner gives each worker+ # its own cache and retries an interpreter that died without answering.+ proc = run_pwsh(["pwsh","-NoLogo",diff --git a/tests/studio/test_installer_av_shapes.py b/tests/studio/test_installer_av_shapes.pyindex 26e4666df8d..1cbca4764a2 100644--- a/tests/studio/test_installer_av_shapes.py+++ b/tests/studio/test_installer_av_shapes.py@@ -649,6 +649,24 @@ def test_an_unreadable_security_log_is_void_rather_than_clean() -> None:assert "void rather than as clean" in body+def test_the_compiler_window_is_cut_to_size_by_timecreated() -> None:+ """The 4688 window has to be exact at the floor, or it scores the step before it.++ Observed on unslothai/unsloth#10626: a csc.exe recorded at 17:51:57.107 came back from+ a window whose floor was 17:51:57.58 and failed a measurement whose step had not+ printed its first line until 17:51:58.58. The compile belonged to the positive control+ one step earlier. $prior is meant to subtract exactly that, and did not, so the filter+ itself has to hold to the precision it was given rather than to the hashtable's.+ """+ body = _WATCHER.read_text(encoding = "utf-8")+ assert "StartTime = $Since.AddSeconds(-1)" in body+ assert "EndTime = $Until.AddSeconds(1)" in body+ assert "$_.TimeCreated -ge $Since -and $_.TimeCreated -le $Until" in body, (+ "the padded query is no longer cut back to the real window, so it reports "+ "compiles from before the action began"+ )++def test_the_native_resolver_still_has_a_lexical_fallback() -> None:"""The point of the change is the acquisition, not the ladder: a host where emit fails mustdegrade exactly as one that could not compile already did.diff --git a/unsloth_cli/commands/studio.py b/unsloth_cli/commands/studio.pyindex 4201f1f8a36..b3aa3a0d87b 100644--- a/unsloth_cli/commands/studio.py+++ b/unsloth_cli/commands/studio.py@@ -3182,18 +3182,29 @@ _PS_PROXY_DEFAULTS_PRELUDE = ()-_UV_CACHE_BUCKETS = ("archive-", "builds-", "built-wheels-", "wheels-", "sdists-")+_UV_CACHE_BUCKETS = ("archive", "builds", "built-wheels", "wheels", "sdists")_UV_CACHE_METADATA_SUFFIXES = (".lock", ".msgpack", ".http", ".rev")+def _uv_is_bucket_name(name: str) -> bool:+ """A name uv itself creates: <kind>-v<N>, whole suffix numeric, kind from the LAST `-v`.+ Mirrors _uv_is_bucket_name in install.sh and Test-StudioUvBucketName in install.ps1."""+ kind, marker, version = name.rpartition("-v")+ # isascii too: str.isdigit() is true for Arabic-Indic and superscript digits, which the sh+ # `*[!0-9]*` case and the PowerShell \A[0-9]+\z both reject. uv writes ASCII.+ return bool(marker) and version.isascii() and version.isdigit() and kind in _UV_CACHE_BUCKETS++def _uv_cache_has_packages(cache_dir: Path) -> bool:"""wheels-* is metadata only on uv 0.10, so counting any file reads a merely-resolved cache- as warm. Same rule as install.sh:_configure_uv_cache."""+ as warm. Same rule as install.sh:_configure_uv_cache, the WHOLE `-v` suffix included: a+ prefix match also takes `archive-v0.backup` and `archive-backup-v0`, whose bytes uv cannot+ reuse, so an update could prefer a cache that is cold in practice and redownload."""try:buckets = [entryfor entry in cache_dir.iterdir()- if entry.name.startswith(_UV_CACHE_BUCKETS) and entry.is_dir()+ if _uv_is_bucket_name(entry.name) and entry.is_dir()]except (OSError, ValueError):return False@@ -3219,14 +3230,19 @@ def _uv_platform_cache_dir() -> Optional[Path]:return Path(home) / ".cache" / "uv" if home else None-# uv's boolish spelling. Anything outside it is a value uv refuses to run on.-_UV_TRUE = ("1", "true", "yes", "on")+# clap's literals, which is what uv binds UV_NO_CACHE to (BoolishValueParser). `y` and `t` are+# real spellings uv honours, and were missing here, in install.sh and in install.ps1 alike.+_UV_TRUE = ("1", "y", "yes", "t", "true", "on")def _uv_no_cache_requested() -> bool:"""uv --no-cache caches in a temporary directory and discards it, outranks --cache-dir,- and recording it would aim later updates at a cache that never existed."""- return (os.environ.get("UV_NO_CACHE") or "").strip().lower() in _UV_TRUE+ and recording it would aim later updates at a cache that never existed.++ Not stripped, matching clap and therefore both installers: uv rejects a padded value+ outright rather than reading it as true, so ` true ` leaves uv's cache ON and this must+ not stand the selection down for it."""+ return (os.environ.get("UV_NO_CACHE") or "").lower() in _UV_TRUEdef _uv_default_cache_dir(cwd: Optional[Path] = None) -> Optional[Path]:@@ -3322,7 +3338,9 @@ def _with_studio_uv_cache(env: Optional[dict], cwd: Optional[Path] = None) -> Opif recorded is not None and _uv_cache_has_packages(recorded):# Only while it holds something: a marker for an emptied cache loses to a warm one.return {**(env or os.environ), "UV_CACHE_DIR": str(recorded)}- # No marker, and content cannot settle it: one on-demand wheel warms the Studio cache even in shared mode, so use uv's default.+ # Content cannot settle it: one on-demand wheel warms the Studio cache even in shared mode,+ # so uv's default goes first and a warm Studio cache is the fallback below. The installers+ # order the same three the same way.default_cache = _uv_default_cache_dir(cwd)if default_cache is not None and _uv_cache_has_packages(default_cache):return {**(env or os.environ), "UV_CACHE_DIR": str(default_cache)}diff --git a/unsloth_cli/tests/test_studio_update_uv_cache.py b/unsloth_cli/tests/test_studio_update_uv_cache.pyindex 90dfd13e818..5611fc19f62 100644--- a/unsloth_cli/tests/test_studio_update_uv_cache.py+++ b/unsloth_cli/tests/test_studio_update_uv_cache.py@@ -179,6 +179,61 @@ def test_the_windows_branch_gets_the_same_cache(monkeypatch, tmp_path, caches):assert seen["env"]["UV_CACHE_DIR"] == str(studio_cache)+def test_a_unicode_digit_version_is_not_a_bucket(monkeypatch, tmp_path, caches):+ """str.isdigit() is true for Arabic-Indic and superscript digits; the sh `*[!0-9]*` case+ and the PowerShell \\A[0-9]+\\z both reject them, and uv writes ASCII. Python was the+ only one of the three that would have counted such a directory as warmth."""+ studio = _studio()+ assert studio._uv_is_bucket_name("archive-v0")+ assert not studio._uv_is_bucket_name("archive-v\u0661")+ assert not studio._uv_is_bucket_name("archive-v\u00b2")+++def test_a_bucket_lookalike_is_not_warmth_for_the_update_either(monkeypatch, tmp_path, caches):+ """`archive-v0.backup` holds bytes uv cannot reuse, so a prefix match read a cache that is+ cold in practice as warm. The installers check the whole `-v` suffix; this did not, and an+ update could prefer the lookalike cache and redownload."""+ studio_cache, default_cache = caches+ _fill(studio_cache)+ default_cache.mkdir(parents = True, exist_ok = True)+ (default_cache / "archive-v0.backup" / "pkg").mkdir(parents = True)+ (default_cache / "archive-v0.backup" / "pkg" / "payload.so").write_text("x")+ seen = _run_posix(monkeypatch, tmp_path)++ assert seen["env"]["UV_CACHE_DIR"] == str(studio_cache), seen["env"].get("UV_CACHE_DIR")+++def test_windows_keeps_uv_s_default_when_both_are_warm_and_unmarked(monkeypatch, tmp_path, caches):+ """The same rule, asserted through the PowerShell spawn rather than the POSIX one."""+ studio = _studio()+ studio_cache, default_cache = caches+ _fill(studio_cache)+ _fill(default_cache)+ monkeypatch.setattr(studio.platform, "system", lambda: "Windows")+ monkeypatch.setattr(+ studio._studio_runtime_gate, "resolve_windows_powershell", lambda: "powershell.exe"+ )+ monkeypatch.setattr(studio, "_probe_profile_proxy_defaults", lambda hosts: None)+ monkeypatch.setattr(studio, "_wait_for_windows_setup_process", lambda process: 0)+ seen: dict = {}++ class _Process:+ pass++ def _fake_popen(+ argv,+ env = None,+ **kwargs,+ ):+ seen["env"] = env+ return _Process()++ monkeypatch.setattr(studio.subprocess, "Popen", _fake_popen)+ studio._run_setup_script(repo_root = _setup_tree(tmp_path))++ assert seen["env"]["UV_CACHE_DIR"] == str(default_cache), seen["env"].get("UV_CACHE_DIR")++def test_the_seeding_does_not_leak_into_this_process(monkeypatch, tmp_path, caches):"""_ensure_studio_env_exported mutates os.environ on purpose; this must not, or alater `unsloth studio` in the same process would look like a caller override to@@ -249,12 +304,53 @@ def test_a_studio_mode_install_wins_over_a_cold_default(monkeypatch, tmp_path, cdef test_two_warm_caches_and_no_marker_keep_uv_s_default(monkeypatch, tmp_path, caches):- """An install that predates the marker cannot say which cache it used, and content- cannot tell either: one on-demand wheel warms the Studio cache (install.sh:705). uv's- default is what it has been updating from, and it cannot record its way out."""+ """An install with no marker cannot say which cache it used, and content cannot either.++ The marker arrived in b66d2a4c8 and the installer's early UV_CACHE_DIR block only in+ e12963071 the day after, so an install old enough to have no marker is old enough that+ `shared` was reachable, and there the launch repoint leaves backend wheels in the Studio+ cache while Torch and CUDA sit in uv's default. So the default keeps its priority when both+ are warm, and the installers order the same three candidates the same way.+ """+ studio_cache, default_cache = caches+ _fill(studio_cache)+ _fill(default_cache)+ seen = _run_posix(monkeypatch, tmp_path)++ assert seen["env"]["UV_CACHE_DIR"] == str(default_cache), seen["env"].get("UV_CACHE_DIR")+++def test_a_warm_studio_cache_still_wins_when_the_default_is_cold(monkeypatch, tmp_path, caches):+ """The other half: the pre-marker install this rule exists for, whose user never filled+ uv's own cache. Nothing is lost by keeping the cache that has the bytes."""+ studio_cache, _default_cache = caches+ _fill(studio_cache)+ seen = _run_posix(monkeypatch, tmp_path)++ assert seen["env"]["UV_CACHE_DIR"] == str(studio_cache), seen["env"].get("UV_CACHE_DIR")+++def test_a_stale_marker_is_no_more_evidence_than_no_marker(monkeypatch, tmp_path, caches):+ """A marker naming a directory that is gone is a stale pointer, not a decision, so it gets+ the same ordering as an absent one rather than promoting the Studio cache."""+ studio_cache, default_cache = caches+ _fill(studio_cache)+ _fill(default_cache)+ _record(tmp_path / "StudioHome", tmp_path / "deleted-cache")+ seen = _run_posix(monkeypatch, tmp_path)++ assert seen["env"]["UV_CACHE_DIR"] == str(default_cache), seen["env"].get("UV_CACHE_DIR")+++def test_a_cold_recorded_cache_that_still_exists_keeps_losing(monkeypatch, tmp_path, caches):+ """The other half: a marker naming a cache that EXISTS and has gone cold is still a+ decision, so the machine that really moved on still reaches uv's default."""studio_cache, default_cache = caches_fill(studio_cache)_fill(default_cache)+ cold = tmp_path / "coldrec"+ cold.mkdir()+ _record(tmp_path / "StudioHome", cold)seen = _run_posix(monkeypatch, tmp_path)assert seen["env"]["UV_CACHE_DIR"] == str(default_cache), seen["env"].get("UV_CACHE_DIR")