Repository navigation
Install Studio on a Windows host whose C# compiler cannot run - #9178
Conversation
A first launch of the desktop app on Windows 10 died with
[ERROR] Could not create the Studio install lock: (0) : Die Quelldatei
'C:\Windows\TEMP\05po312x.0.cs' konnte nicht gefunden werden.
(1) : using System;
which is C# compiler error CS2001, not a locking problem. Get-StudioFinalPath
compiles a GetFinalPathNameByHandleW helper with Add-Type, and Windows
PowerShell 5.1 (the interpreter install.rs spawns) compiles by writing the
source into %TEMP% and running csc.exe. When that directory cannot hold a file,
or a scanner eats the source before csc opens it, Add-Type throws, and the
throw travelled up Get-StudioPathHash into Enter-StudioInstallMutex, where it
was reported as a lock failure. install.rs never sets or validates TEMP, so the
installer inherits whatever the app was started with.
Three parts:
Probe TMP and TEMP once with a write, read back and delete, and if the
inherited one cannot hold a file, point both at a per-user directory for the
rest of the run. The compiler is not the only thing that stages through there;
so do the Python, uv and VC++ downloads. It is restored on every exit path.
Split Get-StudioFinalPath into a cached native initializer and a compiler-free
resolver. The initializer skips compiling under Constrained Language Mode,
retries once with a private %TEMP%, and then remembers the answer. The fallback
resolves reparse points component-wise from the root, since a link on a parent
component is the ordinary Windows shape. Callers get an Exact flag so
Test-StudioPathEqual can answer "unknown" rather than "different", which the
runtime lock already reads as "take both locks".
Stop the in-use check failing open. Get-RunningStudioVenvProcesses called the
compiled helper inside catch { continue }, so a host that could not compile
found no running processes and would happily overwrite a venv Studio had open.
It now falls back to the process image path and Win32_Process, and says so.
With the native helper present every output is byte-identical to before: the
install mutex name, the runtime lock names, path identity and the process scan.
Fixes #9140
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 6a194d11a2
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| Remove-Item -LiteralPath $stale.FullName -Force -ErrorAction SilentlyContinue | ||
| continue | ||
| } | ||
| Remove-Item -LiteralPath $stale.FullName -Recurse -Force -ErrorAction SilentlyContinue |
There was a problem hiding this comment.
Avoid recursing through nested reparse points
On Windows PowerShell 5.1, a stale private temp directory containing a junction below its root still reaches this recursive removal because only $stale.Attributes is checked. Studio and its child processes are explicitly allowed to use this directory after installation, so a tool can leave a nested junction there; the next sweep may then traverse it and delete files from the junction target. The cleanup needs to inspect the complete tree without following reparse points, not merely protect a top-level linked ust-* directory.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Measured on Windows PowerShell 5.1 rather than assumed, and it does not reproduce: with a junction nested one level below a stale ust-* directory, Remove-Item -Recurse -Force removed the directory and left the junction target untouched (NESTED:stale-gone=True, NESTED:target-intact=True). The same run also shows the top-level case behaving that way, which is why the comment on that branch was reworded earlier: what is reproducible today is Remove-Item without -Recurse throwing NullReferenceException on a junction, which is what Directory.Delete replaced.
The fallback temp directory outlives the install on purpose: a Studio started from it inherits it as its own %TEMP%. That means it has to sit somewhere scripts/uninstall.ps1 reclaims, and LOCALAPPDATA\UnslothStudio was a folder of my own invention that nothing would ever clean. The USERPROFILE candidate was worse than litter. ~\.unsloth is removed only when it is empty, so a leftover ~\.unsloth\temp would have stopped the uninstaller clearing the directory at all. Now LOCALAPPDATA\"Unsloth Studio"\temp, which the uninstaller deletes wholesale as the data dir, and ~\.unsloth\.cache\temp, which is on its explicit sibling list. Creating the data dir early cannot be mistaken for an install: the desktop app decides that from find_unsloth_binary(), not from this directory existing.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 7b6791516f
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| if (-not (Test-Path -LiteralPath $Path -PathType Container)) { | ||
| New-Item -ItemType Directory -Path $Path -Force -ErrorAction Stop | Out-Null |
There was a problem hiding this comment.
Create private temp paths literally
When LOCALAPPDATA and USERPROFILE contain wildcard characters such as brackets and the inherited temp directory is unusable, New-Item -Path interprets those characters as wildcards rather than creating the literal candidate path. All private-temp candidates can therefore fail, leaving the installer on the broken temp directory and reproducing the Add-Type/download failure this fallback is intended to handle; use the literal .NET Directory.CreateDirectory API already used elsewhere in this script.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Measured on Windows PowerShell 5.1 rather than assumed, and it does not reproduce: with a bracketed profile component, New-Item -ItemType Directory -Path created the literal nested path and Test-Path -LiteralPath confirmed it (WILD:newitem=ok, WILD:newitem-exists=True). Every other path call in that helper is already literal (Join-Path, Test-Path -LiteralPath, the .NET file APIs), so there is no wildcard surface left to fix.
Surviving a dead compiler is the floor. The retry is supposed to get the native resolver back, and nothing asserted that it does. Add-Type is stubbed to behave the way 5.1's CodeDom does, writing the source into %TEMP% and failing while that cannot hold a file, then calling the real cmdlet once it can, so the type really is defined on the second attempt. Pins the whole sequence: one failure then exactly one retry, the type loaded afterwards, no degraded warning, TMP and TEMP restored to the broken values they came in with, and the retry directory cleaned up.
There was a problem hiding this comment.
💡 Codex Review
Line 909 in 7992ed0
When --tauri is run via irm | iex with an unusable inherited temp directory and an unsupported custom Studio root, the preceding Get-StudioFinalPath calls invoke Initialize-StudioTempEnvironment and redirect TMP/TEMP, but this direct throw occurs before the lock-owning finally and does not call Restore-StudioTempEnvironment. The exception therefore leaves the caller's persistent PowerShell session using the installer-owned temp directory; restore the environment before throwing or place this validation under a finally.
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
Running the sweep on Windows PowerShell 5.1 showed the reparse-point branch never removing the link: Remove-Item without -Recurse reports the junction target's contents and refuses as "directory not empty", so a junction left under the private temp root would sit there forever. Directory.Delete with recursive:$false removes the reparse point itself and, unlike -Recurse on 5.1, cannot follow it into the target.
Measured on windows-latest under PowerShell 5.1: Remove-Item -Recurse on a junction removed only the link and left the target alone, while Remove-Item without -Recurse threw a NullReferenceException that -ErrorAction did not suppress. The comment claimed the first case as the hazard; the second is what is reproducible today. Directory.Delete avoids both.
Running them on windows-latest turned up three things the Linux-only run could not see. The junction-alias test extracts Get-StudioFinalPath alone, which is a dispatcher now, so every call in it was undefined and it read as "could not resolve"; give it the whole resolver chain. The link-shape cases compared a POSIX fixture against a GetFullPath result, which is drive-rooted and backslashed on Windows, so compare paths rather than spellings. And utime with follow_symlinks=False does not exist on Windows, where aging a link any other way writes through onto the target; skip there and say why. Resolve-StudioLinkTarget now normalises $Path before the self-reference check, so a caller passing an unnormalised spelling still trips the guard instead of being handed a link that points at itself.
|
Confirmed this hits install.ps1 where Get-StudioFinalPath compiles the native helper with a bare Add-Type, so a host with an unusable TEMP reports a lock failure instead of the real cause. Could you get Backend CI and the Chat UI job green, then I will review this. |
…s directory Four review findings, all reachable through paths this change itself opened. Two early throws sit before the try/finally that owns the locks: rejecting a custom root under --tauri, and --shortcuts-only finding no managed Python. Resolving a path can redirect TMP and TEMP, so under irm | iex both left the caller's own session pointed at an installer-owned directory. The tauri branch restores before it throws; the shortcuts-only block is now a try/finally, which also covers the tauri return inside it. The stale sweep treated age as proof a directory was unused. A Studio autostarted by an earlier install inherits one as its %TEMP% and can outlive the one-day cutoff without writing to it, and the sweep runs before the runtime mutex is taken. The owner PID is in the name, so a directory whose owner is still running is left alone. The in-use scan resolved the venv and each process image through the same resolver, which is enough while it is exact. Without the native helper an alias it cannot canonicalize keeps its own spelling while the process reports the physical one, so the prefix test found nothing and the install would overwrite a venv Studio had open. When the identity is inexact it now also compares the two paths below their roots, and fails closed.
Three follow-ups, each on a path the earlier round opened rather than closed. A SUBST drive kept its own spelling on a compiler-blocked host, so one directory reached as X:\venv and as its physical target produced two different install mutexes and hid a running Studio from the in-use scan. The Python runtime gate resolves it, since Path.resolve does. Measured on windows-latest that subst.exe is the only source available without a compiler: Get-PSDrive.DisplayRoot, Win32_LogicalDisk.ProviderName, GetFullPath and Resolve-Path all reveal nothing. Get-StudioLexicalPath now folds the alias before it walks components, so the identity, the mutex and the scan all agree with the runtime gate. Stripping the four-character device prefix from \??\UNC\server\share left UNC\server\share, which reads as relative and was combined with the link's own parent. It becomes \\server\share instead. The PID baked into a ust-<pid>- name is the installer's, and the installer is gone by the time the next sweep runs; the process that keeps using the directory is the Studio it autostarted. That one is recorded in owner.pid when the autostart happens, and the sweep prefers it over the name.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: acf03a258a
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| $candidateRoot = [System.IO.Path]::GetPathRoot($executable) | ||
| if ($candidateRoot -and $executable.Length -gt $candidateRoot.Length) { | ||
| $candidateBelowRoot = $executable.Substring($candidateRoot.Length).TrimStart('\', '/') | ||
| $matched = Test-StudioProtectedPathMatch ` | ||
| -Candidate $candidateBelowRoot -ProtectedPath $resolvedBelowRoot -Exact:$Exact |
There was a problem hiding this comment.
Expand 8.3 components before fallback matching
On compiler-blocked hosts whose custom Studio root contains an 8.3 component (for example, C:\PROGRA~1\Unsloth), $resolvedBelowRoot retains PROGRA~1 while the running executable resolves to Program Files, so stripping only the drive roots here still cannot match them. The Python runtime gate hashes the resolved long path while the installer hashes the short spelling, meaning neither the mutex nor this process scan protects the active venv before replacement. Fresh evidence after the prior alias fix is that this newly added fallback removes only roots and never expands the differing 8.3 component.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Measured on Windows PowerShell 5.1 with the compiler dead, rather than reasoned about, and it does not reproduce: an 8.3 spelling and its long form reach the same identity through the resolver already.
SHORTID:short=C:\sn2\PROGRA~1
SHORTID:long=C:\sn2\Program Files Like This
SHORTID:viaShort=C:\sn2\Program Files Like This\venv
SHORTID:viaLong=C:\sn2\Program Files Like This\venv
SHORTID:same=True
The reason is that Get-StudioLexicalPath starts with [System.IO.Path]::GetFullPath, and on .NET Framework that expands a short component. The same run measured the alternatives: Get-Item .FullName also expands, while Resolve-Path, Scripting.FileSystemObject GetFolder().Path and cmd's %f all hand the short form straight back. So $resolvedBelowRoot does not retain PROGRA1, and no extra expansion step is needed.
Worth recording that the first pass at this measured the wrong disk: 8dot3 name creation is per volume, off by default on the runner temp volume (D:) and on for the system volume, so the probe now runs on both and only asserts where short names actually exist.
Same trap as the UNC device form, in a different shape. A mounted folder
reports its target as \??\Volume{GUID}\..., and after the four-character strip
Volume{...}\... is not rooted either, so it was combined with the link's own
parent and the resulting identity named a directory that does not exist. It
becomes the extended-length spelling \\?\Volume{GUID}\... instead, which is the
same device path and stays the volume it names.
A directory symlink can store a target like "\real": rooted as far as IsPathRooted is concerned, but naming no drive. The compiler-free resolver therefore skipped anchoring it to the link and handed it to GetFullPath, which resolves a drive-less path against the PROCESS current drive. A link on D: could normalize to C:\real, so the fallback mutex and the in-use process scan would guard a different directory than the one being installed into. Windows resolves such a target on the link's own volume, so anchor it to GetPathRoot of the link before normalizing. A volume-GUID spelling has no root to anchor to (GetPathRoot is empty there, measured on windows-latest), and those keep today's behaviour rather than a guess.
The Windows job started failing every test in this file as WinError 206, "The filename or extension is too long". These scripts embed the whole extracted helper chain, which has grown past the 32767 character command line cap Windows enforces, so nothing was being tested on the platform the tests exist for. Written to a temp .ps1 and run with -File instead, with a BOM so 5.1 does not read it as ANSI. test_running_venv_process_is_reported also raced: a six-ping child can exit before Windows PowerShell 5.1 has finished its cold start and the csc.exe compile of the native helper, which reads as the in-use scan missing a running process. Same fix already applied to the 32-bit test: a long-lived child and a deadline that allows for a slow shell.
New-StudioPrivateTempDirectory tries $env:LOCALAPPDATA first and falls through to the LocalApplicationData known folder when that path is set but not usable, so a non-blank variable does not tell you where "Unsloth Studio\temp" actually landed. The uninstaller resolved a single root and stopped at the first non-blank candidate, so on those hosts it removed a directory that was never used and left the real tree behind. It now collects both spellings, deduplicated, and stops servers by port file, adds stop roots and removes the data dir for each. On an ordinary host the two agree and the list has one entry, which is exactly today's behaviour.
The stale sweep only ran from New-StudioPrivateTempDirectory, which a run with a usable inherited TMP/TEMP never reaches. So once a host's temp was fixed, by an ACL correction or a cleaned environment, nothing ever collected what the degraded runs had left, including the remains of interrupted downloads, and it sat there until an uninstall. The candidate roots move into Get-StudioPrivateTempRoots so both paths can share them, and the healthy path now sweeps each one. A root that does not exist is a no-op, which is every ordinary host.
|
Codex Review: Didn't find any major issues. Breezy! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
The usability probe created a file, read it back, then deleted it with the error suppressed and reported success regardless. A directory that accepts a file and refuses to give it back, a denied Delete ACE or a scanner sitting on the handle, therefore passed as usable. That is the shape behind this whole issue: csc.exe writes its source and its output into the temp directory and then cleans up, so the private-temp fallback was being skipped for exactly the hosts that needed it. The delete is now verified. Retried up to three times first, since a scanner holding a 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.
|
Codex Review: Didn't find any major issues. Nice work! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
…utf-8 The command line cap caught the other two spawn sites as well: the Add-Type fallback tests and the two mutex holder processes still passed their script inline, so seven tests died as WinError 206 on windows-latest without testing anything. All of them now go through a temp .ps1 with -File, the same as the rest of the file. Output is also decoded as utf-8 with replacement rather than the console codepage. cp1252 cannot decode what PowerShell writes into an error message, and the reader thread raised UnicodeDecodeError from inside subprocess.
|
@codex review |
|
Codex Review: Didn't find any major issues. Breezy! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
…stall Two corrections to #9178, both found by auditing it after it merged. The final normalization kept the \\?\ prefix on a volume GUID. That string is hashed into the runtime mutex name, and unsloth_cli/_studio_runtime_gate.py strips \\?\ unconditionally, so on a host that resolves to a volume GUID the installer and a running Studio computed different names for one directory and neither excluded the other. Every extended spelling comes off again, as it did before #9178. Rootedness does matter while a link target is being anchored, and Resolve-StudioLinkTarget still keeps the extended form for that; nothing after this point anchors anything. The uninstaller resolved both LocalAppData spellings and gave each the full data-directory delete. That delete is recursive and, alone among the deletes in that script, requires no ownership sentinel and consults no deny list. The two spellings differ mainly when one of them names a DIFFERENT USER's profile: CreateProcessAsUser with a null environment block, runas /env, a service token. The second spelling now gets only what install.ps1 puts there, ust- directories matched by shape rather than prefix, and the temp directory and its parent only if they are left empty. The port-file stop and the stop-roots list go back to the single resolved root.
* Stop the temp probe leaving anything behind Three pieces of residue an audit of #9178 turned up, all on hosts whose temp is degraded, which is the population that change exists for. Probing the host's own TMP no longer creates it. New-Item -Force builds the whole parent chain, so a stale or mistyped TMP had the installer silently materialize a tree at a path nobody chose and then trust it as temp. Absent now reads as unusable, which is what the private fallback is for. A directory the installer owns is still created, through an explicit switch. A probe file that could not be deleted is reclaimed by the next run, once it is a day old. The probe cannot clean up after itself when deletion is exactly what failed, and nothing else knows the name, so each such run used to leave one more file in the host's temp forever. The age gate keeps it away from a probe running concurrently in another process. A candidate root that fails its probe is taken back. The probe creates the directory before it tests it, so an install that tried every root and gave up left a "Unsloth Studio" tree on a machine Studio was never installed on. Only if empty, so a directory that already held something is never touched. * Keep the lock name in step with the runtime gate, and narrow the uninstall Two corrections to #9178, both found by auditing it after it merged. The final normalization kept the \\?\ prefix on a volume GUID. That string is hashed into the runtime mutex name, and unsloth_cli/_studio_runtime_gate.py strips \\?\ unconditionally, so on a host that resolves to a volume GUID the installer and a running Studio computed different names for one directory and neither excluded the other. Every extended spelling comes off again, as it did before #9178. Rootedness does matter while a link target is being anchored, and Resolve-StudioLinkTarget still keeps the extended form for that; nothing after this point anchors anything. The uninstaller resolved both LocalAppData spellings and gave each the full data-directory delete. That delete is recursive and, alone among the deletes in that script, requires no ownership sentinel and consults no deny list. The two spellings differ mainly when one of them names a DIFFERENT USER's profile: CreateProcessAsUser with a null environment block, runas /env, a service token. The second spelling now gets only what install.ps1 puts there, ust- directories matched by shape rather than prefix, and the temp directory and its parent only if they are left empty. The port-file stop and the stop-roots list go back to the single resolved root. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Take back the parents the failed candidate created, not just the leaf New-Item -Force builds the whole chain, so removing only the empty ust-* directory still left "Unsloth Studio\temp" standing, which is the data directory tree this cleanup exists to avoid conjuring on a machine Studio was never installed on. It now walks back up, but only through the directory names this path is made of and only while each one is empty, so a tree that already held something is left alone and ~\.unsloth, which is shared, is never removed. The test asserts both halves: nothing remains under a root that was empty before, and a pre-existing studio.port under one of the same parents survives. * Sweep by shape, not by prefix, and say when the native resolver gives up Two audits of the merged change independently reproduced the same deletion on a HEALTHY host: the stale sweep matched ust-* by prefix, and a name whose tail is not a parseable PID leaves $ownerPid at zero, which skips the liveness check entirely. So a pre-existing directory such as "ust-legacy" or "ust-user-cache" under LOCALAPPDATA\Unsloth Studio\temp, older than a day, was recursively deleted by an ordinary install. The uninstaller added in the previous commit already required the allocator's exact shape; the two had drifted apart. The sweep now requires it too, case-insensitively, since Windows filenames are. Separately, a native resolver that COMPILES and then throws falls back to the lexical resolver, which is right, and marks the answer inexact, which is also right, but said nothing. The degraded warning fires only when the compile itself failed, so an operator on a host that looks perfectly healthy was left with a silently inexact identity. It now warns once, with wording distinct from the compile-failure warning. Exit codes and the fallback itself are unchanged: aborting the install is the #9140 symptom, not the fix. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * An owner nobody recorded is unknown, not abandoned Three findings from the second audit round, all in the ownership model. The directory name carries the INSTALLER's pid. An installer killed between Start-Process and the owner.pid write leaves a dead pid in the name while the Studio it started is using that directory as its own %TEMP%, and a later run read that as proof of abandonment and deleted it out from under the live process. Reading owner.pid is proof; guessing from the name is not, so an unrecorded owner now needs a week rather than a day before it is collected. The pile still stays bounded, and a Studio actually using the directory refreshes its timestamp long before that. The uninstaller's private temp sweep ignored owner.pid entirely, so it removed a directory a Studio from another install root, or another user, was live on. It now leaves a live owner alone, exactly as install.ps1's sweep does. That sweep also walked through a link: Get-ChildItem on a reparse point enumerates the target, whose children carry no ReparsePoint attribute, so the recursive delete took the target's tree. It now refuses a temp directory whose own path or parent is a link. In install.ps1 the reparse branch moves ahead of the owner logic, since the allocator never creates a link, reading owner.pid out of one would read through it, and unlinking is safe whatever owns it. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Unwind only what the probe created, and require an owner outside our profile Two review items on this branch. The cleanup walked back up through any empty, correctly named parent. A pre-provisioned "Unsloth Studio\temp" with its own ACLs, or an empty relocation junction, is configuration this installer did not create, and empty plus correctly named is not the same as ours. Which ancestors were absent is now recorded before the probe touches anything, and only those are unwound. A reparse point stops the walk regardless. The uninstaller's private temp sweep treated the directory-name shape as ownership proof in every profile it looked at. Under the profile being uninstalled that is right, since that is what is being removed. In the other LocalAppData spelling, which can be a different user, a directory with no recorded owner now stays: 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. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Reject a reparse point anywhere above another profile's temp root A junction does not have to sit next to the temp directory to redirect it. LocalAppData, the profile directory or the drive root can be the reparse point, and then "<root>\Unsloth Studio\temp" and its parent both look like ordinary directories while Get-ChildItem lands somewhere else. For a LocalAppData spelling that is not the profile being uninstalled, that somewhere else can be another user's tree. Walk every ancestor up to the root for the alternate spelling. The profile the uninstall is actually for keeps the two-level check: 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. * Sweep the private temp trees before removing the data directory The primary private temp directory lives inside the data directory, and the data directory is removed wholesale. A Studio from another install root can still be alive on that temp directory as its %TEMP%, so the live-owner check never got the chance to protect it. Run the sweep first and have it hand back everything it kept, then let the data-dir removal delete around those paths through _RemoveTreeKeeping. With an empty preserve list that is _RemovePath and nothing else, which is what every ordinary uninstall gets. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Sweep only the probe names the installer generates The stale-probe cleanup runs in the HOST's temp directory, where a file that merely starts with unsloth-probe- and ends in .tmp belongs to somebody else. Match the shape the probe actually writes, eight hex characters, the same rule the private temp sweep already uses. --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Fixes #9140.
What happened before
A first launch of Unsloth Studio for Windows on Windows 10 failed three times in a row with:
That message is C# compiler error CS2001, "source file could not be found". It has nothing to do with locking.
Get-StudioFinalPathcompiles aGetFinalPathNameByHandleWhelper at runtime withAdd-Type -TypeDefinition. Windows PowerShell 5.1, whichstudio/src-tauri/src/install.rshardcodes viapowershell_exe(), compiles by writing the generated source into%TEMP%and shelling out tocsc.exe. On that machine%TEMP%wasC:\Windows\TEMPand the source was gone by the timecsc.exeopened it.install.rsnever sets or validatesTEMP/TMP, so the installer inherits whatever the app process had.The throw travelled up
Get-StudioPathHashintoEnter-StudioInstallMutex, whose catch reported it as a lock failure. The install could never start, and nothing in the message pointed at the compiler.This was the only fatal
Add-Typein the tree. Every other one is already tolerant, andEnable-StudioVirtualTerminaleven carries a comment about this exact failure mode.What happens after
The installer completes on a host whose
%TEMP%is unusable or whose C# compiler is blocked, with one clear warning and degraded but safe path identity.Three parts:
A usable-temp layer.
TMPandTEMPare probed once with a write, read back and delete, because the failure shapes that matter here all pass an existence check and then lose the file. If the inherited directory cannot hold a file, both variables point at a per-user directory for the rest of the run and are restored on every exit path. The compiler is not the only thing that stages through there: so do the Python, uv and VC++ downloads.A compiler-free resolver.
Initialize-StudioFinalPathNativeTypecaches the compile result, skips compiling entirely under Constrained Language Mode, and retries exactly once with a private%TEMP%.Get-StudioLexicalPathresolves reparse points component-wise from the root, since a link on a parent component is the ordinary Windows shape.Resolve-StudioFinalPathInfocarries anExactflag soTest-StudioPathEqualcan answer "unknown" instead of "different", whichGet-StudioRuntimeMutexNamesalready reads as "take both locks and fail closed".A private temp directory the uninstaller can reclaim. It outlives the install on purpose, since a Studio started from it inherits it as its own
%TEMP%, so it sits underLOCALAPPDATA\"Unsloth Studio"\temp(deleted wholesale as the data dir) and~\.unsloth\.cache\temp(on the explicit sibling list). Not directly under~\.unsloth: that directory is removed only when empty, so anything left there would stop the uninstaller clearing it at all.An in-use check that no longer fails open.
Get-RunningStudioVenvProcessescalled the compiled helper insidecatch { continue }. On a host that could not compile, every process was skipped, the scan reported nothing running, and the installer would have overwritten a venv that Studio had open. It now falls back to the process image path andWin32_Process, and warns when it is running degraded.Does it break anything
No. With the native helper present, every output is byte-identical to before: the install mutex name, both runtime lock names, path identity and the process scan. That is asserted, not assumed, by diffing the new code against the pre-fix code with a faithful stand-in resolver.
install.ps1is the Windows entry point only.install.shserves Linux, macOS and WSL and is untouched; its references toinstall.ps1are parity comments, and none of the decisions they name are in this diff. No frontend file changes, so no browser is involved. The change runs upstream of every GPU decision andGet-TauriTorchIndexFamily,Get-TauriGpuBranch,Get-HostMachineArchandGet-TauriDiagArchare unchanged.The
--shortcuts-onlymarker the CLI validates a fetched installer by is intact, and the file is still far under the 8 MB fetch cap.How it was tested
New
tests/python/test_windows_installer_addtype_fallback.py, 21 tests, running underpwshon any platform. Every one was mutation tested: the production code was broken in the specific way each test names, and the test was confirmed to fail. Twelve of them cover the shapes of(Get-Item).Targetthat Windows PowerShell 5.1 returns and this repo's CI hosts cannot produce, including the collection form that is not an[array], the\??\device prefix a junction stores, relative targets, and the null target reported by system junctions and Store AppExecLinks.Beyond the suite, simulations over:
.venv, legacyunsloth_studio, Tauri root, fresh, shortcuts-only, redirected profile--tauricustom-root guard, native and degraded(Get-Item).Targetshape 5.1 returns[array]Existing suites: 5754 passed across
tests/andunsloth_cli/tests, 48/48 POSIX installer shell tests, 20/20 cross-platform Studio PowerShell tests. The remaining failures in those runs reproduce identically without this change.Three defects the simulations found and fixed, rather than shipping:
(Get-Item).Targetis a collection on 5.1 and not an[array], so the container test never fired and a junction target would have been space-joined into a path that does not exist;Remove-Item -Recursefollows junctions on 5.1, so the stale sweep could have emptied whatever a plantedust-*link pointed at; and--shortcuts-only, the pathunsloth studio updatetakes, returned before the temp restore.One limitation worth stating: there is no Windows host in the loop here, so PowerShell 5.1's CodeDom path and the
Remove-Item -Recursereparse hazard are covered by reasoning plus source-contract assertions rather than by execution. The Windows-only tests intest_windows_installer_concurrency_guard.pycover them on CI.