Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Docker Studio: keep unsloth-studio-update --ref from leaving Studio dead (#10826)
oobabooga3277f0d96780
diff --git a/.github/workflows/studio-update-smoke.yml b/.github/workflows/studio-update-smoke.ymlindex d1e30408168..e5a9c78d7e9 100644--- a/.github/workflows/studio-update-smoke.yml+++ b/.github/workflows/studio-update-smoke.yml@@ -96,6 +96,10 @@ on:# that depend on it.- '.github/actions/frontend-dist-restore/action.yml'- '.github/actions/frontend-dist-save/action.yml'+ # The Windows job restores and saves the uv download cache directly, as the+ # pull_request list above already records.+ - '.github/actions/uv-cache-restore/action.yml'+ - '.github/actions/uv-cache-save/action.yml'workflow_dispatch:concurrency:@@ -452,6 +456,13 @@ jobs:with:python-version: '3.12'+ # install-unsloth-local restores this for the Linux and macOS jobs above; this+ # hand-written pwsh install never had it, so every run re-downloaded every wheel.+ # install.ps1 preserves the UV_CACHE_DIR the action exports.+ - name: Restore the uv download cache+ id: uv-cache+ uses: ./.github/actions/uv-cache-restore+- name: Install Unsloth (--local, --no-torch)shell: pwshenv:@@ -473,6 +484,13 @@ jobs:ForEach-Object { '[{0,4:N0}s] {1}' -f $sw.Elapsed.TotalSeconds, $_ }if ($LASTEXITCODE -ne 0) { throw "install.ps1 exited with code $LASTEXITCODE" }+ # Paired with the restore above: pruned to built wheels, saved on main only.+ - name: Save the uv download cache+ uses: ./.github/actions/uv-cache-save+ with:+ cache-hit: ${{ steps.uv-cache.outputs.cache-hit }}+ key: ${{ steps.uv-cache.outputs.key }}+- name: A second update does nothing, and proves it# The Windows leg is the one that can catch a path or marker written with the# wrong separator: every comparison in the harness is a byte-for-byte one.diff --git a/docker/studio_home.sh b/docker/studio_home.shindex 7e776dc6d11..4d88292e5dc 100755--- a/docker/studio_home.sh+++ b/docker/studio_home.sh@@ -165,6 +165,25 @@ for target in "$HOME_DIR"/*; doesacdone+# A killed update (docker stop ends in SIGKILL) can leave its previous tree beside src+# and half-replaced packages; unsloth-studio-update keeps a record beside src until the+# update is committed. Finish that restore here, before supervisord starts Studio on the+# unverified tree. The home is linked by now, so the updater finds the venv.+if [ -s "$APP/.src-update.rollback" ]; then+ updater="${UNSLOTH_STUDIO_UPDATER:-/usr/local/bin/unsloth-studio-update}"+ if [ -x "$updater" ]; then+ log "an update was interrupted (record at $APP/.src-update.rollback); putting the previous install back before Studio starts"+ if UNSLOTH_STUDIO_HOME="$HOME_DIR" "$updater" --recover; then+ log "the previous install is back"+ else+ log "WARNING: the previous install could not be put back (see above); Studio may fail to start"+ log " finish it by hand: docker exec <container> unsloth-studio-update --recover"+ fi+ else+ log "WARNING: an update was interrupted (record at $APP/.src-update.rollback) and $updater is not here to finish the restore"+ fi+fi+if [ "${#moved[@]}" -gt 0 ]; thensize="$(du -sh -- "$legacy" 2>/dev/null | cut -f1)"log "kept aside in $legacy (${size:-?}): ${moved[*]}"diff --git a/docker/unsloth_studio_update.sh b/docker/unsloth_studio_update.shindex d527a8d7bab..538f3eb2d61 100755--- a/docker/unsloth_studio_update.sh+++ b/docker/unsloth_studio_update.sh@@ -5,9 +5,22 @@# Studio service. The torch/CUDA stack is left untouched.## docker exec <container> unsloth-studio-update # latest PyPI release-# docker exec <container> unsloth-studio-update --ref main # latest git main-# docker exec <container> unsloth-studio-update --with-deps # also update deps+# docker exec <container> unsloth-studio-update --ref main # latest git main (builds its frontend)+# docker exec <container> unsloth-studio-update --with-deps # also update deps (torch/CUDA stay pinned)# docker exec <container> unsloth-studio-update --no-restart # update, restart later+# --zoo-ref <ref> unsloth-zoo ref to pair with --ref (default: the same ref, else main)+# --packages "<specs>" what a release update installs (default: unsloth unsloth_zoo)+# --recover only finish the restore a killed update left (the container+# start runs this before Studio comes up), then exit+# UNSLOTH_STUDIO_UPDATE_HEALTH_WAIT=<seconds> how long to wait for /api/health after the+# restart (default 180). The previous install is kept until Studio+# answers; if it does not, or the restart fails, it goes back and the+# helper exits 1. 0 skips the wait: the update is committed as soon as+# the restart command succeeds, with no proof that it can serve.+# UNSLOTH_NPM_REGISTRY=<url> npm registry for the --ref frontend build, as in the installer+#+# One update at a time: a second invocation while one runs exits 1 without touching+# anything.## 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.@@ -23,9 +36,11 @@ REF=""ZOO_REF=""NO_DEPS="--no-deps"RESTART=1+RECOVER_ONLY=0PACKAGES="unsloth unsloth_zoo"-usage() { sed -n '2,21p' "$0"; }+# the header comment, up to the first line that is not one+usage() { awk 'NR > 1 && !/^#/ { exit } NR > 1 { print }' "$0"; }while [ $# -gt 0 ]; docase "$1" in@@ -33,6 +48,7 @@ while [ $# -gt 0 ]; do--zoo-ref) ZOO_REF="$2"; shift 2;;--with-deps) NO_DEPS=""; shift;;--no-restart) RESTART=0; shift;;+ --recover) RECOVER_ONLY=1; shift;;--packages) PACKAGES="$2"; shift 2;;-h|--help) usage; exit 0;;*) echo "unsloth-studio-update: unknown argument: $1" >&2; usage; exit 2;;@@ -51,13 +67,346 @@ if [ -z "$PY" ] && [ -L "$STUDIO_HOME/bin/unsloth" ]; thenfi[ -n "$PY" ] || { echo "unsloth-studio-update: could not find the Studio venv under $STUDIO_HOME" >&2; exit 1; }-version_of() { "$PY" -c "from importlib.metadata import version; print(version('unsloth'))" 2>/dev/null || echo "unknown"; }+# The editable tree may sit behind a symlink from the home into the image's copy: work+# on the real path, but keep pip pointed at the home path (SRC_INSTALL) so the recorded+# install resolves through the link whichever image serves it.+SRC="$(readlink -f "$STUDIO_HOME/src" 2>/dev/null || true)"+[ -n "$SRC" ] || SRC="$STUDIO_HOME/src"+SRC_DIR="$(dirname "$SRC")"+SRC_INSTALL="$STUDIO_HOME/src"+[ -e "$SRC_INSTALL" ] || SRC_INSTALL="$SRC"++# From /: `python -` and `python -c` put the caller's cwd first on sys.path (python -m pip+# drops it itself), so a checkout there with its own unsloth.egg-info would answer for+# the venv's installed distribution.+version_of() { (cd / && "$PY" -c "from importlib.metadata import version; print(version('unsloth'))") 2>/dev/null || echo "unknown"; }++log() { echo "[studio-update] $*"; }++# Package record and dependency snapshot of the install being replaced, kept beside the+# tree from the first pip call until the commit, so a killed run can be finished later.+KEEP_ROLLBACK="$SRC_DIR/.src-update.rollback"+KEEP_FREEZE="$SRC_DIR/.src-update.freeze"++# Puts recorded packages back: the snapshot as pinned, the packages by force (pip takes+# a same-version editable tree as already satisfied), what the update added taken out.+# Returns 1 when pip could not do all of it.+reinstall_recorded() {+ local rollback="$1" freeze="$2" ok=0 _absent _added _now+ if [ -n "$freeze" ] && [ -s "$freeze" ]; then+ "$PY" -m pip install --no-deps -r "$freeze" >/dev/null \+ || { log "CRITICAL: pip could not put the previous dependency set back; re-run with --with-deps once the cause is fixed"; ok=1; }+ # -r reinstalls what was there; what the update pulled in on top is taken out too.+ # A failed listing is a failed restore: with an empty list nothing would be removed.+ if _now="$("$PY" -m pip freeze --exclude-editable 2>/dev/null)"; then+ _added="$(printf '%s\n' "$_now" | sed -E 's/[=<>!~ @].*//' | sort -u \+ | comm -23 - <(sed -E 's/[=<>!~ @].*//' "$freeze" | sort -u) | tr '\n' ' ')"+ if [ -n "${_added// /}" ]; then+ # shellcheck disable=SC2086+ "$PY" -m pip uninstall -y $_added >/dev/null \+ || { log "CRITICAL: pip could not remove what the update pulled in: $_added"; ok=1; }+ fi+ else+ log "CRITICAL: pip could not list the installed packages, so what the update pulled in was not removed"+ ok=1+ fi+ fi+ if [ -n "$rollback" ] && [ -s "$rollback" ]; then+ "$PY" -m pip install --no-deps --force-reinstall -r "$rollback" >/dev/null \+ || { log "CRITICAL: pip could not reinstall: $(tr '\n' ' ' < "$rollback")"; ok=1; }+ _absent="$(sed -n 's/^# absent: //p' "$rollback" | tr '\n' ' ')"+ if [ -n "${_absent// /}" ]; then+ # shellcheck disable=SC2086+ "$PY" -m pip uninstall -y $_absent >/dev/null \+ || { log "CRITICAL: pip could not remove what the update added: $_absent"; ok=1; }+ fi+ fi+ return "$ok"+}++# Sets SUPCTL and _st: 0 when supervisord runs studio, 3 when it manages a program that+# is not running (STOPPED, EXITED, FATAL: what a failed earlier update leaves behind),+# 4 when nothing here manages it.+find_supctl() {+ SUPCTL="$(command -v supervisorctl || true)"+ [ -n "$SUPCTL" ] || SUPCTL="/opt/unsloth-venv/bin/supervisorctl"+ _st=0+ [ -x "$SUPCTL" ] && { "$SUPCTL" status studio >/dev/null 2>&1 || _st=$?; } || _st=4+}++log "Studio venv: $PY"+log "before: unsloth $(version_of)"++# One updater at a time: two would take each other's trees for leftovers. Held on an+# open fd, so the kernel drops it however the run ends; the name matches the linker's+# scratch pattern so it is never linked into the home.+LOCK="$SRC_DIR/.src-update.lock"+command -v flock >/dev/null 2>&1 || { echo "unsloth-studio-update: flock (util-linux) is missing; refusing to run unlocked." >&2; exit 1; }+exec 9>>"$LOCK" || { echo "unsloth-studio-update: cannot open $LOCK" >&2; exit 1; }+if ! flock -n 9; then+ echo "unsloth-studio-update: another unsloth-studio-update is running (holding $LOCK); wait for it to finish, then retry. Nothing was changed." >&2+ exit 1+fi++# Leftovers of a run killed outright (no trap ran): .src-prev.* and .src-update.* beside+# src. The kept package record is the one marker of an uncommitted update: with it, a+# previous tree goes back over the unverified one and the packages are reinstalled;+# without it a previous tree is scratch. No src at all means the kill landed between+# the two moves, and the lone previous tree goes back either way.+shopt -s nullglob+_prev=("$SRC_DIR"/.src-prev.*)+if [ "${#_prev[@]}" = "1" ] && [ -d "${_prev[0]}" ]; then+ if [ ! -e "$SRC" ]; then+ log "recovering the source tree an interrupted update left at ${_prev[0]}"+ mv -T "${_prev[0]}" "$SRC"+ _recovered=1+ elif [ -s "$KEEP_ROLLBACK" ]; then+ log "an interrupted update left its previous tree at ${_prev[0]}; putting it back over the unverified one"+ _drop="$(mktemp -d "$SRC_DIR/.src-update.XXXXXX")" && rmdir "$_drop"+ mv -T "$SRC" "$_drop"+ mv -T "${_prev[0]}" "$SRC"+ rm -rf "$_drop"+ _recovered=1+ fi+fi+if [ -s "$KEEP_ROLLBACK" ]; then+ log "an interrupted update left its package record at $KEEP_ROLLBACK; putting the previous packages back first"+ if reinstall_recorded "$KEEP_ROLLBACK" "$KEEP_FREEZE"; then+ rm -f "$KEEP_ROLLBACK" "$KEEP_FREEZE"+ log "the previous packages are back"+ _recovered=1+ # The service may still be running the unverified code, or be FATAL from the+ # interrupted restart: put it on the restored install before anything else.+ if [ "$RESTART" = "1" ]; then+ find_supctl+ if [ "$_st" = "0" ] || [ "$_st" = "3" ]; then+ _cmd=restart+ [ "$_st" = "3" ] && _cmd=start+ if "$SUPCTL" "$_cmd" studio >/dev/null 2>&1 && "$SUPCTL" status studio >/dev/null 2>&1; then+ log "the studio service is running the restored install"+ else+ log "WARNING: supervisorctl $_cmd studio failed on the restored install (see docker logs)"+ fi+ fi+ else+ log "--no-restart: Studio may still be running the interrupted update; restart it to load the restored install"+ fi+ else+ echo "unsloth-studio-update: could not put the previous packages back (see the CRITICAL lines above); fix the cause and run this again. Nothing else was changed." >&2+ exit 1+ fi+fi+if [ -d "$SRC" ]; then+ for _stale in "$SRC_DIR"/.src-update.* "$SRC_DIR"/.src-prev.*; do+ [ "$_stale" = "$LOCK" ] && continue+ log "removing $_stale, left behind by an earlier update"+ rm -rf "$_stale"+ done+fi+shopt -u nullglob+# --recover: the container start (studio_home.sh) runs the recovery above before+# supervisord starts Studio, so a kill that no trap could answer never boots the+# unverified tree; nothing else is done.+if [ "$RECOVER_ONLY" = "1" ]; then+ DONE=1+ if [ "${_recovered:-0}" = "1" ]; then log "recovery done"; else log "nothing to recover"; fi+ exit 0+fi++# The tree must import AND have studio/frontend/dist: without it `unsloth studio` exits+# and supervisord parks it FATAL. From /, so a `studio` dir in the cwd cannot answer.+studio_tree_ok() {+ (cd / && "$PY" -) <<'PY'+import os, sys+try:+ import studio.backend.main # noqa: F401+ import studio+except Exception as exc:+ print(f"[studio-update] ERROR: 'import studio.backend.main' failed: {exc}")+ sys.exit(1)+index = os.path.join(os.path.dirname(studio.__file__), "frontend", "dist", "index.html")+if not os.path.isfile(index):+ print(f"[studio-update] ERROR: no built frontend at {index}")+ sys.exit(1)+PY+}++STAGE=""+PREV_SRC=""+SWAPPED=0+INSTALLING=0+DONE=0+RESTARTED=0+ROLLBACK=""+FREEZE=""+CONSTRAINTS=""+RESTORE_FAILED=0+# Returns 1 when the previous install is not fully back; the kept record then stays+# for the next run to finish from.+restore() {+ log "restoring the previous install"+ # a restore runs to completion: a signal now would leave a half-restored install,+ # and the exit trap must not run it a second time+ trap '' INT TERM+ INSTALLING=0+ if [ "$SWAPPED" = "1" ] && [ -d "$PREV_SRC" ]; then+ rm -rf "$SRC"+ if mv -T "$PREV_SRC" "$SRC"; then+ SWAPPED=0+ else+ log "CRITICAL: could not put $PREV_SRC back at $SRC; move it there by hand"+ RESTORE_FAILED=1+ fi+ fi+ reinstall_recorded "$ROLLBACK" "$FREEZE" || RESTORE_FAILED=1+ [ "$RESTORE_FAILED" = "1" ] && return 1+ rm -f "$KEEP_ROLLBACK" "$KEEP_FREEZE"+ return 0+}+# A failed install ends here: exit 1, saying how far the restore got.+fail_after_restore() {+ if restore; then+ echo "unsloth-studio-update: $1; the previous install is back in place." >&2+ else+ echo "unsloth-studio-update: $1; the previous source tree is back but pip could not put every previous package back (see the CRITICAL lines above). Fix the cause and run this again: the next run finishes the restore first." >&2+ fi+ exit 1+}+# Kept from the moment pip can change the venv until commit_update or a finished restore.+keep_record() {+ cp -- "$ROLLBACK" "$KEEP_ROLLBACK"+ if [ -n "$FREEZE" ] && [ -s "$FREEZE" ]; then cp -- "$FREEZE" "$KEEP_FREEZE"; else rm -f "$KEEP_FREEZE"; fi+}+# Runs on every exit. An interrupt (Ctrl-C, or a TERM) after the swap started would+# otherwise leave the half-installed tree in place and the previous one beside it.+cleanup() {+ # a second signal while the cleanup itself restores must not cut it short+ trap '' INT TERM+ # a release-path pip that was interrupted can have replaced the packages half-way:+ # the recorded previous pins go back the same as after a swap+ if [ "$DONE" != "1" ] && { [ "$SWAPPED" = "1" ] || [ "$INSTALLING" = "1" ]; }; then+ log "interrupted after the install started; putting the previous install back"+ restore || log "the previous install is not fully back; the next run finishes the restore first"+ # a service this run already restarted is running the unverified code over+ # the restored files: put it on the restored install too, as back_out does+ if [ "$RESTARTED" = "1" ]; then+ if { "$SUPCTL" restart studio >/dev/null 2>&1 || "$SUPCTL" start studio >/dev/null 2>&1; } \+ && "$SUPCTL" status studio >/dev/null 2>&1; then+ log "the previous install is running again"+ else+ log "CRITICAL: the previous install is back but supervisorctl could not start it (see docker logs)"+ fi+ fi+ fi+ [ -n "$STAGE" ] && rm -rf "$STAGE"+ [ -n "$ROLLBACK" ] && rm -f "$ROLLBACK"+ [ -n "$FREEZE" ] && rm -f "$FREEZE"+ [ -n "$CONSTRAINTS" ] && rm -f "$CONSTRAINTS"+ # the lock file stays: unlinking it would let a run that opened this inode lock it+ # after we exit while a later run locks a fresh file at the same path+ return 0+}+trap cleanup EXIT+trap 'exit 130' INT+trap 'exit 143' TERM++# How each package is installed now (editable tree, commit or release), so a failed+# update can put it back exactly; a --packages target not installed yet is noted so a+# restore can take it out again.+ROLLBACK="$(mktemp)"+_names="unsloth unsloth_zoo"+for _p in $PACKAGES; do _names="$_names ${_p%%[<>=!~\[@ ]*}"; done+# shellcheck disable=SC2086+(cd / && "$PY" - "$ROLLBACK" $_names) <<'PY'+import json, sys+from importlib.metadata import distribution, PackageNotFoundError+out = []+for name in dict.fromkeys(sys.argv[2:]):+ try:+ dist = distribution(name)+ except PackageNotFoundError:+ out.append("# absent: " + name)+ continue+ raw = dist.read_text("direct_url.json")+ info = json.loads(raw) if raw else {}+ url = info.get("url", "")+ if info.get("dir_info", {}).get("editable") and url.startswith("file://"):+ # the URI as recorded: pip accepts `-e file:///path`, and a path with spaces+ # comes back percent-encoded, which as a bare path is not a valid editable+ out.append("-e " + url)+ elif "vcs_info" in info:+ out.append(f"{name} @ git+{url}@{info['vcs_info']['commit_id']}")+ elif url:+ out.append(f"{name} @ {url}")+ else:+ out.append(f"{name}=={dist.version}")+open(sys.argv[1], "w").write("\n".join(out) + "\n")+PY-echo "[studio-update] Studio venv: $PY"-echo "[studio-update] before: unsloth $(version_of)"+# --with-deps moves dependencies too, so snapshot them for the restore (editable trees+# are in ROLLBACK). The torch/CUDA stack is pinned as constraints: the image links the+# venv's nvidia libraries into the base venv, and a re-resolved torch would overwrite them.+if [ -z "$NO_DEPS" ]; then+ FREEZE="$(mktemp)"+ if ! "$PY" -m pip freeze --exclude-editable > "$FREEZE" 2>/dev/null; then+ echo "unsloth-studio-update: pip freeze failed, so a failed --with-deps update could not be rolled back; nothing was changed." >&2+ exit 1+ fi+ CONSTRAINTS="$(mktemp)"+ grep -E '^(torch|torchvision|torchaudio|triton|nvidia-|xformers|bitsandbytes)' "$FREEZE" > "$CONSTRAINTS" || true+fi+DEP_ARGS=()+if [ -z "$NO_DEPS" ] && [ -s "$CONSTRAINTS" ]; then+ DEP_ARGS=(-c "$CONSTRAINTS")+fi++# --ref installs the same shape the image was built with: an editable source tree whose+# frontend is built here with the bundled Node. A plain `pip install git+...` has no+# studio/frontend/dist (only release wheels ship one) and no oxc-validator runtime.+NPM_REGISTRY_ARGS=()+[ -n "${UNSLOTH_NPM_REGISTRY:-}" ] && NPM_REGISTRY_ARGS=(--registry "$UNSLOTH_NPM_REGISTRY")+build_source_tree() {+ local tree="$1" npm_bin="" oxc+ if [ -x "$STUDIO_HOME/node/bin/npm" ]; then+ npm_bin="$STUDIO_HOME/node/bin/npm"+ else+ # the installer uses the system Node when it is new enough and installs none of its own+ npm_bin="$(command -v npm || true)"+ fi+ [ -n "$npm_bin" ] || { log "ERROR: no npm (neither $STUDIO_HOME/node/bin/npm nor one on PATH); cannot build the frontend for --ref"; return 1; }+ # errexit is ignored inside a `( ... ) || return` list, so each step fails explicitly+ (+ export PATH="$(dirname "$npm_bin"):$PATH"+ cd "$tree/studio/frontend" || exit 1+ log "installing frontend dependencies"+ if [ -f package-lock.json ]; then+ # the lockfile is the build's contract (.npmrc: `npm ci`, never `npm install`)+ npm ci --no-fund --no-audit --loglevel=error ${NPM_REGISTRY_ARGS[@]+"${NPM_REGISTRY_ARGS[@]}"} \+ || { log "ERROR: npm ci failed (lockfile drift or the registry; UNSLOTH_NPM_REGISTRY=<url> for a mirror)"; exit 1; }+ else+ log "no package-lock.json in this ref; resolving with npm install"+ npm install --no-fund --no-audit --loglevel=error ${NPM_REGISTRY_ARGS[@]+"${NPM_REGISTRY_ARGS[@]}"} || exit 1+ fi+ log "building the frontend"+ npm run build || { log "ERROR: npm run build failed"; exit 1; }+ oxc="$tree/studio/backend/core/data_recipe/oxc-validator"+ if [ -f "$oxc/package.json" ]; then+ cd "$oxc" || exit 1+ log "installing the oxc validator runtime"+ # the same lockfile rule as the frontend+ if [ -f package-lock.json ]; then+ npm ci --no-fund --no-audit --loglevel=error ${NPM_REGISTRY_ARGS[@]+"${NPM_REGISTRY_ARGS[@]}"} \+ || { log "ERROR: npm ci failed for the oxc validator (lockfile drift or the registry)"; exit 1; }+ else+ npm install --no-fund --no-audit --loglevel=error ${NPM_REGISTRY_ARGS[@]+"${NPM_REGISTRY_ARGS[@]}"} || exit 1+ fi+ fi+ ) || return 1+ rm -rf "$tree/studio/frontend/node_modules"+ [ -f "$tree/studio/frontend/dist/index.html" ] || { log "ERROR: the frontend build produced no dist/index.html"; return 1; }+}if [ -n "$REF" ]; then- SPECS="git+https://github.com/unslothai/unsloth.git@${REF}#egg=unsloth"# unsloth-zoo does NOT track unsloth's tags_zoo_ref="$ZOO_REF"if [ -z "$_zoo_ref" ]; then@@ -71,56 +420,167 @@ if [ -n "$REF" ]; then_zoo_ref="$REF"elif [ "$_ls_rc" = "2" ]; then_zoo_ref="main"- echo "[studio-update] unsloth-zoo has no ref '${REF}'; using zoo main"+ log "unsloth-zoo has no ref '${REF}'; using zoo main"elseecho "unsloth-studio-update: could not reach unslothai/unsloth-zoo (git ls-remote exit ${_ls_rc}); refusing to guess the zoo ref." >&2echo "unsloth-studio-update: retry, or pin it yourself with --zoo-ref <ref>." >&2exit 1fifi- SPECS="$SPECS git+https://github.com/unslothai/unsloth-zoo.git@${_zoo_ref}#egg=unsloth_zoo"- echo "[studio-update] installing from git: unsloth @${REF}, unsloth-zoo @${_zoo_ref}"+ if [ ! -d "$SRC" ]; then+ echo "unsloth-studio-update: no source tree at $SRC (a wheel install has none, and a broken src link points at nothing); --ref needs the image's Studio checkout. Use a plain update instead; nothing was changed." >&2+ exit 1+ fi+ log "installing from git: unsloth @${REF}, unsloth-zoo @${_zoo_ref}"+ # a sibling of the real src, so the swap below is a same-filesystem rename+ STAGE="$(mktemp -d "$SRC_DIR/.src-update.XXXXXX")"+ if ! { git -C "$STAGE" init -q \+ && git -C "$STAGE" remote add origin https://github.com/unslothai/unsloth \+ && git -C "$STAGE" fetch -q --depth 1 origin "$REF" \+ && git -C "$STAGE" checkout -q FETCH_HEAD; }; then+ echo "unsloth-studio-update: could not fetch unsloth ref '${REF}'; nothing was changed." >&2+ exit 1+ fi+ rm -rf "$STAGE/.git"+ if ! build_source_tree "$STAGE"; then+ echo "unsloth-studio-update: the frontend for '${REF}' did not build; nothing was changed." >&2+ exit 1+ fi+ # a fresh name (mktemp) and -T: an existing directory of the same name would make mv+ # nest the tree inside it, and restore would then move that wrapper over src+ PREV_SRC="$(mktemp -d "$SRC_DIR/.src-prev.XXXXXX")" && rmdir "$PREV_SRC"+ # SWAPPED before the first move: a signal between the two moves must still restore+ keep_record+ SWAPPED=1+ mv -T "$SRC" "$PREV_SRC"+ if ! mv -T "$STAGE" "$SRC"; then+ mv -T "$PREV_SRC" "$SRC" && SWAPPED=0+ echo "unsloth-studio-update: could not move the new source tree into place; nothing was changed." >&2+ exit 1+ fi+ STAGE=""+ _spec="$SRC_INSTALL"+ # with dependencies: the backend's own requirement set is the `studio` extra+ [ -z "$NO_DEPS" ] && _spec="${SRC_INSTALL}[studio]"+ INSTALLING=1+ # shellcheck disable=SC2086+ if ! "$PY" -m pip install $NO_DEPS ${DEP_ARGS[@]+"${DEP_ARGS[@]}"} -e "$_spec" \+ "git+https://github.com/unslothai/unsloth-zoo.git@${_zoo_ref}#egg=unsloth_zoo"; then+ fail_after_restore "pip could not install '${REF}'"+ fielse- SPECS="$PACKAGES"- echo "[studio-update] installing latest release of: $PACKAGES"+ _pkgs="$PACKAGES"+ if [ -z "$NO_DEPS" ]; then+ # a release update with dependencies must bring the backend's requirement set too+ # whatever qualifies the unsloth spec (extras, a version, a marker) is kept+ _pkgs="$(printf '%s\n' $PACKAGES \+ | sed -E 's/^unsloth\[([^]]*)\]/unsloth[studio,\1]/; t; s/^unsloth([=<>!~;@ ]|$)/unsloth[studio]\1/' \+ | tr '\n' ' ')"+ fi+ log "installing latest release of: $_pkgs"+ keep_record+ INSTALLING=1+ # shellcheck disable=SC2086+ if ! "$PY" -m pip install -U $NO_DEPS ${DEP_ARGS[@]+"${DEP_ARGS[@]}"} $_pkgs; then+ fail_after_restore "pip failed"+ fifi-# shellcheck disable=SC2086-"$PY" -m pip install -U $NO_DEPS $SPECS--echo "[studio-update] after: unsloth $(version_of)"--# Restarting into code that cannot import kills a process that is serving fine and-# leaves supervisord's studio program in FATAL, which it never leaves on its own.-if ! "$PY" -c "import studio.backend.main" >/dev/null 2>&1; then- echo "[studio-update] ERROR: 'import studio.backend.main' failed after update." >&2- echo "[studio-update] A new dependency may be missing. Re-run with --with-deps:" >&2- echo "[studio-update] unsloth-studio-update --with-deps" >&2- echo "[studio-update] NOT restarting Studio, so the process already running keeps" >&2- 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] 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+log "after: unsloth $(version_of)"++# Restarting into a tree that cannot start kills a Studio that is serving fine and+# parks supervisord's program in FATAL, so check first and put the old one back.+if ! studio_tree_ok; then+ if restore && studio_tree_ok; then+ log "the update could not start Studio, so the previous install was restored and Studio was not restarted."+ else+ log "CRITICAL: the previous install could not be restored cleanly; Studio will fail to start until this is fixed."+ fi+ log "If a new dependency is missing, re-run with --with-deps."exit 1fi+# The previous tree stays until the restarted service proves it can serve. The record+# is unlinked first: a kill before that leaves a full recovery for the next run, after+# it only scratch. Signals held off, so the exit trap cannot restore over the commit.+commit_update() {+ trap '' INT TERM+ rm -f "$KEEP_ROLLBACK" "$KEEP_FREEZE"+ DONE=1+ if [ "$SWAPPED" = "1" ]; then+ # renamed before it is deleted: a kill during the delete must not leave a half+ # tree that the next run takes for the previous one and puts back+ _gone="$(mktemp -d "$SRC_DIR/.src-update.XXXXXX")" && rmdir "$_gone"+ mv -T "$PREV_SRC" "$_gone" || _gone="$PREV_SRC"+ rm -rf "$_gone"+ fi+}+# The restarted service did not come up: put the previous install back and start that,+# so the container is not left without a Studio.+back_out() {+ log "ERROR: $1; putting the previous install back"+ local _clean=1+ restore || _clean=0+ "$SUPCTL" restart studio >/dev/null 2>&1 || "$SUPCTL" start studio >/dev/null 2>&1 || true+ if "$SUPCTL" status studio; then+ log "the previous install is running again"+ else+ log "CRITICAL: the previous install is back but supervisorctl could not start it either (see docker logs)"+ fi+ if [ "$_clean" = "1" ]; then+ echo "unsloth-studio-update: $1; the previous install is back in place." >&2+ else+ echo "unsloth-studio-update: $1; the previous source tree is back but pip could not put every previous package back (see the CRITICAL lines above). Fix the cause and run this again: the next run finishes the restore first." >&2+ fi+ exit 1+}if [ "$RESTART" = "1" ]; then- SUPCTL="$(command -v supervisorctl || true)"- [ -n "$SUPCTL" ] || SUPCTL="/opt/unsloth-venv/bin/supervisorctl"- if [ -x "$SUPCTL" ] && "$SUPCTL" status studio >/dev/null 2>&1; then- echo "[studio-update] restarting the studio service"- "$SUPCTL" restart studio+ find_supctl+ if [ "$_st" = "0" ] || [ "$_st" = "3" ]; then+ # a program that is not running gets `start`: `restart` first stops it, which+ # supervisorctl reports as an error+ _cmd=restart+ [ "$_st" = "3" ] && _cmd=start+ log "${_cmd}ing the studio service"+ # from here the service may be on the new code: a signal before commit_update+ # has to move it back as well as the files (cleanup)+ RESTARTED=1+ if ! "$SUPCTL" "$_cmd" studio; then+ back_out "supervisorctl $_cmd studio failed"+ fi+ _wait="${UNSLOTH_STUDIO_UPDATE_HEALTH_WAIT:-180}"+ case "$_wait" in ''|*[!0-9]*) log "ignoring UNSLOTH_STUDIO_UPDATE_HEALTH_WAIT='${_wait}' (not a number of seconds); using 180"; _wait=180;; esac+ if [ "$_wait" -eq 0 ]; then+ # no validation asked for: the restart command succeeded, and that is all+ # this run knows+ commit_update+ log "health check skipped (UNSLOTH_STUDIO_UPDATE_HEALTH_WAIT=0); the update is committed"+ else+ _deadline=$(( $(date +%s) + _wait ))+ _up=0+ while [ "$(date +%s)" -lt "$_deadline" ]; do+ # --noproxy: a container-wide HTTP_PROXY must not answer for the loopback+ curl -sf -o /dev/null --max-time 3 --noproxy '*' http://127.0.0.1:8000/api/health && { _up=1; break; }+ sleep 2+ done+ if [ "$_up" = "1" ]; then+ commit_update+ log "Studio is answering on port 8000"+ else+ back_out "Studio did not answer on port 8000 within ${_wait}s (see docker logs)"+ fi+ fielse- echo "[studio-update] supervisor not managing 'studio' here; restart Studio yourself"- echo "[studio-update] (e.g. 'docker restart <container>')"+ # nothing here can start Studio, so the import and frontend checks above are+ # the whole validation+ commit_update+ log "supervisor not managing 'studio' here; restart Studio yourself"+ log " (e.g. 'docker restart <container>')"fielse- echo "[studio-update] --no-restart: restart Studio to load the update"- echo "[studio-update] docker exec <container> supervisorctl restart studio"+ commit_update+ log "--no-restart: restart Studio to load the update"+ log " docker exec <container> supervisorctl restart studio"fi-echo "[studio-update] done"+log "done"diff --git a/tests/python/test_docker_studio_home_volume.py b/tests/python/test_docker_studio_home_volume.pyindex bb158544067..fa5dc873287 100644--- a/tests/python/test_docker_studio_home_volume.py+++ b/tests/python/test_docker_studio_home_volume.py@@ -492,6 +492,40 @@ def test_a_src_lost_between_the_updaters_two_renames_is_put_back(tmp_path):assert "put " in res.stderr+def test_a_killed_updates_record_is_recovered_before_studio_starts(tmp_path):+ """SIGKILL after the swap and the package replacement: no trap ran, so the record+ unsloth-studio-update keeps beside src is still there at the next container start.+ The linker hands it to the updater's --recover, with the home it just linked,+ before supervisord starts Studio on the unverified tree."""+ app = _app(tmp_path)+ (app / ".src-prev.k9x2Qa").mkdir()+ (app / ".src-update.rollback").write_text("-e file:///opt/prev-src\n")+ home = tmp_path / "home"+ stub = tmp_path / "stub" / "unsloth-studio-update"+ stub.parent.mkdir()+ stub.write_text(+ '#!/usr/bin/env bash\necho "UPDATER $* home=$UNSLOTH_STUDIO_HOME" >> "$STUB_LOG"\nexit "${STUB_RC:-0}"\n'+ )+ stub.chmod(0o755)+ log = tmp_path / "calls.log"+ env = {"UNSLOTH_STUDIO_UPDATER": str(stub), "STUB_LOG": str(log)}+ res = _link(app, home, env = env)+ assert res.returncode == 0, res.stderr+ assert log.read_text() == f"UPDATER --recover home={home}\n", log.read_text()+ assert "the previous install is back" in res.stderr, res.stderr+ assert (home / "unsloth_studio").is_symlink(), "recovery must run after the home is linked"+ # a failed recovery is loud but does not stop the container from starting+ log.unlink()+ res = _link(app, home, env = {**env, "STUB_RC": "1"})+ assert res.returncode == 0, res.stderr+ assert "WARNING" in res.stderr and "--recover" in res.stderr, res.stderr+ # no record: the updater is not run at all+ (app / ".src-update.rollback").unlink()+ log.unlink()+ res = _link(app, home, env = env)+ assert res.returncode == 0 and not log.exists()++def test_two_previous_trees_are_left_for_a_human(tmp_path):app = _app(tmp_path)(app / "src").rename(app / ".src-prev.aaaaaa")diff --git a/tests/python/test_docker_update_helpers.py b/tests/python/test_docker_update_helpers.pyindex b57946b8412..794efdf3c25 100644--- a/tests/python/test_docker_update_helpers.py+++ b/tests/python/test_docker_update_helpers.py@@ -53,66 +53,441 @@ def _run()-def _studio_env(tmp_path: Path, *, import_ok: bool) -> dict:+def _studio_env(+ tmp_path: Path,+ *,+ import_ok: bool = True,+ dist_ok: bool = True,+ status_exit: int = 0,+ git_ls_exit: int = 0,+ npm_build_ok: bool = True,+ src_link: bool = False,+ restart_exit: int = 0,+) -> dict:+ """A Studio home whose venv python is the real interpreter over a fake `studio`+ package, so the script's own import and frontend checks run for real. pip,+ supervisorctl, git and the bundled npm are recording stubs."""home = tmp_path / "studio"+ site = tmp_path / "site"+ (site / "studio" / "backend").mkdir(parents = True)+ (site / "studio" / "__init__.py").write_text("")+ (site / "studio" / "backend" / "__init__.py").write_text("")+ (site / "studio" / "backend" / "main.py").write_text(+ "" if import_ok else "raise ImportError('No module named structlog')\n"+ )+ # dist-info for both packages, so importlib.metadata answers from the fake site+ # and never from whatever the runner's own interpreter has installed+ for name, ver in (("unsloth", "2026.9.4"), ("unsloth_zoo", "2026.9.3")):+ info = site / f"{name}-{ver}.dist-info"+ info.mkdir(parents = True)+ (info / "METADATA").write_text(f"Metadata-Version: 2.1\nName: {name}\nVersion: {ver}\n")+ if dist_ok:+ (site / "studio" / "frontend" / "dist").mkdir(parents = True)+ (site / "studio" / "frontend" / "dist" / "index.html").write_text("<html></html>")+ # the Studio image presents src as a link into its own copy of Studio, so the home+ # can be a volume; a standalone image has it as a real directory+ src = (tmp_path / "app" / "src") if src_link else (home / "src")+ (src / "studio").mkdir(parents = True)+ (src / "OLD_TREE").write_text("previous source tree\n")+ if src_link:+ home.mkdir(parents = True, exist_ok = True)+ (home / "src").symlink_to(src)+venv_bin = home / "unsloth_studio" / "bin"- venv_bin.mkdir(parents = True)_stub(venv_bin,"python",- 'if [ "$1" = "-c" ]; then\n'- + (- " exit 0\n"- if import_ok- else ' case "$2" in *studio.backend.main*) exit 1;; esac\n exit 0\n'- )- + "fi\n"'if [ "$1" = "-m" ] && [ "$2" = "pip" ]; then\n'- ' if [ "$3" = "show" ]; then echo "Version: 2026.7.5"; exit 0; fi\n'- ' echo "STUB-PIP $*" >> "$STUB_LOG"; exit 0\n'+ ' echo "STUB-PIP $*" >> "$STUB_LOG"\n'+ # a --with-deps run snapshots the dependency set first+ # after an install, a dependency the update pulled in shows up in the freeze+ # STUB_FREEZE_EXIT fails every freeze; STUB_FREEZE_EXIT_AFTER only the ones after an install+ ' if [ "$3" = "freeze" ]; then [ -n "${STUB_FREEZE_EXIT:-}" ] && exit "$STUB_FREEZE_EXIT"; [ -n "${STUB_FREEZE_EXIT_AFTER:-}" ] && [ -e "$STUB_LOG.installed" ] && exit "$STUB_FREEZE_EXIT_AFTER"; echo "transformers==4.0.0"; echo "torch==2.11.0+cu128"; [ -e "$STUB_LOG.installed" ] && echo "newdep==1.0"; exit 0; fi\n'+ ' case " $* " in *" -r "*) ;; *" install "*) : > "$STUB_LOG.installed" ;; esac\n'+ # the constraints file is deleted on exit, so record what it pinned+ ' _c=0; for _a in "$@"; do [ "$_c" = 1 ] && { echo "STUB-PIP-CONSTRAINTS $(tr "\\n" " " < "$_a")" >> "$STUB_LOG"; _c=0; }; [ "$_a" = "-c" ] && _c=1; done\n'+ # so is the requirements file a restore reinstalls from+ ' _r=0; for _a in "$@"; do [ "$_r" = 1 ] && { echo "STUB-PIP-REQ $(tr "\\n" " " < "$_a")" >> "$STUB_LOG"; _r=0; }; [ "$_a" = "-r" ] && _r=1; done\n'+ # an interrupted install: the updater is waiting on this child, so the signal+ # lands on it and its trap runs once we exit+ ' case " $* " in *" -e "*) [ -n "${STUB_PIP_INTERRUPT:-}" ] && kill -INT "$PPID" ;; esac\n'+ # the release path has no swap; an interrupt during its pip must restore too+ ' case " $* " in *" -U "*) [ -n "${STUB_PIP_INTERRUPT_RELEASE:-}" ] && kill -INT "$PPID" ;; esac\n'+ # a signal that lands while the restore itself runs must not cut the cleanup short+ ' case " $* " in *" -r "*) [ -n "${STUB_PIP_INTERRUPT_RESTORE:-}" ] && kill -TERM "$PPID" ;; esac\n'+ # reinstalling the recorded previous install brings the working tree back+ ' case " $* " in *" -r "*)\n'+ f' : > "{site}/studio/backend/main.py"\n'+ f' mkdir -p "{site}/studio/frontend/dist"; echo ok > "{site}/studio/frontend/dist/index.html" ;;\n'+ " esac\n"+ # STUB_PIP_INSTALL_EXIT fails the update's own install and lets the restore's -r+ # installs through; STUB_PIP_EXIT fails every pip call, the restore included+ ' case " $* " in *" -r "*) ;; *) [ -n "${STUB_PIP_INSTALL_EXIT:-}" ] && exit "$STUB_PIP_INSTALL_EXIT" ;; esac\n'+ ' exit "${STUB_PIP_EXIT:-0}"\n'"fi\n"- "exit 0\n",+ f'PYTHONPATH="{site}" exec "{shutil.which("python3")}" "$@"\n',+ )+ _stub(+ home / "node" / "bin",+ "npm",+ 'echo "STUB-NPM $* in $PWD" >> "$STUB_LOG"\n'+ 'if [ "$1" = "ci" ]; then exit "${STUB_NPM_CI_EXIT:-0}"; fi\n'+ 'if [ "$*" = "run build" ]; then\n'+ + (+ " mkdir -p dist && echo '<html></html>' > dist/index.html; exit 0\n"+ if npm_build_ok+ else " exit 1\n"+ )+ + "fi\nexit 0\n",)bin_dir = tmp_path / "bin"_stub(bin_dir,"supervisorctl",'echo "STUB-SUPERVISORCTL $*" >> "$STUB_LOG"\n'- 'if [ "$1" = "status" ]; then exit 0; fi\nexit 0\n',+ # a program that was started reports RUNNING from then on+ f'if [ "$1" = "status" ]; then [ -e "$STUB_LOG.started" ] && exit 0; exit {status_exit}; fi\n'+ f'if [ "$1" = "restart" ] || [ "$1" = "start" ]; then [ {restart_exit} = 0 ] && : > "$STUB_LOG.started"; exit {restart_exit}; fi\nexit 0\n',+ )+ _stub(+ bin_dir,+ "git",+ 'dir=""; if [ "$1" = "-C" ]; then dir="$2"; shift 2; fi\n'+ 'case "$1" in\n'+ f" ls-remote) exit {git_ls_exit} ;;\n"+ ' checkout) mkdir -p "$dir/studio/frontend/src" "$dir/.git"'+ ' "$dir/studio/backend/core/data_recipe/oxc-validator";'+ ' echo "{}" > "$dir/studio/frontend/package.json";'+ ' [ -n "${STUB_LOCKFILE:-}" ] && echo "{}" > "$dir/studio/frontend/package-lock.json";'+ ' echo "{}" > "$dir/studio/backend/core/data_recipe/oxc-validator/package.json";'+ ' [ -n "${STUB_OXC_LOCKFILE:-}" ] && echo "{}" > "$dir/studio/backend/core/data_recipe/oxc-validator/package-lock.json";'+ ' echo new > "$dir/NEW_TREE" ;;\n'+ "esac\nexit 0\n",)env = dict(os.environ)env["PATH"] = f"{bin_dir}{os.pathsep}" + env["PATH"]env["UNSLOTH_STUDIO_HOME"] = str(home)+ env["UNSLOTH_STUDIO_UPDATE_HEALTH_WAIT"] = "0"env["STUB_LOG"] = str(tmp_path / "calls.log")return env+def _scratch(d: Path, pattern: str = ".src-*") -> list:+ """The updater's scratch entries, minus the lock file it keeps on purpose."""+ return [p for p in d.glob(pattern) if p.name != ".src-update.lock"]+++def _calls(env) -> str:+ log = Path(env["STUB_LOG"])+ return log.read_text() if log.exists() else ""++def test_studio_update_restarts_when_the_backend_imports(tmp_path: Path):- env = _studio_env(tmp_path, import_ok = True)+ env = _studio_env(tmp_path)res = _run(STUDIO_UPDATE, [], env)- calls = Path(env["STUB_LOG"]).read_text() if Path(env["STUB_LOG"]).exists() else ""- assert res.returncode == 0, res.stderr- assert "STUB-SUPERVISORCTL restart studio" in calls, calls+ assert res.returncode == 0, res.stderr + res.stdout+ assert "STUB-SUPERVISORCTL restart studio" in _calls(env), _calls(env)def test_studio_update_does_not_restart_into_a_backend_that_cannot_import(tmp_path: Path):env = _studio_env(tmp_path, import_ok = False)res = _run(STUDIO_UPDATE, [], env)- calls = Path(env["STUB_LOG"]).read_text() if Path(env["STUB_LOG"]).exists() else ""+ calls = _calls(env)assert "STUB-SUPERVISORCTL restart studio" not in calls, ("restarting into code that cannot import kills a process that is serving ""fine and parks supervisord's studio program in FATAL:\n" + calls)assert res.returncode != 0, "a broken update must not report success"- assert "--with-deps" in res.stderr, "the remedy must still be printed"+ assert "--with-deps" in res.stdout, "the remedy must still be printed"+ # --force-reinstall: pip takes a same-version editable as already satisfying the+ # pin and would leave the new tree's metadata in place+ assert "install --no-deps --force-reinstall -r" in calls, (+ "the previous install must be put back:\n" + calls+ )-def _zoo_ref_env(tmp_path: Path, *, git_exit: int) -> dict:- """`--ref` env whose stub `git ls-remote` exits with `git_exit`. git's codes:- 0 = has the ref, 2 = reached the remote with no match, 128 = never reached it."""- env = _studio_env(tmp_path, import_ok = True)- _stub(tmp_path / "bin", "git", f"exit {git_exit}\n")- return env+def test_studio_update_does_not_restart_into_a_tree_without_a_built_frontend(tmp_path: Path):+ """The --ref failure: a git build has no studio/frontend/dist, `unsloth studio`+ exits 1 on start, and three quick exits leave supervisord's program FATAL."""+ env = _studio_env(tmp_path, dist_ok = False)+ res = _run(STUDIO_UPDATE, [], env)+ calls = _calls(env)+ assert res.returncode != 0+ assert "no built frontend" in res.stdout+ assert "STUB-SUPERVISORCTL restart studio" not in calls, calls+ assert "install --no-deps --force-reinstall -r" in calls, calls++[email protected]("status_exit, verb", [(0, "restart"), (3, "start")])+def test_studio_update_restarts_a_studio_that_is_not_running(tmp_path: Path, status_exit, verb):+ """`supervisorctl status` exits 3 for STOPPED/EXITED/FATAL. That is still a program+ supervisord manages, and FATAL is what a failed earlier update left behind. It gets+ `start`: `restart` stops it first, which supervisorctl reports as an error."""+ env = _studio_env(tmp_path, status_exit = status_exit)+ res = _run(STUDIO_UPDATE, [], env)+ assert res.returncode == 0, res.stderr + res.stdout+ assert f"STUB-SUPERVISORCTL {verb} studio" in _calls(env), _calls(env)+ assert "not managing" not in res.stdout+++def test_studio_update_fails_when_supervisor_cannot_restart_studio(tmp_path: Path):+ """A restart that fails used to leave the new install in place with Studio down and+ the previous tree already deleted. The previous tree is kept until the service is+ up, so a failed restart puts it back and starts that."""+ env = _studio_env(tmp_path, restart_exit = 1)+ res = _run(STUDIO_UPDATE, ["--ref", "main"], env)+ home = Path(env["UNSLOTH_STUDIO_HOME"])+ calls = _calls(env)+ assert res.returncode != 0, res.stdout+ assert "ERROR: supervisorctl restart studio failed" in res.stdout, res.stdout+ assert "previous install is back in place" in res.stderr, res.stderr+ assert (home / "src" / "OLD_TREE").exists(), "the previous source tree was not put back"+ assert not (home / "src" / "NEW_TREE").exists()+ assert not _scratch(home)+ assert "install --no-deps --force-reinstall -r" in calls, calls+ sup = [l for l in calls.splitlines() if l.startswith("STUB-SUPERVISORCTL")]+ assert sup[-1] == "STUB-SUPERVISORCTL status studio", calls+ assert "STUB-SUPERVISORCTL restart studio" in sup[1:], (+ "the previous install must be started again:\n" + calls+ )+ # the release path has no tree to swap, but its pins go back the same way+ env = _studio_env(tmp_path / "release", restart_exit = 1)+ res = _run(STUDIO_UPDATE, [], env)+ assert res.returncode != 0, res.stdout+ assert "install --no-deps --force-reinstall -r" in _calls(env), _calls(env)+++def test_studio_update_refuses_to_run_beside_another_updater(tmp_path: Path):+ """Two updaters at once would take each other's staging and previous trees for+ leftovers and swap over each other's src."""+ fcntl = pytest.importorskip("fcntl")+ env = _studio_env(tmp_path)+ home = Path(env["UNSLOTH_STUDIO_HOME"])+ lock = home / ".src-update.lock"+ fd = os.open(lock, os.O_WRONLY | os.O_CREAT)+ fcntl.flock(fd, fcntl.LOCK_EX)+ try:+ res = _run(STUDIO_UPDATE, ["--ref", "main"], env)+ assert res.returncode == 1, res.stderr + res.stdout+ assert "another unsloth-studio-update is running" in res.stderr, res.stderr+ assert "STUB-PIP" not in _calls(env) and "STUB-NPM" not in _calls(env), _calls(env)+ assert (home / "src" / "OLD_TREE").exists()+ finally:+ fcntl.flock(fd, fcntl.LOCK_UN)+ os.close(fd)+ res = _run(STUDIO_UPDATE, ["--ref", "main"], env)+ assert res.returncode == 0, res.stderr + res.stdout+ assert (home / "src" / "NEW_TREE").exists()+ # the lock file shares the scratch prefix so the home linker never links it, and+ # the startup sweep must not take it for a leftover+ assert "left behind" not in res.stdout, res.stdout+ assert not _scratch(home), "the lock file must not outlive the run"+++def test_studio_update_reports_an_unmanaged_studio(tmp_path: Path):+ env = _studio_env(tmp_path, status_exit = 4)+ res = _run(STUDIO_UPDATE, [], env)+ assert res.returncode == 0, res.stderr + res.stdout+ assert "STUB-SUPERVISORCTL restart studio" not in _calls(env)+ assert "not managing 'studio'" in res.stdout+++def test_studio_update_ref_builds_the_frontend_and_swaps_the_source_tree(tmp_path: Path):+ env = _studio_env(tmp_path)+ res = _run(STUDIO_UPDATE, ["--ref", "main", "--no-restart"], env)+ calls = _calls(env)+ home = Path(env["UNSLOTH_STUDIO_HOME"])+ assert res.returncode == 0, res.stderr + res.stdout+ assert "STUB-NPM run build" in calls, calls+ assert (home / "src" / "NEW_TREE").exists(), "src was not replaced by the fetched ref"+ assert (home / "src" / "studio" / "frontend" / "dist" / "index.html").exists()+ assert not (home / "src" / ".git").exists()+ assert not _scratch(home, ".src-prev.*"), "the previous tree was not cleaned up"+ assert not _scratch(home, ".src-update.*"), "the staging tree was not cleaned up"+ assert f"install --no-deps -e {home / 'src'}" in calls, calls+++def test_studio_update_ref_writes_through_a_linked_source_tree(tmp_path: Path):+ """Replacing that link with a directory would put the tree outside the image's copy,+ where the next container start relinks over it and the update is silently gone."""+ env = _studio_env(tmp_path, src_link = True)+ res = _run(STUDIO_UPDATE, ["--ref", "main", "--no-restart"], env)+ home = Path(env["UNSLOTH_STUDIO_HOME"])+ real_src = tmp_path / "app" / "src"+ assert res.returncode == 0, res.stderr + res.stdout+ assert (home / "src").is_symlink(), "the link was replaced by a directory"+ assert (real_src / "NEW_TREE").exists(), "the ref was not installed where the code lives"+ assert not _scratch(home), "staging trees must not land in the data volume"+ assert not _scratch(real_src.parent, ".src-prev.*")+ # pip records the home path, so the install keeps resolving through the link and+ # `unsloth-studio-home --restore` (back to a pre-split image) still finds it+ assert f"install --no-deps -e {home / 'src'}" in _calls(env), _calls(env)+++def test_studio_update_ref_with_a_failed_frontend_build_changes_nothing(tmp_path: Path):+ env = _studio_env(tmp_path, npm_build_ok = False)+ res = _run(STUDIO_UPDATE, ["--ref", "main", "--no-restart"], env)+ home = Path(env["UNSLOTH_STUDIO_HOME"])+ calls = _calls(env)+ assert res.returncode != 0+ assert (home / "src" / "OLD_TREE").exists(), "the running source tree was touched"+ assert "STUB-PIP" not in calls, calls+ assert not _scratch(home, ".src-update.*")+ # errexit is off inside `( ... ) || return`, so the build step has to stop by itself+ assert "npm run build failed" in res.stdout, res.stdout+ assert "oxc-validator" not in calls, (+ "a failed build must not go on to the oxc install:\n" + calls+ )+++def test_studio_update_ref_installs_the_oxc_runtime_after_a_good_build(tmp_path: Path):+ env = _studio_env(tmp_path)+ res = _run(STUDIO_UPDATE, ["--ref", "main", "--no-restart"], env)+ assert res.returncode == 0, res.stderr + res.stdout+ oxc = [+ l+ for l in _calls(env).splitlines()+ if "STUB-NPM install" in l and l.endswith("oxc-validator")+ ]+ assert oxc, _calls(env)+ # the same lockfile rule as the frontend: a ref that ships one is installed from it+ env = _studio_env(tmp_path / "locked")+ env["STUB_OXC_LOCKFILE"] = "1"+ env["UNSLOTH_NPM_REGISTRY"] = "https://mirror.example/npm/"+ res = _run(STUDIO_UPDATE, ["--ref", "main", "--no-restart"], env)+ assert res.returncode == 0, res.stderr + res.stdout+ oxc = [l for l in _calls(env).splitlines() if "STUB-NPM" in l and l.endswith("oxc-validator")]+ assert len(oxc) == 1 and oxc[0].startswith("STUB-NPM ci "), _calls(env)+ assert "--registry https://mirror.example/npm/" in oxc[0], oxc[0]+ env = _studio_env(tmp_path / "drift")+ env["STUB_OXC_LOCKFILE"] = "1"+ env["STUB_NPM_CI_EXIT"] = "1"+ res = _run(STUDIO_UPDATE, ["--ref", "main", "--no-restart"], env)+ assert res.returncode != 0+ assert "npm ci failed for the oxc validator" in res.stdout, res.stdout+ assert not [+ l+ for l in _calls(env).splitlines()+ if "STUB-NPM install" in l and l.endswith("oxc-validator")+ ], "lockfile drift must not be re-resolved:\n" + _calls(env)+ assert (Path(env["UNSLOTH_STUDIO_HOME"]) / "src" / "OLD_TREE").exists()+++def test_studio_update_rollback_keeps_the_editable_uri_pip_recorded(tmp_path: Path):+ """direct_url.json holds a file:// URI; a path with a space comes back percent+ encoded, and pip rejects that as a bare path but takes it as the URI."""+ env = _studio_env(tmp_path, import_ok = False)+ site = tmp_path / "site"+ info = site / "unsloth-2026.9.4.dist-info" # seeded by _studio_env+ (info / "direct_url.json").write_text(+ '{"url": "file:///opt/my%20studio/src", "dir_info": {"editable": true}}'+ )+ res = _run(STUDIO_UPDATE, ["--no-restart"], env)+ assert res.returncode != 0+ assert "STUB-PIP-REQ -e file:///opt/my%20studio/src" in _calls(env), _calls(env)+++def test_studio_update_ref_restores_the_tree_when_interrupted_after_the_swap(tmp_path: Path):+ """Ctrl-C or `docker stop` between the swap and the checks left the half-installed+ tree in place and the previous one beside it as .src-prev.*, which the next+ container start links into the Studio home."""+ env = _studio_env(tmp_path)+ env["STUB_PIP_INTERRUPT"] = "1"+ res = _run(STUDIO_UPDATE, ["--ref", "main", "--no-restart"], env)+ home = Path(env["UNSLOTH_STUDIO_HOME"])+ assert res.returncode == 130, res.stderr + res.stdout+ assert (home / "src" / "OLD_TREE").exists(), "the previous source tree was not put back"+ assert not (home / "src" / "NEW_TREE").exists()+ assert not _scratch(home, ".src-prev.*"), "the previous tree was left beside src"+ assert not _scratch(home, ".src-update.*")+ assert "interrupted" in res.stdout, res.stdout+++def test_studio_update_release_restores_the_pins_when_interrupted_during_pip(tmp_path: Path):+ """The release path swaps nothing, but a pip interrupted half-way can have replaced+ the packages already; the recorded previous install goes back the same way."""+ env = _studio_env(tmp_path)+ env["STUB_PIP_INTERRUPT_RELEASE"] = "1"+ res = _run(STUDIO_UPDATE, ["--no-restart"], env)+ calls = _calls(env)+ assert res.returncode == 130, res.stderr + res.stdout+ assert "install --no-deps --force-reinstall -r" in calls, (+ "the previous install was not put back:\n" + calls+ )+ assert "interrupted" in res.stdout, res.stdout+++def test_studio_update_restores_once_and_leaves_no_temp_files_when_signalled_mid_restore(+ tmp_path: Path,+):+ """After a failed tree check the script restores explicitly, then exits; the exit+ trap must not restore a second time, and a signal during the restore must not skip+ the temp-file cleanup."""+ env = _studio_env(tmp_path, dist_ok = False)+ env["STUB_PIP_INTERRUPT_RESTORE"] = "1"+ tmpd = tmp_path / "tmpd"+ tmpd.mkdir()+ env["TMPDIR"] = str(tmpd)+ res = _run(STUDIO_UPDATE, ["--no-restart"], env)+ calls = _calls(env)+ assert res.returncode != 0+ assert calls.count("--force-reinstall -r") == 1, "restore ran more than once:\n" + calls+ assert not list(tmpd.iterdir()), "temp files left behind: " + str(list(tmpd.iterdir()))+++def test_studio_update_ref_refuses_a_venv_without_a_source_tree(tmp_path: Path):+ """A wheel-only install has no src; `mv` of a missing tree must not be the error."""+ env = _studio_env(tmp_path)+ home = Path(env["UNSLOTH_STUDIO_HOME"])+ shutil.rmtree(home / "src")+ res = _run(STUDIO_UPDATE, ["--ref", "main", "--no-restart"], env)+ assert res.returncode != 0+ assert "no source tree" in res.stderr, res.stderr+ assert "STUB-NPM" not in _calls(+ env+ ), "nothing should be built for a tree that cannot be swapped"+++def test_studio_update_with_deps_puts_the_dependency_set_back(tmp_path: Path):+ """--with-deps lets pip move every dependency; restoring unsloth alone would leave+ the new dependency set under the old code."""+ env = _studio_env(tmp_path, import_ok = False)+ res = _run(STUDIO_UPDATE, ["--with-deps"], env)+ calls = _calls(env)+ assert res.returncode != 0+ assert "STUB-PIP -m pip freeze --exclude-editable" in calls, calls+ # the dependency snapshot goes back as pinned, the package identity by force+ assert calls.count("install --no-deps -r") == 1, "dependency snapshot:\n" + calls+ assert calls.count("install --no-deps --force-reinstall -r") == 1, "previous install:\n" + calls+ # the backend's requirement set is the `studio` extra, and torch/CUDA must not be+ # re-resolved (the venv's nvidia libs are linked into the base venv)+ assert "unsloth[studio]" in calls, calls+ assert "STUB-PIP-CONSTRAINTS torch==2.11.0+cu128" in calls, calls+ assert "transformers==4.0.0" not in [+ l for l in calls.splitlines() if l.startswith("STUB-PIP-CONSTRAINTS")+ ], "only the torch/CUDA stack is a constraint"+ env = _studio_env(tmp_path / "nodeps", import_ok = False)+ res = _run(STUDIO_UPDATE, [], env)+ assert "freeze" not in _calls(env), "a --no-deps update has nothing to snapshot"+ assert " -c " not in _calls(env)+++def test_studio_update_ref_with_deps_installs_the_studio_extra(tmp_path: Path):+ env = _studio_env(tmp_path)+ res = _run(STUDIO_UPDATE, ["--ref", "main", "--with-deps", "--no-restart"], env)+ home = Path(env["UNSLOTH_STUDIO_HOME"])+ assert res.returncode == 0, res.stderr + res.stdout+ assert f"-e {home / 'src'}[studio]" in _calls(env), _calls(env)+ assert "STUB-PIP-CONSTRAINTS torch==2.11.0+cu128" in _calls(env), _calls(env)+++def test_studio_update_ref_puts_the_old_tree_back_when_the_new_one_cannot_start(tmp_path: Path):+ env = _studio_env(tmp_path, import_ok = False)+ res = _run(STUDIO_UPDATE, ["--ref", "main", "--no-restart"], env)+ home = Path(env["UNSLOTH_STUDIO_HOME"])+ assert res.returncode != 0+ assert (home / "src" / "OLD_TREE").exists(), "the previous source tree was not restored"+ assert not (home / "src" / "NEW_TREE").exists()def _zoo_spec(calls: str) -> str:@@ -124,28 +499,26 @@ def _zoo_spec(calls: str) -> str:def test_studio_update_mirrors_the_ref_when_the_zoo_has_it(tmp_path: Path):- env = _zoo_ref_env(tmp_path, git_exit = 0)+ env = _studio_env(tmp_path, git_ls_exit = 0)res = _run(STUDIO_UPDATE, ["--ref", "v2026.7.5", "--no-restart"], env)- calls = Path(env["STUB_LOG"]).read_text() if Path(env["STUB_LOG"]).exists() else ""- assert res.returncode == 0, res.stderr- assert _zoo_spec(calls).endswith("@v2026.7.5#egg=unsloth_zoo"), calls+ assert res.returncode == 0, res.stderr + res.stdout+ assert _zoo_spec(_calls(env)).endswith("@v2026.7.5#egg=unsloth_zoo"), _calls(env)def test_studio_update_falls_back_to_zoo_main_when_the_ref_is_absent(tmp_path: Path):- env = _zoo_ref_env(tmp_path, git_exit = 2)+ env = _studio_env(tmp_path, git_ls_exit = 2)res = _run(STUDIO_UPDATE, ["--ref", "v2026.7.5", "--no-restart"], env)- calls = Path(env["STUB_LOG"]).read_text() if Path(env["STUB_LOG"]).exists() else ""- assert res.returncode == 0, res.stderr- assert _zoo_spec(calls).endswith("@main#egg=unsloth_zoo"), calls+ assert res.returncode == 0, res.stderr + res.stdout+ assert _zoo_spec(_calls(env)).endswith("@main#egg=unsloth_zoo"), _calls(env)assert "has no ref" in res.stdout, res.stdoutdef test_studio_update_aborts_when_the_zoo_lookup_never_reached_the_remote(tmp_path: Path):# treating 2 and 128 alike pairs the requested unsloth revision with an unrelated# zoo one once the network recovers, across a private API- env = _zoo_ref_env(tmp_path, git_exit = 128)+ env = _studio_env(tmp_path, git_ls_exit = 128)res = _run(STUDIO_UPDATE, ["--ref", "v2026.7.5", "--no-restart"], env)- calls = Path(env["STUB_LOG"]).read_text() if Path(env["STUB_LOG"]).exists() else ""+ calls = _calls(env)assert "STUB-PIP" not in calls, "a transport failure must not install anything:\n" + callsassert res.returncode != 0, "an unresolvable zoo ref must not report success"assert "has no ref" not in res.stdout, (@@ -154,6 +527,411 @@ def test_studio_update_aborts_when_the_zoo_lookup_never_reached_the_remote(tmp_passert "--zoo-ref" in res.stderr, "the remedy must be printed"+def test_studio_update_puts_the_install_back_when_pip_itself_fails(tmp_path: Path):+ env = _studio_env(tmp_path)+ env["STUB_PIP_INSTALL_EXIT"] = "1"+ res = _run(STUDIO_UPDATE, ["--ref", "main", "--no-restart"], env)+ home = Path(env["UNSLOTH_STUDIO_HOME"])+ assert res.returncode != 0+ assert "previous install is back in place" in res.stderr, res.stderr+ assert (home / "src" / "OLD_TREE").exists(), "the previous source tree was not put back"+ assert not _scratch(home)+ assert "STUB-SUPERVISORCTL" not in _calls(env)+++def test_a_signal_during_the_health_wait_puts_the_service_back_too(tmp_path: Path):+ """Ctrl-C while waiting for /api/health: the service is already running the new+ code, so restoring the files alone would leave it serving a mix of versions.+ The cleanup restarts it on the restored install, as back_out does."""+ env = _studio_env(tmp_path)+ env["UNSLOTH_STUDIO_UPDATE_HEALTH_WAIT"] = "30"+ _stub(+ tmp_path / "bin",+ "curl",+ 'echo "STUB-CURL $*" >> "$STUB_LOG"\nkill -TERM "$PPID"\nexit 22\n',+ )+ res = _run(STUDIO_UPDATE, ["--ref", "main"], env)+ home = Path(env["UNSLOTH_STUDIO_HOME"])+ calls = _calls(env).splitlines()+ assert res.returncode == 143, res.stdout + res.stderr+ assert "interrupted after the install started" in res.stdout, res.stdout+ assert (home / "src" / "OLD_TREE").exists() and not (home / "src" / "NEW_TREE").exists()+ reinst = [i for i, l in enumerate(calls) if "install --no-deps --force-reinstall -r" in l]+ assert reinst, calls+ after = calls[reinst[-1] + 1 :]+ assert "STUB-SUPERVISORCTL restart studio" in after, calls+ assert "the previous install is running again" in res.stdout, res.stdout+ assert not _scratch(home)+++def test_studio_update_fails_when_studio_does_not_answer_after_the_restart(tmp_path: Path):+ """A backend that imports can still die at startup; the previous tree is kept+ until /api/health answers, and goes back when it does not."""+ env = _studio_env(tmp_path)+ env["UNSLOTH_STUDIO_UPDATE_HEALTH_WAIT"] = "1"+ _stub(tmp_path / "bin", "curl", 'echo "STUB-CURL $*" >> "$STUB_LOG"\nexit 22\n')+ res = _run(STUDIO_UPDATE, ["--ref", "main"], env)+ home = Path(env["UNSLOTH_STUDIO_HOME"])+ calls = _calls(env)+ assert res.returncode != 0, res.stdout+ assert "did not answer on port 8000" in res.stdout, res.stdout+ assert "STUB-CURL" in calls+ # a container-wide HTTP_PROXY must not answer for the loopback probe+ assert "--noproxy * http://127.0.0.1:8000/api/health" in calls, calls+ assert "previous install is back in place" in res.stderr, res.stderr+ assert (home / "src" / "OLD_TREE").exists(), "the previous source tree was not put back"+ assert not (home / "src" / "NEW_TREE").exists()+ assert not _scratch(home)+ assert "install --no-deps --force-reinstall -r" in calls, calls+ assert calls.splitlines()[-1] == "STUB-SUPERVISORCTL status studio", calls+ env = _studio_env(tmp_path / "ok")+ env["UNSLOTH_STUDIO_UPDATE_HEALTH_WAIT"] = "5"+ _stub(tmp_path / "ok" / "bin", "curl", "exit 0\n")+ res = _run(STUDIO_UPDATE, ["--ref", "main"], env)+ home = Path(env["UNSLOTH_STUDIO_HOME"])+ assert res.returncode == 0, res.stdout+ assert "answering on port 8000" in res.stdout+ assert (home / "src" / "NEW_TREE").exists()+ assert not _scratch(home), "the previous tree must go once Studio is up"+ env = _studio_env(tmp_path / "junk")+ env["UNSLOTH_STUDIO_UPDATE_HEALTH_WAIT"] = "soon"+ _stub(tmp_path / "junk" / "bin", "curl", "exit 0\n")+ res = _run(STUDIO_UPDATE, [], env)+ assert res.returncode == 0, res.stdout+ assert "not a number" in res.stdout+++def test_studio_update_health_wait_zero_commits_once_the_restart_command_succeeds(tmp_path: Path):+ """0 asks for no validation: the previous tree goes as soon as the restart command+ returns, and nothing is fetched from port 8000."""+ env = _studio_env(tmp_path)+ env["UNSLOTH_STUDIO_UPDATE_HEALTH_WAIT"] = "0"+ _stub(tmp_path / "bin", "curl", 'echo "STUB-CURL $*" >> "$STUB_LOG"\nexit 22\n')+ res = _run(STUDIO_UPDATE, ["--ref", "main"], env)+ home = Path(env["UNSLOTH_STUDIO_HOME"])+ assert res.returncode == 0, res.stderr + res.stdout+ assert "the update is committed" in res.stdout, res.stdout+ assert "STUB-CURL" not in _calls(env)+ assert (home / "src" / "NEW_TREE").exists()+ assert not _scratch(home)+ # with a restart that fails there is still nothing to commit+ env = _studio_env(tmp_path / "down", restart_exit = 1)+ res = _run(STUDIO_UPDATE, ["--ref", "main"], env)+ home = Path(env["UNSLOTH_STUDIO_HOME"])+ assert res.returncode != 0+ assert (home / "src" / "OLD_TREE").exists()+++def test_studio_update_clears_leftovers_of_a_killed_run_before_it_starts(tmp_path: Path):+ """`docker stop` ends in SIGKILL, so no trap ran: a previous tree can sit beside src+ with a pid-derived name that a later run could reuse (mv would nest into it) and a+ staging tree can sit there with its node_modules."""+ env = _studio_env(tmp_path)+ home = Path(env["UNSLOTH_STUDIO_HOME"])+ (home / ".src-prev.4242" / "junk").mkdir(parents = True)+ (home / ".src-update.abc123" / "node_modules").mkdir(parents = True)+ res = _run(STUDIO_UPDATE, ["--ref", "main", "--no-restart"], env)+ assert res.returncode == 0, res.stderr + res.stdout+ assert "left behind by an earlier update" in res.stdout, res.stdout+ assert (home / "src" / "NEW_TREE").exists()+ assert not (home / "src" / "junk").exists(), "the tree was nested into the stale dir"+ assert not _scratch(home)+++def test_studio_update_recovers_a_source_tree_a_killed_run_moved_aside(tmp_path: Path):+ """SIGKILL between the two moves of the swap leaves no src at all, only .src-prev.*.+ A later plain update must put it back rather than fail on a missing tree."""+ env = _studio_env(tmp_path)+ home = Path(env["UNSLOTH_STUDIO_HOME"])+ (home / "src").rename(home / ".src-prev.abc123")+ res = _run(STUDIO_UPDATE, [], env)+ assert res.returncode == 0, res.stderr + res.stdout+ assert "recovering the source tree" in res.stdout, res.stdout+ assert (home / "src" / "OLD_TREE").exists()+ assert not _scratch(home, ".src-prev.*")+++def test_studio_update_puts_back_a_previous_tree_a_killed_run_never_committed(tmp_path: Path):+ """SIGKILL after the swap but before the health check committed it leaves the new+ tree in src and the previous one beside it. The new tree was never proven to serve,+ so the previous one goes back; treating it as stale would delete the only known-good+ tree."""+ env = _studio_env(tmp_path)+ home = Path(env["UNSLOTH_STUDIO_HOME"])+ (home / "src").rename(home / ".src-prev.abc123")+ (home / "src" / "studio").mkdir(parents = True)+ (home / "src" / "UNVERIFIED").write_text("never passed the health check\n")+ (home / ".src-update.rollback").write_text("-e file:///opt/prev-src\n")+ res = _run(STUDIO_UPDATE, [], env)+ assert res.returncode == 0, res.stderr + res.stdout+ assert "putting it back over the unverified one" in res.stdout, res.stdout+ assert (home / "src" / "OLD_TREE").exists()+ assert not (home / "src" / "UNVERIFIED").exists()+ assert not _scratch(home), "the unverified tree was left behind"+++def test_studio_update_reads_the_install_record_from_the_venv_not_the_cwd(tmp_path: Path):+ """`python -` searches the caller's cwd first, so a checkout there with its own+ dist-info would answer for the venv's installed unsloth and a rollback would+ reinstall the wrong thing."""+ env = _studio_env(tmp_path, import_ok = False)+ site = tmp_path / "site"+ info = site / "unsloth-2026.9.4.dist-info" # seeded by _studio_env+ (info / "direct_url.json").write_text(+ '{"url": "file:///opt/venv-src", "dir_info": {"editable": true}}'+ )+ checkout = tmp_path / "checkout"+ decoy = checkout / "unsloth-0.0.1.dist-info"+ decoy.mkdir(parents = True)+ (decoy / "METADATA").write_text("Metadata-Version: 2.1\nName: unsloth\nVersion: 0.0.1\n")+ (decoy / "direct_url.json").write_text(+ '{"url": "file:///checkout", "dir_info": {"editable": true}}'+ )+ res = _run(STUDIO_UPDATE, ["--no-restart"], env, cwd = checkout)+ assert res.returncode != 0+ assert "STUB-PIP-REQ -e file:///opt/venv-src" in _calls(env), _calls(env)+ assert "checkout" not in _calls(env), _calls(env)+ assert "before: unsloth 2026.9.4" in res.stdout, res.stdout+++def test_studio_update_records_every_packages_target_for_the_rollback(tmp_path: Path):+ """--packages can name more than unsloth and unsloth_zoo; a restore that put only+ those two back would leave the extra target upgraded, or newly installed, while+ reporting the previous install is back."""+ env = _studio_env(tmp_path, import_ok = False)+ site = tmp_path / "site"+ info = site / "bar-1.0.dist-info"+ info.mkdir()+ (info / "METADATA").write_text("Metadata-Version: 2.1\nName: bar\nVersion: 1.0\n")+ res = _run(+ STUDIO_UPDATE, ["--no-restart", "--packages", "unsloth unsloth_zoo bar>=2 foo==2"], env+ )+ calls = _calls(env)+ assert res.returncode != 0+ req = [l for l in calls.splitlines() if l.startswith("STUB-PIP-REQ")][0]+ assert "bar==1.0" in req, req+ assert "# absent: foo" in req, req+ assert "STUB-PIP -m pip uninstall -y foo" in calls, calls+ assert "uninstall -y bar" not in calls+++def test_studio_update_with_deps_stops_when_the_dependency_snapshot_fails(tmp_path: Path):+ """An empty snapshot would let the install run with nothing to pin back."""+ env = _studio_env(tmp_path, import_ok = False)+ env["STUB_FREEZE_EXIT"] = "1"+ res = _run(STUDIO_UPDATE, ["--with-deps"], env)+ assert res.returncode != 0+ assert "pip freeze failed" in res.stderr and "nothing was changed" in res.stderr, res.stderr+ assert "install" not in _calls(env), _calls(env)+++def test_studio_update_finishes_the_package_restore_a_killed_run_left(tmp_path: Path):+ """SIGKILL after pip had replaced the packages but before the commit: the record+ kept beside the tree says what to put back, and the next run does that before it+ records anything as the previous install."""+ env = _studio_env(tmp_path)+ home = Path(env["UNSLOTH_STUDIO_HOME"])+ (home / ".src-update.rollback").write_text("-e file:///opt/prev-src\n# absent: foo\n")+ (home / ".src-update.freeze").write_text("transformers==3.9.0\n")+ res = _run(STUDIO_UPDATE, [], env)+ calls = _calls(env)+ assert res.returncode == 0, res.stderr + res.stdout+ assert "putting the previous packages back first" in res.stdout, res.stdout+ reqs = [l for l in calls.splitlines() if l.startswith("STUB-PIP-REQ")]+ assert reqs[0] == "STUB-PIP-REQ transformers==3.9.0 ", reqs+ assert "-e file:///opt/prev-src" in reqs[1], reqs+ assert "STUB-PIP -m pip uninstall -y foo" in calls, calls+ assert not _scratch(home, ".src-update.*")++[email protected]("status_exit, verb", [(0, "restart"), (3, "start")])+def test_studio_update_recovery_puts_the_service_on_the_restored_install(+ tmp_path: Path, status_exit, verb+):+ """The killed run may have restarted Studio on the unverified code, or left it+ FATAL. After the packages are back the service is restarted on the restored+ install before this run does anything else, so a run that stops early (the ref+ cannot be fetched) still leaves Studio in a known state."""+ env = _studio_env(tmp_path, status_exit = status_exit, git_ls_exit = 1)+ home = Path(env["UNSLOTH_STUDIO_HOME"])+ (home / ".src-update.rollback").write_text("-e file:///opt/prev-src\n")+ res = _run(STUDIO_UPDATE, ["--ref", "main"], env)+ calls = _calls(env)+ assert res.returncode != 0, res.stdout+ assert "the previous packages are back" in res.stdout, res.stdout+ assert "running the restored install" in res.stdout, res.stdout+ sup = [l for l in calls.splitlines() if l.startswith("STUB-SUPERVISORCTL")]+ assert sup[1] == f"STUB-SUPERVISORCTL {verb} studio", sup+ assert not (home / ".src-update.rollback").exists()+ env = _studio_env(tmp_path / "noreset", git_ls_exit = 1)+ home = Path(env["UNSLOTH_STUDIO_HOME"])+ (home / ".src-update.rollback").write_text("-e file:///opt/prev-src\n")+ res = _run(STUDIO_UPDATE, ["--ref", "main", "--no-restart"], env)+ assert "STUB-SUPERVISORCTL" not in _calls(env), _calls(env)+ assert "restart it to load the restored install" in res.stdout, res.stdout+++def test_studio_update_with_deps_rollback_fails_when_pip_cannot_list_packages(tmp_path: Path):+ """The list of what the update pulled in comes from a second `pip freeze`; when+ that fails, nothing would be removed, so the restore is reported as unfinished+ and the record stays."""+ env = _studio_env(tmp_path, import_ok = False)+ env["STUB_FREEZE_EXIT_AFTER"] = "1"+ res = _run(STUDIO_UPDATE, ["--with-deps", "--no-restart"], env)+ home = Path(env["UNSLOTH_STUDIO_HOME"])+ assert res.returncode != 0+ assert "could not list the installed packages" in res.stdout, res.stdout+ assert "could not be restored cleanly" in res.stdout, res.stdout+ assert (+ home / ".src-update.rollback"+ ).is_file(), "the record was dropped after a failed restore"+++def test_recover_finishes_a_killed_update_and_does_nothing_else(tmp_path: Path):+ """The container start runs --recover before supervisord starts Studio: a previous+ tree beside src goes back over the unverified one, the recorded packages are+ reinstalled, and no update is attempted."""+ env = _studio_env(tmp_path)+ home = Path(env["UNSLOTH_STUDIO_HOME"])+ (home / "src" / "OLD_TREE").unlink()+ (home / "src" / "NEW_TREE").write_text("unverified\n")+ (home / ".src-prev.k9x2Qa" / "studio").mkdir(parents = True)+ (home / ".src-prev.k9x2Qa" / "OLD_TREE").write_text("previous\n")+ (home / ".src-update.rollback").write_text("-e file:///opt/prev-src\n")+ res = _run(STUDIO_UPDATE, ["--recover"], env)+ calls = _calls(env)+ assert res.returncode == 0, res.stdout + res.stderr+ assert "recovery done" in res.stdout, res.stdout+ assert (home / "src" / "OLD_TREE").exists() and not (home / "src" / "NEW_TREE").exists()+ assert not (home / ".src-prev.k9x2Qa").exists()+ assert not (home / ".src-update.rollback").exists()+ assert "install --no-deps --force-reinstall -r" in calls, calls+ assert "install -U" not in calls and "STUB-GIT" not in calls, calls+ assert not _scratch(home)+ env = _studio_env(tmp_path / "clean")+ res = _run(STUDIO_UPDATE, ["--recover"], env)+ assert res.returncode == 0 and "nothing to recover" in res.stdout, res.stdout+ assert "STUB-PIP -m pip install" not in _calls(env)+++def test_studio_update_says_when_the_restore_did_not_finish(tmp_path: Path):+ """pip failing during the restore itself must not be reported as the previous+ install being back; the record stays so the next run finishes it."""+ env = _studio_env(tmp_path, import_ok = False)+ env["STUB_PIP_EXIT"] = "1"+ res = _run(STUDIO_UPDATE, ["--no-restart"], env)+ home = Path(env["UNSLOTH_STUDIO_HOME"])+ assert res.returncode != 0+ assert "back in place" not in res.stderr, res.stderr+ assert "could not put every previous package back" in res.stderr, res.stderr+ assert (+ home / ".src-update.rollback"+ ).is_file(), "the record was dropped after a failed restore"+ del env["STUB_PIP_EXIT"]+ res = _run(STUDIO_UPDATE, ["--no-restart"], env)+ assert "putting the previous packages back first" in res.stdout, res.stdout+ assert not (home / ".src-update.rollback").exists()+++def test_studio_update_keeps_the_lock_file(tmp_path: Path):+ """Unlinking the lock would let a run that opened the old inode take the lock after+ this one exits while a later run locks a fresh file at the same path."""+ env = _studio_env(tmp_path)+ res = _run(STUDIO_UPDATE, ["--no-restart"], env)+ assert res.returncode == 0, res.stderr + res.stdout+ assert (Path(env["UNSLOTH_STUDIO_HOME"]) / ".src-update.lock").is_file()+++def test_studio_update_treats_a_previous_tree_without_a_record_as_scratch(tmp_path: Path):+ """The record is unlinked before the previous tree is deleted, so a previous tree+ with no record is a committed update that was killed mid-delete, and src is the+ tree that passed the health check."""+ env = _studio_env(tmp_path)+ home = Path(env["UNSLOTH_STUDIO_HOME"])+ (home / ".src-prev.abc123" / "studio").mkdir(parents = True)+ (home / ".src-prev.abc123" / "COMMITTED_AWAY").write_text("")+ res = _run(STUDIO_UPDATE, [], env)+ assert res.returncode == 0, res.stderr + res.stdout+ assert (home / "src" / "OLD_TREE").exists()+ assert "putting it back" not in res.stdout, res.stdout+ assert not _scratch(home)+++def test_studio_update_with_deps_adds_the_studio_extra_to_a_qualified_unsloth_spec(tmp_path: Path):+ """--packages can pin or qualify unsloth; the studio extra must still ride along,+ and unsloth_zoo must not be mistaken for it."""+ env = _studio_env(tmp_path)+ res = _run(+ STUDIO_UPDATE,+ ["--with-deps", "--no-restart", "--packages", "unsloth==2026.9.1 unsloth_zoo"],+ env,+ )+ assert res.returncode == 0, res.stderr + res.stdout+ calls = _calls(env)+ assert "unsloth[studio]==2026.9.1" in calls, calls+ assert "unsloth[studio]_zoo" not in calls and " unsloth_zoo" in calls, calls+ env = _studio_env(tmp_path / "extras")+ res = _run(+ STUDIO_UPDATE, ["--with-deps", "--no-restart", "--packages", "unsloth[cu128]>=2026.9"], env+ )+ assert "unsloth[studio,cu128]>=2026.9" in _calls(env), _calls(env)+++def test_studio_update_with_deps_rollback_removes_what_the_update_pulled_in(tmp_path: Path):+ """Reinstalling the snapshot puts back what was there; a dependency the update+ introduced would otherwise stay and become part of the next snapshot."""+ env = _studio_env(tmp_path, import_ok = False)+ res = _run(STUDIO_UPDATE, ["--with-deps", "--no-restart"], env)+ assert res.returncode != 0+ calls = _calls(env)+ assert "STUB-PIP -m pip uninstall -y newdep" in calls, calls+ assert "uninstall -y transformers" not in calls and "uninstall -y torch" not in calls, calls+++def test_studio_update_ref_uses_the_lockfile_and_does_not_fall_back_to_npm_install(tmp_path: Path):+ env = _studio_env(tmp_path)+ env["STUB_LOCKFILE"] = "1"+ env["STUB_NPM_CI_EXIT"] = "1"+ res = _run(STUDIO_UPDATE, ["--ref", "main", "--no-restart"], env)+ home = Path(env["UNSLOTH_STUDIO_HOME"])+ calls = _calls(env)+ assert res.returncode != 0+ assert "npm ci failed" in res.stdout, res.stdout+ frontend_installs = [+ l for l in calls.splitlines() if "STUB-NPM install" in l and l.endswith("frontend")+ ]+ assert not frontend_installs, (+ "a lockfile that does not apply must not be re-resolved:\n" + calls+ )+ assert (home / "src" / "OLD_TREE").exists()+ env = _studio_env(tmp_path / "nolock")+ res = _run(STUDIO_UPDATE, ["--ref", "main", "--no-restart"], env)+ calls = _calls(env)+ assert res.returncode == 0, res.stderr + res.stdout+ assert "STUB-NPM ci" not in calls, calls+ assert "no package-lock.json" in res.stdout, res.stdout+++def test_studio_update_ref_threads_the_npm_registry_override(tmp_path: Path):+ env = _studio_env(tmp_path)+ env["STUB_LOCKFILE"] = "1"+ env["UNSLOTH_NPM_REGISTRY"] = "https://mirror.example/npm/"+ res = _run(STUDIO_UPDATE, ["--ref", "main", "--no-restart"], env)+ assert res.returncode == 0, res.stderr + res.stdout+ for line in [+ l for l in _calls(env).splitlines() if "STUB-NPM ci" in l or "STUB-NPM install" in l+ ]:+ assert "--registry https://mirror.example/npm/" in line, line+++def test_studio_update_help_prints_only_the_header(tmp_path: Path):+ env = _studio_env(tmp_path)+ res = _run(STUDIO_UPDATE, ["--help"], env)+ assert res.returncode == 0+ assert "set -euo pipefail" not in res.stdout+ assert "UNSLOTH_STUDIO_UPDATE_HEALTH_WAIT" in res.stdout++def _llama_env(tmp_path: Path,*,@@ -355,27 +1133,12 @@ def test_fetcher_normalizes_the_base_build_for_the_marker_tag(release_tag, expecassert _fetcher_module().base_build_tag(release_tag) == expected-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 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."""+def test_a_failed_studio_update_puts_the_previous_install_back(tmp_path: Path):+ """Not restarting protected only the code the running process had already+ imported; the venv on disk stayed replaced, so any lazy import or later restart+ failed the same way. The update now reinstalls exactly what it started from."""env = _studio_env(tmp_path, import_ok = False)res = _run(STUDIO_UPDATE, [], env)assert res.returncode != 0, "a broken update must not report success"- err = res.stderr.lower()- assert "already replaced" in err, (- "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 "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- )+ assert "previous install was restored" in res.stdout, res.stdout+ assert "not restarted" in res.stdout, res.stdoutdiff --git a/tests/sh/test_setup_staged_root.sh b/tests/sh/test_setup_staged_root.shindex d54a4aa4538..bb8edb54511 100755--- a/tests/sh/test_setup_staged_root.sh+++ b/tests/sh/test_setup_staged_root.sh@@ -49,13 +49,20 @@ done# The legacy single sidecar. Its tiered replacements land under the stage root and# may never be activated, so removing this during a staged run leaves the running# install with no sidecar at all.-_sh_legacy=$(sed -n '/^if \[ -d "\$STUDIO_HOME\/\.venv_t5" \]; then$/,/^fi$/p' "$SETUP_SH")+# The offline fast path took the plain `if` for itself, so the migration branch that+# these two assertions are about is the `elif`. Both anchors are asserted non-empty:+# a reshape that stops matching must fail here, not silently grep an empty string.+_sh_legacy=$(sed -n '/^elif \[ -d "\$STUDIO_HOME\/\.venv_t5" \]; then$/,/^fi$/p' "$SETUP_SH")+check "setup.sh legacy sidecar block found" \+ "$([ -n "$_sh_legacy" ] && echo 0 || echo 1)"check "setup.sh guards the legacy sidecar removal on STAGE_ROOT" \"$(printf '%s' "$_sh_legacy" | grep -qF '[ -z "$STAGE_ROOT" ]' && echo 0 || echo 1)"check "setup.sh still removes it on a live update" \"$(printf '%s' "$_sh_legacy" | grep -qF 'rm -rf "$STUDIO_HOME/.venv_t5"' && echo 0 || echo 1)"-_ps_legacy=$(sed -n '/^if (Test-Path -LiteralPath \$VenvT5Legacy) {$/,/^}$/p' "$SETUP_PS1")+_ps_legacy=$(sed -n '/^} elseif (Test-Path -LiteralPath \$VenvT5Legacy) {$/,/^}$/p' "$SETUP_PS1")+check "setup.ps1 legacy sidecar block found" \+ "$([ -n "$_ps_legacy" ] && echo 0 || echo 1)"check "setup.ps1 guards the legacy sidecar removal on StageRoot" \"$(printf '%s' "$_ps_legacy" | grep -qF 'if (-not $StageRoot)' && echo 0 || echo 1)"check "setup.ps1 still removes it on a live update" \