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.

Stop five Windows jobs rebuilding the same frontend on every commit (#9387)

Daniel Han4880b780a4a8
diff --git a/.github/actions/frontend-dist-restore/action.yml b/.github/actions/frontend-dist-restore/action.yml
new file mode 100644
index 00000000000..7fa5a1a6d46
--- /dev/null
+++ b/.github/actions/frontend-dist-restore/action.yml
@@ -0,0 +1,189 @@
+# 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.
+
+name: Restore the built frontend
+description: >-
+ Restore studio/frontend/dist for this runner, keyed on exactly the sources
+ setup.sh and setup.ps1 check before rebuilding, and make the restored directory
+ outrank the checkout that just wrote those sources. Read-only: the save is a
+ separate action and runs on the default branch only.
+
+inputs:
+ path-prefix:
+ description: >-
+ Where actions/checkout put THIS repo, WITH a trailing slash ("unsloth/"),
+ or the empty string when it is at the workspace root.
+
+ Not cosmetic. `hashFiles()` resolves from GITHUB_WORKSPACE, not from the
+ workflow file, so a job that checks the repo out into a subdirectory and
+ leaves this empty gets globs that match nothing -- and hashFiles returns
+ the EMPTY STRING for that rather than failing, which collapses every commit
+ onto one key and serves an arbitrary dist. The degenerate-key step below
+ refuses that outright, and a prefix missing its trailing slash lands in the
+ same place (loudly), so both mistakes fail at the first step rather than
+ silently.
+ required: false
+ default: ''
+
+outputs:
+ cache-hit:
+ description: "'true' when the exact key was restored."
+ value: ${{ steps.restore.outputs.cache-hit }}
+ key:
+ description: The full cache key, to hand to frontend-dist-save.
+ value: ${{ steps.restore.outputs.cache-primary-key }}
+ dist-path:
+ description: The dist directory this action restored, prefix included.
+ value: ${{ inputs.path-prefix }}studio/frontend/dist
+
+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.
+ - 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)) }}
+ 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.
+ 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
+ fi
+
+ - 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.
+ 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)) }}
+
+ # 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.
+ - name: Make the restored frontend outrank its sources (POSIX)
+ if: steps.restore.outputs.cache-hit == 'true' && runner.os != 'Windows'
+ shell: bash
+ env:
+ DIST: ${{ inputs.path-prefix }}studio/frontend/dist
+ FE: ${{ inputs.path-prefix }}studio/frontend
+ run: |
+ if [ ! -d "$DIST" ]; then
+ echo "::error::the frontend dist cache reported a hit but restored no directory at $DIST"
+ 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
+ fi
+ if [ -n "$newer" ]; then
+ echo "::error::$DIST was touched but $newer is still newer, so setup.sh will rebuild the frontend it just restored"
+ exit 1
+ 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.
+ - name: Make the restored frontend outrank its sources (Windows)
+ if: steps.restore.outputs.cache-hit == 'true' && runner.os == 'Windows'
+ shell: pwsh
+ env:
+ DIST: ${{ inputs.path-prefix }}studio/frontend/dist
+ FE: ${{ inputs.path-prefix }}studio/frontend
+ run: |
+ $ErrorActionPreference = 'Stop'
+ $dist = $env:DIST
+ $fe = $env:FE
+ if (-not (Test-Path -LiteralPath $dist -PathType Container)) {
+ Write-Host "::error::the frontend dist cache reported a hit but restored no directory at $dist"
+ exit 1
+ }
+ (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')) {
+ $subPath = Join-Path $fe $subDir
+ if (Test-Path -LiteralPath $subPath) {
+ $newer = Get-ChildItem -LiteralPath $subPath -Recurse -File -ErrorAction SilentlyContinue |
+ Where-Object { $_.LastWriteTime -gt $distTime } | Select-Object -First 1
+ if ($newer) { break }
+ }
+ }
+ if (-not $newer) {
+ $newer = Get-ChildItem -LiteralPath $fe -File -ErrorAction SilentlyContinue |
+ Where-Object { $_.Name -ne 'bun.lock' -and $_.LastWriteTime -gt $distTime } |
+ Select-Object -First 1
+ }
+ if ($newer) {
+ Write-Host "::error::$dist was stamped $distTime but $($newer.FullName) is still newer, so setup.ps1 will rebuild the frontend it just restored"
+ exit 1
+ }
+ Write-Host "restored a prebuilt frontend; setup.ps1 will report it up to date"
diff --git a/.github/actions/frontend-dist-save/action.yml b/.github/actions/frontend-dist-save/action.yml
new file mode 100644
index 00000000000..b3f6279a1f2
--- /dev/null
+++ b/.github/actions/frontend-dist-save/action.yml
@@ -0,0 +1,127 @@
+# 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.
+
+name: Save the built frontend
+description: >-
+ Prove a restored frontend was actually reused rather than rebuilt, then save
+ studio/frontend/dist under the restore step's key, on the default branch only.
+
+inputs:
+ path-prefix:
+ description: >-
+ The same value passed to frontend-dist-restore: where actions/checkout put
+ this repo, WITH a trailing slash, or the empty string.
+ required: false
+ default: ''
+ cache-hit:
+ description: >-
+ frontend-dist-restore's `cache-hit` output. Drives both halves: 'true' means
+ assert the restore was reused and skip the save (the key is already present,
+ re-uploading it is pure cost); anything else means the build really ran and
+ is worth saving.
+ required: true
+ key:
+ description: frontend-dist-restore's `key` output.
+ required: true
+ save:
+ description: >-
+ 'false' to run the reuse assertion but skip the upload. For a workflow whose
+ triggers cannot routinely put github.ref on refs/heads/main -- no `push`, no
+ `schedule` -- where the save below could only fire if a human dispatched the
+ workflow from main by hand. A cache that fills only when somebody remembers to
+ press a button is not a cache, and leaving the step in place would be config that
+ reads as a caching decision which is not in force.
+
+ The assertion half still runs, deliberately: it is the only check on the one
+ failure mode this cache has that nothing else reveals, and a consumer-only lane is
+ as good a place to catch it as a producer.
+ required: false
+ default: 'true'
+ install-log:
+ description: >-
+ Path to the installer log this job teed, used for the reuse assertion. Every
+ call site writes logs/install.log, which is why that is the default; a job
+ that writes somewhere else must say so rather than have the assertion quietly
+ find no file and pass.
+ required: false
+ default: logs/install.log
+
+runs:
+ using: composite
+ steps:
+ - name: Prove the restored frontend was reused and not rebuilt
+ if: inputs.cache-hit == 'true'
+ shell: bash
+ env:
+ 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.
+ 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
+ fi
+ if [ ! -d "$DIST" ]; then
+ 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
+ exit 1
+ 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.
+ - name: Save the built frontend
+ if: >-
+ github.ref == 'refs/heads/main' && inputs.cache-hit != 'true'
+ && inputs.save != 'false'
+ uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
+ continue-on-error: true
+ with:
+ path: ${{ inputs.path-prefix }}studio/frontend/dist
+ key: ${{ inputs.key }}
diff --git a/.github/actions/install-unsloth-local/action.yml b/.github/actions/install-unsloth-local/action.yml
index c778fd2814b..445de0ac3da 100644
--- a/.github/actions/install-unsloth-local/action.yml
+++ b/.github/actions/install-unsloth-local/action.yml
@@ -101,82 +101,35 @@ runs:
# so what is left is compute, and the only way to stop paying it 13 times is to
# not do it 13 times.
#
- # studio/setup.sh decides whether to rebuild by mtime: it looks for anything
- # under frontend/ (maxdepth 1, minus bun.lock), frontend/src or frontend/public
- # NEWER than frontend/dist, and skips the build when it finds nothing. So the key
- # hashes exactly those three path groups. A hit then means the build inputs are
- # byte-identical, which is a strictly stronger statement than the mtime test it
- # rides on, and the restored dist is correct by construction rather than by luck.
+ # 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.
#
- # tests/studio/test_frontend_dist_cache.py pins the key against the paths setup.sh
- # actually reads, because the two drifting apart is silent: the cache would keep
- # hitting and start serving a dist built from inputs no longer in the key.
+ # 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.
#
- # bun.lock is IN the key even though the staleness check excludes it. The check
- # has to exclude it because the install regenerates it and it would self-trigger
- # every run; the cache has no such problem, and a lockfile change means different
- # dependencies and so a different bundle. That is deliberate and makes the cache
- # safer than the check.
+ # (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.)
- name: Restore the built frontend
id: fe-dist
- uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
- continue-on-error: true
- with:
- path: studio/frontend/dist
- # The two negations are load-bearing, not tidiness. `studio/frontend/*` is
- # RECURSIVE: @actions/glob sets matchDirectories and implicitDescendants true, so a
- # bare `*` matches the subdirectory ENTRY and then expands it. Verified against the
- # real library -- `fe/*` yields fe/tests/t.txt, while `fe/*.txt` yields only
- # fe/top.txt, which is why the docs' non-recursive example does not apply here.
- # Without these, the key hashed all 457 files under frontend/tests and
- # frontend/scripts, so editing any frontend TEST evicted a dist whose bundle is
- # byte-identical. setup.sh reads neither directory, so excluding them makes the key
- # mean what it already claimed to mean.
- #
- # Negations last: they filter everything matched before them. A subdirectory added
- # later is NOT excluded, so it lands in the key and errs toward rebuilding, which is
- # the safe direction. Narrowing this to an extension allowlist would fail the other
- # way, silently serving a stale dist when a new top-level file type appeared.
- # NO restore-keys, deliberately, and the opposite of the uv cache above. 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.
- key: fe-dist-${{ runner.os }}-${{ hashFiles('studio/frontend/*', 'studio/frontend/src/**', 'studio/frontend/public/**', '!studio/frontend/tests/**', '!studio/frontend/scripts/**') }}
-
- - name: Make the restored frontend outrank its sources
- if: steps.fe-dist.outputs.cache-hit == 'true'
- shell: bash
- run: |
- # 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 setup.sh's `find -newer dist` would find the whole tree
- # newer and rebuild anyway -- the cache would cost a download and save
- # nothing, while looking like it worked. 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: the staleness check compares against `frontend/dist`
- # itself, not its contents.
- if [ ! -d studio/frontend/dist ]; then
- echo "::error::the frontend dist cache reported a hit but restored no directory"
- exit 1
- fi
- touch studio/frontend/dist
- echo "restored a prebuilt frontend; setup.sh will report it up to date"
-
- - name: Refuse a frontend cache key that hashes nothing
- shell: bash
- env:
- FE_KEY: ${{ hashFiles('studio/frontend/*', 'studio/frontend/src/**', 'studio/frontend/public/**', '!studio/frontend/tests/**', '!studio/frontend/scripts/**') }}
- run: |
- # hashFiles returns the empty string 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
- # would be invisible: the restore succeeds and the build is skipped.
- if [ -z "$FE_KEY" ]; then
- echo "::error::hashFiles matched no frontend sources, so the dist cache key is degenerate. The frontend layout moved; update the key and tests/studio/test_frontend_dist_cache.py together."
- exit 1
- fi
+ uses: ./.github/actions/frontend-dist-restore
- name: Install Unsloth (--local, --no-torch)
shell: bash
@@ -212,26 +165,20 @@ runs:
printf '[%4ds] %s\n' "$SECONDS" "$line"
done
- # Save on main only, like every other cache in this repo, and for the reason
- # the HF and Playwright caches record: a PR-scoped entry can only be restored
- # by re-runs of that same PR, while every PR can restore from the default
- # branch. Saving on PRs would spend the 50 GiB budget -- measured at 99.3% full
- # once already -- evicting main's copy, which is the one everyone reads.
+ # 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.
#
- # `uv cache prune --ci` first: uv keeps built wheels AND unpacked source
+ # `uv cache prune --ci` further down: uv keeps built wheels AND unpacked source
# artifacts, and only the former are worth carrying between runners. Without it
- # this key grows without bound across 39 jobs and re-opens the eviction thrash
+ # that key grows without bound across 39 jobs and re-opens the eviction thrash
# the GGUF caches were fixed for.
- # 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.
- name: Save the built frontend
- if: github.ref == 'refs/heads/main' && steps.fe-dist.outputs.cache-hit != 'true'
- uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
- continue-on-error: true
+ uses: ./.github/actions/frontend-dist-save
with:
- path: studio/frontend/dist
- key: ${{ steps.fe-dist.outputs.cache-primary-key }}
+ cache-hit: ${{ steps.fe-dist.outputs.cache-hit }}
+ key: ${{ steps.fe-dist.outputs.key }}
- name: Save the uv download cache
if: always() && github.ref == 'refs/heads/main' && steps.uv-cache.outputs.cache-hit != 'true'
diff --git a/.github/workflows/local-agent-guides-ci.yml b/.github/workflows/local-agent-guides-ci.yml
index 8b6ecd99a8f..e36f67a038c 100644
--- a/.github/workflows/local-agent-guides-ci.yml
+++ b/.github/workflows/local-agent-guides-ci.yml
@@ -58,6 +58,11 @@ on:
# The install step in this workflow is `uses:` on that composite action,
# so an edit to the action changes what this workflow actually runs.
- '.github/actions/install-unsloth-local/action.yml'
+ # The dist cache moved out of install-unsloth-local so the Windows jobs could
+ # share one definition of its key; a change to it still has to re-run the jobs
+ # that depend on it.
+ - '.github/actions/frontend-dist-restore/action.yml'
+ - '.github/actions/frontend-dist-save/action.yml'
- '.github/scripts/serve-unsloth-run.sh'
- '.github/scripts/assert-prompt-cache.sh'
- '.github/scripts/agent-guides-install.sh'
@@ -78,6 +83,11 @@ on:
- '.github/workflows/local-agent-guides-ci.yml'
- '.github/scripts/retry-with-apt-lock.sh'
- '.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'
- '.github/scripts/serve-unsloth-run.sh'
- '.github/scripts/assert-prompt-cache.sh'
- '.github/scripts/agent-guides-install.sh'
diff --git a/.github/workflows/startup-profile-ci.yml b/.github/workflows/startup-profile-ci.yml
index 403c433b722..886255bfb36 100644
--- a/.github/workflows/startup-profile-ci.yml
+++ b/.github/workflows/startup-profile-ci.yml
@@ -53,6 +53,8 @@ on:
# makes --local overlay studio.backend*.
- 'install.sh'
- 'install.ps1'
+ - '.github/actions/frontend-dist-restore/action.yml'
+ - '.github/actions/frontend-dist-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
@@ -102,6 +104,34 @@ 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.
+ - name: Restore the built frontend
+ id: fe-dist
+ uses: ./.github/actions/frontend-dist-restore
+
- name: Install Studio
shell: bash
env:
@@ -117,6 +147,18 @@ jobs:
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.
+ - name: Check the restored frontend was reused
+ uses: ./.github/actions/frontend-dist-save
+ with:
+ cache-hit: ${{ steps.fe-dist.outputs.cache-hit }}
+ key: ${{ steps.fe-dist.outputs.key }}
+ save: 'false'
+
- name: Profile startup
shell: bash
run: |
diff --git a/.github/workflows/studio-api-smoke.yml b/.github/workflows/studio-api-smoke.yml
index 39abd8d1813..ad2fb97aaae 100644
--- a/.github/workflows/studio-api-smoke.yml
+++ b/.github/workflows/studio-api-smoke.yml
@@ -36,6 +36,11 @@ on:
# The install step in this workflow is `uses:` on that composite action,
# so an edit to the action changes what this workflow actually runs.
- '.github/actions/install-unsloth-local/action.yml'
+ # The dist cache moved out of install-unsloth-local so the Windows jobs could
+ # share one definition of its key; a change to it still has to re-run the jobs
+ # that depend on it.
+ - '.github/actions/frontend-dist-restore/action.yml'
+ - '.github/actions/frontend-dist-save/action.yml'
push:
branches: [main]
workflow_dispatch:
diff --git a/.github/workflows/studio-inference-smoke.yml b/.github/workflows/studio-inference-smoke.yml
index 4fae9c0cde1..6a561bfd282 100644
--- a/.github/workflows/studio-inference-smoke.yml
+++ b/.github/workflows/studio-inference-smoke.yml
@@ -50,6 +50,11 @@ on:
# The install step in this workflow is `uses:` on that composite action,
# so an edit to the action changes what this workflow actually runs.
- '.github/actions/install-unsloth-local/action.yml'
+ # The dist cache moved out of install-unsloth-local so the Windows jobs could
+ # share one definition of its key; a change to it still has to re-run the jobs
+ # that depend on it.
+ - '.github/actions/frontend-dist-restore/action.yml'
+ - '.github/actions/frontend-dist-save/action.yml'
push:
branches: [main]
# Manual trigger for pre-warming HF_HOME caches on main, or re-running
diff --git a/.github/workflows/studio-mac-install-matrix.yml b/.github/workflows/studio-mac-install-matrix.yml
index aa451c67c45..dfcfc19eaa2 100644
--- a/.github/workflows/studio-mac-install-matrix.yml
+++ b/.github/workflows/studio-mac-install-matrix.yml
@@ -19,6 +19,11 @@ on:
# The install step in this workflow is `uses:` on that composite action,
# so an edit to the action changes what this workflow actually runs.
- '.github/actions/install-unsloth-local/action.yml'
+ # The dist cache moved out of install-unsloth-local so the Windows jobs could
+ # share one definition of its key; a change to it still has to re-run the jobs
+ # that depend on it.
+ - '.github/actions/frontend-dist-restore/action.yml'
+ - '.github/actions/frontend-dist-save/action.yml'
# 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
@@ -50,6 +55,11 @@ on:
# The install step in this workflow is `uses:` on that composite action,
# so an edit to the action changes what this workflow actually runs.
- '.github/actions/install-unsloth-local/action.yml'
+ # The dist cache moved out of install-unsloth-local so the Windows jobs could
+ # share one definition of its key; a change to it still has to re-run the jobs
+ # that depend on it.
+ - '.github/actions/frontend-dist-restore/action.yml'
+ - '.github/actions/frontend-dist-save/action.yml'
# 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
diff --git a/.github/workflows/studio-mac-ui-smoke.yml b/.github/workflows/studio-mac-ui-smoke.yml
index 7eb852cb2d8..645a5dbd854 100644
--- a/.github/workflows/studio-mac-ui-smoke.yml
+++ b/.github/workflows/studio-mac-ui-smoke.yml
@@ -44,6 +44,11 @@ on:
# The install step in this workflow is `uses:` on that composite action,
# so an edit to the action changes what this workflow actually runs.
- '.github/actions/install-unsloth-local/action.yml'
+ # The dist cache moved out of install-unsloth-local so the Windows jobs could
+ # share one definition of its key; a change to it still has to re-run the jobs
+ # that depend on it.
+ - '.github/actions/frontend-dist-restore/action.yml'
+ - '.github/actions/frontend-dist-save/action.yml'
# The absorbed update phase round-trips scripts/uninstall.sh, which none
# of the entries above cover.
- 'scripts/uninstall.sh'
@@ -84,6 +89,11 @@ on:
# The install step in this workflow is `uses:` on that composite action,
# so an edit to the action changes what this workflow actually runs.
- '.github/actions/install-unsloth-local/action.yml'
+ # The dist cache moved out of install-unsloth-local so the Windows jobs could
+ # share one definition of its key; a change to it still has to re-run the jobs
+ # that depend on it.
+ - '.github/actions/frontend-dist-restore/action.yml'
+ - '.github/actions/frontend-dist-save/action.yml'
# The absorbed update phase round-trips scripts/uninstall.sh, which none
# of the entries above cover.
- 'scripts/uninstall.sh'
diff --git a/.github/workflows/studio-ui-smoke.yml b/.github/workflows/studio-ui-smoke.yml
index 81cd4cae490..b36b8db3103 100644
--- a/.github/workflows/studio-ui-smoke.yml
+++ b/.github/workflows/studio-ui-smoke.yml
@@ -41,6 +41,11 @@ on:
# The install step in this workflow is `uses:` on that composite action,
# so an edit to the action changes what this workflow actually runs.
- '.github/actions/install-unsloth-local/action.yml'
+ # The dist cache moved out of install-unsloth-local so the Windows jobs could
+ # share one definition of its key; a change to it still has to re-run the jobs
+ # that depend on it.
+ - '.github/actions/frontend-dist-restore/action.yml'
+ - '.github/actions/frontend-dist-save/action.yml'
push:
branches: [main]
workflow_dispatch:
diff --git a/.github/workflows/studio-update-smoke.yml b/.github/workflows/studio-update-smoke.yml
index 8c50f343f05..674ee163e40 100644
--- a/.github/workflows/studio-update-smoke.yml
+++ b/.github/workflows/studio-update-smoke.yml
@@ -29,6 +29,11 @@ on:
# The install step in this workflow is `uses:` on that composite action,
# so an edit to the action changes what this workflow actually runs.
- '.github/actions/install-unsloth-local/action.yml'
+ # The dist cache moved out of install-unsloth-local so the Windows jobs could
+ # share one definition of its key; a change to it still has to re-run the jobs
+ # that depend on it.
+ - '.github/actions/frontend-dist-restore/action.yml'
+ - '.github/actions/frontend-dist-save/action.yml'
push:
branches: [main]
workflow_dispatch:
diff --git a/.github/workflows/studio-windows-api-smoke.yml b/.github/workflows/studio-windows-api-smoke.yml
index 79d49808b56..d964ee83aec 100644
--- a/.github/workflows/studio-windows-api-smoke.yml
+++ b/.github/workflows/studio-windows-api-smoke.yml
@@ -19,6 +19,8 @@ on:
- 'unsloth/**'
- 'unsloth_cli/**'
- 'install.ps1'
+ - '.github/actions/frontend-dist-restore/action.yml'
+ - '.github/actions/frontend-dist-save/action.yml'
- 'pyproject.toml'
- 'tests/studio/**'
- '.github/workflows/studio-windows-api-smoke.yml'
@@ -149,6 +151,17 @@ 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.
+ - name: Restore the built frontend
+ id: fe-dist
+ uses: ./.github/actions/frontend-dist-restore
+
- name: Install Unsloth (--local, --no-torch)
shell: pwsh
env:
@@ -178,6 +191,15 @@ jobs:
ForEach-Object { '[{0,4:N0}s] {1}' -f $sw.Elapsed.TotalSeconds, $_ }
if ($LASTEXITCODE -ne 0) { throw "install.ps1 exited with code $LASTEXITCODE" }
+ # Paired with the restore above: 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.
+ - 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 }}
+
- name: Assert install.ps1 used the Windows llama.cpp prebuilt
run: |
# Filesystem-based check: it does not depend on which process
diff --git a/.github/workflows/studio-windows-inference-smoke.yml b/.github/workflows/studio-windows-inference-smoke.yml
index f8f5bebc484..08051293af6 100644
--- a/.github/workflows/studio-windows-inference-smoke.yml
+++ b/.github/workflows/studio-windows-inference-smoke.yml
@@ -28,6 +28,8 @@ on:
- 'unsloth/**'
- 'unsloth_cli/**'
- 'install.ps1'
+ - '.github/actions/frontend-dist-restore/action.yml'
+ - '.github/actions/frontend-dist-save/action.yml'
- 'pyproject.toml'
- 'tests/studio_setup_ps1/**'
# The PowerShell unit tests this workflow runs live here. Without this a
@@ -191,6 +193,18 @@ jobs:
# 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.
+ - name: Restore the built frontend
+ id: fe-dist
+ uses: ./.github/actions/frontend-dist-restore
+
- name: Install Unsloth (--local, --no-torch)
id: install
timeout-minutes: 25
@@ -222,6 +236,15 @@ jobs:
ForEach-Object { '[{0,4:N0}s] {1}' -f $sw.Elapsed.TotalSeconds, $_ }
if ($LASTEXITCODE -ne 0) { throw "install.ps1 exited with code $LASTEXITCODE" }
+ # Paired with the restore above: 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.
+ - 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 }}
+
- name: Assert install.ps1 used the Windows llama.cpp prebuilt
id: assert-prebuilt
if: ${{ !cancelled() && steps.install.outcome == 'success' }}
diff --git a/.github/workflows/studio-windows-ui-smoke.yml b/.github/workflows/studio-windows-ui-smoke.yml
index c525d758347..7e691cfb333 100644
--- a/.github/workflows/studio-windows-ui-smoke.yml
+++ b/.github/workflows/studio-windows-ui-smoke.yml
@@ -17,6 +17,8 @@ on:
- 'unsloth/**'
- 'unsloth_cli/**'
- 'install.ps1'
+ - '.github/actions/frontend-dist-restore/action.yml'
+ - '.github/actions/frontend-dist-save/action.yml'
- 'pyproject.toml'
- 'tests/studio/**'
- '.github/scripts/run-studio-permission-browser.sh'
@@ -177,6 +179,17 @@ 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.
+ - name: Restore the built frontend
+ id: fe-dist
+ 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
@@ -215,6 +228,15 @@ jobs:
ForEach-Object { '[{0,4:N0}s] {1}' -f $sw.Elapsed.TotalSeconds, $_ }
if ($LASTEXITCODE -ne 0) { throw "install.ps1 exited with code $LASTEXITCODE" }
+ # Paired with the restore above: 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.
+ - 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 }}
+
- name: Assert install.ps1 used the Windows llama.cpp prebuilt
run: |
# The filesystem is the authority here: setup.ps1's "prebuilt
diff --git a/.github/workflows/studio-windows-update-smoke.yml b/.github/workflows/studio-windows-update-smoke.yml
index 59cb1499553..7cf3c2e96fd 100644
--- a/.github/workflows/studio-windows-update-smoke.yml
+++ b/.github/workflows/studio-windows-update-smoke.yml
@@ -23,6 +23,8 @@ on:
pull_request:
paths:
- 'install.ps1'
+ - '.github/actions/frontend-dist-restore/action.yml'
+ - '.github/actions/frontend-dist-save/action.yml'
- 'scripts/uninstall.ps1'
- 'tests/studio/test_uninstall_*.ps1'
- 'tests/studio/test_psmodulepath_normalization.ps1'
@@ -162,6 +164,17 @@ 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.
+ - name: Restore the built frontend
+ id: fe-dist
+ uses: ./.github/actions/frontend-dist-restore
+
- name: Install Unsloth (--local, --no-torch)
shell: pwsh
env:
@@ -191,6 +204,15 @@ jobs:
ForEach-Object { '[{0,4:N0}s] {1}' -f $sw.Elapsed.TotalSeconds, $_ }
if ($LASTEXITCODE -ne 0) { throw "install.ps1 exited with code $LASTEXITCODE" }
+ # Paired with the restore above: 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.
+ - 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 }}
+
- name: Assert install.ps1 used the Windows llama.cpp prebuilt
run: |
# Filesystem-based check: it does not depend on which process
diff --git a/tests/studio/test_frontend_dist_cache.py b/tests/studio/test_frontend_dist_cache.py
index 3090e1b6c9c..a0a3d66352d 100644
--- a/tests/studio/test_frontend_dist_cache.py
+++ b/tests/studio/test_frontend_dist_cache.py
@@ -1,36 +1,52 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-"""The frontend dist cache and setup.sh's rebuild check must read the same inputs.
+"""The frontend dist cache and BOTH installers' rebuild checks must read the same inputs.
Measured over 13 distinct Linux jobs on main, the frontend build is a median 36s of a
-74s `install-unsloth-local`, 49% of it, and 468s per commit producing byte-identical
-output. The cache exists to stop paying that 13 times.
+74s install, 49% of it. On Windows it is 96s of a ~257s install (`[72s] building
+frontend...` -> `[168s] frontend built`), 37% of it, across five more jobs. The cache
+exists to stop paying that eighteen times per commit.
-What makes it safe is not the cache action, it is the agreement between two places:
+What makes it safe is not the cache action, it is the agreement between three places:
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 action's cache key 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. Break the agreement and nothing goes red: the cache
keeps hitting and quietly starts serving a dist built from inputs the key no longer
covers, and every job downstream tests a stale bundle that passes. That is the whole
-reason this file exists, and it is why it asserts against setup.sh's own source rather
-than a list written down here.
+reason this file exists, and it is why it asserts against setup.sh's AND setup.ps1's own
+source rather than a list written down here. A list written here would agree with itself
+forever while the scripts moved.
-Three subtler failure modes are pinned too, each of which looks like success:
+Since the Windows jobs were added the key lives in ONE place,
+`.github/actions/frontend-dist-restore`, and `install-unsloth-local` delegates to it.
+Twelve workflows with their own copy of a key whose drift is silent would drift twelve
+ways.
+
+Five subtler failure modes are pinned too, each of which looks like success:
* `restore-keys` on this cache. A near-miss download cache still supplies most of the
wheels; a near-miss dist is a bundle built from different source. Wrong, not partial.
- * A restore with no `touch`. actions/cache restores through tar, which preserves the
+ * A restore with no touch. actions/cache restores through tar, which preserves the
original mtimes, so the restored dist is older than the checkout that just wrote
- every source file and setup.sh rebuilds anyway. The cache would cost a download,
- save nothing, and report a hit.
+ every source file and the installer rebuilds anyway. The cache would cost a
+ download, save nothing, and report a hit.
+ * A touch that does not update what the READER reads. setup.ps1 reads
+ `(Get-Item $DistDir).LastWriteTime`; whether MSYS `touch` on a directory handle
+ lands in that field is not something this repo has evidence for either way, so the
+ Windows branch writes that property by name and the POSIX branch keeps the `touch`
+ that is measured working on main.
* An empty `hashFiles`. It returns "" when a glob matches nothing, collapsing every
commit onto one key and serving an arbitrary dist.
+ * A hit that was rebuilt anyway. Invisible in every signal except the wall clock, so
+ the save action asserts it from the install log and fails the job.
"""
from __future__ import annotations
@@ -43,26 +59,49 @@ import yaml
REPO = Path(__file__).resolve().parents[2]
-ACTION = REPO / ".github" / "actions" / "install-unsloth-local" / "action.yml"
+ACTIONS = REPO / ".github" / "actions"
+RESTORE_ACTION = ACTIONS / "frontend-dist-restore" / "action.yml"
+SAVE_ACTION = ACTIONS / "frontend-dist-save" / "action.yml"
+INSTALL_ACTION = ACTIONS / "install-unsloth-local" / "action.yml"
+WORKFLOWS = REPO / ".github" / "workflows"
SETUP_SH = REPO / "studio" / "setup.sh"
+SETUP_PS1 = REPO / "studio" / "setup.ps1"
-def _steps() -> list[dict]:
- doc = yaml.safe_load(ACTION.read_text(encoding = "utf-8")) or {}
+def _steps(action: Path) -> list[dict]:
+ doc = yaml.safe_load(action.read_text(encoding = "utf-8")) or {}
return [s for s in (doc.get("runs") or {}).get("steps") or [] if isinstance(s, dict)]
-def _step(fragment: str) -> dict | None:
- for step in _steps():
+def _step(action: Path, fragment: str) -> dict | None:
+ for step in _steps(action):
if fragment.lower() in str(step.get("name", "")).lower():
return step
return None
+def _code(step: dict) -> str:
+ """A step's `run:` body with comment lines removed.
+
+ Every assertion in this file that greps a script body goes through here, and that is
+ not tidiness. These steps are heavily commented -- deliberately, since the reasoning
+ is the point -- and the comments quote the very strings the assertions look for:
+ "touch", "LastWriteTime", "building frontend", "exit 1". So an assertion run against
+ the raw body can be satisfied by the explanation of the code instead of the code,
+ and a guard that passes because of a comment is exactly the silence this design
+ exists to remove. Two mutations survived that way before this helper existed.
+
+ Line comments only. A `#` inside a string is left alone, which is why the split is
+ anchored to the start of a line rather than done anywhere in it.
+ """
+ body = str(step.get("run", ""))
+ return "\n".join(l for l in body.splitlines() if not l.lstrip().startswith("#"))
+
+
def _restore_step() -> dict:
- step = _step("Restore the built frontend")
+ step = _step(RESTORE_ACTION, "Restore the built frontend")
assert step is not None, (
- "install-unsloth-local no longer restores a built frontend. If the cache was "
+ "frontend-dist-restore no longer restores a built frontend. If the cache was "
"removed on purpose, delete this file; if it was renamed, retarget it."
)
return step
@@ -72,41 +111,66 @@ def _key() -> str:
return str((_restore_step().get("with") or {}).get("key", ""))
-def _raw_key_patterns() -> list[str]:
- inner = re.search(r"hashFiles\((.*?)\)", _key())
- assert inner, f"the dist cache key does not call hashFiles: {_key()!r}"
- return [g.strip().strip("'\"") for g in inner.group(1).split(",")]
-
-
-def _normalise(glob: str) -> str:
- return glob.removeprefix("!").removesuffix("/**").rstrip("/*").rstrip("/")
-
+def _balanced(text: str, open_at: int) -> str:
+ """The substring inside the parentheses that open at ``open_at``.
-def _key_globs() -> set[str]:
- """The paths hashFiles() reads, normalised so a trailing /** does not matter.
-
- Exclusions are split out rather than folded in: a `!` pattern REMOVES files from
- the hash, so counting it as a path the key "reads" inverts its meaning.
+ A non-greedy ``hashFiles\\((.*?)\\)`` stops at the first ``)``, which is the wrong
+ one the moment an argument is itself a call -- and the key's arguments are
+ ``format()`` calls now, because the globs carry a checkout prefix.
"""
- return {_normalise(g) for g in _raw_key_patterns() if not g.startswith("!")}
-
+ depth = 0
+ for i in range(open_at, len(text)):
+ if text[i] == "(":
+ depth += 1
+ elif text[i] == ")":
+ depth -= 1
+ if depth == 0:
+ return text[open_at + 1 : i]
+ raise AssertionError(f"unbalanced parentheses from offset {open_at} in {text!r}")
+
+
+def _key_patterns() -> tuple[set[str], set[str]]:
+ """(hashed, excluded) path groups, read out of the key itself.
+
+ Every argument is `format('{0}<glob>', inputs.path-prefix)`, so the glob is the
+ quoted literal with its `{0}` placeholder stripped. Read structurally rather than by
+ substring, so dropping a path group -- or prefixing one but not another -- shows up
+ as a missing entry rather than as a passing test.
+
+ Negations are separated out rather than treated as more hashed paths.
+ `studio/frontend/*` is RECURSIVE in @actions/glob (matchDirectories plus implicit
+ descendants), so it currently sweeps in `frontend/tests/**`, which the rebuild check
+ never reads; #9380 narrows the key with `!studio/frontend/tests/**` and
+ `!studio/frontend/scripts/**`. Splitting them here is what lets this guard describe
+ the truth whichever order that PR and this one land in, instead of pinning the
+ literal argument list and needing a follow-up edit either way.
+ """
+ at = _key().find("hashFiles(")
+ assert at != -1, f"the dist cache key does not call hashFiles: {_key()!r}"
+ inner = _balanced(_key(), at + len("hashFiles"))
+ hashed, excluded = set(), set()
+ for literal in re.findall(r"'([^']*)'", inner):
+ if "studio/" not in literal:
+ continue # the format spec's own placeholder, or a prefix argument
+ glob = literal.replace("{0}", "")
+ target = excluded if glob.startswith("!") else hashed
+ target.add(glob.lstrip("!").removesuffix("/**").rstrip("/*").rstrip("/"))
+ return hashed, excluded
-def _key_exclusions() -> set[str]:
- return {_normalise(g) for g in _raw_key_patterns() if g.startswith("!")}
+def _key_globs() -> set[str]:
+ return _key_patterns()[0]
-def _staleness_inputs() -> set[str]:
- """The paths setup.sh's rebuild check compares against frontend/dist.
- Read out of setup.sh rather than hardcoded: a list written here would agree with
- itself forever while setup.sh moved.
- """
+def _staleness_inputs_sh() -> set[str]:
+ """The paths setup.sh's rebuild check compares against frontend/dist."""
text = SETUP_SH.read_text(encoding = "utf-8")
block = re.search(
r"Detect whether frontend needs building(.*?)end packaged/Tauri guard", text, re.S
)
assert block, "could not find the frontend staleness check in studio/setup.sh"
body = block.group(1)
+ assert "-newer" in body, "the setup.sh block found is not the mtime staleness check"
found = set()
for m in re.finditer(r'"\$SCRIPT_DIR/(frontend[^"]*)"', body):
path = m.group(1)
@@ -116,146 +180,784 @@ def _staleness_inputs() -> set[str]:
return found
-def test_the_key_covers_every_path_the_rebuild_check_reads() -> None:
- missing = sorted(_staleness_inputs() - _key_globs())
+def _staleness_inputs_ps1() -> set[str]:
+ """The paths setup.ps1's rebuild check compares against frontend/dist.
+
+ Read out of setup.ps1 the same way the setup.sh reader works, and for the same
+ reason. The Windows block does not spell its paths out as string literals -- it
+ walks `@("src", "public")` under `$FrontendDir` recursively and then `$FrontendDir`
+ itself non-recursively -- so this reconstructs the three groups from that structure.
+ Adding a fourth directory to the foreach list, or dropping one, changes what comes
+ back here and the key stops covering the check.
+ """
+ text = SETUP_PS1.read_text(encoding = "utf-8")
+ block = re.search(
+ r'\$DistDir = Join-Path \$FrontendDir "dist"(.*?)# Provision Node when the frontend build',
+ text,
+ re.S,
+ )
+ assert block, "could not find the frontend staleness check in studio/setup.ps1"
+ body = block.group(1)
+ # The anchor that proves this is the mtime comparison and not some other block.
+ assert re.search(r"\(Get-Item \$DistDir\)\.LastWriteTime", body), (
+ "the setup.ps1 block found does not read (Get-Item $DistDir).LastWriteTime, so "
+ "it is not the staleness check this key is supposed to agree with"
+ )
+
+ found = set()
+ # The recursive subdirectory sweep: foreach ($subDir in @("src", "public")).
+ sub = re.search(r"foreach \(\$subDir in @\(([^)]*)\)\)", body)
+ assert sub, "setup.ps1's staleness check no longer sweeps a list of subdirectories"
+ for name in re.findall(r'"([^"]+)"', sub.group(1)):
+ found.add(f"studio/frontend/{name}")
+ # The non-recursive top-level file sweep over $FrontendDir itself.
+ assert re.search(
+ r"Get-ChildItem -Path \$FrontendDir -File", body
+ ), "setup.ps1's staleness check no longer scans the top-level frontend files"
+ found.add("studio/frontend")
+ return found
+
+
+ "reader",
+ [
+ pytest.param(_staleness_inputs_sh, id = "setup.sh"),
+ pytest.param(_staleness_inputs_ps1, id = "setup.ps1"),
+ ],
+)
+def test_the_key_covers_every_path_the_rebuild_check_reads(reader) -> None:
+ missing = sorted(reader() - _key_globs())
assert not missing, (
- f"studio/setup.sh decides to rebuild the frontend by looking at {missing}, and the "
- f"dist cache key does not hash them. A change to those files would not change the "
- f"key, so the cache would hit and serve a dist built from different source, and "
- f"nothing would go red. Key: {_key()!r}"
+ f"{reader.__name__} says the installer decides to rebuild the frontend by "
+ f"looking at {missing}, and the dist cache key does not hash them. A change to "
+ f"those files would not change the key, so the cache would hit and serve a dist "
+ f"built from different source, and nothing would go red. Key: {_key()!r}"
+ )
+
+
+def test_the_two_installers_agree_on_what_makes_a_dist_stale() -> None:
+ """One key serves both, so the two checks reading different paths would be a bug.
+
+ Neither script alone can reveal that. setup.sh could gain a path group, the key
+ could gain it too, both Linux tests would pass, and Windows would keep hitting a key
+ that no longer describes what setup.ps1 reads.
+ """
+ assert _staleness_inputs_sh() == _staleness_inputs_ps1(), (
+ f"studio/setup.sh checks {sorted(_staleness_inputs_sh())} but studio/setup.ps1 "
+ f"checks {sorted(_staleness_inputs_ps1())}. They share one cache key, so the "
+ f"key can only be right for both if they read the same inputs. Fix the scripts, "
+ f"or split the key by runner.os and say why here."
)
def test_the_key_does_not_hash_paths_the_rebuild_check_ignores() -> None:
"""Not a style rule: an over-broad key silently destroys the hit rate.
- bun.lock is the deliberate exception. setup.sh must exclude it because the install
- regenerates it and it would self-trigger every run; the cache has no such problem,
- and a lockfile change means different dependencies and so a different bundle. It is
- covered by the `studio/frontend/*` glob, which is why that glob is allowed to be
- broader than the check's maxdepth-1 scan rather than being narrowed to match it.
-
- Note this compares glob PREFIXES, so it cannot see how far a glob descends. That
- blind spot is real and is covered by
- test_the_key_excludes_the_frontend_subdirs_the_rebuild_check_never_reads below --
- `studio/frontend/*` is recursive, which this check alone would never reveal.
+ bun.lock is the deliberate exception. Both scripts must exclude it because the
+ install regenerates it and it would self-trigger every run; the cache has no such
+ problem, and a lockfile change means different dependencies and so a different
+ bundle. It is covered by the `studio/frontend/*` glob, which is why that glob is
+ allowed to be broader than the checks' maxdepth-1 scan rather than being narrowed to
+ match it.
"""
- extra = sorted(_key_globs() - _staleness_inputs())
+ extra = sorted(_key_globs() - _staleness_inputs_sh() - _staleness_inputs_ps1())
assert extra == [], (
- f"the dist cache key hashes {extra}, which setup.sh's rebuild check does not "
- f"read. Every unrelated edit to those paths would miss the cache for no reason. "
+ f"the dist cache key hashes {extra}, which neither installer's rebuild check "
+ f"reads. Every unrelated edit to those paths would miss the cache for no reason. "
f"If the extra path genuinely affects the built bundle, say so where the key is "
f"defined and widen this test deliberately."
)
+def test_no_exclusion_hides_a_path_the_rebuild_check_reads() -> None:
+ """Narrowing the key is right; narrowing it past what the installers read is a bug.
+
+ `studio/frontend/*` is recursive in @actions/glob, so the key sweeps in directories
+ the rebuild check never looks at (`frontend/tests/**` alone is 456 files here), and
+ every unrelated edit to them misses the cache for nothing. #9380 fixes that with `!`
+ negations, which is a hit-rate improvement and safe.
+
+ One negation too many is not safe, and it fails in the opposite, silent direction: a
+ `!studio/frontend/src/**` would leave the key unchanged across a real source edit, so
+ the cache would hit and serve the previous bundle. This is the guard for that, and it
+ is why the exclusions are read out of the key separately rather than folded in with
+ the hashed paths.
+ """
+ hashed, excluded = _key_patterns()
+ reads = _staleness_inputs_sh() | _staleness_inputs_ps1()
+ offenders = sorted(e for e in excluded if any(r == e or r.startswith(e + "/") for r in reads))
+ assert not offenders, (
+ f"the dist cache key excludes {offenders}, which the installers' rebuild check "
+ f"DOES read. An edit there would not change the key, so the cache would hit and "
+ f"serve a bundle built from different source. Key: {_key()!r}"
+ )
+ for e in excluded:
+ assert any(e.startswith(h + "/") for h in hashed), (
+ f"the key excludes {e!r}, which none of its hashed globs {sorted(hashed)} "
+ f"would have matched anyway. A negation that subtracts nothing reads as a "
+ f"narrowing that is not in force."
+ )
+
+
def test_the_key_excludes_the_frontend_subdirs_the_rebuild_check_never_reads() -> None:
- """`studio/frontend/*` is RECURSIVE, which is the opposite of how it reads.
+ """The other direction, and the one that protects #9380 from being undone.
- @actions/glob runs with matchDirectories and implicitDescendants both true, so a bare
- `*` matches the subdirectory ENTRY and then expands it. Confirmed against the real
- library rather than inferred: `fe/*` yields `fe/tests/t.txt`, while `fe/*.txt` yields
- only `fe/top.txt`. GitHub's documented non-recursive example uses an extension, so it
- does not apply to a bare `*`.
+ Its sibling above forbids an exclusion that hides a path the rebuild check DOES read.
+ This forbids the reverse: dropping an exclusion, which puts the key back to hashing
+ every file under `frontend/tests` (456 of them) and `frontend/scripts`. Neither is
+ read by either installer's staleness check, so an edit to a frontend TEST would evict
+ a dist whose bundle is byte-identical.
- Left alone that hashed 457 files under frontend/tests and frontend/scripts, so any
- edit to a frontend TEST evicted a dist whose bundle is byte-identical. setup.sh reads
- neither directory.
+ That regression is invisible. The cache still works, still hits sometimes, and simply
+ hits less -- there is no failure to notice, only a number nobody is watching.
- Derived from the tree, not a written-down list, so a subdirectory added later shows up
- here as a decision to make rather than silently costing hit rate.
+ Derived from the tree rather than a written-down list, so a frontend subdirectory
+ added later surfaces here as a decision to make instead of quietly costing hit rate.
"""
frontend = REPO / "studio" / "frontend"
if not frontend.is_dir():
pytest.skip("studio/frontend is absent")
- read = {Path(p).name for p in _staleness_inputs() if Path(p).name != "frontend"}
- # dist is the cache payload; node_modules is never committed.
+ _, excluded = _key_patterns()
+ read = {Path(p).name for p in _staleness_inputs_sh() if Path(p).name != "frontend"}
+ # dist is the cache payload itself; node_modules is never committed.
ignored = {"dist", "node_modules"}
unread = {
d.name
for d in frontend.iterdir()
if d.is_dir() and d.name not in read and d.name not in ignored
}
- missing = sorted(d for d in unread if f"studio/frontend/{d}" not in _key_exclusions())
+ missing = sorted(d for d in unread if f"studio/frontend/{d}" not in excluded)
assert not missing, (
f"studio/frontend/{{{','.join(missing)}}} is hashed into the dist cache key but "
- f"setup.sh's rebuild check never reads it, so every edit under it evicts a dist "
- f"that would have been byte-identical. `studio/frontend/*` descends into "
+ f"neither installer's rebuild check reads it, so every edit under it evicts a "
+ f"dist that would have been byte-identical. `studio/frontend/*` descends into "
f"subdirectories. Either add `!studio/frontend/<dir>/**` to the key, or say at "
f"the key why that directory genuinely changes the built bundle."
)
-def test_no_exclusion_hides_a_path_the_rebuild_check_reads() -> None:
- """The dangerous direction, and the reason the exclusions are named individually.
-
- An exclusion that swallowed src/ or public/ would produce a key that ignores real
- build inputs: the cache would hit on a commit that changed the bundle and serve the
- previous one. That is wrong content rather than a wasted download, and every test
- downstream would still pass against a stale UI.
- """
- for excluded in _key_exclusions():
- for read in _staleness_inputs():
- assert not (read == excluded or read.startswith(excluded + "/")), (
- f"the key excludes {excluded!r}, which covers {read!r} -- a path setup.sh's "
- f"rebuild check DOES read. The cache would serve a stale bundle on a commit "
- f"that changed it."
- )
-
-
def test_the_dist_cache_has_no_restore_keys() -> None:
with_ = _restore_step().get("with") or {}
assert "restore-keys" not in with_, (
"the frontend dist cache has restore-keys. A prefix hit would serve a bundle "
"built from DIFFERENT source, which is wrong rather than partial. The uv "
- "download cache in the same action does want them, and that contrast is the "
- "point: a near-miss download still supplies most of the wheels."
+ "download cache in install-unsloth-local does want them, and that contrast is "
+ "the point: a near-miss download still supplies most of the wheels."
)
-def test_a_restored_dist_is_made_newer_than_the_checkout() -> None:
- step = _step("outrank its sources")
- assert step is not None, (
- "nothing touches the restored dist. actions/cache restores through tar, which "
- "preserves the original mtimes, so setup.sh's `find -newer dist` sees the whole "
- "freshly checked-out tree as newer and rebuilds anyway. The cache would report a "
- "hit, cost a download and save nothing."
+# ---------------------------------------------------------------------------
+# The touch, which is where a hit stops being a hit.
+# ---------------------------------------------------------------------------
+
+
+def _touch_steps() -> list[dict]:
+ return [s for s in _steps(RESTORE_ACTION) if "outrank its sources" in str(s.get("name", ""))]
+
+
+def test_a_restored_dist_is_made_newer_than_the_checkout_on_every_os() -> None:
+ """One branch per OS, and BOTH have to exist.
+
+ A single `shell: bash` + `touch` step would look complete and cover Windows by
+ accident at best: setup.ps1 reads `(Get-Item $DistDir).LastWriteTime`, and whether
+ MSYS `touch` on a directory handle updates that field is not something anyone here
+ has evidence for. The five Windows jobs would report a hit and rebuild anyway, which
+ costs a download and saves nothing while looking exactly like success.
+ """
+ steps = _touch_steps()
+ assert steps, (
+ "nothing makes the restored dist outrank its sources. actions/cache restores "
+ "through tar, which preserves the original mtimes, so the freshly checked-out "
+ "tree is newer than the restored dist and the installer rebuilds anyway."
)
- body = str(step.get("run", ""))
- assert re.search(r"^\s*touch studio/frontend/dist\s*$", body, re.M), (
- f"the step meant to make the restored dist outrank its sources does not touch "
- f"studio/frontend/dist: {body!r}"
+ covered = " ".join(str(s.get("if", "")) for s in steps)
+ assert "runner.os != 'Windows'" in covered and "runner.os == 'Windows'" in covered, (
+ f"the touch does not branch on runner.os, so one platform is unhandled: "
+ f"{[s.get('if') for s in steps]}"
+ )
+ for step in steps:
+ assert "steps.restore.outputs.cache-hit == 'true'" in str(step.get("if", "")), (
+ f"the touch in {step.get('name')!r} is not gated on a cache hit, so a MISS "
+ f"would touch a dist that was never restored and suppress the build that "
+ f"has to happen"
+ )
+
+
+def test_the_windows_touch_writes_the_property_setup_ps1_reads() -> None:
+ """`touch` and `LastWriteTime` are not interchangeable claims on NTFS.
+
+ setup.ps1 reads `(Get-Item $DistDir).LastWriteTime`. The Windows branch writes that
+ same property through the same API, so no inference is needed about MSYS's utime
+ path. If someone collapses the two branches back into one bash `touch`, this is the
+ test that says why not.
+ """
+ win = [s for s in _touch_steps() if "runner.os == 'Windows'" in str(s.get("if", ""))]
+ assert len(win) == 1, f"expected exactly one Windows touch branch, got {len(win)}"
+ step = win[0]
+ assert step.get("shell") == "pwsh", (
+ f"the Windows touch runs under {step.get('shell')!r}. It has to be pwsh: the "
+ f"point is to write the same property setup.ps1 reads, by name."
)
- assert str(step.get("if", "")).strip() == "steps.fe-dist.outputs.cache-hit == 'true'", (
- "the touch must be gated on a cache hit, or a miss would touch a dist that was "
- "never restored and suppress the build that has to happen"
+ body = _code(step)
+ assert re.search(r"\(Get-Item[^)]*\)\.LastWriteTime\s*=", body), (
+ f"the Windows touch does not assign (Get-Item ...).LastWriteTime, which is the "
+ f"exact field studio/setup.ps1:3526-3549 compares against: {body!r}"
)
-def test_a_degenerate_key_is_refused() -> None:
- step = _step("hashes nothing")
- assert step is not None, (
+def test_the_posix_touch_still_touches() -> None:
+ posix = [s for s in _touch_steps() if "runner.os != 'Windows'" in str(s.get("if", ""))]
+ assert len(posix) == 1, f"expected exactly one POSIX touch branch, got {len(posix)}"
+ step = posix[0]
+ assert step.get("shell") == "bash", step.get("shell")
+ assert re.search(
+ r"^\s*touch\s+\"?\$?\{?DIST", _code(step), re.M
+ ), f"the POSIX branch no longer touches the dist directory: {_code(step)!r}"
+
+
+# What each branch has to do AFTER stamping the directory, expressed as the two things
+# that distinguish "I called the API" from "the dist actually ended up newer": re-READ
+# the timestamp, and COMPARE it against the sources with a branch that can fail.
+_READBACK = {
+ # `find ... -newer "$DIST"` is setup.sh's own predicate, re-run.
+ "posix": (r'-newer\s+"\$DIST"', r'if\s+\[\s+-n\s+"\$newer"\s+\]'),
+ # A second Get-Item read (the first one is the assignment), then the comparison.
+ "Windows": (r"\$distTime\s*=\s*\(Get-Item[^)]*\)\.LastWriteTime", r"if\s*\(\$newer\)"),
+}
+
+
[email protected]("os_name", sorted(_READBACK))
+def test_each_touch_reads_its_work_back(os_name: str) -> None:
+ """Touching is not the claim that matters; the dist ENDING UP newer is.
+
+ A `touch` that returns 0 and a `find -newer dist` that comes back empty are
+ different statements, and only the second one stops the rebuild. Both branches
+ re-evaluate the installer's own predicate and fail loudly, because the alternative is
+ discovering it as 96s that nobody attributes to anything.
+
+ Asserted as the specific read-and-compare, not as "the body contains ::error:: and
+ exit 1 somewhere". It was written the loose way first, and neutering the entire
+ Windows comparison did not turn it red: the earlier "restored no directory" check
+ supplied both strings, and `bun.lock` survived in the Get-ChildItem filter. A guard
+ satisfied by a different guard standing next to it is not measuring anything.
+ """
+ marker = "runner.os == 'Windows'" if os_name == "Windows" else "runner.os != 'Windows'"
+ step = next(s for s in _touch_steps() if marker in str(s.get("if", "")))
+ body = _code(step)
+ read, compare = _READBACK[os_name]
+ assert re.search(read, body), (
+ f"the {os_name} touch branch never re-reads the timestamp it just wrote, so it "
+ f"proves only that the call returned: {body!r}"
+ )
+ at = re.search(compare, body)
+ assert at, (
+ f"the {os_name} touch branch does not compare the restored dist against its "
+ f"sources after stamping it: {body!r}"
+ )
+ tail = body[at.start() :]
+ assert "::error::" in tail and "exit 1" in tail, (
+ f"the {os_name} touch branch compares, then cannot fail on the result, so a "
+ f"stamp that did not take is silent: {tail!r}"
+ )
+ assert "bun.lock" in body, (
+ f"the {os_name} re-check does not exclude bun.lock, so it is not the predicate "
+ f"the installer is about to evaluate (the install regenerates that file, so it "
+ f"would self-trigger every run)"
+ )
+
+
+def test_a_degenerate_key_is_refused_before_the_restore_runs() -> None:
+ steps = _steps(RESTORE_ACTION)
+ guard = next(
+ (i for i, s in enumerate(steps) if "hashes nothing" in str(s.get("name", ""))), None
+ )
+ restore = next(
+ (i for i, s in enumerate(steps) if "cache/restore" in str(s.get("uses", ""))), None
+ )
+ assert guard is not None, (
'nothing refuses an empty hashFiles result. It returns "" when a glob matches '
"no file, which collapses every commit onto one key and serves an arbitrary "
"dist, with the restore succeeding and the build skipped."
)
- assert "exit 1" in str(step.get("run", "")), "the degenerate-key check does not fail the job"
+ assert "exit 1" in _code(steps[guard]), "the degenerate-key check does not fail the job"
+ assert restore is not None and guard < restore, (
+ "the degenerate-key check runs AFTER the restore, so an empty key is used to "
+ "look something up first -- and on a repo where anything ever saved under that "
+ "empty key, the lookup hits"
+ )
+
+
+def test_the_degenerate_key_check_runs_on_a_miss_too() -> None:
+ """Gating it on a hit would blind it to the case it is actually for.
+
+ An empty key is what a MOVED FRONTEND produces, and on the first run after such a
+ move there is nothing under the empty key yet, so the restore misses and a
+ hit-gated check says nothing. The build then runs, the save writes the freshly
+ built dist under the empty key, and from the next run onward every commit hits it.
+ The damage is done on the miss; the check has to be there for it.
+ """
+ step = _step(RESTORE_ACTION, "hashes nothing")
+ assert step is not None, "the degenerate-key check is gone"
+ cond = str(step.get("if", "")).strip()
+ assert not cond, (
+ f"the degenerate-key check is conditional ({cond!r}). It must run unconditionally: "
+ f"an empty key comes from a moved frontend layout, and on the first run after "
+ f"that move the restore MISSES -- so a hit-gated check is silent for exactly the "
+ f"run that goes on to poison the key."
+ )
+
+
+def test_no_windows_job_reaches_the_posix_install_composite() -> None:
+ """install-unsloth-local runs `bash install.sh`; Windows is installed by install.ps1.
+
+ Worth asserting rather than leaving to review, because the failure would not be a
+ clean "wrong installer" error. Git Bash exists on windows-latest, so `bash
+ install.sh --local --no-torch` starts, and the composite writes UV_CACHE_DIR into
+ $GITHUB_ENV for every later step on the way. The five Windows jobs call install.ps1
+ from their own `shell: pwsh` step and take the dist cache through
+ frontend-dist-restore/-save directly, which is why those two are OS-agnostic and
+ this one is not.
+ """
+ offenders = []
+ for name, jid, job in _jobs():
+ runs_on = str(job.get("runs-on", ""))
+ matrix = str(((job.get("strategy") or {}).get("matrix") or ""))
+ windows = "windows" in runs_on.lower() or "windows" in matrix.lower()
+ if not windows:
+ continue
+ for step in job.get("steps") or []:
+ if "install-unsloth-local" in str(step.get("uses", "")):
+ offenders.append(f"{name}:{jid} (runs-on: {runs_on})")
+ assert not offenders, (
+ f"these Windows jobs use install-unsloth-local, which runs `bash install.sh`: "
+ f"{offenders}. On Windows that is the wrong installer and it does not fail "
+ f"cleanly -- Git Bash is present, so it starts. Use install.ps1 with "
+ f"frontend-dist-restore/-save around it."
+ )
+
+
+# ---------------------------------------------------------------------------
+# The save half, and the assertion that a hit was actually reused.
+# ---------------------------------------------------------------------------
def test_the_dist_cache_is_saved_on_main_only() -> None:
- step = _step("Save the built frontend")
+ step = _step(SAVE_ACTION, "Save the built frontend")
assert step is not None, "the dist cache is restored but never saved, so it can only ever miss"
cond = str(step.get("if", ""))
- assert "refs/heads/main" in cond, (
+ assert re.search(r"github\.ref\s*==\s*'refs/heads/main'", cond), (
f"the dist cache is saved off main: {cond!r}. A PR-scoped entry can only be "
f"restored by re-runs of that same PR while still counting against the shared "
f"budget, evicting the copy every PR can read."
)
+ assert "always()" not in cond, (
+ "the dist save runs under always(), so an install that failed part-way through "
+ "the frontend build would store a partial dist under an immutable key and serve "
+ "it to every later run. Leaving always() off means a failed install simply "
+ "skips this step."
+ )
+
+
+def test_a_cache_hit_that_rebuilt_anyway_fails_the_job() -> None:
+ """The one failure mode of this cache that no other signal reveals.
+
+ Green job, `Cache hit for: fe-dist-...` in the log, a healthy hit rate on the cache
+ dashboard, and 96s still spent. Without this assertion the only way to notice is for
+ someone to time the install by hand, which is how the cost was found the first time.
+ """
+ step = _step(SAVE_ACTION, "reused and not rebuilt")
+ assert step is not None, (
+ "nothing checks that a restored dist was actually reused. A hit whose touch did "
+ "not take rebuilds the frontend and reports success."
+ )
+ assert str(step.get("if", "")).strip() == "inputs.cache-hit == 'true'", (
+ f"the reuse assertion is not gated on a hit: {step.get('if')!r}. On a MISS the "
+ f"installer is supposed to build, so asserting there would fail every cold run."
+ )
+ body = _code(step)
+ assert (
+ "building frontend" in body
+ ), "the reuse assertion does not look for the rebuild marker both installers emit"
+ # Each guarded condition, and the failure that must follow it. Counting `exit 1`s
+ # instead let a mutation through: turning the missing-log branch into a warning plus
+ # `exit 0` left the total unchanged, because the `exit 1` beneath it stayed.
+ for condition, what in (
+ (r'\[\s+!\s+-f\s+"\$INSTALL_LOG"\s+\]', "a missing install log"),
+ (r'\[\s+!\s+-d\s+"\$DIST"\s+\]', "a dist that vanished during the install"),
+ (r"grep\s+-qi\s+'building frontend'", "the rebuild marker"),
+ ):
+ at = re.search(condition, body)
+ assert at, f"the reuse assertion no longer checks for {what}: {body!r}"
+ block = body[at.start() : at.start() + 600]
+ assert "exit 1" in block.split("\nfi")[0], (
+ f"the reuse assertion detects {what} and does not fail the job for it. "
+ f"'Found nothing to read' must not read the same as 'passed': {block!r}"
+ )
+ assert "exit 0" not in body, (
+ f"the reuse assertion contains an `exit 0`, which is how this check gets "
+ f"disarmed while still looking present -- a branch that returns success is "
+ f"indistinguishable from one that verified something: {body!r}"
+ )
+
+
+ "script,marker",
+ [
+ (SETUP_SH, "building frontend"),
+ (SETUP_PS1, "building frontend"),
+ (SETUP_SH, "up to date"),
+ (SETUP_PS1, "up to date"),
+ ],
+)
+def test_the_markers_the_reuse_assertion_greps_for_still_exist(script: Path, marker: str) -> None:
+ """The assertion above is a grep, and a grep for a string nobody prints is vacuous.
+
+ Renaming either marker in an installer would disarm the reuse check without anything
+ going red -- the exact shape of silence this whole file is about. Pinned here so the
+ rename fails in pytest, one file away from the edit, rather than in CI six weeks
+ later as unexplained minutes.
+ """
+ assert marker in script.read_text(encoding = "utf-8"), (
+ f"{script.name} no longer prints {marker!r}, so the reuse assertion in "
+ f"frontend-dist-save greps for a string that never appears. Update both "
+ f"together."
+ )
+
+
+# ---------------------------------------------------------------------------
+# One definition of the key, and where it may be referenced from.
+# ---------------------------------------------------------------------------
+
+
+def test_the_cache_key_has_exactly_one_definition() -> None:
+ """Nine call sites with their own copy would drift, and the drift is silent.
+
+ That is the entire argument for the composite pair over pasting four steps into
+ five workflows: the key and the two installers' staleness checks have to agree, and
+ an agreement maintained in nine places is not maintained.
+ """
+ definers = []
+ for path in sorted(list(ACTIONS.rglob("action.yml")) + list(WORKFLOWS.glob("*.yml"))):
+ if re.search(r"key:\s*fe-dist-", path.read_text(encoding = "utf-8")):
+ definers.append(str(path.relative_to(REPO)))
+ assert definers == [".github/actions/frontend-dist-restore/action.yml"], (
+ f"the fe-dist cache key is defined in {definers}. It must have exactly one "
+ f"definition: a second copy agrees today and drifts silently, with the cache "
+ f"still hitting while it serves a dist built from inputs the key no longer "
+ f"covers."
+ )
+
+
+def test_install_unsloth_local_delegates_rather_than_carrying_its_own_copy() -> None:
+ uses = [str(s.get("uses", "")) for s in _steps(INSTALL_ACTION)]
+ assert "./.github/actions/frontend-dist-restore" in uses, uses
+ assert "./.github/actions/frontend-dist-save" in uses, uses
+ assert not any("actions/cache" in u and "fe" in u for u in uses)
+
+
+def _jobs():
+ for f in sorted(WORKFLOWS.glob("*.yml")):
+ doc = yaml.safe_load(f.read_text(encoding = "utf-8"))
+ if isinstance(doc, dict) and isinstance(doc.get("jobs"), dict):
+ for jid, job in doc["jobs"].items():
+ if isinstance(job, dict):
+ yield f.name, jid, job
+
+
+def test_no_nested_checkout_job_calls_an_action_that_nests_another_one() -> None:
+ """`uses: ./X` resolves as $GITHUB_WORKSPACE/X, in a composite too, and takes no expressions.
+
+ So a job that checks this repo out under `unsloth/` can call
+ `./unsloth/.github/actions/install-unsloth-local` and the runner will find it -- and
+ then fail inside it, on `uses: ./.github/actions/frontend-dist-restore`, with "Can't
+ find 'action.yml'". Three jobs here do check out that way (notebooks-ci
+ api-introspect, version-compat-ci zoo-imports-under-spoof and grpo-fake-run); none
+ calls this action today, and this keeps it that way with a reason attached instead of
+ that error message.
+
+ A nested-checkout job that wants the dist cache calls frontend-dist-restore and
+ frontend-dist-save directly and passes their `path-prefix`. Those two nest nothing.
+ """
+ nesting = {
+ p.parent.name
+ for p in ACTIONS.rglob("action.yml")
+ if re.search(r"uses:\s*\./\.github/actions/", p.read_text(encoding = "utf-8"))
+ }
+ assert nesting, "no composite action nests another any more; retarget or delete this test"
+ offenders = []
+ for name, jid, job in _jobs():
+ steps = job.get("steps") or []
+ if not any(
+ "actions/checkout" in str(s.get("uses", "")) and (s.get("with") or {}).get("path")
+ for s in steps
+ ):
+ continue
+ for step in steps:
+ uses = str(step.get("uses", ""))
+ if any(uses.endswith(f"/.github/actions/{n}") for n in sorted(nesting)):
+ offenders.append(f"{name}:{jid}: {uses}")
+ assert not offenders, (
+ f"these jobs check this repo out into a subdirectory and call an action that "
+ f"itself references a local action by workspace-relative path, which the runner "
+ f"resolves from GITHUB_WORKSPACE and cannot be prefixed (uses: takes no "
+ f"expressions): {offenders}. Call frontend-dist-restore/-save directly with "
+ f"path-prefix instead."
+ )
+
+
+def test_a_nested_checkout_caller_must_pass_a_prefix_that_can_match() -> None:
+ """The prefix is a string glued in front of a glob, so a missing slash matches nothing.
+
+ hashFiles returns "" for that rather than failing, and an empty key collapses every
+ commit onto one entry. The action refuses an empty hash at runtime; this catches the
+ same mistake in pytest, and catches the opposite one -- a nested checkout that
+ forgets the prefix entirely -- which the action cannot distinguish from a moved
+ frontend.
+ """
+ offenders = []
+ for name, jid, job in _jobs():
+ steps = job.get("steps") or []
+ checkout_dirs = [
+ str((s.get("with") or {}).get("path")).strip("/")
+ for s in steps
+ if "actions/checkout" in str(s.get("uses", ""))
+ and (s.get("with") or {}).get("path")
+ and not str((s.get("with") or {}).get("repository") or "")
+ .rstrip("/")
+ .endswith(("/unsloth",))
+ or (
+ "actions/checkout" in str(s.get("uses", ""))
+ and (s.get("with") or {}).get("path")
+ and not (s.get("with") or {}).get("repository")
+ )
+ ]
+ for step in steps:
+ if "frontend-dist-" not in str(step.get("uses", "")):
+ continue
+ prefix = str((step.get("with") or {}).get("path-prefix", ""))
+ if prefix and not prefix.endswith("/"):
+ offenders.append(f"{name}:{jid}: path-prefix {prefix!r} has no trailing slash")
+ expected = f"{checkout_dirs[0]}/" if checkout_dirs else ""
+ if prefix != expected:
+ offenders.append(
+ f"{name}:{jid}: path-prefix is {prefix!r} but the repo is checked "
+ f"out at {expected!r}"
+ )
+ assert not offenders, (
+ "these frontend-dist call sites pass a prefix that cannot resolve, so hashFiles "
+ "matches nothing and the key is degenerate:\n " + "\n ".join(offenders)
+ )
+
+
+def _produces_on_main(name: str) -> bool:
+ """Whether ``name``'s triggers can routinely put github.ref on refs/heads/main.
+
+ The save is gated on `refs/heads/main`, so this is what decides whether a save step
+ in that workflow can ever fire. `pull_request` gives `refs/pull/N/merge`; `push` to
+ main and `schedule` (which runs on the default branch) both give the real thing.
+
+ `workflow_dispatch` is deliberately NOT counted. It can be dispatched from main, so a
+ save would technically fire -- but only when a human remembers to press the button,
+ and a cache that fills on that schedule is not a cache. Counting it would make the
+ rule below vacuous, since almost every workflow here has one.
+ """
+ doc = yaml.safe_load((WORKFLOWS / name).read_text(encoding = "utf-8"))
+ on = doc.get("on", doc.get(True)) or {}
+ if isinstance(on, str):
+ on = {on: None}
+ elif isinstance(on, list):
+ on = dict.fromkeys(on)
+ if "schedule" in on:
+ return True
+ push = on.get("push")
+ if push is None and "push" not in on:
+ return False
+ branches = (push or {}).get("branches") if isinstance(push, dict) else None
+ return branches is None or "main" in branches
+
+
+def test_every_restored_dist_is_also_saved_and_wired_to_its_restore() -> None:
+ """A restore with no save fills nothing; a save reading the wrong id saves nothing.
+
+ Both halves are silent when wrong: the save takes the key and the hit flag from the
+ restore's outputs, so a renamed or missing id yields empty inputs and an entry that
+ is never written, with a green job either way.
+
+ The pair is always required. Whether its UPLOAD half is enabled is derived from the
+ workflow's triggers rather than allowlisted, so the one consumer-only lane
+ (startup-profile-ci, which has no `push` and no `schedule`) passes `save: 'false'`
+ and still runs the reuse assertion -- and adding `push:` there without enabling the
+ save, or enabling the save without the trigger, both go red.
+ """
+ offenders = []
+ for name, jid, job in _jobs():
+ steps = job.get("steps") or []
+ restore = next(
+ (s for s in steps if "frontend-dist-restore" in str(s.get("uses", ""))), None
+ )
+ save = next((s for s in steps if "frontend-dist-save" in str(s.get("uses", ""))), None)
+ if restore is None and save is None:
+ continue
+ if restore is None or save is None:
+ offenders.append(f"{name}:{jid}: restore={restore is not None} save={save is not None}")
+ continue
+ ident = restore.get("id")
+ if not ident:
+ offenders.append(f"{name}:{jid}: the restore step has no id")
+ continue
+ with_ = save.get("with") or {}
+ for field in ("cache-hit", "key"):
+ if f"steps.{ident}.outputs.{field}" not in str(with_.get(field, "")):
+ offenders.append(f"{name}:{jid}: save does not take {field} from steps.{ident}")
+ if steps.index(restore) > steps.index(save):
+ offenders.append(f"{name}:{jid}: the save runs before the restore")
+
+ uploads = str(with_.get("save", "true")) != "false"
+ if uploads and not _produces_on_main(name):
+ offenders.append(
+ f"{name}:{jid}: saves the dist cache, but {name} has no `push` to main "
+ f"and no `schedule`, so github.ref is never refs/heads/main and the "
+ f"upload can only fire on a hand-dispatched run. Pass save: 'false'."
+ )
+ if not uploads and _produces_on_main(name):
+ offenders.append(
+ f"{name}:{jid}: passes save: 'false', but {name} DOES run on main, so "
+ f"it is a producer and is declining to fill the cache every PR reads."
+ )
+ assert not offenders, "\n ".join(["broken frontend-dist wiring:"] + offenders)
+
+
+def test_at_least_one_producer_actually_fills_the_cache() -> None:
+ """A cache every lane consumes and none populates hits exactly never.
+
+ The rule above is a per-job consistency check and would be perfectly happy with
+ `save: 'false'` everywhere, as long as no workflow ran on main. This is the check
+ that the set is non-empty.
+ """
+ producers = {
+ name
+ for name, jid, job in _jobs()
+ for s in job.get("steps") or []
+ if "frontend-dist-save" in str(s.get("uses", ""))
+ and str((s.get("with") or {}).get("save", "true")) != "false"
+ }
+ assert producers, "no job saves the frontend dist cache, so every restore can only ever miss"
+
+
+def test_the_restore_comes_before_the_install_and_the_save_after_it() -> None:
+ """Either one on the wrong side is inert and still looks right.
+
+ A restore after the install restores a dist nothing will read; a save before it
+ stores whatever the previous run left behind.
+ """
+ offenders = []
+ for name, jid, job in _jobs():
+ steps = job.get("steps") or []
+ idx = {
+ role: i
+ for i, s in enumerate(steps)
+ for role in ("restore", "save")
+ if f"frontend-dist-{role}" in str(s.get("uses", ""))
+ }
+ if "restore" not in idx:
+ continue
+ # The step that INVOKES the installer, not every step that mentions it. These
+ # workflows also parse install.ps1 with the AST and grep logs/install.log, and a
+ # bare `install\.(ps1|sh)` match picks those up and reports a false ordering
+ # bug. Every call site passes --local (it is what overlays the checkout, so it
+ # is also what makes the workspace dist the one being built).
+ installs = [
+ i
+ for i, s in enumerate(steps)
+ if re.search(r"install\.(ps1|sh) --local", str(s.get("run", "")))
+ ]
+ if not installs:
+ offenders.append(f"{name}:{jid}: restores a dist but never runs an installer")
+ continue
+ if idx["restore"] > min(installs):
+ offenders.append(f"{name}:{jid}: the restore runs after the install")
+ if "save" in idx and idx["save"] < max(installs):
+ offenders.append(f"{name}:{jid}: the save runs before the install")
+ assert not offenders, "\n ".join(["misordered frontend-dist steps:"] + offenders)
+
+
+# ---------------------------------------------------------------------------
+# Cold lanes.
+# ---------------------------------------------------------------------------
+
+# Named, not detected: a lane whose whole point is a cold machine should have to be
+# removed from this list deliberately, in a diff someone reads.
+COLD_INSTALL_WORKFLOWS = (
+ "clean-machine-install-ci.yml",
+ "desktop-app-clean-machine-ci.yml",
+ "interrupted-install-ci.yml",
+ "release-desktop.yml",
+)
+
+# Cold at JOB level, inside a workflow whose other jobs legitimately use the cache.
+# `no-vs-cpu` installs with no Visual Studio build tools present, on purpose.
+COLD_INSTALL_JOBS = (("studio-windows-inference-smoke.yml", "no-vs-cpu"),)
+
+
[email protected]("name", COLD_INSTALL_WORKFLOWS)
+def test_cold_install_lanes_never_adopt_this_action(name: str) -> None:
+ """A prebuilt frontend on a lane named for a cold machine proves nothing, and passes.
+
+ These exist to show the installer works where nothing is present. Handing one a
+ frontend that was built on another machine last week removes 96s of the thing they
+ are testing, and the lane still reports success.
+ """
+ path = WORKFLOWS / name
+ if not path.exists():
+ pytest.skip(f"{name} no longer exists")
+ text = path.read_text(encoding = "utf-8")
+ assert "frontend-dist-" not in text, (
+ f"{name} uses the frontend dist cache. A cold-install lane served a prebuilt "
+ f"frontend proves nothing and still goes green."
+ )
+ assert "install-unsloth-local" not in text, (
+ f"{name} uses install-unsloth-local, which now restores a prebuilt frontend as "
+ f"well as warming uv's cache."
+ )
+
+
[email protected]("name,jid", COLD_INSTALL_JOBS)
+def test_cold_install_jobs_never_adopt_this_action(name: str, jid: str) -> None:
+ """Workflow-level exclusion is not enough when the cold lane is one job of several.
+
+ studio-windows-inference-smoke.yml's `inference-smoke` is a target and its
+ `no-vs-cpu` is not, in the same file, so a check that reads whole files would either
+ forbid both or permit both.
+ """
+ doc = yaml.safe_load((WORKFLOWS / name).read_text(encoding = "utf-8"))
+ job = (doc.get("jobs") or {}).get(jid)
+ assert job is not None, f"{name} no longer has job {jid}; update COLD_INSTALL_JOBS"
+ offenders = [
+ str(s.get("uses", ""))
+ for s in job.get("steps") or []
+ if "frontend-dist-" in str(s.get("uses", ""))
+ or "install-unsloth-local" in str(s.get("uses", ""))
+ ]
+ assert not offenders, (
+ f"{name}:{jid} is a deliberate cold-install lane and must not be served a "
+ f"prebuilt frontend: {offenders}"
+ )
+
+
+def test_the_actions_are_actually_used() -> None:
+ """Otherwise every assertion above guards something nothing runs."""
+ users = [
+ p.name
+ for p in WORKFLOWS.glob("*.yml")
+ if "frontend-dist-restore" in p.read_text(encoding = "utf-8")
+ ]
+ assert len(users) >= 5, f"only {len(users)} workflows restore a dist: {users}"
def test_the_guard_is_reading_real_files() -> None:
- """Every assertion above passes vacuously if these two files stop being found."""
- assert ACTION.is_file(), ACTION
- assert SETUP_SH.is_file(), SETUP_SH
- assert len(_staleness_inputs()) >= 2, _staleness_inputs()
- assert len(_key_globs()) >= 2, _key_globs()
+ """Every assertion above passes vacuously if these files stop being found."""
+ for path in (RESTORE_ACTION, SAVE_ACTION, INSTALL_ACTION, SETUP_SH, SETUP_PS1):
+ assert path.is_file(), path
+ assert len(_staleness_inputs_sh()) >= 3, _staleness_inputs_sh()
+ assert len(_staleness_inputs_ps1()) >= 3, _staleness_inputs_ps1()
+ assert len(_key_globs()) >= 3, _key_globs()
diff --git a/tests/studio/test_uv_cache_discipline.py b/tests/studio/test_uv_cache_discipline.py
index 27287d75a70..2cd0b581c1a 100644
--- a/tests/studio/test_uv_cache_discipline.py
+++ b/tests/studio/test_uv_cache_discipline.py
@@ -26,6 +26,7 @@ workflows are named after, and they would still go green.
from __future__ import annotations
+import re
from pathlib import Path
import pytest
@@ -41,11 +42,42 @@ COLD_INSTALL_WORKFLOWS = (
"clean-machine-install-ci.yml",
"desktop-app-clean-machine-ci.yml",
"interrupted-install-ci.yml",
+ # Publishes the desktop app from a clean checkout; a restored dist would ship a
+ # bundle this run never built.
+ "release-desktop.yml",
)
+def _own_steps(action: Path = ACTION) -> list[dict]:
+ return yaml.safe_load(action.read_text(encoding = "utf-8"))["runs"]["steps"]
+
+
def _steps() -> list[dict]:
- return yaml.safe_load(ACTION.read_text(encoding = "utf-8"))["runs"]["steps"]
+ """This action's steps, with the steps of every local action it delegates to inlined.
+
+ The frontend dist cache moved into `.github/actions/frontend-dist-restore` and
+ `-save` when the Windows jobs adopted it, because they do not go through this action
+ and the key must have exactly one definition. A reader that only walked this file's
+ own steps would have gone blind to that cache the moment it was factored out -- and
+ silently, since `uses: ./.github/actions/frontend-dist-restore` does not contain the
+ substring `actions/cache` that the path check below looks for. Every assertion in
+ this file would have kept passing while guarding one cache instead of two.
+
+ That is the same failure mode test_cache_budget_discipline.py's `_composite_actions`
+ was written for, one level in: a rule quietly stops applying to the thing it was
+ written for.
+ """
+ flat: list[dict] = []
+ for step in _own_steps():
+ uses = str(step.get("uses", ""))
+ local = re.match(r"\./\.github/actions/([\w-]+)$", uses)
+ if local:
+ nested = REPO_ROOT / ".github" / "actions" / local.group(1) / "action.yml"
+ assert nested.is_file(), f"{uses} does not exist, so this action cannot run"
+ flat.extend(_own_steps(nested))
+ else:
+ flat.append(step)
+ return flat
def _index_of(predicate) -> int:
@@ -154,10 +186,19 @@ def test_cold_install_lanes_never_adopt_this_action(name: str) -> None:
path = WORKFLOWS / name
if not path.exists():
pytest.skip(f"{name} no longer exists")
- assert "install-unsloth-local" not in path.read_text(encoding = "utf-8"), (
+ text = path.read_text(encoding = "utf-8")
+ assert "install-unsloth-local" not in text, (
f"{name} uses install-unsloth-local, which warms uv's cache. A cached "
f"cold-install test proves nothing and still goes green."
)
+ # Named separately because the frontend dist cache can now be adopted WITHOUT this
+ # action -- that is the whole point of splitting it out for the Windows jobs, which
+ # call install.ps1 from a hand-written step. Checking only for install-unsloth-local
+ # would let a cold lane paste in the two `uses:` lines and stay green.
+ assert "frontend-dist-" not in text, (
+ f"{name} restores a prebuilt frontend. A cold-install lane handed a bundle built "
+ f"on another machine last week is not testing a cold install."
+ )
def test_the_action_is_actually_used() -> None: