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.

Repair the six CI checks that are red on main itself (#11139)

Daniel Han73ab683ac0bd
diff --git a/.github/workflows/studio-composer-compatibility.yml b/.github/workflows/studio-composer-compatibility.yml
index e7dbe550a57..65b7b13ffd0 100644
--- a/.github/workflows/studio-composer-compatibility.yml
+++ b/.github/workflows/studio-composer-compatibility.yml
@@ -10,12 +10,21 @@ on:
- 'studio/frontend/src/features/chat/**'
- 'studio/frontend/src/features/settings/components/composer-settings.tsx'
- 'studio/frontend/src/index.css'
+ # playwright_queue_localization.py drives the queue surface in ja and asserts the
+ # shipped Japanese, so a translation-only edit is exactly the change that can break
+ # it, and this workflow is its only invocation. index.ts is in scope with the
+ # catalogs because the driver calls setLocale through it.
+ - 'studio/frontend/src/i18n/**'
- 'studio/frontend/smoke-*'
- 'studio/frontend/tests/**'
- 'studio/frontend/package*.json'
- 'studio/frontend/vite.config.ts'
- 'tests/studio/*composer*'
- 'tests/studio/*prompt_queue*'
+ # `*` does not cross a `/` and matches literally otherwise, so neither pattern above
+ # reaches playwright_queue_localization.py: it carries no "prompt_queue". Without this
+ # line a PR that changes only the driver never runs the driver.
+ - 'tests/studio/*queue_localization*'
- 'tests/studio/_playwright_robust.py'
- '.github/workflows/studio-composer-compatibility.yml'
- '.github/scripts/retry-with-apt-lock.sh'
@@ -128,6 +137,16 @@ jobs:
> "temp/queue-validation/compatibility/$browser-queue.log" 2>&1 || status=1
python tests/studio/playwright_composer_settings.py \
> "temp/queue-validation/compatibility/$browser-composer.log" 2>&1 || status=1
+ # Added by #11117 and left unrun until now, which
+ # tests/studio/test_playwright_suites_run_in_ci.py failed on. It belongs in this
+ # loop rather than a job of its own: it drives the same
+ # /smoke-prompt-queue-actions.html fixture as the queue suite above, and what it
+ # asserts -- IME composition, Escape-during-composition and the send-shortcut
+ # chord in the queued-prompt editor -- is exactly the per-engine behaviour this
+ # matrix exists for. Verified green on chromium 153, firefox 155 and webkit 26.6
+ # before being wired in, so this adds coverage and not a new red.
+ python tests/studio/playwright_queue_localization.py \
+ > "temp/queue-validation/compatibility/$browser-queue-localization.log" 2>&1 || status=1
done
exit "$status"
- name: Native Safari simulations
diff --git a/.github/workflows/studio-frontend-ci.yml b/.github/workflows/studio-frontend-ci.yml
index 6f4f93eb3cf..e0292a59855 100644
--- a/.github/workflows/studio-frontend-ci.yml
+++ b/.github/workflows/studio-frontend-ci.yml
@@ -576,7 +576,15 @@ jobs:
windows:
name: Frontend unit tests (Windows)
runs-on: windows-latest
- timeout-minutes: 15
+ # 30, not 15. The cap stopped fitting the job's own steps once the browser smokes
+ # joined it, and the overrun is deterministic rather than flaky: measured on run
+ # 35166979977, setup and npm ci 1m10s, unit tests 4m12s, browser install 32s,
+ # composer icons 39s, data settings in Chromium 4m21s, and then Firefox was cut off
+ # at 4m13s having needed about the same as Chromium. That is roughly 15m30s of work
+ # under a 15m cap, so every run that reaches the Firefox step dies there and reports
+ # itself as "cancelled" -- the failure mode the comment at the alignment job below
+ # already describes. The Linux sibling of this job allows 40.
+ timeout-minutes: 30
defaults:
run:
shell: bash
diff --git a/studio/backend/tests/test_account_tool_confinement.py b/studio/backend/tests/test_account_tool_confinement.py
index fc6314805b8..8beb9e7b4f0 100644
--- a/studio/backend/tests/test_account_tool_confinement.py
+++ b/studio/backend/tests/test_account_tool_confinement.py
@@ -375,14 +375,32 @@ def test_install_under_a_granted_root_stays_hidden(tmp_path, monkeypatch):
auth = home / "auth" / "auth.db"
auth.parent.mkdir(parents = True, exist_ok = True)
auth.write_text("OWNER_AUTH_DB", encoding = "utf-8")
- out = run_as(
+ # Three separate claims, run as three separate commands. They used to share one
+ # command line, and once the credential pre-flight in tools.py learned to refuse a
+ # command that NAMES the auth database, that one line was refused whole: the reach
+ # probes passed because nothing ran at all, and the usability probe could not run
+ # either. Split, each claim is answered by the layer that actually owns it.
+ reach = run_as(
+ BOB,
+ tools._bash_exec,
+ f"cat {auth}; echo rc=$?",
+ session_id = "chat",
+ )
+ assert "OWNER_AUTH_DB" not in reach and "rc=0" not in reach, reach
+
+ listing = run_as(BOB, tools._bash_exec, f"ls {home}; echo ls_rc=$?", session_id = "chat")
+ assert "OWNER_AUTH_DB" not in listing and "ls_rc=0" not in listing, listing
+
+ # Names no part of the auth path, so nothing short-circuits it: this is the half
+ # that says the rest of the granted root is still usable, which is the whole point
+ # of hiding one directory inside it rather than revoking the root.
+ usable = run_as(
BOB,
tools._bash_exec,
- f"cat {auth}; echo rc=$?; ls {home}; echo ls_rc=$?; python -c 'import sys; print(sys.prefix)'",
+ "python -c 'import sys; print(sys.prefix)'",
session_id = "chat",
)
- assert "OWNER_AUTH_DB" not in out and "rc=0" not in out and "ls_rc=0" not in out, out
- assert sys.prefix in out, out
+ assert sys.prefix in usable, usable
rules = run_as(BOB, tool_confinement._landlock_rules, 3, tools._SANDBOX_SITE_DIR)
assert all(not tool_confinement._contains(p, str(home.resolve())) for p, _ in rules)
finally:
diff --git a/studio/backend/tests/test_setup_llama_cpp_backend.py b/studio/backend/tests/test_setup_llama_cpp_backend.py
index b7ccb3cbb0e..019aa8e17ed 100644
--- a/studio/backend/tests/test_setup_llama_cpp_backend.py
+++ b/studio/backend/tests/test_setup_llama_cpp_backend.py
@@ -18,6 +18,12 @@ from pathlib import Path
import pytest
+# tests/_shared, put on sys.path by studio/backend/tests/conftest.py. Every pwsh spawn in
+# this file goes through it: the two parametrised probes below are 17 pwsh startups in one
+# xdist job, all sharing $XDG_CACHE_HOME/powershell with every other worker, which is the
+# race that kills a startup outright with SIGABRT before the script runs.
+from unsloth_pwsh_runner import run_pwsh
+
_STUDIO = Path(__file__).resolve().parents[2]
_SETUP_SH = _STUDIO / "setup.sh"
_SETUP_PS1 = _STUDIO / "setup.ps1"
@@ -308,7 +314,7 @@ def test_llama_backend_source_choice_in_setup_ps1(backend, force_vulkan, expecte
env["UNSLOTH_LLAMA_CPP_BACKEND"] = backend
if force_vulkan is not None:
env["UNSLOTH_FORCE_VULKAN"] = force_vulkan
- out = subprocess.run(
+ out = run_pwsh(
[
"pwsh",
"-NoProfile",
@@ -353,7 +359,7 @@ def _run_ps1(value: str | None) -> str:
"$explicitLlamaSourceBackend = $null\n"
f'{normalize}\n"ARGS:" + ($prebuiltArgs -join ",")'
)
- out = subprocess.run(
+ out = run_pwsh(
["pwsh", "-NoProfile", "-Command", harness],
capture_output = True,
text = True,
diff --git a/studio/frontend/tests/pasted-text-attachment.test.ts b/studio/frontend/tests/pasted-text-attachment.test.ts
index 7650c504ee6..f5da4d5da2c 100644
--- a/studio/frontend/tests/pasted-text-attachment.test.ts
+++ b/studio/frontend/tests/pasted-text-attachment.test.ts
@@ -531,7 +531,10 @@ test("paste without formatting is the chord each platform binds", () => {
// Shift+Cmd+V is taken too: web apps bind it, so a host that maps it should
// reach the field rather than the attachment path.
assert.ok(
- isPlainPasteChord(keyEvent("KeyV", { metaKey: true, shiftKey: true }), true),
+ isPlainPasteChord(
+ keyEvent("KeyV", { metaKey: true, shiftKey: true }),
+ true,
+ ),
);
assert.ok(
isPlainPasteChord(
@@ -541,7 +544,10 @@ test("paste without formatting is the chord each platform binds", () => {
);
// The other platform's modifier is a different chord, not this one.
assert.equal(
- isPlainPasteChord(keyEvent("KeyV", { ctrlKey: true, shiftKey: true }), true),
+ isPlainPasteChord(
+ keyEvent("KeyV", { ctrlKey: true, shiftKey: true }),
+ true,
+ ),
false,
);
assert.equal(
@@ -572,7 +578,10 @@ test("an ordinary paste is left to the attachment threshold", () => {
false,
);
assert.equal(
- isPlainPasteChord(keyEvent("KeyC", { metaKey: true, shiftKey: true }), true),
+ isPlainPasteChord(
+ keyEvent("KeyC", { metaKey: true, shiftKey: true }),
+ true,
+ ),
false,
);
// Modifiers alone, which is what the first keydowns of the chord carry.
@@ -595,16 +604,10 @@ test("a keyboard reporting no code reads the physical key", () => {
};
assert.ok(isPlainPasteChord(optionChord, true));
// A different physical key on the same glyph path is still refused.
- assert.equal(
- isPlainPasteChord({ ...optionChord, keyCode: 67 }, true),
- false,
- );
+ assert.equal(isPlainPasteChord({ ...optionChord, keyCode: 67 }, true), false);
// keyCode wins over key, so a "v" on another physical key does not pass.
assert.equal(
- isPlainPasteChord(
- { ...optionChord, key: "v", keyCode: 67 },
- true,
- ),
+ isPlainPasteChord({ ...optionChord, key: "v", keyCode: 67 }, true),
false,
);
});
@@ -721,7 +724,10 @@ test("the composer reads the chord from the keydown and clears it", async () =>
// A paste event carries no modifiers, so the chord has to come from the
// keydown before it, on capture so inputProps keeps its own onKeyDown.
assert.match(thread, /onKeyDownCapture=\{notePlainPasteChord\}/);
- assert.match(thread, /isPlainPasteChord\(event\)\n\s*\? performance\.now\(\)/);
+ assert.match(
+ thread,
+ /isPlainPasteChord\(event\)\n\s*\? performance\.now\(\)/,
+ );
// And it lasts only while the keys are down. The paste is the keydown's own
// default action, so it has already run by the time anything is released,
// while a menu cannot be reached without letting go first.
@@ -771,26 +777,58 @@ test("the chord carries a bulk paste past the threshold, inline", () => {
);
});
+/** Every value stored under `key`, anywhere in a locale tree. */
+const valuesForKey = (tree: unknown, key: string): string[] => {
+ const found: string[] = [];
+ const walk = (node: unknown) => {
+ if (typeof node !== "object" || node === null) return;
+ for (const [name, value] of Object.entries(
+ node as Record<string, unknown>,
+ )) {
+ if (name === key && typeof value === "string") found.push(value);
+ else walk(value);
+ }
+ };
+ walk(tree);
+ return found;
+};
+
test("every locale keeps the shortcut in the threshold description", async () => {
- const { readdir, readFile } = await import("node:fs/promises");
+ const { readdir } = await import("node:fs/promises");
const dir = new URL("../src/i18n/locales/", import.meta.url);
const files = (await readdir(dir)).filter((name) => name.endsWith(".ts"));
assert.ok(files.length >= 12, "every shipped locale is read");
for (const name of files) {
- const source = await readFile(new URL(name, dir), "utf8");
- const at = source.indexOf("pastedTextThresholdDescription:");
- assert.notEqual(at, -1, `${name} carries the description`);
- const line = source.slice(at, source.indexOf("\n", at));
+ // The RESOLVED value, not a slice of the source. This used to take
+ // source.indexOf("pastedTextThresholdDescription:") and read to the next
+ // newline, which asserts about the formatter as much as the translation: a
+ // value Prettier wraps onto the following line leaves the slice holding only
+ // the key, and the placeholder is invisible while being right there. ar.ts is
+ // wrapped that way on main today, so this was red on every PR, and every other
+ // locale would have broken it in turn as they got rewrapped. Importing the
+ // module reads what the app reads and cannot be moved by layout.
+ const module = (await import(new URL(name, dir).href)) as Record<
+ string,
+ unknown
+ >;
+ const tree =
+ module[name.replace(/\.ts$/, "").replace(/-/g, "")] ??
+ Object.values(module)[0];
+ const values = valuesForKey(tree, "pastedTextThresholdDescription");
+ assert.equal(
+ values.length,
+ 1,
+ `${name} carries the description exactly once`,
+ );
// The chord reads ⇧⌘V or Ctrl+Shift+V, so the tab supplies it and a
// translation that drops the placeholder loses the escape hatch.
- assert.ok(line.includes("{shortcut}"), `${name} keeps {shortcut}`);
+ assert.ok(values[0].includes("{shortcut}"), `${name} keeps {shortcut}`);
}
});
test("the settings label names the chord the composer accepts", async () => {
- const { formatBindingLabel } = await import(
- "../src/features/settings/lib/keyboard-shortcuts.ts"
- );
+ const { formatBindingLabel } =
+ await import("../src/features/settings/lib/keyboard-shortcuts.ts");
const { readFile } = await import("node:fs/promises");
for (const mac of [true, false]) {
const binding = {
diff --git a/tests/studio/install/test_llama_kind_gate_matches_selector.py b/tests/studio/install/test_llama_kind_gate_matches_selector.py
index e074aab3b56..13ae6c2e751 100644
--- a/tests/studio/install/test_llama_kind_gate_matches_selector.py
+++ b/tests/studio/install/test_llama_kind_gate_matches_selector.py
@@ -28,7 +28,6 @@ import itertools
import pathlib
import re
import shutil
-import subprocess
import sys
import pytest
@@ -38,8 +37,10 @@ SETUP_PS1 = REPO_ROOT / "studio" / "setup.ps1"
SETUP_SRC = SETUP_PS1.read_text(encoding = "utf-8")
sys.path.insert(0, str(REPO_ROOT / "studio"))
+sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2] / "_shared"))
import install_llama_prebuilt as ip # noqa: E402
+from unsloth_pwsh_runner import run_pwsh # noqa: E402
PWSH = shutil.which("pwsh") or shutil.which("powershell")
requires_pwsh = pytest.mark.skipif(PWSH is None, reason = "PowerShell is unavailable")
@@ -121,7 +122,9 @@ def _expected_kinds(*, arm64_venv: bool, nvidia: bool, rocm: bool, opt_out: bool
"Write-Output ('<<<' + ($expectedKinds -join ',') + '>>>')",
]
)
- done = subprocess.run(
+ # run_pwsh, not subprocess.run: one shared $XDG_CACHE_HOME/powershell startup cache
+ # across xdist workers kills ~1 startup in 500 before it reaches the script.
+ done = run_pwsh(
[PWSH, "-NoProfile", "-NonInteractive", "-Command", script],
capture_output = True,
timeout = 120,
diff --git a/tests/studio/install/test_pr10648_offline_and_status.py b/tests/studio/install/test_pr10648_offline_and_status.py
index a54d1f748cf..ae244b0a89b 100644
--- a/tests/studio/install/test_pr10648_offline_and_status.py
+++ b/tests/studio/install/test_pr10648_offline_and_status.py
@@ -663,45 +663,40 @@ def test_pre_pr_an_unreachable_release_listing_escaped_as_an_uncaught_oserror():
assert guard in post
-@requires_merge_base
-def test_the_pr_only_added_new_arms_to_the_setup_status_blocks():
- """The pre-existing tokens must mean exactly what they meant before.
+def test_the_keep_arm_sits_beside_the_status_arms_it_did_not_replace():
+ """The pre-existing tokens must still mean exactly what they meant before.
``already matches`` and llama's two arms carry other behaviour (node greps the same
- token at setup.sh:1261), so the new keep arm is only safe if it was inserted beside
- them rather than rewritten over them. Checked on the diff, not on the current text: a
- reworded arm would still satisfy a substring assertion on the file.
+ token at setup.sh:1261), so this PR's keep arm is only safe next to them rather than
+ written over them.
+
+ Stated on the shipped text, not on a diff. The original spelling of this test read
+ ``git diff <the PR's merge base> -- studio/setup.*`` and asserted that no line carrying
+ a status decision appeared as a REMOVAL, which is a property of one branch and not of
+ the product: on ``main`` that diff is everything the installers have done since
+ 2026-09-09, so it went red the moment the PR landed on a main that had moved, and it
+ said so about whichever unrelated commit happened to touch a ``-match`` line. CI never
+ reported it because ``actions/checkout`` is shallow there and the merge base is absent,
+ so ``requires_merge_base`` skipped the whole thing. What the assertions below keep is
+ the part that is checkable forever: each arm, each guard, and exactly one keep arm per
+ runtime per script -- a rewritten or duplicated arm still fails here.
"""
- diff = _git("diff", "-U0", MERGE_BASE, "--", "studio/setup.sh", "studio/setup.ps1")
- assert diff.returncode == 0, diff.stderr
- removed = [
- line[1:]
- for line in diff.stdout.splitlines()
- if line.startswith("-") and not line.startswith("---")
- ]
- added = [
- line[1:]
- for line in diff.stdout.splitlines()
- if line.startswith("+") and not line.startswith("+++")
- ]
- # Nothing that carries a status decision was removed or rewritten.
- for line in removed:
- assert MATCH_TOKEN not in line, f"the PR rewrote an 'already matches' arm: {line!r}"
- assert "step " not in line, f"the PR rewrote a status line: {line!r}"
- assert "grep -Fq" not in line, f"the PR rewrote a status grep: {line!r}"
- assert "-match" not in line, f"the PR rewrote a status match: {line!r}"
- # What WAS added is the keep arm, once per script.
- keep_arms = [line for line in added if KEEP_TOKEN in line]
- assert len(keep_arms) == 2, keep_arms
- assert any("grep -Fq" in line for line in keep_arms), keep_arms
- assert any("-match" in line for line in keep_arms), keep_arms
-
- # The llama arms and node's grep are still exactly where they were.
setup_sh = (PACKAGE_ROOT / "studio" / "setup.sh").read_text(encoding = "utf-8")
setup_ps1 = (PACKAGE_ROOT / "studio" / "setup.ps1").read_text(encoding = "utf-8")
+
+ # The keep arm this PR added: one per runtime per script, and guarded with each shell's
+ # own test rather than, say, both scripts growing the sh spelling.
+ sh_keeps = [line for line in setup_sh.splitlines() if KEEP_TOKEN in line]
+ ps1_keeps = [line for line in setup_ps1.splitlines() if KEEP_TOKEN in line]
+ assert len(sh_keeps) == 2, sh_keeps
+ assert len(ps1_keeps) == 2, ps1_keeps
+ assert all("grep -Fq" in line for line in sh_keeps), sh_keeps
+ assert all("-match" in line for line in ps1_keeps), ps1_keeps
+
+ # The llama arms and node's grep are still exactly where they were.
assert 'grep -Fq "already matches" "$_PREBUILT_LOG"' in setup_sh
assert 'grep -Fq "already matches" "$_NODE_LOG"' in setup_sh
- assert '$prebuiltOutput -match "already matches"' in setup_ps1
+ assert f'$prebuiltOutput -match "{MATCH_TOKEN}"' in setup_ps1
for script in (setup_sh, setup_ps1):
assert (
script.count("update unavailable, existing prebuilt kept") == 2
diff --git a/tests/studio/install/test_setup_fast_path_guard.py b/tests/studio/install/test_setup_fast_path_guard.py
index a496f811e1b..d4d26609bf9 100644
--- a/tests/studio/install/test_setup_fast_path_guard.py
+++ b/tests/studio/install/test_setup_fast_path_guard.py
@@ -464,9 +464,15 @@ def test_the_deep_verify_only_degrades_on_a_tree_that_lacks_the_keyword(
assert result.returncode == expected, result.stderr.decode()
-def test_the_installer_reads_uv_offline_the_same_way_the_shell_does(tmp_path):
+def test_the_installer_reads_uv_offline_the_same_way_the_shell_does(tmp_path, monkeypatch):
"""A shell that decides "online" while the installer decides "offline" declines a repair
- with a message contradicting the user. `off` and `no` are the spellings that did it."""
+ with a message contradicting the user. `off` and `no` are the spellings that did it.
+
+ ``_uv_is_offline`` reads ``os.environ``, so the loop below has to set it for real. It
+ does that through ``monkeypatch`` rather than assigning ``os.environ`` directly: a bare
+ assignment survives the test and leaves the LAST value in the loop set for the rest of
+ the session, which is a resolver policy every other suite in this directory inherits.
+ """
import ast as _ast
import os
import subprocess
@@ -521,7 +527,7 @@ def test_the_installer_reads_uv_offline_the_same_way_the_shell_does(tmp_path):
).stdout.strip()
== "yes"
)
- os.environ["UV_OFFLINE"] = value
+ monkeypatch.setenv("UV_OFFLINE", value)
assert (
shell == namespace["_uv_is_offline"]()
), f"UV_OFFLINE={value!r}: setup.sh says {shell}, install_python_stack.py disagrees"
diff --git a/tests/studio/install/test_woa_wheelhouse_guard_behaviour.py b/tests/studio/install/test_woa_wheelhouse_guard_behaviour.py
index 5624c6b7438..9e4a0b3cfa3 100644
--- a/tests/studio/install/test_woa_wheelhouse_guard_behaviour.py
+++ b/tests/studio/install/test_woa_wheelhouse_guard_behaviour.py
@@ -25,14 +25,18 @@ Hermetic: no network. The live-PyPI leg of the guard is exercised on hardware, n
from __future__ import annotations
+import os
import pathlib
import re
import shutil
-import subprocess
+import sys
import textwrap
import pytest
+sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2] / "_shared"))
+from unsloth_pwsh_runner import run_pwsh # noqa: E402
+
REPO_ROOT = pathlib.Path(__file__).resolve().parents[3]
INSTALL_PS1 = REPO_ROOT / "install.ps1"
@@ -80,14 +84,58 @@ def _drop_list_block(source: str) -> str:
PRELUDE = "\n".join(_function(INSTALL_SRC, name) for name in HELPERS)
-def _run(script: str) -> str:
- proc = subprocess.run(
+#: Everything Test-WoaResolveReachesPyPI consults before it is told anything. The session
+#: running pytest supplies all of them for free -- a developer with UV_OFFLINE exported, a
+#: sibling suite that sets one and forgets to unset it, or a uv.toml / [tool.uv] anywhere
+#: above the working directory -- and each one silently decides the answer these tests are
+#: asserting on. Scrubbed here so the only resolver policy in a case is the one it sets.
+_UV_POLICY_ENV = (
+ "UV_OFFLINE",
+ "UV_NO_INDEX",
+ "UV_DEFAULT_INDEX",
+ "UV_INDEX_URL",
+ "UV_INDEX",
+ "UV_EXTRA_INDEX_URL",
+ "UV_CONFIG_FILE",
+ "UV_NO_CONFIG",
+ "PIP_NO_INDEX",
+ "PIP_INDEX_URL",
+ "PIP_EXTRA_INDEX_URL",
+ # Get-WoaUvConfigIndexPolicy reads %APPDATA%\uv\uv.toml and the ProgramData copy.
+ "APPDATA",
+ "ProgramData",
+)
+
+#: Matched case-folded, because the one mixed-case name above is the one that would survive
+#: a literal match on the platform it matters on: CPython's `os.environ` puts every key
+#: through `.upper()` on `nt` ("Where Env Var Names Must Be UPPERCASE", os.py), so Windows
+#: hands `ProgramData` to the comprehension below as `PROGRAMDATA`, it compares unequal, and
+#: the child keeps reading %PROGRAMDATA%\uv\uv.toml -- uv's system-level config, and the one
+#: file that can turn a row asserting True into a machine-dependent False.
+_UV_POLICY_ENV_FOLDED = frozenset(name.upper() for name in _UV_POLICY_ENV)
+
+
+def _scrubbed_environ(environ = None) -> dict[str, str]:
+ """`environ` (default: this session's) minus every resolver-policy variable."""
+ items = (os.environ if environ is None else environ).items()
+ return {key: value for key, value in items if key.upper() not in _UV_POLICY_ENV_FOLDED}
+
+
+def _run(script: str, *, cwd: str | pathlib.Path | None = None) -> str:
+ env = _scrubbed_environ()
+ # run_pwsh, not subprocess.run: the scrub above keeps HOME, so without the runner's own
+ # XDG_CACHE_HOME every worker still shares one ~83 KB pwsh startup-profile cache and ~1
+ # startup in 500 dies reading a half-written copy. run_pwsh layers its private cache
+ # directory onto the env dict handed to it and leaves every other key exactly as scrubbed.
+ proc = run_pwsh(
["pwsh", "-NoProfile", "-NonInteractive", "-Command", PRELUDE + "\n" + script],
capture_output = True,
text = True,
encoding = "utf-8",
errors = "replace",
timeout = 120,
+ env = env,
+ cwd = None if cwd is None else str(cwd),
)
assert proc.returncode == 0, f"pwsh failed: {proc.stdout}\n{proc.stderr}"
return proc.stdout.strip()
@@ -140,6 +188,42 @@ def test_a_wheel_is_usable_only_where_it_actually_imports(wheel, py_tag, abi_tag
assert out == str(usable), f"{wheel} on {py_tag}/{abi_tag}: expected {usable}, got {out}"
+def no_uv_config_dir(tmp_path):
+ """A working directory with no uv config anywhere above it.
+
+ Get-WoaUvConfigIndexPolicy walks from the current directory to the filesystem root, so
+ running from the repo (or from under a checkout that grows a `[tool.uv]` table) would
+ let a file decide an answer these rows attribute to their env dict. Asserted rather than
+ assumed: if such a file does appear above the tmp dir, this names it instead of turning
+ one parametrisation into an inexplicable False.
+ """
+ work = tmp_path / "neutral"
+ work.mkdir()
+ for parent in [work, *work.parents]:
+ assert not (parent / "uv.toml").is_file(), f"a uv.toml above the tmp dir: {parent}"
+ pyproject = parent / "pyproject.toml"
+ if pyproject.is_file():
+ text = pyproject.read_text(encoding = "utf-8", errors = "replace")
+ assert not re.search(
+ r"(?m)^\s*\[+tool\.uv(\.|\])", text
+ ), f"a [tool.uv] table above the tmp dir: {pyproject}"
+ return work
+
+
[email protected]("spelling", ["ProgramData", "PROGRAMDATA", "programdata"])
+def test_the_scrub_drops_program_data_however_the_platform_spelled_it(spelling):
+ """The scrub has to survive Windows re-casing the name on the way in.
+
+ Runs everywhere because it is the Windows spelling that is untestable on Windows here:
+ a Linux session has no ProgramData to leak, so a literal-match scrub passes this suite
+ green on CI and quietly stops working on the only platform install.ps1 ships to. Feeding
+ the three spellings a real environment block can carry states the requirement directly.
+ """
+ scrubbed = _scrubbed_environ({spelling: r"C:\ProgramData", "PATH": "/usr/bin"})
+ assert scrubbed == {"PATH": "/usr/bin"}, f"{spelling} survived the scrub: {scrubbed}"
+
+
@requires_pwsh
@pytest.mark.parametrize(
("env", "reaches"),
@@ -161,9 +245,15 @@ def test_a_wheel_is_usable_only_where_it_actually_imports(wheel, py_tag, abi_tag
({"UV_NO_INDEX": "false"}, True),
],
)
-def test_pypi_counts_only_when_the_resolve_would_reach_it(env, reaches):
+def test_pypi_counts_only_when_the_resolve_would_reach_it(no_uv_config_dir, env, reaches):
+ """What the environment alone says. Every OTHER source of the same answer -- the
+ inherited UV_*/PIP_* policy, %APPDATA%, and any uv.toml or [tool.uv] above the working
+ directory -- is removed by `_run` and `no_uv_config_dir`, so a row that says True is
+ measuring its own env dict and not the session pytest happens to be running in. The
+ config half of the same question is `test_a_uv_config_decides_whether_pypi_is_in_the_resolve`.
+ """
sets = "".join(f'$env:{key} = "{value}"; ' for key, value in env.items())
- assert _run(sets + "Test-WoaResolveReachesPyPI") == str(reaches)
+ assert _run(sets + "Test-WoaResolveReachesPyPI", cwd = no_uv_config_dir) == str(reaches)
@requires_pwsh
diff --git a/tests/studio/install/test_woa_wheelhouse_prefers_pypi.py b/tests/studio/install/test_woa_wheelhouse_prefers_pypi.py
index 1c446118898..e1e0d0ded98 100644
--- a/tests/studio/install/test_woa_wheelhouse_prefers_pypi.py
+++ b/tests/studio/install/test_woa_wheelhouse_prefers_pypi.py
@@ -22,10 +22,13 @@ from __future__ import annotations
import pathlib
import re
import shutil
-import subprocess
+import sys
import pytest
+sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2] / "_shared"))
+from unsloth_pwsh_runner import run_pwsh # noqa: E402
+
REPO_ROOT = pathlib.Path(__file__).resolve().parents[3]
INSTALL_PS1 = REPO_ROOT / "install.ps1"
@@ -184,7 +187,9 @@ def test_the_wheelhouse_override_is_normalised(source, configured, expected, why
+ _wheelhouse_assignment(source).strip()
+ '; Write-Output "<<<$script:WoaWheelhouse>>>"'
)
- done = subprocess.run(
+ # run_pwsh, not subprocess.run: one shared $XDG_CACHE_HOME/powershell startup cache
+ # across xdist workers kills ~1 startup in 500 before it reaches the script.
+ done = run_pwsh(
[PWSH, "-NoProfile", "-NonInteractive", "-Command", script],
capture_output = True,
text = True,
diff --git a/tests/studio/install/woa_ps_harness.py b/tests/studio/install/woa_ps_harness.py
index 4a0f6390cc5..fdfcbb17ad4 100644
--- a/tests/studio/install/woa_ps_harness.py
+++ b/tests/studio/install/woa_ps_harness.py
@@ -15,10 +15,12 @@ from __future__ import annotations
import pathlib
import re
import shutil
-import subprocess
+import sys
import pytest
+sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2] / "_shared"))
+from unsloth_pwsh_runner import run_pwsh # noqa: E402
PACKAGE_ROOT = pathlib.Path(__file__).resolve().parents[3]
MANIFEST_PY = PACKAGE_ROOT / "studio" / "install_manifest.py"
@@ -58,8 +60,17 @@ def _ps(
timeout = 120,
**kwargs,
):
- """Run a PowerShell snippet and hand back the completed process."""
- return subprocess.run(
+ """Run a PowerShell snippet and hand back the completed process.
+
+ Through `run_pwsh`, not `subprocess.run`: every module in this directory shares one
+ $XDG_CACHE_HOME/powershell startup cache with the other xdist workers otherwise, and a
+ startup that deserialises a half-written one dies before it reaches the snippet. That
+ lands as `Stack overflow.` + SIGABRT, or as a FileLoadException, on a test that never
+ ran. The runner gives each worker its own cache directory and retries only a run that
+ crashed WITHOUT answering, so a snippet that runs to completion and returns the wrong
+ answer still fails here with its own message.
+ """
+ return run_pwsh(
[PWSH, "-NoProfile", "-NonInteractive", "-Command", script],
capture_output = True,
text = True,
diff --git a/tests/studio/playwright_composer_icons.py b/tests/studio/playwright_composer_icons.py
index 4589d687350..552fb2cca94 100644
--- a/tests/studio/playwright_composer_icons.py
+++ b/tests/studio/playwright_composer_icons.py
@@ -22,6 +22,16 @@ from playwright.sync_api import sync_playwright
from _playwright_robust import start_vite, stop_process, wait_for_smoke_page
+# `wait_for_smoke_page` proves vite ANSWERS, by fetching the raw HTML. The first navigation
+# is what makes it WORK: vite transforms the page's whole module graph on demand, and the
+# default `wait_until = "load"` waits out every one of those requests. On a cold Windows
+# runner that first goto ran past playwright's 30s default and took the job down with
+# `Page.goto: Timeout 30000ms exceeded`, twice, while the node tests either side of it
+# reported `# fail 0`. Every other driver in this directory that navigates a vite dev page
+# already carries an explicit budget; this one and playwright_queue_localization.py were
+# the two that did not.
+NAV_TIMEOUT_MS = 90_000
+
MEASURE = """() => [...document.querySelectorAll('button[data-case]')].map(button => {
const svg = button.querySelector('svg');
const buttonBox = button.getBoundingClientRect();
@@ -75,7 +85,15 @@ def main() -> None:
context = browser.new_context(device_scale_factor = dpr)
try:
page = context.new_page()
- page.goto(f"http://127.0.0.1:{port}/smoke-composer-icons.html")
+ # The wait_for below is the other half of the same cold start:
+ # domcontentloaded returns before the module graph has rendered
+ # the buttons, so the locator inherits this budget too.
+ page.set_default_timeout(NAV_TIMEOUT_MS)
+ page.goto(
+ f"http://127.0.0.1:{port}/smoke-composer-icons.html",
+ wait_until = "domcontentloaded",
+ timeout = NAV_TIMEOUT_MS,
+ )
page.locator("button[data-case]").last.wait_for()
for font, zoom, dark, direction in itertools.product(
(0.75, 1, 1.25), (0.8, 1, 1.25), (False, True), ("ltr", "rtl")
diff --git a/tests/studio/playwright_queue_localization.py b/tests/studio/playwright_queue_localization.py
index becd6b0f556..bf8b3ce7d41 100644
--- a/tests/studio/playwright_queue_localization.py
+++ b/tests/studio/playwright_queue_localization.py
@@ -14,6 +14,13 @@ from _playwright_robust import start_vite, stop_process, wait_for_smoke_page
PAGE = "/smoke-prompt-queue-actions.html"
ENTRY = "/smoke-prompt-queue-actions-main.tsx"
+# `wait_for_smoke_page` proves vite ANSWERS, by fetching the raw HTML. The first navigation
+# is what makes it WORK: vite transforms the page's whole module graph on demand, and the
+# default `wait_until = "load"` waits out every one of those requests, which on a cold
+# Windows runner runs past playwright's 30s default. The `wait_for` at the end of `seed`
+# already carries 60s for the same reason; this is the navigation ahead of it.
+NAV_TIMEOUT_MS = 90_000
+
# The queue view must not fall back to English while Settings shows the
# translated Queue/Steer wording from the same catalog.
JA = {
@@ -32,7 +39,7 @@ def seed(
locale = "en",
shortcut = "enter",
):
- page.goto(base + PAGE)
+ page.goto(base + PAGE, wait_until = "domcontentloaded", timeout = NAV_TIMEOUT_MS)
page.evaluate(
"""([locale, shortcut]) => {
localStorage.setItem("unsloth_locale", locale);
@@ -43,7 +50,7 @@ def seed(
}""",
[locale, shortcut],
)
- page.reload()
+ page.reload(wait_until = "domcontentloaded", timeout = NAV_TIMEOUT_MS)
page.get_by_role("button", name = "Reset fixture", exact = True).wait_for(
state = "visible", timeout = 60_000
)
diff --git a/tests/studio/studiobench/scene/selftest/test_studiobench_queued_idle_live.py b/tests/studio/studiobench/scene/selftest/test_studiobench_queued_idle_live.py
index 4c4df599b35..82f7829656a 100644
--- a/tests/studio/studiobench/scene/selftest/test_studiobench_queued_idle_live.py
+++ b/tests/studio/studiobench/scene/selftest/test_studiobench_queued_idle_live.py
@@ -33,6 +33,7 @@ pass, but it is not a reading either, and a real difference elsewhere in the thr
from __future__ import annotations
+import re
import sys
from pathlib import Path
@@ -276,6 +277,26 @@ def test_what_reading_the_queue_surface_gives_up(page):
# ── the fixtures are the app's markup, not the test's ────────────────
+#: The shipped English catalog. The probes below read the DOM in English, so this file is where
+#: "what the button says" actually lives now that #11117 routed the queue surface through `useT`.
+_EN_LOCALE = _THREAD_TSX.parents[2] / "i18n" / "locales" / "en.ts"
+
+
+def _en_string(key: str) -> str:
+ """`promptQueue.<key>` out of the shipped en.ts, or fail saying the key is gone.
+
+ A regex over the TypeScript rather than a parse: the catalog is a plain object literal of
+ string values, and the alternative is a Node dependency for a suite that is otherwise pure
+ Python. Narrow enough to be honest -- it matches the key at its own indent inside the file,
+ and a key that stops existing raises here instead of returning "" and passing a substring
+ check against everything.
+ """
+ src = _EN_LOCALE.read_text(encoding = "utf-8")
+ match = re.search(rf"(?m)^\s*{re.escape(key)}:\s*\"((?:[^\"\\]|\\.)*)\",?\s*$", src)
+ assert match, f"the en catalog no longer defines promptQueue.{key} ({_EN_LOCALE})"
+ return match.group(1)
+
+
def test_the_shipped_composer_still_renders_the_two_queue_buttons():
"""The fixtures above are hand-written, so they can drift into asserting themselves.
@@ -283,6 +304,16 @@ def test_the_shipped_composer_still_renders_the_two_queue_buttons():
names the queue surface, so this reads that out of the shipped TSX. If Unsloth stops rendering
the queued-idle button the conflation is gone and this file should go with it; if it renames
the queue surface, `dom.promptQueue()` goes quiet and the conflation is back.
+
+ Read through the CATALOG, not off an English literal in the TSX. #11117 localized the queue
+ view -- the label the composer renders became `t("promptQueue.queueButton")` and the queue
+ surface's accessible name became `t("promptQueue.regionLabel", ...)` -- and this file pinned
+ both as the English text that used to be inline, so it went red on a correct change. Worse,
+ the second of the two was hidden behind the first and would have come back one fix later.
+ The invariant that actually matters survived that change untouched and is what is asserted
+ now: the composer still picks between two DIFFERENT labels on `followUpBehavior`, the queue
+ surface still names itself, and the English those keys resolve to is still the English the
+ fixtures above and `dom.js`'s selector are written in.
"""
if not _THREAD_TSX.exists():
pytest.skip(f"the shipped composer is not in this checkout: {_THREAD_TSX}")
@@ -291,12 +322,40 @@ def test_the_shipped_composer_still_renders_the_two_queue_buttons():
"ComposerRightControls no longer renders the Queue button in exactly two places; "
"re-read which of them can appear on an idle thread"
)
- assert 'followUpBehavior === "queue" ? "Queue message" : "Steer response"' in src
+ # The branch itself: one behaviour, two labels. A composer that stopped distinguishing them
+ # would render the same name for queue and steer and the fixtures would stop meaning anything.
+ assert re.search(
+ r'followUpBehavior === "queue"\s*\?\s*"promptQueue\.queueButton"\s*:\s*"promptQueue\.steerButton"',
+ src,
+ ), (
+ "the composer no longer picks its label from followUpBehavior between the queueButton "
+ "and steerButton keys; re-read what the two Queue buttons are now called"
+ )
+ queue_label, steer_label = _en_string("queueButton"), _en_string("steerButton")
+ assert queue_label != steer_label, (
+ f"the en catalog gives queue and steer the same label {queue_label!r}, so the two "
+ "composer states are indistinguishable to every probe that reads the accessible name"
+ )
+ # The English the fixtures and the scene probes are written in.
+ assert queue_label == "Queue message", queue_label
+ assert steer_label == "Steer response", steer_label
+
queue_src = (_THREAD_TSX.parent / "prompt-queue-list.tsx").read_text(encoding = "utf-8")
- assert "aria-label={`Prompt queue, ${entry.current} of ${entry.total}`}" in queue_src, (
+ assert 'aria-label={t("promptQueue.regionLabel"' in queue_src, (
"PromptQueueStack no longer names itself, so dom.promptQueue() matches nothing and the "
"queued-idle interval is indistinguishable again"
)
+ # dom.js matches that name by a HARD-CODED English prefix, so the catalog and the selector
+ # have to agree or the probe goes quiet without anything failing. This is the coupling the
+ # localization pass could have broken silently; it did not, and now it cannot.
+ region_label = _en_string("regionLabel")
+ prefix = re.search(r'\[aria-label\^="([^"]*)"\]', _DOM_JS.read_text(encoding = "utf-8"))
+ assert prefix, "dom.js no longer selects the queue surface by an aria-label prefix"
+ assert region_label.startswith(prefix.group(1)), (
+ f"dom.js matches the queue surface on {prefix.group(1)!r} but the en catalog names it "
+ f"{region_label!r}, so dom.promptQueue() finds nothing and generating() silently "
+ "reads a queued-idle thread as streaming"
+ )
assert 'aria-label="Stop queued message"' in src
diff --git a/tests/studio/test_cache_budget_discipline.py b/tests/studio/test_cache_budget_discipline.py
index 75cd132585e..081e823eac6 100644
--- a/tests/studio/test_cache_budget_discipline.py
+++ b/tests/studio/test_cache_budget_discipline.py
@@ -264,7 +264,130 @@ def _composite_actions():
yield f.parent.name, ((doc.get("runs") or {}).get("steps") or [])
+#: Triggers that can put a workflow on a ref other than `main`. `pull_request` and
+#: `pull_request_target` are the obvious two; `workflow_call` is here because a reusable
+#: workflow runs on the CALLER's ref, so one called from a pull_request workflow saves on
+#: the PR's ref as surely as if it declared the trigger itself.
+_PR_REACHABLE_TRIGGERS = frozenset({"pull_request", "pull_request_target", "workflow_call"})
+
+#: The only triggers that cannot put a workflow anywhere near a pull request's ref.
+#: `schedule` and `repository_dispatch` are documented to run the default branch and nothing
+#: else; `workflow_dispatch` takes a ref, but only from a human who asked for that ref by
+#: name, which is not the "every PR writes its own copy" harm this rule is about. Everything
+#: NOT named here -- `merge_group`, which runs on its own `gh-readonly-queue/...` ref, and
+#: any event added to Actions after this was written -- stays indicted, which is what the
+#: docstring below promises and what a guard whose failure mode is silence has to do.
+_REF_SAFE_TRIGGERS = frozenset({"schedule", "repository_dispatch", "workflow_dispatch"})
+
+
+def _triggers(doc: dict) -> dict:
+ """A workflow's `on:` block as a mapping, whatever shape it was written in.
+
+ YAML 1.1 reads a bare `on:` key as the boolean True (the Norway problem's cousin), so
+ the key is looked up both ways. `on: push`, `on: [push, workflow_dispatch]` and the
+ mapping form all normalise to a dict here so one reader handles all three.
+ """
+ raw = doc.get("on", doc.get(True))
+ if isinstance(raw, str):
+ return {raw: None}
+ if isinstance(raw, list):
+ return {event: None for event in raw}
+ return raw if isinstance(raw, dict) else {}
+
+
+def _pull_request_reachable(doc: dict) -> bool:
+ """Whether any pull request can cause this workflow to run.
+
+ The rule below exists because a save on a PR ref writes an entry only re-runs of that
+ same PR can ever restore, while competing for the shared budget against main's copy.
+ That harm needs a pull request to reach the workflow at all. A workflow no pull request
+ can trigger is therefore outside the rule -- but only if that is READ from its `on:`
+ block, never assumed, so the day it grows a `pull_request` trigger it comes straight
+ back under the rule with no one having to remember.
+
+ Conservative in both directions:
+ * a `push` with no `branches` filter runs on every branch pushed to this repo,
+ including the in-repo topic branches most pull requests here are opened from, so
+ it counts as reachable;
+ * a `push` restricted to `main` does not;
+ * anything unrecognised counts as reachable, because the cost of a wrong "exempt"
+ is a silently refilled cache and the cost of a wrong "reachable" is a comment.
+ """
+ triggers = _triggers(doc)
+ if not triggers:
+ # No parseable `on:` at all. Says nothing, so it does not get to say "exempt".
+ return True
+ for event, spec in triggers.items():
+ if event in _PR_REACHABLE_TRIGGERS:
+ return True
+ if event == "push":
+ branches = (spec or {}).get("branches") if isinstance(spec, dict) else None
+ if not branches or [b for b in branches if b != "main"]:
+ return True
+ continue
+ if event not in _REF_SAFE_TRIGGERS:
+ return True
+ return False
+
+
+ ("on_block", "reachable"),
+ [
+ ({"workflow_dispatch": None}, False),
+ ({"schedule": [{"cron": "0 0 * * *"}]}, False),
+ ({"push": {"branches": ["main"]}}, False),
+ ({"workflow_dispatch": None, "push": {"branches": ["main"]}}, False),
+ ({"pull_request": None}, True),
+ ({"pull_request_target": {"types": ["opened"]}}, True),
+ # Reusable: it runs on the caller's ref, so a pull_request caller saves on the PR ref.
+ ({"workflow_call": None}, True),
+ # No `branches` filter means every branch, which is where PRs here come from.
+ ({"push": None}, True),
+ ({"push": {"branches": ["main", "release/**"]}}, True),
+ ({"push": {"tags": ["v*"]}}, True),
+ # A dispatch-only workflow that also builds every PR is not dispatch-only.
+ ({"workflow_dispatch": None, "pull_request": {"paths": ["x"]}}, True),
+ # Default-branch-only, so exempt for the same reason schedule is.
+ ({"repository_dispatch": {"types": ["x"]}}, False),
+ # The merge queue runs on refs/heads/gh-readonly-queue/..., which is not main.
+ ({"merge_group": None}, True),
+ # An event this predicate has never heard of says nothing about its ref.
+ ({"release": {"types": ["published"]}}, True),
+ # Unparseable says nothing, so it does not get to be called unreachable.
+ ({}, True),
+ ],
+)
+def test_the_pull_request_reachability_check_reads_the_trigger_block(on_block, reachable):
+ """The rule below is only as good as this predicate, so the predicate is tested too.
+
+ Mirrors test_the_main_only_expression_check_reads_the_expression above, and for the same
+ reason: the guard's failure mode is silence, so the thing that can make it silent is the
+ thing that most needs its own rows.
+ """
+ assert _pull_request_reachable({"on": on_block}) is reachable, on_block
+ # YAML 1.1 turns a bare `on:` key into True. Both spellings must read the same.
+ assert _pull_request_reachable({True: on_block}) is reachable, on_block
+
+
def test_no_workflow_saves_a_cache_on_a_pull_request_ref():
+ """A cache save that can land on a pull request's ref, in anything a pull request reaches.
+
+ Scoped by TRIGGER, not by a list of excused filenames. The rule's harm needs a pull
+ request to reach the workflow: a PR-scoped entry is restorable only by re-runs of that
+ same PR while it evicts main's copy, which every PR can read. A workflow no pull request
+ can run writes no PR-scoped entry, and indicting one was this guard reporting a rule it
+ had not checked -- it read each step's `if:` and never read the workflow's `on:`.
+
+ Deliberately NOT an exemption list keyed on filename. Skipping a whole file would blind
+ this to every OTHER step in it, including a `setup-python` implicit save added later, and
+ the excuse would keep applying after the reason for it had gone. Reading `on:` cannot rot
+ that way: the day a workflow gains a `pull_request` or `pull_request_target` trigger,
+ every cache save in it is indicted on that same commit with nobody having to remember.
+
+ Composite actions stay indicted unconditionally, whatever calls them: an action is used
+ BY workflows, so it has no triggers of its own, and one `uses:`d from a pull_request job
+ saves on the PR's ref exactly as an inline step would.
+ """
offenders = []
for name, steps in _composite_actions():
for step in steps:
@@ -273,25 +396,31 @@ def test_no_workflow_saves_a_cache_on_a_pull_request_ref():
continue
if "refs/heads/main" not in str(step.get("if", "")):
offenders.append(f"action {name}: {step.get('name') or step.get('uses')}")
- for name, jid, job in _jobs():
- for step in job.get("steps") or []:
- uses = _uses(step)
- # setup-python's `cache:` is a save too, and an invisible one: the action
- # registers a post-step (`post: dist/cache-save/index.js` in its own
- # action.yml) that runs after the job on whatever ref it ran on, with no
- # condition to gate it. A scan that only looked for `actions/cache` steps
- # read as green while nine jobs wrote PR-scoped entries every run. Nothing
- # is exempt now that all nine are converted.
- if "setup-python" in uses and (step.get("with") or {}).get("cache"):
- offenders.append(f"{name}:{jid}: setup-python implicit post-step save")
- continue
- if "actions/cache" not in uses:
- continue
- saves = "/restore@" not in uses # read-write and /save@ both write
- if not saves:
+ for name, doc in _workflows():
+ # Read once per workflow, then applied to every job in it.
+ if not _pull_request_reachable(doc):
+ continue
+ for jid, job in doc["jobs"].items():
+ if not isinstance(job, dict):
continue
- if not _restricted_to_main(str(step.get("if", ""))):
- offenders.append(f"{name}:{jid}: {step.get('name') or step.get('uses')}")
+ for step in job.get("steps") or []:
+ uses = _uses(step)
+ # setup-python's `cache:` is a save too, and an invisible one: the action
+ # registers a post-step (`post: dist/cache-save/index.js` in its own
+ # action.yml) that runs after the job on whatever ref it ran on, with no
+ # condition to gate it. A scan that only looked for `actions/cache` steps
+ # read as green while nine jobs wrote PR-scoped entries every run. Nothing
+ # is exempt now that all nine are converted.
+ if "setup-python" in uses and (step.get("with") or {}).get("cache"):
+ offenders.append(f"{name}:{jid}: setup-python implicit post-step save")
+ continue
+ if "actions/cache" not in uses:
+ continue
+ saves = "/restore@" not in uses # read-write and /save@ both write
+ if not saves:
+ continue
+ if not _restricted_to_main(str(step.get("if", ""))):
+ offenders.append(f"{name}:{jid}: {step.get('name') or step.get('uses')}")
assert not offenders, (
"these steps save a cache on whatever ref they run on, so every PR writes its own "
"copy and evicts the copy on main that all PRs share:\n " + "\n ".join(offenders)
diff --git a/tests/studio/test_pwsh_calls_use_the_shared_runner.py b/tests/studio/test_pwsh_calls_use_the_shared_runner.py
index ffd452d39ee..eb4b11f0c7d 100644
--- a/tests/studio/test_pwsh_calls_use_the_shared_runner.py
+++ b/tests/studio/test_pwsh_calls_use_the_shared_runner.py
@@ -39,6 +39,14 @@ import pytest
REPO_ROOT = Path(__file__).resolve().parents[2]
TESTS_ROOT = REPO_ROOT / "tests"
+# Both test trees, because the race is a property of the interpreter's startup cache and
+# not of which directory the test lives in. studio/backend/tests runs under xdist in the
+# same job and reaches tests/_shared through its own conftest, so a direct spawn there is
+# the identical defect; it was invisible while this guard scanned tests/ alone, and
+# studio/backend/tests/test_setup_llama_cpp_backend.py duly died with SIGABRT in the
+# Backend-CI "rest" shard while every allowlisted file in tests/ stayed green.
+_SCAN_ROOTS = (TESTS_ROOT, REPO_ROOT / "studio" / "backend" / "tests")
+
# The runner itself calls subprocess.run on a pwsh argv -- that is the whole point of it.
_RUNNER = TESTS_ROOT / "_shared" / "unsloth_pwsh_runner.py"
@@ -50,10 +58,11 @@ _SPAWNERS = frozenset({"run", "Popen", "call", "check_call", "check_output"})
_PWSH_EXECUTABLES = frozenset({"pwsh", "powershell", "powershell_ise"})
# Files allowed to spawn PowerShell without the shared runner, each with the reason the
-# startup-cache race does not reach them. Keep this keyed on the path relative to
-# tests/, and keep the reason specific enough to re-check.
+# startup-cache race does not reach them. Keyed on the path relative to the REPO ROOT,
+# because two test trees are scanned and a bare filename would not say which. Keep the
+# reason specific enough to re-check.
_ALLOWED_DIRECT_PWSH_CALLS = {
- "test_windows_amd_gpu_scan_fallback.py": (
+ "tests/test_windows_amd_gpu_scan_fallback.py": (
"hands the child a hermetic env whose HOME is the per-test tmp_path, so "
"XDG_CACHE_HOME resolves inside tmp_path and the startup cache is already "
"private per test -- this is the one pwsh-heavy file with zero failures in "
@@ -63,15 +72,19 @@ _ALLOWED_DIRECT_PWSH_CALLS = {
def _scanned_files() -> list[Path]:
- """Every Python file under tests/ except the runner.
+ """Every Python file under each scanned tree except the runner.
- All of tests/, not just test_*.py: a conftest or a tests/_shared helper that spawns
+ All of each tree, not just test_*.py: a conftest or a tests/_shared helper that spawns
pwsh puts every file that imports it back in the race, and would be invisible to a
- scan keyed on the filename.
+ scan keyed on the filename. Each root is asserted non-empty separately, so a tree that
+ moves takes this guard red rather than quietly dropping out of it.
"""
- files = sorted(p for p in TESTS_ROOT.rglob("*.py") if p != _RUNNER)
- assert files, f"no Python files under {TESTS_ROOT} -- did the directory move?"
- return files
+ files: list[Path] = []
+ for root in _SCAN_ROOTS:
+ found = sorted(p for p in root.rglob("*.py") if p != _RUNNER)
+ assert found, f"no Python files under {root} -- did the directory move?"
+ files.extend(found)
+ return sorted(files)
def _is_pwsh_executable(text: str) -> bool:
@@ -236,12 +249,12 @@ def direct_pwsh_calls(path: Path) -> list[tuple[int, str]]:
def scan_tests() -> dict[str, list[tuple[int, str]]]:
- """{path relative to tests/: [(lineno, callee), ...]} over the whole suite."""
+ """{path relative to the repo root: [(lineno, callee), ...]} over every scanned tree."""
offenders = {}
for path in _scanned_files():
calls = direct_pwsh_calls(path)
if calls:
- offenders[path.relative_to(TESTS_ROOT).as_posix()] = calls
+ offenders[path.relative_to(REPO_ROOT).as_posix()] = calls
return offenders
@@ -262,7 +275,7 @@ class TestEveryPwshCallUsesTheSharedRunner:
"and can die at startup with `Stack overflow.` or "
"`System.IO.FileLoadException: The given assembly name was invalid`:\n"
+ "\n".join(
- f" tests/{rel}:{lineno}: {callee}(...)"
+ f" {rel}:{lineno}: {callee}(...)"
for rel, calls in sorted(offenders.items())
for lineno, callee in calls
)
@@ -271,11 +284,27 @@ class TestEveryPwshCallUsesTheSharedRunner:
"add it to _ALLOWED_DIRECT_PWSH_CALLS with the reason."
)
+ def test_the_scan_reaches_the_backend_test_tree(self):
+ """The scope this guard silently lacked, pinned so it cannot be lost again.
+
+ studio/backend/tests/test_setup_llama_cpp_backend.py spawned pwsh directly and
+ this guard never saw it, because the scan was rooted at tests/ alone; the bill
+ came in as SIGABRT in the Backend-CI "rest" shard instead. Checking that the root
+ is listed is not enough on its own -- a root contributing no files would pass
+ that -- so this checks a file from under it is really in the scanned set.
+ """
+ backend = REPO_ROOT / "studio" / "backend" / "tests"
+ assert backend in _SCAN_ROOTS, "the backend test tree dropped off the scan roots"
+ scanned = _scanned_files()
+ assert any(
+ p.is_relative_to(backend) for p in scanned
+ ), f"no file under {backend} was scanned"
+
@pytest.mark.parametrize("rel", sorted(_ALLOWED_DIRECT_PWSH_CALLS))
def test_every_allowlist_entry_is_still_needed(self, rel):
"""An allowlist that outlives its call sites is a claim nobody rechecks. This
fails once the file stops spawning PowerShell directly, or moves away."""
- path = TESTS_ROOT / rel
+ path = REPO_ROOT / rel
assert path.is_file(), f"allowlisted {rel} does not exist; drop the entry"
assert direct_pwsh_calls(path), (
f"{rel} no longer spawns PowerShell directly, so its "
diff --git a/tests/test_windows_amd_gpu_scan_fallback.py b/tests/test_windows_amd_gpu_scan_fallback.py
index cf2ea118e41..aa0506af4ee 100644
--- a/tests/test_windows_amd_gpu_scan_fallback.py
+++ b/tests/test_windows_amd_gpu_scan_fallback.py
@@ -524,7 +524,9 @@ def test_the_installer_and_setup_agree_on_which_adapter_is_active(tmp_path):
# ── runtime: install.ps1 leaves the caller's environment as it found it ───────────────────────
-# The block's fifteen save/restore pairs bar the ROCm handoff, which the arch parametrisation drives.
+# The block's nineteen save/restore pairs bar the ROCm handoff, which the arch parametrisation
+# drives. Kept in step with install.ps1 by test_every_saved_variable_in_the_block_is_covered:
+# a save added there and not named here fails that test rather than going quietly uncovered.
_CALLER_ENV_NAMES = (
"SKIP_STUDIO_BASE",
"UNSLOTH_STUDIO_HOME",
@@ -540,6 +542,15 @@ _CALLER_ENV_NAMES = (
"UNSLOTH_LOCAL_LLAMA_CPP_DIR",
"UNSLOTH_INSTALL_ROLLBACK_MANAGED",
"UNSLOTH_SETUP_PYTHON",
+ # The four Windows-on-ARM facts install.ps1 hands setup.ps1 about the torch it just
+ # resolved. Restored from a TABLE rather than from four written-out if/else arms, which
+ # is why they need naming here: the runtime cases below are the only thing that proves
+ # the table is consumed, and a table is exactly the shape where one wrong index restores
+ # every one of the four from the same save.
+ "UNSLOTH_WOA_HAS_TORCHAUDIO",
+ "UNSLOTH_WOA_TORCH_PRERELEASE",
+ "UNSLOTH_WOA_SELECTED_TORCH_INDEX",
+ "UNSLOTH_WOA_PYPI_PROVIDED",
)
# Distinct per variable, or a finally restoring everything from the wrong save reads as a pass.
@@ -857,6 +868,68 @@ def test_every_save_sits_above_the_handoff_try():
)
+#: `$env:NAME = $previousX`, the spelling the finally used when every restore was written out.
+_RESTORE_INLINE = re.compile(r"\$env:(\w+) = \$previous\w+")
+#: `@("NAME", $hadPreviousX, $previousY)`, one row of a table the finally walks. Added for the
+#: four UNSLOTH_WOA_* variables, whose four if/else arms were identical bar the names.
+_RESTORE_TABLE_ROW = re.compile(
+ r"""@\(\s*["'](\w+)["']\s*,\s*\$hadPrevious\w+\s*,\s*\$previous\w+\s*\)"""
+)
+#: What consumes such a table. Without it the rows are data nobody reads.
+_RESTORE_TABLE_APPLY = re.compile(r"""Set-Item\s+["']Env:\$\(""")
+
+
+def _restored_names(block: str) -> set[str]:
+ """Every variable the finally puts back, in either spelling install.ps1 uses.
+
+ A regex that knew only `$env:NAME = $previousX` read the four UNSLOTH_WOA_* restores as
+ absent and called a correct block broken (#10282 landed them as a table and this file said
+ "saved but never restored"). Worse than the noise: had the table genuinely gone missing, the
+ same blind regex would have reported it identically, so the check could not tell the two
+ apart. Both spellings are recognised here, and a table only counts when something walks it --
+ rows nobody consumes restore nothing, and that is the failure this is guarding against.
+ """
+ names = set(_RESTORE_INLINE.findall(block))
+ rows = set(_RESTORE_TABLE_ROW.findall(block))
+ if rows:
+ assert _RESTORE_TABLE_APPLY.search(block), (
+ "the finally carries a restore table for "
+ f'{sorted(rows)} but nothing walks it with Set-Item "Env:$(...)", so those '
+ "variables are left exactly as install.ps1 set them for the child"
+ )
+ names |= rows
+ return names
+
+
+def test_the_restore_reader_sees_both_spellings_and_no_others():
+ """The reader above is what stands between a real leak and a green run, so it gets rows.
+
+ Written as a table rather than against install.ps1 so it still says which spelling broke
+ when the installer is rewritten, and so the negative rows -- text that must NOT read as a
+ restore -- can be stated at all.
+ """
+ inline = " $env:SKIP_STUDIO_BASE = $previousSkipStudioBase\n"
+ table = (
+ " foreach ($_p in @(\n"
+ ' @("UNSLOTH_WOA_HAS_TORCHAUDIO", $hadPreviousA, $previousA),\n'
+ ' @("UNSLOTH_WOA_PYPI_PROVIDED", $hadPreviousB, $previousB))) {\n'
+ ' if ($_p[1]) { Set-Item "Env:$($_p[0])" $_p[2] }\n'
+ " }\n"
+ )
+ assert _restored_names(inline) == {"SKIP_STUDIO_BASE"}
+ assert _restored_names(table) == {"UNSLOTH_WOA_HAS_TORCHAUDIO", "UNSLOTH_WOA_PYPI_PROVIDED"}
+ assert _restored_names(inline + table) == {
+ "SKIP_STUDIO_BASE",
+ "UNSLOTH_WOA_HAS_TORCHAUDIO",
+ "UNSLOTH_WOA_PYPI_PROVIDED",
+ }
+ # A SAVE is not a restore, in either direction of the assignment.
+ assert _restored_names(" $previousSkipStudioBase = $env:SKIP_STUDIO_BASE\n") == set()
+ # A table nobody walks restores nothing, and saying so is the whole point of the apply check.
+ with pytest.raises(AssertionError, match = "nothing walks it"):
+ _restored_names(table.split(" if (")[0])
+
+
def test_every_saved_variable_in_the_block_is_covered():
"""_CALLER_ENV checked against the source, so a save added to the block names the variable
whose restore nothing exercises. UV_CACHE_DIR, TMP and TEMP are out of scope by construction:
@@ -867,7 +940,7 @@ def test_every_saved_variable_in_the_block_is_covered():
saved = set(re.findall(r"\$previous\w+ = \$env:(\w+)", block))
# The restore side closes the anchor hole: a save PREPENDED above the anchor is invisible to
# any save-side check, but its restore cannot escape the finally.
- restored = set(re.findall(r"\$env:(\w+) = \$previous\w+", block))
+ restored = _restored_names(block)
assert restored == covered, (
"the block restores variables this file does not claim to cover: "
f"{sorted(restored - covered)} (a save prepended above the slice anchor looks like this); "