Skip to content

feat(install): fall back to CERNET and npmmirror when package hosts are blocked or slow - #11786

Merged
danielhanchen merged 28 commits into
unslothai:mainfrom
Lyxot:feat/installer-mirror-fallback
Sep 26, 2026
Merged

danielhanchen merged 28 commits into
unslothai:mainfrom
Lyxot:feat/installer-mirror-fallback

Conversation

@Lyxot

@Lyxot Lyxot commented Sep 24, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

In mainland China, pypi.org, download.pytorch.org, nodejs.org, registry.npmjs.org and releases.astral.sh are often blocked or run at a few hundred KB/s. A fresh Unsloth Studio install there either times out or takes hours downloading torch, Node, uv and Python builds. This PR makes install.sh, studio/setup.sh, install.ps1 and studio/setup.ps1 detect that and switch each affected host to a mirror. Healthy hosts are left untouched. The switch goes through the environment variables the package tools already read.

Default host Mirror
pypi.org (and the pinned uv wheel) https://tuna.mirrors.cernet.edu.cn/pypi/web/simple
download.pytorch.org https://tuna.mirrors.cernet.edu.cn/pytorch/whl (UNSLOTH_PYTORCH_MIRROR)
nodejs.org https://registry.npmmirror.com/-/binary/node (UNSLOTH_NODE_MIRROR)
registry.npmjs.org https://registry.npmmirror.com (UNSLOTH_NPM_REGISTRY)
releases.astral.sh (Python builds, POSIX only) https://registry.npmmirror.com/-/binary/python-build-standalone

CERNET's tuna.mirrors.cernet.edu.cn is a redirector. It sends each tree to a healthy university mirror, which gives failover beyond a single mirror.

How it works

  • Speed probe before the first install. Each default host is timed on a 1 MiB range of a real artifact it serves. A host below 1 MiB/s, or one whose index does not answer, is raced against its mirror. It is switched only when the mirror is faster and the mirror's own index answers. Hosts are probed in parallel. install.sh/install.ps1 probe up front and pass the result to setup.sh/setup.ps1. When setup runs on its own (unsloth studio update), it arms the one-shot mirror retries at startup without touching the network, and probes only right before a step that downloads Python packages (the dependency pass or a Transformers sidecar rebuild), so an update with nothing to install contacts no package host. A --local update, which re-runs the dependency pass from uv's cache every time, relies on the armed retries instead of probing.
  • Mirror-only PyPI index. A switched PyPI host uses the mirror alone (UV_DEFAULT_INDEX / PIP_INDEX_URL). pypi.org is deliberately not kept alongside it: uv's unsafe-first-match queries every index for every package, so a pypi.org that drops mid-install would fail every later step.
  • Unsynced-release rerun. If pypi.org was only slow and a resolve fails with "version/package not available" output (a fresh release the mirror has not synced yet), that step reruns once with pypi.org behind the mirror. Later steps keep that setup only if the rerun succeeds. Commands that pin their own index (--index-url, --default-index, --no-index) never take this rerun.
  • Transport-failure rerun. If a host that stayed on its default later fails with a transport error (timeout, reset, DNS/TLS, 5xx/429, stalled download), the failed step reruns once through that host's mirror, after the step's own same-host attempts. A resolution or not-found error never triggers this rerun, so steps that already try one source and fall back to another behave as before. This covers install.sh install commands, setup.sh npm installs, install_python_stack.py's pip_install/pip_install_try, the Node download and the pinned uv download, plus the Windows equivalents.
  • User configuration wins. A host the user already redirected (UV_*/PIP_* index vars, an index in any pip.conf pip would read, including the Unsloth Studio venv's own, or in any uv.toml / [tool.uv] uv would read, including the project config in the current directory or its nearest parent, UNSLOTH_PYTORCH_MIRROR, UNSLOTH_TORCH_INDEX_URL, UNSLOTH_NODE_MIRROR, UNSLOTH_NPM_REGISTRY) is never touched. UNSLOTH_MIRROR_FALLBACK=0 disables the whole feature.
  • Node integrity is unchanged. install_node_prebuilt.py honours UNSLOTH_NODE_MIRROR for index.json, SHASUMS256.txt and the archive, but archives are still checked against the committed node_prebuilt_pins.json sha256 pins. A mirror therefore cannot change what gets installed.
  • Windows specifics.
    • The probes use WebRequest.GetResponseAsync, which needs no Add-Type.
    • They send a User-Agent, because CERNET answers 403 without one.
    • They pin TLS 1.2 only for the probe.
    • They raise Windows PowerShell 5.1's two-connections-per-host limit so parallel probes do not queue.
    • install.ps1 restores every variable the fallback may set when it exits, because under irm | iex they belong to the caller's session.
    • The shared block is kept in sync into setup.ps1 by scripts/sync_shared_ps1_helpers.py.

Risks and tradeoffs

  • The probe adds a few seconds before the first download, and only when a host is slow (healthy hosts return after the 1 MiB sample). A standalone unsloth studio update switches slow hosts only for its Python package downloads; its Node, npm and uv steps stay on the default hosts and fall back to a mirror only when a download fails.
  • Mirror freshness: CERNET can lag PyPI by minutes to hours. The unsynced-release rerun covers that case when pypi.org is reachable. When pypi.org is fully blocked, a release newer than the mirror cannot be installed either way.
  • The mirror block in install.sh and studio/setup.sh is byte-identical, and a test enforces it.

Validation

Unit and contract tests (macOS; the PowerShell suite on pwsh 7 and on Windows PowerShell 5.1):

tests/sh/test_mirror_fallback.sh                 167 passed
tests/studio/test_mirror_fallback.ps1            89 PASS (pwsh 7 and Windows PowerShell 5.1)
tests/python/test_install_python_stack.py + tests/studio/install/{test_torch_probe_memoization,test_denied_llama_cpp_preflight,test_install_node_prebuilt_logic}.py   all pass
tests/sh/{test_uv_pinned_release,test_uv_cache_colocation,test_linux_uv_python_downloads_manual,test_macos_venv_python_preference,test_setup_reuse_installed_uv,test_node_decision,test_setup_sh_denied_install_tree,test_studio_home_node_dir,test_system_node_readonly}.sh   all pass
scripts/sync_shared_ps1_helpers.py --check       shared helpers already match

The two test_dependency_pass_skips.py pip-bootstrap tests fail identically on main in a uv-created venv without pip. They are unrelated to this change.

End-to-end fresh installs from mainland China, each with an isolated home (UNSLOTH_STUDIO_HOME) and run from outside any checkout, then an /api/health check on the installed Unsloth Studio:

Platform Mode Hosts switched Result
Linux (WSL2, RTX 4070 SUPER) --local all six; download.pytorch.org was blocked EXIT 0; torch 2.11.0+cu130 from the CERNET mirror; health 200
macOS (Apple Silicon) release all six EXIT 0; torch 2.11.0, unsloth 2026.9.11, mlx 0.32.2; health 200
macOS (Apple Silicon) --local PyPI, PyTorch, Node, uv EXIT 0; editable overlay; health 200, chat_only: false
macOS (Apple Silicon) --local --no-torch all six EXIT 0; health 200
Windows 11 (Windows PowerShell 5.1, RTX 4070 SUPER) --local download.pytorch.org blocked; Node and uv slow EXIT 0; torch 2.11.0+cu130 from the CERNET mirror; health 200, chat_only: false

install_node_prebuilt.py always fetched index.json, SHASUMS256.txt and the archive from nodejs.org. UNSLOTH_NODE_MIRROR now replaces that base for every Node dist URL; archives are still verified against the sha256 pins committed in node_prebuilt_pins.json, so a mirror cannot change what gets installed.
…re blocked or slow

install.sh and studio/setup.sh now probe pypi.org, download.pytorch.org, nodejs.org and registry.npmjs.org in parallel (5 s connect, 10 s total) before the first package install. A host that fails the probe while its mirror passes is redirected through the env vars the package tools already read: PyPI to https://mirrors.cernet.edu.cn/pypi/web/simple, PyTorch wheels to UNSLOTH_PYTORCH_MIRROR=https://mirrors.cernet.edu.cn/pytorch/whl, Node.js to UNSLOTH_NODE_MIRROR=https://mirrors.cernet.edu.cn/nodejs-release, and npm to UNSLOTH_NPM_REGISTRY=https://registry.npmmirror.com.

When pypi.org still answers but misses the budget, uv gets the mirror first and pypi.org second with UV_INDEX_STRATEGY=unsafe-first-match, and pip gets the mirror as PIP_INDEX_URL with pypi.org as PIP_EXTRA_INDEX_URL, so packages the mirror has not synced yet still resolve. When pypi.org does not answer at all, only the mirror is used: unsafe-first-match fetches every index and fails outright when one is unreachable.

A host the user already redirected (UV_* / PIP_* index vars, an index in uv.toml or pip.conf, UNSLOTH_PYTORCH_MIRROR, UNSLOTH_TORCH_INDEX_URL, UNSLOTH_NODE_MIRROR, UNSLOTH_NPM_REGISTRY) is left alone, setup.sh skips the probe when install.sh already ran it, and UNSLOTH_MIRROR_FALLBACK=0 turns the fallback off.
…indows

install.ps1 and studio/setup.ps1 get the same fallback as install.sh: pypi.org, download.pytorch.org, nodejs.org and registry.npmjs.org are probed in parallel, and a host that fails while its CERNET or npmmirror counterpart passes is redirected through the same env vars (UV_*/PIP_* index vars, UNSLOTH_PYTORCH_MIRROR, UNSLOTH_NODE_MIRROR, UNSLOTH_NPM_REGISTRY), with the same slow-versus-blocked PyPI split and the same respect for indexes the user already configured.

The helpers live in the block shared with setup.ps1. The probe uses WebRequest.GetResponseAsync rather than HttpClient, which would need Add-Type, and sends a User-Agent because the CERNET mirrors answer 403 without one. On a session whose SecurityProtocol excludes TLS 1.2 it pins TLS 1.2 for the probe only. install.ps1 restores every variable the fallback may set when it exits, since under irm | iex they belong to the caller's session. setup.ps1 now computes its npm --registry args after the probe, so a fallback registry reaches every npm and bun install.
…ows when releases.astral.sh is blocked or slow
…auncher heredoc

The mirror fallback functions sat inside the quoted heredoc that writes the launcher script, so install.sh never defined them and aborted with "_mirror_fallback: not found" right before installing uv. Move the block next to its call and add a check that the block is outside every heredoc in install.sh and studio/setup.sh.
Each default package host is timed alone on a 1 MiB slice of an artifact it serves, and one below 1 MiB/s, or whose index does not answer, is raced against its mirror and swapped for it only when the mirror is faster and its own index answers. CERNET redirects each tree to a different university mirror, so each tree is timed on its own, and releases.astral.sh is timed once for both uv and its Python builds.
Ports the speed probe from install.sh to install.ps1 and studio/setup.ps1: each default host is timed alone on a 1 MiB slice of an artifact it serves, and one below 1 MiB/s, or whose index does not answer, is raced against its mirror and swapped for it only when the mirror is faster and its own index answers. Each probe uses a fresh connection and its own deadline, as a separate curl process would, and the probes raise Windows PowerShell 5.1's two-connections-per-host limit so the race's CERNET requests do not queue. The uv Python-builds mirror is dropped on Windows, where uv is always given a resolved interpreter.
…ough its mirror

The mirror probe leaves healthy defaults alone. When a later step fails because the default host stopped answering (a timeout, reset, DNS or TLS error, a 5xx/429, or a download that stalled), the installers now rerun that step once through the host's mirror, after the step's own same-host attempts. The host is read from the failure output, or from the command when a stalled download names no URL; resolution, not-found and other hosts' failures are never retried, so try-then-fallback steps keep their own fallback. A host stays on its mirror for later steps only when the rerun succeeded.

Covers install.sh's install commands, setup.sh's npm installs, install_python_stack.py's pip_install and pip_install_try, and the node and pinned uv downloads (only when no source served the file).
…iled through its mirror

The Windows mirror fallback now exports the same spare list as the POSIX installers: one mirror per probed host still on its default. install.ps1 reruns a failed package install once through that host's mirror after its own attempts, only when the output shows a transport failure on that host (or a stalled download in a command that uses the default index). A torch mirror rewrites the default torch URLs the command reads, and a mirror is kept for later steps only when the rerun succeeds. studio/setup.ps1 does the same for the frontend and OXC npm installs, and retries the Node download and the pinned uv download (the latter only when no source answered). Every install_python_stack.py run on Windows gets the same retry through the exported list.

The shared-helper sync script now also copies a new shared function that has no comment above it.
mirrors.cernet.edu.cn sends the PyPI simple index to a mirror that rate-limits uv's parallel metadata requests (429), failing resolves; tuna.mirrors.cernet.edu.cn serves the index and files from Tsinghua. The Node dist mirror moves to registry.npmmirror.com/-/binary/node, which keeps nodejs.org's layout (index.json, SHASUMS256.txt, archives), and is timed on its own tarball.
…r lacks

A switched PyPI host now uses the mirror alone, also when pypi.org was only slow: uv's unsafe-first-match fetched every package from pypi.org too, so a pypi.org that dropped mid-install failed every step. When pypi.org still answered, a failed resolve that reports a version or package as not available (a fresh release the mirror has not synced yet) reruns once with pypi.org behind the mirror, and later steps keep that setup if the rerun works. Commands that pin their own index are left alone. install_python_stack.py classifies its installs the same way.
…irror lacks

The Windows installers now match install.sh: a switched PyPI host uses the mirror alone, also when pypi.org was only slow, and when pypi.org still answered, an install whose resolve reports a version or package as not available reruns once with pypi.org behind the mirror, keeping that setup for later steps if it works. Commands that pin their own index or pass --no-index are left alone.
…he PyPI mirror

uv reads uv.toml, or pyproject.toml with a [tool.uv] table, from the current directory or the nearest parent, and an exported UV_DEFAULT_INDEX overrides it. The mirror fallback only checked UV_CONFIG_FILE and the user and system uv.toml, so launching the installer from a project that configures its own index would redirect uv to the mirror. It now also checks the nearest project config, as install_python_stack.py's _uv_config_files does, and recognizes [[tool.uv.index]].
…ackages

setup.sh and setup.ps1 ran the mirror speed probe at startup, so every unsloth studio update, even one with nothing to install, fetched a 1 MiB sample from each default package host. The probe now runs right before the Python dependency pass and before a Transformers sidecar is rebuilt, the update steps that download from PyPI and PyTorch. install.sh and install.ps1 still probe up front and pass the result on, so fresh installs are unchanged; a standalone update's Node, npm and uv steps use the default hosts, as before the mirror fallback.
pip_install now wraps _pip_install_once with the mirror retry, and the install itself, including its _effective_requirements call, lives in _pip_install_once.
…pip config

pip also reads site config from the venv it runs in (<venv>/pip.conf, pip.ini on Windows). The mirror fallback only checked PIP_CONFIG_FILE and the user and global files, so a private index set in the Unsloth Studio venv was overridden by the exported PIP_INDEX_URL whenever the install fell back from uv to pip. The check now includes the venv's site config.
The mirror retry reads a failed command's output, so the verbose install arm copied it to a log with tee. install.sh otherwise needs no tee, and on a minimal image without it the pipe closed and the command died of SIGPIPE. The arm now falls back to cat there, which only costs that host the retry. The tests that lift run_install_cmd out of install.sh also lift the functions it now calls, and stub the mirror retry.
… skip the probe on a --local re-overlay

With the probe moved to the Python dependency pass, a standalone setup reached its Node and npm downloads with no mirror retry armed. setup.sh and setup.ps1 now arm every host's one-shot mirror retry at startup without probing (_mirror_fallback spare / Invoke-MirrorFallback -SpareOnly), and still probe lazily before the first package download. setup.sh arms it from the directory its installs run in, once VENV_DIR is set, so the retry respects the same uv and pip config they do.

A --local update runs the dependency pass every time to re-overlay the checkout, almost entirely from uv's cache, so on an existing venv that pass relies on the armed retries instead of probing every host first.
@Lyxot

Lyxot commented Sep 24, 2026

Copy link
Copy Markdown
Collaborator Author

Codex review on the staging copy converged on head 66a865a6c1: Lyxot#87 (comment)

Staging CI on the same head (https://github.com/Lyxot/unsloth/pull/87/checks): 27 workflows passed, 1 skipped (Kaggle T4 GPU), 1 failed.

  • The one failure is Backend CI (Python 3.13, rest): tests/multi_account/test_alice_bob_matrix.py::test_object_route_factory_completeness (1 failed, 13889 passed). It reports the two audio-gallery routes POST /audio/gallery/{audio_id}/move and /project missing from the route-factory registry, and fails the same way on the merge base, so it comes from main and is unrelated to the installer changes here: https://github.com/Lyxot/unsloth/actions/runs/35979804593/job/107568735683
  • The Unsloth Studio update suites (Linux, macOS, Windows), the shell installer tests, the clean machine install, the Mac install matrix and the Windows installer differential all passed.

danielhanchen and others added 2 commits September 25, 2026 14:18
… race

A registry set through NPM_CONFIG_REGISTRY / npm_config_registry outranks
the frontend .npmrc today; the fallback exported UNSLOTH_NPM_REGISTRY,
which becomes --registry and overrode it. Treat it as user configuration.

The race re-timed the default artifact but reused the first-round default
index result, so one index answer lost in the first round forced a healthy
host into blocked mode. Probe the default index again beside the mirror's.
Outside mainland China the installers now behave as before the fallback:
no probe, no mirror retries armed, nothing exported. Location is read
without a network call: a mainland time zone (Asia/Shanghai and its
aliases, Windows "China Standard Time"), or a resolver from a mainland
public DNS or cloud (AliDNS, DNSPod, 114DNS, Baidu, CNNIC, Alibaba Cloud
and Tencent Cloud internal resolvers), which covers UTC cloud VMs there.
UNSLOTH_MIRROR_FALLBACK=1 opts in anywhere; =0 still opts out.
With no mirror retry armed (outside mainland China, or opted out):
- run_install_cmd runs the plain runner, so set -e stops the installer
  where a command fails as before, and verbose output is not copied to a
  temp file through tee.
- The PowerShell runners stream verbose output without buffering it, and
  the npm / install retries return before reading any output.
- _mirror_retry in install_python_stack.py returns before decoding and
  scanning the failed output (183 ms for 1 MB of output before).
- A retry state inherited from a parent process is dropped, so neither a
  stale _UNSLOTH_MIRROR_SPARE nor UNSLOTH_MIRROR_FALLBACK=0 can be bypassed.
- setup.sh no longer changes directory (and OLDPWD) to arm the retries.

The location is read once per process, resolvers come from .NET instead of
Get-DnsClientServerAddress (no module or CIM load on Windows), and the
114DNS filtering resolvers plus DNSPod 182.254.116.116 / 119.28.28.28 count
as mainland China. An interrupted install also removes a kept output copy.
…try sidecars

- pip and uv read an index from every directory in XDG_CONFIG_DIRS; an
  index configured there now counts as user configuration, so the
  fallback no longer overrides it.
- The Node install no longer retries through the mirror on exit 4
  (permission denied), matching setup.ps1.
- Transformers sidecar installs rerun once with pypi.org behind the
  mirror when the probe switched a slow pypi.org, as the dependency pass
  already does for a pin the mirror has not synced.

All three only act when the fallback is on (mainland China or
UNSLOTH_MIRROR_FALLBACK=1).
uv's own no-network switch (its spellings: 1, t, true, y, yes, on) now
skips the speed probes and the mirror race; the one-shot retries stay
armed, as they only follow a failed network command.
shimmyshimmer pushed a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Sep 26, 2026
@danielhanchen

danielhanchen commented Sep 26, 2026 •

Copy link
Copy Markdown
Member

Review record for #11786, carried over from the mirror it was reviewed on: danielhanchen/unsloth-staging-review#111.

Findings are quoted as posted and attributed to the account that posted them. The reactions shown are the triage recorded on the mirror; none were re-applied here. Commits are named as the mirror's, with this PR's equivalent where one was found.

Round 1: reviewed mirror d175d0de6 (no equivalent commit found on this PR)

chatgpt-codex-connector[bot] on install.sh (on the mirror)

@@ -3241,6 +3313,313 @@ case "$OS" in
         ;;
 esac
 
+# ── BEGIN mirror fallback (kept identical in install.sh and studio/setup.sh) ──
+# Only in mainland China (or UNSLOTH_MIRROR_FALLBACK=1): swaps a default host below 1 MiB/s or unreachable for its mirror when faster; user-set sources untouched; UNSLOTH_MIRROR_FALLBACK=0 disables.
+_MIRROR_CERNET="https://tuna.mirrors.cernet.edu.cn"
+_MIRROR_PYPI="$_MIRROR_CERNET/pypi/web/simple"
+_MIRROR_NPM="https://registry.npmmirror.com"
+# GitHub-release mirrors keep only the newest Python builds, while a pinned uv asks for the builds it shipped with; npmmirror keeps every release.
+_MIRROR_PYTHON="$_MIRROR_NPM/-/binary/python-build-standalone"
+_MIRROR_MIN_BPS=1048576
+
+_mirror_probe() {
+    _mp_out=$(curl -sL -o /dev/null -r "0-$3" -w '%{http_code} %{speed_download}' --connect-timeout "$2" --max-time "$2" "$1" 2>/dev/null) || true
+    _mp_bps=${_mp_out#* }
+    _mp_bps=${_mp_bps%%.*}
+    case "$_mp_bps" in ''|*[!0-9]*) _mp_bps=0 ;; esac
+    _mp_code=${_mp_out%% *}
+    case "$_mp_code" in [0-9][0-9][0-9]) ;; *) _mp_code=000 ;; esac
+    echo "$_mp_code $_mp_bps"
+}
+
+_mirror_url() {
+    case "$1" in
+        pypi) echo "https://files.pythonhosted.org/packages/72/d6/207945fe69903b9794e2ef3e42608c91a59972567343a6719078d99c71f7/uv-0.12.1-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl" ;;
+        cernet-pypi) echo "$_MIRROR_CERNET/pypi/web/packages/72/d6/207945fe69903b9794e2ef3e42608c91a59972567343a6719078d99c71f7/uv-0.12.1-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl" ;;
+        torch) echo "https://download-r2.pytorch.org/whl/cpu/torch-2.9.1%2Bcpu-cp312-cp312-manylinux_2_28_x86_64.whl" ;;
+        cernet-torch) echo "$_MIRROR_CERNET/pytorch/whl/cpu/torch-2.9.1%2Bcpu-cp312-cp312-manylinux_2_28_x86_64.whl" ;;
+        node) echo "https://nodejs.org/dist/v24.18.0/node-v24.18.0-linux-x64.tar.gz" ;;
+        npmmirror-node) echo "$_MIRROR_NPM/-/binary/node/v24.18.0/node-v24.18.0-linux-x64.tar.gz" ;;
+        npm) echo "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz" ;;
+        npmmirror) echo "$_MIRROR_NPM/typescript/-/typescript-5.9.3.tgz" ;;
+        astral) echo "https://releases.astral.sh/github/uv/releases/download/0.12.1/uv-x86_64-unknown-linux-gnu.tar.gz" ;;
+        pypi-index) echo "https://pypi.org/simple/uv/" ;;
+        torch-index) echo "https://download.pytorch.org/whl/cpu/torch/" ;;
+        cernet-pypi-index) echo "$_MIRROR_PYPI/uv/" ;;
+        cernet-torch-index) echo "$_MIRROR_CERNET/pytorch/whl/cpu/torch/" ;;
+    esac
+}
+
+_mirror_default() {
+    case "$1" in python|uvbin) echo astral ;; *) echo "$1" ;; esac
+}
+
+_mirror_source() {
+    case "$1" in npm|python) echo npmmirror ;; node) echo npmmirror-node ;; pypi|uvbin) echo cernet-pypi ;; *) echo "cernet-$1" ;; esac
+}
+
+_mirror_index_probe() {
+    for _mip_name in "$@"; do
+        case "$_mip_name" in
+            pypi|torch|cernet-pypi|cernet-torch)
+                _mirror_probe "$(_mirror_url "$_mip_name-index")" 4 1023 > "$_mf_dir/$_mip_name-index" &
+                _mf_pids="$_mf_pids $!" ;;
+        esac
+    done
+}
+
+_mirror_index_wait() {
+    for _miw_pid in $_mf_pids; do
+        wait "$_miw_pid" || true
+    done
+    _mf_pids=""
+}
+
+_mirror_index_ok() {
+    [ -f "$_mf_dir/$1-index" ] || return 0
+    read -r _mio_code _mio_bps < "$_mf_dir/$1-index"
+    case "$_mio_code" in 2??) return 0 ;; *) return 1 ;; esac
+}
+
+_mirror_uv_project_config() {
+    _mup_dir=$PWD
+    while [ -n "$_mup_dir" ]; do
+        if [ -f "$_mup_dir/uv.toml" ]; then echo "$_mup_dir/uv.toml"; return 0; fi
+        if grep -Eqs '^[[:space:]]*\[+tool\.uv(\.|\])' "$_mup_dir/pyproject.toml"; then echo "$_mup_dir/pyproject.toml"; return 0; fi
+        [ "$_mup_dir" = / ] && return 0
+        _mup_dir=$(dirname "$_mup_dir")
+    done
+}
+
+_mirror_configured() {
+    case "$1" in
+        uv)
+            [ -n "${UV_DEFAULT_INDEX:-}${UV_INDEX_URL:-}${UV_INDEX:-}${UV_EXTRA_INDEX_URL:-}" ] && return 0
+            _mic_key='\[\[(tool\.uv\.)?index\]\]|(pip\.)?(index|index-url|default-index|extra-index-url|no-index)[[:space:]]*=' ;;
+        python)
+            [ -n "${UV_PYTHON_INSTALL_MIRROR:-}" ] && return 0
+            _mic_key='python-install-mirror[[:space:]]*=' ;;
+        pip)
+            [ -n "${PIP_INDEX_URL:-}${PIP_EXTRA_INDEX_URL:-}${PIP_NO_INDEX:-}" ] && return 0
+            _mic_key='(index[-_]url|extra[-_]index[-_]url|no[-_]index)[[:space:]]*[=:]' ;;

P2 Badge Honor false no-index values before suppressing pip fallback

When PIP_NO_INDEX=0 or PIP_NO_INDEX=false, this nonempty-string check marks pip as configured even though pip treats those values as false and continues using its default PyPI index; the presence-only config regex similarly misclassifies no-index = false. On a mainland-China or explicitly opted-in host where uv is unavailable and PyPI is slow or blocked, _mirror_vars pypi consequently omits PIP_INDEX_URL, so neither the proactive switch nor the retry can move the pip path to CERNET. Parse no-index as a boolean and suppress fallback only when it is enabled.

Useful? React with 👍 / 👎.

Rejected on the mirror

Reply from danielhanchen:

Not changing this: an explicit PIP_NO_INDEX=false or no-index = false is an unusual setting, and treating it as configured only leaves pip on its default index, which is the behaviour before this PR.

chatgpt-codex-connector[bot] on install.sh (on the mirror)

@@ -3241,6 +3313,313 @@ case "$OS" in
         ;;
 esac
 
+# ── BEGIN mirror fallback (kept identical in install.sh and studio/setup.sh) ──
+# Only in mainland China (or UNSLOTH_MIRROR_FALLBACK=1): swaps a default host below 1 MiB/s or unreachable for its mirror when faster; user-set sources untouched; UNSLOTH_MIRROR_FALLBACK=0 disables.
+_MIRROR_CERNET="https://tuna.mirrors.cernet.edu.cn"
+_MIRROR_PYPI="$_MIRROR_CERNET/pypi/web/simple"
+_MIRROR_NPM="https://registry.npmmirror.com"
+# GitHub-release mirrors keep only the newest Python builds, while a pinned uv asks for the builds it shipped with; npmmirror keeps every release.
+_MIRROR_PYTHON="$_MIRROR_NPM/-/binary/python-build-standalone"
+_MIRROR_MIN_BPS=1048576
+
+_mirror_probe() {
+    _mp_out=$(curl -sL -o /dev/null -r "0-$3" -w '%{http_code} %{speed_download}' --connect-timeout "$2" --max-time "$2" "$1" 2>/dev/null) || true
+    _mp_bps=${_mp_out#* }
+    _mp_bps=${_mp_bps%%.*}
+    case "$_mp_bps" in ''|*[!0-9]*) _mp_bps=0 ;; esac
+    _mp_code=${_mp_out%% *}
+    case "$_mp_code" in [0-9][0-9][0-9]) ;; *) _mp_code=000 ;; esac
+    echo "$_mp_code $_mp_bps"
+}
+
+_mirror_url() {
+    case "$1" in
+        pypi) echo "https://files.pythonhosted.org/packages/72/d6/207945fe69903b9794e2ef3e42608c91a59972567343a6719078d99c71f7/uv-0.12.1-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl" ;;
+        cernet-pypi) echo "$_MIRROR_CERNET/pypi/web/packages/72/d6/207945fe69903b9794e2ef3e42608c91a59972567343a6719078d99c71f7/uv-0.12.1-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl" ;;
+        torch) echo "https://download-r2.pytorch.org/whl/cpu/torch-2.9.1%2Bcpu-cp312-cp312-manylinux_2_28_x86_64.whl" ;;
+        cernet-torch) echo "$_MIRROR_CERNET/pytorch/whl/cpu/torch-2.9.1%2Bcpu-cp312-cp312-manylinux_2_28_x86_64.whl" ;;
+        node) echo "https://nodejs.org/dist/v24.18.0/node-v24.18.0-linux-x64.tar.gz" ;;
+        npmmirror-node) echo "$_MIRROR_NPM/-/binary/node/v24.18.0/node-v24.18.0-linux-x64.tar.gz" ;;
+        npm) echo "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz" ;;
+        npmmirror) echo "$_MIRROR_NPM/typescript/-/typescript-5.9.3.tgz" ;;
+        astral) echo "https://releases.astral.sh/github/uv/releases/download/0.12.1/uv-x86_64-unknown-linux-gnu.tar.gz" ;;
+        pypi-index) echo "https://pypi.org/simple/uv/" ;;
+        torch-index) echo "https://download.pytorch.org/whl/cpu/torch/" ;;
+        cernet-pypi-index) echo "$_MIRROR_PYPI/uv/" ;;
+        cernet-torch-index) echo "$_MIRROR_CERNET/pytorch/whl/cpu/torch/" ;;
+    esac
+}
+
+_mirror_default() {
+    case "$1" in python|uvbin) echo astral ;; *) echo "$1" ;; esac
+}
+
+_mirror_source() {
+    case "$1" in npm|python) echo npmmirror ;; node) echo npmmirror-node ;; pypi|uvbin) echo cernet-pypi ;; *) echo "cernet-$1" ;; esac
+}
+
+_mirror_index_probe() {
+    for _mip_name in "$@"; do
+        case "$_mip_name" in
+            pypi|torch|cernet-pypi|cernet-torch)
+                _mirror_probe "$(_mirror_url "$_mip_name-index")" 4 1023 > "$_mf_dir/$_mip_name-index" &
+                _mf_pids="$_mf_pids $!" ;;
+        esac
+    done
+}
+
+_mirror_index_wait() {
+    for _miw_pid in $_mf_pids; do
+        wait "$_miw_pid" || true
+    done
+    _mf_pids=""
+}
+
+_mirror_index_ok() {
+    [ -f "$_mf_dir/$1-index" ] || return 0
+    read -r _mio_code _mio_bps < "$_mf_dir/$1-index"
+    case "$_mio_code" in 2??) return 0 ;; *) return 1 ;; esac
+}
+
+_mirror_uv_project_config() {
+    _mup_dir=$PWD
+    while [ -n "$_mup_dir" ]; do
+        if [ -f "$_mup_dir/uv.toml" ]; then echo "$_mup_dir/uv.toml"; return 0; fi
+        if grep -Eqs '^[[:space:]]*\[+tool\.uv(\.|\])' "$_mup_dir/pyproject.toml"; then echo "$_mup_dir/pyproject.toml"; return 0; fi
+        [ "$_mup_dir" = / ] && return 0
+        _mup_dir=$(dirname "$_mup_dir")
+    done
+}
+
+_mirror_configured() {
+    case "$1" in
+        uv)
+            [ -n "${UV_DEFAULT_INDEX:-}${UV_INDEX_URL:-}${UV_INDEX:-}${UV_EXTRA_INDEX_URL:-}" ] && return 0
+            _mic_key='\[\[(tool\.uv\.)?index\]\]|(pip\.)?(index|index-url|default-index|extra-index-url|no-index)[[:space:]]*=' ;;
+        python)
+            [ -n "${UV_PYTHON_INSTALL_MIRROR:-}" ] && return 0
+            _mic_key='python-install-mirror[[:space:]]*=' ;;
+        pip)
+            [ -n "${PIP_INDEX_URL:-}${PIP_EXTRA_INDEX_URL:-}${PIP_NO_INDEX:-}" ] && return 0
+            _mic_key='(index[-_]url|extra[-_]index[-_]url|no[-_]index)[[:space:]]*[=:]' ;;
+    esac
+    _mic_suffix=uv/uv.toml
+    [ "$1" != pip ] || _mic_suffix=pip/pip.conf
+    if [ "$1" = pip ]; then
+        set -- "${PIP_CONFIG_FILE:-}" "${VENV_DIR:+$VENV_DIR/pip.conf}" "${XDG_CONFIG_HOME:-$HOME/.config}/pip/pip.conf" "$HOME/.pip/pip.conf" "$HOME/Library/Application Support/pip/pip.conf" /etc/xdg/pip/pip.conf /etc/pip.conf
+    else
+        set -- "${UV_CONFIG_FILE:-}" "$(_mirror_uv_project_config)" "${XDG_CONFIG_HOME:-$HOME/.config}/uv/uv.toml" /etc/xdg/uv/uv.toml /etc/uv/uv.toml
+    fi
+    _mic_xdg=${XDG_CONFIG_DIRS:-}
+    while [ -n "$_mic_xdg" ]; do
+        set -- "$@" "${_mic_xdg%%:*}/$_mic_suffix"
+        case "$_mic_xdg" in *:*) _mic_xdg=${_mic_xdg#*:} ;; *) _mic_xdg="" ;; esac
+    done
+    for _mic_file in "$@"; do
+        if [ -f "$_mic_file" ] && grep -Eq "^[[:space:]]*($_mic_key)" "$_mic_file" 2>/dev/null; then
+            return 0
+        fi
+    done
+    return 1
+}
+
+_mirror_probe_all() {
+    _mpa_dir="$1"
+    _mpa_secs="$2"
+    shift 2
+    _mpa_pids=""
+    for _mpa_name in "$@"; do
+        _mirror_probe "$(_mirror_url "$_mpa_name")" "$_mpa_secs" 1048575 > "$_mpa_dir/$_mpa_name" &
+        _mpa_pids="$_mpa_pids $!"
+    done
+    for _mpa_pid in $_mpa_pids; do
+        wait "$_mpa_pid" || true
+    done
+}
+
+_mirror_vars() {
+    case "$1" in
+        pypi)
+            [ "$_mf_uv" = false ] || echo "UV_DEFAULT_INDEX=$_MIRROR_PYPI"
+            [ "$_mf_pip" = false ] || echo "PIP_INDEX_URL=$_MIRROR_PYPI" ;;
+        unsynced)
+            # Only for one rerun: uv's unsafe-first-match fetches every package from every index, and fails outright when one is unreachable.
+            [ "$_mf_uv" = false ] || echo "UV_DEFAULT_INDEX=https://pypi.org/simple UV_INDEX=$_MIRROR_PYPI UV_INDEX_STRATEGY=${UV_INDEX_STRATEGY:-unsafe-first-match}"
+            [ "$_mf_pip" = false ] || echo "PIP_EXTRA_INDEX_URL=https://pypi.org/simple PIP_INDEX_URL=$_MIRROR_PYPI" ;;
+        torch) echo "UNSLOTH_PYTORCH_MIRROR=$_MIRROR_CERNET/pytorch/whl" ;;

🛡️ Codex Security Review

P1 Badge Security: Pin hashes for mirrored PyTorch wheels

When fallback is active—by default on detected mainland-China hosts or by opt-in—and the official PyTorch host is slow or unavailable, a malicious or compromised CERNET endpoint can control the wheel installed through this new mirror assignment. The later uv pip install --default-index uses version constraints but no repository-pinned digest or upstream-authenticated signature, so an allowed-version wheel can be replaced and execute when Studio imports torch. HTTPS and speed/index probes do not verify content. Require trusted hashes or signatures before automatic mirror use.

Useful? React with 👍 / 👎.

Rejected on the mirror

Reply from danielhanchen:

Intended trade-off: the fallback only runs in mainland China or on explicit opt-in, uses HTTPS to the CERNET university mirrors that users there already configure by hand, and can be disabled with UNSLOTH_MIRROR_FALLBACK=0. Pinning digests for every torch wheel across CUDA variants is not practical.

chatgpt-codex-connector[bot] (on the mirror)

🛡️ Codex Security Review

Here are some automated security review suggestions for this pull request.

Reviewed commit: d175d0de6a

No triage reaction was recorded on the mirror

chatgpt-codex-connector[bot] on install.sh (on the mirror)

@@ -3241,6 +3313,313 @@ case "$OS" in
         ;;
 esac
 
+# ── BEGIN mirror fallback (kept identical in install.sh and studio/setup.sh) ──
+# Only in mainland China (or UNSLOTH_MIRROR_FALLBACK=1): swaps a default host below 1 MiB/s or unreachable for its mirror when faster; user-set sources untouched; UNSLOTH_MIRROR_FALLBACK=0 disables.
+_MIRROR_CERNET="https://tuna.mirrors.cernet.edu.cn"
+_MIRROR_PYPI="$_MIRROR_CERNET/pypi/web/simple"
+_MIRROR_NPM="https://registry.npmmirror.com"
+# GitHub-release mirrors keep only the newest Python builds, while a pinned uv asks for the builds it shipped with; npmmirror keeps every release.
+_MIRROR_PYTHON="$_MIRROR_NPM/-/binary/python-build-standalone"
+_MIRROR_MIN_BPS=1048576
+
+_mirror_probe() {
+    _mp_out=$(curl -sL -o /dev/null -r "0-$3" -w '%{http_code} %{speed_download}' --connect-timeout "$2" --max-time "$2" "$1" 2>/dev/null) || true
+    _mp_bps=${_mp_out#* }
+    _mp_bps=${_mp_bps%%.*}
+    case "$_mp_bps" in ''|*[!0-9]*) _mp_bps=0 ;; esac
+    _mp_code=${_mp_out%% *}
+    case "$_mp_code" in [0-9][0-9][0-9]) ;; *) _mp_code=000 ;; esac
+    echo "$_mp_code $_mp_bps"
+}
+
+_mirror_url() {
+    case "$1" in
+        pypi) echo "https://files.pythonhosted.org/packages/72/d6/207945fe69903b9794e2ef3e42608c91a59972567343a6719078d99c71f7/uv-0.12.1-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl" ;;
+        cernet-pypi) echo "$_MIRROR_CERNET/pypi/web/packages/72/d6/207945fe69903b9794e2ef3e42608c91a59972567343a6719078d99c71f7/uv-0.12.1-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl" ;;
+        torch) echo "https://download-r2.pytorch.org/whl/cpu/torch-2.9.1%2Bcpu-cp312-cp312-manylinux_2_28_x86_64.whl" ;;
+        cernet-torch) echo "$_MIRROR_CERNET/pytorch/whl/cpu/torch-2.9.1%2Bcpu-cp312-cp312-manylinux_2_28_x86_64.whl" ;;
+        node) echo "https://nodejs.org/dist/v24.18.0/node-v24.18.0-linux-x64.tar.gz" ;;
+        npmmirror-node) echo "$_MIRROR_NPM/-/binary/node/v24.18.0/node-v24.18.0-linux-x64.tar.gz" ;;
+        npm) echo "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz" ;;
+        npmmirror) echo "$_MIRROR_NPM/typescript/-/typescript-5.9.3.tgz" ;;
+        astral) echo "https://releases.astral.sh/github/uv/releases/download/0.12.1/uv-x86_64-unknown-linux-gnu.tar.gz" ;;
+        pypi-index) echo "https://pypi.org/simple/uv/" ;;
+        torch-index) echo "https://download.pytorch.org/whl/cpu/torch/" ;;
+        cernet-pypi-index) echo "$_MIRROR_PYPI/uv/" ;;
+        cernet-torch-index) echo "$_MIRROR_CERNET/pytorch/whl/cpu/torch/" ;;
+    esac
+}
+
+_mirror_default() {
+    case "$1" in python|uvbin) echo astral ;; *) echo "$1" ;; esac
+}
+
+_mirror_source() {
+    case "$1" in npm|python) echo npmmirror ;; node) echo npmmirror-node ;; pypi|uvbin) echo cernet-pypi ;; *) echo "cernet-$1" ;; esac
+}
+
+_mirror_index_probe() {
+    for _mip_name in "$@"; do
+        case "$_mip_name" in
+            pypi|torch|cernet-pypi|cernet-torch)
+                _mirror_probe "$(_mirror_url "$_mip_name-index")" 4 1023 > "$_mf_dir/$_mip_name-index" &
+                _mf_pids="$_mf_pids $!" ;;
+        esac
+    done
+}
+
+_mirror_index_wait() {
+    for _miw_pid in $_mf_pids; do
+        wait "$_miw_pid" || true
+    done
+    _mf_pids=""
+}
+
+_mirror_index_ok() {
+    [ -f "$_mf_dir/$1-index" ] || return 0
+    read -r _mio_code _mio_bps < "$_mf_dir/$1-index"
+    case "$_mio_code" in 2??) return 0 ;; *) return 1 ;; esac
+}
+
+_mirror_uv_project_config() {
+    _mup_dir=$PWD
+    while [ -n "$_mup_dir" ]; do
+        if [ -f "$_mup_dir/uv.toml" ]; then echo "$_mup_dir/uv.toml"; return 0; fi
+        if grep -Eqs '^[[:space:]]*\[+tool\.uv(\.|\])' "$_mup_dir/pyproject.toml"; then echo "$_mup_dir/pyproject.toml"; return 0; fi
+        [ "$_mup_dir" = / ] && return 0
+        _mup_dir=$(dirname "$_mup_dir")
+    done
+}
+
+_mirror_configured() {
+    case "$1" in
+        uv)
+            [ -n "${UV_DEFAULT_INDEX:-}${UV_INDEX_URL:-}${UV_INDEX:-}${UV_EXTRA_INDEX_URL:-}" ] && return 0
+            _mic_key='\[\[(tool\.uv\.)?index\]\]|(pip\.)?(index|index-url|default-index|extra-index-url|no-index)[[:space:]]*=' ;;
+        python)
+            [ -n "${UV_PYTHON_INSTALL_MIRROR:-}" ] && return 0
+            _mic_key='python-install-mirror[[:space:]]*=' ;;
+        pip)
+            [ -n "${PIP_INDEX_URL:-}${PIP_EXTRA_INDEX_URL:-}${PIP_NO_INDEX:-}" ] && return 0
+            _mic_key='(index[-_]url|extra[-_]index[-_]url|no[-_]index)[[:space:]]*[=:]' ;;
+    esac
+    _mic_suffix=uv/uv.toml
+    [ "$1" != pip ] || _mic_suffix=pip/pip.conf
+    if [ "$1" = pip ]; then
+        set -- "${PIP_CONFIG_FILE:-}" "${VENV_DIR:+$VENV_DIR/pip.conf}" "${XDG_CONFIG_HOME:-$HOME/.config}/pip/pip.conf" "$HOME/.pip/pip.conf" "$HOME/Library/Application Support/pip/pip.conf" /etc/xdg/pip/pip.conf /etc/pip.conf
+    else
+        set -- "${UV_CONFIG_FILE:-}" "$(_mirror_uv_project_config)" "${XDG_CONFIG_HOME:-$HOME/.config}/uv/uv.toml" /etc/xdg/uv/uv.toml /etc/uv/uv.toml
+    fi
+    _mic_xdg=${XDG_CONFIG_DIRS:-}
+    while [ -n "$_mic_xdg" ]; do
+        set -- "$@" "${_mic_xdg%%:*}/$_mic_suffix"
+        case "$_mic_xdg" in *:*) _mic_xdg=${_mic_xdg#*:} ;; *) _mic_xdg="" ;; esac
+    done
+    for _mic_file in "$@"; do
+        if [ -f "$_mic_file" ] && grep -Eq "^[[:space:]]*($_mic_key)" "$_mic_file" 2>/dev/null; then
+            return 0
+        fi
+    done
+    return 1
+}
+
+_mirror_probe_all() {
+    _mpa_dir="$1"
+    _mpa_secs="$2"
+    shift 2
+    _mpa_pids=""
+    for _mpa_name in "$@"; do
+        _mirror_probe "$(_mirror_url "$_mpa_name")" "$_mpa_secs" 1048575 > "$_mpa_dir/$_mpa_name" &
+        _mpa_pids="$_mpa_pids $!"
+    done
+    for _mpa_pid in $_mpa_pids; do
+        wait "$_mpa_pid" || true
+    done
+}
+
+_mirror_vars() {
+    case "$1" in
+        pypi)
+            [ "$_mf_uv" = false ] || echo "UV_DEFAULT_INDEX=$_MIRROR_PYPI"
+            [ "$_mf_pip" = false ] || echo "PIP_INDEX_URL=$_MIRROR_PYPI" ;;
+        unsynced)
+            # Only for one rerun: uv's unsafe-first-match fetches every package from every index, and fails outright when one is unreachable.
+            [ "$_mf_uv" = false ] || echo "UV_DEFAULT_INDEX=https://pypi.org/simple UV_INDEX=$_MIRROR_PYPI UV_INDEX_STRATEGY=${UV_INDEX_STRATEGY:-unsafe-first-match}"
+            [ "$_mf_pip" = false ] || echo "PIP_EXTRA_INDEX_URL=https://pypi.org/simple PIP_INDEX_URL=$_MIRROR_PYPI" ;;
+        torch) echo "UNSLOTH_PYTORCH_MIRROR=$_MIRROR_CERNET/pytorch/whl" ;;
+        node) echo "UNSLOTH_NODE_MIRROR=$_MIRROR_NPM/-/binary/node" ;;
+        npm) echo "UNSLOTH_NPM_REGISTRY=$_MIRROR_NPM" ;;
+        python) echo "UV_PYTHON_INSTALL_MIRROR=$_MIRROR_PYTHON" ;;
+        uvbin) echo "UNSLOTH_UV_WHEEL_MIRROR=$_MIRROR_CERNET/pypi/web" ;;
+    esac
+}
+
+_mirror_name() {
+    case "$1" in
+        pypi) echo "PyPI" ;;
+        unsynced) echo "The PyPI mirror" ;;
+        torch) echo "download.pytorch.org" ;;
+        node) echo "nodejs.org" ;;
+        npm) echo "registry.npmjs.org" ;;
+        python) echo "releases.astral.sh (Python builds)" ;;
+        uvbin) echo "releases.astral.sh (uv)" ;;
+    esac
+}
+
+_mirror_use() {
+    _mu_to=""
+    for _mu_pair in $(_mirror_vars "$1"); do
+        export "$_mu_pair"
+        [ -n "$_mu_to" ] || _mu_to=${_mu_pair#*=}
+    done
+    step "mirror" "$(_mirror_name "$1") is $2 ($(($3 / 1024)) KB/s, mirror $(($4 / 1024)) KB/s); using $_mu_to" "$C_WARN"
+    _mf_switched="$_mf_switched $1"
+    [ "$1 $2" != "pypi slow" ] || _mf_unsynced=true
+}
+
+_mirror_take() {
+    _MT_PAIRS=""
+    _mt_spare=""
+    for _mt_entry in ${_UNSLOTH_MIRROR_SPARE:-}; do
+        if [ "${_mt_entry%%|*}" = "$1" ]; then
+            _MT_PAIRS=$(printf '%s' "${_mt_entry#*|}" | tr '|' ' ')
+        else
+            _mt_spare="$_mt_spare $_mt_entry"
+        fi
+    done
+    [ -n "$_MT_PAIRS" ] || return 1
+    export _UNSLOTH_MIRROR_SPARE="${_mt_spare# }"
+    _mt_to=${_MT_PAIRS%% *}
+    step "mirror" "$(_mirror_name "$1") failed; retrying through ${_mt_to#*=}" "$C_WARN"
+}
+
+_mirror_switch() {
+    _mirror_take "$1" || return 1
+    for _ms_pair in $_MT_PAIRS; do export "$_ms_pair"; done
+}
+
+_mirror_failed_host() {
+    if ! grep -Eqi 'error sending request|timed out|network timeout|idle timeout|connection (reset|refused|closed|aborted)|network aborted|broken pipe|dns error|failed to lookup address|name resolution|nodename nor servname|network is unreachable|error decoding response body|end of file before message length|unexpected eof|tls handshake|sslerror|certificate verify failed|server error|service unavailable|bad gateway|gateway time-?out|too many requests|max retries exceeded|remotedisconnected|incompleteread|econnreset|etimedout|eidletimeout|eai_again|enotfound|econnrefused|socket hang up' "$1" 2>/dev/null; then
+        grep -Eqi 'only [^ ]+ (.* )?(is|are) available|no versions? of|not found in the package registry|could not find a version that satisfies|no matching distribution found' "$1" 2>/dev/null || return 1
+        echo unsynced
+        return 0
+    fi
+    if grep -Eq 'download(-r2)?\.pytorch\.org' "$1"; then echo torch
+    elif grep -q 'python-build-standalone' "$1"; then echo python
+    elif grep -q 'registry\.npmjs\.org' "$1"; then echo npm
+    elif grep -Eq 'pypi\.org|pythonhosted\.org' "$1"; then echo pypi
+    elif [ -n "${2:-}" ] && ! grep -Eq 'https?://' "$1"; then echo "$2"
+    else return 1
+    fi
+}
+
+# No network call: mainland China time zone or resolver (Alibaba 100.100.2.136/138, Tencent 183.60.83.19/82.98).
+_mirror_in_china() {
+    _mcn_tz=${TZ:-}
+    [ -n "$_mcn_tz" ] || _mcn_tz=$(cat /etc/timezone 2>/dev/null) || true
+    [ -n "$_mcn_tz" ] || _mcn_tz=$(readlink /etc/localtime 2>/dev/null) || true
+    case "${_mcn_tz#:}" in
+        *Asia/Shanghai|*Asia/Chongqing|*Asia/Chungking|*Asia/Harbin|*Asia/Urumqi|*Asia/Kashgar|PRC|*/PRC) return 0 ;;
+    esac
+    grep -Eqs '^[[:space:]]*nameserver[[:space:]]+(223\.5\.5\.5|223\.6\.6\.6|119\.29\.29\.29|114\.114\.11[45]\.11[0459]|182\.254\.116\.116|119\.28\.28\.28|180\.76\.76\.76|1\.2\.4\.8|210\.2\.4\.8|100\.100\.2\.13[68]|183\.60\.8[23]\.(19|98))[[:space:]]*$' /etc/resolv.conf /run/systemd/resolve/resolv.conf
+}
+
+# Decided once per process; when off, a retry state inherited from a parent is dropped so nothing downstream acts on it.
+_mirror_enabled() {
+    if [ -z "${_mirror_on:-}" ]; then
+        case "${UNSLOTH_MIRROR_FALLBACK:-}" in
+            0|false|False|FALSE|no|off) _mirror_on=no ;;
+            1|true|True|TRUE|yes|on) _mirror_on=yes ;;
+            *) if _mirror_in_china; then _mirror_on=yes; else _mirror_on=no; fi ;;
+        esac
+        [ "$_mirror_on" = yes ] || unset _UNSLOTH_MIRROR_SPARE
+    fi
+    [ "$_mirror_on" = yes ]
+}
+
+_mirror_fallback() {
+    _mirror_enabled || return 0
+    [ -z "${_UNSLOTH_MIRROR_PROBED:-}" ] || return 0
+    command -v curl >/dev/null 2>&1 || return 0

P2 Badge Skip network probes when UV_OFFLINE is enabled

When mainland-China detection enables fallback (or the user opts in) while UV_OFFLINE=1, this path proceeds directly to multiple curl probes even when an update would otherwise use only cached data; on a disconnected host, the sequential default probes plus the mirror race add repeated timeouts and make outbound requests before the existing offline branches can defer missing packages. I checked uv 0.12.1 help pip install, which documents --offline / UV_OFFLINE as “Disable network access” and says only locally cached data and files are used. The byte-identical studio/setup.sh block and both PowerShell copies have the same omission, so truthy UV_OFFLINE should bypass probing while false spellings such as 0 or off should retain current behavior.

Useful? React with 👍 / 👎.

Accepted on the mirror

Reply from danielhanchen:

Fixed in 5202643: a truthy UV_OFFLINE (uv's spellings) now skips the probes and the mirror race in both shell blocks and both PowerShell copies; the one-shot retries stay armed.

Round 2: reviewed mirror 8bdc852e6c (this PR's 520264369)

chatgpt-codex-connector[bot] (on the mirror)

Codex Review: Didn't find any major issues. 🚀

Reviewed commit: 8bdc852e6c

No triage reaction was recorded on the mirror

Verdict

The round converged at mirror 8bdc852e6c (this PR's 520264369).

This is the review as it stood at that commit. Anything pushed to this PR afterwards was not part of it.

tests/studio/test_installer_av_shapes.py bans vendor names in shipped
scripts, which are handed whole to scanners; the location check comment
now describes the resolvers without naming the clouds.
@danielhanchen
danielhanchen merged commit 8c8dd86 into unslothai:main Sep 26, 2026
77 of 81 checks passed
shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
…re blocked or slow (unslothai#11786)

* feat(studio): let UNSLOTH_NODE_MIRROR rebase the Node.js dist downloads

install_node_prebuilt.py always fetched index.json, SHASUMS256.txt and the archive from nodejs.org. UNSLOTH_NODE_MIRROR now replaces that base for every Node dist URL; archives are still verified against the sha256 pins committed in node_prebuilt_pins.json, so a mirror cannot change what gets installed.

* feat(install): fall back to CERNET and npmmirror when package hosts are blocked or slow

install.sh and studio/setup.sh now probe pypi.org, download.pytorch.org, nodejs.org and registry.npmjs.org in parallel (5 s connect, 10 s total) before the first package install. A host that fails the probe while its mirror passes is redirected through the env vars the package tools already read: PyPI to https://mirrors.cernet.edu.cn/pypi/web/simple, PyTorch wheels to UNSLOTH_PYTORCH_MIRROR=https://mirrors.cernet.edu.cn/pytorch/whl, Node.js to UNSLOTH_NODE_MIRROR=https://mirrors.cernet.edu.cn/nodejs-release, and npm to UNSLOTH_NPM_REGISTRY=https://registry.npmmirror.com.

When pypi.org still answers but misses the budget, uv gets the mirror first and pypi.org second with UV_INDEX_STRATEGY=unsafe-first-match, and pip gets the mirror as PIP_INDEX_URL with pypi.org as PIP_EXTRA_INDEX_URL, so packages the mirror has not synced yet still resolve. When pypi.org does not answer at all, only the mirror is used: unsafe-first-match fetches every index and fails outright when one is unreachable.

A host the user already redirected (UV_* / PIP_* index vars, an index in uv.toml or pip.conf, UNSLOTH_PYTORCH_MIRROR, UNSLOTH_TORCH_INDEX_URL, UNSLOTH_NODE_MIRROR, UNSLOTH_NPM_REGISTRY) is left alone, setup.sh skips the probe when install.sh already ran it, and UNSLOTH_MIRROR_FALLBACK=0 turns the fallback off.

* feat(install): mirror fallback for blocked or slow package hosts on Windows

install.ps1 and studio/setup.ps1 get the same fallback as install.sh: pypi.org, download.pytorch.org, nodejs.org and registry.npmjs.org are probed in parallel, and a host that fails while its CERNET or npmmirror counterpart passes is redirected through the same env vars (UV_*/PIP_* index vars, UNSLOTH_PYTORCH_MIRROR, UNSLOTH_NODE_MIRROR, UNSLOTH_NPM_REGISTRY), with the same slow-versus-blocked PyPI split and the same respect for indexes the user already configured.

The helpers live in the block shared with setup.ps1. The probe uses WebRequest.GetResponseAsync rather than HttpClient, which would need Add-Type, and sends a User-Agent because the CERNET mirrors answer 403 without one. On a session whose SecurityProtocol excludes TLS 1.2 it pins TLS 1.2 for the probe only. install.ps1 restores every variable the fallback may set when it exits, since under irm | iex they belong to the caller's session. setup.ps1 now computes its npm --registry args after the probe, so a fallback registry reaches every npm and bun install.

* feat(install): fall back to npmmirror for uv-managed Python builds when releases.astral.sh is blocked or slow

* feat(install): install the pinned uv from a PyPI mirror wheel when releases.astral.sh is blocked or slow

* feat(install): install the pinned uv from a PyPI mirror wheel on Windows when releases.astral.sh is blocked or slow

* fix(install): define the mirror fallback outside the Unsloth Studio launcher heredoc

The mirror fallback functions sat inside the quoted heredoc that writes the launcher script, so install.sh never defined them and aborted with "_mirror_fallback: not found" right before installing uv. Move the block next to its call and add a check that the block is outside every heredoc in install.sh and studio/setup.sh.

* feat(install): pick mirrors by measured speed on real artifacts

Each default package host is timed alone on a 1 MiB slice of an artifact it serves, and one below 1 MiB/s, or whose index does not answer, is raced against its mirror and swapped for it only when the mirror is faster and its own index answers. CERNET redirects each tree to a different university mirror, so each tree is timed on its own, and releases.astral.sh is timed once for both uv and its Python builds.

* feat(install): pick Windows mirrors by measured speed on real artifacts

Ports the speed probe from install.sh to install.ps1 and studio/setup.ps1: each default host is timed alone on a 1 MiB slice of an artifact it serves, and one below 1 MiB/s, or whose index does not answer, is raced against its mirror and swapped for it only when the mirror is faster and its own index answers. Each probe uses a fresh connection and its own deadline, as a separate curl process would, and the probes raise Windows PowerShell 5.1's two-connections-per-host limit so the race's CERNET requests do not queue. The uv Python-builds mirror is dropped on Windows, where uv is always given a resolved interpreter.

* feat(install): retry a step whose default host's transport failed through its mirror

The mirror probe leaves healthy defaults alone. When a later step fails because the default host stopped answering (a timeout, reset, DNS or TLS error, a 5xx/429, or a download that stalled), the installers now rerun that step once through the host's mirror, after the step's own same-host attempts. The host is read from the failure output, or from the command when a stalled download names no URL; resolution, not-found and other hosts' failures are never retried, so try-then-fallback steps keep their own fallback. A host stays on its mirror for later steps only when the rerun succeeded.

Covers install.sh's install commands, setup.sh's npm installs, install_python_stack.py's pip_install and pip_install_try, and the node and pinned uv downloads (only when no source served the file).

* feat(install): retry a Windows step whose default host's transport failed through its mirror

The Windows mirror fallback now exports the same spare list as the POSIX installers: one mirror per probed host still on its default. install.ps1 reruns a failed package install once through that host's mirror after its own attempts, only when the output shows a transport failure on that host (or a stalled download in a command that uses the default index). A torch mirror rewrites the default torch URLs the command reads, and a mirror is kept for later steps only when the rerun succeeds. studio/setup.ps1 does the same for the frontend and OXC npm installs, and retries the Node download and the pinned uv download (the latter only when no source answered). Every install_python_stack.py run on Windows gets the same retry through the exported list.

The shared-helper sync script now also copies a new shared function that has no comment above it.

* fix(install): use TUNA's CERNET mirror and npmmirror for Node

mirrors.cernet.edu.cn sends the PyPI simple index to a mirror that rate-limits uv's parallel metadata requests (429), failing resolves; tuna.mirrors.cernet.edu.cn serves the index and files from Tsinghua. The Node dist mirror moves to registry.npmmirror.com/-/binary/node, which keeps nodejs.org's layout (index.json, SHASUMS256.txt, archives), and is timed on its own tarball.

* feat(install): fall back to pypi.org only for releases the PyPI mirror lacks

A switched PyPI host now uses the mirror alone, also when pypi.org was only slow: uv's unsafe-first-match fetched every package from pypi.org too, so a pypi.org that dropped mid-install failed every step. When pypi.org still answered, a failed resolve that reports a version or package as not available (a fresh release the mirror has not synced yet) reruns once with pypi.org behind the mirror, and later steps keep that setup if the rerun works. Commands that pin their own index are left alone. install_python_stack.py classifies its installs the same way.

* feat(install.ps1): fall back to pypi.org only for releases the PyPI mirror lacks

The Windows installers now match install.sh: a switched PyPI host uses the mirror alone, also when pypi.org was only slow, and when pypi.org still answered, an install whose resolve reports a version or package as not available reruns once with pypi.org behind the mirror, keeping that setup for later steps if it works. Commands that pin their own index or pass --no-index are left alone.

* fix(install): keep uv on a project-level index when falling back to the PyPI mirror

uv reads uv.toml, or pyproject.toml with a [tool.uv] table, from the current directory or the nearest parent, and an exported UV_DEFAULT_INDEX overrides it. The mirror fallback only checked UV_CONFIG_FILE and the user and system uv.toml, so launching the installer from a project that configures its own index would redirect uv to the mirror. It now also checks the nearest project config, as install_python_stack.py's _uv_config_files does, and recognizes [[tool.uv.index]].

* fix(studio): probe package hosts only before a setup step downloads packages

setup.sh and setup.ps1 ran the mirror speed probe at startup, so every unsloth studio update, even one with nothing to install, fetched a 1 MiB sample from each default package host. The probe now runs right before the Python dependency pass and before a Transformers sidecar is rebuilt, the update steps that download from PyPI and PyTorch. install.sh and install.ps1 still probe up front and pass the result on, so fresh installs are unchanged; a standalone update's Node, npm and uv steps use the default hosts, as before the mirror fallback.

* test: expect _pip_install_once among the requirements-filter callers

pip_install now wraps _pip_install_once with the mirror retry, and the install itself, including its _effective_requirements call, lives in _pip_install_once.

* fix(install): leave pip on an index set in the Unsloth Studio venv's pip config

pip also reads site config from the venv it runs in (<venv>/pip.conf, pip.ini on Windows). The mirror fallback only checked PIP_CONFIG_FILE and the user and global files, so a private index set in the Unsloth Studio venv was overridden by the exported PIP_INDEX_URL whenever the install fell back from uv to pip. The check now includes the venv's site config.

* fix(install): keep a verbose install working on a host without tee

The mirror retry reads a failed command's output, so the verbose install arm copied it to a log with tee. install.sh otherwise needs no tee, and on a minimal image without it the pipe closed and the command died of SIGPIPE. The arm now falls back to cat there, which only costs that host the retry. The tests that lift run_install_cmd out of install.sh also lift the functions it now calls, and stub the mirror retry.

* fix(studio): arm the mirror retries before setup's first download and skip the probe on a --local re-overlay

With the probe moved to the Python dependency pass, a standalone setup reached its Node and npm downloads with no mirror retry armed. setup.sh and setup.ps1 now arm every host's one-shot mirror retry at startup without probing (_mirror_fallback spare / Invoke-MirrorFallback -SpareOnly), and still probe lazily before the first package download. setup.sh arms it from the directory its installs run in, once VENV_DIR is set, so the retry respects the same uv and pip config they do.

A --local update runs the dependency pass every time to re-overlay the checkout, almost entirely from uv's cache, so on an existing venv that pass relies on the armed retries instead of probing every host first.

* Trim installer mirror fallback comments

* Respect NPM_CONFIG_REGISTRY and recheck default indexes in the mirror race

A registry set through NPM_CONFIG_REGISTRY / npm_config_registry outranks
the frontend .npmrc today; the fallback exported UNSLOTH_NPM_REGISTRY,
which becomes --registry and overrode it. Treat it as user configuration.

The race re-timed the default artifact but reused the first-round default
index result, so one index answer lost in the first round forced a healthy
host into blocked mode. Probe the default index again beside the mirror's.

* Only use the mirror fallback in mainland China

Outside mainland China the installers now behave as before the fallback:
no probe, no mirror retries armed, nothing exported. Location is read
without a network call: a mainland time zone (Asia/Shanghai and its
aliases, Windows "China Standard Time"), or a resolver from a mainland
public DNS or cloud (AliDNS, DNSPod, 114DNS, Baidu, CNNIC, Alibaba Cloud
and Tencent Cloud internal resolvers), which covers UTC cloud VMs there.
UNSLOTH_MIRROR_FALLBACK=1 opts in anywhere; =0 still opts out.

* Keep the installers byte-identical to before outside mainland China

With no mirror retry armed (outside mainland China, or opted out):
- run_install_cmd runs the plain runner, so set -e stops the installer
  where a command fails as before, and verbose output is not copied to a
  temp file through tee.
- The PowerShell runners stream verbose output without buffering it, and
  the npm / install retries return before reading any output.
- _mirror_retry in install_python_stack.py returns before decoding and
  scanning the failed output (183 ms for 1 MB of output before).
- A retry state inherited from a parent process is dropped, so neither a
  stale _UNSLOTH_MIRROR_SPARE nor UNSLOTH_MIRROR_FALLBACK=0 can be bypassed.
- setup.sh no longer changes directory (and OLDPWD) to arm the retries.

The location is read once per process, resolvers come from .NET instead of
Get-DnsClientServerAddress (no module or CIM load on Windows), and the
114DNS filtering resolvers plus DNSPod 182.254.116.116 / 119.28.28.28 count
as mainland China. An interrupted install also removes a kept output copy.

* Mirror fallback: honour XDG_CONFIG_DIRS, skip permission failures, retry sidecars

- pip and uv read an index from every directory in XDG_CONFIG_DIRS; an
  index configured there now counts as user configuration, so the
  fallback no longer overrides it.
- The Node install no longer retries through the mirror on exit 4
  (permission denied), matching setup.ps1.
- Transformers sidecar installs rerun once with pypi.org behind the
  mirror when the probe switched a slow pypi.org, as the dependency pass
  already does for a pin the mirror has not synced.

All three only act when the fallback is on (mainland China or
UNSLOTH_MIRROR_FALLBACK=1).

* Trim mirror fallback comments

* Mirror fallback: probe nothing when UV_OFFLINE is set

uv's own no-network switch (its spellings: 1, t, true, y, yes, on) now
skips the speed probes and the mirror race; the one-shot retries stay
armed, as they only follow a failed network command.

* Keep vendor names out of the installer comments

tests/studio/test_installer_av_shapes.py bans vendor names in shipped
scripts, which are handed whole to scanners; the location check comment
now describes the resolvers without naming the clouds.

---------

Co-authored-by: danielhanchen <[email protected]>
Co-authored-by: Daniel Han <[email protected]>
Sletch added a commit to Sletch/unsloth that referenced this pull request Sep 29, 2026
Get-BlockSource took the Node exit handling from the first
`$nodeExit = $LASTEXITCODE` to the next closing brace at that indent. unslothai#11786
put the mirror retry between the two, `if ($nodeExit -notin 0, 3, 4 -and
(Use-MirrorSpare node)) { ... }`, so the slice ended at the retry's own brace.
Merged with main, four of the five tests on a kept Node failed against a
setup.ps1 that still has the branch they look for.

The marker is now `$nodeExit -eq 3`, the chain's first line, once in
setup.ps1. Against main's setup.ps1 the file still fails 11 of 22 (4, 3, 1, 3
and 0 by block), as it did at a09f376; with this branch's it passes 22.
Stanley00 pushed a commit to stanley-fork/unsloth that referenced this pull request Oct 5, 2026
…unslothai#10075)

* studio: report a denied Node rename as a possible ACL fault, not a scanner

_replace_with_retry retries `os.replace` on WinError 5, 32 and 145 and logs one
message for all three: "a scanner is likely still holding the extracted files".
WinError 5 is not only a scanner. It is equally what a tree with unreadable ACLs
looks like, and that is a permission fault no backoff can clear. It matters most
because `_swap_into_place` also uses this helper to move the EXISTING install
aside, the tree a user is likeliest to have broken permissions on.

In unslothai#9928 the same rename in the llama.cpp installer failed with (5) on every
attempt and reported a scanner. The reporter's cause was corrupt ACLs -- icacls
and Get-Acl both returned access-denied for the directory -- and
`takeown /F ... /R /D Y` followed by `icacls ... /reset /T /C` fixed it. The Node
helper carries the same three codes and the same message.

5 stays in the retry set: a scanner does raise it right after extraction. Only
the reporting changes: the per-retry line offers both causes, and the
takeown/icacls recovery prints once, when the budget is exhausted rather than on
every attempt. WinError 32 and 145 keep their wording. The two commands go on
separate lines for the reason tests/studio/install/test_setup_denied_install_tree.py
pins -- on one line takeown swallows icacls as an argument. The constant and the
recovery lines live in this module because it imports nothing outside the stdlib
on purpose.

Three tests extend the suite that already covers the helper. Two fail without
the change: test_replace_names_acl_recovery_when_access_denied_persists and
test_replace_does_not_blame_a_scanner_for_access_denied.
test_replace_keeps_the_scanner_message_for_a_sharing_violation is a parity guard:
32 keeps its wording and prints no ACL guidance.

One consequence worth naming: a 5 that really was a scanner now prints ACL
guidance that does not apply to it, at the point the rename has already failed.

Refs unslothai#9928.

* studio: make ACL rename recovery actionable

* studio: address ACL recovery review feedback

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* studio: stop reporting every blocked llama.cpp install as an active process

setup.ps1 exits 3 when the existing llama.cpp install could not be replaced, and
both sites that report it asserted an active llama.cpp process as the cause.
Windows raises WinError 5 for a file another process holds open and for a tree
whose ACLs are unreadable alike; is_busy_lock_error in studio/prebuilt_core.py
classifies 5 as busy for exactly that reason, and _access_denied_recovery_lines
prints takeown/icacls guidance for the ACL case. Write-LlamaFailureLog relays
that guidance into the same block, so an ACL-denied user read repair commands
bracketed by a headline and a retry hint that both named a process instead.

Two sites, not one. The prebuilt exit-3 branch is the reported one; the
local-directory link path carries the same three lines and says in its own
comment that it mirrors the prebuilt handling, and that "Denied counts as
surviving: unreadable is not gone" -- so it reaches the message by the same
route and had to move with it.

The classification is unchanged: exit 3 still means blocked, is_busy_lock_error
still treats WinError 5 as busy, and the user is still told to close other
llama.cpp users. Only the claim about which cause it was is dropped, in favour
of naming both recoveries. whisper.cpp's exit-3 branch already reads "install
busy; keeping existing runtime" and is the cause-neutral precedent followed here.

Studio.Setup.BlockedInstallCause.Tests.ps1 pins it: 15 tests, 5 of which fail
without this change, including a file-wide guard that neither phrase reappears
at a third site and that every blocked-install site offers ACL repair.

One consequence worth naming: the local-link path names the directory but cannot
print the takeown/icacls lines, because it has no installer output to relay. It
points at the ACLs on that path and leaves the commands to Write-PathAccessDenied,
which already prints them wherever setup detects a denial up front.

* studio: gate ACL retry guidance on helper output

* studio: keep a running Node when its replacement stays denied

The re-raise of a reported access denial sat ahead of install_prebuilt's
keep-existing check, so a WinError 5 rename that outlasted the retries failed
setup even when the Node already on disk still ran: exit 1, which setup.ps1 and
setup.sh turn into "Could not install an isolated Node runtime". The re-raise
was there for a real reason -- both scripts show the installer's output only on
a non-zero exit, so a plain keep-existing return would have swallowed the
takeown/icacls lines -- but the two goals conflicted only because exit 0 was
silent.

It no longer is. install_llama_prebuilt.py already exits 0 when it keeps the
tree on disk after a transient failure, and setup.ps1 and setup.sh match its
"keeping the existing complete install" line to warn "update unavailable,
existing prebuilt kept". Node now takes the same shape: the reported denial
reaches the keep-existing check like any other failure, a Node that still runs
is kept with exit 0 on a line ending "keeping existing isolated Node", as the
download-failure case already logs, and both scripts match that line, warn
"update not applied, existing isolated Node kept", and relay the installer
output when it carries takeown lines. The line names the rename instead of
"Node download failed" when that is what failed. The warning is not llama.cpp's
text, which test_pr10648_offline_and_status.py holds to exactly two keep arms.

No new exit code, and nothing else moves: a Node that does not run, a forced
reinstall, and a same-version install whose digest is not the pin still raise,
exactly as they do for a failed download. setup.sh gets the arm for parity; its
takeown branch can only fire on Windows output.

test_install_prebuilt_keeps_existing_when_a_reported_denial_blocks_the_swap
replaces test_install_prebuilt_does_not_hide_reported_acl_denial and fails
without this change, when the swap's OSError escapes. The three cases of
test_install_prebuilt_reraises_a_reported_denial_it_cannot_keep_existing_through
are parity guards. Studio.Setup.BlockedInstallCause.Tests.ps1 gains a block on
the setup.ps1 arm, four of its five tests failing without it, and
tests/sh/test_setup_node_kept_existing.sh runs the real setup.sh block against a
stand-in installer, three of its thirteen checks failing without it.

One consequence worth naming: setup now carries on with a Node it could not
replace, so a user can stay on an older runtime while setup succeeds, and the
warning prints once per run.

Refs unslothai#9928.

* studio: offer the Node ACL repair only where the caller names the paths

_replace_with_retry printed takeown/icacls for its source whenever a WinError 5
outlasted the retries, and flagged the exception as a reported denial, whoever
called it. Since unslothai#10648 that includes atomic_replace_from_tempfile, which renames
a temp file onto the downloaded archive and onto the install marker. A denial
there named a temp file that is removed moments later, and the flag made the
keep-existing line say the existing Node "could not be replaced" when the swap
had never run.

The repair lines and the flag now need access_denied_paths, which only
_swap_into_place passes, for its three renames. A temp-file rename still retries
the same budget and still raises; it only stops naming a path that will not
exist, and a Node kept after it is logged as "Node download failed", as before.

test_a_denied_marker_write_offers_no_repair_for_its_temp_file drives
atomic_replace_from_tempfile into an exhausted 5 and fails without this change.
test_replace_names_acl_recovery_when_access_denied_persists now passes its paths,
as the callers that get the lines do.

Refs unslothai#9928.

* studio: describe the llama.cpp exit-3 repair gate by what it checks

The comment above setup.ps1's llama.cpp exit-3 branch said "The helper prints
takeown guidance only when access was denied", and the header of
Studio.Setup.BlockedInstallCause.Tests.ps1 named _access_denied_recovery_lines
as the source of llama.cpp's repair commands. Both described the installer
half this PR carried before the llama.cpp message was left to unslothai#10182.

On main no installer prints those lines: install_llama_prebuilt.py and
prebuilt_core.py contain no takeown at all, and _access_denied_recovery_lines
exists only in install_node_prebuilt.py. So the branch's `-match 'takeown /F'`
arm is correct but cannot fire until unslothai#10182 lands, and both comments said it
could.

The gate stays, because it is what unslothai#10182's output needs, and without it the
ACL repair hint would be offered to every busy install. Only the text changes:
both comments now describe the check rather than a producer.

Comments only, no assertion changes.

Refs unslothai#9928

* tests: anchor the Node exit-chain Pester block on the chain itself

Get-BlockSource took the Node exit handling from the first
`$nodeExit = $LASTEXITCODE` to the next closing brace at that indent. unslothai#11786
put the mirror retry between the two, `if ($nodeExit -notin 0, 3, 4 -and
(Use-MirrorSpare node)) { ... }`, so the slice ended at the retry's own brace.
Merged with main, four of the five tests on a kept Node failed against a
setup.ps1 that still has the branch they look for.

The marker is now `$nodeExit -eq 3`, the chain's first line, once in
setup.ps1. Against main's setup.ps1 the file still fails 11 of 22 (4, 3, 1, 3
and 0 by block), as it did at a09f376; with this branch's it passes 22.

* studio: print the Node ACL repair only when the existing Node is kept

Since unslothai#10533, a denied swap that cannot keep the existing Node reaches main()
as a PermissionError and exits 4, and setup.ps1 answers exit 4 with
Exit-PathAccessDenied: its own elevated takeown/icacls for the refused path
and a note that antivirus can deny it too. _replace_with_retry had already
printed ours, so that path showed two sets of repair commands for the same
folder, with different icacls flags, around unslothai#10533's advice that elevation
may not clear a security-software block.

The lines now ride on the error and install_prebuilt logs them only in the
branch that keeps a Node that still runs. That is exit 0, where setup.ps1
and setup.sh relay them on `takeown /F` and nothing else names a repair.
"rename still blocked (5) after N attempts" still prints at the retry, so the
exit-4 output keeps the rename's own record.

Measured through main() with the real swap and a refused rename: exit 4
printed our four repair commands ahead of unslothai#10533's message, and now prints
none, with the denied-path and denied-scope markers unchanged. A kept Node
prints the same lines as before, ahead of "existing Node could not be
replaced".

test_a_denial_that_cannot_keep_node_leaves_the_repair_to_setup fails
without this change; test_a_kept_node_prints_the_repair_setup_relays is a
parity guard for the kept path. Four tests that read the lines from the log
or checked the old flag, and the swap stand-in that set it, now use the error.

One consequence worth naming: when the rollback of a failed forward rename
is denied too, the repair lines naming the backup no longer print. The line
"could not restore the previous Node install from <backup>" still names it,
and the run exits 4.

* Trim comments in the denied-rename reporting

---------

Co-authored-by: Etherll <[email protected]>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Daniel Han <[email protected]>
danielhanchen added a commit that referenced this pull request Oct 6, 2026
@($null.Keys) is a one-item array holding $null, so the restore loop ran
once with a null key and indexing threw, stopping the finally before the
overrides file and UNSLOTH_KEPT_TORCH were cleaned up. Guard it the same way
as the WoA resolver restore just above it. Production initialises
MirrorEnvSaved before the try, so this only hardens the path.

test_unsloth_torch_override.ps1 replays that finally and had been failing
since #11786 added the restore, unnoticed because no CI job ran it. Cover
both the nothing-saved and the saved-variables cases and run the test in
the Windows inference smoke job with the other installer .ps1 tests.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants