Repository navigation
Add install.sh --portable and --root for a single-directory install - #10189
danielhanchen wants to merge 88 commits into
Conversation
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 8350451c3b
ℹ️ 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".
| --shortcuts-only) _SHORTCUTS_ONLY=true ;; | ||
| --with-llama-cpp-dir) _next_is_llama_cpp_dir=true ;; | ||
| --portable) _PORTABLE_MODE=true ;; | ||
| --root) _next_is_root=true ;; |
There was a problem hiding this comment.
Reject --root when its path argument is absent
When --root is the final argument, _next_is_root remains true but is never validated alongside the existing --package, --python, and --with-llama-cpp-dir checks, so the command silently performs a default non-portable install. If another option follows, that option is consumed as the directory name instead. Reject the missing value rather than installing somewhere the user did not request.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Already handled before this review landed, in a3f79db. install.sh now validates _next_is_root alongside --package, --python and --with-llama-cpp-dir: a trailing --root, an empty --root "", --root= and a flag-shaped value such as --root --local all exit with an error rather than silently installing to the default location. tests/sh/test_install_portable_root.sh covers all four.
| "export UNSLOTH_HOME='$UNSLOTH_ROOT'" \ | ||
| "export UNSLOTH_PORTABLE=1" \ | ||
| "export UNSLOTH_STUDIO_HOME='$STUDIO_HOME'" \ | ||
| "export UNSLOTH_LLAMA_CPP_PATH='$UNSLOTH_ROOT/llama.cpp'" \ |
There was a problem hiding this comment.
Shell-quote paths written into the portable shim
For a valid --root path containing an apostrophe, these interpolations produce malformed shell syntax (for example, export UNSLOTH_HOME='/tmp/user's root'). The installation can complete, but every launch through <root>/bin/unsloth then fails while parsing the wrapper; crafted path text can also become commands when the shim runs. Escape the values as is already done for studio.conf, or generate the assignments with a shell-safe quoting routine.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Already handled before this review landed, in 6a5ea17. The three interpolated values go through the same sed "s/'/'\\''/g" escape studio.conf uses. tests/sh/test_install_portable_shim_quoting.sh drives 14 hostile paths (apostrophes, quotes, backticks, $(...), newlines, spaces, tabs) through sh -n and is differential: it fails on the pre-fix generator with "Unterminated quoted string".
| # The master root, one level above STUDIO_HOME. llama.cpp, node, | ||
| # whisper.cpp and the caches are its siblings, matching the layout | ||
| # the runtime already builds from $HOME/.unsloth. | ||
| UNSLOTH_ROOT="$_resolved_root" |
There was a problem hiding this comment.
Reject unsafe portable roots before populating them
Portable mode accepts any writable resolved path, including $HOME for an ordinary user and / when run as root, even though scripts/uninstall.sh explicitly refuses those paths as unsafe. Such values merge the install's generic bin, share, cache, and studio directories into a user or system root, may overwrite an existing bin/unsloth, cannot be removed by the advertised uninstaller, and lead the completion message to recommend an unsafe rm -rf. Apply the uninstaller's deny list before assigning the portable master root.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not adding a deny list here. --root is an explicit, user-named destination, and it inherits exactly the contract UNSLOTH_STUDIO_HOME has had since #5190: install.sh accepts any writable resolved path, and scripts/uninstall.sh already anticipates that and refuses with "refusing to remove unsafe path: " rather than doing something dangerous. The comment at uninstall.sh:549 states that arrangement in so many words. The closing message does not emit a copy-pasteable rm -rf either; it names the root and prints the UNSLOTH_HOME=... uninstall line. Turning a documented, already-guarded latitude into a hard rejection is a policy change, and it would break the person who genuinely wants their root somewhere the deny list happens to cover.
57b8721 to
61fdb00
Compare
|
Pushed fixes from a simulation pass over this branch. Three real defects, all found by testing rather than reading, plus a Windows gap I should have caught when I opened this. The shim broke on an apostrophe in the install root. Every path in it is embedded in a single-quoted shell string, so
All four forms, Windows would have produced a split install.
To correct the description above: Verification. Re-ran the whole thing end to end after every fix: Also simulated the upgrade path, since that is the case most likely to bite existing users: 59 shell tests pass, plus the The CI failures showing on the previous head were cancellations, not test failures. |
24fe35b to
06ffe56
Compare
cfd69f8 to
6f2e689
Compare
6f2e689 to
0efafaf
Compare
|
@codex review |
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
unsloth/unsloth_cli/commands/studio.py
Lines 211 to 212 in 0efafaf
When install.sh --portable uses its default $HOME/.unsloth root and the user invokes the CLI by activating $HOME/.unsloth/studio/unsloth_studio directly, STUDIO_HOME equals the legacy path, so _STUDIO_HOME_IS_CUSTOM is false and this return prevents _portable_master_root() from reading the marker. unsloth studio update consequently runs without the portable uv/npm variables, and its launcher refresh reruns install.sh --shortcuts-only as a normal installation, writing under $HOME/.local; the fresh evidence beyond the earlier nested-root fix is that only the default portable layout compares equal to the legacy root and bypasses the new marker code. Check and export marker-derived portable settings before returning for non-custom roots.
ℹ️ 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".
| && chmod +x "$_shim_tmp" 2>/dev/null \ | ||
| && mv -f "$_shim_tmp" "$_shim_path" 2>/dev/null |
There was a problem hiding this comment.
Reject a symlink-to-directory portable shim target
If an existing portable root contains bin/unsloth as a symlink to a directory, the preceding directory guard deliberately lets it through because it is a symlink, but this mv follows the directory target instead of replacing the link. The local mv --help identifies -T as the option that treats DEST as a normal file, and a direct reproduction leaves the link intact while moving .unsloth.shim.$$ into the linked directory; the installer then reports success even though the launcher is still a directory and may have written outside the portable root. Reject or unlink this target before publishing the shim.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Reproduced the mechanism and it is exactly as described: with bin/unsloth a symlink to a directory, mv -f left the link intact and deposited the temp file inside it. POSIX puts this beyond GNU too, since the move-into form applies when the final operand is an existing directory "or referenced if target_dir is a symbolic link referring to an existing directory".
Not changing it, because nothing reachable creates that shape. In portable mode _LOCAL_BIN is /bin, a directory the installer owns; install.sh writes a regular file there, the non-portable branch already uses ln -sfn, and the only other writer of studio_bin_root is cloudflared. Worst case is a stray .unsloth.shim.$$ inside a directory the user hand-linked there, with no data loss. That puts it under hardening rather than a bug on well-formed input.
Worth flagging for whoever reads this next: mv -T is GNU coreutils only. install.sh is #!/bin/sh and also runs on macOS, whose BSD mv defines only -f -h -i -n -v, with -h as the analogue and its own man page calling these "non-standard and their use in scripts is not recommended". So that suggestion applied verbatim would have broken every macOS install; the portable form would be an explicit [ -L ] reject.
|
Checked that the default install path is unchanged, with the new uv, npm and cache variables only emitted under --portable or --root, and that the shim and studio.conf carry them through. Will get this reviewed once #10188 lands. |
0efafaf to
2bfb9ab
Compare
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 2bfb9ab7c5
ℹ️ 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".
| # Marker so the roots survive an invocation carrying none of this | ||
| # environment: `source .../activate` reaches the venv binary past the shim. | ||
| printf '%s\n' "$UNSLOTH_ROOT" > "$UNSLOTH_ROOT/.unsloth-portable-root" 2>/dev/null || true |
There was a problem hiding this comment.
Refuse symlinks when publishing the portable marker
When an existing selected root contains .unsloth-portable-root as a symlink, this redirection follows the link and truncates its target before writing the root path; that target can be an arbitrary file outside the portable root, so installing into an otherwise valid directory can corrupt user data and violate containment. Publish the marker through a temporary regular file and rename it, or explicitly reject/unlink a symlink target instead of redirecting through it.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed the mechanism and then rejected it on reachability, same as the /bin/unsloth symlink last round. With a symlink at that path, the redirection did overwrite the link's target and leave the link intact, and POSIX open() resolves through symlinks without O_NOFOLLOW while > is O_WRONLY|O_CREAT|O_TRUNC, so this is the classic shape rather than anything shell-specific.
But only install.sh ever writes that file, the name appears in no documentation anywhere in the tree, and there is no copy, backup or restore path that could turn a regular file into a symlink there. It needs a hand-crafted or planted path, which puts it outside the bar for this PR.
…ries The contained mode filtered its walk to \( -type f -o -type d \), so a leak that is a symlink was invisible to it. That is the leak class the mode exists for: uv puts interpreter links in ~/.local/bin by default, and the unsloth shim on a normal install is a symlink too, so an install that regressed the UV_PYTHON_BIN_DIR pin would still have been reported contained. A fixture with three leaks under already-allowed parents reports OK today and fails once the same three are regular files. Drop the -type filter entirely rather than adding -type l: no entry type is legitimately not a leak, and sockets and fifos were invisible as well. find defaults to -P, so -newer reads the link's own lstat mtime and a dangling link is reported instead of erroring. Second hole in the same block: the ~/.local, ~/.cache and ~/.config allowance is there because the OS bumps a directory's mtime, but it matched on name alone. As a symlink, any of those redirects the whole subtree out of $HOME and hides every child from the walk, so the allowance now requires a real directory. A symlink inside the root pointing outside it stays allowed and is pinned by a test: contained asserts nothing was written outside the root, and what lives outside it is the macho check's business.
_in_root_master_root opens the master-root record "rb" and os.fsdecodes it, because a POSIX path is a byte string. _portable_root_env read share/studio.conf with errors="replace", so the two disagreed on any root holding a byte that is not valid UTF-8. create_studio_shortcuts writes those values from the resolved root verbatim, escaping only the apostrophe, so the raw byte reaches this read. U+FFFD is not an unusable value here, it is a different creatable one: the single byte re-encodes as the three bytes of U+FFFD, so an activated-venv launch pointed UV_CACHE_DIR and PIP_CACHE_DIR at a sibling of the root and refilled the caches outside it. Reproduced on ext4 with a root named opt\xffunsloth. The except clause widens to ValueError for Windows, where os.fsdecode is UTF-8 with surrogatepass and raises rather than mangling. Only install.sh writes this file and Windows paths are UTF-16, so a conf that is not valid UTF-8 there was not written by us and the derived values should stand.
cache_root() is studio_root() / "cache", which in the nested layout is <master>/studio/cache. So a direct uvicorn or activated-venv launch pinned UV_CACHE_DIR at <master>/studio/cache/uv while _export_portable_roots, the share/studio.conf it writes, the generated bin/unsloth wrapper and the CLI's _portable_root_env all pin <master>/cache/uv. wheel_utils.install_wheel and worker._pip_install_cmd both prefer uv at runtime, so that is a second copy of the wheels the installer already downloaded. Bare --portable is the same shape, its root being $HOME/.unsloth with Studio at $HOME/.unsloth/studio. The flat layout already agreed, because the master root is the Studio root there, and UNSLOTH_PORTABLE=1 with no master keeps the cache_root() fallback. A test asserts the flat case stays put so this cannot quietly move it. Auditing the rest of the dict for the same class turned up CUDA_CACHE_PATH: install.sh:933 exports $UNSLOTH_ROOT/cache/cuda, studio.conf and the wrapper restate it, the CLI derives it the same way, and the resolver had root / "cuda". Both now go through _portable_master_cache_dir, applied as an override so a non-portable install keeps its cache_root()-relative paths. An existing <master>/studio/cache/uv from an earlier launch stays on disk and only stops being written to. It is inside the same portable root, so deleting the root still removes it, and both caches re-download; that is the PIP_CACHE_DIR case, not the MPLCONFIGDIR one.
…or gate green Two things CI caught that my own runs did not, because neither tests/test_installer_system32_guard.py nor tests/test_python39_compatibility.py was in any suite I ran. The System32 guard rewrites relative path env vars before it moves the working directory, and its parity test reads the override list straight out of storage_roots.py so the guard cannot fall behind. PIP_CACHE_DIR went into that dict earlier in this PR and never into _RELATIVE_PATH_ENV, so a relative value would have been retargeted by the move. UV_CACHE_DIR and CUDA_CACHE_PATH were already listed; only pip was missing, and install_wheel and worker._pip_install_cmd both fall back to pip whenever uv is missing or fails. The floor gate ratchets the number of studio files that evaluate a PEP 604 union below Python 3.10. test_setup_cache_env_master_caches.py annotates a helper with a "str | None" return, which is evaluated at function definition, taking the count from 35 to 36. Add the __future__ import rather than raising the ratchet.
process.rs carries its own RELATIVE_PATH_ENV, and a Rust test reads unsloth_cli/_system_dir_guard.py and asserts the two lists name exactly the same variables, because a name in one and not the other means the same install puts state in two folders depending on which layer moved the child. Adding PIP_CACHE_DIR to the CLI guard alone broke that pairing. No cargo on this machine, so I could not run the Rust test. Instead I replicated both of its assertions against the two files: 63 names each side, nothing pinned by the desktop that the guard is missing, and the quoted-string count the test compares now agrees. Dropping the entry again takes it to 62 against 63.
install.sh already refused a root with surrounding POSIX whitespace, but the Python readers trim with a bare str.strip(), which removes 29 characters, not six. A --root ending in one of the other 23 was accepted and recorded verbatim, and unsloth_home() then resolved a different, possibly non-existent directory. Node, llama.cpp and whisper.cpp all hang off that value, so one stripped character takes the whole managed toolchain with it: with the binaries installed under the requested root, the resolvers report node_binary_exists False and llama_server_found None. Two things wider than the report. Four of the 23 are ASCII, U+001C to U+001F, which are str.isspace() and are not [[:space:]] anywhere. And the size of the gap depends on the locale: [[:space:]] covers 15 of the 23 under C.UTF-8 and none of them under LC_ALL=C, which is what a piped curl into sh gets. So the gate matches UTF-8 bytes rather than a character class, and its answer does not move with the caller's shell. Rejecting at the door rather than aligning the readers. Aligning is not a small change: bare str.strip() on these roots appears at about 13 Python sites across five files, and install.ps1 trims with .NET String.Trim(), whose whitespace set excludes U+001C to U+001F and so disagrees with Python's. That would put one trim contract in three languages that do not match, which is the installer and the runtime disagreeing about one value in a new place. Refusing makes every reader agree by construction, and Python's set is a superset of .NET's, so the PowerShell reader is covered too. The cost is that a directory whose name legitimately ends in one of these characters cannot be an install root. That is the cost already paid for a trailing space by the check directly above. The test derives the character set from Python at run time instead of copying the installer's list, so a code-and-test pair that were both wrong would still fail.
UNSLOTH_HOME takes the precedence chain in _custom_studio_roots on its own, so UNSLOTH_STUDIO_HOME and STUDIO_HOME are ignored while it is set. That is the tested policy and it stays. What was wrong is that nothing said so. Every build shipped before UNSLOTH_HOME existed read UNSLOTH_STUDIO_HOME as "remove this install", and for an env-mode install re-exporting it is the only way to reach the tree, because install.sh puts DATA_DIR at $STUDIO_HOME/share and leaves no breadcrumb in $HOME. So someone upgrading from such a build, with UNSLOTH_HOME left over from a portable install or exported for anything else, saw "Unsloth Studio uninstalled" and "No studio.db was found" while that tree and its chat history stayed on disk, with nothing naming the variable that had been ignored. Report the skipped root, say the chat history was kept, and give a command that reaches it. Suppressed when both variables name one tree and when the Studio root is the master root's own studio/ child, since that one was removed with the master root and there is nothing left behind to report. The suggested command blanks UNSLOTH_HOME rather than using env -u: the branch trims before testing -n, so an empty value falls through exactly as an unset one does, and BSD env on macOS is not somewhere to send a user for a -u that may not be there. The test pins both halves, including that env -u does not come back.
Both tests lifted the studio.conf writer out of install.sh with a sed range that started at the comment "studio.conf: exe path". #10204 removed that comment, so the range came back empty. test_portable_bun_cache_pinned.sh has a non-emptiness guard and said so; test_install_portable_root.sh had none and reported all eleven exports as missing instead, which points at the wrong file. Start at the UNSLOTH_EXE line the block actually writes, and give test_install_portable_root.sh the same guard so an empty range names itself. tests/sh: 0 failures across the directory.
main's uv cache migration added _restore_uv_cache_marker to _on_install_exit and _on_install_signal. Five tests lift those handlers out of install.sh and run them standalone, and the helper is defined outside every block they lift, so the handlers exited 127. The assertions then read that as the product failing to roll anything back: 5 files failing, all of them reporting restored markers as missing. Stub it in each harness, and guard the stub with a grep for the call so that if main ever drops it we are told to drop the stub rather than leaving a no-op shadowing a real helper. tests/sh: 0 failures across the directory.
…r asked for Five defects found by reviewing the stack against its own acceptance criteria. Each fix was checked by removing it again and watching the new test fail. 1. Uninstalling no longer empties ~/.unsloth. --portable with no --root selects that directory for the user, so it is the one root they never named, and anything they keep beside Unsloth is theirs. The master-root loop rm -rf'd it whole; it now takes the portable children by name and leaves the rest to the default block's rmdir, which refuses a non-empty directory. A root the user DID name still goes in one piece, as it always has for UNSLOTH_STUDIO_HOME. Before: a file at ~/.unsloth/important.txt was deleted. After: it survives. 2. The portable shim, share/studio.conf and _export_portable_roots defaulted the cache locations instead of seizing them. storage_roots._setup_cache_env() has always yielded to an explicit value and main's _configure_uv_cache reports "preserving custom UV_CACHE_DIR", so the same install honoured or discarded a user's multi-GB wheel cache depending on the entry point. Identity stays forced, and so does UV_NO_MODIFY_PATH, which is a promise rather than a path. The installer now names any cache it kept, since one outside the root means rm -rf on the root no longer removes everything. 3. Converting a pre-#5190 install with --portable is no longer refused. The ownership guard wants a sentinel under STUDIO_HOME, and #5190 shipped all three of them alongside custom-root support, so an install last refreshed before 2026-05-05 has none: its studio.conf went to ~/.local/share/unsloth. That tree was accepted by a plain upgrade and refused by the same upgrade plus --portable. The legacy location now counts, but only for the legacy default root, never for a directory the user named. 4. .unsloth-master-root is written through a temporary and renamed. The redirection truncated on open, so a write that then failed left a previous valid record empty, and the error arm cleared its own rollback slot. A full volume is exactly what a portable root on a removable disk meets. The -d test in front is not redundant: mv moves a file INTO a directory rather than failing, which would have reported success and left no record. 5. A plain re-run keeps a portable install portable. The documented update is `curl ... | sh` with no arguments, and the shim's environment does not reach a fresh shell, so that read as a request for a normal install: the markers went, and every cache moved back under $HOME. The installer now adopts the marker a previous run left. Converting back is still available and now has to be asked for, with UNSLOTH_PORTABLE=0. This changes a contract four tests asserted deliberately. What those tests protect is that a marker cannot leave the tree reading as portable with no way out; that still holds, because UNSLOTH_PORTABLE=0 makes the installer normal, which clears the marker, which makes the runtime normal. Only the default moved, from converting silently to preserving what is there. Also: portable mode moves the Hugging Face cache under the root, which costs a re-download rather than a recompile, so the installer now says so when it finds a warm ~/.cache/huggingface and the user named no HF variable of their own. tests/sh: 0 failures across the directory.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: c23775e1c9
ℹ️ 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 [ -n "$_epr_kept" ]; then | ||
| substep "kept your own cache locations:$_epr_kept" "$C_WARN" | ||
| substep "any of these outside $UNSLOTH_ROOT stay behind when the root is removed" "$C_WARN" |
There was a problem hiding this comment.
Include backend-only overrides in the escape warning
When a portable install inherits an explicit backend storage override such as TORCH_HOME, HF_HUB_CACHE, HF_DATASETS_CACHE, or UNSLOTH_STUDIO_PROJECTS_HOME, the runtime deliberately preserves that external path, but _epr_kept is populated only by the installer-specific _epr_default calls above. This warning is therefore absent and the closing summary still says everything lives under UNSLOTH_ROOT, even though model caches or project data can remain outside it after the advertised rm -rf. Include every runtime-preserved storage override in this check, or otherwise report that the install is not fully contained.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not taking this one. The premise is right that _epr_kept covers only the variables the installer pins, but install.sh never sets or writes through TORCH_HOME, HF_HUB_CACHE, HF_DATASETS_CACHE or UNSLOTH_STUDIO_PROJECTS_HOME, so an inherited one causes no wrong path, no re-download and no data loss. That makes it a completeness gap in a warning rather than a defect, and the README already covers the HF case.
A second five-way review of the fixed stack. Every claim below was reproduced here before being acted on, and each fix was checked by removing it again and watching the new assertion fail. 1. An interrupted reinstall no longer changes a portable root's layout. This was reported in the first round and not acted on because I could not reproduce it; I could not because it needs SIGKILL, and HUP/INT/TERM are trapped and roll back. _start_studio_venv_replacement renames <root>/unsloth_studio aside before building the new one, and the flat selector required that directory to exist, so a run killed in that window made the retry resolve <root>/studio: a different data root, with the real studio.db and every cache stranded at <root>. The three sentinels that survive the rename all name the venv path exactly, which is what keeps a nested root mid-reinstall resolving nested. 2. Adoption now recognises a nested portable root. A nested install records its master root in <studio>/.unsloth-master-root, not in a flat marker, so `--root R` plus a rerun carrying UNSLOTH_STUDIO_HOME=R/studio -- which is what share/studio.conf exports -- read as normal with BOTH markers on disk, and the reset then removed them. The record names the root outright, so nothing is inferred; one that is empty or relative is refused rather than becoming a root resolved against the caller's cwd. 3. The ~/.unsloth uninstall exception now covers the flat layout. It removed the markers but left the owned venv and studio.db, because the default block only knows the nested shape: gigabytes retained with their identifying metadata stripped, and the run still reporting success. Gated on our own owner marker, so an unowned unsloth_studio directory is still left alone. 4. The two new backend cache tests no longer leak a replacement module. Both pop utils.hf_cache_settings so the resolver re-snapshots the environment and never put it back, so a later test wrote one module object and read another; test_hf_cache_settings.py::test_diffusion_cache_root_follows_a_live_switch failed only when they ran first. They now carry the same guard test_setup_cache_env_containment.py already had. Two of those tests also still asserted the forced cache exports that the previous round deliberately replaced with defaulted ones. I had missed all three Python failures by running only one file out of studio/backend/tests. tests/sh: 0 failures. studio/backend/tests, every cache/portable/storage_root test: 21 failures, the same 21 IDs as origin/main, none in files this stack touches.
The documented way back to a normal install is UNSLOTH_PORTABLE=0, and the place a user runs it from is a shell opened inside the portable install. Both the shim and share/studio.conf export UNSLOTH_HOME there, so the run carried a root nobody typed, a root is what makes it portable fired, and the escape did nothing at all. A typed off value now outranks an inherited root, and converts the install that root names rather than starting a fresh one at the default location. A root typed on the same command line is different: --root or --portable together with an off value is a contradiction, so it is refused instead of guessed. Nine existing tests anchored their extraction on the exact text of the --portable arm, and one read the off-list from a case arm that now has the empty value split out of it. Both anchors updated.
HUGGINGFACE_ASSETS_CACHE is deprecated but not removed, and huggingface_hub reads HF_ASSETS_CACHE ahead of it. Pinning the modern name under the portable root therefore overrode an assets cache the user had explicitly chosen, without saying so: the alias stayed in the environment and simply stopped meaning anything. The blank-counts-as-unset guard only protects the name it is keyed on, so the skip is keyed on the alias instead. Blank still counts as unset, or an inherited empty alias would leave the assets cache outside the root the run promises holds everything.
A nested portable install keeps node/, llama.cpp/ and whisper.cpp/ beside studio/ under the master root, and every derivation of those reads UNSLOTH_HOME. A bare bash studio/setup.sh carries none, so the fallback chain fell through to its custom-Studio-root arm and rebuilt all three under <root>/studio: a second multi-GB copy, with the ones already at <root> orphaned and still on the disk. Both copies stay inside the root, so this costs disk and correctness rather than containment. unsloth studio update never showed it because the CLI fills UNSLOTH_HOME in first, which is why running the script directly was the way to hit it. The record install.sh leaves at the Studio root is the same evidence install.sh re-adopts from, read under the same rule: absolute paths only, and it has to still be a directory.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: dd9f19d8b2
ℹ️ About Codex in GitHub
Codex has been enabled to automatically 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 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| if not _same_dir(root, Path.home() / ".unsloth" / "studio"): | ||
| return root / name | ||
| # The master-root lookup is paid for only on the legacy path, not on every finder pass. | ||
| return root / name if _root_is_portable_master(root) else legacy |
There was a problem hiding this comment.
Infer the legacy sd.cpp sibling for venv-only launches
When an existing default install is converted into a flat portable root at ~/.unsloth/studio and the backend is then started directly from its activated venv, studio_root() can infer the portable root from sys.prefix, but legacy_sibling_install_root() still returns early unless UNSLOTH_STUDIO_HOME or STUDIO_HOME is exported. This new placement therefore stops discovering the already-owned ~/.unsloth/stable-diffusion.cpp, downloads another bundle under the root, and leaves the old multi-hundred-megabyte tree orphaned. Use the inferred Studio root as the legacy lookup fallback when no environment override exists.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not taking this one. run.py:1397 and main.py:228 both export UNSLOTH_STUDIO_HOME from the sys.prefix-inferred root before any sd.cpp lookup runs, so legacy_sibling_install_root does not hit its early return on a real backend start. Checked end to end: the pre-conversion tree is found. The bare import the item describes is not how the backend starts.
Each was reproduced before it was fixed, and each fix proven by removing it and watching the new checks fail. Publish the parent portable marker through a rename. A redirection truncates before printf runs, so a write that died partway left a zero-byte marker at the path every reader tests with -f, and the failure arm cleared the rollback slot so nothing removed it. Measured: install.sh and storage_roots.portable_mode() both reported portable=true off an empty marker, on an install that had already exited 1. Re-publication over a real portable install truncated its root away. Staging and renaming gives both answers: nothing on a first failure, the previous bytes on a later one. A symlink at the marker path is now replaced rather than followed, which also stops the old in-place write truncating whatever it named. Tell a typed --tauri from an adopted portable layout. Since portable mode is adopted from markers on disk, a desktop repair, which passes --tauri and nothing else, was refused with a message naming --portable and --root on a machine where neither was supplied. Reachable by following the documented instructions, since --portable with no --root selects $HOME/.unsloth, the directory the desktop app uses. Still a refusal, since installing over a portable tree would leave the desktop launching a Studio that is not there, but the message now describes the install and gives the way out. Compare the venv ownership evidence canonically. Installers before #5190 wrote UNSLOTH_EXE with the lexical $HOME spelling while env-mode canonicalizes STUDIO_HOME, so on a symlinked HOME our own config stopped vouching for our own venv and the upgrade died with does not look like an Unsloth Studio install. main accepted any existing studio.conf, so this refusal came in with the tightening. The comparison is canonicalized, not dropped: a config naming another venv, or another program, still fails. Retire the portable configuration a conversion leaves behind. A nested portable run writes share/studio.conf and launch-studio.sh at <root>/share, one level above the tree it owns, and converting back wrote a new pair into <root>/studio/share while retiring only <root>/bin/unsloth. Two otherwise-valid launchers over one install, and whichever path the user kept decided where the HF caches and the projects root went. Moved aside like the wrapper, only when the config is ours and names this install, and never in the flat layout where that share/ is the one being written. Resolve the HF stranding notice through XDG_CACHE_HOME, the way huggingface_hub resolves it. Hardcoding $HOME/.cache looked in the wrong place for anyone who sets it, so exactly the users whose cache is somewhere unusual got no warning it was about to be stranded. Register the generated shim's staging file with the cleanup trap. Its inline failure arm cannot run when a signal diverts into the trap, which left .unsloth.shim.<pid> in the user's ~/.local/bin, where a successful retry never looks and nothing prunes it.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 03b2318f2c
ℹ️ 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".
| # find defaults to -P on GNU and BSD alike, so -newer reads the link's own | ||
| # lstat mtime and a dangling link is still reported rather than erroring. | ||
| # Allowances below are paths the OS or the shell writes. | ||
| strays=$(find "$home_p" -newer "$stamp" -print 2>/dev/null | |
There was a problem hiding this comment.
Inspect writes through pre-existing home-directory symlinks
When a home cache directory such as ~/.cache is already a symlink before the stamp is created, the default find behavior here (-P) neither traverses its target nor reports the old link as newer. Files written through that link after the stamp are therefore invisible, and the containment assertion returns success as long as something was also written under the portable root; this can mask exactly the ~/.cache escape the check is meant to catch. Scan the physical targets of pre-existing symlinked home directories or compare a pre/post snapshot that includes them.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not taking this one. The find -P mechanics are correct, and the script's own comment at line 382 says the same. But contained is invoked by no workflow at head, and its only driver builds fresh homes with mkdir -p, so the pre-existing symlink this depends on cannot occur. Unreachable precondition in test infrastructure that is not yet wired up.
The ordering ones are mine, from the two commits before this. _epr_default was added to stop portable mode overriding a cache location the user chose, but _export_portable_roots is CALLED after the block that seeds UV_CACHE_DIR, so it read the installer's own seed back as a caller's choice: a nested install filled <root>/studio/cache/uv while the shim, studio.conf and storage_roots all read <root>/cache/uv, and a user who had set nothing was told their cache locations were being kept. Both halves are fixed, the seed is portable-aware and the equality case is not counted as a choice. The conversion escape hatch cleared only the private copy of the root. Nothing unsets UNSLOTH_HOME, and setup.sh inherits it and prefers it over a custom Studio root for node, llama.cpp and whisper.cpp, so a conversion could report success while the runtimes it installed sat under the old master root. The flat-vs-nested test during conversion used bare directory existence, where _resolve_studio_destinations and the parent-marker guard both require ownership sentinels; a flat root with a leftover studio/ converted the wrong tree. The legacy launcher record is matched byte-exact against a path written with a logical pwd while env-mode canonicalizes with cd -P, so under a symlinked HOME the installer refused a pre-#5190 install of its own. studio/setup.sh run directly recovered the master root after choosing the uv cache rather than before, and derived neither UV_INSTALL_DIR, UV_NO_MODIFY_PATH nor NPM_CONFIG_CACHE, so uv landed in ~/.local/bin, shell startup files gained permanent PATH lines and npm wrote ~/.npm. The uninstaller never named the default portable root, so the documented flagless uninstall left bin/, share/, cache/ and the marker behind while reporting success; a symlinked studio/ had its database recorded lexically and reported gone while intact on another volume; and a flat root's studio.db was removed without recording it, closing with no studio.db was found. README no longer promises that a flagless update finds every portable install. It cannot find one made with --root, and said so nowhere.
|
@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: 97fabda40f
ℹ️ 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".
| # UNSLOTH_PORTABLE=True as off here clears webview caches a portable run promised to keep. | ||
| case "$(_setup_trim_ws "${UNSLOTH_PORTABLE:-}" | tr '[:upper:]' '[:lower:]')" in 1|true|yes|on) return 0 ;; esac | ||
| if [ -n "${UNSLOTH_HOME:-}" ] && [ -f "${UNSLOTH_HOME}/.unsloth-portable-root" ]; then return 0; fi | ||
| if [ -f "$STUDIO_HOME/.unsloth-portable-root" ]; then return 0; fi |
There was a problem hiding this comment.
Check the in-root record before clearing WebView caches
When a nested portable install uses the supported layout where <master>/studio is a symlink to another volume, direct setup canonicalizes STUDIO_HOME to the physical target. The portable marker is therefore no longer in STUDIO_HOME or its parent, while the .unsloth-master-root record inside STUDIO_HOME is the only remaining signal; this probe ignores that record because recovery happens later at lines 1146-1152. With an existing venv, bash studio/setup.sh consequently calls _clear_webview_caches and modifies desktop data under $HOME even though portable mode deliberately promises to leave it untouched. Honor the in-root record here or recover UNSLOTH_HOME before this probe.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not taking this one. The stated reproduction does not reproduce: a bare setup.sh never canonicalizes STUDIO_HOME, so _spm_parent is the lexical parent and the marker is found through the link. Canonicalization happens only in the validated-override arm, which needs UNSLOTH_STUDIO_HOME exported by hand while UNSLOTH_HOME is unset, and every generated entry point sets both together. If you did construct it, the cost is a WebView cache clear, which the code deliberately fails open toward and which touches no settings, models or database.
pip was reachable from studio/setup.sh in four places and its cache was never pinned, so a standalone portable update parked multi-GB Torch and CUDA wheels in $HOME/.cache/pip, where the advertised rm -rf of the root leaves them and the next update cannot reuse them. Reading the generated shim's exports against that block afterwards showed five more it sets and the block did not: UV_PYTHON_INSTALL_DIR, UV_TOOL_DIR, UV_TOOL_BIN_DIR, UV_PYTHON_BIN_DIR and CUDA_CACHE_PATH. The first is the one that costs real space, since uv downloads a managed CPython when the host has no usable interpreter. Fixed together rather than waiting for each to be found on its own, and the test now checks the block against the shim rather than against a list. The flat-root uninstall reported chat history as deleted when studio.db was a symlink to another volume. rm removes the link and test -f follows it, so the lexical path read as absent while the database was intact elsewhere. The resolved location is recorded before the removal, which is what the helper for every other layout already did. Not taken: checking the in-root record before clearing the WebView caches. The stated reproduction does not reproduce, because a bare setup.sh never canonicalizes STUDIO_HOME and so finds the lexical parent marker; reaching the failing shape needs UNSLOTH_STUDIO_HOME exported by hand without UNSLOTH_HOME, which no generated entry point produces, and it costs only a cache clear.
|
@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: c242669372
ℹ️ 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 [ -z "${UV_CACHE_DIR:-}" ]; then | ||
| UV_CACHE_DIR="$STUDIO_HOME/cache/uv" | ||
| UV_CACHE_DIR="${UNSLOTH_HOME:-$STUDIO_HOME}/cache/uv" |
There was a problem hiding this comment.
Treat whitespace-only UV cache overrides as unset
When a portable install is updated by invoking studio/setup.sh directly with UV_CACHE_DIR containing only whitespace, this raw -z check treats the value as an explicit cache path and skips the portable default. uv then resolves that relative whitespace path from the setup working directory, writing outside the selected root; the installer, CLI recovery, and the later setup defaults all explicitly treat whitespace-only values as unset. Apply _setup_trim_ws in this guard before preserving the override.
Useful? React with 👍 / 👎.
| if [ -n "${UNSLOTH_HOME:-}" ] && [ -z "${BUN_INSTALL_CACHE_DIR:-}" ]; then | ||
| export BUN_INSTALL_CACHE_DIR="$UNSLOTH_HOME/cache/bun" |
There was a problem hiding this comment.
Treat a whitespace-only bun cache as unset
During a direct portable setup that rebuilds the frontend, an inherited BUN_INSTALL_CACHE_DIR=' ' passes this nonempty check, so bun uses a relative directory named by the whitespace instead of <root>/cache/bun. That escapes the portable root depending on the setup working directory, despite the other portable cache defaults treating whitespace-only values as unset; trim the value before deciding that the caller supplied an override.
Useful? React with 👍 / 👎.
| [ "$_PORTABLE_MODE" = true ] || return 0 | ||
| # Every top-level name the install writes at the root: the layout dirs plus the three | ||
| # native runtimes setup.sh hangs off UNSLOTH_HOME (llama.cpp, node, whisper.cpp). | ||
| for _esc_name in studio share bin cache llama.cpp node whisper.cpp; do |
There was a problem hiding this comment.
Report symlinked project workspaces as portable escapes
When an existing portable root has its default project workspace symlinked to another volume—<root>/projects for a flat layout or <root>/studio/projects for a nested one—the backend defaults UNSLOTH_STUDIO_PROJECTS_HOME to that path and writes user projects through the link. This escape scan checks neither spelling, so the completion message still recommends rm -rf <root> without warning that the project data remains elsewhere; include the layout-specific projects path in the escape report.
Useful? React with 👍 / 👎.
| _adopt_master=$(_trim_ws "$(head -n 1 "$_adopt_root/.unsloth-master-root" 2>/dev/null)") | ||
| case "$_adopt_master" in | ||
| /*) | ||
| _PORTABLE_MODE=true | ||
| _UNSLOTH_ROOT="$_adopt_master" |
There was a problem hiding this comment.
Reject multiline master-root records during adoption
If .unsloth-master-root is malformed or edited to contain an extra line, this flagless-update path accepts only its first line and enables portable mode for that path, while both Python resolvers explicitly reject records containing anything after the first line. The installer can therefore create or update a different root even though launching the same venv declines the record and falls back elsewhere; validate that the record contains exactly one line before adopting it.
Useful? React with 👍 / 👎.
Summary
Adds
install.sh --portableand--root DIR, an install that keeps everythingin one directory. Closes #8865 for the shell install path; #5264 is the same
request.
Stacked on #10188, which contains the runtime half. Review that one first; the
diff here is only this PR's commits once it merges.
Why this is needed on top of
UNSLOTH_STUDIO_HOMEUNSLOTH_STUDIO_HOME(#5190) already moves the Studio root,share/, the shimand the llama.cpp / node / whisper.cpp builds, and suppresses the shell-rc and
desktop-entry writes. It is also undocumented enough that nobody finds it. But it
is not sufficient, and the gap is larger than it looks.
Two full
install.sh --localruns on the same machine, each against a throwawayhome directory and an identical
env -ienvironment, measured after the fact:UNSLOTH_STUDIO_HOMEonly--root$HOMEThat 6.9 GB is
~/.cache/uv, mostly torch and CUDA wheels. It goes there becauseuv decides where its cache lives from
UV_CACHE_DIR, and nothing Unsloth writesinto its own directory changes that. The same applies to uv's downloaded
interpreter, that interpreter's symlinks, npm and the NVIDIA JIT cache. Setting
those variables before uv first runs is the only thing that moves them, which is
what this does.
Usage
--portableon its own keeps the layout exactly where it is today; the flag isabout containment, not relocation.
UNSLOTH_HOMEis the piped-install equivalentfor
curl ... | sh, where no flag can be passed.The third form keeps the install exactly where
UNSLOTH_STUDIO_HOMEnames it,with the root and the Studio root being the same directory, so opting an existing
install into containment moves nothing.
Layout
Details worth review
The shim becomes a wrapper, not a symlink. A symlink carries no environment,
so
bin/unslothfrom a fresh shell would find the interpreter (the backend infersSTUDIO_HOME from
sys.prefix) and still send uv to~/.cache/uv. Contained untilthe first update, then not.
A marker file, not just environment. The installer's own closing message
suggests
source <root>/studio/unsloth_studio/bin/activate; unsloth studio, whichreaches the venv binary directly, past the shim. Verified against a real
--rootinstall: that path resolved
~/.unsloth/studioand would have built a second,split install beside the portable one.
install.shnow writes.unsloth-portable-rootat the master root andstorage_rootsreads it, both asa venv-inference sentinel and as the fallback for
unsloth_home().--tauristill refuses a custom root, now including these flags. The desktopapp resolves
~/.unsloth/studioin Rust and never sees a per-session variable, soit would launch a Studio that is not there. Same reason #5190 rejected the env
overrides. Worth a follow-up.
Project workspaces were the last Unsloth-owned thing outside the root,
defaulting under
~/Documents. Now set through the documentedUNSLOTH_STUDIO_PROJECTS_HOME, so an explicit override still wins.documents_root()is deliberately untouched: that is the user's own Documentsfolder, a browse root for picking their files, not a directory Unsloth owns.
Not contained, on purpose
$TMPDIR/unsloth-studio. Scratch, cleared on reboot, already outside$HOME,and moving it would put temp writes on whatever volume the root sits on.
HF_HOME, which owns the token.Also worth being plain about: this gives containment, one directory removable
with a single
rm -rf, not a folder that can be copied to another machine andrun. The venv holds native wheels with absolute paths baked in and needs a repair
step after a move. The ComfyUI_portable style of relocation is separate work.
Verification
End to end,
install.sh --local --root ...under a clean environment: 14 GB inthe root, 0 bytes and 0 entries in the home directory. Studio then launched from
<root>/bin/unsloth,/api/healthreturned healthy, and serving still wrotenothing to the home directory.
The uv containment was also checked directly: a venv, a pip install and a managed
CPython download with these variables set leave zero files behind. That is what
caught
UV_PYTHON_BIN_DIR, which is separate fromUV_PYTHON_INSTALL_DIRand wasleaving interpreter symlinks in
~/.local/bin.New
tests/sh/test_install_portable_root.sh, 41 checks: flag parsing including--root=DIR, precedence againstUNSLOTH_STUDIO_HOMEand theSTUDIO_HOMEalias, the default install staying out of env-override mode, every emitted path
being inside the root, the shim and
studio.confcarrying each variable, and theuninstaller reading the master root back. It follows the existing convention, so
the CI glob picks it up with no registration.
.github/scripts/clean-machine-assert.shgains acontainedmode that diffs thehome directory against a pre-install stamp and fails on anything written outside
the root. It refuses to pass when it finds nothing under the root either, so a
lost stamp cannot look like success. Note the clean-machine workflows preseed
some uv roots, which would mask exactly this leak, so a portable matrix must not.
All 57 shell tests and the backend cache and storage-root suites pass.