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: don't take a port another process holds on 0.0.0.0 (#12011)

Suliman Abdulrazzaqda58421ad950
diff --git a/studio/backend/run.py b/studio/backend/run.py
index 421b12e271c..36242d9393c 100644
--- a/studio/backend/run.py
+++ b/studio/backend/run.py
@@ -1,6 +1,7 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+import errno
import os
import sys
import time
@@ -819,10 +820,12 @@ def _addresses_collide(recorded: "str | None", host: str, port: int) -> bool:
def _is_port_free(host: str, port: int) -> bool:
"""Check if a port is available for binding. For a ``0.0.0.0`` wildcard host, also check whether anything
is listening on ``127.0.0.1`` (and ``::1`` when IPv6 exists): an SSH tunnel may hold loopback while the
- wildcard bind succeeds, making Unsloth unreachable via ``localhost``."""
+ wildcard bind succeeds, making Unsloth unreachable via ``localhost``. A specific host is checked too:
+ Windows and macOS let a ``127.0.0.1`` bind sit beside another process's ``0.0.0.0`` listener."""
import socket
sockets = []
+ bound = []
try:
addr_info = socket.getaddrinfo(host, port, socket.AF_UNSPEC, socket.SOCK_STREAM)
seen = set()
@@ -831,6 +834,7 @@ def _is_port_free(host: str, port: int) -> bool:
if key in seen:
continue
seen.add(key)
+ bound.append((family, sockaddr))
probe = socket.socket(family, socktype, proto)
sockets.append(probe)
# On Windows, SO_REUSEADDR lets a second socket bind a listening
@@ -852,24 +856,55 @@ def _is_port_free(host: str, port: int) -> bool:
for probe in sockets:
probe.close()
- # On a wildcard bind, verify localhost is not already claimed by another process (e.g. an SSH -L
- # tunnel); a successful connect means it is.
+ # A successful bind can still sit beside a live listener, so a connect that lands means taken. Short
+ # timeout: Windows only refuses a free port after ~2 s of SYN retries.
if is_wildcard_host(host):
- for loopback, family in [
- ("127.0.0.1", socket.AF_INET),
- ("::1", socket.AF_INET6),
- ]:
- try:
- with socket.socket(family, socket.SOCK_STREAM) as s:
- s.settimeout(1)
- if s.connect_ex((loopback, port)) == 0:
- return False
- except OSError:
- continue
+ targets = [
+ (socket.AF_INET, ("127.0.0.1", port)),
+ (socket.AF_INET6, ("::1", port)),
+ ]
+ else:
+ targets = bound
+ for family, sockaddr in targets:
+ try:
+ with socket.socket(family, socket.SOCK_STREAM) as s:
+ s.settimeout(0.25)
+ result = s.connect_ex(sockaddr)
+ if result == 0:
+ return False
+ # Windows times out on a full-backlog listener exactly as on a free port.
+ if result not in _CONNECT_REFUSED and _listener_collides(sockaddr[0], port):
+ return False
+ except OSError:
+ continue
return True
+_CONNECT_REFUSED = {errno.ECONNREFUSED, 10061} # WSAECONNREFUSED
+
+
+def _listener_collides(address: str, port: int) -> bool:
+ """A same-family listener on *port* at *address* or its wildcard; a v6-only ``::`` shares the port
+ with IPv4. Best effort: no psutil means no."""
+ import socket
+
+ family = socket.AF_INET6 if ":" in address else socket.AF_INET
+ try:
+ import psutil
+ listeners = [
+ c.laddr[0]
+ for c in psutil.net_connections(kind = "tcp")
+ if c.status == psutil.CONN_LISTEN
+ and c.family == family
+ and c.laddr
+ and c.laddr[1] == port
+ ]
+ except Exception:
+ return False
+ return any(_addresses_collide(listener, address, port) for listener in listeners)
+
+
def _find_free_port(
host: str,
start: int,
diff --git a/studio/backend/tests/test_studio_pid_files.py b/studio/backend/tests/test_studio_pid_files.py
index 80b698eee36..43004d17285 100644
--- a/studio/backend/tests/test_studio_pid_files.py
+++ b/studio/backend/tests/test_studio_pid_files.py
@@ -456,6 +456,106 @@ def test_windows_reuseaddr_listener_is_not_reported_as_a_free_port():
assert run._is_port_free("127.0.0.1", port) is False
+def test_a_loopback_bind_is_not_free_while_another_process_holds_the_wildcard():
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as listener:
+ listener.bind(("0.0.0.0", 0))
+ listener.listen()
+ port = listener.getsockname()[1]
+
+ assert run._is_port_free("127.0.0.1", port) is False
+
+
[email protected](sys.platform != "win32", reason = "Windows drops the SYN to a full backlog")
+def test_a_wildcard_listener_with_a_full_backlog_is_not_a_free_port():
+ # studio.txt alone does not install psutil, the only thing that tells this apart from a free port.
+ pytest.importorskip("psutil")
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as listener:
+ listener.bind(("0.0.0.0", 0))
+ listener.listen(0)
+ port = listener.getsockname()[1]
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as filler:
+ filler.settimeout(2)
+ filler.connect(("127.0.0.1", port))
+
+ assert run._is_port_free("127.0.0.1", port) is False
+
+
+ ("listener", "family", "address", "collides"),
+ [
+ ("0.0.0.0", socket.AF_INET, "127.0.0.1", True),
+ ("127.0.0.1", socket.AF_INET, "127.0.0.1", True),
+ ("192.168.1.5", socket.AF_INET, "127.0.0.1", False),
+ ("::", socket.AF_INET6, "127.0.0.1", False), # a v6-only wildcard shares the port with IPv4
+ ("::", socket.AF_INET6, "::1", True),
+ ],
+)
+def test_only_a_listener_of_the_same_family_takes_the_port(
+ monkeypatch, listener, family, address, collides
+):
+ psutil = pytest.importorskip("psutil")
+ row = SimpleNamespace(status = psutil.CONN_LISTEN, family = family, laddr = (listener, 8888))
+ monkeypatch.setattr(psutil, "net_connections", lambda kind: [row])
+
+ assert run._listener_collides(address, 8888) is collides
+
+
+def test_a_timed_out_connect_is_settled_by_the_listener_table(monkeypatch):
+ monkeypatch.setattr(run, "sys", SimpleNamespace(platform = "win32"))
+ asked = []
+ monkeypatch.setattr(
+ run, "_listener_collides", lambda address, port: asked.append((address, port)) or True
+ )
+
+ class _ProbeSocket:
+ def __init__(self, *_args):
+ pass
+
+ def setsockopt(self, *_args):
+ pass
+
+ def bind(self, _sockaddr):
+ pass
+
+ def settimeout(self, _timeout):
+ pass
+
+ def connect_ex(self, _sockaddr):
+ return errno.EWOULDBLOCK
+
+ def close(self):
+ pass
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *_exc):
+ pass
+
+ monkeypatch.setattr(
+ socket,
+ "getaddrinfo",
+ lambda *_args, **_kwargs: [
+ (socket.AF_INET, socket.SOCK_STREAM, 6, "", ("127.0.0.1", 8888))
+ ],
+ )
+ monkeypatch.setattr(socket, "socket", _ProbeSocket)
+
+ assert run._is_port_free("127.0.0.1", 8888) is False
+ assert asked == [("127.0.0.1", 8888)]
+
+
+def test_a_free_loopback_port_is_reported_without_a_long_wait():
+ # Windows waits out the whole connect timeout on a free port.
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
+ s.bind(("127.0.0.1", 0))
+ port = s.getsockname()[1]
+
+ start = time.monotonic()
+ assert run._is_port_free("127.0.0.1", port) is True
+ assert time.monotonic() - start < 0.75
+
+
def test_a_hostname_records_every_address_it_resolves_to(tmp_path):
# `localhost` binds 127.0.0.1 AND ::1. Recording only the first lets a later
# launch on the other literal miss us and start a duplicate.
@@ -471,6 +571,7 @@ def test_a_hostname_records_every_address_it_resolves_to(tmp_path):
def test_port_probe_checks_every_resolved_bind_address(monkeypatch, platform, occupied):
monkeypatch.setattr(run, "sys", SimpleNamespace(platform = platform))
bind_attempts = []
+ connect_attempts = []
sockets = []
class _ProbeSocket:
@@ -488,9 +589,22 @@ def test_port_probe_checks_every_resolved_bind_address(monkeypatch, platform, oc
if occupied and self.family == socket.AF_INET6:
raise OSError("address already in use")
+ def settimeout(self, _timeout):
+ pass
+
+ def connect_ex(self, sockaddr):
+ connect_attempts.append((self.family, sockaddr))
+ return errno.ECONNREFUSED
+
def close(self):
self.closed = True
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *_exc):
+ self.close()
+
monkeypatch.setattr(
socket,
"getaddrinfo",
@@ -502,7 +616,7 @@ def test_port_probe_checks_every_resolved_bind_address(monkeypatch, platform, oc
monkeypatch.setattr(
socket,
"socket",
- lambda family, _socktype, _proto: _ProbeSocket(family),
+ lambda family, *_args: _ProbeSocket(family),
)
assert run._is_port_free("dual-stack.test", 8888) is (not occupied)
@@ -510,8 +624,9 @@ def test_port_probe_checks_every_resolved_bind_address(monkeypatch, platform, oc
(socket.AF_INET, ("127.0.0.1", 8888)),
(socket.AF_INET6, ("::1", 8888, 0, 0)),
]
+ assert connect_attempts == ([] if occupied else bind_attempts)
assert all(probe.closed for probe in sockets)
- for probe in sockets:
+ for probe in sockets[: len(bind_attempts)]:
assert ((socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) in probe.options) is (
platform != "win32"
)