Skip to content

fix(server): join model workers before the process exits - #2742

Merged
inureyes merged 4 commits into
mainfrom
fix/issue-2738-pp-exit-abort
Oct 30, 2026
Merged

inureyes merged 4 commits into
mainfrom
fix/issue-2738-pp-exit-abort

Conversation

@inureyes

@inureyes inureyes commented Oct 30, 2026 •

Copy link
Copy Markdown
Member

Confirmed mechanism

The abort is a ModelProvider worker thread freeing its model after main has returned. Reproduced on this box (kernel 7.0.0, same as the failing runner image) with the CI configuration (debug profile, no cuda feature, MLXCEL_CI_PP_MODEL=qwen3-0.6b-4bit); gdb with a breakpoint on __cxa_pure_virtual caught it on 3 of 3 attempts. Aborting thread (frames condensed):

#0  __cxa_pure_virtual ()
#1  mlx::core::allocator::Data::~Data  at mlx/allocator.h:79        (allocator().free(buffer))
#11 mlx::core::array::ArrayDesc::~ArrayDesc  at mlx/array.cpp:333
#22 mlx_cxx::MlxArray::~MlxArray  at cpp/mlx_cxx_bridge.h:27
#38 drop_glue<mlxcel_core::cache::paged::PagedBlockPool>
#49 spawn_model_worker_with_batch_config::{closure#0}::{closure#0}  at src/server/model_worker.rs:893
#55 mlxcel::worker_failfast::run_core_thread_or_abort

Main thread at the same instant:

#6  blas_thread_shutdown_ / #8 gotoblas_quit   (libopenblas finalizer)
#9  _dl_call_fini / #10 _dl_fini
#11 __run_exit_handlers / #12 exit

The worker (still joined by nobody: Drop for ModelProvider only sends ModelRequest::Shutdown, and its JoinHandle sits in the observe_worker_exit watcher thread, which gdb shows blocked in pthread_join on it) is dropping the scheduler's PagedBlockPool. Each array free goes through allocator().free(). On the CPU backend allocator() is static CommonAllocator allocator_ in mlx/backend/no_gpu/allocator.cpp, a function-local static whose destructor runs from __run_exit_handlers; after it, the object's vtable is the abstract Allocator's and free is 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 existing WorkerExitObserver, returns Err("server model worker did not exit within 120s") on expiry (the duration is printed with Debug, so the production text is unchanged and a sub-second test timeout reads 500ms, not 0s) and Err("server model worker panicked: ...") on a panic. Idempotent; an exited worker and a closed channel return Ok. WORKER_EXIT_TIMEOUT (120 s) moves here as pub and is re-exported from mlxcel::server so the integration test can use it. InProcessServer::shutdown delegates to it. Drop stays non-blocking.
  • tests/pipeline_ci_multi_stage_real_models.rs: the shared helper calls shutdown_and_wait(WORKER_EXIT_TIMEOUT) on the coordinator provider, then the dense one, and expects both before shutting the stage handles down. tests/pipeline_server_remote_real_models.rs now 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).
  • Unit tests in src/server/model_provider_tests.rs: cooperative worker (Ok, observed, second call Ok), already-exited worker (Ok with a zero timeout), worker panicking during teardown (Err carrying the message), worker ignoring shutdown (Err after a 1 s timeout, then Ok once released).

Production exposure (per path)

  • mlxcel-server single-model mode (start_server): affected. serve_http returning (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 function serve_with_model_provider, whose result flows through join_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 calls shutdown_and_wait on the blocking pool and logs model worker exited before process exit. The serve error is returned unchanged for main to 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-peer signal path).
  • Router mode (run_router_server): partly affected. The Ctrl-C arm already drained through shutdown_all, whose unload waits on each worker's exit observer (and the entry operation guard makes it wait for an in-flight build_model_app too). The serve_http error arm returned without draining, so a bind failure after load-on-startup exited 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 skipping shutdown_all. Residual: a worker that ignores shutdown past ROUTER_SHUTDOWN_TIMEOUT (150 s) still exits with handlers running; the alternative is hanging.
  • --pp-peer stage (serve_remote_pipeline_stage): not affected. RemoteStageServiceHandle::shutdown joins the stage thread, which owns the stage model and its current-thread runtime.
  • mlxcel run / chat: not affected. They already join through InProcessServer::shutdown (refactor: route mlxcel run and chat through the in-process server engine #2224), which now shares the implementation.

tests/server_exit_joins_worker.rs drives a real mlxcel-server into the bind-failure exit (the test holds the port) for the single-model and the router load-on-startup paths and asserts exit code 1, no signal, no C++ abort text, and the join log line. The router test matches router: lifecycle shutdown completed attempted=1 completed=1, since a failed begin_load prints the same message with attempted=0. Both skip without the qwen3-0.6b-4bit checkpoint.

Before / after

Command, on the debug CPU binary exactly as CI runs it:

BIN=target/debug/deps/pipeline_ci_multi_stage_real_models-<hash>
for i in $(seq 50); do MLXCEL_CI_PP_MODEL=qwen3-0.6b-4bit "$BIN" pipeline_multi_stage_two_host_logical_smoke --ignored --nocapture --test-threads=1; done
  • Before the fix (origin/main 8385f40): aborts: 44/50 (every abort log carries pure virtual method called; the other 6 runs exited cleanly)
  • After the fix: 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=1
  • cargo test --profile test-fast --features cuda -p mlxcel --lib server::in_process:: -- --test-threads=1
  • tests/server_exit_joins_worker.rs (both tests, real checkpoint, MLXCEL_REQUIRE_MODELS=1)
  • the smoke test on the debug CPU binary, 50 consecutive runs
  • cargo check --profile test-fast --features cuda,test-utils -p mlxcel --test pipeline_server_remote_real_models
  • cargo clippy --profile test-fast --features cuda -p mlxcel --lib --tests -- -D warnings, cargo fmt --all -- --check

CI stability

Ten consecutive workflow_dispatch runs of pipeline-parallel-ci.yml on this branch at head 03c1e365, dispatched one at a time (the concurrency group cancels overlapping runs on the same ref). All ten passed, and all ten ran on ubuntu24/20261025.353, the runner image every one of the original aborts ran on. No job log contains pure virtual method called.

# Run Head Result Runner image
1 41045436759 03c1e365 success ubuntu24/20261025.353
2 41048002710 03c1e365 success ubuntu24/20261025.353
3 41049748107 03c1e365 success ubuntu24/20261025.353
4 41051499873 03c1e365 success ubuntu24/20261025.353
5 41053271228 03c1e365 success ubuntu24/20261025.353
6 41055089949 03c1e365 success ubuntu24/20261025.353
7 41056817489 03c1e365 success ubuntu24/20261025.353
8 41058570988 03c1e365 success ubuntu24/20261025.353
9 41060493226 03c1e365 success ubuntu24/20261025.353
10 41062232317 03c1e365 success ubuntu24/20261025.353

The two pull_request runs of the same workflow on this PR also passed on ubuntu24/20261025.353: 41024288311 at e4312b89 and 41045135070 at 03c1e365.

Closes #2738

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
@inureyes inureyes added status:review Under review type:bug Bug fixes, error corrections, or issue resolutions priority:medium Medium priority area:inference Generation, sampling, decoding (incl. speculative, DRY) labels Oct 30, 2026
@inureyes

Copy link
Copy Markdown
Member Author

Implementation Review Summary

Intent

Join every ModelProvider worker before main returns so the CPU backend no longer aborts in CommonAllocator::free during exit handlers, in the PP smoke test and in the affected mlxcel-server exit paths (#2738).

Findings Addressed

No CRITICAL or HIGH findings, so no fixes were pushed. The shutdown semantics check out: shutdown_and_wait reuses WorkerExitObserver::wait_timeout, so there is no second wait loop. The observer marks exit only after the worker's JoinHandle is joined, so the model's MLX arrays are already freed when it returns Ok. Calling it again, or after the worker has exited, returns Ok, and a closed channel is not an error. The start_server join runs on spawn_blocking, and a serve error takes precedence over a shutdown error. Drop stays non-blocking. The tail of startup.rs was moved with zero deleted lines.

Remaining Items

  • Side workers in single-model mode (audio STT/TTS, embeddings, rerank, image) are not joined on the bind-failure and side-model-error exits, so the same CPU-backend hazard applies to them. The PR calls this a follow-up, but no follow-up issue exists yet. (MEDIUM)
  • shutdown_and_wait formats the timeout with as_secs(), so a sub-second timeout reads "within 0s". {timeout:?} would keep "120s" and "1s" byte-identical. (LOW)
  • In the router Ctrl-C arm, signal? still returns before the drain if the signal handler cannot be installed. This predates the PR, but it contradicts the new "both exits drain" comment. (LOW)
  • tests/pipeline_server_remote_real_models.rs:186-187 still drops its two providers without joining them. That suite runs only on CUDA and Metal, where the allocators are leaked on purpose, so it is not exposed today. It would be exposed on a CPU runner. (LOW)
  • A panic inside serve_with_model_provider (for example in warmup) unwinds past the join. This is an edge case. (LOW)
  • The PR body says the tail "runs inside one block", but after the split it is the function serve_with_model_provider. (LOW)

Verification

  • All stated requirements implemented (side workers deferred, see above)
  • No placeholder/mock code remaining
  • Integrated into project code flow (start_server, run_router_server, InProcessServer::shutdown, smoke-test helper)
  • Project conventions followed
  • Existing modules reused where applicable
  • No unintended structural changes
  • Tests pass: server::model_provider:: 74/74 and server::in_process:: 17/17 (test-fast, cuda, gpu-lock), server_exit_joins_worker 2/2 with MLXCEL_REQUIRE_MODELS=1, clippy -D warnings on lib and tests, cargo fmt --check. I did not re-run the 50-run CPU debug loop. The 0/50 result is the author's.

@inureyes

Copy link
Copy Markdown
Member Author

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 (shutdown_and_wait by its timeout, the start_server join by WORKER_EXIT_TIMEOUT, the router drain by ROUTER_SHUTDOWN_TIMEOUT). None of the join paths can be reached from the network, because they run only after the listener is gone. The start_server join runs on the blocking pool, not on a runtime worker. A worker with requests in flight leaves its scheduler loop on the next tick after Shutdown, so a long generation cannot hold the join. The router drain is the same shutdown_all code the ctrl_c arm already ran, so it adds no new lock ordering. A shutdown error is logged and never replaces the serving error. The new integration test holds its loopback port for the child's whole lifetime, so there is no bind race, and it honors MLXCEL_REQUIRE_MODELS.

MEDIUM (not fixed, below the auto-fix threshold)

  • The serving error is reported only after the join. With --no-warmup (or in router mode with load-on-startup), a bind or TLS failure first waits for the model load to finish, up to 120 s (single model) or 150 s (router), before main prints why it is exiting. To the operator this looks like a silent hang. Suggested fix: tracing::error! the served error before starting the join, in join_model_worker_before_exit and on the router's serve_http arm. If the load takes longer than the timeout, the join gives up and main returns while the load is still running, so on that path the fix: 2-host logical PP CI aborts with pure virtual call at process exit #2738 race can still happen. The load cannot be cancelled today.
  • When a worker is in idle sleep (--sleep-idle-seconds), shutdown_and_wait makes it reload the full model just to exit. The sleep arm in src/server/model_worker.rs stores any received request, Shutdown included, as pending_request and reloads before admit_pending sees it. This is not new (Drop, InProcessServer::shutdown and router unload behave the same), and the file is outside this PR's scope. It is worth a follow-up issue: in the sleeping recv arm, break on Shutdown instead of reloading.

LOW

  • In run_router_server, signal? inside the ctrl_c arm returns before the new drain if registering the signal handler fails. This is not new and rarely happens, but it is the one exit that still skips shutdown_all.
  • router_server_drains_a_loading_model_when_the_listener_fails checks for "lifecycle shutdown completed", but a failed begin_load (attempted = 0) prints that line too. Also asserting attempted=1 would show that the drain actually covered a loading worker.

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
@inureyes inureyes added status:done Completed and removed status:review Under review labels Oct 30, 2026
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.
@inureyes
inureyes marked this pull request as ready for review October 30, 2026 14:02
@inureyes
inureyes merged commit 99b3e56 into main Oct 30, 2026
16 checks passed
@inureyes
inureyes deleted the fix/issue-2738-pp-exit-abort branch October 30, 2026 14:02
@inureyes inureyes mentioned this pull request Nov 2, 2026
6 of 7 tasks
inureyes added a commit that referenced this pull request Nov 2, 2026
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
inureyes added a commit that referenced this pull request Nov 2, 2026
* 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
@inureyes inureyes added this to the 0.8 milestone Nov 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:inference Generation, sampling, decoding (incl. speculative, DRY) 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: 2-host logical PP CI aborts with pure virtual call at process exit

1 participant