Repository navigation
Studio: stop a Windows update deleting the venv it is running from - #11248
Merged
danielhanchen merged 9 commits intoSep 18, 2026
Merged
danielhanchen merged 9 commits into
danielhanchen merged 9 commits into
Conversation
`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.
This was referenced Sep 18, 2026
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. |
…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.
This was referenced Sep 18, 2026
danielhanchen
added a commit
to danielhanchen/unsloth-staging-2
that referenced
this pull request
Sep 18, 2026
…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.
This was referenced Sep 18, 2026
shimmyshimmer
pushed a commit
to shimmyshimmer/unsloth-staging-4
that referenced
this pull request
Sep 18, 2026
danielhanchen
added a commit
to danielhanchen/unsloth-staging-2
that referenced
this pull request
Sep 18, 2026
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
marked this pull request as ready for review
September 18, 2026 15:17
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes #11247 (the half-deleted venv half; the duplicate repairs are in #11249).
What this fixes
On Windows,
unsloth studio updaterunssetup.ps1from the managed venv's ownpython.exe. When setup decides the venv is stale because the torch flavor no longer matches the host, the direct-update branch didRemove-Item -Recurseon that venv. Windows will not delete a running executable, so the delete removed everything it reached and then failed onScripts\python.exe. You are left with a venv that haspython.exeand nounsloth_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:
"Close any running Unsloth/Python processes" cannot be followed here. The process holding
python.exeis the CLI that launched setup:update.rsspawnspython.exe -c "from unsloth_cli import app" studio updatefrom the venv, and_run_setup_scriptPopens PowerShell and waits, so the venv interpreter is always an ancestor of setup.ps1. From there the desktop was stuck: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-Itemon the directory succeeds, whole tree, atomically.Remove-Item -Recursedeletes every sibling and then stops at the exe.tests/studio/test_amd_venv_repair_loop.ps1already 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.ps1Get-SetupHostInterpreterInVenv. Returns the interpreter setup was launched from when it lives under$VenvDir. It readsUNSLOTH_SETUP_HOST_PYTHONfirst, then walksWin32_Processparents from$PID, bounded to 8 hops. Any failure in the walk reads as "not inside", so the worst case is the old behaviour.$script:PinChangedForceReinstall = $true,$shouldRebuild = $false, reinstall PyTorch in place. Every torch arm (cuda, rocm, xpu, cpu) already honours that flag.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_scriptpassesUNSLOTH_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.TestSetupHostInterpreterInVenvruns the shipped helper underpwshfor hint-inside, hint-outside and no-hint, and on Windows launches it from a real venvpython.exeso the process walk is exercised for real.tests/studio/install/test_windows_torch_flavor_invariant.pyandtests/studio/test_amd_venv_repair_loop.ps1: anchors moved fromRemove-ItemtoRename-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--verbosestill does too.Verification
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.setup.ps1is clean,ruff checkandscripts/run_ruff_format.pyare 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.