From efdbf80785557c7eda8e76b9546df8ce2a4e6bb3 Mon Sep 17 00:00:00 2001 From: Jaeyeong Choi <144660874+Jaeyeong-CHOI@users.noreply.github.com> Date: Thu, 12 Nov 2026 14:17:59 +0900 Subject: [PATCH 1/4] fix(python): preserve socket paths when no child was spawned `ManagedServer.close()` unlinked the configured Unix socket path whether or not this manager had ever started a server. A constructor that failed before the spawn (a missing binary, for example) ran that cleanup too, so an existing file, or another server's live socket, at the `socket=` path was deleted by a client that never created it. The path is now removed only when a child process was created. --- python/src/mlxcel/_server.py | 4 ++- python/tests/test_socket_cleanup.py | 56 +++++++++++++++++++++++++++++ 2 files changed, 59 insertions(+), 1 deletion(-) create mode 100644 python/tests/test_socket_cleanup.py diff --git a/python/src/mlxcel/_server.py b/python/src/mlxcel/_server.py index 700db3657..8a52b38d4 100644 --- a/python/src/mlxcel/_server.py +++ b/python/src/mlxcel/_server.py @@ -368,7 +368,9 @@ def close(self) -> None: if self._log_thread is not None and self._log_thread.is_alive(): self._log_thread.join(timeout=1.0) - if self.uds_path is not None and os.path.exists(self.uds_path): + # Before a child is spawned (for example, binary discovery failed), + # this manager has not created a socket and must not unlink that path. + if proc is not None and self.uds_path is not None and os.path.exists(self.uds_path): try: os.unlink(self.uds_path) except OSError: diff --git a/python/tests/test_socket_cleanup.py b/python/tests/test_socket_cleanup.py new file mode 100644 index 000000000..1869c9988 --- /dev/null +++ b/python/tests/test_socket_cleanup.py @@ -0,0 +1,56 @@ +"""A manager that never spawned a child must not remove another owner's path.""" + +from __future__ import annotations + +import socket +import sys +import tempfile +from pathlib import Path + +import pytest + +import mlxcel +from mlxcel._server import ManagedServer + + +@pytest.mark.skipif(sys.platform.startswith("win"), reason="Unix socket lifecycle") +@pytest.mark.parametrize("path_kind", ["regular", "live_socket"]) +@pytest.mark.parametrize("caller", ["manager_close", "sync_constructor", "async_constructor"]) +def test_unstarted_manager_preserves_existing_path(path_kind: str, caller: str) -> None: + # Keep sun_path short even when pytest's own temporary directory is long. + with tempfile.TemporaryDirectory(prefix="mlxcel-owner-", dir="/tmp") as directory: + root = Path(directory) + path = root / "existing.sock" + live = None + if path_kind == "regular": + path.write_text("owned by the test, not the manager") + else: + live = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + live.bind(str(path)) + live.listen(1) + live.settimeout(1.0) + + try: + if caller == "manager_close": + manager = ManagedServer("unused/model", socket_path=str(path)) + assert manager._proc is None + manager.close() + manager.close() # idempotent, including before start + else: + cls = mlxcel.LLM if caller == "sync_constructor" else mlxcel.AsyncLLM + with pytest.raises(mlxcel.MlxcelServerError, match="binary not found"): + cls("unused/model", binary=str(root / "absent-binary"), socket=str(path)) + + assert path.exists() + if live is None: + assert path.read_text() == "owned by the test, not the manager" + else: + # Check the listener is still reachable, not merely its path. + with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as client: + client.settimeout(1.0) + client.connect(str(path)) + accepted, _ = live.accept() + accepted.close() + finally: + if live is not None: + live.close() From ca887fff19e285acee3370f08dd6ff11ef63c565 Mon Sep 17 00:00:00 2001 From: Jaeyeong Choi <144660874+Jaeyeong-CHOI@users.noreply.github.com> Date: Thu, 12 Nov 2026 14:46:44 +0900 Subject: [PATCH 2/4] fix(python): keep live sockets and non-socket entries at the managed path Before it spawned the server, `ManagedServer.start()` unlinked whatever existed at the Unix socket path. A regular file there was deleted, and a second client started on a running server's socket removed that server's path, leaving it running but unreachable. Remove only a socket nobody listens on (one non-blocking connect that is refused), so a leftover from a crashed server is still replaced. An entry that is not a socket, or a socket that is in use, now fails the start with `MlxcelServerError` before any process is spawned and is left as it is. --- python/README.md | 2 + python/src/mlxcel/_server.py | 76 ++++++++++- python/tests/test_startup_path.py | 220 ++++++++++++++++++++++++++++++ 3 files changed, 292 insertions(+), 6 deletions(-) create mode 100644 python/tests/test_startup_path.py diff --git a/python/README.md b/python/README.md index 6569318e9..7168e21a3 100644 --- a/python/README.md +++ b/python/README.md @@ -59,6 +59,8 @@ Runnable scripts live in [`examples/`](examples/). Each expects the `mlxcel` bin On POSIX, managed mode defaults to a Unix domain socket for low-overhead local IPC. Keep socket paths short (`sun_path` is about 104 bytes on macOS, 108 on Linux); the default lives under `/tmp`. Pass `socket=` to override. Windows uses TCP. +When a managed start finds something at the socket path, it removes a socket nobody listens on (a leftover from a server that crashed) and starts. It does not replace a socket another server is listening on, or an entry that is not a socket (a file, a directory, a symlink): the start raises `MlxcelServerError` and the entry is left as it is. The check is not a lock against another process creating the path at the same moment. + ## Server options (`**server_kwargs`) In managed mode, extra keyword arguments to `LLM` / `AsyncLLM` are forwarded to the spawned `mlxcel serve` process: `ctx_size`, `n_predict`, `alias`, and `warmup` map to the matching CLI flags, `extra_args=[...]` appends raw CLI arguments verbatim, and `shutdown_grace` sets the termination grace period on close. diff --git a/python/src/mlxcel/_server.py b/python/src/mlxcel/_server.py index 8a52b38d4..3ef4a6309 100644 --- a/python/src/mlxcel/_server.py +++ b/python/src/mlxcel/_server.py @@ -17,6 +17,7 @@ import secrets import shutil import socket +import stat import subprocess import sys import threading @@ -83,6 +84,71 @@ def _free_tcp_port() -> int: return int(sock.getsockname()[1]) +def _clear_stale_socket(path: str) -> None: + """Remove a socket nobody listens on; refuse any other existing entry. + + A socket file outlives the process that bound it, so a leftover from a + crashed server is removed and the path reused. Two things are left alone, + with an error instead of a start: an entry that is not a socket (a regular + file, a directory, a symlink), and a socket that still has a listener, which + would otherwise keep running with its path taken away. + + One non-blocking connection attempt decides which it is. Only "connection + refused" reads as nobody there. A connection that is accepted or queued, or + a full accept queue (EAGAIN on Linux), means a listener; any other error (no + permission to connect, a socket of another type) leaves the question open, + and the socket is not removed on a guess. macOS answers "connection refused" + for a full accept queue too, so a saturated listener cannot be told from a + stale socket there. The check and the removal are two steps, so this is not + a lock against another process creating the path in between. + """ + try: + mode = os.lstat(path).st_mode + except FileNotFoundError: + return + except OSError as exc: + raise MlxcelServerError(f"Cannot inspect Unix socket path {path!r}: {exc}") from exc + if not stat.S_ISSOCK(mode): + raise MlxcelServerError( + f"Unix socket path {path!r} exists and is not a socket; it is left as it is. " + "Remove it or pass another socket=... path." + ) + + stale = False + unknown: Optional[OSError] = None + probe = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + try: + probe.setblocking(False) + probe.connect(path) + except (ConnectionRefusedError, FileNotFoundError): + stale = True + except BlockingIOError: + # The listener's accept queue is full: it is there. + pass + except OSError as exc: + unknown = exc + finally: + probe.close() + if unknown is not None: + raise MlxcelServerError( + f"Cannot tell whether Unix socket {path!r} is still in use ({unknown}); it is left " + "as it is. Remove it or pass another socket=... path." + ) from unknown + if not stale: + raise MlxcelServerError( + f"Unix socket path {path!r} is in use by a running listener; it is left as it is. " + "Stop that server, pass another socket=... path, or connect to it by passing " + "socket=... without a model." + ) + + try: + os.unlink(path) + except FileNotFoundError: + pass + except OSError as exc: + raise MlxcelServerError(f"Cannot remove stale Unix socket {path!r}: {exc}") from exc + + def _default_socket_path() -> str: """A short, unique Unix socket path under ``/tmp``. @@ -223,12 +289,10 @@ def start(self) -> None: if self.api_key: env["LLAMA_API_KEY"] = self.api_key - # Remove a stale socket file so bind does not fail on EADDRINUSE. - if self.uds_path is not None and os.path.exists(self.uds_path): - try: - os.unlink(self.uds_path) - except OSError: - pass + # Remove a stale socket file so bind does not fail on EADDRINUSE, and + # refuse to start over anything else that is already at the path. + if self.uds_path is not None: + _clear_stale_socket(self.uds_path) try: self._proc = subprocess.Popen( # noqa: S603 - command built from trusted args diff --git a/python/tests/test_startup_path.py b/python/tests/test_startup_path.py new file mode 100644 index 000000000..cca471c05 --- /dev/null +++ b/python/tests/test_startup_path.py @@ -0,0 +1,220 @@ +"""Managed startup replaces a stale socket and nothing else at its path.""" + +from __future__ import annotations + +import asyncio +import os +import socket +import stat +import sys +import tempfile +from pathlib import Path +from typing import Iterator, List, Optional + +import pytest + +import mlxcel +from mlxcel._server import ManagedServer + +FAKE_SERVER = Path(__file__).resolve().parent / "fake_server.py" + +pytestmark = pytest.mark.skipif(sys.platform.startswith("win"), reason="Unix socket lifecycle") + +KEPT = ["regular", "directory", "symlink", "live_socket", "datagram_socket", "no_permission"] +if sys.platform == "linux": + # A full accept queue answers EAGAIN on Linux. macOS answers ECONNREFUSED, + # the same as for a stale socket, so the case cannot be recognised there. + KEPT.append("full_backlog") + + +@pytest.fixture +def root() -> Iterator[Path]: + # Keep sun_path short even when pytest's own temporary directory is long. + with tempfile.TemporaryDirectory(prefix="mlxcel-start-", dir="/tmp") as directory: + yield Path(directory) + + +def _executable(path: Path, body: str) -> str: + path.write_text(f"#!{sys.executable}\n{body}") + path.chmod(path.stat().st_mode | stat.S_IXUSR) + return str(path) + + +def _start(caller: str, binary: str, path: Path) -> None: + if caller == "manager": + manager = ManagedServer( + "unused/model", + binary=binary, + socket_path=str(path), + startup_timeout=2.0, + shutdown_grace=0.1, + ) + try: + manager.start() + finally: + manager.close() + elif caller == "sync_constructor": + mlxcel.LLM( + "unused/model", binary=binary, socket=str(path), startup_timeout=2.0, shutdown_grace=0.1 + ) + else: + mlxcel.AsyncLLM( + "unused/model", binary=binary, socket=str(path), startup_timeout=2.0, shutdown_grace=0.1 + ) + + +@pytest.mark.parametrize("path_kind", KEPT) +@pytest.mark.parametrize("caller", ["manager", "sync_constructor", "async_constructor"]) +def test_startup_keeps_an_entry_that_is_not_a_stale_socket( + path_kind: str, caller: str, root: Path +) -> None: + path = root / "existing.sock" + marker = root / "child-started" + # The child only records that it ran. It never binds or unlinks, so what + # happens to the path below is the Python client's doing alone. + child = _executable( + root / "child", + f"from pathlib import Path\nPath({str(marker)!r}).write_text('started')\n" + "raise SystemExit(1)\n", + ) + owner: Optional[socket.socket] = None + queued: List[socket.socket] = [] + if path_kind == "regular": + path.write_text("another owner's file") + elif path_kind == "directory": + path.mkdir() + elif path_kind == "symlink": + path.symlink_to(root / "absent-target") + elif path_kind == "datagram_socket": + owner = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM) + owner.bind(str(path)) + elif path_kind == "no_permission": + # A leftover socket this user may not connect to: the probe is denied, + # so nothing is known about its owner. + leftover = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + leftover.bind(str(path)) + leftover.close() + path.chmod(0) + with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as check: + try: + check.connect(str(path)) + except PermissionError: + pass + except OSError: + pytest.skip("this user is not denied by file permissions") + else: + owner = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + owner.bind(str(path)) + owner.listen(0 if path_kind == "full_backlog" else 1) + owner.settimeout(1.0) + if path_kind == "full_backlog": + # Fill the accept queue until the kernel stops taking connections. + for _ in range(16): + client = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + client.setblocking(False) + queued.append(client) + try: + client.connect(str(path)) + except BlockingIOError: + break + else: + pytest.fail("the accept queue never filled") + + before = path.lstat() + try: + with pytest.raises(mlxcel.MlxcelServerError) as caught: + _start(caller, child, path) + + message = str(caught.value) + assert not marker.exists(), f"the child was started: {message}" + assert os.path.lexists(path), f"the entry was removed: {message}" + after = path.lstat() + assert (after.st_dev, after.st_ino, after.st_mode) == ( + before.st_dev, + before.st_ino, + before.st_mode, + ) + assert str(path) in message + if path_kind in ("regular", "directory", "symlink"): + assert "not a socket" in message + elif path_kind in ("datagram_socket", "no_permission"): + assert "Cannot tell whether" in message + else: + assert "in use by a running listener" in message + if path_kind == "regular": + assert path.read_text() == "another owner's file" + elif path_kind == "symlink": + assert os.readlink(path) == str(root / "absent-target") + elif path_kind == "live_socket": + assert owner is not None + with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as client: + client.settimeout(1.0) + client.connect(str(path)) + accepted, _ = owner.accept() + accepted.close() + finally: + for client in queued: + client.close() + if owner is not None: + owner.close() + + +@pytest.mark.parametrize("caller", ["manager", "sync_constructor", "async_constructor"]) +def test_startup_replaces_a_socket_nobody_listens_on(caller: str, root: Path) -> None: + path = root / "stale.sock" + bound = root / "child-bound" + # This child stands in for a server that does not clear the path itself: + # its bind fails with "address already in use" unless the client removed + # the leftover socket first. + child = _executable( + root / "child", + "import socket, sys, time\n" + "from pathlib import Path\n" + "path = sys.argv[sys.argv.index('--host') + 1]\n" + "server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)\n" + "server.bind(path)\n" + "server.listen(1)\n" + f"Path({str(bound)!r}).write_text('bound')\n" + "time.sleep(0.3)\n" + "raise SystemExit(1)\n", + ) + leftover = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + leftover.bind(str(path)) + leftover.close() + before = path.lstat() + assert stat.S_ISSOCK(before.st_mode) + + # The stand-in never answers /health and exits, so startup still reports + # an error; what matters is that it could bind the path. + with pytest.raises(mlxcel.MlxcelServerError) as caught: + _start(caller, child, path) + assert bound.exists(), f"the child could not bind the stale path: {caught.value}" + + +@pytest.mark.parametrize("use_async", [False, True]) +def test_managed_client_serves_on_a_path_with_a_stale_socket(use_async: bool, root: Path) -> None: + path = root / "stale.sock" + shim = _executable( + root / "mlxcel-shim", + "import os, sys\n" + f"argv = [{sys.executable!r}, {str(FAKE_SERVER)!r}] + sys.argv[1:]\n" + f"os.execv({sys.executable!r}, argv)\n", + ) + leftover = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + leftover.bind(str(path)) + leftover.close() + + if use_async: + + async def exercise() -> str: + llm = mlxcel.AsyncLLM("fake/model", binary=shim, socket=str(path)) + try: + return await llm.generate("hello") + finally: + await llm.close() + + assert asyncio.run(exercise()) == "hello world" + else: + with mlxcel.LLM("fake/model", binary=shim, socket=str(path)) as llm: + assert llm.generate("hello") == "hello world" + assert not os.path.lexists(path) From 2144c707ee4e0081aaaf4ac5bb9b35c2b76bb7c6 Mon Sep 17 00:00:00 2001 From: Jeongkyu Shin Date: Sat, 14 Nov 2026 15:28:19 +0900 Subject: [PATCH 3/4] fix(python): treat a dropped health probe as still starting on macOS On macOS, six of the new startup-path cases failed. A child that exits while the readiness probe is queued makes httpx raise RemoteProtocolError there (Linux reports a ReadError), and _probe_once did not catch it, so start() leaked a raw httpx exception instead of reporting the dead child as MlxcelServerError with its stderr. The probe now treats a dropped connection as "still starting" and the next liveness check reports the exit. The live-listener cases used a backlog of 1. The stale-socket probe's connection stays queued until accepted, and macOS then refuses the test's own reachability check, so the fixture listens with a backlog of 8. Validation: pytest python/tests -m "not e2e" on macOS with Python 3.11 and 3.9 (104 passed), ruff check, ruff format --check, mypy python/src. Refs #3016 --- python/src/mlxcel/_server.py | 14 +++++++++++--- python/tests/test_startup_path.py | 5 ++++- 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/python/src/mlxcel/_server.py b/python/src/mlxcel/_server.py index 3ef4a6309..0bbac5076 100644 --- a/python/src/mlxcel/_server.py +++ b/python/src/mlxcel/_server.py @@ -378,12 +378,20 @@ def _wait_until_ready(self) -> None: def _probe_once(client: httpx.Client, url: str) -> bool: """Return True once ``/health`` answers HTTP 200. - Connection errors (socket file not yet present, connection refused) and - HTTP 503 (loading / no slot) are treated as "still starting". + Connection errors (socket file not yet present, connection refused), a + connection dropped before a response (a child that exits mid-request: + macOS reports it as a protocol error, Linux as a read error) and HTTP + 503 (loading / no slot) are treated as "still starting"; the caller's + liveness check then reports a dead child as ``MlxcelServerError``. """ try: resp = client.get(url) - except (httpx.ConnectError, httpx.ConnectTimeout, httpx.ReadError): + except ( + httpx.ConnectError, + httpx.ConnectTimeout, + httpx.ReadError, + httpx.RemoteProtocolError, + ): return False if resp.status_code == 200: return True diff --git a/python/tests/test_startup_path.py b/python/tests/test_startup_path.py index cca471c05..fb650fec0 100644 --- a/python/tests/test_startup_path.py +++ b/python/tests/test_startup_path.py @@ -105,7 +105,10 @@ def test_startup_keeps_an_entry_that_is_not_a_stale_socket( else: owner = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) owner.bind(str(path)) - owner.listen(0 if path_kind == "full_backlog" else 1) + # The probe's connection stays queued until accepted, and macOS refuses + # new connections once a backlog of 1 holds it, so leave room for the + # reachability check below. + owner.listen(0 if path_kind == "full_backlog" else 8) owner.settimeout(1.0) if path_kind == "full_backlog": # Fill the accept queue until the kernel stops taking connections. From abf392bedb8d707138933541b834c830eb2b2b94 Mon Sep 17 00:00:00 2001 From: Jeongkyu Shin Date: Sat, 14 Nov 2026 15:29:28 +0900 Subject: [PATCH 4/4] docs: add technical report for PR #3017 --- ...3017-keep-live-socket-paths-20261114.en.md | 100 ++++++++++++++++++ ...3017-keep-live-socket-paths-20261114.ko.md | 100 ++++++++++++++++++ 2 files changed, 200 insertions(+) create mode 100644 TECHNICAL_REPORTS/3017-keep-live-socket-paths-20261114.en.md create mode 100644 TECHNICAL_REPORTS/3017-keep-live-socket-paths-20261114.ko.md diff --git a/TECHNICAL_REPORTS/3017-keep-live-socket-paths-20261114.en.md b/TECHNICAL_REPORTS/3017-keep-live-socket-paths-20261114.en.md new file mode 100644 index 000000000..57a98d4f0 --- /dev/null +++ b/TECHNICAL_REPORTS/3017-keep-live-socket-paths-20261114.en.md @@ -0,0 +1,100 @@ +# Technical Report: PR #3017 - fix(python): keep live sockets and non-socket entries at the managed path + +**Date**: 2026-11-14 +**Status**: Completed +**Languages**: Python +**Risk Level**: Medium (behavior change at startup) + +--- + +## Executive Summary + +Before spawning `mlxcel serve`, `ManagedServer.start()` unlinked whatever existed at the Unix socket path. A regular file, a directory entry, a symlink, or another server's live socket was silently removed; a running server kept its descriptor but became unreachable by path. Startup now inspects the entry first and removes only a socket nobody listens on. Anything else raises `MlxcelServerError` before a child is spawned and leaves the entry untouched. The rule matches the Rust server's `bind_unix` fix in #3021, so both layers agree on what counts as a stale socket. + +--- + +## 1. Problem Statement + +### 1.1 Background + +Managed mode on POSIX talks to the spawned server over a Unix domain socket. A socket file outlives the process that bound it, so a crashed server leaves a file that makes the next `bind()` fail with `EADDRINUSE`. The client therefore cleared the path before every start. + +### 1.2 Existing Issues + +- The clearing was unconditional: `os.path.exists(path)` then `os.unlink(path)`. +- A user who passed `socket=` pointing at a path in use by another server took that path away from it. +- A typo in `socket=` that hit a regular file deleted the file. +- #3005 (merged just before) stopped `close()` from unlinking the path when no child was spawned. Without it, the error this PR raises would still be followed by an unlink in the constructor's cleanup. + +### 1.3 Risk Assessment + +| Risk | Impact | Likelihood | +|------|--------|------------| +| A start that used to succeed by deleting an entry now fails | Callers see `MlxcelServerError` | Low, and the old behavior was destructive | +| A live listener misread as stale | Path removed as before | macOS with a completely full accept queue only | +| Race between the probe and the unlink | Two simultaneous starts on one stale path | Low, documented as not a lock | + +--- + +## 2. Technical Review + +### 2.1 Security + +The change narrows a destructive operation. `lstat` is used, so a symlink at the path is reported as "not a socket" and its target is never touched. An undeterminable probe result (`EACCES`, `EPROTOTYPE`) is treated as "in use", not as stale, so the client never deletes on a guess. + +### 2.2 Performance + +One non-blocking `connect()` on an existing socket at startup. Negligible. + +### 2.3 Compatibility & Dependencies + +- **Breaking Changes**: a start on a path holding a file, directory, symlink, live socket, or socket of another type now raises instead of deleting it. A leftover socket from a crashed server is still replaced. +- **New Dependencies**: none. +- **Compatibility**: POSIX only; Windows uses TCP and the new tests skip there. + +### 2.4 Code Quality + +`python/tests/test_startup_path.py` runs each case through `ManagedServer.start()`, `LLM(...)`, and `AsyncLLM(...)`. The stand-in child only writes a marker file, so the test proves no process started and that the entry's device, inode, and mode are unchanged. A live listener must still accept a new connection afterwards. A stale-socket case uses a child that binds the path itself and would fail with `EADDRINUSE` if the leftover were still there. + +--- + +## 3. Technical Decisions + +### 3.1 Classify with one non-blocking connect + +**Context:** a socket file carries no record of whether its owner is alive. + +| Probe result | Reading | +|---|---| +| `ECONNREFUSED`, path vanished | stale, remove | +| connected, or `EAGAIN` (Linux full queue) | live listener, refuse | +| anything else (`EACCES`, `EPROTOTYPE`) | unknown, refuse | + +Non-blocking matters: a blocking connect to a full accept queue waits for the listener to accept. The same three-way rule is used by the Rust `probe_unix_socket` in #3021. + +### 3.2 Refuse instead of falling back to a fresh path + +Silently picking another path would hide the conflict and break callers that connect to the path they passed. Raising with the path in the message lets the user stop the other server, pick another path, or connect to the running server by passing `socket=` without a model. + +### 3.3 Review follow-up: dropped probes during startup + +Running the suite on macOS exposed a separate gap in `_probe_once`. When the child exits while a readiness request is queued, httpx raises `RemoteProtocolError` on macOS (Linux reports `ReadError`). It was not caught, so `start()` leaked a raw httpx exception instead of `MlxcelServerError` with the child's stderr. It is now treated as "still starting" and the next liveness check reports the exit. The live-listener fixture also moved from a backlog of 1 to 8, because the probe's queued connection filled the backlog and macOS refused the test's own reachability check. + +--- + +## 4. Change Summary + +| File | Change | +|------|--------| +| `python/src/mlxcel/_server.py` | `_clear_stale_socket()` classifies the existing entry before spawn; `_probe_once()` also tolerates `RemoteProtocolError` | +| `python/README.md` | One paragraph on what a managed start does with an existing path | +| `python/tests/test_startup_path.py` | New: 26 to 29 cases (full-backlog case is Linux-only) | + +--- + +## 5. Learning Points + +- Unix socket semantics differ between Linux and macOS in exactly the corner this code depends on: a full accept queue is `EAGAIN` on Linux and `ECONNREFUSED` on macOS, so a saturated listener on macOS cannot be told from a stale socket. +- A probe connection that is never accepted still occupies a backlog slot. Tests that probe and then connect again need headroom in the backlog. +- Health-check loops should treat every "connection ended without a response" variant as transient and let the process-liveness check produce the error; httpx maps the same event to different exception classes per platform. +- Unverified: the check and the unlink are not atomic, and a socket bound but not yet listening reads as stale. Both are documented in the README. diff --git a/TECHNICAL_REPORTS/3017-keep-live-socket-paths-20261114.ko.md b/TECHNICAL_REPORTS/3017-keep-live-socket-paths-20261114.ko.md new file mode 100644 index 000000000..68858d130 --- /dev/null +++ b/TECHNICAL_REPORTS/3017-keep-live-socket-paths-20261114.ko.md @@ -0,0 +1,100 @@ +# 기술 보고서: PR #3017 - fix(python): keep live sockets and non-socket entries at the managed path + +**날짜**: 2026-11-14 +**상태**: 완료 +**언어**: Python +**위험도**: 중간 (시작 시 동작 변경) + +--- + +## 요약 + +`ManagedServer.start()`는 `mlxcel serve`를 띄우기 전에 Unix 소켓 경로에 있는 것을 무엇이든 삭제했습니다. 일반 파일, 디렉터리 항목, 심볼릭 링크, 다른 서버의 살아 있는 소켓까지 조용히 지워졌고, 실행 중인 서버는 디스크립터는 유지하지만 경로로는 접근할 수 없게 되었습니다. 이제 시작 전에 항목을 먼저 확인하고 아무도 listen하지 않는 소켓만 삭제합니다. 그 밖의 경우에는 자식을 띄우기 전에 `MlxcelServerError`를 발생시키고 항목은 그대로 둡니다. 이 규칙은 #3021의 Rust 서버 `bind_unix` 수정과 같으므로, 두 계층이 stale 소켓을 판단하는 기준이 일치합니다. + +--- + +## 1. 문제 정의 + +### 1.1 배경 + +POSIX의 관리형 모드는 띄운 서버와 Unix 도메인 소켓으로 통신합니다. 소켓 파일은 바인드한 프로세스보다 오래 남으므로, 비정상 종료한 서버가 남긴 파일 때문에 다음 `bind()`가 `EADDRINUSE`로 실패합니다. 그래서 클라이언트는 매번 시작 전에 경로를 비웠습니다. + +### 1.2 기존 문제 + +- 삭제가 무조건적이었습니다: `os.path.exists(path)` 다음 `os.unlink(path)`. +- `socket=`로 다른 서버가 사용 중인 경로를 넘기면 그 서버의 경로를 빼앗았습니다. +- `socket=` 오타가 일반 파일을 가리키면 그 파일이 삭제되었습니다. +- 바로 앞에 머지된 #3005는 자식을 띄우지 않았을 때 `close()`가 경로를 삭제하지 않게 했습니다. 이것이 없으면 이 PR이 발생시키는 오류 뒤에 생성자의 정리 코드가 경로를 다시 삭제했을 것입니다. + +### 1.3 위험 평가 + +| 위험 | 영향 | 가능성 | +|------|------|--------| +| 항목을 지우며 성공하던 시작이 이제 실패 | 호출자가 `MlxcelServerError`를 받음 | 낮음, 이전 동작은 파괴적이었음 | +| 살아 있는 listener를 stale로 오판 | 이전처럼 경로 삭제 | accept 큐가 완전히 찬 macOS에서만 | +| 탐침과 삭제 사이의 경쟁 | 같은 stale 경로에 대한 동시 시작 두 개 | 낮음, 락이 아니라고 문서화 | + +--- + +## 2. 기술 검토 + +### 2.1 보안 + +파괴적인 동작의 범위를 좁힙니다. `lstat`을 사용하므로 경로의 심볼릭 링크는 "소켓 아님"으로 보고되고 링크 대상은 건드리지 않습니다. 판단할 수 없는 탐침 결과(`EACCES`, `EPROTOTYPE`)는 stale이 아니라 "사용 중"으로 취급하므로 추측으로 삭제하지 않습니다. + +### 2.2 성능 + +시작 시 기존 소켓에 대해 non-blocking `connect()` 한 번. 무시할 수준입니다. + +### 2.3 호환성 및 의존성 + +- **호환성 깨짐**: 파일, 디렉터리, 심볼릭 링크, 살아 있는 소켓, 다른 종류의 소켓이 있는 경로에서의 시작은 이제 삭제 대신 오류를 냅니다. 비정상 종료한 서버가 남긴 소켓은 이전처럼 교체됩니다. +- **새 의존성**: 없음. +- **호환 범위**: POSIX 전용. Windows는 TCP를 쓰며 새 테스트는 건너뜁니다. + +### 2.4 코드 품질 + +`python/tests/test_startup_path.py`는 각 케이스를 `ManagedServer.start()`, `LLM(...)`, `AsyncLLM(...)`로 실행합니다. 대역 자식은 마커 파일만 쓰므로 프로세스가 시작되지 않았고 항목의 device, inode, mode가 바뀌지 않았음을 확인할 수 있습니다. 살아 있는 listener는 이후에도 새 연결을 받아야 합니다. stale 소켓 케이스는 경로를 직접 바인드하는 자식을 사용해, 남은 소켓이 그대로 있으면 `EADDRINUSE`로 실패하게 합니다. + +--- + +## 3. 기술적 선택과 그 이유 + +### 3.1 non-blocking connect 한 번으로 분류 + +**맥락:** 소켓 파일에는 소유자가 살아 있는지에 대한 기록이 없습니다. + +| 탐침 결과 | 해석 | +|---|---| +| `ECONNREFUSED`, 경로 사라짐 | stale, 삭제 | +| 연결됨, 또는 `EAGAIN` (Linux에서 큐가 가득 참) | 살아 있는 listener, 거부 | +| 그 밖 (`EACCES`, `EPROTOTYPE`) | 알 수 없음, 거부 | + +non-blocking이 중요합니다. 가득 찬 accept 큐에 대한 blocking connect는 listener가 accept할 때까지 기다립니다. #3021의 Rust `probe_unix_socket`도 같은 세 갈래 규칙을 사용합니다. + +### 3.2 새 경로로 대체하지 않고 거부 + +조용히 다른 경로를 고르면 충돌이 가려지고, 넘긴 경로로 접속하는 호출자가 깨집니다. 경로를 메시지에 담아 오류를 내면 사용자가 다른 서버를 멈추거나, 다른 경로를 고르거나, 모델 없이 `socket=`만 넘겨 실행 중인 서버에 접속할 수 있습니다. + +### 3.3 리뷰 후속 작업: 시작 중 끊긴 탐침 + +macOS에서 테스트를 실행하면서 `_probe_once`의 별도 결함이 드러났습니다. 준비 확인 요청이 큐에 있는 동안 자식이 종료하면 httpx는 macOS에서 `RemoteProtocolError`를(Linux는 `ReadError`) 냅니다. 이를 잡지 않아 `start()`가 자식의 stderr를 담은 `MlxcelServerError` 대신 httpx 예외를 그대로 내보냈습니다. 이제 "아직 시작 중"으로 취급하고 다음 생존 확인이 종료를 보고합니다. 또한 살아 있는 listener 픽스처의 backlog를 1에서 8로 바꿨습니다. 탐침의 대기 연결이 backlog 1을 채워 macOS가 테스트 자신의 접속 확인을 거부했기 때문입니다. + +--- + +## 4. 변경 요약 + +| 파일 | 변경 | +|------|------| +| `python/src/mlxcel/_server.py` | `_clear_stale_socket()`이 spawn 전에 기존 항목을 분류; `_probe_once()`가 `RemoteProtocolError`도 허용 | +| `python/README.md` | 관리형 시작이 기존 경로를 어떻게 다루는지 한 문단 | +| `python/tests/test_startup_path.py` | 신규: 26~29개 케이스 (full-backlog 케이스는 Linux 전용) | + +--- + +## 5. 학습 포인트 + +- Unix 소켓 동작은 이 코드가 의존하는 바로 그 지점에서 Linux와 macOS가 다릅니다. 가득 찬 accept 큐는 Linux에서 `EAGAIN`, macOS에서 `ECONNREFUSED`이므로 macOS에서는 포화된 listener와 stale 소켓을 구별할 수 없습니다. +- accept되지 않은 탐침 연결도 backlog 한 칸을 차지합니다. 탐침 후 다시 접속하는 테스트는 backlog에 여유가 필요합니다. +- 헬스 체크 루프는 "응답 없이 연결이 끝남"의 모든 변형을 일시적인 것으로 보고, 오류는 프로세스 생존 확인이 만들게 해야 합니다. httpx는 같은 사건을 플랫폼마다 다른 예외 클래스로 매핑합니다. +- 검증되지 않은 부분: 확인과 삭제는 원자적이지 않고, 바인드했지만 아직 listen하지 않은 소켓은 stale로 읽힙니다. 둘 다 README에 문서화되어 있습니다.