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.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Stop 19 test files racing on one PowerShell startup cache (#9371)
Daniel Han827d25931b75
diff --git a/tests/_shared/unsloth_pwsh_runner.py b/tests/_shared/unsloth_pwsh_runner.pynew file mode 100644index 00000000000..d99bab81825--- /dev/null+++ b/tests/_shared/unsloth_pwsh_runner.py@@ -0,0 +1,205 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""One `pwsh` runner for every test that shells out to PowerShell, so an interpreter+that dies is reported as an interpreter that died.++Backend CI run 32341628757 on `1c3dde199` finished `284 failed, 8498 passed` and every+one of the 284 was a `pwsh` subprocess ending `died with <Signals.SIGABRT: 6>`, spread+over 19 files that all read as Windows-installer regressions. They were not. The three+tests in that run that assert on `returncode` instead of passing `check = True` kept+pwsh's own stderr, and it says:++ AssertionError: "cd '/tmp/.../me'" failed: 'Stack overflow.\\n'++`Stack overflow.` is the .NET runtime's failfast: the CLR cannot unwind a blown stack, so+it prints that one line and calls `abort()`, which is the SIGABRT. It is a crash *of the+interpreter at startup*, matching PowerShell/PowerShell#24461 ("Stack overflow error when+starting pwsh with -Command"), and it is independent of what we asked pwsh to run -- the+script that produced the line above is a bare `cd`, while its neighbours in the same run+are 60-line installer excerpts.++The reason this is worth a shared module rather than 19 private copies is attribution, not+tidiness. `subprocess.run(..., check = True)` renders a dead interpreter as+`CalledProcessError` carrying the whole script, which reads exactly like the script having+failed, so a runner-level crash costs a full log download and a per-file triage before+anyone can see it was never our code. The crash is also not rare enough to ignore: of the+1409 tests in those 19 files roughly 20% died, interleaved with passes throughout the+12-minute run, which is a per-process coin flip rather than one bad moment.++Two rules, both load-bearing:++ * **A signal is not a verdict.** A shell killed by a signal did not finish its script, so+ it returned no answer either way. That is what makes retrying it honest -- there is no+ failure being papered over yet -- and it is why the crash test is the signal itself+ rather than a message: it needs no per-call-site marker and cannot misread output.+ * **A normal exit is returned untouched, first time, whatever its code.** A pwsh that runs+ to completion and gives the WRONG answer is a real regression and must fail with its own+ message. Nothing here retries it, and nothing here rewrites it.++Generalised from `_run_pwsh` in tests/studio/test_install_phase_timing.py, which handles a+second, signal-free shape: pwsh printing its "The PowerShell process will exit" banner and+exiting normally with nothing on stdout. That one cannot be spotted from the exit status, so+it stays a text match, and a caller that can name a marker its script prints on success can+pass `verdict = ` to say "this run reached a conclusion" without relying on either.+"""++from __future__ import annotations++import atexit+import os+import shutil+import signal+import subprocess+import tempfile++# pwsh aborting mid-flight prints this and leaves stdout empty while still exiting through+# the normal path, so unlike the SIGABRT case there is no signal to key on.+PWSH_CRASH_BANNER = "The PowerShell process will exit"++# Resolved once. `None` on a box with no PowerShell, which is what the skipif guards read.+PWSH = shutil.which("pwsh") or shutil.which("powershell")+++# --------------------------------------------------------------------------------------+# Why the crash happens, and the one-line change that stops it+# --------------------------------------------------------------------------------------+# Every `-NonInteractive` startup reads and rewrites an ~83 KB+# $XDG_CACHE_HOME/powershell/StartupProfileData-NonInteractive, and XDG_CACHE_HOME defaults+# to $HOME/.cache. Under `-n 4` all four xdist workers share one $HOME, so the whole job's+# pwsh processes race on that single file, and a startup that deserialises a half-written+# one dies before it reaches our script.+#+# Measured on this repo's suite shape, 4000 startups per arm:+#+# shared cache dir 7/4000 died -- returncodes {-11: 3, -6: 4}, stderr 'Stack overflow.'+# and 'The PowerShell process will exit. Unhandled exception.+# System.IO.FileLoadException: The given assembly name ...'+# private cache dirs 0/4000+#+# That reproduces BOTH crash shapes this repo has hit -- the SIGABRT that made run+# 32341628757 red and the exit-banner that `_run_pwsh` in test_install_phase_timing.py was+# written for -- and the FileLoadException names the torn cache outright. It is also the+# independent confirmation from CI itself: of the pwsh-heavy test files in that run, exactly+# one had zero failures, tests/test_windows_amd_gpu_scan_fallback.py, and it is the only one+# that hands its child a private HOME (`{"PATH": ..., "HOME": str(tmp_path)}`) and so never+# joined the race, across ~80 startups where a 20% rate predicts ~16 failures.+#+# So the fix is to stop sharing the file rather than to serialise access to it: one cache+# directory per xdist worker. Workers run their tests one at a time, so within a worker the+# startups are sequential and the cache still does its job warm; across workers the+# directories are disjoint and there is nothing left to race on. This is why the runner does+# not bound pwsh concurrency with a lock and does not ask for `-n 4` to be given up: the+# contended resource is removed, not rationed.+_CACHE_ROOT = None+++def _pwsh_cache_dir() -> str:+ """A cache directory private to this xdist worker, fresh for this pytest session.++ Fresh rather than a stable path under TMPDIR: a cache torn by a previous run would+ otherwise persist and poison every later session on the same box, which is the failure+ this whole module exists to remove.+ """+ global _CACHE_ROOT+ if _CACHE_ROOT is None:+ worker = os.environ.get("PYTEST_XDIST_WORKER", "master")+ _CACHE_ROOT = tempfile.mkdtemp(prefix = f"unsloth-pwsh-cache-{worker}-")+ atexit.register(shutil.rmtree, _CACHE_ROOT, True)+ return _CACHE_ROOT+++class PwshInterpreterCrash(AssertionError):+ """The interpreter died before producing a verdict. Says nothing about the script."""+++def _crash_reason(proc: subprocess.CompletedProcess) -> str | None:+ """Why this run produced no verdict, or None if it produced one."""+ if proc.returncode < 0:+ # Popen reports "killed by signal N" as -N. .NET's stack-overflow failfast is+ # SIGABRT; a SIGSEGV or a SIGKILL from the OOM killer would land here too, and all+ # three mean the same thing to us: the script did not run to its end.+ try:+ name = signal.Signals(-proc.returncode).name+ except ValueError:+ name = f"signal {-proc.returncode}"+ return f"killed by {name}"+ # Only inspectable when the caller captured the streams; a call site that streams to the+ # console gets the signal check alone, which is the case that actually bit CI. The+ # byte-level tests capture without `text = True`, so the banner is searched for in+ # whichever form the caller asked for rather than assuming str.+ captured = [stream for stream in (proc.stdout, proc.stderr) if stream]+ if any(isinstance(stream, bytes) for stream in captured):+ streams = b"".join(+ stream if isinstance(stream, bytes) else stream.encode("utf-8", errors = "replace")+ for stream in captured+ ).decode("utf-8", errors = "replace")+ else:+ streams = "".join(captured)+ if PWSH_CRASH_BANNER in streams:+ return "self-aborted with the PowerShell crash banner"+ return None+++def run_pwsh(+ argv: list[str],+ *,+ attempts: int = 3,+ verdict: str | None = None,+ check: bool = False,+ **kwargs,+) -> subprocess.CompletedProcess:+ """`subprocess.run(argv)`, retrying only a run that crashed without answering.++ `argv` is the complete command the call site already built, pwsh path included, so+ migrating a test is a one-word change and no invocation flags move.++ `attempts` defaults to 3 because the observed crash is an independent per-process event+ at roughly p = 0.2: one retry leaves 4% of invocations still red, two leaves 0.8%, which+ across ~1400 tests is the difference between a red run most days and one every few+ months. Retries are consecutive and unslept -- the trigger is process startup, not a+ resource that frees up over time.++ `verdict`, when given, is a marker the script prints once it has reached a conclusion.+ Its presence in stdout ends the loop immediately even if the run also looks crashy,+ which keeps a script that legitimately mentions the banner from being retried.++ `check` is honoured after the loop, not passed down, because `subprocess.run` would+ raise `CalledProcessError` on the crashing attempt and lose the retry.+ """+ if attempts < 1:+ raise ValueError(f"attempts must be >= 1, got {attempts}")++ # Redirect only pwsh's own startup cache, leaving every other variable as the call site+ # meant it: `env = None` still means "inherit", and a hermetic env dict still gets+ # exactly the keys it listed plus this one. See _pwsh_cache_dir for the measurement.+ env = kwargs.get("env")+ env = dict(os.environ if env is None else env)+ env["XDG_CACHE_HOME"] = _pwsh_cache_dir()+ kwargs["env"] = env++ proc = None+ reason = None+ for _ in range(attempts):+ proc = subprocess.run(argv, **kwargs)+ if verdict is not None and verdict in (proc.stdout or ""):+ break+ reason = _crash_reason(proc)+ if reason is None:+ break+ else:+ raise PwshInterpreterCrash(+ f"pwsh itself {reason} on all {attempts} attempts without running the script to "+ f"completion, so this run says nothing about what the script does -- it is the "+ f"interpreter dying, not an assertion failing. A `Stack overflow.` on stderr is "+ f".NET's failfast at pwsh startup (PowerShell/PowerShell#24461) and is a property "+ f"of the runner, not of this repository.\n"+ f"argv: {argv!r}\n"+ f"returncode: {proc.returncode}\n"+ f"stdout: {proc.stdout!r}\n"+ f"stderr: {proc.stderr!r}"+ )++ if check:+ proc.check_returncode()+ return procdiff --git a/tests/conftest.py b/tests/conftest.pyindex e7525d4d66d..865613679cc 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -29,6 +29,19 @@ for _up in _iso.parents:break# -----------------------------------------------------------------------------------+# --- shared test helpers on sys.path -----------------------------------------------+# tests/_shared holds no package marker and pytest only puts a *test file's* own+# directory on sys.path, so tests/python/, tests/studio/install/ and tests/security/+# cannot reach it by import. Adding it here (this conftest is collected for anything+# under tests/) is what lets all four levels share one module rather than each growing+# a private copy -- see tests/_shared/unsloth_pwsh_runner.py for the case that forced it.+import sys as _sys # noqa: E402++_shared_dir = _iso.parent / "_shared"+if _shared_dir.is_dir() and str(_shared_dir) not in _sys.path:+ _sys.path.insert(0, str(_shared_dir))+# -----------------------------------------------------------------------------------+import importlib.utilimport osimport sysdiff --git a/tests/python/test_windows_arm64_python_choice.py b/tests/python/test_windows_arm64_python_choice.pyindex 89546e7ac42..12409b83df6 100644--- a/tests/python/test_windows_arm64_python_choice.py+++ b/tests/python/test_windows_arm64_python_choice.py@@ -15,11 +15,12 @@ from __future__ import annotationsimport osimport reimport shutil-import subprocessfrom pathlib import Pathimport pytest+from unsloth_pwsh_runner import run_pwsh+REPO_ROOT = Path(__file__).resolve().parents[2]INSTALL_PS1 = REPO_ROOT / "install.ps1"@@ -114,7 +115,10 @@ if ($found) {{ Write-Output "$($found.Version)|$($found.Arch)" }} else {{ Write-def _pwsh(script: str) -> str:- result = subprocess.run(+ # Every ARM64 case below is decided by the one "version|arch" line this run prints,+ # and check = True means a pwsh that aborts at startup would surface as the resolver+ # block itself throwing.+ result = run_pwsh(["pwsh", "-NoProfile", "-NonInteractive", "-Command", script],check = True,capture_output = True,diff --git a/tests/python/test_windows_git_gate.py b/tests/python/test_windows_git_gate.pyindex 678a95c7bfe..7ff8b274353 100644--- a/tests/python/test_windows_git_gate.py+++ b/tests/python/test_windows_git_gate.py@@ -7,11 +7,12 @@ from __future__ import annotationsimport osimport shutil-import subprocessfrom pathlib import Pathimport pytest+from unsloth_pwsh_runner import run_pwsh+REPO_ROOT = Path(__file__).resolve().parents[2]SETUP_PS1 = REPO_ROOT / "studio" / "setup.ps1"@@ -68,7 +69,10 @@ Write-Output $gitNeededdef _needs_git(env: dict[str, str]) -> bool:merged = {k: v for k, v in os.environ.items() if not k.startswith(("UNSLOTH_", "STUDIO_"))}merged.update(env)- result = subprocess.run(+ # run_pwsh, not subprocess.run: every case in this file goes through here, so a pwsh+ # that died at startup would come back as $gitNeeded computing the wrong answer for+ # one environment. See tests/_shared/unsloth_pwsh_runner.py.+ result = run_pwsh(["pwsh", "-NoProfile", "-NonInteractive", "-Command", _script()],check = True,capture_output = True,diff --git a/tests/python/test_windows_installer_addtype_fallback.py b/tests/python/test_windows_installer_addtype_fallback.pyindex b5d8acce652..e336a2327ad 100644--- a/tests/python/test_windows_installer_addtype_fallback.py+++ b/tests/python/test_windows_installer_addtype_fallback.py@@ -28,6 +28,7 @@ import timefrom pathlib import Pathimport pytest+from unsloth_pwsh_runner import run_pwshREPO_ROOT = Path(__file__).resolve().parents[2]@@ -89,7 +90,11 @@ def _run_powershell(script: str, env: dict[str, str] | None = None) -> subprocesos.close(handle)try:Path(name).write_text(script, encoding = "utf-8-sig")- return subprocess.run(+ # run_pwsh, not subprocess.run: every test in this file reads this result as+ # "did the Add-Type fallback chain survive", and an interpreter that aborted at+ # startup produces the same empty stdout as a helper that never ran its fallback.+ # See tests/_shared/unsloth_pwsh_runner.py.+ return run_pwsh(["pwsh", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-File", name],capture_output = True,text = True,diff --git a/tests/python/test_windows_no_torch_setup.py b/tests/python/test_windows_no_torch_setup.pyindex d16e52d16bd..7f078e29f29 100644--- a/tests/python/test_windows_no_torch_setup.py+++ b/tests/python/test_windows_no_torch_setup.py@@ -9,10 +9,10 @@ import jsonimport osimport reimport shutil-import subprocessfrom pathlib import Pathimport pytest+from unsloth_pwsh_runner import run_pwshREPO_ROOT = Path(__file__).resolve().parents[2]@@ -149,7 +149,10 @@ def test_no_torch_mode_survives_a_studio_update(tmp_path, env_value, manifest, mif env_value is not None:env["UNSLOTH_NO_TORCH"] = env_value- result = subprocess.run(+ # run_pwsh, not subprocess.run: check = True turns a pwsh that aborted at startup into+ # a CalledProcessError quoting the whole no-torch resolution block, which reads as that+ # block picking the wrong mode. See tests/_shared/unsloth_pwsh_runner.py.+ result = run_pwsh(["pwsh","-NoProfile",diff --git a/tests/python/test_windows_python_313_8_screen.py b/tests/python/test_windows_python_313_8_screen.pyindex 7bc51c46401..f942a1f6260 100644--- a/tests/python/test_windows_python_313_8_screen.py+++ b/tests/python/test_windows_python_313_8_screen.py@@ -24,11 +24,12 @@ import osimport reimport shutilimport stat-import subprocessfrom pathlib import Pathimport pytest+from unsloth_pwsh_runner import run_pwsh+REPO_ROOT = Path(__file__).resolve().parents[2]INSTALL_PS1 = REPO_ROOT / "install.ps1"@@ -92,7 +93,9 @@ $result = Remove-SkippedPython ({candidate})if ($null -eq $result) {{ Write-Output "RESULT: rejected" }}else {{ Write-Output "RESULT: kept" }}"""- completed = subprocess.run(+ # The whole verdict is the single RESULT line this script prints, so a pwsh that+ # aborts at startup would read as a screen that reached the opposite conclusion.+ completed = run_pwsh(["pwsh", "-NoProfile", "-NonInteractive", "-Command", script],capture_output = True,text = True,@@ -135,7 +138,9 @@ $result = Remove-SkippedPython (@{{ Version = "3.13"; Path = "{missing}" }})if ($null -eq $result) {{ Write-Output "RESULT: rejected" }}else {{ Write-Output "RESULT: kept" }}"""- completed = subprocess.run(+ # This case asserts the screen KEEPS an interpreter it could not probe, so an+ # interpreter that dies would masquerade as the screen wrongly rejecting it.+ completed = run_pwsh(["pwsh", "-NoProfile", "-NonInteractive", "-Command", script],capture_output = True,text = True,@@ -261,7 +266,9 @@ $found = Find-CompatiblePythonif ($null -eq $found) {{ Write-Output "RESULT: none" }}else {{ Write-Output "RESULT: $($found.Version)" }}"""- completed = subprocess.run(+ # The caller scrapes the resolver's chosen minor out of stdout; a crashed pwsh+ # leaves nothing to scrape and would fail as if Find-CompatiblePython went silent.+ completed = run_pwsh(["pwsh", "-NoProfile", "-NonInteractive", "-Command", script],capture_output = True,text = True,@@ -324,7 +331,9 @@ $found = Find-CompatiblePythonif ($null -eq $found) {{ Write-Output "RESULT: none" }}else {{ Write-Output "RESULT: $($found.Version)" }}"""- completed = subprocess.run(+ # -NoTorch must leave 3.13.8 in place, and dying before the RESULT line is printed+ # is indistinguishable here from the screen having removed it.+ completed = run_pwsh(["pwsh", "-NoProfile", "-NonInteractive", "-Command", script],capture_output = True,text = True,diff --git a/tests/python/test_windows_python_venv_hardening.py b/tests/python/test_windows_python_venv_hardening.pyindex 82ec1b7c725..fe212d27cf1 100644--- a/tests/python/test_windows_python_venv_hardening.py+++ b/tests/python/test_windows_python_venv_hardening.py@@ -15,6 +15,8 @@ from pathlib import Pathimport pytest+from unsloth_pwsh_runner import run_pwsh+REPO_ROOT = Path(__file__).resolve().parents[2]INSTALL_PS1 = REPO_ROOT / "install.ps1"@@ -45,7 +47,11 @@ def _link_dir(link: Path, target: Path) -> None:def _run_powershell(shell: str, script: str, env: dict[str, str]) -> str:- result = subprocess.run(+ # run_pwsh, not subprocess.run: $shell is always pwsh or powershell (see POWERSHELLS),+ # and every venv and rollback case in this file reads its stdout, so an interpreter that+ # died at startup would surface as install.ps1 losing half a moved environment.+ # See tests/_shared/unsloth_pwsh_runner.py.+ result = run_pwsh([shell, "-NoProfile", "-NonInteractive", "-Command", script],check = True,capture_output = True,diff --git a/tests/python/test_windows_setup_output_encoding.py b/tests/python/test_windows_setup_output_encoding.pyindex 4d8a91b681f..8f280b4d0ea 100644--- a/tests/python/test_windows_setup_output_encoding.py+++ b/tests/python/test_windows_setup_output_encoding.py@@ -56,6 +56,8 @@ from pathlib import Pathimport pytest+from unsloth_pwsh_runner import run_pwsh+REPO_ROOT = Path(__file__).resolve().parents[2]SETUP_PS1 = REPO_ROOT / "studio" / "setup.ps1"@@ -180,7 +182,10 @@ def _run_capturing_bytes(argv = base + ["-Command", f"& '{literal}' *>&1"]else:argv = base + ["-File", str(tmp)]- proc = subprocess.run(argv, stdout = subprocess.PIPE, stderr = subprocess.PIPE, timeout = 180)+ # run_pwsh, not subprocess.run: the byte-level cases read this stdout as the setup+ # log, and an interpreter that aborted leaves an empty or truncated stream, which+ # reads as the banner being mangled or lost. See tests/_shared/unsloth_pwsh_runner.py.+ proc = run_pwsh(argv, stdout = subprocess.PIPE, stderr = subprocess.PIPE, timeout = 180)assert proc.returncode == 0, proc.stderr.decode("utf-8", errors = "replace")return proc.stdoutfinally:@@ -644,7 +649,11 @@ def _run_console_less(path: Path, source: str | None = None) -> tuple[int, bytesprobe = Path(workdir) / f"{path.stem}_console_less_probe.ps1"text = _console_less_probe(path) if source is None else sourceprobe.write_bytes(text.replace("\n", "\r\n").encode("ascii"))- proc = subprocess.run(+ # run_pwsh, not subprocess.run: the console-less cases are phrased as "this run+ # exited non-zero having printed almost nothing", which is also what an aborted+ # interpreter looks like, so the two must not be confused. The retry covers 5.1+ # here as well. See tests/_shared/unsloth_pwsh_runner.py.+ proc = run_pwsh([str(_WINDOWS_POWERSHELL), *TAURI_FLAGS, "-File", str(probe)],stdout = subprocess.PIPE,stderr = subprocess.PIPE,diff --git a/tests/python/test_windows_vcredist_download_tls.py b/tests/python/test_windows_vcredist_download_tls.pyindex 146a9ae1044..9ddf1845fff 100644--- a/tests/python/test_windows_vcredist_download_tls.py+++ b/tests/python/test_windows_vcredist_download_tls.py@@ -6,11 +6,12 @@from __future__ import annotationsimport shutil-import subprocessfrom pathlib import Pathimport pytest+from unsloth_pwsh_runner import run_pwsh+REPO_ROOT = Path(__file__).resolve().parents[2]SETUP_PS1 = REPO_ROOT / "studio" / "setup.ps1"@@ -59,7 +60,10 @@ Write-Output "AFTER=$([System.Net.ServicePointManager]::SecurityProtocol)"def _run(starting_protocol: str) -> dict[str, str]:- result = subprocess.run(+ # The TLS assertions read the BEFORE/DURING/AFTER lines this script prints, so an+ # interpreter that never got as far as running the download block would look like+ # setup.ps1 failing to negotiate TLS 1.2 at all.+ result = run_pwsh(["pwsh", "-NoProfile", "-NonInteractive", "-Command", _script(starting_protocol)],check = True,capture_output = True,diff --git a/tests/python/test_windows_xformers_installer.py b/tests/python/test_windows_xformers_installer.pyindex ff6d6b48245..962adf3049a 100644--- a/tests/python/test_windows_xformers_installer.py+++ b/tests/python/test_windows_xformers_installer.py@@ -14,11 +14,12 @@ from __future__ import annotationsimport reimport shutil-import subprocessfrom pathlib import Pathimport pytest+from unsloth_pwsh_runner import run_pwsh+REPO_ROOT = Path(__file__).resolve().parents[2]INSTALL_PS1 = REPO_ROOT / "install.ps1"@@ -53,7 +54,10 @@ def _selector_harness() -> str:def _run_pwsh(script: str) -> str:- result = subprocess.run(+ # run_pwsh, not subprocess.run: a pwsh killed by a signal never ran this script, and+ # `check = True` would report that as a CalledProcessError carrying the whole excerpt,+ # which reads as the selector being wrong. See tests/_shared/unsloth_pwsh_runner.py.+ result = run_pwsh(["pwsh", "-NoProfile", "-NonInteractive", "-Command", script],check = True,capture_output = True,diff --git a/tests/security/test_release_desktop_signing_simulation.py b/tests/security/test_release_desktop_signing_simulation.pyindex c9d99a1c403..348299c225a 100644--- a/tests/security/test_release_desktop_signing_simulation.py+++ b/tests/security/test_release_desktop_signing_simulation.py@@ -23,13 +23,14 @@ import http.serverimport osimport pathlibimport shutil-import subprocessimport sysimport threadingimport pytestimport yaml+from unsloth_pwsh_runner import run_pwsh+# Only PATHEXT maps a bare name onto the `.exe` the verify step insists on, so# checks needing a *passing* resolution are skipped off Windows rather than@@ -89,7 +90,10 @@ def write_step_script(directory, name, filename):def run_step(script, env):"""Invoke a step script the way the runner does and return (code, output)."""full = {**os.environ, **env}- result = subprocess.run(+ # Every signing check in this file reads the exit code of this one call, so an+ # interpreter that aborts at startup would look exactly like a step body that+ # failed closed -- the opposite of what the test claims to have proven.+ result = run_pwsh(["pwsh", "-NoProfile", "-Command", f". '{script}'"],capture_output = True,text = True,diff --git a/tests/studio/install/test_install_llama_prebuilt_logic.py b/tests/studio/install/test_install_llama_prebuilt_logic.pyindex 4d74b9a2e64..11e15331d71 100644--- a/tests/studio/install/test_install_llama_prebuilt_logic.py+++ b/tests/studio/install/test_install_llama_prebuilt_logic.py@@ -13,6 +13,7 @@ import zipfilefrom pathlib import Pathimport pytest+from unsloth_pwsh_runner import run_pwshPACKAGE_ROOT = Path(__file__).resolve().parents[3]@@ -4400,7 +4401,11 @@ def _run_setup_ps1_routing()script_path = tmp_path / "routing.ps1"script_path.write_text(script, encoding = "utf-8")- completed = subprocess.run(+ # run_pwsh, not subprocess.run: this helper feeds every routing case below, and a pwsh+ # killed at startup returns rc -6 with empty stdout, which the callers would compare+ # against the bash mirror and report as setup.ps1 routing the exit code wrongly.+ # See tests/_shared/unsloth_pwsh_runner.py.+ completed = run_pwsh([shutil.which("pwsh") or "pwsh","-NoProfile",diff --git a/tests/studio/install/test_llama_pr_force_and_source.py b/tests/studio/install/test_llama_pr_force_and_source.pyindex 8d896609240..99086d314d3 100644--- a/tests/studio/install/test_llama_pr_force_and_source.py+++ b/tests/studio/install/test_llama_pr_force_and_source.py@@ -8,6 +8,10 @@ from pathlib import Pathimport pytest+# Aliased: this module already has its own `run_pwsh` fragment helper, which now calls the+# shared runner rather than subprocess.run.+from unsloth_pwsh_runner import run_pwsh as run_pwsh_retrying+PACKAGE_ROOT = Path(__file__).resolve().parents[3]SETUP_SH = PACKAGE_ROOT / "studio" / "setup.sh"SETUP_PS1 = PACKAGE_ROOT / "studio" / "setup.ps1"@@ -48,7 +52,11 @@ def run_pwsh(run_env["NO_COLOR"] = "1"if env:run_env.update(env)- return subprocess.run(+ # The shared runner, not subprocess.run: the PR_FORCE cases below read stdout for the+ # promoted ref and the fixed ggml-org source, and a pwsh killed at startup yields empty+ # stdout that looks like setup.ps1 promoting nothing.+ # See tests/_shared/unsloth_pwsh_runner.py.+ return run_pwsh_retrying([PWSH, "-NoProfile", "-Command", script],capture_output = True,text = True,diff --git a/tests/studio/install/test_rocm_support.py b/tests/studio/install/test_rocm_support.pyindex 5e0a3e953c8..db067b5604e 100644--- a/tests/studio/install/test_rocm_support.py+++ b/tests/studio/install/test_rocm_support.py@@ -15,6 +15,7 @@ from types import SimpleNamespacefrom unittest.mock import MagicMock, mock_open, patch, PropertyMockimport pytest+from unsloth_pwsh_runner import run_pwsh# ── Load modules under test ──────────────────────────────────────────────────@@ -4057,7 +4058,11 @@ $adapters = @(($adapters | Where-Object { ($null -eq $_.ConfigManagerErrorCode) -or ($_.ConfigManagerErrorCode -eq 0) }).Name"""- out = subprocess.run(+ # run_pwsh, not subprocess.run: this asserts the WMI adapter filter is valid+ # PowerShell, so an interpreter that died before parsing it would be recorded as+ # the filter expression itself being malformed.+ # See tests/_shared/unsloth_pwsh_runner.py.+ out = run_pwsh(["pwsh", "-NoProfile", "-NonInteractive", "-Command", script],check = True,capture_output = True,@@ -4203,7 +4208,11 @@ foreach ($v in @('$script:ShadowingIntegratedGfx', '$archFamilyMap')) {merged = {k: v for k, v in os.environ.items() if not k.endswith("_VISIBLE_DEVICES")}merged["SETUP_PS1"] = str(PACKAGE_ROOT / "studio" / "setup.ps1")merged.update(env or {})- out = subprocess.run(+ # run_pwsh, not subprocess.run: every Resolve-ShadowingGfxPick case goes through+ # here, and a crashed interpreter returns no stdout at all, which the callers would+ # read as the shadowing pick returning the wrong gfx arch.+ # See tests/_shared/unsloth_pwsh_runner.py.+ out = run_pwsh(["pwsh", "-NoProfile", "-NonInteractive", "-Command", self._HARNESS + body],check = True,capture_output = True,@@ -4280,7 +4289,10 @@ foreach ($v in @('$script:ShadowingIntegratedGfx', '$archFamilyMap')) {)merged = {k: v for k, v in os.environ.items() if not k.endswith("_VISIBLE_DEVICES")}merged["SETUP_PS1"] = str(PACKAGE_ROOT / "studio" / "setup.ps1")- out = subprocess.run(+ # run_pwsh, not subprocess.run: the advisory text is collected from this run's+ # stdout, so a pwsh that aborted at startup would look like substep never naming+ # the real HIP_VISIBLE_DEVICES index. See tests/_shared/unsloth_pwsh_runner.py.+ out = run_pwsh(["pwsh", "-NoProfile", "-NonInteractive", "-Command", harness + body],check = True,capture_output = True,@@ -6334,7 +6346,10 @@ class TestRocmGfxForwarding:)assert line is not None, "$HelperReleaseRepo selection not found in setup.ps1"harness = f"{line}\nWrite-Output $HelperReleaseRepo"- result = subprocess.run(+ # run_pwsh, not subprocess.run: the returncode assertion just below treats a+ # non-zero exit as $HelperReleaseRepo failing to resolve, and a signal-killed pwsh+ # would be blamed the same way. See tests/_shared/unsloth_pwsh_runner.py.+ result = run_pwsh([pwsh, "-NoProfile", "-Command", harness],capture_output = True,text = True,diff --git a/tests/studio/install/test_unsupported_arch_routing_guards_8529.py b/tests/studio/install/test_unsupported_arch_routing_guards_8529.pyindex b7f11c67b98..cd9d95df2bb 100644--- a/tests/studio/install/test_unsupported_arch_routing_guards_8529.py+++ b/tests/studio/install/test_unsupported_arch_routing_guards_8529.py@@ -42,6 +42,7 @@ from pathlib import Pathfrom unittest.mock import patchimport pytest+from unsloth_pwsh_runner import run_pwshPACKAGE_ROOT = Path(__file__).resolve().parents[3]@@ -508,7 +509,10 @@ class TestPowerShellMapEvaluated:f"}}\n"f"if ($archFamilyMap.ContainsKey('gfx1030')) {{ 'CONTROL_OK' }}\n")- out = subprocess.run(+ # run_pwsh, not subprocess.run: the returncode assertion below reads a non-zero exit+ # as $archFamilyMap failing to evaluate, and a signal-killed interpreter would be+ # filed as that same map being broken. See tests/_shared/unsloth_pwsh_runner.py.+ out = run_pwsh(["pwsh", "-NoProfile", "-NonInteractive", "-Command", script],stdout = subprocess.PIPE,stderr = subprocess.DEVNULL,@@ -536,7 +540,10 @@ class TestPowerShellMapEvaluated:f"}}\n"f"if ($_rocmWheelArches -contains 'gfx1030') {{ 'CONTROL_OK' }}\n")- out = subprocess.run(+ # run_pwsh, not subprocess.run: a crashed interpreter prints nothing, so the+ # CONTROL_OK check below would see the positive control missing and report+ # setup.ps1's $_rocmWheelArches as wrong. See tests/_shared/unsloth_pwsh_runner.py.+ out = run_pwsh(["pwsh", "-NoProfile", "-NonInteractive", "-Command", script],stdout = subprocess.PIPE,stderr = subprocess.DEVNULL,@@ -943,7 +950,10 @@ def _ps_unsupported(path: Path, names):f" Write-Output $hit\n"f"}}\n")- out = subprocess.run(+ # run_pwsh, not subprocess.run: this run's stdout is compared line by line against the+ # Python table, so an interpreter that died mid-list would show up as the PowerShell+ # name-to-arch rows disagreeing. See tests/_shared/unsloth_pwsh_runner.py.+ out = run_pwsh(["pwsh", "-NoProfile", "-NonInteractive", "-Command", script],stdout = subprocess.PIPE,stderr = subprocess.DEVNULL,diff --git a/tests/studio/test_install_phase_timing.py b/tests/studio/test_install_phase_timing.pyindex 854e01a0c66..132d35cd53d 100644--- a/tests/studio/test_install_phase_timing.py+++ b/tests/studio/test_install_phase_timing.py@@ -36,6 +36,8 @@ from pathlib import Pathimport pytestimport yaml+from unsloth_pwsh_runner import run_pwsh+REPO = Path(__file__).resolve().parents[2]WORKFLOWS = REPO / ".github" / "workflows"ACTION = REPO / ".github" / "actions" / "install-unsloth-local" / "action.yml"@@ -368,35 +370,28 @@ for _candidate in ("pwsh", "powershell"):continue-# The banner pwsh prints when the interpreter itself dies rather than the script failing.-# Seen on a hosted ubuntu runner mid-run, with completely empty stdout: no "RC=" at all,-# not a wrong one. Read as a normal failure it accuses the pipeline of losing-# $LASTEXITCODE, which is a claim about install.ps1, so a runner hiccup arrives looking-# like a product regression. Distinguish the two.-_PWSH_CRASHED = "The PowerShell process will exit"--def _run_pwsh(script: str, attempts: int = 2):"""Run `script` under pwsh, retrying only an interpreter crash.+ Delegates to the shared `run_pwsh`, which was generalised out of this function: it keeps+ the crash banner (an interpreter that dies mid-run and still exits normally, seen here on+ a hosted ubuntu runner with completely empty stdout) and adds the SIGABRT case this file+ never covered, where .NET failfasts at pwsh startup and the process is killed by a signal+ instead of printing anything at all.+A crash yields no verdict either way, so retrying it is not papering over a failure:there is nothing to paper over yet. A run that reaches `RC=` is returned as-is on thefirst attempt, whatever the value, so a real regression is never retried into green.+ That is what `verdict` says here. `PwshInterpreterCrash` is an `AssertionError`, so an+ exhausted retry loop still surfaces as a failure naming the interpreter rather than+ accusing install.ps1 of losing $LASTEXITCODE through the pipeline."""- proc = None- for _ in range(attempts):- proc = subprocess.run(- [PWSH, "-NoProfile", "-Command", script], capture_output = True, text = True- )- if "RC=" in proc.stdout:- return proc- if _PWSH_CRASHED not in (proc.stdout + proc.stderr):- return proc- raise AssertionError(- f"pwsh itself terminated abnormally on all {attempts} attempts and never reached "- f"the `RC=` line, so this run says nothing about whether $LASTEXITCODE survives "- f"the pipeline. That is the interpreter dying, not install.ps1 losing its exit "- f"code.\nstdout: {proc.stdout!r}\nstderr: {proc.stderr!r}"+ return run_pwsh(+ [PWSH, "-NoProfile", "-Command", script],+ attempts = attempts,+ verdict = "RC=",+ capture_output = True,+ text = True,)diff --git a/tests/studio/test_pwsh_interpreter_crash_attribution.py b/tests/studio/test_pwsh_interpreter_crash_attribution.pynew file mode 100644index 00000000000..1e64725d225--- /dev/null+++ b/tests/studio/test_pwsh_interpreter_crash_attribution.py@@ -0,0 +1,129 @@+# 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 shared pwsh runner must blame the interpreter for a crash and nothing else.++Backend CI run 32341628757 reported one runner-level pwsh failure mode as 284 independent+Windows-installer regressions across 19 files. tests/_shared/unsloth_pwsh_runner.py exists+to stop that, and its value is entirely in which of these two it does to a given run:++ * a shell killed by a signal produced no verdict -> retry, then blame the interpreter;+ * a shell that exited normally produced a verdict -> hand it back untouched, right or wrong.++Getting the second one wrong would turn this helper into a way to retry real regressions+into green, which is strictly worse than the bug it fixes. So both directions are executed+here against a real SIGABRT rather than reviewed.+"""++import json+import os+import subprocess+import sys++import pytest++from unsloth_pwsh_runner import PWSH, PwshInterpreterCrash, run_pwsh++# A SIGABRT is forged with Python rather than pwsh: the real trigger is a .NET startup+# stack overflow we cannot summon on demand, and the helper keys on the signal, not on who+# sent it, so `os.abort()` reproduces exactly the condition CI hit.+#+# PR_SET_DUMPABLE = 0 first, per tests/test_deliberate_crashes_suppress_cores.py. The+# child still dies of SIGABRT, so every verdict below is unchanged; what goes away is+# apport reading a multi-MB core before the child is reaped, on each of the several+# aborts these tests spend. Linux-only, and deliberately not fatal elsewhere: Windows+# has no CDLL(None) and pipes no core anywhere, so failing to arm it there would turn a+# no-op into a lost test.+_ABORT = [+ sys.executable,+ "-c",+ "import ctypes, os, sys; "+ "sys.platform == 'linux' and ctypes.CDLL(None).prctl(4, 0, 0, 0, 0); "+ "os.abort()",+]+_CLEAN_WRONG_ANSWER = [sys.executable, "-c", "print('WRONG'); raise SystemExit(3)"]+++def test_a_signal_death_is_attributed_to_the_interpreter_not_the_assertion():+ """The message must name pwsh dying, and must not read as the script being wrong."""+ with pytest.raises(PwshInterpreterCrash) as excinfo:+ run_pwsh(_ABORT, attempts = 2, capture_output = True, text = True)++ message = str(excinfo.value)+ assert "pwsh itself killed by SIGABRT on all 2 attempts" in message, message+ assert "interpreter dying, not an assertion failing" in message, message+++def test_a_clean_run_with_the_wrong_answer_still_fails_with_its_own_message():+ """The load-bearing negative. Exit 3 is a verdict, so it is returned as-is, once."""+ proc = run_pwsh(_CLEAN_WRONG_ANSWER, attempts = 3, capture_output = True, text = True)+ assert proc.returncode == 3+ assert proc.stdout.strip() == "WRONG"++ # ...and `check` still raises the ordinary CalledProcessError a caller expects, so+ # migrating a `subprocess.run(..., check = True)` call site changes no failure text.+ with pytest.raises(subprocess.CalledProcessError):+ run_pwsh(_CLEAN_WRONG_ANSWER, check = True, capture_output = True, text = True)+++def test_a_clean_run_is_not_retried():+ """A regression retried three times is a regression that can flake green."""+ calls = []+ real_run = subprocess.run++ def counting_run(argv, **kwargs):+ calls.append(argv)+ return real_run(argv, **kwargs)++ with pytest.MonkeyPatch.context() as mp:+ mp.setattr(subprocess, "run", counting_run)+ run_pwsh(_CLEAN_WRONG_ANSWER, attempts = 3, capture_output = True, text = True)+ assert len(calls) == 1, f"a normally-exiting run was retried {len(calls)} times"+++def test_the_startup_cache_is_redirected_without_disturbing_the_callers_env():+ """The mechanism fix, asserted from the child's own view of its environment.++ Four xdist workers sharing one $HOME share one 83 KB StartupProfileData-NonInteractive,+ and a startup that reads a half-written one dies. Measured at 7/4000 shared against+ 0/4000 private, reproducing both crash shapes this repo has seen. The redirect must+ therefore actually reach the child, and must add exactly one variable: a hermetic env+ dict is how several of these tests keep a developer's exported settings from deciding+ an inference assertion, and quietly widening it would break that silently.+ """+ dump = [sys.executable, "-c", "import json,os; print(json.dumps(dict(os.environ)))"]++ marker = "UNSLOTH_PWSH_RUNNER_LEAK_PROBE"+ os.environ[marker] = "ambient"+ try:+ hermetic = {"PATH": "/usr/bin:/bin", "HOME": "/nonexistent"}+ proc = run_pwsh(dump, env = dict(hermetic), capture_output = True, text = True)+ child = json.loads(proc.stdout)+ finally:+ os.environ.pop(marker, None)++ assert "XDG_CACHE_HOME" in child, sorted(child)+ assert child["HOME"] == "/nonexistent", "the caller's hermetic HOME was overwritten"+ assert child["PATH"] == "/usr/bin:/bin"+ # The whole point of a hermetic dict: nothing ambient may reach the child. (CPython's+ # own PEP 538 locale coercion can add LC_CTYPE, which is why this probes for a named+ # leak rather than asserting an exact key set.)+ assert marker not in child, "the ambient environment leaked past a hermetic env dict"++ # env = None must still mean inherit, or every call site that relies on the ambient+ # PATH silently loses it.+ inherited = json.loads(run_pwsh(dump, capture_output = True, text = True).stdout)+ assert inherited["XDG_CACHE_HOME"] == child["XDG_CACHE_HOME"]+ assert inherited.get("PATH") == os.environ.get("PATH")++[email protected](PWSH is None, reason = "no PowerShell on this platform")+def test_a_real_pwsh_that_answers_correctly_is_untouched():+ """The helper must be transparent on the path every migrated call site takes."""+ proc = run_pwsh(+ [PWSH, "-NoProfile", "-NonInteractive", "-Command", "Write-Output 'ANSWER=7'"],+ capture_output = True,+ text = True,+ )+ assert proc.returncode == 0+ assert "ANSWER=7" in proc.stdoutdiff --git a/tests/test_installer_profile_hardening.py b/tests/test_installer_profile_hardening.pyindex a5ab3a045f8..f100fd9d920 100644--- a/tests/test_installer_profile_hardening.py+++ b/tests/test_installer_profile_hardening.py@@ -24,6 +24,8 @@ from pathlib import Pathimport pytest+from unsloth_pwsh_runner import run_pwsh+REPO_ROOT = Path(__file__).resolve().parents[1]INSTALL_PS1 = REPO_ROOT / "install.ps1"STUDIO_COMMAND = REPO_ROOT / "unsloth_cli" / "commands" / "studio.py"@@ -284,7 +286,10 @@ def _profile_paths(env: dict[str, str]) -> dict[str, Path]:branch, which is only PowerShell's fallback when XDG_CONFIG_HOME is unset, so on a host thatexports it the fixture wrote a file pwsh never opened and the profile silently did not apply."""- res = subprocess.run(+ # This asks pwsh where its own profiles live, and every fixture below plants a file at+ # the answer. An interpreter that dies here returns no paths at all, which would read as+ # pwsh reporting nothing rather than as pwsh never having started.+ res = run_pwsh([shutil.which("pwsh") or "pwsh","-NoProfile",@@ -327,7 +332,9 @@ def _run_with_profile(script = tmp_path / "body.ps1"script.write_text(f". {_ps_literal(profile_path)}\n{body}\n", encoding = "utf-8")# Absolute path: PATH is replaced in some cases, so pwsh could not be found by name.- return subprocess.run(+ # This helper carries most of the hostile-profile suite, so an interpreter crash here would+ # be reported once per test as the installer failing to survive a hostile profile.+ return run_pwsh([shutil.which("pwsh") or "pwsh", "-NoProfile", "-NonInteractive", "-File", str(script)],capture_output = True,text = True,@@ -387,7 +394,9 @@ def test_a_real_profile_reproduces_the_same_state(tmp_path):script.write_text(_STATE_PROBE, encoding = "utf-8")# -NoProfile deliberately omitted; this is the one place the profile is really loaded.- real = subprocess.run(+ # The anchor compares this run against the dot-sourced simulation, so a crashed interpreter+ # would be read as the two diverging rather than as one of them never having run.+ real = run_pwsh([shutil.which("pwsh") or "pwsh", "-NonInteractive", "-File", str(script)],capture_output = True,text = True,@@ -659,7 +668,9 @@ def test_module_autoloading_is_restored():@requires_pwshdef test_install_ps1_parses():"""A syntax error here is a total install failure, and the file is not imported by anything."""- res = subprocess.run(+ # A nonzero exit here is claimed to mean install.ps1 has a syntax error, and pwsh aborting+ # before it ever reached the parser exits nonzero too.+ res = run_pwsh([shutil.which("pwsh") or "pwsh","-NoProfile",@@ -731,7 +742,9 @@ def test_only_serializable_proxy_keys_reach_the_child(tmp_path):encoding = "utf-8",newline = "",)- handoff = subprocess.run(+ # The proxy keys are read straight out of this run's stdout, so an interpreter that+ # died would look like the prologue publishing an empty handoff.+ handoff = run_pwsh([shutil.which("pwsh") or "pwsh", "-NoProfile", "-NonInteractive", "-File", str(driver)],capture_output = True,text = True,@@ -763,7 +776,9 @@ def test_the_child_restores_the_proxy_and_nothing_else(tmp_path):env = {k: v for k, v in os.environ.items() if k != "_UNSLOTH_PS_PROXY_DEFAULTS"}if value is not None:env["_UNSLOTH_PS_PROXY_DEFAULTS"] = value- return subprocess.run(+ # Each case asserts the child launched successfully and restored exactly the proxy key,+ # so a pwsh that aborted at startup would read as the prelude taking setup.ps1 down.+ return run_pwsh([pwsh, "-NoProfile", "-NonInteractive", "-Command", probe],capture_output = True,text = True,@@ -824,7 +839,9 @@ def test_the_filter_takes_lowercase_keys_and_uri_values(tmp_path):encoding = "utf-8",newline = "",)- handoff = subprocess.run(+ # Same reading here for the casing and [uri] cases: no stdout is indistinguishable from+ # the prologue having filtered every key out.+ handoff = run_pwsh([shutil.which("pwsh") or "pwsh", "-NoProfile", "-NonInteractive", "-File", str(driver)],capture_output = True,text = True,@@ -897,7 +914,9 @@ def test_the_probe_reads_a_hostile_profile_without_carrying_anything_else(tmp_paencoding = "utf-8",newline = "",)- result = subprocess.run(+ # Empty stdout is already handled below as "the planted profile was not loaded" and skips+ # the test, so a crashed interpreter would silently retire this check instead of failing.+ result = run_pwsh([shutil.which("pwsh") or "pwsh","-NonInteractive",@@ -1302,7 +1321,9 @@ def test_a_stale_alias_does_not_block_a_current_uv_on_path(tmp_path):"@('stale', 'current')",f"@('{stale.as_posix()}', '{current.as_posix()}')",)- result = subprocess.run(+ # The uv gate is judged by the first and last lines of stdout, and an interpreter crash+ # leaves none, which the assertion would report as the gate stopping at the stale alias.+ result = run_pwsh([shutil.which("pwsh"), "-NoProfile", "-NonInteractive", "-Command", script],capture_output = True,text = True,diff --git a/tests/test_installer_skip_autostart.py b/tests/test_installer_skip_autostart.pyindex fcc199af447..a1c394ccd1f 100644--- a/tests/test_installer_skip_autostart.py+++ b/tests/test_installer_skip_autostart.py@@ -10,6 +10,8 @@ from pathlib import Pathimport pytest+from unsloth_pwsh_runner import run_pwsh+REPO_ROOT = Path(__file__).resolve().parents[1]INSTALL_SH = REPO_ROOT / "install.sh"INSTALL_PS1 = REPO_ROOT / "install.ps1"@@ -90,7 +92,10 @@ def test_windows_skip_autostart_value_parsing_with_no_torch(value: str, expectedenv = os.environ.copy()env["UNSLOTH_NO_TORCH"] = "1"env["UNSLOTH_SKIP_AUTOSTART"] = value- result = subprocess.run(+ # run_pwsh, not subprocess.run: an interpreter killed at startup never evaluated the+ # UNSLOTH_SKIP_AUTOSTART parser, and check = True would present that as this parser+ # answering wrongly for the value. See tests/_shared/unsloth_pwsh_runner.py.+ result = run_pwsh(["pwsh","-NoProfile",@@ -122,7 +127,10 @@ def test_windows_skip_autostart_bypasses_only_the_interactive_prompt():@pytest.mark.skipif(shutil.which("pwsh") is None, reason = "PowerShell is unavailable")def test_windows_installer_invalid_package_fails():- result = subprocess.run(+ # run_pwsh, not subprocess.run: this case asserts a non-zero exit, which a pwsh that+ # aborted at startup also produces, so the crash would read as install.ps1 having+ # rejected the bad package name. See tests/_shared/unsloth_pwsh_runner.py.+ result = run_pwsh(["pwsh","-NoProfile",diff --git a/tests/test_installer_system32_guard.py b/tests/test_installer_system32_guard.pyindex df960701494..8826cce75d1 100644--- a/tests/test_installer_system32_guard.py+++ b/tests/test_installer_system32_guard.py@@ -19,6 +19,8 @@ from pathlib import Pathimport pytest+from unsloth_pwsh_runner import run_pwsh+REPO_ROOT = Path(__file__).resolve().parents[1]INSTALL_PS1 = REPO_ROOT / "install.ps1"CLI_INIT = REPO_ROOT / "unsloth_cli" / "__init__.py"@@ -146,7 +148,11 @@ def test_install_ps1_under_system_root(path: str, expected: str):f"{_extract_helper()}"f"\"RESULT=$(Test-UnderSystemRoot '{path}')\"\n")- result = subprocess.run(+ # run_pwsh, not subprocess.run: Test-UnderSystemRoot only reports a verdict if pwsh+ # lived long enough to print one, and an interpreter that aborted at startup would+ # read here as the containment check answering wrongly for this path.+ # See tests/_shared/unsloth_pwsh_runner.py.+ result = run_pwsh(["pwsh", "-NoProfile", "-NonInteractive", "-Command", script],capture_output = True,text = True,@@ -221,7 +227,10 @@ def _run_relocation_block("HOMEPATH": tail,})- return subprocess.run(+ # run_pwsh, not subprocess.run: every relocation case below reads this run's exit code+ # to tell "moved out of System32" from "routed through Exit-InstallFailure", and a pwsh+ # killed by a signal is neither. See tests/_shared/unsloth_pwsh_runner.py.+ return run_pwsh(["pwsh", "-NoProfile", "-NonInteractive", "-Command", script],capture_output = True,text = True,@@ -505,7 +514,10 @@ def test_cli_guard_cd_line_actually_runs_in_powershell(profile_name: str, tmp_pamessage, _ = _run_cli_guard(r"C:\Windows\System32", userprofile = str(profile))assert message is not Nonecommand = _cd_line(message, "PowerShell")- result = subprocess.run(+ # run_pwsh, not subprocess.run: this is the call whose stderr caught the crash in the+ # first place ('Stack overflow.' from a bare cd), and blaming the advertised recovery+ # command for it is exactly the wrong reading. See tests/_shared/unsloth_pwsh_runner.py.+ result = run_pwsh(["pwsh", "-NoProfile", "-NonInteractive", "-Command", f"{command}; (Get-Location).Path"],capture_output = True,text = True,diff --git a/tests/test_installer_unsloth_version.py b/tests/test_installer_unsloth_version.pyindex 5ee1cfac719..660769a9f0f 100644--- a/tests/test_installer_unsloth_version.py+++ b/tests/test_installer_unsloth_version.py@@ -11,6 +11,8 @@ from pathlib import Pathimport pytest+from unsloth_pwsh_runner import run_pwsh+REPO_ROOT = Path(__file__).resolve().parents[1]INSTALL_SH = REPO_ROOT / "install.sh"INSTALL_PS1 = REPO_ROOT / "install.ps1"@@ -55,7 +57,10 @@ def test_windows_version_reporter_uses_distribution_metadata():r" \$installedPackageVersion = .*?^ if .*?^ \} else \{.*?^ \}",source,)- result = subprocess.run(+ # run_pwsh, not subprocess.run: a pwsh that aborted before reaching the reporter printed+ # no version line at all, and check = True would file that as install.ps1 reading the+ # distribution metadata wrongly. See tests/_shared/unsloth_pwsh_runner.py.+ result = run_pwsh(["pwsh","-NoProfile",