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.

Install Studio on a Windows host whose C# compiler cannot run (#9178)

Daniel Han21296c427497
diff --git a/install.ps1 b/install.ps1
index 0c1d21864a9..f7916b6b81d 100644
--- a/install.ps1
+++ b/install.ps1
@@ -315,12 +315,247 @@ function Install-UnslothStudio {
if (Get-Command Restore-StudioVenvRollback -CommandType Function -ErrorAction SilentlyContinue) {
Restore-StudioVenvRollback
}
+ # Most failures return before the lock try/finally, and under `irm | iex`
+ # these variables are the caller's own. Defined later, so probed like above.
+ if (Get-Command Restore-StudioTempEnvironment -CommandType Function -ErrorAction SilentlyContinue) {
+ Restore-StudioTempEnvironment
+ }
if ($TauriMode) {
exit $Code
}
throw $Message
}
+ # ── Usable temporary storage ──
+ # Windows picks the temp directory from TMP, then TEMP, then the profile, and
+ # never checks it exists or is writable. The desktop app passes on whatever it
+ # inherited (studio/src-tauri/src/install.rs sets neither); one report had it at
+ # C:\Windows\TEMP, where the source Add-Type had just written was gone by the
+ # time csc.exe opened it (issue #9140). The Python, uv and VC++ downloads stage
+ # through it too. Probe it once and, if it cannot hold a file, point BOTH
+ # 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)
+ if ([string]::IsNullOrWhiteSpace($Path)) { return $false }
+ try {
+ if (-not (Test-Path -LiteralPath $Path -PathType Container)) {
+ New-Item -ItemType Directory -Path $Path -Force -ErrorAction Stop | Out-Null
+ }
+ # 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")
+ [System.IO.File]::WriteAllText($probe, "unsloth")
+ $readBack = [System.IO.File]::ReadAllText($probe)
+ # Deleting has to work too, and be VERIFIED. csc.exe writes its source
+ # and its output into this directory and then cleans up, so one that
+ # accepts a file and will not give it back is the shape that produced
+ # #9140; a suppressed Remove-Item said nothing either way. Retried a
+ # couple of times first, because a scanner holding the file for a
+ # moment is not the same as a directory that denies deletion, and only
+ # the second should cost a healthy host its own temp.
+ $probeGone = $false
+ foreach ($attempt in 1..3) {
+ Remove-Item -LiteralPath $probe -Force -ErrorAction SilentlyContinue
+ if (-not [System.IO.File]::Exists($probe)) { $probeGone = $true; break }
+ Start-Sleep -Milliseconds 100
+ }
+ if (-not $probeGone) { return $false }
+ return ($readBack -eq "unsloth")
+ } catch {
+ return $false
+ }
+ }
+
+ function Remove-StudioStalePrivateTempDirectories {
+ param([Parameter(Mandatory = $true)][string]$Root)
+ # These outlive the install (an autostarted Studio inherits one as its own
+ # %TEMP%), so bound the pile by age instead of deleting one still in use.
+ try {
+ $cutoff = (Get-Date).AddDays(-1)
+ foreach ($stale in @(Get-ChildItem -LiteralPath $Root -Directory -Filter "ust-*" -ErrorAction Stop)) {
+ if ($stale.LastWriteTime -ge $cutoff) { 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
+ # Studio, which outlives the installer); the PID in the name is only
+ # the installer's and is already gone. If the owner is alive, leave it.
+ # PID reuse only ever costs a directory its cleanup.
+ $ownerPid = 0
+ $ownerFile = Join-Path $stale.FullName "owner.pid"
+ $recorded = $null
+ try {
+ if ([System.IO.File]::Exists($ownerFile)) {
+ $recorded = [System.IO.File]::ReadAllText($ownerFile).Trim()
+ }
+ } catch { $recorded = $null }
+ if (-not [string]::IsNullOrWhiteSpace($recorded)) {
+ $null = [int]::TryParse($recorded, [ref]$ownerPid)
+ }
+ if ($ownerPid -le 0) {
+ $null = [int]::TryParse(($stale.Name -split '-')[1], [ref]$ownerPid)
+ }
+ if ($ownerPid -gt 0) {
+ $ownerLives = $true
+ try {
+ $null = Get-Process -Id $ownerPid -ErrorAction Stop
+ } catch [Microsoft.PowerShell.Commands.ProcessCommandException] {
+ # The only answer that means "abandoned"; any other failure
+ # says nothing about the owner, so keep the directory.
+ $ownerLives = $false
+ } catch {
+ $ownerLives = $true
+ }
+ 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 {}
+ }
+
+ function Set-StudioPrivateTempOwner {
+ param([Parameter(Mandatory = $true)][int]$OwnerProcessId)
+ # Only meaningful if this run redirected the temp; otherwise it is the host's.
+ if ($null -eq $script:StudioTempOverride) { return }
+ # Only a directory this run created. The other override shape just pins the
+ # absolute spelling of the host's own temp, and dropping a file in there
+ # would be litter in somebody else's directory.
+ if (-not $script:StudioTempOverride.Owned) { return }
+ $owned = $script:StudioTempOverride.Path
+ if ([string]::IsNullOrWhiteSpace($owned)) { return }
+ try {
+ [System.IO.File]::WriteAllText((Join-Path $owned "owner.pid"), [string]$OwnerProcessId)
+ } catch {}
+ }
+
+ function Get-StudioPrivateTempRoots {
+ # Only under paths scripts/uninstall.ps1 already reclaims (LOCALAPPDATA\
+ # "Unsloth Studio", ~\.unsloth\.cache): anywhere else would survive an
+ # uninstall, and a leftover directly under ~\.unsloth would be worse, since
+ # that is removed only when empty.
+ $roots = @()
+ if (-not [string]::IsNullOrWhiteSpace($env:LOCALAPPDATA)) {
+ $roots += (Join-Path $env:LOCALAPPDATA "Unsloth Studio\temp")
+ }
+ try {
+ $localAppData = [Environment]::GetFolderPath("LocalApplicationData")
+ if (-not [string]::IsNullOrWhiteSpace($localAppData)) {
+ $roots += (Join-Path $localAppData "Unsloth Studio\temp")
+ }
+ } catch {}
+ if (-not [string]::IsNullOrWhiteSpace($env:USERPROFILE)) {
+ $roots += (Join-Path $env:USERPROFILE ".unsloth\.cache\temp")
+ }
+ return $roots
+ }
+
+ function New-StudioPrivateTempDirectory {
+ foreach ($root in @(Get-StudioPrivateTempRoots)) {
+ # Short leaf: the .NET Framework compiler 5.1 shells out to is still
+ # 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) {
+ Remove-StudioStalePrivateTempDirectories -Root $root
+ return $candidate
+ }
+ }
+ return $null
+ }
+
+ $script:StudioTempOverride = $null
+ $script:StudioTempChecked = $false
+ function Initialize-StudioTempEnvironment {
+ if ($script:StudioTempChecked) { return }
+ $script:StudioTempChecked = $true
+ # TMP wins over TEMP, so only fall through when TMP is unset. IsNullOrEmpty,
+ # not IsNullOrWhiteSpace: GetTempPath takes the first of TMP/TEMP that is
+ # merely non-empty, so a whitespace-only TMP is what Windows and every child
+ # will use, and treating it as unset would probe a healthy TEMP and change
+ # nothing.
+ $inherited = if (-not [string]::IsNullOrEmpty($env:TMP)) { $env:TMP } else { $env:TEMP }
+ # Resolve BEFORE probing, not after. Test-Path is relative to PowerShell's
+ # location while the .NET file APIs are relative to the process working
+ # directory, and Set-Location moves only the first, so probing a relative
+ # value can check one directory and write to another.
+ # Whitespace-only is left exactly as it is, so the probe below rejects it.
+ # Resolving it first would turn " " or a tab into the working directory
+ # plus that name, which is creatable on some filesystems, and the installer
+ # would manufacture a junk directory and then trust it as the host's temp.
+ $absolute = $inherited
+ if (-not [string]::IsNullOrWhiteSpace($inherited)) {
+ try { $absolute = [System.IO.Path]::GetFullPath($inherited) } catch { $absolute = $inherited }
+ }
+ if (Test-StudioDirectoryUsable -Path $absolute) {
+ # A host whose temp was fixed since the last run never allocates another
+ # private directory, and the allocator is the only thing that sweeps.
+ # Without this, whatever an earlier degraded run left behind ages in
+ # place until an uninstall. Each root that does not exist is a no-op.
+ foreach ($root in @(Get-StudioPrivateTempRoots)) {
+ Remove-StudioStalePrivateTempDirectories -Root $root
+ }
+ # Pin what was probed. A relative value (temp, or the drive-relative
+ # C:temp) is resolved by whoever reads it, and the install relocates
+ # out of a Windows system directory further down, so the same value
+ # could later name somewhere else, or nowhere. An already-absolute
+ # value normalizes to itself and is left alone.
+ if (-not [string]::Equals($absolute, $inherited, [System.StringComparison]::Ordinal)) {
+ $script:StudioTempOverride = [pscustomobject]@{
+ TmpSet = ($null -ne $env:TMP)
+ TmpValue = $env:TMP
+ TempSet = ($null -ne $env:TEMP)
+ TempValue = $env:TEMP
+ Path = $absolute
+ Owned = $false
+ }
+ $env:TMP = $absolute
+ $env:TEMP = $absolute
+ }
+ return
+ }
+ $private = New-StudioPrivateTempDirectory
+ if (-not $private) {
+ Write-StudioLine "[WARN] No writable temporary directory was found; downloads may fail." -ForegroundColor Yellow
+ return
+ }
+ # Absent is not empty: restoring an absent variable as "" would change how
+ # every later child resolves its own temp directory.
+ $script:StudioTempOverride = [pscustomobject]@{
+ TmpSet = ($null -ne $env:TMP)
+ TmpValue = $env:TMP
+ TempSet = ($null -ne $env:TEMP)
+ TempValue = $env:TEMP
+ Path = $private
+ Owned = $true
+ }
+ $env:TMP = $private
+ $env:TEMP = $private
+ Write-StudioLine "[WARN] The inherited temporary directory is not usable; this install will use its own." -ForegroundColor Yellow
+ }
+
+ function Restore-StudioTempEnvironment {
+ $override = $script:StudioTempOverride
+ if ($null -eq $override) { return }
+ $script:StudioTempOverride = $null
+ if ($override.TmpSet) { $env:TMP = $override.TmpValue }
+ else { Remove-Item Env:\TMP -ErrorAction SilentlyContinue }
+ if ($override.TempSet) { $env:TEMP = $override.TempValue }
+ else { Remove-Item Env:\TEMP -ErrorAction SilentlyContinue }
+ # The directory stays: an autostarted Studio inherited it as its own %TEMP%,
+ # and the host's real one is broken. The next run sweeps the old ones.
+ }
+
# ── Parse flags ──
$StudioLocalInstall = $false
$PackageName = "unsloth"
@@ -416,26 +651,42 @@ function Install-UnslothStudio {
try { $defaultProfile = [Environment]::GetFolderPath("UserProfile") } catch {}
$tauriProfile = if ($defaultProfile) { $defaultProfile } else { $env:USERPROFILE }
- function Get-StudioFinalPath {
- param([Parameter(Mandatory = $true)][string]$Path)
- $fullPath = [System.IO.Path]::GetFullPath($Path)
- $fullRoot = [System.IO.Path]::GetPathRoot($fullPath)
- if (-not $fullRoot -or $fullPath.Length -gt $fullRoot.Length) {
- $fullPath = $fullPath.TrimEnd('\', '/')
+ # GetFinalPathNameByHandleW is the only exact answer: it follows junctions,
+ # symlinks and SUBST drives, expands 8.3 aliases and reports the on-disk
+ # spelling, none of which GetFullPath does. It costs a C# compile, and 5.1 (the
+ # interpreter the desktop app spawns) compiles by writing the source to %TEMP%
+ # and running csc.exe. When that directory is unusable, or a scanner eats the
+ # source, Add-Type throws CS2001, which used to abort a first launch as "Could
+ # not create the Studio install lock" (issue #9140). Try once, retry with a
+ # %TEMP% we own, cache the answer (callers resolve dozens of paths), then let
+ # Get-StudioLexicalPath carry the run.
+ $script:StudioFinalPathNativeState = $null
+ $script:StudioFinalPathWarned = $false
+ function Write-StudioFinalPathDegraded {
+ param([string]$Reason)
+ if ($script:StudioFinalPathWarned) { return }
+ $script:StudioFinalPathWarned = $true
+ Write-StudioLine "[WARN] Could not load the native path resolver ($Reason)." -ForegroundColor Yellow
+ Write-StudioLine " Continuing with the PowerShell resolver; installation is unaffected." -ForegroundColor Yellow
+ }
+
+ function Initialize-StudioFinalPathNativeType {
+ if ("UnslothStudioFinalPathV2" -as [type]) {
+ $script:StudioFinalPathNativeState = $true
+ return $true
}
- $existingPath = $fullPath
- $missingSegments = @()
- while (-not (Test-Path -LiteralPath $existingPath)) {
- $leaf = [System.IO.Path]::GetFileName($existingPath)
- $parent = [System.IO.Path]::GetDirectoryName($existingPath)
- if ([string]::IsNullOrEmpty($leaf) -or [string]::IsNullOrEmpty($parent)) {
- return $fullPath
- }
- $missingSegments = @($leaf) + $missingSegments
- $existingPath = $parent
+ if ($null -ne $script:StudioFinalPathNativeState) { return $script:StudioFinalPathNativeState }
+ # Constrained Language Mode forbids Add-Type, so compiling would only produce
+ # a second, less honest error.
+ $languageMode = "FullLanguage"
+ try { $languageMode = [string]$ExecutionContext.SessionState.LanguageMode } catch {}
+ if ($languageMode -ne "FullLanguage") {
+ $script:StudioFinalPathNativeState = $false
+ Write-StudioFinalPathDegraded -Reason "PowerShell is in $languageMode"
+ return $false
}
- if (-not ("UnslothStudioFinalPathV2" -as [type])) {
- Add-Type -TypeDefinition @'
+ Initialize-StudioTempEnvironment
+ $source = @'
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
@@ -539,10 +790,244 @@ public static class UnslothStudioFinalPathV2
}
}
'@
+ $firstError = $null
+ try {
+ Add-Type -TypeDefinition $source -ErrorAction Stop
+ } catch {
+ $firstError = $_.Exception.Message
+ }
+ # A compile that reports failure can still have loaded the type, and the same
+ # name cannot be defined twice in one session.
+ if ("UnslothStudioFinalPathV2" -as [type]) {
+ $script:StudioFinalPathNativeState = $true
+ return $true
+ }
+ $private = New-StudioPrivateTempDirectory
+ if ($private) {
+ $hadTmp = ($null -ne $env:TMP)
+ $previousTmp = $env:TMP
+ $hadTemp = ($null -ne $env:TEMP)
+ $previousTemp = $env:TEMP
+ try {
+ # Both, because GetTempPath reads TMP first.
+ $env:TMP = $private
+ $env:TEMP = $private
+ try { Add-Type -TypeDefinition $source -ErrorAction Stop } catch {}
+ } finally {
+ if ($hadTmp) { $env:TMP = $previousTmp } else { Remove-Item Env:\TMP -ErrorAction SilentlyContinue }
+ if ($hadTemp) { $env:TEMP = $previousTemp } else { Remove-Item Env:\TEMP -ErrorAction SilentlyContinue }
+ # Only now: deleting while csc.exe still holds it is the race being
+ # worked around.
+ Remove-Item -LiteralPath $private -Recurse -Force -ErrorAction SilentlyContinue
+ }
+ }
+ if ("UnslothStudioFinalPathV2" -as [type]) {
+ $script:StudioFinalPathNativeState = $true
+ return $true
+ }
+ $script:StudioFinalPathNativeState = $false
+ # First line of the compiler output, not the whole C# dump it echoes after.
+ $reason = if ($firstError) { ($firstError -split "`r?`n")[0].Trim() } else { "compilation failed" }
+ Write-StudioFinalPathDegraded -Reason $reason
+ return $false
+ }
+
+ function Resolve-StudioLinkTarget {
+ param([Parameter(Mandatory = $true)][string]$Path)
+ $item = $null
+ try { $item = Get-Item -LiteralPath $Path -Force -ErrorAction Stop } catch { return $null }
+ $target = $null
+ # PowerShell 7 walks the whole chain; 5.1 exposes only the raw reparse target,
+ # relative for a relative symlink and still carrying a junction's NT prefix.
+ if ($item.PSObject.Methods.Name -contains 'ResolveLinkTarget') {
+ try {
+ $final = $item.ResolveLinkTarget($true)
+ if ($final) { $target = [string]$final.FullName }
+ } catch { $target = $null }
+ }
+ if ([string]::IsNullOrWhiteSpace($target)) {
+ $raw = $null
+ try { $raw = $item.Target } catch { $raw = $null }
+ # 5.1 hands this back as a COLLECTION, not a string, and not always an
+ # [array], so unwrap anything that is not already a string.
+ if ($null -ne $raw -and $raw -isnot [string]) {
+ $raw = @($raw) | Select-Object -First 1
+ }
+ if (-not [string]::IsNullOrWhiteSpace($raw)) { $target = [string]$raw }
+ }
+ if ([string]::IsNullOrWhiteSpace($target)) { return $null }
+ if ($target.StartsWith('\??\')) {
+ $target = $target.Substring(4)
+ # \??\UNC\server\share is the device spelling of \\server\share. Left as
+ # "UNC\server\share" it reads as RELATIVE and gets combined with the
+ # link's local parent, inventing a path; a wrong identity is a wrong mutex.
+ if ($target.StartsWith('UNC\', [System.StringComparison]::OrdinalIgnoreCase)) {
+ $target = '\\' + $target.Substring(4)
+ } elseif ($target.StartsWith('Volume{', [System.StringComparison]::OrdinalIgnoreCase)) {
+ # A mounted folder reports \??\Volume{GUID}\..., the same trap:
+ # "Volume{...}\..." is not rooted either. \\?\ is the extended-length
+ # spelling of that device path, so it keeps naming the volume.
+ $target = '\\?\' + $target
+ }
+ }
+ # "\real" is rooted as far as IsPathRooted is concerned but names no drive,
+ # so GetFullPath would resolve it against the PROCESS current drive. Windows
+ # resolves a drive-less target on the LINK's own volume, so anchor it there.
+ if ($target.Length -ge 1 -and ($target[0] -eq '\' -or $target[0] -eq '/') -and
+ -not ($target.Length -ge 2 -and ($target[1] -eq '\' -or $target[1] -eq '/'))) {
+ $linkRoot = $null
+ try { $linkRoot = [System.IO.Path]::GetPathRoot([System.IO.Path]::GetFullPath($Path)) } catch { $linkRoot = $null }
+ # Empty for a volume-GUID spelling; leaving the target alone beats guessing.
+ if (-not [string]::IsNullOrEmpty($linkRoot)) {
+ try { $target = [System.IO.Path]::Combine($linkRoot, $target.TrimStart('\', '/')) } catch {}
+ }
+ }
+ try {
+ if (-not [System.IO.Path]::IsPathRooted($target)) {
+ $parent = [System.IO.Path]::GetDirectoryName($Path)
+ if ([string]::IsNullOrEmpty($parent)) { return $null }
+ $target = [System.IO.Path]::Combine($parent, $target)
+ }
+ $target = [System.IO.Path]::GetFullPath($target)
+ } catch { return $null }
+ # Compare like against like: $target went through GetFullPath, so $Path must
+ # too, or a relative spelling misses the self-reference guard and loops.
+ $self = $Path
+ try { $self = [System.IO.Path]::GetFullPath($Path) } catch { $self = $Path }
+ if ([string]::Equals(
+ $target.TrimEnd('\', '/'), $self.TrimEnd('\', '/'), [System.StringComparison]::OrdinalIgnoreCase
+ )) {
+ return $null
+ }
+ return $target
+ }
+
+ # Compiler-free stand-in for the native resolver. Normalized, not exact: it
+ # cannot expand an 8.3 alias or recover stored casing, so callers are told the
+ # answer is inexact. Never throws; an identity nobody can establish must not
+ # stop an install.
+ $script:StudioSubstMap = $null
+ function Get-StudioSubstTarget {
+ param([Parameter(Mandatory = $true)][string]$Path)
+ # A SUBST drive is a DOS device mapping and no 5.1 API reports it: measured
+ # on windows-latest, Get-PSDrive.DisplayRoot and Win32_LogicalDisk.ProviderName
+ # are empty, GetFullPath and Resolve-Path hand X:\ straight back, and
+ # (Get-Item X:\).Target reports the target's tail under the SUBST letter.
+ # `subst` with no arguments prints the mapping in full ("X:\: => D:\real\dir"),
+ # so that is what this reads, once.
+ if ($null -eq $script:StudioSubstMap) {
+ $script:StudioSubstMap = @{}
+ try {
+ foreach ($line in @(& "$env:SystemRoot\System32\subst.exe" 2>$null)) {
+ $m = [regex]::Match([string]$line, '^([A-Za-z]):\\?:\s*=>\s*(\S.*)$')
+ if ($m.Success) {
+ $script:StudioSubstMap[$m.Groups[1].Value.ToUpperInvariant()] =
+ $m.Groups[2].Value.TrimEnd()
+ }
+ }
+ } catch {}
+ }
+ if ($script:StudioSubstMap.Count -eq 0) { return $null }
+ if ($Path.Length -lt 2 -or $Path[1] -ne ':') { return $null }
+ $letter = ([string]$Path[0]).ToUpperInvariant()
+ if (-not $script:StudioSubstMap.ContainsKey($letter)) { return $null }
+ $tail = $Path.Substring(2).TrimStart('\', '/')
+ $target = $script:StudioSubstMap[$letter]
+ if ([string]::IsNullOrWhiteSpace($tail)) { return $target }
+ try { return [System.IO.Path]::Combine($target, $tail) } catch { return $null }
+ }
+
+ function Get-StudioLexicalPath {
+ param([Parameter(Mandatory = $true)][string]$Path)
+ $current = $null
+ try { $current = [System.IO.Path]::GetFullPath($Path) } catch { return $Path }
+ # Fold a SUBST drive BEFORE walking components: the Python runtime gate
+ # resolves it, so leaving it would give the two sides different mutex names
+ # for one directory and hide a running Studio from the in-use scan.
+ $substituted = Get-StudioSubstTarget -Path $current
+ if ($substituted) {
+ try { $current = [System.IO.Path]::GetFullPath($substituted) } catch {}
+ }
+ # Hashtable, not a generic HashSet: already case-insensitive, and a
+ # locked-down host (the kind that got here) can forbid generic types.
+ $visited = @{}
+ # A link on a PARENT component is the ordinary Windows shape (redirected
+ # profiles), so walk from the root and restart at each one. Capped with a
+ # visited set, because reparse points can point at each other.
+ for ($hop = 0; $hop -lt 32; $hop++) {
+ if ($visited.ContainsKey($current)) { break }
+ $visited[$current] = $true
+ $root = ""
+ try { $root = [System.IO.Path]::GetPathRoot($current) } catch { break }
+ if ([string]::IsNullOrEmpty($root) -or $current.Length -lt $root.Length) { break }
+ $walked = $root
+ $rewritten = $null
+ $tail = $current.Substring($root.Length)
+ # [char[]] on purpose: an untyped array binds Split's single-string
+ # overload instead, which splits on nothing.
+ foreach ($segment in $tail.Split([char[]]@('\', '/'), [System.StringSplitOptions]::RemoveEmptyEntries)) {
+ $walked = [System.IO.Path]::Combine($walked, $segment)
+ $target = Resolve-StudioLinkTarget -Path $walked
+ if ($target) {
+ $remainder = $current.Substring($walked.Length).TrimStart('\', '/')
+ $rewritten = if ($remainder) { [System.IO.Path]::Combine($target, $remainder) } else { $target }
+ break
+ }
+ }
+ if (-not $rewritten) { break }
+ try { $current = [System.IO.Path]::GetFullPath($rewritten) } catch { $current = $rewritten; break }
+ }
+ try {
+ $provider = (Resolve-Path -LiteralPath $current -ErrorAction Stop).ProviderPath
+ if (-not [string]::IsNullOrWhiteSpace($provider)) { $current = $provider }
+ } catch {}
+ return $current
+ }
+
+ # Exact = $true means the native resolver answered, so the string is what it
+ # always was. Callers keying a lock on it use that to judge an inequality.
+ function Resolve-StudioFinalPathInfo {
+ param([Parameter(Mandatory = $true)][string]$Path)
+ $fullPath = [System.IO.Path]::GetFullPath($Path)
+ $fullRoot = [System.IO.Path]::GetPathRoot($fullPath)
+ if (-not $fullRoot -or $fullPath.Length -gt $fullRoot.Length) {
+ $fullPath = $fullPath.TrimEnd('\', '/')
+ }
+ $existingPath = $fullPath
+ $missingSegments = @()
+ while (-not (Test-Path -LiteralPath $existingPath)) {
+ $leaf = [System.IO.Path]::GetFileName($existingPath)
+ $parent = [System.IO.Path]::GetDirectoryName($existingPath)
+ if ([string]::IsNullOrEmpty($leaf) -or [string]::IsNullOrEmpty($parent)) {
+ return [pscustomobject]@{ Path = $fullPath; Exact = $false }
+ }
+ $missingSegments = @($leaf) + $missingSegments
+ $existingPath = $parent
+ }
+ $exact = $false
+ $resolved = $null
+ if (Initialize-StudioFinalPathNativeType) {
+ try {
+ $resolved = [UnslothStudioFinalPathV2]::Resolve($existingPath)
+ $exact = $true
+ } catch {
+ $resolved = $null
+ }
+ }
+ if ([string]::IsNullOrEmpty($resolved)) {
+ $resolved = Get-StudioLexicalPath -Path $existingPath
+ $exact = $false
}
- $resolved = [UnslothStudioFinalPathV2]::Resolve($existingPath)
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)) {
$resolved = $resolved.Substring(4)
}
@@ -551,9 +1036,14 @@ public static class UnslothStudioFinalPathV2
}
$resolvedRoot = [System.IO.Path]::GetPathRoot($resolved)
if ($resolvedRoot -and $resolved.Length -le $resolvedRoot.Length) {
- return $resolvedRoot
+ return [pscustomobject]@{ Path = $resolvedRoot; Exact = $exact }
}
- return $resolved.TrimEnd('\', '/')
+ return [pscustomobject]@{ Path = $resolved.TrimEnd('\', '/'); Exact = $exact }
+ }
+
+ function Get-StudioFinalPath {
+ param([Parameter(Mandatory = $true)][string]$Path)
+ return (Resolve-StudioFinalPathInfo -Path $Path).Path
}
# Custom Unsloth roots are not supported with --tauri (the desktop app uses
@@ -582,6 +1072,10 @@ public static class UnslothStudioFinalPathV2
Write-StudioLine " The desktop app uses the Windows profile .unsloth\studio root." -ForegroundColor Red
Write-StudioLine " Run install.ps1 without --tauri for custom-root shell installs," -ForegroundColor Yellow
Write-StudioLine " or unset the env var for default desktop installs." -ForegroundColor Yellow
+ # Resolving the roots above can redirect TMP/TEMP, and this throw is well
+ # before the lock try/finally. Under `irm | iex` those variables are the
+ # caller's own and would stay pointed at an installer-owned directory.
+ Restore-StudioTempEnvironment
throw "$envOverrideVar is not supported with --tauri."
}
}
@@ -605,6 +1099,8 @@ public static class UnslothStudioFinalPathV2
$StudioHome = (Resolve-Path -LiteralPath $envOverride).Path
} catch {
Write-StudioLine "ERROR: $envOverrideVar=$envOverride cannot be created or accessed." -ForegroundColor Red
+ # Same as the --tauri rejection above: still before the lock finally.
+ Restore-StudioTempEnvironment
throw "$envOverrideVar=$envOverride cannot be created or accessed."
}
$probe = Join-Path $StudioHome (".unsloth-write-probe-" + [guid]::NewGuid())
@@ -614,6 +1110,7 @@ public static class UnslothStudioFinalPathV2
Remove-Item -LiteralPath $probe -Force -ErrorAction SilentlyContinue
} catch {
Write-StudioLine "ERROR: $envOverrideVar=$StudioHome is not writable." -ForegroundColor Red
+ Restore-StudioTempEnvironment
throw "$envOverrideVar=$StudioHome is not writable."
}
$StudioDataDir = Join-Path $StudioHome "share"
@@ -685,6 +1182,10 @@ public static class UnslothStudioFinalPathV2
}
Write-StudioLine ""
+ # Here so its warning lands under the banner. A no-op the second time: a --tauri
+ # run with a custom root reaches it first via Initialize-StudioFinalPathNativeType.
+ Initialize-StudioTempEnvironment
+
# ── Helper: refresh PATH from registry (deduplicating entries) ──
# Merge order: venv Scripts (if active) > Machine > User > current $env:Path.
# Dedup compares both raw and expanded forms (%VAR% vs literal).
@@ -2048,6 +2549,11 @@ exit 0
# Regen .lnk + launcher only; used by `unsloth studio update`.
if ($ShortcutsOnly) {
+ # `unsloth studio update` reaches the installer only here, and returns before
+ # the lock try/finally, so undo the temp redirection on every way out,
+ # including the throw below. Under `irm | iex` these variables belong to the
+ # caller's own session, so leaving them redirected outlives the install.
+ try {
if ($TauriMode) { return }
# The launcher runs the interpreter, so that is what has to be there. Checking
# unsloth.exe instead would refuse to regenerate shortcuts on exactly the
@@ -2089,6 +2595,9 @@ exit 0
}
New-StudioShortcuts -ManagedPythonPath $ShortcutPython
return
+ } finally {
+ Restore-StudioTempEnvironment
+ }
}
# ── Leave Windows system directories before installing ──
@@ -2225,6 +2734,11 @@ exit 0
function Get-StudioPathHash {
param([Parameter(Mandatory = $true)][string]$Path)
+ # Unchanged whenever the native resolver answered. When it could not, this
+ # hashes the normalized spelling, so two ALIASES of one root (a junction and
+ # its target, an 8.3 name and its long form) name different mutexes and do not
+ # exclude each other. That needs two installs racing into one directory through
+ # different spellings, and beats refusing to install, which is what this did.
$canonical = (Get-StudioFinalPath -Path $Path).ToUpperInvariant()
$bytes = [System.Text.Encoding]::UTF8.GetBytes($canonical)
$sha256 = [System.Security.Cryptography.SHA256]::Create()
@@ -2243,15 +2757,25 @@ exit 0
[Parameter(Mandatory = $true)][string]$Right
)
try {
- $leftFull = Get-StudioFinalPath -Path $Left
- $rightFull = Get-StudioFinalPath -Path $Right
+ $leftInfo = Resolve-StudioFinalPathInfo -Path $Left
+ $rightInfo = Resolve-StudioFinalPathInfo -Path $Right
} catch {
Write-StudioLine "[WARN] Could not resolve Studio path identity; using the runtime lock." -ForegroundColor Yellow
return $null
}
- return [string]::Equals(
- $leftFull, $rightFull, [System.StringComparison]::OrdinalIgnoreCase
- )
+ if ([string]::Equals(
+ $leftInfo.Path, $rightInfo.Path, [System.StringComparison]::OrdinalIgnoreCase
+ )) {
+ return $true
+ }
+ # Different spellings only prove different directories when both resolved
+ # exactly; otherwise they may be aliases of one. $null is the caller's
+ # "identity unresolved" signal and makes it take both runtime locks.
+ if (-not $leftInfo.Exact -or -not $rightInfo.Exact) {
+ Write-StudioLine "[WARN] Could not resolve Studio path identity; using the runtime lock." -ForegroundColor Yellow
+ return $null
+ }
+ return $false
}
function Get-StudioInstallMutexName {
@@ -2378,6 +2902,52 @@ exit 0
}
}
+ # QueryFullProcessImageNameW answers for processes whose MainModule is not
+ # readable here, but needs the compiled helper. Without a fallback a host that
+ # cannot compile would find NO running processes and overwrite a venv Studio has
+ # open, so the ladder ends at Win32_Process. Every rung reports a real executable
+ # image; a command line or working directory mentioning the path is never proof.
+ $script:StudioProcessImageTable = $null
+ $script:StudioProcessImageWarned = $false
+ function Get-StudioProcessImagePath {
+ param([Parameter(Mandatory = $true)][int]$ProcessId)
+ if (Initialize-StudioFinalPathNativeType) {
+ try {
+ $native = [UnslothStudioFinalPathV2]::GetProcessImagePath($ProcessId)
+ if (-not [string]::IsNullOrWhiteSpace($native)) { return $native }
+ } catch {}
+ return $null
+ }
+ if (-not $script:StudioProcessImageWarned) {
+ $script:StudioProcessImageWarned = $true
+ Write-StudioLine "[WARN] Scanning for running Studio processes without the native helper; a process this shell cannot inspect may go unnoticed." -ForegroundColor Yellow
+ }
+ $process = $null
+ try { $process = Get-Process -Id $ProcessId -ErrorAction Stop } catch { $process = $null }
+ if ($process) {
+ # .Path is MainModule.FileName (an ETS ScriptProperty over it on 5.1), so
+ # there is no second rung here: empty means MainModule was unreadable.
+ try {
+ if (-not [string]::IsNullOrWhiteSpace($process.Path)) { return $process.Path }
+ } catch {}
+ }
+ # Queried once per run, not once per process: this is the slow rung.
+ if ($null -eq $script:StudioProcessImageTable) {
+ $script:StudioProcessImageTable = @{}
+ try {
+ foreach ($row in @(Get-CimInstance -ClassName Win32_Process -ErrorAction Stop)) {
+ if (-not [string]::IsNullOrWhiteSpace($row.ExecutablePath)) {
+ $script:StudioProcessImageTable[[int]$row.ProcessId] = [string]$row.ExecutablePath
+ }
+ }
+ } catch {}
+ }
+ if ($script:StudioProcessImageTable.ContainsKey($ProcessId)) {
+ return $script:StudioProcessImageTable[$ProcessId]
+ }
+ return $null
+ }
+
function Get-RunningStudioVenvProcesses {
param(
[Parameter(Mandatory = $true)][string]$VenvPath,
@@ -2388,12 +2958,18 @@ exit 0
} catch {
throw "Could not resolve managed Studio process path '$VenvPath': $($_.Exception.Message)"
}
+ # No root-relative fallback here: without the native helper EVERY path is
+ # inexact, so it compared path tails across unrelated drives and an ordinary
+ # D:\env\python.exe matched a protected C:\env, aborting a legitimate install
+ # as "still in use". The alias it was written for, SUBST, is folded in
+ # Get-StudioLexicalPath instead. A volume reached by GUID still cannot be
+ # matched to the same volume by drive letter without the compiler.
# Block only confirmed executable identities: a command line or working
# directory that merely mentions the path is not proof of an open file.
foreach ($process in @(Get-Process -ErrorAction SilentlyContinue)) {
$executable = $null
- try { $executable = [UnslothStudioFinalPathV2]::GetProcessImagePath($process.Id) } catch { continue }
+ try { $executable = Get-StudioProcessImagePath -ProcessId $process.Id } catch { continue }
if (-not $executable) { continue }
try { $executable = Get-StudioFinalPath -Path $executable } catch { continue }
if (Test-StudioProtectedPathMatch -Candidate $executable -ProtectedPath $resolvedPath -Exact:$Exact) {
@@ -5692,6 +6268,11 @@ exit 0
$studioAutoStartProcess = Start-Process -FilePath $VenvPython `
-ArgumentList (Get-ManagedUnslothCliCommandLine -Arguments @("studio", "-p", "8888")) `
-NoNewWindow -PassThru
+ # This inherits the private %TEMP% and outlives the installer, so it,
+ # not $PID, is the owner the next sweep must see.
+ if ($null -ne $studioAutoStartProcess) {
+ Set-StudioPrivateTempOwner -OwnerProcessId $studioAutoStartProcess.Id
+ }
} finally {
if ($null -eq $_runtimeGateHandoff) {
Remove-Item Env:_UNSLOTH_STUDIO_RUNTIME_GATE_HANDOFF -ErrorAction SilentlyContinue
@@ -5753,6 +6334,8 @@ exit 0
Exit-StudioInstallMutex -Mutex $studioRuntimeMutexes[$i]
}
Exit-StudioInstallMutex -Mutex $studioInstallMutex
+ # Matters for `irm | iex`, where these are the user's own session variables.
+ Restore-StudioTempEnvironment
}
if ($null -ne $studioAutoStartProcess) {
$studioAutoStartProcess.WaitForExit()
diff --git a/scripts/uninstall.ps1 b/scripts/uninstall.ps1
index 13f969300fe..8c9f5e12deb 100644
--- a/scripts/uninstall.ps1
+++ b/scripts/uninstall.ps1
@@ -507,7 +507,20 @@ Environment:
# Default install root + default data dir.
$defaultStudioHome = if ($env:USERPROFILE) { Join-Path $env:USERPROFILE ".unsloth\studio" } else { $null }
- $defaultDataDir = if ($env:LOCALAPPDATA) { Join-Path $env:LOCALAPPDATA "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.
+ $knownLocalAppData = $null
+ try { $knownLocalAppData = [Environment]::GetFolderPath('LocalApplicationData') } catch { $knownLocalAppData = $null }
+ $defaultDataDirs = @()
+ foreach ($root in @($env:LOCALAPPDATA, $knownLocalAppData)) {
+ if ([string]::IsNullOrWhiteSpace($root)) { continue }
+ $candidate = Join-Path $root "Unsloth Studio"
+ if ($defaultDataDirs -notcontains $candidate) { $defaultDataDirs += $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
# explicitly. No-op in env/custom mode (nested under the custom root, removed
@@ -540,8 +553,8 @@ Environment:
# ── Stop running servers ──
_Step "Stopping any running Unsloth Studio servers..."
- if ($defaultDataDir) {
- _StopByPortFile -PortFile (Join-Path $defaultDataDir "studio.port") -KnownRoots $knownRoots
+ foreach ($d in $defaultDataDirs) {
+ _StopByPortFile -PortFile (Join-Path $d "studio.port") -KnownRoots $knownRoots
}
foreach ($r in $customRoots) {
_StopByPortFile -PortFile (Join-Path $r "share\studio.port") -KnownRoots $knownRoots
@@ -627,7 +640,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) + @($defaultDataDir, $defaultLlamaCpp, $defaultCache, $defaultNode, $defaultWhisperCpp) + @($defaultSdCppToStop | Where-Object { $_ }) + @($customSdCppToStop)
+ $stopRoots = @($knownRoots) + @($defaultDataDirs) + @($defaultLlamaCpp, $defaultCache, $defaultNode, $defaultWhisperCpp) + @($defaultSdCppToStop | Where-Object { $_ }) + @($customSdCppToStop)
_StopProcessesLockingRoots -Roots ($stopRoots + @(_ManagedPathsUnderReparseTargets $knownRoots))
# ── Remove custom-root install trees ──
@@ -665,7 +678,7 @@ Environment:
# Default install dir (always at %USERPROFILE%\.unsloth\studio when present).
if ($defaultStudioHome) { _RemoveRootRecordingDb $defaultStudioHome }
# Default data dir.
- if ($defaultDataDir) { _RemoveDataDirKeepingWslIcon $defaultDataDir }
+ foreach ($d in $defaultDataDirs) { _RemoveDataDirKeepingWslIcon $d }
# 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 }
@@ -756,7 +769,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.)
- if ($defaultDataDir -and (Test-Path -LiteralPath $defaultDataDir)) { _RemoveDataDirKeepingWslIcon $defaultDataDir }
+ foreach ($d in $defaultDataDirs) {
+ if (Test-Path -LiteralPath $d) { _RemoveDataDirKeepingWslIcon $d }
+ }
# ── Clean user PATH and registry backup ──
_Step "Cleaning user PATH and registry..."
diff --git a/tests/python/test_windows_installer_addtype_fallback.py b/tests/python/test_windows_installer_addtype_fallback.py
new file mode 100644
index 00000000000..b5d8acce652
--- /dev/null
+++ b/tests/python/test_windows_installer_addtype_fallback.py
@@ -0,0 +1,987 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+"""The installer must survive a host where Add-Type cannot compile.
+
+install.ps1 resolves path identity through a C# helper it compiles at runtime.
+Windows PowerShell 5.1 -- the interpreter studio/src-tauri/src/install.rs spawns
+-- compiles by writing the source into %TEMP% and running csc.exe, so a %TEMP%
+that cannot hold a file (or a scanner that eats what was just written there)
+makes Add-Type throw CS2001. That exception used to travel up Get-StudioPathHash
+and end a first launch as "Could not create the Studio install lock" (#9140),
+with nothing about the message pointing at the compiler.
+
+These run under pwsh on any platform: the failure being guarded is that a thrown
+Add-Type aborts the install, and that is shell-independent. Windows PowerShell
+5.1's CodeDom behaviour itself is exercised by the Windows-only tests in
+test_windows_installer_concurrency_guard.py.
+"""
+
+from __future__ import annotations
+
+import os
+import re
+import shutil
+import subprocess
+import tempfile
+import time
+from pathlib import Path
+
+import pytest
+
+
+REPO_ROOT = Path(__file__).resolve().parents[2]
+INSTALL_PS1 = REPO_ROOT / "install.ps1"
+
+requires_pwsh = pytest.mark.skipif(shutil.which("pwsh") is None, reason = "PowerShell is unavailable")
+
+# Stands in for every Add-Type in install.ps1 that compiles C# rather than loading
+# an assembly.
+SABOTAGE = (
+ """function Add-Type { throw "(0) : error CS2001: Source file 'a.0.cs' could not be found" }"""
+)
+
+
+def _extract(pattern: str, source: str) -> str:
+ match = re.search(pattern, source, flags = re.DOTALL)
+ assert match is not None, f"install.ps1 block not found: {pattern}"
+ return match.group(0)
+
+
+def _helpers(*names: str) -> str:
+ source = INSTALL_PS1.read_text(encoding = "utf-8")
+ return "\n".join(_extract(rf" function {name} \{{.*?\n \}}\n", source) for name in names)
+
+
+# The whole chain the reported failure walked, plus the fallback it now lands on.
+LOCK_CHAIN = (
+ "Write-StudioLine",
+ "Test-StudioDirectoryUsable",
+ "Remove-StudioStalePrivateTempDirectories",
+ "Get-StudioPrivateTempRoots",
+ "New-StudioPrivateTempDirectory",
+ "Initialize-StudioTempEnvironment",
+ "Restore-StudioTempEnvironment",
+ "Write-StudioFinalPathDegraded",
+ "Initialize-StudioFinalPathNativeType",
+ "Resolve-StudioLinkTarget",
+ "Get-StudioSubstTarget",
+ "Get-StudioLexicalPath",
+ "Resolve-StudioFinalPathInfo",
+ "Get-StudioFinalPath",
+ "Get-StudioPathHash",
+ "Get-StudioInstallMutexName",
+ "Test-StudioPathEqual",
+ "Enter-StudioNamedMutex",
+ "Enter-StudioInstallMutex",
+ "Exit-StudioInstallMutex",
+)
+
+
+def _run_powershell(script: str, env: dict[str, str] | None = None) -> subprocess.CompletedProcess:
+ # Through a FILE, not -Command: these scripts carry the whole extracted helper
+ # chain, and Windows caps a command line at 32767 characters. Passed inline,
+ # the moment the chain grows past that every test here dies as WinError 206
+ # rather than testing anything. utf-8-sig because Windows PowerShell 5.1 reads
+ # a BOM-less .ps1 as ANSI; utf-8 with replacement on the way back because the
+ # default console codepage there cannot decode what PowerShell writes.
+ handle, name = tempfile.mkstemp(suffix = ".ps1")
+ os.close(handle)
+ try:
+ Path(name).write_text(script, encoding = "utf-8-sig")
+ return subprocess.run(
+ ["pwsh", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-File", name],
+ capture_output = True,
+ text = True,
+ encoding = "utf-8",
+ errors = "replace",
+ timeout = 120,
+ env = env if env is not None else os.environ.copy(),
+ )
+ finally:
+ try:
+ os.unlink(name)
+ except OSError:
+ pass
+
+
+def _script(
+ body: str,
+ *,
+ sabotage: bool = True,
+ names: tuple[str, ...] = LOCK_CHAIN,
+) -> str:
+ return "\n".join(
+ [
+ '$ErrorActionPreference = "Stop"',
+ # Write-StudioLine picks its sink from this; unset, it reaches Write-Host,
+ # which the caller cannot capture.
+ "$script:StudioStdoutRedirected = $true",
+ _helpers(*names),
+ SABOTAGE if sabotage else "",
+ body,
+ ]
+ )
+
+
+def _lines(result: subprocess.CompletedProcess, prefix: str) -> list[str]:
+ return [line for line in result.stdout.splitlines() if line.startswith(prefix)]
+
+
+@requires_pwsh
+def test_install_lock_is_acquired_when_the_compiler_fails(tmp_path: Path):
+ """The bug, exactly: a throwing Add-Type must not cost the install its lock."""
+ studio_home = tmp_path / "studio"
+ studio_home.mkdir()
+ result = _run_powershell(
+ _script(
+ f"""
+$name = Get-StudioInstallMutexName -Path '{studio_home}'
+Write-Output "NAME:$name"
+$mutex = Enter-StudioInstallMutex -Path '{studio_home}'
+Write-Output "LOCK:$($null -ne $mutex)"
+Exit-StudioInstallMutex -Mutex $mutex
+"""
+ )
+ )
+ assert result.returncode == 0, result.stderr
+ assert _lines(result, "LOCK:") == ["LOCK:True"]
+ assert re.fullmatch(
+ r"NAME:Global\\UnslothStudioInstall-[0-9a-f]{64}", _lines(result, "NAME:")[0]
+ )
+ # And it says why it degraded, once, without dumping the C# it tried to build.
+ warnings = [line for line in result.stdout.splitlines() if "native path resolver" in line]
+ assert len(warnings) == 1
+ assert "using System" not in result.stdout
+
+
+@requires_pwsh
+def test_the_compiler_is_not_retried_for_every_path(tmp_path: Path):
+ result = _run_powershell(
+ _script(
+ f"""
+$global:AddTypeCalls = 0
+function Add-Type {{
+ $global:AddTypeCalls++
+ throw "(0) : error CS2001: Source file 'a.0.cs' could not be found"
+}}
+foreach ($i in 1..5) {{ Get-StudioFinalPath -Path '{tmp_path}' | Out-Null }}
+Write-Output "CALLS:$global:AddTypeCalls"
+""",
+ sabotage = False,
+ )
+ )
+ assert result.returncode == 0, result.stderr
+ # One attempt, one retry with a private %TEMP%, then cached: the scan below
+ # resolves a path per running process.
+ assert _lines(result, "CALLS:") == ["CALLS:2"]
+
+
+@requires_pwsh
+def test_the_private_temp_retry_recovers_the_native_helper(tmp_path: Path):
+ """Surviving a dead compiler is the floor. The retry has to actually work.
+
+ Add-Type is replaced by a stub that behaves the way 5.1's CodeDom does: it
+ writes the source into %TEMP% and fails when that cannot hold a file, and it
+ calls the real cmdlet once it can, so the type genuinely gets defined.
+ """
+ blocker = tmp_path / "blocker"
+ blocker.write_text("not a directory", encoding = "utf-8")
+ dead = str(blocker / "temp")
+ local_app_data = tmp_path / "localappdata"
+ local_app_data.mkdir()
+ studio_home = tmp_path / "studio"
+ studio_home.mkdir()
+
+ env = os.environ.copy()
+ env.update({"TMP": dead, "TEMP": dead, "LOCALAPPDATA": str(local_app_data)})
+ env.pop("USERPROFILE", None)
+
+ result = _run_powershell(
+ _script(
+ f"""
+$script:RealAddType = Get-Command Add-Type -CommandType Cmdlet
+$global:Attempts = 0
+function Add-Type {{
+ param([string]$TypeDefinition, [string]$ErrorAction)
+ $global:Attempts++
+ $probe = Join-Path $env:TMP ("codedom-" + [guid]::NewGuid().ToString('N').Substring(0, 8) + ".0.cs")
+ try {{
+ [System.IO.File]::WriteAllText($probe, $TypeDefinition)
+ Remove-Item -LiteralPath $probe -Force -ErrorAction SilentlyContinue
+ }} catch {{
+ throw "(0) : error CS2001: Source file '$probe' could not be found"
+ }}
+ & $script:RealAddType -TypeDefinition $TypeDefinition -ErrorAction Stop
+}}
+# Skip the session-wide temp fix, so the RETRY is the only thing that can save it.
+$script:StudioTempChecked = $true
+$info = Resolve-StudioFinalPathInfo -Path '{studio_home}'
+Write-Output "ATTEMPTS:$global:Attempts"
+Write-Output "LOADED:$([bool]("UnslothStudioFinalPathV2" -as [type]))"
+Write-Output "PATH:$($info.Path)"
+Write-Output "TMP:$env:TMP"
+Write-Output "TEMP:$env:TEMP"
+""",
+ sabotage = False,
+ ),
+ env = env,
+ )
+ assert result.returncode == 0, result.stderr
+ # One failed attempt, then one retry with a private %TEMP%, which succeeds.
+ assert _lines(result, "ATTEMPTS:") == ["ATTEMPTS:2"]
+ assert _lines(result, "LOADED:") == ["LOADED:True"]
+ assert not [line for line in result.stdout.splitlines() if "native path resolver" in line]
+ # Restored exactly, broken values and all: they are the caller's, not ours.
+ assert _lines(result, "TMP:") == [f"TMP:{dead}"]
+ assert _lines(result, "TEMP:") == [f"TEMP:{dead}"]
+ assert list((local_app_data / "Unsloth Studio" / "temp").glob("ust-*")) == []
+ # The P/Invoke targets kernel32, so off Windows the type loads but the CALL
+ # fails; it has to degrade to a usable answer rather than throw.
+ assert _lines(result, "PATH:")[0].startswith("PATH:")
+ assert _lines(result, "PATH:") != ["PATH:"]
+
+
+@requires_pwsh
+def test_resolver_follows_a_linked_ancestor(tmp_path: Path):
+ physical = tmp_path / "physical" / "studio"
+ physical.mkdir(parents = True)
+ alias = tmp_path / "alias"
+ try:
+ alias.symlink_to(tmp_path / "physical", target_is_directory = True)
+ except (OSError, NotImplementedError):
+ pytest.skip("creating a symlink requires privilege on this host")
+
+ result = _run_powershell(
+ _script(
+ f"""
+Write-Output "PATH:$(Get-StudioFinalPath -Path '{alias / "studio"}')"
+Write-Output "EQUAL:$(Test-StudioPathEqual -Left '{alias / "studio"}' -Right '{physical}')"
+Write-Output "MISSING:$(Get-StudioFinalPath -Path '{alias / "studio" / "not" / "there"}')"
+"""
+ )
+ )
+ assert result.returncode == 0, result.stderr
+ # A link on a PARENT component is the ordinary Windows shape, and the one
+ # GetFullPath alone gets wrong.
+ assert _lines(result, "PATH:") == [f"PATH:{physical}"]
+ assert _lines(result, "EQUAL:") == ["EQUAL:True"]
+ # Segments that do not exist yet are reattached, as the native resolver does.
+ assert _lines(result, "MISSING:") == [f"MISSING:{physical / 'not' / 'there'}"]
+
+
+@requires_pwsh
+def test_resolver_terminates_on_a_link_loop(tmp_path: Path):
+ left = tmp_path / "left"
+ right = tmp_path / "right"
+ try:
+ left.symlink_to(right, target_is_directory = True)
+ right.symlink_to(left, target_is_directory = True)
+ except (OSError, NotImplementedError):
+ pytest.skip("creating a symlink requires privilege on this host")
+
+ result = _run_powershell(
+ _script(
+ f"""
+Write-Output "PATH:$(Get-StudioFinalPath -Path '{left}')"
+"""
+ )
+ )
+ assert result.returncode == 0, result.stderr
+ assert len(_lines(result, "PATH:")) == 1
+
+
+@requires_pwsh
+def test_unequal_paths_are_unknown_rather_than_different_when_inexact(tmp_path: Path):
+ left = tmp_path / "left"
+ right = tmp_path / "right"
+ left.mkdir()
+ right.mkdir()
+ result = _run_powershell(
+ _script(
+ f"""
+$answer = Test-StudioPathEqual -Left '{left}' -Right '{right}'
+Write-Output "NULL:$($null -eq $answer)"
+"""
+ )
+ )
+ assert result.returncode == 0, result.stderr
+ # Without exact resolution two spellings may still be one directory; $null makes
+ # the caller take BOTH runtime locks, where $false would silently drop one.
+ assert _lines(result, "NULL:") == ["NULL:True"]
+
+
+@requires_pwsh
+def test_a_directory_that_will_not_give_a_file_back_is_not_usable(tmp_path: Path):
+ """Create and read are not enough. csc.exe also has to clean up after itself.
+
+ A directory that accepts a file and then refuses to delete it (a denied
+ Delete ACE, a scanner sitting on the handle) is the shape that produced the
+ reported failure, and it passes a create-and-read probe unchanged.
+ """
+ good = tmp_path / "good"
+ good.mkdir()
+ result = _run_powershell(
+ _script(
+ f"""
+Write-Output "BEFORE:$(Test-StudioDirectoryUsable -Path '{good}')"
+# Every delete is a no-op from here, which is what a denied Delete ACE looks
+# like to the caller: no exception, the file simply stays.
+function Remove-Item {{ param([string]$LiteralPath, [switch]$Force, [string]$ErrorAction) }}
+Write-Output "AFTER:$(Test-StudioDirectoryUsable -Path '{good}')"
+""",
+ sabotage = False,
+ names = ("Write-StudioLine", "Test-StudioDirectoryUsable"),
+ )
+ )
+ assert result.returncode == 0, result.stderr
+ assert _lines(result, "BEFORE:") == ["BEFORE:True"]
+ assert _lines(result, "AFTER:") == ["AFTER:False"]
+ # The healthy probe cleaned up after itself, so only the undeletable one is left.
+ assert len(list(good.glob("unsloth-probe-*.tmp"))) == 1
+
+
+@requires_pwsh
+def test_unusable_temp_is_replaced_and_then_restored(tmp_path: Path):
+ # Under a regular file so it cannot merely be created: the probe has to fail the
+ # way an ACL-restricted temp directory fails.
+ blocker = tmp_path / "blocker"
+ blocker.write_text("not a directory")
+ env = os.environ.copy()
+ env["TMP"] = str(blocker / "temp")
+ env.pop("TEMP", None)
+ result = _run_powershell(
+ _script(
+ """
+Initialize-StudioTempEnvironment
+Write-Output "USABLE:$(Test-StudioDirectoryUsable -Path $env:TMP)"
+Write-Output "MATCHED:$($env:TMP -eq $env:TEMP)"
+$replacement = $env:TMP
+Restore-StudioTempEnvironment
+Write-Output "TMP:$env:TMP"
+Write-Output "TEMPSET:$($null -ne $env:TEMP)"
+Write-Output "KEPT:$(Test-Path -LiteralPath $replacement)"
+""",
+ names = (
+ "Write-StudioLine",
+ "Test-StudioDirectoryUsable",
+ "Remove-StudioStalePrivateTempDirectories",
+ "Get-StudioPrivateTempRoots",
+ "New-StudioPrivateTempDirectory",
+ "Initialize-StudioTempEnvironment",
+ "Restore-StudioTempEnvironment",
+ ),
+ ),
+ env = env,
+ )
+ assert result.returncode == 0, result.stderr
+ assert _lines(result, "USABLE:") == ["USABLE:True"]
+ # Both, because Windows reads TMP before TEMP.
+ assert _lines(result, "MATCHED:") == ["MATCHED:True"]
+ assert _lines(result, "TMP:") == [f"TMP:{env['TMP']}"]
+ # TEMP was absent; restoring it as "" would change how every later child
+ # resolves its own temp directory.
+ assert _lines(result, "TEMPSET:") == ["TEMPSET:False"]
+ # It survives on purpose: an autostarted Studio inherited it as its own %TEMP%,
+ # and the host's real one is broken. Stale ones are swept on the next run.
+ assert _lines(result, "KEPT:") == ["KEPT:True"]
+
+
+def _same_path(got: str, expected: str) -> bool:
+ """Compare two resolved paths without pinning one platform's spelling.
+
+ The resolver ends with [System.IO.Path]::GetFullPath, so on Windows the POSIX
+ fixtures below come back rooted on the current drive and with backslashes:
+ "/real/target" resolves to "D:\\real\\target". That is correct, and it has
+ nothing to do with what these cases measure, which is whether the shape
+ (Get-Item).Target arrived in was unwrapped to the right single target.
+ """
+
+ def norm(value: str) -> str:
+ value = value.replace("\\", "/")
+ if len(value) > 1 and value[1] == ":":
+ value = value[2:]
+ return value.rstrip("/").lower()
+
+ return norm(got) == norm(expected)
+
+
+_NT_DEVICE_PREFIX = "\\??\\"
+_LIST = "$l=[System.Collections.Generic.List[string]]::new(); {0}; $l"
+
+# What (Get-Item).Target actually hands back. 5.1 returns a COLLECTION, not a
+# string and not an [array] either, so a container test naming one type lets the
+# real one fall through and be space-joined. Junctions store the NT device form;
+# system junctions and Store AppExecLinks report nothing. None of these shapes can
+# be produced on Linux, so Get-Item is stubbed and the paths are POSIX-style; see
+# _same_path for why the comparison cannot be a string equality.
+_TARGET_SHAPES = [
+ ("generic collection", _LIST.format('$l.Add("/real/target")'), "/real/target"),
+ (
+ "generic collection, several entries",
+ _LIST.format('$l.Add("/first"); $l.Add("/second")'),
+ "/first",
+ ),
+ ("array", '@("/real/target")', "/real/target"),
+ ("bare string", '"/real/target"', "/real/target"),
+ ("nt device prefix", f'"{_NT_DEVICE_PREFIX}/real/target"', "/real/target"),
+ (
+ "nt device prefix in a collection",
+ _LIST.format(f'$l.Add("{_NT_DEVICE_PREFIX}/real/target")'),
+ "/real/target",
+ ),
+ ("relative to the link", '"sibling"', "/some/sibling"),
+ ("pointing at itself", '"/some/link"', ""),
+ ("null (system junction, AppExecLink)", "$null", ""),
+ ("empty", '""', ""),
+ ("whitespace", '" "', ""),
+ ("throws (access denied)", '$(throw "access denied")', ""),
+]
+
+
+@requires_pwsh
+ "shape,expression,expected",
+ _TARGET_SHAPES,
+ ids = [shape.replace(" ", "-") for shape, _, _ in _TARGET_SHAPES],
+)
+def test_link_targets_of_every_windows_powershell_5_1_shape(
+ shape: str, expression: str, expected: str
+):
+ result = _run_powershell(
+ "\n".join(
+ [
+ '$ErrorActionPreference = "Stop"',
+ _helpers("Resolve-StudioLinkTarget"),
+ "function Get-Item {",
+ " param([string]$LiteralPath, [switch]$Force, [string]$ErrorAction)",
+ " $target = $null",
+ f" try {{ $target = {expression} }} catch {{ $target = $null }}",
+ " $item = New-Object psobject",
+ " $item | Add-Member -MemberType NoteProperty -Name Target -Value $target",
+ " Write-Output $item",
+ "}",
+ "Write-Output \"TARGET:[$(Resolve-StudioLinkTarget -Path '/some/link')]\"",
+ ]
+ )
+ )
+ assert result.returncode == 0, result.stderr
+ got = _lines(result, "TARGET:")
+ assert len(got) == 1, got
+ assert _same_path(got[0][len("TARGET:[") : -1], expected)
+
+
+def _dead_pid() -> int:
+ """A PID that is not running, so a ust-<pid>- directory reads as abandoned."""
+ for candidate in range(4_000_000, 4_000_400):
+ try:
+ os.kill(candidate, 0)
+ except ProcessLookupError:
+ return candidate
+ except (OSError, PermissionError):
+ continue
+ return 4_000_000
+
+
+_DEAD_PID = _dead_pid()
+
+
+@requires_pwsh
+ "raw,expected",
+ [
+ ("\\??\\UNC\\server\\share\\dir", "\\\\server\\share\\dir"),
+ ("\\??\\unc\\server\\share", "\\\\server\\share"),
+ ("\\??\\C:\\real\\target", "C:\\real\\target"),
+ (
+ "\\??\\Volume{11111111-2222-3333-4444-555555555555}\\dir",
+ "\\\\?\\Volume{11111111-2222-3333-4444-555555555555}\\dir",
+ ),
+ ],
+ ids = [
+ "unc-device-form",
+ "lowercase-unc",
+ "ordinary-device-form",
+ "mounted-folder-volume-guid",
+ ],
+)
+def test_the_nt_device_prefix_becomes_a_usable_path(raw: str, expected: str):
+ """\\??\\UNC\\server\\share is the device spelling of \\\\server\\share.
+
+ Dropping the first four characters leaves "UNC\\server\\share", which reads as
+ a RELATIVE path and gets combined with the link's own parent, inventing an
+ identity that matches nothing real -- and a wrong identity here is a wrong
+ mutex. Whether the rewritten form counts as rooted is platform-dependent, so
+ what is asserted is the rewrite; the Windows end of it is covered on the 5.1
+ probe.
+ """
+ result = _run_powershell(
+ "\n".join(
+ [
+ '$ErrorActionPreference = "Stop"',
+ _helpers("Resolve-StudioLinkTarget"),
+ "function Get-Item {",
+ " param([string]$LiteralPath, [switch]$Force, [string]$ErrorAction)",
+ " $item = New-Object psobject",
+ f' $item | Add-Member -MemberType NoteProperty -Name Target -Value "{raw}"',
+ " Write-Output $item",
+ "}",
+ "Write-Output \"TARGET:[$(Resolve-StudioLinkTarget -Path '/some/link')]\"",
+ ]
+ )
+ )
+ assert result.returncode == 0, result.stderr
+ got = _lines(result, "TARGET:")[0]
+ assert expected in got
+ assert "UNC\\" not in got and "unc\\" not in got
+
+
+@requires_pwsh
+def test_a_drive_less_rooted_target_lands_on_the_link_own_root(tmp_path: Path):
+ """A symlink may store "\\real", which is rooted but names no drive.
+
+ IsPathRooted says true, so anchoring against the link is skipped and
+ GetFullPath then resolves the target against whatever drive the PROCESS
+ happens to be sitting on. Windows resolves it on the LINK's volume, so a
+ link on D: must never normalize to C:\\real: that is a different directory,
+ and it would be the one the fallback mutex and the in-use scan protect.
+ """
+ link = tmp_path / "nested" / "link"
+ link.parent.mkdir(parents = True)
+ result = _run_powershell(
+ "\n".join(
+ [
+ '$ErrorActionPreference = "Stop"',
+ _helpers("Resolve-StudioLinkTarget"),
+ "function Get-Item {",
+ " param([string]$LiteralPath, [switch]$Force, [string]$ErrorAction)",
+ " $item = New-Object psobject",
+ ' $item | Add-Member -MemberType NoteProperty -Name Target -Value "\\real"',
+ " Write-Output $item",
+ "}",
+ f"$root = [System.IO.Path]::GetPathRoot('{link}')",
+ f"Write-Output \"TARGET:[$(Resolve-StudioLinkTarget -Path '{link}')]\"",
+ 'Write-Output "ROOT:[$root]"',
+ ]
+ )
+ )
+ assert result.returncode == 0, result.stderr
+ got = _lines(result, "TARGET:")[0].split("[", 1)[1].rstrip("]")
+ root = _lines(result, "ROOT:")[0].split("[", 1)[1].rstrip("]")
+ assert got.startswith(root), f"{got} is not on the link's own root {root}"
+ assert got.rstrip("\\/").endswith("real")
+ # The whole point: it is NOT reparented under the link's own directory either.
+ assert "nested" not in got
+
+
+@requires_pwsh
+ "tmp,expect_override",
+ [
+ (" ", True),
+ ("\t", True),
+ ("", False),
+ (None, False),
+ ],
+ ids = ["whitespace-tmp", "tab-tmp", "empty-tmp", "absent-tmp"],
+)
+def test_a_whitespace_only_tmp_is_set_as_far_as_windows_is_concerned(
+ tmp_path: Path, tmp: str | None, expect_override: bool
+):
+ """GetTempPath takes the first of TMP/TEMP that is merely NON-empty.
+
+ So a whitespace-only TMP is the one Windows and every child process will use.
+ Reading it as "unset" probes a healthy TEMP, changes nothing, and leaves the
+ compile and every later download pointed at a path that cannot exist.
+ """
+ good = tmp_path / "good"
+ good.mkdir()
+ local_app_data = tmp_path / "localappdata"
+ local_app_data.mkdir()
+
+ env = os.environ.copy()
+ env.pop("TMP", None)
+ if tmp is not None:
+ env["TMP"] = tmp
+ env["TEMP"] = str(good)
+ env["LOCALAPPDATA"] = str(local_app_data)
+ env["USERPROFILE"] = str(tmp_path / "profile")
+
+ result = _run_powershell(
+ _script(
+ """
+Initialize-StudioTempEnvironment
+Write-Output "TMP:[$env:TMP]"
+""",
+ sabotage = False,
+ names = (
+ "Write-StudioLine",
+ "Test-StudioDirectoryUsable",
+ "Remove-StudioStalePrivateTempDirectories",
+ "Set-StudioPrivateTempOwner",
+ "Get-StudioPrivateTempRoots",
+ "New-StudioPrivateTempDirectory",
+ "Initialize-StudioTempEnvironment",
+ "Restore-StudioTempEnvironment",
+ ),
+ ),
+ env = env,
+ )
+ assert result.returncode == 0, result.stderr
+ got = _lines(result, "TMP:")[0][len("TMP:[") : -1]
+ if expect_override:
+ assert got not in ("", tmp)
+ assert "ust-" in got
+ else:
+ assert "ust-" not in got
+
+
+@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.
+ """
+ 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
+
+
+@requires_pwsh
+ "path,expected",
+ [
+ ("X:\\", "D:\\real\\dir"),
+ ("X:", "D:\\real\\dir"),
+ ("x:\\venv", "D:\\real\\dir"),
+ ("C:\\other", ""),
+ ],
+ ids = ["drive-root", "bare-drive", "lowercase-letter", "unmapped-drive"],
+)
+def test_a_subst_drive_folds_onto_its_target(path: str, expected: str):
+ """The Python runtime gate resolves a SUBST drive; Path.resolve does that.
+
+ Left unresolved here, one directory reached under two spellings produces two
+ different install mutexes, and a Studio running from the physical spelling is
+ invisible to the in-use scan. Measured on windows-latest: subst.exe is the
+ only source available without a compiler -- Get-PSDrive.DisplayRoot,
+ Win32_LogicalDisk.ProviderName, GetFullPath and Resolve-Path all reveal
+ nothing about the mapping.
+ """
+ result = _run_powershell(
+ "\n".join(
+ [
+ '$ErrorActionPreference = "Stop"',
+ _helpers("Get-StudioSubstTarget"),
+ '$script:StudioSubstMap = @{ "X" = "D:\\real\\dir" }',
+ f"Write-Output \"SUBST:[$(Get-StudioSubstTarget -Path '{path}')]\"",
+ ]
+ )
+ )
+ assert result.returncode == 0, result.stderr
+ got = _lines(result, "SUBST:")[0][len("SUBST:[") : -1]
+ if expected:
+ assert got.startswith(expected)
+ else:
+ assert got == ""
+
+
+@requires_pwsh
+def test_the_recorded_owner_outranks_the_name(tmp_path: Path):
+ """The PID in the name is the INSTALLER's, and it exits.
+
+ The process that keeps using the directory is the Studio the installer
+ autostarted, which is what owner.pid records. Reading only the name would
+ clear a live Studio's %TEMP% on the next run.
+ """
+ root = tmp_path / "root"
+ root.mkdir()
+ # Name says dead, owner.pid says alive: keep it.
+ keep = root / f"ust-{_DEAD_PID}-a"
+ 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.mkdir()
+ (drop / "owner.pid").write_text(str(_DEAD_PID), encoding = "utf-8")
+
+ aged = time.time() - 3 * 24 * 3600
+ for d in (keep, drop):
+ os.utime(d, (aged, aged))
+
+ result = _run_powershell(
+ _script(
+ f"Remove-StudioStalePrivateTempDirectories -Root '{root}'",
+ sabotage = False,
+ names = ("Remove-StudioStalePrivateTempDirectories",),
+ )
+ )
+ assert result.returncode == 0, result.stderr
+ assert keep.exists()
+ assert not drop.exists()
+
+
+@requires_pwsh
+def test_the_sweep_keeps_a_directory_whose_owner_is_still_running(tmp_path: Path):
+ """A Studio autostarted by an earlier install owns one of these as its %TEMP%.
+
+ It can outlive the one-day cutoff without ever writing to the directory, and
+ the sweep runs before the runtime mutex is taken, so age alone must not be
+ read as proof that nothing is using it.
+ """
+ root = tmp_path / "root"
+ root.mkdir()
+ live = root / f"ust-{os.getpid()}-old"
+ live.mkdir()
+ (live / "in-use.txt").write_text("a live process owns this", encoding = "utf-8")
+ abandoned = root / f"ust-{_DEAD_PID}-old"
+ abandoned.mkdir()
+
+ aged = time.time() - 3 * 24 * 3600
+ os.utime(live, (aged, aged))
+ os.utime(abandoned, (aged, aged))
+
+ result = _run_powershell(
+ _script(
+ f"Remove-StudioStalePrivateTempDirectories -Root '{root}'",
+ sabotage = False,
+ names = ("Remove-StudioStalePrivateTempDirectories",),
+ )
+ )
+ assert result.returncode == 0, result.stderr
+ assert (live / "in-use.txt").exists()
+ assert not abandoned.exists()
+
+
+@requires_pwsh
+def test_a_healthy_temp_still_sweeps_what_an_earlier_degraded_run_left(tmp_path: Path):
+ """The allocator is the only thing that sweeps, and a healthy host skips it.
+
+ Once the host's own temp is fixed (an ACL correction, a cleaned environment)
+ no further run allocates a private directory, so whatever the degraded runs
+ left would age in place until an uninstall.
+ """
+ good = tmp_path / "good"
+ good.mkdir()
+ 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.mkdir()
+ (abandoned / "leftover.bin").write_text("half a download", encoding = "utf-8")
+ aged = time.time() - 3 * 24 * 3600
+ os.utime(abandoned, (aged, aged))
+
+ env = os.environ.copy()
+ env.update({"TMP": str(good), "TEMP": str(good), "LOCALAPPDATA": str(local_app_data)})
+ env.pop("USERPROFILE", None)
+
+ result = _run_powershell(
+ _script(
+ """
+Initialize-StudioTempEnvironment
+Write-Output "TMP:$env:TMP"
+Write-Output "OVERRIDE:$($null -ne $script:StudioTempOverride)"
+""",
+ sabotage = False,
+ ),
+ env = env,
+ )
+ assert result.returncode == 0, result.stderr
+ assert not abandoned.exists()
+ # And the healthy path is still the healthy path: nothing was redirected.
+ assert _lines(result, "TMP:") == [f"TMP:{good}"]
+ assert _lines(result, "OVERRIDE:") == ["OVERRIDE:False"]
+
+
+@requires_pwsh
+def test_the_stale_sweep_never_deletes_through_a_link(tmp_path: Path):
+ root = tmp_path / "root"
+ root.mkdir()
+ precious = tmp_path / "precious"
+ precious.mkdir()
+ (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.mkdir()
+ (stale / "junk").write_text("x", encoding = "utf-8")
+ fresh = root / f"ust-{_DEAD_PID}-new"
+ fresh.mkdir()
+ link = root / f"ust-{_DEAD_PID}-link"
+ try:
+ link.symlink_to(precious, target_is_directory = True)
+ except (OSError, NotImplementedError):
+ pytest.skip("creating a symlink requires privilege on this host")
+
+ aged = time.time() - 3 * 24 * 3600
+ os.utime(stale, (aged, aged))
+ try:
+ os.utime(link, (aged, aged), follow_symlinks = False)
+ except (NotImplementedError, OSError):
+ # Windows has no follow_symlinks=False for utime, and aging the link any
+ # other way writes THROUGH it, leaving the link fresh so the sweep skips it.
+ # The 5.1 staging probe ages the reparse point via a
+ # FILE_FLAG_OPEN_REPARSE_POINT handle instead.
+ pytest.skip("this host cannot age a link without writing through it")
+
+ result = _run_powershell(
+ _script(
+ f"Remove-StudioStalePrivateTempDirectories -Root '{root}'",
+ sabotage = False,
+ names = ("Remove-StudioStalePrivateTempDirectories",),
+ )
+ )
+ assert result.returncode == 0, result.stderr
+ assert not stale.exists()
+ assert fresh.exists()
+ assert not link.is_symlink()
+ # 5.1's Remove-Item -Recurse follows a junction and empties what it points at.
+ # Nothing the installer creates here is a reparse point, so one costs only the link.
+ assert (precious / "keepme.txt").exists()
+
+
+@requires_pwsh
+def test_a_failure_before_the_lock_still_restores_temp(tmp_path: Path):
+ """Most install failures return long before the finally that frees the locks."""
+ blocker = tmp_path / "blocker"
+ blocker.write_text("not a directory", encoding = "utf-8")
+ env = os.environ.copy()
+ env["TMP"] = str(blocker / "temp")
+ env["TEMP"] = str(blocker / "temp")
+
+ result = _run_powershell(
+ _script(
+ """
+$TauriMode = $false
+function Write-TauriLog { param([string]$Tag, [string]$Message) }
+Initialize-StudioTempEnvironment
+Write-Output "REDIRECTED:$($env:TMP -ne $env:ORIGINAL_TMP)"
+try { Exit-InstallFailure -Message "preflight failed" } catch {}
+Write-Output "TMP:$env:TMP"
+Write-Output "TEMP:$env:TEMP"
+""",
+ names = (
+ "Write-StudioLine",
+ "Exit-InstallFailure",
+ "Test-StudioDirectoryUsable",
+ "Remove-StudioStalePrivateTempDirectories",
+ "Get-StudioPrivateTempRoots",
+ "New-StudioPrivateTempDirectory",
+ "Initialize-StudioTempEnvironment",
+ "Restore-StudioTempEnvironment",
+ ),
+ ),
+ env = {**env, "ORIGINAL_TMP": str(blocker / "temp")},
+ )
+ assert result.returncode == 0, result.stderr
+ assert _lines(result, "REDIRECTED:") == ["REDIRECTED:True"]
+ assert _lines(result, "TMP:") == [f"TMP:{env['TMP']}"]
+ assert _lines(result, "TEMP:") == [f"TEMP:{env['TEMP']}"]
+
+
+def test_the_private_temp_directory_is_somewhere_uninstall_reclaims():
+ """It outlives the install, so it has to sit where the uninstaller looks."""
+ source = INSTALL_PS1.read_text(encoding = "utf-8")
+ uninstall = (REPO_ROOT / "scripts" / "uninstall.ps1").read_text(encoding = "utf-8")
+ roots = _extract(r" function Get-StudioPrivateTempRoots \{.*?\n \}\n", source)
+
+ # LOCALAPPDATA\"Unsloth Studio" is the data dir uninstall.ps1 removes wholesale.
+ assert 'Join-Path $env:LOCALAPPDATA "Unsloth Studio\\temp"' in roots
+ assert '"Unsloth Studio"' in uninstall
+ # ~\.unsloth\.cache is on its explicit sibling list. Directly under ~\.unsloth
+ # would be worse: that directory is removed only when it is empty.
+ assert 'Join-Path $env:USERPROFILE ".unsloth\\.cache\\temp"' in roots
+ assert (
+ '$defaultCache = if ($defaultUnslothHome) { Join-Path $defaultUnslothHome ".cache" }'
+ in uninstall
+ )
+ assert ".unsloth\\temp" not in roots
+
+ # The GetFolderPath fallback is the whole point of the second root: LOCALAPPDATA
+ # is dropped in service and CI contexts. The uninstaller has to resolve the data
+ # dir the same way, or the tree it places there survives an uninstall on exactly
+ # the hosts that needed the fallback.
+ assert '[Environment]::GetFolderPath("LocalApplicationData")' in roots
+ # And it has to consider BOTH spellings rather than the first that answers:
+ # 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
+
+
+@requires_pwsh
+def test_the_uninstaller_reclaims_both_local_app_data_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.
+ """
+ uninstall = (REPO_ROOT / "scripts" / "uninstall.ps1").read_text(encoding = "utf-8")
+ block = _extract(r" # BOTH LocalAppData spellings.*?\n \}\n", uninstall)
+
+ dead = str(tmp_path / "gone" / "localappdata")
+ env = os.environ.copy()
+ env["LOCALAPPDATA"] = dead
+ result = _run_powershell(
+ "\n".join(
+ [
+ '$ErrorActionPreference = "Stop"',
+ block,
+ '$defaultDataDirs | ForEach-Object { Write-Output "DIR:$_" }',
+ ]
+ ),
+ env = env,
+ )
+ assert result.returncode == 0, result.stderr
+ 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.
+ 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")
+
+ # 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
diff --git a/tests/python/test_windows_installer_concurrency_guard.py b/tests/python/test_windows_installer_concurrency_guard.py
index 9ed35eebc0e..5e713e43748 100644
--- a/tests/python/test_windows_installer_concurrency_guard.py
+++ b/tests/python/test_windows_installer_concurrency_guard.py
@@ -9,6 +9,7 @@ import re
import shutil
import subprocess
import sys
+import tempfile
import time
from pathlib import Path
@@ -33,17 +34,70 @@ def _extract(pattern: str, source: str) -> str:
def _run_powershell(shell: str, script: str, env: dict[str, str]) -> str:
- result = subprocess.run(
- [shell, "-NoProfile", "-NonInteractive", "-Command", script],
- check = True,
- capture_output = True,
- text = True,
- env = env,
- timeout = 30,
- )
+ # Through a FILE, not -Command: these scripts carry the whole extracted helper
+ # chain, and Windows caps a command line at 32767 characters. Passed inline,
+ # the moment the chain grows past that every test here dies as WinError 206
+ # "The filename or extension is too long" instead of testing anything.
+ # utf-8-sig because Windows PowerShell 5.1 reads a BOM-less .ps1 as ANSI.
+ handle, name = tempfile.mkstemp(suffix = ".ps1")
+ os.close(handle)
+ try:
+ Path(name).write_text(script, encoding = "utf-8-sig")
+ result = subprocess.run(
+ [shell, "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-File", name],
+ check = True,
+ capture_output = True,
+ text = True,
+ # Decoded as utf-8 with replacement, not the console codepage: cp1252
+ # cannot decode what PowerShell writes and the whole test then dies as
+ # a UnicodeDecodeError on a byte in an error message.
+ encoding = "utf-8",
+ errors = "replace",
+ env = env,
+ timeout = 60,
+ )
+ finally:
+ try:
+ os.unlink(name)
+ except OSError:
+ pass
return result.stdout.strip()
+def _ps_file(directory: Path, name: str, script: str) -> str:
+ """Same reason as _run_powershell: a 32 KB command line is not available here."""
+ path = directory / name
+ path.write_text(script, encoding = "utf-8-sig")
+ return str(path)
+
+
+# The chain Get-StudioFinalPath dispatches to. It used to compile the native helper
+# inline, so a test could extract it alone; extracting the dispatcher by itself now
+# yields a body whose calls are all undefined, which reads as "could not resolve"
+# rather than as a missing helper (issue #9140).
+_FINAL_PATH_CHAIN = (
+ "Write-StudioLine",
+ "Test-StudioDirectoryUsable",
+ "Remove-StudioStalePrivateTempDirectories",
+ "Get-StudioPrivateTempRoots",
+ "New-StudioPrivateTempDirectory",
+ "Initialize-StudioTempEnvironment",
+ "Write-StudioFinalPathDegraded",
+ "Initialize-StudioFinalPathNativeType",
+ "Resolve-StudioLinkTarget",
+ "Get-StudioSubstTarget",
+ "Get-StudioLexicalPath",
+ "Resolve-StudioFinalPathInfo",
+ "Get-StudioFinalPath",
+)
+
+
+def _final_path_helpers(source: str) -> str:
+ return "\n".join(
+ _extract(rf" function {name} \{{.*?\n \}}\n", source) for name in _FINAL_PATH_CHAIN
+ )
+
+
def _mutex_helpers(source: str) -> str:
return "\n".join(
_extract(rf" function {name} \{{.*?\n \}}\n", source)
@@ -56,6 +110,19 @@ def _mutex_helpers(source: str) -> str:
# stub would keep passing if the real call ever went wrong.
"Write-StudioLine",
"Enter-StudioNamedMutex",
+ # Get-StudioFinalPath is a dispatcher now: it falls back to the pure
+ # PowerShell resolver when the native helper did not compile (#9140).
+ "Test-StudioDirectoryUsable",
+ "Remove-StudioStalePrivateTempDirectories",
+ "Get-StudioPrivateTempRoots",
+ "New-StudioPrivateTempDirectory",
+ "Initialize-StudioTempEnvironment",
+ "Write-StudioFinalPathDegraded",
+ "Initialize-StudioFinalPathNativeType",
+ "Resolve-StudioLinkTarget",
+ "Get-StudioSubstTarget",
+ "Get-StudioLexicalPath",
+ "Resolve-StudioFinalPathInfo",
"Get-StudioFinalPath",
"Get-StudioPathHash",
"Get-StudioInstallMutexName",
@@ -76,8 +143,21 @@ def _process_helpers(source: str) -> str:
return "\n".join(
_extract(rf" function {name} \{{.*?\n \}}\n", source)
for name in (
+ "Write-StudioLine",
+ "Test-StudioDirectoryUsable",
+ "Remove-StudioStalePrivateTempDirectories",
+ "Get-StudioPrivateTempRoots",
+ "New-StudioPrivateTempDirectory",
+ "Initialize-StudioTempEnvironment",
+ "Write-StudioFinalPathDegraded",
+ "Initialize-StudioFinalPathNativeType",
+ "Resolve-StudioLinkTarget",
+ "Get-StudioSubstTarget",
+ "Get-StudioLexicalPath",
+ "Resolve-StudioFinalPathInfo",
"Get-StudioFinalPath",
"Test-StudioProtectedPathMatch",
+ "Get-StudioProcessImagePath",
"Get-RunningStudioVenvProcesses",
)
)
@@ -94,8 +174,13 @@ def test_running_venv_process_is_reported(tmp_path: Path, shell: str):
shutil.copy2(Path(os.environ["SystemRoot"]) / "System32" / "PING.EXE", probe)
creationflags = getattr(subprocess, "CREATE_NO_WINDOW", 0)
+ # Long enough that the child outlives the scan itself. Windows PowerShell 5.1
+ # pays a cold start plus a real csc.exe compile of the native helper before it
+ # can look at anything, which alone can outlast a six-ping child; the process
+ # would then be gone by the time the scan ran, and the test would read as
+ # "the in-use check missed it".
child = subprocess.Popen(
- [str(probe), "-n", "6", "127.0.0.1"],
+ [str(probe), "-n", "120", "127.0.0.1"],
creationflags = creationflags,
)
try:
@@ -107,7 +192,7 @@ $ErrorActionPreference = "Stop"
"""
env = os.environ.copy()
env["TEST_VENV"] = str(scripts.parent)
- deadline = time.monotonic() + 4
+ deadline = time.monotonic() + 60
observed = []
while time.monotonic() < deadline:
observed = _run_powershell(shell, script, env).splitlines()
@@ -255,14 +340,22 @@ def test_installer_ignores_command_line_and_cwd_only_path_mentions():
assert "Get-CimInstance" not in detector
assert ".CommandLine" not in detector
assert "$process.Path" not in detector
- assert "[UnslothStudioFinalPathV2]::GetProcessImagePath($process.Id)" in detector
+ assert "Get-StudioProcessImagePath -ProcessId $process.Id" in detector
+
+ # The same contract has to hold on every rung of that helper's fallback: a
+ # confirmed image, never a command line. Its Win32_Process rung exists because a
+ # host that cannot compile the native helper would otherwise find no running
+ # processes and overwrite a venv Studio has open (issue #9140).
+ image = _extract(r" function Get-StudioProcessImagePath \{.*?\n \}\n", source)
+ assert ".CommandLine" not in image
+ assert "ExecutablePath" in image
@pytest.mark.skipif(os.name != "nt" or not POWERSHELLS, reason = "Windows PowerShell is required")
@pytest.mark.parametrize("shell", POWERSHELLS)
def test_versioned_native_helper_loads_after_older_installer_type(shell: str):
source = INSTALL_PS1.read_text(encoding = "utf-8")
- final_path_helper = _extract(r" function Get-StudioFinalPath \{.*?\n \}\n", source)
+ final_path_helper = _mutex_helpers(source)
script = f"""
$ErrorActionPreference = "Stop"
Add-Type -TypeDefinition @'
@@ -470,7 +563,7 @@ def test_tauri_override_accepts_junction_alias_of_managed_root(tmp_path: Path, s
validation_start = source.index(" # Custom Unsloth roots are not supported with --tauri")
validation_end = source.index(" # LOCALAPPDATA may be unset", validation_start)
validation = source[validation_start:validation_end]
- final_path_helper = _extract(r" function Get-StudioFinalPath \{.*?\n \}\n", source)
+ final_path_helper = _final_path_helpers(source)
script = f"""
$ErrorActionPreference = "Stop"
{final_path_helper}
@@ -538,7 +631,7 @@ def test_path_identity_failure_is_reported_as_unknown(shell: str):
script = f"""
$ErrorActionPreference = "Stop"
{_mutex_helpers(source)}
-function Get-StudioFinalPath {{ throw "identity unavailable" }}
+function Resolve-StudioFinalPathInfo {{ throw "identity unavailable" }}
$match = Test-StudioPathEqual -Left "C:\\one" -Right "C:\\two"
Write-Output ($null -eq $match)
"""
@@ -571,11 +664,21 @@ Write-Output "READY"
Exit-StudioInstallMutex -Mutex $mutex
"""
holder = subprocess.Popen(
- [shell, "-NoProfile", "-NonInteractive", "-Command", holder_script],
+ [
+ shell,
+ "-NoProfile",
+ "-NonInteractive",
+ "-ExecutionPolicy",
+ "Bypass",
+ "-File",
+ _ps_file(tmp_path, "holder.ps1", holder_script),
+ ],
stdin = subprocess.PIPE,
stdout = subprocess.PIPE,
stderr = subprocess.PIPE,
text = True,
+ encoding = "utf-8",
+ errors = "replace",
env = env,
)
try:
@@ -707,11 +810,21 @@ Write-Output "ACQUIRED"
Exit-StudioInstallMutex -Mutex $mutex
"""
holder = subprocess.Popen(
- [shell, "-NoProfile", "-NonInteractive", "-Command", holder_script],
+ [
+ shell,
+ "-NoProfile",
+ "-NonInteractive",
+ "-ExecutionPolicy",
+ "Bypass",
+ "-File",
+ _ps_file(tmp_path, "holder.ps1", holder_script),
+ ],
stdin = subprocess.PIPE,
stdout = subprocess.PIPE,
stderr = subprocess.PIPE,
text = True,
+ encoding = "utf-8",
+ errors = "replace",
env = env,
)
try: