Skip to content

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

Studio installers: add --no-rollback, and report a full disk as a full disk (#11364)

Daniel Han62923f2b1540
diff --git a/README.md b/README.md
index c1bdd917571..20ed48f4c17 100644
--- a/README.md
+++ b/README.md
@@ -358,6 +358,21 @@ For a local run the flag is `--isolated-uv-cache`:
.\install.ps1 --local --isolated-uv-cache
```
+Discard the previous environment immediately when reinstalling, instead of keeping a copy until the new one works. A reinstall normally holds both at once, so it needs room for two; this needs room for one, at the cost of not being able to undo a failed install:
+```bash
+curl -fsSL https://unsloth.ai/install.sh | UNSLOTH_INSTALL_NO_ROLLBACK=1 sh
+```
+```powershell
+$env:UNSLOTH_INSTALL_NO_ROLLBACK=1; irm https://unsloth.ai/install.ps1 | iex
+```
+For a local run the flag is `--no-rollback`:
+```bash
+./install.sh --local --no-rollback
+```
+```powershell
+.\install.ps1 --local --no-rollback
+```
+
Pinning the Python version:
```bash
curl -fsSL https://unsloth.ai/install.sh | UNSLOTH_PYTHON=3.12 sh
diff --git a/install.ps1 b/install.ps1
index 4f3281767da..0eff2248ef7 100644
--- a/install.ps1
+++ b/install.ps1
@@ -7,8 +7,9 @@
#
# The web entry point cannot forward arguments, so it takes options as environment variables set
# beforehand (UNSLOTH_NO_TORCH, UNSLOTH_SKIP_AUTOSTART, UNSLOTH_ISOLATE_UV_CACHE,
-# UNSLOTH_PYTHON, UNSLOTH_STUDIO_HOME); a local run takes the equivalent flags
-# (--no-torch, --skip-autostart, --isolated-uv-cache, --python, --local).
+# UNSLOTH_INSTALL_NO_ROLLBACK, UNSLOTH_PYTHON, UNSLOTH_STUDIO_HOME); a local run takes the
+# equivalent flags (--no-torch, --skip-autostart, --isolated-uv-cache, --no-rollback,
+# --python, --local).
#
# Install dir priority: UNSLOTH_STUDIO_HOME > STUDIO_HOME (alias) > $USERPROFILE\.unsloth\studio
#
@@ -1602,6 +1603,46 @@ function Install-UnslothStudio {
[int]$Code = 1
)
if ($Code -eq 0) { $Code = 1 }
+ # Here rather than at any one failure site: the largest writes are the venv and the torch
+ # install, and both exit through this function long before studio setup is reached, so a
+ # disk that filled during them used to surface as a bare exit code (#11313). Below 64 MB
+ # nothing useful unpacks, which makes it the cause rather than a coincidence. Folded into
+ # $Message as well as printed, because under --tauri nothing reaches the UI except the
+ # single line handed to Write-TauriLog.
+ $_diskSuffix = ""
+ try {
+ # Probed, not called outright: the early exits above happen before this file has
+ # defined the helper, and a command-not-found here would replace the real failure
+ # with a confusing one.
+ if ($StudioHome -and (Get-Command Get-StudioFreeSpaceBytes -CommandType Function -ErrorAction SilentlyContinue)) {
+ $_diskFree = Get-StudioFreeSpaceBytes -Path $StudioHome
+ if ($null -ne $_diskFree -and $_diskFree -lt 64MB) {
+ $_diskMb = [math]::Round($_diskFree / 1MB)
+ # What to advise depends on what actually happened to the old environment,
+ # not on what was asked for. A discard that failed left a tree behind, and
+ # deleting it is very likely what makes the retry fit; telling that user
+ # there is nothing left to reclaim sends them away from the one thing that
+ # would help. install.sh chooses between the same four.
+ $_diskRemedy = if ($script:StudioVenvDiscardLeftover) {
+ "Free some space and re-run. The previous environment could not be removed and is still at $($script:StudioVenvDiscardLeftover); deleting it will reclaim that space."
+ } elseif ($script:StudioVenvDiscardSucceeded) {
+ "Free some space and re-run. The previous environment was already discarded by --no-rollback, so the installer has nothing further of its own to reclaim."
+ } elseif ($script:StudioNoRollback) {
+ # Asked for, but nothing was there to discard: a first install, or a
+ # failure before the replacement began.
+ "Free some space and re-run."
+ } else {
+ "Free some space and re-run. --no-rollback (UNSLOTH_INSTALL_NO_ROLLBACK=1) drops the previous environment instead of keeping a copy of it during the install."
+ }
+ $_diskSuffix = ": $StudioHome has only $_diskMb MB free, so the disk is full, which is very likely the cause. $_diskRemedy"
+ if (-not $TauriMode) {
+ Write-StudioLine " $StudioHome has only $_diskMb MB free -- the disk is full, which is very likely the cause." -ForegroundColor Red
+ Write-StudioLine " $_diskRemedy" -ForegroundColor Red
+ }
+ }
+ }
+ } catch { $_diskSuffix = "" }
+ $Message = "$Message$_diskSuffix"
Write-TauriLog "ERROR_DEFAULT" $Message
# Under `irm | iex` the session survives a failure; a leaked handoff would re-pin it.
Remove-Item Env:UNSLOTH_KEPT_TORCH -ErrorAction SilentlyContinue
@@ -1948,6 +1989,19 @@ function Install-UnslothStudio {
$SkipTorch = $false
$SkipAutostart = $false
$IsolateUvCache = $false
+ # Script-scoped: Start-StudioVenvRollback reads it, and tests/studio/test_install_rollback_lifecycle.ps1
+ # extracts that function on its own.
+ $script:StudioNoRollback = $false
+ # Set later by the cross-volume cache notice and read later still by Start-StudioVenvRollback.
+ # Initialised here rather than beside the other rollback state, which is reset AFTER that
+ # notice runs and would therefore clear it. Under `irm | iex` the script scope IS the caller's
+ # session, so a stale value from a previous run has to be cleared somewhere.
+ # Bounded WMI answer, taken at most once per run. Reset here for the same reason as the rest
+ # of this block: under `irm | iex` the script scope IS the caller's session.
+ $script:StudioVolumeList = $null
+ # Set by the --no-rollback discard when the environment it is about to delete reports XPU,
+ # read by the Intel scan once that tree is gone.
+ $script:StudioPreservedXpuVerdict = $false
$ShortcutsOnly = $false
$WithLlamaCppDir = ""
$argList = $args
@@ -1957,6 +2011,7 @@ function Install-UnslothStudio {
"--tauri" { $TauriMode = $true }
"--no-torch" { $SkipTorch = $true }
"--isolated-uv-cache" { $IsolateUvCache = $true }
+ "--no-rollback" { $script:StudioNoRollback = $true }
"--verbose" { $script:UnslothVerbose = $true }
"-v" { $script:UnslothVerbose = $true }
"--shortcuts-only" { $ShortcutsOnly = $true }
@@ -1983,6 +2038,7 @@ function Install-UnslothStudio {
if ($env:UNSLOTH_NO_TORCH -in @('1', 'true', 'yes', 'on')) { $SkipTorch = $true }
if ($env:UNSLOTH_SKIP_AUTOSTART -in @('1', 'true', 'yes', 'on')) { $SkipAutostart = $true }
if ($env:UNSLOTH_ISOLATE_UV_CACHE -in @('1', 'true', 'yes', 'on')) { $IsolateUvCache = $true }
+ if ($env:UNSLOTH_INSTALL_NO_ROLLBACK -in @('1', 'true', 'yes', 'on')) { $script:StudioNoRollback = $true }
if ($script:UnslothVerbose) {
$env:UNSLOTH_VERBOSE = '1'
@@ -2771,6 +2827,109 @@ exit 1
return (Resolve-StudioFinalPathInfo -Path $Path).Path
}
+ # Free space for the disk-full diagnosis (#11313), answering $null rather than guessing: a
+ # number this cannot produce is a diagnosis it does not print.
+ # A Windows volume can be mounted at a DIRECTORY, and then the drive root is the wrong answer:
+ # GetPathRoot reduces C:\studio to C:\, so two paths on different volumes compare equal.
+ # Win32_Volume lists mount points by the path they are mounted at, so the longest Name that
+ # prefixes a path names the volume really holding it; anywhere CIM cannot answer, callers fall
+ # back to the drive-root logic, which is right for a lettered volume.
+ # Known limit: Name exposes ONE access path, so a volume reached through a second one falls
+ # back to the drive root, the pre-existing answer. Closing it needs a Win32_MountPoint join on
+ # every install, for a diagnostic. Split out so the matching is testable without a mount point.
+ function Select-StudioVolumeForPath {
+ param([Parameter(Mandatory = $true)][AllowEmptyString()][string]$Path,
+ [Parameter(Mandatory = $true)][AllowEmptyCollection()][object[]]$Volumes)
+ if ([string]::IsNullOrWhiteSpace($Path)) { return $null }
+ # Unrooted means GetFullPath would anchor it to the current directory and invent a match
+ # on whichever volume that happens to be. No answer is the honest one.
+ if (-not [System.IO.Path]::IsPathRooted($Path)) { return $null }
+ $full = [System.IO.Path]::GetFullPath($Path)
+ # Name carries a trailing separator and GetFullPath does not, so a path that IS the mount
+ # point would miss its own volume. Appending one also keeps C:\studiofoo from matching a
+ # volume mounted at C:\studio.
+ if (-not $full.EndsWith([System.IO.Path]::DirectorySeparatorChar)) {
+ $full += [System.IO.Path]::DirectorySeparatorChar
+ }
+ $best = $null
+ foreach ($vol in $Volumes) {
+ if (-not $vol -or -not $vol.Name) { continue }
+ if (-not $full.StartsWith($vol.Name, [System.StringComparison]::OrdinalIgnoreCase)) { continue }
+ if ((-not $best) -or $vol.Name.Length -gt $best.Name.Length) { $best = $vol }
+ }
+ return $best
+ }
+
+ # Junctions and symlinks lie about which volume a path is on, so a studio home behind one is
+ # otherwise measured on the link's host drive. The lexical fallback keeps a resolver that
+ # cannot answer from costing the caller its measurement entirely.
+ function Resolve-StudioVolumeQueryPath {
+ param([Parameter(Mandatory = $true)][string]$Path)
+ try {
+ $final = Get-StudioFinalPath -Path $Path
+ # Get-StudioFinalPath strips \\?\ deliberately, so a volume with no drive letter comes
+ # back as Volume{GUID}\..., which is NOT rooted: GetFullPath would then anchor it to
+ # the current directory and name an unrelated volume. Keep the caller's own path.
+ if ($final -and [System.IO.Path]::IsPathRooted($final)) { return $final }
+ return $Path
+ } catch { return $Path }
+ }
+
+ # Bounded out of process, as Invoke-BoundedVideoControllerScan documents: a degraded WMI
+ # repository blocks a CIM query indefinitely, and neither -ErrorAction nor try/catch bounds a
+ # query that never returns. Cached, timeouts included, so a broken repository costs once, and
+ # -Fresh for the free-space caller, whose cached FreeSpace would be a pre-failure snapshot.
+ function Get-StudioVolumeList {
+ param([switch]$Fresh)
+ if (-not $Fresh -and $null -ne $script:StudioVolumeList) { return $script:StudioVolumeList }
+ $script:StudioVolumeList = @()
+ $job = $null
+ try {
+ $job = Start-Job -ScriptBlock {
+ Get-CimInstance -ClassName Win32_Volume -ErrorAction SilentlyContinue |
+ Select-Object Name, DeviceID, FreeSpace
+ }
+ if (Wait-Job -Job $job -Timeout 15) {
+ $script:StudioVolumeList = @(Receive-Job -Job $job -ErrorAction SilentlyContinue |
+ Where-Object { $_ -and $_.Name })
+ } else {
+ Stop-Job -Job $job -ErrorAction SilentlyContinue
+ }
+ } catch {
+ } finally {
+ if ($job) { Remove-Job -Job $job -Force -ErrorAction SilentlyContinue }
+ }
+ return $script:StudioVolumeList
+ }
+
+ function Get-StudioMountedVolume {
+ param([Parameter(Mandatory = $true)][AllowEmptyString()][string]$Path,
+ [switch]$Fresh)
+ if ([string]::IsNullOrWhiteSpace($Path)) { return $null }
+ if (-not ($IsWindows -or $env:OS -eq "Windows_NT")) { return $null }
+ try {
+ return (Select-StudioVolumeForPath -Path (Resolve-StudioVolumeQueryPath -Path $Path) `
+ -Volumes (Get-StudioVolumeList -Fresh:$Fresh))
+ } catch { return $null }
+ }
+
+ # GetPathRoot on a path that does not exist yet still names the volume it would be created on.
+ function Get-StudioFreeSpaceBytes {
+ param([Parameter(Mandatory = $true)][AllowEmptyString()][string]$Path)
+ if ([string]::IsNullOrWhiteSpace($Path)) { return $null }
+ $queryPath = Resolve-StudioVolumeQueryPath -Path $Path
+ # -Fresh: this is the caller that wants a number, and a stale one is worse than none.
+ $mounted = Get-StudioMountedVolume -Path $queryPath -Fresh
+ if ($mounted -and $null -ne $mounted.FreeSpace) { return [int64]$mounted.FreeSpace }
+ try {
+ # The fallback needs the resolved path too: DriveInfo on the lexical one answers for
+ # the drive the junction lives on, not the drive it points at.
+ $root = [System.IO.Path]::GetPathRoot([System.IO.Path]::GetFullPath($queryPath))
+ if (-not $root) { return $null }
+ return ([System.IO.DriveInfo]::new($root)).AvailableFreeSpace
+ } catch { return $null }
+ }
+
# Custom Unsloth roots are not supported with --tauri (the desktop app uses
# the Windows profile folder). Pass through if the override is that same root.
if ($TauriMode -and $envOverride) {
@@ -6873,7 +7032,6 @@ exit 0
# installer is a command-not-found.
Write-StudioRootOwnerMarker -Root $StudioHome
Set-StudioUvCacheEnvironment -StudioRoot $StudioHome -Isolated $IsolateUvCache -UvExecutable $script:UvExe
-
# Bytecode compilation can exceed uv's 60s default on slow machines ("0" disables).
if (-not $env:UV_COMPILE_BYTECODE_TIMEOUT) {
$env:UV_COMPILE_BYTECODE_TIMEOUT = "180"
@@ -6901,6 +7059,13 @@ exit 0
# The existing interpreter's platform tag, read before any rollback move takes it away.
$script:PrevVenvPlatformTag = $null
$script:StudioVenvRollbackActive = $false
+ # Set only by --no-rollback, so a branch that needs the previous tree can tell
+ # "already deleted on purpose" from "not moved aside yet".
+ $script:StudioVenvRollbackDiscarded = $false
+ # Set by the discard itself, so the disk-full remedy describes what happened rather than what
+ # was requested.
+ $script:StudioVenvDiscardSucceeded = $false
+ $script:StudioVenvDiscardLeftover = $null
$script:StudioVenvRollbackPartial = $false
# Reset per run: under `irm | iex` the script scope IS the caller's session.
$script:PrevTorchVer = ""
@@ -6998,6 +7163,46 @@ exit 0
return ($null -ne (Get-Item -LiteralPath $Path -Force -ErrorAction SilentlyContinue))
}
+ # A wedged torch import or a hanging Intel driver init -- what the XPU probes below exist to
+ # detect -- would block a bare `& python -c ...` forever. ProcessStartInfo, not &, so stderr
+ # cannot trip $ErrorActionPreference; BOTH streams drain async so a noisy import cannot
+ # deadlock on a full pipe; WaitForExit bounds the wait and kills the child. Every failure
+ # (timeout, crash, exception) reads as .Ok = $false; .Error carries WHICH one, since stderr
+ # used to be drained and discarded, leaving a driver-level DLL load error and a missing torch
+ # indistinguishable. Defined above the Intel scan: PowerShell binds a function when it runs.
+ function Invoke-BoundedPythonProbe {
+ param([string]$PythonExe, [string]$Code, [int]$TimeoutSec = 30)
+ $result = [pscustomobject]@{ Ok = $false; Output = ""; Error = "" }
+ if (-not $PythonExe -or -not $Code) { return $result }
+ try {
+ $psi = New-Object System.Diagnostics.ProcessStartInfo
+ $psi.FileName = $PythonExe
+ $psi.Arguments = "-c `"$Code`""
+ $psi.RedirectStandardOutput = $true
+ $psi.RedirectStandardError = $true
+ $psi.UseShellExecute = $false
+ $psi.CreateNoWindow = $true
+ $proc = [System.Diagnostics.Process]::Start($psi)
+ $outTask = $proc.StandardOutput.ReadToEndAsync()
+ $errTask = $proc.StandardError.ReadToEndAsync()
+ if (-not $proc.WaitForExit($TimeoutSec * 1000)) {
+ try { $proc.Kill() } catch {}
+ # Synthesised, not read back: waiting on the reader tasks of a wedged child
+ # would reintroduce the hang this helper exists to bound.
+ $result.Error = "python did not answer within $TimeoutSec seconds"
+ return $result
+ }
+ $result.Output = $outTask.GetAwaiter().GetResult()
+ # Kept, not discarded: the only place a failed probe's OSError / WinError text exists.
+ $result.Error = $errTask.GetAwaiter().GetResult()
+ $result.Ok = ($proc.ExitCode -eq 0)
+ return $result
+ } catch {
+ $result.Error = $_.Exception.Message
+ return $result
+ }
+ }
+
function Start-StudioVenvRollback {
param([Parameter(Mandatory = $true)][string]$ExistingDir)
$stamp = Get-Date -Format "yyyyMMddHHmmss"
@@ -7044,13 +7249,56 @@ exit 0
}
throw
}
+ # --no-rollback / UNSLOTH_INSTALL_NO_ROLLBACK: drop the old environment now instead of at
+ # commit, for the disk-constrained cross-volume case. The rename still happens first, so
+ # uv never builds into an occupied path. Clearing the state before the delete is what the
+ # commit path does too: an interrupt must not restore a half-deleted backup.
+ if ($script:StudioNoRollback) {
+ $discard = $script:StudioVenvRollbackDir
+ # The Intel scan rescues an adapter WMI cannot classify by asking the PREVIOUS
+ # environment's torch whether XPU works, and deleting that tree takes the only
+ # interpreter that can answer. Opting out must cost disk, never hardware, so the
+ # verdict is taken first and the scan reads it. Wrapped, because a probe that cannot
+ # run must not cost the rename.
+ try {
+ $_discardPy = Join-Path $discard "Scripts\python.exe"
+ if (Test-Path -LiteralPath $_discardPy -ErrorAction SilentlyContinue) {
+ $_discardXpu = Invoke-BoundedPythonProbe -PythonExe $_discardPy `
+ -Code 'import torch; print(torch.xpu.is_available())'
+ if ($_discardXpu.Ok -and $_discardXpu.Output -match '(?m)^\s*True\s*$') {
+ $script:StudioPreservedXpuVerdict = $true
+ }
+ }
+ } catch { }
+ $script:StudioVenvRollbackActive = $false
+ $script:StudioVenvRollbackDir = $null
+ # Distinct from "never started". Inactive alone cannot tell the two apart, and the
+ # ARM64 migration below reads it to decide whether it still has a tree to move.
+ $script:StudioVenvRollbackDiscarded = $true
+ # The helper already names the reason it could not delete. What it must not do is
+ # report success anyway: a tree left behind by an open handle, a reparse point or a
+ # long path frees none of the space this flag exists to free.
+ if (Remove-StudioVenvTreeWithRetry -Path $discard -Label "previous environment" -LinkAware) {
+ $script:StudioVenvDiscardSucceeded = $true
+ substep "previous environment discarded (--no-rollback); a failed install cannot be undone"
+ } else {
+ $script:StudioVenvDiscardLeftover = $discard
+ substep "it is no longer used for rollback; remove $discard by hand to reclaim the space." "Yellow"
+ }
+ return
+ }
substep "previous environment preserved for rollback"
}
function Remove-StudioVenvTreeWithRetry {
param(
[Parameter(Mandatory = $true)][string]$Path,
- [Parameter(Mandatory = $true)][string]$Label
+ [Parameter(Mandatory = $true)][string]$Label,
+ # Only the --no-rollback discard asks for this. Test-StudioPathPresent is the stricter
+ # check and arguably the right default, but making it the default would change what
+ # this reports on installs that never passed the flag, and this change is meant to be
+ # invisible to them.
+ [switch]$LinkAware
)
$lastError = $null
for ($attempt = 1; $attempt -le 3; $attempt++) {
@@ -7059,7 +7307,12 @@ exit 0
} catch {
$lastError = $_.Exception.Message
}
- if (-not (Test-Path -LiteralPath $Path)) { return $true }
+ # Under -LinkAware, Test-Path is not enough: it follows a directory reparse point, so
+ # a dangling one that could not be unlinked reads as absent and this would report a
+ # removal that did not happen. The discard acts on that answer by clearing the
+ # rollback state and telling the user the environment is gone.
+ $stillThere = if ($LinkAware) { Test-StudioPathPresent -Path $Path } else { Test-Path -LiteralPath $Path }
+ if (-not $stillThere) { return $true }
if ($attempt -lt 3) { Start-Sleep -Milliseconds (250 * $attempt) }
}
Write-StudioLine "[WARN] Could not remove $Label at $Path" -ForegroundColor Yellow
@@ -7320,8 +7573,14 @@ exit 0
if ((Get-HostMachineArch) -eq "arm64" -and (Test-Path -LiteralPath $VenvPython -PathType Leaf)) {
$script:PrevVenvPlatformTag = Get-PythonPlatformTag $VenvPython
}
- # New layout already exists -- replace only after preserving rollback copy.
- substep "preserving existing environment for rollback..."
+ # New layout already exists -- replace only after preserving rollback copy, unless the
+ # caller asked for no copy at all, in which case this line would be contradicted by the
+ # "discarded" one Start-StudioVenvRollback prints a moment later.
+ if ($script:StudioNoRollback) {
+ substep "moving the existing environment aside..."
+ } else {
+ substep "preserving existing environment for rollback..."
+ }
try {
Start-StudioVenvRollback -ExistingDir $VenvDir
} catch {
@@ -7397,10 +7656,23 @@ exit 0
# anything the user pip-installed there is not reinstalled. The old tree is kept
# under $StudioHome as unsloth_studio.arm64.* rather than deleted with the ordinary
# rollback, so it can still be read: $script:StudioVenvRollbackPreserve below.
- substep "the ARM64 environment is kept under $StudioHome as unsloth_studio.arm64.*;" "Yellow"
- substep "re-install any extra packages you had added to it, or set UNSLOTH_ALLOW_ARM64_PYTHON=1 to keep it." "Yellow"
+ # Only when there is a tree to keep. Under --no-rollback it is either already gone or
+ # about to be, and the arms below say which; printing this as well leaves the user
+ # looking for an unsloth_studio.arm64.* that was never written, and told that packages
+ # they are about to lose are recoverable.
+ if (-not ($script:StudioVenvRollbackDiscarded -or $script:StudioNoRollback)) {
+ substep "the ARM64 environment is kept under $StudioHome as unsloth_studio.arm64.*;" "Yellow"
+ substep "re-install any extra packages you had added to it, or set UNSLOTH_ALLOW_ARM64_PYTHON=1 to keep it." "Yellow"
+ }
try {
- if ($script:StudioVenvRollbackActive) {
+ if ($script:StudioVenvRollbackDiscarded) {
+ # --no-rollback already deleted it. There is nothing to move and nothing to
+ # keep, and calling Start-StudioVenvRollback here would try to rename a
+ # directory that is gone, throw, and take the whole migration out through
+ # Exit-InstallFailure -- after the environment had already been destroyed.
+ substep "the previous ARM64 environment was discarded by --no-rollback, so there is" "Yellow"
+ substep "nothing to copy packages out of; the x64 environment is built fresh." "Yellow"
+ } elseif ($script:StudioVenvRollbackActive) {
# The ordinary reinstall already moved this environment aside; a second
# Start-StudioVenvRollback would try to move a directory that is no longer
# there and throw, taking every architecture migration out through
@@ -7409,9 +7681,18 @@ exit 0
$script:StudioVenvRollbackPreserve = $true
} else {
Start-StudioVenvRollback -ExistingDir $VenvDir
- # After the move, so a rollback that never started cannot leave the flag set
- # for some later unrelated rollback to act on.
- $script:StudioVenvRollbackPreserve = $true
+ if ($script:StudioVenvRollbackDiscarded) {
+ # --no-rollback discarded it inside that call, so there is no tree to
+ # preserve and setting the flag would mark one that does not exist. The
+ # user asked for no old environments kept and that is what they get; say
+ # so here, where a moment ago the message promised the opposite.
+ substep "the previous ARM64 environment was discarded by --no-rollback rather than kept;" "Yellow"
+ substep "the x64 environment is built fresh, and extra packages are not recoverable." "Yellow"
+ } else {
+ # After the move, so a rollback that never started cannot leave the flag set
+ # for some later unrelated rollback to act on.
+ $script:StudioVenvRollbackPreserve = $true
+ }
}
} catch {
Write-StudioLine "[ERROR] Could not move the ARM64 environment aside: $($_.Exception.Message)" -ForegroundColor Red
@@ -7445,7 +7726,14 @@ exit 0
if ($_woaMigPlatform -ne "win-arm64") {
$_woaMigLabel = if ($_woaMigPlatform) { $_woaMigPlatform } else { "unknown" }
substep "windows on arm: the migrated environment is $_woaMigLabel, not win-arm64 --" "Yellow"
- substep "rebuilding it as ARM64; the previous one is kept for rollback." "Yellow"
+ # Varied, not printed flat: the call below discards under --no-rollback, and telling
+ # the user the previous environment is recoverable when it is about to be deleted is
+ # the same promise the ARM64 mismatch branch above already had to stop making.
+ if ($script:StudioNoRollback) {
+ substep "rebuilding it as ARM64; --no-rollback discards the previous one rather than keeping it." "Yellow"
+ } else {
+ substep "rebuilding it as ARM64; the previous one is kept for rollback." "Yellow"
+ }
try {
Start-StudioVenvRollback -ExistingDir $VenvDir
# Left set, the install step below would --no-deps into an empty venv.
@@ -8653,47 +8941,6 @@ exit 0
# true on unmapped arches too, and those install CPU torch.
$AmdHasGpuWheels = [bool]($ROCmGfxArch -and $archFamilyMap.ContainsKey($ROCmGfxArch))
- # ── Bounded "ask the venv python" probe ──
- # A wedged torch import or a hanging Intel driver init -- what the XPU probes below exist to
- # detect -- would block a bare `& python -c ...` forever. ProcessStartInfo, not &, so stderr
- # cannot trip $ErrorActionPreference; BOTH streams drain async so a noisy import cannot
- # deadlock on a full pipe; WaitForExit bounds the wait and kills the child. Every failure
- # (timeout, crash, exception) reads as .Ok = $false; .Error carries WHICH one, since stderr
- # used to be drained and discarded, leaving a driver-level DLL load error and a missing torch
- # indistinguishable. Defined above the Intel scan: PowerShell binds a function when it runs.
- function Invoke-BoundedPythonProbe {
- param([string]$PythonExe, [string]$Code, [int]$TimeoutSec = 30)
- $result = [pscustomobject]@{ Ok = $false; Output = ""; Error = "" }
- if (-not $PythonExe -or -not $Code) { return $result }
- try {
- $psi = New-Object System.Diagnostics.ProcessStartInfo
- $psi.FileName = $PythonExe
- $psi.Arguments = "-c `"$Code`""
- $psi.RedirectStandardOutput = $true
- $psi.RedirectStandardError = $true
- $psi.UseShellExecute = $false
- $psi.CreateNoWindow = $true
- $proc = [System.Diagnostics.Process]::Start($psi)
- $outTask = $proc.StandardOutput.ReadToEndAsync()
- $errTask = $proc.StandardError.ReadToEndAsync()
- if (-not $proc.WaitForExit($TimeoutSec * 1000)) {
- try { $proc.Kill() } catch {}
- # Synthesised, not read back: waiting on the reader tasks of a wedged child
- # would reintroduce the hang this helper exists to bound.
- $result.Error = "python did not answer within $TimeoutSec seconds"
- return $result
- }
- $result.Output = $outTask.GetAwaiter().GetResult()
- # Kept, not discarded: the only place a failed probe's OSError / WinError text exists.
- $result.Error = $errTask.GetAwaiter().GetResult()
- $result.Ok = ($proc.ExitCode -eq 0)
- return $result
- } catch {
- $result.Error = $_.Exception.Message
- return $result
- }
- }
-
# Bounded Win32_VideoController scan: the query can block forever on a degraded WMI
# repository, -ErrorAction only suppresses reported errors, and -OperationTimeoutSec is not
# enforced for the local COM session this uses, so out of process with a wall-clock kill is
@@ -8808,6 +9055,13 @@ exit 0
# A rerun has already moved the old venv to $script:StudioVenvRollbackDir and put an
# empty one in its place, so probing $VenvPython would ask an interpreter with no torch.
# Ask the preserved environment instead -- that is the migrated runtime this rescues.
+ # --no-rollback deleted that environment, so the answer was taken before it went. Same
+ # verdict, same effect: opting out of the rollback copy must not narrow the device set.
+ if ($script:StudioPreservedXpuVerdict) {
+ $HasIntelGpu = $true
+ $script:IsIntelXpu = $true
+ if (-not $IntelGpuLabel) { $IntelGpuLabel = "Intel GPU (detected by PyTorch XPU)" }
+ }
$_xpuProbePy = $VenvPython
if ($script:StudioVenvRollbackDir) {
$_rollbackPy = Join-Path $script:StudioVenvRollbackDir "Scripts\python.exe"
diff --git a/install.sh b/install.sh
index 13ee08d39a1..06e76b64d22 100755
--- a/install.sh
+++ b/install.sh
@@ -1,5 +1,5 @@
#!/bin/sh
-# Unsloth Studio Installer. Usage, supported options and the web one-liner live in the README under "Unsloth Studio (web UI)" and are deliberately not repeated here: this file ships inside the Linux desktop bundle, where a header rehearsing download-and-run command lines is the first thing a generic script classifier reads. A piped install takes options as environment variables after the pipe (UNSLOTH_NO_TORCH, UNSLOTH_SKIP_AUTOSTART, UNSLOTH_ISOLATE_UV_CACHE, UNSLOTH_PYTHON, UNSLOTH_STUDIO_HOME), because a bare `--no-torch` after the pipe would be read as an option to sh itself; a local run takes the equivalent flags (--no-torch, --isolated-uv-cache, --python, --local). Install dir priority: UNSLOTH_STUDIO_HOME > STUDIO_HOME > $HOME/.unsloth/studio
+# Unsloth Studio Installer. Usage, supported options and the web one-liner live in the README under "Unsloth Studio (web UI)" and are deliberately not repeated here: this file ships inside the Linux desktop bundle, where a header rehearsing download-and-run command lines is the first thing a generic script classifier reads. A piped install takes options as environment variables after the pipe (UNSLOTH_NO_TORCH, UNSLOTH_SKIP_AUTOSTART, UNSLOTH_ISOLATE_UV_CACHE, UNSLOTH_INSTALL_NO_ROLLBACK, UNSLOTH_PYTHON, UNSLOTH_STUDIO_HOME), because a bare `--no-torch` after the pipe would be read as an option to sh itself; a local run takes the equivalent flags (--no-torch, --isolated-uv-cache, --no-rollback, --python, --local). Install dir priority: UNSLOTH_STUDIO_HOME > STUDIO_HOME > $HOME/.unsloth/studio
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
set -e
@@ -39,6 +39,10 @@ _USER_PYTHON=""
_NO_TORCH_FLAG=false
_SKIP_AUTOSTART=false
_ISOLATE_UV_CACHE=false
+_NO_ROLLBACK=false
+# Set by the discard itself, so the disk-full remedy can describe what happened rather than what was requested.
+_VENV_DISCARDED=false
+_VENV_DISCARD_LEFTOVER=""
_VERBOSE=false
_SHORTCUTS_ONLY=false
_next_is_package=false
@@ -68,6 +72,7 @@ for arg in "$@"; do
--python) _next_is_python=true ;;
--no-torch) _NO_TORCH_FLAG=true ;;
--isolated-uv-cache) _ISOLATE_UV_CACHE=true ;;
+ --no-rollback) _NO_ROLLBACK=true ;;
--verbose|-v) _VERBOSE=true ;;
--shortcuts-only) _SHORTCUTS_ONLY=true ;;
--with-llama-cpp-dir) _next_is_llama_cpp_dir=true ;;
@@ -78,6 +83,7 @@ done
case "${UNSLOTH_NO_TORCH:-}" in 1|true|TRUE|yes|YES|on|ON) _NO_TORCH_FLAG=true ;; esac
case "${UNSLOTH_SKIP_AUTOSTART:-}" in 1|true|TRUE|yes|YES|on|ON) _SKIP_AUTOSTART=true ;; esac
case "${UNSLOTH_ISOLATE_UV_CACHE:-}" in 1|true|TRUE|yes|YES|on|ON) _ISOLATE_UV_CACHE=true ;; esac
+case "${UNSLOTH_INSTALL_NO_ROLLBACK:-}" in 1|true|TRUE|yes|YES|on|ON) _NO_ROLLBACK=true ;; esac
[ -z "$_USER_PYTHON" ] && [ -n "${UNSLOTH_PYTHON:-}" ] && _USER_PYTHON="$UNSLOTH_PYTHON"
if [ "$_VERBOSE" = true ]; then
@@ -1085,9 +1091,53 @@ _start_studio_venv_replacement() {
_VENV_ROLLBACK_DIR=""
return 1
fi
+ # --no-rollback / UNSLOTH_INSTALL_NO_ROLLBACK: drop the old environment now instead of at commit, for the disk-constrained cross-volume case. The rename still happens first, so uv never builds into an occupied path. Clearing the state before the delete is what the commit path does too: a signal must not restore a half-deleted backup.
+ if [ "${_NO_ROLLBACK:-false}" = true ]; then
+ _VENV_ROLLBACK_ACTIVE=false
+ _VENV_ROLLBACK_DIR=""
+ rm -rf "$_candidate" 2>/dev/null || true
+ # -f exempts a missing path from the exit status, not a real unlink failure: an immutable entry, a busy mount point, a sticky-bit parent. Reporting "discarded" there promises space that was never freed, in the one situation this flag exists for. The state above stays cleared either way -- re-arming the rollback would hand an interrupt a half-deleted backup -- so say what is actually on disk.
+ if [ -e "$_candidate" ] || [ -L "$_candidate" ]; then
+ _VENV_DISCARD_LEFTOVER="$_candidate"
+ substep "could not discard the previous environment at $_candidate" "$C_WARN"
+ substep "it is no longer used for rollback; remove it by hand to reclaim the space." "$C_WARN"
+ else
+ _VENV_DISCARDED=true
+ substep "previous environment discarded (--no-rollback); a failed install cannot be undone"
+ fi
+ return 0
+ fi
substep "previous environment preserved for rollback"
}
+_free_space_kb() { # path
+ df -Pk "$1" 2>/dev/null | awk 'NR == 2 { print $4 }'
+}
+
+# Sets _DISK_FULL_SUFFIX to a one-line diagnosis, or empty. Below 64 MiB nothing useful can be unpacked, so a full disk is the cause rather than a coincidence (#11313). Callers fold the suffix into the ERROR_DEFAULT message as well as printing it, because under --tauri the desktop app reads that message and a diagnosis printed only beside it is one the UI never shows.
+_set_disk_full_suffix() {
+ _DISK_FULL_SUFFIX=""
+ _DISK_FULL_REMEDY=""
+ _DISK_FULL_MB=""
+ [ -n "${STUDIO_HOME:-}" ] || return 0
+ _dfs_free=$(_free_space_kb "$STUDIO_HOME")
+ [ -n "$_dfs_free" ] || return 0
+ [ "$_dfs_free" -lt 65536 ] 2>/dev/null || return 0
+ _DISK_FULL_MB=$((_dfs_free / 1024))
+ # What to advise depends on what actually happened to the old environment, not on what was asked for. A discard that failed left a tree behind, and deleting that tree is very likely what makes the retry fit; telling that user there is nothing left to reclaim sends them away from the one thing that would help.
+ if [ -n "${_VENV_DISCARD_LEFTOVER:-}" ]; then
+ _DISK_FULL_REMEDY="Free some space and re-run. The previous environment could not be removed and is still at $_VENV_DISCARD_LEFTOVER; deleting it will reclaim that space."
+ elif [ "${_VENV_DISCARDED:-false}" = true ]; then
+ _DISK_FULL_REMEDY="Free some space and re-run. The previous environment was already discarded by --no-rollback, so the installer has nothing further of its own to reclaim."
+ elif [ "${_NO_ROLLBACK:-false}" = true ]; then
+ # Asked for, but nothing was there to discard: a first install, or a failure before the replacement began. Naming the flag again would describe a re-run that changes nothing.
+ _DISK_FULL_REMEDY="Free some space and re-run."
+ else
+ _DISK_FULL_REMEDY="Free some space and re-run. --no-rollback (UNSLOTH_INSTALL_NO_ROLLBACK=1) drops the previous environment instead of keeping a copy of it during the install."
+ fi
+ _DISK_FULL_SUFFIX=": $STUDIO_HOME has only $_DISK_FULL_MB MB free, so the disk is full, which is very likely the cause. $_DISK_FULL_REMEDY"
+}
+
# uv creates only into a path that is absent or an empty directory. Everything else is occupied, hidden entries and non-resolving symlinks included.
_dir_has_entries() { # dir
if [ ! -d "$1" ]; then
@@ -1227,9 +1277,24 @@ _cleanup_install_temporaries() {
_on_install_exit() {
_status=$?
if [ "$_status" -ne 0 ]; then
+ # Restoring comes first, and nothing below it may be able to prevent it. Putting the
+ # diagnosis ahead of this put a pair of writes under `set -e` in front of the only code
+ # that puts the user's environment back: a closed --tauri stdout, or a redirected stderr,
+ # fails the write, and the trap then aborts with the previous environment still moved
+ # aside. A diagnostic must never be able to cost someone their install.
+ # Measured here and reported further down, which is not the same thing as doing both in one place. The restore immediately below deletes the half-built replacement, and that can free gigabytes: ask afterwards and a disk that really was full reads as healthy, so the early failure it just caused goes back to being a bare exit code. `|| true` because a measurement must not be able to abort the restore either.
+ if [ "${_DISK_FULL_REPORTED:-false}" != true ] && command -v _set_disk_full_suffix >/dev/null 2>&1; then
+ _set_disk_full_suffix || true
+ fi
_restore_studio_venv_replacement
# Separate from the venv restore: an install can fail before one is in flight.
_restore_uv_cache_marker
+ # Every earlier failure lands here, and the largest writes -- the venv and the torch install -- are all earlier, so a disk that filled during them used to surface as a bare exit code (#11313). Written only after the restore, and every write `|| true`, because a closed --tauri stdout must not abort the trap before the environment is back.
+ if [ "${_DISK_FULL_REPORTED:-false}" != true ] && [ -n "${_DISK_FULL_SUFFIX:-}" ]; then
+ tauri_log "ERROR_DEFAULT" "unsloth studio install failed (exit code $_status)$_DISK_FULL_SUFFIX" || true
+ echo " $STUDIO_HOME has only $_DISK_FULL_MB MB free -- the disk is full, which is very likely the cause." >&2 || true
+ echo " $_DISK_FULL_REMEDY" >&2 || true
+ fi
fi
_cleanup_install_temporaries
exit "$_status"
@@ -3495,8 +3560,12 @@ if [ -x "$VENV_DIR/bin/python" ] || _dir_has_entries "$VENV_DIR"; then
# _run_bounded the fallback: without version.py it hits `import torch`, which can wedge.
[ -n "$_PREV_TORCH_VER" ] || _PREV_TORCH_VER=$(_run_bounded "$VENV_DIR/bin/python" -c \
"import torch; print(torch.__version__)" 2>/dev/null | tail -n 1 || true)
- # New layout already exists — replace only after preserving rollback copy.
- substep "preserving existing environment for rollback..."
+ # New layout already exists — replace only after preserving rollback copy, unless the caller asked for no copy at all, in which case this line would be contradicted by the "discarded" one _start_studio_venv_replacement prints a moment later. install.ps1 varies its twin the same way.
+ if [ "${_NO_ROLLBACK:-false}" = true ]; then
+ substep "moving the existing environment aside..."
+ else
+ substep "preserving existing environment for rollback..."
+ fi
# A bare call still aborts under `set -e`, but shows only mv's own stderr. install.ps1 reports this step; say the same here and name the directory.
if ! _start_studio_venv_replacement "$VENV_DIR"; then
echo "ERROR: could not move $VENV_DIR aside to reinstall." >&2
@@ -7745,11 +7814,21 @@ fi
# If setup.sh failed, report and exit now.
if [ "$_SETUP_EXIT" -ne 0 ]; then
echo ""
+ # A full disk surfaces here as nothing but an exit code, with the one "No space left on device" line buried in setup's output (#11313). Ask the filesystem directly and name it. Below 64 MiB nothing useful can be unpacked, so it is the cause rather than a coincidence.
+ # Folded into the ERROR_DEFAULT message as well, not only stderr: under --tauri the desktop app reads that message, so a diagnosis printed beside it is one the UI never shows. One line, because a marker is one line.
+ _set_disk_full_suffix
if [ "$TAURI_MODE" = true ]; then
- tauri_log "ERROR_DEFAULT" "studio setup failed (exit code $_SETUP_EXIT)"
+ tauri_log "ERROR_DEFAULT" "studio setup failed (exit code $_SETUP_EXIT)$_DISK_FULL_SUFFIX"
else
step "error" "studio setup failed (exit code $_SETUP_EXIT)" "$C_ERR"
fi
+ if [ -n "$_DISK_FULL_SUFFIX" ]; then
+ # `|| true` for the same reason the exit trap guards its copy: a closed --tauri stdout or a redirected stderr must not turn a diagnostic into the thing that decides the exit status.
+ echo " $STUDIO_HOME has only $_DISK_FULL_MB MB free -- the disk is full, which is very likely the cause." >&2 || true
+ echo " $_DISK_FULL_REMEDY" >&2 || true
+ fi
+ # Reported here, so the exit trap does not say it twice.
+ _DISK_FULL_REPORTED=true
echo ""
exit "$_SETUP_EXIT"
fi
diff --git a/tests/python/test_cross_platform_parity.py b/tests/python/test_cross_platform_parity.py
index 06515d8ded8..7bb1b4dac62 100644
--- a/tests/python/test_cross_platform_parity.py
+++ b/tests/python/test_cross_platform_parity.py
@@ -1516,3 +1516,392 @@ class TestInstallUvCacheRootParity:
assert "Set-StudioUvCacheForLaunch" in source
assert "Set-Item -LiteralPath Env:UV_CACHE_DIR -Value $PreviousValue" in source
assert "Remove-Item -LiteralPath Env:UV_CACHE_DIR" in source
+
+
+class TestWindowsMountPointVolumes:
+ """A Windows volume can be mounted at a DIRECTORY rather than a drive letter. GetPathRoot
+ reduces C:\\studio to C:\\, so DriveInfo answers for the host drive and two paths on
+ different mounted volumes compare equal on their root: the rollback-space warning is then
+ suppressed or falsely emitted, and the cross-volume cache notice never fires. Win32_Volume
+ lists mount points by the path they are mounted at. Pinned by text because no host in CI
+ has a directory mount point to exercise (#11313)."""
+
+ def test_free_space_asks_the_mounted_volume_first(self):
+ text = INSTALL_PS1.read_text(encoding = "utf-8")
+ assert "Win32_Volume" in text, "install.ps1 does not consult the mount-point view"
+ helper = text.split("function Get-StudioFreeSpaceBytes", 1)[1].split(
+ "function Get-StudioTreeSizeBytes", 1
+ )[0]
+ assert (
+ "Get-StudioMountedVolume" in helper
+ ), "Get-StudioFreeSpaceBytes falls straight through to the drive root"
+ assert "DriveInfo" in helper, "the drive-root fallback was dropped"
+
+ def test_the_probe_is_gated_on_windows(self):
+ # CimCmdlets ships only on Windows, and this helper is reached on every platform.
+ text = INSTALL_PS1.read_text(encoding = "utf-8")
+ helper = text.split("function Get-StudioMountedVolume", 1)[1].split("\n }", 1)[0]
+ assert (
+ "$IsWindows" in helper and "Windows_NT" in helper
+ ), "Get-StudioMountedVolume would call Get-CimInstance off Windows"
+
+
+class TestDiskFullDiagnosisReachesTauri:
+ """The desktop installer and its Repair flow run with --tauri, and there the only thing the
+ UI and its logs ever see is the message handed to the ERROR_DEFAULT marker. A disk-full
+ diagnosis printed beside that message is one the desktop user never reads, which is the
+ scenario #11313 was reported from."""
+
+ def test_shell_folds_the_diagnosis_into_the_marker(self):
+ text = INSTALL_SH.read_text(encoding = "utf-8")
+ assert (
+ 'tauri_log "ERROR_DEFAULT" "studio setup failed (exit code $_SETUP_EXIT)$_DISK_FULL_SUFFIX"'
+ in text
+ ), "install.sh keeps the disk-full diagnosis out of the Tauri message"
+
+ def test_windows_folds_the_diagnosis_into_the_failure_message(self):
+ """Appended inside Exit-InstallFailure, so every caller carries it rather than the one
+ site that remembered to build a suffix."""
+ text = INSTALL_PS1.read_text(encoding = "utf-8")
+ body = text.split("function Exit-InstallFailure", 1)[1].split("\n }", 1)[0]
+ append = body.index('$Message = "$Message$_diskSuffix"')
+ marker = body.index('Write-TauriLog "ERROR_DEFAULT" $Message')
+ assert append < marker, "the diagnosis is appended after the Tauri marker is written"
+
+ def test_windows_measures_in_both_modes(self):
+ # The probe must sit OUTSIDE the non-Tauri console branch, or --tauri never measures.
+ text = INSTALL_PS1.read_text(encoding = "utf-8")
+ body = text.split("function Exit-InstallFailure", 1)[1].split("\n }", 1)[0]
+ probe = body.index("Get-StudioFreeSpaceBytes")
+ guard = body.index("if (-not $TauriMode) {")
+ assert (
+ probe < guard
+ ), "the free-space probe runs only in the non-Tauri branch, so --tauri never measures"
+
+
+class TestDiskFullDiagnosisCoversTheBiggestWrites:
+ """The venv and the torch install are the largest writes an install makes, and both fail long
+ before studio setup is reached. A diagnosis attached only to the studio-setup branch therefore
+ misses the most likely moment for the disk to fill, and those exits report a bare exit code.
+ Both installers attach it to the one funnel every failure passes through instead."""
+
+ def test_windows_attaches_it_to_the_shared_exit(self):
+ text = INSTALL_PS1.read_text(encoding = "utf-8")
+ body = text.split("function Exit-InstallFailure", 1)[1].split("\n }", 1)[0]
+ assert "Get-StudioFreeSpaceBytes" in body, "only the studio-setup branch is diagnosed"
+ # Probed rather than called outright: the early exits happen before it is defined.
+ assert (
+ "Get-Command Get-StudioFreeSpaceBytes" in body
+ ), "an exit before the helper is defined would report command-not-found instead"
+
+ def test_the_shell_attaches_it_to_the_exit_trap(self):
+ text = INSTALL_SH.read_text(encoding = "utf-8")
+ body = text.split("_on_install_exit() {", 1)[1].split("\n}", 1)[0]
+ assert "_set_disk_full_suffix" in body, "earlier failures exit without a diagnosis"
+ assert (
+ "command -v _set_disk_full_suffix" in body
+ ), "argument parsing exits before the helper exists"
+
+ def test_the_shell_does_not_report_it_twice(self):
+ """The studio-setup branch reports with its own wording, and the trap runs afterwards."""
+ text = INSTALL_SH.read_text(encoding = "utf-8")
+ assert "_DISK_FULL_REPORTED=true" in text
+ assert '"${_DISK_FULL_REPORTED:-false}" != true' in text
+
+
+class TestDiagnosticsNeverCostTheRollback:
+ """The diagnosis is the least important thing either installer does on a failure, and the
+ restore is the most important. A closed --tauri stdout or a redirected stderr fails the write,
+ and under `set -e` that used to abort the exit trap before the restore ran, leaving the
+ previous environment moved aside and the install gone (#11313)."""
+
+ def test_the_shell_restores_before_it_reports(self):
+ """Measure first, restore, then report. Reporting before the restore lets a failed write
+ abort the trap; measuring after it reads a disk the restore has just emptied."""
+ text = INSTALL_SH.read_text(encoding = "utf-8")
+ body = text.split("_on_install_exit() {", 1)[1].split("\n}", 1)[0]
+ measure = body.index("_set_disk_full_suffix || true")
+ restore = body.index("_restore_studio_venv_replacement")
+ report = body.index("tauri_log")
+ assert measure < restore, "the restore frees space before the disk is measured"
+ assert restore < report, "a failed diagnostic write can abort the trap before the restore"
+
+ def test_the_windows_probe_precedes_its_restore_too(self):
+ text = INSTALL_PS1.read_text(encoding = "utf-8")
+ body = text.split("function Exit-InstallFailure", 1)[1].split("\n }", 1)[0]
+ assert body.index("Get-StudioFreeSpaceBytes") < body.index(
+ "Restore-StudioVenvRollback"
+ ), "the rollback restore frees space before the disk is measured"
+
+ def test_the_shell_diagnostics_are_best_effort(self):
+ text = INSTALL_SH.read_text(encoding = "utf-8")
+ body = text.split("_on_install_exit() {", 1)[1].split("\n}", 1)[0]
+ writes = [
+ line.strip()
+ for line in body.splitlines()
+ if ("echo " in line or "tauri_log " in line) and not line.strip().startswith("#")
+ ]
+ assert writes, "the trap no longer writes anything, so this test pins nothing"
+ for line in writes:
+ assert line.endswith("|| true"), f"under set -e this write can abort the trap: {line}"
+
+ def test_the_windows_diagnosis_cannot_escape(self):
+ """PowerShell has no `set -e`, but the installer body runs under $ErrorActionPreference
+ Stop, so a write to a closed handle throws. Containing it is the same requirement."""
+ text = INSTALL_PS1.read_text(encoding = "utf-8")
+ body = text.split("function Exit-InstallFailure", 1)[1].split("\n }", 1)[0]
+ probe = body.index("Get-StudioFreeSpaceBytes")
+ opened = body.rindex("try {", 0, probe)
+ closed = body.index("} catch", probe)
+ assert opened < probe < closed, "the disk probe is not inside a try/catch"
+
+
+class TestDiskFullRemedyDescribesWhatHappened:
+ """A run that ran out of space must be told what would actually help, and that depends on what
+ became of the old environment rather than on which flag was passed. The case that matters is a
+ discard that FAILED: the tree is still on disk, deleting it is very likely what makes the retry
+ fit, and "there is nothing further to reclaim" points the user away from it."""
+
+ @pytest.mark.parametrize(
+ "path, leftover",
+ [
+ (INSTALL_SH, "_VENV_DISCARD_LEFTOVER"),
+ (INSTALL_PS1, "$script:StudioVenvDiscardLeftover"),
+ ],
+ ids = ["install.sh", "install.ps1"],
+ )
+ def test_a_failed_discard_names_the_tree_it_left(self, path, leftover):
+ text = path.read_text(encoding = "utf-8")
+ block = text.split("is very likely the cause", 1)[0][-2200:]
+ assert leftover in block, f"{path.name} does not consult what the discard actually left"
+ assert (
+ "deleting it will reclaim that space" in text
+ ), f"{path.name} never points at the tree the user can delete"
+
+ @pytest.mark.parametrize(
+ "path, succeeded",
+ [
+ (INSTALL_SH, "_VENV_DISCARDED"),
+ (INSTALL_PS1, "$script:StudioVenvDiscardSucceeded"),
+ ],
+ ids = ["install.sh", "install.ps1"],
+ )
+ def test_the_already_discarded_case_reads_the_outcome_not_the_flag(self, path, succeeded):
+ """Inferring it from the flag also claims a fresh install discarded something."""
+ text = path.read_text(encoding = "utf-8")
+ block = text.split("is very likely the cause", 1)[0][-2200:]
+ assert succeeded in block, f"{path.name} infers the discard from the request"
+ assert "already discarded by --no-rollback" in text
+
+ @pytest.mark.parametrize(
+ "path",
+ [INSTALL_SH, INSTALL_PS1],
+ ids = ["install.sh", "install.ps1"],
+ )
+ def test_the_flag_is_not_advised_to_a_run_that_used_it(self, path):
+ """The remedy's payload is the opt-out's name, so offering it to someone who already
+ passed it describes a re-run that fails the same way."""
+ text = path.read_text(encoding = "utf-8")
+ block = text.split("is very likely the cause", 1)[0][-2200:]
+ assert (
+ "UNSLOTH_INSTALL_NO_ROLLBACK=1) drops the previous environment" in block
+ ), f"{path.name} lost the remedy for a run that never opted out"
+ flag = "_NO_ROLLBACK" if path is INSTALL_SH else "StudioNoRollback"
+ assert flag in block, f"{path.name} offers the flag unconditionally"
+
+
+class TestVolumeLookupsResolveLinks:
+ """Test-StudioSameVolume canonicalises because junctions and symlinks lie about which volume
+ a path is on. The free-space side has to as well, or a studio home behind a junction (or
+ under a junctioned profile) is measured on the link's host drive rather than the volume that
+ will hold the environment, suppressing or falsely emitting both disk warnings (#11313)."""
+
+ def test_both_volume_lookups_go_through_the_resolver(self):
+ text = INSTALL_PS1.read_text(encoding = "utf-8")
+ assert "function Resolve-StudioVolumeQueryPath" in text
+ for name, end in (
+ ("function Get-StudioMountedVolume", "function Get-StudioFreeSpaceBytes"),
+ ("function Get-StudioFreeSpaceBytes", "function Remove-StudioVenvTreeWithRetry"),
+ ):
+ helper = text.split(name, 1)[1].split(end, 1)[0]
+ assert (
+ "Resolve-StudioVolumeQueryPath" in helper
+ ), f"{name} asks the lexical path, which a junction answers for the wrong volume"
+
+ def test_the_driveinfo_fallback_uses_the_resolved_path(self):
+ # The fallback is the path that runs off Windows and wherever CIM cannot answer.
+ text = INSTALL_PS1.read_text(encoding = "utf-8")
+ helper = text.split("function Get-StudioFreeSpaceBytes", 1)[1].split(
+ "function Get-StudioTreeSizeBytes", 1
+ )[0]
+ assert (
+ "GetFullPath($queryPath)" in helper
+ ), "the DriveInfo fallback still measures the unresolved path"
+
+
+class TestNoRollbackDoesNotNarrowDeviceDetection:
+ """Opting out of the rollback copy must cost disk, never hardware. The Intel scan rescues an
+ adapter WMI cannot classify by asking the PREVIOUS environment's torch whether XPU works,
+ because the replacement venv has no torch yet; discarding that tree without taking the
+ verdict first routes an Arc machine to CPU wheels (#11313)."""
+
+ def test_the_verdict_is_taken_before_the_tree_is_deleted(self):
+ text = INSTALL_PS1.read_text(encoding = "utf-8")
+ discard = text.split("if ($script:StudioNoRollback) {", 1)[1].split(
+ 'substep "previous environment discarded', 1
+ )[0]
+ probe = discard.index("Invoke-BoundedPythonProbe")
+ removal = discard.index("Remove-StudioVenvTreeWithRetry")
+ assert probe < removal, "the tree is deleted before its XPU verdict is taken"
+
+ def test_the_scan_reads_the_preserved_verdict(self):
+ text = INSTALL_PS1.read_text(encoding = "utf-8")
+ assert "$script:StudioPreservedXpuVerdict" in text
+ scan = text.split("$_xpuProbePy = $VenvPython", 1)[0][-900:]
+ assert (
+ "$script:StudioPreservedXpuVerdict" in scan
+ ), "the Intel scan never consults the verdict taken before the discard"
+
+ def test_the_probe_is_defined_before_the_rollback_that_calls_it(self):
+ # PowerShell binds a function when the statement defining it runs, so a helper defined
+ # after its caller is CommandNotFoundException at the call.
+ text = INSTALL_PS1.read_text(encoding = "utf-8")
+ assert text.index("function Invoke-BoundedPythonProbe") < text.index(
+ "function Start-StudioVenvRollback"
+ ), "Invoke-BoundedPythonProbe is defined after the function that calls it"
+
+
+class TestTheVolumeQueryIsBounded:
+ """install.ps1 documents, in Invoke-BoundedVideoControllerScan, that a CIM query can block
+ forever on a degraded WMI repository and that -ErrorAction and try/catch do not bound it.
+ The Win32_Volume lookup runs on every Windows install before the venv exists and only decides
+ the wording of a disk warning, so it takes the same treatment (#11313)."""
+
+ def test_it_runs_out_of_process_with_a_deadline(self):
+ text = INSTALL_PS1.read_text(encoding = "utf-8")
+ helper = text.split("function Get-StudioVolumeList", 1)[1].split(
+ "function Get-StudioMountedVolume", 1
+ )[0]
+ assert (
+ "Start-Job" in helper and "Wait-Job" in helper and "-Timeout" in helper
+ ), "the Win32_Volume query is not bounded by a wall-clock deadline"
+ assert "Stop-Job" in helper, "a query past its deadline is never killed"
+
+ def test_nothing_queries_win32_volume_unbounded(self):
+ text = INSTALL_PS1.read_text(encoding = "utf-8")
+ helper = text.split("function Get-StudioVolumeList", 1)[1].split(
+ "function Get-StudioMountedVolume", 1
+ )[0]
+ # Exactly one call site, and it is the bounded one.
+ assert (
+ text.count("Win32_Volume") == helper.count("Win32_Volume") + 1
+ ), "Win32_Volume is queried somewhere other than the bounded helper"
+
+ def test_the_answer_is_taken_once(self):
+ text = INSTALL_PS1.read_text(encoding = "utf-8")
+ assert (
+ "$script:StudioVolumeList = $null" in text
+ ), "the cached volume list is never reset, so `irm | iex` reuses a previous run's answer"
+
+
+class TestFreeSpaceIsNeverServedFromTheCache:
+ """The volume list is cached so a degraded WMI repository is paid for once, but FreeSpace in
+ a cached row is a snapshot. The failure handler asks after setup has consumed the disk, so a
+ number taken before the environment was built reports room that is gone and misses the
+ disk-full diagnosis this change exists to add (#11313)."""
+
+ def test_the_free_space_caller_asks_for_a_fresh_answer(self):
+ text = INSTALL_PS1.read_text(encoding = "utf-8")
+ helper = text.split("function Get-StudioFreeSpaceBytes", 1)[1].split(
+ "function Get-StudioTreeSizeBytes", 1
+ )[0]
+ assert "-Fresh" in helper, "free space is served from a snapshot taken earlier in the run"
+
+
+class TestVolumeLookupRefusesToGuess:
+ """Get-StudioFinalPath strips the \\\\?\\ prefix unconditionally and deliberately, so a volume
+ with no drive letter comes back as Volume{GUID}\\..., which is not rooted. GetFullPath would
+ anchor that to the current directory and match a volume that has nothing to do with the
+ install, which is worse than answering nothing (#11313)."""
+
+ def test_the_matcher_rejects_an_unrooted_path(self):
+ text = INSTALL_PS1.read_text(encoding = "utf-8")
+ helper = text.split("function Select-StudioVolumeForPath", 1)[1].split(
+ "function Get-StudioVolumeList", 1
+ )[0]
+ assert "IsPathRooted" in helper, "the matcher anchors an unrooted path to the CWD"
+
+ def test_the_resolver_keeps_the_caller_path_when_resolution_is_unrooted(self):
+ text = INSTALL_PS1.read_text(encoding = "utf-8")
+ helper = text.split("function Resolve-StudioVolumeQueryPath", 1)[1].split("\n }", 1)[0]
+ assert (
+ "IsPathRooted" in helper
+ ), "the resolver hands on an unrooted result instead of the caller's own path"
+
+
+class TestRemovalIsConfirmedWithLinkAwareSemantics:
+ """Test-Path follows a Windows directory reparse point, so a dangling one that could not be
+ unlinked reads as absent and the retry helper reports a removal that did not happen. Its
+ callers act on that: the --no-rollback discard clears the rollback state and says the
+ environment is gone (#11313)."""
+
+ def test_the_retry_helper_uses_the_link_aware_check(self):
+ text = INSTALL_PS1.read_text(encoding = "utf-8")
+ helper = text.split("function Remove-StudioVenvTreeWithRetry", 1)[1].split(
+ "\n function ", 1
+ )[0]
+ assert (
+ "Test-StudioPathPresent" in helper
+ ), "the retry helper confirms removal with Test-Path, which a dangling link fools"
+ assert "if (-not (Test-Path -LiteralPath $Path))" not in helper
+
+
+class TestArm64MigrationDoesNotPromiseWhatTheFlagDeletes:
+ """The Windows-on-ARM rebuild tells the user the ARM64 environment is kept as
+ unsloth_studio.arm64.* so extra packages can be recovered. When no rollback has started yet
+ the migration calls Start-StudioVenvRollback itself, and under --no-rollback that call
+ discards, so the promise has to be gated on the flag and not only on an earlier discard."""
+
+ def test_the_promise_is_gated_on_the_flag_too(self):
+ text = INSTALL_PS1.read_text(encoding = "utf-8")
+ gate = text.split("the ARM64 environment is kept under", 1)[0][-400:]
+ assert (
+ "$script:StudioNoRollback" in gate
+ ), "the retention promise is printed on a run whose next call deletes the tree"
+
+ def test_a_discard_inside_the_migration_is_reported(self):
+ text = INSTALL_PS1.read_text(encoding = "utf-8")
+ arm = text.split("Start-StudioVenvRollback -ExistingDir $VenvDir\n if (", 1)
+ assert len(arm) == 2, "the migration does not check what its own rollback call did"
+ assert "discarded by --no-rollback rather than kept" in arm[1][:900]
+
+
+class TestNoRollbackNeverPromisesAKeptCopy:
+ """Every message printed before a call that may discard has to vary on the flag. Three sites
+ promised a recoverable copy and then deleted it: the ordinary reinstall, the ARM64 mismatch
+ rebuild, and the Windows-on-ARM native-CUDA migration rebuild (#11313)."""
+
+ @pytest.mark.parametrize(
+ "path, flag",
+ [
+ (INSTALL_SH, '[ "${_NO_ROLLBACK:-false}" = true ]'),
+ (INSTALL_PS1, "if ($script:StudioNoRollback)"),
+ ],
+ ids = ["install.sh", "install.ps1"],
+ )
+ def test_the_reinstall_message_varies(self, path, flag):
+ text = path.read_text(encoding = "utf-8")
+ before = text.split("preserving existing environment for rollback", 1)[0][-500:]
+ assert flag in before, f"{path.name} promises a rollback copy it may be about to discard"
+
+ def test_the_woa_migration_message_varies(self):
+ text = INSTALL_PS1.read_text(encoding = "utf-8")
+ before = text.split("the previous one is kept for rollback", 1)[0][-600:]
+ assert (
+ "$script:StudioNoRollback" in before
+ ), "the Windows-on-ARM migration rebuild promises a copy --no-rollback deletes"
+
+ def test_every_rollback_call_site_was_audited(self):
+ # If a fourth call site appears, this fails and the promise above it has to be checked.
+ text = INSTALL_PS1.read_text(encoding = "utf-8")
+ assert text.count("Start-StudioVenvRollback -ExistingDir") == 3
diff --git a/tests/python/test_windows_on_arm_python_arch.py b/tests/python/test_windows_on_arm_python_arch.py
index 2b4e254800b..af40363580f 100644
--- a/tests/python/test_windows_on_arm_python_arch.py
+++ b/tests/python/test_windows_on_arm_python_arch.py
@@ -730,12 +730,15 @@ def test_the_architecture_rebuild_does_not_move_the_venv_twice():
keeps it from being swept is missing."""
source = INSTALL_PS1.read_text(encoding = "utf-8")
branch = source.index("windows on arm: the existing environment runs native ARM64 Python")
- tail = source[branch : branch + 2500]
- guard = tail.index("if ($script:StudioVenvRollbackActive)")
- move = tail.index("Start-StudioVenvRollback -ExistingDir $VenvDir")
+ # Searched forward from the branch rather than inside a fixed-size window: a byte count
+ # measures how long the branch happens to be today, so adding an arm to the same if/elseif
+ # chain pushes the move out of view and fails this for a reason that has nothing to do with
+ # what it tests.
+ guard = source.index("if ($script:StudioVenvRollbackActive)", branch)
+ move = source.index("Start-StudioVenvRollback -ExistingDir $VenvDir", branch)
assert guard < move, "the rebuild still moves the environment unconditionally"
assert (
- "$script:StudioVenvRollbackPreserve = $true" in tail[guard:move]
+ "$script:StudioVenvRollbackPreserve = $true" in source[guard:move]
), "an already-active rollback is not marked for preservation"
diff --git a/tests/sh/test_install_rollback_lifecycle.sh b/tests/sh/test_install_rollback_lifecycle.sh
index b0f5dc48bd1..8e0a57d5095 100644
--- a/tests/sh/test_install_rollback_lifecycle.sh
+++ b/tests/sh/test_install_rollback_lifecycle.sh
@@ -504,6 +504,330 @@ marker_case "a committed first install keeps its marker when a later step fails"
"/previous/install/cache" "/tmp/this-attempt-cache" commit
commit_flag_case
+echo "=== --no-rollback discards the old environment instead of keeping a copy (#11313) ==="
+# The rename still has to happen first -- uv creates only into a path that is absent or empty --
+# so what the flag changes is what survives the rename, not whether there is one.
+no_rollback_case() { # label flag_line expect_copy(yes|no)
+ _nr_label="$1"
+ _nr_flag="$2"
+ _nr_expect="$3"
+ _nr_dir="$WORK/no-rollback-$(printf '%s' "$_nr_label" | tr -c 'a-zA-Z0-9' '-')"
+ mkdir -p "$_nr_dir/unsloth_studio"
+ printf 'old\n' > "$_nr_dir/unsloth_studio/generation"
+ _nr_harness="$_nr_dir/harness.sh"
+ {
+ printf '%s\n' 'set -e'
+ printf '%s\n' 'substep() { printf "SUBSTEP %s\n" "$*"; }'
+ printf '%s\n' 'rollback_substep() { substep "$@"; }'
+ printf '%s\n' 'C_WARN=""'
+ printf "STUDIO_HOME='%s'\n" "$_nr_dir"
+ printf "VENV_DIR='%s/unsloth_studio'\n" "$_nr_dir"
+ printf '%s\n' "$_nr_flag"
+ printf '%s\n' "$ROLLBACK_BLOCK"
+ printf '%s\n' '_start_studio_venv_replacement "$VENV_DIR"'
+ } > "$_nr_harness"
+ set +e
+ _nr_out=$(dash "$_nr_harness" 2>&1)
+ _nr_status=$?
+ set -e
+ if [ "$_nr_status" -ne 0 ]; then
+ bad "$_nr_label: harness exited $_nr_status"
+ return
+ fi
+ if find "$_nr_dir" -maxdepth 1 -name 'unsloth_studio.rollback.*' -print -quit | grep -q .; then
+ _nr_got=yes
+ else
+ _nr_got=no
+ fi
+ if [ "$_nr_got" = "$_nr_expect" ]; then
+ ok "$_nr_label"
+ else
+ bad "$_nr_label (rollback copy present: $_nr_got, expected $_nr_expect)"
+ fi
+ # The old venv is gone from its original place either way: the rename is unconditional.
+ if [ ! -e "$_nr_dir/unsloth_studio" ]; then
+ ok "$_nr_label: the old environment was moved aside"
+ else
+ bad "$_nr_label: the old environment is still in place"
+ fi
+ case "$_nr_expect" in
+ no)
+ if printf '%s\n' "$_nr_out" | grep -q 'discarded (--no-rollback)'; then
+ ok "$_nr_label: says the old environment was discarded"
+ else
+ bad "$_nr_label: said nothing about discarding it"
+ fi
+ ;;
+ yes)
+ if printf '%s\n' "$_nr_out" | grep -q 'preserved for rollback'; then
+ ok "$_nr_label: says the old environment was preserved"
+ else
+ bad "$_nr_label: said nothing about preserving it"
+ fi
+ ;;
+ esac
+}
+no_rollback_case "default keeps the rollback copy" "_NO_ROLLBACK=false" yes
+no_rollback_case "flag drops the rollback copy" "_NO_ROLLBACK=true" no
+# Unset is the shape the extracted block sees when the flag parser is not spliced in; it must
+# read as "keep", never as an error under set -e.
+no_rollback_case "an unset flag still keeps the copy" "# no flag set" yes
+
+echo "=== --no-rollback clears the restore state, so a later signal cannot resurrect it ==="
+NR_SIGNAL_DIR="$WORK/no-rollback-signal"
+mkdir -p "$NR_SIGNAL_DIR/unsloth_studio"
+printf 'old\n' > "$NR_SIGNAL_DIR/unsloth_studio/generation"
+{
+ printf '%s\n' 'set -e'
+ printf '%s\n' 'substep() { :; }'
+ printf '%s\n' 'rollback_substep() { substep "$@"; }'
+ printf '%s\n' 'C_WARN=""'
+ printf "STUDIO_HOME='%s'\n" "$NR_SIGNAL_DIR"
+ printf "VENV_DIR='%s/unsloth_studio'\n" "$NR_SIGNAL_DIR"
+ printf '%s\n' '_NO_ROLLBACK=true'
+ printf '%s\n' "$ROLLBACK_BLOCK"
+ printf '%s\n' '_start_studio_venv_replacement "$VENV_DIR"'
+ printf '%s\n' 'mkdir -p "$VENV_DIR"'
+ printf '%s\n' 'printf "partial\n" > "$VENV_DIR/generation"'
+ printf '%s\n' 'kill -TERM $$'
+ printf '%s\n' 'exit 99'
+} > "$NR_SIGNAL_DIR/harness.sh"
+set +e
+dash "$NR_SIGNAL_DIR/harness.sh" >/dev/null 2>&1
+_nr_signal_status=$?
+set -e
+if [ "$_nr_signal_status" -eq 143 ]; then
+ ok "a signal after --no-rollback still exits 143"
+else
+ bad "a signal after --no-rollback exited $_nr_signal_status"
+fi
+# There is nothing to restore, and the half-built environment is what is left. The point is that
+# the restore path does not fail or put back a tree that was deleted.
+if [ ! -e "$NR_SIGNAL_DIR/unsloth_studio" ] \
+ || [ "$(cat "$NR_SIGNAL_DIR/unsloth_studio/generation" 2>/dev/null)" != "old" ]; then
+ ok "--no-rollback does not resurrect the discarded environment"
+else
+ bad "--no-rollback restored an environment it had deleted"
+fi
+
+echo "=== a discard that could not delete says so instead of reporting success (#11313) ==="
+# rm -rf exempts a missing path from its exit status, not a real unlink failure: an immutable
+# entry, a busy mount point, a sticky-bit parent. Shadowing rm is how that is reached portably.
+DISCARD_FAIL_DIR="$WORK/no-rollback-undeletable"
+mkdir -p "$DISCARD_FAIL_DIR/unsloth_studio"
+printf 'old\n' > "$DISCARD_FAIL_DIR/unsloth_studio/generation"
+{
+ printf '%s\n' 'set -e'
+ printf '%s\n' 'substep() { printf "SUBSTEP %s\n" "$1"; }'
+ printf '%s\n' 'rollback_substep() { substep "$@"; }'
+ printf '%s\n' 'C_WARN=""'
+ printf "STUDIO_HOME='%s'\n" "$DISCARD_FAIL_DIR"
+ printf "VENV_DIR='%s/unsloth_studio'\n" "$DISCARD_FAIL_DIR"
+ printf '%s\n' '_NO_ROLLBACK=true'
+ printf '%s\n' "$ROLLBACK_BLOCK"
+ printf '%s\n' 'rm() { return 1; }'
+ printf '%s\n' '_start_studio_venv_replacement "$VENV_DIR"'
+ printf '%s\n' 'echo INSTALL_CONTINUED'
+} > "$DISCARD_FAIL_DIR/harness.sh"
+set +e
+DISCARD_FAIL_OUT=$(dash "$DISCARD_FAIL_DIR/harness.sh" 2>&1)
+DISCARD_FAIL_STATUS=$?
+set -e
+if [ "$DISCARD_FAIL_STATUS" -eq 0 ] && printf '%s\n' "$DISCARD_FAIL_OUT" | grep -q INSTALL_CONTINUED; then
+ ok "a failed discard never aborts the install"
+else
+ bad "a failed discard exited $DISCARD_FAIL_STATUS"
+fi
+if printf '%s\n' "$DISCARD_FAIL_OUT" | grep -q 'could not discard the previous environment'; then
+ ok "a failed discard says the environment is still there"
+else
+ bad "a failed discard said nothing about the tree it could not remove"
+fi
+if printf '%s\n' "$DISCARD_FAIL_OUT" | grep -q 'discarded (--no-rollback)'; then
+ bad "a failed discard still claimed the environment was discarded"
+else
+ ok "a failed discard does not claim success"
+fi
+# Naming the leftover is the whole point: the user came here to reclaim space.
+if printf '%s\n' "$DISCARD_FAIL_OUT" | grep -q "$DISCARD_FAIL_DIR/unsloth_studio.rollback."; then
+ ok "a failed discard names the path left on disk"
+else
+ bad "a failed discard did not name the path left on disk"
+fi
+
+echo "=== a disk that fills before studio setup is still diagnosed (#11313) ==="
+# The venv and the torch install are the biggest writes and both exit long before the studio-setup
+# branch, so the diagnosis has to hang off the exit trap every failure passes through.
+DISK_DIR="$WORK/diskfull"
+mkdir -p "$DISK_DIR"
+DISK_OUT=$(
+ {
+ printf '%s\n' 'set -e'
+ printf '%s\n' 'substep() { :; }'
+ printf '%s\n' 'step() { :; }'
+ printf '%s\n' 'C_WARN=""'
+ printf '%s\n' 'TAURI_MODE=true'
+ printf '%s\n' '_restore_studio_venv_replacement() { :; }'
+ printf '%s\n' '_restore_uv_cache_marker() { :; }'
+ printf '%s\n' '_cleanup_install_temporaries() { :; }'
+ printf "STUDIO_HOME='%s'\n" "$DISK_DIR"
+ printf '%s\n' "$ROLLBACK_BLOCK"
+ # Stubbed after the extraction, so it shadows the real one: filling a disk is not
+ # something this suite can do, and df's own number is whatever the runner happens to have.
+ printf '%s\n' '_free_space_kb() { echo 1024; }'
+ # install.sh defines tauri_log hundreds of lines above this block; the slice starts below it.
+ printf '%s\n' 'tauri_log() { echo "[TAURI:$1] $2"; }'
+ # Any failure at all, standing in for the venv or torch install exiting early.
+ printf '%s\n' 'exit 3'
+ } | dash 2>&1
+) || true
+if printf '%s\n' "$DISK_OUT" | grep -q "the disk is full"; then
+ ok "an early failure names the full disk instead of a bare exit code"
+else
+ bad "an early failure still reports only its exit code: $DISK_OUT"
+fi
+if printf '%s\n' "$DISK_OUT" | grep -q "ERROR_DEFAULT"; then
+ ok "and the diagnosis reaches the Tauri marker the desktop UI reads"
+else
+ bad "the diagnosis never reached the Tauri marker"
+fi
+# A healthy disk must stay silent: the trap runs on every non-zero exit there is.
+DISK_OK_OUT=$(
+ {
+ printf '%s\n' 'set -e'
+ printf '%s\n' 'substep() { :; }'
+ printf '%s\n' 'step() { :; }'
+ printf '%s\n' 'C_WARN=""'
+ printf '%s\n' 'TAURI_MODE=true'
+ printf '%s\n' '_restore_studio_venv_replacement() { :; }'
+ printf '%s\n' '_restore_uv_cache_marker() { :; }'
+ printf '%s\n' '_cleanup_install_temporaries() { :; }'
+ printf "STUDIO_HOME='%s'\n" "$DISK_DIR"
+ printf '%s\n' "$ROLLBACK_BLOCK"
+ printf '%s\n' '_free_space_kb() { echo 104857600; }'
+ printf '%s\n' 'tauri_log() { echo "[TAURI:$1] $2"; }'
+ printf '%s\n' 'exit 3'
+ } | dash 2>&1
+) || true
+if printf '%s\n' "$DISK_OK_OUT" | grep -q "the disk is full"; then
+ bad "a failure with plenty of room blamed the disk: $DISK_OK_OUT"
+else
+ ok "a failure with room to spare does not blame the disk"
+fi
+
+echo "=== a diagnostic write that fails must not cost the rollback (#11313) ==="
+# The trap runs under set -e, so a write to a closed --tauri stdout or a redirected stderr used to
+# abort it before the restore ran, leaving the previous environment moved aside and the install
+# gone. The restore has to happen first and the writes have to be best-effort.
+TRAP_DIR="$WORK/trapsafe"
+mkdir -p "$TRAP_DIR"
+TRAP_OUT=$(
+ {
+ printf '%s\n' 'set -e'
+ printf '%s\n' 'substep() { :; }'
+ printf '%s\n' 'step() { :; }'
+ printf '%s\n' 'C_WARN=""'
+ printf '%s\n' 'TAURI_MODE=true'
+ printf "STUDIO_HOME='%s'\n" "$TRAP_DIR"
+ printf '%s\n' "$ROLLBACK_BLOCK"
+ # After the extraction, so these shadow the real ones rather than being shadowed by them.
+ printf "_restore_studio_venv_replacement() { : > '%s/restored'; }\n" "$TRAP_DIR"
+ printf "_restore_uv_cache_marker() { : > '%s/marker'; }\n" "$TRAP_DIR"
+ printf '%s\n' '_cleanup_install_temporaries() { :; }'
+ printf '%s\n' '_free_space_kb() { echo 1024; }'
+ printf '%s\n' 'tauri_log() { echo "[TAURI:$1] $2"; }'
+ # Both streams closed, so every diagnostic write below fails the way a closed Tauri pipe does.
+ printf '%s\n' 'exec 1>&- 2>&-'
+ printf '%s\n' 'exit 3'
+ } | dash 2>&1
+) || true
+if [ -f "$TRAP_DIR/restored" ]; then
+ ok "the environment is restored even when the diagnostic cannot be written"
+else
+ bad "a failed diagnostic write aborted the trap before the restore"
+fi
+if [ -f "$TRAP_DIR/marker" ]; then
+ ok "and so is the uv cache marker"
+else
+ bad "a failed diagnostic write aborted the trap before the marker restore"
+fi
+
+echo "=== the restore frees space, so the measurement has to precede it (#11313) ==="
+# The restore deletes the half-built replacement. On the failure this diagnosis exists for that
+# tree is gigabytes, so asking the filesystem afterwards reports a disk that is no longer full and
+# the failure it just caused goes back to being a bare exit code.
+FREED_DIR="$WORK/freed"
+mkdir -p "$FREED_DIR"
+FREED_OUT=$(
+ {
+ printf '%s\n' 'set -e'
+ printf '%s\n' 'substep() { :; }'
+ printf '%s\n' 'step() { :; }'
+ printf '%s\n' 'C_WARN=""'
+ printf '%s\n' 'TAURI_MODE=true'
+ printf "STUDIO_HOME='%s'\n" "$FREED_DIR"
+ printf '%s\n' "$ROLLBACK_BLOCK"
+ # Stubbed after the extraction so these shadow the real ones. The restore is what frees
+ # the space, exactly as deleting the partial venv does on a real failure.
+ printf "_restore_studio_venv_replacement() { : > '%s/restored'; }\n" "$FREED_DIR"
+ printf '%s\n' '_restore_uv_cache_marker() { :; }'
+ printf '%s\n' '_cleanup_install_temporaries() { :; }'
+ printf "_free_space_kb() { if [ -f '%s/restored' ]; then echo 104857600; else echo 1024; fi; }\n" "$FREED_DIR"
+ printf '%s\n' 'tauri_log() { echo "[TAURI:$1] $2"; }'
+ printf '%s\n' 'exit 3'
+ } | dash 2>&1
+) || true
+if printf '%s\n' "$FREED_OUT" | grep -q "the disk is full"; then
+ ok "the full disk is still named after the restore has freed the space"
+else
+ bad "the restore hid the full disk from the diagnosis: $FREED_OUT"
+fi
+
+echo "=== the disk-full remedy describes what happened, not what was asked for (#11313) ==="
+# A discard that failed left a tree on disk, and deleting it is very likely what makes the retry
+# fit. Telling that user there is nothing left to reclaim points them away from the one thing that
+# would help, which is the worst of the four answers to give in the one case it is given.
+remedy_case() { # label state_lines expected_grep unexpected_grep
+ _rc_label="$1"; _rc_state="$2"; _rc_want="$3"; _rc_not="$4"
+ _rc_out=$(
+ {
+ printf '%s\n' 'substep() { :; }'
+ printf '%s\n' 'step() { :; }'
+ printf '%s\n' 'C_WARN=""'
+ printf "STUDIO_HOME='%s'\n" "$WORK"
+ printf '%s\n' "$ROLLBACK_BLOCK"
+ printf '%s\n' '_free_space_kb() { echo 1024; }'
+ printf '%s\n' "$_rc_state"
+ printf '%s\n' '_set_disk_full_suffix'
+ printf '%s\n' 'printf "%s\n" "$_DISK_FULL_REMEDY"'
+ } | dash 2>&1
+ )
+ if printf '%s\n' "$_rc_out" | grep -q "$_rc_want"; then
+ ok "$_rc_label names the right remedy"
+ else
+ bad "$_rc_label said: $_rc_out"
+ fi
+ if [ -n "$_rc_not" ]; then
+ if printf '%s\n' "$_rc_out" | grep -q "$_rc_not"; then
+ bad "$_rc_label still says the wrong thing: $_rc_out"
+ else
+ ok "$_rc_label does not say the wrong thing"
+ fi
+ fi
+}
+remedy_case "a discard that left a tree behind" \
+ '_NO_ROLLBACK=true; _VENV_DISCARD_LEFTOVER="/tmp/left-behind"' \
+ "still at /tmp/left-behind" "nothing further"
+remedy_case "a discard that really happened" \
+ '_NO_ROLLBACK=true; _VENV_DISCARDED=true' \
+ "nothing further of its own to reclaim" ""
+remedy_case "the flag with nothing to discard" \
+ '_NO_ROLLBACK=true' \
+ "Free some space and re-run." "already discarded"
+remedy_case "an install that never passed the flag" \
+ '_NO_ROLLBACK=false' \
+ "drops the previous environment" "already discarded"
+
echo ""
echo " PASS: $PASS"
echo " FAIL: $FAIL"
diff --git a/tests/studio/test_install_rollback_lifecycle.ps1 b/tests/studio/test_install_rollback_lifecycle.ps1
index a6ac59d8d76..ccc89e5486d 100644
--- a/tests/studio/test_install_rollback_lifecycle.ps1
+++ b/tests/studio/test_install_rollback_lifecycle.ps1
@@ -24,7 +24,10 @@ $subjectNames = @(
"Remove-StaleStudioVenvRollbacks",
"Restore-StudioVenvRollback",
"Complete-StudioVenvRollback",
- "Restore-StudioUvCacheMarker"
+ "Restore-StudioUvCacheMarker",
+ # Not called by the rollback helpers: the disk-full diagnosis on the failure path calls it,
+ # and it pulls in the mount-point lookup the cases below exercise.
+ "Get-StudioFreeSpaceBytes"
)
$definitions = @{}
@@ -84,6 +87,7 @@ function Write-StudioLine { param([string]$Message, [string]$ForegroundColor) Wr
# not recognized" inside whichever case happened to reach it first. The closure above
# makes an install.ps1-defined callee unreachable by construction; this catches the rest,
# including a helper that calls a sink this file forgot to stub.
+$windowsOnlyCommands = @("Get-CimInstance")
$unresolved = [System.Collections.Generic.List[string]]::new()
foreach ($name in $extracted) {
foreach ($call in $definitions[$name].Body.FindAll({ param($n)
@@ -91,6 +95,11 @@ foreach ($name in $extracted) {
}, $true)) {
$callee = $call.GetCommandName()
if (-not $callee) { continue }
+ # CimCmdlets ships only on Windows and Get-StudioMountedVolume guards its one call.
+ # Keyed on the command being absent, not the platform: $env:OS can say Windows on a host
+ # whose PowerShell has no CimCmdlets, and on a real runner the name is checked as usual.
+ if ($windowsOnlyCommands -contains $callee -and
+ -not (Get-Command -Name $callee -ErrorAction SilentlyContinue)) { continue }
if (-not (Get-Command -Name $callee -ErrorAction SilentlyContinue)) {
$unresolved.Add("$callee (called by $name)")
}
@@ -188,6 +197,295 @@ try {
Microsoft.PowerShell.Management\Remove-Item -LiteralPath Function:\Remove-Item -Force
}
Check "locked rollback deletion retries" ($removed -and $script:removeAttempts -eq 3)
+
+ Write-Host "--no-rollback discards the old environment instead of keeping a copy (#11313)"
+ # The rename still has to happen -- uv creates only into a path that is absent or empty -- so
+ # what the flag changes is what survives it, not whether there is one.
+ foreach ($case in @(
+ @{ Label = "default"; Flag = $false; ExpectCopy = $true },
+ @{ Label = "--no-rollback"; Flag = $true; ExpectCopy = $false })) {
+ [System.IO.Directory]::CreateDirectory($VenvDir) | Out-Null
+ [System.IO.File]::WriteAllText((Join-Path $VenvDir "generation"), "old")
+ Reset-RollbackState $VenvDir
+ $script:StudioNoRollback = $case.Flag
+ Start-StudioVenvRollback -ExistingDir $VenvDir
+ $copies = @(Get-ChildItem -LiteralPath $StudioHome -Directory -Filter "unsloth_studio.rollback.*" -ErrorAction SilentlyContinue)
+ Check "$($case.Label): rollback copy kept = $($case.ExpectCopy)" (($copies.Count -gt 0) -eq $case.ExpectCopy)
+ Check "$($case.Label): the old environment was moved aside" (-not (Test-Path -LiteralPath $VenvDir))
+ if (-not $case.ExpectCopy) {
+ # Cleared before the delete, exactly as the commit path does: an interrupt must not be
+ # handed a backup that is already half gone.
+ Check "--no-rollback clears the restore state" (
+ (-not $script:StudioVenvRollbackActive) -and ($null -eq $script:StudioVenvRollbackDir))
+ # And the restore must then be a no-op rather than a failure.
+ $restoreThrew = $false
+ try { Restore-StudioVenvRollback } catch { $restoreThrew = $true }
+ Check "--no-rollback leaves nothing for the restore to do" (
+ (-not $restoreThrew) -and (-not (Test-Path -LiteralPath $VenvDir)))
+ }
+ foreach ($c in $copies) { Microsoft.PowerShell.Management\Remove-Item -LiteralPath $c.FullName -Recurse -Force -ErrorAction SilentlyContinue }
+ }
+ $script:StudioNoRollback = $false
+
+ Write-Host "--no-rollback tells the ARM64 migration the tree is gone (#11313)"
+ # The migration branch reads the rollback state. "Inactive" means "not moved aside yet", so
+ # without a separate discarded flag it called Start-StudioVenvRollback on a directory
+ # --no-rollback had deleted, threw, and exited having already destroyed the environment.
+ [System.IO.Directory]::CreateDirectory($VenvDir) | Out-Null
+ [System.IO.File]::WriteAllText((Join-Path $VenvDir "generation"), "old")
+ Reset-RollbackState $VenvDir
+ $script:StudioVenvRollbackDiscarded = $false
+ $script:StudioNoRollback = $true
+ Start-StudioVenvRollback -ExistingDir $VenvDir
+ Check "--no-rollback records that the tree was discarded" ($script:StudioVenvRollbackDiscarded)
+ Check "and the tree really is gone" (-not (Test-Path -LiteralPath $VenvDir))
+ # Replay the branch's own decision: neither the "already moved aside" nor the "move it" arm.
+ $wouldMove = (-not $script:StudioVenvRollbackDiscarded) -and (-not $script:StudioVenvRollbackActive)
+ Check "the migration would not try to move a tree that is gone" (-not $wouldMove)
+ # Where no rollback has started the migration calls Start-StudioVenvRollback itself, and
+ # under --no-rollback that DISCARDS after the retention message has printed. Re-checking the
+ # gate here would test this file (it is pinned by text in the parity suite); what is drivable
+ # is that nothing may be marked preserved once the tree is gone.
+ [System.IO.Directory]::CreateDirectory($VenvDir) | Out-Null
+ [System.IO.File]::WriteAllText((Join-Path $VenvDir "generation"), "old")
+ Reset-RollbackState $VenvDir
+ $script:StudioVenvRollbackDiscarded = $false
+ $script:StudioVenvRollbackPreserve = $false
+ $script:StudioNoRollback = $true
+ Start-StudioVenvRollback -ExistingDir $VenvDir
+ Check "a discard inside the migration is not marked as a preserved tree" (
+ $script:StudioVenvRollbackDiscarded -and -not $script:StudioVenvRollbackPreserve)
+ $script:StudioNoRollback = $false
+ $script:StudioVenvRollbackDiscarded = $false
+
+ # The ordinary path must still report "not discarded", or the migration would skip a tree
+ # that is genuinely sitting there waiting to be kept.
+ [System.IO.Directory]::CreateDirectory($VenvDir) | Out-Null
+ [System.IO.File]::WriteAllText((Join-Path $VenvDir "generation"), "old")
+ Reset-RollbackState $VenvDir
+ Start-StudioVenvRollback -ExistingDir $VenvDir
+ Check "the ordinary path does not claim the tree was discarded" (-not $script:StudioVenvRollbackDiscarded)
+ Check "and it is still there to be kept" ($null -ne $script:StudioVenvRollbackDir -and (Test-Path -LiteralPath $script:StudioVenvRollbackDir))
+ foreach ($c in @(Get-ChildItem -LiteralPath $StudioHome -Directory -Filter "unsloth_studio.rollback.*" -ErrorAction SilentlyContinue)) {
+ Microsoft.PowerShell.Management\Remove-Item -LiteralPath $c.FullName -Recurse -Force -ErrorAction SilentlyContinue
+ }
+
+ Write-Host "the volume helpers degrade to the drive root where mount points cannot be read"
+ # Both helpers ask Win32_Volume first, and that view exists only on Windows, so what is
+ # checkable off it is the fallback: "cannot tell" rather than a throw, with the drive-root
+ # logic still answering. The mount-point case is pinned by text in the parity suite.
+ $probed = $null
+ $probeThrew = $false
+ try { $probed = Get-StudioMountedVolume -Path $StudioHome } catch { $probeThrew = $true }
+ Check "the mount-point probe never throws" (-not $probeThrew)
+ if ($IsWindows -or $env:OS -eq "Windows_NT") {
+ # On Windows it answers for real, or legitimately nothing where CIM is unavailable to
+ # this account. What it must never do is throw or return something callers cannot read.
+ Check "on Windows the probe answers a volume or nothing, never something unusable" (
+ $null -eq $probed -or $null -ne $probed.Name)
+ } else {
+ Check "off Windows the probe answers nothing" ($null -eq $probed)
+ }
+ Check "and an empty path is not an error" ($null -eq (Get-StudioMountedVolume -Path ""))
+ # The WMI answer is advisory and runs before the venv exists, so it must be bounded and taken
+ # once. A degraded repository is what the bound is for; what is checkable here is that the
+ # call returns rather than hanging, never throws, and is not repeated.
+ $script:StudioVolumeList = $null
+ $listThrew = $false
+ $t0 = [System.Diagnostics.Stopwatch]::StartNew()
+ try { $null = Get-StudioVolumeList } catch { $listThrew = $true }
+ $firstMs = $t0.ElapsedMilliseconds
+ Check "the volume query returns rather than hanging" (-not $listThrew -and $firstMs -lt 60000)
+ $t0.Restart()
+ $null = Get-StudioVolumeList
+ Check "and is answered from the cache the second time" ($t0.ElapsedMilliseconds -lt $firstMs + 50)
+ Check "a query that answered nothing still caches an answer" (
+ $null -ne $script:StudioVolumeList)
+ # The cache holds identity, which does not move during an install. It must NOT answer the
+ # free-space question: the failure handler asks after setup has eaten the disk, and a number
+ # snapshotted before the environment was built reports room that is gone.
+ $script:StudioVolumeList = @([pscustomobject]@{ Name = "sentinel"; DeviceID = "sentinel"; FreeSpace = 1 })
+ $null = Get-StudioVolumeList
+ Check "the cached list is reused when only identity is wanted" (
+ @(Get-StudioVolumeList)[0].DeviceID -eq "sentinel")
+ $null = Get-StudioVolumeList -Fresh
+ Check "asking for a fresh answer replaces the cached one" (
+ @($script:StudioVolumeList | Where-Object { $_.DeviceID -eq "sentinel" }).Count -eq 0)
+ $script:StudioVolumeList = $null
+ # A link must be measured as the volume it points at. On one filesystem both numbers agree,
+ # so what this proves is that resolution happens and costs nothing: a helper that threw, or
+ # answered $null through a link, takes the disk-full diagnosis down with it.
+ $linkTarget = Join-Path $StudioHome "link-target"
+ [System.IO.Directory]::CreateDirectory($linkTarget) | Out-Null
+ $linkPath = Join-Path $StudioHome "link"
+ $linkMade = $true
+ try { New-Item -ItemType SymbolicLink -Path $linkPath -Target $linkTarget -ErrorAction Stop | Out-Null }
+ catch { $linkMade = $false }
+ if ($linkMade) {
+ # Within a tolerance, not equal: free space on a live filesystem moves between two
+ # calls, and an exact comparison fails for that reason rather than for this one.
+ $viaLink = Get-StudioFreeSpaceBytes -Path $linkPath
+ $viaTarget = Get-StudioFreeSpaceBytes -Path $linkTarget
+ Check "free space through a link is the target's volume, not some other one" (
+ $null -ne $viaLink -and $null -ne $viaTarget -and $viaLink -gt 0 -and
+ [math]::Abs($viaLink - $viaTarget) -lt ([math]::Max($viaLink, $viaTarget) * 0.01))
+ Microsoft.PowerShell.Management\Remove-Item -LiteralPath $linkPath -Force -ErrorAction SilentlyContinue
+ } else {
+ # Windows needs Developer Mode or elevation to create one; not a failure of the code.
+ Write-Host " SKIP this host will not create a symbolic link"
+ }
+ $freeHere = Get-StudioFreeSpaceBytes -Path $StudioHome
+ Check "free space still comes back from the fallback" ($null -ne $freeHere -and $freeHere -gt 0)
+
+ Write-Host "picking the volume that holds a path, including a directory mount point"
+ # Volume list supplied rather than read from CIM, so these run on a host with no mount
+ # points. Both sides come from one GetFullPath call: on Windows a rooted path with no drive
+ # picks up the current drive, so names built from a bare separator match nothing there.
+ $sep = [System.IO.Path]::DirectorySeparatorChar
+ $mountPath = [System.IO.Path]::GetFullPath("${sep}studio")
+ $otherPath = [System.IO.Path]::GetFullPath("${sep}studiofoo")
+ $elsePath = [System.IO.Path]::GetFullPath("${sep}elsewhere${sep}x")
+ $rootVol = [pscustomobject]@{ Name = [System.IO.Path]::GetPathRoot($mountPath); DeviceID = "root"; FreeSpace = 1GB }
+ $mountVol = [pscustomobject]@{ Name = "$mountPath$sep"; DeviceID = "mount"; FreeSpace = 2GB }
+ $otherVol = [pscustomobject]@{ Name = "$otherPath$sep"; DeviceID = "other"; FreeSpace = 3GB }
+ $vols = @($rootVol, $mountVol, $otherVol)
+ Check "a path under a mount point picks the mounted volume" (
+ (Select-StudioVolumeForPath -Path (Join-Path $mountPath "cache") -Volumes $vols).DeviceID -eq "mount")
+ # The regression this section exists for: the mount point itself has no trailing separator.
+ Check "the mount point itself picks the mounted volume, not the drive root" (
+ (Select-StudioVolumeForPath -Path $mountPath -Volumes $vols).DeviceID -eq "mount")
+ Check "a sibling whose name merely starts the same does not match it" (
+ (Select-StudioVolumeForPath -Path $otherPath -Volumes $vols).DeviceID -eq "other")
+ Check "a path under neither falls to the root volume" (
+ (Select-StudioVolumeForPath -Path $elsePath -Volumes $vols).DeviceID -eq "root")
+ # A volume with no drive letter resolves to Volume{GUID}\..., which is not rooted; anchoring
+ # that to the current directory would match whatever volume the installer happens to be run
+ # from. No answer is the honest one.
+ Check "an unrooted path matches no volume at all" (
+ $null -eq (Select-StudioVolumeForPath -Path "Volume{00000000-0000-0000-0000-000000000000}" -Volumes $vols))
+ Check "nothing to choose from is not an error" (
+ $null -eq (Select-StudioVolumeForPath -Path $mountPath -Volumes @()))
+ Check "an empty path chooses nothing" (
+ $null -eq (Select-StudioVolumeForPath -Path "" -Volumes $vols))
+
+ Write-Host "--no-rollback costs disk, never hardware (#11313)"
+ # The Intel scan rescues an adapter WMI cannot classify by asking the PREVIOUS environment's
+ # torch whether XPU works. Discarding that tree without taking the verdict first routes an
+ # Arc machine to CPU wheels for having opted out of a rollback copy.
+ [System.IO.Directory]::CreateDirectory($VenvDir) | Out-Null
+ [System.IO.Directory]::CreateDirectory((Join-Path $VenvDir "Scripts")) | Out-Null
+ # Stands in for the interpreter: the probe is bounded and reads stdout, so what it runs only
+ # has to print True the way torch.xpu.is_available() would on an Arc machine.
+ $fakePy = Join-Path (Join-Path $VenvDir "Scripts") "python.exe"
+ if ($IsWindows -or $env:OS -eq "Windows_NT") {
+ Set-Content -LiteralPath $fakePy -Value "@echo True"
+ } else {
+ Set-Content -LiteralPath $fakePy -Value "#!/bin/sh`necho True"
+ & chmod +x $fakePy
+ }
+ Reset-RollbackState $VenvDir
+ $script:StudioPreservedXpuVerdict = $false
+ $script:StudioNoRollback = $true
+ $script:StudioRollbackCostsFullSize = $true
+ $xpuThrew = $false
+ try { Start-StudioVenvRollback -ExistingDir $VenvDir } catch { $xpuThrew = $true }
+ Check "taking the XPU verdict never costs the discard" (-not $xpuThrew)
+ if ($IsWindows -or $env:OS -eq "Windows_NT") {
+ # A .exe that is really a batch file will not start on Windows, so only the POSIX arm
+ # can drive the probe end to end; here the assertion is that it is attempted and safe.
+ Write-Host " SKIP the stand-in interpreter cannot be executed on this platform"
+ } else {
+ Check "the XPU verdict survives the environment being discarded" (
+ $script:StudioPreservedXpuVerdict)
+ }
+ Check "and the environment really was discarded" (-not (Test-Path -LiteralPath $VenvDir))
+ $script:StudioPreservedXpuVerdict = $false
+ $script:StudioNoRollback = $false
+ foreach ($c in @(Get-ChildItem -LiteralPath $StudioHome -Directory -Filter "unsloth_studio.rollback.*" -ErrorAction SilentlyContinue)) {
+ Microsoft.PowerShell.Management\Remove-Item -LiteralPath $c.FullName -Recurse -Force -ErrorAction SilentlyContinue
+ }
+
+ Write-Host "the discard message tells the truth under --no-rollback"
+ # A delete that could not remove the tree frees none of the space the flag exists to free, so
+ # reporting it as discarded promises the user something that is still on their disk.
+ $script:said = @()
+ function substep { param([string]$Message, [string]$Color) $script:said += $Message }
+ function Write-StudioLine { param([string]$Message, [string]$ForegroundColor) $script:said += $Message }
+
+ [System.IO.Directory]::CreateDirectory($VenvDir) | Out-Null
+ [System.IO.File]::WriteAllText((Join-Path $VenvDir "generation"), "old")
+ Reset-RollbackState $VenvDir
+ $script:StudioNoRollback = $true
+ Start-StudioVenvRollback -ExistingDir $VenvDir
+ Check "--no-rollback reports the discard" (
+ ($script:said -join "`n") -match 'discarded \(--no-rollback\)')
+
+ # Without the flag nothing is discarded and nothing extra is said: the default path is exactly
+ # what it was before this change.
+ [System.IO.Directory]::CreateDirectory($VenvDir) | Out-Null
+ [System.IO.File]::WriteAllText((Join-Path $VenvDir "generation"), "old")
+ Reset-RollbackState $VenvDir
+ $script:StudioNoRollback = $false
+ $script:said = @()
+ Start-StudioVenvRollback -ExistingDir $VenvDir
+ Check "an ordinary install keeps the rollback copy" ($script:StudioVenvRollbackActive)
+ Check "and says nothing about discarding it" (
+ ($script:said -join "`n") -notmatch 'discarded')
+ foreach ($c in @(Get-ChildItem -LiteralPath $StudioHome -Directory -Filter "unsloth_studio.rollback.*" -ErrorAction SilentlyContinue)) {
+ Microsoft.PowerShell.Management\Remove-Item -LiteralPath $c.FullName -Recurse -Force -ErrorAction SilentlyContinue
+ }
+ $script:StudioNoRollback = $true
+
+ # A tree the retry helper could not remove. It shadows the extracted definition, so
+ # Start-StudioVenvRollback resolves to this one at call time.
+ [System.IO.Directory]::CreateDirectory($VenvDir) | Out-Null
+ [System.IO.File]::WriteAllText((Join-Path $VenvDir "generation"), "old")
+ Reset-RollbackState $VenvDir
+ $script:said = @()
+ function Remove-StudioVenvTreeWithRetry { param([string]$Path, [string]$Label) return $false }
+ try {
+ $discardThrew = $false
+ try { Start-StudioVenvRollback -ExistingDir $VenvDir } catch { $discardThrew = $true }
+ } finally {
+ Microsoft.PowerShell.Management\Remove-Item -LiteralPath Function:\Remove-StudioVenvTreeWithRetry -Force
+ }
+ $joined = ($script:said -join "`n")
+ Check "a discard that could not delete never aborts the install" (-not $discardThrew)
+ Check "a discard that could not delete does not claim success" (
+ $joined -notmatch 'discarded \(--no-rollback\)')
+ # A dangling directory reparse point that cannot be unlinked: Test-Path follows the link and
+ # calls it absent, so the retry helper would report a removal that did not happen and the
+ # discard above would clear the rollback state and say the environment was gone.
+ $danglingRoot = Join-Path $StudioHome "dangling"
+ [System.IO.Directory]::CreateDirectory($danglingRoot) | Out-Null
+ $danglingTarget = Join-Path $danglingRoot "gone"
+ [System.IO.Directory]::CreateDirectory($danglingTarget) | Out-Null
+ $danglingLink = Join-Path $danglingRoot "link"
+ $danglingMade = $true
+ try { New-Item -ItemType SymbolicLink -Path $danglingLink -Target $danglingTarget -ErrorAction Stop | Out-Null }
+ catch { $danglingMade = $false }
+ if ($danglingMade) {
+ Microsoft.PowerShell.Management\Remove-Item -LiteralPath $danglingTarget -Recurse -Force
+ # Only the first half is checkable here: measured on this host, Test-Path does NOT follow
+ # a dangling symlink on Linux and answers True, so the divergence the retry helper guards
+ # against is a Windows directory reparse point and is not reproduced anywhere available.
+ # What holds on every platform is that the helper the retry now uses sees the link.
+ Check "a dangling link is reported as present" (Test-StudioPathPresent -Path $danglingLink)
+ Microsoft.PowerShell.Management\Remove-Item -LiteralPath $danglingLink -Force -ErrorAction SilentlyContinue
+ } else {
+ Write-Host " SKIP this host will not create a symbolic link"
+ }
+ Microsoft.PowerShell.Management\Remove-Item -LiteralPath $danglingRoot -Recurse -Force -ErrorAction SilentlyContinue
+
+ Check "a discard that could not delete names the path left on disk" (
+ $joined -match [regex]::Escape($StudioHome) -and $joined -match 'unsloth_studio\.rollback\.')
+ $script:StudioNoRollback = $false
+ foreach ($c in @(Get-ChildItem -LiteralPath $StudioHome -Directory -Filter "unsloth_studio.rollback.*" -ErrorAction SilentlyContinue)) {
+ Microsoft.PowerShell.Management\Remove-Item -LiteralPath $c.FullName -Recurse -Force -ErrorAction SilentlyContinue
+ }
+
+ function substep { param([string]$Message, [string]$Color) }
+ function Write-StudioLine { param([string]$Message, [string]$ForegroundColor) Write-Host $Message }
} finally {
if (Test-Path -LiteralPath $StudioHome) {
Microsoft.PowerShell.Management\Remove-Item -LiteralPath $StudioHome -Recurse -Force