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: only trust file search and dictation servers Studio started (#15600)

Nilayc969323b0ff1
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.py
index 148af3515be..4b99fad524e 100644
--- a/studio/backend/core/inference/llama_cpp.py
+++ b/studio/backend/core/inference/llama_cpp.py
@@ -17885,7 +17885,12 @@ class LlamaCppBackend:
s.bind(("127.0.0.1", 0))
return s.getsockname()[1]
- def _health_listener_is_ours(self, process) -> bool:
+ @staticmethod
+ def _health_listener_is_ours(
+ process,
+ port,
+ bind_host = None,
+ ) -> bool:
"""False when the port answering /health is demonstrably not held by our child's tree.
_find_free_port releases the port before llama-server binds it, so another local user could
@@ -17893,7 +17898,6 @@ class LlamaCppBackend:
on Linux/macOS, so our own (readable) tree not listening counts as foreign. Unreadable
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):
return True
@@ -17915,13 +17919,19 @@ class LlamaCppBackend:
return True
windows = _socket_owner_is_always_named()
+ bind_ips = set(_LOOPBACK_REACHABLE_BIND_IPS)
+ if bind_host:
+ try:
+ bind_ips.update(a[4][0] for a in socket.getaddrinfo(bind_host, port))
+ except OSError:
+ pass
def _listens(conn) -> bool:
laddr = getattr(conn, "laddr", None)
if not (
bool(laddr)
and getattr(laddr, "port", None) == port
- and getattr(laddr, "ip", None) in _LOOPBACK_REACHABLE_BIND_IPS
+ and getattr(laddr, "ip", None) in bind_ips
):
return False
if conn.status == psutil.CONN_LISTEN:
@@ -35132,7 +35142,7 @@ class LlamaCppBackend:
logger.info("llama-server became healthy while the app was shutting down")
self._health_wait_cancelled = True
return False
- if not self._health_listener_is_ours(process):
+ if not self._health_listener_is_ours(process, getattr(self, "_port", None)):
self._stdout_lines.append(_PORT_OWNER_REFUSED_MARKER)
return False
return True
diff --git a/studio/backend/core/inference/stt_mtmd_sidecar.py b/studio/backend/core/inference/stt_mtmd_sidecar.py
index fdf71d2bf75..da282497c31 100644
--- a/studio/backend/core/inference/stt_mtmd_sidecar.py
+++ b/studio/backend/core/inference/stt_mtmd_sidecar.py
@@ -1046,6 +1046,8 @@ class MtmdSttSidecar:
port: int,
cancel_event: Optional[threading.Event] = None,
) -> bool:
+ from core.inference.llama_cpp import LlamaCppBackend
+
deadline = time.monotonic() + _SERVER_START_TIMEOUT_SECONDS
url = f"http://127.0.0.1:{port}/health"
while time.monotonic() < deadline:
@@ -1056,7 +1058,7 @@ class MtmdSttSidecar:
try:
with urllib.request.urlopen(url, timeout = 2) as response:
if response.status == 200:
- return True
+ return LlamaCppBackend._health_listener_is_ours(process, port)
except Exception:
pass
# Outside the except: a non-200 2xx would otherwise spin this loop with no delay.
diff --git a/studio/backend/core/rag/embed_llama_server.py b/studio/backend/core/rag/embed_llama_server.py
index bde53f9c9bb..d00a30c950d 100644
--- a/studio/backend/core/rag/embed_llama_server.py
+++ b/studio/backend/core/rag/embed_llama_server.py
@@ -13,6 +13,7 @@ from utils.gpu_memory_events import invalidates_gpu_memory as _invalidates_gpu_m
import atexit
import logging
import os
+import socket
import struct
import subprocess
import sys
@@ -101,6 +102,17 @@ _GGUF_POOLING = {1: "mean", 2: "cls", 3: "last"}
_GGUF_POOLING_DEFAULT = {"nomic-bert": "mean", "nomic-bert-moe": "mean"}
+@lru_cache(maxsize = 8)
+def _embed_host(host: str) -> str:
+ # One address for bind, URL and owner check: a multi-address name can bind one and dial another.
+ try:
+ ips = [a[4][0] for a in socket.getaddrinfo(host, None, type = socket.SOCK_STREAM)]
+ except OSError:
+ return host
+ v4 = [ip for ip in ips if ":" not in ip]
+ return (v4 or ips or [host])[0]
+
+
@lru_cache(maxsize = 32)
def _gguf_pooling_at(path: str, mtime_ns: int, size: int) -> str:
arch, value = _gguf_arch_uint(path, "pooling_type")
@@ -209,7 +221,8 @@ class LlamaServerBackend:
@property
def _base_url(self) -> str:
- return f"http://{config.EMBED_HOST}:{self._port}"
+ host = _embed_host(config.EMBED_HOST)
+ return f"http://{f'[{host}]' if ':' in host else host}:{self._port}"
def _auth_headers(self) -> dict[str, str]:
return {"Authorization": f"Bearer {self._api_key}"} if self._api_key else {}
@@ -692,7 +705,7 @@ class LlamaServerBackend:
"-m",
model_path,
"--host",
- config.EMBED_HOST,
+ _embed_host(config.EMBED_HOST),
"--port",
str(port),
"--embedding",
@@ -916,6 +929,8 @@ class LlamaServerBackend:
interval: float = 0.5,
) -> bool:
"""Poll /health until 200; bail early if the process exits."""
+ from core.inference.llama_cpp import LlamaCppBackend
+
deadline = time.monotonic() + timeout
url = f"{self._base_url}/health"
while time.monotonic() < deadline:
@@ -926,7 +941,9 @@ class LlamaServerBackend:
try:
# trust_env=False: a proxy that 503s 127.0.0.1 must not block this probe.
if httpx.get(url, timeout = 2.0, trust_env = False).status_code == 200:
- return True
+ return LlamaCppBackend._health_listener_is_ours(
+ self._process, self._port, _embed_host(config.EMBED_HOST)
+ )
except (*_TRANSPORT_ERRORS, httpx.TimeoutException):
pass
time.sleep(interval)
diff --git a/studio/backend/core/systemone/native_worker.py b/studio/backend/core/systemone/native_worker.py
index fb462003773..3a68fac348c 100644
--- a/studio/backend/core/systemone/native_worker.py
+++ b/studio/backend/core/systemone/native_worker.py
@@ -448,6 +448,7 @@ class NativeClefAgent:
return {"Authorization": f"Bearer {self._key}"}
def _wait_ready(self, cancelled: Callable[[], bool] | None) -> None:
+ from core.inference.llama_cpp import LlamaCppBackend
from utils.process_lifetime import is_process_shutting_down
deadline = time.monotonic() + LOAD_TIMEOUT_S
@@ -463,6 +464,8 @@ class NativeClefAgent:
try:
response = self._client.get(f"{self._base}/health", timeout = 2.0)
if response.status_code == 200:
+ if not LlamaCppBackend._health_listener_is_ours(self._process, self.port):
+ raise NativeError(f"Another process holds llama.cpp's port {self.port}.")
return
except httpx.TransportError:
pass
diff --git a/studio/backend/tests/test_llama_cpp_wait_for_health.py b/studio/backend/tests/test_llama_cpp_wait_for_health.py
index 040693a5f2e..57d59353a46 100644
--- a/studio/backend/tests/test_llama_cpp_wait_for_health.py
+++ b/studio/backend/tests/test_llama_cpp_wait_for_health.py
@@ -1538,7 +1538,9 @@ class TestHealthWaitMeasuresStalls:
):
monkeypatch.setattr(LlamaCppBackend, "_STARTUP_PROGRESS_SAMPLE_S", 0.1)
# /health is mocked and the worker never listens, so the port-owner check doesn't apply.
- monkeypatch.setattr(LlamaCppBackend, "_health_listener_is_ours", lambda self, process: True)
+ monkeypatch.setattr(
+ LlamaCppBackend, "_health_listener_is_ours", staticmethod(lambda process, port: True)
+ )
b = _make_backend()
b._process = subprocess.Popen([sys.executable, "-c", *argv])
started = time.monotonic()
diff --git a/studio/backend/tests/test_llama_server_port_owner.py b/studio/backend/tests/test_llama_server_port_owner.py
index d6977ebf0a0..423ccd8ca04 100644
--- a/studio/backend/tests/test_llama_server_port_owner.py
+++ b/studio/backend/tests/test_llama_server_port_owner.py
@@ -173,7 +173,7 @@ def test_an_exited_child_is_never_the_server_that_answered(foreign_listener):
p = subprocess.Popen([sys.executable, "-c", "pass"])
p.wait()
b = _backend(foreign_listener, p)
- assert b._health_listener_is_ours(p) is False
+ assert b._health_listener_is_ours(p, b._port) is False
def test_a_foreign_listener_listed_before_ours_does_not_refuse_us(monkeypatch):
@@ -196,7 +196,7 @@ def test_a_foreign_listener_listed_before_ours_does_not_refuse_us(monkeypatch):
psutil, "net_connections", lambda kind = "inet": [conn(1, "::"), conn(p.pid, "127.0.0.1")]
)
b = _backend(port, p)
- assert b._health_listener_is_ours(p) is True
+ assert b._health_listener_is_ours(p, b._port) is True
finally:
p.kill()
p.wait()
@@ -242,7 +242,7 @@ def test_our_child_reported_with_status_none_is_ours_on_windows(idle_child, monk
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
+ assert LlamaCppBackend._health_listener_is_ours(idle_child, port) is windows
@pytest.mark.parametrize("windows", [True, False])
@@ -255,7 +255,7 @@ def test_a_listener_owned_by_pid_0_is_unknown_on_windows(idle_child, monkeypatch
windows = windows,
)
- assert _backend(port, idle_child)._health_listener_is_ours(idle_child) is windows
+ assert LlamaCppBackend._health_listener_is_ours(idle_child, port) is windows
def test_a_connected_socket_on_our_port_is_not_a_listener(idle_child, monkeypatch):
@@ -264,7 +264,7 @@ def test_a_connected_socket_on_our_port_is_not_a_listener(idle_child, monkeypatc
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
+ assert LlamaCppBackend._health_listener_is_ours(idle_child, port) is False
def test_a_named_foreign_listener_still_refuses_on_windows(idle_child, monkeypatch):
@@ -278,7 +278,7 @@ def test_a_named_foreign_listener_still_refuses_on_windows(idle_child, monkeypat
],
)
- assert _backend(port, idle_child)._health_listener_is_ours(idle_child) is False
+ assert LlamaCppBackend._health_listener_is_ours(idle_child, port) is False
def test_a_refused_listener_is_not_reported_as_a_bad_gguf(probe, foreign_listener, idle_child):
diff --git a/studio/backend/tests/test_sidecar_llama_server_port_owner.py b/studio/backend/tests/test_sidecar_llama_server_port_owner.py
new file mode 100644
index 00000000000..f8c4e09afc7
--- /dev/null
+++ b/studio/backend/tests/test_sidecar_llama_server_port_owner.py
@@ -0,0 +1,172 @@
+# 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 http.server
+import socket
+import subprocess
+import sys
+import threading
+
+import httpx
+import pytest
+
+pytest.importorskip("psutil")
+
+from core.inference.stt_mtmd_sidecar import MtmdSttSidecar
+from core.rag import config
+from core.rag.embed_llama_server import LlamaServerBackend, _embed_host
+from core.systemone.native_worker import NativeClefAgent, NativeError
+
+_CHILD_SERVER = r"""
+import http.server, sys
+class H(http.server.BaseHTTPRequestHandler):
+ def do_GET(self):
+ self.send_response(200); self.end_headers(); self.wfile.write(b'{"status":"ok"}')
+ def log_message(self, *a): pass
+s = http.server.HTTPServer((sys.argv[1] if len(sys.argv) > 1 else "127.0.0.1", 0), H)
+print(s.server_address[1], flush=True)
+s.serve_forever()
+"""
+
+
+class _Health(http.server.BaseHTTPRequestHandler):
+ def do_GET(self):
+ self.send_response(200)
+ self.end_headers()
+ self.wfile.write(b'{"status":"ok"}')
+
+ def log_message(self, *a):
+ pass
+
+
+def foreign_port():
+ srv = http.server.HTTPServer(("127.0.0.1", 0), _Health)
+ threading.Thread(target = srv.serve_forever, daemon = True).start()
+ yield srv.server_address[1]
+ srv.shutdown()
+ srv.server_close()
+
+
+def idle_child():
+ p = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(60)"])
+ yield p
+ p.kill()
+ p.wait()
+
+
+def serving_child():
+ p = subprocess.Popen([sys.executable, "-c", _CHILD_SERVER], stdout = subprocess.PIPE, text = True)
+ port = int(p.stdout.readline())
+ yield p, port
+ p.kill()
+ p.wait()
+
+
+def _embedder(
+ process,
+ port,
+ monkeypatch,
+ host = "127.0.0.1",
+):
+ monkeypatch.setattr(config, "EMBED_HOST", host)
+ b = LlamaServerBackend.__new__(LlamaServerBackend)
+ b._process, b._port = process, port
+ return b
+
+
+def _decision(process, port):
+ a = NativeClefAgent.__new__(NativeClefAgent)
+ a._process, a.port, a.alias, a._log_path = process, port, "clef", None
+ a._client = httpx.Client(trust_env = False)
+ return a
+
+
+def test_embedder_refuses_a_port_another_process_answers(foreign_port, idle_child, monkeypatch):
+ b = _embedder(idle_child, foreign_port, monkeypatch)
+ assert b._wait_for_health(timeout = 3.0, interval = 0.05) is False
+
+
+def test_embedder_accepts_its_own_child(serving_child, monkeypatch):
+ b = _embedder(*serving_child, monkeypatch)
+ assert b._wait_for_health(timeout = 10.0, interval = 0.05) is True
+
+
+def test_embedder_accepts_its_own_child_on_a_configured_host(monkeypatch):
+ p = subprocess.Popen(
+ [sys.executable, "-c", _CHILD_SERVER, "127.0.0.2"], stdout = subprocess.PIPE, text = True
+ )
+ try:
+ line = p.stdout.readline()
+ if not line:
+ pytest.skip("127.0.0.2 is not bindable here")
+ b = _embedder(p, int(line), monkeypatch, host = "127.0.0.2")
+ assert b._wait_for_health(timeout = 10.0, interval = 0.05) is True
+ finally:
+ p.kill()
+ p.wait()
+
+
+def test_embedder_dials_the_address_its_child_bound(monkeypatch):
+ host = "localhost.localdomain"
+ try:
+ families = {a[0] for a in socket.getaddrinfo(host, None, type = socket.SOCK_STREAM)}
+ except OSError:
+ families = set()
+ if families != {socket.AF_INET, socket.AF_INET6}:
+ pytest.skip(f"{host} does not resolve to both ::1 and 127.0.0.1 here")
+
+ class V6(http.server.HTTPServer):
+ address_family = socket.AF_INET6
+
+ hits = []
+
+ class Foreign(_Health):
+ def do_GET(self):
+ hits.append(self.path)
+ super().do_GET()
+
+ foreign = V6(("::1", 0), Foreign)
+ threading.Thread(target = foreign.serve_forever, daemon = True).start()
+ port = foreign.server_address[1]
+ p = subprocess.Popen(
+ [
+ sys.executable,
+ "-c",
+ _CHILD_SERVER.replace(", 0)", ", int(sys.argv[2]))"),
+ _embed_host(host),
+ str(port),
+ ],
+ stdout = subprocess.PIPE,
+ text = True,
+ )
+ try:
+ assert int(p.stdout.readline()) == port
+ b = _embedder(p, port, monkeypatch, host = host)
+ assert b._wait_for_health(timeout = 10.0, interval = 0.05) is True
+ assert b._base_url == f"http://127.0.0.1:{port}"
+ assert hits == []
+ finally:
+ p.kill()
+ p.wait()
+ foreign.shutdown()
+ foreign.server_close()
+
+
+def test_dictation_refuses_a_port_another_process_answers(foreign_port, idle_child):
+ assert MtmdSttSidecar._wait_for_server(idle_child, foreign_port) is False
+
+
+def test_dictation_accepts_its_own_child(serving_child):
+ assert MtmdSttSidecar._wait_for_server(*serving_child) is True
+
+
+def test_decision_worker_refuses_a_port_another_process_answers(foreign_port, idle_child):
+ with pytest.raises(NativeError, match = "port"):
+ _decision(idle_child, foreign_port)._wait_ready(None)
+
+
+def test_decision_worker_accepts_its_own_child(serving_child):
+ _decision(*serving_child)._wait_ready(None)