Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Docker Studio: keep Studio's data on a volume without pinning its code (#10829)

oobabooga6d7fd47ede13
diff --git a/README.md b/README.md
index 7b0fb617eb8..312b228f2b2 100644
--- a/README.md
+++ b/README.md
@@ -157,9 +157,10 @@ docker run -d --gpus all --ipc=host \
-p 8000:8000 -p 8888:8888 \
-e UNSLOTH_STUDIO_PASSWORD="mypassword" -e JUPYTER_PASSWORD="mypassword" \
-v "$PWD":/workspace/host \
+ -v unsloth-studio:/opt/unsloth-studio \
unsloth/unsloth
```
-Follow startup with `docker logs -f`. Studio is at `http://localhost:8000` (user `unsloth`), JupyterLab at `http://localhost:8888`. Tags (`unsloth/unsloth:core` for notebooks only), GPU support and options: [Docker Hub](https://hub.docker.com/r/unsloth/unsloth).
+Follow startup with `docker logs -f`. Studio is at `http://localhost:8000` (user `unsloth`), JupyterLab at `http://localhost:8888`. The `unsloth-studio` volume keeps your accounts, chats and trained models across `docker rm`; each image brings its own Studio code, and a volume from an older image is migrated on the first start (its old code is kept under `.unsloth-studio-legacy/`). Tags (`unsloth/unsloth:core` for notebooks only), GPU support and options: [Docker Hub](https://hub.docker.com/r/unsloth/unsloth).
#### Remote HTTPS & LAN Access
Server-side tools are on by default - so **be careful**! Keep your password safe, or use `--disable-tools` when exposing Unsloth.
diff --git a/docker/.dockerignore b/docker/.dockerignore
index 1d759153e33..05d7e23c198 100644
--- a/docker/.dockerignore
+++ b/docker/.dockerignore
@@ -7,6 +7,7 @@
!studio_launch.sh
!studio_password.sh
!studio_run.sh
+!studio_home.sh
!unsloth_studio_update.sh
!unsloth_llama_update.sh
!unsloth_jupyter_tunnel.sh
diff --git a/docker/DOCKERHUB.md b/docker/DOCKERHUB.md
index dfe5863bc55..970d832e189 100644
--- a/docker/DOCKERHUB.md
+++ b/docker/DOCKERHUB.md
@@ -33,12 +33,13 @@ docker run -d --gpus all --ipc=host \
-e JUPYTER_PASSWORD="choose-a-password" \
-v "$PWD":/workspace/host \
-v "$HOME/.cache/huggingface":/workspace/.cache/huggingface \
+ -v unsloth-studio:/opt/unsloth-studio \
unsloth/unsloth
```
`docker run -d` returns at once; follow the startup with `docker logs -f <container>`, which ends with a ready block once both services answer (Studio takes about a minute). Then open Studio at `http://localhost:8000` (user `unsloth`) and JupyterLab at `http://localhost:8888`. Leave either password variable unset and a random one is generated and printed in that log.
-The `docker/run.sh` helper in the repository sets these flags for you:
+The `docker/run.sh` helper in the repository sets these flags, including the `unsloth-studio` volume, for you:
```bash
git clone https://github.com/unslothai/unsloth && cd unsloth
@@ -120,17 +121,27 @@ The working directory is `/workspace`. Mount what you want to keep:
|---|---|
| `/workspace/host` | Your files. Mount your project directory here. |
| `/workspace/.cache/huggingface` | Model downloads. Mount your host HF cache to reuse it. |
+| `/opt/unsloth-studio` | Studio's accounts, chats, outputs, exports and runs (`latest`). Use a named volume: without one, `docker rm` loses them. A new image still brings new Studio code (see below). |
| `/workspace/.cache/triton` | Compiled kernels. Optional, speeds up restarts. |
| `/workspace/unsloth-notebooks` | The synced notebooks. Your edits are kept across refreshes. |
| `/workspace/Unsloth Notebooks` | The same notebooks grouped by topic, rebuilt on each start. |
The container runs as root by default. On `core`, `--user <uid>:<gid>` is supported and keeps files on your mounts owned by you. `latest` runs its services as root and does not start under `--user`.
+### Studio data and Studio code
+
+Studio's code (its venv, source tree, Node, prebuilt tools) ships in the image under `/opt/unsloth-studio-app` and is linked into `/opt/unsloth-studio` at every start, so the volume holds only your data and every image runs its own code. What that means in practice:
+
+- A volume created by an image from before this split holds that image's code as real directories. The first start of a newer image moves each of them aside to `/opt/unsloth-studio/.unsloth-studio-legacy/<name>` on the volume and links the new code in; nothing is deleted, and the log lists what moved. Delete the legacy directory once the new image works (`docker exec <c> rm -rf /opt/unsloth-studio/.unsloth-studio-legacy`), or start with `-e UNSLOTH_STUDIO_KEEP_LEGACY=0` to skip keeping it. Such a volume also holds that image's uv download cache at `/opt/unsloth-studio/cache/uv` (about 9 GB, hardlinked with the legacy venv); once the legacy directory is gone, `rm -rf /opt/unsloth-studio/cache/uv` frees it.
+- To go back to an image from before the split on the same volume, move the legacy entries back first: `docker run --rm -v unsloth-studio:/h alpine sh -c 'cd /h && for e in .unsloth-studio-legacy/* .unsloth-studio-legacy/.[!.]*; do [ -e "$e" ] || [ -L "$e" ] || continue; rm -rf "${e##*/}"; mv "$e" .; done'`. Images from after the split need nothing. A volume that never held old code (first used after the split, or its legacy directory deleted) gets a copy of the current image's code instead: `docker run --rm -v unsloth-studio:/opt/unsloth-studio --entrypoint unsloth-studio-home <current image> --restore` (about 5 GB, half a minute), after which the older image runs it.
+- `docker rm` still discards anything written into the image's copy: an in-container `unsloth-studio-update` and the `cloudflared` binary `unsloth-jupyter-tunnel` downloads. Studio's caches under `/opt/unsloth-studio/cache` (download resume state, dataset caches) are in the home, so they stay with the volume. Models stay in the Hugging Face cache mount.
+- Use a named volume, not a bind mount of a Windows or macOS host directory. The Studio home needs symlinks, and bind mounts through Docker Desktop's file sharing (a Windows drive under WSL 2 in particular) may refuse to create them; the container then stops at start with the linker's error instead of running a half-linked Studio. A bind mount of a Linux directory (including a directory inside the WSL 2 distribution) works.
+
## Updating inside a running container
On the `latest` image:
-- `unsloth-studio-update` upgrades Studio and Unsloth in place.
+- `unsloth-studio-update` upgrades Studio and Unsloth in place (in the image's copy: survives `docker restart`, not `docker rm`).
- `unsloth-llama-update` fetches the newest prebuilt llama.cpp.
- `unsloth-jupyter-tunnel` opens a Cloudflare quick tunnel to JupyterLab.
diff --git a/docker/Dockerfile.studio b/docker/Dockerfile.studio
index 78dd1f8836a..aeb2b2bb935 100644
--- a/docker/Dockerfile.studio
+++ b/docker/Dockerfile.studio
@@ -7,11 +7,18 @@
# -f docker/Dockerfile.studio -t unsloth/unsloth:studio docker/
# Run:
# docker run --rm --gpus all -p 8000:8000 -p 8888:8888 \
-# -v $HOME/.cache/huggingface:/workspace/.cache/huggingface unsloth/unsloth:studio
+# -v $HOME/.cache/huggingface:/workspace/.cache/huggingface \
+# -v unsloth-studio:/opt/unsloth-studio unsloth/unsloth:studio
#
# Studio on :8000 (user unsloth; UNSLOTH_STUDIO_PASSWORD env, else a generated one
# is printed in the logs; persisted under /opt/unsloth-studio/auth/); JupyterLab on
# :8888 (JUPYTER_PASSWORD env, else a random one is printed). Without a GPU it starts on CPU: no training, but Studio chat / Data Recipes / GGUF / Jupyter work.
+# /opt/unsloth-studio (UNSLOTH_STUDIO_HOME) holds only Studio's data; the code lives in
+# /opt/unsloth-studio-app (UNSLOTH_STUDIO_APP) and unsloth-studio-home links it into the
+# home at build time and at every start, so a named volume on the home keeps accounts,
+# chats and outputs without pinning the first image's code. Real code directories that
+# an older image left on the volume are moved to .unsloth-studio-legacy/ (not deleted;
+# UNSLOTH_STUDIO_KEEP_LEGACY=0 deletes them), which is also the way back to that image.
# CI pins BASE_IMAGE to the published base digest so both images ship the same stack.
ARG BASE_IMAGE=unsloth/unsloth:core
@@ -52,7 +59,11 @@ ARG TARGETARCH
USER root
# UNSLOTH_IMAGE_ALLOW_CPU=1 lets THIS image (:latest) start without a GPU. The entrypoint turns it into
# UNSLOTH_ALLOW_CPU=1 only when no GPU is visible, since that one disables the TRL patches. :core never opts in.
+# UV_CACHE_DIR in the app dir: install.sh, setup.sh and Studio default it to $UNSLOTH_STUDIO_HOME/cache/uv,
+# which would fill a volume on the home with wheels; cache/ there stays runtime data.
ENV UNSLOTH_STUDIO_HOME=/opt/unsloth-studio \
+ UNSLOTH_STUDIO_APP=/opt/unsloth-studio-app \
+ UV_CACHE_DIR=/opt/unsloth-studio-app/uv-cache \
UNSLOTH_IMAGE_ALLOW_CPU=1 \
JUPYTER_PORT=8888 \
UNSLOTH_ENABLE_SSHD=false \
@@ -65,9 +76,12 @@ RUN apt-get update \
curl git ca-certificates supervisor openssh-server \
&& rm -rf /var/lib/apt/lists/*
-# Clone + install Studio into a dedicated venv under $UNSLOTH_STUDIO_HOME.
-# --local is editable, so the source MUST persist -- keep it at $STUDIO_HOME/src,
-# strip .git (~120MB).
+# The linker the install RUN below finishes with, and the entrypoint reruns (studio_home.sh).
+COPY studio_home.sh /usr/local/bin/unsloth-studio-home
+
+# Clone + install Studio into a venv under $UNSLOTH_STUDIO_HOME, then move it to
+# $UNSLOTH_STUDIO_APP (end of this RUN). --local is editable: the venv imports through
+# $STUDIO_HOME/src, which the linker makes a symlink into the app dir. .git is stripped (~120MB).
#
# The llama.cpp symlink BEFORE install.sh points Studio's prebuilt dir at the
# base's baked bundle so the installer skips a second ~400MB download; the
@@ -159,7 +173,18 @@ RUN set -eux \
fi; \
done; \
echo "studio venv size after dedup:"; du -sh "${UNSLOTH_STUDIO_HOME}/unsloth_studio"; \
- fi
+ fi \
+ # Move the code to the app dir in this same layer (a later RUN would store it twice)
+ # and leave symlinks, so a volume on the home no longer freezes the code at the first
+ # image's version. cache/ stays a real directory: with UV_CACHE_DIR in the app dir it
+ # holds only install.sh's uv-cache-dir marker now and Studio's runtime caches later.
+ && mkdir -p "${UNSLOTH_STUDIO_APP}" \
+ && find "${UNSLOTH_STUDIO_HOME}" -mindepth 1 -maxdepth 1 ! -name cache -exec mv -t "${UNSLOTH_STUDIO_APP}" {} + \
+ && test ! -e "${UNSLOTH_STUDIO_HOME}/cache/uv" \
+ # through bash: the exec bit is set further down, with the other bin scripts
+ && bash /usr/local/bin/unsloth-studio-home \
+ && "${UNSLOTH_STUDIO_HOME}/unsloth_studio/bin/python" -c "import os, sys, studio; print('Studio venv', sys.prefix, 'imports studio from', studio.__file__); assert os.path.realpath(studio.__file__).startswith(os.path.realpath('${UNSLOTH_STUDIO_HOME}/src') + '/'), studio.__file__" \
+ && ls -la "${UNSLOTH_STUDIO_HOME}"
COPY supervisord.conf /etc/supervisor/supervisord.conf
COPY studio_launch.sh /usr/local/bin/unsloth-studio-launch
@@ -219,7 +244,8 @@ RUN SP="$(/opt/unsloth-venv/bin/python -c 'import sysconfig; print(sysconfig.get
/opt/unsloth-venv/share/jupyter/UNSLOTH_LICENSE.AGPL-3.0 \
&& rm -rf /tmp/unsloth-branding-guard \
&& /opt/unsloth-venv/bin/python -m unsloth_branding --verify
-RUN chmod +x /usr/local/bin/unsloth-studio-launch \
+RUN chmod +x /usr/local/bin/unsloth-studio-home \
+ /usr/local/bin/unsloth-studio-launch \
/usr/local/bin/unsloth-studio-password \
/usr/local/bin/unsloth-studio-run \
/usr/local/bin/unsloth-studio-update \
diff --git a/docker/entrypoint.sh b/docker/entrypoint.sh
index 8cd5ae8a667..2a48144fb6c 100755
--- a/docker/entrypoint.sh
+++ b/docker/entrypoint.sh
@@ -7,6 +7,15 @@
# Bypass for offline tooling/docs/CI: docker run -e UNSLOTH_SKIP_GPU_CHECK=1 ...
set -euo pipefail
+# Studio image: relink its code into the home (maybe an earlier image's volume) before the
+# CUDA tool selection reads the venv. Fatal on failure (a half-linked home); no-op on the base image.
+if [[ -x /usr/local/bin/unsloth-studio-home ]]; then
+ /usr/local/bin/unsloth-studio-home || {
+ echo "ERROR: could not link Studio's code into ${UNSLOTH_STUDIO_HOME:-/opt/unsloth-studio}; see the messages above" >&2
+ exit 1
+ }
+fi
+
# CUDA 13 ptxas + NVRTC are baked only for sm_103 and sm_121, which cu12.8 cannot
# target and which ship on >=580 drivers; every other arch is cu12.8 on the 570-579
# floor, where a cu13 cubin cannot load. So the choice is per DEVICE at boot.
diff --git a/docker/run.sh b/docker/run.sh
index d590e341040..220928cbb06 100755
--- a/docker/run.sh
+++ b/docker/run.sh
@@ -30,6 +30,9 @@
# HF_HOME=$HOME/.cache/huggingface host HF cache dir to mount
# TRITON_CACHE_DIR=...unsloth-triton host Triton cache dir to mount
# UNSLOTH_WORKDIR=$PWD host dir mounted at /workspace/host
+# UNSLOTH_STUDIO_VOLUME=unsloth-studio named volume for Studio's data (accounts,
+# chats, outputs) at /opt/unsloth-studio;
+# set it empty to run without one
set -euo pipefail
IMAGE="${UNSLOTH_IMAGE:-unsloth/unsloth:latest}"
@@ -49,6 +52,14 @@ esac
HF_CACHE="${HF_HOME:-$HOME/.cache/huggingface}"
TRITON_CACHE="${TRITON_CACHE_DIR:-$HOME/.cache/unsloth-triton}"
WORK_DIR="${UNSLOTH_WORKDIR:-$PWD}"
+# Studio's data lives under /opt/unsloth-studio and the image relinks its code there at
+# every start, so the volume survives `docker rm` without pinning the code. `-` (not `:-`):
+# an explicitly empty value disables the mount. On :core it is an empty dir the image never reads.
+STUDIO_VOLUME="${UNSLOTH_STUDIO_VOLUME-unsloth-studio}"
+STUDIO_MOUNT=()
+if [ -n "$STUDIO_VOLUME" ]; then
+ STUDIO_MOUNT=(-v "$STUDIO_VOLUME":/opt/unsloth-studio)
+fi
mkdir -p "$HF_CACHE" "$TRITON_CACHE"
@@ -166,6 +177,7 @@ exec docker run --rm ${TTY_FLAG[@]+"${TTY_FLAG[@]}"} \
-v "$HF_CACHE":/workspace/.cache/huggingface \
-v "$TRITON_CACHE":/workspace/.cache/triton \
-v "$WORK_DIR":/workspace/host \
+ ${STUDIO_MOUNT[@]+"${STUDIO_MOUNT[@]}"} \
"${ENV_FORWARD[@]}" \
${PORT_FLAGS[@]+"${PORT_FLAGS[@]}"} \
"$IMAGE" "$@"
diff --git a/docker/studio_home.sh b/docker/studio_home.sh
new file mode 100755
index 00000000000..7e776dc6d11
--- /dev/null
+++ b/docker/studio_home.sh
@@ -0,0 +1,174 @@
+#!/usr/bin/env bash
+# Link each code entry of $UNSLOTH_STUDIO_APP (venv, src, Node, whisper.cpp, tiers) into
+# $UNSLOTH_STUDIO_HOME, which keeps only data and is what users mount a volume on; the
+# venv's baked absolute paths keep resolving through the links. Runs at every start, so
+# a volume holding an earlier image's real code directories is relinked rather than
+# frozen at that version. Nothing is deleted: an entry in the way is renamed to
+# .unsloth-studio-legacy/<name> (`--restore` puts it back for an older image;
+# UNSLOTH_STUDIO_KEEP_LEGACY=0 deletes). Entries the app dir lacks are left alone.
+set -euo pipefail
+
+APP="${UNSLOTH_STUDIO_APP:-/opt/unsloth-studio-app}"
+HOME_DIR="${UNSLOTH_STUDIO_HOME:-/opt/unsloth-studio}"
+KEEP_LEGACY="${UNSLOTH_STUDIO_KEEP_LEGACY:-1}"
+LEGACY_NAME=".unsloth-studio-legacy"
+
+log() { echo "[unsloth-studio] $*" >&2; }
+die() { log "ERROR: $*"; exit 1; }
+
+# mkdir -p, rm -rf and mv all follow a link planted at the legacy name (into the app
+# dir, say); refuse rather than write through it.
+check_legacy() {
+ if [ -L "$1" ] || { [ -e "$1" ] && [ ! -d "$1" ]; }; then
+ die "$1 must be a directory, not a link or a file; move or remove it, then start the container again"
+ fi
+}
+
+# `--restore`: put the kept-aside entries back in place of the links, for an image from before the split.
+if [ "${1:-}" = "--restore" ]; then
+ legacy="$HOME_DIR/$LEGACY_NAME"
+ check_legacy "$legacy"
+ shopt -s dotglob nullglob
+ if [ ! -d "$legacy" ]; then
+ # No kept copy (first used after the split, or deleted): a pre-split image finds its
+ # own tree hidden under the mount and links to nothing, so give it real copies.
+ [ -d "$APP" ] || die "no $legacy to restore and no $APP on this image: run --restore under an image that has the Studio code in $APP (the one that last ran this volume), it copies that code into the home for an older image"
+ copied=()
+ for target in "$HOME_DIR"/*; do
+ [ -L "$target" ] || continue
+ link="$(readlink "$target")"
+ case "$link" in "$APP"/*) ;; *) continue;; esac
+ name="${target##*/}"
+ # the uv cache is this image's scratch (9 GB); no image before the split reads it
+ if [ -e "$link" ] && [ "$name" != "uv-cache" ]; then
+ # copy beside the link and swap only once whole: a half-written real
+ # $target is skipped by this symlink-only loop on the rerun
+ tmp="$target.restore-tmp"
+ rm -rf -- "$tmp"
+ cp -a -- "$link" "$tmp" || {
+ rm -rf -- "$tmp"
+ die "cannot copy $link to $target; nothing was changed, rerun --restore"
+ }
+ rm -f -- "$target"
+ mv -T -- "$tmp" "$target" || die "cannot put $tmp at $target; move it there by hand"
+ copied+=("$name")
+ else
+ rm -f -- "$target"
+ fi
+ done
+ if [ "${#copied[@]}" -gt 0 ]; then
+ log "no kept-aside copy on this volume; copied this image's code into the home instead (${copied[*]}), so an image from before the split can run it. The next start of a split image links its own code back in."
+ else
+ log "nothing to restore: no links into $APP and no $legacy"
+ fi
+ exit 0
+ fi
+ # every link of ours goes, kept copy or not: Docker copies nothing into a non-empty volume
+ for target in "$HOME_DIR"/*; do
+ [ -L "$target" ] || continue
+ case "$(readlink "$target")" in
+ "$APP"/*) rm -f -- "$target"; log "unlinked $target";;
+ esac
+ done
+ for entry in "$legacy"/*; do
+ name="${entry##*/}"
+ target="$HOME_DIR/$name"
+ if [ -L "$target" ] || [ ! -e "$target" ]; then
+ rm -f "$target"
+ else
+ die "$target is a real entry, not a link; move it away before restoring $entry"
+ fi
+ mv -T "$entry" "$target"
+ log "restored $target"
+ done
+ rmdir "$legacy" 2>/dev/null || true
+ exit 0
+fi
+
+[ -d "$APP" ] || exit 0
+mkdir -p "$HOME_DIR" || die "cannot create $HOME_DIR"
+
+# as the kernel sees them: an override pointing both at one tree would move the install aside
+app_real="$(cd -P -- "$APP" && pwd -P)"
+home_real="$(cd -P -- "$HOME_DIR" && pwd -P)"
+case "$home_real/" in
+ "$app_real/"*) die "UNSLOTH_STUDIO_HOME ($HOME_DIR) must not be UNSLOTH_STUDIO_APP ($APP) or inside it";;
+esac
+case "$app_real/" in
+ "$home_real/"*) die "UNSLOTH_STUDIO_APP ($APP) must not be inside UNSLOTH_STUDIO_HOME ($HOME_DIR)";;
+esac
+
+legacy="$HOME_DIR/$LEGACY_NAME"
+moved=()
+
+# set_aside <path>: get an entry that is in the way out of the way without losing it.
+set_aside() {
+ local path="$1" name="${1##*/}" kept="$legacy/${1##*/}"
+ if [ "$KEEP_LEGACY" = "0" ]; then
+ rm -rf -- "$path" || die "cannot remove $path"
+ log "removed $path (UNSLOTH_STUDIO_KEEP_LEGACY=0)"
+ return
+ fi
+ check_legacy "$legacy"
+ mkdir -p -m 0700 "$legacy" || die "cannot create $legacy"
+ # one generation only: a second upgrade replaces the copy kept by the first
+ if [ -e "$kept" ] || [ -L "$kept" ]; then
+ rm -rf -- "$kept" || die "cannot clear the earlier copy at $kept"
+ fi
+ mv -T -- "$path" "$kept" || die "cannot move $path aside to $kept; nothing was changed"
+ moved+=("$name")
+ log "kept $path aside at $kept, this image's copy is linked in its place"
+}
+
+shopt -s dotglob nullglob
+
+# unsloth-studio-update renames src to .src-prev.* and the staged tree into place; a kill
+# between the two leaves the previous tree as the only copy, so put it back before the
+# loop below prunes the home's src link as dangling.
+if [ ! -e "$APP/src" ]; then
+ prev=("$APP"/.src-prev.*)
+ if [ "${#prev[@]}" -eq 1 ] && [ -d "${prev[0]}" ]; then
+ mv -T -- "${prev[0]}" "$APP/src" || die "cannot put ${prev[0]} back at $APP/src"
+ log "put ${prev[0]} back at $APP/src: an update was interrupted between its two renames"
+ elif [ "${#prev[@]}" -gt 1 ]; then
+ log "WARNING: $APP/src is missing and several .src-prev.* trees exist; pick one and move it to $APP/src by hand"
+ fi
+fi
+
+for entry in "$APP"/*; do
+ name="${entry##*/}"
+ [ "$name" = "$LEGACY_NAME" ] && continue
+ # a killed update's staging and previous trees: scratch, never linked into the home
+ case "$name" in .src-update.*|.src-prev.*) continue;; esac
+ target="$HOME_DIR/$name"
+ if [ -L "$target" ]; then
+ [ "$(readlink "$target")" = "$entry" ] && continue
+ # a link of ours to an older app path, or a link the user made: keep the user's
+ case "$(readlink "$target")" in
+ "$APP"/*) rm -f -- "$target";;
+ *) set_aside "$target";;
+ esac
+ elif [ -e "$target" ]; then
+ set_aside "$target"
+ fi
+ ln -sT -- "$entry" "$target" \
+ || die "cannot link $target -> $entry$( [ -e "$legacy/$name" ] && echo "; the earlier entry is intact at $legacy/$name")"
+done
+
+# an entry this image dropped (a transformers tier) leaves a dangling link; only links into the app dir are ours
+for target in "$HOME_DIR"/*; do
+ [ -L "$target" ] || continue
+ link="$(readlink "$target")"
+ case "$link" in
+ # -L too: llama.cpp is a link in the app dir, and points outside the Studio home
+ "$APP"/*) [ -e "$link" ] || [ -L "$link" ] || rm -f -- "$target";;
+ esac
+done
+
+if [ "${#moved[@]}" -gt 0 ]; then
+ size="$(du -sh -- "$legacy" 2>/dev/null | cut -f1)"
+ log "kept aside in $legacy (${size:-?}): ${moved[*]}"
+ log " to go back to an image from before the code/data split, put them back first:"
+ log " docker run --rm -v <volume>:$HOME_DIR --entrypoint unsloth-studio-home <this image> --restore"
+ log " to free the space: rm -rf $legacy"
+fi
diff --git a/docker/unsloth_studio_update.sh b/docker/unsloth_studio_update.sh
index 22b976cf0bf..d527a8d7bab 100755
--- a/docker/unsloth_studio_update.sh
+++ b/docker/unsloth_studio_update.sh
@@ -12,10 +12,10 @@
# Not `unsloth studio update`: that re-runs the full installer, which re-probes the
# host GPU for torch wheels and in a CPU-only container downgrades torch to CPU/cu126.
#
-# Persistence: the update is written to the container's writable layer, so it
-# survives `docker restart`. To keep it across a full `docker rm` + `docker run`
-# (and to keep your chats/users/models), run Studio with its home on a named
-# volume: -v unsloth_studio_home:/opt/unsloth-studio
+# Persistence: the updated packages live in the image's copy of Studio, so they
+# survive `docker restart` but not `docker rm`; pull a new image for a lasting update.
+# Studio's data (accounts, chats, models) is separate: keep it with
+# -v unsloth-studio:/opt/unsloth-studio, which never pins Studio's code.
set -euo pipefail
STUDIO_HOME="${UNSLOTH_STUDIO_HOME:-/opt/unsloth-studio}"
@@ -100,10 +100,11 @@ if ! "$PY" -c "import studio.backend.main" >/dev/null 2>&1; then
echo "[studio-update] serving whatever it has already imported. That is the only" >&2
echo "[studio-update] thing still working: the venv on disk is ALREADY replaced." >&2
echo "[studio-update] Anything it imports lazily from here on fails the same way," >&2
- echo "[studio-update] any restart parks Studio in FATAL, and because the venv lives" >&2
- echo "[studio-update] under \$UNSLOTH_STUDIO_HOME, a persisted home keeps it broken" >&2
- echo "[studio-update] across docker rm + docker run. Fix it before restarting." >&2
- echo "[studio-update] Once fixed: supervisorctl restart studio" >&2
+ echo "[studio-update] and any restart parks Studio in FATAL. The venv is the image's" >&2
+ echo "[studio-update] copy (\$UNSLOTH_STUDIO_APP), not part of the Studio home volume," >&2
+ echo "[studio-update] so docker rm + docker run brings back the image's working venv" >&2
+ echo "[studio-update] and keeps your data. Or fix it in place before restarting;" >&2
+ echo "[studio-update] once fixed: supervisorctl restart studio" >&2
exit 1
fi
diff --git a/studio/backend/tests/test_local_llama_cpp_link.py b/studio/backend/tests/test_local_llama_cpp_link.py
index 9568b34fcaf..292f2f71cce 100644
--- a/studio/backend/tests/test_local_llama_cpp_link.py
+++ b/studio/backend/tests/test_local_llama_cpp_link.py
@@ -8,6 +8,10 @@ user's own checkout, Unsloth must treat it as externally managed:
- the in-app updater must not offer or apply a prebuilt over the link
- orphan cleanup must not kill a llama-server the user launched from that tree
+A link into the image's own code tree ($UNSLOTH_STUDIO_APP) is not one of these: the
+Docker image makes it over its own install, and treating it as a checkout disabled the
+update the image ships the runtime for.
+
These exercise real link behavior rather than grepping the scripts.
"""
@@ -20,6 +24,7 @@ import pytest
from utils import llama_cpp_path_settings as path_settings
from utils import llama_cpp_update as u
+from utils import whisper_cpp_update as w
from core.inference import llama_cpp as llama_cpp_module
from core.inference.llama_cpp import LlamaCppBackend
@@ -83,6 +88,56 @@ def test_active_install_is_local_link(tmp_path: Path) -> None:
assert u._active_install_is_local_link(str(plain / _server_subpath())) is False
+def test_a_link_into_the_studio_app_tree_is_not_a_local_link(tmp_path: Path, monkeypatch) -> None:
+ """The Docker image keeps Studio's code in $UNSLOTH_STUDIO_APP and links each entry
+ of it into the Studio home, the directory users mount a volume on. whisper.cpp is
+ discovered through the home (there is no UNSLOTH_WHISPER_CPP_PATH pin to shortcut
+ it), so the image's own link would otherwise read as a user checkout and disable the
+ in-app update. A link into the image's code is Unsloth's own install, not external."""
+ app = tmp_path / "app"
+ home = tmp_path / "home"
+ home.mkdir()
+ monkeypatch.setenv("UNSLOTH_STUDIO_APP", str(app))
+
+ link = home / "llama.cpp"
+ _make_link(link, app / "llama.cpp")
+ assert u._active_install_is_local_link(str(link / _server_subpath())) is False
+
+ whisper_link = home / "whisper.cpp"
+ _make_link(whisper_link, app / "whisper.cpp")
+ whisper_binary = str(whisper_link / "build" / "bin" / "whisper-server")
+ assert w._active_install_is_local_link(whisper_binary) is False
+
+ # a link out of the image's code is still the user's own checkout
+ outside = home / "outside.cpp" / "llama.cpp"
+ outside.parent.mkdir()
+ _make_link(outside, tmp_path / "my-checkout")
+ assert u._active_install_is_local_link(str(outside / _server_subpath())) is True
+
+
+def test_without_the_studio_app_tree_every_link_stays_external(tmp_path: Path, monkeypatch) -> None:
+ """Outside the Docker image nothing sets the variable, so the contract is unchanged.
+ An empty value counts as unset: only a real tree may exempt a link."""
+ app = tmp_path / "app"
+ link = tmp_path / "home" / "llama.cpp"
+ link.parent.mkdir()
+ _make_link(link, app / "llama.cpp")
+ binary = str(link / _server_subpath())
+ monkeypatch.delenv("UNSLOTH_STUDIO_APP", raising = False)
+ assert u._active_install_is_local_link(binary) is True
+ monkeypatch.setenv("UNSLOTH_STUDIO_APP", " ")
+ assert u._active_install_is_local_link(binary) is True
+
+
+def test_a_sibling_of_the_studio_app_tree_is_not_inside_it(tmp_path: Path, monkeypatch) -> None:
+ """$UNSLOTH_STUDIO_APP=/opt/unsloth-studio-app must not claim /opt/unsloth-studio-appx."""
+ monkeypatch.setenv("UNSLOTH_STUDIO_APP", str(tmp_path / "app"))
+ link = tmp_path / "home" / "llama.cpp"
+ link.parent.mkdir()
+ _make_link(link, tmp_path / "appx" / "llama.cpp")
+ assert u._active_install_is_local_link(str(link / _server_subpath())) is True
+
+
def test_get_update_status_reports_local_link(tmp_path: Path, monkeypatch) -> None:
link = tmp_path / "llama.cpp"
_make_link(link, tmp_path / "tgt")
diff --git a/studio/backend/tests/test_transformers_version.py b/studio/backend/tests/test_transformers_version.py
index ae975117e33..5237bf2cf1f 100644
--- a/studio/backend/tests/test_transformers_version.py
+++ b/studio/backend/tests/test_transformers_version.py
@@ -2269,6 +2269,68 @@ class TestVenvDirFileIntegrity:
assert installed == ["transformers==5.3.0"], "damaged sidecar was not reinstalled"
assert not (venv_dir / "transformers").exists(), "damaged tree was not wiped first"
+ def test_ensure_venv_dir_repairs_a_symlinked_sidecar_in_place(
+ self, tmp_path: Path, monkeypatch
+ ):
+ """The Docker image keeps the sidecars under UNSLOTH_STUDIO_APP and links them into
+ the Studio home. rmtree refuses a symlink and ignore_errors hides that, so the
+ damaged tree used to survive the wipe and a version-satisfied install left it in
+ place. The repair has to reach the directory the link points at, and the link
+ itself must stay, since Studio keeps addressing the sidecar through the home."""
+ monkeypatch.setenv("UNSLOTH_STUDIO_APP", str(tmp_path / "app"))
+ real = self._make_venv(tmp_path / "app" / "venv")
+ (real / "transformers" / "__init__.py").write_text("x")
+ link = tmp_path / "home" / "venv"
+ link.parent.mkdir()
+ link.symlink_to(real)
+
+ targets = []
+
+ def _fake_install(pkg, target):
+ targets.append(target)
+ return True
+
+ monkeypatch.setattr("utils.transformers_version._install_to_dir", _fake_install)
+ ok = _ensure_venv_dir(str(link), ("transformers==5.3.0",), "transformers 5.3.0")
+
+ assert ok is True
+ assert link.is_symlink(), "the home's link to the sidecar was replaced by a real dir"
+ assert not (real / "transformers").exists(), "damaged tree behind the link was not wiped"
+ assert targets == [str(real)], "the reinstall did not target the linked directory"
+ assert (real / ".unsloth-studio-owned").is_file()
+
+ def test_ensure_venv_dir_does_not_wipe_behind_a_link_that_is_not_the_image_tree(
+ self, tmp_path: Path, monkeypatch
+ ):
+ """A user who moved a sidecar to another disk and linked it is not the Docker
+ layout, so the repair must not follow that link into a tree it does not own."""
+ monkeypatch.delenv("UNSLOTH_STUDIO_APP", raising = False)
+ real = self._make_venv(tmp_path / "elsewhere" / "venv")
+ (real / "transformers" / "__init__.py").write_text("x")
+ (real / "keep.txt").write_text("mine")
+ link = tmp_path / "home" / "venv"
+ link.parent.mkdir()
+ link.symlink_to(real)
+
+ targets = []
+
+ def _fake_install(pkg, target):
+ targets.append(target)
+ return True
+
+ monkeypatch.setattr("utils.transformers_version._install_to_dir", _fake_install)
+ _ensure_venv_dir(str(link), ("transformers==5.3.0",), "transformers 5.3.0")
+
+ assert link.is_symlink()
+ assert (
+ real / "keep.txt"
+ ).read_text() == "mine", "the user's tree behind the link was wiped"
+ assert targets == [str(link)]
+
+ monkeypatch.setenv("UNSLOTH_STUDIO_APP", str(tmp_path / "app"))
+ _ensure_venv_dir(str(link), ("transformers==5.3.0",), "transformers 5.3.0")
+ assert (real / "keep.txt").exists(), "a link outside the app tree was followed"
+
def test_ensure_venv_dir_restores_the_studio_owned_marker(self, tmp_path: Path, monkeypatch):
"""The wipe takes setup.sh's ownership marker with the old directory. Without a
new one, the next `unsloth studio update` under a custom UNSLOTH_STUDIO_HOME
diff --git a/studio/backend/utils/paths/storage_roots.py b/studio/backend/utils/paths/storage_roots.py
index 9dcf984bcca..7edcb09ba1e 100644
--- a/studio/backend/utils/paths/storage_roots.py
+++ b/studio/backend/utils/paths/storage_roots.py
@@ -39,9 +39,18 @@ def _infer_studio_home_from_venv() -> Path | None:
).is_file()
except OSError:
return None
- if has_sentinel:
- return candidate
- return None
+ if not has_sentinel:
+ return None
+ # In the Docker image sys.prefix resolves to UNSLOTH_STUDIO_APP, which carries the same sentinels
+ # but is the container layer, not the volume: never adopt it as the home.
+ app_dir = os.environ.get("UNSLOTH_STUDIO_APP", "").strip()
+ if app_dir:
+ try:
+ if candidate == Path(app_dir).resolve():
+ return None
+ except (OSError, ValueError):
+ pass
+ return candidate
def studio_root() -> Path:
diff --git a/studio/backend/utils/prebuilt/update_flow.py b/studio/backend/utils/prebuilt/update_flow.py
index b2437793633..7f4a6b6dc4a 100644
--- a/studio/backend/utils/prebuilt/update_flow.py
+++ b/studio/backend/utils/prebuilt/update_flow.py
@@ -274,12 +274,24 @@ def is_external_link(path: Optional[Path]) -> bool:
return False
+def resolves_into_studio_app_tree(path: Path) -> bool:
+ """True when ``path`` resolves inside $UNSLOTH_STUDIO_APP: the Docker image links its own code from there into the Studio home, so such a link is ours, not a user checkout. False wherever the variable is unset."""
+ app = (os.environ.get("UNSLOTH_STUDIO_APP") or "").strip()
+ if not app:
+ return False
+ try:
+ root = os.path.realpath(app)
+ return os.path.commonpath([root, os.path.realpath(path)]) == root
+ except (OSError, ValueError):
+ return False
+
+
def active_install_is_local_link(binary: Optional[str], *, dir_name: str) -> bool:
- """True when the active server binary resolves through a locally-linked component directory. An update would write through that link into the user's checkout (or fail), so the install is treated as externally managed: none is offered or applied. Checks only up to and including the component dir so a symlinked HOME / studio root above it can't trip a false positive."""
+ """True when the active server binary resolves through a locally-linked component directory. An update would write through that link into the user's checkout (or fail), so the install is treated as externally managed: none is offered or applied. Checks only up to and including the component dir so a symlinked HOME / studio root above it can't trip a false positive, and skips a link into the image's own code tree (see resolves_into_studio_app_tree): the Docker image links whisper.cpp into the Studio home from there, and a --with-whisper-cpp-dir / --with-llama-cpp-dir checkout never resolves inside it."""
if not binary:
return False
for parent in Path(binary).parents:
- if is_external_link(parent):
+ if is_external_link(parent) and not resolves_into_studio_app_tree(parent):
return True
if parent.name == dir_name:
break
diff --git a/studio/backend/utils/transformers_version.py b/studio/backend/utils/transformers_version.py
index 881b068c668..1588e93a5f6 100644
--- a/studio/backend/utils/transformers_version.py
+++ b/studio/backend/utils/transformers_version.py
@@ -54,6 +54,7 @@ from hub.utils.hf_tokens import (
qualify_cache_identity,
)
from utils.native_path_leases import child_env_without_native_path_secret
+from utils.prebuilt.update_flow import resolves_into_studio_app_tree
from utils.native_tls import inline_gate_source, vendor_dir
from utils.child_stdio import utf8_child_env
from utils.hf_cache_settings import get_hf_cache_paths
@@ -2417,6 +2418,13 @@ def _ensure_venv_dir(venv_dir: str, packages: tuple[str, ...], label: str) -> bo
return True
logger.warning("%s not found or incomplete at %s -- installing at runtime", label, venv_dir)
+ # The Docker image links its sidecars into the Studio home (UNSLOTH_STUDIO_APP). rmtree refuses a
+ # symlink and ignore_errors hides that, so the damaged files would survive the "wipe" and a
+ # version-satisfied install would leave them in place. Repair the directory the link points at,
+ # but only when it is the image's own tree: a link a user made to some other disk is not ours
+ # to delete, so that keeps the old behaviour.
+ if os.path.islink(venv_dir) and resolves_into_studio_app_tree(Path(venv_dir)):
+ venv_dir = os.path.realpath(venv_dir)
shutil.rmtree(venv_dir, ignore_errors = True)
os.makedirs(venv_dir, exist_ok = True)
_mark_studio_owned(venv_dir)
diff --git a/tests/python/test_docker_cpu_fallback.py b/tests/python/test_docker_cpu_fallback.py
index 90b756b89fd..e0cfbe3f081 100644
--- a/tests/python/test_docker_cpu_fallback.py
+++ b/tests/python/test_docker_cpu_fallback.py
@@ -46,6 +46,7 @@ def _invoke_run_sh(
nvidia,
amd,
groups = "both",
+ extra_env = None,
):
"""Run docker/run.sh with a recording `docker` stub and a staged /dev tree.
@@ -99,8 +100,15 @@ def _invoke_run_sh(
env["UNSLOTH_DEV_ROOT"] = str(dev_root)
env["HOME"] = str(tmp_path / "home")
env["UNSLOTH_WORKDIR"] = str(tmp_path)
- for leak in ("HF_TOKEN", "WANDB_API_KEY", "UNSLOTH_GPUS", "UNSLOTH_ALLOW_CPU"):
+ for leak in (
+ "HF_TOKEN",
+ "WANDB_API_KEY",
+ "UNSLOTH_GPUS",
+ "UNSLOTH_ALLOW_CPU",
+ "UNSLOTH_STUDIO_VOLUME",
+ ):
env.pop(leak, None)
+ env.update(extra_env or {})
# absolute: the "absent" case strips /usr/bin from PATH, so `bash` itself would
# not resolve either
@@ -164,6 +172,52 @@ class TestRunShDegradesWithoutNvidia:
assert "/dev/kfd" not in argv
+def _studio_mounts(argv):
+ return [
+ argv[i + 1]
+ for i, a in enumerate(argv)
+ if a == "-v" and argv[i + 1].endswith(":/opt/unsloth-studio")
+ ]
+
+
+@_posix_shell
+class TestRunShMountsTheStudioVolume:
+ """Studio's accounts, chats and trained models live under /opt/unsloth-studio.
+ The image links its own code in there at every start, so a named volume keeps
+ the data across `docker rm` without pinning the first image's code. The helper
+ has to mount it, or the quick start in DOCKERHUB.md keeps data and the helper
+ does not."""
+
+ def test_the_default_is_a_named_volume(self, tmp_path):
+ argv, _ = _invoke_run_sh(tmp_path, nvidia = True, amd = False)
+ assert _studio_mounts(argv) == ["unsloth-studio:/opt/unsloth-studio"], argv
+
+ @pytest.mark.parametrize("nvidia, amd", [(False, True), (False, False)])
+ def test_the_amd_and_cpu_paths_mount_it_too(self, tmp_path, nvidia, amd):
+ argv, _ = _invoke_run_sh(tmp_path, nvidia = nvidia, amd = amd)
+ assert _studio_mounts(argv) == ["unsloth-studio:/opt/unsloth-studio"], argv
+
+ def test_an_empty_value_disables_the_mount(self, tmp_path):
+ """`${VAR-default}`, not `${VAR:-default}`: an explicitly empty value is an
+ opt-out, for example on :core or for a throwaway run."""
+ argv, _ = _invoke_run_sh(
+ tmp_path, nvidia = True, amd = False, extra_env = {"UNSLOTH_STUDIO_VOLUME": ""}
+ )
+ assert _studio_mounts(argv) == [], argv
+
+ def test_a_custom_name_or_host_path_is_one_argv(self, tmp_path):
+ """A bind mount path with a space must not be word-split."""
+ host = str(tmp_path / "studio home")
+ argv, _ = _invoke_run_sh(
+ tmp_path, nvidia = True, amd = False, extra_env = {"UNSLOTH_STUDIO_VOLUME": host}
+ )
+ assert _studio_mounts(argv) == [f"{host}:/opt/unsloth-studio"], argv
+
+ def test_the_flag_is_documented_in_the_header(self):
+ body = open(_RUN_SH, encoding = "utf-8").read()
+ assert "UNSLOTH_STUDIO_VOLUME=unsloth-studio" in body
+
+
class TestStudioImageAllowsCpu:
def test_studio_image_opts_in_through_its_own_variable(self):
""":latest is the Studio image: without an opt-in every CPU-only, AMD and Docker-Desktop user gets an exit 1."""
diff --git a/tests/python/test_docker_hub_readme.py b/tests/python/test_docker_hub_readme.py
index ede4f6ccdfb..37e83901b7d 100644
--- a/tests/python/test_docker_hub_readme.py
+++ b/tests/python/test_docker_hub_readme.py
@@ -50,6 +50,29 @@ def test_the_hub_readme_describes_the_shipped_images():
assert stale not in text, f"the Hub README still carries {stale!r} from the old image"
+def test_the_hub_readme_explains_the_studio_volume():
+ """The volume keeps Studio's data and never pins its code; a volume from an image
+ before the code/data split is migrated with its old code kept aside. Both facts,
+ the way back to an older image, and what `docker rm` still discards have to be on
+ the page, since the quick start above them mounts the volume by default."""
+ text = HUB_README.read_text(encoding = "utf-8")
+ for needle in (
+ "-v unsloth-studio:/opt/unsloth-studio",
+ "/opt/unsloth-studio-app",
+ ".unsloth-studio-legacy/",
+ "UNSLOTH_STUDIO_KEEP_LEGACY=0",
+ "unsloth-studio-update",
+ "named volume, not a bind mount of a Windows or macOS host directory",
+ ):
+ assert needle in text, f"the Hub README no longer mentions {needle!r}"
+ # the helper is described as setting the flags of the quick start, which now
+ # includes the volume: run.sh must mount it (test_docker_cpu_fallback.py checks)
+ assert "including the `unsloth-studio` volume" in text
+ repo = REPO_README.read_text(encoding = "utf-8")
+ assert "-v unsloth-studio:/opt/unsloth-studio" in repo
+ assert ".unsloth-studio-legacy/" in repo
+
+
def test_the_repo_readme_run_command_matches_the_image():
text = REPO_README.read_text(encoding = "utf-8")
start = text.index("#### Docker")
diff --git a/tests/python/test_docker_studio_home_volume.py b/tests/python/test_docker_studio_home_volume.py
new file mode 100644
index 00000000000..bb158544067
--- /dev/null
+++ b/tests/python/test_docker_studio_home_volume.py
@@ -0,0 +1,584 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+"""The Studio image splits Studio's code from its data.
+
+Studio keeps one root for both: the venv, source tree and Node next to auth/,
+studio.db, outputs/ and exports/. Without a volume on it, `docker rm` lost every
+account, chat and trained model; with one, the volume kept the first image's code and
+every later image ran that old Studio. The image now keeps the code in
+$UNSLOTH_STUDIO_APP and links it into $UNSLOTH_STUDIO_HOME, which the entrypoint
+repairs at every start. Whatever is in the way is kept aside, never deleted, so a
+volume can also go back to an older image.
+"""
+
+import os
+import re
+import shutil
+import stat
+import subprocess
+from pathlib import Path
+
+import pytest
+
+REPO = Path(__file__).resolve().parents[2]
+DOCKER = REPO / "docker"
+LINKER = DOCKER / "studio_home.sh"
+STUDIO_DF = DOCKER / "Dockerfile.studio"
+ENTRYPOINT = DOCKER / "entrypoint.sh"
+LEGACY = ".unsloth-studio-legacy"
+
+pytestmark = pytest.mark.skipif(shutil.which("bash") is None, reason = "needs bash")
+
+
+def _app(tmp_path: Path) -> Path:
+ app = tmp_path / "app"
+ for name in (
+ "unsloth_studio",
+ "src",
+ "node",
+ "bin",
+ "share",
+ "cache",
+ ".venv_t5_550",
+ "uv-cache",
+ ):
+ (app / name).mkdir(parents = True)
+ (app / "unsloth_studio" / "VERSION").write_text("new\n")
+ (app / ".node.install.lock").write_text("")
+ (app / "llama.cpp").symlink_to("/opt/unsloth/llama.cpp")
+ return app
+
+
+def _link(
+ app: Path,
+ home: Path,
+ *args,
+ env = None,
+ path = None,
+):
+ full = dict(os.environ, UNSLOTH_STUDIO_APP = str(app), UNSLOTH_STUDIO_HOME = str(home))
+ full.update(env or {})
+ if path:
+ full["PATH"] = f"{path}:{full['PATH']}"
+ return subprocess.run(
+ ["bash", str(LINKER), *args], env = full, capture_output = True, text = True, timeout = 60
+ )
+
+
+def _legacy_home(tmp_path: Path) -> Path:
+ """A volume created by an image from before the split: real code dirs next to data."""
+ home = tmp_path / "home"
+ (home / "unsloth_studio").mkdir(parents = True)
+ (home / "unsloth_studio" / "VERSION").write_text("old\n")
+ (home / "src" / "studio").mkdir(parents = True)
+ (home / "src" / "studio" / "uncommitted.py").write_text("mine")
+ (home / ".node.install.lock").write_text("")
+ (home / "auth").mkdir()
+ (home / "auth" / "auth.db").write_text("users")
+ (home / "studio.db").write_text("chats")
+ return home
+
+
+def test_an_empty_home_gets_every_code_entry_as_a_link(tmp_path):
+ """A fresh bind mount or named volume starts empty."""
+ app = _app(tmp_path)
+ home = tmp_path / "home"
+ res = _link(app, home)
+ assert res.returncode == 0, res.stderr
+ for entry in app.iterdir():
+ target = home / entry.name
+ assert target.is_symlink(), entry.name
+ assert os.readlink(target) == str(entry)
+ assert (home / "unsloth_studio" / "VERSION").read_text() == "new\n"
+ assert not (home / LEGACY).exists()
+ assert res.stderr == ""
+
+
+def test_a_volume_from_an_earlier_image_runs_this_images_code(tmp_path):
+ """The freeze: an earlier image's venv and source tree sat in the volume as real
+ directories, so a new image kept running the old Studio."""
+ app = _app(tmp_path)
+ home = _legacy_home(tmp_path)
+ res = _link(app, home)
+ assert res.returncode == 0, res.stderr
+ assert (home / "unsloth_studio").is_symlink()
+ assert (home / "unsloth_studio" / "VERSION").read_text() == "new\n"
+ assert (home / "src").is_symlink()
+ assert "kept" in res.stderr and "aside" in res.stderr
+
+
+def test_nothing_in_the_way_is_deleted_it_is_kept_aside(tmp_path):
+ """What an earlier image left, or what the user put under a code entry's name, is
+ a rename away, not gone: the old venv, the old source tree with an uncommitted
+ file, a real file where the lock is, and a link the user pointed elsewhere."""
+ app = _app(tmp_path)
+ home = _legacy_home(tmp_path)
+ (home / "bin").mkdir()
+ (home / "bin" / "mytool").write_text("tool")
+ (home / "share").write_text("a file, not a dir")
+ big = tmp_path / "big"
+ big.mkdir()
+ (home / "cache").symlink_to(big)
+ res = _link(app, home)
+ assert res.returncode == 0, res.stderr
+ legacy = home / LEGACY
+ assert stat.S_IMODE(legacy.stat().st_mode) == 0o700
+ assert (legacy / "unsloth_studio" / "VERSION").read_text() == "old\n"
+ assert (legacy / "src" / "studio" / "uncommitted.py").read_text() == "mine"
+ assert (legacy / "bin" / "mytool").read_text() == "tool"
+ assert (legacy / "share").read_text() == "a file, not a dir"
+ assert (legacy / "cache").is_symlink() and os.readlink(legacy / "cache") == str(big)
+ assert (legacy / ".node.install.lock").is_file()
+ for name in ("unsloth_studio", "src", "bin", "share", "cache", ".node.install.lock"):
+ assert os.readlink(home / name) == str(app / name), name
+ assert "--restore" in res.stderr
+ assert "rm -rf" in res.stderr
+
+
+def test_restore_puts_the_kept_entries_back_for_an_older_image(tmp_path):
+ """Rollback: an image from before the split expects real directories, so the links
+ go and the kept entries return. Data is not touched either way."""
+ app = _app(tmp_path)
+ home = _legacy_home(tmp_path)
+ assert _link(app, home).returncode == 0
+ res = _link(app, home, "--restore")
+ assert res.returncode == 0, res.stderr
+ assert not (home / "unsloth_studio").is_symlink()
+ assert (home / "unsloth_studio" / "VERSION").read_text() == "old\n"
+ assert (home / "src" / "studio" / "uncommitted.py").read_text() == "mine"
+ assert not (home / LEGACY).exists()
+ # links this image added for entries the old image never had are gone too
+ assert not (home / "node").exists()
+ assert (home / "auth" / "auth.db").read_text() == "users"
+ assert (home / "studio.db").read_text() == "chats"
+ # and the next start of this image migrates again
+ assert _link(app, home).returncode == 0
+ assert (home / "unsloth_studio").is_symlink()
+
+
+def test_restore_refuses_to_overwrite_a_real_entry(tmp_path):
+ app = _app(tmp_path)
+ home = _legacy_home(tmp_path)
+ assert _link(app, home).returncode == 0
+ os.unlink(home / "src")
+ (home / "src").mkdir()
+ (home / "src" / "current.py").write_text("keep")
+ res = _link(app, home, "--restore")
+ assert res.returncode == 1
+ assert "real entry" in res.stderr
+ assert (home / "src" / "current.py").read_text() == "keep"
+ assert (home / LEGACY / "src" / "studio" / "uncommitted.py").read_text() == "mine"
+
+
+def test_restore_without_a_legacy_dir_copies_this_images_code_in(tmp_path):
+ """A volume first used after the split has no old code to put back. An older image
+ cannot run links into an app dir it does not have, so --restore materialises copies."""
+ app = _app(tmp_path)
+ home = tmp_path / "home"
+ (home / "outputs").mkdir(parents = True)
+ (home / "outputs" / "model.bin").write_text("weights")
+ assert _link(app, home).returncode == 0
+ res = _link(app, home, "--restore")
+ assert res.returncode == 0, res.stderr
+ assert not (home / "src").is_symlink() and (home / "src").is_dir()
+ assert (home / "unsloth_studio" / "VERSION").read_text() == "new\n"
+ assert not (home / "llama.cpp").exists() or (home / "llama.cpp").is_symlink()
+ assert (home / "outputs" / "model.bin").read_text() == "weights"
+ assert "copied this image's code" in res.stderr
+ # and a split image links its own code back in on the next start, keeping the copies aside
+ assert _link(app, home).returncode == 0
+ assert (home / "src").is_symlink()
+ assert (home / LEGACY / "src").is_dir()
+
+
+def test_restore_without_a_legacy_dir_or_an_app_dir_says_which_image_to_use(tmp_path):
+ app = _app(tmp_path)
+ home = tmp_path / "home"
+ assert _link(app, home).returncode == 0
+ import shutil
+
+ shutil.rmtree(app)
+ res = _link(app, home, "--restore")
+ assert res.returncode == 1
+ assert "run --restore under an image that has the Studio code" in res.stderr
+ assert (home / "src").is_symlink()
+
+
+def test_keep_legacy_0_deletes_instead(tmp_path):
+ app = _app(tmp_path)
+ home = _legacy_home(tmp_path)
+ res = _link(app, home, env = {"UNSLOTH_STUDIO_KEEP_LEGACY": "0"})
+ assert res.returncode == 0, res.stderr
+ assert not (home / LEGACY).exists()
+ assert (home / "src").is_symlink()
+ assert "removed" in res.stderr and "KEEP_LEGACY=0" in res.stderr
+ assert (home / "studio.db").read_text() == "chats"
+
+
+def test_only_the_latest_generation_is_kept_aside(tmp_path):
+ """A second upgrade replaces the copy the first one kept; the legacy dir does not
+ accumulate."""
+ app = _app(tmp_path)
+ home = _legacy_home(tmp_path)
+ assert _link(app, home).returncode == 0
+ os.unlink(home / "src")
+ (home / "src").mkdir()
+ (home / "src" / "gen2.py").write_text("2")
+ res = _link(app, home)
+ assert res.returncode == 0, res.stderr
+ assert (home / LEGACY / "src" / "gen2.py").read_text() == "2"
+ assert not (home / LEGACY / "src" / "studio").exists()
+
+
+def test_runtime_data_is_never_touched(tmp_path):
+ app = _app(tmp_path)
+ home = tmp_path / "home"
+ for name in ("auth", "outputs", "exports", "runs", "rag", "assets"):
+ (home / name).mkdir(parents = True)
+ (home / name / "keep.txt").write_text(name)
+ (home / "studio.db").write_text("chats")
+ res = _link(app, home)
+ assert res.returncode == 0, res.stderr
+ for name in ("auth", "outputs", "exports", "runs", "rag", "assets"):
+ assert not (home / name).is_symlink()
+ assert (home / name / "keep.txt").read_text() == name
+ assert (home / "studio.db").read_text() == "chats"
+
+
+def test_links_already_in_place_are_left_alone_and_stale_ones_retargeted(tmp_path):
+ """A link into an older app path is ours and is simply re-pointed; a link the user
+ made is kept aside like any other entry."""
+ app = _app(tmp_path)
+ home = tmp_path / "home"
+ home.mkdir()
+ (home / "node").symlink_to(app / "node")
+ (home / "src").symlink_to(app / "src-from-an-older-layout")
+ (home / "share").symlink_to(tmp_path / "somewhere-else")
+ before = os.lstat(home / "node").st_ino
+ res = _link(app, home)
+ assert res.returncode == 0, res.stderr
+ assert os.lstat(home / "node").st_ino == before
+ assert os.readlink(home / "src") == str(app / "src")
+ assert os.readlink(home / "share") == str(app / "share")
+ assert not (home / LEGACY / "src").exists()
+ assert os.readlink(home / LEGACY / "share") == str(tmp_path / "somewhere-else")
+
+
+def test_links_to_entries_this_image_dropped_are_pruned(tmp_path):
+ """An earlier image's volume can hold a link to an entry, e.g. a transformers tier,
+ that this image no longer ships. Nothing the user created is pruned with it."""
+ app = _app(tmp_path)
+ home = tmp_path / "home"
+ home.mkdir()
+ (home / ".venv_t5_510").symlink_to(app / ".venv_t5_510")
+ (home / "outputs").symlink_to(tmp_path / "never-created")
+ res = _link(app, home)
+ assert res.returncode == 0, res.stderr
+ assert not (home / ".venv_t5_510").is_symlink()
+ assert (home / "outputs").is_symlink()
+ assert (home / ".venv_t5_550").is_symlink()
+
+
+def test_a_second_run_is_silent_and_changes_nothing(tmp_path):
+ app = _app(tmp_path)
+ home = _legacy_home(tmp_path)
+ assert _link(app, home).returncode == 0
+ snapshot = {p: os.lstat(p).st_ino for p in home.rglob("*")}
+ res = _link(app, home)
+ assert res.returncode == 0
+ assert res.stderr == ""
+ assert {p: os.lstat(p).st_ino for p in home.rglob("*")} == snapshot
+
+
+def test_names_with_spaces_and_dotfiles_are_handled(tmp_path):
+ app = tmp_path / "app dir"
+ (app / "my venv").mkdir(parents = True)
+ (app / ".hidden lock").write_text("")
+ home = tmp_path / "home dir"
+ (home / "my venv").mkdir(parents = True)
+ res = _link(app, home)
+ assert res.returncode == 0, res.stderr
+ assert os.readlink(home / "my venv") == str(app / "my venv")
+ assert os.readlink(home / ".hidden lock") == str(app / ".hidden lock")
+ assert (home / LEGACY / "my venv").is_dir()
+
+
+def test_the_same_root_for_app_and_home_is_refused_with_the_install_intact(tmp_path):
+ """`-e UNSLOTH_STUDIO_HOME=/opt/unsloth-studio-app` would otherwise move the whole
+ install aside and leave links pointing at themselves."""
+ app = _app(tmp_path)
+ res = _link(app, app)
+ assert res.returncode == 1
+ assert "must not be" in res.stderr
+ assert (app / "unsloth_studio" / "VERSION").read_text() == "new\n"
+ assert not (app / "src").is_symlink()
+ assert not (app / LEGACY).exists()
+ # through a symlink too: paths are compared as the kernel sees them
+ alias = tmp_path / "alias"
+ alias.symlink_to(app)
+ res = _link(app, alias)
+ assert res.returncode == 1
+ assert not (app / "src").is_symlink()
+
+
+def test_nested_roots_are_refused(tmp_path):
+ app = _app(tmp_path)
+ inside = app / "home"
+ inside.mkdir()
+ assert _link(app, inside).returncode == 1
+ assert not (inside / "src").exists()
+ home = tmp_path / "home"
+ home.mkdir()
+ nested_app = home / "app"
+ nested_app.mkdir()
+ assert _link(nested_app, home).returncode == 1
+
+
+def _stub(bindir: Path, name: str, body: str):
+ bindir.mkdir(exist_ok = True)
+ p = bindir / name
+ p.write_text("#!/usr/bin/env bash\n" + body)
+ p.chmod(0o755)
+
+
+def test_an_interrupted_migration_never_loses_an_entry(tmp_path):
+ """The move completes before the link is made, so a failure between the two leaves
+ the kept copy in place and names it; a rerun finishes the job."""
+ app = _app(tmp_path)
+ home = _legacy_home(tmp_path)
+ bindir = tmp_path / "bin"
+ _stub(
+ bindir,
+ "ln",
+ 'case "$*" in */src) echo "ln: simulated failure" >&2; exit 1;; esac\n'
+ 'exec /bin/ln "$@"\n',
+ )
+ res = _link(app, home, path = str(bindir))
+ assert res.returncode == 1
+ assert "cannot link" in res.stderr
+ assert "intact at" in res.stderr
+ kept = home / LEGACY
+ # src was moved and its link failed: not lost, its kept copy is named in the message
+ assert not (home / "src").exists() and not (home / "src").is_symlink()
+ assert (kept / "src" / "studio" / "uncommitted.py").read_text() == "mine"
+ assert str(kept / "src") in res.stderr
+ # entries after src in the loop were not reached and are still real
+ assert not (home / "unsloth_studio").is_symlink()
+ assert (home / "studio.db").read_text() == "chats"
+ res = _link(app, home)
+ assert res.returncode == 0, res.stderr
+ assert (home / "src").is_symlink() and (home / "unsloth_studio").is_symlink()
+ assert (kept / "src" / "studio" / "uncommitted.py").read_text() == "mine"
+
+
+def test_a_failed_move_changes_nothing(tmp_path):
+ app = _app(tmp_path)
+ home = _legacy_home(tmp_path)
+ bindir = tmp_path / "bin"
+ _stub(bindir, "mv", 'echo "mv: simulated failure" >&2; exit 1\n')
+ res = _link(app, home, path = str(bindir))
+ assert res.returncode == 1
+ assert "cannot move" in res.stderr
+ assert not (home / "unsloth_studio").is_symlink()
+ assert (home / "unsloth_studio" / "VERSION").read_text() == "old\n"
+ assert not any((home / LEGACY).iterdir())
+
+
+def test_a_link_where_the_kept_aside_copies_go_is_refused(tmp_path):
+ """mkdir -p, rm -rf and mv all follow a symlink, so a link left at
+ .unsloth-studio-legacy would send the kept-aside copies wherever it points, the app
+ dir included. Both the link run and --restore stop before writing through it."""
+ app = _app(tmp_path)
+ home = _legacy_home(tmp_path)
+ decoy = tmp_path / "decoy"
+ (decoy / "src").mkdir(parents = True)
+ (decoy / "src" / "app.py").write_text("this image's code")
+ (home / LEGACY).symlink_to(decoy)
+ for args in ((), ("--restore",)):
+ res = _link(app, home, *args)
+ assert res.returncode == 1, res.stderr
+ assert LEGACY in res.stderr and "must be a directory" in res.stderr
+ assert [p.name for p in decoy.iterdir()] == ["src"]
+ assert (decoy / "src" / "app.py").read_text() == "this image's code"
+ assert (home / LEGACY).is_symlink()
+ assert not (home / "src").is_symlink()
+ assert (home / "src" / "studio" / "uncommitted.py").read_text() == "mine"
+ assert (home / "unsloth_studio" / "VERSION").read_text() == "old\n"
+ assert not (home / "node").exists()
+ # with the link out of the way the migration runs as usual
+ os.unlink(home / LEGACY)
+ assert _link(app, home).returncode == 0
+ assert (home / "src").is_symlink()
+
+
+def test_a_restore_copy_that_fails_leaves_the_link_and_no_half_tree(tmp_path):
+ """The copy lands beside the link and is swapped in whole. A partial real directory
+ at the entry's name would be skipped by the rerun's symlink-only loop, so --restore
+ would then report success over code that is missing files."""
+ app = _app(tmp_path)
+ (app / "src" / "studio").mkdir()
+ (app / "src" / "studio" / "main.py").write_text("code")
+ home = tmp_path / "home"
+ assert _link(app, home).returncode == 0
+ bindir = tmp_path / "bin"
+ _stub(
+ bindir,
+ "cp",
+ 'case "$*" in\n'
+ ' *"/src "*) mkdir -p "${@: -1}"; echo half > "${@: -1}/half.py";\n'
+ ' echo "cp: simulated failure" >&2; exit 1;;\n'
+ "esac\n"
+ 'exec /bin/cp "$@"\n',
+ )
+ res = _link(app, home, "--restore", path = str(bindir))
+ assert res.returncode == 1
+ assert "rerun --restore" in res.stderr
+ assert (home / "src").is_symlink()
+ assert not (home / "src.restore-tmp").exists()
+ # the rerun sees the link it left intact and finishes the job
+ res = _link(app, home, "--restore")
+ assert res.returncode == 0, res.stderr
+ assert (home / "src").is_dir() and not (home / "src").is_symlink()
+ assert (home / "src" / "studio" / "main.py").read_text() == "code"
+ assert not (home / "src" / "half.py").exists()
+ assert not (home / "src.restore-tmp").exists()
+
+
[email protected](os.geteuid() == 0, reason = "root ignores directory modes")
+def test_a_read_only_home_fails_loudly_and_touches_nothing(tmp_path):
+ app = _app(tmp_path)
+ home = _legacy_home(tmp_path)
+ home.chmod(0o555)
+ try:
+ res = _link(app, home)
+ finally:
+ home.chmod(0o755)
+ assert res.returncode == 1
+ assert "ERROR" in res.stderr
+ assert not (home / "unsloth_studio").is_symlink()
+ assert (home / "unsloth_studio" / "VERSION").read_text() == "old\n"
+ assert not (home / LEGACY).exists()
+
+
+def test_updater_scratch_in_the_app_dir_is_never_linked_into_the_home(tmp_path):
+ """unsloth-studio-update stages the new tree as .src-update.* and parks the old one as
+ .src-prev.* next to src; a killed update leaves them behind. They are scratch."""
+ app = _app(tmp_path)
+ (app / ".src-update.abc123").mkdir()
+ (app / ".src-prev.4242").mkdir()
+ home = tmp_path / "home"
+ res = _link(app, home)
+ assert res.returncode == 0, res.stderr
+ assert not (home / ".src-update.abc123").exists()
+ assert not (home / ".src-prev.4242").exists()
+ assert (home / "src").is_symlink()
+
+
+def test_a_src_lost_between_the_updaters_two_renames_is_put_back(tmp_path):
+ """SIGKILL between `mv src .src-prev.X` and `mv .src-update.Y src` leaves the previous
+ tree as the only copy; the home's src link must not be pruned as dangling."""
+ app = _app(tmp_path)
+ (app / "src" / "studio").mkdir()
+ (app / "src").rename(app / ".src-prev.k9x2Qa")
+ (app / ".src-update.abc123").mkdir()
+ home = tmp_path / "home"
+ home.mkdir()
+ (home / "src").symlink_to(app / "src")
+ res = _link(app, home)
+ assert res.returncode == 0, res.stderr
+ assert (app / "src" / "studio").is_dir()
+ assert not (app / ".src-prev.k9x2Qa").exists()
+ assert (home / "src").is_symlink() and (home / "src" / "studio").is_dir()
+ assert "put " in res.stderr
+
+
+def test_two_previous_trees_are_left_for_a_human(tmp_path):
+ app = _app(tmp_path)
+ (app / "src").rename(app / ".src-prev.aaaaaa")
+ (app / ".src-prev.bbbbbb").mkdir()
+ home = tmp_path / "home"
+ res = _link(app, home)
+ assert res.returncode == 0, res.stderr
+ assert not (app / "src").exists()
+ assert "several .src-prev" in res.stderr
+
+
+def test_the_linker_is_a_no_op_without_an_app_dir(tmp_path):
+ """The entrypoint belongs to the base image too, which has no Studio."""
+ home = tmp_path / "home"
+ res = _link(tmp_path / "missing", home)
+ assert res.returncode == 0, res.stderr
+ assert not home.exists()
+
+
+def test_the_code_moves_in_the_same_layer_that_installs_it():
+ """A `mv` in a later RUN stores the 10+ GB Studio install twice."""
+ body = STUDIO_DF.read_text(encoding = "utf-8")
+ runs = re.split(r"\n(?=RUN |COPY |ENV |ARG |FROM |EXPOSE |CMD |USER )", body)
+ install = [r for r in runs if r.startswith("RUN ") and "bash install.sh --local" in r]
+ assert len(install) == 1
+ assert '-exec mv -t "${UNSLOTH_STUDIO_APP}"' in install[0]
+ assert "/usr/local/bin/unsloth-studio-home" in install[0]
+ assert "UNSLOTH_STUDIO_APP=/opt/unsloth-studio-app" in body
+
+
+def test_the_uv_cache_goes_with_the_code_and_cache_stays_data():
+ """install.sh and setup.sh default the uv cache to $STUDIO_HOME/cache/uv only when
+ UV_CACHE_DIR is unset; the venv hardlinks into it (9 GB). Studio's runtime caches
+ (download-resume manifests, llama slots, dataset caches) also live under cache/, so
+ linking the whole directory into the app dir would have deleted a volume's runtime
+ state on upgrade and sent new state into the container layer. The image points uv
+ at the app dir before the install RUN and leaves cache/ in the home."""
+ body = STUDIO_DF.read_text(encoding = "utf-8")
+ env_block = body[
+ body.index("ENV UNSLOTH_STUDIO_HOME=") : body.index(
+ "\n\n", body.index("ENV UNSLOTH_STUDIO_HOME=")
+ )
+ ]
+ assert "UV_CACHE_DIR=/opt/unsloth-studio-app/uv-cache" in env_block
+ install = [
+ r
+ for r in re.split(r"\n(?=RUN |COPY |ENV |ARG |FROM |EXPOSE |CMD |USER )", body)
+ if r.startswith("RUN ") and "bash install.sh --local" in r
+ ]
+ assert (
+ env_block in body[: body.index(install[0])]
+ ), "UV_CACHE_DIR must be set before the install"
+ assert "! -name cache -exec mv -t" in install[0], "cache/ must not move to the app dir"
+ assert (
+ 'test ! -e "${UNSLOTH_STUDIO_HOME}/cache/uv"' in install[0]
+ ), "the build must prove the uv cache did not land in the home"
+
+
+def test_the_entrypoint_relinks_before_it_touches_the_studio_venv_and_stops_on_failure():
+ """A half-linked home must not reach Studio: the hook exits instead of warning."""
+ body = ENTRYPOINT.read_text(encoding = "utf-8")
+ hook = body.index("/usr/local/bin/unsloth-studio-home")
+ assert hook < body.index("select_cuda_jit_tools() {")
+ block = body[hook : body.index("select_cuda_jit_tools() {")]
+ assert "exit 1" in block
+ assert "WARN" not in block
+
+
+def test_the_in_app_updates_know_the_images_code_tree():
+ """whisper.cpp is discovered through the Studio home, where the linker leaves a link
+ into the app dir, and the updater reads a linked component dir as the user's own
+ checkout and offers nothing. It tells the two apart by the same variable the image
+ sets, so the name must not drift apart from the image's."""
+ flow = (REPO / "studio" / "backend" / "utils" / "prebuilt" / "update_flow.py").read_text(
+ encoding = "utf-8"
+ )
+ assert 'os.environ.get("UNSLOTH_STUDIO_APP")' in flow
+ assert "UNSLOTH_STUDIO_APP=/opt/unsloth-studio-app" in STUDIO_DF.read_text(encoding = "utf-8")
+
+
+def test_the_docs_mount_the_studio_home():
+ for doc in (DOCKER / "DOCKERHUB.md", REPO / "README.md"):
+ assert "-v unsloth-studio:/opt/unsloth-studio" in doc.read_text(encoding = "utf-8"), doc
+
+
+def test_the_linker_is_in_the_build_context():
+ """docker/.dockerignore is an allowlist; a file missing from it fails the build
+ with `"/studio_home.sh": not found`."""
+ allowed = (DOCKER / ".dockerignore").read_text(encoding = "utf-8").splitlines()
+ assert "!studio_home.sh" in allowed
diff --git a/tests/python/test_docker_update_helpers.py b/tests/python/test_docker_update_helpers.py
index 5dcd665728b..b57946b8412 100644
--- a/tests/python/test_docker_update_helpers.py
+++ b/tests/python/test_docker_update_helpers.py
@@ -358,10 +358,12 @@ def test_fetcher_normalizes_the_base_build_for_the_marker_tag(release_tag, expec
def test_a_failed_studio_update_says_the_venv_on_disk_is_already_replaced(tmp_path: Path):
"""Not restarting protects the running process, and only the code it has already
imported: the backend defers thousands of imports, so a lazy one fails the same
- way. The venv itself is under $UNSLOTH_STUDIO_HOME, which the header recommends
- putting on a named volume, so the replacement also survives docker rm + docker run.
- The message used to stop at "the running process keeps serving", which reads as
- though nothing is wrong until the operator chooses to restart."""
+ way. The venv is the image's copy under $UNSLOTH_STUDIO_APP, linked into the Studio
+ home, so the volume never holds it: docker rm + docker run is the documented way
+ back to a working venv, and the message has to say so instead of the older claim
+ that a persisted home kept the breakage. The message used to stop at "the running
+ process keeps serving", which reads as though nothing is wrong until the operator
+ chooses to restart."""
env = _studio_env(tmp_path, import_ok = False)
res = _run(STUDIO_UPDATE, [], env)
assert res.returncode != 0, "a broken update must not report success"
@@ -370,7 +372,10 @@ def test_a_failed_studio_update_says_the_venv_on_disk_is_already_replaced(tmp_pa
"the failure never says the on-disk environment has been overwritten:\n" + res.stderr
)
assert "fatal" in err, "the failure never says a restart parks Studio in FATAL:\n" + res.stderr
- assert "unsloth_studio_home" in err or "persisted home" in err, (
- "the failure never says a persisted Studio home keeps it broken across a "
- "container recreate:\n" + res.stderr
+ assert "docker rm" in err and "docker run" in err, (
+ "the failure never says docker rm + docker run restores the image's venv:\n" + res.stderr
+ )
+ assert "persisted home" not in err and "keeps it broken" not in err, (
+ "the failure still claims a persisted home keeps the venv broken, which the "
+ "code/data split made false:\n" + res.stderr
)
diff --git a/tests/test_studio_root_resilience.py b/tests/test_studio_root_resilience.py
index 5d782fd8d8f..f16648fc435 100644
--- a/tests/test_studio_root_resilience.py
+++ b/tests/test_studio_root_resilience.py
@@ -37,6 +37,31 @@ def test_infer_studio_home_swallows_permission_error(tmp_path, monkeypatch):
assert mod._infer_studio_home_from_venv() is None
+def test_infer_studio_home_refuses_the_docker_app_dir(tmp_path, monkeypatch):
+ """The Docker image keeps the venv under UNSLOTH_STUDIO_APP and links it into the
+ Studio home, so sys.prefix resolves to the app dir, which carries the sentinels.
+ Adopting it would send studio.db and auth/ into the container layer instead of the
+ volume; inference must decline so the later defaults apply."""
+ app = tmp_path / "unsloth-studio-app"
+ venv = app / "unsloth_studio"
+ venv.mkdir(parents = True)
+ (app / "share").mkdir()
+ (app / "share" / "studio.conf").write_text("")
+ home = tmp_path / "unsloth-studio"
+ home.mkdir()
+ (home / "unsloth_studio").symlink_to(venv)
+ monkeypatch.setattr(sys, "prefix", str(home / "unsloth_studio"))
+ sys.modules.pop("sr_app_dir", None)
+ mod = _load("sr_app_dir", STORAGE_ROOTS)
+ monkeypatch.delenv("UNSLOTH_STUDIO_APP", raising = False)
+ assert mod._infer_studio_home_from_venv() == app, "sentinel-gated inference broke"
+ monkeypatch.setenv("UNSLOTH_STUDIO_APP", str(app))
+ assert mod._infer_studio_home_from_venv() is None
+ # Any other app dir is not a match, so a bare-metal install keeps its inference.
+ monkeypatch.setenv("UNSLOTH_STUDIO_APP", str(tmp_path / "elsewhere"))
+ assert mod._infer_studio_home_from_venv() == app
+
+
def test_studio_root_does_not_crash_on_permission_error(tmp_path, monkeypatch):
"""studio_root() falls through to the legacy default on a restricted filesystem."""
candidate = tmp_path / "fake_root"