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.

Stop the Studio temp probe leaving anything behind (#9298)

Daniel Hancad00177a40f
diff --git a/install.ps1 b/install.ps1
index a51c7589741..dc64ba60652 100644
--- a/install.ps1
+++ b/install.ps1
@@ -336,12 +336,38 @@ function Install-UnslothStudio {
# variables at a directory we own: every child process and every
# [System.IO.Path]::GetTempPath() call reads the process environment block.
function Test-StudioDirectoryUsable {
- param([string]$Path)
+ param(
+ [string]$Path,
+ # Only for a directory this installer OWNS. Probing the host's own
+ # inherited TMP/TEMP must not bring it into existence: -Force creates
+ # the whole parent chain, so a stale or mistyped TMP would have the
+ # installer silently materialize a tree at a path nobody chose, and
+ # then trust it. Absent means unusable, which is what the private
+ # fallback is for.
+ [switch]$CreateIfMissing
+ )
if ([string]::IsNullOrWhiteSpace($Path)) { return $false }
try {
if (-not (Test-Path -LiteralPath $Path -PathType Container)) {
+ if (-not $CreateIfMissing) { return $false }
New-Item -ItemType Directory -Path $Path -Force -ErrorAction Stop | Out-Null
}
+ # Anything an earlier run could not delete. Bounded self-healing: the
+ # probe below cannot clean up after itself when deletion is what
+ # failed, so each such run used to leave one more file behind forever.
+ try {
+ $cutoff = (Get-Date).AddDays(-1)
+ foreach ($old in @(Get-ChildItem -LiteralPath $Path -File -Filter "unsloth-probe-*.tmp" -ErrorAction Stop)) {
+ # Shape, not prefix. This runs in the HOST's temp directory,
+ # where a name that merely starts the same way belongs to
+ # somebody else; the probe below only ever writes eight hex
+ # characters, so anything else is not ours to delete.
+ if ($old.Name -notmatch '^unsloth-probe-[0-9a-f]{8}\.tmp$') { continue }
+ if ($old.LastWriteTime -lt $cutoff) {
+ Remove-Item -LiteralPath $old.FullName -Force -ErrorAction SilentlyContinue
+ }
+ }
+ } catch {}
# Write, read back, delete -- not Test-Path: the failures that matter
# (write without read, a scanner deleting the file) pass an existence check.
$probe = Join-Path $Path ("unsloth-probe-" + [guid]::NewGuid().ToString('N').Substring(0, 8) + ".tmp")
@@ -374,7 +400,27 @@ function Install-UnslothStudio {
try {
$cutoff = (Get-Date).AddDays(-1)
foreach ($stale in @(Get-ChildItem -LiteralPath $Root -Directory -Filter "ust-*" -ErrorAction Stop)) {
+ # SHAPE, not prefix. The delete below is recursive and this is the
+ # only ownership test there is, so it has to name a directory the
+ # allocator could actually have made: "ust-" + $PID + "-" + 8 hex.
+ # A prefix match takes "ust-legacy" or "ust-user-cache" too, and
+ # since neither has a parseable PID the liveness check is skipped
+ # for exactly the names least likely to be ours. scripts/uninstall.ps1
+ # already requires this shape; the two had drifted apart.
+ if ($stale.Name -notmatch '^ust-[0-9]+-[0-9a-f]{8}$') { continue }
if ($stale.LastWriteTime -ge $cutoff) { continue }
+ # Before any owner logic, because the allocator never makes a link:
+ # anything here that IS one is not ours, reading owner.pid out of it
+ # would read through it, and unlinking is safe whatever owns the
+ # target. Not Remove-Item: on 5.1 without -Recurse it throws a
+ # NullReferenceException on a junction that -ErrorAction
+ # SilentlyContinue does not suppress (measured on windows-latest), and
+ # -Recurse has walked THROUGH the link on some 5.1 builds.
+ # Directory.Delete with recursive:$false cannot follow it.
+ if ($stale.Attributes -band [System.IO.FileAttributes]::ReparsePoint) {
+ try { [System.IO.Directory]::Delete($stale.FullName, $false) } catch {}
+ continue
+ }
# Age alone is not proof it is unused, and this sweep runs before the
# runtime mutex, so it could delete a live process's %TEMP%. owner.pid
# names the process that INHERITED this directory (the autostarted
@@ -392,9 +438,23 @@ function Install-UnslothStudio {
if (-not [string]::IsNullOrWhiteSpace($recorded)) {
$null = [int]::TryParse($recorded, [ref]$ownerPid)
}
+ # Whether the owner was RECORDED, or only guessed from the name.
+ # The name carries the installer's PID, and an installer that was
+ # killed between Start-Process and the owner.pid write leaves a dead
+ # PID in the name while the Studio it started is very much alive on
+ # that directory as its own %TEMP%. Guessing therefore proves much
+ # less than reading, and the two are not treated alike below.
+ $ownerRecorded = ($ownerPid -gt 0)
if ($ownerPid -le 0) {
$null = [int]::TryParse(($stale.Name -split '-')[1], [ref]$ownerPid)
}
+ # No recorded owner: unknown, not abandoned. Still collected, so the
+ # pile stays bounded, but only once it has gone a whole week without
+ # a single entry being created in it, which a Studio actually using
+ # it as %TEMP% would not manage.
+ if (-not $ownerRecorded -and $stale.LastWriteTime -ge (Get-Date).AddDays(-7)) {
+ continue
+ }
if ($ownerPid -gt 0) {
$ownerLives = $true
try {
@@ -408,17 +468,6 @@ function Install-UnslothStudio {
}
if ($ownerLives) { continue }
}
- # Nothing here should be a reparse point, so remove the link and leave
- # its target. Not Remove-Item: on 5.1 without -Recurse it throws a
- # NullReferenceException on a junction that -ErrorAction
- # SilentlyContinue does not suppress (measured on windows-latest), and
- # -Recurse has walked THROUGH the link on some 5.1 builds. Directory
- # .Delete with recursive:$false removes the reparse point and cannot
- # follow it.
- if ($stale.Attributes -band [System.IO.FileAttributes]::ReparsePoint) {
- try { [System.IO.Directory]::Delete($stale.FullName, $false) } catch {}
- continue
- }
Remove-Item -LiteralPath $stale.FullName -Recurse -Force -ErrorAction SilentlyContinue
}
} catch {}
@@ -466,10 +515,47 @@ function Install-UnslothStudio {
# bound by the legacy path limit.
$leaf = "ust-" + $PID + "-" + [guid]::NewGuid().ToString('N').Substring(0, 8)
$candidate = Join-Path $root $leaf
- if (Test-StudioDirectoryUsable -Path $candidate) {
+ # Which of these did not exist BEFORE the probe touched anything. Only
+ # those may be unwound below: a pre-provisioned "Unsloth Studio\temp"
+ # with custom ACLs, or an empty junction pointing somewhere else, is
+ # configuration this installer did not create and must not remove
+ # merely for being empty and correctly named.
+ $preAbsent = @{}
+ $walk = $candidate
+ for ($seen = 0; $seen -lt 4; $seen++) {
+ if ([string]::IsNullOrEmpty($walk)) { break }
+ $preAbsent[$walk] = (-not (Test-Path -LiteralPath $walk))
+ $walk = [System.IO.Path]::GetDirectoryName($walk)
+ }
+ if (Test-StudioDirectoryUsable -Path $candidate -CreateIfMissing) {
Remove-StudioStalePrivateTempDirectories -Root $root
return $candidate
}
+ # The probe creates the candidate before it tests it, and -Force builds
+ # the whole chain, so a root that fails leaves "Unsloth Studio\temp\ust-x"
+ # behind; on a host where every root fails that is a data directory tree
+ # conjured by an install that then gave up. Walk back up, but only through
+ # the directories this path is made of and only while each one is EMPTY,
+ # so a tree that already held something is never touched and neither is
+ # ~\.unsloth itself, which is shared and is not ours to remove.
+ $ours = @("temp", "Unsloth Studio", ".cache")
+ $unwind = $candidate
+ for ($depth = 0; $depth -lt 4; $depth++) {
+ try {
+ if (-not $preAbsent[$unwind]) { break }
+ if (-not (Test-Path -LiteralPath $unwind -PathType Container)) { break }
+ $item = Get-Item -LiteralPath $unwind -Force -ErrorAction Stop
+ # A relocation junction is somebody's configuration even when the
+ # probe created it, and unlinking it is not "taking back what we
+ # made". Leave it and stop.
+ if ($item.Attributes -band [System.IO.FileAttributes]::ReparsePoint) { break }
+ if (@(Get-ChildItem -LiteralPath $unwind -Force -ErrorAction Stop).Count -gt 0) { break }
+ [System.IO.Directory]::Delete($unwind, $false)
+ } catch { break }
+ $unwind = [System.IO.Path]::GetDirectoryName($unwind)
+ if ([string]::IsNullOrEmpty($unwind)) { break }
+ if ($ours -notcontains [System.IO.Path]::GetFileName($unwind)) { break }
+ }
}
return $null
}
@@ -661,6 +747,8 @@ function Install-UnslothStudio {
# %TEMP% we own, cache the answer (callers resolve dozens of paths), then let
# Get-StudioLexicalPath carry the run.
$script:StudioFinalPathNativeState = $null
+ # Reset with the rest: under `irm | iex` these are the caller's own.
+ $script:StudioNativeResolveWarned = $false
$script:StudioFinalPathWarned = $false
function Write-StudioFinalPathDegraded {
param([string]$Reason)
@@ -1011,7 +1099,18 @@ public static class UnslothStudioFinalPathV2
$resolved = [UnslothStudioFinalPathV2]::Resolve($existingPath)
$exact = $true
} catch {
+ # The helper COMPILED and still could not answer: a path renamed
+ # between the Test-Path walk and CreateFileW, an access denial on a
+ # component, a volume with no drive letter. Falling back keeps the
+ # install alive, and Exact = $false already makes the runtime lock
+ # fail closed, but nothing said so out loud: the degraded warning
+ # below only fires when the compile itself failed. An operator was
+ # left with a silently inexact identity on a host that looks fine.
$resolved = $null
+ if (-not $script:StudioNativeResolveWarned) {
+ $script:StudioNativeResolveWarned = $true
+ Write-StudioLine "[WARN] Could not resolve a path with the native helper; continuing with the PowerShell resolver." -ForegroundColor Yellow
+ }
}
}
if ([string]::IsNullOrEmpty($resolved)) {
@@ -1020,15 +1119,15 @@ public static class UnslothStudioFinalPathV2
}
if ($resolved.StartsWith('\\?\UNC\', [System.StringComparison]::OrdinalIgnoreCase)) {
$resolved = '\\' + $resolved.Substring(8)
- } elseif ($resolved.StartsWith('\\?\Volume{', [System.StringComparison]::OrdinalIgnoreCase)) {
- # Kept, unlike an ordinary extended DOS path: \\?\C:\x still names a drive
- # once the prefix comes off, but \\?\Volume{GUID}\x becomes the relative
- # "Volume{GUID}\x", which the link resolver combines with the link's own
- # parent, inventing a directory. Measured on 5.1: GetPathRoot returns empty
- # for BOTH spellings on .NET Framework, so keeping the prefix does not make
- # the volume matchable against a drive-letter spelling of itself; all it
- # buys is not inventing a false path.
} elseif ($resolved.StartsWith('\\?\', [System.StringComparison]::OrdinalIgnoreCase)) {
+ # Every extended spelling, INCLUDING \\?\Volume{GUID}\, because this string
+ # is hashed into the runtime mutex name and unsloth_cli/_studio_runtime_gate.py
+ # strips \\?\ unconditionally (_resolved_windows_path). Keeping the prefix
+ # here made the installer and a running Studio compute different names for
+ # one directory, so neither would exclude the other. Rootedness does matter
+ # while a link target is being anchored, and Resolve-StudioLinkTarget keeps
+ # the extended form for exactly that; nothing after this point anchors
+ # anything, and Combine only drops its left side for a ROOTED right side.
$resolved = $resolved.Substring(4)
}
foreach ($segment in $missingSegments) {
diff --git a/scripts/uninstall.ps1 b/scripts/uninstall.ps1
index 8c9f5e12deb..0ecce9e5a09 100644
--- a/scripts/uninstall.ps1
+++ b/scripts/uninstall.ps1
@@ -142,13 +142,184 @@ Environment:
}
}
+ # Reclaim ONLY what install.ps1 puts under "<LocalAppData>\Unsloth Studio\temp":
+ # directories named ust-<pid>-<hex>, then the temp dir and its parent if they are
+ # left empty. Deliberately narrow. This runs against every LocalAppData spelling,
+ # including one that can name a different user's profile, so it must never be a
+ # recursive delete of anything it did not create. Nothing here follows a link:
+ # Directory.Delete with $false removes a reparse point without touching its target.
+ function _RemoveStudioPrivateTempTrees {
+ param(
+ [string[]]$Paths,
+ # The spelling this uninstall is actually for. Any OTHER spelling can be
+ # a different user's profile, so it gets the stricter rule below.
+ [string]$PrimaryPath
+ )
+ # Every directory this sweep decided to keep, returned so the callers can
+ # keep it too. The wholesale data-directory removal runs over the same
+ # tree, and a live owner preserved here and deleted there is not
+ # preserved at all.
+ $preserved = @()
+ foreach ($temp in @($Paths)) {
+ if ([string]::IsNullOrWhiteSpace($temp)) { continue }
+ if (-not (Test-Path -LiteralPath $temp -PathType Container)) { continue }
+ $isPrimary = (-not [string]::IsNullOrWhiteSpace($PrimaryPath)) -and
+ [string]::Equals($temp.TrimEnd('\','/'), $PrimaryPath.TrimEnd('\','/'), [System.StringComparison]::OrdinalIgnoreCase)
+ # Never descend through a link. Get-ChildItem on a reparse point
+ # enumerates the TARGET, and the target's ordinary children do not
+ # carry the ReparsePoint attribute, so the recursive delete below
+ # would take somebody else's tree by way of a redirected temp dir.
+ #
+ # How far up to look differs by spelling. For the profile this
+ # uninstall is FOR, the temp directory and the "Unsloth Studio"
+ # directory above it are the two this script created and the two
+ # that decide whose tree the enumeration lands in; a redirected
+ # LocalAppData higher up is still that same user's own storage, and
+ # refusing there would leave the installer's own temp tree behind on
+ # every host that uses folder redirection.
+ # Any OTHER spelling may be another profile entirely, and a junction
+ # anywhere along it -- LocalAppData, Users, the drive root -- is
+ # enough to make an ordinary-looking "Unsloth Studio\temp" resolve
+ # into a directory this uninstall has no claim on. There, every
+ # ancestor up to the root has to be ordinary.
+ $ancestors = @()
+ if ($isPrimary) {
+ $ancestors = @($temp, [System.IO.Path]::GetDirectoryName($temp))
+ } else {
+ $walk = $temp
+ # Bounded: GetDirectoryName returns $null at the root, and the
+ # cap keeps a pathological spelling from spinning.
+ for ($depth = 0; $depth -lt 64; $depth++) {
+ if ([string]::IsNullOrWhiteSpace($walk)) { break }
+ $ancestors += $walk
+ $next = [System.IO.Path]::GetDirectoryName($walk)
+ if ($next -eq $walk) { break }
+ $walk = $next
+ }
+ }
+ $linked = $false
+ foreach ($ancestor in $ancestors) {
+ try {
+ if ([string]::IsNullOrWhiteSpace($ancestor)) { continue }
+ $info = Get-Item -LiteralPath $ancestor -Force -ErrorAction Stop
+ if ($info.Attributes -band [System.IO.FileAttributes]::ReparsePoint) { $linked = $true }
+ } catch {}
+ }
+ if ($linked) {
+ _Substep "skipped (reparse point): $temp" "Yellow"
+ # Whatever is behind the link is not ours to delete here, and it is
+ # not ours to delete from the data-directory pass either.
+ $preserved += $temp
+ continue
+ }
+ $entries = @()
+ try { $entries = @(Get-ChildItem -LiteralPath $temp -Force -ErrorAction Stop) } catch { continue }
+ foreach ($entry in $entries) {
+ # Shape, not prefix: "ust-legacy" and "ust-notapid-x" are not ours.
+ if ($entry.Name -notmatch '^ust-[0-9]+-[0-9a-f]{8}$') { continue }
+ if (-not ($entry.PSIsContainer)) { continue }
+ # A LIVE owner keeps its directory, exactly as install.ps1's own
+ # sweep does. An uninstall stops the Studios under the roots it
+ # knows about; a Studio from another install root, or another
+ # user, is not among them and is still using this as its %TEMP%.
+ $ownerPid = 0
+ try {
+ $ownerFile = Join-Path $entry.FullName "owner.pid"
+ if ([System.IO.File]::Exists($ownerFile)) {
+ $null = [int]::TryParse(([System.IO.File]::ReadAllText($ownerFile)).Trim(), [ref]$ownerPid)
+ }
+ } catch { $ownerPid = 0 }
+ if ($ownerPid -gt 0) {
+ $ownerLives = $true
+ try { $null = Get-Process -Id $ownerPid -ErrorAction Stop }
+ catch [Microsoft.PowerShell.Commands.ProcessCommandException] { $ownerLives = $false }
+ catch { $ownerLives = $true }
+ if ($ownerLives) {
+ _Substep "in use by pid ${ownerPid}, left alone: $($entry.FullName)" "Yellow"
+ $preserved += $entry.FullName
+ continue
+ }
+ } elseif (-not $isPrimary) {
+ # No recorded owner, and this is not the profile being uninstalled.
+ # install.ps1 reads that state as UNKNOWN rather than abandoned,
+ # because an installer killed before writing owner.pid leaves a live
+ # Studio holding the directory; deleting another user's live %TEMP%
+ # is not this uninstall's business. Under our own profile the shape
+ # is enough, since that is what is being removed.
+ _Substep "no recorded owner in another profile, left alone: $($entry.FullName)" "Yellow"
+ $preserved += $entry.FullName
+ continue
+ }
+ try {
+ if ($entry.Attributes -band [System.IO.FileAttributes]::ReparsePoint) {
+ [System.IO.Directory]::Delete($entry.FullName, $false)
+ } else {
+ Remove-Item -LiteralPath $entry.FullName -Recurse -Force -ErrorAction Stop
+ }
+ _Substep "removed: $($entry.FullName)" "Green"
+ } catch {
+ _Substep "could not remove: $($entry.FullName) ($($_.Exception.Message))" "Yellow"
+ $script:RemoveFailed = $true
+ }
+ }
+ # Only when empty, so a temp directory holding anything else is left alone,
+ # and likewise the "Unsloth Studio" parent, which on the second spelling may
+ # be a data directory this run has no business deleting.
+ foreach ($dir in @($temp, [System.IO.Path]::GetDirectoryName($temp))) {
+ try {
+ if ((Test-Path -LiteralPath $dir -PathType Container) -and
+ -not @(Get-ChildItem -LiteralPath $dir -Force -ErrorAction Stop)) {
+ [System.IO.Directory]::Delete($dir, $false)
+ }
+ } catch {}
+ }
+ }
+ return $preserved
+ }
+
+ # Delete a tree except for the paths in -Keep, and except for the directories
+ # above them, which have to survive to hold them. With an empty -Keep this is
+ # _RemovePath and nothing else, which is what every ordinary uninstall gets.
+ function _RemoveTreeKeeping {
+ param(
+ [string]$Path,
+ [string[]]$Keep
+ )
+ if ([string]::IsNullOrWhiteSpace($Path)) { return }
+ if (-not (Test-Path -LiteralPath $Path)) { return }
+ $self = $Path.TrimEnd('\','/')
+ $holdsKept = $false
+ foreach ($k in @($Keep)) {
+ if ([string]::IsNullOrWhiteSpace($k)) { continue }
+ $kept = $k.TrimEnd('\','/')
+ # The kept path itself: stop here, with everything inside it.
+ if ([string]::Equals($kept, $self, [System.StringComparison]::OrdinalIgnoreCase)) { return }
+ if ($kept.StartsWith(($self + '\'), [System.StringComparison]::OrdinalIgnoreCase) -or
+ $kept.StartsWith(($self + '/'), [System.StringComparison]::OrdinalIgnoreCase)) {
+ $holdsKept = $true
+ }
+ }
+ if (-not $holdsKept) {
+ _RemovePath $Path
+ return
+ }
+ # Something below survives, so this directory does too; take the rest of
+ # its children one by one.
+ Get-ChildItem -LiteralPath $Path -Force -ErrorAction SilentlyContinue | ForEach-Object {
+ _RemoveTreeKeeping -Path $_.FullName -Keep $Keep
+ }
+ }
+
# Remove the shared data dir, but keep unsloth.ico if a WSL shortcut still points
# at it (else that shortcut blanks); uninstall.sh drops it when WSL is removed.
function _RemoveDataDirKeepingWslIcon {
param(
[string]$DataDir,
# WSL-shortcut search dirs; default Start Menu + Desktop, overridable for tests.
- [string[]]$ShortcutDirs = $null
+ [string[]]$ShortcutDirs = $null,
+ # Paths under the data dir that a previous pass decided to keep, typically
+ # a private temp directory a live Studio is still using as its %TEMP%.
+ [string[]]$Preserve = @()
)
if ([string]::IsNullOrWhiteSpace($DataDir)) { return }
if (-not (Test-Path -LiteralPath $DataDir)) { return }
@@ -172,15 +343,18 @@ Environment:
$wslShortcuts += Get-ChildItem -LiteralPath $d -Filter "Unsloth Studio (WSL*.lnk" -ErrorAction SilentlyContinue
}
}
- if (@($wslShortcuts).Count -eq 0) {
+ $keep = @()
+ foreach ($p in @($Preserve)) { if (-not [string]::IsNullOrWhiteSpace($p)) { $keep += $p } }
+ if (@($wslShortcuts).Count -eq 0 -and $keep.Count -eq 0) {
_RemovePath $DataDir
return
}
- # A WSL shortcut survives: drop everything except its shared icon.
- _Substep "keeping $(Join-Path $DataDir 'unsloth.ico') for the WSL shortcut" "Gray"
- Get-ChildItem -LiteralPath $DataDir -Force -ErrorAction SilentlyContinue | ForEach-Object {
- if ($_.Name -ne "unsloth.ico") { _RemovePath $_.FullName }
+ if (@($wslShortcuts).Count -gt 0) {
+ # A WSL shortcut survives: keep its shared icon.
+ _Substep "keeping $(Join-Path $DataDir 'unsloth.ico') for the WSL shortcut" "Gray"
+ $keep += (Join-Path $DataDir "unsloth.ico")
}
+ _RemoveTreeKeeping -Path $DataDir -Keep $keep
}
# Is this bin\unsloth.cmd the launcher install.ps1 wrote, or just a file with that
@@ -507,19 +681,27 @@ Environment:
# Default install root + default data dir.
$defaultStudioHome = if ($env:USERPROFILE) { Join-Path $env:USERPROFILE ".unsloth\studio" } else { $null }
- # BOTH LocalAppData spellings, not just the first that answers. The variable is
- # dropped entirely in service and CI contexts, and install.ps1 also falls through
- # from it to the known folder when the variable is merely SET but not usable, so
- # a non-blank $env:LOCALAPPDATA does not mean that is where "Unsloth Studio\temp"
- # ended up. Reading one candidate leaves the other behind on exactly the hosts
- # that needed the fallback.
+ $defaultDataRoot = _AppDataRoot $env:LOCALAPPDATA 'LocalApplicationData'
+ $defaultDataDir = if ($defaultDataRoot) { Join-Path $defaultDataRoot "Unsloth Studio" } else { $null }
+ # The SECOND LocalAppData spelling gets the private temp tree only, never the
+ # data directory. install.ps1 falls through from a set-but-unusable
+ # $env:LOCALAPPDATA to the known folder when it places "Unsloth Studio\temp",
+ # so that tree can outlive an uninstall; but the two spellings differ mainly
+ # when they name a DIFFERENT USER's profile (CreateProcessAsUser with a null
+ # environment block, runas /env, a service token), and the data-dir delete is
+ # recursive, sentinel-free and deny-list-free. Reclaiming what this installer
+ # actually put there is the whole requirement; taking a second "Unsloth Studio"
+ # with it is not.
$knownLocalAppData = $null
try { $knownLocalAppData = [Environment]::GetFolderPath('LocalApplicationData') } catch { $knownLocalAppData = $null }
- $defaultDataDirs = @()
+ # The first non-blank spelling is the one _AppDataRoot would have resolved, so
+ # it is the profile this uninstall is for.
+ $primaryPrivateTemp = if ($defaultDataDir) { Join-Path $defaultDataDir "temp" } else { $null }
+ $privateTempDirs = @()
foreach ($root in @($env:LOCALAPPDATA, $knownLocalAppData)) {
if ([string]::IsNullOrWhiteSpace($root)) { continue }
- $candidate = Join-Path $root "Unsloth Studio"
- if ($defaultDataDirs -notcontains $candidate) { $defaultDataDirs += $candidate }
+ $candidate = Join-Path $root "Unsloth Studio\temp"
+ if ($privateTempDirs -notcontains $candidate) { $privateTempDirs += $candidate }
}
# Default-mode ~/.unsloth holds a SHARED llama.cpp build + .cache that are
# siblings of studio (not under it), so deleting <studio> misses them -- handle
@@ -553,8 +735,8 @@ Environment:
# ── Stop running servers ──
_Step "Stopping any running Unsloth Studio servers..."
- foreach ($d in $defaultDataDirs) {
- _StopByPortFile -PortFile (Join-Path $d "studio.port") -KnownRoots $knownRoots
+ if ($defaultDataDir) {
+ _StopByPortFile -PortFile (Join-Path $defaultDataDir "studio.port") -KnownRoots $knownRoots
}
foreach ($r in $customRoots) {
_StopByPortFile -PortFile (Join-Path $r "share\studio.port") -KnownRoots $knownRoots
@@ -640,7 +822,7 @@ Environment:
}
# Also stop anything holding a handle on the exact paths we delete (llama-server,
# the CLI shim, an mp-fork python with a venv DLL) so the dir delete isn't refused.
- $stopRoots = @($knownRoots) + @($defaultDataDirs) + @($defaultLlamaCpp, $defaultCache, $defaultNode, $defaultWhisperCpp) + @($defaultSdCppToStop | Where-Object { $_ }) + @($customSdCppToStop)
+ $stopRoots = @($knownRoots) + @($defaultDataDir, $defaultLlamaCpp, $defaultCache, $defaultNode, $defaultWhisperCpp) + @($defaultSdCppToStop | Where-Object { $_ }) + @($customSdCppToStop)
_StopProcessesLockingRoots -Roots ($stopRoots + @(_ManagedPathsUnderReparseTargets $knownRoots))
# ── Remove custom-root install trees ──
@@ -677,8 +859,12 @@ Environment:
}
# Default install dir (always at %USERPROFILE%\.unsloth\studio when present).
if ($defaultStudioHome) { _RemoveRootRecordingDb $defaultStudioHome }
- # Default data dir.
- foreach ($d in $defaultDataDirs) { _RemoveDataDirKeepingWslIcon $d }
+ # Default data dir. The private temp sweep goes FIRST and hands back what it
+ # kept: the primary temp directory lives under this data dir, so a wholesale
+ # removal here would erase a live Studio's %TEMP% before the sweep ever looked
+ # at its owner.pid.
+ $preservedTemp = @(_RemoveStudioPrivateTempTrees -Paths $privateTempDirs -PrimaryPath $primaryPrivateTemp)
+ if ($defaultDataDir) { _RemoveDataDirKeepingWslIcon $defaultDataDir -Preserve $preservedTemp }
# Default-mode shared llama.cpp build + cache (siblings of studio under
# ~/.unsloth). No-op in env/custom mode and when absent.
if ($defaultLlamaCpp) { _RemovePath $defaultLlamaCpp }
@@ -769,8 +955,9 @@ Environment:
# Re-sweep: the first pass may have left unsloth.ico locked by Explorer/SMEH for
# the native shortcut; that handle is now freed. (A surviving WSL shortcut still
# keeps the icon -- see the helper.)
- foreach ($d in $defaultDataDirs) {
- if (Test-Path -LiteralPath $d) { _RemoveDataDirKeepingWslIcon $d }
+ $preservedTemp = @(_RemoveStudioPrivateTempTrees -Paths $privateTempDirs -PrimaryPath $primaryPrivateTemp)
+ if ($defaultDataDir -and (Test-Path -LiteralPath $defaultDataDir)) {
+ _RemoveDataDirKeepingWslIcon $defaultDataDir -Preserve $preservedTemp
}
# ── Clean user PATH and registry backup ──
diff --git a/tests/python/test_windows_installer_addtype_fallback.py b/tests/python/test_windows_installer_addtype_fallback.py
index e336a2327ad..4af3788bf73 100644
--- a/tests/python/test_windows_installer_addtype_fallback.py
+++ b/tests/python/test_windows_installer_addtype_fallback.py
@@ -642,22 +642,78 @@ Write-Output "TMP:[$env:TMP]"
@requires_pwsh
-def test_final_normalization_keeps_a_volume_guid_rooted():
- """\\\\?\\C:\\x still names a drive once the prefix comes off. A volume GUID does not.
-
- Stripping it leaves the unrooted "Volume{GUID}\\x", which hashes to a
- different identity than the same directory reached by drive letter and leaves
- GetPathRoot empty, so the relaxed process comparison cannot run either.
+def test_final_normalization_strips_every_extended_prefix():
+ r"""This string is hashed into the runtime mutex, so Python decides its shape.
+
+ unsloth_cli/_studio_runtime_gate.py::_resolved_windows_path strips \\?\
+ unconditionally, after one special case for \\?\UNC\. A volume GUID kept its
+ prefix here for a while, on the reasoning that the bare "Volume{GUID}\x" is
+ not rooted. That is true, and it matters while a LINK TARGET is being
+ anchored, which is why Resolve-StudioLinkTarget still keeps the extended
+ form. It does not matter here, and keeping it made the installer and a
+ running Studio compute different names for one directory.
"""
source = INSTALL_PS1.read_text(encoding = "utf-8")
body = _extract(r" function Resolve-StudioFinalPathInfo \{.*?\n \}\n", source)
- guid = body.index("\\\\?\\Volume{")
- dos = body.index("$resolved.Substring(4)")
- # The volume-GUID branch has to come BEFORE the general one, which would
- # otherwise swallow it and strip the prefix anyway.
- assert guid < dos
- branch = body[guid:dos]
- assert "Substring" not in branch
+ assert "'\\\\?\\Volume{'" not in body
+ assert "$resolved.Substring(4)" in body
+
+ gate = (REPO_ROOT / "unsloth_cli" / "_studio_runtime_gate.py").read_text(encoding = "utf-8")
+ # The two sides have to agree about which prefixes come off, and there are
+ # exactly two rules on the Python side.
+ assert 'resolved.startswith("\\\\\\\\?\\\\UNC\\\\")' in gate
+ assert "resolved = resolved[4:]" in gate
+ assert "Volume{" not in gate
+
+
+@requires_pwsh
+ "resolved,expected",
+ [
+ ("\\\\?\\C:\\Users\\bob\\studio", "C:\\Users\\bob\\studio"),
+ ("\\\\?\\UNC\\server\\share\\studio", "\\\\server\\share\\studio"),
+ (
+ "\\\\?\\Volume{11111111-2222-3333-4444-555555555555}\\data\\studio",
+ "Volume{11111111-2222-3333-4444-555555555555}\\data\\studio",
+ ),
+ ],
+ ids = ["extended-dos", "extended-unc", "volume-guid"],
+)
+def test_the_installer_and_the_runtime_gate_normalize_alike(resolved: str, expected: str):
+ """Byte-for-byte agreement, or the two sides key their lock on different names."""
+ source = INSTALL_PS1.read_text(encoding = "utf-8")
+ body = _extract(r" function Resolve-StudioFinalPathInfo \{.*?\n \}\n", source)
+ branch = _extract(
+ r" if \(\$resolved\.StartsWith\('\\\\\?\\UNC\\'.*?\n \}\n", body
+ )
+ result = _run_powershell(
+ "\n".join(
+ [
+ '$ErrorActionPreference = "Stop"',
+ f"$resolved = '{resolved}'",
+ branch,
+ 'Write-Output "OUT:$resolved"',
+ ]
+ )
+ )
+ assert result.returncode == 0, result.stderr
+ got = _lines(result, "OUT:")[0][len("OUT:") :]
+ assert got == expected
+
+ # And the same input through the Python gate's own rules.
+ import importlib.util
+
+ spec = importlib.util.spec_from_file_location(
+ "_studio_runtime_gate", REPO_ROOT / "unsloth_cli" / "_studio_runtime_gate.py"
+ )
+ gate = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(gate)
+ python_side = resolved
+ if python_side.startswith("\\\\?\\UNC\\"):
+ python_side = "\\\\" + python_side[8:]
+ elif python_side.startswith("\\\\?\\"):
+ python_side = python_side[4:]
+ assert got == python_side
@requires_pwsh
@@ -710,11 +766,11 @@ def test_the_recorded_owner_outranks_the_name(tmp_path: Path):
root = tmp_path / "root"
root.mkdir()
# Name says dead, owner.pid says alive: keep it.
- keep = root / f"ust-{_DEAD_PID}-a"
+ keep = root / f"ust-{_DEAD_PID}-000000aa"
keep.mkdir()
(keep / "owner.pid").write_text(str(os.getpid()), encoding = "utf-8")
# Name says alive, owner.pid says dead: the recorded owner wins, so sweep it.
- drop = root / f"ust-{os.getpid()}-b"
+ drop = root / f"ust-{os.getpid()}-000000bb"
drop.mkdir()
(drop / "owner.pid").write_text(str(_DEAD_PID), encoding = "utf-8")
@@ -744,11 +800,13 @@ def test_the_sweep_keeps_a_directory_whose_owner_is_still_running(tmp_path: Path
"""
root = tmp_path / "root"
root.mkdir()
- live = root / f"ust-{os.getpid()}-old"
+ live = root / f"ust-{os.getpid()}-01d01d01"
live.mkdir()
(live / "in-use.txt").write_text("a live process owns this", encoding = "utf-8")
- abandoned = root / f"ust-{_DEAD_PID}-old"
+ abandoned = root / f"ust-{_DEAD_PID}-01d01d01"
abandoned.mkdir()
+ # Recorded, not guessed: an unrecorded owner is now treated as unknown.
+ (abandoned / "owner.pid").write_text(str(_DEAD_PID), encoding = "utf-8")
aged = time.time() - 3 * 24 * 3600
os.utime(live, (aged, aged))
@@ -779,8 +837,10 @@ def test_a_healthy_temp_still_sweeps_what_an_earlier_degraded_run_left(tmp_path:
local_app_data = tmp_path / "localappdata"
root = local_app_data / "Unsloth Studio" / "temp"
root.mkdir(parents = True)
- abandoned = root / f"ust-{_DEAD_PID}-old"
+ abandoned = root / f"ust-{_DEAD_PID}-01d01d01"
abandoned.mkdir()
+ # Recorded, not guessed: an unrecorded owner is now treated as unknown.
+ (abandoned / "owner.pid").write_text(str(_DEAD_PID), encoding = "utf-8")
(abandoned / "leftover.bin").write_text("half a download", encoding = "utf-8")
aged = time.time() - 3 * 24 * 3600
os.utime(abandoned, (aged, aged))
@@ -807,6 +867,268 @@ Write-Output "OVERRIDE:$($null -ne $script:StudioTempOverride)"
assert _lines(result, "OVERRIDE:") == ["OVERRIDE:False"]
+@requires_pwsh
+def test_probing_the_host_temp_never_creates_it(tmp_path: Path):
+ """An inherited TMP that names nothing is unusable, not an instruction.
+
+ New-Item -Force builds the whole parent chain, so treating the host's own
+ TMP as creatable would have the installer materialize a tree at a path
+ nobody chose, on a stale or mistyped value, and then trust it as temp.
+ """
+ ghost = tmp_path / "ghost" / "deeper"
+ result = _run_powershell(
+ _script(
+ f"""
+Write-Output "USABLE:$(Test-StudioDirectoryUsable -Path '{ghost}')"
+Write-Output "EXISTS:$(Test-Path -LiteralPath '{ghost}')"
+""",
+ sabotage = False,
+ names = ("Write-StudioLine", "Test-StudioDirectoryUsable"),
+ )
+ )
+ assert result.returncode == 0, result.stderr
+ assert _lines(result, "USABLE:") == ["USABLE:False"]
+ assert _lines(result, "EXISTS:") == ["EXISTS:False"]
+ assert not ghost.exists()
+ # A directory the installer owns is a different matter: that one it creates.
+ owned = tmp_path / "owned" / "ust-1-aaaaaaaa"
+ result = _run_powershell(
+ _script(
+ f"Write-Output \"USABLE:$(Test-StudioDirectoryUsable -Path '{owned}' -CreateIfMissing)\"",
+ sabotage = False,
+ names = ("Write-StudioLine", "Test-StudioDirectoryUsable"),
+ )
+ )
+ assert result.returncode == 0, result.stderr
+ assert _lines(result, "USABLE:") == ["USABLE:True"]
+ assert owned.is_dir()
+
+
+@requires_pwsh
+def test_an_undeletable_probe_file_is_reclaimed_next_time(tmp_path: Path):
+ """The probe cannot clean up after itself when deletion is what failed.
+
+ Without a sweep every such run leaves one more file in the host's own
+ temp, forever, since nothing else knows the name. Aged, so a probe running
+ concurrently in another process is never touched.
+ """
+ good = tmp_path / "good"
+ good.mkdir()
+ stale = good / "unsloth-probe-deadbeef.tmp"
+ stale.write_text("left by a run that could not delete it", encoding = "utf-8")
+ fresh = good / "unsloth-probe-cafebabe.tmp"
+ fresh.write_text("another process is using this right now", encoding = "utf-8")
+ # Same prefix, same suffix, not the shape the probe writes. This sweep runs in
+ # the HOST's temp directory, so a name that merely starts the same way is
+ # somebody else's file however old it is.
+ theirs = good / "unsloth-probe-report.tmp"
+ theirs.write_text("not ours", encoding = "utf-8")
+ theirs_long = good / "unsloth-probe-deadbeefcafe.tmp"
+ theirs_long.write_text("not ours either", encoding = "utf-8")
+ aged = time.time() - 3 * 24 * 3600
+ for path in (stale, theirs, theirs_long):
+ os.utime(path, (aged, aged))
+
+ result = _run_powershell(
+ _script(
+ f"Write-Output \"USABLE:$(Test-StudioDirectoryUsable -Path '{good}')\"",
+ sabotage = False,
+ names = ("Write-StudioLine", "Test-StudioDirectoryUsable"),
+ )
+ )
+ assert result.returncode == 0, result.stderr
+ assert _lines(result, "USABLE:") == ["USABLE:True"]
+ assert not stale.exists()
+ assert fresh.exists()
+ assert theirs.exists(), "the sweep took a file that only shares the prefix"
+ assert theirs_long.exists(), "the sweep took a file that only shares the prefix"
+
+
+@requires_pwsh
+def test_a_root_that_fails_its_probe_is_not_left_behind(tmp_path: Path):
+ """A failed install must not conjure the data directory tree.
+
+ The probe creates each candidate before testing it, so on a host where
+ every root fails, giving up used to leave a "Unsloth Studio" tree on a
+ machine Studio was never installed on.
+ """
+ local_app_data = tmp_path / "localappdata"
+ local_app_data.mkdir()
+ user_profile = tmp_path / "userprofile"
+ user_profile.mkdir()
+
+ # Pre-existing content under one of the same parents: the unwind must stop.
+ keep = local_app_data / "Unsloth Studio" / "studio.port"
+ keep.parent.mkdir(parents = True)
+ keep.write_text("41343", encoding = "utf-8")
+
+ env = os.environ.copy()
+ env["LOCALAPPDATA"] = str(local_app_data)
+ env["USERPROFILE"] = str(user_profile)
+
+ result = _run_powershell(
+ _script(
+ """
+# Every candidate fails its probe, whatever the filesystem says.
+function Test-StudioDirectoryUsable {
+ param([string]$Path, [switch]$CreateIfMissing)
+ # Creates unconditionally, the way the real probe did before it took the
+ # switch, so this measures the caller rather than the stub.
+ New-Item -ItemType Directory -Path $Path -Force | Out-Null
+ return $false
+}
+Write-Output "PRIVATE:$(New-StudioPrivateTempDirectory)"
+""",
+ sabotage = False,
+ names = (
+ "Write-StudioLine",
+ "Remove-StudioStalePrivateTempDirectories",
+ "Get-StudioPrivateTempRoots",
+ "New-StudioPrivateTempDirectory",
+ ),
+ ),
+ env = env,
+ )
+ assert result.returncode == 0, result.stderr
+ assert _lines(result, "PRIVATE:") == ["PRIVATE:"]
+ # Not just the ust-* leaf: -Force built the whole chain, so "Unsloth Studio"
+ # and "temp" were conjured too and a run that gave up must not leave a data
+ # directory tree on a machine Studio was never installed on.
+ # ~\.unsloth itself is shared and stays; everything the probe made under it goes.
+ assert not (user_profile / ".unsloth" / ".cache").exists()
+ assert not list(user_profile.rglob("ust-*")), list(user_profile.rglob("*"))
+ assert keep.exists()
+ assert not list(local_app_data.rglob("ust-*")), list(local_app_data.rglob("*"))
+ assert not (local_app_data / "Unsloth Studio" / "temp").exists()
+
+
+@requires_pwsh
+def test_the_sweep_only_takes_directories_the_allocator_could_have_made(tmp_path: Path):
+ """Shape, not prefix. The delete is recursive and this is the only owner test.
+
+ A prefix match takes "ust-legacy" and "ust-user-cache" as well, and neither
+ has a parseable PID, so the liveness check is skipped for exactly the names
+ least likely to be ours. scripts/uninstall.ps1 already required the shape;
+ the installer sweep had drifted away from it.
+ """
+ root = tmp_path / "root"
+ root.mkdir()
+ aged = time.time() - 3 * 24 * 3600
+
+ ours = root / f"ust-{_DEAD_PID}-abcdef01"
+ ours.mkdir()
+ # Recorded, not guessed: an unrecorded owner is now treated as unknown.
+ (ours / "owner.pid").write_text(str(_DEAD_PID), encoding = "utf-8")
+ (ours / "scratch.bin").write_text("x", encoding = "utf-8")
+ keep = []
+ # Case-insensitively ours: Windows filenames are case-insensitive, so refusing
+ # the uppercase spelling would leak a directory we created.
+ upper = root / f"ust-{_DEAD_PID}-ABCDEF01"
+ upper.mkdir()
+ (upper / "owner.pid").write_text(str(_DEAD_PID), encoding = "utf-8")
+ for name in ("ust-legacy", "ust-user-cache", "ust-notapid-abcdef01", "ust-", "ust-12-abcdefg1"):
+ victim = root / name
+ victim.mkdir()
+ (victim / "keep.txt").write_text("not ours", encoding = "utf-8")
+ keep.append(victim)
+ for path in [ours, upper] + keep:
+ os.utime(path, (aged, aged))
+
+ result = _run_powershell(
+ _script(
+ f"Remove-StudioStalePrivateTempDirectories -Root '{root}'",
+ sabotage = False,
+ names = ("Remove-StudioStalePrivateTempDirectories",),
+ )
+ )
+ assert result.returncode == 0, result.stderr
+ assert not ours.exists()
+ assert not upper.exists()
+ for victim in keep:
+ assert (victim / "keep.txt").exists(), f"{victim.name} was swept"
+
+
+@requires_pwsh
+def test_a_native_resolver_that_throws_says_so_once(tmp_path: Path):
+ """Compiling and then failing to resolve is not the same as no compiler.
+
+ The install still proceeds on the lexical answer, and Exact = $false already
+ makes the runtime lock fail closed, but nothing said so: the degraded warning
+ fires only when the COMPILE failed. That left an operator with a silently
+ inexact identity on a host that looks perfectly healthy.
+ """
+ studio = tmp_path / "studio"
+ studio.mkdir()
+ result = _run_powershell(
+ _script(
+ f"""
+# The helper is "available" and throws anyway, which is what a rename between
+# the Test-Path walk and CreateFileW looks like.
+function Initialize-StudioFinalPathNativeType {{ return $true }}
+Add-Type -TypeDefinition @'
+public class UnslothStudioFinalPathV2 {{
+ public static string Resolve(string path) {{ throw new System.Exception("access is denied"); }}
+}}
+'@
+foreach ($i in 1..3) {{ $null = Resolve-StudioFinalPathInfo -Path '{studio}' }}
+$info = Resolve-StudioFinalPathInfo -Path '{studio}'
+Write-Output "EXACT:$($info.Exact)"
+Write-Output "PATH:$($info.Path)"
+""",
+ sabotage = False,
+ )
+ )
+ assert result.returncode == 0, result.stderr
+ assert _lines(result, "EXACT:") == ["EXACT:False"]
+ assert _lines(result, "PATH:")[0].endswith("studio")
+ warnings = [line for line in result.stdout.splitlines() if "native helper; continuing" in line]
+ assert len(warnings) == 1, warnings
+
+
+@requires_pwsh
+def test_an_unrecorded_owner_is_unknown_rather_than_abandoned(tmp_path: Path):
+ """The name's PID is the installer's, and it can be dead while Studio is not.
+
+ An installer killed between Start-Process and the owner.pid write leaves a
+ directory whose only owner evidence is a dead installer PID, while the
+ Studio it started is using that directory as its own %TEMP%. Reading is
+ proof; guessing from the name is not, so the two get different patience.
+ """
+ root = tmp_path / "root"
+ root.mkdir()
+ two_days = time.time() - 2 * 24 * 3600
+ eight_days = time.time() - 8 * 24 * 3600
+
+ # No owner.pid, dead name PID, two days old: unknown, so it stays.
+ unknown = root / f"ust-{_DEAD_PID}-aaaaaaaa"
+ unknown.mkdir()
+ (unknown / "in-use.txt").write_text("a live Studio may own this", encoding = "utf-8")
+ os.utime(unknown, (two_days, two_days))
+
+ # Same, but a week past: collected, so the pile still stays bounded.
+ ancient = root / f"ust-{_DEAD_PID}-bbbbbbbb"
+ ancient.mkdir()
+ os.utime(ancient, (eight_days, eight_days))
+
+ # Recorded dead owner, two days old: proof, so it goes at the usual cutoff.
+ recorded = root / f"ust-{_DEAD_PID}-cccccccc"
+ recorded.mkdir()
+ (recorded / "owner.pid").write_text(str(_DEAD_PID), encoding = "utf-8")
+ os.utime(recorded, (two_days, two_days))
+
+ result = _run_powershell(
+ _script(
+ f"Remove-StudioStalePrivateTempDirectories -Root '{root}'",
+ sabotage = False,
+ names = ("Remove-StudioStalePrivateTempDirectories",),
+ )
+ )
+ assert result.returncode == 0, result.stderr
+ assert (unknown / "in-use.txt").exists(), "an unrecorded owner was read as abandoned"
+ assert not ancient.exists(), "an unrecorded owner is never collected at all"
+ assert not recorded.exists(), "a recorded dead owner should still go at one day"
+
+
@requires_pwsh
def test_the_stale_sweep_never_deletes_through_a_link(tmp_path: Path):
root = tmp_path / "root"
@@ -816,12 +1138,15 @@ def test_the_stale_sweep_never_deletes_through_a_link(tmp_path: Path):
(precious / "keepme.txt").write_text("do not delete", encoding = "utf-8")
# A dead owner PID, or the sweep keeps the directory for the live process its
# name says owns it; that case is the test below.
- stale = root / f"ust-{_DEAD_PID}-old"
+ stale = root / f"ust-{_DEAD_PID}-01d01d01"
stale.mkdir()
+ # Recorded, not guessed: an unrecorded owner is now treated as unknown.
+ (stale / "owner.pid").write_text(str(_DEAD_PID), encoding = "utf-8")
(stale / "junk").write_text("x", encoding = "utf-8")
- fresh = root / f"ust-{_DEAD_PID}-new"
+ fresh = root / f"ust-{_DEAD_PID}-0e0e0e0e"
fresh.mkdir()
- link = root / f"ust-{_DEAD_PID}-link"
+ (fresh / "owner.pid").write_text(str(_DEAD_PID), encoding = "utf-8")
+ link = root / f"ust-{_DEAD_PID}-11111111"
try:
link.symlink_to(precious, target_is_directory = True)
except (OSError, NotImplementedError):
@@ -920,20 +1245,330 @@ def test_the_private_temp_directory_is_somewhere_uninstall_reclaims():
# install.ps1 falls through from a set-but-unusable LOCALAPPDATA to the known
# folder, so the variable being non-blank does not say where the tree landed.
assert "foreach ($root in @($env:LOCALAPPDATA, $knownLocalAppData)) {" in uninstall
- assert "foreach ($d in $defaultDataDirs) { _RemoveDataDirKeepingWslIcon $d }" in uninstall
- assert "_RemoveDataDirKeepingWslIcon $defaultDataDir " not in uninstall
+ # And the second spelling gets the TEMP TREE ONLY. It can name a different
+ # user's profile, and the data-dir delete is recursive with no ownership
+ # sentinel, so widening that to both roots would have been the larger bug.
+ assert 'Join-Path $root "Unsloth Studio\\temp"' in uninstall
+ assert "_RemoveStudioPrivateTempTrees -Paths $privateTempDirs" in uninstall
+ assert "foreach ($d in $defaultDataDirs)" not in uninstall
+
+
+@requires_pwsh
+def test_the_uninstall_sweep_leaves_a_live_owner_and_never_follows_a_link(tmp_path: Path):
+ """An uninstall stops the Studios under the roots it knows about, not others.
+
+ A Studio from another install root, or another user, can be alive on one of
+ these directories as its %TEMP%; install.ps1's own sweep preserves it and so
+ must this one. And a temp directory that is itself a link must not be walked:
+ the target's children carry no ReparsePoint attribute, so a recursive delete
+ would take an unrelated tree.
+ """
+ uninstall = (REPO_ROOT / "scripts" / "uninstall.ps1").read_text(encoding = "utf-8")
+ block = _extract(r" function _RemoveStudioPrivateTempTrees \{.*?\n \}\n", uninstall)
+ preamble = (
+ '$ErrorActionPreference = "Stop"\nfunction _Substep { param([string]$Msg, [string]$Color) }'
+ )
+
+ # 1. A live owner is left alone; a dead one goes.
+ temp = tmp_path / "Unsloth Studio" / "temp"
+ temp.mkdir(parents = True)
+ live = temp / "ust-1234-abcdef01"
+ live.mkdir()
+ (live / "owner.pid").write_text(str(os.getpid()), encoding = "utf-8")
+ dead = temp / "ust-1234-abcdef02"
+ dead.mkdir()
+ (dead / "owner.pid").write_text(str(_DEAD_PID), encoding = "utf-8")
+
+ result = _run_powershell(
+ "\n".join(
+ [
+ preamble,
+ block,
+ f"_RemoveStudioPrivateTempTrees -Paths @('{temp}') -PrimaryPath '{temp}'",
+ 'Write-Output "DONE:1"',
+ ]
+ )
+ )
+ assert result.returncode == 0, result.stderr
+ assert _lines(result, "DONE:") == ["DONE:1"]
+ assert (live / "owner.pid").exists(), "a live owner's temp was removed"
+ assert not dead.exists()
+
+ # 2. A linked temp directory is refused outright.
+ victim = tmp_path / "victim"
+ victim.mkdir()
+ (victim / "ust-1234-abcdef03").mkdir()
+ (victim / "ust-1234-abcdef03" / "precious.txt").write_text("not ours", encoding = "utf-8")
+ linked = tmp_path / "Linked Studio" / "temp"
+ linked.parent.mkdir()
+ linked.symlink_to(victim, target_is_directory = True)
+
+ result = _run_powershell(
+ "\n".join(
+ [
+ preamble,
+ block,
+ f"_RemoveStudioPrivateTempTrees -Paths @('{linked}') -PrimaryPath '{linked}'",
+ 'Write-Output "DONE:2"',
+ ]
+ )
+ )
+ assert result.returncode == 0, result.stderr
+ assert _lines(result, "DONE:") == ["DONE:2"]
+ assert (
+ victim / "ust-1234-abcdef03" / "precious.txt"
+ ).exists(), "the sweep walked through a link"
+
+
+@requires_pwsh
+def test_a_live_owner_survives_the_data_directory_removal(tmp_path: Path):
+ """Preserving a directory is worth nothing if the next line deletes its parent.
+
+ The primary private temp directory sits inside the data directory, and the
+ data directory is removed wholesale. A Studio from another install root can
+ be alive on that temp directory as its %TEMP%, so the sweep has to run first
+ and the removal has to be told what the sweep kept.
+ """
+ uninstall = (REPO_ROOT / "scripts" / "uninstall.ps1").read_text(encoding = "utf-8")
+
+ # The order is a property of the script body, not of any one function, so it
+ # is checked as one: every wholesale data-dir removal is preceded by the
+ # sweep and carries what the sweep kept.
+ body = uninstall[uninstall.index("function Uninstall-UnslothStudio") :]
+ calls = [
+ line.strip()
+ for line in body.splitlines()
+ if (
+ "_RemoveDataDirKeepingWslIcon $defaultDataDir" in line
+ or "_RemoveStudioPrivateTempTrees -Paths" in line
+ )
+ ]
+ assert calls, "neither call is in the script body"
+ for index, line in enumerate(calls):
+ if "_RemoveDataDirKeepingWslIcon" not in line:
+ continue
+ assert "-Preserve" in line, f"data dir removed without the preserved list: {line}"
+ assert (
+ index > 0 and "_RemoveStudioPrivateTempTrees" in calls[index - 1]
+ ), f"the data dir is removed before the temp sweep runs: {line}"
+
+ blocks = "\n".join(
+ _extract(rf" function {name} \{{.*?\n \}}\n", uninstall)
+ for name in (
+ "_RemoveStudioPrivateTempTrees",
+ "_RemoveTreeKeeping",
+ "_RemoveDataDirKeepingWslIcon",
+ )
+ )
+
+ data = tmp_path / "Unsloth Studio"
+ temp = data / "temp"
+ temp.mkdir(parents = True)
+ live = temp / "ust-4321-abcdef05"
+ live.mkdir()
+ (live / "owner.pid").write_text(str(os.getpid()), encoding = "utf-8")
+ (live / "scratch.bin").write_text("in use", encoding = "utf-8")
+ dead = temp / "ust-4321-abcdef06"
+ dead.mkdir()
+ (dead / "owner.pid").write_text(str(_DEAD_PID), encoding = "utf-8")
+ other = data / "launcher.db"
+ other.write_text("data", encoding = "utf-8")
+
+ result = _run_powershell(
+ "\n".join(
+ [
+ '$ErrorActionPreference = "Stop"',
+ "function _Substep { param([string]$Msg, [string]$Color) }",
+ "function _RemovePath { param([string]$Path)"
+ " Remove-Item -LiteralPath $Path -Recurse -Force -ErrorAction SilentlyContinue }",
+ blocks,
+ f"$kept = @(_RemoveStudioPrivateTempTrees -Paths @('{temp}') -PrimaryPath '{temp}')",
+ 'Write-Output ("KEPT:" + @($kept).Count)',
+ f"_RemoveDataDirKeepingWslIcon -DataDir '{data}' -ShortcutDirs @() -Preserve $kept",
+ 'Write-Output "DONE:1"',
+ ]
+ )
+ )
+ assert result.returncode == 0, result.stderr
+ assert _lines(result, "DONE:") == ["DONE:1"]
+ assert _lines(result, "KEPT:") == ["KEPT:1"]
+ assert (live / "scratch.bin").exists(), "a live Studio's %TEMP% went with the data dir"
+ assert not dead.exists()
+ assert not other.exists(), "the rest of the data dir was left behind"
+
+
+@requires_pwsh
+def test_a_link_high_above_another_profile_is_still_a_link(tmp_path: Path):
+ r"""A junction does not have to sit next to the temp directory to redirect it.
+
+ LocalAppData itself, the profile, or the drive root can be the reparse
+ point, and then "<root>\Unsloth Studio\temp" and its parent both look like
+ perfectly ordinary directories while the enumeration lands somewhere else
+ entirely. For a spelling that is not the profile being uninstalled, that
+ somewhere else can be another user, so every ancestor has to be ordinary.
+
+ The profile this uninstall IS for is deliberately not held to that: a
+ redirected LocalAppData there is the same user's own storage, and refusing
+ would leave the installer's own temp tree behind on every host that uses
+ folder redirection.
+ """
+ if os.path.realpath(tmp_path) != str(tmp_path):
+ pytest.skip("the temp root itself is a link, which is what this test plants")
+
+ uninstall = (REPO_ROOT / "scripts" / "uninstall.ps1").read_text(encoding = "utf-8")
+ block = _extract(r" function _RemoveStudioPrivateTempTrees \{.*?\n \}\n", uninstall)
+ preamble = (
+ '$ErrorActionPreference = "Stop"\nfunction _Substep { param([string]$Msg, [string]$Color) }'
+ )
+
+ # The real profile, with a Studio temp tree in it that belongs to a dead
+ # owner: nothing about the entries themselves protects them.
+ real = tmp_path / "real profile"
+ real_temp = real / "localappdata" / "Unsloth Studio" / "temp"
+ real_temp.mkdir(parents = True)
+ stale = real_temp / "ust-1234-abcdef04"
+ stale.mkdir()
+ (stale / "owner.pid").write_text(str(_DEAD_PID), encoding = "utf-8")
+ (stale / "precious.txt").write_text("another profile", encoding = "utf-8")
+
+ # Three levels above the temp directory, so neither it nor its parent is a
+ # link. Only a full walk sees this.
+ redirected = tmp_path / "redirected profile"
+ redirected.symlink_to(real, target_is_directory = True)
+ aliased = redirected / "localappdata" / "Unsloth Studio" / "temp"
+
+ other = tmp_path / "mine" / "Unsloth Studio" / "temp"
+ other.mkdir(parents = True)
+
+ result = _run_powershell(
+ "\n".join(
+ [
+ preamble,
+ block,
+ f"_RemoveStudioPrivateTempTrees -Paths @('{aliased}') -PrimaryPath '{other}'",
+ 'Write-Output "DONE:1"',
+ ]
+ )
+ )
+ assert result.returncode == 0, result.stderr
+ assert _lines(result, "DONE:") == ["DONE:1"]
+ assert (stale / "precious.txt").exists(), "the sweep walked through a link high above the root"
+
+ # Same shape, but now it is this uninstall's own profile: the tree goes.
+ result = _run_powershell(
+ "\n".join(
+ [
+ preamble,
+ block,
+ f"_RemoveStudioPrivateTempTrees -Paths @('{aliased}') -PrimaryPath '{aliased}'",
+ 'Write-Output "DONE:2"',
+ ]
+ )
+ )
+ assert result.returncode == 0, result.stderr
+ assert _lines(result, "DONE:") == ["DONE:2"]
+ assert not stale.exists(), "a redirected profile cannot clean its own temp tree"
@requires_pwsh
-def test_the_uninstaller_reclaims_both_local_app_data_spellings(tmp_path: Path):
+def test_a_pre_existing_fallback_parent_is_not_unwound(tmp_path: Path):
+ """Only what the probe created may be taken back.
+
+ A pre-provisioned "Unsloth Studio\temp" with its own ACLs, or an empty
+ relocation junction, is configuration this installer did not create. Empty
+ and correctly named is not the same as ours.
+ """
+ local_app_data = tmp_path / "localappdata"
+ provisioned = local_app_data / "Unsloth Studio" / "temp"
+ provisioned.mkdir(parents = True)
+ user_profile = tmp_path / "userprofile"
+ user_profile.mkdir()
+
+ env = os.environ.copy()
+ env["LOCALAPPDATA"] = str(local_app_data)
+ env["USERPROFILE"] = str(user_profile)
+
+ result = _run_powershell(
+ _script(
+ """
+function Test-StudioDirectoryUsable {
+ param([string]$Path, [switch]$CreateIfMissing)
+ New-Item -ItemType Directory -Path $Path -Force | Out-Null
+ return $false
+}
+Write-Output "PRIVATE:$(New-StudioPrivateTempDirectory)"
+""",
+ sabotage = False,
+ names = (
+ "Write-StudioLine",
+ "Remove-StudioStalePrivateTempDirectories",
+ "Get-StudioPrivateTempRoots",
+ "New-StudioPrivateTempDirectory",
+ ),
+ ),
+ env = env,
+ )
+ assert result.returncode == 0, result.stderr
+ assert _lines(result, "PRIVATE:") == ["PRIVATE:"]
+ # The candidate the probe made is gone; the directory that was already there stays.
+ assert not list(provisioned.glob("ust-*"))
+ assert provisioned.is_dir(), "a pre-existing temp directory was unwound"
+ # And the tree the probe DID create under the other root is still taken back.
+ assert not (user_profile / ".unsloth" / ".cache").exists()
+
+
+@requires_pwsh
+def test_the_uninstall_sweep_needs_a_recorded_owner_outside_its_own_profile(tmp_path: Path):
+ """The alternate LocalAppData spelling can be another user's profile.
+
+ install.ps1 reads a missing owner.pid as unknown rather than abandoned,
+ because an installer killed before writing it leaves a live Studio holding
+ the directory. Deleting that out of somebody else's profile is not this
+ uninstall's business. Under our own profile the shape is enough, since that
+ is what is being removed.
+ """
+ uninstall = (REPO_ROOT / "scripts" / "uninstall.ps1").read_text(encoding = "utf-8")
+ block = _extract(r" function _RemoveStudioPrivateTempTrees \{.*?\n \}\n", uninstall)
+ preamble = (
+ '$ErrorActionPreference = "Stop"\nfunction _Substep { param([string]$Msg, [string]$Color) }'
+ )
+
+ mine = tmp_path / "mine" / "Unsloth Studio" / "temp"
+ theirs = tmp_path / "theirs" / "Unsloth Studio" / "temp"
+ for root in (mine, theirs):
+ root.mkdir(parents = True)
+ (root / "ust-1234-abcdef01").mkdir()
+
+ result = _run_powershell(
+ "\n".join(
+ [
+ preamble,
+ block,
+ f"_RemoveStudioPrivateTempTrees -Paths @('{mine}','{theirs}') -PrimaryPath '{mine}'",
+ 'Write-Output "DONE:1"',
+ ]
+ )
+ )
+ assert result.returncode == 0, result.stderr
+ assert _lines(result, "DONE:") == ["DONE:1"]
+ assert not (mine / "ust-1234-abcdef01").exists(), "our own profile should be reclaimed"
+ assert (
+ theirs / "ust-1234-abcdef01"
+ ).is_dir(), "another profile was swept without a recorded owner"
+
+
+@requires_pwsh
+def test_the_uninstaller_reclaims_the_temp_tree_at_both_spellings(tmp_path: Path):
"""A set-but-unusable LOCALAPPDATA is the case that produced two roots.
install.ps1 skips such a path and places its private temp under the known
- folder instead. An uninstaller that stops at the first non-blank candidate
- then deletes a directory that was never used and leaves the real one behind.
+ folder instead, so an uninstaller that stops at the first non-blank
+ candidate leaves the real tree behind. What the second root must NOT get is
+ the recursive, sentinel-free data-dir delete: the two spellings differ
+ mainly when one of them names a DIFFERENT USER's profile.
"""
uninstall = (REPO_ROOT / "scripts" / "uninstall.ps1").read_text(encoding = "utf-8")
- block = _extract(r" # BOTH LocalAppData spellings.*?\n \}\n", uninstall)
+ block = _extract(r" # The SECOND LocalAppData spelling.*?\n \}\n", uninstall)
dead = str(tmp_path / "gone" / "localappdata")
env = os.environ.copy()
@@ -943,7 +1578,7 @@ def test_the_uninstaller_reclaims_both_local_app_data_spellings(tmp_path: Path):
[
'$ErrorActionPreference = "Stop"',
block,
- '$defaultDataDirs | ForEach-Object { Write-Output "DIR:$_" }',
+ '$privateTempDirs | ForEach-Object { Write-Output "DIR:$_" }',
]
),
env = env,
@@ -952,41 +1587,50 @@ def test_the_uninstaller_reclaims_both_local_app_data_spellings(tmp_path: Path):
dirs = [line[len("DIR:") :] for line in _lines(result, "DIR:")]
assert len(dirs) == 2, dirs
assert any(d.startswith(dead) for d in dirs), dirs
- assert all(d.rstrip("\\/").endswith("Unsloth Studio") for d in dirs), dirs
- # Deduplicated, so the ordinary host where both spellings agree is untouched.
+ # The temp tree, not the data directory.
+ assert all(d.rstrip("\\/").endswith("temp") for d in dirs), dirs
assert len(set(dirs)) == len(dirs)
-def test_path_resolution_and_process_identity_no_longer_need_the_compiler():
- source = INSTALL_PS1.read_text(encoding = "utf-8")
+@requires_pwsh
+def test_the_private_temp_removal_only_takes_what_it_created(tmp_path: Path):
+ """Narrow on purpose: this runs against a root that may be another user's.
- # The resolver callers reach is now a dispatcher; only the initializer builds.
- assert "Add-Type" not in _extract(r" function Get-StudioFinalPath \{.*?\n \}\n", source)
- assert "Add-Type" not in _extract(
- r" function Resolve-StudioFinalPathInfo \{.*?\n \}\n", source
- )
- assert "Add-Type" not in _extract(r" function Get-StudioLexicalPath \{.*?\n \}\n", source)
-
- # Every rung of the fallback must keep the "confirmed executable image only"
- # contract, or a degraded host would block on a name match.
- image = _extract(r" function Get-StudioProcessImagePath \{.*?\n \}\n", source)
- assert ".CommandLine" not in image
- assert "Win32_Process" in image
- assert "QueryFullProcessImageNameW" not in image
-
- # Source rather than behaviour on purpose: PowerShell 7 does not follow a link
- # on -Recurse, so the test above passes with or without this guard. Windows
- # PowerShell 5.1, the shell the desktop app spawns, does follow it.
- sweep = _extract(
- r" function Remove-StudioStalePrivateTempDirectories \{.*?\n \}\n", source
- )
- assert "ReparsePoint" in sweep
- reparse_branch = sweep.index("ReparsePoint")
- branch = sweep[reparse_branch : sweep.index("continue", reparse_branch)]
- assert "-Recurse" not in branch
- # Remove-Item without -Recurse is no answer either: on 5.1 it reports the
- # junction target's contents and refuses as "directory not empty", so the link is
- # never reclaimed (observed on windows-latest).
- assert "Remove-Item" not in branch
- assert "[System.IO.Directory]::Delete(" in branch
- assert ", $false)" in branch
+ Only ust-<pid>-<hex> directories go, matched by shape rather than prefix,
+ and the temp directory and its parent only when they are left empty.
+ """
+ uninstall = (REPO_ROOT / "scripts" / "uninstall.ps1").read_text(encoding = "utf-8")
+ block = _extract(r" function _RemoveStudioPrivateTempTrees \{.*?\n \}\n", uninstall)
+
+ data = tmp_path / "Unsloth Studio"
+ temp = data / "temp"
+ temp.mkdir(parents = True)
+ (temp / "ust-1234-abcdef01").mkdir()
+ (temp / "ust-1234-abcdef01" / "scratch.bin").write_text("x", encoding = "utf-8")
+ (temp / "ust-legacy").mkdir()
+ (temp / "ust-notapid-abcdef01").mkdir()
+ (temp / "somebody-elses").mkdir()
+ (data / "studio.port").write_text("41343", encoding = "utf-8")
+
+ result = _run_powershell(
+ "\n".join(
+ [
+ '$ErrorActionPreference = "Stop"',
+ "function _Substep { param([string]$Msg, [string]$Color) }",
+ block,
+ # The profile being uninstalled, so shape alone is enough here.
+ f"_RemoveStudioPrivateTempTrees -Paths @('{temp}') -PrimaryPath '{temp}'",
+ 'Write-Output "DONE:1"',
+ ]
+ )
+ )
+ assert result.returncode == 0, result.stderr
+ assert _lines(result, "DONE:") == ["DONE:1"]
+ assert not (temp / "ust-1234-abcdef01").exists()
+ # Prefix, not shape, would have taken all three of these.
+ assert (temp / "ust-legacy").is_dir()
+ assert (temp / "ust-notapid-abcdef01").is_dir()
+ assert (temp / "somebody-elses").is_dir()
+ # And neither directory went, because neither was left empty.
+ assert temp.is_dir()
+ assert (data / "studio.port").exists()
diff --git a/tests/studio/test_uninstall_dual_install_icon.ps1 b/tests/studio/test_uninstall_dual_install_icon.ps1
index 938db2cb13b..648d561fceb 100644
--- a/tests/studio/test_uninstall_dual_install_icon.ps1
+++ b/tests/studio/test_uninstall_dual_install_icon.ps1
@@ -18,10 +18,18 @@ $uninstallPath = (Resolve-Path $uninstallPath).Path
$tokens = $null; $errors = $null
$ast = [System.Management.Automation.Language.Parser]::ParseFile($uninstallPath, [ref]$tokens, [ref]$errors)
if ($errors) { $errors | ForEach-Object { $_.ToString() }; throw "uninstall.ps1 has parse errors" }
-$fn = $ast.FindAll({ param($n)
- $n -is [System.Management.Automation.Language.FunctionDefinitionAst] -and $n.Name -eq "_RemoveDataDirKeepingWslIcon"
-}, $true)
-if ($fn.Count -ne 1) { throw "expected exactly one _RemoveDataDirKeepingWslIcon, found $($fn.Count)" }
+# _RemoveTreeKeeping does the actual deleting: the helper delegates to it so a
+# directory a previous pass decided to keep (a live Studio's private %TEMP%)
+# survives the data-dir removal.
+$wanted = @("_RemoveDataDirKeepingWslIcon", "_RemoveTreeKeeping")
+$fn = @()
+foreach ($name in $wanted) {
+ $found = $ast.FindAll({ param($n)
+ $n -is [System.Management.Automation.Language.FunctionDefinitionAst] -and $n.Name -eq $name
+ }.GetNewClosure(), $true)
+ if ($found.Count -ne 1) { throw "expected exactly one $name, found $($found.Count)" }
+ $fn += $found[0]
+}
# Stubs the helper depends on (nested in Uninstall-UnslothStudio in production).
function _Substep { param([string]$Msg, [string]$Color = "Gray") }
@@ -31,7 +39,7 @@ function _RemovePath {
Remove-Item -LiteralPath $Path -Recurse -Force -ErrorAction SilentlyContinue
}
}
-. ([ScriptBlock]::Create($fn[0].Extent.Text)) # defines _RemoveDataDirKeepingWslIcon
+foreach ($f in $fn) { . ([ScriptBlock]::Create($f.Extent.Text)) }
$failures = 0
function Check($name, $cond) {