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 13 jobs rebuilding the same frontend on every commit (#9375)

Daniel Hana2cb0410b909
diff --git a/.github/actions/install-unsloth-local/action.yml b/.github/actions/install-unsloth-local/action.yml
index 6938ee91db5..a5d5fd30f87 100644
--- a/.github/actions/install-unsloth-local/action.yml
+++ b/.github/actions/install-unsloth-local/action.yml
@@ -93,6 +93,77 @@ runs:
restore-keys: |
uv-${{ runner.os }}-
+ # The frontend build is the other half of this step, and unlike the wheels it is
+ # not a download at all. Measured over 13 distinct Linux jobs on main, using the
+ # elapsed-second prefix below: a median 36s of a 74s install, 49% of it, and
+ # 468s per commit spent producing byte-identical output. The uv cache above
+ # already hits exactly (`Cache hit for: uv-Linux-<hash>`, one 31 kB straggler),
+ # so what is left is compute, and the only way to stop paying it 13 times is to
+ # not do it 13 times.
+ #
+ # 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.
+ #
+ # 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.
+ #
+ # 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.
+ - 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
+ # 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/**') }}
+
+ - 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/**') }}
+ 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
+
- name: Install Unsloth (--local, --no-torch)
shell: bash
env:
@@ -137,6 +208,17 @@ runs:
# 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
# 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
+ with:
+ path: studio/frontend/dist
+ key: ${{ steps.fe-dist.outputs.cache-primary-key }}
+
- name: Save the uv download cache
if: always() && github.ref == 'refs/heads/main' && steps.uv-cache.outputs.cache-hit != 'true'
shell: bash
diff --git a/.github/workflows/workflow-trigger-lint.yml b/.github/workflows/workflow-trigger-lint.yml
index 05fe4e3e023..2cdc3990edd 100644
--- a/.github/workflows/workflow-trigger-lint.yml
+++ b/.github/workflows/workflow-trigger-lint.yml
@@ -141,6 +141,7 @@ jobs:
tests/studio/test_compile_caches_are_per_worker.py \
tests/studio/test_composer_rtl_bidi_attribute.py \
tests/studio/test_frontend_dep_removal.py \
+ tests/studio/test_frontend_dist_cache.py \
tests/studio/test_gguf_smoke_phases_stay_independent.py \
tests/studio/test_indicator_browsers_run_in_parallel.py \
tests/studio/test_inference_smoke_http_diagnostics.py \
diff --git a/tests/studio/test_frontend_dist_cache.py b/tests/studio/test_frontend_dist_cache.py
new file mode 100644
index 00000000000..a7a450e048f
--- /dev/null
+++ b/tests/studio/test_frontend_dist_cache.py
@@ -0,0 +1,188 @@
+# 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.
+
+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.
+
+What makes it safe is not the cache action, it is the agreement between two places:
+
+ studio/setup.sh rebuilds when anything under frontend/ (maxdepth 1, minus
+ bun.lock), frontend/src or frontend/public is NEWER than
+ frontend/dist
+ 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.
+
+Three 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
+ 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.
+ * An empty `hashFiles`. It returns "" when a glob matches nothing, collapsing every
+ commit onto one key and serving an arbitrary dist.
+"""
+
+from __future__ import annotations
+
+import re
+from pathlib import Path
+
+import yaml
+
+
+REPO = Path(__file__).resolve().parents[2]
+ACTION = REPO / ".github" / "actions" / "install-unsloth-local" / "action.yml"
+SETUP_SH = REPO / "studio" / "setup.sh"
+
+
+def _steps() -> 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():
+ if fragment.lower() in str(step.get("name", "")).lower():
+ return step
+ return None
+
+
+def _restore_step() -> dict:
+ step = _step("Restore the built frontend")
+ assert step is not None, (
+ "install-unsloth-local no longer restores a built frontend. If the cache was "
+ "removed on purpose, delete this file; if it was renamed, retarget it."
+ )
+ return step
+
+
+def _key() -> str:
+ return str((_restore_step().get("with") or {}).get("key", ""))
+
+
+def _key_globs() -> set[str]:
+ """The paths hashFiles() reads, normalised so a trailing /** does not matter."""
+ inner = re.search(r"hashFiles\((.*?)\)", _key())
+ assert inner, f"the dist cache key does not call hashFiles: {_key()!r}"
+ return {
+ g.strip().strip("'\"").removesuffix("/**").rstrip("/*").rstrip("/")
+ for g in inner.group(1).split(",")
+ }
+
+
+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.
+ """
+ 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)
+ found = set()
+ for m in re.finditer(r'"\$SCRIPT_DIR/(frontend[^"]*)"', body):
+ path = m.group(1)
+ if path.endswith("/dist"):
+ continue
+ found.add("studio/" + path)
+ return found
+
+
+def test_the_key_covers_every_path_the_rebuild_check_reads() -> None:
+ missing = sorted(_staleness_inputs() - _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}"
+ )
+
+
+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.
+ """
+ extra = sorted(_key_globs() - _staleness_inputs())
+ 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"If the extra path genuinely affects the built bundle, say so where the key is "
+ f"defined and widen this test deliberately."
+ )
+
+
+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."
+ )
+
+
+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."
+ )
+ 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}"
+ )
+ 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"
+ )
+
+
+def test_a_degenerate_key_is_refused() -> None:
+ step = _step("hashes nothing")
+ assert step 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"
+
+
+def test_the_dist_cache_is_saved_on_main_only() -> None:
+ step = _step("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, (
+ 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."
+ )
+
+
+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()
diff --git a/tests/studio/test_uv_cache_discipline.py b/tests/studio/test_uv_cache_discipline.py
index e2022914418..27287d75a70 100644
--- a/tests/studio/test_uv_cache_discipline.py
+++ b/tests/studio/test_uv_cache_discipline.py
@@ -55,17 +55,41 @@ def _index_of(predicate) -> int:
return -1
-def test_the_cache_holds_uvs_downloads_and_not_the_venv() -> None:
+# What this action is allowed to cache, and the argument for each. Anything else has
+# to be added here in a diff someone reads, with its own argument written down.
+#
+# .uv-cache uv's download cache. Content-addressed by URL and hash, so a
+# stale entry cannot serve wrong content; the worst it can do
+# is miss.
+# studio/frontend/dist the built frontend. NOT a download, so it does not get the
+# argument above and needs its own: it is a directory of static
+# assets with no absolute paths, no interpreter coupling and no
+# console scripts, which is exactly what makes a venv unsafe to
+# cache and this safe. Its key hashes the same inputs
+# studio/setup.sh checks before rebuilding, so a hit means the
+# build inputs are byte-identical rather than merely similar.
+# tests/studio/test_frontend_dist_cache.py holds that agreement
+# together and is where the reasoning lives.
+CACHEABLE_PATHS = (".uv-cache", "studio/frontend/dist")
+
+
+def test_the_cache_holds_downloads_and_build_output_but_never_the_venv() -> None:
"""
A venv cache would have to reason about the editable overlay, a moving
- unsloth-zoo pin, and absolute paths in console scripts. A download cache
- reasons about none of that, which is why this one is safe at all.
+ unsloth-zoo pin, and absolute paths in console scripts. Neither of the two
+ things this action caches reasons about any of that, which is why they are safe
+ at all. The forbidden list below is the invariant with teeth and applies to
+ every cache step regardless of which allowed path it uses.
"""
for step in _steps():
if "cache" not in str(step.get("uses", "")):
continue
path = str((step.get("with") or {}).get("path", ""))
- assert ".uv-cache" in path, f"cache step points at {path!r}, not uv's download cache"
+ assert any(allowed in path for allowed in CACHEABLE_PATHS), (
+ f"cache step points at {path!r}, which is not one of the paths this action "
+ f"is allowed to cache ({', '.join(CACHEABLE_PATHS)}). Add it to "
+ f"CACHEABLE_PATHS with the argument for why restoring it cannot be wrong."
+ )
for forbidden in (".unsloth", "site-packages", "unsloth_studio", "venv"):
assert forbidden not in path, (
f"cache step points at {path!r}, which is an INSTALL, not a download "