Skip to content

fix(server): drain gracefully on SIGTERM and SIGINT - #3508

Merged
inureyes merged 3 commits into
mainfrom
fix/issue-3483-graceful-shutdown
Nov 28, 2026
Merged

inureyes merged 3 commits into
mainfrom
fix/issue-3483-graceful-shutdown

Conversation

@inureyes

@inureyes inureyes commented Nov 28, 2026 •

Copy link
Copy Markdown
Member

Summary

mlxcel-server and mlxcel serve now stop on SIGTERM and SIGINT through a bounded graceful drain, then join their model workers and exit 0. Before this, a container's PID 1 ignored both signals until the SIGKILL, and outside a container SIGTERM killed the process mid-request (exit 143).

The contract that #3484 and #3486 depend on is implemented as the issue specifies, with no renames: --shutdown-timeout <SECONDS> and MLXCEL_SHUTDOWN_TIMEOUT, default 30, 0 = no drain. Exit code is 0 after a full drain and after a drain that hit the timeout, and 1 on a second signal.

Behavior

  • New src/server/shutdown.rs. The handler is installed at the top of start_server and latches the first signal in a CancellationToken. A signal that arrives during model load or warmup is not lost: the listener logs shutdown requested before the listener was bound; not serving and the process exits 0 through the worker join. The same task logs second shutdown signal (...); exiting without drain on a second signal and exits 1 via _exit, which skips the static destructors behind fix: 2-host logical PP CI aborts with pure virtual call at process exit #2738. If the SIGTERM handler cannot be installed, the error is logged and the server keeps running with SIGINT only.
  • listen::serve takes shutdown and drain in ServeOptions. On shutdown it drops the listener, so new connections are refused, and calls hyper's graceful_shutdown on every live connection: idle keep-alive connections close at once, and in-flight responses, SSE included, finish. Connections still open at the deadline are aborted with shutdown: drain timeout after N s, aborting M connection(s). Connections are tracked in a JoinSet rather than TaskTracker, because JoinSet can abort at the deadline and needs no tokio-util rt feature. A TLS handshake runs inside the tracked task, so it counts as in flight.
  • A Unix-socket listener removes its own socket file when it stops accepting. The unlink happens while the listener is still open, and only if the file still matches the device, inode and change time recorded at bind time. A replacement server started on the same path therefore keeps its socket. The bind_unix doc comment is updated to match.
  • Router mode: the ctrl_c() arm is removed rather than swapped for shutdown_signal(). Racing a signal arm against serve_http would drop it mid-drain. serve_http now owns the signal, and shutdown_all(ROUTER_SHUTDOWN_TIMEOUT) runs after it returns. The remote pipeline stage waits on the same latch.
  • A signal during pipeline bring-up (coordinator discovery, or a --pp-peer waiting for its assignment) now ends startup with exit 0 before any model loads, instead of waiting out the bring-up timeout.
  • An upgraded /v1/realtime WebSocket has already left hyper's connection, so it is cut at process exit. This is documented.

Changes during review

  • The implementation review found two HIGH issues and fixed both. A signal during pipeline bring-up was ignored, which is fixed with shutdown::unless_shutdown. Socket cleanup could remove a replacement server's socket, which is fixed with an identity check.
  • The security review raised two MEDIUM issues, both fixed. The socket is now unlinked before the listener closes, which closes the remaining check-to-unlink race. Each connection now waits on a child token, so connections no longer share one mutex on every IO wake.
  • Known, not changed: if a signal arrives during a model load longer than WORKER_EXIT_TIMEOUT (120 s) on a path that binds before the load finishes, the process exits through the existing worker-join timeout error, which is non-zero.

Test plan

  • cargo test --release --lib -- server::listen:: server::shutdown::: 38 passed. This includes 8 new socket-level drain tests (idle, silent client, keep-alive, in-flight SSE, deadline abort, zero drain, pre-bind cancel, Unix socket removal) plus ConnectionDrain tests and socket-identity tests.
  • cargo test --release --test server_graceful_shutdown: 8 passed against real mlxcel-server and mlxcel serve processes. The cases are idle SIGTERM, a stream finishing with [DONE], --shutdown-timeout 2 abort, SIGINT, second signal exits 1, router mode, mlxcel serve, and Unix socket removal. The test falls back to qwen3-1.7b-4bit, because the qwen3-0.6b-4bit link on this host is dangling. For the same reason server_exit_joins_worker skips here.
  • cargo clippy --release --features metal,accelerate --lib --tests --bins -- -D warnings, cargo fmt --check, check_env_var_docs.py, check_native_env_writes.py, check_llama_compat_manifest.py, check_cross_repo_refs.py.
  • Manual run on M1 Ultra with qwen3-1.7b-4bit, single runs, kill -<SIG> then wait:
Binary Case Exit Signal to exit Client
this PR idle SIGTERM (3 runs) 0 0.15 to 0.16 s
this PR idle SIGINT 0 0.15 s
this PR SIGTERM mid-stream (64 tokens) 0 0.97 s [DONE] received
this PR SIGINT mid-stream 0 0.61 s [DONE] received
this PR SIGTERM, --shutdown-timeout 2 --ignore-eos, 30k-token stream 0 2.21 s aborted, 1 connection logged
this PR SIGTERM 1.5 s into an 11B load 0 after load, not serving
pre-change build idle SIGTERM 143 0.16 s
pre-change build SIGTERM mid-stream 143 0.15 s stream cut, no [DONE]
  • Linux CUDA validation: not possible on this host and still open.

Closes #3483

@inureyes inureyes added status:review Under review type:bug Bug fixes, error corrections, or issue resolutions priority:medium Medium priority labels Nov 28, 2026
@inureyes

Copy link
Copy Markdown
Member Author

Implementation Review Summary

Intent

Drain the HTTP server on SIGTERM/SIGINT within --shutdown-timeout and exit 0 (1 on a second signal), on every serve path.

Findings Addressed

  • --pp-peer assignment wait, coordinator discovery and the assignment push ignored the first signal, because the latch is installed at the top of start_server and nothing consulted it before the listener. Reproduced: a waiting peer was still alive 10 s after SIGTERM (it would wait up to 600 s), where main exits at once. The bring-up now races the token and returns Ok(()) before any model loads; a waiting peer now exits 0 at once. (HIGH, 8ffa232)
  • Unix socket cleanup unlinked any socket at the path. The listener is dropped before the drain, so a replacement server started during the drain could bind the path and then lose its live socket. Cleanup now checks the device, inode and change time captured at bind. Unit tests cover both cases. (HIGH, 8ffa232)

Remaining Items

  • A signal during a model load longer than WORKER_EXIT_TIMEOUT (120 s), on a path that binds before the load completes, ends in the worker-join timeout error (non-zero exit) rather than exit 0. That is the existing fix: 2-host logical PP CI aborts with pure virtual call at process exit #2738 join behavior. No test signals during load. (MEDIUM, report only)
  • resolve_distributed_startup waits are not raced against the token. They are bounded by 5 s timeouts, so this was left alone. (LOW)
  • With no signal, a fatal accept error now waits up to --shutdown-timeout for live connections before returning the error. (LOW)
  • The integration tests skip on qwen3-0.6b-4bit or qwen3-1.7b-4bit. They ran with 1.7b here. Linux CUDA validation is not done. (LOW)

Verification

  • All stated requirements implemented
  • No placeholder/mock code remaining
  • Integrated into project code flow (single model, router mode, disaggregated router front-end, pipeline stage, mlxcel serve)
  • Project conventions followed
  • Existing modules reused where applicable
  • No unintended structural changes
  • Tests pass: server::listen:: server::shutdown:: 38 pass, server_graceful_shutdown 8 pass, clippy --lib --tests --bins -D warnings clean, fmt clean

@inureyes

Copy link
Copy Markdown
Member Author

Security and Performance Review

No CRITICAL or HIGH findings, so no commits were pushed. Everything below is report only. All of it was checked by reading the code. Nothing was benchmarked.

MEDIUM

  • One lock shared by every connection on each wake (listen.rs drive_connection). Every connection selects on a clone of the listener-wide graceful token. In tokio 1.54 a pending Notified takes the token's Notify waiter mutex every time it is polled (notify.rs, State::Waiting), and select! polls both arms on each wake. So each IO wake on each connection (every SSE chunk, for example) takes one mutex that all runtime workers share. Before this PR a connection had no shared lock on its poll path. Suggested fix: give each connection graceful.child_token(). A child has its own Notify, so the parent lock is taken only when the child is created and dropped, and cancelling the parent still reaches every child. I did not measure contention at high concurrency.
  • Socket removal can race a replacement server (shutdown.rs remove_own_socket). The listener is dropped before the drain, and the path is checked and then unlinked afterwards. A replacement can run bind_unix between the stat and the unlink: it clears our stale socket and binds its own. Our remove_file then deletes the replacement's live socket. The window is microseconds wide, and the dev/ino/ctime check cannot close it. Suggested fix: do the identity check and the unlink while the listener is still bound, before drop(listener). While it is bound, bind_unix in any other process sees a live socket and refuses, so the path cannot change between the check and the unlink. New connections are refused either way.

LOW

  • A TLS client that opens TCP and never sends a ClientHello keeps the drain waiting until --shutdown-timeout, because acceptor.accept is not raced against graceful. Slowloris-style header trickling behaves the same way. Both are bounded by the deadline, which is the accepted design. A plaintext connection that has sent nothing closes at once, because hyper-util 0.1.21 cancels ReadVersion on graceful_shutdown.
  • HTTP/2 stream tasks are spawned through TokioExecutor, outside the JoinSet, so abort_all does not cancel them directly. They end once their connection is dropped, so the bound still holds.
  • A chmod or chown on the socket after bind changes its ctime. Cleanup then leaves the socket in place and logs that it belongs to another server. This fails safe, since the next start clears the stale socket, but the log message is misleading.
  • The second-signal _exit(1) depends on the runtime polling the listener task. With the default worker count (at least n_parallel + 4) this always happens. With --threads-http 1 and a load that blocks that worker, the second signal could be delayed.
  • Per-accept cost: each loop iteration registers a fresh cancelled() waiter on the process latch and runs a try_join_next reap loop. The cost is negligible next to accept plus spawn, and the JoinSet cannot grow without bound because finished tasks are reaped on every accept and before the drain.

Checked and clean

  • Unsafe blocks: libc::_exit in shutdown.rs and libc::kill in tests/server_graceful_shutdown.rs both have accurate SAFETY comments.
  • Large --shutdown-timeout values: tokio::time::timeout uses checked_add, so a large value cannot overflow and panic.
  • The drain is bounded by the deadline plus a 1 s abort settle.
  • Panicking connection tasks are reaped without stopping the accept loop.

mlxcel-server and mlxcel serve installed no SIGTERM handler, and the HTTP path no SIGINT handler either. As a container's PID 1 both signals were ignored until the supervisor's SIGKILL cut requests mid-stream and skipped the #2738 worker join; elsewhere SIGTERM killed the process the same way.

A process-wide handler is installed at the top of start_server and latches the first signal in a CancellationToken, so a signal during model load is not lost. The accept loop stops on that token: it drops the listener, calls hyper's graceful_shutdown on every live connection (idle keep-alive closes at once, in-flight responses and SSE streams finish), aborts what is still open after --shutdown-timeout / MLXCEL_SHUTDOWN_TIMEOUT (default 30 s, 0 aborts at once) and returns Ok, so the worker join runs and the process exits 0. A second signal exits 1 through _exit without draining. A Unix-socket listener removes its own socket file. Router mode lets serve_http own the signal and drain before shutdown_all; the pipeline stage waits on the same latch.

Validated with qwen3-1.7b-4bit on M1 Ultra: idle SIGTERM/SIGINT exit 0 in 0.15 s, mid-stream SIGTERM delivers [DONE] and exits 0, --shutdown-timeout 2 exits 0 after 2.2 s with one aborted connection. New tests: listen_shutdown_tests, shutdown_tests, tests/server_graceful_shutdown.rs.

Closes #3483
The shutdown handler installed at the top of start_server replaced the default SIGTERM/SIGINT action for the whole startup, but nothing consulted the latch until the listener or the stage wait. A --pp-peer waiting for its stage assignment (up to PEER_ASSIGNMENT_TIMEOUT, 600 s), coordinator discovery and the assignment push therefore ignored the first signal; on main the process died at once. The zero-config bring-up now races the shutdown token through shutdown::unless_shutdown and returns Ok(()) before any model loads. Verified by sending SIGTERM to a waiting --pp-peer: exit 0 at once, where the previous commit kept waiting.

The Unix socket cleanup removed any socket at the path after the drain. The listener is dropped before the drain, so a replacement server started meanwhile can clear the old socket in bind_unix and bind its own, which the old server then unlinked. The cleanup now compares the device, inode and change time captured at bind time and leaves another server's socket in place, with unit tests for both cases.

Refs #3483
…tokens

Two findings from the security review of the drain. Socket removal ran after the listener closed, which left a microsecond window in which a replacement server's bind_unix could clear the socket and bind its own, and the identity check could not close that window. The unlink now runs while the listener still listens, so a replacement sees the path as in use. Each connection also waits on a child of the drain token instead of a clone, so a pending wait does not take one mutex shared by every connection on every IO wake.

Unit tests (server::listen, server::shutdown: 38) and tests/server_graceful_shutdown.rs (8) pass.

Refs #3483
@inureyes
inureyes force-pushed the fix/issue-3483-graceful-shutdown branch from d18ad9d to 0090482 Compare November 28, 2026 13:35
@inureyes
inureyes marked this pull request as ready for review November 28, 2026 16:08
@inureyes
inureyes merged commit 42a391c into main Nov 28, 2026
33 checks passed
@inureyes
inureyes deleted the fix/issue-3483-graceful-shutdown branch November 28, 2026 16:08
inureyes added a commit that referenced this pull request Nov 28, 2026
Rewrite the GB10 record for a build of main at 15e6395 (includes #3508, #3509 and #3540). A cold-cache Qwen3-4B-4bit generation inside the runtime image under strace opened 11 CUDA toolkit headers, all in the allow-list, and succeeded; the server smoke (uid 65532, chat completion, CLI generate, docker stop drain, PTX cache reuse on a named volume, a root:root 0777 bind mount and a private-group 2775 bind mount) passed again. The record also states the license basis, the amd64 cross builds on Ubuntu 26.04 with CUDA 13.5, and what was not run.

Refs #3484
inureyes added a commit that referenced this pull request Nov 28, 2026
…3543)

## Summary

Adds `docker/Dockerfile.cuda`: a shell-less chiseled Ubuntu `runtime` image and a `debug` image (the whole `nvidia/cuda` `cudnn-devel` image plus mlxcel) for `linux/amd64` and `linux/arm64`, running as uid 65532 with `/models` and `/cache` volumes. The previous attempt stopped at the CUDA header license gate; #3540 removed the non-redistributable includes, so the runtime image now ships.

## What changed

- The runtime image copies exactly `scripts/ci/nvrtc_header_allowlist.txt` into `/usr/local/cuda/include` (`docker/copy-cuda-headers.sh`, no second list). The build fails if a listed header is missing or any other file is there. `docker/copy-cuda-headers_test.sh` covers the guard and runs in CI.
- CUDA and cuDNN files come from NVIDIA's CUDA apt repository. The signing key fingerprints are pinned, and the packages are unpacked without installing. Nothing is copied out of an `nvidia/cuda` image, because the NGC container license allows a derived image only when it includes the whole container (1.c, 4.c). Package versions go to `/opt/mlxcel/share/cuda-packages.txt`.
- Libraries come from a `readelf` closure plus a measured dlopen set, with a glibc/libstdc++ version guard.
- amd64 defaults to Ubuntu 26.04 with CUDA 13.5, because the x86_64 release runner builds with CUDA 13.5 and its binaries need `GLIBC_2.43`. arm64 stays on Ubuntu 24.04 with CUDA 13.0.
- `NOTICE` records the CUDA EULA and cuDNN distribution basis and adds the bundled CCCL (Apache-2.0 with LLVM exceptions) and CUTLASS/CuTe (BSD-3-Clause) headers. `README.md` and `docs/installation.md` describe the image.
- The `/health` wording is corrected, not the server: with `-m` the listener binds only after load and warmup, so probes are refused until the server returns 200. The image has no `HEALTHCHECK`.
- Security review: `HOME=/cache` means `-m owner/name` reads `/cache/.cache/huggingface/hub` before `/models` without an owner check, so a `/cache` other host uids can write lets them substitute a model. The docs now recommend a 65532-owned or private-group bind; a resolver fix is left for a follow-up.

## Test plan

GB10, local build of `main` at `15e63955` (#3508, #3509, #3540), arm64 runtime image, all GPU runs under `gpu-lock`.

- [x] Cold-cache `mlxcel generate` under strace inside the runtime image: exit 0, 0 to 12 PTX files. It opened 11 toolkit headers, all allow-listed, and no header outside the toolkit and bundled include roots.
- [x] Server smoke as 65532, named volume, `root:root 0777` bind with the trusted root, and `65532:65532 2775` bind with the trusted root unset. In every case the chat completion returned text, `docker stop` took under 1 s with exit 0, and the second start compiled nothing and left the cache identical. CLI `generate` worked and `--entrypoint sh` failed.
- [x] The literal `--platform linux/amd64,linux/arm64` build from v0.8.1, cache-only, for `runtime` and `debug`; amd64 runtime also from v0.9.0-beta.3 (glibc 2.43 rootfs).
- [x] The GPU runs used the image before the review follow-up `3ab35c1f` (copyright files, build-step hardening); that version was only rebuilt, not run.
- [x] `docker/copy-cuda-headers_test.sh` (5 cases, including a planted `math_constants.h` and a symlink).
- [ ] Not run: any amd64 container or x86_64 GPU (including NVRTC 13.5), release binaries at run time (no release has #3508/#3509/#3540 yet), either debug image at run time, kernels Qwen3 does not reach. Record: `docs/benchmark_results/docker-cuda-smoke-gb10-2026-11-29.md`.

Owner review requested: the license basis in `NOTICE` (CUDA EULA Attachment A and 1.1.2, cuDNN supplement, NGC container license 1.c/4.c/7) is my reading of those documents, not legal advice.

Closes #3484
inureyes added a commit that referenced this pull request Nov 30, 2026
Bilingual reports for the eight PRs of epic #3488: #3508 (graceful drain), #3509 (CUDA PTX cache trust), #3530 (ROCm hsaco cache trust), #3540 (NVRTC redistributable headers), #3543 (CUDA container image), #3549 (Helm chart), #3550 (GHCR image publishing) and #3554 (chart OCI publishing and docs).

Each report names what the PR record leaves unvalidated: a real GHCR push, a GPU pod on a cluster, the amd64 and debug images. The HuggingFace cache follow-up is #3570.
@inureyes inureyes added this to the 0.9 milestone Nov 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

priority:medium Medium priority status:done Completed type:bug Bug fixes, error corrections, or issue resolutions

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix(server): Handle SIGTERM and SIGINT with a bounded graceful drain

1 participant