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.

Studio: keep a verified install when PyPI is unreachable and UV_OFFLINE is set (#10651)

Daniel Hanc5048022f721
diff --git a/.github/workflows/studio-update-smoke.yml b/.github/workflows/studio-update-smoke.yml
index 6bc144d1af8..d1e30408168 100644
--- a/.github/workflows/studio-update-smoke.yml
+++ b/.github/workflows/studio-update-smoke.yml
@@ -19,7 +19,25 @@ on:
- 'studio/setup.sh'
- 'studio/install_python_stack.py'
- 'studio/install_llama_prebuilt.py'
+ - 'studio/install_whisper_prebuilt.py'
+ - 'studio/install_node_prebuilt.py'
+ - 'studio/install_manifest.py'
+ - 'studio/prebuilt_core.py'
+ # install_node_prebuilt.py reads the default version and archive digests from here.
+ - 'studio/node_prebuilt_pins.json'
+ - 'studio/setup.ps1'
+ - 'install.ps1'
- 'studio/backend/requirements/**'
+ # setup.sh and setup.ps1 run npm against these two trees on every update, and the
+ # harness holds the frontend bundle to be current afterwards; a dependency change
+ # there used to reach these jobs only through the push to main.
+ - 'studio/frontend/package.json'
+ - 'studio/frontend/package-lock.json'
+ - 'studio/backend/core/data_recipe/oxc-validator/package.json'
+ - 'studio/backend/core/data_recipe/oxc-validator/package-lock.json'
+ # The harness below and the proxy it measures with.
+ - 'tests/studio/install/test_update_idempotency.py'
+ - 'tests/studio/install/idempotency_proxy.py'
- 'unsloth_cli/commands/studio.py'
- 'unsloth_cli/__init__.py'
- 'unsloth_cli/_system_dir_guard.py'
@@ -36,6 +54,48 @@ on:
- '.github/actions/uv-cache-save/action.yml'
push:
branches: [main]
+ # The same list as pull_request. This workflow has a macOS leg, and macOS runners
+ # are capped at five concurrent jobs account-wide, so a push trigger without a
+ # filter would spend them on commits that cannot affect what it tests.
+ paths:
+ - 'install.sh'
+ - 'scripts/uninstall.sh'
+ - 'studio/setup.sh'
+ - 'studio/install_python_stack.py'
+ - 'studio/install_llama_prebuilt.py'
+ - 'studio/install_whisper_prebuilt.py'
+ - 'studio/install_node_prebuilt.py'
+ - 'studio/install_manifest.py'
+ - 'studio/prebuilt_core.py'
+ # install_node_prebuilt.py reads the default version and archive digests from here.
+ - 'studio/node_prebuilt_pins.json'
+ - 'studio/setup.ps1'
+ - 'install.ps1'
+ - 'studio/backend/requirements/**'
+ # setup.sh and setup.ps1 run npm against these two trees on every update, and the
+ # harness holds the frontend bundle to be current afterwards; a dependency change
+ # there used to reach these jobs only through the push to main.
+ - 'studio/frontend/package.json'
+ - 'studio/frontend/package-lock.json'
+ - 'studio/backend/core/data_recipe/oxc-validator/package.json'
+ - 'studio/backend/core/data_recipe/oxc-validator/package-lock.json'
+ # The harness below and the proxy it measures with.
+ - 'tests/studio/install/test_update_idempotency.py'
+ - 'tests/studio/install/idempotency_proxy.py'
+ - 'unsloth_cli/commands/studio.py'
+ - 'unsloth_cli/__init__.py'
+ - 'unsloth_cli/_system_dir_guard.py'
+ - 'pyproject.toml'
+ - '.github/workflows/studio-update-smoke.yml'
+ - '.github/scripts/retry-with-apt-lock.sh'
+ # The install step in this workflow is `uses:` on that composite action,
+ # so an edit to the action changes what this workflow actually runs.
+ - '.github/actions/install-unsloth-local/action.yml'
+ # The dist cache moved out of install-unsloth-local so the Windows jobs could
+ # share one definition of its key; a change to it still has to re-run the jobs
+ # that depend on it.
+ - '.github/actions/frontend-dist-restore/action.yml'
+ - '.github/actions/frontend-dist-save/action.yml'
workflow_dispatch:
concurrency:
@@ -54,7 +114,7 @@ jobs:
name: Unsloth Updating Tests
runs-on: ubuntu-latest
# Sized for the apt step's bounded worst case (15m) plus the smoke itself.
- timeout-minutes: 25
+ timeout-minutes: 60
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
@@ -78,9 +138,12 @@ jobs:
bash .github/scripts/retry-with-apt-lock.sh sudo sh -c \
'apt-get install -y --no-install-recommends libcurl4-openssl-dev libssl-dev jq || { apt-get update && apt-get install -y --no-install-recommends libcurl4-openssl-dev libssl-dev jq; }'
+ # Node 24 ships npm 11, which meets setup.sh's floor (Node ^20.19 || >=22.12 with
+ # npm >= 11): this job takes the system-Node path, the developer one. Node 22
+ # ships npm 10 and would take the bundled path, which the other two jobs cover.
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
with:
- node-version: '22'
+ node-version: '24'
- uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0
with:
@@ -98,6 +161,40 @@ jobs:
# Withheld on PR: this step runs checked-out PR code; public GGUF still downloads.
hf-token: ${{ github.event_name != 'pull_request' && secrets.HF_TOKEN || '' }}
+ - name: A second update does nothing, and proves it
+ # The first updates after the install, measured rather than read off their logs:
+ # the update runs with a CONNECT proxy as its only route out, so "downloaded
+ # nothing" is a byte count per host rather than an impression of speed, and the
+ # install is diffed before and after so "changed nothing" covers the files no log
+ # line mentions. Before the log-only steps below on purpose: a regression that
+ # downloads or rewrites state on the first or second update and then records
+ # enough evidence to go quiet would otherwise be measured only on a fourth.
+ #
+ # It also damages the install on purpose (a sidecar file, the manifest, a
+ # llama.cpp binary, a requirements file) and asserts the update repairs exactly
+ # the damaged part. Those cases restore what they broke, but they run BEFORE the
+ # manifest-removal step below rather than after, so a failure here cannot be
+ # mistaken for the deliberately incomplete install that step creates.
+ timeout-minutes: 30
+ env:
+ UNSLOTH_IDEMPOTENCY_E2E: '1'
+ # Each run's update log and proxy journal, kept for the upload below. A
+ # failure here is unreadable without them: the assertion says which host
+ # served bytes, not which of the eight runs did it.
+ UNSLOTH_IDEMPOTENCY_ARTIFACTS: ${{ github.workspace }}/logs/idempotency
+ # The install above is --local and editable, so the CLI would find the
+ # checkout on its own; naming it keeps that working if the install ever
+ # stops being editable.
+ STUDIO_LOCAL_REPO: ${{ github.workspace }}
+ GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+ run: |
+ set -o pipefail
+ mkdir -p logs
+ # setup-python's interpreter runs the harness, and it ships without pytest.
+ python -m pip install --quiet pytest
+ python -m pytest tests/studio/install/test_update_idempotency.py -v -s \
+ 2>&1 | tee logs/idempotency.log
+
- name: First update should be a no-op (prebuilt already validated)
# `unsloth studio update --local` runs studio/setup.sh against
# the local repo. Right after install.sh the llama.cpp prebuilt
@@ -266,6 +363,143 @@ jobs:
logs/install.log
logs/update.log
logs/update2.log
+ logs/idempotency.log
+ logs/idempotency/**/update.log
+ logs/idempotency/**/proxy.jsonl
logs/studio.log
logs/uninstall.log
retention-days: 7
+
+ idempotency-macos:
+ name: Unsloth Updating Tests (macOS)
+ runs-on: macos-15
+ # The install is the expensive half; the harness itself is three updates that are
+ # supposed to do nothing plus five that do one thing each.
+ timeout-minutes: 75
+ steps:
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ with:
+ persist-credentials: false
+
+ # Below setup.sh's floor (Node ^20.19 || >=22.12 with npm >= 11) on purpose: with
+ # it, setup takes the bundled Node path desktop users without a toolchain take, so
+ # the harness's Node marker snapshot and its "nothing from nodejs.org" assertion
+ # measure a managed Node rather than pass vacuously over a system one. The Linux
+ # job keeps a qualifying system Node (Node 24, npm 11), the developer path.
+ - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
+ with:
+ node-version: '20.18.0'
+
+ - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0
+ with:
+ python-version: '3.12'
+
+ - name: Install Unsloth (--local, --no-torch)
+ uses: ./.github/actions/install-unsloth-local
+ with:
+ gh-token: ${{ secrets.GITHUB_TOKEN }}
+ # Withheld on PR: this step runs checked-out PR code; public GGUF still downloads.
+ hf-token: ${{ github.event_name != 'pull_request' && secrets.HF_TOKEN || '' }}
+
+ - name: A second update does nothing, and proves it
+ # macOS is where a no-op update cost the most before this: the llama.cpp and
+ # whisper.cpp re-validations START the servers, which on Apple Silicon means
+ # loading Metal. Same harness as the Linux leg.
+ timeout-minutes: 30
+ env:
+ UNSLOTH_IDEMPOTENCY_E2E: '1'
+ UNSLOTH_IDEMPOTENCY_ARTIFACTS: ${{ github.workspace }}/logs/idempotency
+ STUDIO_LOCAL_REPO: ${{ github.workspace }}
+ GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+ run: |
+ set -o pipefail
+ mkdir -p logs
+ # setup-python's interpreter runs the harness, and it ships without pytest.
+ python -m pip install --quiet pytest
+ python -m pytest tests/studio/install/test_update_idempotency.py -v -s \
+ 2>&1 | tee logs/idempotency.log
+
+ - name: Upload macOS idempotency logs
+ if: always()
+ uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
+ with:
+ name: studio-update-idempotency-macos-log
+ path: |
+ logs/install.log
+ logs/idempotency.log
+ logs/idempotency/**/update.log
+ logs/idempotency/**/proxy.jsonl
+ retention-days: 7
+
+ idempotency-windows:
+ name: Unsloth Updating Tests (Windows)
+ runs-on: windows-latest
+ # Windows installs are 3x the Linux ones (268-292s against 88s in the API smoke),
+ # and Defender is why; the harness after it is the same three updates.
+ timeout-minutes: 90
+ steps:
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ with:
+ persist-credentials: false
+
+ # Node 22 ships npm 10, below setup.ps1's npm 11 floor, so this job takes the
+ # bundled Node path as the macOS job does; the Linux job covers the system-Node one.
+ - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
+ with:
+ node-version: '22'
+
+ - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0
+ with:
+ python-version: '3.12'
+
+ - name: Install Unsloth (--local, --no-torch)
+ shell: pwsh
+ env:
+ GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+ # Withheld on PR: this step runs checked-out PR code; public GGUF still downloads.
+ HF_TOKEN: ${{ github.event_name != 'pull_request' && secrets.HF_TOKEN || '' }}
+ run: |
+ New-Item -ItemType Directory -Force -Path logs | Out-Null
+ # A CHILD process, so install.ps1's Write-StudioLine output reaches
+ # Tee-Object: in-process it goes straight to [Console]::Out and the log is
+ # empty. Same idiom as studio-windows-api-smoke.yml.
+ $child = '$ErrorActionPreference = ''Stop''; $ProgressPreference = ''SilentlyContinue''; & ./install.ps1 --local --no-torch; exit $LASTEXITCODE'
+ # Elapsed-seconds prefix, added to the STEP LOG only. Tee-Object writes
+ # logs/install.log upstream of this filter, so the artifact keeps exactly
+ # what install.ps1 produced. Same idiom as studio-windows-api-smoke.yml.
+ $sw = [System.Diagnostics.Stopwatch]::StartNew()
+ pwsh -NoProfile -ExecutionPolicy Bypass -Command $child 2>&1 |
+ Tee-Object -FilePath logs/install.log |
+ ForEach-Object { '[{0,4:N0}s] {1}' -f $sw.Elapsed.TotalSeconds, $_ }
+ if ($LASTEXITCODE -ne 0) { throw "install.ps1 exited with code $LASTEXITCODE" }
+
+ - 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.
+ timeout-minutes: 40
+ shell: pwsh
+ env:
+ UNSLOTH_IDEMPOTENCY_E2E: '1'
+ UNSLOTH_IDEMPOTENCY_ARTIFACTS: ${{ github.workspace }}\logs\idempotency
+ STUDIO_LOCAL_REPO: ${{ github.workspace }}
+ GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+ run: |
+ New-Item -ItemType Directory -Force -Path logs | Out-Null
+ $ErrorActionPreference = 'Continue'
+ # setup-python's interpreter runs the harness, and it ships without pytest.
+ python -m pip install --quiet pytest
+ python -m pytest tests/studio/install/test_update_idempotency.py -v -s 2>&1 |
+ Tee-Object -FilePath logs/idempotency.log
+ if ($LASTEXITCODE -ne 0) { throw "the idempotency harness failed ($LASTEXITCODE)" }
+
+ - name: Upload Windows idempotency logs
+ if: always()
+ uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
+ with:
+ name: studio-update-idempotency-windows-log
+ path: |
+ logs/install.log
+ logs/idempotency.log
+ logs/idempotency/**/update.log
+ logs/idempotency/**/proxy.jsonl
+ retention-days: 7
diff --git a/studio/backend/tests/test_transformers_version_optional_tiktoken.py b/studio/backend/tests/test_transformers_version_optional_tiktoken.py
index 5e1c30a6960..a19bac7dc7c 100644
--- a/studio/backend/tests/test_transformers_version_optional_tiktoken.py
+++ b/studio/backend/tests/test_transformers_version_optional_tiktoken.py
@@ -21,9 +21,12 @@ complete; the runtime validator used to require it, delete the sidecar and retry
install that had just failed.
"""
+import contextlib
import pathlib
import shutil
import sys
+
+import pytest
import types as _types
import os
from pathlib import Path
@@ -219,7 +222,8 @@ def test_a_remnant_that_will_not_go_fails_the_build_instead_of_shadowing(tmp_pat
monkeypatch.setattr(tv.shutil, "rmtree", stuck_rmtree)
assert tv._ensure_venv_dir(str(root), tv._VENV_T5_550_PACKAGES, "test sidecar") is False
- assert (root / "tiktoken").is_dir()
+ # A failed build wipes the partial tree; either way nothing reads as a usable sidecar.
+ assert tv._venv_dir_is_valid_and_undamaged(str(root), tv._VENV_T5_550_PACKAGES) is False
monkeypatch.setattr(tv.shutil, "rmtree", real_rmtree)
assert tv._ensure_venv_dir(str(root), tv._VENV_T5_550_PACKAGES, "test sidecar") is True
assert not (root / "tiktoken").exists()
@@ -491,6 +495,21 @@ def test_the_top_up_stays_home_offline_and_yields_to_another_process(tmp_path, m
monkeypatch.setenv("UV_OFFLINE", "1")
tv._top_up_optional_packages(str(root), packages)
assert installed == []
+ # Every spelling uv accepts, or an offline miss would be remembered as a failure.
+ for spelling in ("t", "y", "on", "TRUE"):
+ monkeypatch.setenv("UV_OFFLINE", spelling)
+ tv._OPTIONAL_TOP_UP_ATTEMPTED.clear()
+ tv._top_up_optional_packages(str(root), packages)
+ assert installed == [], spelling
+ assert not (root / tv._OPTIONAL_TOP_UP_FAILED).exists()
+ # ...unless pip has a local wheelhouse, the exception _install_to_dir makes.
+ monkeypatch.setenv("UV_OFFLINE", "1")
+ monkeypatch.setattr(tv, "_pip_is_configured_offline", lambda: True)
+ tv._OPTIONAL_TOP_UP_ATTEMPTED.clear()
+ tv._top_up_optional_packages(str(root), packages)
+ assert installed == ["tiktoken"]
+ installed.clear()
+ monkeypatch.setattr(tv, "_pip_is_configured_offline", lambda: False)
monkeypatch.delenv("UV_OFFLINE")
# Another process holds the top-up lock: wait up to the bound, then leave the package to it.
monkeypatch.setattr(tv, "_OPTIONAL_TOP_UP_WAIT_SECONDS", 0.5)
@@ -586,6 +605,425 @@ def test_a_recordless_record_beside_a_complete_install_is_removed_without_a_top_
assert (good / "RECORD").is_file()
+def test_an_offline_session_does_not_wipe_a_sidecar_it_cannot_rebuild(tmp_path, monkeypatch):
+ """`studio update` under UV_OFFLINE leaves a stale tier for the next online update;
+ the runtime repair used to delete that tier and then reach for the network. With a
+ cold cache the tree stays exactly as it was; with a warm one the replacement is
+ built beside it and swapped in whole."""
+ root = tmp_path / ".venv_t5_550"
+ root.mkdir()
+ (root / "keep.txt").write_text("", encoding = "utf-8")
+ # Valid only once every package landed in it: the live tree never does here.
+ built = {}
+ monkeypatch.setattr(
+ tv,
+ "_venv_dir_is_valid_and_undamaged",
+ lambda d, packages, *a, **k: built.get(str(d)) == len(packages),
+ )
+ installed = []
+ monkeypatch.setattr(tv, "_install_to_dir", lambda pkg, target: installed.append(pkg) and False)
+ monkeypatch.delenv("HF_HUB_OFFLINE", raising = False)
+ siblings = lambda: sorted(
+ p.name for p in tmp_path.iterdir() if p.name.startswith(".venv_t5_550.")
+ )
+ for value in ("1", "t", "Y", "true", "on"):
+ monkeypatch.setenv("UV_OFFLINE", value)
+ installed.clear()
+ assert tv._ensure_venv_dir(str(root), tv._VENV_T5_550_PACKAGES, "test sidecar") is False
+ assert (root / "keep.txt").is_file()
+ # The cache was asked, beside the tree, never in it.
+ assert installed == [tv._VENV_T5_550_PACKAGES[0]]
+ assert siblings() == []
+ # A warm cache: every package installs into the staging tree and the swap is whole.
+ staged_into = []
+
+ def warm_install(pkg, target):
+ staged_into.append(target)
+ built[target] = built.get(target, 0) + 1
+ return True
+
+ monkeypatch.setattr(tv, "_install_to_dir", warm_install)
+ monkeypatch.setenv("UV_OFFLINE", "1")
+ assert tv._ensure_venv_dir(str(root), tv._VENV_T5_550_PACKAGES, "test sidecar") is True
+ assert len(set(staged_into)) == 1
+ assert set(staged_into) == {str(tmp_path / f".venv_t5_550.offline-staging-{tv.os.getpid()}")}
+ assert not (root / "keep.txt").exists()
+ assert (root / tv._STUDIO_OWNED_MARKER).is_file()
+ assert siblings() == []
+ # A staging tree that installed every package but does not validate never swaps in.
+ (root / "keep.txt").write_text("", encoding = "utf-8")
+ built.clear()
+ monkeypatch.setattr(tv, "_install_to_dir", lambda pkg, target: True)
+ assert tv._ensure_venv_dir(str(root), tv._VENV_T5_550_PACKAGES, "test sidecar") is False
+ assert (root / "keep.txt").is_file()
+ assert siblings() == []
+ monkeypatch.setattr(tv, "_venv_dir_is_valid_and_undamaged", lambda *a, **k: False)
+ root.mkdir(exist_ok = True)
+ (root / "keep.txt").write_text("", encoding = "utf-8")
+ installed.clear()
+ monkeypatch.setattr(tv, "_install_to_dir", lambda pkg, target: installed.append(pkg) or True)
+ # The HF offline switches turn off Hub access, not the package index: a damaged tier
+ # is still rebuilt under them, or the tier stays unusable while PyPI answers.
+ monkeypatch.setenv("UV_OFFLINE", "0")
+ monkeypatch.setenv("HF_HUB_OFFLINE", "1")
+ assert tv._runtime_repair_is_offline() is False
+ assert tv._ensure_venv_dir(str(root), tv._VENV_T5_550_PACKAGES, "test sidecar") is True
+ assert installed == list(tv._VENV_T5_550_PACKAGES)
+
+
+def test_an_empty_directory_is_still_built_offline_from_the_cache(tmp_path, monkeypatch):
+ """The offline rule protects a tree that may still serve. The latest sidecar's staging
+ directory and a first install have nothing to lose, and uv installs from a warm cache
+ without the network, so they are attempted; only the pip fallback stays out."""
+ root = tmp_path / ".venv_t5_latest.staging"
+ root.mkdir()
+ monkeypatch.setattr(tv, "_venv_dir_is_valid_and_undamaged", lambda *a, **k: False)
+ installed = []
+ monkeypatch.setattr(tv, "_install_to_dir", lambda pkg, target: installed.append(pkg) or True)
+ monkeypatch.setenv("UV_OFFLINE", "1")
+ assert tv._ensure_venv_dir(str(root), tv._VENV_T5_550_PACKAGES, "latest staging") is True
+ assert installed == list(tv._VENV_T5_550_PACKAGES)
+ # A missing directory is a first install, not a repair.
+ installed.clear()
+ assert tv._ensure_venv_dir(str(tmp_path / "fresh"), tv._VENV_T5_550_PACKAGES, "fresh") is True
+ assert installed == list(tv._VENV_T5_550_PACKAGES)
+
+
+def test_the_pip_fallback_stays_out_offline(tmp_path, monkeypatch):
+ calls = []
+
+ class _Result:
+ returncode = 1
+ stdout = "no cached wheel"
+
+ def fake_run(cmd, **kwargs):
+ # The guard asks pip for its configuration first; only installs are counted.
+ if list(cmd[-2:]) == ["config", "list"]:
+ return _Result()
+ calls.append(list(cmd))
+ return _Result()
+
+ monkeypatch.setattr(tv.shutil, "which", lambda name: "/usr/bin/uv" if name == "uv" else None)
+ monkeypatch.setattr(tv.subprocess, "run", fake_run)
+ monkeypatch.setenv("UV_OFFLINE", "1")
+ monkeypatch.delenv("PIP_NO_INDEX", raising = False)
+ assert tv._install_to_dir("tiktoken", str(tmp_path)) is False
+ assert len(calls) == 1 and calls[0][0] == "uv"
+ # Without uv there is no cache to answer from, and pip is still not asked.
+ calls.clear()
+ monkeypatch.setattr(tv.shutil, "which", lambda name: None)
+ assert tv._install_to_dir("tiktoken", str(tmp_path)) is False
+ assert calls == []
+ monkeypatch.setattr(tv.shutil, "which", lambda name: "/usr/bin/uv" if name == "uv" else None)
+ monkeypatch.setenv("UV_OFFLINE", "0")
+ calls.clear()
+ assert tv._install_to_dir("tiktoken", str(tmp_path)) is False
+ assert [c[0] for c in calls] == ["uv", tv.sys.executable]
+
+
+def test_an_unreadable_sidecar_counts_as_content(tmp_path, monkeypatch):
+ """A listing that fails with anything but "not there" cannot say the tree is empty,
+ and the path taken for "empty" begins with deleting it."""
+ root = tmp_path / ".venv_t5_550"
+ root.mkdir()
+ (root / "keep.txt").write_text("", encoding = "utf-8")
+ assert tv._sidecar_has_content(str(tmp_path / "absent")) is False
+ real_listdir = tv.os.listdir
+
+ def denied(path):
+ if str(path) == str(root):
+ raise PermissionError(13, "Permission denied", str(path))
+ return real_listdir(path)
+
+ monkeypatch.setattr(tv.os, "listdir", denied)
+ assert tv._sidecar_has_content(str(root)) is True
+ monkeypatch.setattr(tv, "_venv_dir_is_valid_and_undamaged", lambda *a, **k: False)
+ monkeypatch.setattr(tv, "_install_to_dir", lambda pkg, target: False)
+ monkeypatch.setenv("UV_OFFLINE", "1")
+ assert tv._ensure_venv_dir(str(root), tv._VENV_T5_550_PACKAGES, "test sidecar") is False
+ assert (root / "keep.txt").is_file()
+
+
+def test_a_sibling_that_vanishes_while_sorting_does_not_abort_the_repair(tmp_path, monkeypatch):
+ """Another worker removing an old staging tree between the listing and the mtime
+ read used to raise out of _ensure_venv_dir and abort the activation."""
+ root = tmp_path / ".venv_t5_550"
+ ghost = tmp_path / ".venv_t5_550.offline-old-1"
+ ghost.mkdir()
+ (ghost / tv._STUDIO_OWNED_MARKER).write_text("", encoding = "utf-8")
+ real_getmtime = tv.os.path.getmtime
+
+ def vanishing(path):
+ if str(path) == str(ghost):
+ import shutil as _shutil
+ _shutil.rmtree(ghost, ignore_errors = True)
+ raise FileNotFoundError(2, "No such file or directory", str(path))
+ return real_getmtime(path)
+
+ monkeypatch.setattr(tv.os.path, "getmtime", vanishing)
+ assert tv._sidecar_siblings(str(root), tv._OFFLINE_RETIRED_SUFFIX) == [str(ghost)]
+
+
+def test_a_sidecar_stranded_by_an_interrupted_swap_is_restored_first(tmp_path, monkeypatch):
+ """Killed between the swap's two renames, the live path is empty and the preserved
+ tree sits under the retired name; the next call puts it back before it decides
+ anything, rather than reading the empty path as a first install."""
+ root = tmp_path / ".venv_t5_550"
+ retired = tmp_path / ".venv_t5_550.offline-old-4242"
+ retired.mkdir()
+ (retired / "keep.txt").write_text("", encoding = "utf-8")
+ (retired / tv._STUDIO_OWNED_MARKER).write_text("", encoding = "utf-8")
+ monkeypatch.setattr(
+ tv, "_venv_dir_is_valid_and_undamaged", lambda d, *a, **k: (Path(d) / "keep.txt").is_file()
+ )
+ monkeypatch.setattr(tv, "_top_up_optional_packages", lambda *a, **k: True)
+ installed = []
+ monkeypatch.setattr(tv, "_install_to_dir", lambda pkg, target: installed.append(pkg) and False)
+ monkeypatch.setenv("UV_OFFLINE", "1")
+ assert tv._ensure_venv_dir(str(root), tv._VENV_T5_550_PACKAGES, "test sidecar") is True
+ assert (root / "keep.txt").is_file()
+ assert not retired.exists()
+ assert installed == []
+ # With the live tree in place, a retired copy is a leftover and goes...
+ leftover = tmp_path / ".venv_t5_550.offline-old-99"
+ leftover.mkdir()
+ (leftover / "x").write_text("", encoding = "utf-8")
+ (leftover / tv._STUDIO_OWNED_MARKER).write_text("", encoding = "utf-8")
+ # ...but only a tree this code made, under exactly its name: an unmarked or differently named
+ # directory is the user's.
+ users = tmp_path / ".venv_t5_550.offline-old-backup"
+ users.mkdir()
+ (users / "precious").write_text("", encoding = "utf-8")
+ unowned = tmp_path / ".venv_t5_550.offline-old-7"
+ unowned.mkdir()
+ (unowned / "precious").write_text("", encoding = "utf-8")
+ assert tv._ensure_venv_dir(str(root), tv._VENV_T5_550_PACKAGES, "test sidecar") is True
+ assert (root / "keep.txt").is_file()
+ assert not leftover.exists()
+ assert (users / "precious").is_file() and (unowned / "precious").is_file()
+ # And with the live path empty, only an owned, exactly named tree is put back.
+ import shutil as _shutil
+
+ _shutil.rmtree(root)
+ monkeypatch.setattr(tv, "_repair_offline_beside", lambda *a, **k: False)
+ assert tv._recover_retired_sidecar(str(root)) is None
+ assert not root.exists()
+ assert (users / "precious").is_file() and (unowned / "precious").is_file()
+
+
+def test_a_rebuild_takes_the_tiers_lock_and_keeps_a_tree_finished_under_it(tmp_path, monkeypatch):
+ """Two workers repairing one tier: the second waits on the tier's lock and, once it
+ holds it, finds the first one's finished tree and keeps it rather than wiping it."""
+ root = tmp_path / ".venv_t5_550"
+ root.mkdir()
+ (root / "half").write_text("", encoding = "utf-8")
+ answers = iter([False, True])
+ monkeypatch.setattr(tv, "_venv_dir_is_valid_and_undamaged", lambda *a, **k: next(answers))
+ monkeypatch.setattr(tv, "_top_up_optional_packages", lambda *a, **k: True)
+ monkeypatch.delenv("UV_OFFLINE", raising = False)
+ monkeypatch.setattr(tv, "_env_offline", lambda: False)
+ monkeypatch.setattr(tv, "_runtime_repair_is_offline", lambda: False)
+ installed = []
+ monkeypatch.setattr(tv, "_install_to_dir", lambda pkg, target: installed.append(pkg) or True)
+ locked = []
+ real_lock = tv._file_lock
+
+ @contextlib.contextmanager
+ def recording_lock(path, wait):
+ locked.append(path)
+ with real_lock(path, wait) as held:
+ yield held
+
+ monkeypatch.setattr(tv, "_file_lock", recording_lock)
+ assert tv._ensure_venv_dir(str(root), tv._VENV_T5_550_PACKAGES, "test sidecar") is True
+ assert installed == [] and (root / "half").is_file()
+ assert locked == [tv._rebuild_lock_path(str(root))]
+ # Still incomplete under the lock: the rebuild runs, in this process, once.
+ monkeypatch.setattr(tv, "_venv_dir_is_valid_and_undamaged", lambda *a, **k: False)
+ assert tv._ensure_venv_dir(str(root), tv._VENV_T5_550_PACKAGES, "test sidecar") is True
+ assert installed == list(tv._VENV_T5_550_PACKAGES)
+ # Lock not obtained: no unguarded rebuild, this activation goes without the sidecar.
+ installed.clear()
+ (root / "half").write_text("", encoding = "utf-8")
+
+ @contextlib.contextmanager
+ def not_held(path, wait):
+ yield False
+
+ monkeypatch.setattr(tv, "_file_lock", not_held)
+ assert tv._ensure_venv_dir(str(root), tv._VENV_T5_550_PACKAGES, "test sidecar") is False
+ assert installed == [] and (root / "half").is_file()
+
+
+def test_the_offline_repair_runs_under_the_tiers_lock_too(tmp_path, monkeypatch):
+ """Two workers activating one damaged tier offline would each build a staging tree
+ and race the two-rename swap. The offline repair now waits on the same tier lock as
+ the online rebuild, and a lock not obtained defers rather than swaps."""
+ root = tmp_path / ".venv_t5_550"
+ root.mkdir()
+ (root / "keep.txt").write_text("", encoding = "utf-8")
+ monkeypatch.setattr(tv, "_venv_dir_is_valid_and_undamaged", lambda *a, **k: False)
+ monkeypatch.setenv("UV_OFFLINE", "1")
+ repaired = []
+ monkeypatch.setattr(tv, "_repair_offline_beside", lambda d, p, l: repaired.append(d) or True)
+ locked = []
+ real_lock = tv._file_lock
+
+ @contextlib.contextmanager
+ def recording_lock(path, wait):
+ locked.append(path)
+ with real_lock(path, wait) as held:
+ yield held
+
+ monkeypatch.setattr(tv, "_file_lock", recording_lock)
+ assert tv._ensure_venv_dir(str(root), tv._VENV_T5_550_PACKAGES, "test sidecar") is True
+ assert repaired == [str(root)] and locked == [tv._rebuild_lock_path(str(root))]
+
+ @contextlib.contextmanager
+ def not_held(path, wait):
+ yield False
+
+ monkeypatch.setattr(tv, "_file_lock", not_held)
+ repaired.clear()
+ assert tv._ensure_venv_dir(str(root), tv._VENV_T5_550_PACKAGES, "test sidecar") is False
+ assert repaired == [] and (root / "keep.txt").is_file()
+
+
+def test_a_wheelhouse_pip_is_allowed_offline(tmp_path, monkeypatch):
+ """PIP_NO_INDEX with PIP_FIND_LINKS is a local wheelhouse: an air-gapped install got
+ its sidecars that way before UV_OFFLINE was honoured, and the offline guard must
+ not turn that pip away."""
+ monkeypatch.setenv("UV_OFFLINE", "1")
+ monkeypatch.setattr(tv, "_uv_available", lambda: False, raising = False)
+ calls = []
+
+ class _Done:
+ returncode = 0
+
+ monkeypatch.setattr(tv.subprocess, "run", lambda cmd, **k: calls.append(cmd) or _Done())
+ # Without a pip to ask, the environment is what there is.
+ monkeypatch.setattr(tv, "_pip_effective_settings", lambda: None)
+ monkeypatch.delenv("PIP_NO_INDEX", raising = False)
+ monkeypatch.delenv("PIP_FIND_LINKS", raising = False)
+ assert tv._pip_is_configured_offline() is False
+ monkeypatch.setenv("PIP_NO_INDEX", "1")
+ assert tv._pip_is_configured_offline() is False
+ monkeypatch.setenv("PIP_FIND_LINKS", str(tmp_path))
+ assert tv._pip_is_configured_offline() is True
+ for spelling in ("t", "y", "yes", "on", "TRUE"):
+ monkeypatch.setenv("PIP_NO_INDEX", spelling)
+ assert tv._pip_is_configured_offline() is True, spelling
+ monkeypatch.setenv("PIP_NO_INDEX", "0")
+ assert tv._pip_is_configured_offline() is False
+ monkeypatch.setenv("PIP_NO_INDEX", "1")
+ monkeypatch.setenv("PIP_FIND_LINKS", f"{tmp_path} file://{tmp_path}")
+ assert tv._pip_is_configured_offline() is True
+ # --find-links takes URLs too, and one of those is the network.
+ monkeypatch.setenv("PIP_FIND_LINKS", f"{tmp_path} https://wheels.example/simple")
+ assert tv._pip_is_configured_offline() is False
+ monkeypatch.setenv("PIP_FIND_LINKS", str(tmp_path / "missing"))
+ assert tv._pip_is_configured_offline() is False
+ # A FILE is parsed for links, and those may be URLs: only a directory is local.
+ index = tmp_path / "index.html"
+ index.write_text('<a href="https://wheels.example/tiktoken.whl">x</a>', encoding = "utf-8")
+ monkeypatch.setenv("PIP_FIND_LINKS", str(index))
+ assert tv._pip_is_configured_offline() is False
+ monkeypatch.setenv("PIP_FIND_LINKS", f"file://{index}")
+ assert tv._pip_is_configured_offline() is False
+ # A UNC share: file://server/share keeps its host, which is part of the path.
+ seen = []
+
+ def isdir(path):
+ seen.append(path)
+ return True
+
+ monkeypatch.setattr(tv.os.path, "isdir", isdir)
+ monkeypatch.setenv("PIP_FIND_LINKS", "file://wheelserver/share/wheels")
+ assert tv._pip_is_configured_offline() is True
+ assert seen and "wheelserver" in seen[-1] and "share" in seen[-1]
+
+
+def test_the_wheelhouse_is_read_from_pip_config_files_too(tmp_path, monkeypatch):
+ """An air-gapped host sets no-index and find-links in pip.conf as often as in the
+ environment; the guard asks pip for its effective configuration, with pip's own
+ precedence (environment over [install] over [global])."""
+ monkeypatch.delenv("PIP_NO_INDEX", raising = False)
+ monkeypatch.delenv("PIP_FIND_LINKS", raising = False)
+ settings = {"global.no-index": "true", "global.find-links": f"\n{tmp_path}"}
+ monkeypatch.setattr(tv, "_pip_effective_settings", lambda: dict(settings))
+ assert tv._pip_is_configured_offline() is True
+ # [install] overrides [global] ...
+ settings["install.no-index"] = "false"
+ assert tv._pip_is_configured_offline() is False
+ # ... and the environment overrides both.
+ settings[":env:.no-index"] = "1"
+ assert tv._pip_is_configured_offline() is True
+ settings[":env:.find-links"] = "https://wheels.example/simple"
+ assert tv._pip_is_configured_offline() is False
+ del settings[":env:.find-links"]
+ settings["global.find-links"] = f"{tmp_path} {tmp_path / 'index.html'}"
+ (tmp_path / "index.html").write_text("<a href='https://x/y.whl'>y</a>", encoding = "utf-8")
+ assert tv._pip_is_configured_offline() is False
+
+
+def test_pip_config_list_is_parsed_as_pip_prints_it(tmp_path, monkeypatch):
+ """`pip config list` prints repr'd values (a multi-line find-links comes out with
+ literal \\n escapes); the parser gives back what pip will read."""
+ monkeypatch.delenv("PIP_NO_INDEX", raising = False)
+ monkeypatch.delenv("PIP_FIND_LINKS", raising = False)
+ conf = tmp_path / "pip.conf"
+ conf.write_text(
+ f"[global]\nno-index = true\nfind-links =\n {tmp_path}\n {tmp_path}\n",
+ encoding = "utf-8",
+ )
+ monkeypatch.setenv("PIP_CONFIG_FILE", str(conf))
+ settings = tv._pip_effective_settings()
+ if settings is None:
+ pytest.skip("pip is not importable by this interpreter")
+ assert settings.get("global.no-index") == "true"
+ assert settings.get("global.find-links", "").split() == [str(tmp_path), str(tmp_path)]
+ assert tv._pip_is_configured_offline() is True
+ monkeypatch.setenv("PIP_NO_INDEX", "0")
+ assert tv._pip_is_configured_offline() is False
+ source = open(tv.__file__, encoding = "utf-8").read()
+ assert "if _runtime_repair_is_offline() and not _pip_is_configured_offline():" in source
+
+
+def test_a_failed_install_keeps_a_tree_another_process_completed_meanwhile(tmp_path, monkeypatch):
+ """Two workers repairing one tier: the late cleanup of the failing one must not
+ delete the complete tree the other just finished."""
+ root = tmp_path / ".venv_t5_550"
+ root.mkdir()
+ verdicts = iter([False, True])
+ monkeypatch.setattr(tv, "_venv_dir_is_valid_and_undamaged", lambda *a, **k: next(verdicts))
+ monkeypatch.setattr(tv, "_install_to_dir", lambda pkg, target: False)
+ monkeypatch.delenv("UV_OFFLINE", raising = False)
+ assert tv._ensure_venv_dir(str(root), tv._VENV_T5_550_PACKAGES, "test sidecar") is True
+ assert root.is_dir()
+
+
+def test_a_failed_first_install_leaves_nothing_the_offline_guard_would_keep(tmp_path, monkeypatch):
+ """The owned marker lands before the first package; a first install that then fails
+ must not leave a marker-only or partial tree that the next offline call reads as a
+ tree worth keeping and never asks the cache for again."""
+ root = tmp_path / ".venv_t5_550"
+ monkeypatch.setattr(tv, "_venv_dir_is_valid_and_undamaged", lambda *a, **k: False)
+ monkeypatch.setattr(tv, "_install_to_dir", lambda pkg, target: False)
+ monkeypatch.setenv("UV_OFFLINE", "1")
+ assert tv._ensure_venv_dir(str(root), tv._VENV_T5_550_PACKAGES, "test sidecar") is False
+ assert not root.exists()
+ # The cache is populated now: the next call asks again instead of keeping a husk.
+ installed = []
+ monkeypatch.setattr(tv, "_install_to_dir", lambda pkg, target: installed.append(pkg) or True)
+ assert tv._ensure_venv_dir(str(root), tv._VENV_T5_550_PACKAGES, "test sidecar") is True
+ assert installed == list(tv._VENV_T5_550_PACKAGES)
+ # A marker-only directory is not content either.
+ root2 = tmp_path / "marker-only"
+ root2.mkdir()
+ (root2 / tv._STUDIO_OWNED_MARKER).write_text("", encoding = "utf-8")
+ assert tv._sidecar_has_content(str(root2)) is False
+ (root2 / "keep.txt").write_text("", encoding = "utf-8")
+ assert tv._sidecar_has_content(str(root2)) is True
def test_an_unlockable_filesystem_is_not_waited_out(tmp_path, monkeypatch) -> None:
"""A mount that cannot lock answers at once. Retrying it spent the whole 120 second
bound asleep inside a model activation, to arrive at the same answer."""
diff --git a/studio/backend/utils/transformers_version.py b/studio/backend/utils/transformers_version.py
index e08eb482368..6b6cd735ae0 100644
--- a/studio/backend/utils/transformers_version.py
+++ b/studio/backend/utils/transformers_version.py
@@ -2384,8 +2384,15 @@ def _install_to_dir(pkg: str, target_dir: str) -> bool:
)
if result.returncode == 0:
return True
- logger.warning("uv install of %s failed, falling back to pip", pkg)
-
+ logger.warning("uv install of %s failed", pkg)
+ if _runtime_repair_is_offline() and not _pip_is_configured_offline():
+ # pip has no offline mode: uv's cache is the only answer, unless pip was pointed at a local
+ # wheelhouse (PIP_NO_INDEX with PIP_FIND_LINKS), which an air-gapped install relies on.
+ logger.warning(
+ "%s not installed: the session is offline and pip would use the network", pkg
+ )
+ return False
+ logger.warning("installing %s with pip", pkg)
result = subprocess.run(
[
sys.executable,
@@ -2604,9 +2611,10 @@ def _top_up_optional_packages(venv_dir: str, packages: tuple[str, ...]) -> bool:
for it, then finds the package there.
"""
usable = True
- offline = (
- _env_offline() or os.environ.get("UV_OFFLINE", "").strip().lower() in _OFFLINE_TRUE_VALUES
- )
+ # Under UV_OFFLINE the install could only miss, and the miss would be remembered for hours.
+ # Unless pip has a local wheelhouse (the exception _install_to_dir makes): an air-gapped host
+ # never sees an online session.
+ offline = _env_offline() or (_runtime_repair_is_offline() and not _pip_is_configured_offline())
for pkg in packages:
if not _sidecar_package_is_optional(pkg):
continue
@@ -2720,20 +2728,14 @@ def _close_quietly(handle) -> None:
@contextlib.contextmanager
-def _optional_top_up_lock(venv_dir: str):
- """A cross-process lock on a sidecar's optional top-up, waited for up to a bound.
-
- Workers activate tiers independently, so two can find the package absent at once;
- two installers writing one --target tree leave it half-written, and a worker that
- went on without waiting would activate with the package still absent. Yields True
- when this process holds the lock, False when another kept it past the bound (or
- the lock cannot be taken at all, read as "someone else's turn" rather than a
- reason to write unguarded).
- """
+def _file_lock(path: str, wait_seconds: float):
+ """A cross-process lock on *path*, waited for up to *wait_seconds*. Yields True when
+ this process holds it, False when another kept it past the bound (or it cannot be
+ taken at all, read as "someone else's turn" rather than a reason to write unguarded)."""
handle = None
try:
- handle = open(os.path.join(venv_dir, _OPTIONAL_TOP_UP_LOCK), "a+b")
- deadline = time.monotonic() + _OPTIONAL_TOP_UP_WAIT_SECONDS
+ handle = open(path, "a+b")
+ deadline = time.monotonic() + wait_seconds
while True:
try:
if sys.platform == "win32":
@@ -2775,11 +2777,265 @@ def _optional_top_up_lock(venv_dir: str):
_close_quietly(handle)
+_REBUILD_LOCK_DIR = ".sidecar-locks"
+
+
+def _rebuild_lock_path(venv_dir: str) -> str:
+ """The tier's lock file, in a directory beside the sidecars rather than beside the
+ tier itself: the sidecar scans (and the tests' sibling listings) key on the tier's
+ name as a prefix, and a lock file has to stay once taken."""
+ base = venv_dir.rstrip("/\\")
+ parent, stem = os.path.split(base)
+ lock_dir = os.path.join(parent or ".", _REBUILD_LOCK_DIR)
+ try:
+ os.makedirs(lock_dir, exist_ok = True)
+ except OSError:
+ pass
+ return os.path.join(lock_dir, stem + ".lock")
+
+
+# A worker that finds another mid-rebuild waits rather than building a second copy.
+_REBUILD_WAIT_SECONDS = 15 * 60.0
+
+
+def _optional_top_up_lock(venv_dir: str):
+ """A cross-process lock on a sidecar's optional top-up, waited for up to a bound.
+
+ Workers activate tiers independently, so two can find the package absent at once;
+ two installers writing one --target tree leave it half-written, and a worker that
+ went on without waiting would activate with the package still absent. Yields True
+ when this process holds the lock, False when another kept it past the bound (or
+ the lock cannot be taken at all, read as "someone else's turn" rather than a
+ reason to write unguarded).
+ """
+ with _file_lock(
+ os.path.join(venv_dir, _OPTIONAL_TOP_UP_LOCK), _OPTIONAL_TOP_UP_WAIT_SECONDS
+ ) as held:
+ yield held
+
+
+_UV_OFFLINE_TRUE_VALUES = _OFFLINE_TRUE_VALUES | {"t", "y"}
+
+
+_PIP_TRUE_VALUES = frozenset({"1", "true", "t", "yes", "y", "on"})
+
+# pip's precedence: the environment (":env:" in `pip config list`) over [install] over [global].
+_PIP_SETTING_SCOPES = (":env:", "install", "global")
+
+
+def _pip_effective_settings() -> dict[str, str] | None:
+ """pip's own view of its configuration: `pip config list`, which merges the user,
+ site and global files (or PIP_CONFIG_FILE) with the environment the way the pip
+ fallback in _install_to_dir will read them. None when pip cannot answer, which is
+ also when that fallback has nothing to run."""
+ try:
+ result = subprocess.run(
+ [sys.executable, "-m", "pip", "config", "list"],
+ stdout = subprocess.PIPE,
+ stderr = subprocess.DEVNULL,
+ text = True,
+ encoding = "utf-8",
+ errors = "replace",
+ timeout = 60,
+ env = utf8_child_env(
+ get_hf_cache_paths().child_env(child_env_without_native_path_secret())
+ ),
+ **_windows_hidden_subprocess_kwargs(),
+ )
+ except (OSError, subprocess.SubprocessError):
+ return None
+ if result.returncode != 0:
+ return None
+ settings: dict[str, str] = {}
+ for line in result.stdout.splitlines():
+ key, sep, raw = line.partition("=")
+ if not sep:
+ continue
+ raw = raw.strip()
+ try:
+ value = ast.literal_eval(raw)
+ except (ValueError, SyntaxError):
+ value = raw.strip("'\"")
+ settings[key.strip()] = str(value)
+ return settings
+
+
+def _pip_setting(settings: dict[str, str], name: str) -> str | None:
+ for scope in _PIP_SETTING_SCOPES:
+ value = settings.get(f"{scope}.{name}")
+ if value is not None:
+ return value
+ return None
+
+
+def _is_local_wheelhouse_dir(entry: str) -> bool:
+ """A --find-links entry that can only hand pip local files: a directory, as a path
+ or a file:// URL. A URL is the network; a FILE (an HTML index) is parsed for links
+ and those may point at the network as well."""
+ lowered = entry.lower()
+ if lowered.startswith("file://"):
+ from urllib.parse import urlparse
+ from urllib.request import url2pathname
+
+ parsed = urlparse(entry)
+ path = parsed.path
+ # file://server/share is a UNC share: the host is part of the path.
+ if parsed.netloc and parsed.netloc.lower() != "localhost":
+ path = "//" + parsed.netloc + path
+ entry = url2pathname(path)
+ elif "://" in lowered:
+ return False
+ return os.path.isdir(os.path.expanduser(entry))
+
+
+def _pip_is_configured_offline() -> bool:
+ """pip told to ignore the index and read a LOCAL wheelhouse: `--no-index` with
+ `--find-links` naming only local directories (paths or file:// URLs), by pip's
+ effective configuration: its config files as well as the environment, since an
+ air-gapped host sets these in pip.conf as often as in PIP_* variables. Anything
+ else --find-links accepts could reach for the network under UV_OFFLINE: a URL is
+ fetched, and an HTML file is parsed for links that may be URLs."""
+ settings = _pip_effective_settings()
+ if settings is None:
+ settings = {}
+ for name, variable in (("no-index", "PIP_NO_INDEX"), ("find-links", "PIP_FIND_LINKS")):
+ if variable in os.environ:
+ settings[f":env:.{name}"] = os.environ[variable]
+ # pip's own boolean spellings (strtobool): 1/true/t/yes/y/on.
+ no_index = (_pip_setting(settings, "no-index") or "").strip().lower() in _PIP_TRUE_VALUES
+ if not no_index:
+ return False
+ entries = (_pip_setting(settings, "find-links") or "").split()
+ if not entries:
+ return False
+ return all(_is_local_wheelhouse_dir(entry) for entry in entries)
+
+
+def _runtime_repair_is_offline() -> bool:
+ """Whether a sidecar repair could only reach for a network the caller declared absent.
+
+ UV_OFFLINE is what `studio update` honours when it keeps a verified install and
+ leaves a stale sidecar for the next online update. Under it the repair below would
+ wipe a tree it cannot rebuild: uv refuses the network and _install_to_dir then falls
+ back to a pip that would use it, or fails after the deletion.
+
+ The HF offline switches (HF_HUB_OFFLINE, TRANSFORMERS_OFFLINE, an open
+ force_hf_offline window) are deliberately not read here: they turn off Hub model
+ access, not the package index the repair installs from, and the workers raise them
+ on their own when only the Hub is unreachable. Treating them as offline would leave
+ a damaged sidecar unrepaired and the tier unusable while PyPI answers.
+ """
+ # uv's boolish spellings, as setup.sh and setup.ps1 accept them: t and y count too.
+ return os.environ.get("UV_OFFLINE", "").strip().lower() in _UV_OFFLINE_TRUE_VALUES
+
+
+def _sidecar_has_content(venv_dir: str) -> bool:
+ """Whether a sidecar directory holds anything beyond the ownership marker.
+
+ The owned marker is written before the first package lands, so a directory holding
+ only it is a first install that has not happened yet, not a tree worth keeping.
+ """
+ try:
+ return any(name != _STUDIO_OWNED_MARKER for name in os.listdir(venv_dir))
+ except (FileNotFoundError, NotADirectoryError):
+ return False
+ except OSError:
+ # Unreadable is not empty: the caller's next move on "empty" is to delete the tree.
+ return True
+
+
+_OFFLINE_STAGING_SUFFIX = ".offline-staging-"
+_OFFLINE_RETIRED_SUFFIX = ".offline-old-"
+
+
+def _sidecar_siblings(venv_dir: str, suffix: str) -> list[str]:
+ """`<venv_dir><suffix>*` beside the sidecar, oldest first by modification time."""
+ base = venv_dir.rstrip("/\\")
+ parent, stem = os.path.split(base)
+ try:
+ names = os.listdir(parent or ".")
+ except OSError:
+ return []
+ # Exactly what _repair_offline_beside writes, `<stem><suffix><pid>`, and only with our marker:
+ # the callers delete or rename what this returns.
+ found = [
+ os.path.join(parent, n)
+ for n in names
+ if n.startswith(stem + suffix)
+ and n[len(stem + suffix) :].isdigit()
+ and os.path.isfile(os.path.join(parent, n, _STUDIO_OWNED_MARKER))
+ ]
+
+ def modified(path: str) -> float:
+ # Another worker can remove a sibling between the listing and this read.
+ try:
+ return os.path.getmtime(path)
+ except OSError:
+ return 0.0
+
+ return sorted(found, key = modified)
+
+
+def _recover_retired_sidecar(venv_dir: str) -> None:
+ """Put back a tree an interrupted offline swap left retired.
+
+ The swap renames the live tree aside and the staging tree into place; killed between
+ the two, it leaves the live path empty and the preserved tree next door. Read as a
+ first install, an offline call with a cold cache would then fail with a usable tree
+ a rename away. A live tree with content makes retired copies leftovers, and they go.
+ """
+ retired = _sidecar_siblings(venv_dir, _OFFLINE_RETIRED_SUFFIX)
+ if not retired:
+ return
+ if os.path.isdir(venv_dir) and _sidecar_has_content(venv_dir):
+ for old in retired:
+ shutil.rmtree(old, ignore_errors = True)
+ return
+ newest = retired[-1]
+ shutil.rmtree(venv_dir, ignore_errors = True)
+ try:
+ os.rename(newest, venv_dir)
+ logger.warning("restored %s from %s (an earlier swap was interrupted)", venv_dir, newest)
+ except OSError as exc:
+ logger.warning("could not restore %s from %s: %s", venv_dir, newest, exc)
+ return
+ for old in retired[:-1]:
+ shutil.rmtree(old, ignore_errors = True)
+
+
def _ensure_venv_dir(venv_dir: str, packages: tuple[str, ...], label: str) -> bool:
"""Ensure *venv_dir* exists with all *packages*. Install if missing."""
if _venv_dir_is_valid_and_undamaged(venv_dir, packages):
+ # A live tree with content makes retired copies leftovers to sweep.
+ _recover_retired_sidecar(venv_dir)
return _top_up_optional_packages(venv_dir, packages)
+ # One repair of a tier at a time across processes: two workers used to build into one directory
+ # at once, and the loser could delete the winner's finished tree (or, offline, race the
+ # two-rename swap). The second waits and takes the finished tree.
+ with _file_lock(_rebuild_lock_path(venv_dir), _REBUILD_WAIT_SECONDS) as held:
+ if not held:
+ # Another process is still building it: deferred, this activation goes without.
+ logger.warning(
+ "%s: the rebuild lock was not obtained; leaving the repair to the process holding it",
+ venv_dir,
+ )
+ return False
+ _recover_retired_sidecar(venv_dir)
+ if _venv_dir_is_valid_and_undamaged(venv_dir, packages):
+ logger.info("%s at %s was completed by another process", label, venv_dir)
+ return _top_up_optional_packages(venv_dir, packages)
+ # Only an in-place repair is refused offline: it starts by deleting a tree that may still
+ # serve. The replacement is built beside it from uv's cache (the pip fallback stays out) and
+ # swapped in whole.
+ if _runtime_repair_is_offline() and _sidecar_has_content(venv_dir):
+ return _repair_offline_beside(venv_dir, packages, label)
+ return _rebuild_venv_dir(venv_dir, packages, label)
+
+
+def _rebuild_venv_dir(venv_dir: str, packages: tuple[str, ...], label: str) -> bool:
+ """Wipe *venv_dir* and install every package into it; the caller holds the tier's lock."""
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
@@ -2811,11 +3067,80 @@ def _ensure_venv_dir(venv_dir: str, packages: tuple[str, ...], label: str) -> bo
(os.path.normcase(os.path.abspath(venv_dir)), pkg)
)
continue
+ # A partial tree left behind would count as usable next time and be kept offline. Unless
+ # another process rebuilt it meanwhile: a complete tree is the answer.
+ if _venv_dir_is_valid_and_undamaged(venv_dir, packages):
+ logger.info("%s at %s was completed by another process", label, venv_dir)
+ return True
+ shutil.rmtree(venv_dir, ignore_errors = True)
return False
logger.info("Installed %s to %s", label, venv_dir)
return True
+def _drop_offline_staging(staging: str) -> None:
+ """The staging tree and the per-process rebuild lock _ensure_venv_dir took for it."""
+ shutil.rmtree(staging, ignore_errors = True)
+ try:
+ os.unlink(_rebuild_lock_path(staging))
+ except OSError:
+ pass
+
+
+def _repair_offline_beside(venv_dir: str, packages: tuple[str, ...], label: str) -> bool:
+ """Rebuild *venv_dir* from uv's cache into a staging directory beside it and swap
+ only once every package landed; a cold cache leaves the tree exactly as it was."""
+ base = venv_dir.rstrip("/\\")
+ # Per process: a shared staging path would have one worker deleting the other's build.
+ staging = f"{base}{_OFFLINE_STAGING_SUFFIX}{os.getpid()}"
+ retired = f"{base}{_OFFLINE_RETIRED_SUFFIX}{os.getpid()}"
+ _drop_offline_staging(staging)
+ # Staging trees of processes long gone (a kill mid-build); an hour is beyond any build here.
+ for stale in _sidecar_siblings(venv_dir, _OFFLINE_STAGING_SUFFIX):
+ try:
+ if stale != staging and time.time() - os.path.getmtime(stale) > 3600:
+ shutil.rmtree(stale, ignore_errors = True)
+ except OSError:
+ pass
+ # An empty directory takes the ordinary path; a failure removes the staging tree.
+ if not _ensure_venv_dir(staging, packages, label):
+ _drop_offline_staging(staging)
+ logger.warning(
+ "%s not found or incomplete at %s, and this session is offline with no cached "
+ "copy to rebuild it from -- left as is until the next online update",
+ label,
+ venv_dir,
+ )
+ return False
+ # Right before the swap: only a tree passing the activation's own predicate replaces the live
+ # one.
+ if not _venv_dir_is_valid_and_undamaged(staging, packages):
+ _drop_offline_staging(staging)
+ logger.warning("the offline rebuild of %s did not validate; %s left as is", label, venv_dir)
+ return False
+ try:
+ shutil.rmtree(retired, ignore_errors = True)
+ os.rename(venv_dir, retired)
+ try:
+ os.rename(staging, venv_dir)
+ except OSError:
+ if not os.path.isdir(venv_dir) and os.path.isdir(retired):
+ os.rename(retired, venv_dir)
+ raise
+ except OSError as exc:
+ logger.warning("could not swap the offline rebuild of %s into %s: %s", label, venv_dir, exc)
+ _drop_offline_staging(staging)
+ return False
+ shutil.rmtree(retired, ignore_errors = True)
+ # The staging tree is live now; the lock taken for its build goes with the staging name.
+ try:
+ os.unlink(_rebuild_lock_path(staging))
+ except OSError:
+ pass
+ logger.info("Rebuilt %s at %s offline, from the cache", label, venv_dir)
+ return True
+
+
def _ensure_venv_t5_530_exists() -> bool:
"""Ensure .venv_t5_530/ exists with transformers 5.3.0."""
return _ensure_venv_dir(_VENV_T5_530_DIR, _VENV_T5_530_PACKAGES, "transformers 5.3.0")
diff --git a/studio/install_python_stack.py b/studio/install_python_stack.py
index b6ef88b5d81..a3c535a33d4 100644
--- a/studio/install_python_stack.py
+++ b/studio/install_python_stack.py
@@ -7361,8 +7361,12 @@ def _relaxed_pip_policy_env(cmd: "list[str]") -> "dict[str, str]":
def _uv_is_offline() -> bool:
- """True when uv has been told not to touch the network."""
- return os.environ.get("UV_OFFLINE", "").strip().lower() not in ("", "0", "false")
+ """True when uv has been told not to touch the network.
+
+ uv's own boolish set, as both setup scripts read it. `not in (0, false)` also read `off`
+ and `no` as offline, declining repairs with a message saying the opposite.
+ """
+ return os.environ.get("UV_OFFLINE", "").strip().lower() in ("1", "t", "true", "y", "yes", "on")
def _uv_staging_plan(name: str) -> "tuple[str, dict[str, str]] | None":
diff --git a/studio/setup.ps1 b/studio/setup.ps1
index 2a337dd59fe..a6dc272e683 100644
--- a/studio/setup.ps1
+++ b/studio/setup.ps1
@@ -159,6 +159,9 @@ if ($script:UnslothVerbose) {
$env:UNSLOTH_VERBOSE = '1'
}
$script:LlamaCppDegraded = $false
+# Set by the offline keep, read unconditionally by the sidecar and legacy-migration blocks:
+# initialised for Set-StrictMode and for a dot-sourced rerun in the same session.
+$script:OfflineFastPath = $false
$script:CudaToolkitReady = $false
$script:NvccPath = $null
$script:CudaToolkitRoot = $null
@@ -4679,6 +4682,23 @@ function Get-SetupUvExecutableVerdict {
}
}
+function Get-UvInstallDir {
+ # astral's destination priority. Shared with the probe below, so "where uv was put" and "where
+ # uv is looked for" cannot drift.
+ foreach ($candidate in @($env:UV_INSTALL_DIR, $env:UV_UNMANAGED_INSTALL, $env:XDG_BIN_HOME)) {
+ if ($candidate) { return $candidate }
+ }
+ # Only if Join-Path actually produced one: on a nonexistent drive it returns null under
+ # ErrorActionPreference Continue, and the inline original fell through to the home fallback.
+ if ($env:XDG_DATA_HOME) {
+ $fromData = Join-Path $env:XDG_DATA_HOME "../bin" -ErrorAction SilentlyContinue
+ if ($fromData) { return $fromData }
+ }
+ $userHome = if ($env:USERPROFILE) { $env:USERPROFILE } else { $HOME }
+ if (-not $userHome) { return $null }
+ return (Join-Path $userHome ".local\bin")
+}
+
function Install-UvFromPinnedRelease {
$arch = Get-UvHostArch
if (-not $UvPinnedAssets.ContainsKey($arch)) {
@@ -4690,18 +4710,10 @@ function Install-UvFromPinnedRelease {
# astral's destination priority, so an existing uv is replaced in place and the Get-Command
# probe after Refresh-Environment still finds it.
- $destDir = $null
- foreach ($candidate in @($env:UV_INSTALL_DIR, $env:UV_UNMANAGED_INSTALL, $env:XDG_BIN_HOME)) {
- if ($candidate) { $destDir = $candidate; break }
- }
- if (-not $destDir -and $env:XDG_DATA_HOME) { $destDir = Join-Path $env:XDG_DATA_HOME "../bin" }
+ $destDir = Get-UvInstallDir
if (-not $destDir) {
- $userHome = if ($env:USERPROFILE) { $env:USERPROFILE } else { $HOME }
- if (-not $userHome) {
- Write-Output "Could not determine a home directory to install uv into."
- return $false
- }
- $destDir = Join-Path $userHome ".local\bin"
+ Write-Output "Could not determine a home directory to install uv into."
+ return $false
}
# astral's sources in astral's order, each exclusive when set. UV_DOWNLOAD_URL (and its older
@@ -4828,6 +4840,11 @@ Assert-VenvActivated -VenvDir $VenvDir
$UseUv = $false
if (Get-Command uv -ErrorAction SilentlyContinue) {
$UseUv = $true
+} elseif ((Get-UvInstallDir) -and (Test-Path -LiteralPath (Join-Path (Get-UvInstallDir) "uv.exe"))) {
+ # Already installed, just not on this process's PATH. The install prepends the user registry
+ # PATH, which an update inheriting its parent's PATH never sees, so every update re-downloaded it.
+ $env:PATH = (Get-UvInstallDir) + ";" + $env:PATH
+ $UseUv = $true
} elseif (-not $StageRoot) {
substep "installing uv package manager..."
try {
@@ -4847,6 +4864,14 @@ if (Get-Command uv -ErrorAction SilentlyContinue) {
# Re-activate venv since Refresh-Environment rebuilds PATH from
# registry and drops the venv's Scripts directory
Enter-StudioVenv
+ # Refresh-Environment rebuilds PATH from the registry, where the user-PATH prepend does
+ # not always land (UV_NO_MODIFY_PATH, UV_UNMANAGED_INSTALL, a runner pinning its own
+ # environment). Without this the installing run falls back to pip and writes a manifest
+ # with no uv_version, which the next run rewrites.
+ $uvDir = Get-UvInstallDir
+ if ($uvDir -and (Test-Path -LiteralPath (Join-Path $uvDir "uv.exe"))) {
+ $env:PATH = $uvDir + ";" + $env:PATH
+ }
if (Get-Command uv -ErrorAction SilentlyContinue) { $UseUv = $true }
} catch { }
}
@@ -4926,39 +4951,60 @@ function Fast-Download {
# ── Check if Python deps need updating ──
# Compare installed package version against PyPI latest.
# Skip all Python dependency work if versions match (fast update path).
-$_PkgName = if ($env:STUDIO_PACKAGE_NAME) { $env:STUDIO_PACKAGE_NAME } else { "unsloth" }
-$SkipPythonDeps = $false
-
-if ($env:SKIP_STUDIO_BASE -ne "1" -and $env:STUDIO_LOCAL_INSTALL -ne "1") {
- # Only check when NOT called from install.ps1 (which just installed the package)
- $_InstalledVersionProbeExit = 1
- $InstalledVer = try {
- $_installedVersionOutput = & python -c "
-import sys
-sys.path.insert(0, sys.argv[2])
-import install_manifest
-version, conflict = install_manifest.installed_version_probe(sys.argv[1], ('unsloth-zoo',))
-print(version)
-sys.exit(2 if conflict else (0 if version else 1))
-" $_PkgName $PSScriptRoot 2>$null
- $_InstalledVersionProbeExit = $LASTEXITCODE
- ($_installedVersionOutput | Out-String).Trim()
- } catch { "" }
- $LatestVer = ""
+# Does the venv prove a finished install? One implementation for the incomplete-install guard
+# and the offline rule, so they cannot disagree about "complete".
+function Test-StudioInstallVerified {
try {
- $pypiJson = Invoke-RestMethod -Uri "https://pypi.org/pypi/$_PkgName/json" -TimeoutSec 5 -ErrorAction Stop
- $LatestVer = "$($pypiJson.info.version)".Trim()
- } catch { }
+ & python -c "
+import os, sys
+sys.path.insert(0, sys.argv[1])
+try:
+ import install_manifest
+except Exception:
+ # Present but unimportable is damage, not an old release, and this is the
+ # one file whose damage silences every check below. Absent keeps the old
+ # escape: separating it from an old tree needs a RECORD walk here, and the
+ # CLI already reports studio_install_manifest_missing.
+ sys.exit(1 if os.path.isfile(os.path.join(sys.argv[1], 'install_manifest.py')) else 0)
+import inspect
+# Only skip the payload scan on a tree too old to offer it. Catching TypeError instead
+# also swallowed one raised inside verify_install, and retried shallow on real damage.
+deep = {'deep': True} if 'deep' in inspect.signature(install_manifest.verify_install).parameters else {}
+sys.exit(0 if install_manifest.verify_install(**deep)['ok'] else 1)
+" "$PSScriptRoot" 2>$null | Out-Null
+ # Out-Null, not just 2>$null: an unassigned native call leaves stdout in the
+ # success stream, so `return $false` came back as @("...", $false), which is truthy.
+ return ($LASTEXITCODE -eq 0)
+ } catch { return $false }
+}
- if ($_InstalledVersionProbeExit -eq 2) {
- substep "duplicate metadata found for a core package -- forcing package repair..." "Cyan"
- } elseif ($InstalledVer -and $LatestVer -and ($InstalledVer -eq $LatestVer)) {
- step "python" "$_PkgName $InstalledVer is up to date"
- $SkipPythonDeps = $true
- # A pre-#6483 install stuck on anyio>=4.14 would skip the repair (#6797), so force it.
- $_anyioBad = $false
- try {
- & python -c "
+# UV_OFFLINE is uv's own "no network" switch, and every install here goes through uv.
+function Test-UvOfflineRequested {
+ # uv's boolish parser (uv 0.10.7): y, yes, t, true, on, 1. Mirrors _uv_offline_requested.
+ $value = "$($env:UV_OFFLINE)".Trim()
+ return @('1', 't', 'true', 'y', 'yes', 'on') -contains $value.ToLowerInvariant()
+}
+
+function Invoke-FastPathEscapes {
+ # Every reason an "up to date" package is still not a working install. Both fast-path callers
+ # run it, so an offline skip meets the online bar. Test-StudioInstallVerified and the AMD/ROCm
+ # probe stay out: each caller words them differently. A plain assignment in a function is LOCAL,
+ # so the flag is copied in and published once on the way out.
+ $SkipPythonDeps = $script:SkipPythonDeps
+
+ # The documented escape hatch, first: install_python_stack.py honours
+ # UNSLOTH_STUDIO_FULL_DEPS but never runs once the version compare skips, so it did nothing
+ # for exactly the up-to-date broken install it exists for.
+ $_fullDepsRequested = "$($env:UNSLOTH_STUDIO_FULL_DEPS)".Trim()
+ if (@('1', 'true', 'yes', 'on') -contains $_fullDepsRequested.ToLowerInvariant()) {
+ substep "UNSLOTH_STUDIO_FULL_DEPS is set -- forcing dependency pass..." "Cyan"
+ $SkipPythonDeps = $false
+ }
+
+ # A pre-#6483 install stuck on anyio>=4.14 would skip the repair (#6797), so force it.
+ $_anyioBad = $false
+ try {
+ & python -c "
import re, sys
from importlib.metadata import version, PackageNotFoundError
try:
@@ -4969,22 +5015,17 @@ except (PackageNotFoundError, ValueError, IndexError):
sys.exit(1)
sys.exit(0 if (major, minor) >= (4, 14) else 1)
" 2>$null
- if ($LASTEXITCODE -eq 0) { $_anyioBad = $true }
- } catch {}
- if ($_anyioBad) {
- substep "anyio >=4.14 found (#6483) -- forcing dependency pass to repair..." "Cyan"
- $SkipPythonDeps = $false
- }
- # Same shape, same reason, and the sibling of the probe setup.sh runs: a venv
- # installed before the tokenizers pin can hold a tokenizers the installed
- # transformers rejects at import, which takes down every `import transformers`
- # and so the whole model stack, while $_PkgName itself is current. Without this
- # the fast path reports "up to date" and repairs nothing. Ask the metadata, not
- # an import: the import is what is broken. Any unreadable half exits 1 and
- # changes nothing.
- $_tokenizersBad = $false
- try {
- & python -c "
+ if ($LASTEXITCODE -eq 0) { $_anyioBad = $true }
+ } catch {}
+ if ($_anyioBad) {
+ substep "anyio >=4.14 found (#6483) -- forcing dependency pass to repair..." "Cyan"
+ $SkipPythonDeps = $false
+ }
+ # As setup.sh: a pre-pin tokenizers the installed transformers rejects breaks every `import
+ # transformers` while $_PkgName is current. Ask the metadata, not the broken import.
+ $_tokenizersBad = $false
+ try {
+ & python -c "
import sys
from importlib.metadata import PackageNotFoundError, requires, version
try:
@@ -4999,46 +5040,20 @@ except (PackageNotFoundError, ImportError, ValueError, IndexError):
sys.exit(1)
sys.exit(0 if windows and installed not in windows[0] else 1)
" 2>$null
- if ($LASTEXITCODE -eq 0) { $_tokenizersBad = $true }
- } catch {}
- if ($_tokenizersBad) {
- substep "installed transformers rejects the installed tokenizers -- forcing dependency pass to repair..." "Cyan"
- $SkipPythonDeps = $false
- }
- # An interrupted install leaves $_PkgName current while studio.txt
- # never finished, so the compare above says "up to date" and update --
- # plus the desktop Repair button -- no-ops on a venv that cannot boot.
- $_studioInstallIncomplete = $false
+ if ($LASTEXITCODE -eq 0) { $_tokenizersBad = $true }
+ } catch {}
+ if ($_tokenizersBad) {
+ substep "installed transformers rejects the installed tokenizers -- forcing dependency pass to repair..." "Cyan"
+ $SkipPythonDeps = $false
+ }
+ # If the desktop app specifies a minimum required backend version and the installed
+ # package is older than that requirement, force the dependency pass to upgrade it.
+ if ($env:UNSLOTH_DESKTOP_BACKEND_VERSION) {
+ # Cleared only on a confirmed exit 0, mirroring setup.sh's `if !`: an invocation that
+ # throws left it false, so an install under the floor kept the fast path.
+ $_desktopVerBad = $true
try {
& python -c "
-import os, sys
-sys.path.insert(0, sys.argv[1])
-try:
- import install_manifest
-except Exception:
- # Present but unimportable is damage, not an old release, and this is the
- # one file whose damage silences every check below. Absent keeps the old
- # escape: separating it from an old tree needs a RECORD walk here, and the
- # CLI already reports studio_install_manifest_missing.
- sys.exit(1 if os.path.isfile(os.path.join(sys.argv[1], 'install_manifest.py')) else 0)
-try:
- ok = install_manifest.verify_install(deep = True)['ok']
-except TypeError:
- ok = install_manifest.verify_install()['ok'] # older tree, no payload scan
-sys.exit(0 if ok else 1)
-" "$PSScriptRoot" 2>$null
- if ($LASTEXITCODE -ne 0) { $_studioInstallIncomplete = $true }
- } catch {}
- if ($_studioInstallIncomplete) {
- substep "studio install incomplete -- forcing dependency pass to repair..." "Cyan"
- $SkipPythonDeps = $false
- }
- # If the desktop app specifies a minimum required backend version and the installed
- # package is older than that requirement, force the dependency pass to upgrade it.
- if ($env:UNSLOTH_DESKTOP_BACKEND_VERSION) {
- $_desktopVerBad = $false
- try {
- & python -c "
import re, sys
try:
from packaging.version import parse as parse_v
@@ -5049,14 +5064,119 @@ except ImportError:
installed = parse_v(sys.argv[1])
required = parse_v(sys.argv[2])
sys.exit(0 if installed is not None and required is not None and installed >= required else 1)
-" "$InstalledVer" "$env:UNSLOTH_DESKTOP_BACKEND_VERSION" 2>$null
- if ($LASTEXITCODE -ne 0) { $_desktopVerBad = $true }
- } catch {}
- if ($_desktopVerBad) {
- substep "$_PkgName $InstalledVer < $env:UNSLOTH_DESKTOP_BACKEND_VERSION (required by desktop app) -- forcing dependency pass to update..." "Cyan"
+" "$InstalledVer" "$env:UNSLOTH_DESKTOP_BACKEND_VERSION" 2>$null | Out-Null
+ if ($LASTEXITCODE -eq 0) { $_desktopVerBad = $false }
+ } catch {}
+ if ($_desktopVerBad) {
+ substep "$_PkgName $InstalledVer < $env:UNSLOTH_DESKTOP_BACKEND_VERSION (required by desktop app) -- forcing dependency pass to update..." "Cyan"
+ $SkipPythonDeps = $false
+ }
+ }
+ # ...and for an Intel GPU, or a CPU wheel stays forever. Both escapes reach the XPU install,
+ # gated on $XpuIndexUrl, so $_xpuIsReachable holds them back where a pin or no-torch mode
+ # sends this host elsewhere and they would re-fire forever.
+ $_pinLeafNow = Get-TorchIndexLeaf (Get-PinnedTorchIndexUrl)
+ $_xpuIsReachable = (-not $NoTorchMode) -and ((-not $_pinLeafNow) -or ($_pinLeafNow -eq "xpu"))
+ if ($script:IsIntelXpu -and $SkipPythonDeps -and $_xpuIsReachable) {
+ # The WHEEL, not the runtime: a wedged driver also fails torch.xpu.is_available(), and the
+ # pass cannot repair a driver.
+ if (-not (Test-VenvTorchIsXpuSupported -VenvPath $VenvDir)) {
+ substep "Intel GPU detected but installed PyTorch is not a supported XPU build -- reinstalling XPU PyTorch" "Cyan"
+ $SkipPythonDeps = $false
+ }
+ }
+ # The installed wheel as well as the scan: an explicit xpu pin on a mixed NVIDIA + Intel box
+ # ends up on XPU with $script:IsIntelXpu false, fast-pathing past the bitsandbytes floor and
+ # the Triton replacement forever.
+ if ($SkipPythonDeps -and $_xpuIsReachable -and ($script:IsIntelXpu -or $installedTorchTag -eq "xpu")) {
+ $_xpuDepsCode = "import importlib.metadata as m; " +
+ "print('BNB=' + next((d.version for d in m.distributions() " +
+ "if (d.metadata['Name'] or '').lower() == 'bitsandbytes'), '')); " +
+ "print('TRITONWIN=' + next((d.version for d in m.distributions() " +
+ "if (d.metadata['Name'] or '').lower().replace('_','-') == 'triton-windows'), ''))"
+ $_xpuDeps = Invoke-BoundedPythonProbe -PythonExe "python" -Code $_xpuDepsCode
+ if (-not $_xpuDeps.Ok) {
+ # A probe that did not answer is not "current": one extra pass, as for an unparseable
+ # version.
+ substep "Intel XPU dependencies could not be read -- running the dependency pass" "Cyan"
+ $SkipPythonDeps = $false
+ } else {
+ $_bnbVer = if ($_xpuDeps.Output -match '(?m)^BNB=(\S+)\s*$') { $Matches[1] } else { "" }
+ # Unreadable is stale, the safe direction. Trailing suffixes (0.51.0.dev0) are dropped.
+ $_bnbNum = ($_bnbVer -replace '[^0-9.].*$', '').TrimEnd('.')
+ $_bnbStale = $true
+ if ($_bnbNum -match '^\d+\.\d+') {
+ try { $_bnbStale = [version]$_bnbNum -lt [version]"0.50.0" } catch {}
+ }
+ $_tritonWinPresent = $_xpuDeps.Output -match '(?m)^TRITONWIN=\S+\s*$'
+ if ($_bnbStale -or $_tritonWinPresent) {
+ substep "Intel XPU dependencies are stale -- running the dependency pass" "Cyan"
$SkipPythonDeps = $false
}
}
+ }
+
+ $script:SkipPythonDeps = $SkipPythonDeps
+}
+
+$_PkgName = if ($env:STUDIO_PACKAGE_NAME) { $env:STUDIO_PACKAGE_NAME } else { "unsloth" }
+$SkipPythonDeps = $false
+
+if ($env:SKIP_STUDIO_BASE -ne "1" -and $env:STUDIO_LOCAL_INSTALL -ne "1") {
+ # Only check when NOT called from install.ps1 (which just installed the package)
+ $_InstalledVersionProbeExit = 1
+ $InstalledVer = try {
+ $_installedVersionOutput = & python -c "
+import sys
+sys.path.insert(0, sys.argv[2])
+import install_manifest
+version, conflict = install_manifest.installed_version_probe(sys.argv[1], ('unsloth-zoo',))
+print(version)
+sys.exit(2 if conflict else (0 if version else 1))
+" $_PkgName $PSScriptRoot 2>$null
+ $_InstalledVersionProbeExit = $LASTEXITCODE
+ ($_installedVersionOutput | Out-String).Trim()
+ } catch { "" }
+ $LatestVer = ""
+ try {
+ $pypiJson = Invoke-RestMethod -Uri "https://pypi.org/pypi/$_PkgName/json" -TimeoutSec 5 -ErrorAction Stop
+ $LatestVer = "$($pypiJson.info.version)".Trim()
+ } catch { }
+
+ if ($_InstalledVersionProbeExit -eq 2) {
+ substep "duplicate metadata found for a core package -- forcing package repair..." "Cyan"
+ } elseif ($InstalledVer -and $LatestVer -and ($InstalledVer -eq $LatestVer)) {
+ step "python" "$_PkgName $InstalledVer is up to date"
+ $SkipPythonDeps = $true
+ # An interrupted install leaves $_PkgName current while studio.txt never finished, so update
+ # and the Repair button no-op on a venv that cannot boot.
+ $_studioInstallIncomplete = -not (Test-StudioInstallVerified)
+ if ($_studioInstallIncomplete) {
+ substep "studio install incomplete -- forcing dependency pass to repair..." "Cyan"
+ $SkipPythonDeps = $false
+ }
+ # ...and every remaining escape, shared with the offline rule below.
+ Invoke-FastPathEscapes
+ } elseif ($InstalledVer -and $LatestVer) {
+ substep "$_PkgName $InstalledVer -> $LatestVer available, updating..."
+ } elseif (-not $LatestVer) {
+ # PyPI unreachable: updating to be safe stays the default, since it is usually a blip.
+ # UV_OFFLINE is not a blip, so a verified tree is kept instead, on the incomplete-install
+ # guard's evidence and held to the up-to-date branch's escapes (it can still be below the
+ # floor).
+ if ($InstalledVer -and (Test-UvOfflineRequested) -and (Test-StudioInstallVerified)) {
+ substep "PyPI is unreachable and UV_OFFLINE is set -- keeping the verified install"
+ $SkipPythonDeps = $true
+ $script:OfflineFastPath = $true
+ Invoke-FastPathEscapes
+ } else {
+ substep "could not reach PyPI, updating to be safe..."
+ }
+ }
+
+ # A current package can still have CPU torch on an AMD host. After the chain and gated on the
+ # flag, as setup.sh keeps it, so it covers the UV_OFFLINE branch too.
+ if ($SkipPythonDeps) {
# ...but not if an AMD GPU is present and installed PyTorch is CPU-only
# (host predates ROCm-wheel support, or GPU added later): the fast "up to
# date" path would leave the user on CPU torch with Train/Export disabled.
@@ -5076,61 +5196,6 @@ sys.exit(0 if installed is not None and required is not None and installed >= re
$SkipPythonDeps = $false
}
}
- # ...and the same for an Intel Arc / Data Center GPU, or an up-to-date package on a CPU
- # wheel stays on CPU torch forever. $SkipPythonDeps is re-tested so an escape taken above
- # does not read twice. Both escapes below exist to reach the XPU install and its two
- # remediations, all three gated on $XpuIndexUrl (set only when the resolved leaf is xpu),
- # so $_xpuIsReachable holds them back where a pin or no-torch mode sends this host
- # elsewhere and clearing the fast path would install nothing and re-fire forever.
- $_pinLeafNow = Get-TorchIndexLeaf (Get-PinnedTorchIndexUrl)
- $_xpuIsReachable = (-not $NoTorchMode) -and ((-not $_pinLeafNow) -or ($_pinLeafNow -eq "xpu"))
- if ($script:IsIntelXpu -and $SkipPythonDeps -and $_xpuIsReachable) {
- # The WHEEL, not the runtime: torch.xpu.is_available() is also false for a supported
- # +xpu wheel on a wedged driver, and the dependency pass cannot repair a driver, so
- # keying on it would force a full resolution every update for nothing.
- if (-not (Test-VenvTorchIsXpuSupported -VenvPath $VenvDir)) {
- substep "Intel GPU detected but installed PyTorch is not a supported XPU build -- reinstalling XPU PyTorch" "Cyan"
- $SkipPythonDeps = $false
- }
- }
- # Keyed off the installed wheel as well as the scan: an explicit xpu pin on a host the
- # scan skips (a mixed NVIDIA + Intel box) still ends up on XPU with $script:IsIntelXpu
- # false. The bitsandbytes floor and the Triton replacement live in the dependency pass
- # below, so a venv that reached +xpu without them would fast-path past them forever.
- if ($SkipPythonDeps -and $_xpuIsReachable -and ($script:IsIntelXpu -or $installedTorchTag -eq "xpu")) {
- $_xpuDepsCode = "import importlib.metadata as m; " +
- "print('BNB=' + next((d.version for d in m.distributions() " +
- "if (d.metadata['Name'] or '').lower() == 'bitsandbytes'), '')); " +
- "print('TRITONWIN=' + next((d.version for d in m.distributions() " +
- "if (d.metadata['Name'] or '').lower().replace('_','-') == 'triton-windows'), ''))"
- $_xpuDeps = Invoke-BoundedPythonProbe -PythonExe "python" -Code $_xpuDepsCode
- if (-not $_xpuDeps.Ok) {
- # A probe that did not answer says nothing about the venv, and reading that as
- # "dependencies are current" would fast-path past both remediations forever.
- # Same direction as an unparseable version below: one extra pass.
- substep "Intel XPU dependencies could not be read -- running the dependency pass" "Cyan"
- $SkipPythonDeps = $false
- } else {
- $_bnbVer = if ($_xpuDeps.Output -match '(?m)^BNB=(\S+)\s*$') { $Matches[1] } else { "" }
- # An unreadable version is treated as stale, the safe direction: one extra pass,
- # never a venv left without 4-bit kernels. Trailing suffixes (0.51.0.dev0) are
- # dropped, not cast.
- $_bnbNum = ($_bnbVer -replace '[^0-9.].*$', '').TrimEnd('.')
- $_bnbStale = $true
- if ($_bnbNum -match '^\d+\.\d+') {
- try { $_bnbStale = [version]$_bnbNum -lt [version]"0.50.0" } catch {}
- }
- $_tritonWinPresent = $_xpuDeps.Output -match '(?m)^TRITONWIN=\S+\s*$'
- if ($_bnbStale -or $_tritonWinPresent) {
- substep "Intel XPU dependencies are stale -- running the dependency pass" "Cyan"
- $SkipPythonDeps = $false
- }
- }
- }
- } elseif ($InstalledVer -and $LatestVer) {
- substep "$_PkgName $InstalledVer -> $LatestVer available, updating..."
- } elseif (-not $LatestVer) {
- substep "could not reach PyPI, updating to be safe..."
}
}
@@ -5903,6 +5968,11 @@ function Repair-SidecarTiktoken {
[Parameter(Mandatory = $true)][string]$TargetDir,
[Parameter(Mandatory = $true)][string]$DirName
)
+ # Under the offline keep this would reach the network through Fast-Install's pip fallback, and
+ # give a deferred tier a directory holding tiktoken alone.
+ if ($script:OfflineFastPath) { return }
+ # And under UV_OFFLINE without the fast path: the pip fallback would reach for the network.
+ if (Test-UvOfflineRequested) { return }
# Payload AND dist-info (RECORD is written last): an interrupted install leaves one without the
# other. A recordless dist-info goes first; uv cannot uninstall it, metadata still reads it.
Get-ChildItem -LiteralPath $TargetDir -Directory -Filter "tiktoken-*.dist-info" -ErrorAction SilentlyContinue |
@@ -6028,7 +6098,11 @@ function Install-T5Sidecar {
$_NeedT5_530 = $false
$_NeedT5_550 = $false
$_NeedT5_510 = $false
-if (Test-Path -LiteralPath $VenvT5Legacy) {
+# The migration is a wipe and three rebuilds from a cache that may be cold, and the legacy tree is
+# the only sidecar, so under UV_OFFLINE it waits for the next online update.
+if ((Test-Path -LiteralPath $VenvT5Legacy) -and ($script:OfflineFastPath -or (Test-UvOfflineRequested))) {
+ substep "legacy transformers sidecar left in place -- UV_OFFLINE is set, migration waits for the next online update" "Yellow"
+} elseif (Test-Path -LiteralPath $VenvT5Legacy) {
# Legacy layout. A staged run's venvs may never be activated, so only the live update migrates.
if (-not $StageRoot) {
Assert-StudioOwnedOrAbsent -Path $VenvT5Legacy -Label "legacy transformers sidecar venv"
@@ -6041,6 +6115,35 @@ if (Test-Path -LiteralPath $VenvT5Legacy) {
if (-not (Test-SidecarCurrent -TargetDir $VenvT5_530Dir -Version "5.3.0")) { $_NeedT5_530 = $true }
if (-not (Test-SidecarCurrent -TargetDir $VenvT5_550Dir -Version "5.5.0")) { $_NeedT5_550 = $true }
if (-not (Test-SidecarCurrent -TargetDir $VenvT5_510Dir -Version "5.10.2")) { $_NeedT5_510 = $true }
+# A sidecar rebuild is a wipe and four fetches, through a pip fallback that reaches the network,
+# so under the offline keep it waits for the next online update; the runtime self-heal covers a
+# missing tier meanwhile. Mirrors setup.sh. A deferred tier keeps its own flag so it is not
+# reported "current".
+$_DeferT5_530 = $false
+$_DeferT5_550 = $false
+$_DeferT5_510 = $false
+# UV_OFFLINE without the fast path: the same wipe and fetches, through a pip fallback that does not
+# read UV_OFFLINE. Every stale or missing tier is left for the next online update.
+if (-not $script:OfflineFastPath -and (Test-UvOfflineRequested)) {
+ foreach ($tier in @(@("530", "5.3.0"), @("550", "5.5.0"), @("510", "5.10.2"))) {
+ $flag = "_NeedT5_$($tier[0])"
+ if ((Get-Variable -Name $flag -ValueOnly)) {
+ substep "transformers $($tier[1]) sidecar is stale or missing but UV_OFFLINE is set -- left for the next online update" "Yellow"
+ Set-Variable -Name $flag -Value $false
+ Set-Variable -Name "_DeferT5_$($tier[0])" -Value $true
+ }
+ }
+}
+if ($script:OfflineFastPath) {
+ foreach ($tier in @(@("530", "5.3.0"), @("550", "5.5.0"), @("510", "5.10.2"))) {
+ $flag = "_NeedT5_$($tier[0])"
+ if ((Get-Variable -Name $flag -ValueOnly)) {
+ substep "transformers $($tier[1]) sidecar is stale but UV_OFFLINE is set -- left for the next online update" "Yellow"
+ Set-Variable -Name $flag -Value $false
+ Set-Variable -Name "_DeferT5_$($tier[0])" -Value $true
+ }
+ }
+}
if ($_NeedT5_530 -or $_NeedT5_550 -or $_NeedT5_510) {
Write-StudioLine ""
@@ -6051,18 +6154,24 @@ $ErrorActionPreference = "Continue"
if ($_NeedT5_530) {
Install-T5Sidecar -TargetDir $VenvT5_530Dir -Version "5.3.0" -Label "5.3" -DirName ".venv_t5_530" -Reason "for newer model support"
+} elseif ($_DeferT5_530) {
+ step "transformers" "5.3.0 sidecar stale -- left for the next online update"
} else {
step "transformers" "5.3.0 sidecar current"
Repair-SidecarTiktoken -TargetDir $VenvT5_530Dir -DirName ".venv_t5_530"
}
if ($_NeedT5_550) {
Install-T5Sidecar -TargetDir $VenvT5_550Dir -Version "5.5.0" -Label "5.5" -DirName ".venv_t5_550" -Reason "for Gemma 4 support"
+} elseif ($_DeferT5_550) {
+ step "transformers" "5.5.0 sidecar stale -- left for the next online update"
} else {
step "transformers" "5.5.0 sidecar current"
Repair-SidecarTiktoken -TargetDir $VenvT5_550Dir -DirName ".venv_t5_550"
}
if ($_NeedT5_510) {
Install-T5Sidecar -TargetDir $VenvT5_510Dir -Version "5.10.2" -Label "5.10" -DirName ".venv_t5_510" -Reason "for Gemma 4 Unified support"
+} elseif ($_DeferT5_510) {
+ step "transformers" "5.10.2 sidecar stale -- left for the next online update"
} else {
step "transformers" "5.10.2 sidecar current"
Repair-SidecarTiktoken -TargetDir $VenvT5_510Dir -DirName ".venv_t5_510"
diff --git a/studio/setup.sh b/studio/setup.sh
index a493fd389f9..08287c89094 100755
--- a/studio/setup.sh
+++ b/studio/setup.sh
@@ -1838,42 +1838,62 @@ fi
# Skip all Python dependency work if versions match (fast update path).
# On Colab (no venv), skip this version check (it needs $VENV_DIR/bin/python)
# but still run install_python_stack below (it uses sys.executable).
-_SKIP_PYTHON_DEPS=false
-_SKIP_VERSION_CHECK=false
-if [ "$_COLAB_NO_VENV" = true ]; then
- _SKIP_VERSION_CHECK=true
-fi
-_PKG_NAME="${STUDIO_PACKAGE_NAME:-unsloth}"
-if [ "$_SKIP_VERSION_CHECK" != true ] && [ "${SKIP_STUDIO_BASE:-0}" != "1" ] && [ "${STUDIO_LOCAL_INSTALL:-0}" != "1" ]; then
- # Only check when NOT called from install.sh (which just installed the package)
- _INSTALLED_VERSION_PROBE_EXIT=0
- if INSTALLED_VER=$("$VENV_DIR/bin/python" -c "
-import sys
-sys.path.insert(0, sys.argv[2])
-import install_manifest
-version, conflict = install_manifest.installed_version_probe(sys.argv[1], ('unsloth-zoo',))
-print(version)
-sys.exit(2 if conflict else (0 if version else 1))
-" "$_PKG_NAME" "$SCRIPT_DIR" 2>/dev/null); then
- :
- else
- _INSTALLED_VERSION_PROBE_EXIT=$?
- INSTALLED_VER=""
- fi
+_setup_install_is_verified() {
+ # Does the venv prove a finished install? Exit 0 yes, 1 no. One implementation for the
+ # incomplete-install guard and the offline rule, so they cannot disagree about "complete".
+ "$VENV_DIR/bin/python" -c "
+import os, sys
+sys.path.insert(0, sys.argv[1])
+try:
+ import install_manifest
+except Exception:
+ # Present but unimportable is damage, not an old release, and this is the
+ # one file whose damage silences every check below. Absent keeps the old
+ # escape: separating it from an old tree needs a RECORD walk here, and the
+ # CLI already reports studio_install_manifest_missing.
+ sys.exit(1 if os.path.isfile(os.path.join(sys.argv[1], 'install_manifest.py')) else 0)
+import inspect
+# Only skip the payload scan on a tree too old to offer it. Catching TypeError instead
+# also swallowed one raised inside verify_install, and retried shallow on real damage.
+deep = {'deep': True} if 'deep' in inspect.signature(install_manifest.verify_install).parameters else {}
+sys.exit(0 if install_manifest.verify_install(**deep)['ok'] else 1)
+" "$SCRIPT_DIR" 2>/dev/null
+}
+
+_uv_offline_requested() {
+ # UV_OFFLINE is uv's own "no network" switch, and every install here goes through uv. uv's
+ # boolish spellings (uv 0.10.7): y, yes, t, true, on, 1.
+ _uvo=${UV_OFFLINE:-}
+ _uvo=${_uvo#"${_uvo%%[![:space:]]*}"}
+ _uvo=${_uvo%"${_uvo##*[![:space:]]}"}
+ case "$_uvo" in
+ 1 | [Tt] | [Tt][Rr][Uu][Ee] | [Yy] | [Yy][Ee][Ss] | [Oo][Nn]) unset _uvo; return 0 ;;
+ esac
+ unset _uvo
+ return 1
+}
- LATEST_VER=$(_setup_http_get_timed "https://pypi.org/pypi/$_PKG_NAME/json" 2>/dev/null \
- | "$VENV_DIR/bin/python" -c "import sys,json; print(json.load(sys.stdin)['info']['version'])" 2>/dev/null \
- || echo "")
+_fast_path_escapes() {
+ # Every reason an "up to date" package is still not a working install. Both fast-path
+ # callers run it, so an offline skip meets the online bar. The incomplete-install check
+ # stays out: each caller words it differently.
+
+ # First, costing no probe: the user asked by hand. This branch never starts
+ # install_python_stack.py, whose hatch this is, so the variable did nothing here. Values are
+ # that module's ("1", "true", "yes", "on"), NOT _uv_offline_requested's bare `t` and `y`.
+ _fpe_full=${UNSLOTH_STUDIO_FULL_DEPS:-}
+ _fpe_full=${_fpe_full#"${_fpe_full%%[![:space:]]*}"}
+ _fpe_full=${_fpe_full%"${_fpe_full##*[![:space:]]}"}
+ case "$_fpe_full" in
+ 1 | [Tt][Rr][Uu][Ee] | [Yy][Ee][Ss] | [Oo][Nn])
+ substep "UNSLOTH_STUDIO_FULL_DEPS is set -- forcing dependency pass..."
+ _SKIP_PYTHON_DEPS=false
+ ;;
+ esac
+ unset _fpe_full
- if [ "$_INSTALLED_VERSION_PROBE_EXIT" -eq 2 ]; then
- substep "duplicate metadata found for a core package -- forcing package repair..."
- elif [ -n "$INSTALLED_VER" ] && [ -n "$LATEST_VER" ] && [ "$INSTALLED_VER" = "$LATEST_VER" ]; then
- step "python" "$_PKG_NAME $INSTALLED_VER is up to date"
- _SKIP_PYTHON_DEPS=true
- # A pre-#6483-fix install can be stuck on anyio>=4.14 even though
- # $_PKG_NAME itself is current; the fast path above would otherwise
- # never reach install_python_stack's anyio repair (#6797).
- if "$VENV_DIR/bin/python" -c "
+ # A pre-#6483 install stuck on anyio>=4.14 would never reach the anyio repair (#6797).
+ if "$VENV_DIR/bin/python" -c "
import re, sys
from importlib.metadata import version, PackageNotFoundError
try:
@@ -1884,16 +1904,12 @@ except (PackageNotFoundError, ValueError, IndexError):
sys.exit(1)
sys.exit(0 if (major, minor) >= (4, 14) else 1)
" 2>/dev/null; then
- substep "anyio >=4.14 found (#6483) -- forcing dependency pass to repair..."
- _SKIP_PYTHON_DEPS=false
- fi
- # Same shape, same reason: a venv installed before the tokenizers pin can
- # hold a tokenizers the installed transformers rejects at import, which
- # takes down every `import transformers` and so the whole MLX stack, while
- # $_PKG_NAME itself is current. Without this the fast path reports "up to
- # date" and repairs nothing. Ask the metadata, not an import: the import is
- # what is broken. Any unreadable half exits 1 and changes nothing.
- if "$VENV_DIR/bin/python" -c "
+ substep "anyio >=4.14 found (#6483) -- forcing dependency pass to repair..."
+ _SKIP_PYTHON_DEPS=false
+ fi
+ # Same shape: a pre-pin tokenizers the installed transformers rejects breaks every `import
+ # transformers` while $_PKG_NAME is current. Ask the metadata, not the broken import.
+ if "$VENV_DIR/bin/python" -c "
import sys
from importlib.metadata import PackageNotFoundError, requires, version
try:
@@ -1908,36 +1924,13 @@ except (PackageNotFoundError, ImportError, ValueError, IndexError):
sys.exit(1)
sys.exit(0 if windows and installed not in windows[0] else 1)
" 2>/dev/null; then
- substep "installed transformers rejects the installed tokenizers -- forcing dependency pass to repair..."
- _SKIP_PYTHON_DEPS=false
- fi
- # An interrupted install leaves $_PKG_NAME current while studio.txt
- # never finished, so the compare above says "up to date" and update --
- # plus the desktop Repair button -- no-ops on a venv that cannot boot.
+ substep "installed transformers rejects the installed tokenizers -- forcing dependency pass to repair..."
+ _SKIP_PYTHON_DEPS=false
+ fi
+ # If the desktop app specifies a minimum required backend version and the installed
+ # package is older than that requirement, force the dependency pass to upgrade it.
+ if [ -n "${UNSLOTH_DESKTOP_BACKEND_VERSION:-}" ]; then
if ! "$VENV_DIR/bin/python" -c "
-import os, sys
-sys.path.insert(0, sys.argv[1])
-try:
- import install_manifest
-except Exception:
- # Present but unimportable is damage, not an old release, and this is the
- # one file whose damage silences every check below. Absent keeps the old
- # escape: separating it from an old tree needs a RECORD walk here, and the
- # CLI already reports studio_install_manifest_missing.
- sys.exit(1 if os.path.isfile(os.path.join(sys.argv[1], 'install_manifest.py')) else 0)
-try:
- ok = install_manifest.verify_install(deep = True)['ok']
-except TypeError:
- ok = install_manifest.verify_install()['ok'] # older tree, no payload scan
-sys.exit(0 if ok else 1)
-" "$SCRIPT_DIR" 2>/dev/null; then
- substep "studio install incomplete -- forcing dependency pass to repair..."
- _SKIP_PYTHON_DEPS=false
- fi
- # If the desktop app specifies a minimum required backend version and the installed
- # package is older than that requirement, force the dependency pass to upgrade it.
- if [ -n "${UNSLOTH_DESKTOP_BACKEND_VERSION:-}" ]; then
- if ! "$VENV_DIR/bin/python" -c "
import re, sys
try:
from packaging.version import parse as parse_v
@@ -1949,125 +1942,172 @@ installed = parse_v(sys.argv[1])
required = parse_v(sys.argv[2])
sys.exit(0 if installed is not None and required is not None and installed >= required else 1)
" "$INSTALLED_VER" "$UNSLOTH_DESKTOP_BACKEND_VERSION" 2>/dev/null; then
- substep "$_PKG_NAME $INSTALLED_VER < $UNSLOTH_DESKTOP_BACKEND_VERSION (required by desktop app) -- forcing dependency pass to update..."
- _SKIP_PYTHON_DEPS=false
- fi
- fi
- # An XPU pin the venv does not satisfy. Only the dependency pass acts on it
- # (install_python_stack's _ensure_xpu_torch), so without this escape a CPU install
- # switched to UNSLOTH_TORCH_INDEX_FAMILY=xpu keeps its CPU wheel forever: the package
- # version is current, so the fast path calls it up to date. Mirrors setup.ps1.
- _setup_pin="${UNSLOTH_TORCH_INDEX_URL:-${UNSLOTH_TORCH_INDEX_FAMILY:-}}"
- # Strip query/fragment first: an authenticated mirror (…/whl/xpu?token=...) is a
- # supported pin shape, and missing it reads as "no XPU pin" and skips the repair.
- _setup_pin="${_setup_pin%%\#*}"
- _setup_pin="${_setup_pin%%\?*}"
- # ALL trailing slashes, like the shared leaf parsers: a single %/ leaves "…/xpu/" behind.
- while [ "${_setup_pin%/}" != "$_setup_pin" ]; do _setup_pin="${_setup_pin%/}"; done
- # Exact, lowercased leaf, like every other leaf parser: a *xpu suffix match (…/private-xpu)
- # would force a pass every update that _ensure_xpu_torch then declines to act on, and an
- # uncased match would miss UNSLOTH_TORCH_INDEX_FAMILY=XPU that those parsers do accept.
- _setup_pin_leaf=$(printf '%s' "${_setup_pin##*/}" | tr '[:upper:]' '[:lower:]')
- # Disk first, no interpreter: version.py carries the local label, so a wedged Intel
- # driver cannot hang `studio update` inside `import torch`. Read unconditionally, not
- # only under a pin: the pin is one-shot, so the installed wheel is the only durable
- # signal -- the same one _ensure_xpu_triton keys on.
- _setup_pin_ok=false
- _setup_pin_is_xpu=false
- for _setup_pin_tv in "$VENV_DIR"/lib/python*/site-packages/torch/version.py; do
- [ -f "$_setup_pin_tv" ] || continue
- _setup_pin_ver=$(sed -n "s/^__version__ = '\([^']*\)'.*/\1/p" "$_setup_pin_tv" | head -1)
- case "$_setup_pin_ver" in
- *+xpu)
- _setup_pin_is_xpu=true
- _setup_pin_maj=${_setup_pin_ver%%.*}
- _setup_pin_rest=${_setup_pin_ver#*.}
- _setup_pin_min=${_setup_pin_rest%%.*}
- case "$_setup_pin_maj$_setup_pin_min" in
- *[!0-9]*) ;;
- *) [ "$_setup_pin_maj" -eq 2 ] && [ "$_setup_pin_min" -ge 6 ] && \
- [ "$_setup_pin_min" -lt 11 ] && _setup_pin_ok=true ;;
- esac
- ;;
- esac
- break
- done
- # Correct torch is not enough: the Triton swap also lives in install_python_stack, so a
- # migrated +xpu venv with a leftover generic triton keeps the CUDA build shadowing the
- # XPU one. The dist-info glob below matches only generic "triton-<ver>" -- the XPU builds
- # are pytorch_triton_xpu-* / triton_xpu-*.
- # Leaves the shared classifiers recognise as a non-XPU family. EXACT families, mirroring
- # install.sh _is_pip_rocm_family_leaf and install_python_stack _is_cuda_family_leaf: a
- # merely prefixed leaf (cu128-private) is a custom verbatim pin they never repair, so
- # escaping on one would force a pass every update that changes nothing.
- _setup_known_nonxpu_leaf() {
- case "$1" in
- cpu|gfx[0-9]*) return 0 ;;
- cu[0-9]*) case "${1#cu}" in *[!0-9]*) return 1 ;; esac ;;
- rocm[0-9]*)
- # Both parts non-empty all-digits: rocm7., rocm7.2.1 are custom pins.
- _setup_rocm_rest="${1#rocm}"
- case "$_setup_rocm_rest" in
- *.*.*) return 1 ;;
- *.*)
- case "${_setup_rocm_rest%%.*}" in *[!0-9]*) return 1 ;; esac
- case "${_setup_rocm_rest#*.}" in "" | *[!0-9]*) return 1 ;; esac
- ;;
- *[!0-9]*) return 1 ;;
- esac
- ;;
- *) return 1 ;;
- esac
- return 0
- }
- _setup_pin_known_nonxpu=false
- _setup_known_nonxpu_leaf "$_setup_pin_leaf" && _setup_pin_known_nonxpu=true
- _setup_generic_triton=false
- if [ "$_setup_pin_is_xpu" = true ] || [ "$_setup_pin_leaf" = "xpu" ]; then
- for _setup_tri in "$VENV_DIR"/lib/python*/site-packages/triton-*.dist-info; do
- [ -d "$_setup_tri" ] && _setup_generic_triton=true && break
- done
- fi
- if [ "$_setup_pin_leaf" = "xpu" ] && [ "$_setup_pin_ok" = false ]; then
- substep "XPU index pinned but torch does not match -- forcing dependency pass to repair..."
- _SKIP_PYTHON_DEPS=false
- elif [ "$_setup_pin_is_xpu" = true ] && [ "$_setup_generic_triton" = true ]; then
- substep "generic triton shadows the XPU build -- forcing dependency pass to repair..."
- _SKIP_PYTHON_DEPS=false
- elif [ "$_setup_pin_is_xpu" = true ] && [ "$_setup_pin_known_nonxpu" = true ]; then
- # Migrating AWAY from XPU: the pin is authoritative, but only install_python_stack
- # acts on it, so an up-to-date install kept its +xpu wheel over the requested family.
- substep "$_setup_pin_leaf pinned over an XPU wheel -- forcing dependency pass to migrate..."
+ substep "$_PKG_NAME $INSTALLED_VER < $UNSLOTH_DESKTOP_BACKEND_VERSION (required by desktop app) -- forcing dependency pass to update..."
_SKIP_PYTHON_DEPS=false
fi
- # As setup.ps1's "Torch-index pin changed" branch: an explicit cu*/rocm*/cpu pin over
- # ANOTHER family's torch is a request only the dependency pass acts on, and the version
- # compare calls it up to date. Labelled wheels only; custom leaves left alone.
- _setup_pin_have_family=""
- case "${_setup_pin_ver:-}" in
- *+cu[0-9]*) _setup_pin_have_family=cu ;;
- *+rocm*) _setup_pin_have_family=rocm ;;
- *+cpu) _setup_pin_have_family=cpu ;;
- *+xpu) _setup_pin_have_family=xpu ;;
+ fi
+ # An XPU pin the venv does not satisfy: only the dependency pass acts on it, so a CPU install
+ # switched to UNSLOTH_TORCH_INDEX_FAMILY=xpu kept its wheel forever. Mirrors setup.ps1.
+ _setup_pin="${UNSLOTH_TORCH_INDEX_URL:-${UNSLOTH_TORCH_INDEX_FAMILY:-}}"
+ # Strip query/fragment first: an authenticated mirror (…/whl/xpu?token=...) is a supported pin.
+ _setup_pin="${_setup_pin%%\#*}"
+ _setup_pin="${_setup_pin%%\?*}"
+ # ALL trailing slashes, like the shared leaf parsers: a single %/ leaves "…/xpu/" behind.
+ while [ "${_setup_pin%/}" != "$_setup_pin" ]; do _setup_pin="${_setup_pin%/}"; done
+ # Exact, lowercased leaf, like every other leaf parser: a suffix match (…/private-xpu) would
+ # force a pass _ensure_xpu_torch declines to act on.
+ _setup_pin_leaf=$(printf '%s' "${_setup_pin##*/}" | tr '[:upper:]' '[:lower:]')
+ # Disk, no interpreter: a wedged Intel driver cannot hang `import torch`. Read unconditionally:
+ # the pin is one-shot, the installed wheel is the durable signal.
+ _setup_pin_ok=false
+ _setup_pin_is_xpu=false
+ for _setup_pin_tv in "$VENV_DIR"/lib/python*/site-packages/torch/version.py; do
+ [ -f "$_setup_pin_tv" ] || continue
+ _setup_pin_ver=$(sed -n "s/^__version__ = '\([^']*\)'.*/\1/p" "$_setup_pin_tv" | head -1)
+ case "$_setup_pin_ver" in
+ *+xpu)
+ _setup_pin_is_xpu=true
+ _setup_pin_maj=${_setup_pin_ver%%.*}
+ _setup_pin_rest=${_setup_pin_ver#*.}
+ _setup_pin_min=${_setup_pin_rest%%.*}
+ case "$_setup_pin_maj$_setup_pin_min" in
+ *[!0-9]*) ;;
+ *) [ "$_setup_pin_maj" -eq 2 ] && [ "$_setup_pin_min" -ge 6 ] && \
+ [ "$_setup_pin_min" -lt 11 ] && _setup_pin_ok=true ;;
+ esac
+ ;;
esac
- _setup_pin_want_family=""
- if [ "$_setup_pin_known_nonxpu" = true ]; then
- case "$_setup_pin_leaf" in
- cu[0-9]*) _setup_pin_want_family=cu ;;
- rocm[0-9]* | gfx[0-9]*) _setup_pin_want_family=rocm ;;
- cpu) _setup_pin_want_family=cpu ;;
- esac
- fi
- if [ "$_SKIP_PYTHON_DEPS" = true ] && [ -n "$_setup_pin_want_family" ] \
- && [ -n "$_setup_pin_have_family" ] && [ "$_setup_pin_have_family" != xpu ] \
- && [ "$_setup_pin_have_family" != "$_setup_pin_want_family" ]; then
- substep "$_setup_pin_leaf pinned over a +$_setup_pin_have_family torch wheel -- forcing dependency pass to reinstall torch from the pin..."
+ break
+ done
+ # Correct torch is not enough: a leftover generic triton shadows the XPU build and only the
+ # pass swaps it. Non-XPU leaves matched EXACTly, as install_python_stack does: a prefixed leaf
+ # (cu128-private) is a custom pin it never repairs.
+ _setup_known_nonxpu_leaf() {
+ case "$1" in
+ cpu|gfx[0-9]*) return 0 ;;
+ cu[0-9]*) case "${1#cu}" in *[!0-9]*) return 1 ;; esac ;;
+ rocm[0-9]*)
+ # Both parts non-empty all-digits: rocm7., rocm7.2.1 are custom pins.
+ _setup_rocm_rest="${1#rocm}"
+ case "$_setup_rocm_rest" in
+ *.*.*) return 1 ;;
+ *.*)
+ case "${_setup_rocm_rest%%.*}" in *[!0-9]*) return 1 ;; esac
+ case "${_setup_rocm_rest#*.}" in "" | *[!0-9]*) return 1 ;; esac
+ ;;
+ *[!0-9]*) return 1 ;;
+ esac
+ ;;
+ *) return 1 ;;
+ esac
+ return 0
+ }
+ _setup_pin_known_nonxpu=false
+ _setup_known_nonxpu_leaf "$_setup_pin_leaf" && _setup_pin_known_nonxpu=true
+ _setup_generic_triton=false
+ if [ "$_setup_pin_is_xpu" = true ] || [ "$_setup_pin_leaf" = "xpu" ]; then
+ for _setup_tri in "$VENV_DIR"/lib/python*/site-packages/triton-*.dist-info; do
+ [ -d "$_setup_tri" ] && _setup_generic_triton=true && break
+ done
+ fi
+ if [ "$_setup_pin_leaf" = "xpu" ] && [ "$_setup_pin_ok" = false ]; then
+ substep "XPU index pinned but torch does not match -- forcing dependency pass to repair..."
+ _SKIP_PYTHON_DEPS=false
+ elif [ "$_setup_pin_is_xpu" = true ] && [ "$_setup_generic_triton" = true ]; then
+ substep "generic triton shadows the XPU build -- forcing dependency pass to repair..."
+ _SKIP_PYTHON_DEPS=false
+ elif [ "$_setup_pin_is_xpu" = true ] && [ "$_setup_pin_known_nonxpu" = true ]; then
+ # Migrating AWAY from XPU: only install_python_stack acts on the pin.
+ substep "$_setup_pin_leaf pinned over an XPU wheel -- forcing dependency pass to migrate..."
+ _SKIP_PYTHON_DEPS=false
+ fi
+ # An explicit cu*/rocm*/cpu pin over a torch labelled with ANOTHER family: only the
+ # dependency pass reinstalls from the pin, and the compare above would keep the old wheel.
+ # Labelled wheels only (an untagged torch names no family), custom leaves left alone.
+ _setup_pin_have_family=""
+ case "${_setup_pin_ver:-}" in
+ *+cu[0-9]*) _setup_pin_have_family=cu ;;
+ *+rocm*) _setup_pin_have_family=rocm ;;
+ *+cpu) _setup_pin_have_family=cpu ;;
+ *+xpu) _setup_pin_have_family=xpu ;;
+ esac
+ _setup_pin_want_family=""
+ if [ "$_setup_pin_known_nonxpu" = true ]; then
+ case "$_setup_pin_leaf" in
+ cu[0-9]*) _setup_pin_want_family=cu ;;
+ rocm[0-9]* | gfx[0-9]*) _setup_pin_want_family=rocm ;;
+ cpu) _setup_pin_want_family=cpu ;;
+ esac
+ fi
+ if [ "$_SKIP_PYTHON_DEPS" = true ] && [ -n "$_setup_pin_want_family" ] \
+ && [ -n "$_setup_pin_have_family" ] && [ "$_setup_pin_have_family" != xpu ] \
+ && [ "$_setup_pin_have_family" != "$_setup_pin_want_family" ]; then
+ substep "$_setup_pin_leaf pinned over a +$_setup_pin_have_family torch wheel -- forcing dependency pass to reinstall torch from the pin..."
+ _SKIP_PYTHON_DEPS=false
+ fi
+ # Explicit under `set -e`: an arm ending in a false command would abort the update. The decision
+ # is in _SKIP_PYTHON_DEPS; the exit status carries nothing.
+ return 0
+}
+
+_SKIP_PYTHON_DEPS=false
+_SKIP_VERSION_CHECK=false
+# Set here, not left to `${_OFFLINE_FAST_PATH:-false}`, so an exported value from the caller's
+# environment cannot reach it. setup.ps1 already initialises $script:OfflineFastPath the same way.
+_OFFLINE_FAST_PATH=false
+if [ "$_COLAB_NO_VENV" = true ]; then
+ _SKIP_VERSION_CHECK=true
+fi
+_PKG_NAME="${STUDIO_PACKAGE_NAME:-unsloth}"
+if [ "$_SKIP_VERSION_CHECK" != true ] && [ "${SKIP_STUDIO_BASE:-0}" != "1" ] && [ "${STUDIO_LOCAL_INSTALL:-0}" != "1" ]; then
+ # Only check when NOT called from install.sh (which just installed the package)
+ _INSTALLED_VERSION_PROBE_EXIT=0
+ if INSTALLED_VER=$("$VENV_DIR/bin/python" -c "
+import sys
+sys.path.insert(0, sys.argv[2])
+import install_manifest
+version, conflict = install_manifest.installed_version_probe(sys.argv[1], ('unsloth-zoo',))
+print(version)
+sys.exit(2 if conflict else (0 if version else 1))
+" "$_PKG_NAME" "$SCRIPT_DIR" 2>/dev/null); then
+ :
+ else
+ _INSTALLED_VERSION_PROBE_EXIT=$?
+ INSTALLED_VER=""
+ fi
+
+ LATEST_VER=$(_setup_http_get_timed "https://pypi.org/pypi/$_PKG_NAME/json" 2>/dev/null \
+ | "$VENV_DIR/bin/python" -c "import sys,json; print(json.load(sys.stdin)['info']['version'])" 2>/dev/null \
+ || echo "")
+
+ if [ "$_INSTALLED_VERSION_PROBE_EXIT" -eq 2 ]; then
+ substep "duplicate metadata found for a core package -- forcing package repair..."
+ elif [ -n "$INSTALLED_VER" ] && [ -n "$LATEST_VER" ] && [ "$INSTALLED_VER" = "$LATEST_VER" ]; then
+ step "python" "$_PKG_NAME $INSTALLED_VER is up to date"
+ _SKIP_PYTHON_DEPS=true
+ # An interrupted install leaves $_PKG_NAME current while studio.txt never finished, so
+ # update and the Repair button no-op on a venv that cannot boot.
+ if ! _setup_install_is_verified; then
+ substep "studio install incomplete -- forcing dependency pass to repair..."
_SKIP_PYTHON_DEPS=false
fi
+ # ...and every remaining escape, shared with the offline rule below.
+ _fast_path_escapes
elif [ -n "$INSTALLED_VER" ] && [ -n "$LATEST_VER" ]; then
substep "$_PKG_NAME $INSTALLED_VER -> $LATEST_VER available, updating..."
elif [ -z "$LATEST_VER" ]; then
- substep "could not reach PyPI, updating to be safe..."
+ # PyPI unreachable: updating to be safe stays the default, since it is usually a blip.
+ # UV_OFFLINE is not a blip, so a verified tree is kept instead, on the incomplete-install
+ # guard's evidence and held to the up-to-date branch's escapes (it can still be below the
+ # floor).
+ if [ -n "$INSTALLED_VER" ] && _uv_offline_requested && _setup_install_is_verified; then
+ substep "PyPI is unreachable and UV_OFFLINE is set -- keeping the verified install"
+ _SKIP_PYTHON_DEPS=true
+ _OFFLINE_FAST_PATH=true
+ _fast_path_escapes
+ else
+ substep "could not reach PyPI, updating to be safe..."
+ fi
fi
fi
@@ -2147,6 +2187,11 @@ _sidecar_retire_after_failed_tiktoken() {
_sidecar_top_up_tiktoken() {
_stt_dir="$1"
_stt_label="$2"
+ # Under the offline keep this would reach the network through fast_install's pip fallback,
+ # and give a deferred tier a directory holding tiktoken alone.
+ [ "${_OFFLINE_FAST_PATH:-false}" = true ] && return 0
+ # And under UV_OFFLINE without the fast path: the pip fallback would reach for the network.
+ _uv_offline_requested && return 0
# Payload AND dist-info (RECORD is written last): an interrupted install leaves one without the
# other. A recordless dist-info goes first; uv cannot uninstall it, metadata still reads it.
for _stt_info in "$_stt_dir"/tiktoken-*.dist-info; do
@@ -2264,7 +2309,11 @@ _install_sidecar() {
_NEED_T5_530=false
_NEED_T5_550=false
_NEED_T5_510=false
-if [ -d "$STUDIO_HOME/.venv_t5" ]; then
+# The migration is a wipe and three rebuilds from a cache that may be cold, and the legacy tree is
+# the only sidecar, so under UV_OFFLINE it waits for the next online update.
+if [ -d "$STUDIO_HOME/.venv_t5" ] && { [ "${_OFFLINE_FAST_PATH:-false}" = true ] || _uv_offline_requested; }; then
+ substep "legacy transformers sidecar left in place -- UV_OFFLINE is set, migration waits for the next online update"
+elif [ -d "$STUDIO_HOME/.venv_t5" ]; then
# Legacy layout. A staged run's venvs may never be activated, so only the live update migrates.
if [ -z "$STAGE_ROOT" ]; then
_assert_studio_owned_or_absent "$STUDIO_HOME/.venv_t5" "legacy transformers sidecar venv"
@@ -2277,21 +2326,58 @@ fi
_sidecar_current "$VENV_T5_530_DIR" "5.3.0" || _NEED_T5_530=true
_sidecar_current "$VENV_T5_550_DIR" "5.5.0" || _NEED_T5_550=true
_sidecar_current "$VENV_T5_510_DIR" "5.10.2" || _NEED_T5_510=true
+# A sidecar rebuild is a wipe and four fetches, through a pip fallback that reaches the network,
+# so under the offline keep it waits for the next online update; the runtime self-heal covers a
+# missing tier meanwhile. A deferred tier keeps its own flag so it is not reported "current".
+_DEFER_T5_530=false
+_DEFER_T5_550=false
+_DEFER_T5_510=false
+# UV_OFFLINE without the fast path: the same wipe and fetches, through a pip fallback that does not
+# read UV_OFFLINE. Every stale or missing tier is left for the next online update.
+if [ "${_OFFLINE_FAST_PATH:-false}" != true ] && _uv_offline_requested; then
+ for _ofp in "530 5.3.0" "550 5.5.0" "510 5.10.2"; do
+ # Not `set --`: this runs at top-level scope, where that overwrites the script's own "$@".
+ _ofp_key=${_ofp%% *}; _ofp_ver=${_ofp#* }
+ if eval "[ \"\$_NEED_T5_$_ofp_key\" = true ]"; then
+ substep "transformers $_ofp_ver sidecar is stale or missing but UV_OFFLINE is set -- left for the next online update"
+ eval "_NEED_T5_$_ofp_key=false"
+ eval "_DEFER_T5_$_ofp_key=true"
+ fi
+ done
+ unset _ofp _ofp_key _ofp_ver
+fi
+if [ "${_OFFLINE_FAST_PATH:-false}" = true ]; then
+ for _ofp in "530 5.3.0" "550 5.5.0" "510 5.10.2"; do
+ _ofp_key=${_ofp%% *}; _ofp_ver=${_ofp#* }
+ if eval "[ \"\$_NEED_T5_$_ofp_key\" = true ]"; then
+ substep "transformers $_ofp_ver sidecar is stale but UV_OFFLINE is set -- left for the next online update"
+ eval "_NEED_T5_$_ofp_key=false"
+ eval "_DEFER_T5_$_ofp_key=true"
+ fi
+ done
+ unset _ofp _ofp_key _ofp_ver
+fi
if [ "$_NEED_T5_530" = true ]; then
_install_sidecar "$VENV_T5_530_DIR" "5.3.0" "5.3"
+elif [ "$_DEFER_T5_530" = true ]; then
+ step "transformers" "5.3.0 sidecar stale -- left for the next online update"
else
step "transformers" "5.3.0 sidecar current"
_sidecar_top_up_tiktoken "$VENV_T5_530_DIR" "5.3"
fi
if [ "$_NEED_T5_550" = true ]; then
_install_sidecar "$VENV_T5_550_DIR" "5.5.0" "5.5"
+elif [ "$_DEFER_T5_550" = true ]; then
+ step "transformers" "5.5.0 sidecar stale -- left for the next online update"
else
step "transformers" "5.5.0 sidecar current"
_sidecar_top_up_tiktoken "$VENV_T5_550_DIR" "5.5"
fi
if [ "$_NEED_T5_510" = true ]; then
_install_sidecar "$VENV_T5_510_DIR" "5.10.2" "5.10"
+elif [ "$_DEFER_T5_510" = true ]; then
+ step "transformers" "5.10.2 sidecar stale -- left for the next online update"
else
step "transformers" "5.10.2 sidecar current"
_sidecar_top_up_tiktoken "$VENV_T5_510_DIR" "5.10"
diff --git a/tests/sh/test_setup_desktop_backend_version_fastpath.sh b/tests/sh/test_setup_desktop_backend_version_fastpath.sh
old mode 100644
new mode 100755
index 72b36cda325..873c03a4fd9
--- a/tests/sh/test_setup_desktop_backend_version_fastpath.sh
+++ b/tests/sh/test_setup_desktop_backend_version_fastpath.sh
@@ -2,7 +2,10 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
# Tests that setup.sh's fastpath escapes when UNSLOTH_DESKTOP_BACKEND_VERSION
-# requires a backend upgrade even if INSTALLED_VER == LATEST_VER.
+# requires a backend upgrade even if INSTALLED_VER == LATEST_VER -- and that the
+# UV_OFFLINE branch, which keeps a verified install when PyPI is unreachable, is
+# held to that same bar. Both branches reach the escapes through one helper,
+# _fast_path_escapes, precisely so they cannot answer differently.
set -euo pipefail
@@ -12,6 +15,7 @@ WORK=$(mktemp -d)
trap 'rm -rf "$WORK"' EXIT
BLK="$WORK/fastpath_blk.sh"
+OFFLINE_BLK="$WORK/offline_blk.sh"
# This test runs the fast path by slicing it out of setup.sh, so every slice
# assumption below is checked and reported as drift. An unchecked slice fails
@@ -23,8 +27,9 @@ BLK="$WORK/fastpath_blk.sh"
drift() {
echo "FATAL: the fast-path extraction no longer matches $SETUP_SH -- $1" >&2
echo " Fix the extraction in $0 (or the block in setup.sh), do not silence it:" >&2
- echo " start anchor is the INSTALLED_VER = LATEST_VER condition (any if/elif keyword)," >&2
- echo " end anchor is the first _setup_pin= assignment after it." >&2
+ echo " start anchors are the INSTALLED_VER = LATEST_VER condition and the" >&2
+ echo " -z LATEST_VER condition (any if/elif keyword); each branch ends where it" >&2
+ echo " hands off, at the _fast_path_escapes call and at the chain's own fi." >&2
exit 1
}
@@ -34,51 +39,90 @@ drift() {
# separately below and normalised to a plain `if` on the way out, so the slice
# is always a standalone, parseable construct.
FASTPATH_COND='[ -n "$INSTALLED_VER" ] && [ -n "$LATEST_VER" ] && [ "$INSTALLED_VER" = "$LATEST_VER" ]; then'
+# The sibling branch, taken when PyPI could not be reached at all.
+OFFLINE_COND='[ -z "$LATEST_VER" ]; then'
-_extract_status=0
-awk -v COND="$FASTPATH_COND" '
- index($0, COND) > 0 { starts++ }
- !on && index($0, COND) > 0 {
- prefix = substr($0, 1, index($0, COND) - 1)
- if (prefix !~ /^[ \t]*(el)?if $/) { bad_prefix = prefix; next }
- on = 1
- print "if " COND
- next
- }
- on && !ended && $0 ~ /^[ \t]*_setup_pin=/ { ended = 1; next }
- on && !ended { body++; print }
- END {
- if (starts != 1) { print starts + 0 > "/dev/stderr"; exit 3 }
- if (!on) { print bad_prefix > "/dev/stderr"; exit 4 }
- if (!ended) { exit 5 }
- if (body == 0) { exit 6 }
- print "fi"
- }
-' "$SETUP_SH" > "$BLK" 2> "$WORK/extract_err" || _extract_status=$?
-
-case "$_extract_status" in
- 0) ;;
- 3) drift "expected exactly 1 line holding the fast-path condition, found $(cat "$WORK/extract_err")" ;;
- 4) drift "the fast-path condition is no longer introduced by if/elif (leading text: '$(cat "$WORK/extract_err")')" ;;
- 5) drift "the end anchor (_setup_pin=) no longer follows the fast-path condition" ;;
- 6) drift "the fast-path block is empty" ;;
- *) drift "the extraction failed with status $_extract_status" ;;
-esac
-
-# The slice has to still contain what this test claims to test. Without these
+# $1 condition literal, $2 end-anchor regex, $3 destination. KEEP consumes the anchor line: the
+# up-to-date branch ends ON its handoff line, the offline branch on the chain's closing `fi`.
+extract_branch() {
+ _extract_status=0
+ awk -v COND="$1" -v ENDRE="$2" -v KEEP="$3" '
+ index($0, COND) > 0 { starts++ }
+ !on && index($0, COND) > 0 {
+ prefix = substr($0, 1, index($0, COND) - 1)
+ if (prefix !~ /^[ \t]*(el)?if $/) { bad_prefix = prefix; next }
+ on = 1
+ print "if " COND
+ next
+ }
+ on && !ended && $0 ~ ENDRE { ended = 1; if (KEEP == "keep") { body++; print } next }
+ on && !ended { body++; print }
+ END {
+ if (starts != 1) { print starts + 0 > "/dev/stderr"; exit 3 }
+ if (!on) { print bad_prefix > "/dev/stderr"; exit 4 }
+ if (!ended) { exit 5 }
+ if (body == 0) { exit 6 }
+ print "fi"
+ }
+ ' "$SETUP_SH" > "$4" 2> "$WORK/extract_err" || _extract_status=$?
+
+ case "$_extract_status" in
+ 0) ;;
+ 3) drift "expected exactly 1 line holding '$1', found $(cat "$WORK/extract_err")" ;;
+ 4) drift "'$1' is no longer introduced by if/elif (leading text: '$(cat "$WORK/extract_err")')" ;;
+ 5) drift "the end anchor ($2) no longer follows '$1'" ;;
+ 6) drift "the block after '$1' is empty" ;;
+ *) drift "the extraction of '$1' failed with status $_extract_status" ;;
+ esac
+}
+
+extract_branch "$FASTPATH_COND" '^[ \t]*_fast_path_escapes$' keep "$BLK"
+extract_branch "$OFFLINE_COND" '^ fi$' drop "$OFFLINE_BLK"
+
+# The slices have to still contain what this test claims to test. Without these
# the extraction could shrink to nothing meaningful and every case would pass.
grep -q '_SKIP_PYTHON_DEPS=true' "$BLK" \
- || drift "the extracted block never sets _SKIP_PYTHON_DEPS=true"
-grep -q 'UNSLOTH_DESKTOP_BACKEND_VERSION' "$BLK" \
- || drift "the extracted block no longer consults UNSLOTH_DESKTOP_BACKEND_VERSION"
+ || drift "the extracted up-to-date block never sets _SKIP_PYTHON_DEPS=true"
+grep -q '^[[:space:]]*_fast_path_escapes$' "$BLK" \
+ || drift "the extracted up-to-date block no longer calls _fast_path_escapes"
+grep -q '_SKIP_PYTHON_DEPS=true' "$OFFLINE_BLK" \
+ || drift "the extracted offline block never sets _SKIP_PYTHON_DEPS=true"
+grep -q '^[[:space:]]*_fast_path_escapes$' "$OFFLINE_BLK" \
+ || drift "the extracted offline block no longer calls _fast_path_escapes -- an offline
+ skip that ducks the shared escapes reports success and repairs nothing"
+grep -q 'could not reach PyPI' "$OFFLINE_BLK" \
+ || drift "the extracted offline block lost its updating-to-be-safe default"
# The part that matters: a slice that does not parse is drift, not a test failure.
-if ! _syntax_err=$(bash -n "$BLK" 2>&1); then
- echo "--- extracted block ---" >&2
- cat -n "$BLK" >&2
- echo "--- bash -n ---" >&2
+for _blk in "$BLK" "$OFFLINE_BLK"; do
+ if ! _syntax_err=$(bash -n "$_blk" 2>&1); then
+ echo "--- extracted block ($_blk) ---" >&2
+ cat -n "$_blk" >&2
+ echo "--- bash -n ---" >&2
+ echo "$_syntax_err" >&2
+ drift "the extracted block $_blk is not valid bash (see above)"
+ fi
+done
+
+# The shared helpers come with the slices, extracted by name and checked: a helper silently missing
+# is a "command not found" that reads as an incomplete install, the very answer three cases below
+# expect for a DIFFERENT reason.
+HELPERS="$WORK/helpers.sh"
+: > "$HELPERS"
+for _fn in _setup_install_is_verified _uv_offline_requested _fast_path_escapes; do
+ awk -v FN="^${_fn}\\\\(\\\\) \\\\{" '
+ $0 ~ FN { grab = 1 }
+ grab { print }
+ grab && /^}/ { grab = 0 }
+ ' "$SETUP_SH" >> "$HELPERS"
+ grep -q "^${_fn}() {" "$HELPERS" \
+ || drift "$_fn is no longer a top-level function in setup.sh"
+done
+grep -q 'UNSLOTH_DESKTOP_BACKEND_VERSION' "$HELPERS" \
+ || drift "the shared escapes no longer consult UNSLOTH_DESKTOP_BACKEND_VERSION"
+if ! _syntax_err=$(bash -n "$HELPERS" 2>&1); then
echo "$_syntax_err" >&2
- drift "the extracted block is not valid bash (see above)"
+ drift "the extracted helpers are not valid bash"
fi
PASS=0
@@ -109,6 +153,16 @@ chmod +x "$VENV_DIR/bin/python"
# Mock install_manifest to return ok: True so manifest check passes
printf 'def verify_install(**kwargs):\n return {"ok": True}\n' > "$WORK/install_manifest.py"
+# Shared by both drivers: an ambient torch pin would fire the XPU arm and every case would read
+# "false" for the wrong reason.
+_common_env() {
+ _PKG_NAME="unsloth"
+ SCRIPT_DIR="$WORK"
+ UNSLOTH_TORCH_INDEX_URL=""
+ UNSLOTH_TORCH_INDEX_FAMILY=""
+ _SKIP_PYTHON_DEPS=false
+}
+
eval_fastpath() {
local installed_ver="$1"
local latest_ver="$2"
@@ -117,9 +171,7 @@ eval_fastpath() {
INSTALLED_VER="$installed_ver"
LATEST_VER="$latest_ver"
UNSLOTH_DESKTOP_BACKEND_VERSION="$desktop_ver"
- _PKG_NAME="unsloth"
- SCRIPT_DIR="$WORK"
- _SKIP_PYTHON_DEPS=false
+ _common_env
# false is also what a block that never ran leaves behind, so three of
# the six cases below would pass on a block that did nothing at all.
# Both ways that can happen report themselves instead.
@@ -129,12 +181,42 @@ eval_fastpath() {
# Execute extracted block
# shellcheck disable=SC1090
+ . "$HELPERS"
+ # shellcheck disable=SC1090
. "$BLK" || { echo "BLOCK_FAILED_TO_RUN"; exit 0; }
[ "$_STEP_CALLS" -gt 0 ] || { echo "BLOCK_NOT_ENTERED"; exit 0; }
echo "$_SKIP_PYTHON_DEPS"
)
}
+# The offline branch prints no `step`: exactly one of its two substep messages must appear.
+eval_offline() {
+ local installed_ver="$1"
+ local uv_offline="$2"
+ local desktop_ver="${3:-}"
+ (
+ INSTALLED_VER="$installed_ver"
+ LATEST_VER=""
+ UV_OFFLINE="$uv_offline"
+ UNSLOTH_DESKTOP_BACKEND_VERSION="$desktop_ver"
+ _common_env
+ _SUBSTEPS=""
+ substep() { _SUBSTEPS="$_SUBSTEPS
+$1"; }
+ step() { :; }
+
+ # shellcheck disable=SC1090
+ . "$HELPERS"
+ # shellcheck disable=SC1090
+ . "$OFFLINE_BLK" || { echo "BLOCK_FAILED_TO_RUN"; exit 0; }
+ case "$_SUBSTEPS" in
+ *"keeping the verified install"* | *"could not reach PyPI"*) ;;
+ *) echo "BLOCK_NOT_ENTERED"; exit 0 ;;
+ esac
+ echo "$_SKIP_PYTHON_DEPS"
+ )
+}
+
echo "Testing UNSLOTH_DESKTOP_BACKEND_VERSION fastpath escape in setup.sh:"
# 1. When versions match and no desktop version required -> skips python deps
@@ -159,5 +241,31 @@ check "installed older than desktop requirement (2026.8.14 < 2026.8.15)" \
check "post-release requirement forces dependency pass without packaging" \
"$(eval_fastpath '2026.8.15' '2026.8.15' '2026.8.15.post1')" "false"
+echo "The offline branch is held to the same bar:"
+# UV_OFFLINE turns "updating to be safe" into a skip bought by a verified tree, which can still be
+# below the desktop floor; before the escapes were shared this reported success.
+check "offline, verified, no desktop requirement" \
+ "$(eval_offline '2026.8.15' '1' '')" "true"
+
+check "offline, verified, satisfies desktop requirement" \
+ "$(eval_offline '2026.8.15' '1' '2026.8.15')" "true"
+
+check "offline, verified, BELOW desktop requirement" \
+ "$(eval_offline '2026.8.4' '1' '2026.8.15')" "false"
+
+check "offline, verified, unorderable desktop requirement" \
+ "$(eval_offline '2026.8.15' '1' '2026.8.15.post1')" "false"
+
+# The default is unchanged: without UV_OFFLINE an unreachable PyPI still updates to be safe.
+check "unreachable PyPI without UV_OFFLINE still updates" \
+ "$(eval_offline '2026.8.15' '' '')" "false"
+
+check "unreachable PyPI, UV_OFFLINE off, below requirement" \
+ "$(eval_offline '2026.8.4' 'false' '2026.8.15')" "false"
+
+# No installed version at all is not something to keep, offline or not.
+check "offline with nothing installed still updates" \
+ "$(eval_offline '' '1' '')" "false"
+
echo "Results: $PASS passed, $FAIL failed"
[ "$FAIL" -eq 0 ]
diff --git a/tests/sh/test_setup_full_deps_override.sh b/tests/sh/test_setup_full_deps_override.sh
new file mode 100755
index 00000000000..16475edf1c1
--- /dev/null
+++ b/tests/sh/test_setup_full_deps_override.sh
@@ -0,0 +1,240 @@
+#!/bin/bash
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+#
+# UNSLOTH_STUDIO_FULL_DEPS is read INSIDE install_python_stack.py, and setup.sh's fast path is the
+# branch that never starts it, so `UNSLOTH_STUDIO_FULL_DEPS=1 unsloth studio update` printed
+# "dependencies up to date" and did nothing. The escape now lives in _fast_path_escapes, which the
+# UV_OFFLINE branch calls too. This drives the real blocks and helper out of setup.sh.
+
+set -euo pipefail
+
+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
+SETUP_SH="$SCRIPT_DIR/../../studio/setup.sh"
+WORK=$(mktemp -d)
+trap 'rm -rf "$WORK"' EXIT
+
+BLK="$WORK/fastpath_blk.sh"
+OFFLINE_BLK="$WORK/offline_blk.sh"
+HELPERS="$WORK/helpers.sh"
+
+# Every slice assumption is reported as drift: a block that never sourced leaves _SKIP_PYTHON_DEPS
+# at its false default, the answer half the cases want.
+drift() {
+ echo "FATAL: the fast-path extraction no longer matches $SETUP_SH -- $1" >&2
+ echo " Fix the extraction in $0 (or the block in setup.sh), do not silence it." >&2
+ exit 1
+}
+
+FASTPATH_COND='[ -n "$INSTALLED_VER" ] && [ -n "$LATEST_VER" ] && [ "$INSTALLED_VER" = "$LATEST_VER" ]; then'
+OFFLINE_COND='[ -z "$LATEST_VER" ]; then'
+
+# $1 condition literal, $2 end-anchor regex, $3 keep|drop the anchor line, $4 destination.
+extract_branch() {
+ _extract_status=0
+ awk -v COND="$1" -v ENDRE="$2" -v KEEP="$3" '
+ index($0, COND) > 0 { starts++ }
+ !on && index($0, COND) > 0 {
+ prefix = substr($0, 1, index($0, COND) - 1)
+ if (prefix !~ /^[ \t]*(el)?if $/) { bad_prefix = prefix; next }
+ on = 1
+ print "if " COND
+ next
+ }
+ on && !ended && $0 ~ ENDRE { ended = 1; if (KEEP == "keep") { body++; print } next }
+ on && !ended { body++; print }
+ END {
+ if (starts != 1) { print starts + 0 > "/dev/stderr"; exit 3 }
+ if (!on) { print bad_prefix > "/dev/stderr"; exit 4 }
+ if (!ended) { exit 5 }
+ if (body == 0) { exit 6 }
+ print "fi"
+ }
+ ' "$SETUP_SH" > "$4" 2> "$WORK/extract_err" || _extract_status=$?
+
+ case "$_extract_status" in
+ 0) ;;
+ 3) drift "expected exactly 1 line holding '$1', found $(cat "$WORK/extract_err")" ;;
+ 4) drift "'$1' is no longer introduced by if/elif (leading text: '$(cat "$WORK/extract_err")')" ;;
+ 5) drift "the end anchor ($2) no longer follows '$1'" ;;
+ 6) drift "the block after '$1' is empty" ;;
+ *) drift "the extraction of '$1' failed with status $_extract_status" ;;
+ esac
+}
+
+extract_branch "$FASTPATH_COND" '^[ \t]*_fast_path_escapes$' keep "$BLK"
+extract_branch "$OFFLINE_COND" '^ fi$' drop "$OFFLINE_BLK"
+
+grep -q '^[[:space:]]*_fast_path_escapes$' "$BLK" \
+ || drift "the up-to-date block no longer calls _fast_path_escapes"
+grep -q '^[[:space:]]*_fast_path_escapes$' "$OFFLINE_BLK" \
+ || drift "the offline block no longer calls _fast_path_escapes"
+
+: > "$HELPERS"
+for _fn in _setup_install_is_verified _uv_offline_requested _fast_path_escapes; do
+ awk -v FN="^${_fn}\\\\(\\\\) \\\\{" '
+ $0 ~ FN { grab = 1 }
+ grab { print }
+ grab && /^}/ { grab = 0 }
+ ' "$SETUP_SH" >> "$HELPERS"
+ grep -q "^${_fn}() {" "$HELPERS" \
+ || drift "$_fn is no longer a top-level function in setup.sh"
+done
+
+# The escape has to live in the SHARED helper, or the offline branch answers differently. Sliced to
+# a FILE, never `awk ... | grep -q`: under `set -o pipefail` grep's early exit kills awk with
+# SIGPIPE and fails the pipeline (the uv cache scan's defect, reproduced here).
+FPE="$WORK/fast_path_escapes.sh"
+awk '/^_fast_path_escapes\(\) \{/ { grab = 1 } grab { print } grab && /^}/ { grab = 0 }' \
+ "$SETUP_SH" > "$FPE"
+grep -q 'UNSLOTH_STUDIO_FULL_DEPS' "$FPE" \
+ || drift "_fast_path_escapes no longer consults UNSLOTH_STUDIO_FULL_DEPS -- the hatch is
+ unreachable on an up-to-date install, which is the only install it exists for"
+grep -q 'substep "UNSLOTH_STUDIO_FULL_DEPS' "$FPE" \
+ || drift "the full-deps escape no longer announces itself; a pass nobody asked for and
+ nothing explains is indistinguishable from the fast path being broken"
+
+for _blk in "$BLK" "$OFFLINE_BLK" "$HELPERS"; do
+ if ! _syntax_err=$(bash -n "$_blk" 2>&1); then
+ cat -n "$_blk" >&2
+ echo "$_syntax_err" >&2
+ drift "the extracted block $_blk is not valid bash (see above)"
+ fi
+done
+
+# This region is POSIX sh like its neighbours: dash parses it or this fails.
+if command -v dash >/dev/null 2>&1; then
+ if ! _dash_err=$(dash -n "$FPE" 2>&1); then
+ echo "$_dash_err" >&2
+ drift "the shared escapes are no longer POSIX sh"
+ fi
+fi
+
+PASS=0
+FAIL=0
+check() {
+ if [ "$2" = "$3" ]; then
+ echo " PASS: $1 (got=$2)"
+ PASS=$((PASS + 1))
+ else
+ echo " FAIL: $1 (got=$2, want=$3)"
+ FAIL=$((FAIL + 1))
+ fi
+}
+
+# A python without site-packages: every probe takes its "cannot answer" path.
+VENV_DIR="$WORK/mock_venv"
+mkdir -p "$VENV_DIR/bin"
+cat << 'EOF' > "$VENV_DIR/bin/python"
+#!/bin/sh
+exec python3 -S "$@"
+EOF
+chmod +x "$VENV_DIR/bin/python"
+printf 'def verify_install(**kwargs):\n return {"ok": True}\n' > "$WORK/install_manifest.py"
+
+_common_env() {
+ _PKG_NAME="unsloth"
+ SCRIPT_DIR="$WORK"
+ # An ambient torch pin or desktop floor would fire another arm and read false for the wrong
+ # reason.
+ UNSLOTH_TORCH_INDEX_URL=""
+ UNSLOTH_TORCH_INDEX_FAMILY=""
+ UNSLOTH_DESKTOP_BACKEND_VERSION=""
+ _SKIP_PYTHON_DEPS=false
+}
+
+# $1 is passed to the block as the environment variable, or the literal <unset> to remove it.
+eval_fastpath() {
+ (
+ INSTALLED_VER="2026.8.15"
+ LATEST_VER="2026.8.15"
+ if [ "$1" = "<unset>" ]; then unset UNSLOTH_STUDIO_FULL_DEPS; else UNSLOTH_STUDIO_FULL_DEPS="$1"; fi
+ _common_env
+ # false is also what a block that never ran leaves, so both ways that can happen report
+ # here.
+ _STEP_CALLS=0
+ step() { _STEP_CALLS=$((_STEP_CALLS + 1)); }
+ substep() { :; }
+ # shellcheck disable=SC1090
+ . "$HELPERS"
+ # shellcheck disable=SC1090
+ . "$BLK" || { echo "BLOCK_FAILED_TO_RUN"; exit 0; }
+ [ "$_STEP_CALLS" -gt 0 ] || { echo "BLOCK_NOT_ENTERED"; exit 0; }
+ echo "$_SKIP_PYTHON_DEPS"
+ )
+}
+
+# The offline branch prints no `step`, so "did it run at all" is answered by its substeps.
+eval_offline() {
+ (
+ INSTALLED_VER="2026.8.15"
+ LATEST_VER=""
+ UV_OFFLINE="1"
+ if [ "$1" = "<unset>" ]; then unset UNSLOTH_STUDIO_FULL_DEPS; else UNSLOTH_STUDIO_FULL_DEPS="$1"; fi
+ _common_env
+ _SUBSTEPS=""
+ substep() { _SUBSTEPS="$_SUBSTEPS
+$1"; }
+ step() { :; }
+ # shellcheck disable=SC1090
+ . "$HELPERS"
+ # shellcheck disable=SC1090
+ . "$OFFLINE_BLK" || { echo "BLOCK_FAILED_TO_RUN"; exit 0; }
+ case "$_SUBSTEPS" in
+ *"keeping the verified install"* | *"could not reach PyPI"*) ;;
+ *) echo "BLOCK_NOT_ENTERED"; exit 0 ;;
+ esac
+ echo "$_SKIP_PYTHON_DEPS"
+ )
+}
+
+# What the user is told to run, and what it has to print while doing it.
+eval_message() {
+ (
+ INSTALLED_VER="2026.8.15"
+ LATEST_VER="2026.8.15"
+ UNSLOTH_STUDIO_FULL_DEPS="$1"
+ _common_env
+ _SUBSTEPS=""
+ step() { :; }
+ substep() { _SUBSTEPS="$_SUBSTEPS
+$1"; }
+ # shellcheck disable=SC1090
+ . "$HELPERS"
+ # shellcheck disable=SC1090
+ . "$BLK" || { echo "BLOCK_FAILED_TO_RUN"; exit 0; }
+ case "$_SUBSTEPS" in
+ *"UNSLOTH_STUDIO_FULL_DEPS is set"*) echo "announced" ;;
+ *) echo "silent" ;;
+ esac
+ )
+}
+
+echo "Testing UNSLOTH_STUDIO_FULL_DEPS against setup.sh's up-to-date fast path:"
+
+# The baseline the hatch has to be able to override: same version, nothing else wrong.
+check "unset leaves the fast path alone" "$(eval_fastpath '<unset>')" "true"
+
+# Accepted exactly as install_python_stack.py's _full_deps_requested: .strip().lower() in ("1",
+# "true", "yes", "on"), or the same command means different things per half.
+for truthy in 1 true TRUE True yes YES on ON " 1 " " on " " true "; do
+ check "UNSLOTH_STUDIO_FULL_DEPS=[$truthy] forces the dependency pass" \
+ "$(eval_fastpath "$truthy")" "false"
+done
+
+# ...and nothing wider: 0/false/empty are what a script wanting the default writes.
+for falsy in 0 false FALSE no off "" " " maybe 2 "1x" "on!" "yes please"; do
+ check "UNSLOTH_STUDIO_FULL_DEPS=[$falsy] leaves the fast path alone" \
+ "$(eval_fastpath "$falsy")" "true"
+done
+
+echo "The offline branch shares the escape, so it answers the same:"
+check "offline, verified, hatch unset" "$(eval_offline '<unset>')" "true"
+check "offline, verified, hatch set" "$(eval_offline '1')" "false"
+check "offline, verified, hatch=maybe" "$(eval_offline 'maybe')" "true"
+
+echo "And it says why it is doing the work:"
+check "a forced pass names the variable that forced it" "$(eval_message '1')" "announced"
+
+echo "Results: $PASS passed, $FAIL failed"
+[ "$FAIL" -eq 0 ]
diff --git a/tests/sh/test_setup_xpu_fastpath_escape.sh b/tests/sh/test_setup_xpu_fastpath_escape.sh
index bcaf14f178d..3f9bc9603d9 100755
--- a/tests/sh/test_setup_xpu_fastpath_escape.sh
+++ b/tests/sh/test_setup_xpu_fastpath_escape.sh
@@ -23,12 +23,17 @@ SETUP_SH="${1:-$SCRIPT_DIR/../../studio/setup.sh}"
WORK=$(mktemp -d)
trap 'rm -rf "$WORK"' EXIT
-# From the pin read to the end of the acting if/elif chain.
-# Stop at the `fi` that closes the escape chain, NOT after the Nth _SKIP_PYTHON_DEPS=false:
-# counting assignments truncates the block as soon as an arm is added, silently.
-awk '/_setup_pin="\$\{UNSLOTH_TORCH_INDEX_URL/{on=1} on && /^ elif \[ -n "\$INSTALLED_VER"/{exit} on{print}' \
+# From the pin read to the closing brace of _fast_path_escapes(), which BOTH fast-path branches
+# call. Not the Nth _SKIP_PYTHON_DEPS=false: counting assignments truncates silently when an arm is
+# added.
+awk '/_setup_pin="\$\{UNSLOTH_TORCH_INDEX_URL/{on=1} on && /^}$/{exit} on{print}' \
"$SETUP_SH" > "$WORK/blk.sh"
[ -s "$WORK/blk.sh" ] || { echo "FATAL: escape block not found in $SETUP_SH" >&2; exit 1; }
+# The anchor must be the helper's own closing brace, or the slice drags in unrelated code.
+grep -q '^_fast_path_escapes() {$' "$SETUP_SH" \
+ || { echo "FATAL: _fast_path_escapes is no longer a top-level function in $SETUP_SH" >&2; exit 1; }
+grep -q 'INSTALLED_VER' "$WORK/blk.sh" \
+ && { echo "FATAL: extraction ran past the end of _fast_path_escapes" >&2; exit 1; }
# An extraction that lost any of the three moving parts would make cases below pass vacuously.
_arms=$(grep -c '_SKIP_PYTHON_DEPS=false' "$WORK/blk.sh")
[ "$_arms" = "4" ] || { echo "FATAL: expected 4 escape arms, extracted $_arms" >&2; exit 1; }
@@ -182,7 +187,8 @@ check "cpu pin + cpu wheel" "$(escape "$(make_venv '2.9.1+cpu' yes v)" "https
# ask both predicates rather than trust them to stay in step.
PY_STACK="$SCRIPT_DIR/../../studio/install_python_stack.py"
if [ -f "$PY_STACK" ] && command -v python3 >/dev/null 2>&1; then
- awk '/^ _setup_known_nonxpu_leaf\(\) \{/{on=1} on{print} on && /^ \}$/{exit}' \
+ # One indent level shallower: the predicate lives in a function now.
+ awk '/^ _setup_known_nonxpu_leaf\(\) \{/{on=1} on{print} on && /^ \}$/{exit}' \
"$WORK/blk.sh" > "$WORK/leaf.sh"
grep -q 'rocm\[0-9\]' "$WORK/leaf.sh" || { echo "FATAL: predicate not extracted" >&2; exit 1; }
# shellcheck disable=SC1091
diff --git a/tests/studio/install/idempotency_proxy.py b/tests/studio/install/idempotency_proxy.py
new file mode 100644
index 00000000000..31981874220
--- /dev/null
+++ b/tests/studio/install/idempotency_proxy.py
@@ -0,0 +1,321 @@
+#!/usr/bin/env python3
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""A logging HTTP proxy (CONNECT tunnels plus plain HTTP), stdlib only.
+
+test_update_idempotency.py claims that a second `unsloth studio update` does no network
+work. A claim like that cannot be checked from inside the process being measured, and
+"the update finished quickly" is not evidence: a warm uv cache also finishes quickly,
+and so does a run that fetched three release manifests. So the child gets a proxy as its
+ONLY route out (HTTPS_PROXY/HTTP_PROXY/ALL_PROXY, with 127.0.0.1 in NO_PROXY), and every
+attempt is written down whether it succeeds or not.
+
+There is no TLS interception here and there does not need to be: the destination host,
+the byte counts in each direction and the duration are all recorded from the CONNECT
+line, which is enough to say which hosts a run talked to and how much it moved.
+
+ python idempotency_proxy.py serve --port 0 --log p.jsonl --port-file p.port
+ python idempotency_proxy.py serve --refuse ... # 403 everything, still log it
+ python idempotency_proxy.py serve --deny-hosts pypi.org,github.com ...
+ python idempotency_proxy.py summary p.jsonl [--since-ts T]
+
+--refuse is how offline is MEASURED rather than asserted: the child still has a proxy to
+talk to, every attempt is answered 403 and recorded, so a run that claims to have done
+nothing has to prove it made no connections. --deny-hosts is the same aimed at the
+package hosts alone.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import os
+import select
+import socket
+import sys
+import threading
+import time
+from collections import defaultdict
+from urllib.parse import urlsplit
+
+BUF = 1 << 16
+
+
+def _now() -> float:
+ return time.time()
+
+
+class Proxy:
+ def __init__(
+ self,
+ port: int,
+ log_path: str,
+ port_file: str | None,
+ refuse: bool = False,
+ deny_hosts: tuple[str, ...] = (),
+ ):
+ self.log_path = log_path
+ self.refuse = refuse
+ self.deny_hosts = tuple(h.strip().lower() for h in deny_hosts if h.strip())
+ self.lock = threading.Lock()
+ # Workers between accept and their journal record, published so the harness can tell "quiet"
+ # from "nothing left to journal": a worker blocked in the upstream connect has written
+ # nothing yet.
+ self.active = 0
+ self.active_path = log_path + ".active"
+ self._publish_active()
+ self.srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ self.srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
+ self.srv.bind(("127.0.0.1", port))
+ self.srv.listen(256)
+ self.port = self.srv.getsockname()[1]
+ if port_file:
+ # Written last and in one go: the caller polls this file for the port.
+ tmp = port_file + ".tmp"
+ with open(tmp, "w") as fh:
+ fh.write(str(self.port))
+ os.replace(tmp, port_file)
+ if refuse:
+ mode = "refuse-all"
+ elif self.deny_hosts:
+ mode = "deny=" + ",".join(self.deny_hosts)
+ else:
+ mode = "allow-all"
+ print(f"[proxy] 127.0.0.1:{self.port} log={log_path} mode={mode}", flush = True)
+
+ def denied(self, host: str | None) -> bool:
+ if self.refuse:
+ return True
+ h = (host or "").lower()
+ return any(h == d or h.endswith("." + d) for d in self.deny_hosts)
+
+ def log(self, rec: dict) -> None:
+ line = json.dumps(rec, separators = (",", ":"))
+ with self.lock:
+ with open(self.log_path, "a") as fh:
+ fh.write(line + "\n")
+ fh.flush()
+
+ def _publish_active(self) -> None:
+ # Whole file, then rename: the reader must never see a half-written count.
+ tmp = self.active_path + ".tmp"
+ with open(tmp, "w") as fh:
+ fh.write(str(self.active))
+ os.replace(tmp, self.active_path)
+
+ def _adjust_active(self, delta: int) -> None:
+ with self.lock:
+ self.active += delta
+ self._publish_active()
+
+ def serve(self) -> None:
+ while True:
+ try:
+ conn, _ = self.srv.accept()
+ except OSError:
+ return
+ # Before the worker exists: an accepted, unscheduled connection is invisible to the
+ # journal.
+ self._adjust_active(+1)
+ threading.Thread(target = self.handle, args = (conn,), daemon = True).start()
+
+ @staticmethod
+ def _read_head(conn: socket.socket) -> bytes:
+ data = b""
+ conn.settimeout(30)
+ while b"\r\n\r\n" not in data:
+ chunk = conn.recv(BUF)
+ if not chunk:
+ break
+ data += chunk
+ if len(data) > 1 << 20:
+ break
+ return data
+
+ def _record(self, t0: float, host, port, method: str, down: int, up: int, status: str) -> dict:
+ return {
+ "ts": round(t0, 3),
+ "host": host,
+ "port": port,
+ "method": method,
+ "bytes_down": down,
+ "bytes_up": up,
+ "seconds": round(_now() - t0, 3),
+ "status": status,
+ }
+
+ def handle(self, conn: socket.socket) -> None:
+ # Released once the record is in the journal (or the worker died trying).
+ try:
+ self._handle(conn)
+ finally:
+ self._adjust_active(-1)
+
+ def _handle(self, conn: socket.socket) -> None:
+ t0 = _now()
+ host = port = None
+ method = "?"
+ down = up = 0
+ status = "ok"
+ upstream = None
+ # Set once journalled, so an early journal does not get a second record from the `finally`.
+ recorded = False
+ try:
+ head = self._read_head(conn)
+ if not head:
+ return
+ line = head.split(b"\r\n", 1)[0].decode("latin-1")
+ parts = line.split()
+ if len(parts) < 2:
+ return
+ method, target = parts[0], parts[1]
+ probe = (
+ target.rpartition(":")[0]
+ if method == "CONNECT"
+ else (urlsplit(target).hostname or "")
+ )
+ if self.denied(probe):
+ host, status = probe, "refused"
+ port = 443 if method == "CONNECT" else 80
+ # Journalled BEFORE the 403 reaches the client: a caller can tear the proxy down on
+ # seeing the refusal, and a lost record reads as a connection that never happened.
+ self.log(self._record(t0, host, port, method, down, up, status))
+ recorded = True
+ conn.sendall(
+ b"HTTP/1.1 403 Forbidden\r\nProxy-Agent: unsloth-idempotency\r\n"
+ b"Content-Length: 0\r\nConnection: close\r\n\r\n"
+ )
+ return
+ if method == "CONNECT":
+ host, _, p = target.rpartition(":")
+ port = int(p or 443)
+ upstream = socket.create_connection((host, port), timeout = 60)
+ conn.sendall(b"HTTP/1.1 200 Connection Established\r\n\r\n")
+ initial = b""
+ else:
+ u = urlsplit(target)
+ host = u.hostname or ""
+ port = u.port or 80
+ upstream = socket.create_connection((host, port), timeout = 60)
+ initial = head
+ conn.settimeout(None)
+ upstream.settimeout(None)
+ if initial:
+ upstream.sendall(initial)
+ up += len(initial)
+ socks = [conn, upstream]
+ while True:
+ r, _, x = select.select(socks, [], socks, 600)
+ if x or not r:
+ status = "timeout" if not r else "error"
+ break
+ done = False
+ for s in r:
+ try:
+ data = s.recv(BUF)
+ except OSError:
+ data = b""
+ if not data:
+ done = True
+ break
+ if s is conn:
+ upstream.sendall(data)
+ up += len(data)
+ else:
+ conn.sendall(data)
+ down += len(data)
+ if done:
+ break
+ except Exception as exc: # noqa: BLE001 - a proxy that dies takes the run with it
+ status = f"error:{type(exc).__name__}"
+ finally:
+ for s in (conn, upstream):
+ try:
+ if s:
+ s.close()
+ except OSError:
+ pass
+ if not recorded:
+ self.log(self._record(t0, host, port, method, down, up, status))
+
+
+def summary(
+ path: str,
+ since_ts: float | None = None,
+ until_ts: float | None = None,
+) -> dict:
+ # largest_bytes_down is the biggest SINGLE connection, which is what separates a release's
+ # metadata from its payload: both are served by the same host over the same URL shape, so a
+ # total or a connection count cannot tell them apart (see PREBUILT_METADATA_CEILING).
+ by_host: dict[str, dict] = defaultdict(
+ lambda: {
+ "bytes_down": 0,
+ "bytes_up": 0,
+ "largest_bytes_down": 0,
+ "connections": 0,
+ "refused": 0,
+ "seconds": 0.0,
+ }
+ )
+ total = connections = refused = 0
+ if os.path.exists(path):
+ with open(path) as fh:
+ for line in fh:
+ try:
+ rec = json.loads(line)
+ except json.JSONDecodeError:
+ continue
+ if since_ts is not None and rec["ts"] < since_ts:
+ continue
+ if until_ts is not None and rec["ts"] > until_ts:
+ continue
+ h = by_host[rec.get("host") or "?"]
+ h["bytes_down"] += rec["bytes_down"]
+ h["bytes_up"] += rec["bytes_up"]
+ h["largest_bytes_down"] = max(h["largest_bytes_down"], rec["bytes_down"])
+ h["connections"] += 1
+ h["seconds"] += rec["seconds"]
+ connections += 1
+ if rec.get("status") == "refused":
+ h["refused"] += 1
+ refused += 1
+ total += rec["bytes_down"]
+ ordered = dict(sorted(by_host.items(), key = lambda kv: -kv[1]["bytes_down"]))
+ return {
+ "total_bytes_down": total,
+ "connections": connections,
+ "refused": refused,
+ "by_host": ordered,
+ }
+
+
+def main() -> None:
+ ap = argparse.ArgumentParser()
+ sub = ap.add_subparsers(dest = "cmd", required = True)
+ s = sub.add_parser("serve")
+ s.add_argument("--port", type = int, default = 0)
+ s.add_argument("--log", required = True)
+ s.add_argument("--port-file")
+ s.add_argument("--refuse", action = "store_true", help = "403 every request and log it")
+ s.add_argument("--deny-hosts", default = "", help = "comma list of hosts to 403 (suffix match)")
+ m = sub.add_parser("summary")
+ m.add_argument("log")
+ m.add_argument("--since-ts", type = float)
+ m.add_argument("--until-ts", type = float)
+ a = ap.parse_args()
+ if a.cmd == "serve":
+ Proxy(
+ a.port,
+ a.log,
+ a.port_file,
+ refuse = a.refuse,
+ deny_hosts = tuple(a.deny_hosts.split(",")),
+ ).serve()
+ else:
+ json.dump(summary(a.log, a.since_ts, a.until_ts), sys.stdout, indent = 2)
+ print()
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tests/studio/install/test_install_manifest_damage.py b/tests/studio/install/test_install_manifest_damage.py
index f685eb13449..924c9f89b7d 100644
--- a/tests/studio/install/test_install_manifest_damage.py
+++ b/tests/studio/install/test_install_manifest_damage.py
@@ -309,9 +309,9 @@ def test_the_installers_ask_for_the_scan():
repo = Path(__file__).resolve().parents[3]
for name in ("studio/setup.sh", "studio/setup.ps1"):
text = (repo / name).read_text(encoding = "utf-8")
- assert "verify_install(deep = True)" in text, f"{name} stopped asking for the scan"
+ assert "'deep': True" in text, f"{name} stopped asking for the scan"
# and it must survive an older module that has no such keyword
- assert "except TypeError:" in text, f"{name} lost its older-tree fallback"
+ assert "inspect.signature" in text, f"{name} lost its older-tree fallback"
def test_the_desktop_boot_path_does_not_ask_for_the_scan():
@@ -658,8 +658,10 @@ def _installer_helper_probe() -> str:
repo = Path(__file__).resolve().parents[3]
setup = (repo / "studio" / "setup.sh").read_text(encoding = "utf-8")
+ # Anchored on the probe itself, not on the `if !` that used to precede it: the same
+ # probe now lives in _setup_install_is_verified, which two callers share.
match = re.search(
- r'if ! "\$VENV_DIR/bin/python" -c "\n(import os, sys\n.*?)" "\$SCRIPT_DIR"', setup, re.S
+ r'"\$VENV_DIR/bin/python" -c "\n(import os, sys\n.*?)" "\$SCRIPT_DIR"', setup, re.S
)
assert match, "the manifest-helper probe moved; this test is reading the wrong block"
return match.group(1)
diff --git a/tests/studio/install/test_setup_fast_path_guard.py b/tests/studio/install/test_setup_fast_path_guard.py
index 813027674e4..a496f811e1b 100644
--- a/tests/studio/install/test_setup_fast_path_guard.py
+++ b/tests/studio/install/test_setup_fast_path_guard.py
@@ -16,6 +16,7 @@ from __future__ import annotations
import pathlib
import re
+import sys
import pytest
@@ -225,6 +226,307 @@ def test_the_ps1_sidecar_predicate_reads_no_version_gated_variable():
assert "PSVersion.Major -ge 7" not in body
+# The offline rule: "updating to be safe" is wrong under UV_OFFLINE, where every install can only
+# fail; a complete install is kept, on the incomplete-install guard's own evidence.
+
+
[email protected]("script", [SETUP_SH, SETUP_PS1], ids = ["setup.sh", "setup.ps1"])
+def test_an_unreachable_pypi_still_updates_by_default(script: pathlib.Path):
+ """Nothing above changes for a plain offline blip."""
+ text = script.read_text(encoding = "utf-8")
+ assert text.count('substep "could not reach PyPI, updating to be safe..."') == 1
+
+
[email protected]("script", [SETUP_SH, SETUP_PS1], ids = ["setup.sh", "setup.ps1"])
+def test_the_offline_rule_needs_all_three_conditions(script: pathlib.Path):
+ """An installed version, a declared offline mode, and a verified tree. Any two of
+ them is a skip that ships a half-built venv or a venv that was never built."""
+ text = script.read_text(encoding = "utf-8")
+ if script.name.endswith(".ps1"):
+ condition = (
+ "if ($InstalledVer -and (Test-UvOfflineRequested) -and "
+ "(Test-StudioInstallVerified)) {"
+ )
+ taken = "$SkipPythonDeps = $true"
+ else:
+ condition = (
+ 'if [ -n "$INSTALLED_VER" ] && _uv_offline_requested '
+ "&& _setup_install_is_verified; then"
+ )
+ taken = "_SKIP_PYTHON_DEPS=true"
+ assert condition in text, f"{script.name} no longer gates the offline skip on all three"
+ start = text.index(condition)
+ body = text[start : start + 400]
+ assert taken in body
+ assert "could not reach PyPI" in body, (
+ f"{script.name} lost the else branch, so a host that fails any one of the three "
+ "conditions now skips silently instead of updating to be safe"
+ )
+
+
[email protected]("script", [SETUP_SH, SETUP_PS1], ids = ["setup.sh", "setup.ps1"])
+def test_the_two_callers_share_one_definition_of_complete(script: pathlib.Path):
+ """The guard forces the pass when the tree is not verified and the offline rule keeps
+ it when it is. Two copies of that check is how they come to disagree."""
+ text = script.read_text(encoding = "utf-8")
+ helper = (
+ "function Test-StudioInstallVerified"
+ if script.name.endswith(".ps1")
+ else "_setup_install_is_verified() {"
+ )
+ assert helper in text
+ assert text.count("install_manifest.verify_install(**deep)") == 1, (
+ f"{script.name} has more than one deep verify; the offline rule and the "
+ "incomplete-install guard must ask the same question"
+ )
+
+
+def test_the_posix_offline_switch_reads_the_boolish_spellings(tmp_path):
+ """Same spelling UV_NO_CACHE accepts, because a user who set one expects the other
+ to be read the same way."""
+ import subprocess
+
+ text = SETUP_SH.read_text(encoding = "utf-8")
+ start = text.index("_uv_offline_requested() {")
+ body = text[start : text.index("\n}\n", start) + 3]
+ probe = tmp_path / "probe.sh"
+ probe.write_text(body + "\nif _uv_offline_requested; then echo yes; else echo no; fi\n")
+ for value, expected in (
+ ("1", "yes"),
+ ("true", "yes"),
+ ("TRUE", "yes"),
+ (" yes ", "yes"),
+ ("on", "yes"),
+ # uv's boolish parser takes the single letters too (uv 0.10.7).
+ ("t", "yes"),
+ ("T", "yes"),
+ ("y", "yes"),
+ ("0", "no"),
+ ("false", "no"),
+ ("", "no"),
+ ("maybe", "no"),
+ ("tr", "no"),
+ ):
+ result = subprocess.run(
+ ["sh", str(probe)],
+ capture_output = True,
+ text = True,
+ env = {"PATH": "/usr/bin:/bin", "UV_OFFLINE": value},
+ )
+ assert result.stdout.strip() == expected, (value, result.stdout)
+
+
+def test_the_offline_fast_path_never_wipes_a_sidecar():
+ """The offline rule keeps the install because nothing can be fetched. A sidecar
+ rebuild is a wipe followed by four fetches, so under that rule it would either reach
+ for the network or destroy a usable sidecar and then fail. Both shells flag the
+ offline keep and clear every rebuild flag behind it."""
+ sh = SETUP_SH.read_text(encoding = "utf-8")
+ ps1 = SETUP_PS1.read_text(encoding = "utf-8")
+ keep_sh = sh.index("keeping the verified install")
+ assert "_OFFLINE_FAST_PATH=true" in sh[keep_sh : keep_sh + 400]
+ guard_sh = sh.index('if [ "${_OFFLINE_FAST_PATH:-false}" = true ]; then')
+ assert (
+ sh.index('_sidecar_current "$VENV_T5_510_DIR"')
+ < guard_sh
+ < sh.index('if [ "$_NEED_T5_530" = true ]; then')
+ )
+ assert 'eval "_NEED_T5_$_ofp_key=false"' in sh[guard_sh : guard_sh + 900]
+ keep_ps1 = ps1.index("keeping the verified install")
+ assert "$script:OfflineFastPath = $true" in ps1[keep_ps1 : keep_ps1 + 400]
+ guard_ps1 = ps1.index("if ($script:OfflineFastPath) {\n foreach ($tier in")
+ assert (
+ ps1.index("Test-SidecarCurrent -TargetDir $VenvT5_510Dir")
+ < guard_ps1
+ < ps1.index("if ($_NeedT5_530 -or $_NeedT5_550 -or $_NeedT5_510) {")
+ )
+ assert "Set-Variable -Name $flag -Value $false" in ps1[guard_ps1 : guard_ps1 + 900]
+ # The legacy migration is itself a wipe above the guard: skipped under the offline keep, and
+ # under UV_OFFLINE without the fast path.
+ assert sh.index(
+ '[ "${_OFFLINE_FAST_PATH:-false}" = true ] || _uv_offline_requested; }; then'
+ ) < sh.index('rm -rf "$STUDIO_HOME/.venv_t5"')
+ assert ps1.index(
+ "(Test-Path -LiteralPath $VenvT5Legacy) -and ($script:OfflineFastPath -or (Test-UvOfflineRequested))"
+ ) < ps1.index("Remove-Item -LiteralPath $VenvT5Legacy -Recurse -Force")
+ # ...nor the tiktoken top-up: its pip fallback reaches the network.
+ top_up = sh[sh.index("_sidecar_top_up_tiktoken() {") :]
+ assert '[ "${_OFFLINE_FAST_PATH:-false}" = true ] && return 0' in top_up[:600]
+ repair = ps1[ps1.index("function Repair-SidecarTiktoken {") :]
+ assert "if ($script:OfflineFastPath) { return }" in repair[:600]
+
+
+def test_uv_offline_without_the_fast_path_still_keeps_an_existing_sidecar():
+ """UV_OFFLINE with the core not verified (or PyPI still answering) takes the ordinary
+ path, whose sidecar rebuild is a wipe followed by four fetches from a cache that may
+ be cold, and an absent tier would go through the pip fallback that does not read
+ UV_OFFLINE. Both shells defer every stale or missing tier under the offline request
+ itself, ahead of the fast-path guard; the runtime self-heal covers a missing tier."""
+ sh = SETUP_SH.read_text(encoding = "utf-8")
+ ps1 = SETUP_PS1.read_text(encoding = "utf-8")
+ offline_sh = sh.index(
+ 'if [ "${_OFFLINE_FAST_PATH:-false}" != true ] && _uv_offline_requested; then'
+ )
+ assert (
+ sh.index('_sidecar_current "$VENV_T5_510_DIR"')
+ < offline_sh
+ < sh.index('if [ "${_OFFLINE_FAST_PATH:-false}" = true ]; then')
+ )
+ block_sh = sh[offline_sh : offline_sh + 1100]
+ # Stale AND missing: an absent tier would reach the pip fallback. No path in the loop's word
+ # list (a space in the Studio home would split it).
+ assert '[ -d "$' not in block_sh.split("for _ofp in", 1)[1].split("done", 1)[0]
+ assert "$VENV_T5_530_DIR" not in block_sh.split("for _ofp in", 1)[1].split("\n", 1)[0]
+ assert (
+ 'eval "_NEED_T5_$_ofp_key=false"' in block_sh
+ and 'eval "_DEFER_T5_$_ofp_key=true"' in block_sh
+ )
+ offline_ps1 = ps1.index("if (-not $script:OfflineFastPath -and (Test-UvOfflineRequested)) {")
+ assert (
+ ps1.index("Test-SidecarCurrent -TargetDir $VenvT5_510Dir")
+ < offline_ps1
+ < ps1.index("if ($script:OfflineFastPath) {\n foreach ($tier in")
+ )
+ block_ps1 = ps1[offline_ps1 : offline_ps1 + 1100]
+ assert "Test-Path -LiteralPath $tier[2]" not in block_ps1
+ assert "Set-Variable -Name $flag -Value $false" in block_ps1
+ # The tiktoken top-up stays home under the offline request too.
+ top_up = sh[sh.index("_sidecar_top_up_tiktoken() {") :]
+ assert "_uv_offline_requested && return 0" in top_up[:900]
+ repair = ps1[ps1.index("function Repair-SidecarTiktoken {") :]
+ assert "if (Test-UvOfflineRequested) { return }" in repair[:900]
+
+
+def test_the_ps1_offline_flag_is_initialised_before_its_unconditional_reads():
+ """Only the offline keep assigns the flag, and the sidecar block reads it on every
+ update. Under a caller's Set-StrictMode an unassigned script variable is a
+ terminating error, and a dot-sourced rerun would otherwise inherit an earlier
+ offline run's $true."""
+ text = SETUP_PS1.read_text(encoding = "utf-8")
+ init = text.index("$script:OfflineFastPath = $false")
+ assert init < text.index("$script:OfflineFastPath = $true")
+ assert init < text.index("if ($script:OfflineFastPath)")
+
+
+def test_the_windows_uv_probe_looks_where_the_pinned_installer_put_uv():
+ """setup.ps1 installs uv into $USERPROFILE\\.local\\bin, and only astral's own installer
+ edits the registry PATH. Probing PATH alone therefore missed it in every fresh update
+ process, so Windows re-downloaded uv on every run: the idempotency harness measured two
+ files.pythonhosted.org connections on an update with nothing to do, where Linux and macOS
+ had none. The probe and the installer must resolve the same directory."""
+ text = SETUP_PS1.read_text(encoding = "utf-8")
+ assert "function Get-UvInstallDir" in text, (
+ "the install directory is no longer a shared helper; the probe and the installer can "
+ "now disagree about where uv lives"
+ )
+ start = text.index("$UseUv = $false")
+ probe = text[start : start + 700]
+ assert (
+ "Get-UvInstallDir" in probe
+ ), "the uv probe checks PATH only again; on Windows that reinstalls uv every update"
+ assert 'Join-Path (Get-UvInstallDir) "uv.exe"' in probe
+ # And the run that installs uv has to use it, or it records a manifest with no uv_version and
+ # the next run rewrites it: a no-op update that is not one.
+ install_arm = text[text.index('substep "installing uv package manager..."') :][:2000]
+ assert "Get-UvInstallDir" in install_arm, (
+ "after installing uv, setup.ps1 relies on Refresh-Environment alone; it rebuilds PATH "
+ "from a registry the pinned installer never edits, so that run falls back to pip"
+ )
+
+
+ "module_src, expected",
+ [
+ ("def verify_install(deep = False): return {'ok': True}", 0),
+ ("def verify_install(deep = False): return {'ok': False}", 1),
+ # The hole this replaced: `except TypeError` also caught one raised INSIDE a deep
+ # verify, and retried without the payload scan, so real damage read as verified.
+ ("def verify_install(deep = False): raise TypeError('inside')", 1),
+ ("def verify_install(): return {'ok': True}", 0), # older tree, no such keyword
+ ("def verify_install(): return {'ok': False}", 1),
+ ],
+)
+def test_the_deep_verify_only_degrades_on_a_tree_that_lacks_the_keyword(
+ tmp_path, module_src, expected
+):
+ import subprocess
+
+ probe = re.search(
+ r'"\$VENV_DIR/bin/python" -c "\n(import os, sys\n.*?)" "\$SCRIPT_DIR"',
+ SETUP_SH.read_text(encoding = "utf-8"),
+ re.S,
+ )
+ assert probe, "the verify probe moved; this test is reading the wrong block"
+ (tmp_path / "install_manifest.py").write_text(module_src + "\n", encoding = "utf-8")
+ result = subprocess.run(
+ [sys.executable, "-c", probe.group(1), str(tmp_path)], capture_output = True
+ )
+ assert result.returncode == expected, result.stderr.decode()
+
+
+def test_the_installer_reads_uv_offline_the_same_way_the_shell_does(tmp_path):
+ """A shell that decides "online" while the installer decides "offline" declines a repair
+ with a message contradicting the user. `off` and `no` are the spellings that did it."""
+ import ast as _ast
+ import os
+ import subprocess
+
+ sh = SETUP_SH.read_text(encoding = "utf-8")
+ start = sh.index("_uv_offline_requested() {")
+ probe = tmp_path / "probe.sh"
+ probe.write_text(
+ sh[start : sh.index("\n}\n", start) + 3]
+ + "\nif _uv_offline_requested; then echo yes; else echo no; fi\n"
+ )
+
+ stack = (REPO_ROOT / "studio" / "install_python_stack.py").read_text(encoding = "utf-8")
+ node = next(
+ n
+ for n in _ast.parse(stack).body
+ if isinstance(n, _ast.FunctionDef) and n.name == "_uv_is_offline"
+ )
+ namespace: dict = {"os": os}
+ exec(compile(_ast.Module(body = [node], type_ignores = []), "<stack>", "exec"), namespace)
+
+ for value in (
+ "1",
+ "0",
+ "t",
+ "f",
+ "true",
+ "false",
+ "y",
+ "n",
+ "yes",
+ "no",
+ "on",
+ "off",
+ "",
+ " ",
+ "TRUE",
+ "On",
+ "T",
+ "Y",
+ "maybe",
+ "2",
+ ):
+ # `sh` with a pinned POSIX PATH, as the sibling test above: `bash` on a Windows
+ # runner resolves to the WSL stub, which answers in UTF-16 and runs nothing.
+ shell = (
+ subprocess.run(
+ ["sh", str(probe)],
+ capture_output = True,
+ text = True,
+ env = {"PATH": "/usr/bin:/bin", "UV_OFFLINE": value},
+ ).stdout.strip()
+ == "yes"
+ )
+ os.environ["UV_OFFLINE"] = value
+ assert (
+ shell == namespace["_uv_is_offline"]()
+ ), f"UV_OFFLINE={value!r}: setup.sh says {shell}, install_python_stack.py disagrees"
+
+
def test_the_installer_pins_come_from_the_audited_pin_list():
"""The list the audit demands and the list the install performs must be one variable: a
pin `sidecar_is_current` requires but `_install_sidecar` never installs reads stale every
diff --git a/tests/studio/install/test_update_idempotency.py b/tests/studio/install/test_update_idempotency.py
new file mode 100644
index 00000000000..d4f37b48a23
--- /dev/null
+++ b/tests/studio/install/test_update_idempotency.py
@@ -0,0 +1,1131 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""End to end: a second `unsloth studio update` must do no network work and change
+nothing on disk.
+
+The unit half of this lives in test_dependency_pass_skips.py and in the prebuilt
+installers' own suites. It cannot answer the question this file asks, because every skip
+is conditional on evidence that only a real install produces: a manifest written by a
+real dependency pass, sidecar trees with real RECORD files, prebuilt markers whose
+hashes describe binaries that are really on disk.
+
+Two things make the claim measurable rather than plausible:
+
+ * The child's ONLY route out is a logging proxy (idempotency_proxy.py). Every
+ connection attempt is recorded whether it succeeds, so "did no network work" is a
+ byte count per host, not an impression of speed. A warm uv cache also finishes fast.
+ * The install is snapshotted before and after. "Nothing changed" means a sorted
+ distribution list, the manifest minus its timestamp, the prebuilt markers byte for
+ byte, the uv cache marker, the no-torch marker, each sidecar's file count and mtime,
+ and the mtime of every runtime binary.
+
+Opt in, because it needs a real install:
+
+ UNSLOTH_IDEMPOTENCY_E2E=1 pytest tests/studio/install/test_update_idempotency.py
+
+By default it exercises the install under $HOME. UNSLOTH_IDEMPOTENCY_HOME points it at
+an isolated one instead, which is how it is run locally against a scratch install:
+
+ UNSLOTH_IDEMPOTENCY_E2E=1 UNSLOTH_IDEMPOTENCY_HOME=/path/to/fake/home pytest ...
+
+Two update modes are measured, because they take different paths and only one of them
+is the flow a desktop user gets:
+
+ * `studio update` (no --local) is the desktop flow. When the installed version equals
+ PyPI's latest it takes setup.sh's fast path, skips the dependency pass entirely, and
+ the prebuilt pre-checks answer from their markers. This is where the byte counts are
+ asserted. It only runs when the two versions do agree; otherwise a "no-op" update
+ would legitimately be an upgrade, so those cases skip themselves rather than measure
+ an upgrade and call it idempotency.
+ * `studio update --local` reinstalls from the checkout, so the dependency pass always
+ runs, and it runs WITHOUT last run's evidence: a checkout is a development install
+ shape, and the pass refuses to skip steps on a manifest that may not describe the
+ tree (install_python_stack._plan_pass). What it demonstrates is the rest: the pip
+ bootstrap skip, the sidecars answering "current", the prebuilts answering from their
+ markers, and that a full pass over a settled venv still downloads nothing. It is
+ asserted from the LOG as well as from bytes: with a warm uv cache a full pass also
+ downloads nothing, so bytes cannot tell a skip from a re-resolve there. A full pass
+ has some churn of its own, named in FULL_PASS_CHURN; everything else must hold still.
+
+The fault-injection cases DAMAGE that install and expect the update to repair exactly
+the damaged part. They restore what they broke, but a failure mid-case can leave the
+install in the damaged state, so never point this at an install you care about.
+
+Reading a CI failure: run 1 is the SETTLE run and is deliberately not measured. The
+first update performed by new installer code legitimately rewrites the manifest --
+`step_results` and `pass_inputs` are recorded by the pass that introduces them, so an
+install laid down by an older build has neither -- and it may repair torchao, which an
+earlier release installed from the wrong index. Only runs 2 and later are asserted on.
+A staging run confirmed the third (offline) run changed nothing at all, which is the
+claim this branch makes; a diff reported against `run1-settle` is not that claim.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import os
+import pathlib
+import re
+import subprocess
+import sys
+import time
+
+import pytest
+
+
+E2E = os.environ.get("UNSLOTH_IDEMPOTENCY_E2E") == "1"
+
+PROXY = pathlib.Path(__file__).resolve().parent / "idempotency_proxy.py"
+IS_WINDOWS = sys.platform == "win32"
+IS_MACOS = sys.platform == "darwin"
+# Each run's update log and proxy journal: pytest's tmp dir, or UNSLOTH_IDEMPOTENCY_ARTIFACTS to
+# keep them (a failure is unreadable without them).
+ARTIFACTS = os.environ.get("UNSLOTH_IDEMPOTENCY_ARTIFACTS", "")
+
+# Hosts a no-op update must not touch. pypi.org and github.com are bounded separately (a version
+# check and a latest-release HEAD are legitimate); these are where the megabytes are.
+PAYLOAD_HOSTS = (
+ "files.pythonhosted.org",
+ "objects.githubusercontent.com",
+ "nodejs.org",
+)
+# NOT release-assets.githubusercontent.com: deciding whether the installed prebuilt is still the
+# right one reads that release's manifest and sha256 JSON, and release_asset_download_url builds
+# metadata and payload URLs alike, so both land on that host (~46 KB every run). A count or a total
+# cannot separate them either, because macOS walks back 16 releases of metadata. The biggest SINGLE
+# transfer can: largest metadata asset 19 KB, smallest published payload 567 KB, and no Range header
+# anywhere, so a payload is always one connection carrying the whole file.
+PREBUILT_METADATA_HOST = "release-assets.githubusercontent.com"
+PREBUILT_METADATA_CEILING = 256 * 1024
+
+# Per prebuilt, all before the local marker is consulted: HEAD /releases/latest, the 302 to
+# /releases/tag/<tag> that urllib re-issues and that stays on this host, then one GET per metadata
+# asset (whose redirects leave for release-assets).
+GITHUB_PER_PREBUILT = 4
+# macOS llama.cpp skips that fast path (install_llama_prebuilt.py:6470) and collects
+# DEFAULT_MAX_MACOS_RELEASE_FALLBACKS plans even when the first is fine, 2 assets each.
+MACOS_LLAMA_GITHUB = 2 * 16
+MAX_GITHUB_DESKTOP = (
+ (MACOS_LLAMA_GITHUB if IS_MACOS else GITHUB_PER_PREBUILT) # llama.cpp
+ + GITHUB_PER_PREBUILT # whisper.cpp, fast path on every platform
+ + GITHUB_PER_PREBUILT # an AMD iGPU host resolves llama twice (:8597)
+ + 2 # the whisper/llama ggml_tree pairing (install_whisper_prebuilt.py:381)
+ + 2 # slack for a retried fetch
+)
+# --local adds the triton kernels ref probe (one git ls-remote, Linux only) and uv's git fetch for
+# the zoo overlay on a cache miss. One git invocation is one tunnel, not two.
+MAX_GITHUB_LOCAL = MAX_GITHUB_DESKTOP + (0 if (IS_MACOS or IS_WINDOWS) else 1) + 2
+
+# api.github.com on --local is uv's, not ours: it resolves each git+https://github.com requirement
+# to a SHA through the API before cloning (UV_NO_GITHUB_FAST_PATH disables it), and the zoo overlay
+# reinstalls from git every run. We reach it only where the download-host fast path does not apply,
+# which is macOS llama.cpp listing its releases a page at a time.
+MACOS_LLAMA_API_GITHUB = 5
+MAX_API_GITHUB_DESKTOP = MACOS_LLAMA_API_GITHUB if IS_MACOS else 0
+MAX_API_GITHUB_LOCAL = MAX_API_GITHUB_DESKTOP + 1
+
+
+def assert_read_metadata_but_no_payload(run) -> None:
+ """The release metadata a no-op update legitimately reads, and nothing bigger."""
+ largest = run.largest_transfer_from(PREBUILT_METADATA_HOST)
+ assert largest <= PREBUILT_METADATA_CEILING, (
+ f"{PREBUILT_METADATA_HOST} served a single {largest} byte transfer to an update with "
+ f"nothing to do: that size is a prebuilt archive, not a release manifest. {run.report()}"
+ )
+
+
+# NOT raw.githubusercontent.com: install.sh's shortcut refresh reads rounded-512.png from it, and on
+# --local uv reads the resolved zoo commit's pyproject.toml from it too. The ceiling covers both.
+ICON_FETCH_CEILING = 64 * 1024
+
+# What the installers print when they decline to do work (setup.sh consumes the prebuilt installers'
+# "already matches" and prints its own line).
+NO_WORK_MARKERS = ("dependencies up to date", "prebuilt up to date", "sidecar current")
+# setup.sh's column-padded frontend line: a rebuild on a warm npm cache talks to no forbidden host,
+# so the log line is the only witness.
+FRONTEND_CURRENT_MARKER = re.compile(r"frontend\s+up to date")
+# What setup.sh / setup.ps1 print when the version check found a newer release, and when
+# it could not ask PyPI at all (the pass runs on purpose in both cases).
+UPGRADE_MARKER = "available, updating..."
+# What both shells print (step "python", column-padded) when PyPI's latest equals the
+# installed version and the dependency pass is skipped for it.
+UPTODATE_MARKER = re.compile(r"python\s+\S+ \S+ is up to date")
+PYPI_UNREACHABLE_MARKER = "could not reach PyPI, updating to be safe..."
+# What --local installs from the checkout on every pass, so its RECORD moving is expected.
+LOCAL_CORE = frozenset({"unsloth", "unsloth-zoo", "unsloth_zoo"})
+# What a FULL pass (no evidence: every --local pass, the pass after a deleted manifest) reinstalls
+# at the same version: the two path-installed seed plugins, and click, caught between sqlfluff<4
+# (click<=8.3.0) and huggingface-hub 1.23+ (click>=8.4.2) and recorded as known_unmet. A version
+# CHANGE is still seen, since the distribution list is compared separately.
+FULL_PASS_CHURN = LOCAL_CORE | frozenset(
+ {"data-designer-github-repo-seed", "data-designer-unstructured-seed", "click"}
+)
+
+DIST_LIST = (
+ "import importlib.metadata as m, json; "
+ "print(json.dumps(sorted(((d.metadata['Name'] or '').lower(), d.version) "
+ "for d in m.distributions())))"
+)
+# Names and versions cannot see a same-version reinstall; the RECORD mtime can. Per distribution, so
+# a failure names the package.
+DIST_RECORDS = (
+ "import importlib.metadata as m, json, os; "
+ "out = []\n"
+ "for d in m.distributions():\n"
+ " p = getattr(d, '_path', None) and (d._path / 'RECORD')\n"
+ " try:\n"
+ " st = os.stat(p)\n"
+ " out.append([(d.metadata['Name'] or '').lower(), d.version, st.st_mtime_ns, st.st_size])\n"
+ " except (OSError, TypeError):\n"
+ " out.append([(d.metadata['Name'] or '').lower(), d.version, None, None])\n"
+ "print(json.dumps(sorted(out)))"
+)
+
+
+# ── the install under test ──
+
+
+def _home() -> pathlib.Path:
+ return pathlib.Path(os.environ.get("UNSLOTH_IDEMPOTENCY_HOME") or pathlib.Path.home())
+
+
+def _studio_home() -> pathlib.Path:
+ override = os.environ.get("UNSLOTH_IDEMPOTENCY_STUDIO_HOME")
+ return pathlib.Path(override) if override else _home() / ".unsloth" / "studio"
+
+
+def _unsloth_home() -> pathlib.Path:
+ """Where the prebuilts (llama.cpp, whisper.cpp, node) live: setup.sh's UNSLOTH_HOME
+ rule, which nests them under a CUSTOM Studio home and keeps ~/.unsloth otherwise."""
+ if os.environ.get("UNSLOTH_IDEMPOTENCY_STUDIO_HOME"):
+ return _studio_home()
+ return _home() / ".unsloth"
+
+
+def _venv_python() -> pathlib.Path:
+ venv = _studio_home() / "unsloth_studio"
+ return venv / ("Scripts/python.exe" if IS_WINDOWS else "bin/python")
+
+
+def _installed_version(venv_python: pathlib.Path) -> str:
+ probe = subprocess.run(
+ [
+ str(venv_python),
+ "-I",
+ "-c",
+ "import importlib.metadata as m; print(m.version('unsloth'))",
+ ],
+ capture_output = True,
+ text = True,
+ timeout = 120,
+ )
+ return probe.stdout.strip()
+
+
+def _pypi_latest() -> str:
+ import urllib.request
+ try:
+ with urllib.request.urlopen("https://pypi.org/pypi/unsloth/json", timeout = 60) as fh:
+ return json.load(fh)["info"]["version"]
+ except Exception: # noqa: BLE001 - no answer means do not run the non-local cases
+ return ""
+
+
[email protected](scope = "session")
+def install() -> pathlib.Path:
+ # Gated here, not on the module, so the proxy self test still runs in ordinary CI.
+ if not E2E:
+ pytest.skip("opt-in end to end; set UNSLOTH_IDEMPOTENCY_E2E=1")
+ venv_python = _venv_python()
+ if not venv_python.is_file():
+ # Opted in and nothing to measure: a skip would keep the job green while measuring nothing.
+ pytest.fail(
+ f"UNSLOTH_IDEMPOTENCY_E2E is set but there is no Studio install at {venv_python}"
+ )
+ return venv_python
+
+
+# ── the proxy ──
+
+
+class ProxyRun:
+ """One update, measured."""
+
+ def __init__(self, directory: pathlib.Path, log: str, summary: dict, seconds: float, rc: int):
+ self.directory = directory
+ self.log = log
+ self.summary = summary
+ self.seconds = seconds
+ self.rc = rc
+
+ def bytes_from(self, host: str) -> int:
+ return sum(
+ v["bytes_down"]
+ for h, v in self.summary["by_host"].items()
+ if h == host or h.endswith("." + host)
+ )
+
+ def connections_to(self, host: str) -> int:
+ return sum(
+ v["connections"]
+ for h, v in self.summary["by_host"].items()
+ if h == host or h.endswith("." + host)
+ )
+
+ def largest_transfer_from(self, host: str) -> int:
+ """The biggest single connection from `host`. 0 when it was never contacted."""
+ return max(
+ (
+ v["largest_bytes_down"]
+ for h, v in self.summary["by_host"].items()
+ if h == host or h.endswith("." + host)
+ ),
+ default = 0,
+ )
+
+ @property
+ def connections(self) -> int:
+ return self.summary.get("connections", 0)
+
+ @property
+ def refused(self) -> int:
+ return self.summary.get("refused", 0)
+
+ def report(self) -> str:
+ hosts = ", ".join(
+ f"{h}={v['bytes_down'] / 1e6:.1f}MB/{v['connections']}c"
+ for h, v in list(self.summary["by_host"].items())[:8]
+ )
+ return (
+ f"{self.seconds:.1f}s exit={self.rc} "
+ f"down={self.summary['total_bytes_down'] / 1e6:.1f}MB "
+ f"conns={self.connections} refused={self.refused} [{hosts}]"
+ )
+
+
+def _start_proxy(directory: pathlib.Path, *extra: str):
+ log = directory / "proxy.jsonl"
+ port_file = directory / "proxy.port"
+ port_file.unlink(missing_ok = True)
+ # The proxy appends: a retained journal would attribute the previous run's traffic to this one.
+ log.unlink(missing_ok = True)
+ process = subprocess.Popen(
+ [
+ sys.executable,
+ str(PROXY),
+ "serve",
+ "--port",
+ "0",
+ "--log",
+ str(log),
+ "--port-file",
+ str(port_file),
+ *extra,
+ ],
+ stdout = (directory / "proxy.out").open("w"),
+ stderr = subprocess.STDOUT,
+ )
+ for _ in range(100):
+ if port_file.is_file() and port_file.read_text().strip():
+ break
+ if process.poll() is not None:
+ raise RuntimeError((directory / "proxy.out").read_text())
+ time.sleep(0.1)
+ else:
+ process.kill()
+ raise RuntimeError("the proxy never reported a port")
+ return process, f"http://127.0.0.1:{port_file.read_text().strip()}", log
+
+
+def _wait_until(
+ predicate,
+ *,
+ timeout: float = 5.0,
+ interval: float = 0.05,
+) -> bool:
+ """Poll until `predicate` holds or the deadline passes. A monotonic deadline rather
+ than a fixed sleep: the wait is for something the proxy is already doing, and a sleep
+ long enough to be safe on a loaded CI box is wasted on every ordinary run."""
+ deadline = time.monotonic() + timeout
+ while True:
+ if predicate():
+ return True
+ if time.monotonic() >= deadline:
+ return False
+ time.sleep(interval)
+
+
+def _settle_journal(
+ log_path: pathlib.Path,
+ *,
+ timeout: float = 5.0,
+ quiet: float = 0.25,
+ active_grace: float = 75.0,
+) -> bool:
+ """Wait for the proxy's journal to stop growing, before the proxy is terminated.
+
+ Returns False when a worker was still between accept and its record after
+ `active_grace` seconds, longer than the proxy's 60 s upstream connect timeout: the
+ journal is then incomplete and the caller must not read it as a zero-connection proof.
+
+ A worker appends its record once the connection it describes has closed, so the child
+ can exit -- or a client can see its response -- with records still in flight, and
+ terminating the proxy at that moment drops them. A dropped record is a connection this
+ harness would then report as never having happened, which is precisely the claim it
+ exists to make. Waits for quiescence rather than for a count, because how many
+ connections a run makes is the thing being measured.
+ """
+ active_path = log_path.with_name(log_path.name + ".active")
+
+ def _workers_active() -> bool:
+ # A worker blocked in an upstream connect has written nothing: a quiet journal alone is not
+ # proof.
+ try:
+ return int(active_path.read_text().strip() or "0") > 0
+ except (OSError, ValueError):
+ return False
+
+ size = -1
+ stable_since = time.monotonic()
+ deadline = stable_since + timeout
+ grace_deadline = stable_since + active_grace
+ while True:
+ now = time.monotonic()
+ try:
+ current = log_path.stat().st_size
+ except OSError:
+ current = 0
+ if current != size:
+ size, stable_since = current, now
+ elif now - stable_since >= quiet and not _workers_active():
+ return True
+ if now >= deadline and not _workers_active():
+ # A journal still growing past the deadline with no worker in flight is bounded here.
+ return True
+ if now >= grace_deadline:
+ return not _workers_active()
+ time.sleep(0.05)
+
+
+def run_update(
+ tmp_path: pathlib.Path,
+ label: str,
+ *,
+ local: bool = True,
+ offline: bool = False,
+ refuse: bool = False,
+ deny_hosts: str = "",
+) -> ProxyRun:
+ """One `unsloth studio update`, through the proxy, timed and logged."""
+ directory = (pathlib.Path(ARTIFACTS) if ARTIFACTS else tmp_path) / label
+ directory.mkdir(parents = True, exist_ok = True)
+ extra = ["--refuse"] if refuse else (["--deny-hosts", deny_hosts] if deny_hosts else [])
+ process, url, log_path = _start_proxy(directory, *extra)
+ # Inherited, not replaced: a hand-built environment fails in ways that look like the product.
+ env = dict(os.environ)
+ env.pop("UNSLOTH_IDEMPOTENCY_E2E", None)
+ # The venv pytest runs in is not the venv under test: anything pointing the child at this
+ # interpreter's environment has to go.
+ for leaked in (
+ "VIRTUAL_ENV",
+ "PYTHONPATH",
+ "PYTHONHOME",
+ "UV_CACHE_DIR",
+ "UV_PYTHON",
+ "UV_CONSTRAINT",
+ "UV_CONFIG_FILE",
+ "PIP_CONSTRAINT",
+ "PIP_CONFIG_FILE",
+ "XDG_CACHE_HOME",
+ "XDG_DATA_HOME",
+ "XDG_CONFIG_HOME",
+ "UNSLOTH_STUDIO_HOME",
+ "STUDIO_HOME",
+ "NPM_CONFIG_PROXY",
+ "NPM_CONFIG_HTTPS_PROXY",
+ "NPM_CONFIG_NOPROXY",
+ ):
+ env.pop(leaked, None)
+ env.update(
+ HOME = str(_home()),
+ USERPROFILE = str(_home()),
+ UNSLOTH_SKIP_AUTOSTART = "1",
+ UNSLOTH_STUDIO_DISABLE_PUBLIC_CHECK = "1",
+ PYTHONUNBUFFERED = "1",
+ HTTPS_PROXY = url,
+ HTTP_PROXY = url,
+ ALL_PROXY = url,
+ https_proxy = url,
+ http_proxy = url,
+ NO_PROXY = "127.0.0.1,localhost",
+ no_proxy = "127.0.0.1,localhost",
+ # npm_config_https_proxy outranks HTTPS_PROXY (npm 11): an inherited value would route the
+ # registry traffic around the proxy that counts it.
+ npm_config_proxy = url,
+ npm_config_https_proxy = url,
+ npm_config_noproxy = "127.0.0.1,localhost",
+ # Presence, not truthiness: without it the CLI reads an Invoke-WebRequest proxy default from
+ # the PowerShell profiles, which would outrank the variables above.
+ _UNSLOTH_PS_PROXY_DEFAULTS = "{}",
+ )
+ if os.environ.get("UNSLOTH_IDEMPOTENCY_STUDIO_HOME"):
+ env["UNSLOTH_STUDIO_HOME"] = os.environ["UNSLOTH_IDEMPOTENCY_STUDIO_HOME"]
+ if offline:
+ env["UV_OFFLINE"] = "1"
+ else:
+ env.pop("UV_OFFLINE", None)
+ command = [str(_venv_python()), "-I", "-X", "utf8", "-m", "unsloth_cli", "studio", "update"]
+ if local:
+ command.append("--local")
+ started = time.time()
+ try:
+ completed = subprocess.run(
+ command,
+ cwd = str(_home()),
+ env = env,
+ capture_output = True,
+ text = True,
+ encoding = "utf-8",
+ errors = "replace",
+ timeout = 3600,
+ )
+ text = completed.stdout + completed.stderr
+ rc = completed.returncode
+ finally:
+ seconds = time.time() - started
+ # Read first: a proxy that died mid-run journalled nothing after, and a CONNECT refused by a
+ # dead listener looks like no connection at all.
+ proxy_died = process.poll() is not None
+ settled = _settle_journal(log_path)
+ process.terminate()
+ try:
+ process.wait(timeout = 10)
+ except subprocess.TimeoutExpired: # pragma: no cover - a wedged tunnel
+ process.kill()
+ (directory / "update.log").write_text(text, encoding = "utf-8")
+ assert not proxy_died, (
+ f"{label}: the measurement proxy exited (code {process.returncode}) before the update "
+ "finished; its journal is incomplete and proves nothing about connections"
+ )
+ assert settled, (
+ f"{label}: the update finished while a proxy worker was still between accept and "
+ "its journal record; the journal is incomplete and proves nothing about connections"
+ )
+ summary = _load_proxy_module().summary(str(log_path))
+ run = ProxyRun(directory, text, summary, seconds, rc)
+ print(f"[idempotency] {label}: {run.report()}", flush = True)
+ return run
+
+
+def _load_proxy_module():
+ import importlib.util
+
+ spec = importlib.util.spec_from_file_location("idempotency_proxy", PROXY)
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return module
+
+
+# ── the snapshot ──
+
+
+def _digest(path: pathlib.Path) -> str | None:
+ try:
+ return hashlib.sha256(path.read_bytes()).hexdigest()
+ except OSError:
+ return None
+
+
+def _tree_state(root: pathlib.Path) -> dict | None:
+ """File count and newest mtime. Cheap enough for a sidecar of 4000 files, and it
+ moves the moment anything in the tree is rewritten."""
+ if not root.is_dir():
+ return None
+ count = 0
+ newest = 0.0
+ total = 0
+ for path in root.rglob("*"):
+ try:
+ stat = path.stat()
+ except OSError:
+ continue
+ if path.is_file():
+ count += 1
+ total += stat.st_size
+ newest = max(newest, stat.st_mtime)
+ return {"files": count, "bytes": total, "newest_mtime": round(newest, 3)}
+
+
+def snapshot(venv_python: pathlib.Path) -> dict:
+ studio_home = _studio_home()
+ venv = venv_python.parent.parent
+ unsloth_home = _unsloth_home()
+ state: dict = {}
+ distributions = subprocess.run(
+ [str(venv_python), "-I", "-c", DIST_LIST],
+ capture_output = True,
+ text = True,
+ timeout = 300,
+ )
+ state["distributions"] = json.loads(distributions.stdout or "[]")
+ records = subprocess.run(
+ [str(venv_python), "-I", "-c", DIST_RECORDS],
+ capture_output = True,
+ text = True,
+ timeout = 300,
+ )
+ # FULL_PASS_CHURN moves its RECORD on every full pass: mtime and size are not compared, name and
+ # version still are.
+ state["dist_records"] = [
+ [name, version, None, None] if name in FULL_PASS_CHURN else [name, version, mtime, size]
+ for name, version, mtime, size in json.loads(records.stdout or "[]")
+ ]
+
+ manifest_path = venv / "unsloth_install_manifest.json"
+ manifest = None
+ if manifest_path.is_file():
+ manifest = json.loads(manifest_path.read_text(encoding = "utf-8"))
+ # The one key ALLOWED to move: a pass that correctly did nothing still finished.
+ manifest.pop("completed_at_ms", None)
+ state["manifest"] = manifest
+
+ # Byte for byte: the point of the prebuilt pre-checks is that they do not rewrite the marker.
+ for marker in (
+ "UNSLOTH_PREBUILT_INFO.json",
+ "UNSLOTH_WHISPER_PREBUILT_INFO.json",
+ "UNSLOTH_NODE_PREBUILT_INFO.json",
+ ):
+ found = sorted(unsloth_home.glob(f"*/{marker}")) if unsloth_home.is_dir() else []
+ # The digest alone cannot see a rewrite with identical bytes; the mtime can.
+ state[marker] = {
+ str(p.relative_to(unsloth_home)): (_digest(p), p.stat().st_mtime_ns) for p in found
+ }
+
+ state["uv_cache_marker"] = _digest(studio_home / "cache" / "uv-cache-dir")
+ state["no_torch_marker"] = (venv / ".unsloth-no-torch").is_file()
+ for name in (".venv_t5_530", ".venv_t5_550", ".venv_t5_510"):
+ state[name] = _tree_state(studio_home / name)
+
+ binaries: dict[str, float] = {}
+ if unsloth_home.is_dir():
+ for pattern in (
+ "llama.cpp/**/llama-server*",
+ "llama.cpp/**/llama-quantize*",
+ "whisper.cpp/**/whisper-server*",
+ "node/**/node*",
+ ):
+ for path in unsloth_home.glob(pattern):
+ if path.is_file():
+ binaries[str(path.relative_to(unsloth_home))] = round(path.stat().st_mtime, 3)
+ state["binaries"] = binaries
+ return state
+
+
+def diff(before: dict, after: dict) -> list[str]:
+ return [key for key in sorted(set(before) | set(after)) if before.get(key) != after.get(key)]
+
+
+# ── run 1 and run 2 ──
+
+
[email protected](scope = "session")
+def settled(install, tmp_path_factory):
+ """One update, so whatever the install left half-decided is decided. Everything
+ below measures the update AFTER this one."""
+ directory = tmp_path_factory.mktemp("idempotency")
+ run = run_update(directory, "run1-settle")
+ assert run.rc == 0, f"the first update failed:\n{run.log[-8000:]}"
+ return directory, snapshot(install)
+
+
+def test_a_second_update_changes_nothing_on_disk(install, settled):
+ directory, before = settled
+ run = run_update(directory, "run2-noop")
+ assert run.rc == 0, run.log[-8000:]
+ after = snapshot(install)
+ assert diff(before, after) == [], "a no-op update rewrote part of the install:\n" + "\n".join(
+ f" {key}:\n before={before.get(key)!r}\n after={after.get(key)!r}"
+ for key in diff(before, after)
+ )
+ # The same run's traffic too: a download parked in an npm or uv cache leaves the snapshot alone
+ # and is quiet by the network case that follows.
+ for host in PAYLOAD_HOSTS:
+ assert run.connections_to(host) == 0, f"{host}: {run.report()}"
+ assert run.bytes_from(host) == 0, f"{host}: {run.report()}"
+ assert_read_metadata_but_no_payload(run)
+
+
+def test_a_second_update_downloads_no_payload(install, settled):
+ """The measurement the timings cannot make: a fast run and a run that refetched
+ three release manifests look the same on a warm cache."""
+ directory, _ = settled
+ run = run_update(directory, "run3-network")
+ assert run.rc == 0, run.log[-8000:]
+ for host in PAYLOAD_HOSTS:
+ # Connections, not only bytes: a failed attempt is still a fetch the update decided to make.
+ assert run.connections_to(host) == 0, (
+ f"{host} was contacted {run.connections_to(host)} time(s) by an update with "
+ f"nothing to do: {run.report()}"
+ )
+ assert run.bytes_from(host) == 0, (
+ f"{host} served {run.bytes_from(host)} bytes to an update with nothing to "
+ f"do: {run.report()}"
+ )
+ assert_read_metadata_but_no_payload(run)
+
+
+def test_a_second_local_update_reuses_everything_it_can(install, settled):
+ """--local is the CI and developer path. It always runs the dependency pass, without
+ last run's evidence (a checkout is a development install shape, and a checkout can
+ change in ways no requirements digest sees), so what it demonstrates is the rest:
+ the pip bootstrap skip, all three sidecars answering "current" without a rebuild,
+ and both prebuilts answering from their markers."""
+ directory, _ = settled
+ run = run_update(directory, "run4-local", local = True)
+ assert run.rc == 0, run.log[-8000:]
+ # The full message: several other steps end in the same suffix.
+ assert "pip bootstrap (satisfied, skipped)" in run.log, (
+ "the pip bootstrap reinstalled pip on a venv that already had one:\n" + run.log[-8000:]
+ )
+ assert FRONTEND_CURRENT_MARKER.search(run.log), (
+ "the frontend was rebuilt on a checkout whose dist was already current:\n" + run.log[-8000:]
+ )
+ assert run.log.count("sidecar current") == 3, (
+ "a settled transformers sidecar was rebuilt:\n" + run.log[-8000:]
+ )
+ # One line each from llama.cpp and whisper.cpp: a single match would let one re-validate.
+ assert run.log.count("prebuilt up to date") >= 2, (
+ "a prebuilt was re-validated instead of answered from its marker:\n" + run.log[-8000:]
+ )
+ assert "falling back to source build" not in run.log
+ for host in PAYLOAD_HOSTS:
+ assert run.connections_to(host) == 0, f"{host}: {run.report()}"
+ assert run.bytes_from(host) == 0, f"{host}: {run.report()}"
+ assert_read_metadata_but_no_payload(run)
+ # The release is never listed. Not zero: this is the --local pass, and uv resolves the zoo
+ # overlay's git ref through the API before cloning (see MAX_API_GITHUB_LOCAL).
+ assert run.connections_to("api.github.com") <= MAX_API_GITHUB_LOCAL, run.report()
+ assert run.connections_to("github.com") <= MAX_GITHUB_LOCAL, run.report()
+
+
+# ── offline ──
+
+
+def test_the_desktop_update_path_keeps_a_verified_install_offline(install, settled):
+ """UV_OFFLINE plus a proxy that 403s everything. Every attempt is still recorded, so
+ this asserts zero SUCCESSFUL connections, not merely zero bytes.
+
+ Non-local only, and not because --local is uninteresting: --local re-overlays
+ `unsloth-zoo @ git+main` on every run by design, so it cannot complete without a
+ network on any branch of this code, and a run that fails mid-pass leaves no manifest
+ behind. The flow a user is in on a plane is this one.
+
+ Without the rule this PR adds, an unreachable PyPI means "update to be safe", which
+ offline can only fail: the pass starts, the first git requirement 403s, and the
+ update exits non-zero on an install that was already complete.
+ """
+ directory, before = settled
+ run = run_update(directory, "run6-offline", local = False, offline = True, refuse = True)
+ assert run.rc == 0, (
+ "an update with nothing to do failed offline. That is the state a user on a "
+ f"plane, or behind a corporate proxy, is in:\n{run.log[-8000:]}"
+ )
+ # Either the offline rule or the ordinary fast path: Invoke-RestMethod ignores HTTPS_PROXY, so
+ # on Windows the version check can still answer "up to date". Either way nothing got through the
+ # proxy and nothing on disk moved.
+ assert "keeping the verified install" in run.log or UPTODATE_MARKER.search(run.log), run.log[
+ -8000:
+ ]
+ assert run.connections == run.refused, run.report()
+ assert diff(before, snapshot(install)) == []
+
+
+# Fault injection: each case damages one thing and asserts the update repairs THAT thing, and where
+# cheap to check, nothing else.
+
+
+def _replace_bytes(path: pathlib.Path, data: bytes) -> None:
+ """Write *data* to a NEW inode at *path*, so a hardlinked original is left alone."""
+ path.unlink()
+ path.write_bytes(data)
+
+
+def _sidecar_dirs() -> list[pathlib.Path]:
+ return [
+ path
+ for path in (
+ _studio_home() / name for name in (".venv_t5_530", ".venv_t5_550", ".venv_t5_510")
+ )
+ if path.is_dir()
+ ]
+
+
+def test_a_truncated_sidecar_file_rebuilds_only_that_sidecar(install, settled):
+ directory, before = settled
+ sidecars = _sidecar_dirs()
+ if not sidecars:
+ pytest.skip("no transformers sidecars in this install")
+ target = sidecars[0]
+ victim = next(
+ (p for p in sorted(target.rglob("*.py")) if p.stat().st_size > 0),
+ None,
+ )
+ assert victim is not None, f"no file to damage in {target}"
+ saved = victim.read_bytes()
+ # Replaced, not truncated in place: uv hardlinks --target trees from its cache (NTFS too), so an
+ # in-place truncation would poison the cache and every tier with it.
+ _replace_bytes(victim, b"")
+ try:
+ run = run_update(directory, "fault-sidecar", local = True)
+ assert run.rc == 0, run.log[-8000:]
+ # Judged before the cleanup, which would restore the bytes and advance the mtime.
+ restored = victim.read_bytes() if victim.is_file() else b""
+ assert restored != b"", "the update exited 0 and left the truncated sidecar file as it was"
+ assert (
+ restored == saved
+ ), "the rebuilt sidecar file differs from the bytes the settled install had"
+ finally:
+ if victim.is_file() and victim.read_bytes() == b"":
+ _replace_bytes(victim, saved)
+ after = snapshot(install)
+ changed = diff(before, after)
+ assert target.name in changed, f"the damaged sidecar was not rebuilt (changed: {changed})"
+ # Exactly the damaged component; the manifest may move, as it records the renewed evidence.
+ unexpected = sorted(set(changed) - {target.name, "manifest"})
+ assert unexpected == [], f"the sidecar repair changed more than the damaged sidecar: {changed}"
+
+
+def test_a_deleted_manifest_re_runs_the_pass_and_changes_nothing(install, settled):
+ """The manifest is the only record of what the last pass did. Without it every step
+ must run -- and every step must then find its work already done, so the venv comes
+ out identical."""
+ directory, _ = settled
+ manifest = install.parent.parent / "unsloth_install_manifest.json"
+ saved = manifest.read_bytes()
+ # Baseline taken here: the fault tests before this one legitimately move records.
+ before = snapshot(install)
+ manifest.unlink()
+ try:
+ run = run_update(directory, "fault-manifest", local = True)
+ assert run.rc == 0, run.log[-8000:]
+ # Judged before the cleanup puts the saved copy back.
+ assert manifest.is_file(), "the pass exited 0 without rewriting the manifest"
+ finally:
+ if not manifest.is_file():
+ manifest.write_bytes(saved)
+ after = snapshot(install)
+ assert (
+ after["distributions"] == before["distributions"]
+ ), "a pass with no evidence resolved to a different set of packages"
+ assert after["manifest"] is not None, "the pass did not rewrite the manifest"
+ # A pass with no evidence re-checks every component and must leave the valid ones alone; the
+ # manifest itself is the one key allowed to differ.
+ untouched = [key for key in diff(before, after) if key not in ("manifest", "dist_records")]
+ assert untouched == [], (
+ "a pass with no evidence redid work on already-valid components: " + ", ".join(untouched)
+ )
+ # Names and versions cannot see a same-version reinstall; the RECORD mtime can (FULL_PASS_CHURN
+ # excepted).
+ was = {tuple(record) for record in before["dist_records"]}
+ moved = sorted(record[0] for record in after["dist_records"] if tuple(record) not in was)
+ assert moved == [], "a pass with no evidence reinstalled: " + ", ".join(moved)
+
+
+def test_a_missing_llama_binary_makes_the_marker_check_decline(install, settled):
+ """A runtime binary the install no longer has sends the update back to the release it
+ was skipping.
+
+ MISSING, not corrupt, and that distinction is the whole test. The pre-check is
+ `[ -x .../llama-server ]` (setup.sh:2932) plus the marker fingerprint: it asks whether
+ the file is there, never what is in it. Truncating it, which this case used to do on
+ POSIX, leaves the log and the traffic byte-identical, so only the Windows branch (which
+ unlinked) ever damaged anything the check could see. Both halves of the symlink pair now
+ go on every platform. That a CORRUPT binary survives unnoticed is a real gap in the
+ product's damage detection, left unasserted here rather than blessed as intended.
+
+ Measured on the network, because setup.sh reprints the same line either way, and by SIZE,
+ because every update reads that release's metadata from the same host: an archive coming
+ back is the decline.
+ """
+ directory, before = settled
+ candidates = sorted(_unsloth_home().glob("llama.cpp/**/llama-server*"))
+ victim = next((p for p in candidates if p.is_file() and p.stat().st_size > 1024), None)
+ if victim is None:
+ pytest.skip("no llama.cpp prebuilt in this install")
+ saved = victim.read_bytes()
+ mode = victim.stat().st_mode
+ # The pre-check accepts EITHER path, so removing one leaves it answering from the other.
+ sibling = _unsloth_home() / "llama.cpp" / "llama-server"
+ sibling_target = (
+ os.readlink(sibling)
+ if sibling.is_symlink()
+ else (sibling.read_bytes() if sibling.is_file() else None)
+ )
+ sibling_was_symlink = sibling.is_symlink()
+ victim.unlink()
+ if sibling_target is not None and sibling != victim:
+ sibling.unlink()
+ try:
+ run = run_update(directory, "fault-llama", local = True)
+ assert run.rc == 0, run.log[-8000:]
+ assert run.largest_transfer_from(PREBUILT_METADATA_HOST) > PREBUILT_METADATA_CEILING, (
+ "a missing runtime binary was still answered from the marker -- nothing larger "
+ "than the release metadata every update reads came back: " + run.report()
+ )
+ finally:
+ if not victim.exists():
+ victim.write_bytes(saved)
+ if sibling_target is not None and not sibling.exists():
+ if sibling_was_symlink:
+ os.symlink(sibling_target, sibling)
+ else:
+ sibling.write_bytes(sibling_target)
+ victim.chmod(mode)
+ assert snapshot(install)["distributions"] == before["distributions"]
+
+
+def test_the_manifest_records_the_evidence_the_next_run_needs(install, settled):
+ """Every skip is conditional on this. A pass that finished but recorded nothing is
+ not a bug anyone would notice until the NEXT update quietly redoes everything -- or,
+ worse, skips on a key it happens to find and cannot check.
+
+ Not a test that an edited requirements file re-runs its step: --local, which is what
+ this harness and CI install with, never skips anything (a checkout can change in ways
+ no requirements digest sees), so there would be nothing to observe. That gate is
+ covered by tests/studio/install/test_dependency_pass_skips.py.
+ """
+ _directory, _before = settled
+ # The manifest on disk now: the previous case regenerated it, and that copy is what the next
+ # update's skips read.
+ manifest_path = install.parent.parent / "unsloth_install_manifest.json"
+ manifest = json.loads(manifest_path.read_text(encoding = "utf-8"))
+ assert manifest is not None, "the install finished without a manifest"
+ inputs = manifest.get("pass_inputs")
+ assert isinstance(inputs, dict) and inputs, "no pass_inputs recorded"
+ assert all(isinstance(v, str) and len(v) == 64 for v in inputs.values()), inputs
+ steps = manifest.get("step_results")
+ assert isinstance(steps, dict) and steps, "no step_results recorded"
+ # The keys a later run gates on, spelled the same way it will look them up.
+ for key in ("studio.txt", "base.txt"):
+ assert key in inputs, f"{key} is not in {sorted(inputs)}"
+ assert manifest.get("installer_python_tag"), manifest.keys()
+
+
+def test_full_deps_forces_every_step_and_still_changes_nothing(install, settled):
+ """The escape hatch. It must do the work -- no "(satisfied, skipped)" anywhere --
+ and arrive at the same venv, which is what makes the skips safe."""
+ directory, before = settled
+ env_backup = os.environ.get("UNSLOTH_STUDIO_FULL_DEPS")
+ os.environ["UNSLOTH_STUDIO_FULL_DEPS"] = "1"
+ try:
+ run = run_update(directory, "fault-full-deps", local = True)
+ finally:
+ if env_backup is None:
+ os.environ.pop("UNSLOTH_STUDIO_FULL_DEPS", None)
+ else:
+ os.environ["UNSLOTH_STUDIO_FULL_DEPS"] = env_backup
+ assert run.rc == 0, run.log[-8000:]
+ assert "(satisfied, skipped)" not in run.log, (
+ "UNSLOTH_STUDIO_FULL_DEPS still skipped a step:\n" + run.log[-8000:]
+ )
+ after = snapshot(install)
+ assert after["distributions"] == before["distributions"], (
+ "doing every step produced a different venv from skipping the settled ones, so "
+ "at least one skip was not equivalent to the work it replaced"
+ )
+
+
+def test_the_install_is_left_working(install, settled):
+ """Runs last. The fault cases legitimately move mtimes -- a rebuilt sidecar is a
+ rebuilt sidecar -- so this asserts what has to be true anyway: the same packages are
+ installed, and the install reports itself complete."""
+ _directory, before = settled
+ _assert_install_working(install, before)
+
+
+def _assert_install_working(
+ install: pathlib.Path,
+ before: dict,
+ *,
+ same_distributions: bool = True,
+) -> None:
+ """The same packages as *before* are installed, and the CLI reports the install
+ complete. Shared by the last ordered case and the desktop case's restore, which is
+ the last product operation of the run and is otherwise judged by exit code alone.
+
+ After a real upgrade to PyPI's release the restore reinstalls the checkout only where
+ needed, and a transitive dependency the release moved that the checkout's ranges
+ still admit legitimately stays: then only the checkout's own packages are held to
+ *before*."""
+ after = snapshot(install)
+ if same_distributions:
+ assert after["distributions"] == before["distributions"]
+ else:
+ core = lambda dists: sorted(d for d in dists if d[0] in LOCAL_CORE) # noqa: E731
+ assert core(after["distributions"]) == core(before["distributions"])
+ assert core(after["distributions"]), "the checkout's own packages are gone"
+ assert after["manifest"] is not None
+ verify_env = {**os.environ, "HOME": str(_home()), "USERPROFILE": str(_home())}
+ # The same root the measured runs used, or the CLI verifies a default one.
+ if os.environ.get("UNSLOTH_IDEMPOTENCY_STUDIO_HOME"):
+ verify_env["UNSLOTH_STUDIO_HOME"] = os.environ["UNSLOTH_IDEMPOTENCY_STUDIO_HOME"]
+ verify = subprocess.run(
+ [str(install), "-I", "-X", "utf8", "-m", "unsloth_cli", "studio", "verify-install"],
+ env = verify_env,
+ capture_output = True,
+ text = True,
+ timeout = 600,
+ )
+ assert verify.returncode == 0, verify.stdout + verify.stderr
+
+
+def test_the_harness_measures_a_real_proxy(tmp_path):
+ """A proxy that silently failed to start would make every assertion above pass, and
+ so would one that relays a tunnel without counting its bytes: the byte ceilings are
+ the only bound on hosts that are allowed through. So both halves are exercised: a
+ refused CONNECT, and an allowed one carrying a response of known size."""
+ import http.server
+ import socket
+ import threading
+ import urllib.error
+ import urllib.request
+ from urllib.parse import urlsplit
+
+ body = b"x" * 4096
+
+ class _Handler(http.server.BaseHTTPRequestHandler):
+ def do_GET(self):
+ self.send_response(200)
+ self.send_header("Content-Length", str(len(body)))
+ self.end_headers()
+ self.wfile.write(body)
+
+ def log_message(self, *_args):
+ pass
+
+ upstream = http.server.HTTPServer(("127.0.0.1", 0), _Handler)
+ threading.Thread(target = upstream.serve_forever, daemon = True).start()
+ module = _load_proxy_module()
+ process, url, log_path = _start_proxy(tmp_path, "--deny-hosts", "pypi.org")
+ try:
+ opener = urllib.request.build_opener(
+ urllib.request.ProxyHandler({"http": url, "https": url})
+ )
+ # A refused CONNECT is a URLError: urllib never gets a tunnel to raise an HTTP status
+ # through.
+ with pytest.raises(urllib.error.URLError) as excinfo:
+ opener.open("https://pypi.org/simple/", timeout = 30)
+ assert "403" in str(excinfo.value)
+ # The proxy journals before it answers (Proxy.handle's refused branch), so only an in-flight
+ # write is absorbed here; a proxy that stopped journalling must fail loudly.
+ if not _wait_until(lambda: module.summary(str(log_path))["connections"] >= 1):
+ pytest.fail(f"the proxy answered 403 but never journalled the connection: {log_path}")
+ # An allowed tunnel by hand: CONNECT, then a GET through it; the bytes must match the
+ # journal.
+ proxy = urlsplit(url)
+ port = upstream.server_address[1]
+ with socket.create_connection((proxy.hostname, proxy.port), timeout = 30) as tunnel:
+ tunnel.sendall(
+ f"CONNECT 127.0.0.1:{port} HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\n\r\n".encode()
+ )
+ head = b""
+ while b"\r\n\r\n" not in head:
+ chunk = tunnel.recv(4096)
+ assert chunk, "the proxy closed the tunnel before answering CONNECT"
+ head += chunk
+ assert head.split(b"\r\n", 1)[0].split()[1] == b"200", head
+ tunnel.sendall(b"GET / HTTP/1.0\r\nHost: 127.0.0.1\r\n\r\n")
+ received = b""
+ while True:
+ chunk = tunnel.recv(65536)
+ if not chunk:
+ break
+ received += chunk
+ assert received.endswith(body), received[:200]
+ counted = (
+ lambda: module.summary(str(log_path))["by_host"]
+ .get("127.0.0.1", {})
+ .get("bytes_down", 0)
+ )
+ if not _wait_until(lambda: counted() >= len(body)):
+ pytest.fail(
+ f"the proxy relayed {len(received)} bytes but journalled {counted()} for the host: {log_path}"
+ )
+ finally:
+ process.terminate()
+ process.wait(timeout = 10)
+ upstream.shutdown()
+ summary = module.summary(str(log_path))
+ assert summary["connections"] == 2 and summary["refused"] == 1
+ assert summary["by_host"]["127.0.0.1"]["bytes_down"] >= len(body)
+ assert summary["by_host"]["pypi.org"]["bytes_down"] == 0
+
+
+# The desktop path, last: when the installed version is not PyPI's latest this is a real upgrade,
+# and anything measured after it would be measuring the released package.
+
+
+def test_the_desktop_update_path_does_no_network_work(install, settled):
+ """No --local: the flow the desktop app and the Repair button run. Its whole cost on
+ a settled install should be one version check and the prebuilt HEADs.
+
+ Judged only when the version check short-circuited, read off the measured run's own
+ log rather than a separate request to PyPI made earlier (which can fail or see another
+ release than the one the update saw). With a version
+ mismatch this run IS an upgrade to PyPI's release, whose Node, sidecar, llama.cpp and
+ whisper.cpp pins can differ from the checkout's, and an upgrade that rebuilds or
+ downloads those is behaving correctly; a version bump would otherwise fail this
+ smoke test for doing its job. The run still has to succeed on that branch, and the
+ checkout is put back for the workflow steps after this harness.
+ """
+ directory, _ = settled
+ # Its own baseline: the fault-injection cases before it legitimately moved things.
+ before = snapshot(install)
+ # Read BEFORE the run: after it the installed version may already be PyPI's.
+ installed, latest = _installed_version(install), _pypi_latest()
+ print(f"[idempotency] installed={installed!r} pypi={latest!r}", flush = True)
+ run = run_update(directory, "run5-desktop", local = False)
+ assert run.rc == 0, run.log[-8000:]
+ took_fast_path = NO_WORK_MARKERS[0] in run.log
+ if not took_fast_path:
+ # The checkout goes back first either way: later workflow steps expect the code under test.
+ # Held to the same bar as the ordered cases, not its exit code alone.
+ restore = run_update(directory, "run5-restore", local = True)
+ assert restore.rc == 0, restore.log[-8000:]
+ _assert_install_working(install, before, same_distributions = UPGRADE_MARKER not in run.log)
+ # Why the pass ran, off the measured run's own log: the separate lookup can see another
+ # release.
+ if UPGRADE_MARKER in run.log:
+ # A real upgrade to PyPI's release, whose pins may differ: nothing below can be
+ # asserted.
+ pytest.skip(
+ "installed version is not PyPI's latest; the desktop no-op path was not taken"
+ )
+ if PYPI_UNREACHABLE_MARKER in run.log:
+ # The pass runs on purpose when PyPI cannot be asked: nothing to judge. Only the
+ # measured run's own lookup counts, or this would look away from the equal-version pass.
+ pytest.skip("PyPI was unreachable; the desktop no-op path could not be judged")
+ # Equal versions, a reachable index, and the pass still ran: the regression this catches.
+ pytest.fail(
+ f"the desktop update ran the dependency pass with unsloth {installed!r} installed "
+ f"and {latest!r} on PyPI; the fast path was not taken:\n{run.log[-8000:]}"
+ )
+ for host in PAYLOAD_HOSTS:
+ assert run.connections_to(host) == 0, f"{host}: {run.report()}"
+ assert run.bytes_from(host) == 0, f"{host}: {run.report()}"
+ assert run.bytes_from("raw.githubusercontent.com") <= ICON_FETCH_CEILING, run.report()
+ for marker in NO_WORK_MARKERS:
+ assert marker in run.log, f"{marker!r} missing from a no-op update:\n{run.log[-8000:]}"
+ # Each component, not the generic line once.
+ assert run.log.count("prebuilt up to date") >= 2, run.log[-8000:]
+ assert run.log.count("sidecar current") == 3, run.log[-8000:]
+ # One version check per run; the bounds stop a full listing or a payload returning.
+ assert run.connections_to("pypi.org") <= 2, run.report()
+ assert run.connections_to("github.com") <= MAX_GITHUB_DESKTOP, run.report()
+ # The other half of the prebuilt claim: the release itself is never listed. Zero everywhere the
+ # download-host fast path applies, which is everywhere except macOS llama.cpp.
+ assert run.connections_to("api.github.com") <= MAX_API_GITHUB_DESKTOP, run.report()
+ assert_read_metadata_but_no_payload(run)
+ assert diff(before, snapshot(install)) == []
diff --git a/tests/studio_setup_ps1/Studio.Setup.OfflineFastPath.Tests.ps1 b/tests/studio_setup_ps1/Studio.Setup.OfflineFastPath.Tests.ps1
new file mode 100644
index 00000000000..f28eb710e8c
--- /dev/null
+++ b/tests/studio_setup_ps1/Studio.Setup.OfflineFastPath.Tests.ps1
@@ -0,0 +1,445 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+<#
+ `unsloth studio update` treats an unreachable PyPI as a reason to update anyway,
+ which is right for a blip. It is wrong when the caller SET UV_OFFLINE: uv then
+ refuses to reach a network at all, so the pass that follows can only fail, and an
+ install that was already complete ends the update broken-looking and non-zero.
+
+ Test-UvOfflineRequested is what tells those two apart, so it has to read the same
+ boolish spellings the POSIX half does -- a user who wrote UV_OFFLINE=true on one
+ platform means the same thing on the other.
+#>
+
+BeforeAll {
+ . (Join-Path $PSScriptRoot 'Get-FunctionSource.ps1')
+
+ $candidates = @(
+ $env:SETUP_PS1_PATH,
+ (Join-Path $PSScriptRoot '..\..\studio\setup.ps1')
+ ) | Where-Object { $_ }
+ $script:SetupPs1 = $candidates | Where-Object { Test-Path -LiteralPath $_ } | Select-Object -First 1
+ if (-not $script:SetupPs1) { throw "Could not locate studio/setup.ps1 (set SETUP_PS1_PATH)." }
+
+ $src = Get-FunctionSource -Path $script:SetupPs1 -Name 'Test-UvOfflineRequested'
+ if (-not $src) { throw "Test-UvOfflineRequested is gone from setup.ps1." }
+ . ([scriptblock]::Create($src))
+
+ $script:SetupText = Get-Content -Raw -LiteralPath $script:SetupPs1
+ $script:SavedOffline = $env:UV_OFFLINE
+}
+
+AfterAll {
+ if ($null -eq $script:SavedOffline) {
+ Remove-Item Env:UV_OFFLINE -ErrorAction SilentlyContinue
+ } else {
+ $env:UV_OFFLINE = $script:SavedOffline
+ }
+}
+
+Describe 'Test-UvOfflineRequested' {
+ It 'accepts <value>' -ForEach @(
+ @{ value = '1' }, @{ value = 'true' }, @{ value = 'TRUE' }, @{ value = 'True' },
+ @{ value = 'yes' }, @{ value = 'on' }, @{ value = ' true ' },
+ @{ value = 't' }, @{ value = 'T' }, @{ value = 'y' }
+ ) {
+ $env:UV_OFFLINE = $value
+ Test-UvOfflineRequested | Should -BeTrue
+ }
+
+ It 'rejects <value>' -ForEach @(
+ @{ value = '0' }, @{ value = 'false' }, @{ value = '' }, @{ value = 'maybe' },
+ @{ value = 'offline' }, @{ value = 'tr' }
+ ) {
+ $env:UV_OFFLINE = $value
+ Test-UvOfflineRequested | Should -BeFalse
+ }
+
+ It 'reads an unset variable as not offline' {
+ Remove-Item Env:UV_OFFLINE -ErrorAction SilentlyContinue
+ Test-UvOfflineRequested | Should -BeFalse
+ }
+}
+
+Describe 'the offline skip' {
+ It 'is gated on an installed version, offline mode and a verified tree' {
+ $script:SetupText | Should -Match ([regex]::Escape(
+ 'if ($InstalledVer -and (Test-UvOfflineRequested) -and (Test-StudioInstallVerified)) {'))
+ }
+
+ It 'still updates to be safe when any condition fails' {
+ # The else branch is the whole default behaviour; losing it turns every
+ # unreachable-PyPI update into a silent skip.
+ $script:SetupText | Should -Match 'could not reach PyPI, updating to be safe'
+ }
+
+ It 'asks the same question the incomplete-install guard asks' {
+ ([regex]::Matches($script:SetupText, [regex]::Escape('verify_install(**deep)'))).Count |
+ Should -Be 1
+ }
+}
+
+<#
+ Keeping a verified install is only half the rule. A tree can verify and still be
+ below the backend version the desktop app requires, hold the anyio/tokenizers damage,
+ or sit on a CPU wheel next to an Intel or AMD GPU -- and only the dependency pass
+ repairs any of that. The up-to-date branch has always escaped on those; the offline
+ branch used to skip past every one of them, so an offline `unsloth studio update` of a
+ below-floor install reported success and repaired nothing.
+
+ Both branches now reach them through Invoke-FastPathEscapes. This runs the real
+ offline branch and the real helper, sliced out of setup.ps1 into a standalone driver
+ script -- a script, not a dot-sourced scriptblock, because the helper writes
+ $script:SkipPythonDeps and the scope it means has to be a real script scope.
+#>
+Describe 'the offline skip takes the shared escapes' {
+ BeforeAll {
+ $escapeSrc = Get-FunctionSource -Path $script:SetupPs1 -Name 'Invoke-FastPathEscapes'
+ if (-not $escapeSrc) { throw "Invoke-FastPathEscapes is gone from setup.ps1." }
+ if ($escapeSrc -notmatch 'UNSLOTH_DESKTOP_BACKEND_VERSION') {
+ throw "Invoke-FastPathEscapes no longer consults UNSLOTH_DESKTOP_BACKEND_VERSION."
+ }
+ $offlineSrc = Get-FunctionSource -Path $script:SetupPs1 -Name 'Test-UvOfflineRequested'
+
+ # The offline arm itself, sliced rather than restated: a branch that stopped calling the
+ # helper has to fail this file.
+ $lines = $script:SetupText -split "`r?`n"
+ $start = -1
+ for ($i = 0; $i -lt $lines.Count; $i++) {
+ if ($lines[$i] -match '^\s*\}\s*elseif \(-not \$LatestVer\) \{\s*$') { $start = $i; break }
+ }
+ if ($start -lt 0) { throw "the '-not `$LatestVer' arm is gone from setup.ps1." }
+ $end = -1
+ for ($i = $start + 1; $i -lt $lines.Count; $i++) {
+ if ($lines[$i] -eq ' }') { $end = $i; break }
+ }
+ if ($end -lt 0) { throw "could not find the end of the '-not `$LatestVer' arm." }
+ $branch = $lines[($start + 1)..($end - 1)] -join "`n"
+ # A slice that lost either half would let every case below pass vacuously.
+ if ($branch -notmatch 'Invoke-FastPathEscapes') {
+ throw ("the offline arm no longer calls Invoke-FastPathEscapes -- an offline skip " +
+ "that ducks the shared escapes reports success and repairs nothing.")
+ }
+ if ($branch -notmatch 'could not reach PyPI') {
+ throw "the offline arm lost its updating-to-be-safe default."
+ }
+
+ $script:DriverDir = Join-Path ([System.IO.Path]::GetTempPath()) ("unsloth-offline-" + [guid]::NewGuid())
+ New-Item -ItemType Directory -Path $script:DriverDir -Force | Out-Null
+ $script:DriverPath = Join-Path $script:DriverDir 'driver.ps1'
+
+ $prelude = @'
+param(
+ [AllowEmptyString()][string]$InstalledVer,
+ [AllowEmptyString()][string]$UvOffline,
+ [AllowEmptyString()][string]$DesktopVer,
+ [bool]$Verified
+)
+$env:UV_OFFLINE = $UvOffline
+$env:UNSLOTH_DESKTOP_BACKEND_VERSION = $DesktopVer
+$LatestVer = ""
+$SkipPythonDeps = $false
+$installedTorchTag = "cu128"
+$NoTorchMode = $false
+$VenvDir = Join-Path $PSScriptRoot "venv"
+$_PkgName = "unsloth"
+$script:IsIntelXpu = $false
+$script:ROCmGfxArch = $null
+$script:Substeps = @()
+
+function step { param([string]$a, [string]$b, [string]$c) }
+function substep { param([string]$Message, [string]$Color = "DarkGray") $script:Substeps += $Message }
+function Test-StudioInstallVerified { return $Verified }
+function Get-PinnedTorchIndexUrl { return "" }
+function Get-TorchIndexLeaf { param([AllowNull()][string]$Url) return "" }
+function Invoke-BoundedPythonProbe {
+ param([string]$PythonExe, [string]$Code, [int]$TimeoutSec = 30)
+ return [pscustomobject]@{ Ok = $true; Output = ""; Error = ""; TimedOut = $false }
+}
+function Test-VenvTorchIsXpuSupported { param([string]$VenvPath) return $true }
+function python {
+ # Not the real interpreter. The escapes ask three fixed questions and read the answer
+ # out of $LASTEXITCODE, so this answers them directly; a function call does not set
+ # $LASTEXITCODE by itself, hence the explicit $global: writes.
+ $code = [string]$args[1]
+ if ($code -match 'anyio') { $global:LASTEXITCODE = 1; return }
+ if ($code -match 'tokenizers') { $global:LASTEXITCODE = 1; return }
+ if ($code -match 'parse_v') {
+ # Mirrors the interpreter's own no-packaging fallback: anything that is not a plain
+ # three-part version cannot be ordered, and unorderable forces the dependency pass.
+ $installed = [string]$args[2]
+ $required = [string]$args[3]
+ $plain = '^\d+\.\d+\.\d+$'
+ if ($installed -notmatch $plain -or $required -notmatch $plain) {
+ $global:LASTEXITCODE = 1
+ return
+ }
+ $global:LASTEXITCODE = if ([version]$installed -ge [version]$required) { 0 } else { 1 }
+ return
+ }
+ $global:LASTEXITCODE = 0
+}
+'@
+ $epilogue = @'
+
+"SKIP=$SkipPythonDeps"
+"SUBSTEPS=" + ($script:Substeps -join '|')
+'@
+ Set-Content -LiteralPath $script:DriverPath -Encoding utf8 -Value (
+ $prelude + "`n" + $offlineSrc + "`n" + $escapeSrc + "`n`nif (`$true) {`n" +
+ $branch + "`n}`n" + $epilogue)
+
+ function script:Invoke-OfflineBranch {
+ param([string]$InstalledVer, [string]$UvOffline, [string]$DesktopVer, [bool]$Verified = $true)
+ $out = & $script:DriverPath -InstalledVer $InstalledVer -UvOffline $UvOffline `
+ -DesktopVer $DesktopVer -Verified $Verified
+ $text = ($out | Out-String)
+ $skip = if ($text -match '(?m)^SKIP=(\S+)\s*$') { $Matches[1] } else { "<no SKIP line>" }
+ $steps = if ($text -match '(?m)^SUBSTEPS=(.*)$') { $Matches[1] } else { "" }
+ # Both outcomes announce themselves; neither means the slice never ran.
+ if ($steps -notmatch 'keeping the verified install' -and $steps -notmatch 'could not reach PyPI') {
+ throw "the offline arm did not run (substeps: '$steps', output: '$text')"
+ }
+ return $skip
+ }
+ }
+
+ AfterAll {
+ # Guarded: a failed slice check names no driver directory, and an unguarded Remove-Item
+ # would bury that message.
+ if ($script:DriverDir) {
+ Remove-Item -Recurse -Force -LiteralPath $script:DriverDir -ErrorAction SilentlyContinue
+ }
+ Remove-Item Env:UNSLOTH_DESKTOP_BACKEND_VERSION -ErrorAction SilentlyContinue
+ }
+
+ It 'keeps a verified install when nothing else is owed' {
+ Invoke-OfflineBranch -InstalledVer '2026.8.15' -UvOffline '1' -DesktopVer '' |
+ Should -Be 'True'
+ }
+
+ It 'keeps it when the install already meets the desktop backend floor' {
+ Invoke-OfflineBranch -InstalledVer '2026.8.15' -UvOffline '1' -DesktopVer '2026.8.15' |
+ Should -Be 'True'
+ }
+
+ It 'forces the dependency pass for an install BELOW the desktop backend floor' {
+ # The regression this exists for: verified, offline, and still too old for the
+ # desktop app that launched it. Only the dependency pass raises it.
+ Invoke-OfflineBranch -InstalledVer '2026.8.4' -UvOffline '1' -DesktopVer '2026.8.15' |
+ Should -Be 'False'
+ }
+
+ It 'forces the dependency pass for a requirement it cannot order' {
+ Invoke-OfflineBranch -InstalledVer '2026.8.15' -UvOffline '1' -DesktopVer '2026.8.15.post1' |
+ Should -Be 'False'
+ }
+
+ It 'still updates to be safe when UV_OFFLINE is not set' {
+ Invoke-OfflineBranch -InstalledVer '2026.8.15' -UvOffline '' -DesktopVer '' |
+ Should -Be 'False'
+ }
+
+ It 'still updates to be safe when the tree does not verify' {
+ Invoke-OfflineBranch -InstalledVer '2026.8.15' -UvOffline '1' -DesktopVer '' -Verified $false |
+ Should -Be 'False'
+ }
+
+ It 'still updates to be safe when nothing is installed' {
+ Invoke-OfflineBranch -InstalledVer '' -UvOffline '1' -DesktopVer '' | Should -Be 'False'
+ }
+}
+
+<#
+ UNSLOTH_STUDIO_FULL_DEPS is the documented way out of every dependency-pass skip:
+ install_python_stack.py's _full_deps_requested is written around "a skip nobody can
+ turn off is a bug nobody can work around". But install_python_stack.py is only ever
+ REACHED when $SkipPythonDeps is false, and the version compare above sets it true the
+ moment the installed version equals the PyPI latest -- so on exactly the install the
+ hatch exists for, one that reports "up to date" and still does not work, setting the
+ variable did nothing at all.
+
+ Invoke-FastPathEscapes is where it belongs: the up-to-date branch and the UV_OFFLINE
+ branch both run it, so neither can honour the hatch while the other ignores it. The
+ driver below is the real helper, sliced out of setup.ps1 the same way as above.
+#>
+Describe 'UNSLOTH_STUDIO_FULL_DEPS reaches the fast path' {
+ BeforeAll {
+ $fullDepsEscapeSrc = Get-FunctionSource -Path $script:SetupPs1 -Name 'Invoke-FastPathEscapes'
+ if (-not $fullDepsEscapeSrc) { throw "Invoke-FastPathEscapes is gone from setup.ps1." }
+ # An unset hatch and an ignored hatch both preserve the skip: this tells them apart.
+ if ($fullDepsEscapeSrc -notmatch 'UNSLOTH_STUDIO_FULL_DEPS') {
+ throw ("Invoke-FastPathEscapes no longer reads UNSLOTH_STUDIO_FULL_DEPS -- the " +
+ "escape hatch is honoured only inside install_python_stack.py, which a " +
+ "skipped dependency pass never runs.")
+ }
+
+ $script:FullDepsDir = Join-Path ([System.IO.Path]::GetTempPath()) ("unsloth-fulldeps-" + [guid]::NewGuid())
+ New-Item -ItemType Directory -Path $script:FullDepsDir -Force | Out-Null
+ $script:FullDepsDriver = Join-Path $script:FullDepsDir 'driver.ps1'
+
+ # Every other probe answers "no repair owed", so only the variable under test can clear the
+ # skip.
+ $fullDepsPrelude = @'
+param(
+ [AllowEmptyString()][string]$FullDeps,
+ [bool]$SetFullDeps,
+ [bool]$StartSkipping
+)
+if ($SetFullDeps) {
+ $env:UNSLOTH_STUDIO_FULL_DEPS = $FullDeps
+} else {
+ Remove-Item Env:UNSLOTH_STUDIO_FULL_DEPS -ErrorAction SilentlyContinue
+}
+# No desktop floor to fail, so that arm cannot clear the skip behind the hatch's back.
+Remove-Item Env:UNSLOTH_DESKTOP_BACKEND_VERSION -ErrorAction SilentlyContinue
+$InstalledVer = "2026.8.15"
+$_PkgName = "unsloth"
+$installedTorchTag = "cu128"
+$NoTorchMode = $false
+$VenvDir = Join-Path $PSScriptRoot "venv"
+$script:IsIntelXpu = $false
+$script:ROCmGfxArch = $null
+$script:Substeps = @()
+# The flag the version compare would have set. A plain assignment at script top level IS
+# $script:SkipPythonDeps, which is what the helper copies in and publishes back.
+$SkipPythonDeps = $StartSkipping
+
+function step { param([string]$a, [string]$b, [string]$c) }
+function substep { param([string]$Message, [string]$Color = "DarkGray") $script:Substeps += $Message }
+function Get-PinnedTorchIndexUrl { return "" }
+function Get-TorchIndexLeaf { param([AllowNull()][string]$Url) return "" }
+function Test-VenvTorchIsXpuSupported { param([string]$VenvPath) return $true }
+function Invoke-BoundedPythonProbe {
+ param([string]$PythonExe, [string]$Code, [int]$TimeoutSec = 30)
+ return [pscustomobject]@{ Ok = $true; Output = ""; Error = ""; TimedOut = $false }
+}
+function python {
+ # Every probe in the helper reads $LASTEXITCODE and treats a nonzero as "nothing to
+ # repair". A function call does not set it by itself, hence the explicit $global: write.
+ $global:LASTEXITCODE = 1
+}
+'@
+ $fullDepsEpilogue = @'
+
+Invoke-FastPathEscapes
+"SKIP=$SkipPythonDeps"
+"SUBSTEPS=" + ($script:Substeps -join '|')
+'@
+ Set-Content -LiteralPath $script:FullDepsDriver -Encoding utf8 -Value (
+ $fullDepsPrelude + "`n" + $fullDepsEscapeSrc + "`n" + $fullDepsEpilogue)
+
+ function script:Invoke-FullDepsEscape {
+ param(
+ [AllowEmptyString()][string]$FullDeps,
+ [bool]$SetFullDeps = $true,
+ [bool]$StartSkipping = $true
+ )
+ $out = & $script:FullDepsDriver -FullDeps $FullDeps -SetFullDeps $SetFullDeps `
+ -StartSkipping $StartSkipping
+ $text = ($out | Out-String)
+ if ($text -notmatch '(?m)^SKIP=(\S+)\s*$') {
+ throw "the escapes did not run (output: '$text')"
+ }
+ return $Matches[1]
+ }
+
+ function script:Get-FullDepsSubsteps {
+ param([AllowEmptyString()][string]$FullDeps, [bool]$SetFullDeps = $true)
+ $out = & $script:FullDepsDriver -FullDeps $FullDeps -SetFullDeps $SetFullDeps -StartSkipping $true
+ $text = ($out | Out-String)
+ if ($text -match '(?m)^SUBSTEPS=(.*)$') { return $Matches[1] }
+ return ""
+ }
+ }
+
+ AfterAll {
+ if ($script:FullDepsDir) {
+ Remove-Item -Recurse -Force -LiteralPath $script:FullDepsDir -ErrorAction SilentlyContinue
+ }
+ Remove-Item Env:UNSLOTH_STUDIO_FULL_DEPS -ErrorAction SilentlyContinue
+ }
+
+ It 'leaves the skip alone when the variable is unset' {
+ # The default. The hatch must cost nothing to the overwhelming majority of updates.
+ Invoke-FullDepsEscape -FullDeps '' -SetFullDeps $false | Should -Be 'True'
+ }
+
+ It 'clears the skip for <value>' -ForEach @(
+ @{ value = '1' }, @{ value = 'true' }, @{ value = 'TRUE' }, @{ value = 'True' },
+ @{ value = 'yes' }, @{ value = 'on' }, @{ value = ' 1 ' }, @{ value = ' true ' }
+ ) {
+ # The spellings Test-UvOfflineRequested and _full_deps_requested accept, the same
+ # everywhere.
+ Invoke-FullDepsEscape -FullDeps $value | Should -Be 'False'
+ }
+
+ It 'leaves the skip alone for <value>' -ForEach @(
+ @{ value = '0' }, @{ value = '' }, @{ value = ' ' }, @{ value = 'maybe' },
+ @{ value = 'false' }, @{ value = 'off' }, @{ value = 'no' }
+ ) {
+ # Not "set means true": a stale FULL_DEPS=0 in a profile must not force every update.
+ Invoke-FullDepsEscape -FullDeps $value | Should -Be 'True'
+ }
+
+ It 'says why it is running the pass' {
+ # A user who set the variable has to see from the log that it took effect.
+ Get-FullDepsSubsteps -FullDeps '1' | Should -Match 'UNSLOTH_STUDIO_FULL_DEPS'
+ }
+
+ It 'says nothing when the hatch is not used' {
+ Get-FullDepsSubsteps -FullDeps '' -SetFullDeps $false |
+ Should -Not -Match 'UNSLOTH_STUDIO_FULL_DEPS'
+ }
+
+ It 'does not turn a forced pass back into a skip' {
+ # The helper only ever clears the flag: a compare that decided to update stays updating.
+ Invoke-FullDepsEscape -FullDeps '1' -StartSkipping $false | Should -Be 'False'
+ Invoke-FullDepsEscape -FullDeps '0' -StartSkipping $false | Should -Be 'False'
+ }
+}
+
+Describe "Test-StudioInstallVerified returns a Boolean, not a collection" {
+ It "stays falsey when the verifier prints to stdout and then fails" {
+ # Stray stdout made `return $false` come back as @("...", $false), which is truthy,
+ # so a failed verify read as verified.
+ $body = (Get-Content -Raw (Join-Path $PSScriptRoot "../../studio/setup.ps1"))
+ $match = [regex]::Match($body, '(?ms)^function Test-StudioInstallVerified \{.*?^\}')
+ $match.Success | Should -BeTrue
+ $match.Value | Should -Match '\|\s*Out-Null'
+
+ function Probe {
+ try {
+ & python3 -c 'import sys; print("diagnostic"); sys.exit(1)' 2>$null | Out-Null
+ return ($LASTEXITCODE -eq 0)
+ } catch { return $false }
+ }
+ $result = Probe
+ @($result).Count | Should -Be 1
+ $result | Should -BeOfType [bool]
+ if ($result) { throw "a failed verify read as verified" }
+ }
+}
+
+Describe "The desktop backend floor check fails closed" {
+ It "forces the pass when the version check cannot run, as setup.sh does" {
+ # setup.sh uses `if ! python ...`, so a check that cannot execute forces the pass.
+ # PowerShell's empty catch left the flag false, keeping an under-floor install.
+ $ps1 = Get-Content -Raw (Join-Path $PSScriptRoot "../../studio/setup.ps1")
+ $ps1 | Should -Match '\$_desktopVerBad = \$true'
+ $ps1 | Should -Match 'if \(\$LASTEXITCODE -eq 0\) \{ \$_desktopVerBad = \$false \}'
+
+ function Floor([string] $exe) {
+ $skip = $true
+ $bad = $true
+ try {
+ & $exe -c "import sys; sys.exit(1)" 2>$null | Out-Null
+ if ($LASTEXITCODE -eq 0) { $bad = $false }
+ } catch {}
+ if ($bad) { $skip = $false }
+ return $skip
+ }
+ Floor "nosuchpython-xyz" | Should -BeFalse
+ Floor "python3" | Should -BeFalse
+ }
+}
diff --git a/tests/studio_setup_ps1/Studio.Setup.UvInstallDir.Tests.ps1 b/tests/studio_setup_ps1/Studio.Setup.UvInstallDir.Tests.ps1
new file mode 100644
index 00000000000..d5f976c94c0
--- /dev/null
+++ b/tests/studio_setup_ps1/Studio.Setup.UvInstallDir.Tests.ps1
@@ -0,0 +1,94 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+<#
+ setup.ps1 writes uv to $USERPROFILE\.local\bin and used to probe for it with
+ Get-Command alone, which reads PATH. Only astral's own installer edits the registry
+ PATH, so a fresh update process never saw the uv already on disk and downloaded it
+ again, every run. Get-UvInstallDir is the shared answer to "where does uv go", used by
+ both the installer and the probe so the two cannot drift.
+
+ These drive the real function out of setup.ps1 against the inline logic it replaced.
+ The nonexistent-drive case is the one that matters: Join-Path returns null there under
+ ErrorActionPreference Continue, and the original fell through to the home fallback.
+#>
+
+BeforeAll {
+ $setup = Join-Path $PSScriptRoot "../../studio/setup.ps1"
+ $match = [regex]::Match((Get-Content -Raw $setup), '(?ms)^function Get-UvInstallDir \{.*?^\}')
+ if (-not $match.Success) { throw "Get-UvInstallDir is no longer a top-level function in setup.ps1" }
+ Invoke-Expression $match.Value
+
+ # The block Get-UvInstallDir was extracted from, kept verbatim as the oracle.
+ function Original-Inline {
+ $destDir = $null
+ foreach ($candidate in @($env:UV_INSTALL_DIR, $env:UV_UNMANAGED_INSTALL, $env:XDG_BIN_HOME)) {
+ if ($candidate) { $destDir = $candidate; break }
+ }
+ if (-not $destDir -and $env:XDG_DATA_HOME) { $destDir = Join-Path $env:XDG_DATA_HOME "../bin" }
+ if (-not $destDir) {
+ $userHome = if ($env:USERPROFILE) { $env:USERPROFILE } else { $HOME }
+ if (-not $userHome) { return $null }
+ $destDir = Join-Path $userHome ".local\bin"
+ }
+ return $destDir
+ }
+
+ $script:saved = @{}
+ foreach ($name in 'UV_INSTALL_DIR', 'UV_UNMANAGED_INSTALL', 'XDG_BIN_HOME', 'XDG_DATA_HOME', 'USERPROFILE') {
+ $script:saved[$name] = [Environment]::GetEnvironmentVariable($name)
+ }
+}
+
+AfterAll {
+ foreach ($name in $script:saved.Keys) {
+ Set-Item -Path "Env:$name" -Value $script:saved[$name] -ErrorAction SilentlyContinue
+ }
+}
+
+Describe "Get-UvInstallDir matches the inline logic it replaced" {
+ It "agrees on every combination of the five variables it reads" {
+ $ErrorActionPreference = 'Continue'
+ $differing = @()
+ # The third XDG_DATA_HOME value is a drive that does not exist: Join-Path answers null.
+ foreach ($a in @($null, "/tmp/a")) {
+ foreach ($b in @($null, "/tmp/b")) {
+ foreach ($c in @($null, "/tmp/c")) {
+ foreach ($d in @($null, "/tmp/d", "Q:\nosuch")) {
+ foreach ($e in @($null, "/tmp/home")) {
+ $env:UV_INSTALL_DIR = $a
+ $env:UV_UNMANAGED_INSTALL = $b
+ $env:XDG_BIN_HOME = $c
+ $env:XDG_DATA_HOME = $d
+ $env:USERPROFILE = $e
+ $got = Get-UvInstallDir 2>$null
+ $want = Original-Inline 2>$null
+ if ("$got" -ne "$want") { $differing += "$a/$b/$c/$d/$e got=$got want=$want" }
+ }}}}}
+ $differing | Should -BeNullOrEmpty
+ }
+
+ It "falls through to the home directory when XDG_DATA_HOME cannot be joined" {
+ $ErrorActionPreference = 'Continue'
+ $env:UV_INSTALL_DIR = $null
+ $env:UV_UNMANAGED_INSTALL = $null
+ $env:XDG_BIN_HOME = $null
+ $env:XDG_DATA_HOME = "Q:\nosuch"
+ $env:USERPROFILE = "/tmp/home"
+ Get-UvInstallDir 2>$null | Should -Be (Join-Path "/tmp/home" ".local\bin")
+ }
+
+ It "honours the documented priority order" {
+ $env:USERPROFILE = "/tmp/home"
+ $env:XDG_DATA_HOME = "/tmp/d"
+ $env:XDG_BIN_HOME = "/tmp/c"
+ $env:UV_UNMANAGED_INSTALL = "/tmp/b"
+ $env:UV_INSTALL_DIR = "/tmp/a"
+ Get-UvInstallDir | Should -Be "/tmp/a"
+ $env:UV_INSTALL_DIR = $null
+ Get-UvInstallDir | Should -Be "/tmp/b"
+ $env:UV_UNMANAGED_INSTALL = $null
+ Get-UvInstallDir | Should -Be "/tmp/c"
+ $env:XDG_BIN_HOME = $null
+ Get-UvInstallDir | Should -Be (Join-Path "/tmp/d" "../bin")
+ }
+}