Skip to content

fix(python): keep live sockets and non-socket entries at the managed path - #3017

Merged
inureyes merged 5 commits into
lablup:mainfrom
Jaeyeong-CHOI:fix/python-keep-live-socket-paths
Nov 14, 2026
Merged

inureyes merged 5 commits into
lablup:mainfrom
Jaeyeong-CHOI:fix/python-keep-live-socket-paths

Conversation

@Jaeyeong-CHOI

@Jaeyeong-CHOI Jaeyeong-CHOI commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

Summary

ManagedServer.start() unlinked whatever existed at the Unix socket path before it spawned the server, so a regular file there was deleted and a running server's socket was taken away from it. It now removes only a socket nobody listens on; anything else at the path fails the start with MlxcelServerError and is left as it is.

Related issues

Closes #3016.

Stacked on #3005 (the fix for #3004): the first commit of this branch is that PR, and only the second commit is new. Without #3005 the constructor's error cleanup would delete the path that this change has just refused to touch.

Type of change

  • fix — bug fix

Cause

python/src/mlxcel/_server.py, ManagedServer.start(): if self.uds_path is not None and os.path.exists(self.uds_path): os.unlink(self.uds_path) ran right before subprocess.Popen, with no look at what the entry was.

Change

  • New _clear_stale_socket(path), called from start():
    • nothing at the path: nothing to do;
    • an entry that is not a socket (lstat, so a symlink counts as a symlink): MlxcelServerError, entry untouched;
    • a socket: one non-blocking connect. ECONNREFUSED (or the path vanishing) means nobody listens, and the socket is removed as before. A connection that is accepted or queued, or a full accept queue (EAGAIN), means a listener: MlxcelServerError ("in use by a running listener"), entry untouched. Any other error, such as EACCES or EPROTOTYPE for a socket of another type, leaves the question open: MlxcelServerError ("Cannot tell whether … is still in use"), entry untouched.
  • The error is raised before the child is spawned.
  • python/README.md: one paragraph describing this.
  • python/tests/test_startup_path.py (new), each case through ManagedServer.start(), LLM(...) and AsyncLLM(...):
    • test_startup_keeps_an_entry_that_is_not_a_stale_socket: regular file, directory, dangling symlink, live listener, datagram socket, a leftover socket the user may not connect to, and (Linux) a listener with a full accept queue. The child only writes a marker file, so the test can tell that no process was started and that the entry's device, inode and mode are unchanged; the live listener must still accept a new connection.
    • test_startup_replaces_a_socket_nobody_listens_on: the child binds the path itself and would fail with "address already in use" if the leftover socket were still there.
    • test_managed_client_serves_on_a_path_with_a_stale_socket: a full request through the suite's fake server, sync and async.

Before / after

Linux aarch64. The snippet from the issue, run as written:

main This PR
a listener at the path path removed; a new connection by path fails with FileNotFoundError MlxcelServerError: Unix socket path '…' is in use by a running listener; it is left as it is. …; a new connection succeeds
a regular file at the path deleted MlxcelServerError: Unix socket path '…' exists and is not a socket; it is left as it is. …; file kept

New test file, on the parent commit and on this PR, in both environments (Python 3.9.25 with openai 1.40.0 / httpx 0.27.0, and Python 3.12.3 with openai 3.49.0 / httpx 0.28.1):

parent (#3005) This PR
the 26 new cases 21 failed, 5 passed (the five stale-socket cases, which already worked) 26 passed
whole suite (-m "not e2e") 57 passed, 2 deselected (without the new file) 83 passed, 2 deselected

Three mutations of the fix, same two environments: with the stale socket recognised but not removed, the three test_startup_replaces_a_socket_nobody_listens_on cases fail; with an undetermined probe result treated as stale, the six datagram-socket and no-permission cases fail; with a full accept queue treated as stale, the three full-backlog cases fail.

Test plan

Run on this PR's source (the second commit of the branch; tree bedb3af550cc).

  • python -m pytest -m "not e2e" in python/: 83 passed, 2 deselected, on Python 3.9.25 with the declared lower bounds and on Python 3.12.3 with current releases
  • The new file on the parent commit: 21 failed, 5 passed, both environments
  • The three mutations above fail the cases named, both environments
  • ruff check python, ruff format --check python: pass; mypy python/src (Python 3.9 target): pass
  • What a non-blocking connect returns for each kind of socket, measured on Linux 7.0 (aarch64) and on macOS 26.2 with the standard library: stale ECONNREFUSED, live listener connects, datagram socket EPROTOTYPE, a socket with mode 000 EACCES whether or not it is live; a full accept queue gives EAGAIN on Linux and ECONNREFUSED on macOS
  • The test suite on macOS and Windows: not run (the new tests skip on Windows, where the client uses TCP)
  • The two live-model e2e tests: not run
  • Rust gates: not applicable, no Rust file changes

Notes for reviewers

  • Behavior change. A start on a path that holds a file or a live socket used to delete it and go on; it now raises. A start on a leftover socket from a crashed server works as before.
  • Limits. The check and the removal are two steps, so this is not a lock: two starts on the same stale path at the same moment can still both proceed. A socket that is bound but not yet listening answers ECONNREFUSED and reads as stale. On macOS a listener whose accept queue is completely full answers ECONNREFUSED as well, so it cannot be told from a stale socket there and loses its path as it does on main; the full-backlog test is Linux-only for that reason.
  • The Rust server's bind removes an existing path unconditionally as well; that is not changed here. fix(server): keep a running listener's Unix socket and non-socket paths #3021 applies the same rule (stale, in use, unknown from one non-blocking connect) to the Rust bind_unix.
  • Maintainer follow-up (2144c70), found running the suite on macOS. A child that exits while the readiness probe is queued makes httpx raise RemoteProtocolError on macOS (Linux reports ReadError); _probe_once did not catch it, so start() leaked a raw httpx exception instead of MlxcelServerError. It is now treated as "still starting" and the liveness check reports the dead child. The live-listener fixture also listens with a backlog of 8, since the probe's queued connection filled a backlog of 1 and macOS refused the test's own reachability check. After merging main: 104 passed, 2 deselected on macOS with Python 3.11 and 3.9.
  • Implemented and validated with AI assistance (Claude). Every number above comes from the logs of those runs.

Checklist

  • PR title uses a Conventional Commits prefix
  • One logical change per PR
  • Updated docs/: python/README.md
  • Updated // Used by: ... comments: not applicable (Python)
  • No secrets, credentials, or .env files committed

`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.
…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.
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 lablup#3016
@inureyes

Copy link
Copy Markdown
Member

Thank you for the thorough investigation, including the per-platform connect measurements. Reviewed against #3016: the stale / in use / unknown classification is sound, it refuses on any undeterminable result, and it now matches the Rust bind_unix fix in #3021, so the client and the server agree on what may be removed.

Running the suite on macOS (the first macOS run, per the test plan) turned up two things, fixed in 2144c70:

  • A child that exits while the readiness probe is queued makes httpx raise RemoteProtocolError on macOS (Linux reports ReadError). _probe_once did not catch it, so start() leaked the raw httpx exception instead of MlxcelServerError. It is now treated as "still starting" and the liveness check reports the dead child. This failed the three test_startup_replaces_a_socket_nobody_listens_on cases.
  • The live-listener fixture used a backlog of 1; the probe's queued connection filled it and macOS refused the test's own reachability check. It now listens with a backlog of 8.

I also merged main (no conflicts) and added the technical report. Locally on macOS: 104 passed, 2 deselected on Python 3.11 and 3.9; ruff and mypy clean. The test (Python 3.9) CI job fails only in setup-python (tracked by #3013).

@inureyes
inureyes merged commit bce6629 into lablup:main Nov 14, 2026
34 of 35 checks passed
@inureyes inureyes added the status:done Completed label Nov 14, 2026
inureyes pushed a commit that referenced this pull request Nov 14, 2026
…hs (#3021)

## Summary

`bind_unix` removed whatever existed at the `--host <path>.sock` path before it bound. That is right for the socket an earlier run left behind (the server leaves its own behind when it stops). It also took the path from a server still listening on it, which kept running unreachable, and deleted a regular file or a symlink found there. The path is now looked at first: only a socket nobody listens on is replaced.

## Related issues

Closes #3020.

## Type of change

- [x] `fix`: bug fix

## Cause

`src/server/listen.rs`, `bind_unix`: `if path.exists() { std::fs::remove_file(path) }`, with no look at what the entry is or whether anything answers on it.

## Change

- **`bind_unix`** takes `symlink_metadata` of the path. Nothing there: bind. Not a socket: fail, the entry is left as it is. A socket: probe it; remove it and bind as before only if the probe says nobody is there, otherwise fail and leave it.
- **`probe_unix_socket`** (new) makes one non-blocking connection attempt and returns one of three answers. *Stale*: "connection refused", or the path vanished meanwhile. *In use*: the connection was accepted or queued, or the accept queue is full (`EAGAIN` on Linux); the error says "in use by a running listener". *Unknown*: anything else, such as `EACCES` or `EPROTOTYPE` for a socket of another type; the error says "cannot tell whether the socket is still in use" and carries the OS error. Non-blocking, because a blocking connect to a full accept queue waits for the listener to accept.
- **Docs**: a paragraph in `docs/server-features.md` next to the `.sock` sentence.
- Not changed: the Python client's managed server, which removes the path itself before it spawns the server (#3016, fixed separately in #3017 with the same rule).

## Before / after

GB10 host, release builds of `955335a38` (`main`, the base of this branch) and of this PR. No model is loaded (`serve --models-dir <empty> --no-models-autoload --offline --no-webui --host <path> --port 0`); every fixture lives in a temporary directory and every child process was reaped.

| At the path before the start | `main` | This PR |
|---|---|---|
| nothing | listens, `/health` 200 | the same |
| a regular file | listens; the file is gone | exits 1, "the path exists and is not a socket"; contents intact |
| a socket with a listener | listens; the first listener no longer receives connections | exits 1, "the socket is in use by a running listener"; the first listener still accepts |
| a socket whose owner has exited | replaced, `/health` 200 | the same |
| a symlink to a file | listens; the link is gone | exits 1; link and target intact |
| restart on the server's own socket after SIGTERM, and after SIGINT | starts, `/health` 200 | the same |

Two real servers on one path:

| | `main` | This PR |
|---|---|---|
| second start | reports listening | exits 1 with the "in use" message |
| `/health` on the path while both run | 200 | 200 |
| second stopped, first still running: `/health` on the path | connection refused | 200 |

## Test plan

Run on this PR's commit (`155ac62cb`, one commit on `955335a38`, tree `fcec3af3c201`) on a DGX Spark (GB10).

- [x] `cargo fmt --all -- --check`
- [x] `cargo clippy --workspace --all-targets --features cuda -- -D warnings` (the Linux spelling of the template's line)
- [x] `cargo build --release --features cuda`
- [x] `cargo test --profile test-fast --features cuda --lib server::listen::listen_unix_tests -- --test-threads=1`: 9 passed. The cases: the server's own leftover socket, a socket whose owner is gone, a live listener (which still accepts afterwards), a listener with a full accept queue (Linux only, see the notes), a regular file, a live and a dangling symlink, a bound datagram socket, a leftover socket the user may not connect to, a new nested path
- [x] Negative control 1: with the body of `bind_unix` put back as it is on `main`, 6 of the 9 fail (regular file, symlinks, live listener, full accept queue, datagram socket, no permission) and the 3 that describe what `main` already did right pass (own leftover, owner gone, new path)
- [x] Negative control 2: with an unknown probe result taken for stale, the datagram-socket and no-permission cases fail. Restored, 9 pass again
- [x] `make verify-test-cuda` (`cargo test --workspace --profile test-fast --features cuda --no-fail-fast -- --test-threads=1`): 186 of 187 test binaries pass (15502 tests passed, 1 failed, 496 ignored), the 9 new tests among them. The one failure is `native_env_tests::the_cuda_cache_defaults_reach_mlx`, which fails the same way on a clean `main` (order-dependent; #2987)
- [x] The self-hosted `ci.yml` jobs a pull request from a fork does not get, run by hand: `clippy` (`cargo clippy -p mlxcel --lib --tests -- -D warnings`, default features), the 9 new tests on that CPU build, and `xla-compile` (`cargo check --features cuda,xla-iree --all-targets`, `cargo check --no-default-features --features xla-diagnostics --all-targets`): all pass
- [x] `make verify-python-tooling` (219 tests OK), license headers, env-var docs, kernel dtype keys, kernel port dispatch, cross-repo refs
- [x] Validated with the real binaries: the tables above
- [ ] `cargo deny check`: not run and not applicable (no manifest, lockfile or `deny.toml` change; `socket2` is already a dependency with `all`)
- [x] What a non-blocking `connect` answers for each kind of socket, measured with the Python standard library on Linux 7.0 (aarch64) and macOS 26.2: stale `ECONNREFUSED`, bound but not listening `ECONNREFUSED`, live listener connects, datagram socket `EPROTOTYPE`, mode 000 `EACCES` (live or stale); full accept queue `EAGAIN` on Linux and `ECONNREFUSED` on macOS
- [ ] macOS: the Rust code was not built or run there

## Notes for reviewers

- **Behavior change, on purpose.** A start on a path that holds a file, a symlink or a live listener's socket now fails with a message that says which. A start on a stale socket is unchanged.
- **Why not refuse every existing entry.** The server does not remove its socket on SIGTERM or SIGINT (measured on both), so that rule cannot restart on its own path. I tried it first and it failed exactly there.
- **The check and the removal are two steps.** Two servers started on one stale path at the same instant can both see "nobody there"; the later bind takes the path, which is what happens today in every case. This closes the ordinary double start, not that race.
- **A bound socket that has not called `listen` yet** also answers "connection refused". `tokio`'s `UnixListener::bind` binds and listens in one call, so for mlxcel's own servers that state is not observable from outside; a foreign program that binds early and listens much later could still lose its path, as it does today.
- **Full accept queue on macOS.** Linux answers a non-blocking connect to a full accept queue with `EAGAIN`, which the probe counts as in use (tested). macOS answers "connection refused", the same as for a stale socket, so a listener that is saturated at that moment is treated as stale there and loses its path, as it does on `main`. The test for this case is `#[cfg(target_os = "linux")]` for that reason, and the docs paragraph says so.
- **A socket the user may not connect to is refused, not removed.** `main` removed a leftover socket owned by another user if the directory allowed it; the probe gets `EACCES` for such a socket whether it is live or not, so the start now fails with the "cannot tell" message and the user removes it or picks another path.
- **The probe is a real connection.** A live server sees one connection that is closed at once.

## Checklist

- [x] PR title uses a Conventional Commits prefix
- [x] One logical change per PR
- [x] Updated `docs/`: `docs/server-features.md`
- [x] Updated `// Used by: ...` comments: on the new function
- [x] No secrets, credentials, or `.env` files committed


Maintainer follow-up: the socket probe treats EINPROGRESS as in use, a directory-at-path test was added, and the change was validated on macOS with two real servers on one socket path.
inureyes added a commit to Jaeyeong-CHOI/mlxcel that referenced this pull request Nov 14, 2026
test_startup_replaces_a_socket_nobody_listens_on (from lablup#3017) failed in about one run in two on a loaded macOS host with "did not become ready within 2s": a freshly written stand-in executable can take seconds to launch there (XProtect scans it on first exec), and the 2 s budget killed the child before it recorded that it bound the path. The stand-ins exit on their own well before the budget, so raising it to 10 s costs no time on a healthy run.

Validation: five consecutive full runs of pytest python/tests -m "not e2e" on Python 3.9 on the same host (128 passed each, previously 3 of 5 failed), plus Python 3.11, ruff check, ruff format --check.

Refs lablup#3008
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

status:done Completed

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix(python): managed server start unlinks any existing socket path, including a live server's socket

2 participants