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.

unsloth CLI: check a Studio pid with psutil before spawning tasklist on Windows (#17271)

Daniel Han89d4c20ddcd1
diff --git a/tests/studio/test_cli_studio_stop_windows.py b/tests/studio/test_cli_studio_stop_windows.py
index 8f7419215cd..9bcefcd7e5f 100644
--- a/tests/studio/test_cli_studio_stop_windows.py
+++ b/tests/studio/test_cli_studio_stop_windows.py
@@ -1,7 +1,7 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
-"""stop used os.kill(pid, 0), which raises WinError 87 on Windows; _pid_alive uses tasklist there."""
+"""stop used os.kill(pid, 0), which raises WinError 87 on Windows; _pid_alive uses psutil, else tasklist, there."""
import ast
import os
@@ -38,6 +38,93 @@ def _load_pid_alive(platform: str, fake_run = None):
return ns["_pid_alive"]
[email protected](autouse = True)
+def _no_psutil(monkeypatch):
+ monkeypatch.setitem(sys.modules, "psutil", None)
+
+
+def _fake_psutil(
+ monkeypatch,
+ result = None,
+ *,
+ raises = None,
+):
+ calls = []
+
+ def pid_exists(pid):
+ calls.append(pid)
+ if raises is not None:
+ raise raises
+ return result
+
+ monkeypatch.setitem(sys.modules, "psutil", types.SimpleNamespace(pid_exists = pid_exists))
+ return calls
+
+
+def _counting_tasklist(returns_pid):
+ spawns = []
+ inner = _fake_tasklist(returns_pid)
+
+ def _run(cmd, *args, **kwargs):
+ spawns.append(cmd)
+ return inner(cmd, *args, **kwargs)
+
+ return _run, spawns
+
+
[email protected]("alive", [True, False])
+def test_pid_alive_windows_uses_psutil_without_spawning(monkeypatch, alive):
+ calls = _fake_psutil(monkeypatch, alive)
+ run, spawns = _counting_tasklist(4242 if alive else None)
+ assert _load_pid_alive("win32", fake_run = run)(4242) is alive
+ assert calls == [4242]
+ assert spawns == []
+
+
[email protected]("alive", [True, False])
+def test_pid_alive_windows_falls_back_to_tasklist_without_psutil(alive):
+ run, spawns = _counting_tasklist(4242 if alive else None)
+ assert _load_pid_alive("win32", fake_run = run)(4242) is alive
+ assert len(spawns) == 1
+
+
[email protected]("err", [OSError("denied"), RuntimeError("boom")])
[email protected]("alive", [True, False])
+def test_pid_alive_windows_falls_back_to_tasklist_when_psutil_raises(monkeypatch, err, alive):
+ _fake_psutil(monkeypatch, raises = err)
+ run, spawns = _counting_tasklist(4242 if alive else None)
+ assert _load_pid_alive("win32", fake_run = run)(4242) is alive
+ assert len(spawns) == 1
+
+
+def test_pid_alive_windows_psutil_raises_and_tasklist_fails_means_alive(monkeypatch):
+ _fake_psutil(monkeypatch, raises = OSError("denied"))
+ pid_alive = _load_pid_alive("win32", fake_run = _fake_tasklist(None, raises = True))
+ assert pid_alive(4242) is True
+
+
[email protected](sys.platform != "win32", reason = "real psutil on Windows")
+def test_pid_alive_windows_real_psutil_without_spawning(monkeypatch):
+ monkeypatch.delitem(sys.modules, "psutil")
+ pytest.importorskip("psutil")
+ run, spawns = _counting_tasklist(None)
+ pid_alive = _load_pid_alive("win32", fake_run = run)
+ child = subprocess.Popen([sys.executable, "-c", "pass"])
+ dead_pid = child.pid
+ child.wait()
+ del child # drops the process handle, else Windows keeps the exited process listed
+ assert pid_alive(os.getpid()) is True
+ assert pid_alive(dead_pid) is False
+ assert spawns == []
+
+
[email protected](sys.platform == "win32", reason = "os.kill(pid, 0) terminates on Windows")
+def test_pid_alive_posix_never_consults_psutil(monkeypatch):
+ calls = _fake_psutil(monkeypatch, False)
+ assert _load_pid_alive("linux")(os.getpid()) is True
+ assert calls == []
+
+
# `stop` delegates to `_signal_stop`, so both must be guarded against os.kill(pid, 0).
@pytest.mark.parametrize("func", ["stop", "_signal_stop"])
def test_stop_does_not_use_bare_oskill_liveness_probe(func):
diff --git a/unsloth_cli/commands/studio.py b/unsloth_cli/commands/studio.py
index 32ec30189be..9cc740c24a4 100644
--- a/unsloth_cli/commands/studio.py
+++ b/unsloth_cli/commands/studio.py
@@ -3165,8 +3165,15 @@ PID_FILE_GLOB = "studio-*.pid"
def _pid_alive(pid: int) -> bool:
- """True if pid exists; os.kill(pid, 0) raises WinError 87 on Windows, so tasklist is used."""
+ """True if pid exists; os.kill(pid, 0) raises WinError 87 on Windows, so psutil (else tasklist) decides there."""
if sys.platform == "win32":
+ try:
+ import psutil
+
+ # OpenProcess-based; access denied already counts as alive.
+ return bool(psutil.pid_exists(int(pid)))
+ except Exception:
+ pass # psutil is optional for the CLI install
try:
out = subprocess.run(
["tasklist", "/FI", f"PID eq {int(pid)}", "/NH", "/FO", "CSV"],
diff --git a/unsloth_cli/tests/test_studio_stop.py b/unsloth_cli/tests/test_studio_stop.py
index c09c776b074..9d0c107a1b5 100644
--- a/unsloth_cli/tests/test_studio_stop.py
+++ b/unsloth_cli/tests/test_studio_stop.py
@@ -517,6 +517,7 @@ def test_windows_failed_liveness_probe_preserves_the_record(monkeypatch):
studio_mod = _studio()
monkeypatch.setattr(sys, "platform", "win32")
+ monkeypatch.setitem(sys.modules, "psutil", None)
monkeypatch.setattr(
subprocess, "run", lambda *args, **kwargs: SimpleNamespace(stdout = "", returncode = 1)
)