Distribute and run LLMs with a single file.
C++ cross-platformggufllama-cpplocal-ailocal-inferencelocal-llmopen-source-aisingle-file-executablespeech-to-text
server: accept Unix socket paths shorter than 14 bytes (#1073)
Pablo De Chiaro Rosa6bfbec3af98c
diff --git a/llama.cpp.patches/README.md b/llama.cpp.patches/README.mdindex 6a3d180a..96d5e109 100644--- a/llama.cpp.patches/README.md+++ b/llama.cpp.patches/README.md@@ -126,7 +126,7 @@ Cosmopolitan libc has specific behaviors with condition variables and signals th| `tools_server_server-models.cpp.patch` | Adds `#include <csignal>`; blocks signals via `pthread_sigmask` on `server_monitor`'s thread (b11100 replaced the per-model `stopping_thread` this used to cover with one monitor thread watching every child); replaces untimed `cv.wait()` with `wait_for(30s)` loops on every model-lifecycle wait (`unload_lru`, the reload-drain wait, `unload_all`, the `is_reloading` guard in `load`, and the generic `wait()` predicate helper) to work around the XNU futex timeout bug || `tools_server_server-queue.cpp.patch` | Adds missing includes (`<cerrno>`, `<system_error>`, `<csignal>`); blocks `SIGINT`/`SIGTERM` on queue thread (the `yield_to_queue` worker thread is spawned after this, so it inherits the mask); replaces `wait()` with `wait_for(30s)` loops in five locations (`wait_until_no_sleep`, main loop, `recv`, plus `worker_loop` and `yield_to_queue`, both new upstream in b10441); runs `yield_to_queue()` inline when a GPU backend is loaded (see "GPU decode must stay on the main thread" below) || `tools_server_server-stream.cpp.patch` | Adds `#include <csignal>`; blocks signals on the stream-session GC thread via `pthread_sigmask`. Without it, Ctrl+C on `llama-server` aborts with *"libc++abi: terminating due to uncaught exception ... condition_variable timed_wait failed: Interrupted system call"* instead of shutting down: `SIGINT` is delivered to that thread while it sits in `gc_wake_cv.wait_for(60s)`, `pthread_cond_timedwait()` returns `EINTR`, and libcxx rethrows it as `std::system_error` that nothing catches. This thread was the last one in the server with a condition-variable wait and no signal mask (the log worker, task queue, model-stopping thread and httplib pool were already covered). Pre-existing, not introduced by b10441; combined TUI mode is unaffected |-| `vendor_cpp-httplib_httplib.cpp.patch` | Fixes httplib thread pool with `wait_for()` instead of `wait()` for XNU futex compatibility; also see HTTPS / TLS Support below |+| `vendor_cpp-httplib_httplib.cpp.patch` | Fixes httplib thread pool with `wait_for()` instead of `wait()` for XNU futex compatibility; passes the full `sockaddr_un` for a pathname Unix socket, since Cosmopolitan's `bind()`/`connect()` reject addresses shorter than `struct sockaddr` and a `--host` socket path under 14 bytes failed with `EINVAL`; also see HTTPS / TLS Support below |### HTTPS / TLS Supportdiff --git a/llama.cpp.patches/patches/vendor_cpp-httplib_httplib.cpp.patch b/llama.cpp.patches/patches/vendor_cpp-httplib_httplib.cpp.patchindex 82f01dd9..16c52d3e 100644--- a/llama.cpp.patches/patches/vendor_cpp-httplib_httplib.cpp.patch+++ b/llama.cpp.patches/patches/vendor_cpp-httplib_httplib.cpp.patch@@ -1,7 +1,24 @@diff --git a/vendor/cpp-httplib/httplib.cpp b/vendor/cpp-httplib/httplib.cpp--- a/llama.cpp/vendor/cpp-httplib/httplib.cpp+++ b/llama.cpp/vendor/cpp-httplib/httplib.cpp-@@ -7244,6 +7244,22 @@ void ThreadPool::cleanup_finished_threads() {+@@ -2382,6 +2382,16 @@ socket_t create_socket(const std::string &host, const std::string &ip, int port,+ hints.ai_addr = reinterpret_cast<sockaddr *>(&addr);+ hints.ai_addrlen = static_cast<socklen_t>(+ sizeof(addr) - sizeof(addr.sun_path) + addrlen);++#ifdef __COSMOPOLITAN__++ // Cosmopolitan's bind() and connect() reject an address shorter than++ // struct sockaddr (16 bytes) with EINVAL, so a socket path under 14++ // bytes would fail. Passing the whole sockaddr_un is fine for a++ // pathname socket, which the kernel reads up to the NUL; an abstract++ // name (leading NUL) is length-delimited, so it keeps its exact size.++ if (addr.sun_path[0] != '\0') {++ hints.ai_addrlen = static_cast<socklen_t>(sizeof(addr));++ }++#endif++ #ifndef SOCK_CLOEXEC+ #ifndef _WIN32+@@ -7244,6 +7254,22 @@ void ThreadPool::cleanup_finished_threads() {}void ThreadPool::worker(bool is_dynamic) {@@ -24,7 +41,7 @@ diff --git a/vendor/cpp-httplib/httplib.cpp b/vendor/cpp-httplib/httplib.cppfor (;;) {std::function<void()> fn;{-@@ -7261,7 +7277,13 @@ void ThreadPool::worker(bool is_dynamic) {+@@ -7261,7 +7287,13 @@ void ThreadPool::worker(bool is_dynamic) {break;}} else {@@ -39,7 +56,7 @@ diff --git a/vendor/cpp-httplib/httplib.cpp b/vendor/cpp-httplib/httplib.cpp}idle_thread_count_--;-@@ -14003,6 +14025,13 @@ bool enumerate_macos_keychain_certs(Callback cb) {+@@ -14003,6 +14035,13 @@ bool enumerate_macos_keychain_certs(Callback cb) {#if !defined(_WIN32) && !(defined(__APPLE__) && \defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN))@@ -53,7 +70,7 @@ diff --git a/vendor/cpp-httplib/httplib.cpp b/vendor/cpp-httplib/httplib.cpp// Common CA certificate file paths on Linux/Unixconst char **system_ca_paths() {static const char *paths[] = {-@@ -14020,6 +14049,10 @@ const char **system_ca_dirs() {+@@ -14020,6 +14059,10 @@ const char **system_ca_dirs() {static const char *dirs[] = {"/etc/ssl/certs", // Debian/Ubuntu"/etc/pki/tls/certs", // RHEL/CentOS"/usr/share/ca-certificates", // Otherdiff --git a/tests/integration/tests/test_server.py b/tests/integration/tests/test_server.pyindex 02c2534f..d9ec85a1 100644--- a/tests/integration/tests/test_server.py+++ b/tests/integration/tests/test_server.py@@ -1,5 +1,10 @@"""Server mode integration tests."""+import os+import socket+import sys+import time+import pytestfrom utils.llamafile import LlamafileRunner@@ -156,3 +161,70 @@ class TestServerParameters:finally:proc.terminate()proc.wait()+++def _unix_http_get(sock_path: str, path: str, timeout: float) -> tuple[int, bytes]:+ """Minimal HTTP/1.1 GET over a Unix domain socket: (status, body)."""+ with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as s:+ s.settimeout(timeout)+ s.connect(sock_path)+ s.sendall(+ f"GET {path} HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n".encode()+ )+ data = b""+ while chunk := s.recv(65536):+ data += chunk+ head, _, body = data.partition(b"\r\n\r\n")+ return int(head.split(b" ", 2)[1]), body++[email protected](sys.platform == "win32", reason="the test client needs AF_UNIX on a POSIX host")+class TestServerUnixSocket:+ """--host <path>.sock serves HTTP over a Unix domain socket.++ --unsecure keeps these independent of the pledge() sandbox, which+ test_sandbox.py covers.+ """++ # "server.sock" relative to the server's cwd is 11 bytes: shorter than+ # the 14 a path needs for 2 + strlen(path) to reach sizeof(struct+ # sockaddr), below which Cosmopolitan's bind() returns EINVAL.+ @pytest.mark.parametrize(+ "relative", [False, True], ids=["absolute-path", "short-relative-path"]+ )+ def test_server_on_unix_socket(+ self, executable, model, gpu_mode, server_port, timeouts, tmp_path, monkeypatch, relative+ ):+ # absolute paths so the runner is unaffected by the chdir below+ runner = LlamafileRunner(+ executable=os.path.abspath(executable),+ model=os.path.abspath(model) if model else None,+ gpu=gpu_mode,+ )+ monkeypatch.chdir(tmp_path) # the server inherits it+ host = "server.sock" if relative else str(tmp_path / "server.sock")+ sock_path = str(tmp_path / "server.sock")+ if len(sock_path) >= 108:+ pytest.skip("tmp_path too long for sun_path")++ proc = runner.start_server(port=server_port, extra_args=["--host", host, "--unsecure"])+ try:+ deadline = time.time() + timeouts.server_ready+ status = None+ while time.time() < deadline and proc.poll() is None:+ if os.path.exists(sock_path):+ try:+ status, _ = _unix_http_get(sock_path, "/health", 5)+ if status == 200:+ break+ except OSError:+ pass+ time.sleep(0.5)+ assert status == 200, f"server did not answer /health on --host {host}"++ status, body = _unix_http_get(sock_path, "/v1/models", timeouts.http_request)+ assert status == 200 and b'"data"' in body+ finally:+ proc.terminate()+ proc.wait()