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.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
fix(studio/install): keep the rollback reference when a venv move stops partway (#7810) (#7823)
Tai An6ea2b91d04c1
diff --git a/install.ps1 b/install.ps1index 9d4118277d9..e80b0626df2 100644--- a/install.ps1+++ b/install.ps1@@ -1828,6 +1828,7 @@ exit 0$script:StudioVenvRollbackDir = $null$script:StudioVenvRollbackTarget = $VenvDir$script:StudioVenvRollbackActive = $false+ $script:StudioVenvRollbackPartial = $falsefunction Test-VenvPythonReady {param([Parameter(Mandatory = $true)][string]$PythonExe)@@ -1875,16 +1876,35 @@ exit 0$script:StudioVenvRollbackDir = $candidate$script:StudioVenvRollbackTarget = $ExistingDir$script:StudioVenvRollbackActive = $true+ $script:StudioVenvRollbackPartial = $false# Publish the rollback state before the atomic rename so interruption# cannot land after Move-Item but before cleanup knows where the old venv went.try {Move-Item -LiteralPath $ExistingDir -Destination $candidate -ErrorAction Stop} catch {# A collision or ordinary rename failure leaves the original in place.- # Keep state active only when the rename happened before interruption.- if (Test-Path -LiteralPath $ExistingDir) {+ # On Windows an open handle inside the tree fails the rename *partway*+ # instead: entries walked before the locked one land at $candidate while+ # the rest stay at $ExistingDir. Reading only $ExistingDir scores that+ # split tree as "the rename never happened" and drops the sole reference+ # to where the other half went, so the caller can neither restore nor+ # report it. Clear the state only when the destination is genuinely+ # absent; when both paths exist keep it active so Restore-StudioVenvRollback+ # can reverse the partial move, and name both locations either way.+ $candidateExists = Test-Path -LiteralPath $candidate+ if ((Test-Path -LiteralPath $ExistingDir) -and (-not $candidateExists)) {$script:StudioVenvRollbackActive = $false$script:StudioVenvRollbackDir = $null+ } elseif ($candidateExists -and (Test-Path -LiteralPath $ExistingDir)) {+ # Flag the split: both paths now hold halves of the *same* previous+ # environment, so restoration must merge them rather than clear the+ # destination first the way the committed-replacement path does.+ $script:StudioVenvRollbackPartial = $true+ Write-Host "[WARN] Moving the existing environment aside stopped partway -- files are in both places." -ForegroundColor Yellow+ Write-Host " still in place: $ExistingDir" -ForegroundColor Yellow+ Write-Host " moved aside: $candidate" -ForegroundColor Yellow+ Write-Host " A running 'unsloth studio' process usually holds a file open here." -ForegroundColor Yellow+ Write-Host " Close Unsloth Studio and re-run the installer to reverse the move." -ForegroundColor Yellow}throw}@@ -1948,15 +1968,90 @@ exit 0}}+ function Merge-StudioVenvRollbackTree {+ # Moves every entry of $Source into $Destination without ever overwriting or+ # deleting what is already there. Returns $true only when $Source ends up+ # empty and removed, i.e. the two halves were fully reunited.+ param(+ [Parameter(Mandatory = $true)][string]$Source,+ [Parameter(Mandatory = $true)][string]$Destination+ )+ if (-not (Test-Path -LiteralPath $Destination)) {+ [System.IO.Directory]::CreateDirectory($Destination) | Out-Null+ }+ $complete = $true+ foreach ($entry in @(Get-ChildItem -LiteralPath $Source -Force -ErrorAction Stop)) {+ # Not $destination: PowerShell names are case-insensitive, so that would+ # reassign the $Destination parameter and nest every later sibling under+ # the previous entry's name.+ $entryTarget = Join-Path $Destination $entry.Name+ if (-not (Test-Path -LiteralPath $entryTarget)) {+ Move-Item -LiteralPath $entry.FullName -Destination $entryTarget -ErrorAction Stop+ continue+ }+ # Same relative path on both sides: the move stopped inside this subtree.+ # Recurse so the halves reunite -- Move-Item -Force would overwrite the+ # half that never moved, which is exactly the data this path protects.+ # A junction on either side is a leaf, not a subtree: recursing through one+ # moves files to wherever it points, outside $StudioHome. Keep both instead.+ # Get-Item both sides: Get-ChildItem has reported Attributes inconsistently.+ $entryItem = Get-Item -LiteralPath $entry.FullName -Force -ErrorAction Stop+ $targetItem = Get-Item -LiteralPath $entryTarget -Force -ErrorAction Stop+ $linked = (($entryItem.Attributes -band [System.IO.FileAttributes]::ReparsePoint) -ne 0) -or+ (($targetItem.Attributes -band [System.IO.FileAttributes]::ReparsePoint) -ne 0)+ if ($entryItem.PSIsContainer -and $targetItem.PSIsContainer -and -not $linked) {+ if (-not (Merge-StudioVenvRollbackTree -Source $entry.FullName -Destination $entryTarget)) {+ $complete = $false+ }+ continue+ }+ Write-Host "[WARN] Kept both copies of $($entry.Name)" -ForegroundColor Yellow+ Write-Host " $($entry.FullName)" -ForegroundColor Yellow+ Write-Host " $entryTarget" -ForegroundColor Yellow+ $complete = $false+ }+ if ($complete) {+ Remove-Item -LiteralPath $Source -Force -ErrorAction SilentlyContinue+ return (-not (Test-Path -LiteralPath $Source))+ }+ return $false+ }+function Restore-StudioVenvRollback {if (-not $script:StudioVenvRollbackActive) { return }$backup = $script:StudioVenvRollbackDir$target = $script:StudioVenvRollbackTargetif (-not $backup -or -not (Test-Path -LiteralPath $backup)) {$script:StudioVenvRollbackActive = $false+ $script:StudioVenvRollbackPartial = $falsereturn}substep "restoring previous environment after failed install..." "Yellow"+ if ($script:StudioVenvRollbackPartial) {+ # $target is not an incomplete *new* environment here -- it is the half of+ # the previous one the interrupted move left behind. Removing it first,+ # the way the branch below does, would delete files that exist nowhere+ # else and "restore" a corrupted venv. Merge the halves instead.+ $merged = $false+ try {+ $merged = Merge-StudioVenvRollbackTree -Source $backup -Destination $target+ } catch {+ Write-Host "[WARN] Could not merge $backup back into $target" -ForegroundColor Yellow+ Write-Host " $($_.Exception.Message)" -ForegroundColor Yellow+ }+ if ($merged) {+ substep "restored previous environment"+ $script:StudioVenvRollbackActive = $false+ $script:StudioVenvRollbackDir = $null+ $script:StudioVenvRollbackPartial = $false+ } else {+ Write-Host "[WARN] The previous environment is still split in two." -ForegroundColor Yellow+ Write-Host " still in place: $target" -ForegroundColor Yellow+ Write-Host " moved aside: $backup" -ForegroundColor Yellow+ Write-Host " Close Unsloth Studio and re-run the installer to finish reversing the move." -ForegroundColor Yellow+ }+ return+ }try {if (Test-Path -LiteralPath $target) {if (-not (Remove-StudioVenvTreeWithRetry -Path $target -Label "incomplete environment")) {@@ -1980,6 +2075,7 @@ exit 0# backup so interruption cannot restore a partially deleted environment.$script:StudioVenvRollbackActive = $false$script:StudioVenvRollbackDir = $null+ $script:StudioVenvRollbackPartial = $falseif ($backup -and (Test-Path -LiteralPath $backup)) {Remove-StudioVenvTreeWithRetry -Path $backup -Label "environment rollback" | Out-Null}diff --git a/tests/python/test_windows_python_venv_hardening.py b/tests/python/test_windows_python_venv_hardening.pyindex 87c545aa68a..cba4e7335bc 100644--- a/tests/python/test_windows_python_venv_hardening.py+++ b/tests/python/test_windows_python_venv_hardening.py@@ -27,6 +27,23 @@ def _extract(pattern: str, source: str) -> str:return match.group(0)+def _link_dir(link: Path, target: Path) -> None:+ """Directory link, without needing SeCreateSymbolicLinkPrivilege on Windows.++ A junction is also the reparse point a Windows venv actually runs into, so this+ is the faithful construct there rather than a stand-in.+ """+ if os.name == "nt":+ subprocess.run(+ ["cmd", "/c", "mklink", "/J", str(link), str(target)],+ check = True,+ capture_output = True,+ text = True,+ )+ else:+ os.symlink(target, link, target_is_directory = True)++def _run_powershell(shell: str, script: str, env: dict[str, str]) -> str:result = subprocess.run([shell, "-NoProfile", "-NonInteractive", "-Command", script],@@ -122,6 +139,235 @@ Write-Output (Get-VenvBaseHome -VenvRoot $env:TEST_VENV_ROOT)assert _run_powershell(shell, script, env) == str(expected)[email protected](not POWERSHELLS, reason = "PowerShell is unavailable")[email protected]("shell", POWERSHELLS)[email protected]("case", ["partial", "clean"])+def test_rollback_keeps_state_when_the_move_stops_partway(tmp_path: Path, shell: str, case: str):+ """A half-finished rename must not be read as "the rename never happened".++ On Windows an open handle inside the tree fails Move-Item after it has already+ walked part of it, so entries exist at both paths. Testing only the source then+ clears StudioVenvRollbackDir -- the sole record of where the other half went --+ and the environment is stranded with no way to restore or even name it.+ """+ source = INSTALL_PS1.read_text(encoding = "utf-8")+ rollback = _extract(r" function Start-StudioVenvRollback \{.*?\n \}\n", source)+ existing = tmp_path / "unsloth_studio"+ (existing / "Scripts").mkdir(parents = True)+ (existing / "Scripts" / "unsloth.exe").write_text("locked", encoding = "utf-8")++ script = f"""+$ErrorActionPreference = "Stop"+$StudioHome = $env:TEST_STUDIO_HOME+function substep {{ param([string]$Text, [string]$Color) }}+function Move-Item {{+ param([string]$LiteralPath, [string]$Destination, [string]$ErrorAction, [switch]$Force)+ if ($env:TEST_ROLLBACK_CASE -eq "partial") {{+ # The entries walked before the locked one are already at the destination.+ [System.IO.Directory]::CreateDirectory((Join-Path $Destination "Lib")) | Out-Null+ }}+ throw "The process cannot access the file because it is being used by another process."+}}+{rollback}+try {{ Start-StudioVenvRollback -ExistingDir $env:TEST_EXISTING_DIR }} catch {{ }}+Write-Output ("active=" + $script:StudioVenvRollbackActive)+Write-Output ("dir=" + [string]$script:StudioVenvRollbackDir)+"""+ env = os.environ.copy()+ env["TEST_STUDIO_HOME"] = str(tmp_path)+ env["TEST_EXISTING_DIR"] = str(existing)+ env["TEST_ROLLBACK_CASE"] = case+ out = _run_powershell(shell, script, env)+ state = dict(+ line.split("=", 1) for line in out.splitlines() if line.startswith(("active=", "dir="))+ )++ if case == "clean":+ # Nothing moved, so the original is intact and there is nothing to restore.+ assert state["active"] == "False", out+ assert state["dir"] == "", out+ return++ assert state["active"] == "True", out+ assert state["dir"].startswith(os.path.join(str(tmp_path), "unsloth_studio.rollback.")), out+ assert Path(state["dir"]).is_dir(), out+ # Both halves are named, so the user is not left hunting for the moved tree.+ assert str(existing) in out and state["dir"] in out, out++[email protected](not POWERSHELLS, reason = "PowerShell is unavailable")[email protected]("shell", POWERSHELLS)+def test_restoring_a_split_move_never_deletes_the_half_left_behind(tmp_path: Path, shell: str):+ """Restoration must merge the two halves, not clear the destination first.++ After a partway move the target holds the entries the move never got to -- not+ an incomplete *new* environment. The committed-replacement path removes the+ target before moving the backup back, which for a split tree deletes files that+ exist nowhere else. Keeping the rollback active is only safe if restoration+ takes a merge path, so this pins the file that never moved to being still there.+ """+ source = INSTALL_PS1.read_text(encoding = "utf-8")+ blocks = "".join(+ _extract(rf" function {name} \{{.*?\n \}}\n", source)+ for name in (+ "Remove-StudioVenvTreeWithRetry",+ "Merge-StudioVenvRollbackTree",+ "Restore-StudioVenvRollback",+ )+ )+ target = tmp_path / "unsloth_studio"+ backup = tmp_path / "unsloth_studio.rollback.20260804120000.999"+ # The half the interrupted move left behind, and the half that got across.+ (target / "Scripts").mkdir(parents = True)+ (target / "Scripts" / "unsloth.exe").write_text("irreplaceable", encoding = "utf-8")+ (backup / "Lib" / "site-packages").mkdir(parents = True)+ (backup / "Lib" / "site-packages" / "marker.txt").write_text("moved", encoding = "utf-8")++ script = f"""+$ErrorActionPreference = "Stop"+function substep {{ param([string]$Text, [string]$Color) }}+{blocks}+$script:StudioVenvRollbackActive = $true+$script:StudioVenvRollbackDir = $env:TEST_BACKUP_DIR+$script:StudioVenvRollbackTarget = $env:TEST_TARGET_DIR+$script:StudioVenvRollbackPartial = $true+Restore-StudioVenvRollback+Write-Output ("active=" + $script:StudioVenvRollbackActive)+"""+ env = os.environ.copy()+ env["TEST_BACKUP_DIR"] = str(backup)+ env["TEST_TARGET_DIR"] = str(target)+ out = _run_powershell(shell, script, env)++ # The file that never moved is the whole point: the pre-merge path deleted it.+ assert (target / "Scripts" / "unsloth.exe").read_text(encoding = "utf-8") == "irreplaceable", out+ # ...and the half that did move comes back rather than being stranded.+ assert (target / "Lib" / "site-packages" / "marker.txt").is_file(), out+ assert not backup.exists(), out+ assert "active=False" in out, out++[email protected](not POWERSHELLS, reason = "PowerShell is unavailable")[email protected]("shell", POWERSHELLS)+def test_merging_a_split_move_keeps_every_sibling_at_its_own_path(tmp_path: Path, shell: str):+ """Each entry must land at its own path, not nested under the previous one.++ PowerShell variable names are case-insensitive, so a per-entry $destination+ reassigns the $Destination parameter. Only the first sibling at a level then+ lands correctly and the rest are appended to its path, so a restored venv comes+ back with pyvenv.cfg buried inside Lib. One entry per level hides it, so this+ uses several.+ """+ source = INSTALL_PS1.read_text(encoding = "utf-8")+ blocks = "".join(+ _extract(rf" function {name} \{{.*?\n \}}\n", source)+ for name in (+ "Remove-StudioVenvTreeWithRetry",+ "Merge-StudioVenvRollbackTree",+ "Restore-StudioVenvRollback",+ )+ )+ target = tmp_path / "unsloth_studio"+ backup = tmp_path / "unsloth_studio.rollback.20260804120000.999"+ # The half left behind, and a moved half with several siblings at two levels.+ (target / "Scripts").mkdir(parents = True)+ (target / "Scripts" / "unsloth.exe").write_text("irreplaceable", encoding = "utf-8")+ (target / "Lib").mkdir()+ (target / "Lib" / "stayed.py").write_text("stayed", encoding = "utf-8")+ (backup / "Lib" / "site-packages").mkdir(parents = True)+ (backup / "Lib" / "site-packages" / "marker.txt").write_text("moved", encoding = "utf-8")+ (backup / "Lib" / "other.py").write_text("other", encoding = "utf-8")+ (backup / "pyvenv.cfg").write_text("cfg", encoding = "utf-8")+ (backup / "unsloth_install_manifest.json").write_text("{}", encoding = "utf-8")++ script = f"""+$ErrorActionPreference = "Stop"+function substep {{ param([string]$Text, [string]$Color) }}+{blocks}+$script:StudioVenvRollbackActive = $true+$script:StudioVenvRollbackDir = $env:TEST_BACKUP_DIR+$script:StudioVenvRollbackTarget = $env:TEST_TARGET_DIR+$script:StudioVenvRollbackPartial = $true+Restore-StudioVenvRollback+Write-Output ("active=" + $script:StudioVenvRollbackActive)+"""+ env = os.environ.copy()+ env["TEST_BACKUP_DIR"] = str(backup)+ env["TEST_TARGET_DIR"] = str(target)+ out = _run_powershell(shell, script, env)++ restored = sorted(+ str(p.relative_to(target)).replace("\\", "/") for p in target.rglob("*") if p.is_file()+ )+ assert restored == [+ "Lib/other.py",+ "Lib/site-packages/marker.txt",+ "Lib/stayed.py",+ "Scripts/unsloth.exe",+ "pyvenv.cfg",+ "unsloth_install_manifest.json",+ ], out+ assert not backup.exists(), out+ assert "active=False" in out, out++[email protected](not POWERSHELLS, reason = "PowerShell is unavailable")[email protected]("shell", POWERSHELLS)[email protected]("side", ["destination", "source"])+def test_merging_a_split_move_never_walks_through_a_link(tmp_path: Path, shell: str, side: str):+ """A junction on either side is a leaf, not a subtree to recurse into.++ Recursing through one moves venv files to wherever the link points, outside+ $StudioHome, and replaces the link with a real directory. Either half can carry+ the link, so both directions are pinned here.+ """+ source = INSTALL_PS1.read_text(encoding = "utf-8")+ blocks = "".join(+ _extract(rf" function {name} \{{.*?\n \}}\n", source)+ for name in (+ "Remove-StudioVenvTreeWithRetry",+ "Merge-StudioVenvRollbackTree",+ "Restore-StudioVenvRollback",+ )+ )+ target = tmp_path / "unsloth_studio"+ backup = tmp_path / "unsloth_studio.rollback.20260804120000.999"+ # A sibling of the environment, never under it.+ outside = tmp_path / "outside"+ outside.mkdir()+ (outside / "keep.txt").write_text("untouched", encoding = "utf-8")+ target.mkdir()+ backup.mkdir()++ linked, real = (target, backup) if side == "destination" else (backup, target)+ _link_dir(linked / "Lib", outside)+ (real / "Lib").mkdir()+ (real / "Lib" / "payload.txt").write_text("venv-only", encoding = "utf-8")++ script = f"""+$ErrorActionPreference = "Stop"+function substep {{ param([string]$Text, [string]$Color) }}+{blocks}+$script:StudioVenvRollbackActive = $true+$script:StudioVenvRollbackDir = $env:TEST_BACKUP_DIR+$script:StudioVenvRollbackTarget = $env:TEST_TARGET_DIR+$script:StudioVenvRollbackPartial = $true+Restore-StudioVenvRollback+Write-Output ("active=" + $script:StudioVenvRollbackActive)+"""+ env = os.environ.copy()+ env["TEST_BACKUP_DIR"] = str(backup)+ env["TEST_TARGET_DIR"] = str(target)+ out = _run_powershell(shell, script, env)++ # Nothing from the environment may be written through the link.+ assert not (outside / "payload.txt").exists(), out+ assert sorted(p.name for p in outside.iterdir()) == ["keep.txt"], out+ assert (outside / "keep.txt").read_text(encoding = "utf-8") == "untouched", out+ # An unresolved conflict keeps both copies, so the rollback stays tracked.+ assert "active=True" in out, out++@pytest.mark.skipif(not POWERSHELLS, reason = "PowerShell is unavailable")@pytest.mark.parametrize("shell", POWERSHELLS)@pytest.mark.parametrize("case", ["missing", "unlaunchable", "working"])