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.

Studio: stop refusing our own llama-server on Windows when psutil misreports its listener (#15022) (#15034)

Debojyoti Banerjee5f558cb4f588
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.py
index a5ca48c0fbf..08fb0a169a8 100644
--- a/studio/backend/core/inference/llama_cpp.py
+++ b/studio/backend/core/inference/llama_cpp.py
@@ -1011,6 +1011,16 @@ _LOOPBACK_REACHABLE_BIND_IPS = frozenset(
)
+def _socket_owner_is_always_named() -> bool:
+ """Windows' connection tables carry every socket's owning pid, so an unnamed one there is a
+ psutil quirk rather than another user's listener (#15022)."""
+ return sys.platform == "win32"
+
+
+# Left in startup output when the ownership gate refuses, so it is not reported as a bad GGUF.
+_PORT_OWNER_REFUSED_MARKER = "llama-server port ownership check refused the listener"
+
+
def _llama_line_is_warning_or_error(line: str, line_lower: str) -> bool:
level = _LOG_LEVEL_TOKEN_RE.match(line)
if level is not None:
@@ -20225,7 +20235,8 @@ class LlamaCppBackend:
_find_free_port releases the port before llama-server binds it, so another local user could
answer /health and receive every prompt plus the per-launch key. Their socket shows no pid
on Linux/macOS, so our own (readable) tree not listening counts as foreign. Unreadable
- ownership keeps today's behaviour."""
+ ownership keeps today's behaviour. On Windows psutil can report our live listener as NONE
+ and/or pid 0 (#15022), so only a named foreign pid refuses there."""
port = getattr(self, "_port", None)
pid = getattr(process, "pid", None)
if not isinstance(pid, int) or not isinstance(port, int):
@@ -20247,13 +20258,24 @@ class LlamaCppBackend:
except Exception: # noqa: BLE001 -- access denied / platform quirk
return True
+ windows = _socket_owner_is_always_named()
+
def _listens(conn) -> bool:
laddr = getattr(conn, "laddr", None)
- return (
+ if not (
bool(laddr)
and getattr(laddr, "port", None) == port
and getattr(laddr, "ip", None) in _LOOPBACK_REACHABLE_BIND_IPS
- and conn.status == psutil.CONN_LISTEN
+ ):
+ return False
+ if conn.status == psutil.CONN_LISTEN:
+ return True
+ # Windows can report the live listener as NONE: a TCP socket with no peer still is one.
+ return (
+ windows
+ and conn.status == psutil.CONN_NONE
+ and not getattr(conn, "raddr", None)
+ and getattr(conn, "type", socket.SOCK_STREAM) == socket.SOCK_STREAM
)
tree_readable = True
@@ -20271,7 +20293,8 @@ class LlamaCppBackend:
try:
# Scan every listener: a foreign one listed before ours must not refuse our start.
for conn in psutil.net_connections(kind = "inet"):
- if not _listens(conn) or conn.pid is None:
+ # pid 0 is the System Idle Process on Windows: psutil's other "unknown owner".
+ if not _listens(conn) or conn.pid is None or (windows and conn.pid == 0):
continue
if conn.pid in tree_pids or _has_ancestor(conn.pid, pid):
return True
@@ -20286,7 +20309,7 @@ class LlamaCppBackend:
pid,
)
return False
- if tree_readable:
+ if tree_readable and not windows:
logger.error(
"llama-server port %s answered /health but our child %s is not listening on it; "
"refusing to use it",
@@ -23638,7 +23661,16 @@ class LlamaCppBackend:
"""
lowered = (output or "").lower()
- # First: every branch below advises reinstall, memory or administrator,
+ # A healthy server we stopped ourselves: its output holds no failure to classify.
+ if _PORT_OWNER_REFUSED_MARKER.lower() in lowered:
+ return (
+ "llama-server started and answered on its local port, but Studio could not "
+ "confirm that the listener on that port belongs to the server it launched, so it "
+ "stopped the server. The model file and memory are not the problem; the backend "
+ "log names the port and the process that held it."
+ )
+
+ # Then: every branch below advises reinstall, memory or administrator,
# none of which lift a refusal to load a file that is present.
blocked = code_integrity_block_reason(returncode) or code_integrity_block_reason(output)
if blocked is not None:
@@ -39632,6 +39664,7 @@ class LlamaCppBackend:
self._health_wait_cancelled = True
return False
if not self._health_listener_is_ours(process):
+ self._stdout_lines.append(_PORT_OWNER_REFUSED_MARKER)
return False
return True
except (
diff --git a/studio/backend/core/inference/sd_cpp_server.py b/studio/backend/core/inference/sd_cpp_server.py
index 258ad7d97a4..0e5ef58e020 100644
--- a/studio/backend/core/inference/sd_cpp_server.py
+++ b/studio/backend/core/inference/sd_cpp_server.py
@@ -40,6 +40,7 @@ import re
import shutil
import socket
import subprocess
+import sys
import tempfile
import threading
import time
@@ -101,6 +102,11 @@ _TERMINAL_CANCELLED = "cancelled"
_CANCEL_GRACE_S = 5.0
+def _socket_owner_is_always_named() -> bool:
+ """Windows names every socket's owner: an unnamed one there is a psutil quirk (#15022)."""
+ return sys.platform == "win32"
+
+
def _has_ancestor(
pid: int,
ancestor_pid: int,
@@ -383,6 +389,22 @@ class SdCppServer:
import psutil
except Exception: # noqa: BLE001 -- optional dependency
return True
+ windows = _socket_owner_is_always_named()
+
+ def _listens(conn) -> bool:
+ laddr = getattr(conn, "laddr", None)
+ if not laddr or getattr(laddr, "port", None) != self.port:
+ return False
+ if conn.status == psutil.CONN_LISTEN:
+ return True
+ # psutil maps a TCP state it cannot decode to NONE, seen on live Windows listeners (#15022).
+ return (
+ windows
+ and conn.status == getattr(psutil, "CONN_NONE", "NONE")
+ and not getattr(conn, "raddr", None)
+ and getattr(conn, "type", socket.SOCK_STREAM) == socket.SOCK_STREAM
+ )
+
# Another user's socket shows no pid on Linux/macOS: our readable tree not listening = foreign.
tree_says_foreign = False
try:
@@ -394,31 +416,23 @@ class SdCppServer:
for member in tree:
try:
read = getattr(member, "net_connections", None) or member.connections
- for conn in read(kind = "inet"):
- laddr = getattr(conn, "laddr", None)
- if (
- laddr
- and getattr(laddr, "port", None) == self.port
- and conn.status == psutil.CONN_LISTEN
- ):
- return True
+ if any(_listens(conn) for conn in read(kind = "inet")):
+ return True
except psutil.NoSuchProcess:
continue
except Exception: # noqa: BLE001 -- access denied / platform quirk
readable = False
- tree_says_foreign = readable
+ tree_says_foreign = readable and not windows
except Exception as exc: # noqa: BLE001 -- platform quirk: fall back below
if isinstance(exc, getattr(psutil, "NoSuchProcess", ())):
return False
try:
for conn in psutil.net_connections(kind = "inet"):
- laddr = getattr(conn, "laddr", None)
- if not laddr or getattr(laddr, "port", None) != self.port:
- continue
- if conn.status != psutil.CONN_LISTEN:
+ if not _listens(conn):
continue
owner = conn.pid
- if owner is None:
+ # pid 0 is the System Idle Process on Windows: psutil's other "unknown owner".
+ if owner is None or (windows and owner == 0):
continue # not visible to us; do not punish a healthy start
if owner == proc.pid or _has_ancestor(owner, proc.pid):
return True
diff --git a/studio/backend/tests/test_llama_server_port_owner.py b/studio/backend/tests/test_llama_server_port_owner.py
index c66f5dc0dbf..d6977ebf0a0 100644
--- a/studio/backend/tests/test_llama_server_port_owner.py
+++ b/studio/backend/tests/test_llama_server_port_owner.py
@@ -111,6 +111,8 @@ def test_foreign_listener_on_our_port_is_not_healthy(probe, foreign_listener, id
def test_hidden_owner_with_our_child_not_listening_is_not_healthy(
probe, foreign_listener, idle_child, monkeypatch
):
+ # The Linux/macOS case: another user's socket shows no pid.
+ monkeypatch.setattr(llama_cpp, "_socket_owner_is_always_named", lambda: False)
real = psutil.net_connections
def hidden(kind = "inet"):
@@ -198,3 +200,94 @@ def test_a_foreign_listener_listed_before_ours_does_not_refuse_us(monkeypatch):
finally:
p.kill()
p.wait()
+
+
+# ── Windows: psutil can misdescribe our own live listener (#15022) ──
+
+
+def _row(
+ port,
+ *,
+ pid,
+ status,
+ ip = "127.0.0.1",
+ raddr = (),
+):
+ return SimpleNamespace(
+ laddr = SimpleNamespace(ip = ip, port = port),
+ raddr = raddr,
+ status = status,
+ pid = pid,
+ type = llama_cpp.socket.SOCK_STREAM,
+ )
+
+
+def _tables(
+ monkeypatch,
+ *,
+ own,
+ everyone,
+ windows = True,
+):
+ monkeypatch.setattr(llama_cpp, "_socket_owner_is_always_named", lambda: windows)
+ monkeypatch.setattr(
+ psutil.Process, "net_connections", lambda self, kind = "inet": own, raising = False
+ )
+ monkeypatch.setattr(psutil, "net_connections", lambda kind = "inet": everyone)
+
+
[email protected]("windows", [True, False])
+def test_our_child_reported_with_status_none_is_ours_on_windows(idle_child, monkeypatch, windows):
+ port = 50855
+ none = _row(port, pid = idle_child.pid, status = psutil.CONN_NONE)
+ _tables(monkeypatch, own = [none], everyone = [none], windows = windows)
+
+ assert _backend(port, idle_child)._health_listener_is_ours(idle_child) is windows
+
+
[email protected]("windows", [True, False])
+def test_a_listener_owned_by_pid_0_is_unknown_on_windows(idle_child, monkeypatch, windows):
+ port = 54185
+ _tables(
+ monkeypatch,
+ own = [],
+ everyone = [_row(port, pid = 0, status = psutil.CONN_LISTEN)],
+ windows = windows,
+ )
+
+ assert _backend(port, idle_child)._health_listener_is_ours(idle_child) is windows
+
+
+def test_a_connected_socket_on_our_port_is_not_a_listener(idle_child, monkeypatch):
+ port = 57043
+ peer = SimpleNamespace(ip = "127.0.0.1", port = 60000)
+ accepted = _row(port, pid = idle_child.pid, status = psutil.CONN_NONE, raddr = peer)
+ _tables(monkeypatch, own = [accepted], everyone = [_row(port, pid = 4242, status = "LISTEN")])
+
+ assert _backend(port, idle_child)._health_listener_is_ours(idle_child) is False
+
+
+def test_a_named_foreign_listener_still_refuses_on_windows(idle_child, monkeypatch):
+ port = 52792
+ _tables(
+ monkeypatch,
+ own = [],
+ everyone = [
+ _row(port, pid = 0, status = psutil.CONN_LISTEN),
+ _row(port, pid = 4242, status = psutil.CONN_LISTEN),
+ ],
+ )
+
+ assert _backend(port, idle_child)._health_listener_is_ours(idle_child) is False
+
+
+def test_a_refused_listener_is_not_reported_as_a_bad_gguf(probe, foreign_listener, idle_child):
+ b = _backend(foreign_listener, idle_child)
+ assert b._wait_for_health(timeout = 3.0, interval = 0.05) is False
+
+ message = LlamaCppBackend._classify_llama_start_failure(
+ "\n".join(b._stdout_lines), "model.gguf", None
+ )
+
+ assert "could not confirm that the listener" in message
+ assert "enough memory" not in message
diff --git a/studio/backend/tests/test_sd_cpp_server.py b/studio/backend/tests/test_sd_cpp_server.py
index 01a56a4aaf6..f6c1d5dc8f9 100644
--- a/studio/backend/tests/test_sd_cpp_server.py
+++ b/studio/backend/tests/test_sd_cpp_server.py
@@ -535,7 +535,9 @@ def test_readiness_check_is_best_effort(patched):
assert s._port_is_ours() is True
-def test_readiness_refuses_a_hidden_owner_when_our_child_is_not_listening():
+def test_readiness_refuses_a_hidden_owner_when_our_child_is_not_listening(monkeypatch):
+ # The Linux/macOS case: another user's socket shows no pid.
+ monkeypatch.setattr(srv, "_socket_owner_is_always_named", lambda: False)
import http.server
import subprocess
import sys
@@ -582,3 +584,70 @@ def test_readiness_refuses_a_child_that_already_exited():
s._process = child
s.port = 1234
assert s._port_is_ours() is False
+
+
+# ── Windows: psutil can misdescribe our own live listener (#15022) ──
+
+
+def idle_child():
+ import subprocess
+ import sys
+
+ child = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(60)"])
+ yield child
+ child.kill()
+ child.wait()
+
+
+_PORT = 50855
+
+
+def _row(
+ status,
+ pid,
+ raddr = (),
+):
+ import types
+ return types.SimpleNamespace(
+ laddr = types.SimpleNamespace(ip = "127.0.0.1", port = _PORT),
+ raddr = raddr,
+ status = status,
+ pid = pid,
+ )
+
+
+def _owner_check(monkeypatch, child, *, own, everyone, windows):
+ psutil = pytest.importorskip("psutil")
+ monkeypatch.setattr(srv, "_socket_owner_is_always_named", lambda: windows)
+ monkeypatch.setattr(
+ psutil.Process, "net_connections", lambda self, kind = "inet": own, raising = False
+ )
+ monkeypatch.setattr(psutil, "net_connections", lambda kind = "inet": everyone)
+ s = srv.SdCppServer.__new__(srv.SdCppServer)
+ s._process = child
+ s.port = _PORT
+ return s._port_is_ours()
+
+
[email protected]("windows", [True, False])
+def test_our_child_reported_with_status_none_is_ours_on_windows(idle_child, monkeypatch, windows):
+ none = _row("NONE", idle_child.pid)
+ ours = _owner_check(monkeypatch, idle_child, own = [none], everyone = [none], windows = windows)
+ assert ours is windows
+
+
[email protected]("windows", [True, False])
+def test_a_listener_owned_by_pid_0_is_unknown_on_windows(idle_child, monkeypatch, windows):
+ everyone = [_row("LISTEN", 0)]
+ ours = _owner_check(monkeypatch, idle_child, own = [], everyone = everyone, windows = windows)
+ assert ours is windows
+
+
+def test_a_named_foreign_listener_still_refuses_on_windows(idle_child, monkeypatch):
+ import types
+
+ accepted = _row("NONE", idle_child.pid, types.SimpleNamespace(ip = "127.0.0.1", port = 60000))
+ foreign = [_row("LISTEN", 0), _row("LISTEN", idle_child.pid + 100000)]
+ ours = _owner_check(monkeypatch, idle_child, own = [accepted], everyone = foreign, windows = True)
+ assert ours is False