Skip to content

Studio: stop a Windows update deleting the venv it is running from - #11248

Merged
danielhanchen merged 9 commits into
unslothai:mainfrom
LeoBorcherding:fix/setup-ps1-stale-venv-in-place-rebuild
Sep 18, 2026
Merged

danielhanchen merged 9 commits into
unslothai:mainfrom
LeoBorcherding:fix/setup-ps1-stale-venv-in-place-rebuild

Conversation

@LeoBorcherding

@LeoBorcherding LeoBorcherding commented Sep 18, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes #11247 (the half-deleted venv half; the duplicate repairs are in #11249).

What this fixes

On Windows, unsloth studio update runs setup.ps1 from the managed venv's own python.exe. When setup decides the venv is stale because the torch flavor no longer matches the host, the direct-update branch did Remove-Item -Recurse on that venv. Windows will not delete a running executable, so the delete removed everything it reached and then failed on Scripts\python.exe. You are left with a venv that has python.exe and no unsloth_cli. It cannot start, and it cannot update or repair itself either, because both of those start from that same interpreter.

How I ran into it

Swapped an RTX 5060 Ti for an RX 6500 XT and opened the desktop app. Backend came up chat-only with "PyTorch cannot use them (torch_cuda_unavailable, installed 2.10.0+cu130)", so I hit update. Setup got the host right and then did the one thing it could not do:

  gpu            AMD ROCm (gfx1034)
                 Python found: <studio_home>\unsloth_studio\Scripts\python.exe
                 Stale venv detected (torch cu130 != required rocm) -- rebuilding...
   [ERROR] Could not remove stale venv: Access to the path 'python.exe' is denied.
           Close any running Unsloth/Python processes and re-run setup.
[TAURI:ERROR] Could not remove the stale environment at <studio_home>\unsloth_studio
Manual recovery copy retained at: <studio_home>\unsloth_studio\Scripts\unsloth.exe.update-backup

"Close any running Unsloth/Python processes" cannot be followed here. The process holding python.exe is the CLI that launched setup: update.rs spawns python.exe -c "from unsloth_cli import app" studio update from the venv, and _run_setup_script Popens PowerShell and waits, so the venv interpreter is always an ancestor of setup.ps1. From there the desktop was stuck:

19:08:46 Starting backend: ...\unsloth_studio\Scripts\python.exe -X utf8 -c import sys, os; ... from unsloth_cli import app ...
19:08:46 [backend] [stderr] ModuleNotFoundError: No module named 'unsloth_cli'
19:08:47 [ERROR] Backend process stdout closed unexpectedly (crash detected)
19:08:48 Managed preflight: install probe result Stale { bin: "...\Scripts\unsloth.exe", reason: "cli_unusable" }
19:08:52 [update] Starting backend update via "...\unsloth_studio\Scripts\unsloth.exe"
19:08:52 [update][stderr] ModuleNotFoundError: No module named 'unsloth_cli'
19:08:52 [WARN] Managed repair update failed, falling back to bundled installer: Update exited with code 1

The bundled installer did rebuild it in the end, because the repair path falls through to it and that path keeps a rollback copy. But that is the desktop recovering from the update, not the update working.

I checked the mechanism on its own with a throwaway venv whose python was sleeping: Rename-Item on the directory succeeds, whole tree, atomically. Remove-Item -Recurse deletes every sibling and then stops at the exe. tests/studio/test_amd_venv_repair_loop.ps1 already states this for the install.ps1-managed branch ("install.ps1 runs setup through the venv's own unsloth.exe"), and that branch was changed to reinstall torch in place. The direct-update branch has exactly the same shape and still deleted.

What changes

studio/setup.ps1

  • New Get-SetupHostInterpreterInVenv. Returns the interpreter setup was launched from when it lives under $VenvDir. It reads UNSLOTH_SETUP_HOST_PYTHON first, then walks Win32_Process parents from $PID, bounded to 8 hops. Any failure in the walk reads as "not inside", so the worst case is the old behaviour.
  • A direct update that finds itself inside the venv now takes the same route as the installer-managed branch: $script:PinChangedForceReinstall = $true, $shouldRebuild = $false, reinstall PyTorch in place. Every torch arm (cuda, rocm, xpu, cpu) already honours that flag.
  • When a rebuild does run (setup.ps1 run by hand from a checkout, nothing inside the venv), the venv is renamed to unsloth_studio.stale-<timestamp> first and the moved copy is deleted best-effort. A lock now fails the rename whole and the environment is untouched; leftovers from a partial delete of the moved copy are swept on the next run. The [TAURI:ERROR] text on a lock is unchanged so nothing downstream keys on new wording, and the human-readable line now says the environment was left as it was.

unsloth_cli/commands/studio.py

  • _run_setup_script passes UNSLOTH_SETUP_HOST_PYTHON=sys.executable, so a current CLI never needs the process walk.

Tests

  • tests/test_studio_install_workspace_guard.py: the custom-root guard test anchors on the rename now. Two new source tests: the stale venv is moved aside rather than deleted in place, and the in-place route is chosen before the rebuild branch. TestSetupHostInterpreterInVenv runs the shipped helper under pwsh for hint-inside, hint-outside and no-hint, and on Windows launches it from a real venv python.exe so the process walk is exercised for real.
  • tests/studio/install/test_windows_torch_flavor_invariant.py and tests/studio/test_amd_venv_repair_loop.ps1: anchors moved from Remove-Item to Rename-Item, plus two new checks in the .ps1 for the in-place route and the rename.
  • unsloth_cli/tests/test_studio_update_host_python.py: both the POSIX and Windows spawns carry the interpreter, and --verbose still does too.

Verification

  • Helper probed live on this machine under pwsh 7.6 and Windows PowerShell 5.1: hint inside gives the path, hint outside gives null, no hint gives null, and launched from a venv python the walk finds that python.
  • pytest on the three touched Python test files: every new and changed test passes on Windows. The remaining failures in the guard file are the bash and symlink cases and are identical on upstream main.
  • pwsh -File tests/studio/test_amd_venv_repair_loop.ps1: the new checks pass; the 8 bounded-probe failures are pre-existing on this host.
  • Whole-file parse of setup.ps1 is clean, ruff check and scripts/run_ruff_format.py are clean on the Python.

What I have not done is drive an actual cu130 to rocm in-place reinstall through unsloth studio update. It is the code path install.ps1 already takes on the same host, and it is what the installer fallback ended up doing on my machine, but a run on a real AMD box before merge would be sensible.

`unsloth studio update` runs setup.ps1 from the managed venv's own python.exe.
When the torch flavor no longer matches the host (here: cu130 installed, an
AMD GPU now in the machine, so rocm required), the direct-update branch did
Remove-Item -Recurse on that venv. Windows will not delete a running image, so
the delete emptied Lib\ and failed on Scripts\python.exe, leaving a venv with
no unsloth_cli and no rollback copy; the desktop's update and repair both start
from that interpreter, so neither could recover it.

setup.ps1 now knows when it runs from inside the venv (the CLI names its
interpreter as UNSLOTH_SETUP_HOST_PYTHON; a bounded Win32_Process walk covers
an older CLI) and takes the in-place PyTorch reinstall install.ps1 already uses
for the same situation. A rebuild that does run renames the venv aside first,
so a lock fails whole instead of after deleting most of the tree.
@danielhanchen

Copy link
Copy Markdown
Member

Confirmed the stale-venv branch in studio/setup.ps1 still does Remove-Item on the venv that the update interpreter is running from, so the move-aside plus in-place reinstall route looks like the right shape; please mark it ready for review once you are happy with it and we will get it reviewed.

@danielhanchen danielhanchen self-assigned this Sep 18, 2026
…arator-correct

The new direct-update escape sat ahead of the nvidia-smi cu* preservation guard. Its
condition is true for every stale direct update, because the desktop always runs setup
from the venv's own python.exe, so it consumed $shouldRebuild before the narrower guard
was tested and that guard could never fire.

That guard does two things: it keeps the venv, and it publishes
$script:PreservedInstallerTorchTag, which is what holds the index selection on the cu*
arm. Shadowed, the tag stayed null while the in-place route set
$script:PinChangedForceReinstall, and the pair reached the CPU arm. Replaying the
shipped ladder over 320 enumerated cells, base and head agree on 289; the one cell that
is neither an intended fix nor a match is an unpinned direct update with a cu128 venv
and a silent nvidia-smi:

  base: uv pip install torch torchvision torchaudio --index-url .../whl/cu128
  head: uv pip install torch torchvision torchaudio --force-reinstall --index-url .../whl/cpu

which is the CPU-only update unslothai#9857 added that guard to stop. Moving the block below the
guard leaves all 30 intended fixes and restores that cell; base and fixed now differ in
0 cells where the venv is kept on both sides.

Get-SetupHostInterpreterInVenv built its containment prefix with a literal backslash.
.NET returns '/'-separated paths from GetFullPath off Windows and treats '\' as an
ordinary filename character, so the prefix matched nothing and the helper answered null
for every input. Only Windows runs setup.ps1 for real, but the shipped pwsh tests run
everywhere, and test_the_cli_hint_names_the_venv_interpreter was red on every non-Windows
runner while its sibling passed vacuously. Build the prefix from
DirectorySeparatorChar instead.

Also move the stale-venv sweep out of the rebuild branch, so an install that renamed a
venv aside, failed to delete the copy under a lock, and thereafter only ever repairs in
place still collects it, and give the destination a pid suffix so two rebuilds inside
one second cannot collide on a name.
…deleting it

Moving the sweep out of the rebuild branch put it ahead of the custom-root ownership
guard, so that guard can no longer cover it, and "$_venvLeaf.stale-*" is a wildcard
rather than a proof of ownership: a user's own unsloth_studio.stale-backup matches it and
was deleted on an ordinary healthy update.

Validate the way install.ps1 already validates its own rollback sweep
(Test-StudioVenvRollbackMustBePreserved): refuse anything outside the generated
timestamp-PID shape, refuse reparse points, and spare a copy whose owning process is
still alive, which is a concurrent setup's rescue copy rather than our litter. Enumerate
with -Force too, so a leftover that picked up the hidden attribute is not skipped
forever by the sweep meant to collect it.

test_setup_ps1_stale_sweep_only_removes_its_own_litter runs the shipped sweep under pwsh
against real directories rather than reading it: an abandoned copy in the generated shape
goes, a stale-backup directory and a live owner's copy stay, and the live venv is never
touched. It fails on the unvalidated sweep with "a directory outside the generated name
shape must be left alone".

Routing is unchanged: replaying the ladder over the same 320 cells still gives 30 fixes,
0 violations and 0 newly wiped cells against base.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 18, 2026
sys.executable is the managed venv's python.exe on the path that matters, where the
desktop spawns the managed CLI. It is not on the others: a pip-installed CLI, a repo
checkout and a staged run all put an interpreter here that lives nowhere near $VenvDir.

That is already safe, because setup.ps1 tests containment itself and a value outside the
venv reads as 'not inside', which keeps the pre-existing rebuild. The comment asserted
the guarantee as fact, which is the kind of thing that later justifies dropping the
containment test as redundant. Say which path it holds on and who checks.
The sweep decided what to delete from a capture group it reached through $Matches after
a -notmatch. Which of -match and -notmatch populates $Matches, and on which result, is
version-sensitive in exactly the way unslothai#9857's empty-string-vs-null was, and a read that
comes back empty here feeds [int]::TryParse and skips the entry. Failing safe is the good
case; a wrong pid is not. Take the group off a [regex]::Match whose semantics do not
move between Windows PowerShell 5.1 and 7.x.
Opening comment-reduction pass over this PR's own additions only, not the surrounding
file: 62 added comment lines to 43. Every surviving line names a mistake the next reader
would otherwise make, which is why the ordering rationale and the ownership rationale
keep a line each. AST-verified comment-only against b30af0c.
The in-place-route block restated the undeletable-running-image mechanism the function
header above it already gives, so it keeps only what is local to the decision: the issue
number, and that a hand-run checkout still rebuilds. setup.ps1 additions 32 comment lines
to 27. AST-verified comment-only against 7d0b1da.
Three things found while simulating this PR, all in the new code rather than in what it replaced.

The sweep runs on every qualifying setup, including one that rebuilds nothing, and it runs ahead
of the custom-root guard. Its only authority for a recursive delete was a name, so a directory
named unsloth_studio.stale-<14 digits>-<pid> next to the venv was deleted on a run that otherwise
changed nothing, and also on a custom UNSLOTH_STUDIO_HOME whose venv the rebuild then refused to
touch for want of an Unsloth sentinel. Both are now refused: the guard predicate is hoisted so the
sweep asks the same ownership question the rebuild asks, and a candidate must carry pyvenv.cfg,
the studio-owned marker, or the new .unsloth-studio-stale marker that the rename drops into the
copy it moved. A copy too far gone to carry any of the three is named and left alone rather than
deleted blind. The marker is rewritten when the delete after the rename fails, so the litter that
branch announces is still litter the next run can identify.

Get-SetupHostInterpreterInVenv accepted a hint that named nothing. The hint is an inherited
environment variable and can outlive what it names, and a stale one pointing inside the venv would
route a venv that genuinely needs rebuilding into an in-place repair with no interpreter to
perform it. It must now name a file that is there. The parent walk also compares creation dates
before following ParentProcessId, which is what Microsoft's own Win32_Process guidance says to do
about reused process ids.

The rename destination took the timestamp and the pid but had no retry, while install.sh's
_start_studio_venv_replacement, which this mirrors, appends a numeric suffix until the name is
free. One process can reach this twice inside a second, and a copy it left earlier can still be on
disk because its delete failed. A taken name now takes a bounded suffix, and the sweep's shape
recognises it, or the copy it names could never be cleaned up.

Tests: the sweep test now drives the shipped sweep over six directories, including one that wears
the name and holds no environment and one whose name took a collision suffix; a new test refuses
an unclaimable custom root and then, as a negative control, sweeps the same tree once the owned
marker is present; the helper test adds a hint naming a deleted path, a directory, and Scripts
itself, with the real interpreter as its control.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 18, 2026
@danielhanchen
danielhanchen marked this pull request as ready for review September 18, 2026 15:17
@danielhanchen
danielhanchen self-requested a review as a code owner September 18, 2026 15:17
@danielhanchen
danielhanchen merged commit 22192f7 into unslothai:main Sep 18, 2026
9 of 62 checks passed
shimmyshimmer pushed a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Sep 18, 2026
danielhanchen added a commit that referenced this pull request Sep 18, 2026
…1285)

tests/studio/test_pwsh_calls_use_the_shared_runner.py is red on main. Two changes that landed
today added pwsh calls through subprocess.run: the stale-copy sweep and helper tests in #11248,
and the temp-scanner tests carried over in #11280. Both share one $XDG_CACHE_HOME/powershell
startup cache with every other xdist worker, which is the failure mode that test exists to
prevent, and which reads as a Windows-installer regression when it hits.

run_pwsh takes the argv the call site already built, so each is a one-word change and no
invocation flags move.
shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
…nslothai#11248)

* setup.ps1: stop a stale-venv rebuild deleting the venv it runs from

`unsloth studio update` runs setup.ps1 from the managed venv's own python.exe.
When the torch flavor no longer matches the host (here: cu130 installed, an
AMD GPU now in the machine, so rocm required), the direct-update branch did
Remove-Item -Recurse on that venv. Windows will not delete a running image, so
the delete emptied Lib\ and failed on Scripts\python.exe, leaving a venv with
no unsloth_cli and no rollback copy; the desktop's update and repair both start
from that interpreter, so neither could recover it.

setup.ps1 now knows when it runs from inside the venv (the CLI names its
interpreter as UNSLOTH_SETUP_HOST_PYTHON; a bounded Win32_Process walk covers
an older CLI) and takes the in-place PyTorch reinstall install.ps1 already uses
for the same situation. A rebuild that does run renames the venv aside first,
so a lock fails whole instead of after deleting most of the tree.

* setup.ps1: order the in-place route last, and make the venv probe separator-correct

The new direct-update escape sat ahead of the nvidia-smi cu* preservation guard. Its
condition is true for every stale direct update, because the desktop always runs setup
from the venv's own python.exe, so it consumed $shouldRebuild before the narrower guard
was tested and that guard could never fire.

That guard does two things: it keeps the venv, and it publishes
$script:PreservedInstallerTorchTag, which is what holds the index selection on the cu*
arm. Shadowed, the tag stayed null while the in-place route set
$script:PinChangedForceReinstall, and the pair reached the CPU arm. Replaying the
shipped ladder over 320 enumerated cells, base and head agree on 289; the one cell that
is neither an intended fix nor a match is an unpinned direct update with a cu128 venv
and a silent nvidia-smi:

  base: uv pip install torch torchvision torchaudio --index-url .../whl/cu128
  head: uv pip install torch torchvision torchaudio --force-reinstall --index-url .../whl/cpu

which is the CPU-only update unslothai#9857 added that guard to stop. Moving the block below the
guard leaves all 30 intended fixes and restores that cell; base and fixed now differ in
0 cells where the venv is kept on both sides.

Get-SetupHostInterpreterInVenv built its containment prefix with a literal backslash.
.NET returns '/'-separated paths from GetFullPath off Windows and treats '\' as an
ordinary filename character, so the prefix matched nothing and the helper answered null
for every input. Only Windows runs setup.ps1 for real, but the shipped pwsh tests run
everywhere, and test_the_cli_hint_names_the_venv_interpreter was red on every non-Windows
runner while its sibling passed vacuously. Build the prefix from
DirectorySeparatorChar instead.

Also move the stale-venv sweep out of the rebuild branch, so an install that renamed a
venv aside, failed to delete the copy under a lock, and thereafter only ever repairs in
place still collects it, and give the destination a pid suffix so two rebuilds inside
one second cannot collide on a name.

* setup.ps1: let the stale-venv sweep prove a directory is ours before deleting it

Moving the sweep out of the rebuild branch put it ahead of the custom-root ownership
guard, so that guard can no longer cover it, and "$_venvLeaf.stale-*" is a wildcard
rather than a proof of ownership: a user's own unsloth_studio.stale-backup matches it and
was deleted on an ordinary healthy update.

Validate the way install.ps1 already validates its own rollback sweep
(Test-StudioVenvRollbackMustBePreserved): refuse anything outside the generated
timestamp-PID shape, refuse reparse points, and spare a copy whose owning process is
still alive, which is a concurrent setup's rescue copy rather than our litter. Enumerate
with -Force too, so a leftover that picked up the hidden attribute is not skipped
forever by the sweep meant to collect it.

test_setup_ps1_stale_sweep_only_removes_its_own_litter runs the shipped sweep under pwsh
against real directories rather than reading it: an abandoned copy in the generated shape
goes, a stale-backup directory and a live owner's copy stay, and the live venv is never
touched. It fails on the unvalidated sweep with "a directory outside the generated name
shape must be left alone".

Routing is unchanged: replaying the ladder over the same 320 cells still gives 30 fixes,
0 violations and 0 newly wiped cells against base.

* studio.py: say that UNSLOTH_SETUP_HOST_PYTHON is a hint, not a promise

sys.executable is the managed venv's python.exe on the path that matters, where the
desktop spawns the managed CLI. It is not on the others: a pip-installed CLI, a repo
checkout and a staged run all put an interpreter here that lives nowhere near $VenvDir.

That is already safe, because setup.ps1 tests containment itself and a value outside the
venv reads as 'not inside', which keeps the pre-existing rebuild. The comment asserted
the guarantee as fact, which is the kind of thing that later justifies dropping the
containment test as redundant. Say which path it holds on and who checks.

* setup.ps1: read the stale-venv pid from an explicit Match, not $Matches

The sweep decided what to delete from a capture group it reached through $Matches after
a -notmatch. Which of -match and -notmatch populates $Matches, and on which result, is
version-sensitive in exactly the way unslothai#9857's empty-string-vs-null was, and a read that
comes back empty here feeds [int]::TryParse and skips the entry. Failing safe is the good
case; a wrong pid is not. Take the group off a [regex]::Match whose semantics do not
move between Windows PowerShell 5.1 and 7.x.

* Tighten the comments added by this change

Opening comment-reduction pass over this PR's own additions only, not the surrounding
file: 62 added comment lines to 43. Every surviving line names a mistake the next reader
would otherwise make, which is why the ordering rationale and the ownership rationale
keep a line each. AST-verified comment-only against b30af0c.

* Second comment sweep over this change's own additions

The in-place-route block restated the undeletable-running-image mechanism the function
header above it already gives, so it keeps only what is local to the decision: the issue
number, and that a hand-run checkout still rebuilds. setup.ps1 additions 32 comment lines
to 27. AST-verified comment-only against 7d0b1da.

* Make the stale-copy sweep prove ownership before it deletes

Three things found while simulating this PR, all in the new code rather than in what it replaced.

The sweep runs on every qualifying setup, including one that rebuilds nothing, and it runs ahead
of the custom-root guard. Its only authority for a recursive delete was a name, so a directory
named unsloth_studio.stale-<14 digits>-<pid> next to the venv was deleted on a run that otherwise
changed nothing, and also on a custom UNSLOTH_STUDIO_HOME whose venv the rebuild then refused to
touch for want of an Unsloth sentinel. Both are now refused: the guard predicate is hoisted so the
sweep asks the same ownership question the rebuild asks, and a candidate must carry pyvenv.cfg,
the studio-owned marker, or the new .unsloth-studio-stale marker that the rename drops into the
copy it moved. A copy too far gone to carry any of the three is named and left alone rather than
deleted blind. The marker is rewritten when the delete after the rename fails, so the litter that
branch announces is still litter the next run can identify.

Get-SetupHostInterpreterInVenv accepted a hint that named nothing. The hint is an inherited
environment variable and can outlive what it names, and a stale one pointing inside the venv would
route a venv that genuinely needs rebuilding into an in-place repair with no interpreter to
perform it. It must now name a file that is there. The parent walk also compares creation dates
before following ParentProcessId, which is what Microsoft's own Win32_Process guidance says to do
about reused process ids.

The rename destination took the timestamp and the pid but had no retry, while install.sh's
_start_studio_venv_replacement, which this mirrors, appends a numeric suffix until the name is
free. One process can reach this twice inside a second, and a copy it left earlier can still be on
disk because its delete failed. A taken name now takes a bounded suffix, and the sweep's shape
recognises it, or the copy it names could never be cleaned up.

Tests: the sweep test now drives the shipped sweep over six directories, including one that wears
the name and holds no environment and one whose name took a collision suffix; a new test refuses
an unclaimable custom root and then, as a negative control, sweeps the same tree once the owned
marker is present; the helper test adds a hint naming a deleted path, a directory, and Scripts
itself, with the real interpreter as its control.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

---------

Co-authored-by: Daniel Han <[email protected]>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
…slothai#11285)

tests/studio/test_pwsh_calls_use_the_shared_runner.py is red on main. Two changes that landed
today added pwsh calls through subprocess.run: the stale-copy sweep and helper tests in unslothai#11248,
and the temp-scanner tests carried over in unslothai#11280. Both share one $XDG_CACHE_HOME/powershell
startup cache with every other xdist worker, which is the failure mode that test exists to
prevent, and which reads as a Windows-installer regression when it hits.

run_pwsh takes the argv the call site already built, so each is a one-word change and no
invocation flags move.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Studio (Windows): update after a GPU vendor change half-deletes the venv, and Retry starts duplicate repairs

2 participants