Repository navigation
fix(server): join model workers before the process exits - #2742
Conversation
The hosted `Pipeline Parallel CI / 2-host logical` job aborted with `pure virtual method called` about 40 ms after libtest printed its summary. gdb with a breakpoint on `__cxa_pure_virtual` shows the mechanism on every captured run: a `ModelProvider` worker thread (`spawn_model_worker_with_batch_config`, model_worker.rs:893) is still dropping its `PagedBlockPool` arrays, `mlx::core::allocator::Data::~Data` calls `allocator().free()`, and the CPU backend's `CommonAllocator` (a function-local static with virtual `free`) has already been destroyed by `__run_exit_handlers` on the main thread, which at that instant is in `_dl_fini` running OpenBLAS's finalizer. `Drop for ModelProvider` only sends the shutdown request, so the test (and any binary that returns from `main`) left the worker freeing MLX state while static destructors ran. The runner image change to kernel 7.0 only altered the scheduling that exposed it. - `ModelProvider::shutdown_and_wait(timeout)` sends the shutdown signal and waits on the worker exit observer, erroring on timeout or with the worker's panic message; `WORKER_EXIT_TIMEOUT` moves to `model_provider.rs` and is re-exported from `server`. `InProcessServer::shutdown` delegates to it. `Drop` stays non-blocking. - The multi-stage smoke helper shuts both providers down explicitly (coordinator first) before the stage handles, and fails if either worker does not exit. - `start_server` joins the chat worker before returning, for the listener error and for the side-model resolution errors that run while the worker is still loading; `run_router_server` drains the pool on the listener-error exit too, not only on Ctrl-C. - New unit tests cover the cooperative, already-exited, panicking and non-exiting worker cases; `tests/server_exit_joins_worker.rs` drives a real `mlxcel-server` (single-model and router `load-on-startup`) into the bind-failure exit and checks it exits with code 1 through the join, not a signal. Looping the debug CPU smoke binary 50 times on a kernel 7.0 box: 44 of 50 runs aborted before the fix, 0 of 50 after it. Closes #2738
Implementation Review SummaryIntent
Findings AddressedNo CRITICAL or HIGH findings, so no fixes were pushed. The shutdown semantics check out: Remaining Items
Verification
|
Security and performance review (head e4312b8)No CRITICAL or HIGH findings, so nothing was auto-fixed and no commits were added. Checked: every new wait is bounded ( MEDIUM (not fixed, below the auto-fix threshold)
LOW
|
Review follow-ups for #2742. - `join_model_worker_before_exit` logs the serve error at error level before the bounded join, and the router's `serve_http` arm does the same before `shutdown_all`, so a bind or TLS failure during a long model load is not a silent wait of up to 120 s or 150 s. The error is still returned unchanged for `main` to print. - The router Ctrl-C arm no longer returns early when the signal handler cannot be installed: it logs the error, drains through `shutdown_all`, and returns the error afterwards, so every router exit drains. - `shutdown_and_wait` prints its timeout with `Debug`: the production message stays `did not exit within 120s`, and a sub-second timeout reads `500ms` instead of `0s`. - `tests/server_exit_joins_worker.rs` asserts `attempted=1 completed=1` on the router drain line, because a failed `begin_load` prints the same message with `attempted=0`. - `tests/pipeline_server_remote_real_models.rs` joins its two providers with `shutdown_and_wait(WORKER_EXIT_TIMEOUT)` instead of dropping them, matching the multi-stage smoke helper. Validated with `server::model_provider::` (74/74), `server_exit_joins_worker` (2/2, `MLXCEL_REQUIRE_MODELS=1`), a manual bind-failure run of `mlxcel-server` in both modes showing the new error lines, a `cargo check` of the remote pipeline target, clippy `-D warnings` on lib and tests, and `cargo fmt --check`. Refs #2738
English and Korean report for the model worker join at process exit: the confirmed mechanism behind the 2-host logical CI abort (a detached worker freeing MLX arrays after the CPU backend's static allocator was destroyed), the per-path production verdicts, the shutdown_and_wait design, the local 44/50 to 0/50 result and the ten-run CI stability table, plus the residuals tracked in #2745.
On a CPU build, an MLX free that runs after the C runtime's static destructors start aborts with `pure virtual method called`. PR #2742 joined the chat model worker but left the audio, realtime, embedding, image and rerank workers joining only in their unbounded `Drop`, on whichever thread dropped the last `Arc`. Each side provider now exposes `shutdown_and_wait`, sharing the chat worker's `WorkerExitObserver`, and `serve_with_model_provider` keeps one clone of every side `Arc` and joins the side workers first, then the chat worker, on the blocking pool under one `WORKER_EXIT_TIMEOUT` deadline. Side-worker failures log `warn!` and never replace the error that ended serving. The sleeping worker now exits on `Shutdown` without reloading. `join_model_worker_before_exit` takes its timeout as a parameter and reports that a timed-out worker is still running, which a CPU build may abort on; the limitation is documented because model load has no cancellation point. The remote pipeline stage path always shuts the stage down and joins it on the blocking pool, including when the Ctrl-C handler cannot be installed. Validation: cargo fmt --check, clippy on the lib and tests with -D warnings, cargo check, the server build and the startup unit tests pass. The real-model integration tests skip on this host because their checkpoints are absent. Refs #2745
* fix: join side-model workers on server exit On a CPU build, an MLX free that runs after the C runtime's static destructors start aborts with `pure virtual method called`. PR #2742 joined the chat model worker but left the audio, realtime, embedding, image and rerank workers joining only in their unbounded `Drop`, on whichever thread dropped the last `Arc`. Each side provider now exposes `shutdown_and_wait`, sharing the chat worker's `WorkerExitObserver`, and `serve_with_model_provider` keeps one clone of every side `Arc` and joins the side workers first, then the chat worker, on the blocking pool under one `WORKER_EXIT_TIMEOUT` deadline. Side-worker failures log `warn!` and never replace the error that ended serving. The sleeping worker now exits on `Shutdown` without reloading. `join_model_worker_before_exit` takes its timeout as a parameter and reports that a timed-out worker is still running, which a CPU build may abort on; the limitation is documented because model load has no cancellation point. The remote pipeline stage path always shuts the stage down and joins it on the blocking pool, including when the Ctrl-C handler cannot be installed. Validation: cargo fmt --check, clippy on the lib and tests with -D warnings, cargo check, the server build and the startup unit tests pass. The real-model integration tests skip on this host because their checkpoints are absent. Refs #2745 * docs: add technical report for PR #2827
Confirmed mechanism
The abort is a
ModelProviderworker thread freeing its model aftermainhas returned. Reproduced on this box (kernel 7.0.0, same as the failing runner image) with the CI configuration (debug profile, nocudafeature,MLXCEL_CI_PP_MODEL=qwen3-0.6b-4bit); gdb with a breakpoint on__cxa_pure_virtualcaught it on 3 of 3 attempts. Aborting thread (frames condensed):Main thread at the same instant:
The worker (still joined by nobody:
Drop for ModelProvideronly sendsModelRequest::Shutdown, and itsJoinHandlesits in theobserve_worker_exitwatcher thread, which gdb shows blocked inpthread_joinon it) is dropping the scheduler'sPagedBlockPool. Each array free goes throughallocator().free(). On the CPU backendallocator()isstatic CommonAllocator allocator_inmlx/backend/no_gpu/allocator.cpp, a function-local static whose destructor runs from__run_exit_handlers; after it, the object's vtable is the abstractAllocator's andfreeis pure virtual. The Metal, CUDA and ROCm allocators are heap-leaked on purpose and never reach this state, which is why only the CPU CI build aborts. The kernel change in the runner image only altered the scheduling that exposes the window; the test never joined the two providers.Fix
ModelProvider::shutdown_and_wait(timeout)(src/server/model_provider.rs): sends the shutdown signal, waits on the existingWorkerExitObserver, returnsErr("server model worker did not exit within 120s")on expiry (the duration is printed withDebug, so the production text is unchanged and a sub-second test timeout reads500ms, not0s) andErr("server model worker panicked: ...")on a panic. Idempotent; an exited worker and a closed channel returnOk.WORKER_EXIT_TIMEOUT(120 s) moves here aspuband is re-exported frommlxcel::serverso the integration test can use it.InProcessServer::shutdowndelegates to it.Dropstays non-blocking.tests/pipeline_ci_multi_stage_real_models.rs: the shared helper callsshutdown_and_wait(WORKER_EXIT_TIMEOUT)on the coordinator provider, then the dense one, andexpects both before shutting the stage handles down.tests/pipeline_server_remote_real_models.rsnow does the same instead of dropping its two providers (CUDA and Metal only today, where the allocators are leaked, but exposed on a CPU runner).src/server/model_provider_tests.rs: cooperative worker (Ok, observed, second callOk), already-exited worker (Okwith a zero timeout), worker panicking during teardown (Errcarrying the message), worker ignoring shutdown (Errafter a 1 s timeout, thenOkonce released).Production exposure (per path)
mlxcel-serversingle-model mode (start_server): affected.serve_httpreturning (bind or TLS error) and the five side-model resolution errors after the chat worker started loading all returned with the worker alive. Fixed: everything after the provider is created moved into the functionserve_with_model_provider, whose result flows throughjoin_model_worker_before_exit. That logs the serve error at error level first (server stopped: ...; waiting for the model worker to exit), so a bind or TLS failure during a long load is not a silent wait, then callsshutdown_and_waiton the blocking pool and logsmodel worker exited before process exit. The serve error is returned unchanged formainto print, and a shutdown failure never replaces it. SIGINT/SIGTERM in this mode still die by default disposition (no exit handlers run), unchanged. The audio, embedding, image and rerank side workers are trait objects without an exit observer and are not joined here; the same hazard class applies to them on the CPU backend and is tracked in fix: join side-model workers and finish remaining exit-path gaps after #2738 #2745 (with the sleeping-worker reload on shutdown, the uncancellable load past the join timeout, and the--pp-peersignal path).run_router_server): partly affected. The Ctrl-C arm already drained throughshutdown_all, whoseunloadwaits on each worker's exit observer (and the entry operation guard makes it wait for an in-flightbuild_model_apptoo). Theserve_httperror arm returned without draining, so a bind failure afterload-on-startupexited under loading workers. Fixed: both arms drain before returning. The listener error is logged before the drain starts, and a Ctrl-C handler that cannot be installed now drains before its error is returned instead of skippingshutdown_all. Residual: a worker that ignores shutdown pastROUTER_SHUTDOWN_TIMEOUT(150 s) still exits with handlers running; the alternative is hanging.--pp-peerstage (serve_remote_pipeline_stage): not affected.RemoteStageServiceHandle::shutdownjoins the stage thread, which owns the stage model and its current-thread runtime.mlxcel run/chat: not affected. They already join throughInProcessServer::shutdown(refactor: route mlxcel run and chat through the in-process server engine #2224), which now shares the implementation.tests/server_exit_joins_worker.rsdrives a realmlxcel-serverinto the bind-failure exit (the test holds the port) for the single-model and the routerload-on-startuppaths and asserts exit code 1, no signal, no C++ abort text, and the join log line. The router test matchesrouter: lifecycle shutdown completed attempted=1 completed=1, since a failedbegin_loadprints the same message withattempted=0. Both skip without theqwen3-0.6b-4bitcheckpoint.Before / after
Command, on the debug CPU binary exactly as CI runs it:
aborts: 44/50(every abort log carriespure virtual method called; the other 6 runs exited cleanly)aborts: 0/50(same binary rebuilt from this branch, same box, loops overlapped in time)Test plan
cargo test --profile test-fast --features cuda -p mlxcel --lib server::model_provider:: -- --test-threads=1cargo test --profile test-fast --features cuda -p mlxcel --lib server::in_process:: -- --test-threads=1tests/server_exit_joins_worker.rs(both tests, real checkpoint,MLXCEL_REQUIRE_MODELS=1)cargo check --profile test-fast --features cuda,test-utils -p mlxcel --test pipeline_server_remote_real_modelscargo clippy --profile test-fast --features cuda -p mlxcel --lib --tests -- -D warnings,cargo fmt --all -- --checkCI stability
Ten consecutive
workflow_dispatchruns ofpipeline-parallel-ci.ymlon this branch at head03c1e365, dispatched one at a time (the concurrency group cancels overlapping runs on the same ref). All ten passed, and all ten ran onubuntu24/20261025.353, the runner image every one of the original aborts ran on. No job log containspure virtual method called.03c1e365ubuntu24/20261025.35303c1e365ubuntu24/20261025.35303c1e365ubuntu24/20261025.35303c1e365ubuntu24/20261025.35303c1e365ubuntu24/20261025.35303c1e365ubuntu24/20261025.35303c1e365ubuntu24/20261025.35303c1e365ubuntu24/20261025.35303c1e365ubuntu24/20261025.35303c1e365ubuntu24/20261025.353The two
pull_requestruns of the same workflow on this PR also passed onubuntu24/20261025.353: 41024288311 ate4312b89and 41045135070 at03c1e365.Closes #2738