Skip to content

Studio: preserve the Windows launcher during updates - #8092

Merged
danielhanchen merged 12 commits into
unslothai:mainfrom
Etherll:windows-update-fix
Aug 7, 2026
Merged

danielhanchen merged 12 commits into
unslothai:mainfrom
Etherll:windows-update-fix

Conversation

@Etherll

@Etherll Etherll commented Aug 7, 2026

Copy link
Copy Markdown
Collaborator

Summary

Keep the managed Windows unsloth.exe launcher available and recoverable while Studio updates its Python environment. Validate the resulting launcher before accepting the update.

Motivation

The previous updater renamed the running launcher to unsloth.exe.deleteme before setup. When pip determined that Unsloth was already up to date, it did not create a replacement launcher. This left the managed environment without Scripts\unsloth.exe and caused Tauri recovery to fall back to a full reinstall.

Changes

  • Replace the Windows launcher rename helpers with _WindowsLauncherUpdateTransaction in unsloth_cli/commands/studio.py:3140.
  • Keep the canonical launcher in place while creating an atomic unsloth.exe.update-backup.
  • Serialize updates with a Windows byte-range lock.
  • Recover a missing launcher from the transaction backup or a legacy .deleteme file.
  • Require the updated launcher to be a non-empty PE file and pass unsloth.exe --version.
  • Restore the previous launcher after setup failures, missing or invalid replacements, nonzero exits, and validation timeouts.
  • Run launcher validation even with studio update --no-verify; that flag only skips the broader package-integrity scan.
  • Add focused coverage for no-op updates, concurrent updates, recovery paths, runtime validation, setup failures, and non-Windows behavior.

How to test

pytest tests/python/test_windows_studio_update_launcher.py unsloth_cli/tests/test_studio_update_local_repo.py unsloth_cli/tests/test_studio_update_verify.py

@Etherll
Etherll requested a review from danielhanchen as a code owner August 7, 2026 08:34
chatgpt-codex-connector[bot]

This comment was marked as resolved.

@danielhanchen

Copy link
Copy Markdown
Member

Thanks for this. The launcher transaction is a real improvement over the rename-to-.deleteme approach, and I confirmed the new tests are meaningful: 60 pass on this branch, and 11 of the 12 in test_windows_studio_update_launcher.py fail when replayed against main.

One thing to flag before this gets treated as closing out the report. The diagnostics that motivated it list three damaged files, and this PR addresses one of them:

Update finished, but some installed files are damaged:
  einx: test/conftest.py is missing
  unsloth: ../../Scripts/unsloth.exe is missing
  unsloth: studio/backend/core/data_recipe/oxc-validator/package-lock.json is 27225 bytes, expected 28473

_fail_if_install_damaged raises typer.Exit(1) whenever the finding list is non-empty, so the other two still fail the update on their own. I reproduced both, and neither is user-specific: both are produced by our own installer, which means the update they fail is the update meant to repair them.

einx: test/conftest.py is missing

einx and torchao both ship a top level test/conftest.py, so they write into the same site-packages/test/ tree:

test/conftest.py owners: {('einx', '20650'), ('torchao', '1585')}

install_python_stack.py force-reinstalls torchao to a pinned version on every update. pip deletes the file along with the outgoing torchao, and the pinned incoming one does not ship it, so einx's RECORD is left describing a file nothing will recreate:

$ pip install einx torchao==0.18.0
$ pip install --force-reinstall --no-deps torchao==0.17.0
$ ls site-packages/test/conftest.py
No such file or directory

$ damaged_installed_files()
   einx: test/conftest.py is missing

Also reproduced on a windows-latest runner.

package-lock.json is 27225 bytes, expected 28473

studio/setup.ps1 runs npm install inside the installed tree:

$OxcValidatorDir = Join-Path $ScriptDir "backend\core\data_recipe\oxc-validator"   # :163
Push-Location $OxcValidatorDir
$oxcInstallExit = Invoke-SetupCommand { npm install @NpmRegistryArgs }             # :3263

For a pip install $ScriptDir is site-packages/studio/, so npm rewrites a file the wheel owns and whose size pip recorded. setup.sh:949 does the same on Linux and macOS.

A plain npm install leaves it alone, which is why this is not universal. With legacy-peer-deps set, npm dedupes three hoisted @emnapi/* entries and the file lands on exactly the reported byte count:

npm install                        28473  (no change)
npm install --legacy-peer-deps     27225  (-1248)
with legacy-peer-deps=true in .npmrc   27225

removed: node_modules/@emnapi/core, @emnapi/runtime, @emnapi/wasi-threads

The reporter is on system Node (v24.9.0 | npm 11.6.0 (system) in their diagnostics), so their own global npm config applies. Note it is a shrink, which is the only direction the scan treats as damage.

Net effect

Replaying their exact three findings through the real damaged_installed_files:

launcher missing:    3 findings -> exit 1
launcher preserved:  2 findings -> exit 1
    einx: test/conftest.py is missing
    unsloth: .../oxc-validator/package-lock.json is 27225 bytes, expected 28473

And the desktop cannot route around it: update.rs:59,68 invokes studio update with no --no-verify, which is the path in their logs.

I have a separate change for those two that filters non-runtime rows while RECORD is read, so they also stay out of the ownership tally and the limit budget. Happy to keep it separate from this PR, since the launcher work stands on its own.

One thing worth fixing here

__enter__ now hard-exits at studio.py:3335-3342 before _run_setup_script when the launcher is missing or invalid. On main the equivalent helper just returned:

    exe = venv_scripts / "unsloth.exe"
    if not exe.exists():
        return

For someone already broken by the old updater there is usually no .deleteme left, because _cleanup_self_exe_lock_windows unlinked it after the setup that appeared to succeed. So _recover_missing_launcher finds nothing and they can no longer update at all, where before this they could. That is the cohort the PR is aimed at.

The hardlinked shim install.ps1 creates at $StudioHome\bin\unsloth.exe survives that unlink and is a valid recovery source, but _recover_missing_launcher does not look at it. Worth adding it, and letting setup run with a warning rather than exiting.

Two smaller ones while you are in there:

  • _recover_missing_launcher:3248 gates on .exists() rather than validity, so a present but corrupt launcher is never recovered even though :3340 confirms a valid backup exists one line later and prints its path.
  • _atomic_copy(self.launcher, self.backup) at :3343 can raise a bare OSError and abort the update with a traceback. The old code's equivalent step was deliberately non-fatal.

…nslothai#8092

The report this PR targets listed three damaged files. Preserving the
launcher fixes one; the other two still fail the update on their own,
since _fail_if_install_damaged exits 1 on any finding.

Both are produced by our own installer, so the update they fail is the
update meant to repair them. einx and torchao both ship a top-level
test/conftest.py, and install_python_stack.py force-reinstalls torchao
every update, so pip deletes the file and the pinned torchao does not
ship it. package-lock.json is rewritten in place by setup.ps1 and
setup.sh, which run npm install inside the installed tree; under
legacy-peer-deps npm dedupes hoisted entries and the file shrinks below
its recorded size, reproduced exactly as 28473 to 27225.

Drop both classes while reading RECORD rather than when reporting, so a
filtered row also stays out of the ownership tally and the limit budget
and cannot crowd out a real finding. Mirrored into the sidecar scanner,
whose docstring asks for the two predicates to be kept in sync.

Also three fixes to the transaction itself:

- Recover from the hardlinked bin/unsloth.exe shim, which survives the
  old updater's .deleteme unlink.
- Warn instead of exiting when the launcher is missing or invalid. An
  install already broken by the old updater has neither launcher nor
  .deleteme, and exiting before setup stopped exactly those users from
  updating. validate_launcher still judges the result.
- Gate recovery on validity rather than existence, and treat a failed
  backup as a missing safety net rather than a fatal error.
@danielhanchen

Copy link
Copy Markdown
Member

Pushed c97c01e to this branch covering the two remaining findings, plus three fixes to the transaction itself.

The other two damaged files

_fail_if_install_damaged exits 1 on any finding, so these failed the update on their own even with the launcher preserved. Both are dropped while RECORD is read rather than when reporting, so a filtered row also stays out of the ownership tally and the limit budget and cannot crowd out a real finding. Mirrored into _sidecar_scan_impl, whose docstring asks for the two predicates to be kept in sync.

Transaction fixes

  • Recover from the hardlinked bin/unsloth.exe shim. It survives the old updater's .deleteme unlink, so it is usually the only recovery source an affected install has left.
  • Warn instead of exiting when the launcher is missing or invalid. _cleanup_self_exe_lock_windows unlinked the .deleteme after a setup that appeared to succeed, so an already-broken install has neither file, and exiting before _run_setup_script stopped exactly those users from updating at all. validate_launcher still judges the result.
  • Gate recovery on validity rather than .exists(), so a zero-byte launcher is repaired from the backup. The old _restore_self_exe_lock_windows restored on that shape, so gating on existence had regressed it.
  • Treat a failed backup as a missing safety net rather than a fatal error, instead of a bare OSError traceback before setup runs.

Tests

9 added, each confirmed to fail without its fix:

unsloth_cli/tests/test_studio_update_verify.py            6
tests/python/test_windows_studio_update_launcher.py       4
studio/backend/tests/test_transformers_version.py         1

Run on this branch:

tests/python/test_windows_studio_update_launcher.py
unsloth_cli/tests/test_studio_update_verify.py
unsloth_cli/tests/test_studio_update_local_repo.py        64 passed
unsloth_cli/tests                                        848 passed, 4 skipped
studio/backend/tests/test_transformers_version.py        279 passed

The reproductions also ran on a windows-latest runner with real pip and npm: both findings appear before the change, the scan is clean after it, and a torn runtime module is still reported.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: c97c01e5e0

ℹ️ 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".

Comment thread unsloth_cli/commands/studio.py Outdated
Comment on lines 3143 to 3144
with _WindowsLauncherUpdateTransaction() as launcher_update:
_run_setup_script(verbose = verbose, repo_root = repo_root)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Move the active launcher aside before package upgrades

On Windows, when a newer unsloth version is available, _run_setup_script() reaches the uv --upgrade-package unsloth path in studio/install_python_stack.py, which must remove or replace Scripts\unsloth.exe. This transaction now keeps that executable at its canonical path even though it is still the running launcher image (including when invoked through the hard-linked PATH shim), so the installer can fail with a Windows sharing violation before validation runs. The added tests exercise no-op or mocked setup paths and therefore do not cover a real package upgrade; preserve the backup, but move the active canonical launcher aside before invoking setup so the installer can publish its replacement.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not taking this one. The suggested remedy is the rename that main already removed as non-working: setup.ps1:4386-4391 says so in tree, from #6296. "setup.ps1 runs via unsloth.exe, so renaming the running launcher only ever failed (WinError 32) and printed a scary warning." That comment also covers the upgrade path you describe: 'studio update' goes through uv (--upgrade-package), whose pip fallback no-ops on the already-satisfied bare unsloth, so unsloth.exe stays either way. Reintroducing the rename would restore the warning without changing the outcome.

Two things also narrow the case. The desktop never runs the stub: update.rs:59 spawns python.exe, and there is a test pinning that. And after 15cae75 the transaction targets STUDIO_HOME/unsloth_studio, so for a pip-installed or checkout CLI the managed launcher is not the running image at all. What is left is a real limitation of the console path, but it is pre-existing and not one a rename fixes.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correcting myself: you were right, and my earlier reply was wrong. Fixed in 724b274.

I rejected this on the strength of setup.ps1:4386-4391, which states that renaming the running launcher "only ever failed (WinError 32)". That claim does not hold. I ran a probe on windows-latest that builds a real console-script package, starts it, and renames the live launcher:

RESULT idle-launcher:       RENAME SUCCEEDED
RESULT running-launcher:    RENAME SUCCEEDED
RESULT publish-replacement: WROTE a new launcher at the canonical path

So the rename works, and main did do it at studio.py:3182. Removing it on this branch meant uv could no longer replace Scripts\unsloth.exe: uv only self-replaces its own executable and deletes a third-party console script outright, and the pip fallback then no-ops on the already-satisfied bare unsloth, so the upgrade was silently skipped rather than failing loudly.

The launcher is moved aside again before setup, with the part this branch was written for kept: if setup publishes no launcher, validate_launcher restores it instead of leaving the venv with none, which was the original bug. Restore prefers the backup over the moved-aside copy, since the backup is the last launcher known to run while the moved-aside one is only this run's unvalidated file.

One limitation worth stating: the mocked test harness cannot reproduce a sharing violation, so the tests pin the invariant (canonical path free during setup, a recoverable copy always present) and the CI probe covers the Windows semantics.

pre-commit-ci Bot and others added 2 commits August 7, 2026 10:20
Three follow-ups from review.

The transaction resolved Scripts from sys.executable, but setup.ps1
installs into STUDIO_HOME/unsloth_studio (setup.ps1:3411). When a
pip-installed or checkout CLI drives the update, those differ, so it
backed up and --version validated the caller's launcher while the one
actually being replaced went unprotected. Resolve the managed venv the
same way _studio_deps._managed_root does for the damage scan.

__enter__ overwrote the transaction backup unconditionally, guarded only
by the two-byte MZ check. A backup outlives __enter__ only when a
previous run died before validating, so it holds the last launcher known
to run; overwriting it with a PE-shaped but unvalidated canonical file
destroyed the only recovery copy. Write a backup only when there is no
usable one already.

package-lock.json was skipped outright, which dropped its existence
check too. npm rewrites it in place but never deletes it, so keep the
row and drop only its recorded size. Also add scripts/ to the shared
non-runtime roots: unsloth_zoo ships a top-level scripts/, the same
squatted-namespace shape as einx's test/, and it has no __init__.py so
nothing imports it.
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Delightful!

Reviewed commit: 15cae75f47

ℹ️ 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".

I rejected this on the strength of setup.ps1:4386-4391, which says
renaming the running launcher "only ever failed (WinError 32)". That is
not right. A probe on windows-latest builds a real console-script
package, runs it, and renames the live launcher: the rename succeeds and
a replacement can then be written at the freed path.

    RESULT idle-launcher:       RENAME SUCCEEDED
    RESULT running-launcher:    RENAME SUCCEEDED
    RESULT publish-replacement: WROTE a new launcher at the canonical path

main moved the launcher aside before setup (studio.py:3182) and this
branch had removed it, so uv could no longer replace Scripts\unsloth.exe.
uv only self-replaces its own executable and deletes a third-party
console script outright, and the pip fallback then no-ops on the
already-satisfied bare unsloth, so the upgrade was silently skipped.

Move it aside again, but keep what this branch was written for: when
setup publishes no launcher, validate_launcher restores it rather than
leaving the venv with none. That was the original bug, where the old
updater renamed the launcher away and then deleted its own .deleteme.

Restore prefers the backup over the moved-aside copy: the backup is the
last launcher known to run, the moved-aside one is only this run's
unvalidated canonical file.

The mocked harness cannot reproduce a sharing violation, so the tests
pin the invariant (the canonical path is free during setup, a recoverable
copy always exists) while the CI probe covers the Windows semantics.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

Two follow-ups, both from the restore path added in 724b274.

Restoring before the health check could not tell setup publishing
nothing from setup publishing something unusable. A zero-byte or non-PE
replacement was quietly swapped for the previous launcher, which then
passed --version, so the update reported success and deleted its own
recovery copies. Sample whether setup published anything before any
restore: nothing published and a good restore is the no-op update this
transaction exists for, while a launcher setup did write and that cannot
run stays a failure even though the previous one goes back.

_restore_backup also picked the first candidate passing the two-byte
header check and stopped there. Backups are taken after only that check,
so an interrupted run can leave a PE-shaped but non-runnable one, and
preferring it stranded the working launcher this run had moved aside.
Split restoration: _restore_from puts one candidate back, and
_restore_runnable walks the candidates until one actually runs.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

__exit__ restored the first PE-shaped candidate, so an interrupted run's
non-runnable backup was installed over the working launcher this run had
moved aside, and it could undo a restore validate_launcher had just made.
It now uses _restore_runnable, which leaves an already-working launcher
alone, walks the candidates until one passes --version, and falls back to
the best candidate rather than whichever was tried last.

The shared-namespace exemption was also too broad. I justified it on the
grounds that tests/ and scripts/ ship no __init__.py, which is wrong: PEP
420 makes them importable, and this repo does 'from scripts import ...'
itself. Restrict it to distributions Unsloth does not ship, so einx and
torchao squatting on a top-level test/ is exempt while our own top-level
trees stay checked.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 7, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 7, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 7, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 7, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 7, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 7, 2026
@unslothai unslothai deleted a comment from wasimysaid Aug 7, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

_recovery_candidates only offered the backup and the moved-aside copy, so
when an interrupted run left a PE-shaped but non-runnable backup and the
legacy .deleteme or the PATH shim was still good, the bad backup was
accepted on its header alone and the good copy was never reached. The
update then failed every time with the broken bytes canonical.

All four are candidates now, deduplicated by normalised path, and
_restore_runnable walks them until one passes --version.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

Resolving Scripts from the managed venv put the lock inside $VenvDir, and
setup.ps1:3748 removes that whole directory to rebuild a stale torch.
Windows refuses a recursive delete while a handle inside it is open, so
an external CLI holding the lock for the whole setup run failed the
repair with "Could not remove stale venv".

Keep it under the Studio home instead, which is stable and is the right
grain anyway: it is what names the managed venv.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 7, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 7, 2026
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

# Conflicts:
#	unsloth_cli/commands/studio.py
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🚀

Reviewed commit: 3098cb8785

ℹ️ 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".

@danielhanchen
danielhanchen merged commit e0a2bd8 into unslothai:main Aug 7, 2026
78 of 83 checks passed

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 1ef3bcd17e

ℹ️ 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".

Comment on lines +3378 to +3379
except OSError as exc:
typer.echo(f"Warning: could not move the Unsloth launcher aside: {exc}", err = True)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Abort when the launcher cannot be moved

On Windows, if os.replace fails because an ACL or endpoint-security tool is holding Scripts\unsloth.exe, this warning leaves the canonical launcher in place and still runs setup. In the inspected install_python_stack.py path, uv then cannot replace that launcher, while the pip fallback removes --upgrade-package; uv pip install --help identifies that flag as what allows a specific package upgrade, so pip can treat the installed bare requirement as already satisfied. Setup may therefore exit 0 and validation merely runs the unchanged old launcher, reporting a successful update that installed nothing. Fresh evidence beyond the earlier active-launcher comment is this new exception path, which deliberately continues after the normal move-aside fix fails; return a failed update instead of silently proceeding.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right about the outcome: a failed move-aside leaves uv unable to replace the launcher, the pip fallback drops --upgrade-package, and setup still exits 0, so the update reads as successful while unsloth stays at its old version. That also explains the repair loop in the original report, where preflight kept finding the backend stale after a "successful" update.

I did not take the abort. main did not fail here either, and making an antivirus hold enough to render the environment unupdatable trades a silent partial update for a hard block on every update. What was missing is that the cost was invisible, so the warning now names it and says which process to close.

This landed after the PR merged, so it is not on this branch. Carrying it as a follow-up rather than leaving it implied here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants