Repository navigation
Windows: stop depending on the generated unsloth.exe console script - #8592
Conversation
…mote script text studio/setup.ps1 piped astral's install.ps1 straight into Invoke-Expression. That download-and-execute shape is the single construct AMSI providers and cloud ML scanners score hardest, and install.ps1 already replaced it with a pinned-SHA-256 archive download. Port the same implementation across. Progress goes to the pipeline rather than the console, so the quiet path swallows it exactly as it swallowed astral's installer output and the printed lines around the call site are unchanged.
The Studio shortcut launched launch-studio.ps1 with -WindowStyle Hidden and -ExecutionPolicy Bypass on the same command line. That pair is what Microsoft's own detections key on, and studio/src-tauri/src/install.rs already refuses it for the app's own launch of install.ps1. The installer writes launch-studio.ps1 itself, so the file carries no mark-of-the-web and RemoteSigned loads it. The hidden window is unchanged, so the shortcut behaves exactly as before. The generated launcher's own child launch moves to RemoteSigned for the same reason: it runs an inline -Command against an executable, where no script file is loaded and the two policies are equivalent. Also refresh a stale comment in studio/setup.ps1 that attributed the PSModulePath fix to astral's uv installer, which no longer runs in-process.
…ript text AMSI scans install.ps1 in full before a single line of it runs, and generic script classifiers read install.sh the same way inside the Linux bundle. Both headers rehearsed the piped web one-liner five times over, plus a scriptblock form and an execution-policy bypass, none of which anything in the scripts reads and all of which the README already documents. Point at the README instead and reword the in-body comments that quoted the one-liner as shorthand. Every printed line is untouched: the remediation text the installers show users still spells out the command in full. Same treatment for scripts/uninstall.ps1's header.
install.ps1's venv-holder probe opened a handle to every running PID through inline C# compiled at runtime. Opening a handle per process is a shape AV heuristics score hard, and it bought nothing: Win32_Process reports ExecutablePath for exactly the processes those handles could be opened against, and answers for all of them in a single query instead of once per PID. The remaining file-canonicalisation imports stay -- handle-based resolution of linked ancestors has no faithful Windows PowerShell 5.1 equivalent, and it runs on security-relevant paths. Falls back to the per-process .Path when the query is unavailable, so a degraded WMI repository degrades exactly as the old code did on a process it could not open.
PowerShell hands the whole top-level script block to AMSI while compiling it, so a security product's verdict arrives as a parse error over the entire file before install.ps1 runs a statement: no [TAURI:ERROR] marker, no phase log, and a stderr tail the user cannot act on. unsloth#8523 shows what that looks like in the UI -- "Installation failed: + FullyQualifiedErrorId : ScriptContainedMaliciousContent". Recognise the two stable error ids on either stream and append what the user actually needs: nothing was installed, nothing was changed, it is a false positive, update definitions and retry, do not turn off endpoint protection. The raw id stays in the message, because the diagnostics report and any vendor submission both need it. Matches the id, never the message text, which is localized, and tolerates the cmdlet suffix the Invoke-Expression form carries.
resolve_install_script picks install.sh on unix and install.ps1 everywhere else, but the shared Tauri config bundled both into every target. The Linux AppImage therefore carried 280 KB of Windows PowerShell it can never execute -- and it is the largest script body a generic classifier walking the squashfs reads, which is where Microsoft's Trojan:Script/Wacatac.B!ml verdict on 0.1.701-beta landed. Move the resource map into the per-platform configs. The clean-machine job already fails when a Linux bundle ships no install.sh; it now also fails when one ships install.ps1, so the split cannot silently regress in either direction. The .deb scanned clean with the same payload, so this is surface reduction rather than a proven fix for that verdict.
install.sh downloaded astral's install.sh to a temp file, ran it and deleted the file; studio/setup.sh piped it straight into a shell. Both are, shape for shape, what a dropper does, and generic ML script classifiers score them accordingly -- the 0.1.701-beta Linux AppImage came back Trojan:Script/Wacatac.B!ml while the .deb carrying the same scripts came back clean. Fetch the pinned release archive and verify a hardcoded SHA-256 instead, matching what install.ps1 already does on Windows. Only the four mainstream targets are pinned: musl, armv7 and any host without a digest tool keep the path they have today, because guessing a target triple wrong would break the install outright and that costs far more than the heuristic score of the fallback. Destination, PATH handling and every printed line are unchanged, so a host that takes either path ends up in the same state it did before.
One file collecting what was removed, so it cannot drift back: no remote script run in-process, no encoded or base64 payload, no hidden window paired with a bypassed execution policy, no handle opened against another process, and no new runtime-compiled native import outside an allowlist that carries a reason for each entry that stays. The last test is the other half of the contract. Hardening must not change what a user sees, so the remediation lines the installers print -- which still spell out the web one-liner in full -- are asserted verbatim. Removing the one-liner from comments is the point; removing it from what the user is told to run would be a regression. Runs on the existing discovery-based pytest step, no workflow list to update.
…agged The build job assembles a Microsoft submission packet, but only for the Windows -setup.exe. The detection that actually arrived on 0.1.701-beta was Trojan:Script/Wacatac.B!ml on the Linux AppImage, so nothing was produced for the one asset that needed it. The VirusTotal job already knows which assets were flagged and by which engines, so put the packet there: hash, size and both portals, for every flagged asset whatever platform it came from, with a note that clearance is per hash and per vendor. Engine names are not repeated -- they are third-party text and already appear escaped under Flagging engines. The gate stays advisory; this only makes acting on it take seconds.
…uery" This reverts commit 7897865. tests/python/test_windows_installer_concurrency_guard.py bans Get-CimInstance and $process.Path from Get-RunningStudioVenvProcesses outright, and requires the native image-path lookup. That contract came out of #7764, which closed a set of races where the installer inferred "in use" from something other than a confirmed executable identity and blocked installs that should have proceeded. Win32_Process.ExecutablePath does answer the same question, but a wrongly blocked install costs far more than the heuristic weight of three native imports. Record the imports in the AV-shapes allowlist with that reasoning instead, and keep the ban on the process-memory APIs, which the installer has no use for.
Opening comment-reduction pass over the PR diff: same intent, fewer lines. Cut hardest on the prose that restated the PR description rather than explaining the code next to it. Comments and docstrings only, verified with comment_tools.py check --strip-docstrings across every Python file in the diff.
Stray-resource check aborted the step it was meant to assert. grep exits 1 when it selects nothing, and under this step's set -o pipefail plus the runner's bash -e that kills the assignment outright, so every correctly split .deb failed clean-machine CI before reaching the check. Both lookups take || true now: no match is the passing case for the stray one, and for install.sh it was swallowing the explicit annotation in favour of a bare exit 1. studio/setup.sh skipped astral's XDG_DATA_HOME/../bin destination tier, which install.sh, install.ps1 and studio/setup.ps1 all honour. A host that configured an XDG location got uv under ~/.local/bin instead, where no later shell looks for it. The session PATH prepend hid it at install time. The AMSI guidance claimed nothing was changed even when the block landed on the nested studio/setup.ps1, which install.ps1 launches through the same inherited pipes after the venv, PyTorch and the packages are already on disk. Split the wording on whether a [TAURI:STEP] marker has been seen: a pre-start block produces none, so the reassurance is only given where it is true.
stats and results are separate fields of the same VirusTotal response, so an asset can carry a flagged count with no readable results map. The summary table reports that asset and the packet skipped it, which is exactly the one that needs a packet. Select on stats.flagged and keep the engine list for the Flagging engines section, which is correctly keyed on having engines to name.
That job downloads a published release, never a bundle built from the branch, so asserting the new resource split there turns every run red until a release ships with it. The split is a property of the Tauri config, and tests/studio/test_tauri_installer_resource_contract.py already enforces it at the right layer. The || true on the install.sh lookup stays: it is what lets the explicit annotation print instead of the step dying on grep's exit 1 under pipefail.
Fixes #8490. On Windows the `unsloth` entry point is materialised as a generated, unsigned launcher .exe. AppLocker, WDAC and Smart App Control deny it, while the venv's python.exe, a copy of the signed CPython binary, still runs. The installer died at "running unsloth studio setup" with `Program 'unsloth.exe' failed to run: An Application Control policy has blocked this file`, and because the launch throws rather than returning an exit code, it escaped Install-UnslothStudio and printed a raw NativeCommandFailed dump instead of a diagnostic. The desktop updater already solved this in update.rs by reaching the CLI through the interpreter. This applies the same idea everywhere else: the setup handoff, autostart, the shortcut launcher, the Tauri backend, auth provisioning, the install health probe, the preflight probes and the `studio run` respawn. unsloth.exe is still generated, still hardlinked to the shim, and still works. Nothing depends on it any more. Also adds `python -m unsloth_cli` as a supported entry point, and a bin\unsloth.cmd companion to the shim so `unsloth.cmd` is available where the .exe is denied. The trampoline is one string shared by install.ps1, process.rs and studio.py: import sys, os; sys.path[:1] = [x for x in sys.path[:1] if x not in ('', os.getcwd())]; sys.argv[0] = 'unsloth'; from unsloth_cli import app; app() Both halves are load bearing. argv[0] is assigned before the import because unsloth_cli decides at import time whether it is the console script, which gates the UTF-8 stream setup and the -np<N> rewrite, and it keeps typer's prog_name at `unsloth`. The sys.path[:1] filter drops the working directory entry that `python -c` adds and a console script does not, which is what lets the invocation stay off -I: -I would drop it too, but also PYTHONPATH, PYTHONWARNINGS and user site-packages, which the console script honours. Behaviour on a machine with no policy is unchanged, and that is enforced rather than asserted. tests/python/test_module_entry_point.py compares stdout, stderr and exit code between the console script, `-m unsloth_cli` and the trampoline over --version, --help, `studio --help` and two error paths. The writes are idempotent: bin\unsloth.cmd, launch-studio.ps1 and the .lnk files are content compared, so a second install changes no bytes and no timestamps. tests/studio/test_application_control_cli_fallback.ps1 pins the pieces that are easy to get wrong: the failure is classified off the exception (Win32 1260), never off $LASTEXITCODE, which no process was created to set; Start-Process gets one pre-quoted command line, since -ArgumentList joins an array with spaces and quotes nothing; and bin\unsloth.cmd only counts as an ownership marker when its contents match the shim we write, so an unrelated file of that name in a custom root cannot qualify it for removal. The new windows-application-control-ci.yml leg reproduces the report: AppLocker denies only Scripts\unsloth.exe for a standard user, a negative control proves the rule is actually enforced (the job fails loudly if the stub runs), and the full installer then has to succeed.
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 6e9163677d
ℹ️ 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".
| if os.name == "nt": | ||
| return "unsloth.cmd studio reset-password" |
There was a problem hiding this comment.
Keep spaced custom-root reset commands self-contained
When a Windows UNSLOTH_STUDIO_HOME contains spaces, this branch cannot use the absolute interpreter and always returns unsloth.cmd; however, env-mode deliberately does not persist <StudioHome>\bin on PATH, and the cmd shim is not installed in the activated venv's Scripts directory. Consequently, a backend launched later from launch-studio.ps1 or a freshly activated custom environment shows a reset-password command that the shell cannot resolve, precisely when the user is locked out. Resolve the installer-root cmd shim explicitly or emit a shell-safe absolute interpreter command instead of assuming unsloth.cmd is on PATH.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
The limitation is real but it predates this PR and no available string improves on it, so I am leaving it. Before this change the same branch returned bare unsloth studio reset-password (see auth.py on main): identical PATH dependence, and strictly worse, because where the shim dir IS on PATH, PATHEXT resolves .EXE ahead of .CMD and bare unsloth lands on exactly the file the policy denies. Naming .cmd is what stops that.
The spaced-path branch exists because there is no one string that runs in both shells: cmd.exe wants "C:...\python.exe" -m unsloth_cli ..., PowerShell needs a leading & or it just echoes the path back, which fails silently rather than loudly. Resolving the shim absolutely hits the same wall, since a custom root with a spaced interpreter path almost always has a spaced bin dir too.
Fixing it properly means the API returning something structured the frontend can render per shell, rather than one command string. That is worth doing but it is a change to this endpoint's contract, not to the Application Control work here.
|
@codex review |
The pre-install hook runs before the user can still cancel, and $INSTDIR can be a directory they picked in the GUI, so deleting install.sh there could take a file that was never ours. Both hooks now only act where our own executable already is. A signal between the two renames restored a predecessor but did nothing when there was none, leaving a 0.12.1 uv beside whatever uvx the machine had. It now removes what it published, which is what the ordinary rollback already does.
astral's uv installer wires ~/.profile, each of .bashrc, .bash_profile and .bash_login that exists, .zshrc or .zshenv under ZDOTDIR, and a fish drop-in under ~/.config. Replacing that installer with a pinned archive meant the PATH entry only reached the one file for whichever shell happened to be running, so a bash user whose .bash_profile does not source .bashrc, a /bin/sh login, or anyone who later switched shells would have no uv on PATH where they used to. Both POSIX installers now write the same set, once each, with the existing whole-entry check keeping a re-run idempotent. Files that do not exist are not created, apart from ~/.profile, which astral creates too.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 6d4b27e4f6
ℹ️ 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".
| let started = Instant::now(); | ||
| let mut cmd = Command::new(bin); | ||
| cmd.args(args).stdout(Stdio::null()).stderr(Stdio::null()); | ||
| let Ok(mut cmd) = crate::process::build_managed_cli_command_tokio(bin, args) else { |
There was a problem hiding this comment.
Allow interpreter-backed preflight probes more than 10 seconds
On Windows this now runs the -h preflight through the managed Python trampoline, but run_cli_probe still kills it after 10 seconds. On a cold venv being scanned by antivirus—the quarantine scenario this change is intended to support—the same managed CLI import is given 60 seconds by _MANAGED_CLI_IMPORT_PROBE_TIMEOUT; if it takes 10–60 seconds here, probe_managed_bin incorrectly returns Stale { reason: "cli_unusable" } for a healthy installation and sends the desktop into repair instead of launching. Use an import-appropriate timeout for the interpreter-backed probe (and the similarly converted capability probe).
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not taking this one, because the exposure is not new and the remedy has its own cost.
The import was already inside that 10 second ceiling before this PR. run_cli_probe ran unsloth.exe -h, and the console script imports the same unsloth_cli package the trampoline does; the exe is a launcher around that import, not an alternative to it. Replacing it with python -X utf8 -c <trampoline> removes the wrapper's own startup rather than adding work, so a cold venv under an antivirus scan was equally able to exceed 10 seconds on main.
The comparison with _MANAGED_CLI_IMPORT_PROBE_TIMEOUT is also not quite like for like. That 60 seconds sits in front of a decision with no user waiting on it, where overrunning costs nothing but time. run_cli_probe is on the desktop launch path, so raising it to 60 seconds means a genuinely broken install hangs the window for a minute before saying so, twice over given the capability probe. That is a real judgement about desktop responsiveness and it should be made on its own merits for every platform, not folded into this change on the strength of a Windows-only rewrite that did not move the number.
Happy to be wrong if there is a measurement showing the trampoline import is materially slower than the console script's; I did not find one.
| return f"{exe} studio reset-password" | ||
| python = os.path.abspath(sys.executable) | ||
| if " " not in python: | ||
| return f"{python} -I -m unsloth_cli studio reset-password" |
There was a problem hiding this comment.
Avoid isolated reset commands for user-site installs
When the Windows backend is running from a pip install --user installation and sys.executable has no spaces, this always advertises an isolated -I -m unsloth_cli reset command. -I implies -s and therefore hides the user site containing unsloth_cli—the new unsloth_cli/__main__.py documentation explicitly calls out this exception—so a locked-out user receives a command that fails with No module named unsloth_cli, even though the PATH-based command used to start the server is usable. Detect that the package is user-site installed or emit the non-isolated, cwd-scrubbing trampoline for this case.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 97c35f3. The hint now checks whether unsloth_cli resolves inside the running interpreter's prefix, and prints the bootstrap unsloth_cli/__main__.py documents for the user-site case when it does not. That bootstrap carries single quotes only, so one pair of double quotes wraps it identically in cmd and in PowerShell, which is the constraint that made -m preferable in the first place. New studio/backend/tests/test_reset_password_command.py covers both interpreter shapes, the spaced-path fallback, the prefix check, and drift between this copy of the bootstrap and _WINDOWS_CLI_ENTRYPOINT.
The rollback machinery that grew over the review rounds covered cases a user is very unlikely to meet: an incumbent that cannot be hard-linked, a signal landing between two renames, a restore that itself fails, a second installer racing the first. It was 281 net lines, and every finding in the last two rounds was in it rather than in the hardening. What stays is what the common case needs. POSIX stages both binaries, runs the staged uv, and publishes the pair with two renames; a failure anywhere before them leaves the destination untouched, and the caller falls back to astral's installer exactly as before. Windows probes the extracted uv.exe before touching the destination, then copies the three under -ErrorAction Stop and re-checks the digest at the destination. The staging files are still removed on a signal, since they live in a directory that is on PATH. 64 shell checks and 114 installer tests cover the rest.
The fish drop-in is the only thing that puts uv on a fish user's PATH, since fish reads none of the POSIX files, and its check treated any occurrence of the directory as proof: /opt/uv-old suppressed /opt/uv. It now matches the exact fish_add_path line it would write. A launcher on a UNC share is a remote script to PowerShell, and RemoteSigned refuses an unsigned one, so a roaming profile got a shortcut that exits without starting Studio. That case, and only that case, uses Bypass, and drops -WindowStyle Hidden with it so the pair the detections key on never appears.
…a fallback The all-profile PATH write was gated on the uv destination differing from ~/.local/bin, which is exactly where a normal install puts it, so every ordinary machine still got the single-file write the shim path has always done. Three independent audits found this. The gate is gone, and the idempotency check now also matches the $HOME-relative spelling the shim block writes, so the default case does not end up with two lines for one directory. studio/setup.ps1 replaced astral's installer with the pinned archive and had nothing to fall back to. A failed pinned install therefore left UseUv false and silently ran torch, bitsandbytes, Triton and the rest through pip: a different resolver, not just a different download. winget is the fallback, as install.ps1 already does, rather than the remote script this branch exists to remove.
Three more from review, all the same shape: a Windows path that still treats the generated unsloth.exe as the only evidence of an install. * Root inference. _looks_like_installer_managed_studio_home accepted share/studio.conf or bin\unsloth.exe, and only install.sh writes studio.conf, so on a custom-root Windows install the quarantinable launcher was the only sentinel there was. Once antivirus took it, STUDIO_HOME fell back to ~/.unsloth/studio and every studio subcommand read and wrote the wrong tree while reporting success. bin\unsloth.cmd now counts, validated against the same marker pair and 8 KB ceiling Test-UnslothCmdShimFile and the uninstaller's recursive-delete guard use, because this decides which installation the CLI manages and the directory is on PATH. * The PATH gate took any leaf named unsloth.cmd as a usable launcher. Write-UnslothCmdShim warns and leaves an unwritable file alone, so a foreign shim in a custom root survives the run, and counting it put its directory on PATH and advertised someone else's command as the policy-safe way in. It goes through Test-UnslothCmdShimFile now. * The reset-password hint always advertised `-I -m unsloth_cli` on Windows. -I implies -s, so a pip install --user install was handed a command that cannot find its own package, and the person reading it is by definition already locked out. It now checks whether the package is inside the interpreter's prefix and otherwise prints the bootstrap unsloth_cli/__main__.py documents for exactly this case, which carries no double quote and so wraps identically for cmd and PowerShell. Tests: root inference through a validated .cmd with four rejected impostors, an oversized shim, POSIX unchanged; the PATH gate as a source contract; and a new studio/backend/tests/test_reset_password_command.py covering both interpreter shapes, the spaced-path fallback, the prefix check, and drift between the bootstrap here and _WINDOWS_CLI_ENTRYPOINT.
|
@codex review |
|
Codex Review: Didn't find any major issues. What shall we delve into next? Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 3b66a91f01
ℹ️ 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".
| if (-not (Test-Path -LiteralPath $ShimCmd -PathType Leaf)) { return $false } | ||
| if (-not (Test-Path -LiteralPath $ShimExe -PathType Leaf)) { return $true } |
There was a problem hiding this comment.
Validate the cmd shim before recommending it
When a custom Studio root contains an unwritable foreign bin\unsloth.cmd and the generated .exe is missing or quarantined, Write-UnslothCmdShim leaves the foreign file in place, but this existence-only check marks it as preferred. The decline and manual-instructions branches then advertise an unrelated or unusable command, even though $ShimUsable correctly rejects the same file. Fresh evidence after the prior fix is that this separate preference helper still bypasses Test-UnslothCmdShimFile; apply the ownership check here as well.
Useful? React with 👍 / 👎.
| error = self._launcher_runs_error() | ||
| if error is self._POLICY_BLOCKED: | ||
| return self._interpreter_health_error(error) |
There was a problem hiding this comment.
Retain recovery copies after policy-only validation
When Application Control denies unsloth.exe and setup publishes a PE-shaped but corrupt replacement, this treats the launcher as healthy solely because the adjacent interpreter can import the CLI. validate_launcher then marks the update validated and deletes the backup and stale launchers because _is_valid_pe checks only the MZ prefix; if the policy is later removed or relaxed, the generated launcher is unusable and every recovery copy has been destroyed. Preserve the recovery files whenever the launcher itself never successfully answered --version.
Useful? React with 👍 / 👎.
| # An Application Control policy can block the generated | ||
| # unsloth.exe while the signed interpreter beside it still | ||
| # runs, so name a route that does not go through it. | ||
| f" - or through the interpreter: {sys.executable} -I -m unsloth_cli studio\n" |
There was a problem hiding this comment.
Emit a shell-safe interpreter recovery command
When the Windows interpreter lives under a path containing spaces, such as the common C:\Users\Jane Doe\... layout, this newly printed command splits the executable path and cannot be pasted into either cmd.exe or PowerShell as shown. This is specifically the fallback offered when Application Control makes the .exe launcher unusable, so the affected user receives no working direct-launch command from this diagnostic. Format the interpreter invocation for the target shell, including PowerShell's call operator where needed.
Useful? React with 👍 / 👎.
#8586 went in as a single squashed commit, so main's copy of that work shares no history with the copies this branch merged, and git saw every line the two have in common as a conflict. Resolved file by file: * install.sh, studio/setup.sh and tests/sh/test_uv_pinned_release.sh are #8586's alone and this branch never touched them, so they take main's version whole. That is also the newer one: #8586 gained commits after the last merge here. * install.ps1, six hunks. The Studio launcher command, the launch-studio.ps1 byte comparison and its Unblock-File rationale stay this branch's, since they are #8586's substance plus this branch's changes on top. The UNC launcher check, the uv source-precedence comment and the staged-probe comment take main's: all three are newer there, and the UNC one now covers mapped drives through DriveInfo, which the version here did not. * studio/setup.ps1 takes main's on both hunks. It reads the pinned-install verdict off a script-scope flag rather than the pipeline, because Invoke-SetupCommand returns [int]$LASTEXITCODE and not the block's value, so the Select-Object form here could not have driven the winget fallback at all. * studio/src-tauri/src/process.rs, one region where both sides added disjoint functions: this branch's managed CLI invocation builders and main's working-directory and environment context helpers. Both kept. The conflict cut through build_managed_cli_command_tokio, whose closing brace was on the far side, so that had to be put back by hand. * preflight/managed.rs merged clean but not correct: main widened run_cli_probe and probe_cli_capability to Result so a context failure can be told apart from a bad install, and the two early returns this branch added still handed back bare values. They return Ok(false) and Ok(None): a venv with no interpreter beside the launcher is a verdict, not a failure to ask. Verified on the merged tree: 4657 Python tests, 359 Rust tests, every PowerShell suite, and #8586's test_uv_pinned_release.sh. The three frontend contract tests and test_amd_venv_repair_loop.ps1 that were red on this branch an hour ago are green, fixed by #8703 on main.
c24a93c to
6ececda
Compare
|
@codex review |
|
Codex Review: Didn't find any major issues. Keep it up! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
Two conflicts, both from unslothai#8490 / unslothai#8592 landing on main after this branch was cut. tests/python/test_windows_studio_update_launcher.py: main stubs the runtime gate, whose process scan is Windows-only, so without it every test in the file dies on a real Windows host reading .stdout off a fake that carries only a returncode. This branch had widened the _fail_if_install_damaged stub on the same line. Keep both. studio/setup.ps1: main explains that no unsloth.exe rename is needed because install.ps1 runs the CLI through the venv's python.exe. Keep that, and record that duplicate metadata repair is the one pass that does reinstall unsloth under SKIP_STUDIO_BASE, which is why the CLI wraps this script in its launcher transaction.
|
pre-commit.ci run |
`validate_launcher` sampled `_launcher_health_error()` before attempting
recovery and then printed that, while `_restore_runnable()` returned a bare
bool -- so the verdict recovery actually acted on was computed and discarded.
Reproduced at head with the file's own fixtures: launcher quarantined away,
managed CLI answering `returncode = 3`. `_recovered_cli_health_error()`
returns "the managed Python CLI returned 3 for --version", and the user is
told:
Error: Unsloth Studio update failed because the updated launcher is not on disk.
Once the launcher is gone `_launcher_health_error()` answers `_LAUNCHER_ABSENT`
whatever the cause, so that message named the one condition
`_recovered_cli_health_error` exists to excuse (unslothai#8592) and said nothing about
the update. It is why unslothai#9804 cannot be diagnosed from its own log: the report
shows "not on disk" and "Manual recovery copy retained at", which together mean
the interpreter probe failed too -- on an install whose Studio then started
normally -- and nothing says why.
`_restore_failure_reason()` is the same walk returning the reason;
`_restore_runnable()` is now the bool of it, so `__exit__` is unchanged.
`validate_launcher` reports `reason or error`: the sampled error still answers
when recovery SUCCEEDED and the launcher setup published is itself the broken
one, which is what the `published` arm is for.
`_recover_missing_launcher` already reports its cause this way, so this is the
exit-time half of a convention the entry-time half already keeps.
Regression tests `test_a_failed_recovery_reports_the_verdict_it_acted_on` and
`test_a_failed_recovery_with_no_interpreter_says_both` pin both reasons the
interpreter fallback can give; both fail on the unfixed code. The second also
covers `_interpreter_health_error`'s "is missing" wording, which had no test
and is only reachable through `_recovered_cli_health_error`.
`test_a_recovered_launcher_still_reports_what_setup_published` is the parity
guard for the case the reason must not speak in.
One consequence worth naming: the message for a failed recovery now varies with
what the interpreter said, where it was previously fixed. Nothing asserted the
old text, and `tests/python` is unchanged at 47 pre-existing failures with 3
added passes, but a downstream log scraper matching the literal absence string
would stop matching.
Refs unslothai#9804.
`validate_launcher` sampled `_launcher_health_error()` before attempting
recovery and then printed that, while `_restore_runnable()` returned a bare
bool -- so the verdict recovery actually acted on was computed and discarded.
Reproduced at head with the file's own fixtures: launcher quarantined away,
managed CLI answering `returncode = 3`. `_recovered_cli_health_error()`
returns "the managed Python CLI returned 3 for --version", and the user is
told:
Error: Unsloth Studio update failed because the updated launcher is not on disk.
Once the launcher is gone `_launcher_health_error()` answers `_LAUNCHER_ABSENT`
whatever the cause, so that message named the one condition
`_recovered_cli_health_error` exists to excuse (unslothai#8592) and said nothing about
the update. It is why unslothai#9804 cannot be diagnosed from its own log: the report
shows "not on disk" and "Manual recovery copy retained at", which together mean
the interpreter probe failed too -- on an install whose Studio then started
normally -- and nothing says why.
`_restore_failure_reason()` is the same walk returning the reason;
`_restore_runnable()` is now the bool of it, so `__exit__` is unchanged.
`validate_launcher` reports `reason or error`: the sampled error still answers
when recovery SUCCEEDED and the launcher setup published is itself the broken
one, which is what the `published` arm is for.
`_recover_missing_launcher` already reports its cause this way, so this is the
exit-time half of a convention the entry-time half already keeps.
Regression tests `test_a_failed_recovery_reports_the_verdict_it_acted_on` and
`test_a_failed_recovery_with_no_interpreter_says_both` pin both reasons the
interpreter fallback can give; both fail on the unfixed code. The second also
covers `_interpreter_health_error`'s "is missing" wording, which had no test
and is only reachable through `_recovered_cli_health_error`.
`test_a_recovered_launcher_still_reports_what_setup_published` is the parity
guard for the case the reason must not speak in.
One consequence worth naming: the message for a failed recovery now varies with
what the interpreter said, where it was previously fixed. Nothing asserted the
old text, but a downstream log scraper matching the literal absence string
would stop matching.
Refs unslothai#9804.
…nslothai#9924) * studio: report why launcher recovery failed, not that it was absent `validate_launcher` sampled `_launcher_health_error()` before attempting recovery and then printed that, while `_restore_runnable()` returned a bare bool -- so the verdict recovery actually acted on was computed and discarded. Reproduced at head with the file's own fixtures: launcher quarantined away, managed CLI answering `returncode = 3`. `_recovered_cli_health_error()` returns "the managed Python CLI returned 3 for --version", and the user is told: Error: Unsloth Studio update failed because the updated launcher is not on disk. Once the launcher is gone `_launcher_health_error()` answers `_LAUNCHER_ABSENT` whatever the cause, so that message named the one condition `_recovered_cli_health_error` exists to excuse (unslothai#8592) and said nothing about the update. It is why unslothai#9804 cannot be diagnosed from its own log: the report shows "not on disk" and "Manual recovery copy retained at", which together mean the interpreter probe failed too -- on an install whose Studio then started normally -- and nothing says why. `_restore_failure_reason()` is the same walk returning the reason; `_restore_runnable()` is now the bool of it, so `__exit__` is unchanged. `validate_launcher` reports `reason or error`: the sampled error still answers when recovery SUCCEEDED and the launcher setup published is itself the broken one, which is what the `published` arm is for. `_recover_missing_launcher` already reports its cause this way, so this is the exit-time half of a convention the entry-time half already keeps. Regression tests `test_a_failed_recovery_reports_the_verdict_it_acted_on` and `test_a_failed_recovery_with_no_interpreter_says_both` pin both reasons the interpreter fallback can give; both fail on the unfixed code. The second also covers `_interpreter_health_error`'s "is missing" wording, which had no test and is only reachable through `_recovered_cli_health_error`. `test_a_recovered_launcher_still_reports_what_setup_published` is the parity guard for the case the reason must not speak in. One consequence worth naming: the message for a failed recovery now varies with what the interpreter said, where it was previously fixed. Nothing asserted the old text, but a downstream log scraper matching the literal absence string would stop matching. Refs unslothai#9804. * Keep the published launcher's own verdict when recovery also fails * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Trim comments on launcher recovery reason --------- Co-authored-by: oobabooga <[email protected]> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Daniel Han <[email protected]>
Fixes #8490, and the earlier report of the same failure in #7147.
The bug
pyproject.tomldeclaresunsloth = "unsloth_cli:app". On Windows that entry point is materialised as a generated, unsigned launcher.exeat<venv>\Scripts\unsloth.exe. AppLocker, WDAC and Smart App Control deny it atCreateProcess, while the venv'spython.exe, which is a copy of the signed CPython binary, still runs fine. So the install is healthy and Windows is blocking one file.install.ps1ran& $UnslothExe studio setupunder$ErrorActionPreference = "Stop", so the blocked launch threw before$setupExitwas ever assigned. Theif ($setupExit -ne 0)branch and itsExit-InstallFailurewere unreachable, the error escapedInstall-UnslothStudio, and the user got PowerShell's raw formatter output:This is not ROCm specific. It reproduces on a clean Windows runner with a deny rule scoped to that single file.
The fix
The desktop updater already solved this in
update.rsby reaching the CLI through the interpreter beside the launcher. This applies the same idea to every remaining call site: the setup handoff, interactive autostart, the generatedlaunch-studio.ps1behind both shortcuts, the Tauri backend spawn, desktop auth provisioning, the install health probe, the preflight capability probes, and thestudio runrespawn.unsloth.exeis still generated, still hardlinked into the shim directory, and still works. Machines without a policy are untouched. Nothing depends on it any more.Also added:
python -m unsloth_clias a supported, documented entry point.bin\unsloth.cmdbeside the shim.exe, sounsloth.cmdis available where the.exeis denied. PATHEXT resolves.EXEbefore.CMD, so bareunslothis unchanged on a normal machine; the installer probes the shim once and prints the.cmdform only when it observes a block.build_managed_cli_commandinprocess.rs, so the updater and the backend can no longer drift apart.The trampoline is a single string shared by
install.ps1,studio/src-tauri/src/process.rsandunsloth_cli/commands/studio.py:Both halves are load bearing:
argv[0]is assigned before the import, becauseunsloth_cli/__init__decides at import time whether it is the console script. That gate controls the Windows UTF-8 stream reconfigure and the-np<N>argv rewrite, and it keeps typer'sprog_nameatunslothso usage and error strings do not change.sys.path[:1]filter drops the working directory entry thatpython -cadds and a console script does not. That is what lets the invocation stay off-I.-Iwould drop the cwd too, but it also discardsPYTHONPATH,PYTHONWARNINGS,PYTHONHASHSEEDand user site-packages, all of which the console script honours.Behaviour on a machine with no policy is unchanged
That is enforced, not asserted:
tests/python/test_module_entry_point.pycompares stdout, stderr and exit code between the console script,-m unsloth_cliand the trampoline over--version,--help,studio --helpand two error paths. All byte identical.PYTHONPROFILEIMPORTTIME=1, the console script and the trampoline now both emit 24,815 bytes of profiling stderr. Under-Ithe trampoline emitted none, which is why-Iis gone.unsloth_cli/directory in the working directory still does not shadow the managed package.bin\unsloth.cmd,launch-studio.ps1and the two.lnkfiles are content compared before being written, so a second install changes no bytes and no timestamps.Tests
tests/studio/test_application_control_cli_fallback.ps1pins the parts that are easy to get subtly wrong:InnerExceptionforWin32Exception.NativeErrorCode == 1260, and never off$LASTEXITCODE. No process was created, so that variable holds a stale value from whatever ran last.Start-Processreceives one pre-quoted command line.-ArgumentListjoins an array with spaces and quotes nothing, so passing the trampoline as an array element hands Python eleven arguments instead of one.bin\unsloth.cmdonly counts as an ownership marker when its contents match the shim we write. A file of that name in an unrelated directory must not qualify a custom root for removal..github/workflows/windows-application-control-ci.ymlreproduces the report end to end: AppLocker denies onlyScripts\unsloth.exefor a standard user, a negative control proves the rule is actually enforced and fails the job loudly if the stub runs, and the full installer then has to succeed.Notes for reviewers
studio/setup.ps1needed no functional change. It already prefers$env:UNSLOTH_SETUP_PYTHONand never re-invokes the launcher; only its comments claimed otherwise.unsloth.exe.process.rsidle detection, the installer's running-process scan and_studio_runtime_gatematch by venv root, so a python hosted Studio is still detected and an update still cannot mutate a venv somebody is running._WindowsLauncherUpdateTransactionstill probes the launcher first and only consults the interpreter when the probe comes back 1260. Validating the file it just restored is the point of that check, and going interpreter only would be blind to a corrupt launcher on every machine without a policy. The cost is one denied-launch event per update on affected machines.